Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes
Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
@@ -23,6 +23,8 @@ class ECTransferConfig:
|
||||
safetensors) and ``ECMooncakeConnector`` (Mooncake TransferEngine RDMA;
|
||||
requires ``mooncake-transfer-engine`` and matching producer/consumer
|
||||
``ec_connector_extra_config``; see ``mooncake_ec_connector`` module docstring).
|
||||
Set ``cross_encoder_cache`` in Mooncake extra config to reuse shared
|
||||
Encoder outputs from Store before encoding, retaining P2P delivery.
|
||||
"""
|
||||
|
||||
engine_id: str | None = None
|
||||
|
||||
+12
-5
@@ -38,7 +38,9 @@ DistributedExecutorBackend = Literal["ray", "mp", "uni", "external_launcher"]
|
||||
DataParallelBackend = Literal["ray", "mp"]
|
||||
EPLBPolicyOption = Literal["default"]
|
||||
DCPCommBackend = Literal["ag_rs", "a2a"]
|
||||
EPLBCommunicatorBackend = Literal["torch_nccl", "torch_gloo", "nixl", "pynccl"]
|
||||
EPLBCommunicatorBackend = Literal[
|
||||
"torch_nccl", "torch_gloo", "torch_xccl", "nixl", "pynccl"
|
||||
]
|
||||
All2AllBackend = Literal[
|
||||
"naive",
|
||||
"pplx",
|
||||
@@ -94,9 +96,11 @@ class EPLBConfig:
|
||||
Backend for EPLB expert weight communication:
|
||||
- "torch_nccl": Use torch.distributed on the device process group
|
||||
- "torch_gloo": Use torch.distributed gloo with CPU staging
|
||||
- "torch_xccl": Use torch.distributed XCCL device P2P on XPU
|
||||
- "nixl": Use NIXL with staged send/recv buffers
|
||||
- "pynccl": Use PyNccl send/recv
|
||||
- None: Auto-select backend (prefers "nixl", falls back to "torch_gloo")
|
||||
- None: Auto-select backend ("torch_xccl" on XPU, prefers "nixl"
|
||||
on CUDA, falls back to "torch_gloo")
|
||||
"""
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -525,10 +529,10 @@ class ParallelConfig:
|
||||
)
|
||||
|
||||
if self.enable_eplb:
|
||||
if not current_platform.is_cuda_alike():
|
||||
if not current_platform.is_cuda_alike() and not current_platform.is_xpu():
|
||||
raise ValueError(
|
||||
"Expert parallelism load balancing is only supported on "
|
||||
"CUDA devices or ROCm devices now."
|
||||
"CUDA devices or ROCm devices or XPU devices now."
|
||||
)
|
||||
if not self.enable_expert_parallel:
|
||||
raise ValueError("enable_expert_parallel must be True to use EPLB.")
|
||||
@@ -1034,7 +1038,10 @@ class ParallelConfig:
|
||||
# See https://github.com/pytorch/pytorch/issues/174288
|
||||
from vllm.distributed.nixl_utils import is_nixl_available
|
||||
|
||||
if is_nixl_available():
|
||||
if current_platform.is_xpu():
|
||||
# On XPU, use the device-native XCCL P2P backend.
|
||||
self.eplb_config.communicator = "torch_xccl"
|
||||
elif is_nixl_available():
|
||||
self.eplb_config.communicator = "nixl"
|
||||
elif self.enable_elastic_ep:
|
||||
self.eplb_config.communicator = "pynccl"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import os
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
@@ -1048,6 +1049,9 @@ class DeepEPV2All2AllManager(All2AllManagerBase):
|
||||
# missing GIN support.
|
||||
probe = torch.zeros(1, device="cuda")
|
||||
torch.distributed.all_reduce(probe, group=group)
|
||||
# DeepEPv2 respects EP_DISABLE_GIN, so skip the GIN requirement check.
|
||||
if os.environ.get("EP_DISABLE_GIN", "0") != "0":
|
||||
return
|
||||
|
||||
gin_type = query_nccl_gin_type(group)
|
||||
if gin_type is None:
|
||||
|
||||
@@ -226,8 +226,7 @@ class ECConnectorBase(ABC):
|
||||
return None
|
||||
|
||||
def get_ec_connector_stats(self) -> "ECConnectorStats | None":
|
||||
"""
|
||||
Get the EC connector stats collected during the last interval.
|
||||
"""Get the EC connector stats collected during the last interval.
|
||||
|
||||
Callable on either a worker-side or scheduler-side connector
|
||||
instance: the worker-side instance reports stats gathered during
|
||||
@@ -358,8 +357,7 @@ class ECConnectorBase(ABC):
|
||||
def build_ec_connector_stats(
|
||||
cls, data: dict[str, Any] | None = None
|
||||
) -> "ECConnectorStats | None":
|
||||
"""
|
||||
ECConnectorStats resolution method. This method allows dynamically
|
||||
"""ECConnectorStats resolution method. This method allows dynamically
|
||||
registered connectors to return their own ECConnectorStats object,
|
||||
which can implement custom aggregation logic on the data dict.
|
||||
"""
|
||||
@@ -373,8 +371,7 @@ class ECConnectorBase(ABC):
|
||||
labelnames: list[str],
|
||||
per_engine_labelvalues: dict[int, list[object]],
|
||||
) -> "ECConnectorPromMetrics | None":
|
||||
"""
|
||||
Create an ECConnectorPromMetrics subclass which should register
|
||||
"""Create an ECConnectorPromMetrics subclass which should register
|
||||
per-connector Prometheus metrics and implement observe() to
|
||||
expose connector transfer stats via Prometheus.
|
||||
"""
|
||||
|
||||
@@ -17,8 +17,7 @@ logger = init_logger(__name__)
|
||||
|
||||
@dataclass
|
||||
class ECConnectorStats:
|
||||
"""
|
||||
Base class for EC Connector Stats, a container for transfer performance
|
||||
"""Base class for EC Connector Stats, a container for transfer performance
|
||||
metrics or otherwise important telemetry from the connector.
|
||||
All sub-classes need to be serializable as stats are sent from worker to
|
||||
logger process.
|
||||
@@ -31,14 +30,11 @@ class ECConnectorStats:
|
||||
raise NotImplementedError
|
||||
|
||||
def aggregate(self, other: "ECConnectorStats") -> "ECConnectorStats":
|
||||
"""
|
||||
Aggregate stats with another `ECConnectorStats` object.
|
||||
"""
|
||||
"""Aggregate stats with another `ECConnectorStats` object."""
|
||||
raise NotImplementedError
|
||||
|
||||
def reduce(self) -> dict[str, int | float]:
|
||||
"""
|
||||
Reduce the observations collected during a time interval to one or
|
||||
"""Reduce the observations collected during a time interval to one or
|
||||
more representative values (eg avg/median/sum of the series).
|
||||
This is meant to be called by the logger to produce a summary of the
|
||||
stats for the last time interval.
|
||||
@@ -107,8 +103,7 @@ class ECConnectorLogging:
|
||||
|
||||
|
||||
class ECConnectorPromMetrics:
|
||||
"""
|
||||
A base class for per-connector Prometheus metric registration
|
||||
"""A base class for per-connector Prometheus metric registration
|
||||
and recording.
|
||||
"""
|
||||
|
||||
@@ -127,8 +122,7 @@ class ECConnectorPromMetrics:
|
||||
self.per_engine_labelvalues = per_engine_labelvalues
|
||||
|
||||
def observe(self, transfer_stats_data: dict[str, Any], engine_idx: int = 0):
|
||||
"""
|
||||
Record the supplied transfer statistics to Prometheus metrics. These
|
||||
"""Record the supplied transfer statistics to Prometheus metrics. These
|
||||
statistics are engine-specific, and should be recorded to a metric
|
||||
with the appropriate 'engine' label. These metric instances can be
|
||||
created using the create_metric_per_engine() helper method.
|
||||
@@ -137,8 +131,7 @@ class ECConnectorPromMetrics:
|
||||
|
||||
|
||||
class ECConnectorProm:
|
||||
"""
|
||||
Support for registering per-connector Prometheus metrics, and
|
||||
"""Support for registering per-connector Prometheus metrics, and
|
||||
recording transfer statistics to those metrics. Uses
|
||||
ECConnectorBase.build_prom_metrics().
|
||||
"""
|
||||
|
||||
@@ -69,6 +69,10 @@ class MooncakeECConfig:
|
||||
control_timeout_ms: int
|
||||
push_wait_timeout_s: float
|
||||
pool_size: int
|
||||
cross_encoder_cache: bool = False
|
||||
store_max_pending_items: int = 32
|
||||
store_max_pending_bytes: int = 2 * 1024**3
|
||||
store_read_buffer_bytes: int = 128 * 1024**2
|
||||
|
||||
@classmethod
|
||||
def from_vllm_config(cls, vllm_config: VllmConfig) -> MooncakeECConfig:
|
||||
@@ -94,6 +98,24 @@ class MooncakeECConfig:
|
||||
"ec_buffer_size", ec_config.ec_buffer_size
|
||||
)
|
||||
get = ec_config.get_from_extra_config
|
||||
shared_reuse = get("cross_encoder_cache", False)
|
||||
if not isinstance(shared_reuse, bool):
|
||||
raise ValueError("cross_encoder_cache must be a boolean")
|
||||
if shared_reuse:
|
||||
if not ec_config.is_encode_only:
|
||||
raise ValueError(
|
||||
"cross_encoder_cache requires an Encoder-only producer"
|
||||
)
|
||||
if not vllm_config.use_v2_model_runner:
|
||||
raise ValueError("cross_encoder_cache requires Model Runner V2")
|
||||
if vllm_config.lora_config is not None:
|
||||
raise ValueError("cross_encoder_cache does not support LoRA")
|
||||
mm_config = vllm_config.model_config.multimodal_config
|
||||
if mm_config is not None and mm_config.mm_processor_cache_gb == 0:
|
||||
raise ValueError(
|
||||
"cross_encoder_cache requires mm_processor_cache_gb > 0 "
|
||||
"to preserve content identifiers across Encoders and restarts"
|
||||
)
|
||||
control_port = int(ec_config.ec_port) + (
|
||||
parallel_config.data_parallel_index * parallel_config.tensor_parallel_size
|
||||
)
|
||||
@@ -120,4 +142,14 @@ class MooncakeECConfig:
|
||||
"push_wait_timeout_s", get("push_wait_timeout_s", 60)
|
||||
),
|
||||
pool_size=registered_buffer_size,
|
||||
cross_encoder_cache=shared_reuse,
|
||||
store_max_pending_items=_positive_int(
|
||||
"store_max_pending_items", get("store_max_pending_items", 32)
|
||||
),
|
||||
store_max_pending_bytes=_positive_int(
|
||||
"store_max_pending_bytes", get("store_max_pending_bytes", 2 * 1024**3)
|
||||
),
|
||||
store_read_buffer_bytes=_positive_int(
|
||||
"store_read_buffer_bytes", get("store_read_buffer_bytes", 128 * 1024**2)
|
||||
),
|
||||
)
|
||||
|
||||
@@ -10,6 +10,9 @@ from vllm.distributed.ec_transfer.ec_connector.base import (
|
||||
ECConnectorMetadata,
|
||||
ECConnectorWorkerMetadata,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake_store_embedding.data import (
|
||||
TensorSpec,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -46,6 +49,7 @@ class ECMooncakeConnectorMetadata(ECConnectorMetadata):
|
||||
loads: list[ECMooncakeLoadSpec] = field(default_factory=list)
|
||||
pushes: list[ECMooncakePushSpec] = field(default_factory=list)
|
||||
freed: list[str] | None = None
|
||||
store_candidates: dict[str, TensorSpec] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -45,6 +45,9 @@ from vllm.distributed.ec_transfer.ec_connector.mooncake.state import (
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake.transfer import (
|
||||
ensure_mooncake_available,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake_store_embedding.data import (
|
||||
TensorSpec,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.utils import (
|
||||
PlaceholderMetadataResolver,
|
||||
collect_ec_item_metadata,
|
||||
@@ -76,6 +79,8 @@ class ECMooncakeScheduler:
|
||||
ensure_mooncake_available()
|
||||
config = MooncakeECConfig.from_vllm_config(vllm_config)
|
||||
|
||||
self._store_candidates: list[tuple[str, str, TensorSpec]] = []
|
||||
self._cross_encoder_cache = config.cross_encoder_cache
|
||||
self._is_producer = config.is_producer
|
||||
self._is_consumer = config.is_consumer
|
||||
self._control_addr = config.control_addr
|
||||
@@ -427,28 +432,40 @@ class ECMooncakeScheduler:
|
||||
transfer_id = f"{request.request_id}:{index}"
|
||||
if not consumer_zmq or transfer_id in self._prepared_push_transfer_ids:
|
||||
return
|
||||
num_tokens = request.get_num_encoder_embeds(index)
|
||||
dtype = self._model_config.dtype
|
||||
assert isinstance(dtype, torch.dtype)
|
||||
assert self._encoder_cache_hidden_dim is not None
|
||||
dtype_name = str(dtype).split(".")[-1]
|
||||
shape = (num_tokens, self._encoder_cache_hidden_dim)
|
||||
nbytes = math.prod(shape) * dtype.itemsize
|
||||
output = self._encoder_output_spec(request, index)
|
||||
self._pushes_to_prepare[transfer_id] = ECMooncakePushSpec(
|
||||
mm_hash=mm_hash,
|
||||
nbytes=nbytes,
|
||||
shape=shape,
|
||||
dtype=dtype_name,
|
||||
nbytes=output.nbytes,
|
||||
shape=output.shape,
|
||||
dtype=output.dtype.removeprefix("torch."),
|
||||
consumer_zmq=str(consumer_zmq),
|
||||
transfer_id=transfer_id,
|
||||
request_id=request.request_id,
|
||||
)
|
||||
self._prepared_push_transfer_ids.add(transfer_id)
|
||||
|
||||
def _encoder_output_spec(self, request: Any, index: int) -> TensorSpec:
|
||||
dtype = self._model_config.dtype
|
||||
assert isinstance(dtype, torch.dtype)
|
||||
assert self._encoder_cache_hidden_dim is not None
|
||||
shape = (request.get_num_encoder_embeds(index), self._encoder_cache_hidden_dim)
|
||||
return TensorSpec(shape, str(dtype), math.prod(shape) * dtype.itemsize)
|
||||
|
||||
def update_state_after_alloc(self, request: Any, index: int) -> None:
|
||||
self._local_cache.add(request.mm_features[index].identifier)
|
||||
if self._is_producer:
|
||||
self._prepare_push_spec(request, index)
|
||||
if (
|
||||
self._cross_encoder_cache
|
||||
and request.mm_features[index].modality == "image"
|
||||
):
|
||||
self._store_candidates.append(
|
||||
(
|
||||
request.request_id,
|
||||
request.mm_features[index].identifier,
|
||||
self._encoder_output_spec(request, index),
|
||||
)
|
||||
)
|
||||
|
||||
def update_state_after_free(self, request: Any, index: int) -> None:
|
||||
if not self._is_consumer:
|
||||
@@ -474,6 +491,13 @@ class ECMooncakeScheduler:
|
||||
meta = ECMooncakeConnectorMetadata(
|
||||
freed=scheduler_output.free_encoder_mm_hashes
|
||||
)
|
||||
preempted = scheduler_output.preempted_req_ids or set()
|
||||
meta.store_candidates = {
|
||||
identifier: output
|
||||
for request_id, identifier, output in self._store_candidates
|
||||
if request_id not in preempted
|
||||
}
|
||||
self._store_candidates.clear()
|
||||
for push_spec in self._pushes_to_prepare.values():
|
||||
meta.pushes.append(push_spec)
|
||||
self._pushes_to_prepare.clear()
|
||||
|
||||
@@ -49,6 +49,9 @@ from vllm.distributed.ec_transfer.ec_connector.mooncake.transfer import (
|
||||
MooncakeTransfer,
|
||||
ensure_mooncake_available,
|
||||
)
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake_store_embedding.data import (
|
||||
build_embedding_namespace,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.network_utils import get_ip
|
||||
|
||||
@@ -59,6 +62,10 @@ _T = TypeVar("_T")
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
from ..mooncake_store_embedding.backend import (
|
||||
MooncakeEmbeddingStoreBackend,
|
||||
)
|
||||
|
||||
_RESERVATION_REFRESH_SECONDS = _RESERVATION_TTL_SECONDS / 2
|
||||
_MAX_CANCELLED_TRANSFER_IDS = 1 << 16
|
||||
_CANCEL_ATTEMPTS = 2
|
||||
@@ -87,6 +94,17 @@ class ECMooncakeWorker:
|
||||
def __init__(self, vllm_config: VllmConfig) -> None:
|
||||
ensure_mooncake_available()
|
||||
config = MooncakeECConfig.from_vllm_config(vllm_config)
|
||||
self._store_config = (
|
||||
(
|
||||
build_embedding_namespace(vllm_config),
|
||||
config.store_max_pending_items,
|
||||
config.store_max_pending_bytes,
|
||||
config.store_read_buffer_bytes,
|
||||
)
|
||||
if config.cross_encoder_cache
|
||||
else None
|
||||
)
|
||||
self._output_store: MooncakeEmbeddingStoreBackend | None = None
|
||||
self.is_producer = config.is_producer
|
||||
self.is_consumer = config.is_consumer
|
||||
self._buffer_device = config.buffer_device
|
||||
@@ -173,6 +191,21 @@ class ECMooncakeWorker:
|
||||
self._is_receiving_rank = True
|
||||
|
||||
def start_services(self) -> None:
|
||||
if self._store_config is not None and self._output_store is None:
|
||||
from ..mooncake_store_embedding.backend import (
|
||||
MooncakeEmbeddingStoreBackend,
|
||||
)
|
||||
from ..mooncake_store_embedding.store_client import (
|
||||
create_mooncake_embedding_store_client,
|
||||
)
|
||||
|
||||
namespace, max_items, max_bytes, read_bytes = self._store_config
|
||||
self._output_store = MooncakeEmbeddingStoreBackend(
|
||||
create_mooncake_embedding_store_client(read_buffer_bytes=read_bytes),
|
||||
namespace,
|
||||
max_pending_items=max_items,
|
||||
max_pending_bytes=max_bytes,
|
||||
)
|
||||
if not self.is_consumer or self._control_server is not None:
|
||||
return
|
||||
self._resolve_consumer_rank()
|
||||
@@ -470,6 +503,14 @@ class ECMooncakeWorker:
|
||||
tensor = encoder_cache.get(mm_hash)
|
||||
if tensor is not None:
|
||||
self._bind_push_source(tensor, mm_hash)
|
||||
if self._output_store is not None:
|
||||
loaded = self._output_store.resolve_inputs(
|
||||
metadata.store_candidates, encoder_cache, self._buffer_device
|
||||
)
|
||||
# Loaded entries precede the runner's new-output snapshot, so they
|
||||
# need explicit P2P source binding here.
|
||||
for mm_hash in loaded:
|
||||
self._bind_push_source(encoder_cache[mm_hash], mm_hash)
|
||||
|
||||
def _reserve_batch(self, records: list[ProducerPushRecord]) -> None:
|
||||
"""Resolve independent item futures with one reserve RPC per shard."""
|
||||
@@ -851,6 +892,8 @@ class ECMooncakeWorker:
|
||||
if not self.is_producer:
|
||||
return None, None
|
||||
|
||||
if self._output_store is not None:
|
||||
self._output_store.reap()
|
||||
for record in self._producer_pushes.cancel_requests(finished_req_ids):
|
||||
self._producer_pushes.submit_cancel(
|
||||
record,
|
||||
@@ -866,6 +909,8 @@ class ECMooncakeWorker:
|
||||
return
|
||||
tensor = encoder_cache[mm_hash]
|
||||
self._bind_push_source(tensor, mm_hash)
|
||||
if self._output_store is not None:
|
||||
self._output_store.save_output(mm_hash, tensor)
|
||||
|
||||
def build_connector_worker_meta(self) -> ECMooncakeWorkerMetadata | None:
|
||||
if self.is_consumer and not self._is_receiving_rank:
|
||||
@@ -938,3 +983,6 @@ class ECMooncakeWorker:
|
||||
)
|
||||
self._producer_memory.close()
|
||||
self._transfer.close()
|
||||
if self._output_store is not None:
|
||||
self._output_store.shutdown()
|
||||
self._output_store = None
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Mooncake Store support for cross-Encoder output reuse."""
|
||||
@@ -0,0 +1,214 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Encoder-side Mooncake Store resolver and publisher."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import traceback
|
||||
from collections.abc import Mapping
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .data import TensorSpec, make_embedding_key
|
||||
from .store_client import (
|
||||
EmbeddingStoreError,
|
||||
EmbeddingStoreOperationError,
|
||||
MooncakeEmbeddingStoreClient,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _StoreSave:
|
||||
tensor: torch.Tensor | None
|
||||
ready_event: torch.Event | None
|
||||
storage_ptr: int
|
||||
|
||||
def release(self) -> None:
|
||||
self.tensor = None
|
||||
self.ready_event = None
|
||||
|
||||
|
||||
class MooncakeEmbeddingStoreBackend:
|
||||
"""Resolve immutable encoder outputs and publish misses asynchronously."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store_client: MooncakeEmbeddingStoreClient,
|
||||
namespace: str,
|
||||
*,
|
||||
max_pending_items: int,
|
||||
max_pending_bytes: int,
|
||||
) -> None:
|
||||
self.store_client = store_client
|
||||
self.namespace = namespace
|
||||
self.max_pending_items = max_pending_items
|
||||
self.max_pending_bytes = max_pending_bytes
|
||||
self._executor = ThreadPoolExecutor(
|
||||
max_workers=1,
|
||||
thread_name_prefix="ec-mooncake-store",
|
||||
)
|
||||
self._pending: dict[str, tuple[Future[None], _StoreSave]] = {}
|
||||
self._pending_storages: dict[int, tuple[torch.UntypedStorage, int]] = {}
|
||||
self._pending_lock = threading.Lock()
|
||||
self._pending_bytes = 0
|
||||
self._step_candidates: set[str] = set()
|
||||
self._closed = False
|
||||
self._fatal_error: BaseException | None = None
|
||||
|
||||
def save_output(self, identifier: str, tensor: torch.Tensor) -> None:
|
||||
if identifier in self._step_candidates:
|
||||
self.reap()
|
||||
self._enqueue_save(identifier, tensor)
|
||||
|
||||
def resolve_inputs(
|
||||
self,
|
||||
expected_tensors: Mapping[str, TensorSpec],
|
||||
encoder_cache: dict[str, torch.Tensor],
|
||||
device: torch.device | str,
|
||||
) -> set[str]:
|
||||
"""Load outputs before encoding; unresolved items retain normal computation."""
|
||||
self.reap()
|
||||
self._step_candidates = set(expected_tensors)
|
||||
candidates = [key for key in expected_tensors if key not in encoder_cache]
|
||||
if not candidates:
|
||||
return set()
|
||||
|
||||
pool_keys = [
|
||||
make_embedding_key(self.namespace, identifier) for identifier in candidates
|
||||
]
|
||||
try:
|
||||
exists = self.store_client.batch_exists(pool_keys)
|
||||
except (EmbeddingStoreOperationError, OSError):
|
||||
logger.warning(
|
||||
"Mooncake embedding Store lookup failed; falling back to encoder",
|
||||
exc_info=True,
|
||||
)
|
||||
return set()
|
||||
|
||||
hits = {
|
||||
pool_key: expected_tensors[identifier]
|
||||
for identifier, pool_key, hit in zip(
|
||||
candidates, pool_keys, exists, strict=True
|
||||
)
|
||||
if hit
|
||||
}
|
||||
try:
|
||||
tensors = self.store_client.load_tensors(hits, device)
|
||||
except (EmbeddingStoreOperationError, OSError):
|
||||
logger.warning(
|
||||
"Mooncake embedding Store GET failed; falling back to encoder",
|
||||
exc_info=True,
|
||||
)
|
||||
return set()
|
||||
loaded: set[str] = set()
|
||||
for identifier, pool_key in zip(candidates, pool_keys, strict=True):
|
||||
if pool_key in tensors:
|
||||
encoder_cache[identifier] = tensors[pool_key]
|
||||
loaded.add(identifier)
|
||||
return loaded
|
||||
|
||||
def _enqueue_save(self, identifier: str, tensor: torch.Tensor) -> bool:
|
||||
"""Admit contiguous outputs, charging each retained storage once."""
|
||||
if not tensor.is_contiguous():
|
||||
return False
|
||||
storage = tensor.untyped_storage()
|
||||
storage_ptr = storage.data_ptr()
|
||||
with self._pending_lock:
|
||||
if self._fatal_error is not None:
|
||||
raise EmbeddingStoreError(
|
||||
"Store publisher has failed"
|
||||
) from self._fatal_error
|
||||
if self._closed or identifier in self._pending:
|
||||
return False
|
||||
_, ref_count = self._pending_storages.get(storage_ptr, (storage, 0))
|
||||
budget_bytes = 0 if ref_count else storage.nbytes()
|
||||
if (
|
||||
len(self._pending) >= self.max_pending_items
|
||||
or self._pending_bytes + budget_bytes > self.max_pending_bytes
|
||||
):
|
||||
return False
|
||||
# Only admitted work creates an event. Runtime errors propagate.
|
||||
save = _StoreSave(
|
||||
tensor,
|
||||
_record_tensor_ready_event(tensor),
|
||||
storage_ptr,
|
||||
)
|
||||
future = self._executor.submit(
|
||||
self._save, make_embedding_key(self.namespace, identifier), save
|
||||
)
|
||||
self._pending[identifier] = (future, save)
|
||||
# Keep the storage alive until reaping so its address cannot be reused.
|
||||
self._pending_storages[storage_ptr] = (storage, ref_count + 1)
|
||||
self._pending_bytes += budget_bytes
|
||||
return True
|
||||
|
||||
def _save(self, pool_key: str, save: _StoreSave) -> None:
|
||||
try:
|
||||
if self.store_client.exists(pool_key):
|
||||
return
|
||||
tensor = save.tensor
|
||||
assert tensor is not None
|
||||
if save.ready_event is not None:
|
||||
save.ready_event.synchronize()
|
||||
self.store_client.put_tensor(pool_key, tensor)
|
||||
except BaseException as error:
|
||||
# Returned client frames can otherwise keep tensors via a Future's
|
||||
# traceback. Uncertain I/O owners remain retained by the client.
|
||||
traceback.clear_frames(error.__traceback__)
|
||||
raise
|
||||
finally:
|
||||
tensor = None
|
||||
save.release()
|
||||
|
||||
def reap(self) -> None:
|
||||
with self._pending_lock:
|
||||
for identifier, (future, save) in list(self._pending.items()):
|
||||
# Observe once; a racing completion is handled on the next poll.
|
||||
if not future.done():
|
||||
continue
|
||||
try:
|
||||
future.result() # Already done: never waits on Store I/O.
|
||||
except (EmbeddingStoreOperationError, OSError) as error:
|
||||
logger.warning("Store PUT failed for %s: %s", identifier, error)
|
||||
# This failure is consumed; do not retain publisher/caller frames.
|
||||
error.__traceback__ = None
|
||||
except BaseException as error:
|
||||
# The client may still own unsafe native-I/O buffers. Keep
|
||||
# their charge and fatal result until worker termination.
|
||||
if self._fatal_error is None:
|
||||
self._fatal_error = error
|
||||
continue
|
||||
del self._pending[identifier]
|
||||
storage, ref_count = self._pending_storages[save.storage_ptr]
|
||||
if ref_count == 1:
|
||||
del self._pending_storages[save.storage_ptr]
|
||||
self._pending_bytes -= storage.nbytes()
|
||||
else:
|
||||
self._pending_storages[save.storage_ptr] = (storage, ref_count - 1)
|
||||
fatal = self._fatal_error
|
||||
if fatal is not None:
|
||||
raise fatal
|
||||
|
||||
def shutdown(self) -> None:
|
||||
with self._pending_lock:
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
self._executor.shutdown(wait=True, cancel_futures=False)
|
||||
self.reap()
|
||||
self.store_client.close()
|
||||
|
||||
|
||||
def _record_tensor_ready_event(tensor: torch.Tensor) -> torch.Event | None:
|
||||
if tensor.device.type != "cuda":
|
||||
return None
|
||||
event = torch.Event()
|
||||
event.record(torch.accelerator.current_stream(tensor.device))
|
||||
return event
|
||||
@@ -0,0 +1,51 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Content identities and output contracts for the shared Encoder Store."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
EMBEDDING_CACHE_KEY_VERSION = "v3"
|
||||
|
||||
|
||||
def make_embedding_key(namespace: str, identifier: str) -> str:
|
||||
return f"{namespace}@id:{identifier}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TensorSpec:
|
||||
"""Contiguous output contract used by the Encoder and Store codec."""
|
||||
|
||||
shape: tuple[int, ...]
|
||||
dtype: str
|
||||
nbytes: int
|
||||
|
||||
|
||||
def build_embedding_namespace(vllm_config: VllmConfig) -> str:
|
||||
model_config = vllm_config.model_config
|
||||
ec_config = vllm_config.ec_transfer_config
|
||||
assert ec_config is not None
|
||||
extra_config = ec_config.ec_connector_extra_config
|
||||
|
||||
multimodal_config = model_config.multimodal_config
|
||||
encoder_hash = (
|
||||
multimodal_config.compute_hash()
|
||||
if multimodal_config is not None
|
||||
else "encoder:default"
|
||||
)
|
||||
cache_prefix = str(extra_config.get("embedding_cache_prefix", ""))
|
||||
model_name = str(extra_config.get("embedding_model_identity", model_config.model))
|
||||
prefix = f"{cache_prefix}@" if cache_prefix else ""
|
||||
return (
|
||||
f"{prefix}embedding"
|
||||
f"@model:{model_name}"
|
||||
f"@revision:{model_config.revision or 'default'}"
|
||||
f"@encoder:{encoder_hash}"
|
||||
f"@dtype:{model_config.dtype}"
|
||||
f"@protocol:{EMBEDDING_CACHE_KEY_VERSION}"
|
||||
)
|
||||
@@ -0,0 +1,463 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Thin Mooncake Store client for embedding objects.
|
||||
|
||||
Originally adapted from vLLM PR #47302 (0d1f71f5d36c). The v3 key namespace
|
||||
uses a compact header for complete 2D embeddings, not that PR's tensor format.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import struct
|
||||
import threading
|
||||
from collections.abc import Callable, Iterator, Mapping
|
||||
from contextlib import contextmanager
|
||||
from enum import IntEnum
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.distributed.ec_transfer.ec_connector.mooncake_store_embedding.data import (
|
||||
TensorSpec,
|
||||
)
|
||||
from vllm.distributed.mooncake_store import MooncakeStoreConfig, setup_mooncake_store
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.network_utils import get_ip
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# A failed transfer can still use registered memory after the binding returns.
|
||||
# Poisoned clients retain their owners until process exit, including if normal
|
||||
# worker teardown drops the connector. New operations are rejected.
|
||||
_UNSAFE_CLIENTS: list[Any] = []
|
||||
|
||||
|
||||
# Values from Mooncake v0.3.12 / v0.3.12.post1 types.h (ErrorCode).
|
||||
# Python exposes integer returns, not this enum.
|
||||
class _MooncakeErrorCode(IntEnum):
|
||||
NO_AVAILABLE_HANDLE = -200
|
||||
INVALID_PARAMS = -600
|
||||
INVALID_REPLICA = -702
|
||||
REPLICA_IS_NOT_READY = -703
|
||||
OBJECT_NOT_FOUND = -704
|
||||
OBJECT_ALREADY_EXISTS = -705
|
||||
LEASE_EXPIRED = -707
|
||||
RPC_FAIL = -900
|
||||
RPC_TIMEOUT = -901
|
||||
TENANT_QUOTA_EXCEEDED = -1700
|
||||
|
||||
|
||||
# For RAM batch reads and single-replica writes, these rejections occur
|
||||
# before submission or after completed I/O. Transfer timeouts can leave I/O
|
||||
# in flight; all other failures retain registered buffers and poison the client.
|
||||
_SAFE_IO_REJECTIONS = frozenset(
|
||||
{
|
||||
_MooncakeErrorCode.NO_AVAILABLE_HANDLE,
|
||||
_MooncakeErrorCode.REPLICA_IS_NOT_READY,
|
||||
_MooncakeErrorCode.OBJECT_NOT_FOUND,
|
||||
_MooncakeErrorCode.OBJECT_ALREADY_EXISTS,
|
||||
_MooncakeErrorCode.RPC_FAIL,
|
||||
_MooncakeErrorCode.RPC_TIMEOUT,
|
||||
}
|
||||
)
|
||||
# Batch GET validates capacity/replicas before I/O and checks leases afterwards.
|
||||
# PUT rejects tenant quotas before allocating replicas or submitting transfers.
|
||||
_SAFE_GET_REJECTIONS = _SAFE_IO_REJECTIONS | {
|
||||
_MooncakeErrorCode.INVALID_PARAMS,
|
||||
_MooncakeErrorCode.INVALID_REPLICA,
|
||||
_MooncakeErrorCode.LEASE_EXPIRED,
|
||||
}
|
||||
_SAFE_PUT_REJECTIONS = _SAFE_IO_REJECTIONS | {_MooncakeErrorCode.TENANT_QUOTA_EXCEEDED}
|
||||
|
||||
|
||||
_MOONCAKE_TENSOR_OBJECT_MAGIC = 0x4D4F4F4E
|
||||
# Magic, dtype, token count, hidden dimension. Format versioning is in the key.
|
||||
_MOONCAKE_TENSOR_HEADER = struct.Struct("<IIQQ")
|
||||
_MOONCAKE_DTYPE_TO_TORCH_DTYPE = {
|
||||
0: "torch.float32",
|
||||
11: "torch.float16",
|
||||
12: "torch.bfloat16",
|
||||
}
|
||||
_TORCH_DTYPE_TO_MOONCAKE_DTYPE = {
|
||||
value: key for key, value in _MOONCAKE_DTYPE_TO_TORCH_DTYPE.items()
|
||||
}
|
||||
|
||||
|
||||
def create_mooncake_embedding_store_client(
|
||||
read_buffer_bytes: int = 128 * 1024**2,
|
||||
) -> MooncakeEmbeddingStoreClient:
|
||||
try:
|
||||
from mooncake.store import ( # type: ignore
|
||||
MooncakeDistributedStore,
|
||||
ObjectDataType,
|
||||
ReplicateConfig,
|
||||
)
|
||||
except ImportError as e:
|
||||
raise ImportError(
|
||||
"Install mooncake with Store support to enable cross_encoder_cache."
|
||||
) from e
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake import rdma_utils
|
||||
|
||||
config = MooncakeStoreConfig.load_from_config()
|
||||
if config.enable_offload:
|
||||
raise ValueError(
|
||||
"cross_encoder_cache supports a RAM Store; disable enable_offload"
|
||||
)
|
||||
store = MooncakeDistributedStore()
|
||||
local_ip = get_ip()
|
||||
local_hostname = rdma_utils.get_requester_local_hostname(local_ip)
|
||||
setup_mooncake_store(store, config, local_hostname)
|
||||
|
||||
logger.info(
|
||||
"Initialized embedding Mooncake store mode=%s global_segment_size=%d "
|
||||
"local_buffer_size=%d",
|
||||
config.mode,
|
||||
config.global_segment_size,
|
||||
config.local_buffer_size,
|
||||
)
|
||||
replicate_config = ReplicateConfig()
|
||||
replicate_config.data_type = ObjectDataType.TENSOR
|
||||
return MooncakeEmbeddingStoreClient(
|
||||
store, replicate_config=replicate_config, read_buffer_bytes=read_buffer_bytes
|
||||
)
|
||||
|
||||
|
||||
class EmbeddingStoreError(RuntimeError):
|
||||
"""A Store failure that must propagate to the worker."""
|
||||
|
||||
|
||||
class EmbeddingStoreOperationError(EmbeddingStoreError):
|
||||
"""A rejected or completed operation that permits normal Encoder fallback."""
|
||||
|
||||
|
||||
def _batch_get_completed_safely(results: Any, capacities: list[int]) -> bool:
|
||||
return (
|
||||
isinstance(results, list)
|
||||
and len(results) == len(capacities)
|
||||
and all(
|
||||
type(result) is int
|
||||
and (0 <= result <= capacity or result in _SAFE_GET_REJECTIONS)
|
||||
for result, capacity in zip(results, capacities, strict=True)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class MooncakeEmbeddingStoreClient:
|
||||
"""Wraps Mooncake object and buffer APIs used by embedding transfer."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: Any,
|
||||
replicate_config: Any | None = None,
|
||||
*,
|
||||
read_buffer_bytes: int = 128 * 1024**2,
|
||||
):
|
||||
self._lifetime_lock = threading.Lock()
|
||||
self._unsafe_owners: list[Any] = []
|
||||
self._poisoned = False
|
||||
self.store = store
|
||||
self.replicate_config = replicate_config
|
||||
self._read_buffer_bytes = read_buffer_bytes
|
||||
self._read_buffer: torch.Tensor | None = None
|
||||
self._put_header: ctypes.Array[ctypes.c_char] | None = None
|
||||
|
||||
def _check_healthy(self) -> None:
|
||||
if self._poisoned:
|
||||
raise EmbeddingStoreError(
|
||||
"Mooncake I/O completion is unconfirmed; worker must exit"
|
||||
)
|
||||
|
||||
def _poison(self, owners: list[Any]) -> None:
|
||||
with self._lifetime_lock:
|
||||
self._unsafe_owners.extend(owners)
|
||||
if not self._poisoned:
|
||||
self._poisoned = True
|
||||
_UNSAFE_CLIENTS.append(self)
|
||||
|
||||
@contextmanager
|
||||
def _registered_io(
|
||||
self,
|
||||
buffers: list[tuple[Any, int, int]],
|
||||
) -> Iterator[Callable[[int], None]]:
|
||||
self._check_healthy()
|
||||
registered = []
|
||||
submitted = False
|
||||
confirmed = False
|
||||
|
||||
def confirm(result: int) -> None:
|
||||
nonlocal confirmed
|
||||
if type(result) is not int or (
|
||||
result < 0 and result not in _SAFE_PUT_REJECTIONS
|
||||
):
|
||||
raise EmbeddingStoreError(
|
||||
"Mooncake I/O completion is unconfirmed; retaining buffers"
|
||||
)
|
||||
confirmed = True
|
||||
|
||||
try:
|
||||
for owner, addr, size in buffers:
|
||||
ret = self.store.register_buffer(addr, size)
|
||||
if ret != 0:
|
||||
raise EmbeddingStoreOperationError(
|
||||
f"Failed to register embedding buffer: {ret}"
|
||||
)
|
||||
registered.append(addr)
|
||||
submitted = True
|
||||
yield confirm
|
||||
except BaseException as error:
|
||||
if submitted and not confirmed:
|
||||
self._poison([owner for owner, _, _ in buffers])
|
||||
raise EmbeddingStoreError(
|
||||
"Mooncake I/O completion is unconfirmed; retaining buffers"
|
||||
) from error
|
||||
raise
|
||||
finally:
|
||||
if not submitted or confirmed:
|
||||
try:
|
||||
for addr in reversed(registered):
|
||||
self._unregister_buffer(addr)
|
||||
except BaseException:
|
||||
self._poison([owner for owner, _, _ in buffers])
|
||||
raise
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the supported Mooncake binding after all I/O is drained."""
|
||||
self._check_healthy()
|
||||
if self._read_buffer is not None:
|
||||
try:
|
||||
self._unregister_buffer(self._read_buffer.data_ptr())
|
||||
except BaseException:
|
||||
self._poison([self._read_buffer])
|
||||
raise
|
||||
self._read_buffer = None
|
||||
if self._put_header is not None:
|
||||
try:
|
||||
self._unregister_buffer(ctypes.addressof(self._put_header))
|
||||
except BaseException:
|
||||
self._poison([self._put_header])
|
||||
raise
|
||||
self._put_header = None
|
||||
ret = self.store.close()
|
||||
if ret != 0:
|
||||
raise EmbeddingStoreError(
|
||||
f"failed to close embedding Mooncake Store: {ret}"
|
||||
)
|
||||
|
||||
def exists(self, pool_key: str) -> bool:
|
||||
return self.batch_exists([pool_key])[0]
|
||||
|
||||
def batch_exists(self, keys: list[str]) -> list[bool]:
|
||||
self._check_healthy()
|
||||
if not keys:
|
||||
return []
|
||||
|
||||
states = self.store.batch_is_exist(keys)
|
||||
if len(states) != len(keys):
|
||||
raise RuntimeError(
|
||||
"Mooncake Store returned an unexpected number of lookup results"
|
||||
)
|
||||
return [state == 1 for state in states]
|
||||
|
||||
def load_tensors(
|
||||
self, expected: Mapping[str, TensorSpec], device: torch.device | str
|
||||
) -> dict[str, torch.Tensor]:
|
||||
"""Synchronously load runner inputs into independently owned tensors."""
|
||||
self._check_healthy()
|
||||
device = torch.device(device)
|
||||
loaded: dict[str, torch.Tensor] = {}
|
||||
chunk: dict[str, TensorSpec] = {}
|
||||
chunk_bytes = 0
|
||||
for key, spec in expected.items():
|
||||
size = _MOONCAKE_TENSOR_HEADER.size + spec.nbytes
|
||||
if size > self._read_buffer_bytes:
|
||||
logger.warning(
|
||||
"Skipping Store GET for %s: object bytes=%d exceed read buffer=%d",
|
||||
key,
|
||||
size,
|
||||
self._read_buffer_bytes,
|
||||
)
|
||||
continue
|
||||
if chunk_bytes + size > self._read_buffer_bytes:
|
||||
loaded.update(self._load_chunk(chunk, device))
|
||||
chunk = {}
|
||||
chunk_bytes = 0
|
||||
chunk[key] = spec
|
||||
chunk_bytes += size
|
||||
if chunk:
|
||||
loaded.update(self._load_chunk(chunk, device))
|
||||
return loaded
|
||||
|
||||
def _load_chunk(
|
||||
self, expected: dict[str, TensorSpec], device: torch.device
|
||||
) -> dict[str, torch.Tensor]:
|
||||
self._check_healthy()
|
||||
if self._read_buffer is None:
|
||||
buffer = torch.empty(
|
||||
self._read_buffer_bytes,
|
||||
dtype=torch.uint8,
|
||||
device="cpu",
|
||||
pin_memory=device.type == "cuda",
|
||||
)
|
||||
ret = self.store.register_buffer(buffer.data_ptr(), buffer.nbytes)
|
||||
if ret != 0:
|
||||
raise EmbeddingStoreOperationError(
|
||||
f"Failed to register embedding read buffer: {ret}"
|
||||
)
|
||||
self._read_buffer = buffer
|
||||
buffer = self._read_buffer
|
||||
base = buffer.data_ptr()
|
||||
sizes = [
|
||||
_MOONCAKE_TENSOR_HEADER.size + spec.nbytes for spec in expected.values()
|
||||
]
|
||||
offsets: list[int] = []
|
||||
end = 0
|
||||
for size in sizes:
|
||||
offsets.append(end)
|
||||
end += size
|
||||
try:
|
||||
results = self.store.batch_get_into(
|
||||
list(expected), [base + offset for offset in offsets], sizes
|
||||
)
|
||||
if not _batch_get_completed_safely(results, sizes):
|
||||
raise EmbeddingStoreError("Unsafe batch GET results")
|
||||
except BaseException as error:
|
||||
self._poison([buffer])
|
||||
raise EmbeddingStoreError(
|
||||
"Mooncake I/O completion is unconfirmed; retaining read buffer"
|
||||
) from error
|
||||
|
||||
valid: list[tuple[str, TensorSpec, int]] = []
|
||||
for (key, spec), offset, size, result in zip(
|
||||
expected.items(), offsets, sizes, results, strict=True
|
||||
):
|
||||
if result != size:
|
||||
logger.warning(
|
||||
"Store GET skipped for %s: result=%d, expected bytes=%d",
|
||||
key,
|
||||
result,
|
||||
size,
|
||||
)
|
||||
continue
|
||||
try:
|
||||
_validate_mooncake_tensor_metadata(
|
||||
key,
|
||||
ctypes.string_at(base + offset, _MOONCAKE_TENSOR_HEADER.size),
|
||||
spec,
|
||||
)
|
||||
except EmbeddingStoreOperationError as error:
|
||||
logger.warning("Store GET skipped for %s: %s", key, error)
|
||||
continue
|
||||
valid.append((key, spec, offset + _MOONCAKE_TENSOR_HEADER.size))
|
||||
if not valid:
|
||||
return {}
|
||||
# Allocate every destination before submitting any asynchronous copy.
|
||||
targets = {
|
||||
key: torch.empty(
|
||||
spec.shape,
|
||||
dtype=getattr(torch, spec.dtype.removeprefix("torch.")),
|
||||
device=device,
|
||||
)
|
||||
for key, spec, _ in valid
|
||||
}
|
||||
ready = torch.Event() if device.type == "cuda" else None
|
||||
try:
|
||||
for key, spec, offset in valid:
|
||||
targets[key].view(torch.uint8).view(-1).copy_(
|
||||
buffer[offset : offset + spec.nbytes],
|
||||
non_blocking=ready is not None,
|
||||
)
|
||||
if ready is not None:
|
||||
ready.record(torch.accelerator.current_stream(device))
|
||||
ready.synchronize()
|
||||
except BaseException as error:
|
||||
if ready is not None:
|
||||
self._poison([buffer, *targets.values(), ready])
|
||||
raise EmbeddingStoreError(
|
||||
"Embedding copy completion is unconfirmed; retaining buffers"
|
||||
) from error
|
||||
raise
|
||||
return targets
|
||||
|
||||
def put_tensor(self, pool_key: str, tensor: torch.Tensor) -> None:
|
||||
self._check_healthy()
|
||||
if not tensor.is_contiguous():
|
||||
raise EmbeddingStoreOperationError("embedding tensor must be contiguous")
|
||||
metadata = _encode_mooncake_tensor_metadata(tensor)
|
||||
# The single publisher reuses this header only after PUT completion.
|
||||
if self._put_header is None:
|
||||
header = ctypes.create_string_buffer(len(metadata))
|
||||
ret = self.store.register_buffer(ctypes.addressof(header), len(metadata))
|
||||
if ret != 0:
|
||||
raise EmbeddingStoreOperationError(
|
||||
f"Failed to register embedding header: {ret}"
|
||||
)
|
||||
self._put_header = header
|
||||
header_ptr = ctypes.addressof(self._put_header)
|
||||
ctypes.memmove(header_ptr, metadata, len(metadata))
|
||||
data_size = tensor.numel() * tensor.element_size()
|
||||
buffers = [
|
||||
(tensor, tensor.data_ptr(), data_size),
|
||||
]
|
||||
with self._registered_io(buffers) as confirm:
|
||||
[result] = self.store.batch_put_from_multi_buffers(
|
||||
[pool_key],
|
||||
[[header_ptr, tensor.data_ptr()]],
|
||||
[[len(metadata), data_size]],
|
||||
self.replicate_config,
|
||||
)
|
||||
confirm(result)
|
||||
if result < 0:
|
||||
raise EmbeddingStoreOperationError(
|
||||
f"failed to put embedding tensor for {pool_key}"
|
||||
)
|
||||
|
||||
def _unregister_buffer(self, addr: int) -> None:
|
||||
try:
|
||||
ret = self.store.unregister_buffer(addr)
|
||||
except Exception as error:
|
||||
raise EmbeddingStoreError(
|
||||
f"could not confirm buffer unregistration addr={addr:#x}"
|
||||
) from error
|
||||
if ret != 0:
|
||||
raise EmbeddingStoreError(
|
||||
f"failed to unregister embedding buffer addr={addr:#x}: {ret}"
|
||||
)
|
||||
|
||||
|
||||
def _validate_mooncake_tensor_metadata(
|
||||
pool_key: str,
|
||||
metadata: bytes,
|
||||
expected: TensorSpec,
|
||||
) -> None:
|
||||
magic, dtype, num_tokens, hidden_dim = _MOONCAKE_TENSOR_HEADER.unpack(metadata)
|
||||
if magic != _MOONCAKE_TENSOR_OBJECT_MAGIC:
|
||||
raise EmbeddingStoreOperationError(
|
||||
f"invalid Mooncake tensor metadata header for {pool_key}"
|
||||
)
|
||||
if _MOONCAKE_DTYPE_TO_TORCH_DTYPE.get(dtype) != expected.dtype:
|
||||
raise EmbeddingStoreOperationError(
|
||||
f"unexpected Mooncake tensor dtype for {pool_key}: {dtype}"
|
||||
)
|
||||
if (num_tokens, hidden_dim) != expected.shape:
|
||||
raise EmbeddingStoreOperationError(
|
||||
f"embedding tensor shape mismatch for {pool_key}: expected={expected.shape}"
|
||||
)
|
||||
|
||||
|
||||
def _encode_mooncake_tensor_metadata(tensor: torch.Tensor) -> bytes:
|
||||
dtype = str(tensor.dtype)
|
||||
if dtype not in _TORCH_DTYPE_TO_MOONCAKE_DTYPE:
|
||||
raise EmbeddingStoreOperationError(
|
||||
f"unsupported embedding tensor dtype: {dtype}"
|
||||
)
|
||||
if tensor.ndim != 2:
|
||||
raise EmbeddingStoreOperationError(
|
||||
f"embedding tensor must be 2D: shape={tuple(tensor.shape)}"
|
||||
)
|
||||
return _MOONCAKE_TENSOR_HEADER.pack(
|
||||
_MOONCAKE_TENSOR_OBJECT_MAGIC,
|
||||
_TORCH_DTYPE_TO_MOONCAKE_DTYPE[dtype],
|
||||
*tensor.shape,
|
||||
)
|
||||
@@ -10,7 +10,7 @@ import torch
|
||||
from vllm.distributed.parallel_state import get_eplb_group
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .eplb_utils import CpuGpuEvent
|
||||
from .eplb_utils import CpuGpuEvent, device_stream
|
||||
from .rebalance_execute import AsyncEplbLayerResult, transfer_layer
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -24,17 +24,17 @@ def start_async_worker(
|
||||
is_profile: bool = False,
|
||||
) -> threading.Thread:
|
||||
rank = get_eplb_group().device_group.rank()
|
||||
device_index = state.cuda_device_index
|
||||
device_index = state.device_index
|
||||
assert state.is_async
|
||||
|
||||
def thread_target() -> None:
|
||||
assert device_index is not None
|
||||
torch.accelerator.set_device_index(device_index)
|
||||
cuda_stream = torch.cuda.Stream(device=device_index)
|
||||
stream = torch.Stream(device=torch.accelerator.current_accelerator())
|
||||
try:
|
||||
transfer_run_periodically(
|
||||
state=state,
|
||||
cuda_stream=cuda_stream,
|
||||
stream=stream,
|
||||
is_profile=is_profile,
|
||||
)
|
||||
except Exception as exc: # pragma: no cover - diagnostic path
|
||||
@@ -49,13 +49,13 @@ def run_rebalance_experts(
|
||||
model_state: "EplbModelState",
|
||||
eplb_state: "EplbState",
|
||||
physical_to_logical_map_cpu: torch.Tensor,
|
||||
cuda_stream: torch.cuda.Stream,
|
||||
stream: torch.Stream,
|
||||
) -> torch.Tensor:
|
||||
assert model_state.eplb_stats is not None
|
||||
eplb_stats = model_state.eplb_stats
|
||||
|
||||
# Move the global expert load window to CPU for computation.
|
||||
with torch.cuda.stream(cuda_stream):
|
||||
with device_stream(stream):
|
||||
global_expert_load_window = eplb_stats.global_expert_load_window.cpu()
|
||||
# Compute new expert mappings for the model
|
||||
new_physical_to_logical_map = eplb_state.policy.rebalance_experts(
|
||||
@@ -73,11 +73,11 @@ def run_rebalance_experts(
|
||||
|
||||
def transfer_run_periodically(
|
||||
state: "EplbState",
|
||||
cuda_stream: torch.cuda.Stream,
|
||||
stream: torch.Stream,
|
||||
is_profile: bool = False,
|
||||
) -> None:
|
||||
while True:
|
||||
state.rearrange_event.wait(stream=cuda_stream)
|
||||
state.rearrange_event.wait(stream=stream)
|
||||
|
||||
eplb_group = get_eplb_group().device_group
|
||||
eplb_cpu_group = get_eplb_group().cpu_group
|
||||
@@ -87,16 +87,16 @@ def transfer_run_periodically(
|
||||
for model_state in state.model_states.values():
|
||||
layer_idx = 0
|
||||
# Set the async worker's CUDA stream on the communicator
|
||||
model_state.communicator.set_stream(cuda_stream)
|
||||
model_state.communicator.set_stream(stream)
|
||||
num_layers = model_state.model.num_moe_layers
|
||||
|
||||
# Snapshot the physical_to_logical_map (synchronized with
|
||||
# rearrange_event) and copy it to CPU
|
||||
with torch.cuda.stream(cuda_stream):
|
||||
with device_stream(stream):
|
||||
physical_to_logical_map_cpu = model_state.physical_to_logical_map.cpu()
|
||||
|
||||
new_physical_to_logical_map = run_rebalance_experts(
|
||||
model_state, state, physical_to_logical_map_cpu, cuda_stream
|
||||
model_state, state, physical_to_logical_map_cpu, stream
|
||||
)
|
||||
|
||||
# Execute one EPLB layer transfer per model forward pass. Each iteration
|
||||
@@ -132,13 +132,13 @@ def transfer_run_periodically(
|
||||
communicator=model_state.communicator,
|
||||
ep_group=eplb_group,
|
||||
is_profile=is_profile,
|
||||
cuda_stream=cuda_stream,
|
||||
stream=stream,
|
||||
layer_idx=layer_idx,
|
||||
)
|
||||
|
||||
# Wait until all writes to expert_buffer have finished before making the
|
||||
# AsyncEplbLayerResult visible to the main thread.
|
||||
cuda_stream.synchronize()
|
||||
stream.synchronize()
|
||||
|
||||
# This event guarantees that expert_buffer will not be overwritten by
|
||||
# subsequent iterations of this loop until the main thread has consumed
|
||||
@@ -155,6 +155,6 @@ def transfer_run_periodically(
|
||||
# Block this thread until the main thread and main stream
|
||||
# finish copying model_state.expert_buffer into
|
||||
# model_state.model.expert_weights[layer_idx]
|
||||
consumed_event.wait(stream=cuda_stream)
|
||||
consumed_event.wait(stream=stream)
|
||||
assert model_state.pending_result is None
|
||||
layer_idx += 1
|
||||
|
||||
@@ -22,6 +22,7 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.device_communicators.pynccl_wrapper import (
|
||||
ncclDataTypeEnum,
|
||||
)
|
||||
from vllm.distributed.eplb.eplb_utils import device_stream
|
||||
from vllm.distributed.parallel_state import (
|
||||
GroupCoordinator,
|
||||
get_pp_group,
|
||||
@@ -87,8 +88,8 @@ class EplbCommunicator(ABC):
|
||||
communication buffers."""
|
||||
return True
|
||||
|
||||
def set_stream(self, cuda_stream: torch.cuda.Stream | None) -> None:
|
||||
self._cuda_stream = cuda_stream
|
||||
def set_stream(self, stream: torch.Stream | None) -> None:
|
||||
self._stream = stream
|
||||
|
||||
def _log_initialized(self) -> None:
|
||||
if is_local_first_rank():
|
||||
@@ -101,10 +102,10 @@ class TorchDistNcclEplbCommunicator(EplbCommunicator):
|
||||
def __init__(
|
||||
self,
|
||||
ep_group: ProcessGroup,
|
||||
cuda_stream: torch.cuda.Stream | None = None,
|
||||
stream: torch.Stream | None = None,
|
||||
) -> None:
|
||||
self._ep_group = ep_group
|
||||
self._cuda_stream = cuda_stream
|
||||
self._stream = stream
|
||||
self._p2p_ops: list[P2POp] = []
|
||||
self._log_initialized()
|
||||
|
||||
@@ -144,7 +145,7 @@ class TorchDistNcclEplbCommunicator(EplbCommunicator):
|
||||
if not self._p2p_ops:
|
||||
return
|
||||
try:
|
||||
with torch.cuda.stream(self._cuda_stream):
|
||||
with device_stream(self._stream):
|
||||
reqs = batch_isend_irecv(self._p2p_ops)
|
||||
for req in reqs:
|
||||
req.wait()
|
||||
@@ -158,10 +159,10 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
def __init__(
|
||||
self,
|
||||
cpu_group: ProcessGroup,
|
||||
cuda_stream: torch.cuda.Stream | None = None,
|
||||
stream: torch.Stream | None = None,
|
||||
) -> None:
|
||||
self._cpu_group = cpu_group
|
||||
self._cuda_stream = cuda_stream
|
||||
self._stream = stream
|
||||
self._ops: list[tuple[str, torch.Tensor, int]] = []
|
||||
self._log_initialized()
|
||||
|
||||
@@ -217,7 +218,7 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
recv_staging.append((tensor, cpu_tensor))
|
||||
|
||||
try:
|
||||
with torch.cuda.stream(self._cuda_stream):
|
||||
with device_stream(self._stream):
|
||||
build_ops()
|
||||
finally:
|
||||
self._ops.clear()
|
||||
@@ -225,10 +226,10 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
# Wait for all D2H copies to finish
|
||||
# before issuing gloo batch_isend_irecv operations.
|
||||
with gpu_sync_allowed():
|
||||
if self._cuda_stream is not None:
|
||||
self._cuda_stream.synchronize()
|
||||
if self._stream is not None:
|
||||
self._stream.synchronize()
|
||||
else:
|
||||
torch.cuda.current_stream().synchronize()
|
||||
torch.accelerator.current_stream().synchronize()
|
||||
|
||||
reqs = batch_isend_irecv(p2p_ops)
|
||||
for req in reqs:
|
||||
@@ -236,11 +237,69 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
|
||||
if not recv_staging:
|
||||
return
|
||||
with torch.cuda.stream(self._cuda_stream):
|
||||
with device_stream(self._stream):
|
||||
for dst_tensor, cpu_tensor in recv_staging:
|
||||
dst_tensor.copy_(cpu_tensor, non_blocking=True)
|
||||
|
||||
|
||||
class TorchDistXCCLStagedEplbCommunicator(EplbCommunicator):
|
||||
"""EPLB communicator using XCCL device-to-device P2P on XPU."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ep_group: ProcessGroup,
|
||||
stream: torch.Stream | None = None,
|
||||
) -> None:
|
||||
self._ep_group = ep_group
|
||||
self._stream = stream
|
||||
self._ops: list[tuple[str, torch.Tensor, int]] = []
|
||||
self._log_initialized()
|
||||
|
||||
def add_send(
|
||||
self,
|
||||
tensors: list[torch.Tensor],
|
||||
dst_rank: int,
|
||||
expert_id: int, # unused by this backend
|
||||
) -> None:
|
||||
for tensor in tensors:
|
||||
self._ops.append(("send", tensor, dst_rank))
|
||||
|
||||
def add_recv(
|
||||
self,
|
||||
tensors: list[torch.Tensor],
|
||||
src_rank: int,
|
||||
expert_id: int, # unused by this backend
|
||||
) -> None:
|
||||
for tensor in tensors:
|
||||
self._ops.append(("recv", tensor, src_rank))
|
||||
|
||||
def execute(self) -> None:
|
||||
if not self._ops:
|
||||
return
|
||||
|
||||
p2p_ops: list[P2POp] = []
|
||||
try:
|
||||
for op, tensor, peer_rank in self._ops:
|
||||
send_or_recv = (
|
||||
torch.distributed.isend if op == "send" else torch.distributed.irecv
|
||||
)
|
||||
p2p_ops.append(
|
||||
P2POp(
|
||||
send_or_recv,
|
||||
tensor,
|
||||
peer_rank,
|
||||
self._ep_group,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
self._ops.clear()
|
||||
|
||||
with device_stream(self._stream):
|
||||
reqs = batch_isend_irecv(p2p_ops)
|
||||
for req in reqs:
|
||||
req.wait()
|
||||
|
||||
|
||||
class NixlEplbCommunicator(EplbCommunicator):
|
||||
"""EPLB communicator backed by NIXL READ transfers."""
|
||||
|
||||
@@ -343,7 +402,7 @@ class NixlEplbCommunicator(EplbCommunicator):
|
||||
uid = uuid.uuid4().hex[:8]
|
||||
return f"eplb-{self._rank}{pp_suffix}-{uid}"
|
||||
|
||||
def set_stream(self, cuda_stream: torch.cuda.Stream | None) -> None:
|
||||
def set_stream(self, stream: torch.Stream | None) -> None:
|
||||
pass
|
||||
|
||||
def add_send(
|
||||
@@ -602,10 +661,10 @@ class PyNcclEplbCommunicator(EplbCommunicator):
|
||||
def __init__(
|
||||
self,
|
||||
pynccl_comm: PyNcclCommunicator,
|
||||
cuda_stream: torch.cuda.Stream | None = None,
|
||||
stream: torch.Stream | None = None,
|
||||
) -> None:
|
||||
self._pynccl_comm = pynccl_comm
|
||||
self._cuda_stream = cuda_stream
|
||||
self._stream = stream
|
||||
self._group_started = False
|
||||
self._log_initialized()
|
||||
|
||||
@@ -622,7 +681,7 @@ class PyNcclEplbCommunicator(EplbCommunicator):
|
||||
) -> None:
|
||||
self._ensure_group_started()
|
||||
for tensor in tensors:
|
||||
self._pynccl_comm.send(tensor, dst_rank, stream=self._cuda_stream)
|
||||
self._pynccl_comm.send(tensor, dst_rank, stream=self._stream)
|
||||
|
||||
def add_recv(
|
||||
self,
|
||||
@@ -632,7 +691,7 @@ class PyNcclEplbCommunicator(EplbCommunicator):
|
||||
) -> None:
|
||||
self._ensure_group_started()
|
||||
for tensor in tensors:
|
||||
self._pynccl_comm.recv(tensor, src_rank, stream=self._cuda_stream)
|
||||
self._pynccl_comm.recv(tensor, src_rank, stream=self._stream)
|
||||
|
||||
def execute(self) -> None:
|
||||
if self._group_started:
|
||||
@@ -750,6 +809,8 @@ def create_eplb_communicator(
|
||||
return TorchDistGlooStagedEplbCommunicator(
|
||||
cpu_group=group_coordinator.cpu_group,
|
||||
)
|
||||
elif backend == "torch_xccl":
|
||||
return TorchDistXCCLStagedEplbCommunicator(ep_group=torch_group)
|
||||
elif backend == "torch_nccl":
|
||||
return TorchDistNcclEplbCommunicator(ep_group=torch_group)
|
||||
elif backend == "pynccl":
|
||||
|
||||
@@ -203,9 +203,9 @@ class EplbModelState:
|
||||
"""
|
||||
EPLB stats for the model.
|
||||
"""
|
||||
cuda_device_index: int | None
|
||||
device_index: int | None
|
||||
"""
|
||||
CUDA device index for the async EPLB worker thread.
|
||||
Device index for the async EPLB worker thread.
|
||||
"""
|
||||
communicator: EplbCommunicator
|
||||
"""
|
||||
@@ -286,14 +286,14 @@ class EplbState:
|
||||
"""
|
||||
Background thread handling async transfers.
|
||||
"""
|
||||
self.cuda_device_index: int | None = None
|
||||
self.device_index: int | None = None
|
||||
"""
|
||||
CUDA device index for the async EPLB worker thread.
|
||||
Device index for the async EPLB worker thread.
|
||||
"""
|
||||
if self.device.type == "cuda":
|
||||
self.cuda_device_index = self.device.index
|
||||
if self.cuda_device_index is None and torch.cuda.is_available():
|
||||
self.cuda_device_index = torch.accelerator.current_device_index()
|
||||
if self.device.type in ("cuda", "xpu"):
|
||||
self.device_index = self.device.index
|
||||
if self.device_index is None and torch.accelerator.is_available():
|
||||
self.device_index = torch.accelerator.current_device_index()
|
||||
|
||||
@staticmethod
|
||||
def build_initial_global_physical_to_logical_map(
|
||||
@@ -504,7 +504,7 @@ class EplbState:
|
||||
expert_buffer=expert_buffer,
|
||||
rebalanced=False,
|
||||
eplb_stats=None,
|
||||
cuda_device_index=self.cuda_device_index,
|
||||
device_index=self.device_index,
|
||||
communicator=communicator,
|
||||
num_unpadded_tokens_tensors=num_unpadded_tokens_tensors,
|
||||
)
|
||||
@@ -763,8 +763,8 @@ class EplbState:
|
||||
is_main_rank = ep_rank == 0
|
||||
if is_main_rank:
|
||||
if not self.is_async or is_profile:
|
||||
start_event = torch.cuda.Event(enable_timing=True)
|
||||
end_event = torch.cuda.Event(enable_timing=True)
|
||||
start_event = torch.Event(enable_timing=True)
|
||||
end_event = torch.Event(enable_timing=True)
|
||||
start_event.record()
|
||||
logger.info(
|
||||
"Rearranging experts %s %s...",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Utility functions for EPLB (Expert Parallel Load Balancing)."""
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import threading
|
||||
|
||||
@@ -13,6 +14,22 @@ from vllm.logger import init_logger
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def device_stream(stream: torch.Stream | None):
|
||||
"""Platform-agnostic context manager that activates *stream* as the
|
||||
current accelerator stream for the duration of the ``with`` block.
|
||||
A no-op when *stream* is ``None``."""
|
||||
if stream is None:
|
||||
yield
|
||||
return
|
||||
prev = torch.accelerator.current_stream()
|
||||
torch.accelerator.set_stream(stream)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
torch.accelerator.set_stream(prev)
|
||||
|
||||
|
||||
class CpuGpuEvent:
|
||||
"""Combines a CUDA event with a CPU threading event to enforce record->wait
|
||||
ordering across two threads.
|
||||
@@ -30,10 +47,10 @@ class CpuGpuEvent:
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._event = torch.cuda.Event()
|
||||
self._event = torch.Event()
|
||||
self._recorded = threading.Event()
|
||||
|
||||
def wait(self, stream: torch.cuda.Stream | None = None):
|
||||
def wait(self, stream: torch.Stream | None = None):
|
||||
"""Blocks the calling thread until record finishes. Used to guarantee that the
|
||||
record kernel is called before wait.
|
||||
|
||||
@@ -43,7 +60,7 @@ class CpuGpuEvent:
|
||||
self._event.wait(stream)
|
||||
self._recorded.clear()
|
||||
|
||||
def record(self, stream: torch.cuda.Stream | None = None):
|
||||
def record(self, stream: torch.Stream | None = None):
|
||||
"""Unblocks the waiting thread after calling event.record().
|
||||
|
||||
Should only be called by the main thread.
|
||||
@@ -53,7 +70,7 @@ class CpuGpuEvent:
|
||||
"CpuGpuEvent.record() called before the previous event was "
|
||||
"consumed by wait()"
|
||||
)
|
||||
self._event = torch.cuda.Event()
|
||||
self._event = torch.Event()
|
||||
self._event.record(stream)
|
||||
self._recorded.set()
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import torch
|
||||
from torch.distributed import ProcessGroup, all_gather
|
||||
|
||||
from vllm.distributed.eplb.eplb_communicator import EplbCommunicator
|
||||
from vllm.distributed.eplb.eplb_utils import CpuGpuEvent
|
||||
from vllm.distributed.eplb.eplb_utils import CpuGpuEvent, device_stream
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
|
||||
|
||||
@@ -173,7 +173,7 @@ def move_to_buffer(
|
||||
new_indices: np.ndarray,
|
||||
expert_weights: Sequence[torch.Tensor],
|
||||
expert_weights_buffers: Sequence[torch.Tensor],
|
||||
cuda_stream: torch.cuda.Stream | None,
|
||||
stream: torch.Stream | None,
|
||||
ep_rank: int,
|
||||
communicator: EplbCommunicator,
|
||||
layer_idx: int = 0,
|
||||
@@ -183,12 +183,12 @@ def move_to_buffer(
|
||||
Args:
|
||||
num_local_experts: Number of local experts.
|
||||
old_indices: (num_experts_total,) ndarray of current (old)
|
||||
global-to-local expert assignments.
|
||||
global-to-locals expert assignments.
|
||||
new_indices: (num_experts_total,) ndarray of desired (new)
|
||||
global-to-local assignments after rebalance.
|
||||
expert_weights: Original expert weights for the layer.
|
||||
expert_weights_buffers: Intermediate buffers (one per tensor).
|
||||
cuda_stream: CUDA stream for async copies (can be None for sync mode).
|
||||
stream: CUDA/XPU stream for async copies (can be None for sync mode).
|
||||
ep_rank: Rank of this process in expert parallel group.
|
||||
communicator: EplbCommunicator instance for P2P communication.
|
||||
layer_idx: Index of the MoE layer being transferred.
|
||||
@@ -261,10 +261,9 @@ def move_to_buffer(
|
||||
expert = new_local_expert_ids[dst]
|
||||
src_local = expert_to_src_map.get(expert, -1)
|
||||
if src_local != -1:
|
||||
with torch.cuda.stream(cuda_stream):
|
||||
with device_stream(stream):
|
||||
for w, b in zip(expert_weights, expert_weights_buffers):
|
||||
b[dst].copy_(w[src_local], non_blocking=True)
|
||||
|
||||
communicator.set_transfer_context(old_indices, layer_idx)
|
||||
|
||||
# 2. Post sends
|
||||
@@ -430,7 +429,7 @@ def transfer_layer(
|
||||
ep_group: ProcessGroup,
|
||||
communicator: EplbCommunicator,
|
||||
is_profile: bool = False,
|
||||
cuda_stream: torch.cuda.Stream | None = None,
|
||||
stream: torch.Stream | None = None,
|
||||
rank_mapping: dict[int, int] | None = None,
|
||||
layer_idx: int = 0,
|
||||
) -> TransferMetadata:
|
||||
@@ -451,7 +450,7 @@ def transfer_layer(
|
||||
is_profile (bool): If `True`, do not perform any actual weight copy.
|
||||
This is used during profile run, where we only perform dummy
|
||||
communications to reserve enough memory for the buffers.
|
||||
cuda_stream: CUDA stream for async copies (can be None for sync mode).
|
||||
stream: CUDA stream for async copies (can be None for sync mode).
|
||||
rank_mapping: Optional rank mapping for elastic expert parallelism.
|
||||
layer_idx: Index of the MoE layer being transferred.
|
||||
|
||||
@@ -499,7 +498,7 @@ def transfer_layer(
|
||||
new_indices=new_layer_indices_np,
|
||||
expert_weights=expert_weights,
|
||||
expert_weights_buffers=expert_weights_buffer,
|
||||
cuda_stream=cuda_stream,
|
||||
stream=stream,
|
||||
ep_rank=ep_group.rank(),
|
||||
communicator=communicator,
|
||||
layer_idx=layer_idx,
|
||||
@@ -601,7 +600,7 @@ def rearrange_expert_weights_inplace(
|
||||
new_indices=new_global_expert_indices_cpu[layer_idx],
|
||||
expert_weights=expert_weights[layer_idx],
|
||||
expert_weights_buffers=weights_buffer,
|
||||
cuda_stream=None,
|
||||
stream=None,
|
||||
ep_rank=ep_rank,
|
||||
communicator=communicator,
|
||||
layer_idx=layer_idx,
|
||||
|
||||
@@ -11,7 +11,6 @@ and MooncakeDistributedStore integration.
|
||||
"""
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import queue
|
||||
@@ -20,10 +19,8 @@ import threading
|
||||
import time
|
||||
from collections.abc import Callable, Sequence
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal, TypeVar
|
||||
from typing import Any, TypeVar
|
||||
|
||||
import regex as re
|
||||
import torch
|
||||
import zmq
|
||||
|
||||
@@ -67,6 +64,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.protocol import
|
||||
decode_lookup_response,
|
||||
encode_lookup_response,
|
||||
)
|
||||
from vllm.distributed.mooncake_store import MooncakeStoreConfig, setup_mooncake_store
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.network_utils import get_ip, make_zmq_socket
|
||||
@@ -94,10 +92,6 @@ from .metrics import MooncakeStoreConnectorStats
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
DEFAULT_GLOBAL_SEGMENT_SIZE = 4 * 1024 * 1024 * 1024 # 4 GiB
|
||||
DEFAULT_LOCAL_BUFFER_SIZE = 4 * 1024 * 1024 * 1024 # 4 GiB
|
||||
DEFAULT_TENANT_ID = "default"
|
||||
|
||||
MOONCAKE_NO_AVAILABLE_HANDLE = -200
|
||||
_T = TypeVar("_T")
|
||||
|
||||
@@ -149,115 +143,6 @@ _DIRECT_IO_ALIGNMENT = 4096
|
||||
_DIRECT_IO_PADDING_BYTES = 2 * _DIRECT_IO_ALIGNMENT
|
||||
|
||||
|
||||
MooncakeMode = Literal["embedded", "standalone-store"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class MooncakeStoreConfig:
|
||||
"""Configuration for MooncakeDistributedStore.
|
||||
|
||||
``mode`` selects the topology: ``embedded`` (each rank contributes
|
||||
``global_segment_size`` in-process) or ``standalone-store`` (rank
|
||||
contributes 0; an external ``mooncake_client`` process owns the pool
|
||||
and the SSD tier).
|
||||
"""
|
||||
|
||||
metadata_server: str
|
||||
master_server_address: str
|
||||
protocol: str
|
||||
device_name: str
|
||||
mode: MooncakeMode = "embedded"
|
||||
global_segment_size: int = DEFAULT_GLOBAL_SEGMENT_SIZE
|
||||
local_buffer_size: int = DEFAULT_LOCAL_BUFFER_SIZE
|
||||
enable_offload: bool = False
|
||||
tenant_id: str = DEFAULT_TENANT_ID
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.mode not in ("embedded", "standalone-store"):
|
||||
raise ValueError(f"unknown Mooncake mode: {self.mode!r}")
|
||||
if self.local_buffer_size <= 0:
|
||||
raise ValueError("local_buffer_size must be > 0")
|
||||
if self.mode == "embedded" and self.global_segment_size == 0:
|
||||
raise ValueError("embedded mode requires global_segment_size > 0")
|
||||
if self.mode == "standalone-store" and self.global_segment_size != 0:
|
||||
raise ValueError("standalone-store mode requires global_segment_size == 0")
|
||||
|
||||
@staticmethod
|
||||
def from_file(file_path: str) -> "MooncakeStoreConfig":
|
||||
with open(file_path) as file:
|
||||
config = json.load(file)
|
||||
return MooncakeStoreConfig(
|
||||
metadata_server=config.get("metadata_server", ""),
|
||||
master_server_address=config.get("master_server_address", ""),
|
||||
protocol=config.get("protocol", "rdma"),
|
||||
device_name=config.get("device_name", ""),
|
||||
mode=config.get("mode", "embedded"),
|
||||
global_segment_size=_parse_size(
|
||||
config.get("global_segment_size", DEFAULT_GLOBAL_SEGMENT_SIZE)
|
||||
),
|
||||
local_buffer_size=_parse_size(
|
||||
config.get("local_buffer_size", DEFAULT_LOCAL_BUFFER_SIZE)
|
||||
),
|
||||
enable_offload=bool(config.get("enable_offload", False)),
|
||||
tenant_id=_normalize_tenant_id(config.get("tenant_id", DEFAULT_TENANT_ID)),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def load_from_config() -> "MooncakeStoreConfig":
|
||||
config_path = os.getenv("MOONCAKE_CONFIG_PATH")
|
||||
if not config_path:
|
||||
raise ValueError(
|
||||
"The environment variable 'MOONCAKE_CONFIG_PATH' is not set."
|
||||
)
|
||||
return MooncakeStoreConfig.from_file(config_path)
|
||||
|
||||
|
||||
def _normalize_tenant_id(value: Any) -> str:
|
||||
if value is None:
|
||||
return DEFAULT_TENANT_ID
|
||||
if not isinstance(value, str):
|
||||
raise TypeError(
|
||||
f"tenant_id must be a string or null, got {type(value).__name__}: {value!r}"
|
||||
)
|
||||
tenant_id = value.strip()
|
||||
return tenant_id if tenant_id else DEFAULT_TENANT_ID
|
||||
|
||||
|
||||
def _parse_size(value: Any) -> int:
|
||||
"""Parse storage size strings with units: GB, MB, KB, B."""
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as e:
|
||||
raise TypeError(f"Unsupported type for size: {type(value)}") from e
|
||||
|
||||
cleaned = value.strip().lower()
|
||||
if not cleaned:
|
||||
raise ValueError("Size cannot be empty.")
|
||||
|
||||
unit_multipliers = {
|
||||
"gb": 1024**3,
|
||||
"mb": 1024**2,
|
||||
"kb": 1024,
|
||||
"b": 1,
|
||||
}
|
||||
match = re.match(r"^\s*([\d.]+)\s*(gb|mb|kb|b)?\s*$", cleaned)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid format: '{value}'")
|
||||
|
||||
number_str = match.group(1)
|
||||
unit = match.group(2) or "b"
|
||||
multiplier = unit_multipliers[unit]
|
||||
|
||||
try:
|
||||
numeric_value = float(number_str)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Invalid numeric value '{number_str}' in: '{value}'") from exc
|
||||
return int(numeric_value * multiplier)
|
||||
|
||||
|
||||
def _align_up(value: int, alignment: int) -> int:
|
||||
return ((value + alignment - 1) // alignment) * alignment
|
||||
|
||||
@@ -1595,23 +1480,7 @@ class MooncakeStoreWorker:
|
||||
self.store = MooncakeDistributedStore()
|
||||
local_ip = get_ip()
|
||||
local_hostname = rdma_utils.get_requester_local_hostname(local_ip)
|
||||
setup_kwargs: dict[str, str] = {}
|
||||
if store_config.tenant_id != DEFAULT_TENANT_ID:
|
||||
setup_kwargs["tenant_id"] = store_config.tenant_id
|
||||
ret = self.store.setup(
|
||||
local_hostname,
|
||||
store_config.metadata_server,
|
||||
store_config.global_segment_size,
|
||||
store_config.local_buffer_size,
|
||||
store_config.protocol,
|
||||
store_config.device_name,
|
||||
store_config.master_server_address,
|
||||
**setup_kwargs,
|
||||
)
|
||||
if ret != 0:
|
||||
msg = "Initialize MooncakeDistributedStore failed."
|
||||
logger.error(msg)
|
||||
raise RuntimeError(msg)
|
||||
setup_mooncake_store(self.store, store_config, local_hostname)
|
||||
|
||||
preferred_segment = rdma_utils.get_configured_preferred_segment(extra_config)
|
||||
self.preferred_segment = preferred_segment
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Shared configuration and setup for EC and KV Mooncake Store clients."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
import regex as re
|
||||
|
||||
DEFAULT_GLOBAL_SEGMENT_SIZE = 4 * 1024 * 1024 * 1024 # 4 GiB
|
||||
DEFAULT_LOCAL_BUFFER_SIZE = 4 * 1024 * 1024 * 1024 # 4 GiB
|
||||
DEFAULT_TENANT_ID = "default"
|
||||
|
||||
|
||||
MooncakeMode = Literal["embedded", "standalone-store"]
|
||||
|
||||
|
||||
@dataclass
|
||||
class MooncakeStoreConfig:
|
||||
"""Configuration for MooncakeDistributedStore.
|
||||
|
||||
``mode`` selects the topology: ``embedded`` (each rank contributes
|
||||
``global_segment_size`` in-process) or ``standalone-store`` (rank
|
||||
contributes 0; an external ``mooncake_client`` process owns the pool
|
||||
and the SSD tier).
|
||||
"""
|
||||
|
||||
metadata_server: str
|
||||
master_server_address: str
|
||||
protocol: str
|
||||
device_name: str
|
||||
mode: MooncakeMode = "embedded"
|
||||
global_segment_size: int = DEFAULT_GLOBAL_SEGMENT_SIZE
|
||||
local_buffer_size: int = DEFAULT_LOCAL_BUFFER_SIZE
|
||||
enable_offload: bool = False
|
||||
tenant_id: str = DEFAULT_TENANT_ID
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if self.mode not in ("embedded", "standalone-store"):
|
||||
raise ValueError(f"unknown Mooncake mode: {self.mode!r}")
|
||||
if self.local_buffer_size <= 0:
|
||||
raise ValueError("local_buffer_size must be > 0")
|
||||
if self.mode == "embedded" and self.global_segment_size == 0:
|
||||
raise ValueError("embedded mode requires global_segment_size > 0")
|
||||
if self.mode == "standalone-store" and self.global_segment_size != 0:
|
||||
raise ValueError("standalone-store mode requires global_segment_size == 0")
|
||||
|
||||
@staticmethod
|
||||
def from_file(file_path: str) -> "MooncakeStoreConfig":
|
||||
with open(file_path) as file:
|
||||
config = json.load(file)
|
||||
return MooncakeStoreConfig(
|
||||
metadata_server=config.get("metadata_server", ""),
|
||||
master_server_address=config.get("master_server_address", ""),
|
||||
protocol=config.get("protocol", "rdma"),
|
||||
device_name=config.get("device_name", ""),
|
||||
mode=config.get("mode", "embedded"),
|
||||
global_segment_size=_parse_size(
|
||||
config.get("global_segment_size", DEFAULT_GLOBAL_SEGMENT_SIZE)
|
||||
),
|
||||
local_buffer_size=_parse_size(
|
||||
config.get("local_buffer_size", DEFAULT_LOCAL_BUFFER_SIZE)
|
||||
),
|
||||
enable_offload=bool(config.get("enable_offload", False)),
|
||||
tenant_id=_normalize_tenant_id(config.get("tenant_id", DEFAULT_TENANT_ID)),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def load_from_config() -> "MooncakeStoreConfig":
|
||||
config_path = os.getenv("MOONCAKE_CONFIG_PATH")
|
||||
if not config_path:
|
||||
raise ValueError(
|
||||
"The environment variable 'MOONCAKE_CONFIG_PATH' is not set."
|
||||
)
|
||||
return MooncakeStoreConfig.from_file(config_path)
|
||||
|
||||
|
||||
def _normalize_tenant_id(value: Any) -> str:
|
||||
if value is None:
|
||||
return DEFAULT_TENANT_ID
|
||||
if not isinstance(value, str):
|
||||
raise TypeError(
|
||||
f"tenant_id must be a string or null, got {type(value).__name__}: {value!r}"
|
||||
)
|
||||
tenant_id = value.strip()
|
||||
return tenant_id if tenant_id else DEFAULT_TENANT_ID
|
||||
|
||||
|
||||
def _parse_size(value: Any) -> int:
|
||||
"""Parse storage size strings with units: GB, MB, KB, B."""
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if not isinstance(value, str):
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError) as e:
|
||||
raise TypeError(f"Unsupported type for size: {type(value)}") from e
|
||||
|
||||
cleaned = value.strip().lower()
|
||||
if not cleaned:
|
||||
raise ValueError("Size cannot be empty.")
|
||||
|
||||
unit_multipliers = {
|
||||
"gb": 1024**3,
|
||||
"mb": 1024**2,
|
||||
"kb": 1024,
|
||||
"b": 1,
|
||||
}
|
||||
match = re.match(r"^\s*([\d.]+)\s*(gb|mb|kb|b)?\s*$", cleaned)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid format: '{value}'")
|
||||
|
||||
number_str = match.group(1)
|
||||
unit = match.group(2) or "b"
|
||||
multiplier = unit_multipliers[unit]
|
||||
|
||||
try:
|
||||
numeric_value = float(number_str)
|
||||
except ValueError as exc:
|
||||
raise ValueError(f"Invalid numeric value '{number_str}' in: '{value}'") from exc
|
||||
return int(numeric_value * multiplier)
|
||||
|
||||
|
||||
def setup_mooncake_store(
|
||||
store: Any, config: MooncakeStoreConfig, local_hostname: str
|
||||
) -> None:
|
||||
"""Initialize a native Store, preserving explicit tenant configuration."""
|
||||
setup_kwargs: dict[str, str] = {}
|
||||
if config.tenant_id != DEFAULT_TENANT_ID:
|
||||
setup_kwargs["tenant_id"] = config.tenant_id
|
||||
ret = store.setup(
|
||||
local_hostname,
|
||||
config.metadata_server,
|
||||
config.global_segment_size,
|
||||
config.local_buffer_size,
|
||||
config.protocol,
|
||||
config.device_name,
|
||||
config.master_server_address,
|
||||
**setup_kwargs,
|
||||
)
|
||||
if ret != 0:
|
||||
raise RuntimeError("Initialize MooncakeDistributedStore failed.")
|
||||
@@ -1632,10 +1632,7 @@ def get_pcp_group() -> GroupCoordinator:
|
||||
|
||||
|
||||
@contextmanager
|
||||
def graph_capture(
|
||||
device: torch.device,
|
||||
graph_capture_context: GraphCaptureContext | None = None,
|
||||
):
|
||||
def graph_capture(device: torch.device):
|
||||
"""`graph_capture` is a context manager which should surround the code that
|
||||
is capturing the CUDA graph. Its main purpose is to ensure that some
|
||||
operations will be run after the graph is captured, before the graph
|
||||
@@ -1647,13 +1644,8 @@ def graph_capture(
|
||||
the graph capture is running on a separate stream from the default stream,
|
||||
in order to explicitly distinguish the kernels to capture
|
||||
from other kernels possibly launched on background in the default stream.
|
||||
|
||||
A caller may pass an explicit ``graph_capture_context`` to control the
|
||||
stream used (e.g. to capture on the default stream).
|
||||
"""
|
||||
context = graph_capture_context or GraphCaptureContext(
|
||||
torch.cuda.Stream(device=device)
|
||||
)
|
||||
context = GraphCaptureContext(torch.cuda.Stream(device=device))
|
||||
with (
|
||||
get_tp_group().graph_capture(context),
|
||||
get_pp_group().graph_capture(context),
|
||||
|
||||
@@ -486,13 +486,9 @@ class ServingTokens(GenerateBaseServing):
|
||||
total_tokens=(num_prompt_tokens + num_generated_tokens[i]),
|
||||
)
|
||||
|
||||
# Omit absent prompt metadata (Rust skips None fields).
|
||||
exclude = {
|
||||
name
|
||||
for name in ("prompt_token_ids", "mm_placeholders")
|
||||
if getattr(chunk, name) is None
|
||||
}
|
||||
yield f"data: {chunk.model_dump_json(exclude=exclude)}\n\n"
|
||||
# Omit absent fields, like the Rust frontend and the
|
||||
# final usage chunk below.
|
||||
yield f"data: {chunk.model_dump_json(exclude_none=True)}\n\n"
|
||||
|
||||
total_completion_tokens = sum(num_generated_tokens)
|
||||
final_usage_info = UsageInfo(
|
||||
|
||||
@@ -171,6 +171,7 @@ class XPUExperts(mk.FusedMoEExpertsModular):
|
||||
num_experts=self.moe_config.num_local_experts,
|
||||
ep_rank=self.moe_config.ep_rank,
|
||||
ep_size=self.moe_config.ep_size,
|
||||
expert_map=expert_map,
|
||||
gemm1_clamp_limit=self.gemm1_clamp_limit,
|
||||
)
|
||||
assert self.fused_moe_impl is not None
|
||||
|
||||
@@ -13,7 +13,7 @@ from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.worker.ubatching import dbo_current_ubatch_id
|
||||
|
||||
if current_platform.is_cuda_alike():
|
||||
if current_platform.is_cuda_alike() or current_platform.is_xpu():
|
||||
|
||||
@triton.jit
|
||||
def _eplb_map_and_record_i32_kernel(
|
||||
|
||||
@@ -85,6 +85,7 @@ class SharedExperts(torch.nn.Module):
|
||||
# Both these comm backends have been shown to be safe for shared expert overlap.
|
||||
_EPLB_OVERLAP_SAFE_BACKENDS = (
|
||||
"allgather_reducescatter",
|
||||
"deepep_v2",
|
||||
"flashinfer_nvlink_one_sided",
|
||||
)
|
||||
|
||||
|
||||
@@ -865,25 +865,8 @@ class RocmPlatform(Platform):
|
||||
@classmethod
|
||||
def apply_config_platform_defaults(cls, vllm_config: "VllmConfig") -> None:
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
|
||||
compilation_config = vllm_config.compilation_config
|
||||
model_config = vllm_config.model_config
|
||||
if (
|
||||
compilation_config.cudagraph_mode is None
|
||||
and model_config is not None
|
||||
and on_gfx950()
|
||||
and vllm_config.use_v2_model_runner
|
||||
and model_config.architecture
|
||||
in {
|
||||
"DeepseekV4ForCausalLM",
|
||||
"DeepseekV4ForConditionalGeneration",
|
||||
}
|
||||
):
|
||||
# Default to eager after reported gfx950/MRV2 accuracy regressions:
|
||||
# https://github.com/vllm-project/vllm/issues/52644
|
||||
compilation_config.cudagraph_mode = CUDAGraphMode.NONE
|
||||
|
||||
use_aiter_fused_moe = rocm_aiter_ops.is_fused_moe_enabled()
|
||||
use_aiter_fp8_linear = rocm_aiter_ops.is_linear_fp8_enabled()
|
||||
use_aiter_fused_se = rocm_aiter_ops.is_fusion_moe_shared_experts_enabled()
|
||||
|
||||
@@ -46,7 +46,6 @@ from vllm.distributed.kv_transfer.kv_connector.utils import (
|
||||
copy_kv_blocks,
|
||||
)
|
||||
from vllm.distributed.parallel_state import (
|
||||
GraphCaptureContext,
|
||||
get_dcp_group,
|
||||
get_pp_group,
|
||||
get_tp_group,
|
||||
@@ -128,7 +127,6 @@ from vllm.utils.platform_utils import num_compute_units
|
||||
from vllm.utils.torch_utils import (
|
||||
PIN_MEMORY,
|
||||
async_tensor_h2d,
|
||||
current_stream,
|
||||
kv_cache_dtype_str_to_dtype,
|
||||
)
|
||||
from vllm.v1.attention.backend import (
|
||||
@@ -6712,31 +6710,11 @@ class GPUModelRunner(
|
||||
per_graph_estimate = {}
|
||||
encoder_memory_estimate = 0
|
||||
|
||||
# On ROCm, capture these throwaway profiling graphs on vLLM's dedicated
|
||||
# compute stream instead of the fresh side stream graph_capture()
|
||||
# allocates by default. torch's allocator pools free blocks per stream,
|
||||
# so a side-stream forward strands a persistent aiter scratch buffer in
|
||||
# a separate pool, shifting the physical placement of the real KV cache
|
||||
# allocated afterward and slowing bandwidth-bound decode ~20%. The
|
||||
# graphs are discarded, so a side stream is unnecessary here.
|
||||
# Use current_stream(), not torch.cuda.current_stream(): before vLLM
|
||||
# initializes its dedicated stream, torch returns the per-thread default
|
||||
# stream (cuda_stream=0), which cannot be used for cudagraph capture.
|
||||
# cap_ctx=None keeps the side-stream path on CUDA.
|
||||
cap_ctx = (
|
||||
GraphCaptureContext(current_stream())
|
||||
if current_platform.is_rocm()
|
||||
else None
|
||||
)
|
||||
|
||||
# Cleanup-only guard: CUDA graph capture errors should still propagate
|
||||
# because encoder graph capture is opt-in.
|
||||
try:
|
||||
set_cudagraph_capturing_enabled(True)
|
||||
with (
|
||||
self._freeze_gc(),
|
||||
graph_capture(device=self.device, graph_capture_context=cap_ctx),
|
||||
):
|
||||
with self._freeze_gc(), graph_capture(device=self.device):
|
||||
torch.accelerator.synchronize()
|
||||
torch.accelerator.empty_cache()
|
||||
|
||||
|
||||
@@ -98,6 +98,7 @@ from vllm.v1.worker.worker_base import CompilationTimes, WorkerBase
|
||||
from vllm.v1.worker.workspace import init_workspace_manager
|
||||
|
||||
from ...model_executor.model_loader import TensorizerLoader
|
||||
from .gpu.cudagraph_utils import has_compiled_submodule
|
||||
from .gpu.warmup import warmup_kernels
|
||||
from .utils import request_memory
|
||||
|
||||
@@ -772,7 +773,10 @@ class Worker(WorkerBase):
|
||||
def compile_or_warm_up_model(self) -> CompilationTimes:
|
||||
warmup_sizes: list[int] = []
|
||||
|
||||
if self.vllm_config.compilation_config.mode == CompilationMode.VLLM_COMPILE:
|
||||
if (
|
||||
self.vllm_config.compilation_config.mode == CompilationMode.VLLM_COMPILE
|
||||
and has_compiled_submodule(self.model_runner.get_model())
|
||||
):
|
||||
# warm up sizes that are not in cudagraph capture sizes,
|
||||
# but users still want to compile for better performance,
|
||||
# e.g. for the max-num-batched token size in chunked prefill.
|
||||
|
||||
Reference in New Issue
Block a user