Merge main and preserve dispatch backlog across monitor windows

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 committed 2026-09-21 17:13:27 +08:00
commit ea7de7e3de
769 files changed
+73802 -22805

No files matched your search

+73 -182
View File
@@ -59,7 +59,11 @@ from vllm_omni.worker.omni_connector_model_runner_mixin import (
)
from vllm_omni.worker.output.payload_build import build_omni_mm_payload
from vllm_omni.worker.runner_assisted_metadata import RunnerAssistedFullAttentionMetadataRequest
from vllm_omni.worker.sampling_utils import clamp_prompt_ids_to_penalty_padding, sanitize_min_tokens_stop_ids
from vllm_omni.worker.sampling_utils import (
call_model_sampler,
clamp_prompt_ids_to_penalty_padding,
sanitize_min_tokens_stop_ids,
)
from vllm_omni.worker.sparse_audio import resolve_sparse_mm_routing
logger = init_logger(__name__)
@@ -342,6 +346,9 @@ class ExecuteModelState(NamedTuple):
multimodal_outputs: Any
# slot_mappings for attention/drafter (aligned with upstream v1 API)
slot_mappings: dict[str, torch.Tensor] | list[dict[str, torch.Tensor]] | None = None
# OMNI: prefix-cache step id; the step context saved under it must be
# consumed exactly once (materialize or discard_step) in sample_tokens.
prefix_cache_step_id: int | None = None
class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, DuplexSamplingRunnerMixin):
@@ -565,7 +572,14 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
CUDAGraphWrapper.clear_all_graphs()
BreakableCUDAGraphWrapper.clear_all_graphs()
# 6. Delegate to upstream shutdown (model = None, KV caches, workspace).
# 6. Stop the prefix-cache committer before the CUDA context and the
# tensors it copies from are torn down.
cache = self.omni_prefix_cache
if cache is not None:
cache.shutdown()
self.omni_prefix_cache = None
# 7. Delegate to upstream shutdown (model = None, KV caches, workspace).
super().shutdown()
def _capture_talker_mtp_graphs(self) -> None:
@@ -625,18 +639,6 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
finally:
set_cudagraph_capturing_enabled(False)
def _model_needs_full_prefix_hidden_states(self) -> bool:
"""Opt-out hook for models whose postprocess only consumes the tail.
When False, we skip both the per-step GPU->CPU hidden-state write into
OmniTensorPrefixCache and the merged-tensor reconstruction on hits;
postprocess receives the normal scheduled-token slice instead. Models
that need the full cached_prefix + new_tail span (default) are not
affected.
"""
model = getattr(self, "model", None)
return bool(getattr(model, "requires_full_prefix_cached_hidden_states", True))
def _get_runner_assisted_full_attention_metadata_request(
self,
*,
@@ -724,132 +726,34 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
)
return True
def _deferred_prefix_cache_mm_keys(self) -> set[str]:
"""Model-declared multimodal keys whose prefix-cache writes are deferred."""
model = getattr(self, "model", None)
keys = getattr(model, "deferred_prefix_cache_mm_keys", ())
return set(keys or ())
def _maybe_update_prefix_cache(
self,
hidden_states: torch.Tensor,
hidden_states_cpu: torch.Tensor | None,
multimodal_outputs: dict,
num_tokens_unpadded: int,
num_tokens_padded: int,
):
"""If prefix caching is enabled and it's the last pipeline parallelism rank,
retrieve the hidden states & multimodal outputs from the prefix cache based
on our batch slot mappings.
"""
# Cache hidden states if we've enabled hidden state prefix caching
# unless this isn't the last pipeline parallelism rank.
is_last_pp_rank = get_pp_group().is_last_rank
if hidden_states_cpu is not None and not is_last_pp_rank:
raise RuntimeError("hidden_states_cpu staging is only valid on the last pipeline parallel rank.")
if self.omni_prefix_cache is not None and is_last_pp_rank:
# If this happens, it generally means the model is not following the correct
# interface yet and is therefore currently not compatible with prefix cache.
hs_for_cache = hidden_states if self._model_needs_full_prefix_hidden_states() else None
# FIX: The .cpu attribute of slot_mapping is stale (not updated by the Triton
# _compute_slot_mapping_kernel which only writes to .gpu). We must use .gpu and
# sync back to CPU to get the correctly computed slot mapping.
slot_mapping_gpu = self.input_batch.block_table[0].slot_mapping.gpu
slot_mapping_cpu = slot_mapping_gpu[:num_tokens_padded].cpu()
self.omni_prefix_cache.update_omni_tensor_prefix_cache(
hidden_states=hs_for_cache,
multimodal_outputs=flatten_payload(multimodal_outputs) if multimodal_outputs else multimodal_outputs,
num_tokens_unpadded=num_tokens_unpadded,
slot_mapping=slot_mapping_cpu,
num_tokens_padded=num_tokens_padded,
skip_mm_cache_keys=self._deferred_prefix_cache_mm_keys(),
hidden_states_cpu=hidden_states_cpu,
)
def _maybe_get_combined_prefix_cache_tensors(
self,
hidden_states: torch.Tensor,
hidden_states_cpu: torch.Tensor | None,
multimodal_outputs: dict,
num_scheduled_tokens: dict[str, int],
) -> tuple[dict[str, torch.Tensor] | None, dict | None]:
"""If prefix caching is enabled, extract the merged hidden states and multimodal outputs for
all requests in the batch (including those that aren't a hit on Prefix cache).
"""
# Prior to applying the post-processing func, extract
# the prefix cached hidden states and multimodal states.
combined_hidden_states, combined_multimodal_outputs = None, None
is_last_pp_rank = get_pp_group().is_last_rank
if hidden_states_cpu is not None and not is_last_pp_rank:
raise RuntimeError("hidden_states_cpu staging is only valid on the last pipeline parallel rank.")
if self.omni_prefix_cache is not None:
if not is_last_pp_rank:
raise RuntimeError("Omni prefix-cache tensor merge is only valid on the last pipeline parallel rank.")
if (
not self._model_needs_full_prefix_hidden_states()
and not self.omni_prefix_cache.has_prefix_cached_new_req_ids()
):
return None, None
if self._model_needs_full_prefix_hidden_states():
combined_hidden_states = self.omni_prefix_cache.get_merged_hidden_states(
query_start_loc=self.query_start_loc.cpu,
input_batch=self.input_batch,
hidden_states=hidden_states,
hidden_states_cpu=hidden_states_cpu,
num_scheduled_tokens=num_scheduled_tokens,
)
combined_multimodal_outputs = self.omni_prefix_cache.get_merged_multimodal_states(
query_start_loc=self.query_start_loc.cpu,
input_batch=self.input_batch,
multimodal_outputs=flatten_payload(multimodal_outputs) if multimodal_outputs else multimodal_outputs,
num_scheduled_tokens=num_scheduled_tokens,
)
return combined_hidden_states, combined_multimodal_outputs
def _stage_deferred_prefix_cache_mm_outputs(
self,
*,
scheduler_output: SchedulerOutput,
multimodal_outputs: Any,
query_start_loc_cpu: Any,
) -> None:
if self.omni_prefix_cache is None:
return
deferred_mm_cache_keys = self._deferred_prefix_cache_mm_keys()
if not deferred_mm_cache_keys:
return
self.omni_prefix_cache.stage_deferred_mm_outputs(
query_start_loc=query_start_loc_cpu,
input_batch=self.input_batch,
multimodal_outputs=flatten_payload(multimodal_outputs) if multimodal_outputs else multimodal_outputs,
num_scheduled_tokens=scheduler_output.num_scheduled_tokens,
deferred_mm_cache_keys=deferred_mm_cache_keys,
)
def _prepare_prefix_cache_pooler_payload_sources(
self,
*,
hidden_states: torch.Tensor,
staged_hidden_states_cpu: torch.Tensor | None,
multimodal_outputs: Any,
scheduler_output: SchedulerOutput,
needs_scheduled_hidden_payload: bool,
req_ids: list[str],
step_id: int | None,
) -> tuple[torch.Tensor | None, dict[str, torch.Tensor] | None, dict | None]:
"""Prefix-cache payload sources for the pooler payload build.
req_ids must be the step's snapshot, not ``input_batch.req_ids``: under
async omni output this runs a step late, when the live batch has moved on.
"""
if not get_pp_group().is_last_rank:
raise RuntimeError("Omni prefix-cache merge is only valid on the last pipeline parallel rank.")
hidden_states_cpu = None
if needs_scheduled_hidden_payload:
if staged_hidden_states_cpu is None:
raise RuntimeError("Prefix-cache hidden-state payload requires staged CPU hidden states.")
hidden_states_cpu = staged_hidden_states_cpu
combined_hidden_states, combined_multimodal_outputs = self._maybe_get_combined_prefix_cache_tensors(
hidden_states,
staged_hidden_states_cpu,
multimodal_outputs,
scheduler_output.num_scheduled_tokens,
)
return hidden_states_cpu, combined_hidden_states, combined_multimodal_outputs
if step_id is None:
# save_outputs did not run this step (no last-rank AR output), so
# there is no step context to consume; serve the fresh slice.
if hidden_states_cpu is None and staged_hidden_states_cpu is not None:
hidden_states_cpu = staged_hidden_states_cpu
return hidden_states_cpu, None, None
combined_hidden, combined_mm = self._prefix_cache_materialize(step_id, list(req_ids))
return hidden_states_cpu, combined_hidden, combined_mm
def _build_omni_pooler_payload(
self,
@@ -956,15 +860,9 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
if hasattr(self.model, "_clear_warmup_state"):
self.model._clear_warmup_state()
# Async-write pipeline: apply any pending GPU->CPU prefix-cache writes
# whose copy event has already fired. Non-blocking — entries whose D2H
# is still in flight stay queued and will be picked up on the next
# step's drain. This guarantees any downstream read of
# ``omni_prefix_cache.hidden_states_cache`` /
# ``omni_prefix_cache.mm_outputs_cache`` in this step sees the
# state produced no later than the previous forward step.
if self.omni_prefix_cache is not None:
self.omni_prefix_cache.drain_ready_async_writes()
# Exactly once per real scheduler_output, before _update_states
# (dummy/warmup runs never reach execute_model).
self._prefix_cache_step_begin(scheduler_output)
# [Omni] Handle KV transfer BEFORE updating states (which removes finished requests)
finished_reqs = getattr(scheduler_output, "finished_requests_needing_kv_transfer", {})
@@ -988,12 +886,6 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
if flush_ids:
self.flush_full_payload_outputs(flush_ids)
if self.omni_prefix_cache is not None and scheduler_output.finished_req_ids:
self.omni_prefix_cache.commit_deferred_mm_outputs(
set(scheduler_output.finished_req_ids),
self.input_batch,
)
if self.routed_experts_initialized:
capturer = self.routed_experts_capturer
if capturer is not None and hasattr(capturer, "finalize_pending_copy"):
@@ -1294,30 +1186,22 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
else:
hidden_states, multimodal_outputs = self.extract_multimodal_outputs(model_output)
hidden_states_cpu = None
# Async-write pipeline (replaces the per-step blocking
# ``.to("cpu")`` + ``aten::index_put_`` on pageable host memory).
# Schedules non-blocking GPU->CPU copies on a dedicated stream;
# the actual CPU scatter into ``hidden_states_cache`` /
# ``mm_outputs_cache`` happens in ``drain_ready_async_writes``
# at the top of subsequent execute_model() calls.
if not self.is_pooling_model and self.omni_prefix_cache is not None and get_pp_group().is_last_rank:
hs_for_cache = hidden_states if self._model_needs_full_prefix_hidden_states() else None
# Some models (e.g. qwen3-tts-talker) opt out of full-hidden-state
# prefix caching but the downstream pooler payload path still
# needs a CPU hidden-states view. Materialize it synchronously
# in that case; the legacy behavior is preserved.
if hs_for_cache is None and self._model_omni_pooler_payload_include_hidden():
hidden_states_cpu = hidden_states[:num_tokens_unpadded].detach().to("cpu").contiguous()
slot_mapping_gpu = self.input_batch.block_table[0].slot_mapping.gpu
self.omni_prefix_cache.schedule_async_write(
hidden_states_gpu=hs_for_cache,
multimodal_outputs_gpu=(flatten_payload(multimodal_outputs) if multimodal_outputs else None),
slot_mapping_gpu=slot_mapping_gpu,
num_tokens_unpadded=num_tokens_unpadded,
num_tokens_padded=num_tokens_padded,
skip_mm_cache_keys=self._deferred_prefix_cache_mm_keys(),
)
# Prefix-cache write: freeze + submit; policy gating (full
# hidden, skip/deferred keys) happens inside the manager.
prefix_cache_step_id = self._prefix_cache_save_step(
hidden_states,
multimodal_outputs,
num_tokens_unpadded=num_tokens_unpadded,
num_tokens_padded=num_tokens_padded,
)
if (
prefix_cache_step_id is not None
and not self._model_needs_full_prefix_hidden_states()
and self._model_omni_pooler_payload_include_hidden()
):
# Opt-out models keep the scheduled-slice CPU view for the
# pooler payload (runner-side bypass, legacy parity).
hidden_states_cpu = hidden_states[:num_tokens_unpadded].detach().to("cpu").contiguous()
if not self.broadcast_pp_output:
# Common case.
@@ -1391,6 +1275,7 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
cudagraph_stats,
multimodal_outputs,
slot_mappings, # OMNI: pass slot_mappings for drafter
prefix_cache_step_id,
)
self.kv_connector_output = kv_connector_output
@@ -1434,7 +1319,14 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
)
prepared_sampling_metadata = self._sampling_metadata_for_model_sampler(sampling_metadata)
self._apply_duplex_sampling(logits, prepared_sampling_metadata)
sampler_output = model_sample(logits, prepared_sampling_metadata)
sampler_output = call_model_sampler(
self.model,
model_sample,
logits,
prepared_sampling_metadata,
input_batch=self.input_batch,
requests=getattr(self, "requests", None),
)
if sampler_output is not None:
return sampler_output
# Contract: None => fall back to the default sampler (see
@@ -1673,12 +1565,12 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
return raw
def _model_omni_pooler_payload_include_hidden(self) -> bool:
return self._runner_model_omni_flag("omni_pooler_payload_include_hidden", default=True)
return self._pooler_payload_include_hidden_flag
def _should_defer_full_payload_d2h(self) -> bool:
"""Keep opted-in full payloads on device until request completion."""
return (
getattr(self, "omni_prefix_cache", None) is None
self.omni_prefix_cache is None
and self._runner_model_omni_flag("omni_payload_at_request_end")
and self._should_accumulate_full_payload_output()
)
@@ -1707,8 +1599,6 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
def _should_use_async_omni_output(self) -> bool:
if not self.use_async_scheduling:
return False
if self.omni_prefix_cache is not None:
return False
if self.speculative_config is not None:
return False
@@ -1854,6 +1744,7 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
num_scheduled_tokens_np: np.ndarray,
query_start_loc_cpu: Any,
postprocess_already_applied: bool = False,
prefix_cache_step_id: int | None = None,
) -> OmniModelRunnerOutput:
combined_hidden_states = None
combined_multimodal_outputs = None
@@ -1877,12 +1768,11 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
and needs_pooler_payload
and (self.omni_prefix_cache is None or not self._model_needs_full_prefix_hidden_states())
)
self._stage_deferred_prefix_cache_mm_outputs(
scheduler_output=scheduler_output,
multimodal_outputs=multimodal_outputs,
query_start_loc_cpu=query_start_loc_cpu,
)
if not needs_pooler_payload and prefix_cache_step_id is not None:
# No consumer for this step's merge: consume the step context by
# id (exactly-once contract). The cache write still lands.
self.omni_prefix_cache.discard_step(prefix_cache_step_id)
prefix_cache_step_id = None
if self.omni_prefix_cache is None and needs_scheduled_hidden_payload and not audio_sparse_output:
num_valid_tokens = min(
int(scheduler_output.total_num_scheduled_tokens),
@@ -1916,11 +1806,10 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
combined_hidden_states,
combined_multimodal_outputs,
) = self._prepare_prefix_cache_pooler_payload_sources(
hidden_states=hidden_states,
staged_hidden_states_cpu=staged_hidden_states_cpu,
multimodal_outputs=multimodal_outputs,
scheduler_output=scheduler_output,
needs_scheduled_hidden_payload=needs_scheduled_hidden_payload,
step_id=prefix_cache_step_id,
req_ids=req_ids_output_copy,
)
if combined_multimodal_outputs is None:
flat_mm = flatten_payload(multimodal_outputs) if multimodal_outputs else multimodal_outputs
@@ -2060,6 +1949,7 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
cudagraph_stats,
multimodal_outputs,
slot_mappings, # OMNI: unpack slot_mappings for drafter
prefix_cache_step_id,
) = self.execute_model_state
self.execute_model_state = None
@@ -2259,6 +2149,7 @@ class GPUARModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin, Duplex
num_scheduled_tokens_np=num_scheduled_tokens_np,
query_start_loc_cpu=query_start_loc_cpu,
postprocess_already_applied=omni_postprocess_already_applied,
prefix_cache_step_id=prefix_cache_step_id,
)
if not use_async_omni_output:
+20 -7
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import gc
import os
@@ -75,7 +78,6 @@ class GPUARWorker(OmniWorkerMixin, OmniGPUWorkerBase):
f"DP adjusted local rank {self.local_rank} is out of "
f"bounds for {torch.accelerator.device_count()} devices."
)
visible_device_index = current_platform.logical_device_id_to_visible_device_id(self.local_rank)
self.device = current_omni_platform.get_torch_device(visible_device_index)
torch.accelerator.set_device_index(self.device)
@@ -113,13 +115,24 @@ class GPUARWorker(OmniWorkerMixin, OmniGPUWorkerBase):
num_ubatches = 2 if self.vllm_config.parallel_config.enable_dbo else 1
init_workspace_manager(self.device, num_ubatches)
if self.use_v2_model_runner:
# OMNI: v2 model runner does not yet include omni hooks.
logger.warning("OMNI GPUARWorker forces v1 model runner for omni hooks.")
self.use_v2_model_runner = False
model_stage = getattr(self.model_config, "model_stage", None)
stage_id = getattr(self.model_config, "stage_id", None)
# Construct the model runner
self.model_runner = self.model_runner_cls(self.vllm_config, self.device)
self.use_v2_model_runner = bool(getattr(self.model_config, "use_v2_model_runner", False))
if self.use_v2_model_runner:
from vllm_omni.worker_v2.omni_ar_model_runner import (
OmniARModelRunner,
)
logger.info(
"Using MR v2 OmniARModelRunner for omni AR stage (stage_id=%s model_stage=%s).",
stage_id,
model_stage,
)
self.model_runner = OmniARModelRunner(self.vllm_config, self.device)
else:
self.use_v2_model_runner = False
self.model_runner = self.model_runner_cls(self.vllm_config, self.device)
if self.rank == 0:
# If usage stat is enabled, collect relevant info.
@@ -407,6 +407,7 @@ class GPUGenerationModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin
cudagraph_stats,
multimodal_outputs_raw,
slot_mappings, # OMNI: unpack slot_mappings for upstream v1 API compatibility
_prefix_cache_step_id, # generation stages never save to the prefix cache
) = self.execute_model_state
self.execute_model_state = None
@@ -812,7 +813,7 @@ class GPUGenerationModelRunner(OmniGPUModelRunner, OmniConnectorModelRunnerMixin
if self.uses_mrope:
positions = self.mrope_positions.gpu[:, :num_tokens_padded]
elif self.uses_xdrope_dim > 0:
elif getattr(self, "uses_xdrope_dim", 0) > 0:
positions = self.xdrope_positions.gpu[:, :num_tokens_padded]
else:
positions = self.positions[:num_tokens_padded]
+26 -5
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import gc
import os
@@ -8,7 +11,10 @@ from vllm.tracing import instrument
from vllm.utils.mem_utils import MemorySnapshot, format_gib
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.utils import report_usage_stats
from vllm.v1.worker.gpu_worker import init_worker_distributed_environment
from vllm.v1.worker.gpu_worker import (
CompilationTimes,
init_worker_distributed_environment,
)
from vllm.v1.worker.workspace import init_workspace_manager
from vllm_omni.platforms import current_omni_platform
@@ -96,13 +102,28 @@ class GPUGenerationWorker(OmniWorkerMixin, OmniGPUWorkerBase):
num_ubatches = 2 if self.vllm_config.parallel_config.enable_dbo else 1
init_workspace_manager(self.device, num_ubatches)
self.use_v2_model_runner = bool(getattr(self.model_config, "use_v2_model_runner", False))
if self.use_v2_model_runner:
# OMNI: v2 model runner does not yet include omni hooks.
logger.warning("OMNI GPUGenerationWorker forces v1 model runner for omni hooks.")
self.use_v2_model_runner = False
from vllm_omni.worker_v2.omni_generation_model_runner import (
OmniGenerationModelRunner,
)
self.model_runner = self.model_runner_cls(self.vllm_config, self.device)
logger.info("Using MR v2 OmniGenerationModelRunner for generation stage.")
self.model_runner = OmniGenerationModelRunner(self.vllm_config, self.device)
else:
self.model_runner = self.model_runner_cls(self.vllm_config, self.device)
if self.rank == 0:
# If usage stat is enabled, collect relevant info.
report_usage_stats(self.vllm_config)
@instrument(span_name="Compile/warmup")
def compile_or_warm_up_model(self) -> CompilationTimes:
"""Generation stages have no KV cache or sampler — skip warmup_kernels."""
if not self.use_v2_model_runner:
return super().compile_or_warm_up_model()
import time
start = time.perf_counter()
self.model_runner.profile_run()
return CompilationTimes(language_model=time.perf_counter() - start, encoder=0.0)
+39 -29
View File
@@ -33,7 +33,8 @@ from vllm.v1.worker.gpu_input_batch import CachedRequestState
from vllm.v1.worker.gpu_model_runner import GPUModelRunner, PerLayerAttnMetadata
from vllm.v1.worker.ubatch_utils import maybe_create_ubatch_slices
from vllm_omni.core.prefix_cache import OmniTensorPrefixCache
from vllm_omni.core.prefix_cache import stage_prefix_cache_config
from vllm_omni.core.prefix_cache.runner_mixin import PrefixCacheRunnerMixin
from vllm_omni.data_entry_keys import OmniPayload
from vllm_omni.engine.serialization import deserialize_additional_information
from vllm_omni.model_executor.layers.rotary_embedding.mrope import OmniMRotaryEmbedding as MRotaryEmbedding
@@ -79,7 +80,7 @@ def _filter_mrope_kwargs_for_model(model: object, kwargs: dict[str, Any]) -> dic
return {key: value for key, value in kwargs.items() if key in accepted}
class OmniGPUModelRunner(GPUModelRunner):
class OmniGPUModelRunner(PrefixCacheRunnerMixin, GPUModelRunner):
intermediate_tensors: IntermediateTensors | None
def __init__(self, *args, **kwargs):
@@ -87,11 +88,16 @@ class OmniGPUModelRunner(GPUModelRunner):
self.model_intermediate_buffer: dict[str, dict[str, Any]] = {}
self._omni_num_scheduled_tokens_np: np.ndarray | None = None
self._omni_last_model_output: object | None = None
# The Omni tensor prefix cache will be allocated
# when we initialize the metadata builders if enabled
# Omni prefix cache (hidden / per-token mm tensors reused on prefix
# hits). Built once, on the first real step after load_model: the
# config is staged at kv-cache init and cleared after construction.
self.omni_prefix_cache = None
self._omni_prefix_cache_cfg = None
self._sampled_token_ids_cpu_override = None
self._omni_query_start_loc_model_kwarg = False
# Output-payload constant snapshotted once in load_model; the cache
# policy counterpart lives on PrefixCacheRunnerMixin.
self._pooler_payload_include_hidden_flag = True
def _to_list(self, sampled_token_ids: torch.Tensor) -> list[list[int]]:
override_fn = self._sampled_token_ids_cpu_override
@@ -172,15 +178,20 @@ class OmniGPUModelRunner(GPUModelRunner):
device=sm.device,
)
# Initialize the wrapper for both multimodal output tensors
# and for hidden states to be passed between stages
if self.cache_config.enable_prefix_caching:
self.omni_prefix_cache = OmniTensorPrefixCache(
num_blocks=kv_cache_config.num_blocks,
block_size=self.cache_config.block_size,
hidden_size=self.model_config.get_hidden_size(),
hs_dtype=self.dtype,
)
# Stage the config; the manager is built on the first step once
# input_batch exists. The gate (pooling stage, kv_consumer, hybrid
# kv groups) is shared with the NPU runner.
cfg = stage_prefix_cache_config(
kv_cache_config=kv_cache_config,
cache_config=self.cache_config,
kv_transfer_config=getattr(self.vllm_config, "kv_transfer_config", None),
scheduler_config=self.scheduler_config,
model_config=self.model_config,
is_pooling_model=self.is_pooling_model,
speculative_config=self.speculative_config,
)
if cfg is not None:
self._omni_prefix_cache_cfg = cfg
@instrument(span_name="Loading (GPU)")
def load_model(self, *args, **kwargs) -> None:
@@ -192,6 +203,8 @@ class OmniGPUModelRunner(GPUModelRunner):
if callable(candidate):
override_fn = candidate
self._sampled_token_ids_cpu_override = override_fn
self._snapshot_prefix_cache_model_policy(model)
self._pooler_payload_include_hidden_flag = bool(getattr(model, "omni_pooler_payload_include_hidden", True))
self._omni_query_start_loc_model_kwarg = bool(getattr(model, "supports_omni_query_start_loc", False))
self._maybe_enable_output_token_ids_for_model_sampler()
self._init_talker_mtp()
@@ -515,10 +528,6 @@ class OmniGPUModelRunner(GPUModelRunner):
The SamplingMetadata is updated and copied to the GPU if there is a
new/resumed/paused/finished request in the batch.
"""
# Used for prefix cache
if self.omni_prefix_cache is not None:
self.omni_prefix_cache.reset_prefix_cached_new_req_ids()
# Remove finished requests from the cached states.
# cleanup_finished_request lives on OmniConnectorModelRunnerMixin and
# is only safe to call once init_omni_connectors() has finished
@@ -535,8 +544,6 @@ class OmniGPUModelRunner(GPUModelRunner):
self.requests.pop(req_id, None)
self.model_intermediate_buffer.pop(req_id, None)
self.num_prompt_logprobs.pop(req_id, None)
if self.omni_prefix_cache is not None:
self.omni_prefix_cache.discard_deferred_mm_outputs(req_id)
if hasattr(self, "_downstream_payload_cache"):
self._downstream_payload_cache.pop(req_id, None)
if hasattr(self, "_talker_mtp_generators"):
@@ -600,13 +607,6 @@ class OmniGPUModelRunner(GPUModelRunner):
reqs_to_add.append(req_state)
continue
# Since this is the first time the request has been scheduled,
# num_computed_tokens > 0 means that we have a hit in prefix
# caching; mark it so that we can manage the hidden states
# later on as needed.
if self.omni_prefix_cache is not None and new_req_data.num_computed_tokens > 0:
self.omni_prefix_cache.add_prefix_cached_new_req_id(req_id)
sampling_params = new_req_data.sampling_params
pooling_params = new_req_data.pooling_params
@@ -690,7 +690,7 @@ class OmniGPUModelRunner(GPUModelRunner):
self._init_mrope_positions(req_state)
# Only relevant for models using XD-RoPE (e.g, HunYuan-VL)
if self.uses_xdrope_dim > 0:
if getattr(self, "uses_xdrope_dim", 0) > 0:
self._init_xdrope_positions(req_state)
reqs_to_add.append(self.requests[req_id])
@@ -1164,7 +1164,7 @@ class OmniGPUModelRunner(GPUModelRunner):
if self.uses_mrope:
positions = self.mrope_positions.gpu[:, :num_tokens_padded]
elif self.uses_xdrope_dim > 0:
elif getattr(self, "uses_xdrope_dim", 0) > 0:
positions = self.xdrope_positions.gpu[:, :num_tokens_padded]
else:
positions = self.positions[:num_tokens_padded]
@@ -1701,7 +1701,7 @@ class OmniGPUModelRunner(GPUModelRunner):
if self.uses_mrope:
positions = self.mrope_positions.gpu[:, :num_input_tokens]
elif self.uses_xdrope_dim > 0:
elif getattr(self, "uses_xdrope_dim", 0) > 0:
positions = self.xdrope_positions.gpu[:, :num_input_tokens]
else:
positions = self.positions[:num_input_tokens]
@@ -2042,10 +2042,20 @@ class OmniGPUModelRunner(GPUModelRunner):
if req_state is not None:
existing = self.model_intermediate_buffer.setdefault(req_id, {})
existing.setdefault(out_key[0], {})[out_key[1]] = row
validity_key = getattr(self.model, "talker_mtp_validity_key", None)
if validity_key is not None:
existing.setdefault(validity_key[0], {})[validity_key[1]] = torch.ones(
(), dtype=torch.bool, device=code_predictor_codes.device
)
req_state.additional_information_cpu = existing
else:
for idx, req_id in enumerate(decode_req_ids):
update_dict = {out_key[0]: {out_key[1]: code_predictor_codes[idx : idx + 1]}}
validity_key = getattr(self.model, "talker_mtp_validity_key", None)
if validity_key is not None:
update_dict.setdefault(validity_key[0], {})[validity_key[1]] = torch.ones(
(), dtype=torch.bool, device=code_predictor_codes.device
)
self._update_intermediate_buffer(req_id, update_dict)
def _model_forward(
+11 -1
View File
@@ -7,7 +7,7 @@ from typing import Any
class OmniWorkerMixin:
"""Mixin to ensure Omni plugins are loaded in worker processes."""
"""Shared Omni plugin and native KV connector setup for workers."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -15,6 +15,16 @@ class OmniWorkerMixin:
load_omni_general_plugins()
def initialize_from_config(self, kv_cache_config) -> None:
# The concrete GPU/NPU/XPU worker supplies this method through the MRO.
super().initialize_from_config(kv_cache_config) # type: ignore[misc]
from vllm.distributed.kv_transfer import get_kv_transfer_group, has_kv_transfer_group
if has_kv_transfer_group():
from vllm_omni.diffusion.diffusion_kv.kv_connector import install_mooncake_cfg_fanout
install_mooncake_cfg_fanout(get_kv_transfer_group())
def maybe_unpad_input_ids(model, input_ids, num_tokens_unpadded):
"""Trim cudagraph-bucket padding for models that split a flat ``input_ids``
+48
View File
@@ -0,0 +1,48 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Helpers for explicit thinker decode span metadata."""
from collections.abc import Mapping
from typing import Any
import torch
TensorSpan = tuple[torch.Tensor, int, int]
def get_tensor_span(payload: Mapping[str, Any], *, tensor_key: str, start_key: str, end_key: str) -> TensorSpan | None:
tensor = payload.get(tensor_key)
start = payload.get(start_key)
end = payload.get(end_key)
if not isinstance(tensor, torch.Tensor):
return None
if not isinstance(start, int) or not isinstance(end, int):
return None
if start < 0 or end < start or (end - start) != int(tensor.shape[0]):
return None
return tensor, start, end
def merge_tensor_spans(existing_span: TensorSpan | None, incoming_span: TensorSpan | None) -> TensorSpan | None:
if existing_span is None or incoming_span is None:
return None
existing_tensor, existing_start, existing_end = existing_span
incoming_tensor, incoming_start, incoming_end = incoming_span
if incoming_tensor.device != existing_tensor.device or incoming_tensor.dtype != existing_tensor.dtype:
incoming_tensor = incoming_tensor.to(device=existing_tensor.device, dtype=existing_tensor.dtype)
if incoming_start == existing_end:
if existing_start == existing_end:
return incoming_tensor, incoming_start, incoming_end
return torch.cat([existing_tensor, incoming_tensor], dim=0), existing_start, incoming_end
if incoming_start < existing_end:
overlap = existing_end - incoming_start
if overlap >= int(incoming_tensor.shape[0]):
return existing_tensor, existing_start, existing_end
trimmed_tensor = incoming_tensor[overlap:]
return (
torch.cat([existing_tensor, trimmed_tensor], dim=0),
existing_start,
existing_end + int(trimmed_tensor.shape[0]),
)
return None
+97 -2
View File
@@ -1,14 +1,109 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Sampling-state guards shared by the GPU and NPU AR model runners."""
"""Sampling helpers shared by the GPU and NPU AR model runners."""
from typing import Any
import torch
from vllm.logger import init_logger
from vllm.sampling_params import SamplingParams
from vllm.v1.sample.logits_processor import LogitsProcessors, MinTokensLogitsProcessor
logger = init_logger(__name__)
__all__ = ["clamp_prompt_ids_to_penalty_padding", "sanitize_min_tokens_stop_ids"]
__all__ = [
"apply_fixed_seed_to_sampling_params",
"get_tts_local_seed",
"clamp_prompt_ids_to_penalty_padding",
"sanitize_min_tokens_stop_ids",
"sanitize_sampling_params_min_tokens_stop_ids",
"build_model_sampler_extra_args",
"call_model_sampler",
]
def get_tts_local_seed(sampling_params: Any) -> int | None:
"""Return the explicit per-request Talker MTP seed, if configured."""
extra_args = getattr(sampling_params, "extra_args", None) if sampling_params is not None else None
seed = extra_args.get("tts_local_seed") if isinstance(extra_args, dict) else None
return int(seed) if seed is not None else None
def apply_fixed_seed_to_sampling_params(
sampling_params: Any,
seed: int,
*,
seed_talker_mtp: bool,
) -> None:
"""Apply one request seed to a stage sampler and, for Talkers, its MTP RNG."""
seed = int(seed)
sampling_params.seed = seed
if not seed_talker_mtp:
return
extra_args = dict(getattr(sampling_params, "extra_args", None) or {})
extra_args["tts_local_seed"] = seed
sampling_params.extra_args = extra_args
def sanitize_sampling_params_min_tokens_stop_ids(
sampling_params: SamplingParams,
logits_vocab: int,
) -> None:
"""Remove unreachable ids before MRv2 builds persistent min-token state.
MRv2 copies ``SamplingParams.all_stop_token_ids`` into GPU-resident
``LogitBiasState`` when a request is registered. Narrow codec heads cannot
safely carry the text tokenizer EOS in that state. The engine-facing EOS
and explicit ``stop_token_ids`` fields remain unchanged; only the set used
by the sampler's min-token mask is normalized.
"""
if sampling_params.min_tokens <= 0:
return
stop_token_ids = sampling_params.all_stop_token_ids
unreachable = {token_id for token_id in stop_token_ids if token_id < 0 or token_id >= logits_vocab}
if not unreachable:
return
stop_token_ids.difference_update(unreachable)
logger.warning_once(
"min_tokens: dropped stop token ids %s that exceed the logits vocabulary (%d); "
"the model head cannot emit them.",
str(sorted(unreachable)),
logits_vocab,
)
def build_model_sampler_extra_args(input_batch: Any, requests: Any) -> list[dict | None]:
"""Return per-request ``SamplingParams.extra_args`` in batch-row order."""
request_states = requests or {}
per_req_extra_args: list[dict | None] = []
for req_id in getattr(input_batch, "req_ids", []):
state = request_states.get(req_id)
params = getattr(state, "sampling_params", None)
per_req_extra_args.append(getattr(params, "extra_args", None))
return per_req_extra_args
def call_model_sampler(
model: Any,
model_sample: Any,
logits: torch.Tensor,
sampling_metadata: Any,
*,
input_batch: Any,
requests: Any,
) -> Any:
"""Call an opted-in model sampler with per-request extra arguments.
The opt-in keeps the existing two-argument sampler contract unchanged for
every other model while allowing custom samplers to make row-local choices.
"""
if not getattr(model, "model_sampler_wants_extra_args", False):
return model_sample(logits, sampling_metadata)
return model_sample(
logits,
sampling_metadata,
per_req_extra_args=build_model_sampler_extra_args(input_batch, requests),
)
def clamp_prompt_ids_to_penalty_padding(prompt_token_ids: torch.Tensor, logits_vocab: int) -> torch.Tensor: