Merge branch 'main' into lance-model-support

This commit is contained in:
SYLAR authored and GitHub committed 2026-05-22 04:13:58 +08:00
commit f0cec3ecd4
224 files changed
+19202 -7026

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Streaming-audio continuity metrics for the TTS bench.
Captures the failure mode where ``RTF_p50 < 1`` (server keeps up with realtime
in aggregate) but per-stream chunk arrival is bursty enough that listeners
hear audible gaps. Companion to ``audio_ttfp`` / ``audio_rtf``.
The math is purposefully simple so the helper has no ``vllm`` dependency and
can be unit-tested in isolation: given the wall-clock arrival timeline of
audio chunks and the PCM format, simulate a player that consumes at realtime
rate from the first chunk onward, and surface the worst-case deficit.
A deficit > ``threshold_s`` at any point counts as an audible underrun.
"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class ContinuityStats:
"""Result of a single-request continuity analysis.
Attributes:
max_underrun_s: Worst-case wall-clock seconds the player was starved.
underrun_event_count: Inter-chunk intervals during which the buffer
went negative (one per gap, not per starved millisecond).
is_continuous: ``max_underrun_s <= threshold_s`` for the request.
"""
max_underrun_s: float
underrun_event_count: int
is_continuous: bool
def compute_continuity_stats(
chunk_arrival_times_s: list[float],
chunk_bytes: list[int],
sample_rate: int,
sample_width: int = 2,
channels: int = 1,
threshold_s: float = 0.1,
) -> ContinuityStats:
"""Compute the continuity stats for one streaming response.
Args:
chunk_arrival_times_s: Wall-clock seconds (since request start) at
which each non-empty audio chunk's *last byte* arrived. Must be
monotonically non-decreasing.
chunk_bytes: Byte count of each chunk in the same order.
sample_rate: PCM sample rate (Hz). 24 000 for Qwen3-TTS / VoxCPM2.
sample_width: Bytes per sample (2 = s16le).
channels: PCM channel count (1 = mono).
threshold_s: Underrun budget. The default 0.1 s matches the
commonly-cited "audible gap" threshold for streaming TTS.
Returns:
A :class:`ContinuityStats` summarising the worst-case deficit and
whether it stayed under the threshold.
"""
n = len(chunk_arrival_times_s)
if n == 0 or n != len(chunk_bytes):
return ContinuityStats(0.0, 0, True)
bytes_per_s = sample_rate * sample_width * channels
if bytes_per_s <= 0:
return ContinuityStats(0.0, 0, True)
t0 = chunk_arrival_times_s[0]
received_before = 0
max_underrun_s = 0.0
event_count = 0
for i in range(n):
if i > 0:
played_bytes = (chunk_arrival_times_s[i] - t0) * bytes_per_s
deficit_bytes = played_bytes - received_before
if deficit_bytes > 0:
deficit_s = deficit_bytes / bytes_per_s
if deficit_s > max_underrun_s:
max_underrun_s = deficit_s
event_count += 1
received_before += chunk_bytes[i]
return ContinuityStats(
max_underrun_s=max_underrun_s,
underrun_event_count=event_count,
is_continuous=max_underrun_s <= threshold_s,
)
+24 -2
View File
@@ -25,6 +25,12 @@ class MultiModalsBenchmarkMetrics(BenchmarkMetrics):
median_audio_duration_s: float = 0.0
std_audio_duration_s: float = 0.0
percentiles_audio_duration_s: list[tuple[float, float]] = None
# Streaming-audio continuity (see vllm_omni/benchmarks/audio_continuity.py).
mean_audio_underrun_s: float = 0.0
median_audio_underrun_s: float = 0.0
std_audio_underrun_s: float = 0.0
percentiles_audio_underrun_s: list[tuple[float, float]] = None
audio_continuity_ok_rate: float = 1.0
def print_metrics(
@@ -83,6 +89,12 @@ def print_audio_metrics(selected_percentile_metrics, metrics: MultiModalsBenchma
print("{:<40} {:<10.2f}".format("Total audio duration generated(s):", metrics.total_audio_duration_s))
print("{:<40} {:<10}".format("Total audio frames generated:", metrics.total_audio_frames))
print("{:<40} {:<10.2f}".format("Audio throughput(audio duration/s):", metrics.audio_throughput))
print(
"{:<40} {:<10.2%}".format(
"Streaming continuity OK rate:",
metrics.audio_continuity_ok_rate,
)
)
for metric in selected_percentile_metrics:
if metric.startswith("audio"):
process_one_metric(metric, metrics)
@@ -100,17 +112,18 @@ def process_one_metric(
"audio_ttfp": "Time to First Packet",
"audio_rtf": "Real Time Factor",
"audio_duration": "Audio Duration",
"audio_underrun": "Streaming Audio Underrun",
}
header = metric_header_map.get(metric_attribute_name, metric_attribute_name)
print("{s:{c}^{n}}".format(s=header, n=50, c="-"))
is_audio_rtf = metric_attribute_name == "audio_rtf"
is_audio_duration = metric_attribute_name == "audio_duration"
is_audio_duration_or_underrun = metric_attribute_name in ("audio_duration", "audio_underrun")
suffix = "_ms"
unit_suffix = " (ms)"
if is_audio_duration:
if is_audio_duration_or_underrun:
suffix = "_s"
unit_suffix = " (s)"
elif is_audio_rtf:
@@ -172,6 +185,8 @@ def calculate_metrics(
audio_rtfs: list[float] = []
audio_duration: list[float] = []
audio_frames: list[int] = []
audio_underruns: list[float] = []
audio_continuity_ok: list[bool] = []
input_audio_duration = 0.0
for i in range(len(outputs)):
if outputs[i].success:
@@ -205,6 +220,8 @@ def calculate_metrics(
audio_rtfs.append(getattr(outputs[i], "audio_rtf", 0.0))
audio_duration.append(getattr(outputs[i], "audio_duration", 0.0))
audio_frames.append(getattr(outputs[i], "audio_frames", 0.0))
audio_underruns.append(getattr(outputs[i], "audio_underrun_s", 0.0))
audio_continuity_ok.append(bool(getattr(outputs[i], "audio_continuity_ok", True)))
e2els.append(outputs[i].latency)
input_audio_duration += outputs[i].input_audio_duration
completed += 1
@@ -332,6 +349,11 @@ def calculate_metrics(
std_audio_rtf=np.std(audio_rtfs or 0),
median_audio_rtf=np.median(audio_rtfs or 0),
percentiles_audio_rtf=[(p, np.percentile(audio_rtfs or 0, p)) for p in selected_percentiles],
mean_audio_underrun_s=np.mean(audio_underruns or 0),
std_audio_underrun_s=np.std(audio_underruns or 0),
median_audio_underrun_s=np.median(audio_underruns or 0),
percentiles_audio_underrun_s=[(p, np.percentile(audio_underruns or 0, p)) for p in selected_percentiles],
audio_continuity_ok_rate=(sum(audio_continuity_ok) / len(audio_continuity_ok)) if audio_continuity_ok else 1.0,
mean_tpot_ms=np.mean(tpots or 0) * 1000,
std_tpot_ms=np.std(tpots or 0) * 1000,
median_tpot_ms=np.median(tpots or 0) * 1000,
+58 -4
View File
@@ -36,6 +36,7 @@ from vllm.tokenizers import TokenizerLike
logger = init_logger(__name__)
from vllm_omni.benchmarks.audio_continuity import compute_continuity_stats
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 (
@@ -46,6 +47,33 @@ from vllm_omni.benchmarks.data_modules.seed_tts_dataset import (
SeedTTSTextDataset,
)
_AUDIO_CONTINUITY_THRESHOLD_ENV = "VLLM_OMNI_BENCH_AUDIO_CONTINUITY_THRESHOLD_S"
_DEFAULT_AUDIO_CONTINUITY_THRESHOLD_S = 0.1
def _audio_continuity_threshold_s() -> float:
"""Return the per-request underrun budget (s).
Read from ``VLLM_OMNI_BENCH_AUDIO_CONTINUITY_THRESHOLD_S`` so users can
re-aim the SLO without rebuilding. Defaults to 100 ms - the standard
"audible gap" budget for streaming TTS.
"""
raw = os.environ.get(_AUDIO_CONTINUITY_THRESHOLD_ENV)
if not raw:
return _DEFAULT_AUDIO_CONTINUITY_THRESHOLD_S
try:
value = float(raw)
except ValueError:
logger.warning(
"Invalid %s=%r; using default %.3fs",
_AUDIO_CONTINUITY_THRESHOLD_ENV,
raw,
_DEFAULT_AUDIO_CONTINUITY_THRESHOLD_S,
)
return _DEFAULT_AUDIO_CONTINUITY_THRESHOLD_S
return max(value, 0.0)
get_samples_old = datasets.get_samples
_DEFAULT_DAILY_OMNI_REPO = "liarliar/Daily-Omni"
@@ -315,6 +343,16 @@ class MixRequestFuncOutput(RequestFuncOutput):
audio_frames: int = 0
audio_rtf: float = 0.0
text_latency: float = 0.0
#: Worst-case streaming-audio underrun (wall-clock seconds the player
#: would have been starved). Populated by the audio-speech backend; ``0.0``
#: for backends that do not run continuity analysis.
audio_underrun_s: float = 0.0
#: Whether the request stayed under the continuity threshold (default
#: 100 ms). Mirrors ``audio_underrun_s <= threshold``.
audio_continuity_ok: bool = True
#: Number of inter-chunk intervals during which the player buffer went
#: negative.
audio_underrun_event_count: int = 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
@@ -605,6 +643,8 @@ async def async_request_openai_audio_speech(
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
chunk_arrival_times_s: list[float] = []
chunk_sizes: list[int] = []
try:
async with session.post(url=api_url, json=payload, headers=headers) as response:
if response.status == 200:
@@ -617,6 +657,8 @@ async def async_request_openai_audio_speech(
# not defined here; only audio TTFP is meaningful.
output.audio_ttfp = timestamp - st
total_pcm_bytes += len(chunk)
chunk_arrival_times_s.append(timestamp - st)
chunk_sizes.append(len(chunk))
if pcm_capture is not None:
pcm_capture.extend(chunk)
@@ -631,6 +673,18 @@ async def async_request_openai_audio_speech(
else:
output.audio_rtf = 0
logger.warning("Audio duration is zero")
continuity = compute_continuity_stats(
chunk_arrival_times_s=chunk_arrival_times_s,
chunk_bytes=chunk_sizes,
sample_rate=sample_rate,
sample_width=sample_width,
channels=channels,
threshold_s=_audio_continuity_threshold_s(),
)
output.audio_underrun_s = continuity.max_underrun_s
output.audio_continuity_ok = continuity.is_continuous
output.audio_underrun_event_count = continuity.underrun_event_count
if pcm_capture is not None and pcm_capture:
output.tts_output_pcm_bytes = bytes(pcm_capture)
elif capture_wer_pcm:
@@ -1020,14 +1074,14 @@ async def benchmark(
return
# No text tokens generated (e.g. pure TTS speech endpoint): per-token
# latency metrics (ttft/tpot/itl) are undefined, so skip them.
is_text_token_metric = metric_attribute_name not in ("e2el", "audio_ttfp", "audio_rtf", "audio_duration")
is_text_token_metric = not (metric_attribute_name == "e2el" or metric_attribute_name.startswith("audio"))
if is_text_token_metric and getattr(metrics, "total_output", 0) == 0:
return
is_audio_rtf = metric_attribute_name == "audio_rtf"
is_audio_duration = metric_attribute_name == "audio_duration"
is_audio_duration_or_underrun = metric_attribute_name in ("audio_duration", "audio_underrun")
suffix = "_ms"
if is_audio_duration:
if is_audio_duration_or_underrun:
suffix = "_s"
elif is_audio_rtf:
suffix = ""
@@ -1038,7 +1092,7 @@ async def benchmark(
median_attr_name = f"median_{metric_attribute_name}{suffix}"
median_value = getattr(metrics, median_attr_name, 0.0)
result[median_attr_name] = median_value
for p, value in getattr(metrics, f"percentiles_{metric_attribute_name}{suffix}"):
for p, value in getattr(metrics, f"percentiles_{metric_attribute_name}{suffix}", None) or []:
p_word = str(int(p)) if int(p) == p else str(p)
result[f"p{p_word}_{metric_attribute_name}{suffix}"] = value
+10
View File
@@ -15,6 +15,16 @@ connectors:
device_name: ""
memory_pool_size: 4294967296
memory_pool_device: "cpu"
yuanrong_te_connector:
name: YuanrongTransferEngineConnector
extra:
host: "auto"
zmq_port: 50051
rpc_port: "auto"
protocol: "ascend"
device_name: "auto"
memory_pool_size: 1073741824
memory_pool_device: "npu"
shared_memory_connector:
name: SharedMemoryConnector
extra:
+3 -2
View File
@@ -1,3 +1,4 @@
# MiMo Audio deploy: 2-stage thinker+talker → code2wav.
#
# Default mode is async-chunk streaming on a single GPU (both stages on
@@ -17,8 +18,8 @@ connectors:
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
codec_chunk_frames: 30
codec_left_context_frames: 40
stages:
- stage_id: 0
-69
View File
@@ -1,69 +0,0 @@
# VoxCPM two-stage (latent → VAE) without async_chunk: one-shot latent then decode.
stage_args:
- stage_id: 0
stage_type: llm
is_comprehension: true
runtime:
devices: "0"
max_batch_size: 1
engine_args:
dtype: bfloat16
model_stage: latent_generator
model_arch: VoxCPMForConditionalGeneration
# Optional persistent HF-compatible config dir for native VoxCPM models.
hf_config_path: ${oc.env:VLLM_OMNI_VOXCPM_HF_CONFIG_PATH,}
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: false
enable_prefix_caching: false
engine_output_type: latent
gpu_memory_utilization: 0.7
distributed_executor_backend: "mp"
max_num_batched_tokens: 4096
max_model_len: 4096
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 4096
stop_token_ids: [2]
seed: 42
detokenize: false
repetition_penalty: 1.0
final_output: false
- stage_id: 1
stage_type: llm
runtime:
devices: "0"
max_batch_size: 1
engine_args:
dtype: float32
model_stage: vae
model_arch: VoxCPMForConditionalGeneration
hf_config_path: ${oc.env:VLLM_OMNI_VOXCPM_HF_CONFIG_PATH,}
worker_type: generation
scheduler_cls: vllm_omni.core.sched.omni_generation_scheduler.OmniGenerationScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: false
enable_prefix_caching: false
engine_output_type: audio
gpu_memory_utilization: 0.15
distributed_executor_backend: "mp"
max_num_batched_tokens: 8192
max_model_len: 4096
engine_input_source: [0]
custom_process_input_func: vllm_omni.model_executor.stage_input_processors.voxcpm.latent2vae
final_output: true
final_output_type: audio
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 1
seed: 42
detokenize: true
repetition_penalty: 1.0
@@ -136,7 +136,9 @@ class FlashAttentionImpl(AttentionImpl):
)
batch_size, q_len = query.size()[:2]
cu_seqlens = torch.arange(0, (batch_size + 1) * q_len, step=q_len, dtype=torch.int32, device=query.device)
k_len = key.size(1)
cu_seqlens_q = torch.arange(0, (batch_size + 1) * q_len, step=q_len, dtype=torch.int32, device=query.device)
cu_seqlens_k = torch.arange(0, (batch_size + 1) * k_len, step=k_len, dtype=torch.int32, device=query.device)
# b s ... -> (b s) ...
query = query.flatten(0, 1)
key = key.flatten(0, 1)
@@ -146,10 +148,10 @@ class FlashAttentionImpl(AttentionImpl):
q=query,
k=key,
v=value,
cu_seqlens_q=cu_seqlens,
cu_seqlens_k=cu_seqlens,
cu_seqlens_q=cu_seqlens_q,
cu_seqlens_k=cu_seqlens_k,
max_seqlen_q=q_len,
max_seqlen_k=q_len,
max_seqlen_k=k_len,
causal=self.causal,
softmax_scale=self.softmax_scale,
)
+8 -4
View File
@@ -171,9 +171,13 @@ class Attention(nn.Module):
def _init_kv_cache_quantization(self, config) -> None:
if config is None:
return
dtype = config.diffusion_kv_cache_dtype
dtype = getattr(config, "diffusion_kv_cache_dtype", None)
if dtype == "auto":
dtype = None
parallel_config = getattr(config, "parallel_config", None)
ring_degree = getattr(parallel_config, "ring_degree", 1)
if dtype:
if config.parallel_config.ring_degree > 1:
if ring_degree > 1:
raise ValueError(
"KV quantization is not compatible with ring attention "
"(ring_degree > 1). Ring kernels do not propagate quantization descale "
@@ -190,8 +194,8 @@ class Attention(nn.Module):
)
dtype = None
self._kv_cache_dtype = dtype
self._kv_cache_skip_steps = config.diffusion_kv_cache_skip_step_indices
self._kv_cache_skip_layers = config.diffusion_kv_cache_skip_layer_indices
self._kv_cache_skip_steps = getattr(config, "diffusion_kv_cache_skip_step_indices", None)
self._kv_cache_skip_layers = getattr(config, "diffusion_kv_cache_skip_layer_indices", None)
def _should_apply_kv_cache_quant(self) -> bool:
skip_steps = self._kv_cache_skip_steps
-1
View File
@@ -1505,7 +1505,6 @@ CUSTOM_DIT_ENABLERS.update(
{
"Wan22Pipeline": enable_cache_for_wan22,
"Wan22I2VPipeline": enable_cache_for_wan22,
"Wan22TI2VPipeline": enable_cache_for_wan22,
"HunyuanImage3Pipeline": enable_cache_for_hunyuan_image3,
"FluxPipeline": enable_cache_for_flux,
"Flux2KleinPipeline": enable_cache_for_flux2_klein,
@@ -0,0 +1,145 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Any
import torch
from vllm.logger import init_logger
from vllm_omni.diffusion.distributed.autoencoders.distributed_vae_executor import (
DistributedOperator,
DistributedVaeMixin,
GridSpec,
TileTask,
)
from vllm_omni.diffusion.models.hunyuan_image3.autoencoder import AutoencoderKLConv3D
logger = init_logger(__name__)
class DistributedAutoencoderKLHunyuan(AutoencoderKLConv3D, DistributedVaeMixin):
@classmethod
def from_config(cls, config: Any, **kwargs: Any):
model = super().from_config(config, **kwargs)
model.init_distributed()
return model
@classmethod
def from_pretrained(cls, *args: Any, **kwargs: Any):
model = super().from_pretrained(*args, **kwargs)
model.init_distributed()
return model
@property
def use_tiling(self) -> bool:
return self.use_spatial_tiling
@use_tiling.setter
def use_tiling(self, use_tiling: bool) -> None:
self.use_spatial_tiling = use_tiling
def tile_split(self, z: torch.Tensor) -> tuple[list[TileTask], GridSpec]:
_, _, _, height, width = z.shape
overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)
row_limit = int(self.tile_sample_min_size - blend_extent)
tiletask_list = []
for i in range(0, height, overlap_size):
for j in range(0, width, overlap_size):
tile = z[:, :, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
tiletask_list.append(
TileTask(
len(tiletask_list),
(i // overlap_size, j // overlap_size),
tile,
workload=tile.shape[3] * tile.shape[4],
)
)
grid_spec = GridSpec(
split_dims=(3, 4),
grid_shape=(tiletask_list[-1].grid_coord[0] + 1, tiletask_list[-1].grid_coord[1] + 1),
tile_spec={"blend_extent": blend_extent, "row_limit": row_limit},
output_dtype=self.dtype,
)
return tiletask_list, grid_spec
def tile_exec(self, task: TileTask) -> torch.Tensor:
return self.decoder(task.tensor)
def tile_merge(self, coord_tensor_map: dict[tuple[int, ...], torch.Tensor], grid_spec: GridSpec) -> torch.Tensor:
grid_h, grid_w = grid_spec.grid_shape
result_rows = []
for i in range(grid_h):
result_row = []
for j in range(grid_w):
tile = coord_tensor_map[(i, j)]
if i > 0:
tile = self.blend_v(coord_tensor_map[(i - 1, j)], tile, grid_spec.tile_spec["blend_extent"])
if j > 0:
tile = self.blend_h(coord_tensor_map[(i, j - 1)], tile, grid_spec.tile_spec["blend_extent"])
result_row.append(tile[:, :, :, : grid_spec.tile_spec["row_limit"], : grid_spec.tile_spec["row_limit"]])
result_rows.append(torch.cat(result_row, dim=-1))
return torch.cat(result_rows, dim=-2)
def encode_tile_split(self, x: torch.Tensor) -> tuple[list[TileTask], GridSpec]:
_, _, _, height, width = x.shape
overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
row_limit = int(self.tile_latent_min_size - blend_extent)
tiletask_list = []
for i in range(0, height, overlap_size):
for j in range(0, width, overlap_size):
tile = x[:, :, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
tiletask_list.append(
TileTask(
len(tiletask_list),
(i // overlap_size, j // overlap_size),
tile,
workload=tile.shape[3] * tile.shape[4],
)
)
grid_spec = GridSpec(
split_dims=(3, 4),
grid_shape=(tiletask_list[-1].grid_coord[0] + 1, tiletask_list[-1].grid_coord[1] + 1),
tile_spec={"blend_extent": blend_extent, "row_limit": row_limit},
output_dtype=self.dtype,
)
return tiletask_list, grid_spec
def encode_tile_exec(self, task: TileTask) -> torch.Tensor:
return self.encoder(task.tensor)
def encode_tile_merge(
self, coord_tensor_map: dict[tuple[int, ...], torch.Tensor], grid_spec: GridSpec
) -> torch.Tensor:
return self.tile_merge(coord_tensor_map, grid_spec)
def spatial_tiled_encode(self, x: torch.Tensor):
if not self.is_distributed_enabled():
return super().spatial_tiled_encode(x)
logger.debug("Encode running with distributed executor")
return self.distributed_executor.execute(
x,
DistributedOperator(
split=self.encode_tile_split,
exec=self.encode_tile_exec,
merge=self.encode_tile_merge,
),
broadcast_result=True,
)
def spatial_tiled_decode(self, z: torch.Tensor):
if not self.is_distributed_enabled():
return super().spatial_tiled_decode(z)
logger.debug("Decode running with distributed executor")
return self.distributed_executor.execute(
z,
DistributedOperator(split=self.tile_split, exec=self.tile_exec, merge=self.tile_merge),
broadcast_result=True,
)
@@ -10,6 +10,7 @@ from typing import Any
import torch
from vllm.logger import init_logger
from vllm.sequence import IntermediateTensors
from vllm_omni.diffusion.distributed.parallel_state import (
get_cfg_group,
@@ -369,7 +370,7 @@ class CFGParallelMixin(metaclass=ABCMeta):
results.append(comb)
return _unwrap(tuple(results))
def predict_noise(self, *args: Any, **kwargs: Any) -> torch.Tensor | tuple[torch.Tensor, ...]:
def predict_noise(self, *args: Any, **kwargs: Any) -> torch.Tensor | tuple[torch.Tensor, ...] | IntermediateTensors:
"""
Forward pass through transformer to predict noise.
@@ -381,8 +382,11 @@ class CFGParallelMixin(metaclass=ABCMeta):
multi-output models (e.g., video + audio). Multi-output models
must also override combine_cfg_noise() and set self.scheduler
to a composite scheduler that handles tuples.
Non-last Pipeline Parallel stages return `IntermediateTensors`
instead of final noise tensors wrapped in a tuple.
"""
return self.transformer(*args, **kwargs)[0]
result = self.transformer(*args, **kwargs)
return result if isinstance(result, IntermediateTensors) else result[0]
def diffuse(
self,
@@ -429,6 +429,78 @@ class GroupCoordinator:
async_handle.wait()
return tensor_dict
def isend_tensor_dict(
self,
tensor_dict: dict[str, torch.Tensor | Any],
dst: int | None = None,
) -> list[torch.distributed.Work]:
"""Non-blocking send of a tensor dictionary.
Sends metadata via the Gloo CPU group (blocking) then starts a
non-blocking NCCL isend for each GPU tensor. Returns the list of
Work handles; the caller must call handle.wait() before the tensors
can be safely reused or freed.
NOTE: `dst` is the group rank of the destination.
"""
if not torch.distributed.is_initialized() or self.world_size == 1:
return []
if dst is None:
dst = self.group_next_rank
assert dst < self.world_size, f"Invalid dst rank ({dst})"
metadata_list, tensor_list = _split_tensor_dict(tensor_dict)
self.send_object(metadata_list, dst=dst)
handles: list[torch.distributed.Work] = []
for tensor in tensor_list:
if tensor.numel() == 0:
continue
group = self.cpu_group if tensor.is_cpu else self.device_group
handle = torch.distributed.isend(tensor, dst=self.ranks[dst], group=group)
if tensor.is_cuda:
# Keep allocator from reusing this CUDA buffer before the async send finishes.
tensor.record_stream(torch.cuda.current_stream(tensor.device))
handles.append(handle)
return handles
def irecv_tensor_dict(
self,
src: int | None = None,
) -> tuple[dict[str, torch.Tensor | Any], list[torch.distributed.Work], list]:
"""Non-blocking receive of a tensor dictionary.
Receives metadata via the Gloo CPU group (blocking) then starts a
non-blocking NCCL irecv for each GPU tensor. Returns
``(tensor_dict, comm_handles, comm_postprocess)`` matching the
interface expected by ``AsyncIntermediateTensors``.
NOTE: `src` is the group rank of the source.
"""
if not torch.distributed.is_initialized() or self.world_size == 1:
return {}, [], []
if src is None:
src = self.group_prev_rank
assert src < self.world_size, f"Invalid src rank ({src})"
recv_metadata_list = self.recv_object(src=src)
tensor_dict: dict[str, Any] = {}
handles: list[torch.distributed.Work] = []
for key, value in recv_metadata_list:
if isinstance(value, TensorMetadata):
tensor = torch.empty(value.size, dtype=value.dtype, device=value.device)
if tensor.numel() > 0:
group = self.cpu_group if tensor.is_cpu else self.device_group
handles.append(torch.distributed.irecv(tensor, src=self.ranks[src], group=group))
_update_nested_dict(tensor_dict, key, tensor)
else:
_update_nested_dict(tensor_dict, key, value)
return tensor_dict, handles, []
def send_tensor_dict(
self,
tensor_dict: dict[str, torch.Tensor | Any],
@@ -746,11 +746,6 @@ def initialize_model_parallel(
f" but got {sequence_parallel_size} != {ring_degree} * {ulysses_degree}"
)
# FIXME: Since the async p2p communication operation of NPU is not same as cuda in torch,
# the pipefusion is not ready for npu yet
if current_omni_platform.is_npu():
assert pipeline_parallel_size == 1, "Current pipefusion is not ready for NPU"
dit_parallel_size = (
data_parallel_size * cfg_parallel_size * sequence_parallel_size * pipeline_parallel_size * tensor_parallel_size
)
@@ -0,0 +1,291 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from functools import wraps
from typing import Any
import torch
from vllm.v1.worker.gpu_worker import AsyncIntermediateTensors
from vllm_omni.diffusion.distributed.parallel_state import (
get_cfg_group,
get_classifier_free_guidance_rank,
get_classifier_free_guidance_world_size,
get_pipeline_parallel_world_size,
get_pp_group,
is_pipeline_first_stage,
)
class AsyncLatents:
"""Transparent async wrapper returned by scheduler_step on rank 0.
Wraps a pending ``irecv_tensor_dict`` and defers ``handle.wait()`` until the
underlying tensor is actually consumed — either via attribute access
(e.g. ``latents.to(dtype)``, ``latents.shape``) or via a torch operation
(e.g. ``mask * latents``). This keeps the first PP rank non-blocking after
posting the receive, matching the async philosophy used everywhere else in
the PP communication layer.
"""
__slots__ = ("_tensor_dict", "_handles", "_postproc", "_tensor")
def __init__(
self,
tensor_dict: dict[str, torch.Tensor],
handles: list[torch.distributed.Work],
postproc: list,
):
self._tensor_dict = tensor_dict
self._handles = handles
self._postproc = postproc
self._tensor: torch.Tensor | None = None
def _resolve(self) -> torch.Tensor:
if self._tensor is not None:
return self._tensor
for h in self._handles:
h.wait()
for fn in self._postproc:
fn()
self._tensor = self._tensor_dict["latents"]
return self._tensor
# Attribute access (e.g. .shape, .to(), .dtype) delegates to the resolved tensor.
def __getattr__(self, name: str):
return getattr(self._resolve(), name)
# Torch function protocol: any torch op involving an AsyncLatents resolves it first.
@classmethod
def __torch_function__(cls, func, types, args=(), kwargs=None):
kwargs = kwargs or {}
def _unwrap(x):
if isinstance(x, AsyncLatents):
return x._resolve()
if isinstance(x, (list, tuple)):
return type(x)(_unwrap(item) for item in x) # type(x) return the class of x to preserve its type
return x
args = tuple(_unwrap(a) for a in args)
kwargs = {k: _unwrap(v) for k, v in kwargs.items()}
return func(*args, **kwargs)
class PipelineParallelMixin:
"""
Mixin providing Pipeline Parallelism for diffusion pipelines.
All PP ranks run the full denoising loop in `forward()`.
`predict_noise_maybe_with_cfg` and `scheduler_step_maybe_with_cfg` encapsulate all inter-rank communication.
Communication pattern per denoising step:
Forward chain : rank 0 → 1 → … → N-1 via async isend/irecv (AsyncIntermediateTensors)
Next timestep : last rank → rank 0 via async isend/irecv (AsyncLatents)
All communication is asynchronous using isend_tensor_dict/irecv_tensor_dict.
Only rank 0 needs updated latents for the next forward pass start.
For sequential CFG (cfg_parallel_size=1) with PP, two full forward chains are
executed — one for the positive pass and one for the negative pass — so that each
PP stage operates on the correct encoder_hidden_states.
"""
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
if not issubclass(cls, CFGParallelMixin):
raise TypeError(
f"{cls.__name__} inherits PipelineParallelMixin but not CFGParallelMixin. "
"Pipeline Parallelism requires CFGParallelMixin for predict_noise(), "
"predict_noise_maybe_with_cfg(), scheduler_step_maybe_with_cfg(), and combine_cfg_noise(). "
"Add CFGParallelMixin to the base classes of your pipeline."
)
mro = cls.mro()
if mro.index(PipelineParallelMixin) > mro.index(CFGParallelMixin):
raise TypeError(
f"{cls.__name__} must inherit PipelineParallelMixin before CFGParallelMixin so MRO selects "
f"PP-aware predict/scheduler wrappers and their `super()` calls delegate to CFGParallelMixin."
)
init = cls.__dict__.get("__init__")
if callable(init):
@wraps(init)
def wrapped_init(self, *args: Any, **kwargs: Any) -> None:
init(self, *args, **kwargs)
vae = getattr(self, "vae", None)
if vae is not None and hasattr(vae, "decode"):
self._wrapped_vae_decode()
cls.__init__ = wrapped_init
diffuse = cls.__dict__.get("diffuse")
if callable(diffuse):
@wraps(diffuse)
def wrapped_diffuse(self, *args: Any, **kwargs: Any) -> Any:
try:
latents = diffuse(self, *args, **kwargs)
if isinstance(latents, AsyncLatents):
latents = torch.as_tensor(latents) # avoid copying
return latents
finally:
self._sync_pp_send()
cls.diffuse = wrapped_diffuse
def _wrapped_vae_decode(self) -> None:
vae, orig_decode = self.vae, self.vae.decode
@wraps(orig_decode)
def wrapped_decode(z: torch.Tensor, *args: Any, **kwargs: Any):
if hasattr(vae, "is_distributed_enabled") and vae.is_distributed_enabled():
# Middle ranks (world size 3 or more) hold stale latents after the denoising loop.
# Broadcast from rank 0 so every rank splits identical tiles.
if get_pipeline_parallel_world_size() > 2:
z = get_pp_group().broadcast(z, src=0)
return orig_decode(z, *args, **kwargs)
elif is_pipeline_first_stage():
return orig_decode(z, *args, **kwargs)
return (None,) # decoder returns a tuple
self.vae.decode = wrapped_decode
@property
def _pp_send_work(self) -> list[torch.distributed.Work]:
if not hasattr(self, "_pp_send_work_list"):
self._pp_send_work_list: list[torch.distributed.Work] = []
return self._pp_send_work_list
@_pp_send_work.setter
def _pp_send_work(self, work: list[torch.distributed.Work]) -> None:
self._pp_send_work_list = work
def _sync_pp_send(self) -> None:
"""
Wait on all pending non-blocking PP sends.
Must be called after the denoising loop so that the isend handles
from the last iteration are completed before any subsequent
collective (e.g. VAE decode broadcast) or tensor reuse.
"""
if self._pp_send_work:
for handle in self._pp_send_work:
handle.wait()
self._pp_send_work = []
def predict_noise_maybe_with_cfg(
self,
do_true_cfg: bool,
true_cfg_scale: float,
positive_kwargs: dict[str, Any],
negative_kwargs: dict[str, Any] | None,
cfg_normalize: bool = True,
output_slice: int | None = None,
) -> torch.Tensor | tuple[torch.Tensor, ...] | None:
"""
Drop-in replacement for predict_noise_maybe_with_cfg that also handles PP.
Supports three modes:
- PP only, sequential CFG: both branches (cond and uncond) run through this PP pipeline.
This doubles communication volume per denoising step compared to PP + CFG-parallel.
- PP + CFG-parallel: each PP pipeline carries one branch. The last PP
rank all-gathers across the CFG group and combines, mirroring
CFGParallelMixin.predict_noise_maybe_with_cfg exactly.
- PP only, no CFG: cond branch only.
Returns:
noise_pred on the last PP rank (all CFG ranks when CFG-parallel is active).
None on all other ranks.
"""
if get_pipeline_parallel_world_size() == 1:
return super().predict_noise_maybe_with_cfg(
do_true_cfg, true_cfg_scale, positive_kwargs, negative_kwargs, cfg_normalize, output_slice
)
self._sync_pp_send()
pp_group = get_pp_group()
cfg_parallel_ready = do_true_cfg and get_classifier_free_guidance_world_size() > 1
if cfg_parallel_ready:
# Each PP pipeline carries exactly one CFG branch determined by cfg_rank.
all_kwargs = [positive_kwargs if get_classifier_free_guidance_rank() == 0 else negative_kwargs]
else:
# Sequential CFG (or no CFG): this PP pipeline handles all branches.
all_kwargs = [positive_kwargs] + ([negative_kwargs] if do_true_cfg else [])
# Non-first ranks receive intermediate tensors asynchronously
n = len(all_kwargs)
its: list[AsyncIntermediateTensors | None] = [None] * n
if not pp_group.is_first_rank:
for i in range(n):
its[i] = AsyncIntermediateTensors(*pp_group.irecv_tensor_dict())
if not pp_group.is_last_rank:
# First / middle rank: run partial forwards and propagate ITs downstream.
for kwargs, it in zip(all_kwargs, its):
result = self.predict_noise(**kwargs, intermediate_tensors=it)
self._pp_send_work.extend(pp_group.isend_tensor_dict(result.tensors))
return None
# Last rank: run full forward
noise_preds = [self.predict_noise(**kwargs, intermediate_tensors=it) for kwargs, it in zip(all_kwargs, its)]
if cfg_parallel_ready:
# All-gather the single-branch prediction across the CFG group and combine
# on all CFG ranks so every last PP rank has an identical noise_pred.
local_pred = noise_preds[0]
if output_slice is not None:
local_pred = local_pred[:, :output_slice]
gathered = get_cfg_group().all_gather(local_pred, separate_tensors=True)
return self.combine_cfg_noise(gathered[0], gathered[1], true_cfg_scale, cfg_normalize)
# Sequential CFG or no-CFG path.
if do_true_cfg:
pos, neg = noise_preds[0], noise_preds[1]
if output_slice is not None:
pos = pos[:, :output_slice]
neg = neg[:, :output_slice]
return self.combine_cfg_noise(pos, neg, true_cfg_scale, cfg_normalize)
pred = noise_preds[0]
if output_slice is not None:
pred = pred[:, :output_slice]
return pred
def scheduler_step_maybe_with_cfg(
self,
noise_pred: torch.Tensor | tuple[torch.Tensor, ...] | None,
t: torch.Tensor | tuple[torch.Tensor, ...],
latents: torch.Tensor | tuple[torch.Tensor, ...],
do_true_cfg: bool,
per_request_scheduler: Any | None = None,
generator: torch.Generator | None = None,
) -> torch.Tensor | tuple[torch.Tensor, ...] | AsyncLatents:
"""
Drop-in replacement for scheduler_step_maybe_with_cfg that also handles PP.
Only the last rank runs the scheduler (it already has noise_pred); the result
is sent to rank 0 which needs it for the next forward pass.
Returns a ``AsyncLatents`` on rank 0 that transparently defers
``handle.wait()`` until the tensor is actually consumed (via attribute
access or a torch operation), keeping the rank non-blocking after the
``irecv`` is posted.
"""
if get_pipeline_parallel_world_size() == 1:
return super().scheduler_step_maybe_with_cfg(
noise_pred, t, latents, do_true_cfg, per_request_scheduler, generator
)
pp_group = get_pp_group()
if pp_group.is_last_rank:
latents = super().scheduler_step_maybe_with_cfg(
noise_pred, t, latents, do_true_cfg, per_request_scheduler, generator
)
self._pp_send_work = pp_group.isend_tensor_dict({"latents": latents}, dst=0)
elif pp_group.is_first_rank:
latents = AsyncLatents(*pp_group.irecv_tensor_dict(src=pp_group.world_size - 1))
return latents
@@ -701,6 +701,10 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
raise ValueError(
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
)
elif isinstance(prompt, str) and not prompt.strip():
raise ValueError("`prompt` cannot be empty or whitespace-only.")
elif isinstance(prompt, list) and any(isinstance(p, str) and not p.strip() for p in prompt):
raise ValueError("`prompt` cannot contain empty or whitespace-only strings.")
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)}")
@@ -861,7 +865,11 @@ class Flux2KleinPipeline(nn.Module, CFGParallelMixin, SupportImageInput, Diffusi
height = req.sampling_params.height or height
width = req.sampling_params.width or width
num_inference_steps = req.sampling_params.num_inference_steps or num_inference_steps
num_inference_steps = (
req.sampling_params.num_inference_steps
if req.sampling_params.num_inference_steps is not None
else num_inference_steps
)
sigmas = req.sampling_params.sigmas or sigmas
guidance_scale = (
req.sampling_params.guidance_scale if req.sampling_params.guidance_scale is not None else guidance_scale
@@ -72,6 +72,7 @@ from vllm_omni.diffusion.distributed.sp_plan import (
SequenceParallelOutput,
)
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from vllm_omni.diffusion.layers.rope import RotaryEmbedding
from vllm_omni.diffusion.models.hunyuan_image3.hunyuan_fused_moe import HunyuanFusedMoE
from vllm_omni.model_executor.layers.timestep_embedding import timestep_embedding
@@ -868,7 +869,15 @@ class ImageKVCacheManager:
Manages specialized caching and updating of KV-Cache for image tokens in multimodal models.
"""
def __init__(self, num_heads: int, num_kv_heads: int, head_dim: int, scaling: float, image_token_len: int = 4097):
def __init__(
self,
num_heads: int,
num_kv_heads: int,
head_dim: int,
scaling: float,
image_token_len: int = 4097,
prefix: str = "",
):
"""
Args:
image_token_len: Number of tokens per image (including special placeholders),
@@ -892,6 +901,7 @@ class ImageKVCacheManager:
causal=False,
softmax_scale=self.scaling,
num_kv_heads=self.num_kv_heads,
prefix=f"{prefix}.attn" if prefix else "",
)
def _cache_prompt_kv(
@@ -1650,6 +1660,7 @@ class HunYuanAttention(nn.Module):
num_kv_heads=self.num_kv_heads,
scaling=self.scaling,
image_token_len=4097,
prefix=f"{prefix}.image_attn",
)
self.image_rope2d_emb = HunYuanRotary2DEmbedder(
num_heads=self.num_heads,
@@ -3021,6 +3032,7 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
with self.progress_bar(total=num_inference_steps) as progress_bar:
for i, t in enumerate(timesteps):
set_forward_context_denoise_step_idx(i)
if cfg_parallel_ready:
# CFG parallel: each rank forwards its own branch (no batch doubling)
latent_model_input = latents
@@ -3109,6 +3121,8 @@ class HunyuanImage3Text2ImagePipeline(DiffusionPipeline):
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
progress_bar.update()
set_forward_context_denoise_step_idx(None)
if hasattr(self.vae.config, "scaling_factor") and self.vae.config.scaling_factor:
latents = latents / self.vae.config.scaling_factor
if hasattr(self.vae.config, "shift_factor") and self.vae.config.shift_factor:
@@ -30,7 +30,6 @@ from vllm_omni.diffusion.request import OmniDiffusionRequest
from vllm_omni.inputs.data import OmniTextPrompt
from vllm_omni.model_executor.models.hunyuan_image3.siglip2 import Siglip2VisionTransformer
from .autoencoder import AutoencoderKLConv3D
from .hunyuan_image3_tokenizer import TokenizerWrapper
from .hunyuan_image3_transformer import (
CausalMMOutputWithPast,
@@ -343,7 +342,13 @@ class HunyuanImage3Pipeline(
quant_config = od_config.quantization_config
self.model = HunyuanImage3Model(self.hf_config, quant_config=quant_config)
self.transformer = self.model
self.vae = AutoencoderKLConv3D.from_config(self.hf_config.vae)
# Lazy import to break circular dependency:
# autoencoder_kl_hunyuan -> hunyuan_image3/__init__ -> pipeline_hunyuan_image3 -> autoencoder_kl_hunyuan
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_hunyuan import ( # noqa: PLC0415
DistributedAutoencoderKLHunyuan,
)
self.vae = DistributedAutoencoderKLHunyuan.from_config(self.hf_config.vae)
self.vae.use_spatial_tiling = self.od_config.vae_use_tiling
self._pipeline = None
self._tkwrapper = TokenizerWrapper(od_config.model)
@@ -17,7 +17,7 @@ import inspect
from collections.abc import Iterable
from dataclasses import dataclass
from types import SimpleNamespace
from typing import Any
from typing import TYPE_CHECKING, Any
import torch
import torch.distributed
@@ -39,6 +39,9 @@ from vllm.model_executor.layers.linear import (
)
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
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
@@ -173,7 +176,16 @@ class LTX2AdaLayerNormSingle(nn.Module):
class ColumnParallelApproxGELU(nn.Module):
def __init__(self, dim_in: int, dim_out: int, *, approximate: str, bias: bool = True):
def __init__(
self,
dim_in: int,
dim_out: int,
*,
approximate: str,
bias: bool = True,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
):
super().__init__()
self.proj = ColumnParallelLinear(
dim_in,
@@ -181,6 +193,8 @@ class ColumnParallelApproxGELU(nn.Module):
bias=bias,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.proj" if prefix else "proj",
)
self.approximate = approximate
@@ -200,6 +214,8 @@ class LTX2FeedForward(nn.Module):
bias: bool = True,
dropout: float = 0.0,
final_dropout: bool = False,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
) -> None:
super().__init__()
@@ -211,13 +227,22 @@ class LTX2FeedForward(nn.Module):
dropout_layer: nn.Module = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
layers: list[nn.Module] = [
ColumnParallelApproxGELU(dim, inner_dim, approximate="tanh", bias=bias),
ColumnParallelApproxGELU(
dim,
inner_dim,
approximate="tanh",
bias=bias,
quant_config=quant_config,
prefix=f"{prefix}.net.0" if prefix else "net.0",
),
dropout_layer,
RowParallelLinear(
inner_dim,
dim_out,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.net.2" if prefix else "net.2",
),
]
if final_dropout:
@@ -515,6 +540,9 @@ class LTX2Attention(torch.nn.Module):
rope_type: str = "interleaved",
apply_gated_attention: bool = False,
processor=None,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
disable_kv_quant: bool = False,
):
super().__init__()
# LTX-2 uses "rms_norm_across_heads", LTX-2.3 uses "rms_norm" -- both
@@ -548,6 +576,8 @@ class LTX2Attention(torch.nn.Module):
head_size=self.head_dim,
total_num_heads=heads,
bias=bias,
quant_config=quant_config,
prefix=f"{prefix}.to_qkv" if prefix else "to_qkv",
)
self.query_num_heads = self.to_qkv.num_heads
self.kv_num_heads = self.to_qkv.num_kv_heads
@@ -562,6 +592,8 @@ class LTX2Attention(torch.nn.Module):
bias=bias,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.to_q" if prefix else "to_q",
)
self.to_k = ColumnParallelLinear(
self.cross_attention_dim,
@@ -569,6 +601,8 @@ class LTX2Attention(torch.nn.Module):
bias=bias,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.to_k" if prefix else "to_k",
)
self.to_v = ColumnParallelLinear(
self.cross_attention_dim,
@@ -576,6 +610,8 @@ class LTX2Attention(torch.nn.Module):
bias=bias,
gather_output=False,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.to_v" if prefix else "to_v",
)
self.heads = self.query_num_heads
@@ -617,6 +653,8 @@ class LTX2Attention(torch.nn.Module):
bias=out_bias,
input_is_parallel=True,
return_bias=False,
quant_config=quant_config,
prefix=f"{prefix}.to_out.0" if prefix else "to_out.0",
),
torch.nn.Dropout(dropout) if dropout > 0 else torch.nn.Identity(),
]
@@ -627,9 +665,12 @@ class LTX2Attention(torch.nn.Module):
num_kv_heads=self.kv_num_heads,
softmax_scale=1.0 / (dim_head**0.5),
causal=False,
prefix=prefix,
disable_kv_quant=disable_kv_quant,
)
# LTX-2.3: per-head gated attention
# leave unquantized for this linear
if apply_gated_attention:
self.to_gate_logits = nn.Linear(query_dim, heads, bias=True)
else:
@@ -748,6 +789,8 @@ class LTX2VideoTransformerBlock(nn.Module):
elementwise_affine: bool = False,
rope_type: str = "interleaved",
perturbed_attn: bool = False,
quant_config: "QuantizationConfig | None" = None,
prefix: str = "",
):
super().__init__()
self.video_cross_attn_adaln = video_cross_attn_adaln
@@ -767,6 +810,8 @@ class LTX2VideoTransformerBlock(nn.Module):
qk_norm=qk_norm,
rope_type=rope_type,
apply_gated_attention=video_gated_attn,
quant_config=quant_config,
prefix=f"{prefix}.attn1" if prefix else "attn1",
)
self.audio_norm1 = _make_rms_norm(audio_dim, eps=eps, elementwise_affine=elementwise_affine)
@@ -781,6 +826,8 @@ class LTX2VideoTransformerBlock(nn.Module):
qk_norm=qk_norm,
rope_type=rope_type,
apply_gated_attention=audio_gated_attn,
quant_config=quant_config,
prefix=f"{prefix}.audio_attn1" if prefix else "audio_attn1",
)
# 2. Prompt Cross-Attention
@@ -796,6 +843,9 @@ class LTX2VideoTransformerBlock(nn.Module):
qk_norm=qk_norm,
rope_type=rope_type,
apply_gated_attention=video_gated_attn,
quant_config=quant_config,
prefix=f"{prefix}.attn2" if prefix else "attn2",
disable_kv_quant=True,
)
self.audio_norm2 = _make_rms_norm(audio_dim, eps=eps, elementwise_affine=elementwise_affine)
@@ -810,9 +860,14 @@ class LTX2VideoTransformerBlock(nn.Module):
qk_norm=qk_norm,
rope_type=rope_type,
apply_gated_attention=audio_gated_attn,
quant_config=quant_config,
prefix=f"{prefix}.audio_attn2" if prefix else "audio_attn2",
disable_kv_quant=True,
)
# 3. Audio-to-Video (a2v) and Video-to-Audio (v2a) Cross-Attention
# K/V here come from the other modality's latents (long sequences),
# so KV-cache quant remains enabled.
self.audio_to_video_norm = _make_rms_norm(dim, eps=eps, elementwise_affine=elementwise_affine)
self.audio_to_video_attn = LTX2Attention(
query_dim=dim,
@@ -825,6 +880,8 @@ class LTX2VideoTransformerBlock(nn.Module):
qk_norm=qk_norm,
rope_type=rope_type,
apply_gated_attention=video_gated_attn,
quant_config=quant_config,
prefix=f"{prefix}.audio_to_video_attn" if prefix else "audio_to_video_attn",
)
self.video_to_audio_norm = _make_rms_norm(audio_dim, eps=eps, elementwise_affine=elementwise_affine)
@@ -839,14 +896,26 @@ class LTX2VideoTransformerBlock(nn.Module):
qk_norm=qk_norm,
rope_type=rope_type,
apply_gated_attention=audio_gated_attn,
quant_config=quant_config,
prefix=f"{prefix}.video_to_audio_attn" if prefix else "video_to_audio_attn",
)
# 4. Feedforward layers
self.norm3 = _make_rms_norm(dim, eps=eps, elementwise_affine=elementwise_affine)
self.ff = LTX2FeedForward(dim, activation_fn=activation_fn)
self.ff = LTX2FeedForward(
dim,
activation_fn=activation_fn,
quant_config=quant_config,
prefix=f"{prefix}.ff" if prefix else "ff",
)
self.audio_norm3 = _make_rms_norm(audio_dim, eps=eps, elementwise_affine=elementwise_affine)
self.audio_ff = LTX2FeedForward(audio_dim, activation_fn=activation_fn)
self.audio_ff = LTX2FeedForward(
audio_dim,
activation_fn=activation_fn,
quant_config=quant_config,
prefix=f"{prefix}.audio_ff" if prefix else "audio_ff",
)
# 5. Per-Layer Modulation Parameters
# LTX-2.3 with cross_attn_adaln uses 9 params (extra 3 for cross-attn modulation);
@@ -1365,6 +1434,9 @@ class LTX2VideoTransformer3DModel(nn.Module):
_layerwise_offload_blocks_attrs = ["transformer_blocks"]
_hsdp_shard_conditions = [is_transformer_block_module]
_sp_plan: dict[str, Any] | None = None
packed_modules_mapping = {
"to_qkv": ["to_q", "to_k", "to_v"],
}
@staticmethod
def _build_sp_plan(rope_type: str) -> dict[str, Any]:
@@ -1453,6 +1525,7 @@ class LTX2VideoTransformer3DModel(nn.Module):
cross_attn_mod: bool = False,
audio_gated_attn: bool = False,
audio_cross_attn_mod: bool = False,
quant_config: "QuantizationConfig | None" = None,
) -> None:
super().__init__()
self.perturbed_attn = perturbed_attn
@@ -1647,8 +1720,10 @@ class LTX2VideoTransformer3DModel(nn.Module):
elementwise_affine=norm_elementwise_affine,
rope_type=rope_type,
perturbed_attn=perturbed_attn,
quant_config=quant_config,
prefix=f"transformer_blocks.{layer_idx}",
)
for _ in range(num_layers)
for layer_idx in range(num_layers)
]
)
@@ -9,10 +9,13 @@ import json
import os
from collections.abc import Iterable
from contextlib import nullcontext
from typing import Any, ClassVar
from typing import TYPE_CHECKING, Any, ClassVar
import numpy as np
import torch
if TYPE_CHECKING:
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from diffusers import AutoencoderKLLTX2Audio, AutoencoderKLLTX2Video, FlowMatchEulerDiscreteScheduler
from diffusers.pipelines.ltx2 import LTX2TextConnectors
from diffusers.pipelines.ltx2.utils import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES
@@ -67,14 +70,20 @@ def load_transformer_config(model_path: str, subfolder: str = "transformer", loc
return {}
def create_transformer_from_config(config: dict) -> LTX2VideoTransformer3DModel:
def create_transformer_from_config(
config: dict,
quant_config: QuantizationConfig | None = None,
) -> LTX2VideoTransformer3DModel:
"""Create LTX2VideoTransformer3DModel from config dict."""
if not config:
if not config and quant_config is None:
return LTX2VideoTransformer3DModel()
signature = inspect.signature(LTX2VideoTransformer3DModel.__init__)
allowed_keys = set(signature.parameters.keys())
kwargs = {k: v for k, v in config.items() if k in allowed_keys}
if quant_config is not None:
kwargs["quant_config"] = quant_config
return LTX2VideoTransformer3DModel(**kwargs)
@@ -214,7 +223,8 @@ class LTX2Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin):
).to(self.device)
transformer_config = load_transformer_config(model, "transformer", local_files_only)
self.transformer = create_transformer_from_config(transformer_config)
quant_config = getattr(self.od_config, "quantization_config", None)
self.transformer = create_transformer_from_config(transformer_config, quant_config=quant_config)
self.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
model, subfolder="scheduler", local_files_only=local_files_only
@@ -174,7 +174,8 @@ class LTX23Pipeline(nn.Module, ProgressBarMixin):
# --- Transformer: created empty, weights loaded via AutoWeightsLoader ---
transformer_config = load_transformer_config(model, "transformer", local_files_only)
self.transformer = create_transformer_from_config(transformer_config)
quant_config = getattr(self.od_config, "quantization_config", None)
self.transformer = create_transformer_from_config(transformer_config, quant_config=quant_config)
# --- Scheduler ---
self.scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
@@ -290,7 +290,22 @@ class QwenImagePipeline(nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineP
)
self.text_encoder = Qwen2_5_VLForConditionalGeneration.from_pretrained(
model, subfolder="text_encoder", local_files_only=local_files_only
).to(self.device)
)
# Qwen2.5-VL ships a vision tower that text-to-image does not use.
# Drop it while the model is still on CPU, before moving to GPU, so
# the vision tower never consumes GPU memory. Handle both transformers
# layouts: newer puts visual under .model, older puts it directly on
# the model.
visual_owner = None
if hasattr(self.text_encoder, "model") and hasattr(self.text_encoder.model, "visual"):
visual_owner = self.text_encoder.model
elif hasattr(self.text_encoder, "visual"):
visual_owner = self.text_encoder
if visual_owner is not None:
del visual_owner.visual
else:
logger.warning("Qwen-Image: vision tower not found on text encoder; skipping drop")
self.text_encoder = self.text_encoder.to(self.device)
self.vae = DistributedAutoencoderKLQwenImage.from_pretrained(
model, subfolder="vae", local_files_only=local_files_only
).to(self.device)
@@ -22,11 +22,6 @@ from .pipeline_wan2_2_s2v import (
get_wan22_s2v_post_process_func,
get_wan22_s2v_pre_process_func,
)
from .pipeline_wan2_2_ti2v import (
Wan22TI2VPipeline,
get_wan22_ti2v_post_process_func,
get_wan22_ti2v_pre_process_func,
)
from .pipeline_wan2_2_vace import (
Wan22VACEPipeline,
get_wan22_vace_post_process_func,
@@ -50,9 +45,6 @@ __all__ = [
"Wan22S2VPipeline",
"get_wan22_s2v_post_process_func",
"get_wan22_s2v_pre_process_func",
"Wan22TI2VPipeline",
"get_wan22_ti2v_post_process_func",
"get_wan22_ti2v_pre_process_func",
"Wan22VACEPipeline",
"get_wan22_vace_post_process_func",
"get_wan22_vace_pre_process_func",
@@ -17,10 +17,12 @@ from torch import nn
from transformers import AutoTokenizer, UMT5EncoderModel
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.sequence import IntermediateTensors
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
from vllm_omni.diffusion.distributed.pipeline_parallel import AsyncLatents, PipelineParallelMixin
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
@@ -120,8 +122,7 @@ def load_transformer_config(model_path: str, subfolder: str = "transformer", loc
def create_transformer_from_config(
config: dict,
quant_config: QuantizationConfig | None = None,
config: dict, quant_config: QuantizationConfig | None = None, prefix: str = ""
) -> WanTransformer3DModel:
"""Create WanTransformer3DModel from config dict."""
kwargs: dict = {}
@@ -157,57 +158,15 @@ def create_transformer_from_config(
if "pos_embed_seq_len" in config:
kwargs["pos_embed_seq_len"] = config["pos_embed_seq_len"]
# Auto-detect quantization from transformer's config.json when not explicitly provided.
# merge_mxfp8_checkpoint.py injects quantization_config into config.json so that
# offline quantized checkpoints are recognized here without a CLI flag.
if "quantization_config" in config:
from vllm_omni.quantization.factory import build_quant_config
from vllm_omni.quantization.factory import resolve_quant_config_from_disk
disk_qc = config["quantization_config"]
if isinstance(disk_qc, dict) and "quant_method" in disk_qc:
qc_method = disk_qc["quant_method"]
qc_kwargs = {k: v for k, v in disk_qc.items() if k != "quant_method"}
if quant_config is None:
# No CLI flag: full auto-detection.
quant_config = build_quant_config(qc_method, **qc_kwargs)
logger.info(
"Auto-detected quantization from transformer config.json: method=%s kwargs=%s",
qc_method,
qc_kwargs,
)
elif quant_config.get_name() != qc_method:
# The caller supplied a quant_config of a different method than
# what the checkpoint was built with. Loading serialized tensors
# (e.g. MXFP8 weight scales) with the wrong linear method would
# produce corrupt output or a shape mismatch crash. Reject early
# so the user gets a clear message instead of a silent failure.
raise ValueError(
f"Checkpoint config.json declares quant_method={qc_method!r} but the "
f"active quantization config is {quant_config.get_name()!r}. "
"Pass a matching --quantization flag or omit it for auto-detection."
)
elif (
qc_kwargs.get("is_checkpoint_mxfp8_serialized", False)
and hasattr(quant_config, "is_checkpoint_mxfp8_serialized")
and not quant_config.is_checkpoint_mxfp8_serialized
):
# Same method: CLI provided online mode but config.json marks this
# as a pre-quantized offline checkpoint. Switch to offline mode so
# users can pass --quantization mxfp8 without knowing the
# online/offline distinction.
quant_config = build_quant_config(qc_method, **qc_kwargs)
logger.info(
"config.json marks checkpoint as serialized; switching from online to offline MXFP8 mode.",
)
elif isinstance(disk_qc, str) and quant_config is None:
quant_config = build_quant_config(disk_qc)
logger.info(
"Auto-detected quantization from transformer config.json: method=%s",
disk_qc,
)
quant_config = resolve_quant_config_from_disk(quant_config, config["quantization_config"])
if quant_config is not None:
kwargs["quant_config"] = quant_config
if prefix:
kwargs["prefix"] = prefix
return WanTransformer3DModel(**kwargs)
@@ -297,7 +256,9 @@ def get_wan22_pre_process_func(
return pre_process_func
class Wan22Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, DiffusionPipelineProfilerMixin):
class Wan22Pipeline(
nn.Module, PipelineParallelMixin, CFGParallelMixin, ProgressBarMixin, DiffusionPipelineProfilerMixin
):
def __init__(
self,
*,
@@ -460,7 +421,7 @@ class Wan22Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, DiffusionPipe
attention_kwargs: dict[str, Any],
latent_condition: torch.Tensor | None = None,
first_frame_mask: torch.Tensor | None = None,
) -> torch.Tensor:
) -> torch.Tensor | AsyncLatents:
if attention_kwargs is None:
attention_kwargs = {}
with self.progress_bar(total=len(timesteps)) as pbar:
@@ -858,7 +819,11 @@ class Wan22Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, DiffusionPipe
output=output, stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None
)
def predict_noise(self, current_model: nn.Module | None = None, **kwargs: Any) -> torch.Tensor:
def predict_noise(
self,
current_model: nn.Module | None = None,
**kwargs: Any,
) -> torch.Tensor | IntermediateTensors:
"""
Forward pass through transformer to predict noise.
@@ -867,11 +832,12 @@ class Wan22Pipeline(nn.Module, CFGParallelMixin, ProgressBarMixin, DiffusionPipe
**kwargs: Arguments to pass to the transformer
Returns:
Predicted noise tensor
Predicted noise tensor or IntermediateTensors on non-last PP stages.
"""
if current_model is None:
current_model = self.transformer
return current_model(**kwargs)[0]
result = current_model(**kwargs)
return result if isinstance(result, IntermediateTensors) else result[0]
def encode_prompt(
self,
@@ -17,10 +17,12 @@ from diffusers.utils.torch_utils import randn_tensor
from torch import nn
from transformers import AutoTokenizer, CLIPImageProcessor, CLIPVisionModel, UMT5EncoderModel
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm.sequence import IntermediateTensors
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import DistributedAutoencoderKLWan
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
from vllm_omni.diffusion.distributed.pipeline_parallel import AsyncLatents, PipelineParallelMixin
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
@@ -135,7 +137,12 @@ def get_wan22_i2v_pre_process_func(
class Wan22I2VPipeline(
nn.Module, SupportImageInput, CFGParallelMixin, ProgressBarMixin, DiffusionPipelineProfilerMixin
nn.Module,
SupportImageInput,
PipelineParallelMixin,
CFGParallelMixin,
ProgressBarMixin,
DiffusionPipelineProfilerMixin,
):
"""
Wan2.2 Image-to-Video Pipeline.
@@ -224,10 +231,25 @@ class Wan22I2VPipeline(
# Transformers (weights loaded via load_weights)
# Load config from model directory or HF Hub to get correct in_channels for I2V models
transformer_config = load_transformer_config(model, "transformer", local_files_only)
self.transformer = self._create_transformer(transformer_config)
self.transformer = create_transformer_from_config(
transformer_config,
quant_config=od_config.quantization_config,
)
if self.has_transformer_2:
transformer_2_config = load_transformer_config(model, "transformer_2", local_files_only)
self.transformer_2 = self._create_transformer(transformer_2_config)
t2_quant = transformer_2_config.get("quantization_config")
if isinstance(t2_quant, dict) and "quant_method" in t2_quant:
from vllm_omni.quantization.factory import build_quant_config
method = t2_quant["quant_method"]
kwargs = {k: v for k, v in t2_quant.items() if k != "quant_method"}
t2_quant = build_quant_config(method, **kwargs)
else:
t2_quant = None
self.transformer_2 = create_transformer_from_config(
transformer_2_config,
quant_config=t2_quant,
)
else:
self.transformer_2 = None
@@ -283,7 +305,7 @@ class Wan22I2VPipeline(
attention_kwargs: dict[str, Any],
condition: torch.Tensor,
first_frame_mask: torch.Tensor,
) -> torch.Tensor:
) -> torch.Tensor | AsyncLatents:
if attention_kwargs is None:
attention_kwargs = {}
with self.progress_bar(total=len(timesteps)) as pbar:
@@ -348,7 +370,6 @@ class Wan22I2VPipeline(
# 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()
return latents
@@ -667,7 +688,11 @@ class Wan22I2VPipeline(
output=output, stage_durations=self.stage_durations if hasattr(self, "stage_durations") else None
)
def predict_noise(self, current_model: nn.Module | None = None, **kwargs: Any) -> torch.Tensor:
def predict_noise(
self,
current_model: nn.Module | None = None,
**kwargs: Any,
) -> torch.Tensor | IntermediateTensors:
"""
Forward pass through transformer to predict noise.
@@ -676,11 +701,12 @@ class Wan22I2VPipeline(
**kwargs: Arguments to pass to the transformer
Returns:
Predicted noise tensor
Predicted noise tensor or IntermediateTensors on non-last PP stages.
"""
if current_model is None:
current_model = self.transformer
return current_model(**kwargs)[0]
result = current_model(**kwargs)
return result if isinstance(result, IntermediateTensors) else result[0]
def encode_prompt(
self,
@@ -1,731 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Wan2.2 TI2V (Text-Image-to-Video) Pipeline.
This pipeline supports the unified TI2V-5B model that can generate videos from:
- Text only (T2V mode)
- Text + Image (I2V mode)
The key difference from the MoE-based I2V pipeline is:
- Single transformer (not MoE with two transformers)
- Uses expand_timesteps mode for image conditioning
- No CLIP image encoder - only VAE encoding for image condition
"""
from __future__ import annotations
import logging
import os
from collections.abc import Iterable
from typing import Any, cast
import numpy as np
import PIL.Image
import torch
from diffusers.utils.torch_utils import randn_tensor
from torch import nn
from transformers import AutoTokenizer, UMT5EncoderModel
from vllm.model_executor.models.utils import AutoWeightsLoader
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_wan import OmniAutoencoderKLWan
from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
from vllm_omni.diffusion.distributed.utils import get_local_device
from vllm_omni.diffusion.forward_context import set_forward_context_denoise_step_idx
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
from vllm_omni.diffusion.model_loader.hub_prefetch import prefetch_subfolders
from vllm_omni.diffusion.models.interface import SupportImageInput
from vllm_omni.diffusion.models.progress_bar import ProgressBarMixin
from vllm_omni.diffusion.models.wan2_2.pipeline_wan2_2 import (
build_wan_scheduler,
create_transformer_from_config,
load_transformer_config,
resolve_wan_flow_shift,
resolve_wan_sample_solver,
retrieve_latents,
)
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.request import OmniDiffusionRequest
from vllm_omni.inputs.data import OmniTextPrompt
from vllm_omni.platforms import current_omni_platform
logger = logging.getLogger(__name__)
def get_wan22_ti2v_post_process_func(
od_config: OmniDiffusionConfig,
):
from diffusers.video_processor import VideoProcessor
video_processor = VideoProcessor(vae_scale_factor=8)
def post_process_func(
video: torch.Tensor,
output_type: str = "np",
sampling_params=None,
):
if output_type == "latent":
return video
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
def get_wan22_ti2v_pre_process_func(
od_config: OmniDiffusionConfig,
):
"""Pre-process function for TI2V: optionally load and resize input image."""
def pre_process_func(request: OmniDiffusionRequest) -> OmniDiffusionRequest:
for i, prompt in enumerate(request.prompts):
multi_modal_data = prompt.get("multi_modal_data", {}) if not isinstance(prompt, str) else None
raw_image = multi_modal_data.get("image", None) if multi_modal_data is not None else None
if isinstance(prompt, str):
prompt = OmniTextPrompt(prompt=prompt)
if "additional_information" not in prompt:
prompt["additional_information"] = {}
if raw_image is None:
raise ValueError(
"""No image is provided. This model requires an image to run.""",
"""Please correctly set `"multi_modal_data": {"image": <an image object or file path>, …}`""",
)
if not isinstance(raw_image, (str, PIL.Image.Image)):
raise TypeError(
f"""Unsupported image format {raw_image.__class__}.""",
"""Please correctly set `"multi_modal_data": {"image": <an image object or file path>, …}`""",
)
image = PIL.Image.open(raw_image).convert("RGB") if isinstance(raw_image, str) else raw_image
# Calculate dimensions based on aspect ratio if not provided
if request.sampling_params.height is None or request.sampling_params.width is None:
# Default max area for 720P (TI2V-5B default)
max_area = 720 * 1280
aspect_ratio = image.height / image.width
# Calculate dimensions maintaining aspect ratio
mod_value = 16 # Must be divisible by 16
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
if request.sampling_params.height is None:
request.sampling_params.height = height
if request.sampling_params.width is None:
request.sampling_params.width = width
# Resize image to target dimensions
image = image.resize(
(request.sampling_params.width, request.sampling_params.height), # type: ignore # Above has ensured that width & height are not None
PIL.Image.Resampling.LANCZOS,
)
prompt["multi_modal_data"]["image"] = image # type: ignore # key existence already checked above
request.prompts[i] = prompt
return request
return pre_process_func
class Wan22TI2VPipeline(nn.Module, SupportImageInput, CFGParallelMixin, ProgressBarMixin):
"""
Wan2.2 Text-Image-to-Video (TI2V) Pipeline.
This is a unified pipeline that supports both:
- Text-to-Video (T2V): when no image is provided
- Image-to-Video (I2V): when an image is provided
Uses expand_timesteps mode for I2V conditioning where the first frame
is conditioned on the input image latent.
"""
def __init__(
self,
*,
od_config: OmniDiffusionConfig,
prefix: str = "",
):
super().__init__()
self.od_config = od_config
self.device = get_local_device()
dtype = getattr(od_config, "dtype", torch.bfloat16)
model = od_config.model
local_files_only = os.path.exists(model)
# Set up weights sources for single transformer
self.weights_sources = [
DiffusersPipelineLoader.ComponentSource(
model_or_path=od_config.model,
subfolder="transformer",
revision=None,
prefix="transformer.",
fall_back_to_pt=True,
),
]
# See ``hub_prefetch.py`` for the transformers v5 subfolder race.
prefetch_subfolders(
model,
["tokenizer", "text_encoder", "vae"],
local_files_only=local_files_only,
)
# Text encoder
self.tokenizer = AutoTokenizer.from_pretrained(model, subfolder="tokenizer", local_files_only=local_files_only)
self.text_encoder = UMT5EncoderModel.from_pretrained(
model, subfolder="text_encoder", torch_dtype=dtype, local_files_only=local_files_only
).to(self.device)
# VAE
self.vae = OmniAutoencoderKLWan.from_pretrained(
model, subfolder="vae", torch_dtype=dtype, local_files_only=local_files_only
).to(self.device)
# Single transformer (TI2V uses dense 5B model, not MoE)
# Load config from model to get correct dimensions
transformer_config = load_transformer_config(model, "transformer", local_files_only)
self.transformer = self._create_transformer(transformer_config)
self._sample_solver = "unipc"
self._flow_shift = od_config.flow_shift if od_config.flow_shift is not None else 5.0
self.scheduler = build_wan_scheduler(self._sample_solver, self._flow_shift)
# VAE scale factors
self.vae_scale_factor_temporal = self.vae.config.scale_factor_temporal if hasattr(self.vae, "config") else 4
self.vae_scale_factor_spatial = self.vae.config.scale_factor_spatial if hasattr(self.vae, "config") else 8
# TI2V always uses expand_timesteps mode
self.expand_timesteps = True
self._guidance_scale = None
self._num_timesteps = None
self._current_timestep = None
def _create_transformer(self, config: dict) -> WanTransformer3DModel:
"""Create a transformer from a config dict. Respects od_config.quantization_config."""
quant_config = getattr(self.od_config, "quantization_config", None)
return create_transformer_from_config(config, quant_config=quant_config)
@property
def guidance_scale(self):
return self._guidance_scale
@property
def do_classifier_free_guidance(self):
return self._guidance_scale is not None and self._guidance_scale > 1.0
@property
def num_timesteps(self):
return self._num_timesteps
@property
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:
if attention_kwargs is None:
attention_kwargs = {}
with self.progress_bar(total=len(timesteps)) as pbar:
for step_idx, t in enumerate(timesteps):
self._current_timestep = t
set_forward_context_denoise_step_idx(step_idx)
# 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,
prompt: str | None = None,
negative_prompt: str | None = None,
image: PIL.Image.Image | torch.Tensor | None = None,
height: int = 704,
width: int = 1280,
num_inference_steps: int = 40,
guidance_scale: float = 5.0,
frame_num: int = 81,
output_type: str | None = "np",
generator: torch.Generator | list[torch.Generator] | None = None,
prompt_embeds: torch.Tensor | None = None,
negative_prompt_embeds: torch.Tensor | None = None,
attention_kwargs: dict | None = None,
**kwargs,
) -> DiffusionOutput:
# Get parameters from request or arguments
if len(req.prompts) > 1:
raise ValueError(
"""This model only supports a single prompt, not a batched request.""",
"""Please pass in a single prompt object or string, or a single-item list.""",
)
if len(req.prompts) == 1: # If req.prompt is empty, default to prompt & neg_prompt in param list
prompt = req.prompts[0] if isinstance(req.prompts[0], str) else req.prompts[0].get("prompt")
negative_prompt = None if isinstance(req.prompts[0], str) else req.prompts[0].get("negative_prompt")
if prompt is None and prompt_embeds is None:
raise ValueError("Prompt or prompt_embeds is required for Wan2.2 generation.")
# Get image from request (optional for TI2V)
if image is None:
multi_modal_data = (
req.prompts[0].get("multi_modal_data", {}) if not isinstance(req.prompts[0], str) else None
)
raw_image = multi_modal_data.get("image", None) if multi_modal_data is not None else None
if isinstance(raw_image, list):
if len(raw_image) > 1:
logger.warning(
"""Received a list of image. Only a single image is supported by this model."""
"""Taking only the first image for now."""
)
raw_image = raw_image[0]
if raw_image is None:
image = None
elif isinstance(raw_image, str):
image = PIL.Image.open(raw_image)
else:
image = cast(PIL.Image.Image | torch.Tensor, raw_image)
# Default dimensions for TI2V-5B (720P)
height = req.sampling_params.height or height
width = req.sampling_params.width or width
num_frames = req.sampling_params.num_frames if req.sampling_params.num_frames else frame_num
num_steps = req.sampling_params.num_inference_steps or num_inference_steps
# Respect per-request guidance_scale when explicitly provided.
if req.sampling_params.guidance_scale_provided:
guidance_scale = req.sampling_params.guidance_scale
self._guidance_scale = guidance_scale
# Validate inputs
self.check_inputs(
prompt=prompt,
negative_prompt=negative_prompt,
image=image,
height=height,
width=width,
prompt_embeds=prompt_embeds,
negative_prompt_embeds=negative_prompt_embeds,
)
# Adjust num_frames to be compatible with VAE temporal scaling
if num_frames % self.vae_scale_factor_temporal != 1:
num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
num_frames = max(num_frames, 1)
device = self.device
dtype = self.transformer.dtype
# Generator setup
if generator is None:
generator = req.sampling_params.generator
if generator is None and req.sampling_params.seed is not None:
generator = torch.Generator(device=device).manual_seed(req.sampling_params.seed)
# Encode prompts
if prompt_embeds is None:
prompt_embeds, negative_prompt_embeds = self.encode_prompt(
prompt=prompt,
negative_prompt=negative_prompt,
do_classifier_free_guidance=guidance_scale > 1.0,
num_videos_per_prompt=req.sampling_params.num_outputs_per_prompt or 1,
max_sequence_length=req.sampling_params.max_sequence_length or 512,
device=device,
dtype=dtype,
)
else:
prompt_embeds = prompt_embeds.to(device=device, dtype=dtype)
if negative_prompt_embeds is not None:
negative_prompt_embeds = negative_prompt_embeds.to(device=device, dtype=dtype)
batch_size = prompt_embeds.shape[0]
sample_solver = resolve_wan_sample_solver(req, default=self._sample_solver)
flow_shift = resolve_wan_flow_shift(req, self.od_config)
if sample_solver != self._sample_solver or abs(flow_shift - self._flow_shift) > 1e-6:
self.scheduler = build_wan_scheduler(sample_solver, flow_shift)
self._sample_solver = sample_solver
self._flow_shift = flow_shift
# Timesteps
self.scheduler.set_timesteps(num_steps, device=device)
timesteps = self.scheduler.timesteps
self._num_timesteps = len(timesteps)
# Prepare latents
num_channels_latents = self.transformer.config.in_channels
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
latent_height = height // self.vae_scale_factor_spatial
latent_width = width // self.vae_scale_factor_spatial
# Check if we have an image (I2V mode) or not (T2V mode)
if image is not None:
# I2V mode: prepare latents with image condition
from diffusers.video_processor import VideoProcessor
video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
if isinstance(image, PIL.Image.Image):
image_tensor = video_processor.preprocess(image, height=height, width=width)
else:
image_tensor = image
image_tensor = image_tensor.to(device=device, dtype=torch.float32)
latents, latent_condition, first_frame_mask = self.prepare_i2v_latents(
image=image_tensor,
batch_size=batch_size,
num_channels_latents=num_channels_latents,
height=height,
width=width,
num_frames=num_frames,
dtype=torch.float32,
device=device,
generator=generator,
latents=req.sampling_params.latents,
)
else:
# T2V mode: prepare random latents
latents = self.prepare_latents(
batch_size=batch_size,
num_channels_latents=num_channels_latents,
height=height,
width=width,
num_frames=num_frames,
dtype=torch.float32,
device=device,
generator=generator,
latents=req.sampling_params.latents,
)
latent_condition = None
first_frame_mask = torch.ones(
1, 1, num_latent_frames, latent_height, latent_width, dtype=torch.float32, device=device
)
if attention_kwargs is None:
attention_kwargs = {}
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.
if current_omni_platform.is_available():
current_omni_platform.empty_cache()
self._current_timestep = None
# For I2V mode, blend final latents with condition
if latent_condition is not None:
latents = (1 - first_frame_mask) * latent_condition + first_frame_mask * latents
# Decode
if output_type == "latent":
output = latents
else:
latents = latents.to(self.vae.dtype)
latents_mean = (
torch.tensor(self.vae.config.latents_mean)
.view(1, self.vae.config.z_dim, 1, 1, 1)
.to(latents.device, latents.dtype)
)
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
latents.device, latents.dtype
)
latents = latents / latents_std + latents_mean
output = self.vae.decode(latents, return_dict=False)[0]
return DiffusionOutput(output=output)
def predict_noise(self, current_model: nn.Module | None = None, **kwargs: Any) -> torch.Tensor:
"""
Forward pass through transformer to predict noise.
Args:
current_model: The transformer model to use
**kwargs: Arguments to pass to the transformer
Returns:
Predicted noise tensor
"""
if current_model is None:
current_model = self.transformer
return current_model(**kwargs)[0]
def encode_prompt(
self,
prompt: str | list[str],
negative_prompt: str | list[str] | None = None,
do_classifier_free_guidance: bool = True,
num_videos_per_prompt: int = 1,
max_sequence_length: int = 512,
device: torch.device | None = None,
dtype: torch.dtype | None = None,
):
"""Encode text prompts using T5 text encoder."""
device = device or self.device
dtype = dtype or self.text_encoder.dtype
prompt = [prompt] if isinstance(prompt, str) else prompt
prompt_clean = [self._prompt_clean(p) for p in prompt]
batch_size = len(prompt_clean)
text_inputs = self.tokenizer(
prompt_clean,
padding="max_length",
max_length=max_sequence_length,
truncation=True,
add_special_tokens=True,
return_attention_mask=True,
return_tensors="pt",
)
ids, mask = text_inputs.input_ids, text_inputs.attention_mask
seq_lens = mask.gt(0).sum(dim=1).long()
prompt_embeds = self.text_encoder(ids.to(device), mask.to(device)).last_hidden_state
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
prompt_embeds = torch.stack(
[torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
)
_, seq_len, _ = prompt_embeds.shape
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
negative_prompt_embeds = None
if do_classifier_free_guidance:
negative_prompt = negative_prompt or ""
negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
neg_text_inputs = self.tokenizer(
[self._prompt_clean(p) for p in negative_prompt],
padding="max_length",
max_length=max_sequence_length,
truncation=True,
add_special_tokens=True,
return_attention_mask=True,
return_tensors="pt",
)
ids_neg, mask_neg = neg_text_inputs.input_ids, neg_text_inputs.attention_mask
seq_lens_neg = mask_neg.gt(0).sum(dim=1).long()
negative_prompt_embeds = self.text_encoder(ids_neg.to(device), mask_neg.to(device)).last_hidden_state
negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
negative_prompt_embeds = [u[:v] for u, v in zip(negative_prompt_embeds, seq_lens_neg)]
negative_prompt_embeds = torch.stack(
[
torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))])
for u in negative_prompt_embeds
],
dim=0,
)
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_videos_per_prompt, 1)
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
return prompt_embeds, negative_prompt_embeds
@staticmethod
def _prompt_clean(text: str) -> str:
return " ".join(text.strip().split())
def prepare_latents(
self,
batch_size: int,
num_channels_latents: int,
height: int,
width: int,
num_frames: int,
dtype: torch.dtype | None,
device: torch.device | None,
generator: torch.Generator | list[torch.Generator] | None,
latents: torch.Tensor | None = None,
) -> torch.Tensor:
"""Prepare random latents for T2V mode."""
if latents is not None:
return latents.to(device=device, dtype=dtype)
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
shape = (
batch_size,
num_channels_latents,
num_latent_frames,
int(height) // self.vae_scale_factor_spatial,
int(width) // self.vae_scale_factor_spatial,
)
if isinstance(generator, list) and len(generator) != batch_size:
raise ValueError(f"Generator list length {len(generator)} does not match batch size {batch_size}.")
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
return latents
def prepare_i2v_latents(
self,
image: torch.Tensor,
batch_size: int,
num_channels_latents: int,
height: int,
width: int,
num_frames: int,
dtype: torch.dtype | None,
device: torch.device | None,
generator: torch.Generator | list[torch.Generator] | None,
latents: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Prepare latents for I2V mode with image conditioning.
Returns:
latents: Initial noise latents
latent_condition: Encoded first frame condition
first_frame_mask: Mask (0 for first frame, 1 for rest)
"""
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
latent_height = height // self.vae_scale_factor_spatial
latent_width = width // self.vae_scale_factor_spatial
shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
if latents is None:
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
else:
latents = latents.to(device=device, dtype=dtype)
# Prepare first frame condition
image = image.unsqueeze(2) # [batch, channels, 1, height, width]
image = image.to(device=device, dtype=self.vae.dtype)
# Encode through VAE
latent_condition = retrieve_latents(self.vae.encode(image), sample_mode="argmax")
latent_condition = latent_condition.repeat(batch_size, 1, 1, 1, 1)
# Normalize latents
latents_mean = (
torch.tensor(self.vae.config.latents_mean)
.view(1, self.vae.config.z_dim, 1, 1, 1)
.to(latent_condition.device, latent_condition.dtype)
)
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
latent_condition.device, latent_condition.dtype
)
latent_condition = (latent_condition - latents_mean) * latents_std
latent_condition = latent_condition.to(dtype)
# Create mask: 0 for first frame (condition), 1 for rest (to denoise)
first_frame_mask = torch.ones(1, 1, num_latent_frames, latent_height, latent_width, dtype=dtype, device=device)
first_frame_mask[:, :, 0] = 0
return latents, latent_condition, first_frame_mask
def check_inputs(
self,
prompt,
negative_prompt,
image,
height,
width,
prompt_embeds=None,
negative_prompt_embeds=None,
):
if height % 16 != 0 or width % 16 != 0:
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
if prompt is not None and prompt_embeds is not None:
raise ValueError("Cannot forward both `prompt` and `prompt_embeds`. Please provide only one.")
if negative_prompt is not None and negative_prompt_embeds is not None:
raise ValueError(
"Cannot forward both `negative_prompt` and `negative_prompt_embeds`. Please provide only one."
)
if prompt is None and prompt_embeds is None:
raise ValueError("Provide either `prompt` or `prompt_embeds`.")
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
"""Load weights using AutoWeightsLoader for vLLM integration."""
loader = AutoWeightsLoader(self)
return loader.load_weights(weights)
@@ -45,6 +45,7 @@ logger = init_logger(__name__)
def create_vace_transformer_from_config(
config: dict,
quant_config: QuantizationConfig | None = None,
prefix: str = "",
) -> WanVACETransformer3DModel:
"""Create WanVACETransformer3DModel from config dict."""
kwargs = {}
@@ -84,6 +85,8 @@ def create_vace_transformer_from_config(
kwargs["vace_in_channels"] = config["vace_in_channels"]
if quant_config is not None:
kwargs["quant_config"] = quant_config
if prefix:
kwargs["prefix"] = prefix
return WanVACETransformer3DModel(**kwargs)
@@ -21,9 +21,21 @@ from vllm.model_executor.layers.conv import Conv3dLayer
from vllm.model_executor.layers.linear import ColumnParallelLinear, QKVParallelLinear, RowParallelLinear
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.models.utils import (
PPMissingLayer,
is_pp_missing_parameter,
make_empty_intermediate_tensors_factory,
make_layers,
)
from vllm.sequence import IntermediateTensors
from vllm_omni.diffusion.attention.backends.abstract import AttentionMetadata
from vllm_omni.diffusion.attention.layer import Attention
from vllm_omni.diffusion.distributed.parallel_state import (
get_pipeline_parallel_world_size,
is_pipeline_first_stage,
is_pipeline_last_stage,
)
from vllm_omni.diffusion.distributed.sp_plan import (
SequenceParallelInput,
SequenceParallelOutput,
@@ -871,14 +883,23 @@ class WanTransformer3DModel(nn.Module):
inner_dim = num_attention_heads * attention_head_dim
out_channels = out_channels or in_channels
if get_pipeline_parallel_world_size() == 0 and not is_pipeline_first_stage():
raise RuntimeError(
"`initialize_model_parallel()` must be called before constructing `WanTransformer3DModel`"
)
# 1. Patch & position embedding
self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
self.patch_embedding = Conv3dLayer(
in_channels=in_channels,
out_channels=inner_dim,
kernel_size=patch_size,
stride=patch_size,
)
# Patch embedding only on first PP stage; other stages receive hidden_states via P2P
if is_pipeline_first_stage():
self.patch_embedding = Conv3dLayer(
in_channels=in_channels,
out_channels=inner_dim,
kernel_size=patch_size,
stride=patch_size,
)
else:
self.patch_embedding = PPMissingLayer()
# 2. Condition embeddings
self.condition_embedder = WanTimeTextImageEmbedding(
@@ -890,30 +911,39 @@ class WanTransformer3DModel(nn.Module):
pos_embed_seq_len=pos_embed_seq_len,
)
# 3. Transformer blocks
self.blocks = nn.ModuleList(
[
WanTransformerBlock(
inner_dim,
ffn_dim,
num_attention_heads,
eps,
added_kv_proj_dim,
cross_attn_norm,
quant_config=quant_config,
prefix=f"blocks.{layer_idx}",
)
for layer_idx in range(num_layers)
]
# 3. Transformer blocks — partitioned across PP stages via vLLM's `make_layers`.
# It computes the [start_layer, end_layer) slice for this rank and fills the remaining slots
# with PPMissingLayer so that weight names stay globally consistent.
self.start_layer, self.end_layer, self.blocks = make_layers(
num_layers,
lambda prefix: WanTransformerBlock(
inner_dim,
ffn_dim,
num_attention_heads,
eps,
added_kv_proj_dim,
cross_attn_norm,
quant_config=quant_config,
prefix=prefix,
),
prefix="blocks",
)
# 4. Output norm & projection
self.norm_out = AdaLayerNorm(inner_dim, elementwise_affine=False, eps=eps)
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
# 4. Output norm & projection — only on the last PP stage
if is_pipeline_last_stage():
self.norm_out = AdaLayerNorm(inner_dim, elementwise_affine=False, eps=eps)
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
else:
self.norm_out, self.proj_out = PPMissingLayer(), PPMissingLayer()
# SP helper modules
self.timestep_proj_prepare = TimestepProjPrepare()
self.output_scale_shift_prepare = OutputScaleShiftPrepare(inner_dim)
if is_pipeline_last_stage():
self.output_scale_shift_prepare = OutputScaleShiftPrepare(inner_dim)
else:
self.output_scale_shift_prepare = PPMissingLayer()
self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(["hidden_states"], inner_dim)
# ROPE helper
self._cached_rope_emb = None
@@ -930,9 +960,10 @@ class WanTransformer3DModel(nn.Module):
timestep: torch.LongTensor,
encoder_hidden_states: torch.Tensor,
encoder_hidden_states_image: torch.Tensor | None = None,
intermediate_tensors: IntermediateTensors | None = None,
return_dict: bool = True,
attention_kwargs: dict[str, Any] | None = None,
) -> torch.Tensor | Transformer2DModelOutput:
) -> torch.Tensor | Transformer2DModelOutput | IntermediateTensors:
batch_size, num_channels, num_frames, height, width = hidden_states.shape
p_t, p_h, p_w = self.config.patch_size
post_patch_num_frames = num_frames // p_t
@@ -949,18 +980,25 @@ class WanTransformer3DModel(nn.Module):
self._hidden_states_shape = hidden_states.shape
self._cached_rope_emb = rotary_emb
# Patch embedding and flatten to sequence
# (hidden_states is sharded at blocks.0 input by _sp_plan)
hidden_states = self.patch_embedding(hidden_states)
hidden_states = hidden_states.flatten(2).transpose(1, 2)
if is_pipeline_first_stage():
# Patch embedding and flatten to sequence
# (hidden_states is sharded at blocks.0 input by _sp_plan)
hidden_states = self.patch_embedding(hidden_states)
hidden_states = hidden_states.flatten(2).transpose(1, 2)
else:
if intermediate_tensors is None:
raise RuntimeError("intermediate_tensors must be provided for non-first PP stages")
hidden_states = intermediate_tensors["hidden_states"]
# Handle timestep shape
# Handle timestep shape (2-D for TI2V, 1-D for T2V)
if timestep.ndim == 2:
ts_seq_len = timestep.shape[1]
timestep = timestep.flatten()
else:
ts_seq_len = None
# Compute conditioning on all PP stages.
# Each stage needs temb/timestep_proj for scale-shift modulation in its local blocks.
temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
timestep, encoder_hidden_states, encoder_hidden_states_image, timestep_seq_len=ts_seq_len
)
@@ -996,14 +1034,13 @@ class WanTransformer3DModel(nn.Module):
hidden_states_mask = None
# Transformer blocks
for block in self.blocks:
hidden_states = block(
hidden_states,
encoder_hidden_states,
timestep_proj,
rotary_emb,
hidden_states_mask,
)
for block in self.blocks[self.start_layer : self.end_layer]:
hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, hidden_states_mask)
if not is_pipeline_last_stage():
# Non-last PP stage: hand the token sequence to the caller via IntermediateTensors.
# predict_noise will broadcast it to the next stage before calling that stage's forward.
return IntermediateTensors({"hidden_states": hidden_states})
# Output norm, projection & unpatchify
shift, scale = self.output_scale_shift_prepare(temb)
@@ -1074,7 +1111,8 @@ class WanTransformer3DModel(nn.Module):
if weight_name not in original_name:
continue
lookup_name = original_name.replace(weight_name, param_name)
if lookup_name not in params_dict:
# Skip weights that belong to PP stages other than this one
if is_pp_missing_parameter(lookup_name, self) or lookup_name not in params_dict:
break
param = params_dict[lookup_name]
weight_loader = param.weight_loader
@@ -1098,6 +1136,10 @@ class WanTransformer3DModel(nn.Module):
if modulation_alias in params_dict:
lookup_name = modulation_alias
# Skip weights that belong to PP stages other than this one
if is_pp_missing_parameter(lookup_name, self):
continue
if lookup_name not in params_dict:
logger.warning(f"Skipping weight {original_name} -> {lookup_name}")
continue
+8 -2
View File
@@ -22,7 +22,9 @@ from vllm_omni.diffusion.sched.interface import (
logger = init_logger(__name__)
_KEY_FIELD_NAMES = frozenset(f.name for f in fields(SamplingParamsKey))
# LoRA identity is derived from `sampling.lora_request`, not a same-named field
# on sampling params, so it must be resolved separately from the bulk lookup.
_KEY_FIELD_NAMES = frozenset(f.name for f in fields(SamplingParamsKey)) - {"lora_int_id"}
def get_sampling_params_key(request: OmniDiffusionRequest) -> SamplingParamsKey | None:
@@ -31,7 +33,11 @@ def get_sampling_params_key(request: OmniDiffusionRequest) -> SamplingParamsKey
return None
sampling = request.sampling_params
return SamplingParamsKey(**{name: getattr(sampling, name) for name in _KEY_FIELD_NAMES})
lora_request = getattr(sampling, "lora_request", None)
return SamplingParamsKey(
lora_int_id=lora_request.lora_int_id if lora_request is not None else None,
**{name: getattr(sampling, name) for name in _KEY_FIELD_NAMES},
)
class _BaseScheduler(SchedulerInterface):
+5
View File
@@ -65,6 +65,11 @@ class SamplingParamsKey:
true_cfg_scale: float | None = None
cfg_normalize: bool = False
# LoRA identity. Requests with different adapters or scales must run in
# separate batches so the worker can activate exactly one adapter per step.
lora_int_id: int | None = None
lora_scale: float = 1.0
@dataclass
class DiffusionRequestState:
+23 -4
View File
@@ -17,6 +17,7 @@ from threading import Thread
from typing import TYPE_CHECKING, Any
import zmq
import zmq.asyncio
from vllm.logger import init_logger
from vllm.v1.engine.exceptions import EngineDeadError
@@ -124,6 +125,11 @@ class StageDiffusionClient(StageClientBase):
self.engine_input_source = getattr(metadata, "engine_input_source", [])
self._proc = proc
self._owns_process = proc is not None
# Expose the ZMQ addresses on the instance so callers (e.g.
# ``StagePool._client_input_addr``) can identify the diffusion
# replica by its bound address.
self.request_address = request_address
self.response_address = response_address
self._zmq_ctx = zmq.Context()
self._request_socket = self._zmq_ctx.socket(zmq.PUSH)
@@ -131,6 +137,9 @@ class StageDiffusionClient(StageClientBase):
self._response_socket = self._zmq_ctx.socket(zmq.PULL)
self._response_socket.connect(response_address)
self._response_poller = zmq.asyncio.Poller()
self._response_poller.register(self._response_socket, zmq.POLLIN)
self._encoder = OmniMsgpackEncoder()
self._decoder = OmniMsgpackDecoder()
@@ -468,17 +477,27 @@ class StageDiffusionClient(StageClientBase):
try:
while True:
self._drain_responses()
if rpc_id in self._rpc_results:
return self._rpc_results.pop(rpc_id)
result = self._rpc_results.pop(rpc_id, None)
if result is not None:
return result
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})"
)
if deadline and time.monotonic() > deadline:
if deadline is not None and time.monotonic() > deadline:
raise TimeoutError(f"collective_rpc_async '{method}' timed out after {timeout}s")
await asyncio.sleep(0.01)
# Block (async) until data arrives on the ZMQ response
# socket or until the timeout expires, then loop back to
# drain and check.
if deadline is not None:
poll_timeout_ms = max(int((deadline - time.monotonic()) * 1000), 0)
else:
poll_timeout_ms = 100
# no exception raised on timeout (capped at 100ms so the
# engine-dead check still fires regularly).
await self._response_poller.poll(timeout=min(poll_timeout_ms, 100))
finally:
self._pending_rpcs.discard(rpc_id)
+158 -2
View File
@@ -7,6 +7,7 @@ communicating with StageDiffusionClient via ZMQ (PUSH/PULL).
from __future__ import annotations
import asyncio
import contextlib
import signal
import time
from concurrent.futures import ThreadPoolExecutor
@@ -30,6 +31,7 @@ from vllm_omni.distributed.omni_connectors.utils.serialization import (
OmniMsgpackDecoder,
OmniMsgpackEncoder,
)
from vllm_omni.distributed.omni_coordinator import OmniCoordClientForStage
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
@@ -54,6 +56,56 @@ class StageDiffusionProc:
self._engine: DiffusionEngine | None = None
self._executor: ThreadPoolExecutor | None = None
self._closed = False
# Set by ``run_loop`` to the live dispatch task dict so
# :attr:`queue_length` can report in-flight requests for the
# OmniCoordinator heartbeat hook.
self._active_tasks: dict[str, asyncio.Task] | None = None
# Set when a request-handler detects that the engine's multiproc
# executor has died (e.g. a worker process crashed and the executor's
# monitor thread closed it). Once set, ``run_loop`` breaks out so the
# outer ``except``/``finally`` can send ``DIFFUSION_PROC_DEAD`` and
# ``ReplicaStatus.DOWN``, then the subprocess exits non-zero. Without
# this, the run_loop would swallow per-request errors and keep
# serving 500s indefinitely while heartbeats still report UP.
self._fatal_event: asyncio.Event | None = None
@property
def queue_length(self) -> int:
"""Number of in-flight diffusion requests.
Returns 0 before :meth:`run_loop` starts and after it exits.
"""
tasks = self._active_tasks
return 0 if tasks is None else len(tasks)
def _is_executor_dead(self) -> bool:
"""True iff the multiproc executor has been closed or marked failed.
Detects the "workers died but the diffusion proc is still pulling
requests" case: ``MultiprocDiffusionExecutor`` sets ``_closed = True``
and ``is_failed = True`` from its worker-monitor thread the moment any
worker process exits; every subsequent ``execute_request`` /
``collective_rpc`` then raises ``RuntimeError("DiffusionExecutor is
closed.")`` inside the engine. Callers in ``run_loop`` use this to
decide whether a per-request failure is recoverable or fatal.
"""
if self._engine is None:
return False
executor = getattr(self._engine, "executor", None)
if executor is None:
return False
return bool(getattr(executor, "_closed", False) or getattr(executor, "is_failed", False))
def _signal_fatal_engine_failure(self, reason: str) -> None:
"""Idempotently signal ``run_loop`` to tear down on a fatal engine error."""
if self._fatal_event is None or self._fatal_event.is_set():
return
logger.error(
"[StageDiffusionProc] fatal engine failure detected (%s); "
"signaling run_loop to send DIFFUSION_PROC_DEAD and exit.",
reason,
)
self._fatal_event.set()
# ------------------------------------------------------------------
# Initialization
@@ -309,6 +361,14 @@ class StageDiffusionProc:
decoder = OmniMsgpackDecoder()
tasks: dict[str, asyncio.Task] = {}
# Expose the live task dict so :attr:`queue_length` (used by the
# OmniCoordinator heartbeat hook) can read the in-flight count.
self._active_tasks = tasks
# Wakes the main recv loop when a request-handler detects a fatal
# engine failure so we tear down promptly instead of swallowing
# "DiffusionExecutor is closed" on every subsequent request.
fatal_event = asyncio.Event()
self._fatal_event = fatal_event
async def _dispatch_request(
request_id: str,
@@ -342,12 +402,40 @@ class StageDiffusionProc:
}
)
)
# Per-request errors are usually recoverable, but a closed
# executor means every future request will get the same
# "DiffusionExecutor is closed" error. Signal the main loop
# to send DIFFUSION_PROC_DEAD and exit so the head's hub
# demotes this replica instead of waiting on the heartbeat
# timeout (~30 s by default).
if self._is_executor_dead():
self._signal_fatal_engine_failure(f"add_request {request_id}: {e!s}")
finally:
tasks.pop(request_id, None)
try:
while True:
raw = await request_socket.recv()
# Await recv and fatal_event concurrently so the loop wakes
# up immediately when a per-request handler signals a fatal
# engine failure — even if no fresh ZMQ frame arrives.
recv_task: asyncio.Task = asyncio.ensure_future(request_socket.recv())
fatal_task: asyncio.Task = asyncio.ensure_future(fatal_event.wait())
try:
done, pending = await asyncio.wait(
[recv_task, fatal_task],
return_when=asyncio.FIRST_COMPLETED,
)
finally:
for waiter in (recv_task, fatal_task):
if not waiter.done():
waiter.cancel()
with contextlib.suppress(asyncio.CancelledError, Exception):
await waiter
if fatal_event.is_set():
raise RuntimeError(
"StageDiffusionProc executor reported permanent failure; tearing down the diffusion subprocess."
)
raw = recv_task.result()
msg = decoder.decode(raw)
msg_type = msg.get("type")
@@ -397,6 +485,11 @@ class StageDiffusionProc:
}
)
)
# Same rationale as the single-request path: a
# closed executor turns every subsequent batch
# into a 500, so escalate now.
if self._is_executor_dead():
self._signal_fatal_engine_failure(f"add_batch_request {rid}: {e!s}")
finally:
tasks.pop(rid, None)
@@ -446,6 +539,13 @@ class StageDiffusionProc:
}
)
)
# Collective RPCs run through the same multiproc
# executor — a closed executor means every future
# RPC fails the same way, so tear down promptly.
if self._is_executor_dead():
self._signal_fatal_engine_failure(
f"collective_rpc {msg['method']} (rpc_id={rpc_id}): {e!s}"
)
elif msg_type == "shutdown":
break
@@ -466,6 +566,8 @@ class StageDiffusionProc:
if tasks:
await asyncio.gather(*tasks.values(), return_exceptions=True)
self._active_tasks = None
self._fatal_event = None
request_socket.close()
response_socket.close()
ctx.term()
@@ -504,8 +606,22 @@ class StageDiffusionProc:
handshake_address: str,
request_address: str,
response_address: str,
*,
omni_coordinator_address: str | None = None,
omni_stage_id: int | None = None,
omni_replica_id: int = 0,
) -> None:
"""Entry point for the diffusion subprocess."""
"""Entry point for the diffusion subprocess.
Omni-specific kwargs (mirroring :meth:`StageEngineCoreProc.run_stage_core`):
- ``omni_coordinator_address``: ROUTER address of the head-side
OmniCoordinator. When set, a :class:`OmniCoordClientForStage`
reports the diffusion replica's status + queue length.
- ``omni_stage_id``: logical stage id; required when
``omni_coordinator_address`` is set.
- ``omni_replica_id``: cluster-unique replica id within the
stage (logging / metrics only).
"""
shutdown_requested = False
def signal_handler(signum: int, frame: Any) -> None:
@@ -518,6 +634,7 @@ class StageDiffusionProc:
signal.signal(signal.SIGINT, signal_handler)
proc = cls(model, od_config)
coord_client: OmniCoordClientForStage | None = None
try:
proc.initialize()
@@ -529,6 +646,32 @@ class StageDiffusionProc:
handshake_socket.close()
handshake_ctx.term()
# Wire OmniCoordClientForStage *after* READY so that the head
# has bound its head-side request/response sockets — the
# address pair we report is the same pair this proc binds to
# (request/response addresses passed in).
if omni_coordinator_address is not None:
if omni_stage_id is None:
raise ValueError("omni_stage_id must be provided when omni_coordinator_address is set")
coord_client = OmniCoordClientForStage(
coord_zmq_addr=omni_coordinator_address,
input_addr=request_address,
output_addr=response_address,
stage_id=int(omni_stage_id),
)
def _refresh_queue_length() -> None:
coord_client._queue_length = proc.queue_length # type: ignore[union-attr]
coord_client._on_heartbeat = _refresh_queue_length
logger.info(
"StageDiffusionProc registered with OmniCoordinator (stage_id=%d replica_id=%d coord=%s)",
omni_stage_id,
omni_replica_id,
omni_coordinator_address,
)
# Run async event loop
asyncio.run(proc.run_loop(request_address, response_address))
@@ -539,6 +682,9 @@ class StageDiffusionProc:
logger.exception("StageDiffusionProc encountered a fatal error.")
raise
finally:
if coord_client is not None:
with contextlib.suppress(RuntimeError):
coord_client.close()
proc.close()
@@ -551,10 +697,17 @@ def spawn_diffusion_proc(
handshake_address: str | None = None,
request_address: str | None = None,
response_address: str | None = None,
*,
omni_coordinator_address: str | None = None,
omni_stage_id: int | None = None,
omni_replica_id: int = 0,
) -> tuple[BaseProcess, str, str, str]:
"""Spawn a StageDiffusionProc subprocess.
Returns ``(proc, handshake_address, request_address, response_address)``.
Pass ``omni_coordinator_address`` / ``omni_stage_id`` / ``omni_replica_id``
to have the subprocess publish heartbeats to an OmniCoordinator.
"""
handshake_address = handshake_address or get_open_zmq_ipc_path()
request_address = request_address or get_open_zmq_ipc_path()
@@ -570,6 +723,9 @@ def spawn_diffusion_proc(
"handshake_address": handshake_address,
"request_address": request_address,
"response_address": response_address,
"omni_coordinator_address": omni_coordinator_address,
"omni_stage_id": omni_stage_id,
"omni_replica_id": omni_replica_id,
},
)
proc.start()
+42 -7
View File
@@ -185,6 +185,10 @@ class DiffusionWorker:
self.model_runner: DiffusionModelRunner | None = None
self._sleep_saved_buffers: dict[str, torch.Tensor] = {}
self.lora_manager: DiffusionLoRAManager | None = None
# Worker-side cache of (lora_request, lora_scale) per scheduled
# request id. Used by step mode to recover LoRA identity for cached
# requests, which only carry their sched_req_id in subsequent ticks.
self._step_lora_state: dict[str, tuple[LoRARequest | None, float]] = {}
self.stage_id = getattr(od_config, "stage_id", 0)
self.init_device()
# Create model runner using the platform-specified class
@@ -367,13 +371,7 @@ class DiffusionWorker:
def execute_stepwise(self, scheduler_output: DiffusionSchedulerOutput) -> BaseRunnerOutput:
"""Execute one diffusion step by delegating to the model runner."""
assert self.model_runner is not None, "Model runner not initialized"
if self.lora_manager is not None:
# Step mode does not support LoRA yet. Clear any previously active
# adapter first so worker-local LoRA state cannot leak in.
self.lora_manager.set_active_adapter(None)
if any(new_req.req.sampling_params.lora_request is not None for new_req in scheduler_output.scheduled_new_reqs):
raise ValueError("Step mode does not support LoRA yet.")
self._activate_step_lora(scheduler_output)
profiler = self._get_profiler()
ctx = profiler.annotate_context_manager("diffusion_step") if profiler else nullcontext()
with ctx:
@@ -382,6 +380,43 @@ class DiffusionWorker:
profiler.step()
return output
def _activate_step_lora(self, scheduler_output: DiffusionSchedulerOutput) -> None:
"""Activate the LoRA adapter for the scheduled step batch.
Newly scheduled requests register their (lora_request, lora_scale)
in ``_step_lora_state`` so cached requests can resolve to the same
adapter on later ticks. Finished requests are evicted. Batch
homogeneity is enforced by the scheduler via ``SamplingParamsKey``,
so any scheduled request id resolves to the active LoRA identity.
"""
for sched_req_id in scheduler_output.finished_req_ids:
self._step_lora_state.pop(sched_req_id, None)
for new_req in scheduler_output.scheduled_new_reqs:
sampling = new_req.req.sampling_params
self._step_lora_state[new_req.sched_req_id] = (
sampling.lora_request,
sampling.lora_scale,
)
if self.lora_manager is None:
return
lora_request: LoRARequest | None = None
lora_scale = 1.0
for sched_req_id in scheduler_output.scheduled_req_ids:
entry = self._step_lora_state.get(sched_req_id)
if entry is not None:
lora_request, lora_scale = entry
break
try:
self.lora_manager.set_active_adapter(lora_request, lora_scale)
except Exception as exc:
if lora_request is not None:
raise
logger.warning("LoRA activation skipped: %s", exc)
def load_weights(self, weights) -> set[str]:
"""Load weights by delegating to the model runner."""
assert self.model_runner is not None, "Model runner not initialized"
+2
View File
@@ -11,6 +11,7 @@ from .omni_connectors import (
OmniTransferConfig,
SharedMemoryConnector,
YuanrongConnector,
YuanrongTransferEngineConnector,
load_omni_transfer_config,
)
@@ -26,6 +27,7 @@ __all__ = [
"MooncakeTransferEngineConnector",
"SharedMemoryConnector",
"YuanrongConnector",
"YuanrongTransferEngineConnector",
# Utilities
"load_omni_transfer_config",
]
@@ -6,6 +6,13 @@ from .connectors.mooncake_store_connector import MooncakeStoreConnector
from .connectors.shm_connector import SharedMemoryConnector
from .connectors.yuanrong_connector import YuanrongConnector
try:
from vllm_omni.platforms.npu.omni_connectors.yuanrong_transfer_engine_connector import (
YuanrongTransferEngineConnector,
)
except ImportError:
YuanrongTransferEngineConnector = None
try:
from .connectors.mooncake_transfer_engine_connector import MooncakeTransferEngineConnector
except ImportError:
@@ -39,6 +46,7 @@ __all__ = [
"MooncakeTransferEngineConnector",
"SharedMemoryConnector",
"YuanrongConnector",
"YuanrongTransferEngineConnector",
# Utilities
"load_omni_transfer_config",
"initialize_connectors_from_config",
@@ -16,6 +16,7 @@ import torch
import zmq
from ..utils.logging import get_connector_logger
from ..utils.memory_pool import BufferAllocator, ManagedBuffer
from ..utils.serialization import OmniSerializer
from .base import OmniConnectorBase
@@ -66,160 +67,6 @@ class MooncakeAgentMetadata:
lengths: list[int]
class BufferAllocator:
"""
Manages the allocation of memory segments within the registered pool.
Thread-safe implementation using a simple free list.
"""
def __init__(self, total_size: int, alignment: int = 4096):
self.total_size = total_size
self.alignment = alignment
self.lock = threading.Lock()
# Free list: [(start, size), ...] sorted by start
self.free_blocks = [(0, total_size)]
def alloc(self, size: int) -> int:
"""
Allocates a block of 'size' bytes.
Returns the starting offset.
"""
# Align size upwards
aligned_size = (size + self.alignment - 1) // self.alignment * self.alignment
with self.lock:
for i, (start, block_size) in enumerate(self.free_blocks):
if block_size >= aligned_size:
# Found a block
new_start = start + aligned_size
new_size = block_size - aligned_size
if new_size > 0:
self.free_blocks[i] = (new_start, new_size)
else:
self.free_blocks.pop(i)
return start
raise MemoryError(f"Out of memory in buffer pool. Requested {size} bytes (aligned {aligned_size}).")
def free(self, offset: int, size: int):
"""
Frees a previously allocated block.
"""
aligned_size = (size + self.alignment - 1) // self.alignment * self.alignment
with self.lock:
# Check for double-free and corruption
for start, length in self.free_blocks:
# Case 1: Exact match = double free, safe to ignore
if offset == start and aligned_size == length:
logger.warning(f"Double free detected at offset {offset}, size {aligned_size}. Ignoring.")
return
# Case 2: Block is fully contained within an existing free block = also double free
# This happens when the block was freed and then merged with adjacent blocks
if offset >= start and offset + aligned_size <= start + length:
logger.warning(
f"Double free detected: block {offset}-{offset + aligned_size} "
f"is already within free block {start}-{start + length}. Ignoring."
)
return
# Case 3: Partial overlap (but not fully contained) = memory corruption
if not (offset + aligned_size <= start or start + length <= offset):
raise RuntimeError(
f"Memory corruption detected: freeing {offset}-{offset + aligned_size} "
f"partially overlaps with free block {start}-{start + length}"
)
self.free_blocks.append((offset, aligned_size))
self.free_blocks.sort() # Sort by offset
# Merge adjacent blocks
i = 0
while i < len(self.free_blocks) - 1:
curr_start, curr_size = self.free_blocks[i]
next_start, next_size = self.free_blocks[i + 1]
if curr_start + curr_size == next_start:
self.free_blocks[i] = (curr_start, curr_size + next_size)
self.free_blocks.pop(i + 1)
else:
i += 1
class ManagedBuffer:
"""
A temporary view into the global memory pool.
Must be kept alive while the data view is being used.
"""
def __init__(self, allocator: BufferAllocator, offset: int, size: int, pool_tensor: torch.Tensor):
self.allocator = allocator
self.offset = offset
self.size = size
self.pool_tensor = pool_tensor
self._released = False
def release(self):
"""Explicitly release the buffer back to the pool."""
if not self._released:
self.allocator.free(self.offset, self.size)
self._released = True
def __del__(self):
self.release()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.release()
@property
def tensor(self) -> torch.Tensor:
"""
Returns a 1D uint8 zero-copy view of the buffer.
"""
return self.pool_tensor[self.offset : self.offset + self.size]
def as_tensor(self, dtype: torch.dtype, shape: tuple) -> torch.Tensor:
"""
Returns a typed, shaped zero-copy view.
Validates size, shape, and alignment.
"""
itemsize = torch.tensor([], dtype=dtype).element_size()
# Calculate expected size
expected_bytes = itemsize
for dim in shape:
if dim < 0:
raise ValueError("Dynamic dimension (-1) is not supported in as_tensor")
expected_bytes *= dim
if expected_bytes != self.size:
raise ValueError(
f"Shape {shape} with dtype {dtype} requires {expected_bytes} bytes, but buffer size is {self.size}"
)
# Check alignment (offset must be divisible by itemsize)
if self.offset % itemsize != 0:
raise RuntimeError(f"Buffer offset {self.offset} is not aligned for dtype {dtype} (itemsize {itemsize})")
raw_view = self.tensor
# view() requires contiguous memory, slice of contiguous tensor is contiguous
typed_view = raw_view.view(dtype)
return typed_view.reshape(shape)
def to_bytes(self) -> bytes:
"""
Returns a copy of the data as python bytes.
Performs D2H copy if pool is on GPU.
"""
t = self.tensor
if t.is_cuda:
t = t.cpu()
return t.numpy().tobytes()
class MooncakeTransferEngineConnector(OmniConnectorBase):
"""
OmniConnector implementation using Mooncake Transfer Engine with a managed memory pool.
@@ -0,0 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Compatibility import for the NPU-only Yuanrong TransferEngine connector."""
from vllm_omni.platforms.npu.omni_connectors.yuanrong_transfer_engine_connector import (
YuanrongTransferEngineConnector,
)
__all__ = ["YuanrongTransferEngineConnector"]
@@ -91,6 +91,18 @@ def _create_yuanrong_connector(config: dict[str, Any]) -> OmniConnectorBase:
return YuanrongConnector(config)
def _create_yuanrong_transfer_engine_connector(config: dict[str, Any]) -> OmniConnectorBase:
try:
from vllm_omni.platforms.npu.omni_connectors import YuanrongTransferEngineConnector
except ImportError as exc:
raise ImportError(
"YuanrongTransferEngineConnector is only available in the NPU platform "
"environment. Install the Ascend/Yuanrong runtime dependencies before "
"using this connector."
) from exc
return YuanrongTransferEngineConnector(config)
def _create_mooncake_transfer_engine_connector(config: dict[str, Any]) -> OmniConnectorBase:
try:
from .connectors.mooncake_transfer_engine_connector import MooncakeTransferEngineConnector
@@ -107,5 +119,6 @@ OmniConnectorFactory.register_connector("MooncakeStoreConnector", _create_moonca
OmniConnectorFactory.register_connector("MooncakeTransferEngineConnector", _create_mooncake_transfer_engine_connector)
OmniConnectorFactory.register_connector("SharedMemoryConnector", _create_shm_connector)
OmniConnectorFactory.register_connector("YuanrongConnector", _create_yuanrong_connector)
OmniConnectorFactory.register_connector("YuanrongTransferEngineConnector", _create_yuanrong_transfer_engine_connector)
# Backward-compatible aliases – will be removed in the future
OmniConnectorFactory.register_connector("MooncakeConnector", _create_mooncake_store_connector)
@@ -13,7 +13,8 @@ import torch
from vllm.logger import init_logger
from .factory import OmniConnectorFactory
from .utils.config import ConnectorSpec
from .utils.config import TRANSFER_ENGINE_CONNECTOR_NAMES, ConnectorSpec
from .utils.env import expand_env_int
from .utils.initialization import KV_RANK_PORT_STRIDE
from .utils.kv_utils import (
KVTPTopology,
@@ -21,6 +22,7 @@ from .utils.kv_utils import (
build_rank_aware_send_keys,
get_kv_target_ranks,
get_local_tp_rank,
get_omni_replica_id,
get_tp_world_size,
kv_zmq_port,
merge_received_rank_shards,
@@ -105,7 +107,7 @@ class KVCacheTransferData:
t = tensor.detach().contiguous()
if cpu:
t = t.cpu()
elif device is None and t.is_cuda:
elif device is None and getattr(t.device, "type", "cpu") != "cpu":
device = t.device
nbytes = t.numel() * t.element_size()
tensors_desc.append(
@@ -142,10 +144,10 @@ class KVCacheTransferData:
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."""
"""Convert to a packed device 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")
raise RuntimeError("No device 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))
@@ -168,19 +170,19 @@ class KVCacheTransferData:
return json.loads(bytes(raw_mv[4 : 4 + header_len])), raw_mv[4 + header_len :]
@staticmethod
def _load_header_from_tensor(gpu_tensor: torch.Tensor) -> tuple[dict[str, Any], int]:
if gpu_tensor.dtype != torch.uint8 or gpu_tensor.dim() != 1:
raise ValueError("Packed GPU KV payload must be a 1-D uint8 tensor")
def _load_header_from_tensor(tensor: torch.Tensor) -> tuple[dict[str, Any], int]:
if tensor.dtype != torch.uint8 or tensor.dim() != 1:
raise ValueError("Packed device KV payload must be a 1-D uint8 tensor")
total_bytes = int(gpu_tensor.numel())
total_bytes = int(tensor.numel())
if total_bytes < 4:
raise ValueError("Corrupted KV payload: missing 4-byte header length")
header_len = struct.unpack(">I", gpu_tensor[:4].cpu().numpy().tobytes())[0]
header_len = struct.unpack(">I", tensor[:4].cpu().numpy().tobytes())[0]
if header_len > total_bytes - 4:
raise ValueError(f"Corrupted KV payload: header_len={header_len} exceeds buffer size={total_bytes}")
header_bytes = gpu_tensor[4 : 4 + header_len].cpu().numpy().tobytes()
header_bytes = tensor[4 : 4 + header_len].cpu().numpy().tobytes()
return json.loads(header_bytes), 4 + header_len
@staticmethod
@@ -259,17 +261,22 @@ class KVCacheTransferData:
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
def from_bytes_device(tensor: torch.Tensor) -> dict[str, Any]:
"""Reconstruct KV cache data from a packed device tensor."""
header, data_start = KVCacheTransferData._load_header_from_tensor(tensor)
data_len = int(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()
return tensor[data_start + offset : data_start + offset + nbytes].clone()
return KVCacheTransferData._populate_caches(header, _get)
@staticmethod
def from_bytes_gpu(tensor: torch.Tensor) -> dict[str, Any]:
"""Compatibility alias for callers using the old GPU-specific name."""
return KVCacheTransferData.from_bytes_device(tensor)
class OmniKVTransferManager:
"""Unified management for OmniConnector and KV cache transfer.
@@ -404,8 +411,8 @@ class OmniKVTransferManager:
if cfg and (c_type := cfg.get("type")):
try:
c_extra = {k: v for k, v in cfg.items() if k != "type"}
if c_type == "MooncakeTransferEngineConnector":
base_port = c_extra.get("zmq_port", 50051)
if c_type in TRANSFER_ENGINE_CONNECTOR_NAMES:
base_port = expand_env_int(c_extra.get("zmq_port", 50051), "zmq_port")
c_extra["from_stage"] = (
str(self.config.from_stage) if self.config.from_stage is not None else "0"
)
@@ -415,15 +422,26 @@ class OmniKVTransferManager:
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)
replica_id = get_omni_replica_id()
zmq_port = kv_zmq_port(
base_port,
stage_int,
self._tp_topo.local_rank,
replica_id=replica_id,
)
if self.config.need_send_cache:
c_extra["role"] = "sender"
c_extra["zmq_port"] = zmq_port
elif self.config.need_recv_cache:
c_extra["role"] = "receiver"
c_extra.setdefault("sender_host", c_extra.get("host", "127.0.0.1"))
c_extra.setdefault("sender_zmq_port", zmq_port)
# Receiver-side sender endpoints are request-scoped.
# They are attached by the orchestrator as
# kv_sender_info and applied in update_sender_info().
# Do not derive sender_host from this receiver's
# local YAML host; on multi-node runs that points at
# the wrong process. Explicit sender_* YAML values
# are still preserved for standalone connector use.
logger.info(
"Initializing OmniConnector type=%s role=%s",
@@ -1051,8 +1069,8 @@ class OmniKVTransferManager:
managed_buffer = raw_data
try:
buf_tensor = raw_data.tensor
if buf_tensor.is_cuda:
data = KVCacheTransferData.from_bytes_gpu(buf_tensor)
if getattr(buf_tensor.device, "type", "cpu") != "cpu":
data = KVCacheTransferData.from_bytes_device(buf_tensor)
raw_data.release()
managed_buffer = None
else:
@@ -1068,7 +1086,10 @@ class OmniKVTransferManager:
elif isinstance(raw_data, (bytes, bytearray)):
data = KVCacheTransferData.from_bytes(raw_data)
elif isinstance(raw_data, torch.Tensor) and raw_data.dtype == torch.uint8 and raw_data.dim() == 1:
data = KVCacheTransferData.from_bytes(raw_data.cpu().numpy().tobytes())
if getattr(raw_data.device, "type", "cpu") != "cpu":
data = KVCacheTransferData.from_bytes_device(raw_data)
else:
data = KVCacheTransferData.from_bytes(raw_data.numpy().tobytes())
else:
data = raw_data
@@ -8,6 +8,13 @@ from .logging import get_connector_logger
logger = get_connector_logger(__name__)
TRANSFER_ENGINE_CONNECTOR_NAMES = frozenset(
{
"MooncakeTransferEngineConnector",
"YuanrongTransferEngineConnector",
}
)
@dataclass
class ConnectorSpec:
@@ -0,0 +1,47 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
import re
from typing import Any
AUTO_HOST_VALUES = {"", "auto", "*", "0.0.0.0", "::"}
AUTO_DEVICE_VALUES = {"", "auto"}
_UNEXPANDED_ENV_VAR_PATTERN = re.compile(r"\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_]*)|%([^%]+)%")
class EnvVarExpansionError(ValueError):
pass
def _unexpanded_env_vars(value: str) -> list[str]:
names: list[str] = []
for match in _UNEXPANDED_ENV_VAR_PATTERN.finditer(value):
name = next(group for group in match.groups() if group)
if name not in names:
names.append(name)
return names
def expand_env_value(value: Any, *, strict: bool = False, field_name: str = "value") -> Any:
if not isinstance(value, str):
return value
expanded = os.path.expandvars(value)
if strict:
unresolved = _unexpanded_env_vars(expanded)
if unresolved:
names = ", ".join(unresolved)
raise EnvVarExpansionError(
f"{field_name} references unset environment variable(s): {names}. Original value: {value!r}"
)
return expanded
def expand_env_int(value: Any, field_name: str) -> int:
expanded = expand_env_value(value, strict=True, field_name=field_name)
try:
return int(expanded)
except (TypeError, ValueError) as exc:
raise ValueError(f"{field_name} must be an integer after environment expansion, got {expanded!r}") from exc
@@ -10,7 +10,9 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any
from ..factory import OmniConnectorFactory
from .config import ConnectorSpec, OmniTransferConfig
from .config import TRANSFER_ENGINE_CONNECTOR_NAMES, ConnectorSpec, OmniTransferConfig
from .env import expand_env_int
from .local_rank import get_connector_local_rank
from .logging import get_connector_logger
if TYPE_CHECKING:
@@ -26,9 +28,17 @@ KV_TRANSFER_PORT_OFFSET = 100
# Port stride between TP ranks so each worker binds a unique ZMQ port
# when TP > 1. Must be larger than the maximum number of pipeline stages.
# Formula: zmq_port = base + KV_TRANSFER_PORT_OFFSET + rank * STRIDE + stage
# Formula:
# zmq_port = base + KV_TRANSFER_PORT_OFFSET
# + replica * KV_REPLICA_PORT_STRIDE
# + rank * KV_RANK_PORT_STRIDE
# + stage
KV_RANK_PORT_STRIDE = 16
# Port stride between Omni replicas of the same stage. This reserves a
# comfortably sized block per replica for TP-rank and stage offsets.
KV_REPLICA_PORT_STRIDE = 1024
def initialize_connectors_from_config(
config_path: str | Path | None = None,
@@ -85,18 +95,20 @@ def create_connectors_from_config(
for edge_key, connector_spec in connectors_config.items():
from_stage, to_stage = edge_key
try:
if connector_spec.name == "MooncakeTransferEngineConnector":
if connector_spec.name in TRANSFER_ENGINE_CONNECTOR_NAMES:
extra = dict(connector_spec.extra) if connector_spec.extra else {}
base_port = extra.get("zmq_port", 50051)
base_port = expand_env_int(extra.get("zmq_port", 50051), "zmq_port")
try:
stage_offset = int(from_stage)
except (TypeError, ValueError):
stage_offset = 0
local_rank = 0 if str(caller_stage_id) == "orchestrator" else get_connector_local_rank()
if str(caller_stage_id) == "orchestrator":
adjusted_port = base_port + orchestrator_port_offset + stage_offset
rank0_port = base_port + orchestrator_port_offset + stage_offset
else:
adjusted_port = base_port + port_offset + stage_offset
rank0_port = base_port + port_offset + stage_offset
adjusted_port = rank0_port + local_rank * KV_RANK_PORT_STRIDE
extra["zmq_port"] = adjusted_port
if is_sender is not None:
@@ -16,7 +16,7 @@ from vllm.distributed.parallel_state import (
)
from vllm.logger import init_logger
from .initialization import KV_RANK_PORT_STRIDE, KV_TRANSFER_PORT_OFFSET
from .initialization import KV_RANK_PORT_STRIDE, KV_REPLICA_PORT_STRIDE, KV_TRANSFER_PORT_OFFSET
logger = init_logger(__name__)
@@ -94,20 +94,42 @@ def get_tp_world_size() -> int:
return 1
def get_omni_replica_id() -> int:
"""Return the Omni replica id for this worker process."""
try:
replica_id = int(os.environ.get("VLLM_OMNI_REPLICA_ID", "0"))
except (ValueError, TypeError):
return 0
return max(replica_id, 0)
# ------------------------------------------------------------------ #
# ZMQ port computation
# ------------------------------------------------------------------ #
def kv_zmq_port(base_port: int, from_stage: int, local_rank: int = 0) -> int:
def kv_zmq_port(
base_port: int,
from_stage: int,
local_rank: int = 0,
replica_id: int | None = None,
) -> 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.
Each Omni replica and TP rank gets its own port so multi-replica or
TP > 1 deployments do not cause ``EADDRINUSE`` when multiple sender
workers bind on the same host. The formula is backward-compatible:
replica 0 / rank 0 produces the previous ``base + OFFSET + stage`` port.
"""
return base_port + KV_TRANSFER_PORT_OFFSET + local_rank * KV_RANK_PORT_STRIDE + from_stage
replica = get_omni_replica_id() if replica_id is None else max(int(replica_id), 0)
return (
base_port
+ KV_TRANSFER_PORT_OFFSET
+ replica * KV_REPLICA_PORT_STRIDE
+ local_rank * KV_RANK_PORT_STRIDE
+ from_stage
)
# ------------------------------------------------------------------ #
@@ -0,0 +1,49 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
_LOCAL_RANK_ENV_NAMES = (
"LOCAL_RANK",
"VLLM_LOCAL_RANK",
"OMPI_COMM_WORLD_LOCAL_RANK",
"MV2_COMM_WORLD_LOCAL_RANK",
)
_GLOBAL_RANK_ENV_NAMES = ("RANK", "RANK_ID")
def _visible_device_count() -> int | None:
visible = os.environ.get("ASCEND_RT_VISIBLE_DEVICES") or os.environ.get("CUDA_VISIBLE_DEVICES")
if not visible:
return None
devices = [item.strip() for item in visible.split(",") if item.strip()]
return len(devices) or None
def _get_tensor_model_parallel_rank() -> int:
from vllm.distributed.parallel_state import get_tensor_model_parallel_rank
return int(get_tensor_model_parallel_rank())
def get_connector_local_rank() -> int:
try:
return _get_tensor_model_parallel_rank()
except Exception:
pass
for env_name in _LOCAL_RANK_ENV_NAMES:
try:
return int(os.environ[env_name])
except (KeyError, TypeError, ValueError):
pass
visible_count = _visible_device_count()
for env_name in _GLOBAL_RANK_ENV_NAMES:
try:
rank = int(os.environ[env_name])
except (KeyError, TypeError, ValueError):
continue
return rank % visible_count if visible_count else rank
return 0
@@ -0,0 +1,153 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import threading
import torch
from .logging import get_connector_logger
logger = get_connector_logger(__name__)
class BufferAllocator:
"""
Manages the allocation of memory segments within a registered pool.
Thread-safe implementation using a simple free list.
"""
def __init__(self, total_size: int, alignment: int = 4096):
self.total_size = total_size
self.alignment = alignment
self.lock = threading.Lock()
self.free_blocks = [(0, total_size)]
def alloc(self, size: int) -> int:
"""
Allocates a block of *size* bytes and returns the starting offset.
"""
aligned_size = (size + self.alignment - 1) // self.alignment * self.alignment
with self.lock:
for i, (start, block_size) in enumerate(self.free_blocks):
if block_size >= aligned_size:
new_start = start + aligned_size
new_size = block_size - aligned_size
if new_size > 0:
self.free_blocks[i] = (new_start, new_size)
else:
self.free_blocks.pop(i)
return start
raise MemoryError(f"Out of memory in buffer pool. Requested {size} bytes (aligned {aligned_size}).")
def free(self, offset: int, size: int) -> None:
"""
Frees a previously allocated block.
"""
aligned_size = (size + self.alignment - 1) // self.alignment * self.alignment
with self.lock:
for start, length in self.free_blocks:
if offset == start and aligned_size == length:
logger.warning("Double free detected at offset %s, size %s. Ignoring.", offset, aligned_size)
return
if offset >= start and offset + aligned_size <= start + length:
logger.warning(
"Double free detected: block %s-%s is already within free block %s-%s. Ignoring.",
offset,
offset + aligned_size,
start,
start + length,
)
return
if not (offset + aligned_size <= start or start + length <= offset):
raise RuntimeError(
f"Memory corruption detected: freeing {offset}-{offset + aligned_size} "
f"partially overlaps with free block {start}-{start + length}"
)
self.free_blocks.append((offset, aligned_size))
self.free_blocks.sort()
i = 0
while i < len(self.free_blocks) - 1:
curr_start, curr_size = self.free_blocks[i]
next_start, next_size = self.free_blocks[i + 1]
if curr_start + curr_size == next_start:
self.free_blocks[i] = (curr_start, curr_size + next_size)
self.free_blocks.pop(i + 1)
else:
i += 1
class ManagedBuffer:
"""
A temporary view into a global memory pool.
Must be kept alive while the data view is being used.
"""
def __init__(self, allocator: BufferAllocator, offset: int, size: int, pool_tensor: torch.Tensor):
self.allocator = allocator
self.offset = offset
self.size = size
self.pool_tensor = pool_tensor
self._released = False
def release(self) -> None:
"""Explicitly release the buffer back to the pool."""
if not self._released:
self.allocator.free(self.offset, self.size)
self._released = True
def __del__(self):
self.release()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.release()
@property
def tensor(self) -> torch.Tensor:
"""
Returns a 1D uint8 zero-copy view of the buffer.
"""
return self.pool_tensor[self.offset : self.offset + self.size]
def as_tensor(self, dtype: torch.dtype, shape: tuple) -> torch.Tensor:
"""
Returns a typed, shaped zero-copy view.
Validates size, shape, and alignment.
"""
itemsize = torch.tensor([], dtype=dtype).element_size()
expected_bytes = itemsize
for dim in shape:
if dim < 0:
raise ValueError("Dynamic dimension (-1) is not supported in as_tensor")
expected_bytes *= dim
if expected_bytes != self.size:
raise ValueError(
f"Shape {shape} with dtype {dtype} requires {expected_bytes} bytes, but buffer size is {self.size}"
)
if self.offset % itemsize != 0:
raise RuntimeError(f"Buffer offset {self.offset} is not aligned for dtype {dtype} (itemsize {itemsize})")
typed_view = self.tensor.view(dtype)
return typed_view.reshape(shape)
def to_bytes(self) -> bytes:
"""
Returns a copy of the data as Python bytes.
Performs D2H copy if the pool is on a device.
"""
t = self.tensor
if getattr(t.device, "type", "cpu") != "cpu":
t = t.cpu()
return t.numpy().tobytes()
@@ -8,18 +8,21 @@ from .load_balancer import (
RandomBalancer,
RoundRobinBalancer,
Task,
build_load_balancer_factory,
)
from .messages import InstanceEvent, InstanceInfo, InstanceList, StageStatus
from .messages import ReplicaEvent, ReplicaInfo, ReplicaList, ReplicaStatus
from .omni_coord_client_for_hub import OmniCoordClientForHub
from .omni_coord_client_for_stage import OmniCoordClientForStage
from .omni_coordinator import OmniCoordinator
from .runtime import OmniCoordinatorRuntime
__all__ = [
"OmniCoordinator",
"StageStatus",
"InstanceEvent",
"InstanceInfo",
"InstanceList",
"OmniCoordinatorRuntime",
"ReplicaStatus",
"ReplicaEvent",
"ReplicaInfo",
"ReplicaList",
"OmniCoordClientForStage",
"OmniCoordClientForHub",
"Task",
@@ -28,4 +31,5 @@ __all__ = [
"RandomBalancer",
"RoundRobinBalancer",
"LeastQueueLengthBalancer",
"build_load_balancer_factory",
]
@@ -6,17 +6,18 @@ from __future__ import annotations
import random
import threading
from abc import ABC, abstractmethod
from collections.abc import Callable
from enum import Enum
from typing import Any, TypedDict
from .messages import InstanceInfo
from .messages import ReplicaInfo
class Task(TypedDict, total=False):
"""Task structure passed from async_omni (stage.submit(task)).
"""Task structure passed to ``StagePool.pick`` / ``LoadBalancer.select``.
Mirrors the dict built in AsyncOmni with request_id, engine_inputs,
sampling_params. Future load-balancing policies may use these fields.
Mirrors the dict built around a stage submission with request_id and any
payload-related fields a future load-balancing policy might inspect.
"""
request_id: str
@@ -28,10 +29,7 @@ class LoadBalancingPolicy(str, Enum):
"""Enumeration for load balancing policies.
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
tasks to a subset of available replicas.
"""
RANDOM = "random"
@@ -42,74 +40,60 @@ class LoadBalancingPolicy(str, Enum):
class LoadBalancer(ABC):
"""Abstract base class for load balancers.
Subclasses implement :meth:`select` to choose an instance for a given task.
Subclasses implement :meth:`select` to choose a replica for a given task.
"""
@abstractmethod
def select(self, task: Task, instances: list[InstanceInfo]) -> int:
"""Route a task to one of the available instances.
def select(self, task: Task, replicas: list[ReplicaInfo]) -> int:
"""Route a task to one of the available replicas.
Args:
task: The task to route. Not used by the random policy but reserved
for future strategies that may inspect task metadata.
instances: List of available instances to choose from.
replicas: List of available replicas to choose from.
Returns:
Index of the selected instance in ``instances``.
Index of the selected replica in ``replicas``.
Raises:
ValueError: If ``instances`` is empty.
ValueError: If ``replicas`` is empty.
"""
raise NotImplementedError
class RandomBalancer(LoadBalancer):
"""Load balancer that selects an instance uniformly at random.
"""Load balancer that selects a replica uniformly at random."""
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, replicas: list[ReplicaInfo]) -> int: # noqa: ARG002
if not replicas:
raise ValueError("replicas must not be empty")
def select(self, task: Task, instances: list[InstanceInfo]) -> int: # noqa: ARG002
if not instances:
raise ValueError("instances must not be empty")
return random.randrange(len(instances))
return random.randrange(len(replicas))
class RoundRobinBalancer(LoadBalancer):
"""Load balancer that selects instances in a round-robin fashion.
"""Load balancer that selects replicas 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``
This implementation keeps a running index modulo ``len(replicas)``. It
therefore depends on the **order and stable meaning** of the ``replicas``
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).
Concurrency: a ``threading.Lock`` serializes updates to ``_next_index``
for callers that 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")
def select(self, task: Task, replicas: list[ReplicaInfo]) -> int: # noqa: ARG002
if not replicas:
raise ValueError("replicas must not be empty")
n = len(instances)
n = len(replicas)
with self._lock:
idx = self._next_index % n
self._next_index = (self._next_index + 1) % n
@@ -117,27 +101,43 @@ class RoundRobinBalancer(LoadBalancer):
class LeastQueueLengthBalancer(LoadBalancer):
"""Select the instance with the smallest ``queue_length``.
"""Select the replica with the smallest ``queue_length``.
If multiple instances share the same minimum queue length, one of them is
If multiple replicas share the same minimum queue length, one of them is
chosen uniformly at random.
Raises:
ValueError: If any instance has a negative ``queue_length``.
ValueError: If any replica 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")
def select(self, task: Task, replicas: list[ReplicaInfo]) -> int: # noqa: ARG002
if not replicas:
raise ValueError("replicas must not be empty")
queue_lengths = [inst.queue_length for inst in instances]
queue_lengths = [rep.queue_length for rep in replicas]
if any(q < 0 for q in queue_lengths):
raise ValueError("queue_length must be non-negative for all instances")
raise ValueError("queue_length must be non-negative for all replicas")
min_q = min(queue_lengths)
candidates = [i for i, q in enumerate(queue_lengths) if q == min_q]
return random.choice(candidates)
def build_load_balancer_factory(policy: str) -> Callable[[], LoadBalancer]:
"""Translate ``--omni-lb-policy`` (string) into a per-pool LB factory."""
try:
normalized = LoadBalancingPolicy(policy)
except ValueError as exc:
valid = ", ".join(p.value for p in LoadBalancingPolicy)
raise ValueError(f"unknown --omni-lb-policy {policy!r} (valid: {valid})") from exc
if normalized is LoadBalancingPolicy.RANDOM:
return RandomBalancer
if normalized is LoadBalancingPolicy.ROUND_ROBIN:
return RoundRobinBalancer
if normalized is LoadBalancingPolicy.LEAST_QUEUE_LENGTH:
return LeastQueueLengthBalancer
raise ValueError(f"unhandled load balancing policy {normalized!r}")
__all__ = [
"Task",
"LoadBalancingPolicy",
@@ -145,4 +145,5 @@ __all__ = [
"RandomBalancer",
"RoundRobinBalancer",
"LeastQueueLengthBalancer",
"build_load_balancer_factory",
]
@@ -7,55 +7,55 @@ from dataclasses import dataclass
from enum import Enum
class StageStatus(str, Enum):
"""Enumeration for stage instance status."""
class ReplicaStatus(str, Enum):
"""Enumeration for stage replica status."""
UP = "up" # Instance is ready and available
DOWN = "down" # Instance is shutdown gracefully
ERROR = "error" # Instance encountered an error or timeout
UP = "up" # Replica is ready and available
DOWN = "down" # Replica is shutdown gracefully
ERROR = "error" # Replica encountered an error or timeout
@dataclass
class InstanceEvent:
class ReplicaEvent:
"""Wire payload from OmniCoordClientForStage to OmniCoordinator.
Schema for Stage → Coordinator events over ZMQ:
input_addr, output_addr, stage_id, status, queue_length, event_type.
"""
input_addr: str # Stage instance input ZMQ address (e.g., "tcp://host:port")
output_addr: str # Stage instance output ZMQ address (e.g., "tcp://host:port")
input_addr: str # Stage replica input ZMQ address (e.g., "tcp://host:port")
output_addr: str # Stage replica output ZMQ address (e.g., "tcp://host:port")
stage_id: int # Stage ID
event_type: str # "update" | "heartbeat"
status: StageStatus # Current status
status: ReplicaStatus # Current status
queue_length: int # Current queue length
@dataclass
class InstanceInfo:
"""Metadata for a single stage instance.
class ReplicaInfo:
"""Metadata for a single stage replica.
This type is stored in OmniCoordinator's internal registry and is also
published to hubs via :class:`InstanceList`.
published to hubs via :class:`ReplicaList`.
"""
input_addr: str # Stage instance input ZMQ address (e.g., "tcp://host:port")
output_addr: str # Stage instance output ZMQ address (e.g., "tcp://host:port")
stage_id: int # Stage ID of this instance
status: StageStatus # Current status of the instance
queue_length: int # Current queue length of this instance
input_addr: str # Stage replica input ZMQ address (e.g., "tcp://host:port")
output_addr: str # Stage replica output ZMQ address (e.g., "tcp://host:port")
stage_id: int # Stage ID of this replica
status: ReplicaStatus # Current status of the replica
queue_length: int # Current queue length of this replica
last_heartbeat: float # Timestamp of the last heartbeat received (seconds)
registered_at: float # Timestamp when the instance was registered (seconds)
registered_at: float # Timestamp when the replica was registered (seconds)
@dataclass
class InstanceList:
"""Container for instance list updates.
class ReplicaList:
"""Container for replica list updates.
OmniCoordinator publishes an :class:`InstanceList` whenever its view of
active instances changes. OmniCoordClientForHub caches the latest value
OmniCoordinator publishes a :class:`ReplicaList` whenever its view of
active replicas changes. OmniCoordClientForHub caches the latest value
and exposes it to AsyncOmni and the load balancer.
"""
instances: list[InstanceInfo]
replicas: list[ReplicaInfo]
timestamp: float # Time when the list was last updated (seconds)
@@ -9,16 +9,16 @@ from typing import Any
import zmq
from .messages import InstanceInfo, InstanceList, StageStatus
from .messages import ReplicaInfo, ReplicaList, ReplicaStatus
logger = logging.getLogger(__name__)
class OmniCoordClientForHub:
"""Client for AsyncOmni side to receive instance list updates.
"""Client for AsyncOmni side to receive replica list updates.
This client maintains a SUB socket connected to OmniCoordinator's PUB
endpoint and caches the latest :class:`InstanceList` in memory for use by
endpoint and caches the latest :class:`ReplicaList` in memory for use by
the load balancer and routing logic.
"""
@@ -28,7 +28,7 @@ class OmniCoordClientForHub:
self._ctx = zmq.Context()
self._lock = threading.Lock()
self._instance_list: InstanceList | None = None
self._replica_list: ReplicaList | None = None
self._closed = False
self._stop_event = threading.Event()
self._init_done = threading.Event()
@@ -41,29 +41,29 @@ class OmniCoordClientForHub:
if self._init_error:
raise RuntimeError(f"Failed to connect to coordinator at {self._coord_zmq_addr}") from self._init_error[0]
def _decode_instance_list(self, payload: dict[str, Any]) -> InstanceList:
"""Convert a JSON-decoded dict into an :class:`InstanceList`."""
instances_payload = payload.get("instances", [])
instances: list[InstanceInfo] = []
for inst in instances_payload:
instances.append(
InstanceInfo(
input_addr=inst["input_addr"],
output_addr=inst["output_addr"],
stage_id=int(inst["stage_id"]),
status=StageStatus(inst["status"]),
queue_length=int(inst["queue_length"]),
last_heartbeat=float(inst["last_heartbeat"]),
registered_at=float(inst["registered_at"]),
def _decode_replica_list(self, payload: dict[str, Any]) -> ReplicaList:
"""Convert a JSON-decoded dict into a :class:`ReplicaList`."""
replicas_payload = payload.get("replicas", [])
replicas: list[ReplicaInfo] = []
for rep in replicas_payload:
replicas.append(
ReplicaInfo(
input_addr=rep["input_addr"],
output_addr=rep["output_addr"],
stage_id=int(rep["stage_id"]),
status=ReplicaStatus(rep["status"]),
queue_length=int(rep["queue_length"]),
last_heartbeat=float(rep["last_heartbeat"]),
registered_at=float(rep["registered_at"]),
)
)
timestamp = float(payload.get("timestamp", time()))
return InstanceList(instances=instances, timestamp=timestamp)
return ReplicaList(replicas=replicas, timestamp=timestamp)
def _recv_loop(self) -> None:
"""Background loop that receives and caches instance lists."""
sub = None
"""Background loop that receives and caches replica lists."""
sub: zmq.Socket | None = None
try:
sub = self._ctx.socket(zmq.SUB)
sub.setsockopt(zmq.SUBSCRIBE, b"")
@@ -115,9 +115,9 @@ class OmniCoordClientForHub:
try:
payload = json.loads(data.decode("utf-8"))
inst_list = self._decode_instance_list(payload)
rep_list = self._decode_replica_list(payload)
with self._lock:
self._instance_list = inst_list
self._replica_list = rep_list
except (
json.JSONDecodeError,
KeyError,
@@ -125,7 +125,7 @@ class OmniCoordClientForHub:
TypeError,
AttributeError,
) as e:
logger.warning("Invalid instance list message, skipping: %s", e)
logger.warning("Invalid replica list message, skipping: %s", e)
finally:
try:
if sub is not None:
@@ -137,22 +137,22 @@ class OmniCoordClientForHub:
except zmq.ZMQError:
pass
def get_instance_list(self) -> InstanceList:
"""Return the latest cached :class:`InstanceList`.
def get_replica_list(self) -> ReplicaList:
"""Return the latest cached :class:`ReplicaList`.
If no update has been received yet, returns an empty list with
``timestamp=0.0``.
"""
with self._lock:
if self._instance_list is None:
return InstanceList(instances=[], timestamp=0.0)
return self._instance_list
if self._replica_list is None:
return ReplicaList(replicas=[], timestamp=0.0)
return self._replica_list
def get_instances_for_stage(self, stage_id: int) -> InstanceList:
"""Return instances filtered by ``stage_id``."""
base = self.get_instance_list()
filtered = [inst for inst in base.instances if inst.stage_id == stage_id]
return InstanceList(instances=filtered, timestamp=base.timestamp)
def get_replicas_for_stage(self, stage_id: int) -> ReplicaList:
"""Return replicas filtered by ``stage_id``."""
base = self.get_replica_list()
filtered = [rep for rep in base.replicas if rep.stage_id == stage_id]
return ReplicaList(replicas=filtered, timestamp=base.timestamp)
def close(self) -> None:
"""Close the SUB socket and stop the background thread."""
@@ -1,24 +1,26 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import contextlib
import json
import logging
import threading
import time
from collections.abc import Callable
from dataclasses import asdict
import zmq
from .messages import InstanceEvent, StageStatus
from .messages import ReplicaEvent, ReplicaStatus
logger = logging.getLogger(__name__)
class OmniCoordClientForStage:
"""Client used by stage instances to send events to OmniCoordinator.
"""Client used by stage replicas to send events to OmniCoordinator.
This client maintains a DEALER socket connected to OmniCoordinator's
ROUTER endpoint and sends JSON-encoded events describing instance status.
ROUTER endpoint and sends JSON-encoded events describing replica status.
"""
def __init__(
@@ -42,13 +44,18 @@ class OmniCoordClientForStage:
self._socket.close()
raise RuntimeError(f"Failed to connect to coordinator at {self._coord_zmq_addr}: {e}") from e
self._status = StageStatus.UP
self._status = ReplicaStatus.UP
self._queue_length = 0
self._closed = False
self._closing = False
self._heartbeat_interval = 5.0
self._stop_event = threading.Event()
self._send_lock = threading.RLock()
# Optional hook invoked from the heartbeat thread before each
# heartbeat send. Stages set this to refresh ``queue_length`` (or any
# other field) just-in-time. Exceptions raised by the hook are
# suppressed and logged.
self._on_heartbeat: Callable[[], None] | None = None
self._send_event("update")
@@ -100,11 +107,13 @@ class OmniCoordClientForStage:
return False
def _send_event(self, event_type: str) -> None:
"""Send an InstanceEvent to OmniCoordinator.
"""Send a ReplicaEvent to OmniCoordinator.
Wire format: input_addr, output_addr, stage_id, status, queue_length, event_type.
For "update": includes status and queue_length from instance state.
For "heartbeat": status and queue_length are null.
For "update": includes status and queue_length from replica state.
For "heartbeat": includes the latest queue_length (refreshed by the
optional ``_on_heartbeat`` hook) so the coordinator can propagate
live load to load balancers between explicit ``update`` events.
On send failure (ZMQError / RuntimeError), attempts to reconnect up
to 3 times (5s sleep each) and retries the send once after a
@@ -114,7 +123,7 @@ class OmniCoordClientForStage:
if self._closed:
raise RuntimeError("Client already closed")
event = InstanceEvent(
event = ReplicaEvent(
input_addr=self._input_addr,
output_addr=self._output_addr,
stage_id=self._stage_id,
@@ -147,10 +156,10 @@ class OmniCoordClientForStage:
def update_info(
self,
status: StageStatus | None = None,
status: ReplicaStatus | None = None,
queue_length: int | None = None,
) -> None:
"""Update instance information and notify OmniCoordinator.
"""Update replica information and notify OmniCoordinator.
At least one of ``status`` or ``queue_length`` must be provided.
"""
@@ -174,6 +183,15 @@ class OmniCoordClientForStage:
if self._closed:
break
# Invoke the optional pre-heartbeat hook so callers (e.g. the
# engine subprocess) can refresh ``queue_length`` from live state
# before the heartbeat is sent. Exceptions are swallowed so a
# buggy hook never breaks the heartbeat loop.
hook = self._on_heartbeat
if hook is not None:
with contextlib.suppress(Exception):
hook()
try:
self._send_event("heartbeat")
except (RuntimeError, zmq.ZMQError) as e:
@@ -199,7 +217,7 @@ class OmniCoordClientForStage:
self._closing = True
# Mark status as DOWN and send one last update.
self._status = StageStatus.DOWN
self._status = ReplicaStatus.DOWN
try:
self._send_event("update")
except (RuntimeError, zmq.ZMQError):
@@ -11,22 +11,22 @@ from typing import Any
import zmq
from .messages import InstanceEvent, InstanceInfo, InstanceList, StageStatus
from .messages import ReplicaEvent, ReplicaInfo, ReplicaList, ReplicaStatus
logger = logging.getLogger(__name__)
class OmniCoordinator:
"""Coordinator for stage instances and hub clients.
"""Coordinator for stage replicas and hub clients.
This service receives instance events from :class:`OmniCoordClientForStage`
via a ZMQ ROUTER socket and publishes active instance lists to
This service receives replica events from :class:`OmniCoordClientForStage`
via a ZMQ ROUTER socket and publishes active replica lists to
:class:`OmniCoordClientForHub` via a PUB socket.
The coordinator maintains an in-memory registry of all known instances,
The coordinator maintains an in-memory registry of all known replicas,
including their status, queue length, and heartbeat timestamps. A
background thread periodically checks for heartbeat timeouts and marks
unhealthy instances as ``StageStatus.ERROR``.
unhealthy replicas as ``ReplicaStatus.ERROR``.
"""
def __init__(
@@ -40,7 +40,7 @@ class OmniCoordinator:
Args:
router_zmq_addr: ZMQ address to bind the ROUTER socket.
pub_zmq_addr: ZMQ address to bind the PUB socket.
heartbeat_timeout: Seconds before an instance is considered
heartbeat_timeout: Seconds before a replica is considered
unhealthy if no heartbeat / update is received.
"""
self._router_zmq_addr = router_zmq_addr
@@ -55,7 +55,7 @@ class OmniCoordinator:
self._pub = self._ctx.socket(zmq.PUB)
self._pub.bind(self._pub_zmq_addr)
self._instances: dict[str, InstanceInfo] = {}
self._replicas: dict[str, ReplicaInfo] = {}
self._lock = threading.Lock()
self._pub_lock = threading.Lock()
@@ -75,43 +75,43 @@ class OmniCoordinator:
self._periodic_thread = threading.Thread(target=self._periodic_loop, daemon=True)
self._periodic_thread.start()
def get_active_instances(self) -> InstanceList:
"""Return an :class:`InstanceList` of active (UP) instances only."""
def get_active_replicas(self) -> ReplicaList:
"""Return a :class:`ReplicaList` of active (UP) replicas only."""
with self._lock:
active = [inst for inst in self._instances.values() if inst.status == StageStatus.UP]
return InstanceList(instances=active, timestamp=time())
active = [rep for rep in self._replicas.values() if rep.status == ReplicaStatus.UP]
return ReplicaList(replicas=active, timestamp=time())
def add_new_instance(self, event: InstanceEvent) -> None:
"""Add a new instance based on an incoming event."""
def add_new_replica(self, event: ReplicaEvent) -> None:
"""Add a new replica based on an incoming event."""
with self._lock:
self._add_new_instance_locked(event)
self._add_new_replica_locked(event)
self._schedule_broadcast()
def update_instance_info(self, event: InstanceEvent) -> None:
"""Update an existing instance based on an incoming event."""
def update_replica_info(self, event: ReplicaEvent) -> None:
"""Update an existing replica based on an incoming event."""
with self._lock:
self._update_instance_info_locked(event)
self._update_replica_info_locked(event)
self._schedule_broadcast()
def remove_instance(self, event: InstanceEvent) -> None:
"""Mark an instance as removed / down based on an incoming event.
def remove_replica(self, event: ReplicaEvent) -> None:
"""Mark a replica as removed / down based on an incoming event.
This marks the instance's status as DOWN or ERROR (depending on the
This marks the replica's status as DOWN or ERROR (depending on the
event) but keeps it in the internal registry. It is removed from the
*active* instance list published to hubs.
*active* replica list published to hubs.
"""
with self._lock:
self._remove_instance_locked(event)
self._remove_replica_locked(event)
self._schedule_broadcast()
def publish_instance_list_update(self) -> bool:
"""Publish the current active instance list to all subscribers.
def publish_replica_list_update(self) -> bool:
"""Publish the current active replica list to all subscribers.
Returns:
True if the PUB send succeeded, False if it was dropped (e.g.
socket not ready when using ``zmq.NOBLOCK``).
"""
active_list = self.get_active_instances()
active_list = self.get_active_replicas()
payload = asdict(active_list)
data = json.dumps(payload).encode("utf-8")
@@ -133,12 +133,12 @@ class OmniCoordinator:
with self._pending_lock:
self._pending_broadcast = True
def _mark_instance_error_locked(self, info: InstanceInfo) -> None:
"""Mark instance as ERROR (e.g. after heartbeat timeout)."""
info.status = StageStatus.ERROR
def _mark_replica_error_locked(self, info: ReplicaInfo) -> None:
"""Mark replica as ERROR (e.g. after heartbeat timeout)."""
info.status = ReplicaStatus.ERROR
def _check_heartbeat_timeouts(self) -> None:
"""Mark instances as ERROR if their heartbeat has timed out."""
"""Mark replicas as ERROR if their heartbeat has timed out."""
now = time()
timed_out = False
gc_ttl = 600.0 # 10 minutes
@@ -146,17 +146,17 @@ class OmniCoordinator:
with self._lock:
to_delete: list[str] = []
for input_addr, info in self._instances.items():
if info.status == StageStatus.UP and now - info.last_heartbeat > self._heartbeat_timeout:
self._mark_instance_error_locked(info)
for input_addr, info in self._replicas.items():
if info.status == ReplicaStatus.UP and now - info.last_heartbeat > self._heartbeat_timeout:
self._mark_replica_error_locked(info)
timed_out = True
elif info.status in (StageStatus.DOWN, StageStatus.ERROR) and now - info.last_heartbeat > gc_ttl:
elif info.status in (ReplicaStatus.DOWN, ReplicaStatus.ERROR) and now - info.last_heartbeat > gc_ttl:
to_delete.append(input_addr)
for input_addr in to_delete:
del self._instances[input_addr]
del self._replicas[input_addr]
if timed_out:
# Instance liveness changed; request broadcast.
# Replica liveness changed; request broadcast.
self._schedule_broadcast()
def close(self) -> None:
@@ -187,22 +187,22 @@ class OmniCoordinator:
except zmq.ZMQError:
pass
def _parse_instance_event(self, data: dict[str, Any]) -> InstanceEvent | None:
"""Parse wire payload dict into InstanceEvent. Returns None if invalid."""
def _parse_replica_event(self, data: dict[str, Any]) -> ReplicaEvent | None:
"""Parse wire payload dict into ReplicaEvent. Returns None if invalid."""
try:
return InstanceEvent(
return ReplicaEvent(
input_addr=str(data["input_addr"]),
output_addr=str(data["output_addr"]),
stage_id=int(data["stage_id"]),
event_type=str(data["event_type"]),
status=StageStatus(data.get("status")),
status=ReplicaStatus(data.get("status")),
queue_length=data.get("queue_length"),
)
except (KeyError, ValueError, TypeError):
return None
def _recv_loop(self) -> None:
"""Background loop that receives and processes instance events."""
"""Background loop that receives and processes replica events."""
while self._running:
try:
frames = self._router.recv_multipart()
@@ -219,12 +219,12 @@ class OmniCoordinator:
payload = frames[-1]
try:
data = json.loads(payload.decode("utf-8"))
event = self._parse_instance_event(data)
event = self._parse_replica_event(data)
except json.JSONDecodeError as e:
logger.warning("Invalid JSON in instance event, dropping: %s", e)
logger.warning("Invalid JSON in replica event, dropping: %s", e)
continue
if event is None:
logger.warning("Malformed instance event, dropping")
logger.warning("Malformed replica event, dropping")
continue
self._handle_event(event)
@@ -234,7 +234,10 @@ class OmniCoordinator:
Heartbeat timeouts are checked on their original cadence, while all
broadcast requests are coalesced and flushed at most once per
``_publish_min_interval``.
``_publish_min_interval``. The heartbeat-check tick also schedules a
keepalive broadcast so late-joining hubs (which miss any PUB sends
that happened before their SUB connected) catch up within at most
``heartbeat_interval`` seconds.
"""
heartbeat_interval = max(1.0, min(self._heartbeat_timeout / 2.0, 5.0))
loop_interval = self._publish_min_interval
@@ -245,6 +248,13 @@ class OmniCoordinator:
if now - last_heartbeat_check >= heartbeat_interval:
self._check_heartbeat_timeouts()
# Keepalive broadcast: ZMQ PUB doesn't queue for late
# subscribers, so an OmniCoordClientForHub that connects
# after the initial UP events miss them entirely and would
# never see the current replica list otherwise. Scheduling a
# broadcast on every heartbeat tick caps that staleness at
# ``heartbeat_interval`` without flooding the wire.
self._schedule_broadcast()
last_heartbeat_check = now
with self._pending_lock:
@@ -256,43 +266,51 @@ class OmniCoordinator:
continue
# Publish outside lock. Clear pending only on success.
if self.publish_instance_list_update():
if self.publish_replica_list_update():
with self._pending_lock:
self._pending_broadcast = False
if self._stop_event.wait(timeout=loop_interval):
break
def _handle_event(self, event: InstanceEvent) -> None:
def _handle_event(self, event: ReplicaEvent) -> None:
"""Dispatch an incoming event to the appropriate handler."""
try:
input_addr = event.input_addr
# Heartbeat: only update last_heartbeat; if previously ERROR,
# promote back to UP and broadcast once.
# Heartbeat: refresh last_heartbeat and queue_length. The stage
# client refreshes queue_length just-in-time via its
# ``_on_heartbeat`` hook, so heartbeats are the only periodic
# source of live load for LeastQueueLengthBalancer; failing to
# propagate it here would let the policy route on stale data.
# If previously ERROR, promote back to UP and broadcast once.
if event.event_type == "heartbeat":
promote = False
queue_changed = False
with self._lock:
info = self._instances.get(input_addr)
info = self._replicas.get(input_addr)
if info is not None:
info.last_heartbeat = time()
if info.status == StageStatus.ERROR:
info.status = StageStatus.UP
if event.queue_length is not None and info.queue_length != event.queue_length:
info.queue_length = event.queue_length
queue_changed = True
if info.status == ReplicaStatus.ERROR:
info.status = ReplicaStatus.UP
promote = True
if promote:
if promote or queue_changed:
self._schedule_broadcast()
return
# Check-and-act under single lock to avoid TOCTOU race (duplicate
# registration when concurrent events arrive for the same instance).
# registration when concurrent events arrive for the same replica).
with self._lock:
if input_addr not in self._instances:
self._add_new_instance_locked(event)
if input_addr not in self._replicas:
self._add_new_replica_locked(event)
else:
if event.status == StageStatus.DOWN:
self._remove_instance_locked(event)
if event.status == ReplicaStatus.DOWN:
self._remove_replica_locked(event)
else:
self._update_instance_info_locked(event)
self._update_replica_info_locked(event)
# Any non-heartbeat state change that affects the active list
# is coalesced and flushed via the periodic loop.
@@ -300,7 +318,7 @@ class OmniCoordinator:
except (KeyError, ValueError, TypeError) as e:
logger.warning("Dropping malformed event: %s", e)
def _add_new_instance_locked(self, event: InstanceEvent) -> None:
def _add_new_replica_locked(self, event: ReplicaEvent) -> None:
input_addr = event.input_addr
if not input_addr:
raise KeyError("input_addr required")
@@ -309,7 +327,7 @@ class OmniCoordinator:
raise KeyError("stage_id required and must be non-negative")
now = time()
info = InstanceInfo(
info = ReplicaInfo(
input_addr=input_addr,
output_addr=event.output_addr,
stage_id=stage_id,
@@ -318,11 +336,11 @@ class OmniCoordinator:
last_heartbeat=now,
registered_at=now,
)
self._instances[input_addr] = info
self._replicas[input_addr] = info
def _update_instance_info_locked(self, event: InstanceEvent) -> None:
def _update_replica_info_locked(self, event: ReplicaEvent) -> None:
input_addr = event.input_addr
info = self._instances[input_addr]
info = self._replicas[input_addr]
if event.status is not None:
info.status = event.status
@@ -330,10 +348,10 @@ class OmniCoordinator:
if event.queue_length is not None:
info.queue_length = event.queue_length
def _remove_instance_locked(self, event: InstanceEvent) -> None:
def _remove_replica_locked(self, event: ReplicaEvent) -> None:
input_addr = event.input_addr
info = self._instances.get(input_addr)
info = self._replicas.get(input_addr)
if info is None:
return
info.status = StageStatus.DOWN
info.status = ReplicaStatus.DOWN
@@ -0,0 +1,74 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Lifecycle wrapper around :class:`OmniCoordinator`.
``OmniCoordinatorRuntime`` is the single-purpose owner of the head-side
coordinator process artifacts: it picks two free TCP ports, constructs an
:class:`OmniCoordinator` bound to them, exposes the resulting addresses, and
provides a single ``close()`` method to tear everything down.
The ROUTER address is later handed to :class:`OmniMasterServer` so it can be
published to registering replicas; the PUB address is handed to the
``Orchestrator``, which constructs its :class:`OmniCoordClientForHub` against
it.
"""
from __future__ import annotations
import logging
from vllm.utils.network_utils import get_open_ports_list
from .omni_coordinator import OmniCoordinator
logger = logging.getLogger(__name__)
class OmniCoordinatorRuntime:
"""Own one :class:`OmniCoordinator` and the two ports it binds.
Constructor binds; :meth:`close` tears down. The class deliberately does
not expose the coordinator instance — callers should consume the
coordinator only via its wire protocol through
:class:`OmniCoordClientForStage` and :class:`OmniCoordClientForHub`.
"""
def __init__(
self,
*,
host: str,
heartbeat_timeout: float,
) -> None:
if not host:
raise ValueError("host must be a non-empty string")
if heartbeat_timeout <= 0:
raise ValueError("heartbeat_timeout must be positive")
router_port, pub_port = get_open_ports_list(count=2)
self.router_address: str = f"tcp://{host}:{router_port}"
self.pub_address: str = f"tcp://{host}:{pub_port}"
self._closed = False
self._coordinator = OmniCoordinator(
router_zmq_addr=self.router_address,
pub_zmq_addr=self.pub_address,
heartbeat_timeout=heartbeat_timeout,
)
logger.info(
"[OmniCoordinatorRuntime] Started (router=%s pub=%s heartbeat_timeout=%.1fs)",
self.router_address,
self.pub_address,
heartbeat_timeout,
)
def close(self) -> None:
"""Tear down the underlying coordinator. Idempotent."""
if self._closed:
return
self._closed = True
try:
self._coordinator.close()
except Exception:
logger.exception("[OmniCoordinatorRuntime] coordinator close failed")
+4 -1
View File
@@ -22,7 +22,6 @@ _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.
@@ -155,6 +154,10 @@ class OmniEngineArgs(EngineArgs):
omni_master_address: str | None = None
omni_master_port: int | None = None
# OmniCoordinator integration knobs (process-local).
omni_dp_size_local: int = 1
omni_lb_policy: str = "random"
omni_heartbeat_timeout: float = 30.0
stage_configs_path: str | None = None
output_modalities: list[str] | None = None
log_stats: bool = False
+301 -64
View File
@@ -18,7 +18,7 @@ import threading
import time
import uuid
import weakref
from collections.abc import Mapping, Sequence
from collections.abc import Awaitable, Callable, Mapping, Sequence
from contextlib import ExitStack
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, Any, Literal, cast
@@ -45,6 +45,10 @@ from vllm_omni.diffusion.stage_diffusion_proc import (
from vllm_omni.distributed.omni_connectors.utils.initialization import (
resolve_omni_kv_config_for_stage,
)
from vllm_omni.distributed.omni_coordinator import (
LoadBalancer,
build_load_balancer_factory,
)
from vllm_omni.engine import OmniEngineCoreRequest
from vllm_omni.engine.messages import (
AbortRequestMessage,
@@ -53,6 +57,7 @@ from vllm_omni.engine.messages import (
CollectiveRPCResultMessage,
EngineQueueMessage,
ErrorMessage,
RegisterRemoteReplicaMessage,
ShutdownRequestMessage,
StageSubmissionMessage,
)
@@ -77,6 +82,7 @@ from vllm_omni.engine.stage_engine_startup import (
from vllm_omni.engine.stage_init_utils import (
LogicalStageInitPlan,
ReplicaInitPlan,
StageRemoteFactoryContext,
_inject_inferred_kv_tp_topology,
acquire_device_locks,
acquire_diffusion_device_locks,
@@ -85,6 +91,7 @@ from vllm_omni.engine.stage_init_utils import (
build_llm_stage_output_processor,
build_stage0_input_processor,
build_vllm_config,
capture_stage_factory_contexts,
compute_replica_layout,
extract_stage_metadata,
get_stage_connector_spec,
@@ -148,6 +155,7 @@ _PARENT_ARGS_KEEP: frozenset[str] = frozenset(
# 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.
@@ -229,10 +237,9 @@ def _weak_shutdown_async_omni_engine(
pass
for q in (request_queue, output_queue, rpc_output_queue):
if q is None:
continue
try:
q.close()
if q is not None:
q.close()
except Exception:
pass
@@ -301,6 +308,23 @@ class AsyncOmniEngine:
self._omni_master_port: int | None = kwargs.get("omni_master_port")
self._omni_master_server: OmniMasterServer | None = None
# New omni-coordinator flags. Consumed only in single_stage_mode.
# ``omni_dp_size_local`` is process-local: each invocation (head and
# every headless) launches that many replicas for its own stage.
self._omni_dp_size_local: int = int(kwargs.get("omni_dp_size_local") or 1)
if self._omni_dp_size_local < 1:
raise ValueError(f"--omni-dp-size-local must be >= 1, got {self._omni_dp_size_local}")
self._omni_lb_policy: str = str(kwargs.get("omni_lb_policy") or "random")
self._omni_heartbeat_timeout: float = float(kwargs.get("omni_heartbeat_timeout") or 30.0)
if self._omni_heartbeat_timeout <= 0:
raise ValueError(f"--omni-heartbeat-timeout must be > 0, got {self._omni_heartbeat_timeout}")
# Coordinator runtime (head-distributed only).
self._coordinator_runtime: Any | None = None
# Per-stage construction context, captured after _initialize_stages
# and used by ``_build_remote_replica`` (the RemoteReplicaFactory
# passed to Orchestrator) when a headless replica registers.
self._stage_remote_factory_contexts: dict[int, StageRemoteFactoryContext] = {}
if single_stage_mode:
logger.info(
"[AsyncOmniEngine] Single-stage mode enabled (stage_id_filter=%s, master=%s:%s)",
@@ -321,9 +345,14 @@ class AsyncOmniEngine:
self.supported_tasks: tuple[str, ...] = ("generate",)
self.default_sampling_params_list: list[OmniSamplingParams] = []
self.stage_metadata: list[StageRuntimeInfo] = []
self.request_queue: janus.Queue[EngineQueueMessage] | None = None
self.output_queue: janus.Queue[EngineQueueMessage] | None = None
self.rpc_output_queue: janus.Queue[EngineQueueMessage] | None = None
# Janus queues are constructed eagerly here (not deferred to the
# orchestrator thread) so the master server's ROUTER thread always
# sees a non-None ``self.request_queue`` when on_register fires.
# ``async_q`` lazily binds to whatever event loop first awaits on
# it (the orchestrator loop), so cross-thread use stays correct.
self.request_queue: janus.Queue[EngineQueueMessage] = janus.Queue()
self.output_queue: janus.Queue[EngineQueueMessage] = janus.Queue()
self.rpc_output_queue: janus.Queue[EngineQueueMessage] = janus.Queue()
self._shutdown_called = False
self._weak_finalizer: weakref.finalize | None = None
self._rpc_lock = threading.Lock()
@@ -443,30 +472,37 @@ class AsyncOmniEngine:
)
def _validate_single_stage_mode_replica_constraints(self) -> None:
"""Reject unsupported replica fan-out in single-stage mode."""
"""Apply --omni-dp-size-local to the local stage's runtime.num_replicas.
In the previous revision this method rejected LLM stages with
``num_replicas > 1``. The whole point of ``--omni-dp-size-local`` is
to lift that restriction for the *local* stage, so the rejection is
gone. We now use this hook to write ``--omni-dp-size-local`` onto
the self-stage's runtime config so downstream code
(``compute_replica_layout`` → ``_build_logical_stage_init_plans``)
sees a consistent view.
"""
if not self.single_stage_mode:
return
target_stage_id = self._single_stage_id_filter
if target_stage_id is None:
return
unsupported: list[tuple[int, int]] = []
for idx, stage_cfg in enumerate(self.stage_configs):
runtime_cfg = getattr(stage_cfg, "runtime", {})
num_replicas = int(
runtime_cfg.get("num_replicas", 1)
if hasattr(runtime_cfg, "get")
else getattr(runtime_cfg, "num_replicas", 1)
)
if num_replicas <= 1:
continue
if getattr(stage_cfg, "stage_type", "llm") == "diffusion":
continue
stage_id = int(getattr(stage_cfg, "stage_id", idx))
unsupported.append((stage_id, num_replicas))
if unsupported:
raise ValueError(
"single_stage_mode only supports num_replicas > 1 for diffusion stages; "
f"found non-diffusion stages {unsupported}"
)
runtime_cfg = getattr(stage_cfg, "runtime", None)
if runtime_cfg is None:
continue
if stage_id == target_stage_id:
# Self stage: take --omni-dp-size-local from this process.
try:
runtime_cfg.num_replicas = self._omni_dp_size_local
except Exception:
if hasattr(runtime_cfg, "__setitem__"):
runtime_cfg["num_replicas"] = self._omni_dp_size_local
# Other stages keep their config-declared num_replicas; in
# head-distributed mode they will be launched as ``launch_mode
# == "remote"`` with the configured count.
def _build_logical_stage_init_plans(
self,
@@ -540,9 +576,18 @@ class AsyncOmniEngine:
replica_metadata = extract_stage_metadata(replica_cfg)
replica_metadata.replica_id = replica_id
if self.single_stage_mode:
if replica_metadata.stage_type != "diffusion":
replica_metadata.runtime_cfg = None
# In single_stage_mode the head only owns its self stage's
# replicas; the remote-stage metadata exists only so the
# orchestrator can route requests through StagePool. Wiping
# ``runtime_cfg`` there makes sense (we don't manage those
# devices). For the *self stage* we MUST keep the
# per-replica runtime so ``setup_stage_devices`` can apply
# the device split from ``compute_replica_layout`` —
# otherwise every replica inherits the parent's full
# CUDA_VISIBLE_DEVICES and stacks on cuda:0 (OOM with any
# model whose footprint exceeds ~1/(2N) of the card).
if launch_mode == "remote" and replica_metadata.stage_type != "diffusion":
replica_metadata.runtime_cfg = None
replicas.append(
ReplicaInitPlan(
@@ -578,6 +623,11 @@ class AsyncOmniEngine:
all_stage_ids: list[int] = []
stage_replica_counts: dict[int, int] = {}
# Slots that the head itself will register (launch_mode == "local")
# — auto-assign on the master must not hand these out to remote
# headless registrations even within the race window before the
# head's own register_stage_with_omni_master call completes.
head_local_replicas: dict[int, list[int]] = {}
seen_stage_ids: set[int] = set()
for plan in stage_plans:
stage_id = plan.configured_stage_id
@@ -588,12 +638,27 @@ class AsyncOmniEngine:
seen_stage_ids.add(stage_id)
all_stage_ids.append(stage_id)
stage_replica_counts[stage_id] = len(plan.replicas)
local_rids = [rep.replica_id for rep in plan.replicas if rep.launch_mode == "local"]
if local_rids:
head_local_replicas[stage_id] = local_rids
# Start the OmniCoordinator runtime first so its router address is
# available to publish in every registration reply.
from vllm_omni.distributed.omni_coordinator import OmniCoordinatorRuntime
self._coordinator_runtime = OmniCoordinatorRuntime(
host=self._omni_master_address,
heartbeat_timeout=self._omni_heartbeat_timeout,
)
self._omni_master_server = OmniMasterServer(
master_address=self._omni_master_address,
master_port=self._omni_master_port,
stage_ids=all_stage_ids,
stage_replica_counts=stage_replica_counts,
coordinator_router_address=self._coordinator_runtime.router_address,
on_register=self._dispatch_master_register,
head_local_replicas=head_local_replicas,
)
self._omni_master_server.start()
logger.info(
@@ -601,6 +666,147 @@ class AsyncOmniEngine:
all_stage_ids,
)
# ------------------------------------------------------------------
# Remote replica factory (head-side client construction)
# ------------------------------------------------------------------
async def _build_remote_replica(self, stage_id: int, replica_id: int) -> Any:
"""Construct a head-side stage client for a newly-registered remote replica.
Used by :class:`Orchestrator` as its ``remote_replica_factory``.
The orchestrator awaits this from its own asyncio loop, so the
client is created in the same loop that owns ZMQ sockets — no
cross-thread setup is required.
Raises if the stage is not known or if its construction context
was not captured (e.g. the stage was empty at bring-up time).
"""
ctx = self._stage_remote_factory_contexts.get(stage_id)
if ctx is None:
raise RuntimeError(
f"no factory context captured for stage {stage_id}; "
f"known stages: {sorted(self._stage_remote_factory_contexts.keys())}"
)
if self._omni_master_server is None:
raise RuntimeError("OmniMasterServer is not running; cannot build remote replica")
alloc = self._omni_master_server.get_allocation(stage_id, replica_id=replica_id)
# Build a per-replica copy of the base metadata so ``replica_id``
# is correct (StageMetadata is a plain dataclass-like).
metadata = copy.copy(ctx.base_metadata)
try:
metadata.replica_id = replica_id
except Exception:
# Best-effort: if the metadata object is frozen / unusual, the
# downstream client will fall back to ``replica_id = 0``.
pass
if ctx.stage_type == "diffusion":
client = StageDiffusionClient.from_addresses(
metadata,
request_address=alloc.input_bind_address,
response_address=alloc.output_bind_address,
batch_size=ctx.diffusion_batch_size,
)
logger.info(
"[AsyncOmniEngine] Built remote diffusion client for stage=%d replica=%d (req=%s resp=%s)",
stage_id,
replica_id,
alloc.input_bind_address,
alloc.output_bind_address,
)
return client
# LLM path
if ctx.vllm_config is None or ctx.executor_class is None:
raise RuntimeError(f"stage {stage_id} factory context is missing vllm_config / executor_class")
# The headless's StageEngineCoreProc subprocess calls
# vllm.v1.engine.core.startup_handshake at boot and blocks until the
# head's handshake ROUTER answers — without this step it hits the
# built-in 5-minute timeout and exits. The bootstrap (pre-allocated)
# path runs `connect_remote_engine_cores` to perform that
# handshake; dynamic attach must do the same, otherwise every
# replica that comes in via `on_register` (auto-assigned or
# explicit-id-beyond-pre-alloc) deadlocks. Run the blocking
# handshake in a thread so the orchestrator loop stays responsive,
# then build the async client on this loop where `make_async_mp_client`
# expects to be invoked.
master_server = self._omni_master_server
ctx_vllm_config = ctx.vllm_config
ctx_executor_class = ctx.executor_class
def _run_handshake() -> Any:
with connect_remote_engine_cores(
vllm_config=ctx_vllm_config,
omni_master_server=master_server,
stage_id=stage_id,
replica_id=replica_id,
) as remote_resources:
_engine_manager, _coordinator, addresses, _ = remote_resources
return _engine_manager, _coordinator, addresses
engine_manager, coordinator, addresses = await asyncio.to_thread(_run_handshake)
client_addresses: dict[str, str] = {
"input_address": addresses.inputs[0],
"output_address": addresses.outputs[0],
}
if addresses.frontend_stats_publish_address is not None:
client_addresses["stats_update_address"] = addresses.frontend_stats_publish_address
client = StageEngineCoreClientBase.make_async_mp_client(
vllm_config=ctx_vllm_config,
executor_class=ctx_executor_class,
metadata=metadata,
client_addresses=client_addresses,
proc=None,
engine_manager=engine_manager,
coordinator=coordinator,
)
logger.info(
"[AsyncOmniEngine] Built remote LLM client for stage=%d replica=%d (input=%s)",
stage_id,
replica_id,
client_addresses["input_address"],
)
return client
# ------------------------------------------------------------------
# OmniCoordinator on_register proxy
# ------------------------------------------------------------------
def _dispatch_master_register(self, stage_id: int, replica_id: int, alloc: Any) -> None:
"""Forward a master-server registration to the orchestrator queue.
Called on :class:`OmniMasterServer`'s ROUTER thread (not the
orchestrator loop). Must return promptly. ``self.request_queue``
is initialized in :meth:`_initialize_janus_queues` (running inside
the orchestrator thread) before the master server starts, so it
is non-None here; ``janus.Queue.sync_q`` is thread-safe by
construction.
"""
if self.request_queue is None:
logger.warning(
"[AsyncOmniEngine] request_queue not initialized; dropping register_remote_replica stage=%d replica=%d",
stage_id,
replica_id,
)
return
msg = RegisterRemoteReplicaMessage(
stage_id=int(stage_id),
replica_id=int(replica_id),
)
try:
self.request_queue.sync_q.put_nowait(msg)
except Exception:
logger.exception(
"[AsyncOmniEngine] Failed to enqueue register_remote_replica for stage=%d replica=%d",
stage_id,
replica_id,
)
def _initialize_llm_replica(
self,
plan: ReplicaInitPlan,
@@ -686,6 +892,11 @@ class AsyncOmniEngine:
stage_init_timeout,
)
if self.single_stage_mode and self._omni_master_server is not None:
coord_router_addr: str | None = (
self._coordinator_runtime.router_address
if self._coordinator_runtime is not None
else None
)
engine_manager, coordinator, addresses = launch_stack.enter_context(
launch_omni_core_engines(
vllm_config=vllm_config,
@@ -695,6 +906,7 @@ class AsyncOmniEngine:
stage_id=plan.metadata.stage_id,
stage_config=stage_cfg,
replica_id=plan.replica_id,
omni_coordinator_address=coord_router_addr,
)
)
else:
@@ -830,12 +1042,20 @@ class AsyncOmniEngine:
"[AsyncOmniEngine] Stage %s diffusion registration completed",
plan.metadata.stage_id,
)
coord_router_addr: str | None = (
self._coordinator_runtime.router_address
if self._coordinator_runtime is not None
else None
)
proc, _, _, _ = spawn_diffusion_proc(
self.model,
od_config,
handshake_address=handshake_address,
request_address=request_address,
response_address=response_address,
omni_coordinator_address=coord_router_addr,
omni_stage_id=plan.metadata.stage_id,
omni_replica_id=plan.replica_id,
)
complete_diffusion_handshake(proc, handshake_address, stage_init_timeout)
logger.info(
@@ -1049,7 +1269,13 @@ class AsyncOmniEngine:
replicas_per_stage,
replica_devices_map,
)
# Capture per-stage context now (before _start_omni_master_server)
# so the on_register proxy can build head-side clients for
# registrations that arrive immediately after the server starts.
if self.single_stage_mode:
self._stage_remote_factory_contexts = capture_stage_factory_contexts(
stage_plans, diffusion_batch_size=self.diffusion_batch_size
)
self._start_omni_master_server(stage_plans)
stage_pools: list[StagePool] = []
@@ -1085,6 +1311,14 @@ class AsyncOmniEngine:
self._omni_master_server.stop()
except Exception:
logger.exception("[AsyncOmniEngine] Failed to stop OmniMasterServer during stage-init cleanup")
if self._coordinator_runtime is not None:
try:
self._coordinator_runtime.close()
except Exception:
logger.exception(
"[AsyncOmniEngine] Failed to close OmniCoordinatorRuntime during stage-init cleanup"
)
self._coordinator_runtime = None
raise
self.stage_pools = stage_pools
@@ -1104,13 +1338,6 @@ class AsyncOmniEngine:
supported_tasks.add("speech")
self.supported_tasks = tuple(supported_tasks) if supported_tasks else ("generate",)
def _initialize_janus_queues(self) -> None:
"""Initialize janus queues inside orchestrator thread loop context."""
self.request_queue = janus.Queue()
self.output_queue = janus.Queue()
self.rpc_output_queue = janus.Queue()
logger.debug("[AsyncOmniEngine] janus queues initialized in orchestrator thread loop")
def _bootstrap_orchestrator(
self,
stage_init_timeout: int,
@@ -1122,10 +1349,15 @@ class AsyncOmniEngine:
asyncio.set_event_loop(loop)
async def _run_orchestrator() -> None:
self._initialize_janus_queues()
self._initialize_stages(stage_init_timeout)
pd_config = self._detect_pd_config()
coordinator_pub_address: str | None = None
load_balancer_factory: Callable[[], LoadBalancer] | None = None
remote_replica_factory: Callable[[int, int], Awaitable[Any]] | None = None
if self._coordinator_runtime is not None:
coordinator_pub_address = self._coordinator_runtime.pub_address
load_balancer_factory = build_load_balancer_factory(self._omni_lb_policy)
remote_replica_factory = self._build_remote_replica
orchestrator = Orchestrator(
request_async_queue=self.request_queue.async_q,
output_async_queue=self.output_queue.async_q,
@@ -1133,6 +1365,9 @@ class AsyncOmniEngine:
stage_pools=self.stage_pools,
async_chunk=self.async_chunk,
pd_config=pd_config,
coordinator_pub_address=coordinator_pub_address,
load_balancer_factory=load_balancer_factory,
remote_replica_factory=remote_replica_factory,
)
if not startup_future.done():
startup_future.set_result(asyncio.get_running_loop())
@@ -1322,21 +1557,30 @@ class AsyncOmniEngine:
if stage0_pool.stage_type == "diffusion" or self._stage_pool_replica_count(stage0_pool) <= 1:
return None
# This synchronous request path can safely pre-bind local in-process
# replicas. Distributed head mode still uses the async picker inside
# StagePool.submit_initial().
if self._stage_pool_is_distributed(stage0_pool):
logger.debug(
"[AsyncOmniEngine] Skipping stage-0 multimodal cache scoping for distributed routing req=%s",
request_id,
)
return None
prompts = prompt if isinstance(prompt, list) else [prompt]
if not any(isinstance(p, dict) and p.get("multi_modal_data") for p in prompts):
return None
replica_id = stage0_pool.select_replica_id(request_id)
if self._stage_pool_is_distributed(stage0_pool):
preselect_replica_id = getattr(stage0_pool, "preselect_replica_id", None)
if not callable(preselect_replica_id):
logger.debug(
"[AsyncOmniEngine] Skipping stage-0 multimodal cache scoping for distributed routing "
"without preselect support req=%s",
request_id,
)
return None
replica_id = preselect_replica_id(request_id)
if replica_id is None:
logger.debug(
"[AsyncOmniEngine] Skipping stage-0 multimodal cache scoping for distributed routing "
"because no serviceable replica is available yet req=%s",
request_id,
)
return None
else:
replica_id = stage0_pool.select_replica_id(request_id)
for p in prompts:
self._ensure_stage_replica_mm_uuids(
p,
@@ -1632,6 +1876,7 @@ class AsyncOmniEngine:
data_parallel_size = normalized_kwargs.get("data_parallel_size") or 1
tensor_parallel_size = normalized_kwargs.get("tensor_parallel_size") or 1
cfg_parallel_size = normalized_kwargs.get("cfg_parallel_size") or 1
pipeline_parallel_size = normalized_kwargs.get("pipeline_parallel_size") or 1
vae_patch_parallel_size = normalized_kwargs.get("vae_patch_parallel_size") or 1
enable_expert_parallel = normalized_kwargs.get("enable_expert_parallel") or False
use_hsdp = normalized_kwargs.get("use_hsdp", False)
@@ -1947,8 +2192,6 @@ class AsyncOmniEngine:
reasoning_ended=reasoning_ended,
resumable=resumable,
)
if self.request_queue is None:
raise RuntimeError("request_queue is not initialized")
self.request_queue.sync_q.put_nowait(msg)
# CFG companion expansion: create and enqueue companion requests
@@ -2016,8 +2259,6 @@ class AsyncOmniEngine:
resumable=resumable,
message_type="streaming_update",
)
if self.request_queue is None:
raise RuntimeError("request_queue is not initialized")
self.request_queue.sync_q.put_nowait(msg)
async def add_streaming_update_async(
@@ -2044,8 +2285,6 @@ class AsyncOmniEngine:
def try_get_output(self, timeout: float = 0.001) -> EngineQueueMessage | None:
"""Read one output message from the Orchestrator output queue."""
if self.output_queue is None:
return None
try:
return self.output_queue.sync_q.get(timeout=timeout)
except queue.Empty:
@@ -2055,8 +2294,6 @@ class AsyncOmniEngine:
async def try_get_output_async(self) -> EngineQueueMessage | None:
"""Async read from the Orchestrator output queue."""
if self.output_queue is None:
return None
try:
return self.output_queue.sync_q.get_nowait()
except queue.Empty:
@@ -2091,11 +2328,6 @@ class AsyncOmniEngine:
This uses a dedicated RPC output queue so control-plane messages do not
race with the normal request output polling loop.
"""
if self.request_queue is None:
raise RuntimeError("request_queue is not initialized")
if self.rpc_output_queue is None:
raise RuntimeError("rpc_output_queue is not initialized")
rpc_id = uuid.uuid4().hex
msg = CollectiveRPCRequestMessage(
rpc_id=rpc_id,
@@ -2183,8 +2415,6 @@ class AsyncOmniEngine:
logger.warning("[AsyncOmniEngine] Orchestrator thread did not exit in time")
for q in (self.request_queue, self.output_queue, self.rpc_output_queue):
if q is None:
continue
try:
q.close()
except Exception:
@@ -2197,6 +2427,13 @@ class AsyncOmniEngine:
logger.exception("[AsyncOmniEngine] Failed to stop OmniMasterServer during shutdown")
self._omni_master_server = None
if self._coordinator_runtime is not None:
try:
self._coordinator_runtime.close()
except Exception:
logger.exception("[AsyncOmniEngine] Failed to close OmniCoordinatorRuntime during shutdown")
self._coordinator_runtime = None
def _try_shutdown(self, *args, **kwargs) -> None:
try:
self.shutdown()
+12
View File
@@ -56,6 +56,18 @@ class ShutdownRequestMessage(EngineQueueMessage, kw_only=True):
type: Literal["shutdown"] = "shutdown"
class RegisterRemoteReplicaMessage(EngineQueueMessage, kw_only=True):
type: Literal["register_remote_replica"] = "register_remote_replica"
stage_id: int
replica_id: int
class UnregisterRemoteReplicaMessage(EngineQueueMessage, kw_only=True):
type: Literal["unregister_remote_replica"] = "unregister_remote_replica"
stage_id: int
input_addr: str
class ErrorMessage(EngineQueueMessage, kw_only=True):
type: Literal["error"] = "error"
error: str
@@ -0,0 +1,162 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Process manager for omni stage engine subprocesses.
This is a drop-in replacement for vLLM's :class:`CoreEngineProcManager` that
spawns :meth:`StageEngineCoreProc.run_stage_core` instead of the upstream
``EngineCoreProc.run_engine_core``, and forwards omni-specific kwargs
(coordinator address, stage id, per-rank replica id).
Each spawned subprocess corresponds to exactly one omni *replica*: it has its
own ZMQ allocation from :class:`OmniMasterServer` and (when an
``omni_coordinator_address`` is provided) its own
:class:`OmniCoordClientForStage` reporting heartbeat / status.
Liveness monitoring and shutdown are inherited from
:class:`CoreEngineProcManager` unchanged.
"""
from __future__ import annotations
import contextlib
import threading
import weakref
from multiprocessing.process import BaseProcess
from multiprocessing.queues import Queue
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils import numa_utils
from vllm.utils.system_utils import get_mp_context
from vllm.v1.engine.utils import CoreEngineProcManager
from vllm.v1.executor import Executor
from vllm.v1.utils import shutdown
from vllm_omni.engine.stage_engine_core_proc import StageEngineCoreProc
logger = init_logger(__name__)
try:
# ``set_device_control_env_var`` lives next to CoreEngineProcManager and
# is only required for non-CUDA DP, so we tolerate its absence on
# older / future vLLM revisions.
from vllm.v1.engine.utils import set_device_control_env_var # type: ignore
except ImportError: # pragma: no cover - depends on vLLM build
set_device_control_env_var = None # type: ignore[assignment]
class OmniCoreEngineProcManager(CoreEngineProcManager):
"""Spawn :class:`StageEngineCoreProc` subprocesses with omni kwargs.
The body mirrors :class:`CoreEngineProcManager.__init__` because the
upstream class hardcodes ``target=EngineCoreProc.run_engine_core`` and
does not expose an extensibility hook. The differences from upstream are:
* ``target`` is :meth:`StageEngineCoreProc.run_stage_core`.
* Per-rank ``omni_replica_id`` is computed as
``base_replica_id + rank_idx`` and added to each subprocess's kwargs.
* ``omni_coordinator_address`` (if provided) and ``omni_stage_id`` are
added to every subprocess's kwargs.
"""
def __init__(
self,
local_engine_count: int,
start_index: int,
local_start_index: int,
vllm_config: VllmConfig,
local_client: bool,
handshake_address: str,
executor_class: type[Executor],
log_stats: bool,
*,
omni_stage_id: int,
omni_coordinator_address: str | None = None,
omni_replica_base_id: int = 0,
client_handshake_address: str | None = None,
tensor_queue: Queue | None = None,
) -> None:
# NOTE: we intentionally do not call ``super().__init__`` — the
# parent's body hardcodes the wrong target. We re-implement it here
# while reusing the parent's instance methods (shutdown, monitor).
if local_engine_count <= 0:
raise ValueError(f"local_engine_count must be > 0, got {local_engine_count}")
context = get_mp_context()
common_kwargs: dict[str, object] = {
"vllm_config": vllm_config,
"local_client": local_client,
"handshake_address": handshake_address,
"executor_class": executor_class,
"log_stats": log_stats,
"tensor_queue": tensor_queue,
"omni_stage_id": int(omni_stage_id),
"omni_coordinator_address": omni_coordinator_address,
}
if client_handshake_address:
common_kwargs["client_handshake_address"] = client_handshake_address
# Intra-replica vLLM DP mesh (i.e. ``data_parallel_size`` ranks sharing
# one engine, one DPCoordinator, one set of weights). Distinct from
# the omni-level notion of multiple independent replicas of a stage —
# those each spawn their own OmniCoreEngineProcManager and never join
# a vLLM DP group across replicas.
has_intra_replica_dp = vllm_config.parallel_config.data_parallel_size > 1
self.processes: list[BaseProcess] = []
local_dp_ranks: list[int] = []
for index in range(local_engine_count):
local_index = local_start_index + index
global_index = start_index + index
# Each spawned subprocess is one omni replica. The replica id
# is contiguous within this manager; the master server may have
# pre-allocated a contiguous block starting at ``omni_replica_base_id``.
omni_replica_id = omni_replica_base_id + index
local_dp_ranks.append(local_index)
self.processes.append(
context.Process(
target=StageEngineCoreProc.run_stage_core,
name=(
f"StageEngineCoreProc_stage{omni_stage_id}"
f"_replica{omni_replica_id}" + (f"_DP{global_index}" if has_intra_replica_dp else "")
),
kwargs=common_kwargs
| {
"dp_rank": global_index,
"local_dp_rank": local_index,
"omni_replica_id": omni_replica_id,
},
)
)
self._finalizer = weakref.finalize(self, shutdown, self.processes)
self.manager_stopped = threading.Event()
self.failed_proc_name: str | None = None
try:
for proc, local_dp_rank in zip(self.processes, local_dp_ranks):
device_control_context: contextlib.AbstractContextManager[None] = contextlib.nullcontext()
if (
has_intra_replica_dp
and set_device_control_env_var is not None
and (not current_platform.is_cuda_alike() or vllm_config.parallel_config.use_ray)
):
device_control_context = set_device_control_env_var(vllm_config, local_dp_rank)
with (
device_control_context,
numa_utils.configure_subprocess(
vllm_config,
local_rank=0,
dp_local_rank=local_dp_rank,
process_kind="EngineCore",
),
):
proc.start()
finally:
if self.finished_procs():
self.shutdown()
+252 -8
View File
@@ -4,12 +4,20 @@ Orchestrator for vLLM-Omni multi-stage runtime.
Runs inside a background thread with its own asyncio event loop.
Owns logical request progression across stage pools and handles
stage-to-stage transfer logic.
In distributed mode (``coordinator_pub_address`` provided), it also
owns the single :class:`OmniCoordClientForHub`, runs a
:meth:`_watch_replica_list` task that converts replica disappearances
into ``unregister_remote_replica`` control messages, and handles the
``register_remote_replica`` / ``unregister_remote_replica`` flow that
attaches / detaches head-side stage clients for headless replicas.
"""
from __future__ import annotations
import asyncio
import time as _time
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from typing import Any
@@ -22,6 +30,12 @@ from vllm.sampling_params import SamplingParams
from vllm.v1.engine import EngineCoreOutputs
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.distributed.omni_coordinator import (
LoadBalancer,
OmniCoordClientForHub,
RandomBalancer,
ReplicaStatus,
)
from vllm_omni.engine import OmniEngineCoreRequest
from vllm_omni.engine.cfg_companion_tracker import CfgCompanionTracker
from vllm_omni.engine.messages import (
@@ -32,13 +46,26 @@ from vllm_omni.engine.messages import (
EngineQueueMessage,
ErrorMessage,
OutputMessage,
RegisterRemoteReplicaMessage,
ShutdownRequestMessage,
StageMetricsMessage,
StageSubmissionMessage,
UnregisterRemoteReplicaMessage,
)
from vllm_omni.engine.serialization import serialize_additional_information
from vllm_omni.engine.stage_pool import StagePool
from vllm_omni.outputs import OmniRequestOutput
# Factory signature for building a head-side stage client for a
# *dynamically attached* (auto-assigned) remote replica.
#
# Receives ``(stage_id, replica_id)`` and returns an awaitable yielding the
# constructed client (any type — it must satisfy the shape expected by the
# matching :class:`StagePool`, i.e. expose ``client_addresses["input_address"]``
# or ``request_address``, plus the usual ``add_request_async`` /
# ``get_output_async`` / ``shutdown`` surface).
RemoteReplicaFactory = Callable[[int, int], Awaitable[Any]]
logger = init_logger(__name__)
@@ -124,6 +151,10 @@ class StreamingInputState:
class Orchestrator:
"""Runs inside a background thread's asyncio event loop."""
# Cadence at which the replica-list watcher polls for disappearances.
_WATCH_REPLICA_INTERVAL_S: float = 0.5
_WATCH_REPLICA_IDLE_INTERVAL_S: float = 1.0
def __init__(
self,
request_async_queue: janus.AsyncQueue[EngineQueueMessage],
@@ -133,6 +164,9 @@ class Orchestrator:
*,
async_chunk: bool = False,
pd_config: dict[str, Any] | None = None,
coordinator_pub_address: str | None = None,
load_balancer_factory: Callable[[], LoadBalancer] | None = None,
remote_replica_factory: RemoteReplicaFactory | None = None,
) -> None:
self.request_async_queue = request_async_queue
self.output_async_queue = output_async_queue
@@ -159,6 +193,28 @@ class Orchestrator:
self._fatal_error: str | None = None
self._fatal_error_stage_id: int | None = None
# Background tasks for fire-and-forget message handlers (currently
# only ``register_remote_replica`` and ``unregister_remote_replica``).
# Held as a set so each task's reference survives the loop and the
# task can self-deregister on completion.
self._membership_tasks: set[asyncio.Task[None]] = set()
# Distributed-mode wiring. The hub is constructed on the
# orchestrator's asyncio loop because it spawns a SUB background
# thread; building it from another thread would race the
# ``_init_done`` event.
self._hub: OmniCoordClientForHub | None = (
OmniCoordClientForHub(coordinator_pub_address) if coordinator_pub_address is not None else None
)
self._remote_replica_factory = remote_replica_factory
# Inject hub + per-pool LB into each StagePool so they can run
# distributed dispatch via ``StagePool.pick``.
if self._hub is not None:
factory = load_balancer_factory or RandomBalancer
for pool in self.stage_pools:
pool.attach_hub(self._hub)
pool.attach_load_balancer(factory())
async def run(self) -> None:
"""Main entry point for the Orchestrator event loop."""
logger.info("[Orchestrator] Starting event loop")
@@ -168,9 +224,16 @@ class Orchestrator:
self._orchestration_output_handler(),
name="orchestrator-stage-output-handler",
)
# The replica watcher only runs in distributed mode. It's still
# created in both cases so ``run()`` has a uniform task graph;
# ``_watch_replica_list`` is a no-op poll when ``self._hub`` is None.
watch_task = asyncio.create_task(
self._watch_replica_list(),
name="orchestrator-replica-watcher",
)
try:
await asyncio.gather(request_task, output_task)
await asyncio.gather(request_task, output_task, watch_task)
except asyncio.CancelledError:
raise
except EngineDeadError as e:
@@ -185,11 +248,11 @@ class Orchestrator:
raise
finally:
self._shutdown_event.set()
for task in (request_task, output_task):
for task in (request_task, output_task, watch_task):
if not task.done():
task.cancel()
try:
await asyncio.gather(request_task, output_task, return_exceptions=True)
await asyncio.gather(request_task, output_task, watch_task, return_exceptions=True)
except Exception:
pass
@@ -199,8 +262,32 @@ class Orchestrator:
if self._fatal_error is not None:
await self._drain_pending_requests_on_fatal()
# Wait briefly for any in-flight membership handlers (register /
# unregister remote replica) to finish so they don't leave the
# head-side pool in a half-attached state. Cancel anything that
# hasn't completed in time; the generic pending-task sweep below
# will collect the cancellations.
if self._membership_tasks:
try:
await asyncio.wait_for(
asyncio.gather(*self._membership_tasks, return_exceptions=True),
timeout=10.0,
)
except (asyncio.TimeoutError, Exception):
for t in self._membership_tasks:
if not t.done():
t.cancel()
self._shutdown_stages()
# Close the hub last so any in-flight dispatch still has access.
if self._hub is not None:
try:
self._hub.close()
except RuntimeError:
pass
self._hub = None
loop = asyncio.get_running_loop()
pending = [t for t in asyncio.all_tasks(loop) if t is not asyncio.current_task() and not t.done()]
for task in pending:
@@ -208,6 +295,27 @@ class Orchestrator:
if pending:
await asyncio.gather(*pending, return_exceptions=True)
# ---- Background task helpers ----
def _spawn_membership_task(self, coro: Awaitable[None], *, label: str) -> None:
"""Run a fire-and-forget membership-change coroutine.
Holds a strong reference until completion (asyncio would otherwise
garbage-collect a bare task), and logs any uncaught exception.
"""
task = asyncio.create_task(coro, name=f"orchestrator-{label}")
self._membership_tasks.add(task)
def _on_done(t: asyncio.Task[None]) -> None:
self._membership_tasks.discard(t)
if t.cancelled():
return
exc = t.exception()
if exc is not None:
logger.error("[Orchestrator] %s task crashed", label, exc_info=exc)
task.add_done_callback(_on_done)
# ---- Request handling ----
async def _request_handler(self) -> None:
@@ -226,7 +334,20 @@ class Orchestrator:
await self._handle_abort(msg)
elif msg_type == "collective_rpc":
await self._handle_collective_rpc(msg)
elif msg_type == "shutdown":
elif isinstance(msg, RegisterRemoteReplicaMessage):
# Dynamic-attach involves a ~5s blocking handshake (run in a
# thread by ``_build_remote_replica``); ``await`` here would
# block the queue and stall the next ``add_request`` until
# the attach finishes. Dispatch as a background task so the
# main message loop keeps draining.
self._spawn_membership_task(self._handle_register_remote_replica(msg), label="register_remote_replica")
elif isinstance(msg, UnregisterRemoteReplicaMessage):
# Symmetric with register: keep the main queue flowing.
self._spawn_membership_task(
self._handle_unregister_remote_replica(msg),
label="unregister_remote_replica",
)
elif isinstance(msg, ShutdownRequestMessage):
logger.info("[Orchestrator] Received shutdown signal")
self._shutdown_event.set()
# Pre-mark stage clients as shutting down to prevent
@@ -415,7 +536,7 @@ class Orchestrator:
results: list[Any] = []
stage_ids: list[int] = []
for pool in target_pools:
for replica_id in range(pool.num_replicas):
for replica_id in pool.live_replica_ids():
stage_result = await pool.collective_rpc(
replica_id=replica_id,
method=method,
@@ -451,7 +572,7 @@ class Orchestrator:
idle = True
for stage_id in range(self.num_stages):
pool = self.stage_pools[stage_id]
for replica_id in range(pool.num_replicas):
for replica_id in pool.live_replica_ids():
if self._shutdown_event.is_set():
return
@@ -1105,14 +1226,137 @@ class Orchestrator:
)
self.request_states.pop(req_id, None)
# ---- Distributed-mode replica attach / detach ----
async def _watch_replica_list(self) -> None:
"""Convert hub replica disappearances into unregister control messages."""
last_up: set[tuple[int, str]] = set()
while not self._shutdown_event.is_set():
if self._hub is None:
# No coordinator wired up; sleep coarsely and re-check shutdown.
try:
await asyncio.sleep(self._WATCH_REPLICA_IDLE_INTERVAL_S)
except asyncio.CancelledError:
raise
continue
try:
snap = self._hub.get_replica_list()
current = {(rep.stage_id, rep.input_addr) for rep in snap.replicas if rep.status == ReplicaStatus.UP}
for stage_id, addr in last_up - current:
await self.request_async_queue.put(
UnregisterRemoteReplicaMessage(
stage_id=stage_id,
input_addr=addr,
)
)
last_up = current
except asyncio.CancelledError:
raise
except Exception:
logger.exception("[Orchestrator] _watch_replica_list iteration failed")
try:
await asyncio.sleep(self._WATCH_REPLICA_INTERVAL_S)
except asyncio.CancelledError:
raise
async def _handle_register_remote_replica(self, msg: RegisterRemoteReplicaMessage) -> None:
"""Bind a head-side client for a newly registered remote replica."""
stage_id = int(msg.stage_id)
replica_id = int(msg.replica_id)
if not (0 <= stage_id < self.num_stages):
logger.warning(
"[Orchestrator] register_remote_replica: stage_id %d out of range (num_stages=%d)",
stage_id,
self.num_stages,
)
return
if self._remote_replica_factory is None:
logger.warning(
"[Orchestrator] register_remote_replica received for stage=%d replica=%d but no factory installed",
stage_id,
replica_id,
)
return
try:
await self._attach_remote_replica(stage_id, replica_id)
except Exception:
logger.exception(
"[Orchestrator] failed to attach remote replica stage=%d replica=%d",
stage_id,
replica_id,
)
async def _handle_unregister_remote_replica(self, msg: UnregisterRemoteReplicaMessage) -> None:
"""Tear down the head-side client for a vanished remote replica."""
stage_id = int(msg.stage_id)
input_addr = str(msg.input_addr)
if not (0 <= stage_id < self.num_stages):
return
pool = self.stage_pools[stage_id]
affected = pool.invalidate_addr(input_addr)
self._detach_remote_replica(stage_id, input_addr)
if affected:
await self._cleanup_request_ids(affected, abort=True)
for req_id in affected:
await self.output_async_queue.put(
ErrorMessage(
error="stage replica disappeared",
request_id=req_id,
stage_id=stage_id,
)
)
async def _attach_remote_replica(self, stage_id: int, replica_id: int) -> None:
"""Build a head-side stage client via the injected factory and register it."""
factory = self._remote_replica_factory
if factory is None:
return
pool = self.stage_pools[stage_id]
client = await factory(stage_id, replica_id)
input_addr = StagePool._client_input_addr(client)
if input_addr is None:
raise RuntimeError(
f"remote replica factory for stage {stage_id} produced a client without a discoverable input address"
)
pool.add_client(input_addr, client)
logger.info(
"[Orchestrator] attached remote replica stage=%d replica=%d addr=%s",
stage_id,
replica_id,
input_addr,
)
def _detach_remote_replica(self, stage_id: int, input_addr: str) -> None:
"""Shut down + remove the head-side client at ``input_addr``."""
pool = self.stage_pools[stage_id]
client = pool.remove_client(input_addr)
if client is None:
return
try:
client.shutdown()
except Exception:
logger.exception(
"[Orchestrator] failed to shutdown client for stage=%d addr=%s",
stage_id,
input_addr,
)
logger.info(
"[Orchestrator] detached remote replica stage=%d addr=%s",
stage_id,
input_addr,
)
def _shutdown_stages(self) -> None:
"""Shutdown all stage pools."""
if self._stages_shutdown:
return
self._stages_shutdown = True
total = sum(pool.num_replicas for pool in self.stage_pools)
total = sum(pool.live_num_replicas for pool in self.stage_pools)
logger.info("[Orchestrator] Shutting down all %d client(s)", total)
for pool in self.stage_pools:
for replica_id in range(pool.num_replicas):
for replica_id in pool.live_replica_ids():
pool.shutdown_replica(replica_id)
+20 -3
View File
@@ -8,6 +8,7 @@ from __future__ import annotations
import inspect
import multiprocessing.connection
import os
import socket
import threading
import weakref
@@ -20,9 +21,13 @@ from vllm.v1.engine import EngineCoreRequest
from vllm.v1.engine.core_client import AsyncMPClient, DPLBAsyncMPClient
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.distributed.omni_connectors.utils.config import (
TRANSFER_ENGINE_CONNECTOR_NAMES,
)
from vllm_omni.distributed.omni_connectors.utils.initialization import (
KV_TRANSFER_PORT_OFFSET,
)
from vllm_omni.distributed.omni_connectors.utils.kv_utils import kv_zmq_port
from vllm_omni.engine.stage_client import StageClientBase
from vllm_omni.engine.stage_init_utils import StageMetadata
@@ -330,11 +335,13 @@ class StageEngineCoreClientBase(StageClientBase):
if sender_host is not None:
self._kv_sender_host = sender_host
connector_type = connector_config.get("type")
sender_port = connector_config.get("sender_zmq_port")
if sender_port is None:
if connector_type in TRANSFER_ENGINE_CONNECTOR_NAMES or sender_port is None:
base_port = connector_config.get("zmq_port")
if base_port is None:
return
base_port = os.path.expandvars(str(base_port))
omni_kv_config = getattr(self, "_omni_kv_config", None)
from_stage = self.stage_id
@@ -344,7 +351,12 @@ class StageEngineCoreClientBase(StageClientBase):
try:
# Orchestrator always reports rank-0's port; receiver
# workers add their own local_rank * KV_RANK_PORT_STRIDE.
sender_port = int(base_port) + KV_TRANSFER_PORT_OFFSET + int(from_stage)
sender_port = kv_zmq_port(
int(base_port),
int(from_stage),
local_rank=0,
replica_id=self.replica_id,
)
except (TypeError, ValueError):
logger.warning(
"[StageEngineCoreClient] stage-%s [rep-%s] could not resolve sender_zmq_port "
@@ -386,7 +398,12 @@ class StageEngineCoreClientBase(StageClientBase):
# rank-0 base port; receiver workers adjust per KV_RANK_PORT_STRIDE.
return {
"host": self._kv_sender_host,
"zmq_port": base_port + kv_transfer_port_offset + int(self.stage_id),
"zmq_port": kv_zmq_port(
base_port - KV_TRANSFER_PORT_OFFSET + kv_transfer_port_offset,
int(self.stage_id),
local_rank=0,
replica_id=self.replica_id,
),
}
def set_engine_outputs(self, engine_outputs: EngineCoreOutput) -> None:
+68 -13
View File
@@ -7,6 +7,8 @@ busy loop in a subprocess, communicating with StageEngineCoreClient via ZMQ.
from __future__ import annotations
import contextlib
import os
import signal
from multiprocessing.process import BaseProcess
from typing import TYPE_CHECKING, Any
@@ -33,6 +35,8 @@ from vllm.v1.engine.utils import (
)
from vllm.v1.utils import shutdown
from vllm_omni.distributed.omni_coordinator import OmniCoordClientForStage
if TYPE_CHECKING:
from vllm.config import VllmConfig
from vllm.v1.executor import Executor
@@ -53,28 +57,41 @@ class StageEngineCoreProc(EngineCoreProc):
*args: Any,
dp_rank: int = 0,
local_dp_rank: int = 0,
omni_coordinator_address: str | None = None,
omni_stage_id: int | None = None,
omni_replica_id: int = 0,
**kwargs: Any,
) -> None:
"""Launch StageEngineCoreProc busy loop in background process."""
"""Launch StageEngineCoreProc busy loop in background process.
Omni-specific kwargs:
- ``omni_coordinator_address``: ROUTER address of the head-side
:class:`OmniCoordinator`. When provided, this subprocess
instantiates an :class:`OmniCoordClientForStage` after the
HELLO/INIT/READY handshake completes and reports its status +
queue length via heartbeats. The hook is wired so each
heartbeat refreshes ``queue_length`` from the live scheduler.
- ``omni_stage_id``: logical stage id this replica belongs to.
Required when ``omni_coordinator_address`` is provided.
- ``omni_replica_id``: cluster-unique replica id within the
stage (assigned by :class:`OmniMasterServer`). Used for
logging / metrics only.
"""
signal_callback: SignalCallback | None = None
maybe_register_config_serialize_by_value()
engine_core: StageEngineCoreProc | None = None
coord_client: OmniCoordClientForStage | None = None
try:
vllm_config: VllmConfig = kwargs["vllm_config"]
parallel_config = vllm_config.parallel_config
# NOTE: previous revisions hardcoded data_parallel_size=1 here
# (TODO referencing issue #984). The hardcoding has been removed
# so the DP fields propagate through from the caller exactly
# like upstream vLLM.
set_process_title(f"StageEngineCoreProc_DP{dp_rank}")
stage_label = f"stage{omni_stage_id}" if omni_stage_id is not None else "noid"
set_process_title(f"StageEngineCoreProc_{stage_label}_replica{omni_replica_id}_DP{dp_rank}")
decorate_logs()
# the current vllm-omni does not support data parallelism,
# so we set the data parallel size to 1.
# [TODO] support data parallelism in the future.
# https://github.com/vllm-project/vllm-omni/issues/984
parallel_config.data_parallel_size = 1
parallel_config.data_parallel_size_local = 1
parallel_config.data_parallel_rank = 0
parallel_config.data_parallel_index = dp_rank
os.environ["VLLM_OMNI_REPLICA_ID"] = str(max(int(omni_replica_id), 0))
engine_core = StageEngineCoreProc(
*args,
@@ -82,6 +99,41 @@ class StageEngineCoreProc(EngineCoreProc):
**kwargs,
)
# Each subprocess corresponds to exactly one omni replica with
# its own OmniMasterServer allocation, so the heartbeat client
# runs unconditionally — there is no dp_rank-based gating.
if omni_coordinator_address is not None:
if omni_stage_id is None:
raise ValueError("omni_stage_id must be provided when omni_coordinator_address is set")
addresses: EngineZmqAddresses = engine_core.addresses
if not addresses.inputs or not addresses.outputs:
raise RuntimeError(
"EngineCore handshake did not populate input/output addresses; "
"cannot start OmniCoordClientForStage"
)
coord_client = OmniCoordClientForStage(
coord_zmq_addr=omni_coordinator_address,
input_addr=addresses.inputs[0],
output_addr=addresses.outputs[0],
stage_id=int(omni_stage_id),
)
def _refresh_queue_length() -> None:
"""Pre-heartbeat hook: refresh queue_length from scheduler."""
scheduler = getattr(engine_core, "scheduler", None)
if scheduler is None:
return
try:
coord_client._queue_length = int( # type: ignore[union-attr]
scheduler.get_num_unfinished_requests()
)
except Exception:
# Live scheduler stats are best-effort — heartbeats
# must not fail because of a stats lookup error.
pass
coord_client._on_heartbeat = _refresh_queue_length
def wakeup_engine() -> None:
engine_core.input_queue.put_nowait((EngineCoreRequestType.WAKEUP, None))
@@ -111,6 +163,9 @@ class StageEngineCoreProc(EngineCoreProc):
signal.signal(signal.SIGINT, signal.SIG_DFL)
if signal_callback is not None:
signal_callback.stop()
if coord_client is not None:
with contextlib.suppress(RuntimeError):
coord_client.close()
if engine_core is not None:
engine_core.shutdown()
+390 -59
View File
@@ -4,8 +4,9 @@ from __future__ import annotations
import contextlib
import dataclasses
import socket
import threading
from collections.abc import Iterator
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from typing import Any
@@ -31,6 +32,15 @@ logger = init_logger(__name__)
StageRoute = tuple[int, int]
# Sentinel that signals "auto-assign me a replica_id" on the wire. Negative
# values are not valid replica ids, so any sub-zero value works equivalently.
AUTO_ASSIGN_REPLICA_ID = -1
# Callback signature for OmniMasterServer.on_register. Fires only for
# auto-assigned replicas (new, headless-launched). The arguments are
# (stage_id, replica_id, allocation).
OnRegisterCallback = Callable[[int, int, "StageAllocation"], None]
# Poll period (ms) used by the registration/handshake loop.
_POLL_PERIOD_MS = 5_000
# Default timeout (s) for a stage to send READY.
@@ -110,6 +120,10 @@ class OmniMasterServer:
master_port: int,
stage_ids: list[int],
stage_replica_counts: dict[int, int] | None = None,
*,
coordinator_router_address: str | None = None,
on_register: OnRegisterCallback | None = None,
head_local_replicas: dict[int, list[int]] | None = None,
) -> None:
self._address = master_address
self._port = master_port
@@ -117,25 +131,41 @@ class OmniMasterServer:
self._stage_configs: dict[StageRoute, Any] = {}
self._stage_coordinator_addresses: dict[StageRoute, StageCoordinatorAddresses] = {}
self._stage_config_events: dict[StageRoute, threading.Event] = {}
# Coordinator ROUTER address echoed back in every registration reply
# so OmniCoordClientForStage knows where to connect from inside the
# engine subprocess.
self._coordinator_router_address = coordinator_router_address
# Fires only for *newly assigned* (auto-assigned) replicas, not for
# head-side pre-allocated slots that already have head-side clients.
self._on_register = on_register
# Per-stage allocation lock + auto-assign cursor, so concurrent
# registrations from multiple headless processes for the same stage
# don't race on the routing table.
self._alloc_lock = threading.Lock()
self._stage_ids_known: set[int] = set(int(sid) for sid in stage_ids)
self._thread: threading.Thread | None = None
self._stop_event = threading.Event()
stage_replica_counts = dict(stage_replica_counts or {})
# Slots the *head* itself will fill via ``launch_omni_core_engines``
# / its own ``register_stage_with_omni_master`` call. Auto-assigning
# headless registrations must skip these even when they appear
# ``_stage_configs``-unfilled — otherwise a fast headless on the same
# host can race the head's own registration and steal slot 0.
self._head_local_slots: set[StageRoute] = set()
for sid, rids in (head_local_replicas or {}).items():
for rid in rids:
self._head_local_slots.add((int(sid), int(rid)))
for sid in stage_ids:
replica_count = max(1, int(stage_replica_counts.get(sid, 1)))
replica_count = int(stage_replica_counts.get(sid, 1))
# Allow 0 explicitly so non-self stages (head distributed mode)
# can declare "no local replicas; remote ones will register
# dynamically".
if replica_count < 0:
raise ValueError(f"stage_replica_counts[{sid}] must be >= 0, got {replica_count}")
for replica_id in range(replica_count):
route = (sid, replica_id)
self._stage_config_events[route] = threading.Event()
self._stage_coordinator_addresses[route] = StageCoordinatorAddresses()
hs_port, inp_port, out_port = get_open_ports_list(count=3)
self._stage_routes[route] = StageAllocation(
handshake_bind_address=f"tcp://{master_address}:{hs_port}",
handshake_connect_address=f"tcp://{master_address}:{hs_port}",
input_bind_address=f"tcp://{master_address}:{inp_port}",
input_connect_address=f"tcp://{master_address}:{inp_port}",
output_bind_address=f"tcp://{master_address}:{out_port}",
output_connect_address=f"tcp://{master_address}:{out_port}",
)
self._allocate_route_locked(sid, replica_id)
logger.info(
"[OmniMasterServer] Pre-allocated addresses for stages %s (master=%s:%d)",
@@ -157,10 +187,84 @@ class OmniMasterServer:
"""Return the registration port exposed to stage launchers."""
return self._port
@property
def coordinator_router_address(self) -> str | None:
"""Return the OmniCoordinator ROUTER address echoed to replicas."""
return self._coordinator_router_address
def get_allocation(self, stage_id: int, replica_id: int = 0) -> StageAllocation:
"""Return the full address allocation for *stage_id*."""
return self._stage_routes[(stage_id, replica_id)]
# ------------------------------------------------------------------
# Allocation
# ------------------------------------------------------------------
def _allocate_route_locked(self, stage_id: int, replica_id: int) -> StageAllocation:
"""Allocate handshake/input/output ports for ``(stage_id, replica_id)``.
Idempotent: if the route already exists, returns the existing
allocation unchanged. Caller is responsible for holding
``self._alloc_lock`` when needed.
"""
route = (stage_id, replica_id)
existing = self._stage_routes.get(route)
if existing is not None:
return existing
self._stage_config_events[route] = threading.Event()
self._stage_coordinator_addresses[route] = StageCoordinatorAddresses()
hs_port, inp_port, out_port = get_open_ports_list(count=3)
alloc = StageAllocation(
handshake_bind_address=f"tcp://{self._address}:{hs_port}",
handshake_connect_address=f"tcp://{self._address}:{hs_port}",
input_bind_address=f"tcp://{self._address}:{inp_port}",
input_connect_address=f"tcp://{self._address}:{inp_port}",
output_bind_address=f"tcp://{self._address}:{out_port}",
output_connect_address=f"tcp://{self._address}:{out_port}",
)
self._stage_routes[route] = alloc
return alloc
def _next_free_replica_id(self, stage_id: int) -> int:
"""Return the next replica id to assign for an auto-assign registration.
Strategy: prefer filling a pre-allocated-but-unfilled slot (one that
``__init__`` reserved in ``_stage_routes`` but no registration has
completed yet) so the head's bootstrap path — which waits on
``_stage_config_events[(stage_id, replica_id)]`` for specific
pre-allocated ids — unblocks. Only when every pre-allocated slot for
this stage has been filled do we allocate a fresh id.
Slots in ``_head_local_slots`` are reserved for the head's own
``launch_omni_core_engines`` registration. Auto-assign must skip
them even when ``_stage_configs`` shows them unfilled — otherwise a
same-host headless that registers before the head's own
``register_stage_with_omni_master`` call would steal slot 0.
Without this, a headless contributor using ``--omni-dp-size-local > 1``
(auto-assign mode) would skip past pre-allocated slot 0 and pick ids
beyond ``num_replicas``, deadlocking the head's
``connect_remote_engine_cores`` wait.
"""
# Pre-allocated slots that haven't received a registration yet are
# tracked by absence from ``_stage_configs``. Head-owned slots are
# not auto-assignable.
for sid, rid in sorted(self._stage_routes):
if sid != stage_id:
continue
if (sid, rid) in self._head_local_slots:
continue
if (sid, rid) not in self._stage_configs:
return rid
# Every pre-allocated slot is filled (or head-owned); allocate a
# fresh id past the existing routes.
used = {rid for (sid, rid) in self._stage_routes if sid == stage_id}
rid = 0
while rid in used:
rid += 1
return rid
def register_stage_config(
self,
stage_id: int,
@@ -280,12 +384,21 @@ class OmniMasterServer:
poller = zmq.Poller()
poller.register(reg_socket, zmq.POLLIN)
# The server runs until ``stop()`` is called so that headless replicas
# spawned after the head finished its initial bring-up can still
# register dynamically. ``pending`` is kept around purely for
# debug-level logging of which pre-allocated slots have not yet
# registered; once empty it does not terminate the loop.
pending: set[StageRoute] = set(self._stage_routes.keys())
while pending and not self._stop_event.is_set():
while not self._stop_event.is_set():
events: list[tuple[zmq.Socket, int]] = poller.poll(_POLL_PERIOD_MS) # type: ignore[assignment]
if not events:
logger.debug("[OmniMasterServer] Still waiting for registration from stages: %s", pending)
if pending:
logger.debug(
"[OmniMasterServer] Still waiting for registration from pre-allocated slots: %s",
pending,
)
continue
for sock, _ in events:
@@ -296,12 +409,12 @@ class OmniMasterServer:
# Cleanup
reg_socket.close(linger=0)
logger.info("[OmniMasterServer] All stages registered; server thread exiting.")
logger.info("[OmniMasterServer] Server thread exiting.")
def _handle_registration(self, reg_socket: zmq.Socket) -> StageRoute | None: # type: ignore[type-arg]
"""Receive a stage registration and reply with the handshake address.
Returns the registered stage_id on success, or None on failure.
Returns ``(stage_id, replica_id)`` on success or ``None`` on failure.
"""
frames = reg_socket.recv_multipart()
if len(frames) < 2:
@@ -318,45 +431,186 @@ class OmniMasterServer:
logger.warning("[OmniMasterServer] Failed to decode registration message: %s", exc)
return None
stage_id: int | None = msg.get("stage_id")
replica_id = int(msg.get("replica_id", 0) or 0)
key = (stage_id, replica_id)
if key not in self._stage_routes:
stage_id_raw = msg.get("stage_id")
if not isinstance(stage_id_raw, int) or stage_id_raw < 0:
logger.warning(
"[OmniMasterServer] Received registration for unknown stage_id=%s replica_id=%s",
stage_id,
replica_id,
"[OmniMasterServer] Registration missing or invalid stage_id: %r",
stage_id_raw,
)
return None
stage_id: int = stage_id_raw
self.register_stage_config(
stage_id,
msg.get("stage_config"),
coordinator_addresses=StageCoordinatorAddresses(
coordinator_input=msg.get("coordinator_input"),
coordinator_output=msg.get("coordinator_output"),
frontend_stats_publish_address=msg.get("frontend_stats_publish_address"),
),
replica_id=replica_id,
)
incoming_replica_id = int(msg.get("replica_id", 0) or 0)
was_auto_assigned = incoming_replica_id < 0
# Distinguish two registration shapes:
# - Pre-allocated slots (concrete replica_id >= 0): the head built
# this slot during _initialize_stages. Just confirm it; do NOT
# fire ``on_register`` (the head already has a head-side client).
# - Auto-assigned slots (replica_id == AUTO_ASSIGN_REPLICA_ID):
# a *new* replica from a headless launcher. Allocate, then
# fire ``on_register`` so the orchestrator attaches.
with self._alloc_lock:
if was_auto_assigned:
replica_id = self._next_free_replica_id(stage_id)
# When auto-assign picks a slot the head pre-allocated (and
# is therefore waiting on in ``connect_remote_engine_cores``),
# the head's bootstrap path builds the head-side client. We
# must NOT also fire ``on_register`` for it; otherwise the
# orchestrator would build a duplicate client and overwrite
# the bootstrap-built one in the pool, leaking it.
preexisting_slot = (stage_id, replica_id) in self._stage_routes
alloc = self._allocate_route_locked(stage_id, replica_id)
if preexisting_slot:
was_auto_assigned = False
else:
replica_id = incoming_replica_id
if (stage_id, replica_id) not in self._stage_routes:
# Tolerate explicit replica_ids that haven't been
# pre-allocated (e.g. headless that wants a specific id).
alloc = self._allocate_route_locked(stage_id, replica_id)
was_auto_assigned = True
else:
alloc = self._stage_routes[(stage_id, replica_id)]
# Cross-host override: when the registering replica advertised
# its own bind address + ports, rewrite the StageAllocation so
# each socket is rooted on the host that actually binds it
# (the master's pre-allocated ports are unreachable from a
# remote replica's host).
#
# Diffusion and LLM stages have different binder ownership:
#
# Diffusion remote replica (StageDiffusionProc):
# - handshake: replica binds -> rewrite to replica IP
# - input : replica binds -> rewrite to replica IP
# - output : replica binds -> rewrite to replica IP
#
# LLM remote replica (CoreClient on head):
# - handshake: head binds (``connect_remote_engine_cores``)
# -> keep on master IP, worker TCP-connects
# - input : head binds (``CoreClient`` ROUTER)
# -> keep on master IP, worker TCP-connects
# - output : head binds (``CoreClient`` PULL — default
# bind=True for PULL in ``make_zmq_socket``)
# -> keep on master IP, worker TCP-connects
#
# The registrant indicates which case via the boolean
# ``replica_binds_sockets`` payload flag. It defaults to
# True (the diffusion / single-host case) so older callers
# still get the previous full-rewrite semantics. For LLM
# remote replicas, the master keeps every address on its
# own host and the remote worker establishes 3 outbound
# TCP connections to the master.
new_bind_address = msg.get("replica_bind_address")
if new_bind_address:
replica_binds_sockets = bool(msg.get("replica_binds_sockets", True))
if replica_binds_sockets:
hs_port = int(msg["replica_handshake_port"])
inp_port = int(msg["replica_input_port"])
out_port = int(msg["replica_output_port"])
hs_bind_addr = f"tcp://{new_bind_address}:{hs_port}"
inp_bind_addr = f"tcp://{new_bind_address}:{inp_port}"
out_bind_addr = f"tcp://{new_bind_address}:{out_port}"
alloc = StageAllocation(
handshake_bind_address=hs_bind_addr,
handshake_connect_address=hs_bind_addr,
input_bind_address=inp_bind_addr,
input_connect_address=inp_bind_addr,
output_bind_address=out_bind_addr,
output_connect_address=out_bind_addr,
)
self._stage_routes[(stage_id, replica_id)] = alloc
logger.info(
"[OmniMasterServer] Stage %d replica %d cross-host bind (sockets bound on %s; replica_ip=%s)",
stage_id,
replica_id,
"replica" if replica_binds_sockets else "master",
new_bind_address,
)
# Mark the slot as filled *inside* the lock. Without this,
# concurrent auto-assign registrations from a second headless
# could call ``_next_free_replica_id`` between the lock
# releasing above and the ``register_stage_config`` call
# below, observe the slot as unfilled, and hand the same
# pre-allocated handshake/input/output addresses to two
# different replicas — which then collide on
# ``zmq_socket_ctx(handshake_address, ROUTER, bind=True)``.
self.register_stage_config(
stage_id,
msg.get("stage_config"),
coordinator_addresses=StageCoordinatorAddresses(
coordinator_input=msg.get("coordinator_input"),
coordinator_output=msg.get("coordinator_output"),
frontend_stats_publish_address=msg.get("frontend_stats_publish_address"),
),
replica_id=replica_id,
)
# Fire on_register only for genuinely new (auto-assigned or newly
# allocated) replicas, on the ROUTER thread. Callback is expected to
# be cheap and non-blocking (e.g. enqueue onto an asyncio queue).
if was_auto_assigned and self._on_register is not None:
try:
self._on_register(stage_id, replica_id, alloc)
except Exception:
logger.exception(
"[OmniMasterServer] on_register callback failed for stage=%d replica=%d",
stage_id,
replica_id,
)
alloc = self._stage_routes[key]
response = msgspec.msgpack.encode(
{
"handshake_address": alloc.handshake_connect_address,
"input_address": alloc.input_bind_address,
"output_address": alloc.output_bind_address,
"replica_id": replica_id,
"coordinator_router_address": self._coordinator_router_address,
}
)
# ROUTER-DEALER: reply is [identity, payload] (no empty delimiter).
reg_socket.send_multipart([identity, response])
logger.info(
"[OmniMasterServer] Stage %d replica %d registered; assigned handshake=%s",
"[OmniMasterServer] Stage %d replica %d registered (auto=%s); handshake=%s",
stage_id,
replica_id,
was_auto_assigned,
alloc.handshake_connect_address,
)
return key
return (stage_id, replica_id)
@dataclass(frozen=True)
class StageRegistrationResponse:
"""Reply payload returned by :class:`OmniMasterServer` after a successful registration."""
handshake_address: str
input_address: str
output_address: str
replica_id: int
coordinator_router_address: str | None
def _detect_local_bind_address(master_address: str, master_port: int) -> str:
"""Return the local IP the kernel would use to reach the master.
Uses a connected UDP socket as a routing-table probe: ``connect()`` on
SOCK_DGRAM sends no packets but forces a route lookup, after which
``getsockname()[0]`` exposes the source IP that an outbound packet to
``(master_address, master_port)`` would carry. For a co-located master
this returns the loopback or eth0 IP (same effect as the legacy
``self._address`` behaviour); for a remote master it returns the
NIC IP that's actually reachable from the master — which is exactly
the address the headless's per-stage ZMQ sockets must bind on.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((master_address, master_port))
return s.getsockname()[0]
finally:
s.close()
def register_stage_with_omni_master(
@@ -367,23 +621,37 @@ def register_stage_with_omni_master(
omni_stage_config: Any = None,
coordinator: DPCoordinator | None = None,
return_addresses: bool = False,
replica_id: int = 0,
) -> str | tuple[str, str, str]:
replica_id: int | None = 0,
return_full_response: bool = False,
replica_bind_address: str | None = None,
replica_binds_sockets: bool = True,
) -> str | tuple[str, str, str] | StageRegistrationResponse:
"""Register a stage with the omni master server.
Returns the per-stage handshake address by default. When
``return_addresses`` is true, also returns the stage input/output
addresses allocated by the master.
addresses allocated by the master. When ``return_full_response`` is
true, returns the full :class:`StageRegistrationResponse` including the
assigned ``replica_id`` and the OmniCoordinator ROUTER address (if
published by the master).
Pass ``replica_id=None`` to request auto-assignment of a free replica
id by the master (used by headless launchers).
"""
if replica_id is None:
wire_replica_id = AUTO_ASSIGN_REPLICA_ID
else:
wire_replica_id = int(replica_id)
reg_ctx = zmq.Context()
try:
reg_sock: zmq.Socket = reg_ctx.socket(zmq.DEALER) # type: ignore[attr-defined]
try:
reg_sock.connect(f"tcp://{omni_master_address}:{omni_master_port}")
payload = {
payload: dict[str, Any] = {
"stage_id": omni_stage_id,
"replica_id": replica_id,
"replica_id": wire_replica_id,
"stage_config": _serialize_stage_config(omni_stage_config),
}
if coordinator is not None:
@@ -392,6 +660,31 @@ def register_stage_with_omni_master(
payload["coordinator_output"] = coordinator_output
payload["frontend_stats_publish_address"] = coordinator.get_stats_publish_address()
# Always advertise THIS host's local bind address + 3 locally
# free ports so the master can root the per-stage socket
# allocation on the replica's own interface. For a co-located
# replica the detected IP matches the master's address and
# the override is a no-op semantically; for a cross-host
# replica it's what makes the headless's ROUTER bind succeed
# (otherwise the master would hand back ``tcp://<master_ip>:port``
# and ``zmq.bind`` would EADDRNOTAVAIL on the remote host).
if replica_bind_address is None:
replica_bind_address = _detect_local_bind_address(omni_master_address, omni_master_port)
hs_port, inp_port, out_port = get_open_ports_list(count=3)
payload["replica_bind_address"] = replica_bind_address
payload["replica_handshake_port"] = hs_port
payload["replica_input_port"] = inp_port
payload["replica_output_port"] = out_port
# ``False`` only for LLM headless replicas: the head's
# ``connect_remote_engine_cores`` is the binder for the
# handshake ROUTER, and ``CoreClient.__init__`` binds the
# input ROUTER and the output PULL (``make_zmq_socket``
# defaults bind=True for PULL). The master must keep all
# three addresses on the master's host so the head can
# ``bind`` them; the remote LLM worker TCP-connects across
# hosts on all three.
payload["replica_binds_sockets"] = bool(replica_binds_sockets)
reg_sock.send(msgspec.msgpack.encode(payload))
timeout_ms = _DEFAULT_STARTUP_TIMEOUT_S * 1_000
if not reg_sock.poll(timeout=timeout_ms):
@@ -402,13 +695,16 @@ def register_stage_with_omni_master(
f"for stage {omni_stage_id}."
)
response_bytes = reg_sock.recv()
response = msgspec.msgpack.decode(response_bytes)
handshake_address: str = response["handshake_address"]
input_address: str = response["input_address"]
output_address: str = response["output_address"]
response_msg = msgspec.msgpack.decode(response_bytes)
handshake_address: str = response_msg["handshake_address"]
input_address: str = response_msg["input_address"]
output_address: str = response_msg["output_address"]
assigned_replica_id: int = int(response_msg.get("replica_id", wire_replica_id))
coord_router_addr: str | None = response_msg.get("coordinator_router_address")
logger.info(
"Stage %d registered; handshake_address=%s",
"Stage %d replica %d registered; handshake_address=%s",
omni_stage_id,
assigned_replica_id,
handshake_address,
)
finally:
@@ -416,6 +712,14 @@ def register_stage_with_omni_master(
finally:
reg_ctx.term()
if return_full_response:
return StageRegistrationResponse(
handshake_address=handshake_address,
input_address=input_address,
output_address=output_address,
replica_id=assigned_replica_id,
coordinator_router_address=coord_router_addr,
)
if return_addresses:
return handshake_address, input_address, output_address
return handshake_address
@@ -543,8 +847,16 @@ def launch_omni_core_engines(
stage_id: int,
stage_config: Any = None,
replica_id: int = 0,
*,
omni_coordinator_address: str | None = None,
) -> Iterator[tuple[CoreEngineProcManager, DPCoordinator | None, EngineZmqAddresses]]:
"""Launch local engine cores using the omni registration flow."""
"""Launch local engine cores using the omni registration flow.
When ``omni_coordinator_address`` is provided, the spawned engine
subprocesses use :class:`OmniCoreEngineProcManager` and each
instantiates an :class:`OmniCoordClientForStage` after the handshake
completes so the head's :class:`OmniCoordinator` knows about them.
"""
addresses = omni_master_server.get_zmq_addresses(stage_id, replica_id=replica_id)
parallel_config = vllm_config.parallel_config
# Determine the number of local engines and their ranks.
@@ -608,16 +920,35 @@ def launch_omni_core_engines(
handshake_bind_address = omni_master_server.get_allocation(stage_id, replica_id=replica_id).handshake_bind_address
with zmq_socket_ctx(handshake_bind_address, zmq.ROUTER, bind=True) as handshake_socket:
local_engine_manager = CoreEngineProcManager(
local_engine_count=local_engine_count,
start_index=start_index,
local_start_index=local_start_index,
vllm_config=vllm_config,
local_client=True,
handshake_address=handshake_address,
executor_class=executor_class,
log_stats=log_stats,
)
if omni_coordinator_address is not None:
# Use the omni subclass so each spawned subprocess instantiates
# an OmniCoordClientForStage and heartbeats to the coordinator.
from vllm_omni.engine.omni_core_engine_proc_manager import OmniCoreEngineProcManager
local_engine_manager: CoreEngineProcManager = OmniCoreEngineProcManager(
local_engine_count=local_engine_count,
start_index=start_index,
local_start_index=local_start_index,
vllm_config=vllm_config,
local_client=True,
handshake_address=handshake_address,
executor_class=executor_class,
log_stats=log_stats,
omni_stage_id=stage_id,
omni_coordinator_address=omni_coordinator_address,
omni_replica_base_id=replica_id,
)
else:
local_engine_manager = CoreEngineProcManager(
local_engine_count=local_engine_count,
start_index=start_index,
local_start_index=local_start_index,
vllm_config=vllm_config,
local_client=True,
handshake_address=handshake_address,
executor_class=executor_class,
log_stats=log_stats,
)
yield local_engine_manager, coordinator, addresses
+115 -19
View File
@@ -61,6 +61,63 @@ class LogicalStageInitPlan:
replicas: list[ReplicaInitPlan]
@dataclass
class StageRemoteFactoryContext:
"""Per-stage context cached by AsyncOmniEngine for dynamic replica attach.
Populated once during ``_bootstrap_orchestrator`` from the per-stage
init plans. ``_build_remote_replica`` consumes it to construct the
right head-side stage client when a headless replica registers.
"""
stage_id: int
stage_type: str
stage_cfg: Any
base_metadata: Any
# LLM-only fields:
vllm_config: Any | None = None
executor_class: type | None = None
# Diffusion-only fields:
diffusion_batch_size: int = 1
def capture_stage_factory_contexts(
stage_plans: Sequence[LogicalStageInitPlan],
diffusion_batch_size: int,
) -> dict[int, StageRemoteFactoryContext]:
"""Snapshot per-stage construction context for dynamic replica attach.
Called once after ``_initialize_stages`` finishes. The captured
context holds everything ``_build_remote_replica`` needs to build a
fresh head-side client when a new headless replica registers
(vllm_config / executor_class for LLM, batch_size for diffusion,
plus the base stage metadata).
Per-replica fields like ``replica_id`` are filled in at build time,
not at capture time.
"""
contexts: dict[int, StageRemoteFactoryContext] = {}
for plan in stage_plans:
if not plan.replicas:
# Stage was declared but has zero replicas locally; we still
# want to be able to attach incoming headless ones, so use
# the stage_cfg-derived context if any replica plan exists.
continue
template = plan.replicas[0]
stage_id = int(plan.configured_stage_id)
stage_type = template.metadata.stage_type or "llm"
contexts[stage_id] = StageRemoteFactoryContext(
stage_id=stage_id,
stage_type=stage_type,
stage_cfg=template.stage_cfg,
base_metadata=template.metadata,
vllm_config=template.stage_vllm_config,
executor_class=template.executor_class,
diffusion_batch_size=diffusion_batch_size,
)
return contexts
def _resolve_model_to_local_path(model: str) -> str:
"""Resolve an HF Hub model ID to a local cache path."""
if os.path.isdir(model):
@@ -420,32 +477,59 @@ def split_devices_for_replicas(
"""Split a devices string into per-replica subsets.
When ``num_replicas`` is 1, returns ``[devices_str]`` unchanged.
Otherwise, the total number of device IDs must equal
``num_replicas * tp_size``; each replica gets ``tp_size`` consecutive
device IDs.
Otherwise, two YAML shapes are accepted:
Example::
1. **Legacy / pool mode** — ``len(devices) == num_replicas * tp_size``:
the string enumerates the full per-stage pool. Each replica gets
``tp_size`` consecutive entries. The values are logical indices
into the launcher's ``CUDA_VISIBLE_DEVICES``.
split_devices_for_replicas("1,2,3,4", num_replicas=2, tp_size=2, stage_id=1)
# → ["1,2", "3,4"]
``split_devices_for_replicas("1,2,3,4", 2, 2, 1) → ["1,2", "3,4"]``
2. **Template mode** — ``len(devices) == tp_size``: the YAML declares
a single per-replica template (the same shape one replica would
use), and is **dp-independent**. Each replica r gets the offsets
``[r*tp_size + a for a in template]`` of the launcher's
``CUDA_VISIBLE_DEVICES``. The template's entries must lie in
``[0, tp_size)``.
``split_devices_for_replicas("0,1", 2, 2, 1) → ["0,1", "2,3"]``
``split_devices_for_replicas("0,1", 4, 2, 1) → ["0,1", "2,3", "4,5", "6,7"]``
This lets the same ``devices: "0,1"`` YAML work for any
``--omni-dp-size-local``: the launcher's CVD scales, the YAML
does not.
Any other length raises ``ValueError`` (the two modes are
length-disjoint for ``num_replicas > 1``).
"""
if num_replicas <= 1 or devices_str is None:
return [devices_str] if devices_str is not None else [devices_str]
device_list = [d.strip() for d in devices_str.split(",") if d.strip()]
required = num_replicas * tp_size
if len(device_list) != required:
raise ValueError(
f"Stage {stage_id}: num_replicas={num_replicas}, "
f"tensor_parallel_size={tp_size} requires "
f"{required} devices, got {len(device_list)}: {devices_str}"
)
result: list[str] = []
for r in range(num_replicas):
chunk = device_list[r * tp_size : (r + 1) * tp_size]
result.append(",".join(chunk))
return result
if len(device_list) == num_replicas * tp_size:
return [",".join(device_list[r * tp_size : (r + 1) * tp_size]) for r in range(num_replicas)]
if len(device_list) == tp_size:
try:
offsets = [int(a) for a in device_list]
except ValueError as e:
raise ValueError(f"Stage {stage_id}: template-mode devices must be ints, got {devices_str!r}") from e
bad = [a for a in offsets if not (0 <= a < tp_size)]
if bad:
raise ValueError(
f"Stage {stage_id}: template-mode device offset(s) {bad} "
f"out of range [0, {tp_size}); devices={devices_str!r}"
)
return [",".join(str(r * tp_size + a) for a in offsets) for r in range(num_replicas)]
raise ValueError(
f"Stage {stage_id}: devices={devices_str!r} has {len(device_list)} id(s); "
f"need either {tp_size} (template, dp-independent) or "
f"{num_replicas * tp_size} (pool / legacy). "
f"num_replicas={num_replicas}, tensor_parallel_size={tp_size}."
)
def get_stage_tp_size(stage_cfg: Any) -> int:
@@ -479,9 +563,19 @@ def get_stage_devices_per_replica(stage_cfg: Any) -> int:
def compute_replica_layout(
stage_configs: Sequence[Any],
*,
allow_zero: bool = False,
) -> tuple[list[int], dict[int, list[str]]]:
"""Compute per-stage replica counts and device assignments.
Args:
stage_configs: per-stage config objects with a ``runtime`` sub-config
exposing ``num_replicas`` and ``devices``.
allow_zero: when True, ``num_replicas == 0`` is honored (used by
single-stage / head-distributed mode for non-self stages that
will be filled dynamically by remote registrations); when False
(default), the count is clamped to at least 1.
Returns:
replicas_per_stage: num_replicas per logical stage.
replica_devices_map: stage_idx -> per-replica device strings
@@ -495,7 +589,9 @@ def compute_replica_layout(
if hasattr(runtime_cfg, "get")
else getattr(runtime_cfg, "num_replicas", 1)
)
replicas_per_stage.append(max(1, num_replicas))
if num_replicas < 0:
raise ValueError(f"num_replicas must be >= 0, got {num_replicas}")
replicas_per_stage.append(num_replicas if allow_zero else max(1, num_replicas))
replica_devices_map: dict[int, list[str]] = {}
for stage_id, stage_cfg in enumerate(stage_configs):
+400 -32
View File
@@ -10,6 +10,13 @@ from typing import TYPE_CHECKING, Any, cast
from vllm.logger import init_logger
from vllm.v1.engine import EngineCoreOutputs
from vllm_omni.distributed.omni_coordinator import (
LoadBalancer,
OmniCoordClientForHub,
ReplicaInfo,
ReplicaStatus,
)
from vllm_omni.distributed.omni_coordinator.load_balancer import Task
from vllm_omni.engine.stage_client import (
StagePoolClient,
StagePoolDiffusionClient,
@@ -35,7 +42,33 @@ class _ReplicaMetrics:
class StagePool:
"""Replicas of one logical stage with RR + affinity selection."""
"""Replicas of one logical stage + per-stage routing (LB + affinity).
The pool owns the head-side stage clients for one logical stage. It also
absorbs the per-stage dispatch responsibility (load balancing, affinity
tracking, bounded-wait pick) that used to live in a separate
``StageDispatcher`` class — see the design doc for the rationale.
In distributed mode (when an :class:`OmniCoordClientForHub` and a
:class:`LoadBalancer` are injected via :meth:`attach_hub` /
:meth:`attach_load_balancer`), :meth:`pick` consults the hub's cached
replica list and routes via the load balancer, sticking subsequent calls
for the same ``request_id`` to the same replica.
In non-distributed mode (no hub attached), :meth:`pick` falls back to the
legacy ``select_replica_id`` round-robin path so the multi-stage
in-process invocation is unchanged.
Dynamic replica membership: when a remote replica is added or removed
(driven by :class:`Orchestrator` via :meth:`add_client` /
:meth:`remove_client`), the pool keeps stable integer ``replica_id``s by
storing clients in a list whose entries can be ``None`` after a removal.
Iteration callers should use :meth:`live_replica_ids` rather than
``range(pool.num_replicas)`` to skip the gaps.
"""
DISPATCH_WAIT_TIMEOUT_S: float = 10.0
DISPATCH_RETRY_INTERVAL_S: float = 0.1
def __init__(
self,
@@ -50,33 +83,69 @@ class StagePool:
else:
normalized_clients = [clients]
if not normalized_clients:
raise ValueError(f"StagePool for stage {stage_id} has no replicas")
# Allow empty pools when running in distributed head mode for a
# non-self stage; clients will arrive via add_client(...).
self.stage_id = stage_id
self.clients: list[StagePoolClient] = normalized_clients
# Slots can become None after a dynamic remove_client (distributed mode);
# iterate via live_replica_ids() to skip holes.
self.clients: list[StagePoolClient | None] = list(normalized_clients)
self._output_processor = output_processor
self._stage_vllm_config = stage_vllm_config
self._next_replica_id = 0
self._request_bindings: dict[str, int] = {}
self._replica_metrics: list[_ReplicaMetrics] = [_ReplicaMetrics() for _ in self.clients]
# Distributed-mode state. Populated by add_client / remove_client.
self._addr_to_replica_id: dict[str, int] = {}
for replica_id, client in enumerate(self.clients):
if client is not None:
addr = self._client_input_addr(client)
if addr is not None:
self._addr_to_replica_id[addr] = replica_id
# Distributed-mode dispatch hooks (injected by Orchestrator on bring-up).
self._hub: OmniCoordClientForHub | None = None
self._lb: LoadBalancer | None = None
# ``request_id`` → ``input_addr`` affinity (distributed mode only).
# Kept separate from the legacy ``_request_bindings`` so the two
# binding shapes do not collide.
self._affinity: dict[str, str] = {}
# ---- Stage-level properties ----
@property
def num_replicas(self) -> int:
"""Total slot count, including ``None`` holes from removed replicas.
Use :meth:`live_replica_ids` to iterate only live entries.
"""
return len(self.clients)
@property
def live_num_replicas(self) -> int:
"""Number of currently live (non-None) replicas in this pool."""
return sum(1 for c in self.clients if c is not None)
def live_replica_ids(self) -> list[int]:
"""Return the indices of currently live replicas in this pool."""
return [i for i, c in enumerate(self.clients) if c is not None]
@property
def stage_type(self) -> str | None:
return self.stage_client.stage_type
client = self.stage_client
return None if client is None else client.stage_type
@property
def final_output(self) -> bool:
return self.clients[0].final_output
client = self.stage_client
return False if client is None else bool(client.final_output)
@property
def stage_client(self) -> StagePoolClient:
return self.clients[0]
def stage_client(self) -> StagePoolClient | None:
for client in self.clients:
if client is not None:
return client
return None
@property
def llm_stage_client(self) -> StagePoolLLMClient:
@@ -90,11 +159,254 @@ class StagePool:
def output_processor(self) -> Any:
return self._output_processor
# ---- Route binding lifecycle ----
@property
def is_distributed(self) -> bool:
"""True iff a hub has been attached (i.e. running in head-distributed mode)."""
return self._hub is not None
# ---- Distributed-mode dispatch hooks ----
def attach_hub(self, hub: OmniCoordClientForHub | None) -> None:
"""Inject the shared :class:`OmniCoordClientForHub`.
Called once by :class:`Orchestrator` after the hub is constructed.
``hub=None`` keeps the pool in legacy mode (no behavior change).
"""
self._hub = hub
def attach_load_balancer(self, lb: LoadBalancer | None) -> None:
"""Inject the per-pool :class:`LoadBalancer` for distributed-mode pick."""
self._lb = lb
# ---- Dynamic membership (distributed mode) ----
@staticmethod
def _client_input_addr(client: Any) -> str | None:
"""Return the input ZMQ address advertised by ``client`` if any.
LLM clients expose ``client_addresses["input_address"]``; diffusion
clients expose ``request_address``. Both are stable strings used by
:class:`OmniCoordinator` to key replicas.
"""
request_address = getattr(client, "request_address", None)
if isinstance(request_address, str) and request_address:
return request_address
addrs = getattr(client, "client_addresses", None)
if isinstance(addrs, dict):
addr = addrs.get("input_address")
if isinstance(addr, str) and addr:
return addr
return None
def add_client(self, input_addr: str, client: Any) -> int:
"""Register a head-side client for ``input_addr``.
Returns the assigned ``replica_id`` (index into :attr:`clients`).
If the address is already known, replaces the existing client and
returns its existing id (this should not happen in practice — the
master server assigns unique slots — but the contract is idempotent
to keep the dispatch layer robust).
"""
if not input_addr:
raise ValueError("input_addr must be a non-empty string")
existing = self._addr_to_replica_id.get(input_addr)
if existing is not None:
self.clients[existing] = client
return existing
replica_id = len(self.clients)
self.clients.append(client)
self._addr_to_replica_id[input_addr] = replica_id
self._replica_metrics.append(_ReplicaMetrics())
return replica_id
def remove_client(self, input_addr: str) -> Any | None:
"""Remove the client at ``input_addr``. Returns the removed client or ``None``.
Slot is marked ``None`` to preserve indices for outstanding bindings.
"""
replica_id = self._addr_to_replica_id.pop(input_addr, None)
if replica_id is None:
return None
client = self.clients[replica_id]
self.clients[replica_id] = None
return client
def get_client_by_addr(self, input_addr: str) -> Any | None:
"""Return the live client for ``input_addr`` if present."""
replica_id = self._addr_to_replica_id.get(input_addr)
if replica_id is None:
return None
return self.clients[replica_id]
def get_replica_id_by_addr(self, input_addr: str) -> int | None:
"""Return the stable replica_id for ``input_addr`` if registered."""
return self._addr_to_replica_id.get(input_addr)
# ---- Per-request distributed dispatch ----
async def pick(
self,
request_id: str,
task: Task | None = None,
*,
affinity_request_id: str | None = None,
) -> int:
"""Return a replica id for ``request_id``.
In distributed mode: consults the hub for UP replicas, runs the load
balancer, and records affinity so future picks for the same
``request_id`` return the same replica. Bounded wait up to
``DISPATCH_WAIT_TIMEOUT_S`` when no UP replica is currently usable.
In non-distributed (legacy) mode: delegates to
:meth:`select_replica_id`.
"""
if self._hub is None or self._lb is None:
return self.select_replica_id(request_id, affinity_request_id=affinity_request_id)
# 1. Sticky: previously bound and still serviceable?
bound_addr = self._affinity.get(request_id)
if bound_addr is not None:
replica_id = self._serviceable_replica_id_for_addr(bound_addr)
if replica_id is not None:
return replica_id
# Bound replica is gone or DOWN — fall through to re-select.
self._affinity.pop(request_id, None)
# 2. Inherited affinity (CFG companion sharing a parent request_id).
if affinity_request_id is not None:
parent_addr = self._affinity.get(affinity_request_id)
if parent_addr is not None:
replica_id = self._serviceable_replica_id_for_addr(parent_addr)
if replica_id is not None:
self._affinity[request_id] = parent_addr
return replica_id
# 3. Fresh pick: poll hub + LB with bounded wait.
task = task or Task(request_id=request_id)
deadline = _time.monotonic() + self.DISPATCH_WAIT_TIMEOUT_S
while True:
candidates = self._collect_serviceable_replicas()
if candidates:
# LB chose an index *into our candidates list*.
lb_idx = self._lb.select(task, [rep for rep, _ in candidates])
replica_info, replica_id = candidates[lb_idx]
self._affinity[request_id] = replica_info.input_addr
return replica_id
now = _time.monotonic()
if now >= deadline:
raise RuntimeError(f"no UP replica for stage {self.stage_id} after {self.DISPATCH_WAIT_TIMEOUT_S:.1f}s")
await asyncio.sleep(min(self.DISPATCH_RETRY_INTERVAL_S, deadline - now))
def preselect_replica_id(
self,
request_id: str,
task: Task | None = None,
*,
affinity_request_id: str | None = None,
) -> int | None:
"""Synchronously pick and bind a replica before request preprocessing.
The main-thread input preprocessing path cannot await :meth:`pick`, but
multimodal cache UUID scoping needs to know the same replica that
:meth:`submit_initial` will later use. In distributed mode this checks
the hub's cached replica snapshot once and records the selected input
address in ``_affinity`` so the async submit path reuses the route. If
no replica is currently serviceable, return ``None`` and let the async
submit-time router wait without blocking the caller.
"""
if self._hub is None or self._lb is None:
return self.select_replica_id(request_id, affinity_request_id=affinity_request_id)
bound_addr = self._affinity.get(request_id)
if bound_addr is not None:
replica_id = self._serviceable_replica_id_for_addr(bound_addr)
if replica_id is not None:
return replica_id
self._affinity.pop(request_id, None)
if affinity_request_id is not None:
parent_addr = self._affinity.get(affinity_request_id)
if parent_addr is not None:
replica_id = self._serviceable_replica_id_for_addr(parent_addr)
if replica_id is not None:
self._affinity[request_id] = parent_addr
return replica_id
task = task or Task(request_id=request_id)
candidates = self._collect_serviceable_replicas()
if not candidates:
return None
lb_idx = self._lb.select(task, [rep for rep, _ in candidates])
replica_info, replica_id = candidates[lb_idx]
self._affinity[request_id] = replica_info.input_addr
return replica_id
def _collect_serviceable_replicas(self) -> list[tuple[ReplicaInfo, int]]:
"""Return list of ``(ReplicaInfo, replica_id)`` for UP, attached replicas."""
if self._hub is None:
return []
snap = self._hub.get_replicas_for_stage(self.stage_id)
out: list[tuple[ReplicaInfo, int]] = []
for rep in snap.replicas:
if rep.status != ReplicaStatus.UP:
continue
replica_id = self._addr_to_replica_id.get(rep.input_addr)
if replica_id is None:
continue # Hub knows about it but head-side client not attached yet.
if self.clients[replica_id] is None:
continue
out.append((rep, replica_id))
return out
def _serviceable_replica_id_for_addr(self, input_addr: str) -> int | None:
"""Return ``replica_id`` for ``input_addr`` iff currently UP + attached."""
if self._hub is None:
return None
replica_id = self._addr_to_replica_id.get(input_addr)
if replica_id is None or self.clients[replica_id] is None:
return None
snap = self._hub.get_replicas_for_stage(self.stage_id)
for rep in snap.replicas:
if rep.input_addr == input_addr and rep.status == ReplicaStatus.UP:
return replica_id
return None
def bind(self, request_id: str, input_addr: str) -> None:
"""Explicitly record affinity (distributed mode)."""
self._affinity[request_id] = input_addr
def release(self, request_id: str) -> None:
"""Drop affinity (distributed mode) and legacy binding for ``request_id``."""
self._affinity.pop(request_id, None)
self.release_binding(request_id)
def invalidate_addr(self, input_addr: str) -> list[str]:
"""Drop affinity rows pointing at ``input_addr``; return affected request ids."""
affected: list[str] = [rid for rid, addr in self._affinity.items() if addr == input_addr]
for rid in affected:
self._affinity.pop(rid, None)
return affected
# ---- Legacy (non-distributed) route binding ----
def get_bound_replica_id(self, request_id: str) -> int | None:
"""Return the currently bound replica id for *request_id* if present."""
return self._request_bindings.get(request_id)
"""Return the currently bound replica id for *request_id* if present.
In distributed mode the binding may have been recorded via
:meth:`pick`; we honor it transparently here.
"""
legacy = self._request_bindings.get(request_id)
if legacy is not None:
return legacy
addr = self._affinity.get(request_id)
if addr is None:
return None
return self._addr_to_replica_id.get(addr)
def get_bound_client(self, request_id: str) -> StagePoolClient | None:
"""Return the currently bound client for *request_id* if present."""
@@ -113,6 +425,7 @@ class StagePool:
def release_binding(self, request_id: str) -> None:
"""Drop the route binding for *request_id* in this stage."""
self._request_bindings.pop(request_id, None)
self._affinity.pop(request_id, None)
def release_bindings(self, request_ids: list[str]) -> None:
"""Drop route bindings for the given request ids in this stage."""
@@ -125,27 +438,43 @@ class StagePool:
*,
affinity_request_id: str | None = None,
) -> int:
"""Pick a replica id for *request_id* and cache the choice."""
"""Pick a replica id for *request_id* and cache the choice (legacy path)."""
cached = self.get_bound_replica_id(request_id)
if cached is not None:
if cached is not None and self.clients[cached] is not None:
return cached
chosen = self.get_bound_replica_id(affinity_request_id) if affinity_request_id is not None else None
chosen: int | None = None
if affinity_request_id is not None:
parent = self.get_bound_replica_id(affinity_request_id)
if parent is not None and self.clients[parent] is not None:
chosen = parent
if chosen is None:
if self.num_replicas == 1:
chosen = 0
live = self.live_replica_ids()
if not live:
raise RuntimeError(f"stage {self.stage_id} has no live replicas")
if len(live) == 1:
chosen = live[0]
else:
chosen = self._next_replica_id
self._next_replica_id = (self._next_replica_id + 1) % self.num_replicas
# Round-robin over live replicas only.
start = self._next_replica_id % len(live)
chosen = live[start]
self._next_replica_id = (self._next_replica_id + 1) % len(live)
self._request_bindings[request_id] = chosen
return chosen
def _llm_client(self, replica_id: int) -> StagePoolLLMClient:
return cast(StagePoolLLMClient, self.clients[replica_id])
client = self.clients[replica_id]
if client is None:
raise RuntimeError(f"stage {self.stage_id} replica {replica_id} is not attached")
return cast(StagePoolLLMClient, client)
def _diffusion_client(self, replica_id: int) -> StagePoolDiffusionClient:
return cast(StagePoolDiffusionClient, self.clients[replica_id])
client = self.clients[replica_id]
if client is None:
raise RuntimeError(f"stage {self.stage_id} replica {replica_id} is not attached")
return cast(StagePoolDiffusionClient, client)
# ---- Metrics ----
@@ -206,7 +535,7 @@ class StagePool:
params = params_override if params_override is not None else req_state.sampling_params_list[self.stage_id]
submit_kwargs = dict(submit_kwargs or {})
if self.stage_type == "diffusion":
replica_id = self.select_replica_id(
replica_id = await self._pick_or_select(
request_id,
affinity_request_id=affinity_request_id,
)
@@ -217,10 +546,13 @@ class StagePool:
await client.add_request_async(request_id, request, params, **submit_kwargs)
return replica_id
replica_id = self.select_replica_id(
replica_id = await self._pick_or_select(
request_id,
affinity_request_id=affinity_request_id,
)
client = self.clients[replica_id]
if client is None:
raise RuntimeError(f"stage {self.stage_id} replica {replica_id} is not attached")
try:
self.output_processor.add_request(
request=request,
@@ -262,8 +594,12 @@ class StagePool:
"""Submit a streaming update to an already admitted request."""
params = req_state.sampling_params_list[self.stage_id]
replica_id = self.get_bound_replica_id(request_id)
if replica_id is None:
replica_id = self.select_replica_id(request_id)
if replica_id is None or self.clients[replica_id] is None:
replica_id = await self._pick_or_select(request_id)
client = self.clients[replica_id]
if client is None:
raise RuntimeError(f"stage {self.stage_id} replica {replica_id} is not attached")
if self.stage_type == "diffusion":
await self._diffusion_client(replica_id).add_request_async(request_id, request, params)
@@ -281,6 +617,17 @@ class StagePool:
await self._llm_client(replica_id).add_request_async(request)
return replica_id
async def _pick_or_select(
self,
request_id: str,
*,
affinity_request_id: str | None = None,
) -> int:
"""Bridge to ``pick`` in distributed mode or ``select_replica_id`` legacy."""
if self.is_distributed:
return await self.pick(request_id, affinity_request_id=affinity_request_id)
return self.select_replica_id(request_id, affinity_request_id=affinity_request_id)
# ---- Stage-local polling ----
async def _poll_stage_raw(self, client: StagePoolLLMClient) -> EngineCoreOutputs | None:
@@ -296,7 +643,10 @@ class StagePool:
raw_outputs: EngineCoreOutputs,
) -> list[Any]:
"""Run the shared LLM output processor on one raw poll result."""
client = self._llm_client(replica_id)
raw_client = self.clients[replica_id]
if raw_client is None:
return []
client = cast(StagePoolLLMClient, raw_client)
processor = self.output_processor
processed = processor.process_outputs(
raw_outputs.outputs,
@@ -319,7 +669,10 @@ class StagePool:
timeout_s: float = 0.001,
) -> EngineCoreOutputs | None:
"""Poll raw EngineCore outputs from one LLM replica once."""
client = self._llm_client(replica_id)
raw_client = self.clients[replica_id]
if raw_client is None:
return None
client = cast(StagePoolLLMClient, raw_client)
try:
return await asyncio.wait_for(
self._poll_stage_raw(client),
@@ -339,7 +692,10 @@ class StagePool:
def poll_diffusion_output(self, replica_id: int) -> Any | None:
"""Drain one ready diffusion output from the given replica if present."""
return self._diffusion_client(replica_id).get_diffusion_output_nowait()
raw_client = self.clients[replica_id]
if raw_client is None:
return None
return cast(StagePoolDiffusionClient, raw_client).get_diffusion_output_nowait()
# ---- Stage-local control plane ----
@@ -347,7 +703,7 @@ class StagePool:
"""Abort the given requests in this stage pool.
Request-bound abort routing stays inside the pool because route affinity
(`request_id -> replica_id`) is pool-owned.
(``request_id -> replica_id``) is pool-owned.
"""
if not request_ids:
return
@@ -355,13 +711,16 @@ class StagePool:
request_ids_by_replica: dict[int, list[str]] = {}
for request_id in request_ids:
replica_id = self.get_bound_replica_id(request_id)
if replica_id is None:
logger.debug("[StagePool] abort: no binding for req=%s in stage-%s", request_id, self.stage_id)
if replica_id is None or self.clients[replica_id] is None:
logger.debug("[StagePool] abort: no live binding for req=%s in stage-%s", request_id, self.stage_id)
continue
request_ids_by_replica.setdefault(replica_id, []).append(request_id)
for replica_id, replica_request_ids in request_ids_by_replica.items():
await self.clients[replica_id].abort_requests_async(replica_request_ids)
client = self.clients[replica_id]
if client is None:
continue
await client.abort_requests_async(replica_request_ids)
# Clean up OutputProcessor state (e.g. mm_accumulated tensors) that
# would otherwise leak — aborted requests never produce a final
@@ -377,10 +736,15 @@ class StagePool:
timeout: float | None = None,
args: tuple[Any, ...] = (),
kwargs: dict[str, Any] | None = None,
) -> Any:
) -> dict[str, Any] | Any:
"""Dispatch a stage-scoped control-plane RPC to one physical route."""
kwargs = dict(kwargs or {})
client = self.clients[replica_id]
if client is None:
return {
"supported": False,
"error": f"stage {self.stage_id} replica {replica_id} is not attached",
}
try:
return await client.collective_rpc_async(
method=method,
@@ -402,7 +766,11 @@ class StagePool:
def shutdown_replica(self, replica_id: int) -> None:
"""Shutdown one backend handle in this stage pool."""
if replica_id >= len(self.clients):
return
client = self.clients[replica_id]
if client is None:
return
try:
client.shutdown()
logger.info(
+368 -68
View File
@@ -9,6 +9,8 @@ import argparse
import json
import os
import signal
import threading
from multiprocessing import connection
from types import FrameType
from typing import Any
@@ -103,6 +105,62 @@ class OmniServeCommand(CLISubcommand):
if args.stage_id is not None and (args.omni_master_address is None or args.omni_master_port is None):
raise ValueError("--stage-id requires both --omni-master-address and --omni-master-port to be set")
# --omni-replica-address is only consulted in run_headless(); reject it
# on the head so a misconfigured launch fails loudly instead of being
# silently ignored.
if getattr(args, "omni_replica_address", None) is not None and not args.headless:
raise ValueError("--omni-replica-address requires --headless to be set")
# --omni-dp-size-local is process-local. A value other than 1 only
# makes sense when this process owns a stage (head or headless).
omni_dp_size_local = getattr(args, "omni_dp_size_local", None)
if omni_dp_size_local is not None:
if omni_dp_size_local < 1:
raise ValueError(f"--omni-dp-size-local must be >= 1, got {omni_dp_size_local}")
if omni_dp_size_local != 1 and args.stage_id is None:
raise ValueError("--omni-dp-size-local != 1 requires --stage-id to be set")
# vLLM CLI args that omni does not honor: parallelism comes from the
# per-stage YAML (parallel_config:, enable_expert_parallel:) and the
# process-local replica count from --omni-dp-size-local. Passing the
# vLLM equivalents on the command line would silently disagree with
# those sources of truth, so reject them at parse time.
if getattr(args, "omni", False):
explicit_cli_keys: set[str] = getattr(args, "_cli_explicit_keys", set()) or set()
prohibited_with_omni: dict[str, str] = {
"data_parallel_size": "--data-parallel-size",
"data_parallel_size_local": "--data-parallel-size-local",
"data_parallel_address": "--data-parallel-address",
"data_parallel_rpc_port": "--data-parallel-rpc-port",
"data_parallel_start_rank": "--data-parallel-start-rank",
"data_parallel_backend": "--data-parallel-backend",
"api_server_count": "--api-server-count",
"enable_expert_parallel": "--enable-expert-parallel",
}
offenders = sorted(flag for dest, flag in prohibited_with_omni.items() if dest in explicit_cli_keys)
if offenders:
raise ValueError(
"The following CLI args are not supported under --omni: "
f"{', '.join(offenders)}. Configure parallelism through the "
"per-stage YAML (`--deploy-config` / `--stage-configs-path`) "
"and replica count via `--omni-dp-size-local`."
)
# --omni-lb-policy is validated against the LoadBalancingPolicy enum.
omni_lb_policy = getattr(args, "omni_lb_policy", None)
if omni_lb_policy is not None:
from vllm_omni.distributed.omni_coordinator import LoadBalancingPolicy
try:
LoadBalancingPolicy(omni_lb_policy)
except ValueError as exc:
valid = ", ".join(p.value for p in LoadBalancingPolicy)
raise ValueError(f"--omni-lb-policy={omni_lb_policy!r} is not one of: {valid}") from exc
omni_heartbeat_timeout = getattr(args, "omni_heartbeat_timeout", None)
if omni_heartbeat_timeout is not None and omni_heartbeat_timeout <= 0:
raise ValueError(f"--omni-heartbeat-timeout must be > 0, got {omni_heartbeat_timeout}")
# Skip validation for diffusion models as they have different requirements
from vllm_omni.diffusion.utils.hf_utils import is_diffusion_model
@@ -190,8 +248,12 @@ class OmniServeCommand(CLISubcommand):
omni_config_group.add_argument(
"--replica-id",
type=int,
default=0,
help="Replica id to register when launching a single headless stage.",
default=None,
help=(
"Deprecated and ignored — replica ids are auto-assigned by the "
"master server. Specifying this flag prints a warning and has "
"no effect."
),
)
omni_config_group.add_argument(
"--stage-init-timeout",
@@ -253,6 +315,50 @@ class OmniServeCommand(CLISubcommand):
type=int,
help="Port of the Omni orchestrator (master).",
)
omni_config_group.add_argument(
"--omni-replica-address",
"-ora",
type=str,
default=None,
help=(
"Local bind address (this host's IP) that the headless stage "
"advertises to the Omni master for its handshake/input/output "
"ZMQ sockets. If unset, auto-detected via a UDP-connect "
"routing probe against --omni-master-address. Override only "
"when the auto-detected IP is wrong (e.g. multi-NIC host "
"where the master is reachable on the wrong interface)."
),
)
omni_config_group.add_argument(
"--omni-dp-size-local",
type=int,
default=1,
help=(
"Number of stage replicas this runtime launches locally for its "
"own --stage-id. Process-local: head and every headless invocation "
"read their own copy; values may differ across invocations. "
"Requires --stage-id to be set when not equal to 1."
),
)
omni_config_group.add_argument(
"--omni-lb-policy",
type=str,
default="random",
choices=["random", "round-robin", "least-queue-length"],
help=(
"Per-stage load-balancing policy used by the head's StagePool to "
"route requests across UP replicas. Only consulted on the head runtime."
),
)
omni_config_group.add_argument(
"--omni-heartbeat-timeout",
type=float,
default=30.0,
help=(
"Seconds before an unreporting replica is marked ERROR in the "
"OmniCoordinator. Only consulted on the head runtime."
),
)
# Diffusion model specific arguments
omni_config_group.add_argument(
@@ -564,9 +670,15 @@ def _create_default_diffusion_stage_cfg(args: argparse.Namespace) -> list[dict[s
def run_headless(args: argparse.Namespace) -> None:
"""Run a single stage in headless mode."""
"""Run a single stage in headless mode.
Honors ``--omni-dp-size-local``: launches that many replicas locally for
``--stage-id``. Each replica registers with the head's OmniMasterServer
(auto-assigned replica id when ``--omni-dp-size-local > 1`` so multiple
headless invocations can coexist) and reports heartbeats to the head's
OmniCoordinator.
"""
from vllm.v1.engine.coordinator import DPCoordinator
from vllm.v1.engine.utils import CoreEngineProcManager
from vllm.v1.executor.multiproc_executor import MultiprocExecutor
from vllm.version import __version__ as VLLM_VERSION
@@ -575,6 +687,7 @@ def run_headless(args: argparse.Namespace) -> None:
spawn_diffusion_proc,
)
from vllm_omni.distributed.omni_connectors.utils.initialization import resolve_omni_kv_config_for_stage
from vllm_omni.engine.omni_core_engine_proc_manager import OmniCoreEngineProcManager
from vllm_omni.engine.stage_engine_startup import register_stage_with_omni_master
from vllm_omni.engine.stage_init_utils import (
build_diffusion_config,
@@ -582,23 +695,40 @@ def run_headless(args: argparse.Namespace) -> None:
build_vllm_config,
extract_stage_metadata,
get_stage_connector_spec,
get_stage_devices_per_replica,
inject_kv_stage_info,
load_omni_transfer_config_for_model,
prepare_engine_environment,
setup_stage_devices,
split_devices_for_replicas,
terminate_alive_proc,
)
from vllm_omni.entrypoints.utils import inject_omni_kv_config, load_and_resolve_stage_configs
from vllm_omni.platforms import current_omni_platform
model = args.model
stage_id: int | None = args.stage_id
replica_id: int = args.replica_id
omni_master_address: str | None = args.omni_master_address
omni_master_port: int | None = args.omni_master_port
omni_replica_address: str | None = getattr(args, "omni_replica_address", None)
omni_dp_size_local: int = max(1, int(getattr(args, "omni_dp_size_local", 1) or 1))
if stage_id is None:
raise ValueError("--stage-id is required in headless mode")
if replica_id < 0:
raise ValueError("--replica-id must be >= 0 in headless mode")
# ``--replica-id`` is deprecated and ignored — replica ids are
# auto-assigned by ``OmniMasterServer`` so headless processes carry
# no knowledge of their per-replica id at launch time. Warn (don't
# error) when the operator still supplies it so existing launchers
# keep working with a single log line.
explicit_cli_keys: set[str] = getattr(args, "_cli_explicit_keys", set()) or set()
if "replica_id" in explicit_cli_keys:
logger.warning(
"[Headless] --replica-id is deprecated and ignored "
"(supplied value: %s). Replica ids are auto-assigned by the "
"master server.",
args.replica_id,
)
if omni_master_address is None or omni_master_port is None:
raise ValueError("--omni-master-address and --omni-master-port are required in headless mode")
api_server_count = args.api_server_count or 0
@@ -609,6 +739,11 @@ def run_headless(args: argparse.Namespace) -> None:
args_dict = vars(args).copy()
args_dict.pop("_cli_explicit_keys", None)
# Forward ``--deploy-config`` so the headless reads the same YAML the
# head was launched with — otherwise ``load_and_resolve_stage_configs``
# falls back to ``vllm_omni/deploy/<model>.yaml`` and the headless's
# view of ``stage.runtime.devices`` diverges from the head's, breaking
# the per-replica device split.
config_path, stage_configs = load_and_resolve_stage_configs(
model,
args_dict.get("stage_configs_path"),
@@ -631,47 +766,151 @@ def run_headless(args: argparse.Namespace) -> None:
omni_transfer_config = load_omni_transfer_config_for_model(model, config_path)
omni_conn_cfg, omni_from, omni_to = resolve_omni_kv_config_for_stage(omni_transfer_config, stage_id)
# When ``--omni-dp-size-local > 1``, slice the YAML's ``devices:`` field
# into per-replica subsets so each subprocess we spawn below sees a
# narrowed ``CUDA_VISIBLE_DEVICES`` and doesn't stack on cuda:0. Mirrors
# the head-side per-replica device application at
# ``async_omni_engine.py`` (setup_stage_devices around each launch).
runtime_cfg = getattr(stage_cfg, "runtime", None)
devices_str: str | None = None
if runtime_cfg is not None:
devices_str = (
runtime_cfg.get("devices") if hasattr(runtime_cfg, "get") else getattr(runtime_cfg, "devices", None)
)
devices_per_replica = get_stage_devices_per_replica(stage_cfg)
if devices_str:
# Always remap YAML's logical devices through setup_stage_devices,
# even for omni_dp_size_local==1. The launcher's CUDA_VISIBLE_DEVICES
# is dropped from the engine-subprocess env between vllm-serve and
# OmniCoreEngineProcManager.Process, so the worker would otherwise
# default cuda:0 to physical GPU 0 and collide with a co-located
# head on the same host (see hyi3_multi_host_1 reproducer).
per_replica_devices: list[str | None] = split_devices_for_replicas(
devices_str, omni_dp_size_local, devices_per_replica, stage_id
)
logger.info(
"[Headless] Stage %d: %d local replicas, devices_per_replica=%d, per-replica devices: %s",
stage_id,
omni_dp_size_local,
devices_per_replica,
per_replica_devices,
)
else:
per_replica_devices = [None] * omni_dp_size_local
device_control_env = current_omni_platform.device_control_env_var
if stage_cfg.stage_type == "diffusion":
metadata = extract_stage_metadata(stage_cfg)
if omni_conn_cfg:
inject_omni_kv_config(stage_cfg, omni_conn_cfg, omni_from, omni_to)
inject_kv_stage_info(stage_cfg, stage_id)
# Headless single-stage launch must still infer cross-stage TP topology
# from the loaded deploy config so heterogeneous KV routing keys match
# the head process (e.g. from_tp=2, to_tp=1).
inject_kv_stage_info(stage_cfg, stage_id, stage_configs)
od_config = build_diffusion_config(model, stage_cfg, metadata)
logger.info(
"[Headless] Launching diffusion stage %d replica %d via OmniMasterServer at %s:%d",
"[Headless] Launching %d diffusion replica(s) for stage %d via OmniMasterServer at %s:%d",
omni_dp_size_local,
stage_id,
replica_id,
omni_master_address,
omni_master_port,
)
proc = None
procs: list[Any] = []
try:
handshake_address, request_address, response_address = register_stage_with_omni_master(
omni_master_address=omni_master_address,
omni_master_port=omni_master_port,
omni_stage_id=stage_id,
omni_stage_config=stage_cfg,
return_addresses=True,
replica_id=replica_id,
for _rep_idx in range(omni_dp_size_local):
# Always auto-assign: headless processes carry no knowledge
# of their per-replica id and the master server is the sole
# authority on the per-stage id namespace.
response = register_stage_with_omni_master(
omni_master_address=omni_master_address,
omni_master_port=omni_master_port,
omni_stage_id=stage_id,
omni_stage_config=stage_cfg,
replica_id=None,
return_full_response=True,
replica_bind_address=omni_replica_address,
)
# Apply this replica's CUDA_VISIBLE_DEVICES (only when
# ``--omni-dp-size-local > 1`` and the YAML's stage devices
# field is set). The spawned subprocess inherits the env at
# spawn time; we restore the parent env afterwards so the
# next replica's setup sees the same baseline.
previous_visible_devices = os.environ.get(device_control_env)
try:
if per_replica_devices[_rep_idx] is not None:
setup_stage_devices(stage_id, {"devices": per_replica_devices[_rep_idx]})
# Each StageDiffusionProc starts its own
# torch.distributed group bound to
# ``od_config.master_port``. Without an explicit
# per-replica override all spawned subprocesses
# share the value ``OmniDiffusionConfig.__post_init__``
# picked once (and the second binder hits EADDRINUSE
# on ``init_process_group``). We can't use
# kernel-ephemeral allocation either, because the
# master server's pre-allocated ZMQ ports (returned
# by ``register_stage_with_omni_master``) also live
# in the ephemeral range and are not actually bound
# until the headless ``_perform_diffusion_handshake``
# runs — so picking an ephemeral port here can steal
# a port the master server already promised to a
# sibling headless. Use ``settle_port`` from a base
# above the Linux default ephemeral range
# (32768-60999) so torch.distributed master ports
# never overlap with ZMQ allocations.
if omni_dp_size_local > 1:
od_config.master_port = od_config.settle_port(
61000 + _rep_idx * 100,
port_inc=37,
)
proc, _, _, _ = spawn_diffusion_proc(
model,
od_config,
handshake_address=response.handshake_address,
request_address=response.input_address,
response_address=response.output_address,
omni_coordinator_address=response.coordinator_router_address,
omni_stage_id=stage_id,
omni_replica_id=response.replica_id,
)
finally:
if previous_visible_devices is None:
current_omni_platform.unset_device_control_env_var()
else:
current_omni_platform.set_device_control_env_var(previous_visible_devices)
complete_diffusion_handshake(proc, response.handshake_address, args.stage_init_timeout)
procs.append(proc)
logger.info(
"[Headless] Diffusion replica id=%d for stage %d is up (coord=%s)",
response.replica_id,
stage_id,
response.coordinator_router_address,
)
# Block on the sentinel set so any replica crash is detected
# immediately (the previous per-proc join loop only noticed
# crashes in registration order). Any exit triggers fleet
# shutdown via the finally block; non-zero exits propagate.
sentinel_to_proc = {p.sentinel: p for p in procs}
died = connection.wait(list(sentinel_to_proc.keys()))
first = sentinel_to_proc[died[0]]
logger.info(
"[Headless] Diffusion replica %s exited (code=%s); shutting down stage %d.",
first.name,
first.exitcode,
stage_id,
)
proc, _, _, _ = spawn_diffusion_proc(
model,
od_config,
handshake_address=handshake_address,
request_address=request_address,
response_address=response_address,
)
complete_diffusion_handshake(proc, handshake_address, args.stage_init_timeout)
proc.join()
if proc.exitcode not in (None, 0):
raise RuntimeError(f"Diffusion stage {stage_id} replica {replica_id} exited with code {proc.exitcode}")
if first.exitcode not in (None, 0):
raise RuntimeError(
f"Diffusion stage {stage_id} replica {first.name!r} exited with code {first.exitcode}"
)
return
finally:
logger.info("[Headless] Shutting down stage %d replica %d.", stage_id, replica_id)
if proc is not None and proc.is_alive():
terminate_alive_proc(proc)
logger.info("[Headless] Shutting down %d diffusion replica(s) for stage %d.", len(procs), stage_id)
for p in procs:
if p.is_alive():
terminate_alive_proc(p)
stage_connector_spec = get_stage_connector_spec(
omni_transfer_config=omni_transfer_config,
@@ -679,8 +918,10 @@ def run_headless(args: argparse.Namespace) -> None:
async_chunk=False,
)
# Device assignment is managed externally (e.g. CUDA_VISIBLE_DEVICES);
# runtime_cfg is intentionally ignored in headless mode.
# ``runtime_cfg`` is mostly inherited from the parent's
# CUDA_VISIBLE_DEVICES; when ``--omni-dp-size-local > 1`` we additionally
# bracket each replica's spawn below with setup_stage_devices so they
# don't all stack on cuda:0 (see ``per_replica_devices`` above).
engine_args_dict = build_engine_args_dict(
stage_cfg,
model,
@@ -746,57 +987,116 @@ def run_headless(args: argparse.Namespace) -> None:
enable_wave_coordination=vllm_config.model_config.is_moe,
)
logger.info(
"[Headless] Started DP Coordinator process for stage %d replica %d (PID: %d)",
"[Headless] Started DP Coordinator process for stage %d (PID: %d)",
stage_id,
replica_id,
coordinator.proc.pid,
)
logger.info(
"[Headless] Launching %d engine core(s) for stage %d replica %d via OmniMasterServer at %s:%d",
"[Headless] Launching %d omni replica(s) (vLLM dp_size_local=%d each) for stage %d "
"via OmniMasterServer at %s:%d",
omni_dp_size_local,
local_engine_count,
stage_id,
replica_id,
omni_master_address,
omni_master_port,
)
# Headless mode launches all local engine cores for a single stage.
# The OmniMasterServer allocates one handshake endpoint per stage, so we
# register the stage once here and let every local engine core reuse the
# returned handshake address directly.
handshake_address = register_stage_with_omni_master(
omni_master_address=omni_master_address,
omni_master_port=omni_master_port,
omni_stage_id=stage_id,
omni_stage_config=stage_cfg,
coordinator=coordinator,
replica_id=replica_id,
)
engine_manager = None
# One OmniMasterServer registration per omni replica; each registration
# yields its own (handshake, input, output) allocation and the head's
# OmniCoordinator ROUTER address. We then spawn one
# OmniCoreEngineProcManager per replica so its subprocess gets the
# right replica id wired into its OmniCoordClientForStage.
log_stats = bool(args.log_stats)
if args.disable_log_stats:
log_stats = False
engine_managers: list[Any] = []
monitor_threads: list[threading.Thread] = []
def _monitor_target(mgr: Any) -> None:
try:
mgr.monitor_engine_liveness()
except Exception:
logger.exception("[Headless] monitor_engine_liveness raised")
try:
engine_manager = CoreEngineProcManager(
local_engine_count=local_engine_count,
start_index=dp_rank,
local_start_index=0,
vllm_config=vllm_config,
local_client=False,
handshake_address=handshake_address,
executor_class=executor_class,
log_stats=log_stats,
)
# vllm>=0.19 renamed CoreEngineProcManager.join_first() to
# monitor_engine_liveness() (see upstream PR #35862).
engine_manager.monitor_engine_liveness()
for _rep_idx in range(omni_dp_size_local):
# Always auto-assign: see the diffusion branch comment above
# for the rationale (headless owns no replica-id namespace).
response = register_stage_with_omni_master(
omni_master_address=omni_master_address,
omni_master_port=omni_master_port,
omni_stage_id=stage_id,
omni_stage_config=stage_cfg,
coordinator=coordinator,
replica_id=None,
return_full_response=True,
replica_bind_address=omni_replica_address,
# LLM headless: the head binds *all* three sockets —
# handshake ROUTER (``connect_remote_engine_cores``),
# input ROUTER and output PULL (``CoreClient`` —
# ``make_zmq_socket`` defaults bind=True for PULL).
# The remote LLM worker is purely a connector: it
# opens 3 outbound TCP connections to the master's
# host. So the master must keep every address on
# its own host; rewriting any of them to this
# replica's NIC makes the head's ``bind`` go
# EADDRNOTAVAIL on a cross-host launch.
replica_binds_sockets=False,
)
# Per-replica CUDA_VISIBLE_DEVICES, same pattern as the diffusion
# branch above. OmniCoreEngineProcManager.__init__ spawns its
# subprocesses via context.Process inside the constructor, so we
# must set the env *before* instantiation and restore after.
previous_visible_devices = os.environ.get(device_control_env)
try:
if per_replica_devices[_rep_idx] is not None:
setup_stage_devices(stage_id, {"devices": per_replica_devices[_rep_idx]})
mgr = OmniCoreEngineProcManager(
local_engine_count=local_engine_count,
start_index=dp_rank,
local_start_index=0,
vllm_config=vllm_config,
local_client=False,
handshake_address=response.handshake_address,
executor_class=executor_class,
log_stats=log_stats,
omni_stage_id=stage_id,
omni_coordinator_address=response.coordinator_router_address,
omni_replica_base_id=response.replica_id,
)
finally:
if previous_visible_devices is None:
current_omni_platform.unset_device_control_env_var()
else:
current_omni_platform.set_device_control_env_var(previous_visible_devices)
engine_managers.append(mgr)
logger.info(
"[Headless] Stage %d replica id=%d up (coord=%s)",
stage_id,
response.replica_id,
response.coordinator_router_address,
)
# Run all managers' liveness monitors in parallel. Each blocks
# until its own subprocesses exit (or fail).
if len(engine_managers) == 1:
engine_managers[0].monitor_engine_liveness()
else:
for mgr in engine_managers:
t = threading.Thread(target=_monitor_target, args=(mgr,), name=f"omni-replica-monitor-{id(mgr):x}")
t.start()
monitor_threads.append(t)
for t in monitor_threads:
t.join()
finally:
logger.info("[Headless] Shutting down stage %d.", stage_id)
if engine_manager is not None:
engine_manager.shutdown()
logger.info("[Headless] Shutting down stage %d (%d managers).", stage_id, len(engine_managers))
for mgr in engine_managers:
try:
mgr.shutdown()
except Exception:
logger.exception("[Headless] engine manager shutdown failed")
if coordinator is not None:
coordinator.shutdown()
+30 -82
View File
@@ -65,7 +65,6 @@ _FISH_TTS_MODEL_STAGES = {"fish_speech_slow_ar"}
_COSYVOICE3_TTS_MODEL_STAGES = {"cosyvoice3_talker"}
_OMNIVOICE_TTS_MODEL_STAGES = {"omnivoice_generator"}
_COVO_AUDIO_MODEL_STAGES = {"fused_thinker_talker"}
_VOXCPM_TTS_MODEL_STAGES = {"latent_generator", "vae"}
_VOXCPM2_TTS_MODEL_STAGES = {"latent_generator"}
_MING_TTS_MODEL_STAGES = {"ming_tts"}
_MOSS_TTS_MODEL_STAGES = {"moss_tts_nano"}
@@ -76,7 +75,6 @@ _TTS_MODEL_STAGES: set[str] = (
| _COSYVOICE3_TTS_MODEL_STAGES
| _OMNIVOICE_TTS_MODEL_STAGES
| _COVO_AUDIO_MODEL_STAGES
| _VOXCPM_TTS_MODEL_STAGES
| _VOXCPM2_TTS_MODEL_STAGES
| _MING_TTS_MODEL_STAGES
| _MOSS_TTS_MODEL_STAGES
@@ -481,8 +479,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
model_arch = getattr(self._tts_stage.engine_args, "model_arch", None)
if model_arch == "VoxCPM2TalkerForConditionalGeneration":
return "voxcpm2"
if model_arch == "VoxCPMForConditionalGeneration":
return "voxcpm"
if model_stage in _QWEN3_TTS_MODEL_STAGES:
return "qwen3_tts"
if model_stage in _VOXTRAL_TTS_MODEL_STAGES:
@@ -497,12 +493,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
model_arch = getattr(self._tts_stage.engine_args, "model_arch", None)
if model_arch and "CovoAudio" in model_arch:
return "covo_audio"
if model_stage in (_VOXCPM_TTS_MODEL_STAGES | _VOXCPM2_TTS_MODEL_STAGES):
has_vae_stage = any(
getattr(getattr(stage, "engine_args", None), "model_stage", None) == "vae"
for stage in self.engine_client.stage_configs
)
return "voxcpm" if has_vae_stage or model_stage == "vae" else "voxcpm2"
if model_stage in _VOXCPM2_TTS_MODEL_STAGES:
return "voxcpm2"
if model_stage in _MING_TTS_MODEL_STAGES:
return "ming_flash_omni_tts"
if model_stage in _MOSS_TTS_MODEL_STAGES:
@@ -536,8 +528,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# is no static speaker list to surface here.
return set()
try:
if self._tts_model_type == "voxcpm":
return set()
if self._tts_model_type == "voxcpm2":
return {"default"}
if self._tts_model_type == "voxtral_tts":
@@ -599,8 +589,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
def _estimate_prompt_len(self, tts_params: dict[str, Any]) -> int:
"""Estimate prompt length so the placeholder matches model-side embeddings."""
try:
if self._tts_model_type == "voxcpm":
return 1
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker import (
Qwen3TTSTalkerForConditionalGeneration,
)
@@ -1136,8 +1124,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
return self._validate_fish_tts_request(request)
if self._tts_model_type == "cosyvoice3":
return self._validate_cosyvoice3_request(request)
if self._tts_model_type == "voxcpm":
return self._validate_voxcpm_request(request)
if self._tts_model_type == "voxcpm2":
if request.max_new_tokens is not None:
if request.max_new_tokens < _TTS_MAX_NEW_TOKENS_MIN:
@@ -1242,43 +1228,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
return None
def _validate_voxcpm_request(self, request: OpenAICreateSpeechRequest) -> str | None:
"""Validate VoxCPM request parameters. Returns error message or None."""
if not request.input or not request.input.strip():
return "Input text cannot be empty"
if request.voice is not None:
return "'voice' is not supported for VoxCPM"
if request.instructions is not None:
return "'instructions' is not supported for VoxCPM"
if request.language is not None:
return "'language' is not supported for VoxCPM"
if request.task_type not in (None, "Base"):
return "VoxCPM only supports plain TTS or voice cloning with ref_audio/ref_text"
if request.x_vector_only_mode is not None:
return "'x_vector_only_mode' is not supported for VoxCPM"
if request.speaker_embedding is not None:
return "'speaker_embedding' is not supported for VoxCPM"
if request.initial_codec_chunk_frames is not None:
return "'initial_codec_chunk_frames' is not supported for VoxCPM"
if request.ref_audio is not None:
fmt_err = self._validate_ref_audio_format(request.ref_audio)
if fmt_err:
return fmt_err
if not request.ref_text or not request.ref_text.strip():
return "Voice cloning requires 'ref_text' (transcript of the reference audio)"
elif request.ref_text is not None:
return "'ref_text' requires 'ref_audio' for VoxCPM voice cloning"
if request.max_new_tokens is not None:
if request.max_new_tokens < _TTS_MAX_NEW_TOKENS_MIN:
return f"max_new_tokens must be at least {_TTS_MAX_NEW_TOKENS_MIN}"
if request.max_new_tokens > _TTS_MAX_NEW_TOKENS_MAX:
return f"max_new_tokens cannot exceed {_TTS_MAX_NEW_TOKENS_MAX}"
return None
def _validate_qwen_tts_request(self, request: OpenAICreateSpeechRequest) -> str | None:
"""Validate Qwen TTS request parameters. Returns error message or None."""
# Infer Base task when ref_audio or ref_text is provided without explicit task_type.
@@ -1643,18 +1592,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
Processes each parameter if present, skips if not.
Values are wrapped in lists as required by the model.
"""
if self._tts_model_type == "voxcpm":
params: dict[str, Any] = {
"text": [request.input],
"cfg_value": [2.0],
"inference_timesteps": [10],
"min_len": [2],
"max_new_tokens": [request.max_new_tokens or 4096],
}
if request.ref_text is not None:
params["ref_text"] = [request.ref_text]
return params
params: dict[str, Any] = {}
# Text content (always required)
@@ -1787,6 +1724,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
self,
request: OpenAICreateSpeechRequest,
ref_audio_data: tuple[list[float], int] | None = None,
*,
has_inline_ref_audio: bool = False,
) -> dict[str, Any]:
"""Build prompt for Fish Speech S2 Pro.
@@ -1838,7 +1777,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# Pass voice identity for model-side DAC code caching.
if request.voice is not None:
voice_lower = request.voice.lower()
if voice_lower in self.uploaded_speakers:
if voice_lower in self.uploaded_speakers and not has_inline_ref_audio:
additional_information["voice_name"] = voice_lower
additional_information["voice_created_at"] = self._voice_created_at(voice_lower)
if request.max_new_tokens is not None:
@@ -1852,6 +1791,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
async def _build_cosyvoice3_prompt(
self,
request: OpenAICreateSpeechRequest,
*,
has_inline_ref_audio: bool = False,
) -> dict[str, Any]:
"""Build prompt for CosyVoice3.
@@ -1870,8 +1811,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# Pass voice metadata for caching in the processor
if request.voice:
voice_lower = request.voice.lower()
mm_kwargs["voice_name"] = voice_lower
mm_kwargs["voice_created_at"] = self._voice_created_at(voice_lower)
if voice_lower in self.uploaded_speakers and not has_inline_ref_audio:
mm_kwargs["voice_name"] = voice_lower
mm_kwargs["voice_created_at"] = self._voice_created_at(voice_lower)
return {
"prompt": request.input,
@@ -2020,6 +1962,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# Resolve uploaded voice for non-Qwen3 models.
# Qwen3 TTS has its own uploaded voice handling in _build_tts_params().
has_inline_ref_audio = request.ref_audio is not None
if self._tts_model_type in ("fish_tts", "cosyvoice3", "moss_tts_nano"):
err = self._apply_uploaded_speaker(request)
if err:
@@ -2033,7 +1976,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
if request.ref_audio is not None:
wav_list, sr = await self._resolve_ref_audio(request.ref_audio)
ref_audio_data = (wav_list, sr)
prompt = await self._build_fish_speech_prompt_async(request, ref_audio_data=ref_audio_data)
prompt = await self._build_fish_speech_prompt_async(
request, ref_audio_data=ref_audio_data, has_inline_ref_audio=has_inline_ref_audio
)
tts_params = {}
elif self._tts_model_type == "omnivoice":
if not request.input or not request.input.strip():
@@ -2050,8 +1995,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
prompt["ref_text"] = request.ref_text
if request.voice:
voice_lower = request.voice.lower()
prompt["voice_name"] = voice_lower
prompt["voice_created_at"] = self._voice_created_at(voice_lower)
if voice_lower in self.uploaded_speakers and not has_inline_ref_audio:
prompt["voice_name"] = voice_lower
prompt["voice_created_at"] = self._voice_created_at(voice_lower)
if request.language:
prompt["lang"] = request.language
if request.instructions:
@@ -2068,7 +2014,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
if voice_lower not in self.uploaded_speakers and voice_lower not in self.supported_speakers:
all_voices = sorted(self.uploaded_speakers.keys() | self.supported_speakers)
raise ValueError(f"Invalid voice '{request.voice}'. Supported: {', '.join(all_voices) or 'none'}")
if voice_lower in self.uploaded_speakers:
if voice_lower in self.uploaded_speakers and not has_inline_ref_audio:
if self.uploaded_speakers[voice_lower].get("embedding_source") == "direct":
raise ValueError(
f"Uploaded voice '{request.voice}' uses a speaker embedding (Qwen3-only). "
@@ -2080,9 +2026,10 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
tts_params = {}
if request.voice:
voice_lower = request.voice.lower()
additional = prompt.setdefault("additional_information", {})
additional["voice_name"] = voice_lower
additional["voice_created_at"] = self._voice_created_at(voice_lower)
if voice_lower in self.uploaded_speakers and not has_inline_ref_audio:
additional = prompt.setdefault("additional_information", {})
additional["voice_name"] = voice_lower
additional["voice_created_at"] = self._voice_created_at(voice_lower)
elif self._is_tts:
validation_error = self._validate_tts_request(request)
if validation_error:
@@ -2092,7 +2039,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
prompt = await self._build_voxtral_prompt_async(request)
tts_params = {}
elif self._tts_model_type == "cosyvoice3":
prompt = await self._build_cosyvoice3_prompt(request)
prompt = await self._build_cosyvoice3_prompt(request, has_inline_ref_audio=has_inline_ref_audio)
tts_params = {}
elif self._tts_model_type == "ming_flash_omni_tts":
prompt = self._build_ming_prompt(request)
@@ -2101,8 +2048,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
tts_params = await self._build_moss_tts_params(request)
if request.voice:
voice_lower = request.voice.lower()
tts_params["voice_name"] = [voice_lower]
tts_params["voice_created_at"] = [self._voice_created_at(voice_lower)]
if voice_lower in self.uploaded_speakers and not has_inline_ref_audio:
tts_params["voice_name"] = [voice_lower]
tts_params["voice_created_at"] = [self._voice_created_at(voice_lower)]
# Propagate seed from sampling params for deterministic generation.
# MOSS-TTS-Nano uses its own internal sampling inside
# inference_stream(), which reads seed from additional_information
@@ -2158,8 +2106,6 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
model_type = "voxtral_tts"
elif self._tts_model_type == "cosyvoice3":
model_type = "cosyvoice3"
elif self._tts_model_type == "voxcpm":
model_type = "voxcpm"
elif self._tts_model_type == "voxcpm2":
model_type = "voxcpm2"
elif self._tts_model_type == "ming_flash_omni_tts":
@@ -2375,6 +2321,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
all_voices = sorted(self.uploaded_speakers.keys() | self.supported_speakers)
raise ValueError(f"Invalid voice '{request.voice}'. Supported: {', '.join(all_voices) or 'none'}")
has_inline_ref_audio = request.ref_audio is not None
err = self._apply_uploaded_speaker(request)
if err:
raise ValueError(err)
@@ -2388,8 +2335,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
prompt["ref_text"] = request.ref_text
if request.voice:
voice_lower = request.voice.lower()
prompt["voice_name"] = voice_lower
prompt["voice_created_at"] = self._voice_created_at(voice_lower)
if voice_lower in self.uploaded_speakers and not has_inline_ref_audio:
prompt["voice_name"] = voice_lower
prompt["voice_created_at"] = self._voice_created_at(voice_lower)
if request.language:
prompt["lang"] = request.language
if request.instructions:
+18
View File
@@ -95,6 +95,24 @@ def _map_device_list(stage_id: int, device_list: list[str], visible_device_list:
if not all(device.isdigit() for device in device_list):
raise ValueError("Logical devices must be non-negative integers")
# Idempotency: if every requested id already names an entry in the visible
# pool (by value, not by index), treat the YAML field as physical and skip
# the remap. This avoids a double-mapping crash when a parent harness has
# already narrowed CUDA_VISIBLE_DEVICES to specific physical ids before
# spawning the subprocess (the test runtime's OmniServerStageCli does this
# — it sets each stage subprocess's env via ``_set_stage_device_env``).
# Without this guard, a YAML ``devices: "1"`` against a narrowed visible
# list ``["1"]`` would try ``visible[1]`` (out of range) and raise.
visible_set = set(visible_device_list)
if all(device in visible_set for device in device_list):
logger.info(
"Stage %s requested devices %s are already in the visible set %s; using as-is (no remap).",
stage_id,
device_list,
visible_device_list,
)
return list(device_list)
logical_ids = [int(device) for device in device_list]
mapped_devices = [visible_device_list[idx] for idx in logical_ids if idx < num_visible]
mapping_pairs = [
-48
View File
@@ -746,54 +746,6 @@ def filter_dataclass_kwargs(cls: Any, kwargs: dict) -> dict:
return filtered_kwargs
# TODO(wuhang): Remove after PR #1115.
def build_base_engine_args(source: Any) -> dict[str, Any] | None:
"""Build base engine args with tokenizer and parallel configuration.
Automatically detects whether source is a dict-like object or namespace object.
Args:
source: Source object (args namespace or kwargs dict) containing configuration.
Returns:
Dictionary containing tokenizer and parallel configuration overrides,
or None if no configuration is present.
"""
# Auto-detect source type: dict-like objects have 'get' method
is_dict_like = hasattr(source, "get") and callable(getattr(source, "get"))
# Extract tokenizer
if is_dict_like:
tokenizer = source.get("tokenizer", None)
else:
tokenizer = getattr(source, "tokenizer", None)
base_engine_args = {"tokenizer": tokenizer} if tokenizer is not None else None
# Extract parallel configuration
parallel_keys = [
"tensor_parallel_size",
"pipeline_parallel_size",
"data_parallel_size",
"data_parallel_size_local",
"data_parallel_backend",
"distributed_executor_backend",
]
if is_dict_like:
parallel_overrides = {k: source[k] for k in parallel_keys if k in source and source[k] is not None}
else:
parallel_overrides = {
k: getattr(source, k) for k in parallel_keys if hasattr(source, k) and getattr(source, k) is not None
}
if parallel_overrides:
base_engine_args = base_engine_args or {}
base_engine_args.update(parallel_overrides)
return base_engine_args
# The following code detects if the process is running in a container and if
# PID host is available. If so, we can use process-scoped memory tracking;
# otherwise we need sequential init locks.
@@ -1590,6 +1590,10 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
self._sampler: Sampler | None = None
self._eos_token_id: int = tokenizer.eos_token_id
# Lazily built on first sample() call so we can pick up logits.device
# without guessing during init. See `sample()` for the comprehension
# fast path that uses this.
self._blocked_token_ids_tensor: torch.Tensor | None = None
self._replace_rotary_embeddings()
self._patch_moe_blocks()
@@ -1992,25 +1996,39 @@ class HunyuanImage3ForConditionalGeneration(nn.Module, SupportsMultiModal, Suppo
min_score = torch.finfo(logits.dtype).min
if self._is_comprehension:
# Comprehension path is stateless: we only need to mask a fixed
# set of blocked token ids on every step. Do it in one batched
# index_fill_ instead of a per-(req, id) Python loop of scalar
# GPU writes, and skip reading `output_token_ids` from CPU
# (unused here) so this branch never forces a D2H sync.
if self._blocked_token_ids_tensor is None and self._blocked_token_ids:
self._blocked_token_ids_tensor = torch.tensor(
sorted(self._blocked_token_ids),
dtype=torch.long,
device=logits.device,
)
if self._blocked_token_ids_tensor is not None:
logits.index_fill_(-1, self._blocked_token_ids_tensor, min_score)
return self._sampler(logits=logits, sampling_metadata=sampling_metadata)
# Generation path retains the per-request stateful logic for forced
# stage-transition tokens and ratio-restriction.
for req_idx in range(logits.shape[0]):
decoded_tokens: list[int] = (
sampling_metadata.output_token_ids[req_idx] if req_idx < len(sampling_metadata.output_token_ids) else []
)
last_token = decoded_tokens[-1] if decoded_tokens else -1
if self._is_comprehension:
for tid in self._blocked_token_ids:
logits[req_idx, tid] = min_score
else:
forced = self._get_forced_token(decoded_tokens)
if forced is not None:
logits[req_idx].fill_(min_score)
logits[req_idx, forced] = 0
elif last_token == self._size_token_id:
self._apply_ratio_restriction(logits, req_idx, min_score)
elif last_token in self._all_ratio_ids:
logits[req_idx].fill_(min_score)
logits[req_idx, self._eos_token_id] = 0
forced = self._get_forced_token(decoded_tokens)
if forced is not None:
logits[req_idx].fill_(min_score)
logits[req_idx, forced] = 0
elif last_token == self._size_token_id:
self._apply_ratio_restriction(logits, req_idx, min_score)
elif last_token in self._all_ratio_ids:
logits[req_idx].fill_(min_score)
logits[req_idx, self._eos_token_id] = 0
return self._sampler(logits=logits, sampling_metadata=sampling_metadata)
@@ -26,6 +26,13 @@ from vllm_omni.model_executor.models.output_templates import OmniOutput
logger = logging.getLogger(__name__)
# Minimum safe values for codec streaming parameters. Mirrors the constants
# in stage_input_processors/mimo_audio.py — keep in sync.
_MIN_CODEC_CHUNK_FRAMES = 3
_MIN_CODEC_LEFT_CONTEXT_FRAMES = 40 # must cover vocoder_attn_window_size[0]
_DEFAULT_CODEC_CHUNK_FRAMES = 10
_DEFAULT_CODEC_LEFT_CONTEXT_FRAMES = 40
def flat_codec_group_element_count(group_size: int, audio_channels: int) -> int:
"""Flat token count for one MiMo talker codec group on the code2wav wire.
@@ -485,12 +492,37 @@ class MiMoAudioToken2WavForConditionalGenerationVLLM(nn.Module, SupportsPP):
if connector_cfg
else None
)
self._codec_chunk_frames = int(extra_cfg.get("codec_chunk_frames", 3)) if isinstance(extra_cfg, dict) else 3
if self._codec_chunk_frames <= 0:
raise ValueError(f"codec_chunk_frames must be positive, got {self._codec_chunk_frames}")
self._codec_left_context_frames = (
int(extra_cfg.get("codec_left_context_frames", 3)) if isinstance(extra_cfg, dict) else 3
raw_chunk = (
int(extra_cfg.get("codec_chunk_frames", _DEFAULT_CODEC_CHUNK_FRAMES))
if isinstance(extra_cfg, dict)
else _DEFAULT_CODEC_CHUNK_FRAMES
)
if raw_chunk < _MIN_CODEC_CHUNK_FRAMES:
logger.warning(
"codec_chunk_frames=%d is below minimum %d; falling back to %d.",
raw_chunk,
_MIN_CODEC_CHUNK_FRAMES,
_DEFAULT_CODEC_CHUNK_FRAMES,
)
raw_chunk = _DEFAULT_CODEC_CHUNK_FRAMES
self._codec_chunk_frames = raw_chunk
raw_left = (
int(extra_cfg.get("codec_left_context_frames", _DEFAULT_CODEC_LEFT_CONTEXT_FRAMES))
if isinstance(extra_cfg, dict)
else _DEFAULT_CODEC_LEFT_CONTEXT_FRAMES
)
if raw_left < _MIN_CODEC_LEFT_CONTEXT_FRAMES:
logger.warning(
"codec_left_context_frames=%d is below minimum %d (must cover vocoder attention "
"window %s); falling back to %d to prevent voice instability.",
raw_left,
_MIN_CODEC_LEFT_CONTEXT_FRAMES,
getattr(self.config, "vocoder_attn_window_size", [40, 10]),
_DEFAULT_CODEC_LEFT_CONTEXT_FRAMES,
)
raw_left = _DEFAULT_CODEC_LEFT_CONTEXT_FRAMES
self._codec_left_context_frames = raw_left
def load_weights(
self,
@@ -542,8 +542,20 @@ class MiMoAudioLLMForConditionalGeneration(nn.Module, SupportsMultiModal, Suppor
)
self.device = current_omni_platform.get_torch_device()
# global_sampler MUST stay greedy (do_sample=False) so its token decision
# matches vLLM's external sampler (SamplingParams temperature=0.0). Both
# run argmax on the same logits, so they always agree on whether the next
# token is <|empty|> (audio step) or a real text token. Enabling
# do_sample=True here without also routing vLLM's sampled token back into
# this gate check would cause the two to diverge and corrupt KV-cache state.
self.global_sampler = MiMoSampler(do_sample=False, temperature=0.6, top_p=0.95)
self.local_sampler = MiMoSampler(do_sample=False, temperature=0.9, top_p=0.95)
# local_sampler drives audio-code generation inside local_forward. It is
# entirely internal and NOT subject to vLLM's SamplingParams, so stochastic
# sampling is safe here and is required to produce natural, varied speech.
# Setting do_sample=True also disables the CUDA-graph path (use_cg gate in
# local_forward checks `do_sample is False`), preventing MiMoLocalSamplerTensor
# from silently forcing argmax even when temperature > 0.
self.local_sampler = MiMoSampler(do_sample=True, temperature=0.9, top_p=0.95)
self.removed_tokens = None
self.speech_vocab_sizes = config.parsed_speech_vocab_sizes()
@@ -806,7 +818,7 @@ class MiMoAudioLLMForConditionalGeneration(nn.Module, SupportsMultiModal, Suppor
device=tokens_device,
)
if local_sampler is None:
local_sampler = MiMoSampler(do_sample=False, temperature=0.6, top_p=0.9)
local_sampler = MiMoSampler(do_sample=True, temperature=0.9, top_p=0.95)
past_key_values = DynamicCache()
for t in range(delay_iters):
@@ -852,7 +864,7 @@ class MiMoAudioLLMForConditionalGeneration(nn.Module, SupportsMultiModal, Suppor
local_sampler: MiMoSampler | None = None,
):
if local_sampler is None:
local_sampler = MiMoSampler(do_sample=False, temperature=0.6, top_p=0.9)
local_sampler = MiMoSampler(do_sample=True, temperature=0.9, top_p=0.95)
b = int(local_embeds.shape[0])
use_cg = (local_sampler.do_sample is None or local_sampler.do_sample is False) and bool(
@@ -30,6 +30,7 @@ import torch.nn as nn
import torch.nn.functional as F
from transformers import PreTrainedTokenizerBase, Qwen2Config, Qwen2Model, StaticCache
from vllm.logger import init_logger
from vllm.platforms import current_platform
from x_transformers.x_transformers import RotaryEmbedding, apply_rotary_pos_emb
from vllm_omni.model_executor.layers.timestep_embedding import DiTTimestepEmbedding
@@ -479,7 +480,7 @@ class CFMGraphExecutor:
self.sde_rnd_placeholder = torch.empty_like(sde_rnd)
self.graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(self.graph):
with torch.cuda.graph(self.graph, pool=current_platform.get_global_graph_pool()):
self.gen_lat_placeholder = self.cfm.sample(
self.last_hidden_state_placeholder,
self.his_lat_placeholder,
@@ -81,7 +81,6 @@ class Qwen2_5OmniForConditionalGeneration(
# Initialize thinker model (multimodal processing)
self.thinker = init_vllm_registered_model(
vllm_config=vllm_config,
prefix=maybe_prefix(prefix, "thinker"),
hf_config=thinker_config,
# Use registry architecture key
architectures=["Qwen2_5OmniThinkerModel"],
@@ -324,6 +324,16 @@ class Qwen2_5OmniThinkerForConditionalGeneration(
"gate_proj",
"up_proj",
],
"attn_qkv_proj": [
"attn_q_proj",
"attn_k_proj",
"attn_v_proj",
],
"qkv": [
"q",
"k",
"v",
],
}
@classmethod
@@ -554,10 +554,10 @@ class CUDAGraphDecoderWrapper:
chunk_size: int = 300,
left_context_size: int = 25,
) -> torch.Tensor:
wavs = []
start_index = 0
total_len = codes.shape[-1]
total_upsample = self.decoder.total_upsample
wav_out = None
while start_index < total_len:
end_index = min(start_index + chunk_size, total_len)
@@ -566,21 +566,16 @@ class CUDAGraphDecoderWrapper:
codes_chunk = codes[..., start_index - context_size : end_index]
wav_chunk = self._decode(codes_chunk, clone_graph_output=False)
if wav_out is None:
wav_out = torch.empty(
(*wav_chunk.shape[:-1], total_len * total_upsample),
dtype=wav_chunk.dtype,
device=wav_chunk.device,
)
src_start = context_size * total_upsample
dst_start = start_index * total_upsample
dst_end = end_index * total_upsample
wav_out[..., dst_start:dst_end].copy_(wav_chunk[..., src_start:])
# Keep origin/main's concat semantics: Qwen3-Omni can return a chunk
# that is shorter than the nominal code_len * total_upsample length.
# Clone each slice because graph outputs are static buffers that later
# replays may overwrite.
wavs.append(wav_chunk[..., context_size * total_upsample :].clone())
start_index = end_index
if wav_out is None:
if not wavs:
return self.decoder(codes)
return wav_out
return torch.cat(wavs, dim=-1)
def batched_chunked_decode_with_cudagraph(
self,
@@ -156,12 +156,6 @@ _OMNI_MODELS = {
"fish_speech_dac_decoder",
"FishSpeechDACDecoder",
),
## VoxCPM
"VoxCPMForConditionalGeneration": (
"voxcpm",
"voxcpm",
"VoxCPMForConditionalGeneration",
),
## VoxCPM2
"VoxCPM2TalkerForConditionalGeneration": (
"voxcpm2",
@@ -1,5 +0,0 @@
from .voxcpm import VoxCPMForConditionalGeneration
__all__ = [
"VoxCPMForConditionalGeneration",
]
@@ -1,886 +0,0 @@
from __future__ import annotations
import json
import os
import sys
import tempfile
import warnings
import wave
from collections.abc import Callable, Generator, Iterable
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.nn as nn
from einops import rearrange
from tqdm import tqdm
from vllm.config import VllmConfig
from vllm.logger import init_logger
from vllm.sequence import IntermediateTensors
from vllm_omni.model_executor.models.output_templates import OmniOutput
from .voxcpm_loader import (
_build_prompt_cache_with_soundfile,
_device_to_string,
_force_cuda_available_for_npu,
_import_voxcpm_audio_vae_classes,
_import_voxcpm_base_model_class,
_is_torchcodec_load_error,
_normalize_dtype_name,
_prepare_runtime_model_dir,
_resolve_runtime_device,
)
from .voxcpm_runtime_utils import resolve_voxcpm_model_dir
from .voxcpm_stage_wrappers import _DirectVoxCPMAudioVAE, _DirectVoxCPMLatentGenerator
logger = init_logger(__name__)
_VOXCPM_LATENT_MAGIC = 131071
def _make_voxcpm_model_for_omni(base: type[Any]) -> type[Any]:
"""Subclass upstream VoxCPMModel: local ``_inference`` + ``latents_only`` prompt-cache generation."""
from voxcpm.model.utils import get_dtype
class VoxCPMModelForOmni(base):
@torch.inference_mode()
def build_prompt_cache(self, *args: Any, **kwargs: Any):
try:
return super().build_prompt_cache(*args, **kwargs)
except (ImportError, ModuleNotFoundError, RuntimeError) as exc:
if not _is_torchcodec_load_error(exc):
raise
return _build_prompt_cache_with_soundfile(self, *args, **kwargs)
@torch.inference_mode()
def _inference(
self,
text: torch.Tensor,
text_mask: torch.Tensor,
feat: torch.Tensor,
feat_mask: torch.Tensor,
min_len: int = 2,
max_len: int = 2000,
inference_timesteps: int = 10,
cfg_value: float = 2.0,
streaming: bool = False,
streaming_prefix_len: int = 3,
) -> Generator[tuple[torch.Tensor, torch.Tensor | list[torch.Tensor]], None, None]:
B, _, _, _ = feat.shape
feat_embed = self.feat_encoder(feat)
feat_embed = self.enc_to_lm_proj(feat_embed)
scale_emb = self.config.lm_config.scale_emb if self.config.lm_config.use_mup else 1.0
text_embed = self.base_lm.embed_tokens(text) * scale_emb
combined_embed = text_mask.unsqueeze(-1) * text_embed + feat_mask.unsqueeze(-1) * feat_embed
prefix_feat_cond = feat[:, -1, ...]
pred_feat_seq: list[torch.Tensor] = []
audio_patch_count = int(feat_mask.sum().item())
if audio_patch_count > 0:
context_len = min(streaming_prefix_len - 1, audio_patch_count)
prompt_context_patches = list(feat[:, -context_len:, :, :].split(1, dim=1))
pred_feat_seq = prompt_context_patches + pred_feat_seq
enc_outputs, kv_cache_tuple = self.base_lm(
inputs_embeds=combined_embed,
is_causal=True,
)
self.base_lm.kv_cache.fill_caches(kv_cache_tuple)
enc_outputs = self.fsq_layer(enc_outputs) * feat_mask.unsqueeze(-1) + enc_outputs * text_mask.unsqueeze(-1)
lm_hidden = enc_outputs[:, -1, :]
residual_enc_outputs, residual_kv_cache_tuple = self.residual_lm(
inputs_embeds=enc_outputs + feat_mask.unsqueeze(-1) * feat_embed,
is_causal=True,
)
self.residual_lm.kv_cache.fill_caches(residual_kv_cache_tuple)
residual_hidden = residual_enc_outputs[:, -1, :]
for step_idx in tqdm(range(max_len)):
dit_hidden = self.lm_to_dit_proj(lm_hidden) + self.res_to_dit_proj(residual_hidden)
pred_feat = self.feat_decoder(
mu=dit_hidden,
patch_size=self.patch_size,
cond=prefix_feat_cond.transpose(1, 2).contiguous(),
n_timesteps=inference_timesteps,
cfg_value=cfg_value,
).transpose(1, 2)
curr_embed = self.enc_to_lm_proj(self.feat_encoder(pred_feat.unsqueeze(1)))
pred_feat_seq.append(pred_feat.unsqueeze(1))
prefix_feat_cond = pred_feat
if streaming:
pred_feat_chunk = torch.cat(pred_feat_seq[-streaming_prefix_len:], dim=1)
feat_pred = rearrange(pred_feat_chunk, "b t p d -> b d (t p)", b=B, p=self.patch_size)
yield feat_pred, pred_feat_seq
stop_flag = self.stop_head(self.stop_actn(self.stop_proj(lm_hidden))).argmax(dim=-1)[0].cpu().item()
if step_idx > min_len and stop_flag == 1:
break
lm_hidden = self.base_lm.forward_step(
curr_embed[:, 0, :],
torch.tensor([self.base_lm.kv_cache.step()], device=curr_embed.device),
).clone()
lm_hidden = self.fsq_layer(lm_hidden)
residual_hidden = self.residual_lm.forward_step(
lm_hidden + curr_embed[:, 0, :],
torch.tensor([self.residual_lm.kv_cache.step()], device=curr_embed.device),
).clone()
if not streaming:
pred_feat_seq_cat = torch.cat(pred_feat_seq, dim=1)
feat_pred = rearrange(pred_feat_seq_cat, "b t p d -> b d (t p)", b=B, p=self.patch_size)
yield feat_pred, pred_feat_seq_cat.squeeze(0).cpu()
@torch.inference_mode()
def generate_latents_with_prompt_cache(
self,
target_text: str,
prompt_cache: dict,
min_len: int = 2,
max_len: int = 2000,
inference_timesteps: int = 10,
cfg_value: float = 2.0,
retry_badcase: bool = False,
retry_badcase_max_times: int = 3,
retry_badcase_ratio_threshold: float = 6.0,
streaming_prefix_len: int = 3,
) -> tuple[None, torch.Tensor, torch.Tensor]:
return next(
self._generate_with_prompt_cache(
target_text=target_text,
prompt_cache=prompt_cache,
min_len=min_len,
max_len=max_len,
inference_timesteps=inference_timesteps,
cfg_value=cfg_value,
retry_badcase=retry_badcase,
retry_badcase_max_times=retry_badcase_max_times,
retry_badcase_ratio_threshold=retry_badcase_ratio_threshold,
streaming=False,
streaming_prefix_len=streaming_prefix_len,
latents_only=True,
)
)
@torch.inference_mode()
def generate_latents_with_prompt_cache_streaming(
self,
target_text: str,
prompt_cache: dict,
min_len: int = 2,
max_len: int = 2000,
inference_timesteps: int = 10,
cfg_value: float = 2.0,
retry_badcase: bool = False,
retry_badcase_max_times: int = 3,
retry_badcase_ratio_threshold: float = 6.0,
streaming_prefix_len: int = 3,
) -> Generator[tuple[None, torch.Tensor, torch.Tensor], None, None]:
return self._generate_with_prompt_cache(
target_text=target_text,
prompt_cache=prompt_cache,
min_len=min_len,
max_len=max_len,
inference_timesteps=inference_timesteps,
cfg_value=cfg_value,
retry_badcase=retry_badcase,
retry_badcase_max_times=retry_badcase_max_times,
retry_badcase_ratio_threshold=retry_badcase_ratio_threshold,
streaming=True,
streaming_prefix_len=streaming_prefix_len,
latents_only=True,
)
@torch.inference_mode()
def _generate_with_prompt_cache(
self,
target_text: str,
prompt_cache: dict,
min_len: int = 2,
max_len: int = 2000,
inference_timesteps: int = 10,
cfg_value: float = 2.0,
retry_badcase: bool = False,
retry_badcase_max_times: int = 3,
retry_badcase_ratio_threshold: float = 6.0,
streaming: bool = False,
streaming_prefix_len: int = 3,
latents_only: bool = False,
) -> Generator[tuple[torch.Tensor | None, torch.Tensor, torch.Tensor | list[torch.Tensor]], None, None]:
if retry_badcase and streaming:
warnings.warn("Retry on bad cases is not supported in streaming mode, setting retry_badcase=False.")
retry_badcase = False
if prompt_cache is None:
prompt_audio_feat = torch.empty((0, self.patch_size, self.audio_vae.latent_dim), dtype=torch.float32)
text = target_text
else:
prompt_audio_feat = prompt_cache["audio_feat"]
prompt_text = prompt_cache["prompt_text"]
text = prompt_text + target_text
text_token = torch.LongTensor(self.text_tokenizer(text))
text_token = torch.cat(
[
text_token,
torch.tensor([self.audio_start_token], dtype=torch.int32, device=text_token.device),
],
dim=-1,
)
target_text_token = torch.LongTensor(self.text_tokenizer(target_text))
audio_length = prompt_audio_feat.size(0)
text_length = text_token.shape[0]
text_pad_token = torch.zeros(audio_length, dtype=torch.int32, device=text_token.device)
audio_pad_feat = torch.zeros(
(text_token.shape[0], self.patch_size, self.audio_vae.latent_dim),
dtype=torch.float32,
device=text_token.device,
)
text_token = torch.cat([text_token, text_pad_token])
audio_feat = torch.cat([audio_pad_feat, prompt_audio_feat], dim=0)
text_mask = (
torch.cat([torch.ones(text_length), torch.zeros(audio_length)]).type(torch.int32).to(text_token.device)
)
audio_mask = (
torch.cat([torch.zeros(text_length), torch.ones(audio_length)]).type(torch.int32).to(text_token.device)
)
text_token = text_token.unsqueeze(0).to(self.device)
text_mask = text_mask.unsqueeze(0).to(self.device)
audio_feat = audio_feat.unsqueeze(0).to(self.device).to(get_dtype(self.config.dtype))
audio_mask = audio_mask.unsqueeze(0).to(self.device)
target_text_length = len(self.text_tokenizer(target_text))
retry_badcase_times = 0
while retry_badcase_times < retry_badcase_max_times:
inference_result = self._inference(
text_token,
text_mask,
audio_feat,
audio_mask,
min_len=min_len,
max_len=min(int(target_text_length * retry_badcase_ratio_threshold + 10), max_len),
inference_timesteps=inference_timesteps,
cfg_value=cfg_value,
streaming=streaming,
streaming_prefix_len=streaming_prefix_len,
)
if streaming:
patch_len = self.patch_size * self.chunk_size
for latent_pred, pred_audio_feat in inference_result:
if latents_only:
decode_audio = None
yield (decode_audio, target_text_token, latent_pred)
else:
decode_audio = self.audio_vae.decode(latent_pred.to(torch.float32))
decode_audio = decode_audio[..., -patch_len:].squeeze(1).cpu()
yield (decode_audio, target_text_token, pred_audio_feat)
break
latent_pred, pred_audio_feat = next(inference_result)
if retry_badcase and pred_audio_feat.shape[0] >= target_text_length * retry_badcase_ratio_threshold:
ratio = pred_audio_feat.shape[0] / target_text_length
print(f" Badcase detected, audio_text_ratio={ratio}, retrying...", file=sys.stderr)
retry_badcase_times += 1
continue
break
if not streaming:
if latents_only:
decode_audio = None
else:
decode_audio = self.audio_vae.decode(latent_pred.to(torch.float32))
patch_len = self.patch_size * self.chunk_size
if audio_mask.sum().item() > 0:
decode_audio = decode_audio[..., patch_len * (streaming_prefix_len - 1) :].squeeze(1).cpu()
else:
decode_audio = decode_audio[..., :].squeeze(1).cpu()
yield (decode_audio, target_text_token, pred_audio_feat)
VoxCPMModelForOmni.__name__ = "VoxCPMModelForOmni"
VoxCPMModelForOmni.__qualname__ = "VoxCPMModelForOmni"
return VoxCPMModelForOmni
def _import_voxcpm_model_class() -> type[Any]:
base = _import_voxcpm_base_model_class()
return _make_voxcpm_model_for_omni(base)
def _load_native_voxcpm_model(
model_path: str,
*,
device: torch.device,
dtype: str | None,
):
VoxCPMModel = _import_voxcpm_model_class()
model_dir = resolve_voxcpm_model_dir(model_path)
runtime_model_path = _prepare_runtime_model_dir(model_dir, target_device=device, target_dtype=dtype)
if device.type == "npu" and hasattr(torch, "npu"):
torch.npu.set_device(device)
with _force_cuda_available_for_npu(device):
return VoxCPMModel.from_local(
runtime_model_path,
optimize=device.type == "cuda",
)
def _load_native_voxcpm_latent_generator(
model_path: str,
*,
device: torch.device,
dtype: str | None,
) -> _DirectVoxCPMLatentGenerator:
return _DirectVoxCPMLatentGenerator(_load_native_voxcpm_model(model_path, device=device, dtype=dtype))
def _load_native_voxcpm_audio_vae(
model_path: str,
*,
device: torch.device,
) -> _DirectVoxCPMAudioVAE:
AudioVAE, AudioVAEConfig = _import_voxcpm_audio_vae_classes()
model_dir = resolve_voxcpm_model_dir(model_path)
runtime_model_path = _prepare_runtime_model_dir(model_dir, target_device=device, target_dtype="float32")
config_dict = json.loads((Path(runtime_model_path) / "config.json").read_text())
audio_vae_config = config_dict.get("audio_vae_config")
audio_vae = AudioVAE(config=AudioVAEConfig(**audio_vae_config)) if audio_vae_config is not None else AudioVAE()
state_dict = torch.load(
Path(runtime_model_path) / "audiovae.pth",
map_location="cpu",
weights_only=True,
)["state_dict"]
audio_vae.load_state_dict(state_dict, strict=True)
audio_vae = audio_vae.to(device=device, dtype=torch.float32).eval()
if device.type == "npu" and hasattr(torch, "npu"):
torch.npu.set_device(device)
patch_size = int(config_dict.get("patch_size", 2))
return _DirectVoxCPMAudioVAE(audio_vae, patch_size=patch_size)
class VoxCPMForConditionalGeneration(nn.Module):
input_modalities = "audio"
_LATENT_STAGES = {"latent_generator", "latent", "ar_dit"}
_VAE_STAGES = {"vae", "audio_vae"}
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
super().__init__()
del prefix
self.vllm_config = vllm_config
self.model_path = vllm_config.model_config.model
self.model_stage = getattr(vllm_config.model_config, "model_stage", "latent_generator")
self.have_multimodal_outputs = True
self.has_preprocess = False
self.has_postprocess = False
self.enable_update_additional_information = True
self.requires_raw_input_tokens = True
self.inject_omni_request_id_into_runtime_info = True
self._pipeline = None
self._latent_stream_gens: dict[str, Any] = {}
self._latent_stream_terminal_pending: dict[str, int] = {}
self._latent_stream_completed: set[str] = set()
self._next_local_stream_key = 0
self._ar_emit_stop_token = True
def _runner_hidden_device_dtype(self) -> tuple[torch.device, torch.dtype]:
device = _resolve_runtime_device(self.vllm_config)
model_config = getattr(self.vllm_config, "model_config", None)
dtype = getattr(model_config, "dtype", torch.float32) if model_config is not None else torch.float32
return device, dtype
def _ensure_model_loaded(self):
if self._pipeline is not None:
return
target_device = _resolve_runtime_device(self.vllm_config)
model_dtype = getattr(self.vllm_config.model_config, "dtype", None)
normalized_dtype = _normalize_dtype_name(model_dtype)
if self.model_stage in self._LATENT_STAGES:
self._pipeline = _load_native_voxcpm_latent_generator(
self.model_path,
device=target_device,
dtype=normalized_dtype,
)
elif self.model_stage in self._VAE_STAGES:
self._pipeline = _load_native_voxcpm_audio_vae(
self.model_path,
device=target_device,
)
else:
raise ValueError(
f"Unsupported VoxCPM model_stage: {self.model_stage}. "
"pure_voxcpm only supports split-stage latent_generator/vae inference."
)
logger.info("Loaded VoxCPM stage '%s' on %s", self.model_stage, _device_to_string(target_device))
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
del weights
self._ensure_model_loaded()
return set()
@staticmethod
def _extract_val(info: dict[str, Any], key: str, default: Any) -> Any:
value = info.get(key, default)
if isinstance(value, list):
return value[0] if value else default
return value
def _resolve_stream_request_key(self, info: dict[str, Any]) -> str:
request_key = info.get("__voxcpm_stream_key")
if request_key is not None:
return str(request_key)
request_key = info.get("_omni_req_id")
if request_key is not None:
request_key = str(request_key)
info["__voxcpm_stream_key"] = request_key
return request_key
request_key = f"voxcpm-local-{self._next_local_stream_key}"
self._next_local_stream_key += 1
info["__voxcpm_stream_key"] = request_key
return str(request_key)
def _recover_latent_from_input_ids(self, input_ids: torch.Tensor | None) -> torch.Tensor | None:
if input_ids is None or input_ids.numel() == 0:
return None
flat_ids = input_ids.detach().reshape(-1).to("cpu")
if flat_ids.numel() < 4 or int(flat_ids[0].item()) != _VOXCPM_LATENT_MAGIC:
return None
latent_dim = int(flat_ids[1].item())
time_dim = int(flat_ids[2].item())
payload = flat_ids[3:]
expected = latent_dim * time_dim
if latent_dim <= 0 or time_dim <= 0:
raise ValueError(f"Invalid VoxCPM latent header: latent_dim={latent_dim}, time_dim={time_dim}")
if int(payload.numel()) != expected:
raise ValueError(
"Invalid VoxCPM latent payload size: "
f"expected={expected}, actual={int(payload.numel())}, "
f"latent_dim={latent_dim}, time_dim={time_dim}"
)
packed = payload.to(dtype=torch.int32).to(torch.uint16)
return packed.view(torch.bfloat16).to(torch.float32).reshape(1, latent_dim, time_dim)
def _maybe_recover_vae_infos(
self,
infos: list[dict[str, Any]],
input_ids: torch.Tensor | None,
*,
async_chunk: bool,
) -> list[dict[str, Any]]:
if not async_chunk:
return infos
if any(self._extract_val(info, "latent_audio_feat", None) is not None for info in infos):
return infos
recovered = self._recover_latent_from_input_ids(input_ids)
if recovered is None:
return infos
return [{"latent_audio_feat": recovered}]
@staticmethod
def _normalize_audio_samples(samples: Any) -> np.ndarray:
if isinstance(samples, torch.Tensor):
return samples.detach().cpu().float().reshape(-1).numpy()
return np.asarray(samples, dtype=np.float32).reshape(-1)
@classmethod
def _normalize_ref_audio(cls, ref_audio: Any) -> tuple[np.ndarray, int]:
if isinstance(ref_audio, str):
raise TypeError("String ref_audio should be handled as a path before waveform normalization.")
if isinstance(ref_audio, dict):
sample_rate = ref_audio.get("sample_rate") or ref_audio.get("sampling_rate") or ref_audio.get("sr")
samples = None
for key in ("audio", "wav", "samples", "array", "waveform"):
if key in ref_audio and ref_audio[key] is not None:
samples = ref_audio[key]
break
if sample_rate is None or samples is None:
raise ValueError("ref_audio dict must contain waveform data and sample rate.")
return cls._normalize_audio_samples(samples), int(sample_rate)
if isinstance(ref_audio, (list, tuple)):
if len(ref_audio) == 1:
return cls._normalize_ref_audio(ref_audio[0])
if len(ref_audio) == 2 and np.isscalar(ref_audio[1]):
return cls._normalize_audio_samples(ref_audio[0]), int(ref_audio[1])
raise TypeError(f"Unsupported ref_audio format: {type(ref_audio)!r}")
@staticmethod
def _write_temp_prompt_wav(waveform: np.ndarray, sample_rate: int) -> str:
prompt_file = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
prompt_file.close()
wav = np.asarray(waveform, dtype=np.float32).reshape(-1)
wav = np.clip(wav, -1.0, 1.0)
pcm16 = (wav * 32767.0).astype(np.int16)
with wave.open(prompt_file.name, "wb") as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(int(sample_rate))
wav_file.writeframes(pcm16.tobytes())
return prompt_file.name
@classmethod
def _resolve_prompt_inputs(cls, info: dict[str, Any]) -> tuple[str | None, str | None, str | None]:
prompt_text = cls._extract_val(info, "prompt_text", None)
prompt_wav_path = cls._extract_val(info, "prompt_wav_path", None)
if prompt_wav_path:
if prompt_text is None:
prompt_text = cls._extract_val(info, "ref_text", None)
return prompt_wav_path, prompt_text, None
ref_audio = cls._extract_val(info, "ref_audio", None)
ref_text = cls._extract_val(info, "ref_text", None)
if ref_audio is None or ref_text is None:
return None, None, None
if isinstance(ref_audio, str):
return ref_audio, ref_text, None
waveform, sample_rate = cls._normalize_ref_audio(ref_audio)
temp_prompt_wav = cls._write_temp_prompt_wav(waveform, sample_rate)
return temp_prompt_wav, ref_text, temp_prompt_wav
def embed_input_ids(self, input_ids: torch.Tensor, **_: Any) -> torch.Tensor:
if input_ids.numel() == 0:
return torch.empty((0, 1), device=input_ids.device, dtype=torch.float32)
return torch.zeros((input_ids.shape[0], 1), device=input_ids.device, dtype=torch.float32)
def _get_vocab_size(self) -> int:
model_config = getattr(self.vllm_config, "model_config", None)
if model_config is not None:
getter = getattr(model_config, "get_vocab_size", None)
if callable(getter):
try:
return int(getter())
except Exception:
pass
hf_config = getattr(model_config, "hf_text_config", None)
if hf_config is not None and hasattr(hf_config, "vocab_size"):
return int(hf_config.vocab_size)
return 32000
def _make_empty_output(
self,
*,
output_key: str,
payload_factory: Callable[[], torch.Tensor],
infos: list[dict[str, Any]],
sample_rate: int,
out_device: torch.device,
out_dtype: torch.dtype,
hidden_rows: int | None = None,
) -> OmniOutput:
if hidden_rows is None:
hidden_rows = len(infos)
return OmniOutput(
text_hidden_states=torch.zeros((hidden_rows, 1), device=out_device, dtype=out_dtype),
multimodal_outputs={
output_key: [payload_factory() for _ in infos],
"sr": [torch.tensor(sample_rate, dtype=torch.int32) for _ in infos],
},
)
def _finalize_stage_output(
self,
*,
output_key: str,
outputs: list[torch.Tensor],
sample_rates: list[torch.Tensor],
out_device: torch.device,
out_dtype: torch.dtype,
hidden_rows: int | None = None,
) -> OmniOutput:
multimodal_outputs: dict[str, Any] = {output_key: outputs, "sr": sample_rates}
if hidden_rows is not None:
text_hidden_states = torch.zeros((hidden_rows, 1), device=out_device, dtype=out_dtype)
elif outputs:
outputs_tensor = torch.stack(outputs)
text_hidden_states = (
outputs_tensor.unsqueeze(-1)
if outputs_tensor.ndim == 1
else outputs_tensor.reshape(-1, outputs_tensor.shape[-1])
)
else:
text_hidden_states = torch.zeros((0, 1), device=out_device, dtype=out_dtype)
text_hidden_states = text_hidden_states.to(device=out_device, dtype=out_dtype)
return OmniOutput(
text_hidden_states=text_hidden_states,
multimodal_outputs=multimodal_outputs,
)
def _forward_vae_stage(
self,
infos: list[dict[str, Any]],
*,
sample_rate: int,
async_chunk: bool,
out_device: torch.device,
out_dtype: torch.dtype,
) -> OmniOutput:
if all(self._extract_val(info, "latent_audio_feat", None) is None for info in infos):
self._ar_emit_stop_token = True
return self._make_empty_output(
output_key="model_outputs",
payload_factory=lambda: torch.zeros((0,), dtype=torch.float32),
infos=infos,
sample_rate=sample_rate,
out_device=out_device,
out_dtype=out_dtype,
)
outputs: list[torch.Tensor] = []
sample_rates: list[torch.Tensor] = []
for info in infos:
latent_audio_feat = self._extract_val(info, "latent_audio_feat", None)
audio_tensor = self._pipeline.decode(latent_audio_feat, trim_streaming_patch=async_chunk)
outputs.append(audio_tensor.float().cpu())
sample_rates.append(torch.tensor(sample_rate, dtype=torch.int32))
self._ar_emit_stop_token = True
return self._finalize_stage_output(
output_key="model_outputs",
outputs=outputs,
sample_rates=sample_rates,
out_device=out_device,
out_dtype=out_dtype,
)
def _forward_latent_stage(
self,
infos: list[dict[str, Any]],
*,
sample_rate: int,
async_chunk: bool,
out_device: torch.device,
out_dtype: torch.dtype,
hidden_rows: int,
) -> OmniOutput:
texts = [self._extract_val(info, "text", "") for info in infos]
if all(not text for text in texts):
self._ar_emit_stop_token = True
return self._make_empty_output(
output_key="latent_audio_feat",
payload_factory=lambda: torch.zeros((0,), dtype=torch.float32),
infos=infos,
sample_rate=sample_rate,
out_device=out_device,
out_dtype=out_dtype,
hidden_rows=hidden_rows,
)
outputs: list[torch.Tensor] = []
sample_rates: list[torch.Tensor] = []
last_chunk_flags: list[bool] | None = [] if async_chunk else None
payload_finished_flags: list[bool] | None = [] if async_chunk else None
for info in infos:
text = self._extract_val(info, "text", "")
cfg_value = float(self._extract_val(info, "cfg_value", 2.0))
inference_timesteps = int(self._extract_val(info, "inference_timesteps", 10))
min_len = int(self._extract_val(info, "min_len", 2))
max_len = int(self._extract_val(info, "max_len", self._extract_val(info, "max_new_tokens", 4096)))
retry_badcase = bool(self._extract_val(info, "retry_badcase", True))
retry_badcase_max_times = int(self._extract_val(info, "retry_badcase_max_times", 3))
retry_badcase_ratio_threshold = float(self._extract_val(info, "retry_badcase_ratio_threshold", 6.0))
streaming_prefix_len = int(self._extract_val(info, "streaming_prefix_len", 3))
request_key = self._resolve_stream_request_key(info)
created_temp: str | None = None
if async_chunk:
terminal_pending = self._latent_stream_terminal_pending.get(request_key, 0)
if terminal_pending > 0:
outputs.append(torch.zeros((0,), dtype=torch.float32))
assert last_chunk_flags is not None
last_chunk_flags.append(True)
assert payload_finished_flags is not None
payload_finished_flags.append(terminal_pending == 1)
if terminal_pending == 1:
self._latent_stream_terminal_pending.pop(request_key, None)
else:
self._latent_stream_terminal_pending[request_key] = terminal_pending - 1
sample_rates.append(torch.tensor(sample_rate, dtype=torch.int32))
continue
if request_key in self._latent_stream_completed:
outputs.append(torch.zeros((0,), dtype=torch.float32))
assert last_chunk_flags is not None
last_chunk_flags.append(True)
assert payload_finished_flags is not None
payload_finished_flags.append(False)
sample_rates.append(torch.tensor(sample_rate, dtype=torch.int32))
continue
if request_key not in self._latent_stream_gens:
prompt_wav_path, prompt_text, temp_prompt_wav = self._resolve_prompt_inputs(info)
created_temp = temp_prompt_wav
self._latent_stream_gens[request_key] = self._pipeline.iter_latent_chunks_streaming(
text=text,
prompt_wav_path=prompt_wav_path,
prompt_text=prompt_text,
cfg_value=cfg_value,
inference_timesteps=inference_timesteps,
min_len=min_len,
max_len=max_len,
streaming_prefix_len=streaming_prefix_len,
retry_badcase=False,
retry_badcase_max_times=retry_badcase_max_times,
retry_badcase_ratio_threshold=retry_badcase_ratio_threshold,
)
generator = self._latent_stream_gens[request_key]
try:
chunk_latent, is_last = next(generator)
except StopIteration:
self._latent_stream_gens.pop(request_key, None)
self._latent_stream_terminal_pending[request_key] = 1
self._latent_stream_completed.add(request_key)
outputs.append(torch.zeros((0,), dtype=torch.float32))
assert last_chunk_flags is not None
last_chunk_flags.append(True)
assert payload_finished_flags is not None
payload_finished_flags.append(True)
else:
if is_last:
self._latent_stream_gens.pop(request_key, None)
self._latent_stream_terminal_pending[request_key] = 1
self._latent_stream_completed.add(request_key)
outputs.append(chunk_latent.detach().float().cpu())
assert last_chunk_flags is not None
last_chunk_flags.append(bool(is_last))
assert payload_finished_flags is not None
payload_finished_flags.append(False)
finally:
if created_temp is not None and os.path.exists(created_temp):
os.unlink(created_temp)
sample_rates.append(torch.tensor(sample_rate, dtype=torch.int32))
continue
prompt_wav_path, prompt_text, temp_prompt_wav = self._resolve_prompt_inputs(info)
try:
latent_audio_feat = self._pipeline.generate_latents(
text=text,
prompt_wav_path=prompt_wav_path,
prompt_text=prompt_text,
cfg_value=cfg_value,
inference_timesteps=inference_timesteps,
min_len=min_len,
max_len=max_len,
retry_badcase=retry_badcase,
retry_badcase_max_times=retry_badcase_max_times,
retry_badcase_ratio_threshold=retry_badcase_ratio_threshold,
)
outputs.append(latent_audio_feat.float().cpu())
finally:
if temp_prompt_wav is not None and os.path.exists(temp_prompt_wav):
os.unlink(temp_prompt_wav)
sample_rates.append(torch.tensor(sample_rate, dtype=torch.int32))
self._ar_emit_stop_token = all(last_chunk_flags) if async_chunk and last_chunk_flags else True
output = self._finalize_stage_output(
output_key="latent_audio_feat",
outputs=outputs,
sample_rates=sample_rates,
out_device=out_device,
out_dtype=out_dtype,
hidden_rows=hidden_rows,
)
if async_chunk and payload_finished_flags is not None:
output.multimodal_outputs["finished"] = [
torch.tensor(flag, dtype=torch.bool) for flag in payload_finished_flags
]
return output
def compute_logits(self, hidden_states: torch.Tensor | OmniOutput, sampling_metadata: Any = None) -> torch.Tensor:
del sampling_metadata
if isinstance(hidden_states, OmniOutput):
hidden_states = hidden_states.text_hidden_states
if hidden_states is None:
device, dtype = self._runner_hidden_device_dtype()
hidden_states = torch.zeros((0, 1), device=device, dtype=dtype)
if hidden_states.ndim == 1:
hidden_states = hidden_states.unsqueeze(-1)
elif hidden_states.ndim > 2:
hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1])
vocab_size = self._get_vocab_size()
num_rows = int(hidden_states.shape[0])
logits = torch.zeros((num_rows, vocab_size), dtype=torch.float32, device=hidden_states.device)
eos_id = 2 if vocab_size > 2 else 0
safe_id = 1 if vocab_size > 1 and 1 != eos_id else 0
emit_stop = getattr(self, "_ar_emit_stop_token", True)
if num_rows > 0:
if emit_stop:
logits[:, eos_id] = 1.0e6
else:
logits[:, eos_id] = -1.0e9
logits[:, safe_id] = 1.0e6
return logits
@torch.no_grad()
def forward(
self,
input_ids: torch.Tensor | None = None,
positions: torch.Tensor | None = None,
intermediate_tensors: Any = None,
inputs_embeds: torch.Tensor | None = None,
runtime_additional_information: list[dict[str, Any]] | None = None,
model_intermediate_buffer: list[dict[str, Any]] | None = None,
**kwargs: Any,
) -> OmniOutput:
del positions, intermediate_tensors, inputs_embeds, kwargs
self._ensure_model_loaded()
out_device, out_dtype = self._runner_hidden_device_dtype()
if input_ids is not None and input_ids.device.type == out_device.type:
out_device = input_ids.device
infos = model_intermediate_buffer or runtime_additional_information or [{}]
hidden_rows = len(infos)
if input_ids is not None and len(input_ids.shape) > 0:
hidden_rows = max(hidden_rows, int(input_ids.shape[0]))
sample_rate = int(getattr(self._pipeline, "sample_rate", 24000))
async_chunk = bool(getattr(self.vllm_config.model_config, "async_chunk", False))
if self.model_stage in self._VAE_STAGES:
infos = self._maybe_recover_vae_infos(infos, input_ids, async_chunk=async_chunk)
return self._forward_vae_stage(
infos,
sample_rate=sample_rate,
async_chunk=async_chunk,
out_device=out_device,
out_dtype=out_dtype,
)
if self.model_stage in self._LATENT_STAGES:
return self._forward_latent_stage(
infos,
sample_rate=sample_rate,
async_chunk=async_chunk,
out_device=out_device,
out_dtype=out_dtype,
hidden_rows=hidden_rows,
)
raise ValueError(f"Unsupported VoxCPM model_stage at runtime: {self.model_stage}")
def make_empty_intermediate_tensors(
self, batch_size: int, dtype: torch.dtype, device: torch.device
) -> IntermediateTensors:
del batch_size, dtype, device
return {}
__all__ = ["VoxCPMForConditionalGeneration"]
@@ -1,247 +0,0 @@
from __future__ import annotations
import importlib
import json
import os
import shutil
import sys
import tempfile
from contextlib import contextmanager
from hashlib import sha256
from pathlib import Path
from typing import Any
from unittest.mock import patch
import numpy as np
import torch
from vllm.config import VllmConfig
from vllm.logger import init_logger
logger = init_logger(__name__)
def _iter_voxcpm_src_candidates() -> list[Path]:
candidates: list[Path] = []
env_path = os.environ.get("VLLM_OMNI_VOXCPM_CODE_PATH")
if env_path:
candidates.append(Path(env_path).expanduser())
repo_root = Path(__file__).resolve().parents[4]
candidates.append(repo_root.parent / "VoxCPM" / "src")
unique_candidates: list[Path] = []
seen: set[str] = set()
for candidate in candidates:
candidate_key = str(candidate)
if candidate_key in seen:
continue
seen.add(candidate_key)
unique_candidates.append(candidate)
return unique_candidates
def _prepend_voxcpm_src(candidate: Path) -> None:
candidate_str = str(candidate)
if candidate_str not in sys.path:
sys.path.insert(0, candidate_str)
def _import_voxcpm_attrs(module_name: str, *attr_names: str) -> tuple[Any, ...]:
last_exc: ImportError | None = None
for candidate in _iter_voxcpm_src_candidates():
if not candidate.exists():
continue
_prepend_voxcpm_src(candidate)
try:
module = importlib.import_module(module_name)
return tuple(getattr(module, attr_name) for attr_name in attr_names)
except ImportError as exc:
last_exc = exc
try:
module = importlib.import_module(module_name)
return tuple(getattr(module, attr_name) for attr_name in attr_names)
except ImportError as exc:
last_exc = exc
raise ImportError(f"Failed to import {module_name}.") from last_exc
def _import_voxcpm_base_model_class():
"""Import upstream ``VoxCPMModel`` from ``VoxCPM/src/voxcpm`` (env, sibling tree, or pip)."""
try:
(VoxCPMModel,) = _import_voxcpm_attrs("voxcpm.model.voxcpm", "VoxCPMModel")
return VoxCPMModel
except ImportError as exc:
raise ImportError(
"Failed to import VoxCPMModel. Install the `voxcpm` package or set "
"`VLLM_OMNI_VOXCPM_CODE_PATH` to the VoxCPM repository `src` directory "
"(the parent of the `voxcpm` package that contains `model/` and `modules/`)."
) from exc
def _import_voxcpm_audio_vae_classes():
try:
return _import_voxcpm_attrs("voxcpm.modules.audiovae", "AudioVAE", "AudioVAEConfig")
except ImportError as exc:
raise ImportError(
"Failed to import VoxCPM AudioVAE. Install the `voxcpm` package or set "
"`VLLM_OMNI_VOXCPM_CODE_PATH` to the VoxCPM repository `src` directory."
) from exc
def _device_to_string(device: torch.device) -> str:
if device.index is None:
return device.type
return f"{device.type}:{device.index}"
def _normalize_dtype_name(dtype: Any) -> str | None:
if dtype is None:
return None
if isinstance(dtype, torch.dtype):
mapping = {
torch.bfloat16: "bfloat16",
torch.float16: "float16",
torch.float32: "float32",
}
return mapping.get(dtype, str(dtype).removeprefix("torch."))
dtype_str = str(dtype)
return dtype_str.removeprefix("torch.")
def _resolve_runtime_device(vllm_config: VllmConfig) -> torch.device:
try:
from vllm_omni.platforms import current_omni_platform
return current_omni_platform.get_torch_device()
except Exception:
pass
device = getattr(getattr(vllm_config, "device_config", None), "device", None)
if isinstance(device, torch.device):
return device
if device:
return torch.device(device)
return torch.device("cpu")
def _prepare_runtime_model_dir(
model_path: str | Path,
*,
target_device: torch.device,
target_dtype: str | None,
) -> str:
source_dir = Path(model_path)
config_path = source_dir / "config.json"
if not config_path.exists():
return str(source_dir)
config_text = config_path.read_text()
config_dict = json.loads(config_text)
desired_device = target_device.type
desired_dtype = target_dtype or config_dict.get("dtype")
if config_dict.get("device") == desired_device and config_dict.get("dtype") == desired_dtype:
return str(source_dir)
digest = sha256(f"{source_dir.resolve()}:{config_text}:{desired_device}:{desired_dtype}".encode()).hexdigest()[:16]
runtime_dir = Path(tempfile.gettempdir()) / "vllm_omni_voxcpm_runtime" / digest
runtime_dir.mkdir(parents=True, exist_ok=True)
for entry in source_dir.iterdir():
target = runtime_dir / entry.name
if entry.name == "config.json" or target.exists():
continue
try:
target.symlink_to(entry, target_is_directory=entry.is_dir())
except OSError as exc:
logger.warning(
"Falling back to copying VoxCPM runtime artifact %s into %s because symlink creation failed: %s",
entry,
runtime_dir,
exc,
)
if entry.is_dir():
shutil.copytree(entry, target, dirs_exist_ok=True)
else:
shutil.copy2(entry, target)
patched_config = dict(config_dict)
patched_config["device"] = desired_device
if desired_dtype is not None:
patched_config["dtype"] = desired_dtype
(runtime_dir / "config.json").write_text(json.dumps(patched_config, indent=2, sort_keys=True))
return str(runtime_dir)
@contextmanager
def _force_cuda_available_for_npu(device: torch.device):
if device.type != "npu":
yield
return
with patch("torch.cuda.is_available", return_value=True):
yield
def _is_torchcodec_load_error(exc: BaseException) -> bool:
message = str(exc).lower()
return "torchcodec" in message or "load_with_torchcodec" in message
def _load_audio_with_soundfile(
prompt_wav_path: str,
*,
sample_rate: int,
) -> torch.Tensor:
try:
import soundfile as sf
except ImportError:
raise
audio_np, source_sr = sf.read(prompt_wav_path, dtype="float32", always_2d=True)
audio = torch.from_numpy(np.ascontiguousarray(audio_np.T))
if audio.size(0) > 1:
audio = audio.mean(dim=0, keepdim=True)
if int(source_sr) != int(sample_rate):
try:
import torchaudio
except ImportError as exc:
raise ImportError("torchaudio is required for resampling prompt audio.") from exc
audio = torchaudio.functional.resample(audio, int(source_sr), int(sample_rate))
return audio
def _build_prompt_cache_with_soundfile(model: Any, *args: Any, **kwargs: Any) -> dict[str, Any]:
if args:
prompt_text = args[0]
prompt_wav_path = args[1] if len(args) > 1 else kwargs.get("prompt_wav_path")
else:
prompt_text = kwargs.get("prompt_text")
prompt_wav_path = kwargs.get("prompt_wav_path")
if not prompt_text or not prompt_wav_path:
raise ValueError("prompt_text and prompt_wav_path are required")
audio = _load_audio_with_soundfile(prompt_wav_path, sample_rate=int(model.sample_rate))
patch_len = model.patch_size * model.chunk_size
if audio.size(1) % patch_len != 0:
padding_size = patch_len - audio.size(1) % patch_len
audio = torch.nn.functional.pad(audio, (padding_size, 0))
audio_feat = model.audio_vae.encode(audio.to(model.device), model.sample_rate).cpu()
audio_feat = audio_feat.view(
model.audio_vae.latent_dim,
-1,
model.patch_size,
).permute(1, 2, 0)
return {
"prompt_text": prompt_text,
"audio_feat": audio_feat,
}
@@ -1,44 +0,0 @@
from __future__ import annotations
import json
import shutil
from pathlib import Path
def resolve_voxcpm_model_dir(model: str) -> Path:
model_path = Path(model).expanduser()
if model_path.exists():
return model_path
from huggingface_hub import snapshot_download
return Path(snapshot_download(repo_id=model))
def prepare_voxcpm_hf_config_dir(model_dir: str | Path, hf_config_dir: str | Path) -> Path:
model_dir = Path(model_dir).expanduser()
hf_config_dir = Path(hf_config_dir).expanduser()
hf_config_dir.mkdir(parents=True, exist_ok=True)
source_config_path = model_dir / "config.json"
if not source_config_path.exists():
raise FileNotFoundError(f"VoxCPM config.json not found under {model_dir}")
config_path = hf_config_dir / "config.json"
shutil.copy2(source_config_path, config_path)
source_generation_config_path = model_dir / "generation_config.json"
if source_generation_config_path.exists():
shutil.copy2(source_generation_config_path, hf_config_dir / "generation_config.json")
config_dict = json.loads(config_path.read_text(encoding="utf-8"))
config_dict["model_type"] = "voxcpm"
config_dict.setdefault("architectures", ["VoxCPMForConditionalGeneration"])
config_path.write_text(json.dumps(config_dict, indent=2, ensure_ascii=False), encoding="utf-8")
return hf_config_dir
__all__ = [
"prepare_voxcpm_hf_config_dir",
"resolve_voxcpm_model_dir",
]
@@ -1,185 +0,0 @@
from __future__ import annotations
import os
from collections.abc import Generator
from typing import Any
import torch
import torch.nn as nn
from einops import rearrange
class _DirectVoxCPMLatentGenerator:
def __init__(self, tts_model: Any):
self.tts_model = tts_model
self.sample_rate = int(getattr(tts_model, "sample_rate", 24000))
def generate_latents(
self,
*,
text: str,
prompt_wav_path: str | None = None,
prompt_text: str | None = None,
cfg_value: float = 2.0,
inference_timesteps: int = 10,
min_len: int = 2,
max_len: int = 4096,
retry_badcase: bool = True,
retry_badcase_max_times: int = 3,
retry_badcase_ratio_threshold: float = 6.0,
) -> torch.Tensor:
if not isinstance(text, str) or not text.strip():
raise ValueError("target text must be a non-empty string")
if (prompt_wav_path is None) != (prompt_text is None):
raise ValueError("prompt_wav_path and prompt_text must both be provided or both be None")
if prompt_wav_path is not None and not os.path.exists(prompt_wav_path):
raise FileNotFoundError(f"prompt_wav_path does not exist: {prompt_wav_path}")
prompt_cache = None
if prompt_wav_path is not None and prompt_text is not None:
prompt_cache = self.tts_model.build_prompt_cache(
prompt_text=prompt_text,
prompt_wav_path=prompt_wav_path,
)
gen_kw = dict(
target_text=" ".join(text.split()),
prompt_cache=prompt_cache,
min_len=min_len,
max_len=max_len,
inference_timesteps=inference_timesteps,
cfg_value=cfg_value,
retry_badcase=retry_badcase,
retry_badcase_max_times=retry_badcase_max_times,
retry_badcase_ratio_threshold=retry_badcase_ratio_threshold,
)
latent_entry = getattr(self.tts_model, "generate_latents_with_prompt_cache", None)
if latent_entry is not None:
_, _, pred_audio_feat = latent_entry(**gen_kw)
else:
try:
_, _, pred_audio_feat = self.tts_model.generate_with_prompt_cache(
**gen_kw,
latents_only=True,
)
except TypeError:
_, _, pred_audio_feat = self.tts_model.generate_with_prompt_cache(**gen_kw)
return pred_audio_feat.detach().cpu().to(torch.float32)
def iter_latent_chunks_streaming(
self,
*,
text: str,
prompt_wav_path: str | None = None,
prompt_text: str | None = None,
cfg_value: float = 2.0,
inference_timesteps: int = 10,
min_len: int = 2,
max_len: int = 4096,
streaming_prefix_len: int = 3,
retry_badcase: bool = False,
retry_badcase_max_times: int = 3,
retry_badcase_ratio_threshold: float = 6.0,
) -> Generator[tuple[torch.Tensor, bool], None, None]:
"""Yield ``(latent_window, is_last_chunk)`` for Omni async_chunk latent to VAE."""
if not isinstance(text, str) or not text.strip():
raise ValueError("target text must be a non-empty string")
if (prompt_wav_path is None) != (prompt_text is None):
raise ValueError("prompt_wav_path and prompt_text must both be provided or both be None")
if prompt_wav_path is not None and not os.path.exists(prompt_wav_path):
raise FileNotFoundError(f"prompt_wav_path does not exist: {prompt_wav_path}")
prompt_cache = None
if prompt_wav_path is not None and prompt_text is not None:
prompt_cache = self.tts_model.build_prompt_cache(
prompt_text=prompt_text,
prompt_wav_path=prompt_wav_path,
)
gen_kw = dict(
target_text=" ".join(text.split()),
prompt_cache=prompt_cache,
min_len=min_len,
max_len=max_len,
inference_timesteps=inference_timesteps,
cfg_value=cfg_value,
retry_badcase=retry_badcase,
retry_badcase_max_times=retry_badcase_max_times,
retry_badcase_ratio_threshold=retry_badcase_ratio_threshold,
streaming_prefix_len=streaming_prefix_len,
)
stream_entry = getattr(self.tts_model, "generate_latents_with_prompt_cache_streaming", None)
if stream_entry is not None:
gen = stream_entry(**gen_kw)
else:
fallback_stream_entry = getattr(self.tts_model, "generate_with_prompt_cache_streaming", None)
if fallback_stream_entry is not None:
gen = fallback_stream_entry(**gen_kw, latents_only=True)
else:
gen = self.tts_model._generate_with_prompt_cache(streaming=True, latents_only=True, **gen_kw)
iterator = iter(gen)
previous = next(iterator, None)
while previous is not None:
current = next(iterator, None)
_, _target_tok, chunk_latent = previous
if not isinstance(chunk_latent, torch.Tensor):
chunk_latent = torch.as_tensor(chunk_latent)
yield chunk_latent, current is None
previous = current
class _DirectVoxCPMAudioVAE:
def __init__(self, audio_vae: nn.Module, *, patch_size: int = 2):
self.audio_vae = audio_vae
self.sample_rate = int(getattr(audio_vae, "sample_rate", 24000))
self.latent_dim = int(getattr(audio_vae, "latent_dim", 64))
self.patch_size = int(patch_size)
self._chunk_size = int(getattr(audio_vae, "chunk_size", 1))
self._stream_audio_patch_samples = max(1, self.patch_size * self._chunk_size)
def _prepare_latents_for_decode(self, latent_audio_feat: Any) -> torch.Tensor:
latents = latent_audio_feat
if not isinstance(latents, torch.Tensor):
latents = torch.tensor(latents, dtype=torch.float32)
latents = latents.detach().to(torch.float32)
if latents.ndim == 3:
if latents.shape[-1] == self.latent_dim:
latents = rearrange(latents, "t p d -> 1 d (t p)")
elif latents.shape[1] == self.latent_dim:
latents = latents.contiguous()
else:
raise ValueError(f"Unsupported latent_audio_feat shape: {tuple(latents.shape)}")
elif latents.ndim == 2:
if latents.shape[0] == self.latent_dim:
latents = latents.unsqueeze(0)
elif latents.shape[1] == self.latent_dim:
latents = rearrange(latents, "t d -> 1 d t")
else:
raise ValueError(f"Unsupported latent_audio_feat shape: {tuple(latents.shape)}")
else:
raise ValueError(f"Unsupported latent_audio_feat ndim: {latents.ndim}")
return latents
@torch.no_grad()
def decode(self, latent_audio_feat: Any, *, trim_streaming_patch: bool = False) -> torch.Tensor:
latents = self._prepare_latents_for_decode(latent_audio_feat)
device = next(self.audio_vae.parameters()).device
raw = self.audio_vae.decode(latents.to(device=device, dtype=torch.float32))
if isinstance(raw, dict):
audio = raw.get("audio")
if audio is None:
audio = next(v for v in raw.values() if isinstance(v, torch.Tensor))
else:
audio = raw
if audio.dim() == 3:
stream = audio.squeeze(1)
elif audio.dim() == 2:
stream = audio
else:
stream = audio.reshape(audio.shape[0], -1)
if trim_streaming_patch:
stream = stream[..., -self._stream_audio_patch_samples :]
return stream.reshape(-1).detach().cpu().to(torch.float32)
@@ -31,6 +31,7 @@ from vllm.model_executor.models.utils import (
maybe_prefix,
)
from vllm.multimodal.audio import AudioResampler
from vllm.platforms import current_platform
from vllm.sequence import IntermediateTensors
from vllm_omni.model_executor.models.output_templates import OmniOutput
@@ -456,7 +457,6 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
self._scaffold_graphs: dict[int, _CapturedGraph] = {}
self._residual_graphs: dict[int, _CapturedGraph] = {}
self._max_cached_graphs = self._max_batch_size
self._cuda_graph_pool: tuple | None = None
self._cuda_graph_warmup_steps = 0
self._cuda_graph_warmup_threshold = 3
@@ -661,11 +661,6 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
tts = self.tts
return tts.stop_head(tts.stop_actn(tts.stop_proj(lm_h)))
def _get_cuda_graph_pool(self) -> tuple:
if self._cuda_graph_pool is None:
self._cuda_graph_pool = torch.cuda.graph_pool_handle()
return self._cuda_graph_pool
@staticmethod
def _nullify_volatile_metadata(ctx: Any) -> Any:
"""Set ``scheduler_metadata`` to None on all attention layers.
@@ -698,7 +693,6 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
hidden_size = self.config.hidden_size
dtype = self._side_dtype
dev = torch.device(self._device)
pool = self._get_cuda_graph_pool()
model.precompute_fused_qkv()
@@ -721,7 +715,7 @@ class VoxCPM2TalkerForConditionalGeneration(nn.Module):
for _ in range(3):
_ = model(**call_kwargs)
with torch.cuda.graph(g.graph, pool=pool):
with torch.cuda.graph(g.graph, pool=current_platform.get_global_graph_pool()):
g.output = model(**call_kwargs)
logger.info("CUDA Graph captured for %s (batch_size=%d)", label, batch_size)
@@ -0,0 +1,61 @@
# 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: 30
codec_left_context_frames: 40
stages:
- stage_id: 0
max_num_seqs: 1
gpu_memory_utilization: 0.5
enforce_eager: true
trust_remote_code: true
enable_prefix_caching: false
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.4
enforce_eager: true
trust_remote_code: true
enable_prefix_caching: false
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
@@ -1,95 +0,0 @@
async_chunk: true
stage_args:
- stage_id: 0
stage_type: llm
is_comprehension: true
runtime:
devices: "0"
engine_args:
model_stage: qwen3_tts
max_num_seqs: 10
model_arch: Qwen3TTSTalkerForConditionalGeneration
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
enforce_eager: false
trust_remote_code: true
async_scheduling: true
enable_prefix_caching: false
engine_output_type: latent
gpu_memory_utilization: 0.3
max_num_batched_tokens: 512
max_model_len: 4096
custom_process_next_stage_input_func: vllm_omni.model_executor.stage_input_processors.qwen3_tts.talker2code2wav_async_chunk
# Use named connector to apply runtime.connectors.extra.
output_connectors:
to_stage_1: connector_of_shared_memory
default_sampling_params:
temperature: 0.9
top_k: 50
max_tokens: 4096
seed: 42
detokenize: false
repetition_penalty: 1.05
stop_token_ids: [2150]
- stage_id: 1
stage_type: llm
runtime:
devices: "0"
engine_args:
model_stage: code2wav
max_num_seqs: 10
model_arch: Qwen3TTSCode2Wav
worker_type: generation
scheduler_cls: vllm_omni.core.sched.omni_generation_scheduler.OmniGenerationScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: true
enable_prefix_caching: false
engine_output_type: audio
gpu_memory_utilization: 0.3
# 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 accumulated flat codec stream.
max_model_len: 65536
engine_input_source: [0]
final_output: true
final_output_type: audio
# Distributed connector configuration
input_connectors:
from_stage_0: connector_of_shared_memory
tts_args:
max_instructions_length: 500
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 65536
seed: 42
detokenize: true
repetition_penalty: 1.0
runtime:
enabled: true
connectors:
connector_of_shared_memory:
name: SharedMemoryConnector
extra:
shm_threshold_bytes: 65536
# Frame-aligned codec streaming transport.
codec_streaming: true
# Connector polling / timeout (unit: loop count, sleep interval in seconds).
connector_get_sleep_s: 0.01
connector_get_max_wait_first_chunk: 3000
connector_get_max_wait: 300
# Match the decoder sliding attention window to avoid chunk-boundary noise.
codec_chunk_frames: 25
codec_left_context_frames: 72
# Emit only the first audio chunk early, then return to codec_chunk_frames.
initial_codec_chunk_frames: 1
edges:
- from: 0
to: 1
@@ -1,98 +0,0 @@
# VoxCPM two-stage streaming (align with qwen3_tts.yaml async_chunk pattern).
# Stage0 (latent_generator) emits latent in time chunks; Stage1 (VAE) decodes as chunks arrive.
async_chunk: true
stage_args:
- stage_id: 0
stage_type: llm
is_comprehension: true
runtime:
devices: "0"
max_batch_size: 1
engine_args:
dtype: bfloat16
model_stage: latent_generator
model_arch: VoxCPMForConditionalGeneration
# Optional persistent HF-compatible config dir for native VoxCPM models.
hf_config_path: ${oc.env:VLLM_OMNI_VOXCPM_HF_CONFIG_PATH,}
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: true
enable_prefix_caching: false
engine_output_type: latent
gpu_memory_utilization: 0.7
distributed_executor_backend: "mp"
max_num_batched_tokens: 4096
max_model_len: 4096
custom_process_next_stage_input_func: vllm_omni.model_executor.stage_input_processors.voxcpm.latent2vae_async_chunk
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 4096
stop_token_ids: [2]
seed: 42
detokenize: false
repetition_penalty: 1.0
final_output: false
output_connectors:
to_stage_1: voxcpm_shm
- stage_id: 1
stage_type: llm
runtime:
devices: "0"
max_batch_size: 1
engine_args:
dtype: float32
model_stage: vae
model_arch: VoxCPMForConditionalGeneration
hf_config_path: ${oc.env:VLLM_OMNI_VOXCPM_HF_CONFIG_PATH,}
worker_type: generation
scheduler_cls: vllm_omni.core.sched.omni_generation_scheduler.OmniGenerationScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: false
enable_prefix_caching: false
engine_output_type: audio
gpu_memory_utilization: 0.15
distributed_executor_backend: "mp"
max_num_batched_tokens: 8192
max_model_len: 4096
engine_input_source: [0]
final_output: true
final_output_type: audio
input_connectors:
from_stage_0: voxcpm_shm
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 128
seed: 42
detokenize: true
repetition_penalty: 1.0
runtime:
enabled: true
connectors:
voxcpm_shm:
name: SharedMemoryConnector
extra:
shm_threshold_bytes: 65536
# Frame-aligned codec streaming transport.
codec_streaming: true
# Connector polling / timeout (unit: loop count, sleep interval in seconds).
connector_get_sleep_s: 0.01
connector_get_max_wait_first_chunk: 3000
connector_get_max_wait: 300
# Align with Omni: small chunks with sufficient context overlap.
codec_chunk_frames: 1
codec_left_context_frames: 1
edges:
- from: 0
to: 1
@@ -23,6 +23,16 @@ logger = init_logger(__name__)
# example ``examples/offline_inference/mimo_audio/end2end.py``.
MAX_CODE2WAV_TOKENS = 18192
# Minimum safe values for codec streaming parameters.
# codec_left_context_frames must cover the vocoder attention window
# (vocoder_attn_window_size defaults to [40, 10]). Values below the minimum
# cause acoustic-state resets at chunk boundaries, producing voice instability
# (multiple speakers / timbre shifts in the output audio).
_MIN_CODEC_CHUNK_FRAMES = 3
_MIN_CODEC_LEFT_CONTEXT_FRAMES = 40
_DEFAULT_CODEC_CHUNK_FRAMES = 10
_DEFAULT_CODEC_LEFT_CONTEXT_FRAMES = 40
def prepend_and_flatten_colmajor(x: torch.Tensor, pad_vec: torch.Tensor) -> torch.Tensor:
"""
@@ -80,6 +90,10 @@ def _flush_remaining_codes(
length = len(accumulated)
chunk_length = length % chunk_size
# When the accumulated length aligns with chunk_size boundary (remainder == 0),
# we still need to flush the final chunk with full context to give the vocoder
# enough attention window — otherwise the tail audio cuts off and produces
# voice instability. Fall back to chunk_size as the context length.
context_length = chunk_length if chunk_length != 0 else chunk_size
end_index = min(length, left_context_size + context_length)
@@ -136,8 +150,26 @@ def llm2code2wav_async_chunk(
connector = getattr(transfer_manager, "connector", None)
raw_cfg = getattr(connector, "config", {}) or {}
cfg = raw_cfg.get("extra", raw_cfg) if isinstance(raw_cfg, dict) else {}
chunk_size = int(cfg.get("codec_chunk_frames", 3))
left_context_size = int(cfg.get("codec_left_context_frames", 3))
chunk_size = int(cfg.get("codec_chunk_frames", _DEFAULT_CODEC_CHUNK_FRAMES))
if chunk_size < _MIN_CODEC_CHUNK_FRAMES:
logger.warning(
"codec_chunk_frames=%d is below minimum %d; falling back to %d.",
chunk_size,
_MIN_CODEC_CHUNK_FRAMES,
_DEFAULT_CODEC_CHUNK_FRAMES,
)
chunk_size = _DEFAULT_CODEC_CHUNK_FRAMES
left_context_size = int(cfg.get("codec_left_context_frames", _DEFAULT_CODEC_LEFT_CONTEXT_FRAMES))
if left_context_size < _MIN_CODEC_LEFT_CONTEXT_FRAMES:
logger.warning(
"codec_left_context_frames=%d is below minimum %d (must cover vocoder attention window); "
"falling back to %d to prevent voice instability.",
left_context_size,
_MIN_CODEC_LEFT_CONTEXT_FRAMES,
_DEFAULT_CODEC_LEFT_CONTEXT_FRAMES,
)
left_context_size = _DEFAULT_CODEC_LEFT_CONTEXT_FRAMES
request_id = getattr(request, "external_req_id", None)
@@ -157,11 +189,6 @@ def llm2code2wav_async_chunk(
pad_vec = torch.tensor([TALKER_CODEC_PAD_TOKEN_ID] * 4, device=code_tensor.device, dtype=code_tensor.dtype)
code_list = prepend_and_flatten_colmajor(code_tensor, pad_vec).tolist()
if sum(code_list) == 0:
if is_finished:
return _flush_remaining_codes(transfer_manager, request_id, chunk_size, left_context_size)
return None
if request_id is None:
return None
@@ -1,115 +0,0 @@
from __future__ import annotations
from typing import Any
import torch
from vllm.inputs import TextPrompt
from vllm_omni.data_entry_keys import (
CodesStruct,
MetaStruct,
OmniPayloadStruct,
)
from vllm_omni.inputs.data import OmniTokensPrompt
_VOXCPM_LATENT_MAGIC = 131071
def _serialize_latent_to_codes(latent: Any) -> list[int]:
latent_tensor = latent if isinstance(latent, torch.Tensor) else torch.as_tensor(latent)
latent_tensor = latent_tensor.detach().cpu().contiguous()
if latent_tensor.ndim == 3:
if latent_tensor.shape[0] != 1:
raise ValueError(f"Expected batch=1 latent tensor, got shape={tuple(latent_tensor.shape)}")
latent_tensor = latent_tensor.squeeze(0)
if latent_tensor.ndim != 2:
raise ValueError(f"Unsupported latent_audio_feat shape for async chunk: {tuple(latent_tensor.shape)}")
latent_dim, time_dim = int(latent_tensor.shape[0]), int(latent_tensor.shape[1])
packed = latent_tensor.to(torch.bfloat16).contiguous().view(torch.uint16).reshape(-1).to(torch.int32)
return [_VOXCPM_LATENT_MAGIC, latent_dim, time_dim, *packed.tolist()]
def _coerce_finished_flag(value: Any) -> bool:
"""Normalize VoxCPM async-chunk finished markers to a Python bool."""
if value is None:
return False
if isinstance(value, torch.Tensor):
if value.numel() != 1:
raise ValueError(f"finished tensor must be scalar, got shape={tuple(value.shape)}")
return bool(value.detach().cpu().item())
if isinstance(value, (list, tuple)):
if not value:
return False
if len(value) != 1:
raise ValueError(f"finished container must have one element, got len={len(value)}")
return _coerce_finished_flag(value[0])
return bool(value)
def latent2vae(
source_outputs: list[Any],
_prompt: OmniTokensPrompt | TextPrompt | None = None,
_requires_multimodal_data: bool = False,
) -> list[OmniTokensPrompt]:
vae_inputs: list[OmniTokensPrompt] = []
for source_output in source_outputs:
output = source_output.outputs[0]
multimodal_output = getattr(output, "multimodal_output", None)
if not isinstance(multimodal_output, dict) or "latent_audio_feat" not in multimodal_output:
raise ValueError(
"VoxCPM latent stage output missing 'latent_audio_feat'. "
f"request_id={getattr(source_output, 'request_id', None)}"
)
additional_information = {
"latent_audio_feat": multimodal_output["latent_audio_feat"],
}
if "sr" in multimodal_output:
additional_information["sample_rate"] = [int(multimodal_output["sr"])]
vae_inputs.append(
OmniTokensPrompt(
prompt_token_ids=[0],
additional_information=additional_information,
multi_modal_data=None,
mm_processor_kwargs=None,
)
)
return vae_inputs
def _eof_payload() -> OmniPayloadStruct:
return OmniPayloadStruct(
codes=CodesStruct(audio=torch.empty(0, dtype=torch.long)),
meta=MetaStruct(finished=torch.tensor(True, dtype=torch.bool)),
)
def latent2vae_async_chunk(
transfer_manager: Any,
pooling_output: dict[str, Any] | None,
request: Any,
is_finished: bool = False,
) -> OmniPayloadStruct | None:
"""Stage-0 latent → stage-1 VAE under ``async_chunk`` (connector payload)."""
# Kept for callback signature compatibility with OmniChunkTransferAdapter.
_ = transfer_manager
finished_request = _coerce_finished_flag(is_finished)
if callable(getattr(request, "is_finished", None)):
finished_request = finished_request or _coerce_finished_flag(request.is_finished())
if not isinstance(pooling_output, dict):
return _eof_payload() if finished_request else None
latent = pooling_output.get("latent_audio_feat")
if isinstance(latent, torch.Tensor) and latent.numel() == 0:
latent = None
if latent is None:
return _eof_payload() if finished_request else None
serialized_codes = _serialize_latent_to_codes(latent)
return OmniPayloadStruct(
codes=CodesStruct(audio=torch.tensor(serialized_codes, dtype=torch.long)),
meta=MetaStruct(finished=torch.tensor(finished_request, dtype=torch.bool)),
)
@@ -0,0 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
try:
from vllm_omni.platforms.npu.omni_connectors.yuanrong_transfer_engine_connector import (
YuanrongTransferEngineConnector,
)
except ImportError:
YuanrongTransferEngineConnector = None
__all__ = ["YuanrongTransferEngineConnector"]
@@ -0,0 +1,862 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import queue
import socket
import threading
import time as _time_mod
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any
import msgspec
import torch
import zmq
from vllm_omni.distributed.omni_connectors.connectors.base import OmniConnectorBase
from vllm_omni.distributed.omni_connectors.utils.env import (
AUTO_DEVICE_VALUES,
AUTO_HOST_VALUES,
expand_env_int,
expand_env_value,
)
from vllm_omni.distributed.omni_connectors.utils.local_rank import get_connector_local_rank
from vllm_omni.distributed.omni_connectors.utils.logging import get_connector_logger
from vllm_omni.distributed.omni_connectors.utils.memory_pool import BufferAllocator, ManagedBuffer
from vllm_omni.distributed.omni_connectors.utils.serialization import OmniSerializer
logger = get_connector_logger(__name__)
try:
from yr.datasystem import TransferEngine
except ImportError:
TransferEngine = None
_BUFFER_TTL_SECONDS = 300
QUERY_INFO = b"query_info"
CLEANUP_KEY = b"cleanup_key"
ACK_OK = b"ack_ok"
ACK_ERROR = b"ack_error"
INFO_NOT_FOUND = b"info_not_found"
@dataclass
class QueryRequest:
"""Request to query metadata for a specific key."""
request_id: str
@dataclass
class CleanupRequest:
"""Response containing metadata for a request."""
request_id: str
@dataclass
class QueryResponse:
request_id: str
rpc_port: int
data_size: int
is_fast_path: bool
src_addrs: list[int]
lengths: list[int]
def _resolve_device_name(configured_device: Any, protocol: str) -> str:
device_name = str(expand_env_value(configured_device or "auto")).strip()
if device_name.lower() not in AUTO_DEVICE_VALUES:
return device_name
if protocol.lower() in {"ascend", "hccl", "npu"}:
return f"npu:{get_connector_local_rank()}"
return ""
def _resolve_pool_device(configured_device: Any) -> str:
pool_device = str(expand_env_value(configured_device or "npu")).strip().lower()
if pool_device in AUTO_DEVICE_VALUES:
return "npu"
if not (pool_device == "npu" or pool_device.startswith("npu:")):
raise ValueError(
f"YuanrongTransferEngineConnector requires an NPU memory pool. Got memory_pool_device={pool_device!r}."
)
return pool_device
class YuanrongTransferEngineConnector(OmniConnectorBase):
"""Pull-based connector backed by Yuanrong transfer_engine."""
supports_raw_data: bool = True
def __init__(self, config: dict[str, Any]):
if TransferEngine is None:
raise ImportError("Yuanrong is not available.")
self._closed = False
self._bind_error: Exception | None = None
self._stop_event = threading.Event()
self._listener_thread: threading.Thread | None = None
self._listener_ready = threading.Event()
self._control_executor: ThreadPoolExecutor | None = None
self._local_buffers: dict[str, Any] = {}
self._local_buffers_lock = threading.Lock()
self._req_local = threading.local()
self._worker_local = threading.local()
self._last_ttl_check: float = _time_mod.monotonic()
self._metrics = {
"puts": 0,
"gets": 0,
"bytes_transferred": 0,
"errors": 0,
"timeouts": 0,
}
self.config = {key: expand_env_value(value) for key, value in config.items()}
config = self.config
raw_host_config = config.get("host")
host_config = "auto" if raw_host_config is None else str(raw_host_config).strip()
self.host = self._get_local_ip() if host_config.lower() in AUTO_HOST_VALUES else host_config
self.zmq_port = self._resolve_port(config.get("zmq_port"), self.host, "zmq_port")
self.rpc_port = self._resolve_port(config.get("rpc_port"), self.host, "rpc_port")
self.protocol = str(config.get("protocol", "ascend"))
self.device_name = _resolve_device_name(config.get("device_name", "auto"), self.protocol)
self.pool_size = int(config.get("memory_pool_size", 1024**3))
self.pool_device = _resolve_pool_device(config.get("memory_pool_device", "npu"))
self.sender_host = config.get("sender_host")
sender_zmq_port = config.get("sender_zmq_port")
self.sender_zmq_port = self._resolve_optional_port(sender_zmq_port, "sender_zmq_port")
role = str(config.get("role", "sender")).lower()
if role not in {"sender", "receiver"}:
raise ValueError(
f"Invalid role={role!r} for YuanrongTransferEngineConnector. Expected 'sender' or 'receiver'."
)
self.can_put = role == "sender"
self.engine = TransferEngine()
local_endpoint = f"{self.host}:{self.rpc_port}"
self._ensure_result_ok(
self.engine.initialize(local_endpoint, self.protocol, self.device_name),
f"initialize transfer engine on {local_endpoint}",
)
resolved_rpc_port = int(self.engine.get_rpc_port())
if resolved_rpc_port > 0:
self.rpc_port = resolved_rpc_port
logger.info(
"YuanrongTransferEngineConnector initialized at %s:%s (protocol=%s, device=%s)",
self.host,
self.rpc_port,
self.protocol,
self.device_name,
)
try:
self.pool = torch.empty(self.pool_size, dtype=torch.uint8, device=self.pool_device)
self.base_ptr = int(self.pool.data_ptr())
self._ensure_result_ok(
self.engine.register_memory(self.base_ptr, self.pool_size),
f"register memory pool ({self.pool_size} bytes)",
)
except Exception as exc:
logger.error("Failed to allocate/register transfer_engine pool: %s", exc)
raise
self.allocator = BufferAllocator(self.pool_size, alignment=4096)
self.zmq_ctx = zmq.Context()
self._control_executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="yuanrong-transfer-control")
if self.can_put:
self._listener_thread = threading.Thread(target=self._zmq_listener_loop, daemon=True)
self._listener_thread.start()
self._listener_ready.wait(timeout=1.0)
if self._bind_error is not None:
raise RuntimeError(
f"YuanrongTransferEngineConnector failed to bind ZMQ on "
f"{self.host}:{self.zmq_port}: {self._bind_error}"
) from self._bind_error
else:
logger.info(
"YuanrongTransferEngineConnector started in receiver mode (sender_host=%r, sender_zmq_port=%r)",
self.sender_host,
self.sender_zmq_port,
)
@staticmethod
def _ensure_result_ok(result: Any, action: str) -> None:
if result.is_error():
raise RuntimeError(f"{action} failed: {result.to_string()}")
@staticmethod
def _resolve_optional_port(configured_port: Any, field_name: str) -> int | None:
configured_port = expand_env_value(configured_port, strict=True, field_name=field_name)
if configured_port is None or str(configured_port).strip().lower() in {"", "auto"}:
return None
return expand_env_int(configured_port, field_name)
@classmethod
def _resolve_port(cls, configured_port: Any, host: str, field_name: str) -> int:
resolved_port = cls._resolve_optional_port(configured_port, field_name)
if resolved_port is not None:
return resolved_port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((host, 0))
return int(sock.getsockname()[1])
@staticmethod
def _get_local_ip() -> str:
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.connect(("8.8.8.8", 80))
return sock.getsockname()[0]
except Exception:
try:
return socket.gethostbyname(socket.gethostname())
except Exception:
return "127.0.0.1"
@staticmethod
def _sync_tensor_device(tensor: torch.Tensor | None) -> None:
if tensor is None:
return
device = getattr(tensor, "device", None)
if device is None or getattr(device, "type", "cpu") == "cpu":
return
backend = getattr(torch, device.type, None)
if backend is None:
return
current_stream = getattr(backend, "current_stream", None)
if callable(current_stream):
try:
current_stream(device).synchronize()
return
except TypeError:
try:
current_stream().synchronize()
return
except Exception:
pass
except Exception:
pass
synchronize = getattr(backend, "synchronize", None)
if callable(synchronize):
try:
synchronize(device)
except TypeError:
synchronize()
def get_connection_info(self) -> dict[str, Any]:
return {
"host": self.host,
"zmq_port": self.zmq_port,
"rpc_port": self.rpc_port,
"can_put": self.can_put,
}
def update_sender_info(
self,
sender_host: str,
sender_zmq_port: int,
) -> None:
self.sender_host = sender_host
self.sender_zmq_port = int(sender_zmq_port)
def _get_req_socket(self, zmq_addr: str, timeout_ms: int) -> zmq.Socket:
cache: dict[str, zmq.Socket] = getattr(self._req_local, "cache", None) # type: ignore[assignment]
if cache is None:
cache = {}
self._req_local.cache = cache
sock = cache.get(zmq_addr)
if sock is None:
sock = self.zmq_ctx.socket(zmq.REQ)
sock.connect(zmq_addr)
cache[zmq_addr] = sock
sock.setsockopt(zmq.SNDTIMEO, timeout_ms)
sock.setsockopt(zmq.RCVTIMEO, timeout_ms)
return sock
def _invalidate_req_socket(self, zmq_addr: str) -> None:
cache: dict[str, zmq.Socket] = getattr(self._req_local, "cache", None) # type: ignore[assignment]
if cache is None:
return
sock = cache.pop(zmq_addr, None)
if sock is not None:
try:
sock.close(linger=0)
except Exception:
pass
def put(self, from_stage: str, to_stage: str, put_key: str, data: Any) -> tuple[bool, int, dict[str, Any] | None]:
if self._closed:
raise RuntimeError("Cannot put data: YuanrongTransferEngineConnector is closed")
if not self.can_put:
self._metrics["errors"] += 1
logger.warning("Rejecting put for %s: connector is in receiver mode", put_key)
return False, 0, None
put_key = self._make_key(put_key, from_stage, to_stage)
try:
src_addr = 0
size = 0
holder = None
is_fast_path = True
should_release_holder = False
if isinstance(data, bytes) and len(data) == 0:
self._metrics["errors"] += 1
logger.warning("Rejecting put for %s: empty bytes payload", put_key)
return False, 0, None
if isinstance(data, torch.Tensor) and data.nbytes == 0:
self._metrics["errors"] += 1
logger.warning("Rejecting put for %s: zero-size tensor", put_key)
return False, 0, None
if not isinstance(data, (ManagedBuffer, torch.Tensor, bytes)):
data = OmniSerializer.serialize(data)
is_fast_path = False
if isinstance(data, ManagedBuffer):
if data.pool_tensor.data_ptr() != self.pool.data_ptr():
logger.warning("ManagedBuffer from different pool detected. Falling back to copy path.")
data = data.tensor.contiguous()
else:
src_addr = self.base_ptr + data.offset
size = data.size
holder = data
should_release_holder = False
if isinstance(data, (torch.Tensor, bytes)):
if isinstance(data, torch.Tensor):
size = data.nbytes
tensor_data = data
else:
size = len(data)
tensor_data = torch.frombuffer(data, dtype=torch.uint8)
try:
offset = self.allocator.alloc(size)
holder = ManagedBuffer(self.allocator, offset, size, self.pool)
should_release_holder = True
except MemoryError:
self._metrics["errors"] += 1
logger.error("Pool exhausted, cannot put data size %s", size)
return False, 0, None
try:
dst_tensor = holder.tensor
if isinstance(data, torch.Tensor):
if not data.is_contiguous():
data = data.contiguous()
src_view = data.view(torch.uint8).flatten()
dst_tensor.copy_(src_view, non_blocking=src_view.device != dst_tensor.device)
self._sync_tensor_device(src_view)
self._sync_tensor_device(dst_tensor)
else:
dst_tensor.copy_(tensor_data)
self._sync_tensor_device(dst_tensor)
except Exception as exc:
holder.release()
self._metrics["errors"] += 1
logger.error("Failed to copy data to pool: %s", exc)
return False, 0, None
src_addr = self.base_ptr + offset
if size <= 0:
if should_release_holder and isinstance(holder, ManagedBuffer):
holder.release()
self._metrics["errors"] += 1
logger.warning("Rejecting put for %s: final payload size is %s", put_key, size)
return False, 0, None
with self._local_buffers_lock:
old_item = self._local_buffers.pop(put_key, None)
if old_item:
_, _, old_holder, old_should_release, _, _ = old_item
if old_should_release and isinstance(old_holder, ManagedBuffer):
old_holder.release()
self._local_buffers[put_key] = (
[src_addr],
[size],
holder,
should_release_holder,
is_fast_path,
_time_mod.monotonic(),
)
metadata = {
"source_host": self.host,
"source_port": self.zmq_port,
"source_rpc_port": self.rpc_port,
"source_addrs": [src_addr],
"lengths": [size],
"data_size": size,
"is_fast_path": is_fast_path,
}
self._metrics["puts"] += 1
self._metrics["bytes_transferred"] += size
return True, size, metadata
except Exception as exc:
self._metrics["errors"] += 1
logger.error("transfer_engine put failed for %s: %s", put_key, exc, exc_info=True)
return False, 0, None
def _query_metadata_at(self, get_key: str, host: str, port: int) -> dict[str, Any] | None:
zmq_addr = f"tcp://{host}:{port}"
req_socket = self._get_req_socket(zmq_addr, timeout_ms=5000)
try:
query = QueryRequest(request_id=get_key)
req_socket.send(QUERY_INFO + msgspec.msgpack.encode(query))
resp = req_socket.recv()
if resp == INFO_NOT_FOUND:
return None
query_resp = msgspec.msgpack.decode(resp, type=QueryResponse)
return {
"source_host": host,
"source_port": port,
"source_rpc_port": query_resp.rpc_port,
"source_addrs": query_resp.src_addrs,
"lengths": query_resp.lengths,
"data_size": query_resp.data_size,
"is_fast_path": query_resp.is_fast_path,
}
except Exception as exc:
self._invalidate_req_socket(zmq_addr)
logger.debug("Failed to query metadata at %s for %s: %s", zmq_addr, get_key, exc)
return None
@classmethod
def _buffer_to_bytes(cls, buffer: ManagedBuffer) -> bytes:
tensor = buffer.tensor
cls._sync_tensor_device(tensor)
if getattr(tensor.device, "type", "cpu") != "cpu":
tensor = tensor.cpu()
return tensor.numpy().tobytes()
def _request_sender_cleanup(self, request_id: str, source_host: str | None, source_port: int | None) -> bool:
if not source_host or not source_port:
return False
zmq_addr = f"tcp://{source_host}:{source_port}"
req_socket = self._get_req_socket(zmq_addr, timeout_ms=3000)
try:
payload = CleanupRequest(request_id=request_id)
req_socket.send(CLEANUP_KEY + msgspec.msgpack.encode(payload))
return req_socket.recv() == ACK_OK
except Exception as exc:
self._invalidate_req_socket(zmq_addr)
logger.warning("Failed to cleanup sender buffer for %s: %s", request_id, exc)
return False
def get(
self,
from_stage: str,
to_stage: str,
get_key: str,
metadata: dict[str, Any] | None = None,
) -> tuple[Any, int] | None:
if self._closed:
raise RuntimeError("Cannot get data: YuanrongTransferEngineConnector is closed")
get_key = self._make_key(get_key, from_stage, to_stage)
t0 = _time_mod.perf_counter()
if not metadata:
if not self.sender_host or self.sender_zmq_port is None or str(self.sender_host).lower() == "auto":
self._metrics["errors"] += 1
raise RuntimeError(
"get(metadata=None) requires sender_host and sender_zmq_port to be resolved. "
"Call update_sender_info(host, port) before polling."
)
metadata = self._query_metadata_at(get_key, str(self.sender_host), int(self.sender_zmq_port))
if not metadata:
return None
elif not (metadata.get("source_host") and metadata.get("source_rpc_port") and metadata.get("source_addrs")):
partial_host = metadata.get("source_host")
partial_port = metadata.get("source_port")
if not partial_host or not partial_port:
self._metrics["errors"] += 1
logger.warning(
"get(%s): partial metadata missing source_host/source_port. metadata=%s",
get_key,
metadata,
)
return None
queried = self._query_metadata_at(get_key, str(partial_host), int(partial_port))
if not queried:
return None
metadata = queried
t1 = _time_mod.perf_counter()
query_ms = (t1 - t0) * 1000
source_host = metadata.get("source_host")
source_port = metadata.get("source_port")
source_rpc_port = metadata.get("source_rpc_port")
source_addrs = list(metadata.get("source_addrs") or [])
lengths = list(metadata.get("lengths") or [])
data_size = int(metadata.get("data_size", 0))
is_fast_path = bool(metadata.get("is_fast_path", False))
if not source_host or not source_rpc_port or str(source_host).lower() == "auto":
self._metrics["errors"] += 1
logger.error(
"Invalid metadata for %s: source_host=%r, source_rpc_port=%r",
get_key,
source_host,
source_rpc_port,
)
return None
if not source_addrs:
self._metrics["errors"] += 1
logger.error("Invalid metadata for %s: missing source_addrs", get_key)
return None
if not lengths:
lengths = [data_size]
if len(source_addrs) != len(lengths):
self._metrics["errors"] += 1
logger.error(
"Invalid metadata for %s: source_addrs/lengths mismatch (%s vs %s)",
get_key,
len(source_addrs),
len(lengths),
)
return None
total_size = sum(int(length) for length in lengths)
if data_size <= 0:
data_size = total_size
if data_size <= 0:
self._metrics["errors"] += 1
logger.warning("Skipping get for %s: data_size is 0", get_key)
return None
try:
offset = self.allocator.alloc(data_size)
recv_buffer = ManagedBuffer(self.allocator, offset, data_size, self.pool)
base_dst_ptr = self.base_ptr + offset
except MemoryError:
self._metrics["errors"] += 1
logger.error("Failed to allocate %s bytes in receive pool", data_size)
return None
dst_addrs: list[int] = []
cursor = 0
for length in lengths:
dst_addrs.append(base_dst_ptr + cursor)
cursor += int(length)
if cursor != data_size:
recv_buffer.release()
self._metrics["errors"] += 1
logger.error("Length sum mismatch for %s: lengths_sum=%s, data_size=%s", get_key, cursor, data_size)
return None
t2 = _time_mod.perf_counter()
alloc_ms = (t2 - t1) * 1000
target_hostname = f"{source_host}:{int(source_rpc_port)}"
try:
result = self.engine.batch_transfer_sync_read(target_hostname, dst_addrs, source_addrs, lengths)
self._ensure_result_ok(result, f"read from {target_hostname}")
self._sync_tensor_device(recv_buffer.tensor)
t3 = _time_mod.perf_counter()
read_ms = (t3 - t2) * 1000
cleanup_ok = self._request_sender_cleanup(get_key, source_host, int(source_port) if source_port else None)
if not cleanup_ok:
logger.warning("Sender-side cleanup not confirmed for %s", get_key)
if is_fast_path:
total_ms = (_time_mod.perf_counter() - t0) * 1000
mbps = (data_size / 1024 / 1024) / (total_ms / 1000) if total_ms > 0 else 0
logger.info(
"[YR GET] %s: query=%.1fms, alloc=%.1fms, read=%.1fms, total=%.1fms, %.1f MB/s "
"(fast_path, zero-copy)",
get_key,
query_ms,
alloc_ms,
read_ms,
total_ms,
mbps,
)
self._metrics["gets"] += 1
self._metrics["bytes_transferred"] += data_size
return recv_buffer, data_size
try:
copy_start = _time_mod.perf_counter()
raw_bytes = self._buffer_to_bytes(recv_buffer)
copy_end = _time_mod.perf_counter()
value = OmniSerializer.deserialize(raw_bytes)
end = _time_mod.perf_counter()
total_ms = (end - t0) * 1000
mbps = (data_size / 1024 / 1024) / (total_ms / 1000) if total_ms > 0 else 0
logger.info(
"[YR GET] %s: query=%.1fms, alloc=%.1fms, read=%.1fms, copy=%.1fms, total=%.1fms, %.1f MB/s",
get_key,
query_ms,
alloc_ms,
read_ms,
(copy_end - copy_start) * 1000,
total_ms,
mbps,
)
self._metrics["gets"] += 1
self._metrics["bytes_transferred"] += data_size
return value, data_size
finally:
recv_buffer.release()
except Exception as exc:
self._metrics["errors"] += 1
self._metrics["timeouts"] += 1
logger.error("transfer_engine get failed for %s: %s", get_key, exc, exc_info=True)
recv_buffer.release()
return None
def cleanup(self, request_id: str, from_stage: str | None = None, to_stage: str | None = None) -> None:
if (from_stage is None) != (to_stage is None):
raise ValueError(
"cleanup() requires both from_stage and to_stage, or neither. "
f"Got from_stage={from_stage!r}, to_stage={to_stage!r}"
)
if from_stage is not None and to_stage is not None:
request_id = self._make_key(request_id, from_stage, to_stage)
with self._local_buffers_lock:
item = self._local_buffers.pop(request_id, None)
if not item:
return
_, _, holder, should_release, _, _ = item
if should_release and isinstance(holder, ManagedBuffer):
holder.release()
def health(self) -> dict[str, Any]:
if self._closed:
return {"status": "unhealthy", "error": "Connector is closed"}
return {
"status": "healthy",
"host": self.host,
"zmq_port": self.zmq_port,
"rpc_port": self.rpc_port,
"protocol": self.protocol,
"pool_device": self.pool_device,
"pool_size": self.pool_size,
**self._metrics,
}
def close(self) -> None:
if getattr(self, "_closed", True):
return
self._closed = True
self._stop_event.set()
if self._listener_thread is not None and self._listener_thread.is_alive():
self._listener_thread.join(timeout=2.0)
if self._control_executor is not None:
self._control_executor.shutdown(wait=True, cancel_futures=False)
with self._local_buffers_lock:
for _, item in list(self._local_buffers.items()):
_, _, holder, should_release, _, _ = item
if should_release and isinstance(holder, ManagedBuffer):
holder.release()
self._local_buffers.clear()
cache: dict[str, zmq.Socket] = getattr(self._req_local, "cache", None) # type: ignore[assignment]
if cache:
for sock in cache.values():
try:
sock.close(linger=0)
except Exception:
pass
cache.clear()
try:
if hasattr(self, "engine") and hasattr(self.engine, "unregister_memory"):
result = self.engine.unregister_memory(self.base_ptr)
if result.is_error():
logger.warning("Failed to unregister memory: %s", result.to_string())
except Exception as exc:
logger.warning("Failed to unregister memory: %s", exc)
try:
if hasattr(self, "engine") and hasattr(self.engine, "finalize"):
result = self.engine.finalize()
if result.is_error():
logger.warning("Failed to finalize transfer engine: %s", result.to_string())
except Exception as exc:
logger.warning("Failed to finalize transfer engine: %s", exc)
try:
if hasattr(self, "zmq_ctx"):
self.zmq_ctx.term()
except Exception as exc:
logger.warning("Failed to terminate ZMQ context: %s", exc)
self.pool = None
def _cleanup_stale_buffers(self) -> None:
now = _time_mod.monotonic()
with self._local_buffers_lock:
stale_keys = [k for k, v in self._local_buffers.items() if now - v[5] > _BUFFER_TTL_SECONDS]
for key in stale_keys:
item = self._local_buffers.pop(key)
_, _, holder, should_release, _, _ = item
if should_release and isinstance(holder, ManagedBuffer):
holder.release()
logger.warning("TTL expired (%ss): cleaned up stale buffer for %s", _BUFFER_TTL_SECONDS, key)
def _zmq_listener_loop(self) -> None:
socket_obj = self.zmq_ctx.socket(zmq.ROUTER)
try:
socket_obj.bind(f"tcp://{self.host}:{self.zmq_port}")
except zmq.ZMQError as exc:
logger.error("ZMQ bind failed on %s:%s: %s", self.host, self.zmq_port, exc)
self.can_put = False
self._bind_error = exc
self._listener_ready.set()
return
self._listener_ready.set()
notify_addr = f"inproc://notify-{id(self)}"
notify_recv = self.zmq_ctx.socket(zmq.PULL)
notify_recv.bind(notify_addr)
poller = zmq.Poller()
poller.register(socket_obj, zmq.POLLIN)
poller.register(notify_recv, zmq.POLLIN)
response_queue: queue.Queue = queue.Queue()
try:
while not self._stop_event.is_set():
try:
events = dict(poller.poll(1000))
if notify_recv in events:
while True:
try:
notify_recv.recv(zmq.NOBLOCK)
except zmq.Again:
break
while True:
try:
identity, response = response_queue.get_nowait()
socket_obj.send_multipart([identity, b"", response])
except queue.Empty:
break
now = _time_mod.monotonic()
if now - self._last_ttl_check >= 10.0:
self._last_ttl_check = now
self._cleanup_stale_buffers()
if socket_obj in events:
frames = socket_obj.recv_multipart()
if len(frames) >= 2:
self._control_executor.submit(
self._handle_control_request,
response_queue,
notify_addr,
frames[0],
frames[-1],
)
except zmq.ContextTerminated:
break
except Exception:
logger.debug("Listener loop error", exc_info=True)
finally:
try:
notify_recv.close(linger=0)
socket_obj.close(linger=0)
except Exception:
pass
def _handle_control_request(self, response_queue: queue.Queue, notify_addr: str, identity, payload: bytes) -> None:
try:
if payload.startswith(QUERY_INFO):
self._handle_query_request(response_queue, notify_addr, identity, payload[len(QUERY_INFO) :])
return
if payload.startswith(CLEANUP_KEY):
self._handle_cleanup_request(response_queue, notify_addr, identity, payload[len(CLEANUP_KEY) :])
return
response_queue.put((identity, ACK_ERROR))
except Exception as exc:
logger.error("Control request failed: %s", exc)
response_queue.put((identity, ACK_ERROR))
self._notify_listener(notify_addr)
def _handle_query_request(self, response_queue: queue.Queue, notify_addr: str, identity, payload: bytes) -> None:
try:
query = msgspec.msgpack.decode(payload, type=QueryRequest)
with self._local_buffers_lock:
item = self._local_buffers.get(query.request_id)
if not item:
response_queue.put((identity, INFO_NOT_FOUND))
else:
src_addrs, src_lengths, _, _, is_fast_path, _ = item
resp = QueryResponse(
request_id=query.request_id,
rpc_port=self.rpc_port,
data_size=sum(int(length) for length in src_lengths),
is_fast_path=is_fast_path,
src_addrs=src_addrs,
lengths=src_lengths,
)
response_queue.put((identity, msgspec.msgpack.encode(resp)))
except Exception as exc:
logger.error("Query request failed: %s", exc)
response_queue.put((identity, INFO_NOT_FOUND))
self._notify_listener(notify_addr)
def _handle_cleanup_request(self, response_queue: queue.Queue, notify_addr: str, identity, payload: bytes) -> None:
try:
request = msgspec.msgpack.decode(payload, type=CleanupRequest)
self.cleanup(request.request_id)
response_queue.put((identity, ACK_OK))
except Exception as exc:
logger.error("Cleanup request failed: %s", exc)
response_queue.put((identity, ACK_ERROR))
self._notify_listener(notify_addr)
def _notify_listener(self, notify_addr: str) -> None:
try:
local = self._worker_local
sock = getattr(local, "notify_socket", None)
cached_addr = getattr(local, "notify_addr", None)
if sock is None or cached_addr != notify_addr:
if sock is not None:
sock.close(linger=0)
sock = self.zmq_ctx.socket(zmq.PUSH)
sock.connect(notify_addr)
local.notify_socket = sock
local.notify_addr = notify_addr
sock.send(b"", zmq.NOBLOCK)
except Exception:
local.notify_socket = None
local.notify_addr = None
+8
View File
@@ -31,6 +31,14 @@ class NPUOmniPlatform(OmniPlatform, NPUPlatform):
_omni_enum = OmniPlatformEnum.NPU
dist_backend: str = "hccl"
@classmethod
def set_device(cls, device: torch.device) -> None:
super().set_device(device)
# Ascend quantized weights are converted from ND to FRACTAL_NZ
# after loading. Enable internal format so the NZ storage layout
# is preserved for fused NPU kernels.
torch.npu.config.allow_internal_format = True
@classmethod
def get_omni_ar_worker_cls(cls) -> str:
return "vllm_omni.platforms.npu.worker.npu_ar_worker.NPUARWorker"
@@ -1,67 +0,0 @@
stage_args:
- stage_id: 0
stage_type: llm
is_comprehension: true
runtime:
devices: "0"
max_batch_size: 1
engine_args:
dtype: bfloat16
model_stage: latent_generator
model_arch: VoxCPMForConditionalGeneration
# Optional persistent HF-compatible config dir for native VoxCPM models.
hf_config_path: ${oc.env:VLLM_OMNI_VOXCPM_HF_CONFIG_PATH,}
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: false
enable_prefix_caching: false
engine_output_type: latent
gpu_memory_utilization: 0.75
distributed_executor_backend: "mp"
max_num_batched_tokens: 4096
max_model_len: 4096
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 4096
seed: 42
detokenize: false
repetition_penalty: 1.0
final_output: false
- stage_id: 1
stage_type: llm
runtime:
devices: "0"
max_batch_size: 1
engine_args:
dtype: float32
model_stage: vae
model_arch: VoxCPMForConditionalGeneration
hf_config_path: ${oc.env:VLLM_OMNI_VOXCPM_HF_CONFIG_PATH,}
worker_type: generation
scheduler_cls: vllm_omni.core.sched.omni_generation_scheduler.OmniGenerationScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: false
enable_prefix_caching: false
engine_output_type: audio
gpu_memory_utilization: 0.1
distributed_executor_backend: "mp"
max_num_batched_tokens: 8192
max_model_len: 4096
engine_input_source: [0]
custom_process_input_func: vllm_omni.model_executor.stage_input_processors.voxcpm.latent2vae
final_output: true
final_output_type: audio
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 1
seed: 42
detokenize: true
repetition_penalty: 1.0
@@ -1,89 +0,0 @@
async_chunk: true
stage_args:
- stage_id: 0
stage_type: llm
is_comprehension: true
runtime:
devices: "0"
max_batch_size: 1
engine_args:
dtype: bfloat16
model_stage: latent_generator
model_arch: VoxCPMForConditionalGeneration
# Optional persistent HF-compatible config dir for native VoxCPM models.
hf_config_path: ${oc.env:VLLM_OMNI_VOXCPM_HF_CONFIG_PATH,}
worker_type: ar
scheduler_cls: vllm_omni.core.sched.omni_ar_scheduler.OmniARScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: false
enable_prefix_caching: false
engine_output_type: latent
gpu_memory_utilization: 0.75
distributed_executor_backend: "mp"
max_num_batched_tokens: 4096
max_model_len: 4096
custom_process_next_stage_input_func: vllm_omni.model_executor.stage_input_processors.voxcpm.latent2vae_async_chunk
output_connectors:
to_stage_1: connector_of_shared_memory
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 4096
seed: 42
detokenize: false
repetition_penalty: 1.0
final_output: false
- stage_id: 1
stage_type: llm
runtime:
devices: "0"
max_batch_size: 1
engine_args:
dtype: float32
model_stage: vae
model_arch: VoxCPMForConditionalGeneration
hf_config_path: ${oc.env:VLLM_OMNI_VOXCPM_HF_CONFIG_PATH,}
worker_type: generation
scheduler_cls: vllm_omni.core.sched.omni_generation_scheduler.OmniGenerationScheduler
enforce_eager: true
trust_remote_code: true
async_scheduling: false
enable_prefix_caching: false
engine_output_type: audio
gpu_memory_utilization: 0.1
distributed_executor_backend: "mp"
max_num_batched_tokens: 8192
max_model_len: 4096
engine_input_source: [0]
input_connectors:
from_stage_0: connector_of_shared_memory
final_output: true
final_output_type: audio
default_sampling_params:
temperature: 0.0
top_p: 1.0
top_k: -1
max_tokens: 1
seed: 42
detokenize: true
repetition_penalty: 1.0
runtime:
enabled: true
connectors:
connector_of_shared_memory:
name: SharedMemoryConnector
extra:
shm_threshold_bytes: 65536
codec_streaming: false
connector_get_sleep_s: 0.01
connector_get_max_wait_first_chunk: 3000
connector_get_max_wait: 300
edges:
- from: 0
to: 1
+8
View File
@@ -36,12 +36,20 @@ class XPUOmniPlatform(OmniPlatform, XPUPlatform):
selected_backend: str | None,
head_size: int,
) -> str:
compute_capability = torch.xpu.get_device_capability()
# Intel Max 1100 and 1550 will not support flash_attn currently
flash_attn_supported = compute_capability["architecture"] not in [13136561920]
if selected_backend is not None:
backend_upper = selected_backend.upper()
backend = DiffusionAttentionBackendEnum[backend_upper]
logger.debug("Using diffusion attention backend '%s'", backend_upper)
return backend.get_path()
if flash_attn_supported:
logger.debug("Defaulting to diffusion attention backend FLASH_ATTN")
return DiffusionAttentionBackendEnum.FLASH_ATTN.get_path()
logger.debug("Defaulting to diffusion attention backend SDPA")
return DiffusionAttentionBackendEnum.TORCH_SDPA.get_path()
+141
View File
@@ -48,6 +48,29 @@ def _build_mxfp8(**kw: Any) -> QuantizationConfig:
return DiffusionMXFP8Config(**kw)
def _build_mxfp4(**kw: Any) -> QuantizationConfig:
"""Lazy import for W4A4 MXFP4 diffusion config (NPU only)."""
from .mxfp4_config import DiffusionMXFP4Config
return DiffusionMXFP4Config(**kw)
def _build_mxfp4_dualscale(**kw: Any) -> QuantizationConfig:
"""Lazy import for MXFP4 DualScale + BF16 mixed diffusion config (NPU only).
Offline mode (is_checkpoint_serialized=True):
ignored_layers from config.json marks interleaved BF16 fallback layers.
All other linear layers use W4A4 MXFP4 DualScale.
Online mode (is_checkpoint_serialized=False):
num_bf16_fallback_layers leading transformer blocks use BF16 original weights
(default 5 when not specified). Remaining blocks use W4A4 MXFP4 DualScale online.
"""
from .mxfp4_config import DiffusionMXFP4DualScaleMixedConfig
return DiffusionMXFP4DualScaleMixedConfig(**kw)
def _build_inc(**kw: Any) -> QuantizationConfig:
"""Lazy import for INC/AutoRound config with checkpoint kwarg normalization."""
from .inc_config import OmniINCConfig
@@ -66,6 +89,8 @@ _OVERRIDES: dict[str, Callable[..., QuantizationConfig]] = {
"gguf": _build_gguf,
"int8": _build_int8,
"mxfp8": _build_mxfp8,
"mxfp4": _build_mxfp4,
"mxfp4_dualscale": _build_mxfp4_dualscale,
"inc": _build_inc,
"auto-round": _build_inc,
"auto_round": _build_inc,
@@ -74,6 +99,43 @@ _OVERRIDES: dict[str, Callable[..., QuantizationConfig]] = {
SUPPORTED_QUANTIZATION_METHODS: list[str] = list(dict.fromkeys(QUANTIZATION_METHODS + list(_OVERRIDES.keys())))
def _build_reverse_alias_map() -> dict[str, str]:
"""Build a mapping from normalized method aliases to canonical names.
All keys in _OVERRIDES that share the same builder function are considered
aliases of each other. The canonical name is the first key (in definition
order) that maps to a given builder — i.e. the one returned by
builder().get_name().
"""
builder_to_first_key: dict[Callable[..., QuantizationConfig], str] = {}
for key in _OVERRIDES:
builder = _OVERRIDES[key]
if builder not in builder_to_first_key:
builder_to_first_key[builder] = key
result: dict[str, str] = {}
for key, builder in _OVERRIDES.items():
canonical = builder_to_first_key[builder]
result[key.lower().replace("-", "_")] = canonical
return result
_CACHED_ALIAS_MAP: dict[str, str] | None = None
def _normalize_quant_method_alias(method: str | None) -> str | None:
"""Map a method name (or any of its aliases) to its canonical internal name.
Returns the input unchanged if it is not a known alias.
"""
if method is None:
return None
global _CACHED_ALIAS_MAP
if _CACHED_ALIAS_MAP is None:
_CACHED_ALIAS_MAP = _build_reverse_alias_map()
normalized = method.lower().replace("-", "_")
return _CACHED_ALIAS_MAP.get(normalized, normalized)
_MODEL_OPT_METHODS = {
"modelopt",
}
@@ -255,3 +317,82 @@ def build_quant_config(
return _build_from_method_and_config(method, merged)
raise TypeError(f"quantization config must be str, dict, QuantizationConfig, or None, got {type(spec).__name__}")
def _disk_marks_serialized(qc_kwargs: dict[str, Any], quant_config: object) -> bool:
"""Return True when config.json says serialized but the active quant_config does not.
Matches any flag following the is_checkpoint_*_serialized naming convention,
so new quant methods don't require updating an explicit allowlist.
"""
for key, val in qc_kwargs.items():
if key.startswith("is_checkpoint_") and key.endswith("_serialized"):
if val and hasattr(quant_config, key) and not getattr(quant_config, key):
return True
return False
def resolve_quant_config_from_disk(
quant_config: QuantizationConfig | None,
disk_qc: dict[str, Any] | str | None,
) -> QuantizationConfig | None:
"""Reconcile an active quant_config against quantization_config from a transformer's config.json.
Used when loading individual transformer blocks that each have their own config.json
(e.g. cascade models with separate transformer and transformer_2 directories).
Rules:
- disk_qc is None: return quant_config unchanged.
- quant_config is None: auto-detect from disk_qc (full build).
- Methods mismatch: raise ValueError — prevents silent weight corruption.
- Disk marks serialized but quant_config is online: rebuild from disk.
- ignored_layers differ: rebuild from disk (per-transformer BF16 routing).
"""
if disk_qc is None:
return quant_config
if isinstance(disk_qc, str):
if quant_config is None:
logger.info("Auto-detected quantization from config.json: method=%s", disk_qc)
return build_quant_config(disk_qc)
return quant_config
if not isinstance(disk_qc, Mapping) or "quant_method" not in disk_qc:
return quant_config
qc_method: str = disk_qc["quant_method"]
qc_kwargs: dict[str, Any] = {k: v for k, v in disk_qc.items() if k != "quant_method"}
if quant_config is None:
logger.info(
"Auto-detected quantization from config.json: method=%s kwargs=%s",
qc_method,
qc_kwargs,
)
return build_quant_config(qc_method, **qc_kwargs)
active_method = _normalize_quant_method_alias(quant_config.get_name())
disk_method = _normalize_quant_method_alias(qc_method)
if active_method != disk_method:
raise ValueError(
f"Checkpoint config.json declares quant_method={qc_method!r} but the "
f"active quantization config is {quant_config.get_name()!r}. "
"Pass a matching --quantization flag or omit it for auto-detection."
)
if _disk_marks_serialized(qc_kwargs, quant_config):
logger.info(
"config.json marks checkpoint as serialized; switching to offline %s mode.",
qc_method,
)
return build_quant_config(qc_method, **qc_kwargs)
if (
"ignored_layers" in qc_kwargs
and hasattr(quant_config, "ignored_layers")
and set(qc_kwargs.get("ignored_layers") or []) != set(quant_config.ignored_layers or [])
):
logger.info("config.json ignored_layers differs from active config; rebuilding quant_config.")
return build_quant_config(qc_method, **qc_kwargs)
return quant_config
+709
View File
@@ -0,0 +1,709 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""W4A4 MXFP4 (Microscaling FP4) online/offline quantization for diffusion transformers.
Architecture mirrors mxfp8_config.py:
MXFPLinearMethodBase – platform-agnostic skeleton (imported from mxfp8_config)
NPUMxfp4LinearMethod – NPU single-scale offline (W4A4 MXFP4)
NPUMxfp4OnlineLinearMethod – NPU single-scale online (BF16 → FP4)
NPUMxfp4DualScaleLinearMethod – NPU dual-scale offline (W4A4 MXFP4 DualScale)
NPUMxfp4DualScaleOnlineLinearMethod – NPU dual-scale online (BF16 → FP4)
Quantization configs:
DiffusionMXFP4Config – single-scale online/offline (quant_method="mxfp4")
DiffusionMXFP4DualScaleMixedConfig – dual-scale + per-layer BF16 fallback (quant_method="mxfp4_dualscale")
Offline: ignored_layers from config.json routes interleaved BF16 layers
Online: num_bf16_fallback_layers leading blocks stay in BF16 (default 5)
Key differences from MXFP8:
1. Precision: float4_e2m1fn_x2 (FP4 packed, 2 values per element).
npu_dynamic_mx_quant(x) without dst_type defaults to float4_e2m1fn_x2.
2. Weight layout: stored as (N, K) — NOT pre-transposed.
FP4 uses a packed format; transposing a packed tensor is not safely contiguous.
Transpose is done inline in _quant_matmul via layer.weight.transpose(0, 1).
3. GEMM signature: npu_quant_matmul requires explicit
x1_dtype=float4_e2m1fn_x2 and x2_dtype=float4_e2m1fn_x2.
Scale layout: (N, S/2, 2) — same reshape as MXFP8, also NOT pre-transposed;
transposed inline in _quant_matmul.
Dual-scale (W4A4_MXFP4_DUALSCALE):
Two-level quantization: fine scale (per-32 K) + coarse scale (per-512 K) + per-channel
activation pre-scale (mul_scale from calibration). Uses npu_dynamic_dual_level_mx_quant
and npu_dual_level_quant_matmul. Weight stored in NZ hardware format via npu_format_cast.
Checkpoint tensor shapes for dual-scale:
weight : (N, K) float8_e4m3fn – FP4 packed
weight_scale : (N, K//32) uint8 – fine scale (float8_e8m0fnu bits)
weight_dual_scale : (N, K//512, 1) float32 – coarse scale (extra dim avoids shape assert)
mul_scale : (K,) float32 – per-input-channel activation pre-scale
Reference: MindIE-SD W4A4MXFP4QuantLinear / W4A4MXFP4DualQuantLinear (mindiesd/quantization/layer.py).
"""
from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any
import torch
from torch.nn import Module
from vllm.logger import init_logger
from vllm.model_executor.layers.linear import (
LinearBase,
UnquantizedLinearMethod,
)
from vllm.model_executor.layers.quantization import QuantizationMethods
from vllm.model_executor.layers.quantization.base_config import (
QuantizationConfig,
QuantizeMethodBase,
)
from vllm.model_executor.layers.quantization.fp8 import _copy_missing_attrs
from vllm.model_executor.layers.quantization.utils.quant_utils import is_layer_skipped
from vllm.model_executor.model_loader.weight_utils import initialize_single_dummy_weight
from vllm.model_executor.parameter import ModelWeightParameter
from vllm.model_executor.utils import replace_parameter
from vllm_omni.platforms import current_omni_platform
from vllm_omni.quantization.mxfp8_config import (
MXFPLinearMethodBase,
_LazyWeightMixin,
)
if TYPE_CHECKING:
from vllm.model_executor.models.utils import WeightsMapper
logger = init_logger(__name__)
# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
class DiffusionMXFP4Config(QuantizationConfig):
"""W4A4 MXFP4 quantization config for diffusion transformers.
Supports both online (BF16 checkpoint → quantize at load time) and offline
(pre-quantized MXFP4 checkpoint) modes, mirroring DiffusionMXFP8Config.
MX (microscaling) format: groups of 32 K-dimension elements share one
float8_e8m0fnu exponent scale. Weight and activation are float4_e2m1fn_x2.
"""
def __init__(
self,
is_checkpoint_mxfp4_serialized: bool = False,
ignored_layers: list[str] | None = None,
) -> None:
super().__init__()
self.is_checkpoint_mxfp4_serialized = is_checkpoint_mxfp4_serialized
self.ignored_layers = ignored_layers or []
@classmethod
def get_name(cls) -> QuantizationMethods:
return "mxfp4"
@classmethod
def get_supported_act_dtypes(cls) -> list[torch.dtype]:
return [torch.bfloat16, torch.float16]
@classmethod
def get_min_capability(cls) -> int:
return 80
@classmethod
def get_config_filenames(cls) -> list[str]:
return []
def apply_vllm_mapper(self, hf_to_vllm_mapper: WeightsMapper) -> None:
if self.ignored_layers:
self.ignored_layers = hf_to_vllm_mapper.apply_list(self.ignored_layers)
@classmethod
def from_config(cls, config: dict[str, Any]) -> DiffusionMXFP4Config:
is_serialized = cls.get_from_keys_or(config, ["is_checkpoint_mxfp4_serialized"], False)
ignored_layers = cls.get_from_keys_or(config, ["ignored_layers"], None)
if not ignored_layers:
ignored_layers = cls.get_from_keys_or(config, ["modules_to_not_convert"], None)
return cls(
is_checkpoint_mxfp4_serialized=is_serialized,
ignored_layers=ignored_layers,
)
def get_quant_method(
self,
layer: torch.nn.Module,
prefix: str,
) -> QuantizeMethodBase | None:
if isinstance(layer, LinearBase):
if is_layer_skipped(
prefix=prefix,
ignored_layers=self.ignored_layers,
fused_mapping=self.packed_modules_mapping,
):
return UnquantizedLinearMethod()
if current_omni_platform.is_npu():
if self.is_checkpoint_mxfp4_serialized:
return NPUMxfp4LinearMethod(self)
return NPUMxfp4OnlineLinearMethod(self)
raise NotImplementedError(
"DiffusionMXFP4Config (W4A4 MXFP4) is currently only supported "
"on NPU (Ascend) platforms. CUDA support is not yet implemented."
)
return None
# ---------------------------------------------------------------------------
# NPU MXFP4 single-scale offline method (pre-quantized checkpoint)
# ---------------------------------------------------------------------------
class NPUMxfp4LinearMethod(MXFPLinearMethodBase):
"""NPU W4A4 MXFP4 offline linear method for pre-quantized checkpoints.
Weight canonical layout after process_weights_after_loading:
weight : (N, K) in float4_e2m1fn_x2 — NOT pre-transposed (FP4 packed)
weight_scale: (N, S/2, 2) in float8_e8m0fnu — NOT pre-transposed
Both are transposed inline in _quant_matmul, unlike MXFP8 which pre-transposes.
NPUMxfp4OnlineLinearMethod normalizes to the same layout so apply() is shared.
"""
def __init__(self, quant_config: DiffusionMXFP4Config) -> None:
self.quant_config = quant_config
self.out_dtype = torch.get_default_dtype()
def create_weights(
self,
layer: torch.nn.Module,
input_size_per_partition: int,
output_partition_sizes: list[int],
input_size: int,
output_size: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
) -> None:
output_size_per_partition = sum(output_partition_sizes)
weight_loader = extra_weight_attrs.get("weight_loader")
layer.logical_widths = output_partition_sizes
layer.input_size_per_partition = input_size_per_partition
layer.output_size_per_partition = output_size_per_partition
layer.orig_dtype = params_dtype
layer.weight_block_size = None
# BF16 placeholder; cast to float4_e2m1fn_x2 in process_weights.
layer.register_parameter(
"weight",
ModelWeightParameter(
data=torch.empty(output_size_per_partition, input_size_per_partition, dtype=params_dtype),
input_dim=1,
output_dim=0,
weight_loader=weight_loader,
),
)
# Scale stored as uint8 in safetensors (float8_e8m0fnu is same bit width).
# Using uint8 avoids a lossy float32 round-trip when loading the checkpoint.
num_groups = (input_size_per_partition + 31) // 32
layer.register_parameter(
"weight_scale",
ModelWeightParameter(
data=torch.empty(output_size_per_partition, num_groups, dtype=torch.uint8),
input_dim=1,
output_dim=0,
weight_loader=weight_loader,
),
)
def process_weights_after_loading(self, layer: Module) -> None:
if getattr(layer, "_already_called_process_weights_after_loading", False):
return
import torch_npu
# NPU: cast to float4_e2m1fn_x2. Weight stays (N, K) — no pre-transpose.
w = layer.weight
if w.dtype != torch_npu.float4_e2m1fn_x2:
w = torch_npu.npu_dtype_cast(w.npu(), torch_npu.float4_e2m1fn_x2)
# Scale: checkpoint stores uint8 bytes that ARE float8_e8m0fnu bits.
# Only convert if neither uint8 nor the target NPU dtype already.
# (N, K_groups) → (N, K_groups/2, 2). Not pre-transposed; done inline in _quant_matmul.
s = layer.weight_scale.data
if s.dtype not in (torch.uint8, torch_npu.float8_e8m0fnu):
s = s.to(torch_npu.float8_e8m0fnu)
N, K_groups = s.shape
if K_groups % 2 == 1:
s = torch.cat([s, torch.zeros(N, 1, dtype=s.dtype, device=s.device)], dim=1)
s = s.reshape(N, -1, 2).contiguous()
replace_parameter(layer, "weight", w)
replace_parameter(layer, "weight_scale", s)
layer._already_called_process_weights_after_loading = True
# --- NPU MXFP4 ops — shared with online path via inheritance ---
def _quantize_activation(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
import torch_npu
# No dst_type: npu_dynamic_mx_quant defaults to float4_e2m1fn_x2.
return torch_npu.npu_dynamic_mx_quant(x)
def _quant_matmul(
self,
x_q: torch.Tensor,
x_scale: torch.Tensor,
layer: torch.nn.Module,
bias: torch.Tensor | None,
ori_dtype: torch.dtype,
) -> torch.Tensor:
import torch_npu
if bias is not None and bias.dtype != torch.float32:
bias = bias.to(torch.float32)
# FP4 differences vs FP8:
# weight (N,K) transposed inline → (K,N); scale (N,S/2,2) transposed inline → (S/2,N,2).
# x1_dtype / x2_dtype required — FP4 dtype not inferred from tensor dtype.
return torch_npu.npu_quant_matmul(
x_q,
layer.weight.transpose(0, 1), # (K, N) inline
layer.weight_scale.transpose(0, 1), # (S/2, N, 2) inline
scale_dtype=torch_npu.float8_e8m0fnu,
x1_dtype=torch_npu.float4_e2m1fn_x2,
x2_dtype=torch_npu.float4_e2m1fn_x2,
pertoken_scale=x_scale,
pertoken_scale_dtype=torch_npu.float8_e8m0fnu,
bias=bias,
output_dtype=ori_dtype,
group_sizes=[1, 1, 32],
)
# ---------------------------------------------------------------------------
# NPU MXFP4 single-scale online method (BF16 checkpoint → quantize at load time)
# ---------------------------------------------------------------------------
class NPUMxfp4OnlineLinearMethod(_LazyWeightMixin, NPUMxfp4LinearMethod):
"""NPU W4A4 MXFP4 online linear method.
MRO: NPUMxfp4OnlineLinearMethod → _LazyWeightMixin → NPUMxfp4LinearMethod
→ MXFPLinearMethodBase → LinearMethodBase
create_weights : _LazyWeightMixin (meta device + patched loader)
process_weights : NPUMxfp4OnlineLinearMethod (BF16 → FP4 + normalize)
apply / ops : NPUMxfp4LinearMethod / MXFPLinearMethodBase (shared)
"""
def process_weights_after_loading(self, layer: Module) -> None:
if getattr(layer, "_already_called_process_weights_after_loading", False):
return
import torch_npu
if layer.weight.device == torch.device("meta"):
weight = ModelWeightParameter(
data=torch.empty_like(layer.weight, device=layer._load_device),
input_dim=1,
output_dim=0,
weight_loader=layer.weight.weight_loader,
)
_copy_missing_attrs(layer.weight, weight)
layer.register_parameter("weight", weight)
initialize_single_dummy_weight(layer.weight)
# NPU: quantize BF16/FP16 (N, K) → FP4. No dst_type → float4_e2m1fn_x2.
weight_fp4, weight_scale_raw = torch_npu.npu_dynamic_mx_quant(layer.weight)
# Weight stays (N, K) — no pre-transpose for FP4 packed format.
# Scale: (N, S) → (N, S/2, 2). Not pre-transposed; done inline in _quant_matmul.
weight_scale = weight_scale_raw.reshape(weight_scale_raw.shape[0], -1, 2).contiguous()
replace_parameter(layer, "weight", weight_fp4)
replace_parameter(layer, "weight_scale", weight_scale)
layer._already_called_process_weights_after_loading = True
# ---------------------------------------------------------------------------
# NPU MXFP4 dual-scale offline method (W4A4_MXFP4_DUALSCALE checkpoint)
# ---------------------------------------------------------------------------
class NPUMxfp4DualScaleLinearMethod(MXFPLinearMethodBase):
"""NPU W4A4 MXFP4 dual-scale offline method for pre-quantized checkpoints.
Checkpoint tensors and their canonical post-load shapes:
weight : (N, K) float8_e4m3fn – FP4 packed (2 values per byte)
weight_scale : (N, K//32) uint8 – fine scale (float8_e8m0fnu bits); reshaped to (N, K//64, 2)
weight_dual_scale : (N, K//512, 1) float32 – coarse scale; transposed to (K//512, N)
mul_scale : (K,) float32 – per-input-channel activation pre-scale (from calibration)
Forward pass:
x_q, l0, l1 = npu_dynamic_dual_level_mx_quant(x, smooth_scale=mul_scale)
out = npu_dual_level_quant_matmul(x_q, weight, l0, weight_dual_scale, l1, weight_scale)
Reference: MindIE-SD W4A4MXFP4DualQuantLinear.
"""
def __init__(self, quant_config: Any) -> None:
self.quant_config = quant_config
self.out_dtype = torch.get_default_dtype()
def create_weights(
self,
layer: torch.nn.Module,
input_size_per_partition: int,
output_partition_sizes: list[int],
input_size: int,
output_size: int,
params_dtype: torch.dtype,
**extra_weight_attrs,
) -> None:
output_size_per_partition = sum(output_partition_sizes)
weight_loader = extra_weight_attrs.get("weight_loader")
layer.logical_widths = output_partition_sizes
layer.input_size_per_partition = input_size_per_partition
layer.output_size_per_partition = output_size_per_partition
layer.orig_dtype = params_dtype
layer.weight_block_size = None
# FP4 packed: 2 values per float8_e4m3fn byte → checkpoint stores as float8_e4m3fn; register as BF16
layer.register_parameter(
"weight",
ModelWeightParameter(
data=torch.empty(output_size_per_partition, input_size_per_partition, dtype=params_dtype),
input_dim=1,
output_dim=0,
weight_loader=weight_loader,
),
)
# Fine scale: one uint8 exponent (float8_e8m0fnu bit pattern) per group of 32 K elements.
# input_dim=1: RowParallelLinear weight_loader shards along the K-group dimension (dim 1)
# so each rank receives only its (K/TP)//32 groups; ColumnParallelLinear only uses
# output_dim=0 for sharding and leaves dim 1 intact.
num_groups_fine = (input_size_per_partition + 31) // 32
layer.register_parameter(
"weight_scale",
ModelWeightParameter(
data=torch.empty(output_size_per_partition, num_groups_fine, dtype=torch.uint8),
input_dim=1,
output_dim=0,
weight_loader=weight_loader,
),
)
# Coarse scale: one float32 per group of 512 K elements.
# Shape (N, K_coarse, 1) matches checkpoint layout exactly, avoiding the
# shape-mismatch assert in linear.py:1344.
# input_dim=1: same TP sharding rationale as weight_scale above.
num_groups_coarse = (input_size_per_partition + 511) // 512
layer.register_parameter(
"weight_dual_scale",
ModelWeightParameter(
data=torch.empty(output_size_per_partition, num_groups_coarse, 1, dtype=torch.float32),
input_dim=1,
output_dim=0,
weight_loader=weight_loader,
),
)
# mul_scale is a float32 calibration tensor; register as float32
# to avoid precision loss from an implicit BF16 cast during weight loading.
# input_dim=0: RowParallelLinear shards the 1-D per-input-channel tensor along dim 0
# so each rank receives only its K/TP channels; ColumnParallelLinear leaves it intact.
layer.register_parameter(
"mul_scale",
ModelWeightParameter(
data=torch.empty(input_size_per_partition, dtype=torch.float32),
input_dim=0,
output_dim=None,
weight_loader=weight_loader,
),
)
setattr(layer.mul_scale, "ignore_warning", True)
def process_weights_after_loading(self, layer: Module) -> None:
if getattr(layer, "_already_called_process_weights_after_loading", False):
return
import torch_npu
# float8_e4m3fn (FP4 packed) → float4_e2m1fn_x2 → NZ hardware format (format ID 29).
# NZ layout is required by npu_dual_level_quant_matmul for FP4 weight matrices.
w = torch_npu.npu_dtype_cast(layer.weight.data.npu(), torch_npu.float4_e2m1fn_x2)
w = torch_npu.npu_format_cast(w.view(torch.int8), 29, customize_dtype=torch.int8)
# Fine scale: (N, K//32) uint8 → cast to float8_e8m0fnu → (N, K//64, 2).
# The cast reinterprets the stored uint8 bit-patterns as float8_e8m0fnu exponents,
# which is required for npu_dual_level_quant_matmul to compute correct scale values.
s = layer.weight_scale.data.npu()
s = s.reshape(s.shape[0], -1, 2).contiguous()
# Coarse scale: (N, K//512, 1) → squeeze → (N, K//512) → transpose → (K//512, N).
ds = layer.weight_dual_scale.data.squeeze(-1).transpose(0, 1).npu().contiguous()
ms = layer.mul_scale.to(torch.bfloat16).data.view(-1).npu().contiguous()
replace_parameter(layer, "weight", w)
replace_parameter(layer, "weight_scale", s)
replace_parameter(layer, "weight_dual_scale", ds)
replace_parameter(layer, "mul_scale", ms)
layer._already_called_process_weights_after_loading = True
def _apply_inner(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None,
ori_dtype: torch.dtype,
) -> torch.Tensor:
"""Dual-scale inner loop: dtype guard → 3-tuple quantize (mul_scale as smooth) → matmul.
Overrides the default single-scale _apply_inner from MXFPLinearMethodBase.
apply() in the base class handles reshape/unreshape; this method is not
responsible for that.
"""
if ori_dtype not in (torch.bfloat16, torch.float16):
x = x.to(torch.bfloat16)
x_q, l0_scale, l1_scale = self._quantize_activation(x, layer.mul_scale)
return self._quant_matmul(x_q, l0_scale, l1_scale, layer, bias, ori_dtype)
def _quantize_activation( # type: ignore[override]
self,
x: torch.Tensor,
smooth_scale: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
import torch_npu
return torch_npu.npu_dynamic_dual_level_mx_quant(x, smooth_scale=smooth_scale)
def _quant_matmul( # type: ignore[override]
self,
x_q: torch.Tensor,
l0_scale: torch.Tensor,
l1_scale: torch.Tensor,
layer: torch.nn.Module,
bias: torch.Tensor | None,
ori_dtype: torch.dtype,
) -> torch.Tensor:
import torch_npu
if bias is not None and bias.dtype != torch.float32:
bias = bias.to(torch.float32)
# weight_scale is (N, K//64, 2) float8_e8m0fnu — operator expects output-major layout.
# weight_dual_scale is (K//512, N) float32 — transposed to K-major in process_weights.
return torch_npu.npu_dual_level_quant_matmul(
x_q,
layer.weight,
l0_scale,
layer.weight_dual_scale,
l1_scale,
layer.weight_scale,
bias=bias,
output_dtype=ori_dtype,
)
# ---------------------------------------------------------------------------
# NPU MXFP4 dual-scale online method (BF16 checkpoint → quantize at load time)
# ---------------------------------------------------------------------------
class NPUMxfp4DualScaleOnlineLinearMethod(_LazyWeightMixin, NPUMxfp4DualScaleLinearMethod):
"""NPU W4A4 MXFP4 dual-scale online method: quantises BF16 weights at load time.
MRO: NPUMxfp4DualScaleOnlineLinearMethod → _LazyWeightMixin
→ NPUMxfp4DualScaleLinearMethod → MXFPLinearMethodBase
create_weights : _LazyWeightMixin (meta device + patched loader)
process_weights : NPUMxfp4DualScaleOnlineLinearMethod (BF16 → FP4 + dual scales)
apply / _quant_matmul : NPUMxfp4DualScaleLinearMethod (shared with offline path)
"""
def process_weights_after_loading(self, layer: Module) -> None:
if getattr(layer, "_already_called_process_weights_after_loading", False):
return
import torch_npu
if layer.weight.device == torch.device("meta"):
weight = ModelWeightParameter(
data=torch.empty_like(layer.weight, device=layer._load_device),
input_dim=1,
output_dim=0,
weight_loader=layer.weight.weight_loader,
)
_copy_missing_attrs(layer.weight, weight)
layer.register_parameter("weight", weight)
initialize_single_dummy_weight(layer.weight)
# Quantize BF16 weight → FP4 + dual-level scales (no smooth pre-scale for online).
# Returns: (weight_fp4, l0_scale[coarse per-512], l1_scale[fine per-32])
weight_fp4, w_l0_scale, w_l1_scale = torch_npu.npu_dynamic_dual_level_mx_quant(
layer.weight.data.npu(), smooth_scale=None
)
# NZ hardware format for the FP4 weight (same as offline path).
w = torch_npu.npu_format_cast(weight_fp4.view(torch.int8), 29, customize_dtype=torch.int8)
# Fine scale (l1): (N, K//32) → (N, K//64, 2). Dtype from op output (float8_e8m0fnu).
s = w_l1_scale.reshape(w_l1_scale.shape[0], -1, 2).contiguous()
# Coarse scale (l0): (N, K_coarse) → (K_coarse, N). Dtype from op output.
ds = w_l0_scale.reshape(w_l0_scale.shape[0], -1).transpose(0, 1).contiguous()
# No calibration available: identity pre-scale (no smooth quantization effect).
ms = torch.ones(layer.input_size_per_partition, dtype=torch.bfloat16, device="npu")
replace_parameter(layer, "weight", w)
replace_parameter(layer, "weight_scale", s)
replace_parameter(layer, "weight_dual_scale", ds)
replace_parameter(layer, "mul_scale", ms)
layer._already_called_process_weights_after_loading = True
# ---------------------------------------------------------------------------
# Block-index helper (shared by DiffusionMXFP4DualScaleMixedConfig)
# ---------------------------------------------------------------------------
_BLOCK_IDX_RE = re.compile(r"^blocks\.(\d+)\.")
def _parse_block_idx(prefix: str) -> int | None:
"""Extract block index from prefix like 'blocks.5.attn1.to_q'."""
m = _BLOCK_IDX_RE.match(prefix)
return int(m.group(1)) if m else None
# ---------------------------------------------------------------------------
# Config: MXFP4 DualScale + per-layer BF16 fallback
# ---------------------------------------------------------------------------
class DiffusionMXFP4DualScaleMixedConfig(QuantizationConfig):
"""W4A4 MXFP4 DualScale with per-layer BF16 fallback for diffusion transformers.
Sensitive layers fall back to BF16 (original weights) while all other linear
layers use W4A4 MXFP4 DualScale. BF16 fallback layers may be interleaved
anywhere in the transformer.
Offline mode (is_checkpoint_serialized=True):
Layers whose prefix appears in ignored_layers → UnquantizedLinearMethod (BF16)
All other linear layers → NPUMxfp4DualScaleLinearMethod
ignored_layers is injected into transformer/config.json by the merge script
and contains the prefixes of all non-MXFP4 linear layers.
Online mode (is_checkpoint_serialized=False):
Layer routing applies two rules in priority order:
1. ignored_layers (explicit per-layer BF16 override, user-supplied) → BF16
2. Blocks 0 .. num_bf16_fallback_layers-1 (coarse leading-block rule) → BF16
3. All other linear layers → NPUMxfp4DualScaleOnlineLinearMethod
num_bf16_fallback_layers defaults to 5 when not specified.
Set ignored_layers to pin arbitrary interleaved layers to BF16 without
needing an offline checkpoint (useful for accuracy debugging).
Layers outside "blocks.N.*" (condition_embedder etc.) always use online MXFP4
unless they appear in ignored_layers.
Config injected by merge_mxfp4_dualscale_checkpoint.py:
{
"quant_method": "mxfp4_dualscale",
"is_checkpoint_serialized": true,
"ignored_layers": ["blocks.0.attn1.to_q", ...]
}
"""
def __init__(
self,
is_checkpoint_serialized: bool = False,
ignored_layers: list[str] | None = None,
num_bf16_fallback_layers: int = 5,
) -> None:
super().__init__()
self.is_checkpoint_serialized = is_checkpoint_serialized
self.ignored_layers = ignored_layers or []
self.num_bf16_fallback_layers = num_bf16_fallback_layers
@classmethod
def get_name(cls) -> QuantizationMethods:
return "mxfp4_dualscale"
@classmethod
def get_supported_act_dtypes(cls) -> list[torch.dtype]:
return [torch.bfloat16, torch.float16]
@classmethod
def get_min_capability(cls) -> int:
return 80
@classmethod
def get_config_filenames(cls) -> list[str]:
return []
def apply_vllm_mapper(self, hf_to_vllm_mapper: WeightsMapper) -> None:
if self.ignored_layers:
self.ignored_layers = hf_to_vllm_mapper.apply_list(self.ignored_layers)
@classmethod
def from_config(cls, config: dict[str, Any]) -> DiffusionMXFP4DualScaleMixedConfig:
is_serialized = cls.get_from_keys_or(config, ["is_checkpoint_serialized"], False)
ignored_layers = cls.get_from_keys_or(config, ["ignored_layers"], None)
if not ignored_layers:
ignored_layers = cls.get_from_keys_or(config, ["modules_to_not_convert"], None)
num_bf16_fallback_layers = cls.get_from_keys_or(config, ["num_bf16_fallback_layers"], 5)
return cls(
is_checkpoint_serialized=is_serialized,
ignored_layers=ignored_layers,
num_bf16_fallback_layers=num_bf16_fallback_layers,
)
def get_quant_method(
self,
layer: torch.nn.Module,
prefix: str,
) -> QuantizeMethodBase | None:
if not isinstance(layer, LinearBase):
return None
if self.is_checkpoint_serialized:
# Offline: ignored_layers lists interleaved BF16 fallback layer prefixes.
if is_layer_skipped(
prefix=prefix,
ignored_layers=self.ignored_layers,
fused_mapping=self.packed_modules_mapping,
):
return UnquantizedLinearMethod()
if not current_omni_platform.is_npu():
raise NotImplementedError(
"DiffusionMXFP4DualScaleMixedConfig is currently only supported on NPU (Ascend) platforms."
)
return NPUMxfp4DualScaleLinearMethod(self)
# Online: explicit ignored_layers take priority (user-specified per-layer BF16 override),
# then fall back to the coarse leading-block rule.
if is_layer_skipped(
prefix=prefix,
ignored_layers=self.ignored_layers,
fused_mapping=self.packed_modules_mapping,
):
return UnquantizedLinearMethod()
block_idx = _parse_block_idx(prefix)
if block_idx is not None and block_idx < self.num_bf16_fallback_layers:
return UnquantizedLinearMethod()
if not current_omni_platform.is_npu():
raise NotImplementedError(
"DiffusionMXFP4DualScaleMixedConfig is currently only supported on NPU (Ascend) platforms."
)
return NPUMxfp4DualScaleOnlineLinearMethod(self)
+2
View File
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -0,0 +1,637 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Compare diffusion quantization quality with final output metrics.
This tool runs a reference diffusion configuration and a candidate
configuration with the same prompt, seed, resolution, and step count. It reports
final image or video frame similarity metrics plus generation latency and memory.
The main metrics are:
* output images: the same pixel-space metrics plus PSNR
* runtime: per-run and average generation latency, and worker-reported peak
device memory when available
Online FP8 Qwen-Image example:
python -m vllm_omni.quantization.tools.compare_diffusion_trajectory_similarity \\
--model Qwen/Qwen-Image \\
--candidate-quantization fp8 \\
--ignored-layers img_mlp \\
--prompt "a cup of coffee on the table" \\
--height 1024 --width 1024 --num-inference-steps 20 --seed 42 \\
--output-json /mnt/data4/cwq/tmp/qwen_image_fp8_similarity.json
Offline checkpoint example:
python -m vllm_omni.quantization.tools.compare_diffusion_trajectory_similarity \\
--reference-model Qwen/Qwen-Image \\
--candidate-model /path/to/quantized/qwen-image-checkpoint \\
--candidate-quantization-config-json '{"method":"inc","weight_bits":4}' \\
--prompt "a cup of coffee on the table" \\
--output-json /mnt/data4/cwq/tmp/qwen_image_checkpoint_similarity.json
Offline FP8 model-id example:
python -m vllm_omni.quantization.tools.compare_diffusion_trajectory_similarity \\
--model Qwen/Qwen-Image \\
--candidate-model Qwen/Qwen-Image-FP8 \\
--prompt "a cup of coffee on the table" \\
--height 1024 --width 1024 --num-inference-steps 20 --seed 42 \\
--output-json /mnt/data4/cwq/tmp/qwen_image_fp8_checkpoint_similarity.json
If the checkpoint does not carry a loadable quantization config, add
--candidate-quantization-config-json, for example '{"method":"fp8"}'.
"""
from __future__ import annotations
import argparse
import gc
import json
import math
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
import torch
import torch.nn.functional as F
@dataclass
class VariantConfig:
label: str
model: str
quantization: str | None
quantization_config: dict[str, Any] | None
diffusion_load_format: str
@dataclass
class VariantRun:
label: str
result: Any
generation_times_s: list[float]
peak_memory_mb: list[float | None]
def metric_guidance() -> dict[str, Any]:
"""Human-readable metric notes and default heuristic thresholds."""
return {
"scope": (
"Heuristic defaults for same-model comparisons with identical prompt, seed, resolution, scheduler, "
"and inference steps. Tune thresholds per model family, task, and quantization method; visual review is "
"still recommended for release gating."
),
"descriptions": {
"output_metrics": (
"Pixel-space metrics computed on generated RGB images or video frames after decode. These are often "
"the most actionable signal for image/video quality regressions."
),
"cosine_similarity": (
"Higher is better. Measures vector direction similarity and is less sensitive to scale."
),
"mae": (
"Lower is better. Mean absolute error in the tensor's native scale; uint8 output MAE is in "
"pixel values."
),
"mse": "Lower is better. Mean squared error; more sensitive to large localized differences than MAE.",
"rmse": "Lower is better. Square root of MSE, in the same unit as the compared tensor.",
"max_abs": (
"Lower is better. Worst absolute element error; useful for debugging outliers, not stable as a gate."
),
"l2": "Lower is better. Absolute L2 distance; shape- and scale-dependent.",
"relative_l2": "Lower is better. L2 distance normalized by the reference L2 norm.",
"psnr_db": "Higher is better. Pixel-space signal-to-noise ratio in dB for uint8 images/frames.",
"generation_time_s": "Lower is better. Wall-clock time for the last measured generation run.",
"avg_generation_time_s": "Lower is better. Mean wall-clock time across measured runs.",
"peak_memory_mb": (
"Lower is better. Worker-reported peak device memory for the last measured generation run."
),
"max_peak_memory_mb": "Lower is better. Maximum worker-reported peak memory across measured runs.",
},
"recommended_thresholds": {
"output_images_or_frames_uint8": {
"psnr_db": {
"recommended_min": 20.0,
"good_min": 25.0,
"strict_min": 30.0,
"note": (
"For stochastic diffusion outputs, 20 dB is a practical smoke threshold; 25+ dB is usually "
"close."
),
},
"mae": {
"recommended_max": 12.0,
"good_max": 6.0,
"strict_max": 3.0,
"note": "Measured on uint8 RGB pixels or frames.",
},
"cosine_similarity": {
"recommended_min": 0.98,
"strict_min": 0.995,
"note": "Useful as a broad image/frame similarity sanity check.",
},
"relative_l2": {
"recommended_max": 0.20,
"strict_max": 0.08,
"note": "Pixel-space relative L2 is generally more interpretable than latent-space relative L2.",
},
},
"performance": {
"avg_generation_time_ratio_candidate_over_reference": {
"recommended_max": 1.10,
"note": (
"A value above 1.10 suggests a latency regression unless expected for the quantization mode."
),
},
"max_peak_memory_ratio_candidate_over_reference": {
"recommended_max": 1.00,
"target_max": 0.95,
"note": (
"Quantization should usually not increase peak memory; <=0.95 indicates a meaningful saving."
),
},
},
},
}
def _split_csv(value: str | None) -> list[str]:
if not value:
return []
return [item.strip() for item in value.split(",") if item.strip()]
def _load_json_arg(value: str | None) -> dict[str, Any] | None:
if value is None:
return None
path = Path(value).expanduser()
if path.exists():
value = path.read_text(encoding="utf-8")
parsed = json.loads(value)
if not isinstance(parsed, dict):
raise ValueError("quantization config JSON must decode to an object.")
return parsed
def _cosine_similarity(flat_a: torch.Tensor, flat_b: torch.Tensor) -> float:
norm_a = torch.linalg.vector_norm(flat_a).item()
norm_b = torch.linalg.vector_norm(flat_b).item()
if norm_a == 0.0 and norm_b == 0.0:
return 1.0
if norm_a == 0.0 or norm_b == 0.0:
return 0.0
cosine = float(F.cosine_similarity(flat_a, flat_b, dim=0).item())
return max(-1.0, min(1.0, cosine))
def compute_tensor_metrics(lhs: Any, rhs: Any) -> dict[str, float]:
lhs_tensor = torch.as_tensor(lhs).detach().cpu().double()
rhs_tensor = torch.as_tensor(rhs).detach().cpu().double()
if lhs_tensor.shape != rhs_tensor.shape:
raise ValueError(f"Metric shape mismatch: {tuple(lhs_tensor.shape)} vs {tuple(rhs_tensor.shape)}")
diff = lhs_tensor - rhs_tensor
mse = float(diff.square().mean().item())
rmse = float(math.sqrt(mse))
mae = float(diff.abs().mean().item())
max_abs = float(diff.abs().max().item())
l2 = float(torch.linalg.vector_norm(diff).item())
ref_l2 = float(torch.linalg.vector_norm(lhs_tensor).item())
relative_l2 = 0.0 if ref_l2 == 0.0 and l2 == 0.0 else float("inf") if ref_l2 == 0.0 else l2 / ref_l2
cosine = _cosine_similarity(lhs_tensor.reshape(-1), rhs_tensor.reshape(-1))
return {
"cosine_similarity": cosine,
"mae": mae,
"mse": mse,
"rmse": rmse,
"max_abs": max_abs,
"l2": l2,
"relative_l2": relative_l2,
}
def compute_uint8_image_metrics(lhs: Any, rhs: Any) -> dict[str, float]:
metrics = compute_tensor_metrics(lhs, rhs)
mse = metrics["mse"]
metrics["psnr_db"] = float("inf") if mse == 0.0 else 20 * math.log10(255.0) - 10 * math.log10(mse)
return metrics
def summarize_output_frame_metrics(reference_frames: list[Any], candidate_frames: list[Any]) -> dict[str, Any]:
if len(reference_frames) != len(candidate_frames):
raise ValueError(f"Output frame count mismatch: {len(reference_frames)} vs {len(candidate_frames)}")
if not reference_frames:
raise ValueError("No output frames available for comparison.")
ref_stack = np.stack([np.asarray(frame.convert("RGB")) for frame in reference_frames], axis=0)
cand_stack = np.stack([np.asarray(frame.convert("RGB")) for frame in candidate_frames], axis=0)
frame0_metrics = compute_uint8_image_metrics(ref_stack[0], cand_stack[0])
mid_index = len(reference_frames) // 2
mid_metrics = compute_uint8_image_metrics(ref_stack[mid_index], cand_stack[mid_index])
all_metrics = compute_uint8_image_metrics(ref_stack, cand_stack)
return {
"num_frames": len(reference_frames),
"frame0_metrics": frame0_metrics,
"mid_frame_index": mid_index,
"mid_frame_metrics": mid_metrics,
"all_frames_metrics": all_metrics,
# Backward-compatible aliases for existing image callers.
"num_images": len(reference_frames),
"image0_metrics": frame0_metrics,
"mid_image_index": mid_index,
"mid_image_metrics": mid_metrics,
"all_images_metrics": all_metrics,
}
def summarize_output_image_metrics(reference_images: list[Any], candidate_images: list[Any]) -> dict[str, Any]:
return summarize_output_frame_metrics(reference_images, candidate_images)
def _extract_inner_output(outputs: Any) -> Any:
if isinstance(outputs, list):
if len(outputs) != 1:
raise ValueError(f"Expected one request output, got {len(outputs)}.")
outputs = outputs[0]
inner = getattr(outputs, "request_output", None)
if inner is not None:
return inner
return outputs
def _request_peak_memory_mb(result: Any) -> float | None:
diffusion_output = getattr(result, "request_output", None)
peak_memory_mb = getattr(diffusion_output, "peak_memory_mb", None)
if peak_memory_mb is None:
peak_memory_mb = getattr(result, "peak_memory_mb", None)
if peak_memory_mb is None:
return None
return float(peak_memory_mb)
def _build_quantization_config(
*,
quantization: str | None,
quantization_config_json: str | None,
ignored_layers: str | None,
gguf_model: str | None,
) -> dict[str, Any] | None:
explicit = _load_json_arg(quantization_config_json)
if explicit is not None:
return explicit
if quantization is None:
return None
config: dict[str, Any] = {"method": quantization}
ignored = _split_csv(ignored_layers)
if ignored:
config["ignored_layers"] = ignored
if gguf_model is not None:
config["gguf_model"] = gguf_model
return config
def _build_variant_config(args: argparse.Namespace, variant: str) -> VariantConfig:
common_ignored_layers = args.ignored_layers if variant == "candidate" else None
ignored_layers = getattr(args, f"{variant}_ignored_layers") or common_ignored_layers
quantization = getattr(args, f"{variant}_quantization")
quantization_config = _build_quantization_config(
quantization=quantization,
quantization_config_json=getattr(args, f"{variant}_quantization_config_json"),
ignored_layers=ignored_layers,
gguf_model=getattr(args, f"{variant}_gguf_model"),
)
return VariantConfig(
label=variant,
model=getattr(args, f"{variant}_model") or args.model,
quantization=quantization if quantization_config is None else None,
quantization_config=quantization_config,
diffusion_load_format=getattr(args, f"{variant}_load_format"),
)
def _build_omni_kwargs(args: argparse.Namespace, config: VariantConfig) -> dict[str, Any]:
from vllm_omni.diffusion.data import DiffusionParallelConfig
parallel_config = DiffusionParallelConfig(
ulysses_degree=args.ulysses_degree,
ring_degree=args.ring_degree,
cfg_parallel_size=args.cfg_parallel_size,
tensor_parallel_size=args.tensor_parallel_size,
vae_patch_parallel_size=args.vae_patch_parallel_size,
)
kwargs: dict[str, Any] = {
"model": config.model,
"mode": "text-to-video" if args.task == "t2v" else "text-to-image",
"parallel_config": parallel_config,
"enforce_eager": args.enforce_eager,
"enable_cpu_offload": args.enable_cpu_offload,
"enable_layerwise_offload": args.enable_layerwise_offload,
"vae_use_slicing": args.vae_use_slicing,
"vae_use_tiling": args.vae_use_tiling,
"step_execution": args.step_execution if args.task == "t2i" else False,
"diffusion_load_format": config.diffusion_load_format,
}
if args.model_class_name:
kwargs["model_class_name"] = args.model_class_name
if args.flow_shift is not None:
kwargs["flow_shift"] = args.flow_shift
if config.quantization_config is not None:
kwargs["quantization_config"] = config.quantization_config
elif config.quantization is not None:
kwargs["quantization"] = config.quantization
return kwargs
def _build_sampling_params(args: argparse.Namespace, seed: int):
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.platforms import current_omni_platform
generator = torch.Generator(device=current_omni_platform.device_type).manual_seed(seed)
kwargs: dict[str, Any] = {
"height": args.height,
"width": args.width,
"generator": generator,
"seed": seed,
"guidance_scale": args.guidance_scale,
"guidance_scale_2": args.guidance_scale_2,
"num_inference_steps": args.num_inference_steps,
"return_frames": True,
"extra_args": {
"timesteps_shift": args.timesteps_shift,
"cfg_schedule": args.cfg_schedule,
"use_norm": args.use_norm,
"use_system_prompt": args.use_system_prompt,
"system_prompt": args.system_prompt,
},
}
if args.task == "t2v":
kwargs["num_frames"] = args.num_frames
kwargs["fps"] = args.fps
kwargs["frame_rate"] = args.frame_rate
else:
kwargs["true_cfg_scale"] = args.cfg_scale
kwargs["num_outputs_per_prompt"] = args.num_images_per_prompt
return OmniDiffusionSamplingParams(**kwargs)
def _run_variant(args: argparse.Namespace, config: VariantConfig) -> VariantRun:
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.platforms import current_omni_platform
omni = Omni(**_build_omni_kwargs(args, config))
measured_results: list[Any] = []
generation_times: list[float] = []
peak_memory_mb: list[float | None] = []
try:
for _ in range(args.warmup_runs):
sampling_params = _build_sampling_params(args, args.seed)
omni.generate(
{"prompt": args.prompt, "negative_prompt": args.negative_prompt},
sampling_params,
use_tqdm=False,
)
for _ in range(args.measure_runs):
sampling_params = _build_sampling_params(args, args.seed)
start = time.perf_counter()
outputs = omni.generate(
{"prompt": args.prompt, "negative_prompt": args.negative_prompt},
sampling_params,
use_tqdm=False,
)
current_omni_platform.synchronize()
generation_times.append(time.perf_counter() - start)
result = _extract_inner_output(outputs)
peak_memory_mb.append(_request_peak_memory_mb(result))
measured_results.append(result)
finally:
omni.close()
del omni
gc.collect()
current_omni_platform.empty_cache()
if not measured_results:
raise RuntimeError("No measured results were produced.")
return VariantRun(
label=config.label,
result=measured_results[-1],
generation_times_s=generation_times,
peak_memory_mb=peak_memory_mb,
)
def _get_output_frames(result: Any) -> list[Any]:
images = list(getattr(result, "images", []) or [])
if len(images) == 1 and isinstance(images[0], list):
return list(images[0])
return images
def _save_outputs(result: Any, output_dir: Path, label: str, task: str, fps: int) -> list[str]:
frames = _get_output_frames(result)
saved: list[str] = []
if not frames:
return saved
variant_dir = output_dir / label
variant_dir.mkdir(parents=True, exist_ok=True)
if task == "t2v":
from diffusers.utils import export_to_video
video_path = variant_dir / "video.mp4"
export_to_video(frames, str(video_path), fps=fps)
saved.append(str(video_path))
for idx in (0, len(frames) // 2, len(frames) - 1):
path = variant_dir / f"frame_{idx}.png"
frames[idx].save(path)
saved.append(str(path))
return saved
for idx, image in enumerate(frames):
path = variant_dir / f"image_{idx}.png"
image.save(path)
saved.append(str(path))
return saved
def _run_summary(run: VariantRun) -> dict[str, Any]:
valid_peak = [value for value in run.peak_memory_mb if value is not None]
return {
"generation_time_s": run.generation_times_s[-1],
"avg_generation_time_s": sum(run.generation_times_s) / len(run.generation_times_s),
"per_run_generation_time_s": run.generation_times_s,
"peak_memory_mb": valid_peak[-1] if valid_peak else None,
"avg_peak_memory_mb": sum(valid_peak) / len(valid_peak) if valid_peak else None,
"max_peak_memory_mb": max(valid_peak) if valid_peak else None,
"per_run_peak_memory_mb": run.peak_memory_mb,
}
def _to_jsonable(result: dict[str, Any]) -> dict[str, Any]:
return json.loads(json.dumps(result, allow_nan=True))
def run_comparison(args: argparse.Namespace) -> dict[str, Any]:
if args.warmup_runs < 0:
raise ValueError("--warmup-runs must be >= 0.")
if args.measure_runs <= 0:
raise ValueError("--measure-runs must be >= 1.")
reference_config = _build_variant_config(args, "reference")
candidate_config = _build_variant_config(args, "candidate")
reference_run = _run_variant(args, reference_config)
candidate_run = _run_variant(args, candidate_config)
save_output_paths: dict[str, list[str]] = {}
if args.save_output_dir:
save_dir = Path(args.save_output_dir).expanduser().resolve()
save_output_paths["reference"] = _save_outputs(reference_run.result, save_dir, "reference", args.task, args.fps)
save_output_paths["candidate"] = _save_outputs(candidate_run.result, save_dir, "candidate", args.task, args.fps)
result = {
"model": args.model,
"prompt": args.prompt,
"negative_prompt": args.negative_prompt,
"seed": args.seed,
"warmup_runs": args.warmup_runs,
"measure_runs": args.measure_runs,
"variant_configs": {
"reference": reference_config.__dict__,
"candidate": candidate_config.__dict__,
},
"sampling_kwargs": {
"task": args.task,
"width": args.width,
"height": args.height,
"num_frames": args.num_frames if args.task == "t2v" else None,
"num_inference_steps": args.num_inference_steps,
"guidance_scale": args.guidance_scale,
"cfg_scale": args.cfg_scale,
"guidance_scale_2": args.guidance_scale_2,
"flow_shift": args.flow_shift,
"num_images_per_prompt": args.num_images_per_prompt,
"step_execution": args.step_execution if args.task == "t2i" else False,
},
"metric_guidance": metric_guidance(),
"reference_generation": _run_summary(reference_run),
"candidate_generation": _run_summary(candidate_run),
"output_metrics": summarize_output_image_metrics(
_get_output_frames(reference_run.result),
_get_output_frames(candidate_run.result),
),
}
if save_output_paths:
result["saved_outputs"] = save_output_paths
return _to_jsonable(result)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("--task", choices=["t2i", "t2v"], default="t2i")
parser.add_argument("--model", default="Qwen/Qwen-Image", help="Default model for both variants.")
parser.add_argument("--model-class-name", help="Optional diffusion pipeline class override.")
parser.add_argument("--reference-model", help="Reference model path or HF ID. Defaults to --model.")
parser.add_argument("--candidate-model", help="Candidate model path or HF ID. Defaults to --model.")
parser.add_argument("--reference-quantization", help="Reference online quantization method.")
parser.add_argument("--candidate-quantization", help="Candidate online quantization method, e.g. fp8.")
parser.add_argument(
"--reference-quantization-config-json",
help="Reference quantization_config JSON string or file.",
)
parser.add_argument(
"--candidate-quantization-config-json",
help="Candidate quantization_config JSON string or file.",
)
parser.add_argument("--reference-ignored-layers", help="Comma-separated reference ignored layer patterns.")
parser.add_argument("--candidate-ignored-layers", help="Comma-separated candidate ignored layer patterns.")
parser.add_argument("--ignored-layers", help="Alias for --candidate-ignored-layers.")
parser.add_argument("--reference-gguf-model", help="Reference GGUF file or HF reference when using gguf.")
parser.add_argument("--candidate-gguf-model", help="Candidate GGUF file or HF reference when using gguf.")
parser.add_argument("--reference-load-format", default="default", help="Reference diffusion load format.")
parser.add_argument("--candidate-load-format", default="default", help="Candidate diffusion load format.")
parser.add_argument("--prompt", default="a cup of coffee on the table")
parser.add_argument("--negative-prompt")
parser.add_argument("--output-json", required=True)
parser.add_argument("--save-output-dir")
parser.add_argument("--width", type=int, default=1024)
parser.add_argument("--height", type=int, default=1024)
parser.add_argument("--num-frames", type=int, default=1, help="Number of frames for t2v.")
parser.add_argument("--fps", type=int, default=24, help="FPS for saved t2v videos.")
parser.add_argument("--frame-rate", type=float, help="Optional generation frame rate for t2v.")
parser.add_argument("--num-inference-steps", type=int, default=50)
parser.add_argument("--num-images-per-prompt", type=int, default=1)
parser.add_argument("--guidance-scale", type=float, default=4.0)
parser.add_argument("--cfg-scale", type=float, default=4.0, help="Qwen-Image true CFG scale.")
parser.add_argument("--guidance-scale-2", type=float)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--warmup-runs", type=int, default=0)
parser.add_argument("--measure-runs", type=int, default=1)
parser.add_argument("--ulysses-degree", type=int, default=1)
parser.add_argument("--ring-degree", type=int, default=1)
parser.add_argument("--cfg-parallel-size", type=int, default=1, choices=[1, 2])
parser.add_argument("--tensor-parallel-size", type=int, default=1)
parser.add_argument("--vae-patch-parallel-size", type=int, default=1)
parser.add_argument("--enforce-eager", action="store_true")
parser.add_argument("--enable-cpu-offload", action="store_true")
parser.add_argument("--enable-layerwise-offload", action="store_true")
parser.add_argument("--vae-use-slicing", action="store_true")
parser.add_argument("--vae-use-tiling", action="store_true")
parser.add_argument("--flow-shift", type=float)
parser.add_argument(
"--step-execution",
action=argparse.BooleanOptionalAction,
default=False,
help=(
"Use the diffusion step scheduler for text-to-image models. Disabled by default so the tool follows the "
"normal offline inference path unless explicitly requested."
),
)
parser.add_argument("--timesteps-shift", type=float, default=1.0)
parser.add_argument("--cfg-schedule", choices=["constant", "linear"], default="constant")
parser.add_argument("--use-norm", action="store_true")
parser.add_argument(
"--use-system-prompt",
choices=[
"None",
"dynamic",
"en_vanilla",
"en_recaption",
"en_think_recaption",
"en_unified",
"custom",
],
)
parser.add_argument("--system-prompt")
return parser.parse_args()
def main() -> None:
args = parse_args()
output_json = Path(args.output_json).expanduser().resolve()
output_json.parent.mkdir(parents=True, exist_ok=True)
result = run_comparison(args)
output_json.write_text(json.dumps(result, indent=2, sort_keys=True), encoding="utf-8")
image0 = result["output_metrics"]["image0_metrics"]
summary = {
"output_json": str(output_json),
"reference_avg_generation_time_s": result["reference_generation"]["avg_generation_time_s"],
"candidate_avg_generation_time_s": result["candidate_generation"]["avg_generation_time_s"],
"image0_psnr_db": image0["psnr_db"],
"image0_mae": image0["mae"],
}
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()
@@ -0,0 +1,491 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Merge W4A4_MXFP4_DUALSCALE quantized Wan2.2 weights into HF Diffusers format.
msModelSlim produces a checkpoint where each linear layer is either:
- W4A4_MXFP4_DUALSCALE: quantized weights with fine/coarse scales and mul_scale
- FLOAT (BF16 fallback): kept as original BF16 weights for precision-sensitive layers
BF16 fallback layers may be interleaved anywhere in the transformer (not just leading
blocks). The merge script detects them from quant_model_description.json and writes
their prefixes into config.json as ignored_layers so the runtime dynamically routes
each layer to the correct quantization method at weight-loading time.
MXFP4_DUALSCALE key structure per linear layer (msModelSlim naming)
---------------------------------------------------------------------
blocks.N.X.linear.weight W4A4_MXFP4_DUALSCALE – int8 (FP4 packed)
blocks.N.X.linear.weight_scale W4A4_MXFP4_DUALSCALE – uint8 (float8_e8m0fnu fine scale, per-32K)
blocks.N.X.linear.weight_dual_scale W4A4_MXFP4_DUALSCALE – float32 (coarse scale, per-512K)
blocks.N.X.linear.bias FLOAT – bias (if present)
blocks.N.X.div.mul_scale FLOAT – float32 per-input-channel activation pre-scale
BF16 fallback key structure (no wrappers, plain linear weights):
blocks.N.X.weight FLOAT
condition_embedder.*.weight FLOAT (always BF16 — not quantized)
Self-attention QKV notes
------------------------
Self-attention Q/K/V weights are separate in the checkpoint (self_attn.q/k/v) but fused
into a single to_qkv layer in vllm-omni. The transformer's load_weights() handles this via
stacked_params_mapping. This script keeps Q/K/V keys separate — do NOT pre-fuse them here.
For mul_scale specifically: even though Q/K/V process the same input (same mul_scale value),
they are kept separate. load_weights() routes all three to the same to_qkv.mul_scale parameter
and each overwrites the previous. Since Q=K=V for mul_scale, the final value is correct.
NOTE: Pre-fusing as to_qkv.mul_scale would BREAK loading because ".attn1.to_q" is a
substring of ".attn1.to_qkv", causing load_weights() stacked_params_mapping to produce a
garbage key ("to_qkvkv") that is not in params_dict, triggering a break that skips the
direct-load else branch entirely.
Supported model types:
- Wan2.2-T2V-A14B (MoE cascade: transformer + transformer_2)
- Wan2.2-I2V-A14B (MoE cascade: transformer + transformer_2)
Note: Wan2.2-TI2V-5B is NOT supported. Its smaller parameter count causes
unacceptable accuracy loss under W4A4 quantization. Use MXFP8 for TI2V-5B.
Usage:
python merge_mxfp4_dualscale_checkpoint.py \\
--model-type Wan2.2-T2V-A14B \\
--original-model /path/to/Wan2.2-T2V-A14B-Diffusers \\
--quant-path /path/to/msmodelslim-output \\
--output-path /path/to/merged-output
"""
from __future__ import annotations
import argparse
import json
import pathlib
import re
import shutil
from typing import Any
import torch
from safetensors.torch import load_file, save_file
# ---------------------------------------------------------------------------
# Key rename: msModelSlim naming → Diffusers / vllm-omni naming
# Identical to merge_mxfp8_checkpoint.py; applied to all blocks uniformly.
# ---------------------------------------------------------------------------
TRANSFORMER_KEYS_RENAME_DICT: dict[str, str] = {
"time_embedding.0": "condition_embedder.time_embedder.linear_1",
"time_embedding.2": "condition_embedder.time_embedder.linear_2",
"text_embedding.0": "condition_embedder.text_embedder.linear_1",
"text_embedding.2": "condition_embedder.text_embedder.linear_2",
"time_projection.1": "condition_embedder.time_proj",
"head.modulation": "scale_shift_table",
"head.head": "proj_out",
"modulation": "scale_shift_table",
"ffn.0": "ffn.net.0.proj",
"ffn.2": "ffn.net.2",
# Norm order swap (quant tool: norm1, norm3, norm2 → diffusers: norm1, norm2, norm3)
"norm2": "norm__placeholder",
"norm3": "norm2",
"norm__placeholder": "norm3",
# Self-attention
"self_attn.q": "attn1.to_q",
"self_attn.k": "attn1.to_k",
"self_attn.v": "attn1.to_v",
"self_attn.o": "attn1.to_out.0",
"self_attn.norm_q": "attn1.norm_q",
"self_attn.norm_k": "attn1.norm_k",
# Cross-attention
"cross_attn.q": "attn2.to_q",
"cross_attn.k": "attn2.to_k",
"cross_attn.v": "attn2.to_v",
"cross_attn.o": "attn2.to_out.0",
"cross_attn.norm_q": "attn2.norm_q",
"cross_attn.norm_k": "attn2.norm_k",
"attn2.to_k_img": "attn2.add_k_proj",
"attn2.to_v_img": "attn2.add_v_proj",
"attn2.norm_k_img": "attn2.norm_added_k",
# I2V image embedder
"img_emb.proj.0": "condition_embedder.image_embedder.norm1",
"img_emb.proj.1": "condition_embedder.image_embedder.ff.net.0.proj",
"img_emb.proj.3": "condition_embedder.image_embedder.ff.net.2",
"img_emb.proj.4": "condition_embedder.image_embedder.norm2",
"img_emb.emb_pos": "condition_embedder.image_embedder.pos_embed",
}
SUPPORTED_MODEL_TYPES = ["Wan2.2-T2V-A14B", "Wan2.2-I2V-A14B"]
CASCADE_MODEL_TYPES = {"Wan2.2-T2V-A14B", "Wan2.2-I2V-A14B"}
# Suffixes that appear inside .linear.* wrapper for MXFP4 tensors.
_LINEAR_ATTRS = ("weight_dual_scale", "weight_scale", "weight", "bias")
_BLOCK_IDX_RE = re.compile(r"^blocks\.(\d+)\.")
# ---------------------------------------------------------------------------
# Key transformation helpers
# ---------------------------------------------------------------------------
def _parse_block_idx(key: str) -> int | None:
"""Extract block index from a key like 'blocks.5.attn1.to_q.weight'."""
m = _BLOCK_IDX_RE.match(key)
return int(m.group(1)) if m else None
def _apply_rename_dict(key: str) -> str:
for src, dst in TRANSFORMER_KEYS_RENAME_DICT.items():
key = key.replace(src, dst)
return key
def _strip_mxfp4_wrapper(key: str) -> str:
"""Strip .linear.ATTR or .div.mul_scale wrappers added by msModelSlim.
MXFP4 tensors are wrapped in sub-modules:
X.linear.weight / weight_scale / weight_dual_scale / bias
X.div.mul_scale
MXFP8 and FLOAT tensors have no wrappers — this function is a no-op for them.
Examples after apply_rename_dict:
attn1.to_q.linear.weight → attn1.to_q.weight
attn1.to_q.linear.weight_scale → attn1.to_q.weight_scale
attn1.to_q.div.mul_scale → attn1.to_q.mul_scale
attn1.norm_q.weight → attn1.norm_q.weight (unchanged)
"""
# Check longest attribute names first to avoid partial suffix matches.
for attr in _LINEAR_ATTRS:
suffix = f".linear.{attr}"
if key.endswith(suffix):
return key[: -len(suffix)] + f".{attr}"
if key.endswith(".div.mul_scale"):
return key[: -len(".div.mul_scale")] + ".mul_scale"
return key
# ---------------------------------------------------------------------------
# Quantization metadata helpers
# ---------------------------------------------------------------------------
# Known quantized weight types (FLOAT tensors don't determine block type).
_MXFP8_TYPE = "mxfp8"
_MXFP4_DUALSCALE_TYPE = "mxfp4_dualscale"
def _classify_blocks(quant_meta: dict[str, str]) -> dict[int, str]:
"""Classify each transformer block by quantization type from quant_meta.
Returns a dict mapping block_idx → 'mxfp8' | 'mxfp4_dualscale'.
A block's type is determined by the first quantized (non-FLOAT) tensor found for it.
"""
block_types: dict[int, str] = {}
for key, qtype in quant_meta.items():
idx = _parse_block_idx(key)
if idx is None or idx in block_types:
continue
if qtype.startswith("W8A8_MXFP8"):
block_types[idx] = _MXFP8_TYPE
elif qtype.startswith("W4A4_MXFP4_DUALSCALE"):
block_types[idx] = _MXFP4_DUALSCALE_TYPE
return block_types
def _print_block_summary(block_types: dict[int, str]) -> None:
"""Print a compact run-length summary of the block layout."""
if not block_types:
print(" Block layout: (empty)")
return
sorted_indices = sorted(block_types)
runs: list[tuple[int, int, str]] = []
run_start = sorted_indices[0]
run_type = block_types[run_start]
for idx in sorted_indices[1:]:
if block_types[idx] != run_type:
runs.append((run_start, idx - 1, run_type))
run_start = idx
run_type = block_types[idx]
runs.append((run_start, sorted_indices[-1], run_type))
print(f" Block layout ({len(sorted_indices)} blocks classified):")
for start, end, btype in runs:
count = end - start + 1
range_str = f"{start}" if start == end else f"{start}–{end}"
print(f" blocks {range_str:>8}: {btype} ({count} block{'s' if count > 1 else ''})")
# ---------------------------------------------------------------------------
# Safetensors I/O
# ---------------------------------------------------------------------------
def _load_safetensors_dir(directory: pathlib.Path, glob: str = "*.safetensors") -> dict[str, torch.Tensor]:
candidates = sorted(directory.glob(glob))
if not candidates:
raise FileNotFoundError(f"No safetensors matching '{glob}' found in {directory}")
state: dict[str, torch.Tensor] = {}
for f in candidates:
state.update(load_file(str(f)))
return state
def _load_quant_safetensors(directory: pathlib.Path) -> dict[str, torch.Tensor]:
try:
return _load_safetensors_dir(directory, "quant_model_weight*.safetensors")
except FileNotFoundError:
return _load_safetensors_dir(directory)
def _load_quant_meta(directory: pathlib.Path) -> dict[str, str]:
candidates = sorted(directory.glob("quant_model_description*.json"))
if not candidates:
print(f" WARNING: No quant_model_description*.json in {directory}; treating all tensors as FLOAT.")
return {}
with open(candidates[0]) as f:
return json.load(f)
# ---------------------------------------------------------------------------
# Per-transformer conversion
# ---------------------------------------------------------------------------
def _is_mxfp4_tensor(key: str, qtype: str) -> bool:
"""Return True for MXFP4 quantized tensors and their companion tensors.
MXFP4 DualScale layers produce four tensor types:
.linear.weight / .linear.weight_scale / .linear.weight_dual_scale (W4A4_MXFP4_DUALSCALE)
.linear.bias / .div.mul_scale (FLOAT but companion to a quantized layer)
BF16 fallback layers have plain .weight / .bias without .linear. / .div. wrappers.
"""
if qtype.startswith("W4A4_MXFP4_DUALSCALE"):
return True
# Companion tensors: bias and mul_scale that belong to an MXFP4 layer.
return ".linear." in key or ".div.mul_scale" in key
def _diffusers_to_vllm_ignored(diffusers_ignored: list[str]) -> list[str]:
"""Translate diffusers checkpoint prefixes to vllm-omni model parameter names.
Three transformations align the naming conventions:
1. Self-attention QKV fusion (attn1 only, not attn2):
attn1.to_q + attn1.to_k + attn1.to_v → attn1.to_qkv
Cross-attention (attn2) to_q/k/v are not fused and remain separate.
2. FFN naming:
ffn.net.0.proj → ffn.net_0.proj
ffn.net.2 → ffn.net_2
3. to_out index:
attn1.to_out.0 / attn2.to_out.0 → attn1.to_out / attn2.to_out
"""
ignored_set = set(diffusers_ignored)
result: set[str] = set()
for name in diffusers_ignored:
m = re.match(r"^(.*\.attn1)\.to_([qkv])$", name)
if m:
prefix = m.group(1)
if all(f"{prefix}.to_{c}" in ignored_set for c in ("q", "k", "v")):
result.add(f"{prefix}.to_qkv")
else:
present = [f"to_{c}" for c in ("q", "k", "v") if f"{prefix}.to_{c}" in ignored_set]
missing = [f"to_{c}" for c in ("q", "k", "v") if f"{prefix}.to_{c}" not in ignored_set]
raise ValueError(
f"Partial BF16 fallback for '{prefix}': "
f"{', '.join(present)} in ignored_layers but {', '.join(missing)} is not. "
f"Self-attention Q/K/V are fused into a single to_qkv layer at runtime; "
f"all three must share the same precision. "
f"Either quantize all of to_q/to_k/to_v or keep all three in BF16."
)
continue
name = re.sub(r"\.ffn\.net\.0\.proj$", ".ffn.net_0.proj", name)
name = re.sub(r"\.ffn\.net\.2$", ".ffn.net_2", name)
name = re.sub(r"\.to_out\.0$", ".to_out", name)
result.add(name)
return sorted(result)
def _collect_ignored_layers(merged: dict[str, Any], mxfp4_layer_prefixes: set[str]) -> list[str]:
"""Collect vllm-omni parameter name prefixes for BF16 fallback layers.
A layer is BF16 if it has a .weight tensor but its prefix is not in
mxfp4_layer_prefixes. Prefixes are returned in vllm-omni parameter naming
(QKV-fused, FFN underscored, to_out unindexed) so the list can be written
directly into ignored_layers in config.json without further translation.
"""
all_weight_prefixes = {key[: -len(".weight")] for key in merged if key.endswith(".weight")}
return _diffusers_to_vllm_ignored(sorted(all_weight_prefixes - mxfp4_layer_prefixes))
def _convert_transformer(
quant_subdir: pathlib.Path,
output_dir: pathlib.Path,
original_transformer_dir: pathlib.Path,
) -> None:
"""Convert one transformer directory to the mxfp4_dualscale + BF16 mixed format."""
output_dir.mkdir(parents=True, exist_ok=True)
# BF16 base: provides the scaffold for non-MXFP4 tensors (norms, embeddings,
# BF16 fallback linear layers that msModelSlim may omit or keep as FLOAT).
print(f" Loading BF16 base from {original_transformer_dir} …")
base_state = _load_safetensors_dir(original_transformer_dir)
print(f" {len(base_state)} BF16 tensors loaded")
print(f" Loading quantized weights from {quant_subdir} …")
quant_state = _load_quant_safetensors(quant_subdir)
quant_meta = _load_quant_meta(quant_subdir)
print(f" {len(quant_state)} quant tensors, {len(quant_meta)} meta entries")
# Classify blocks for a compact summary (informational only in the new scheme).
block_types = _classify_blocks(quant_meta)
_print_block_summary(block_types)
# Remap MXFP4 quantized tensors only.
# BF16 fallback tensors (FLOAT in quant_meta, no .linear./.div. wrapper) are
# skipped here; the base_state provides them unchanged.
remapped: dict[str, torch.Tensor] = {}
remapped_meta: dict[str, str] = {}
mxfp4_layer_prefixes: set[str] = set()
skipped: list[str] = []
for key, tensor in quant_state.items():
qtype = quant_meta.get(key, "FLOAT")
if not _is_mxfp4_tensor(key, qtype):
continue # BF16 fallback — base_state already covers this tensor
renamed = _apply_rename_dict(key)
final_key = _strip_mxfp4_wrapper(renamed)
if final_key.endswith(".quant_type"):
skipped.append(key)
continue
remapped[final_key] = tensor
remapped_meta[final_key] = qtype
# Track MXFP4 layer prefixes (via their .weight keys) for ignored_layers.
if final_key.endswith(".weight") and qtype.startswith("W4A4_MXFP4_DUALSCALE"):
mxfp4_layer_prefixes.add(final_key[: -len(".weight")])
if skipped:
print(f" Skipped {len(skipped)} metadata keys (quant_type markers): {skipped[:5]}")
print(f" {len(remapped)} MXFP4 tensors remapped, {len(mxfp4_layer_prefixes)} quantized layers")
# Merge: base_state provides BF16 scaffold; MXFP4 tensors override their BF16 counterparts
# and add the new scale tensors (weight_scale, weight_dual_scale, mul_scale).
merged = {**base_state, **remapped}
# Determine ignored_layers: BF16 fallback layer prefixes in vllm-omni parameter naming.
ignored_layers = _collect_ignored_layers(merged, mxfp4_layer_prefixes)
print(f" {len(ignored_layers)} BF16 fallback layers → ignored_layers in config.json")
# Save weights.
out_weights = output_dir / "diffusion_pytorch_model.safetensors"
save_file(merged, str(out_weights))
print(f" Saved {len(merged)} tensors → {out_weights}")
# Save remapped quant metadata (for inspection / debugging).
out_meta_path = output_dir / "quant_model_description.json"
with open(out_meta_path, "w") as f:
json.dump(remapped_meta, f, indent=2)
# Inject quantization_config into config.json.
src_config = original_transformer_dir / "config.json"
if src_config.is_file():
with open(src_config) as f:
config = json.load(f)
config["quantization_config"] = _build_quant_config(ignored_layers)
out_config = output_dir / "config.json"
with open(out_config, "w") as f:
json.dump(config, f, indent=2)
print(f" Injected quantization_config (mxfp4_dualscale, {len(ignored_layers)} ignored_layers) → {out_config}")
else:
print(f" WARNING: No config.json at {src_config}; quantization_config not injected.")
def _build_quant_config(ignored_layers: list[str]) -> dict[str, Any]:
return {
"quant_method": "mxfp4_dualscale",
"is_checkpoint_serialized": True,
"ignored_layers": ignored_layers,
}
# ---------------------------------------------------------------------------
# Model-type helpers
# ---------------------------------------------------------------------------
def _get_transformer_dirs(model_type: str) -> list[str]:
return ["transformer", "transformer_2"] if model_type in CASCADE_MODEL_TYPES else ["transformer"]
def _get_quant_subdir(model_type: str, quant_path: pathlib.Path, transformer_dir: str) -> pathlib.Path:
if model_type in CASCADE_MODEL_TYPES:
sub = "high_noise_model" if transformer_dir == "transformer" else "low_noise_model"
return quant_path / sub
return quant_path
# ---------------------------------------------------------------------------
# Main repack
# ---------------------------------------------------------------------------
def repack(
model_type: str,
original_model_path: pathlib.Path,
quant_path: pathlib.Path,
output_path: pathlib.Path,
) -> None:
transformer_dirs = _get_transformer_dirs(model_type)
print(f"Copying original model to {output_path} (skipping {transformer_dirs}) …")
shutil.copytree(
str(original_model_path),
str(output_path),
ignore=shutil.ignore_patterns(*transformer_dirs),
)
for tdir in transformer_dirs:
q_subdir = _get_quant_subdir(model_type, quant_path, tdir)
out_tdir = output_path / tdir
orig_tdir = original_model_path / tdir
print(f"\nConverting {tdir} (quant source: {q_subdir.name}) …")
_convert_transformer(q_subdir, out_tdir, orig_tdir)
print(f"\nDone. Merged model → {output_path}")
print("\nRun inference (quantization auto-detected from config.json):")
print(f" python text_to_video.py --model {output_path}")
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main() -> None:
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("--model-type", required=True, choices=SUPPORTED_MODEL_TYPES, help="Model variant.")
parser.add_argument("--original-model", required=True, help="Original HF Diffusers model directory (BF16).")
parser.add_argument("--quant-path", required=True, help="msModelSlim quantized weights directory.")
parser.add_argument("--output-path", required=True, help="Output directory for merged model.")
args = parser.parse_args()
repack(
model_type=args.model_type,
original_model_path=pathlib.Path(args.original_model),
quant_path=pathlib.Path(args.quant_path),
output_path=pathlib.Path(args.output_path),
)
if __name__ == "__main__":
main()
@@ -17,7 +17,6 @@ _CLASS_TO_MODULE: dict[str, str] = {
"FishSpeechConfig": "vllm_omni.transformers_utils.configs.fish_speech",
"FishSpeechSlowARConfig": "vllm_omni.transformers_utils.configs.fish_speech",
"FishSpeechFastARConfig": "vllm_omni.transformers_utils.configs.fish_speech",
"VoxCPMConfig": "vllm_omni.transformers_utils.configs.voxcpm",
"VoxCPM2Config": "vllm_omni.transformers_utils.configs.voxcpm2",
"VoxtralTTSConfig": "vllm_omni.transformers_utils.configs.voxtral_tts",
"CosyVoice3Config": "vllm_omni.transformers_utils.configs.cosyvoice3",
@@ -37,7 +36,6 @@ __all__ = [
"FishSpeechConfig",
"FishSpeechSlowARConfig",
"FishSpeechFastARConfig",
"VoxCPMConfig",
"VoxCPM2Config",
"VoxtralTTSConfig",
"CosyVoice3Config",
@@ -70,6 +68,5 @@ from vllm_omni.transformers_utils.configs import fish_speech as _fish_speech #
from vllm_omni.transformers_utils.configs import mammoth_moda2 as _mammoth_moda2 # noqa: F401, E402
from vllm_omni.transformers_utils.configs import ming_flash_omni as _ming_flash_omni # noqa: F401, E402
from vllm_omni.transformers_utils.configs import omnivoice as _omnivoice # noqa: F401, E402
from vllm_omni.transformers_utils.configs import voxcpm as _voxcpm # noqa: F401, E402
from vllm_omni.transformers_utils.configs import voxcpm2 as _voxcpm2 # noqa: F401, E402
from vllm_omni.transformers_utils.configs import voxtral_tts as _voxtral_tts # noqa: F401, E402
@@ -1,68 +0,0 @@
from transformers import AutoConfig
from transformers.configuration_utils import PretrainedConfig
class VoxCPMConfig(PretrainedConfig):
model_type = "voxcpm"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
bos_token_id: int = 1,
eos_token_id: int = 2,
vocab_size: int = 32000,
hidden_size: int = 1024,
intermediate_size: int = 4096,
max_position_embeddings: int = 4096,
num_attention_heads: int = 16,
num_hidden_layers: int = 24,
num_key_value_heads: int = 16,
rms_norm_eps: float = 1e-6,
rope_theta: float = 10000.0,
rope_scaling: dict | None = None,
lm_config: dict | None = None,
encoder_config: dict | None = None,
dit_config: dict | None = None,
audio_vae_config: dict | None = None,
patch_size: int = 2,
feat_dim: int = 64,
residual_lm_num_layers: int = 6,
scalar_quantization_latent_dim: int = 256,
scalar_quantization_scale: int = 9,
max_length: int = 4096,
device: str = "cuda",
dtype: str = "bfloat16",
dit_mean_mode: bool = False,
**kwargs,
):
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.max_position_embeddings = max_position_embeddings
self.num_attention_heads = num_attention_heads
self.num_hidden_layers = num_hidden_layers
self.num_key_value_heads = num_key_value_heads
self.rms_norm_eps = rms_norm_eps
self.rope_theta = rope_theta
self.rope_scaling = rope_scaling
self.lm_config = lm_config or {}
self.encoder_config = encoder_config or {}
self.dit_config = dit_config or {}
self.audio_vae_config = audio_vae_config
self.patch_size = patch_size
self.feat_dim = feat_dim
self.residual_lm_num_layers = residual_lm_num_layers
self.scalar_quantization_latent_dim = scalar_quantization_latent_dim
self.scalar_quantization_scale = scalar_quantization_scale
self.max_length = max_length
self.device = device
self.dtype = dtype
self.dit_mean_mode = dit_mean_mode
AutoConfig.register("voxcpm", VoxCPMConfig)
__all__ = ["VoxCPMConfig"]