repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/parallel_state.py
vllm/distributed/parallel_state.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright 2023 The vLLM team. # Adapted from # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/parallel_state.py # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. """vLLM distributed state. It takes over the control of the distributed environment from PyTorch. The typical workflow is: - call `init_distributed_environment` to initialize the distributed environment. - call `initialize_model_parallel` or `ensure_model_parallel_initialized` to initialize the model parallel groups. - any code dealing with the distributed stuff - call `destroy_model_parallel` to destroy the model parallel groups. - call `destroy_distributed_environment` to destroy the distributed environment. If you only need to use the distributed environment without model/pipeline parallelism, you can skip the model parallel initialization and destruction steps. """ import contextlib import gc import pickle import weakref from collections import namedtuple from collections.abc import Callable from contextlib import contextmanager, nullcontext from dataclasses import dataclass from datetime import timedelta from multiprocessing import shared_memory from typing import Any, Optional from unittest.mock import patch import torch import torch.distributed import torch.distributed._functional_collectives as funcol import torch.distributed._symmetric_memory from torch.distributed import Backend, ProcessGroup import vllm.envs as envs from vllm.distributed.device_communicators.base_device_communicator import ( DeviceCommunicatorBase, ) from vllm.distributed.utils import StatelessProcessGroup from vllm.logger import init_logger from vllm.utils.import_utils import resolve_obj_by_qualname from vllm.utils.network_utils import get_distributed_init_method from vllm.utils.system_utils import suppress_stdout from vllm.utils.torch_utils import ( direct_register_custom_op, supports_custom_op, ) @dataclass class GraphCaptureContext: stream: torch.cuda.Stream TensorMetadata = namedtuple("TensorMetadata", ["device", "dtype", "size"]) def _split_tensor_dict( tensor_dict: dict[str, torch.Tensor | Any], ) -> tuple[list[tuple[str, Any]], list[torch.Tensor]]: """Split the tensor dictionary into two parts: 1. A list of (key, value) pairs. If the value is a tensor, it is replaced by its metadata. 2. A list of tensors. """ metadata_list: list[tuple[str, Any]] = [] tensor_list: list[torch.Tensor] = [] for key, value in tensor_dict.items(): if isinstance(value, torch.Tensor): # Note: we cannot use `value.device` here, # because it contains not only the device type but also the device # index (e.g. "cuda:0"). We only need the device type. # receiving side will set the device index. device = value.device.type metadata_list.append( (key, TensorMetadata(device, value.dtype, value.size())) ) tensor_list.append(value) else: metadata_list.append((key, value)) return metadata_list, tensor_list _group_name_counter: dict[str, int] = {} def _get_unique_name(name: str) -> str: """Get a unique name for the group. Example: _get_unique_name("tp") -> "tp:0" _get_unique_name("tp") -> "tp:1" """ if name not in _group_name_counter: _group_name_counter[name] = 0 newname = f"{name}:{_group_name_counter[name]}" _group_name_counter[name] += 1 return newname _groups: dict[str, Callable[[], Optional["GroupCoordinator"]]] = {} def _register_group(group: "GroupCoordinator") -> None: _groups[group.unique_name] = weakref.ref(group) def all_reduce(tensor: torch.Tensor, group_name: str) -> torch.Tensor: assert group_name in _groups, f"Group {group_name} is not found." group = _groups[group_name]() if group is None: raise ValueError(f"Group {group_name} is destroyed.") return group._all_reduce_out_place(tensor) def all_reduce_fake(tensor: torch.Tensor, group_name: str) -> torch.Tensor: return torch.empty_like(tensor) def reduce_scatter( tensor: torch.Tensor, dim: int, world_size: int, group_name: str ) -> torch.Tensor: assert group_name in _groups, f"Group {group_name} is not found." group = _groups[group_name]() if group is None: raise ValueError(f"Group {group_name} is destroyed.") return group._reduce_scatter_out_place(tensor, dim) def reduce_scatter_fake( tensor: torch.Tensor, dim: int, world_size: int, group_name: str ) -> torch.Tensor: new_shape = list(tensor.shape) new_shape[dim] = tensor.shape[dim] // world_size return torch.empty(new_shape, dtype=tensor.dtype, device=tensor.device) def all_gather( tensor: torch.Tensor, dim: int, world_size: int, group_name: str ) -> torch.Tensor: assert group_name in _groups, f"Group {group_name} is not found." group = _groups[group_name]() if group is None: raise ValueError(f"Group {group_name} is destroyed.") return group._all_gather_out_place(tensor, dim) def all_gather_fake( tensor: torch.Tensor, dim: int, world_size: int, group_name: str ) -> torch.Tensor: new_shape = list(tensor.shape) new_shape[dim] = tensor.shape[dim] * world_size return torch.empty(new_shape, dtype=tensor.dtype, device=tensor.device) def patched_fused_scaled_matmul_reduce_scatter_fake( A: torch.Tensor, B: torch.Tensor, A_scale: torch.Tensor, B_scale: torch.Tensor, reduce_op: str, orig_scatter_dim: int, scatter_dim_after_maybe_reshape: int, group_name: str, output_shape: list[int], bias: torch.Tensor | None = None, result_scale: torch.Tensor | None = None, out_dtype: torch.dtype | None = None, use_fast_accum: bool = False, ) -> torch.Tensor: # Copied from # https://github.com/pytorch/pytorch/blob/50c338c2da905062449e4d9ac807832d1b5cd90e/torch/distributed/_symmetric_memory/__init__.py#L1189 if A_scale.numel() > 1: if A_scale.shape[:-1] != A.shape[:-1]: raise ValueError( "For row-wise scaling, the leading dims of A_scale " "must match the leading dims of A " f"(A shape: {A.shape}, A_scale shape: {A_scale.shape})" ) A_scale = A_scale.flatten(0, -2).contiguous() elif A_scale.numel() != 1: raise ValueError( "Invalid A_scale shape " f"(A shape: {A.shape}, A_scale shape: {A_scale.shape})" ) C = torch._scaled_mm( A.flatten(0, -2).contiguous(), B, A_scale, B_scale, bias, result_scale, out_dtype, use_fast_accum, ) C = C.view(*output_shape[:-1], B.shape[1]) res = funcol.reduce_scatter_tensor( C, reduce_op, orig_scatter_dim, # need original scatter dim for 3D+ output tensor here group_name, ) res = funcol.wait_tensor(res) return res def patched_fused_scaled_matmul_reduce_scatter( A: torch.Tensor, B: torch.Tensor, A_scale: torch.Tensor, B_scale: torch.Tensor, reduce_op: str, orig_scatter_dim: int, scatter_dim_after_maybe_reshape: int, group_name: str, output_shape: list[int], bias: torch.Tensor | None = None, result_scale: torch.Tensor | None = None, out_dtype: torch.dtype | None = None, use_fast_accum: bool = False, ) -> torch.Tensor: return torch.ops.symm_mem.fused_scaled_matmul_reduce_scatter( A, B, A_scale, B_scale, reduce_op, orig_scatter_dim, scatter_dim_after_maybe_reshape, group_name, output_shape, bias, result_scale, out_dtype, use_fast_accum, ) if supports_custom_op(): direct_register_custom_op( op_name="all_reduce", op_func=all_reduce, fake_impl=all_reduce_fake, ) direct_register_custom_op( op_name="reduce_scatter", op_func=reduce_scatter, fake_impl=reduce_scatter_fake, ) direct_register_custom_op( op_name="all_gather", op_func=all_gather, fake_impl=all_gather_fake, ) # TODO: Remove this once the pytorch fix # (https://github.com/pytorch/pytorch/pull/165086) gets released, # in either 2.9.1 or 2.10 direct_register_custom_op( op_name="patched_fused_scaled_matmul_reduce_scatter", op_func=patched_fused_scaled_matmul_reduce_scatter, fake_impl=patched_fused_scaled_matmul_reduce_scatter_fake, ) class GroupCoordinator: """ PyTorch ProcessGroup wrapper for a group of processes. PyTorch ProcessGroup is bound to one specific communication backend, e.g. NCCL, Gloo, MPI, etc. GroupCoordinator takes charge of all the communication operations among the processes in the group. It manages both CPU and device communication. """ # available attributes: rank: int # global rank ranks: list[int] # global ranks in the group world_size: int # size of the group # difference between `local_rank` and `rank_in_group`: # if we have a group of size 4 across two nodes: # Process | Node | Rank | Local Rank | Rank in Group # 0 | 0 | 0 | 0 | 0 # 1 | 0 | 1 | 1 | 1 # 2 | 1 | 2 | 0 | 2 # 3 | 1 | 3 | 1 | 3 local_rank: int # local rank used to assign devices rank_in_group: int # rank inside the group cpu_group: ProcessGroup # group for CPU communication device_group: ProcessGroup # group for device communication # device communicator (if use_device_communicator=True) device_communicator: DeviceCommunicatorBase | None mq_broadcaster: Any | None # shared memory broadcaster def __init__( self, group_ranks: list[list[int]], local_rank: int, torch_distributed_backend: str | Backend, use_device_communicator: bool, # whether to use device communicator use_message_queue_broadcaster: bool = False, group_name: str | None = None, ): group_name = group_name or "anonymous" self.unique_name = _get_unique_name(group_name) _register_group(self) self.rank = torch.distributed.get_rank() self.local_rank = local_rank self_device_group = None self_cpu_group = None for ranks in group_ranks: device_group = torch.distributed.new_group( ranks, backend=torch_distributed_backend ) # a group with `gloo` backend, to allow direct coordination between # processes through the CPU. with suppress_stdout(): cpu_group = torch.distributed.new_group(ranks, backend="gloo") if self.rank in ranks: self.ranks = ranks self.world_size = len(ranks) self.rank_in_group = ranks.index(self.rank) self_device_group = device_group self_cpu_group = cpu_group assert self_cpu_group is not None assert self_device_group is not None self.cpu_group = self_cpu_group self.device_group = self_device_group from vllm.platforms import current_platform if current_platform.is_cuda_alike(): self.device = torch.device(f"cuda:{local_rank}") elif current_platform.is_xpu(): self.device = torch.device(f"xpu:{local_rank}") elif current_platform.is_out_of_tree(): self.device = torch.device(f"{current_platform.device_name}:{local_rank}") else: self.device = torch.device("cpu") self.use_device_communicator = use_device_communicator self.device_communicator = None if use_device_communicator and self.world_size > 1: device_comm_cls = resolve_obj_by_qualname( current_platform.get_device_communicator_cls() ) self.device_communicator = device_comm_cls( cpu_group=self.cpu_group, device=self.device, device_group=self.device_group, unique_name=self.unique_name, ) from vllm.distributed.device_communicators.shm_broadcast import MessageQueue self.mq_broadcaster: MessageQueue | None = None if use_message_queue_broadcaster and self.world_size > 1: self.mq_broadcaster = MessageQueue.create_from_process_group( self.cpu_group, 1 << 22, 6 ) from vllm.platforms import current_platform self.use_custom_op_call = ( current_platform.is_cuda_alike() or current_platform.is_tpu() ) self.use_cpu_custom_send_recv = current_platform.is_cpu() and hasattr( torch.ops._C, "init_shm_manager" ) def create_mq_broadcaster( self, writer_rank=0, external_writer_handle=None, blocking=True ): from vllm.distributed.device_communicators.shm_broadcast import MessageQueue return MessageQueue.create_from_process_group( self.cpu_group, 1 << 22, 6, writer_rank=writer_rank, external_writer_handle=external_writer_handle, blocking=blocking, ) def create_single_reader_mq_broadcasters( self, reader_rank_in_group=0, blocking=False ): from vllm.distributed.device_communicators.shm_broadcast import MessageQueue return MessageQueue.create_from_process_group_single_reader( self.cpu_group, 1 << 22, 6, reader_rank=self.ranks[reader_rank_in_group], blocking=blocking, ) @property def first_rank(self): """Return the global rank of the first process in the group""" return self.ranks[0] @property def last_rank(self): """Return the global rank of the last process in the group""" return self.ranks[-1] @property def is_first_rank(self): """Return whether the caller is the first process in the group""" return self.rank == self.first_rank @property def is_last_rank(self): """Return whether the caller is the last process in the group""" return self.rank == self.last_rank @property def next_rank(self): """Return the global rank of the process that follows the caller""" rank_in_group = self.rank_in_group world_size = self.world_size return self.ranks[(rank_in_group + 1) % world_size] @property def prev_rank(self): """Return the global rank of the process that precedes the caller""" rank_in_group = self.rank_in_group world_size = self.world_size return self.ranks[(rank_in_group - 1) % world_size] @contextmanager def graph_capture(self, graph_capture_context: GraphCaptureContext | None = None): if graph_capture_context is None: stream = torch.cuda.Stream() graph_capture_context = GraphCaptureContext(stream) else: stream = graph_capture_context.stream # only cuda uses this function, # so we don't abstract it into the base class maybe_ca_context = nullcontext() from vllm.distributed.device_communicators.cuda_communicator import ( CudaCommunicator, ) if self.device_communicator is not None: assert isinstance(self.device_communicator, CudaCommunicator) ca_comm = self.device_communicator.ca_comm if ca_comm is not None: maybe_ca_context = ca_comm.capture() # type: ignore # ensure all initialization operations complete before attempting to # capture the graph on another stream curr_stream = torch.cuda.current_stream() if curr_stream != stream: stream.wait_stream(curr_stream) with torch.cuda.stream(stream), maybe_ca_context: yield graph_capture_context def all_reduce(self, input_: torch.Tensor) -> torch.Tensor: """ User-facing all-reduce function before we actually call the all-reduce operation. We need this because Dynamo does not support passing an arbitrary object (`self` in this case) to a custom op. We need to pass the group name as a string, and then look up the group coordinator from the group name, dispatch the all-reduce operation to the group coordinator. In addition, PyTorch custom ops do not support mutation or returning a new tensor in the same op. So we always make the all-reduce operation out-of-place. """ # Bypass the function if we are using only 1 GPU. if self.world_size == 1: return input_ if self.use_custom_op_call: return torch.ops.vllm.all_reduce(input_, group_name=self.unique_name) else: return self._all_reduce_out_place(input_) def _all_reduce_out_place(self, input_: torch.Tensor) -> torch.Tensor: if self.device_communicator is None: raise ValueError("No device communicator found") return self.device_communicator.all_reduce(input_) def all_gather(self, input_: torch.Tensor, dim: int = -1) -> torch.Tensor: world_size = self.world_size # Bypass the function if we are using only 1 GPU. if world_size == 1: return input_ assert -input_.dim() <= dim < input_.dim(), ( f"Invalid dim ({dim}) for input tensor with shape {input_.size()}" ) if self.use_custom_op_call: return torch.ops.vllm.all_gather( input_, dim, world_size, group_name=self.unique_name ) else: return self._all_gather_out_place(input_, dim) def _all_gather_out_place(self, input_: torch.Tensor, dim: int) -> torch.Tensor: if self.device_communicator is None: raise ValueError("No device communicator found") return self.device_communicator.all_gather(input_, dim) def all_gatherv( self, input_: torch.Tensor | list[torch.Tensor], dim: int = 0, sizes: list[int] | None = None, ): if self.device_communicator is None: raise ValueError("No device communicator found") return self.device_communicator.all_gatherv(input_, dim, sizes) def reduce_scatter(self, input_: torch.Tensor, dim: int = -1) -> torch.Tensor: world_size = self.world_size # Bypass the function if we are using only 1 GPU. if world_size == 1: return input_ assert -input_.dim() <= dim < input_.dim(), ( f"Invalid dim ({dim}) for input tensor with shape {input_.size()}" ) if self.use_custom_op_call: return torch.ops.vllm.reduce_scatter( input_, dim, world_size, group_name=self.unique_name ) else: return self._reduce_scatter_out_place(input_, dim) def reduce_scatterv( self, input_: torch.Tensor, dim: int = -1, sizes: list[int] | None = None ) -> torch.Tensor: if self.device_communicator is None: raise ValueError("No device communicator found") return self.device_communicator.reduce_scatterv(input_, dim, sizes) def _reduce_scatter_out_place(self, input_: torch.Tensor, dim: int) -> torch.Tensor: if self.device_communicator is None: raise ValueError("No device communicator found") return self.device_communicator.reduce_scatter(input_, dim) def gather( self, input_: torch.Tensor, dst: int = 0, dim: int = -1 ) -> torch.Tensor | None: """ NOTE: We assume that the input tensor is on the same device across all the ranks. NOTE: `dst` is the local rank of the destination rank. """ world_size = self.world_size # Bypass the function if we are using only 1 GPU. if world_size == 1: return input_ if self.device_communicator is None: raise ValueError("No device communicator found") return self.device_communicator.gather(input_, dst, dim) def broadcast(self, input_: torch.Tensor, src: int = 0): """Broadcast the input tensor. NOTE: `src` is the local rank of the source rank. """ assert src < self.world_size, f"Invalid src rank ({src})" # Bypass the function if we are using only 1 GPU. if self.world_size == 1: return input_ # Broadcast. torch.distributed.broadcast( input_, src=self.ranks[src], group=self.device_group ) return input_ def broadcast_object(self, obj: Any | None = None, src: int = 0): """Broadcast the input object. NOTE: `src` is the local rank of the source rank. """ assert src < self.world_size, f"Invalid src rank ({src})" # Bypass the function if we are using only 1 GPU. if self.world_size == 1: return obj if self.mq_broadcaster is not None: assert src == 0, "Message queue broadcaster only supports src=0" return self.mq_broadcaster.broadcast_object(obj) if self.rank_in_group == src: torch.distributed.broadcast_object_list( [obj], src=self.ranks[src], group=self.cpu_group ) return obj else: recv = [None] torch.distributed.broadcast_object_list( recv, src=self.ranks[src], group=self.cpu_group ) return recv[0] def broadcast_object_list( self, obj_list: list[Any], src: int = 0, group: ProcessGroup | None = None ): """Broadcast the input object list. NOTE: `src` is the local rank of the source rank. """ assert src < self.world_size, f"Invalid src rank ({src})" # Bypass the function if we are using only 1 GPU. if self.world_size == 1: return obj_list # Broadcast. torch.distributed.broadcast_object_list( obj_list, src=self.ranks[src], group=self.device_group ) return obj_list def send_object(self, obj: Any, dst: int) -> None: """Send the input object list to the destination rank.""" """NOTE: `dst` is the local rank of the destination rank.""" assert dst < self.world_size, f"Invalid dst rank ({dst})" assert dst != self.rank_in_group, ( "Invalid destination rank. Destination rank is the same " "as the current rank." ) # Serialize object to tensor and get the size as well object_tensor = torch.frombuffer(pickle.dumps(obj), dtype=torch.uint8) size_tensor = torch.tensor( [object_tensor.numel()], dtype=torch.long, device="cpu" ) # Send object size torch.distributed.send(size_tensor, dst=self.ranks[dst], group=self.cpu_group) # Send object torch.distributed.send(object_tensor, dst=self.ranks[dst], group=self.cpu_group) return None def recv_object(self, src: int) -> Any: """Receive the input object list from the source rank.""" """NOTE: `src` is the local rank of the source rank.""" assert src < self.world_size, f"Invalid src rank ({src})" assert src != self.rank_in_group, ( "Invalid source rank. Source rank is the same as the current rank." ) size_tensor = torch.empty(1, dtype=torch.long, device="cpu") # Receive object size rank_size = torch.distributed.recv( size_tensor, src=self.ranks[src], group=self.cpu_group ) # Tensor to receive serialized objects into. object_tensor = torch.empty( # type: ignore[call-overload] size_tensor.item(), # type: ignore[arg-type] dtype=torch.uint8, device="cpu", ) rank_object = torch.distributed.recv( object_tensor, src=self.ranks[src], group=self.cpu_group ) assert rank_object == rank_size, ( "Received object sender rank does not match the size sender rank." ) obj = pickle.loads(object_tensor.numpy().tobytes()) return obj def broadcast_tensor_dict( self, tensor_dict: dict[str, torch.Tensor | Any] | None = None, src: int = 0, group: ProcessGroup | None = None, metadata_group: ProcessGroup | None = None, ) -> dict[str, torch.Tensor | Any] | None: """Broadcast the input tensor dictionary. NOTE: `src` is the local rank of the source rank. """ # Bypass the function if we are using only 1 GPU. if not torch.distributed.is_initialized() or self.world_size == 1: return tensor_dict group = self.device_group metadata_group = self.cpu_group assert src < self.world_size, f"Invalid src rank ({src})" rank_in_group = self.rank_in_group if rank_in_group == src: metadata_list: list[tuple[Any, Any]] = [] assert isinstance(tensor_dict, dict), ( f"Expecting a dictionary, got {type(tensor_dict)}" ) metadata_list, tensor_list = _split_tensor_dict(tensor_dict) # `metadata_list` lives in CPU memory. # `broadcast_object_list` has serialization & deserialization, # all happening on CPU. Therefore, we can use the CPU group. self.broadcast_object(metadata_list, src=src) async_handles = [] for tensor in tensor_list: if tensor.numel() == 0: # Skip broadcasting empty tensors. continue if tensor.is_cpu: # use metadata_group for CPU tensors handle = torch.distributed.broadcast( tensor, src=self.ranks[src], group=metadata_group, async_op=True ) else: # use group for GPU tensors handle = torch.distributed.broadcast( tensor, src=self.ranks[src], group=group, async_op=True ) async_handles.append(handle) for async_handle in async_handles: async_handle.wait() else: metadata_list = self.broadcast_object(None, src=src) tensor_dict = {} async_handles = [] for key, value in metadata_list: if isinstance(value, TensorMetadata): tensor = torch.empty( value.size, dtype=value.dtype, device=value.device ) if tensor.numel() == 0: # Skip broadcasting empty tensors. tensor_dict[key] = tensor continue if tensor.is_cpu: # use metadata_group for CPU tensors handle = torch.distributed.broadcast( tensor, src=self.ranks[src], group=metadata_group, async_op=True, ) else: # use group for GPU tensors handle = torch.distributed.broadcast( tensor, src=self.ranks[src], group=group, async_op=True ) async_handles.append(handle) tensor_dict[key] = tensor else: tensor_dict[key] = value for async_handle in async_handles: async_handle.wait() return tensor_dict def send_tensor_dict( self, tensor_dict: dict[str, torch.Tensor | Any], dst: int | None = None, all_gather_group: Optional["GroupCoordinator"] = None, all_gather_tensors: dict[str, bool] | None = None, ) -> dict[str, torch.Tensor | Any] | None: """Send the input tensor dictionary. NOTE: `dst` is the local rank of the source rank. all_gather_group: The group for the all-gather operation. If provided, an optimization is enabled where each rank in the group sends a slice of a tensor and the receiver reconstructs it using an all-gather, which can improve performance. This is typically the tensor-parallel group. all_gather_tensors: A dictionary to specify which tensors should use the all-gather optimization, which is only effective when `all_gather_group` is provided. By default, this optimization is on for any tensor whose size is divisible by the `all_gather_group`'s world size. However, it should be disabled for tensors that are not fully replicated across the group (e.g., the residual tensor when sequence parallelism is enabled). This dictionary allows overriding the default behavior on a per-tensor basis. """ # Bypass the function if we are using only 1 GPU. if not torch.distributed.is_initialized() or self.world_size == 1: return tensor_dict all_gather_size = 1 if all_gather_group is None else all_gather_group.world_size all_gather_rank = ( 0 if all_gather_group is None else all_gather_group.rank_in_group ) group = self.device_group metadata_group = self.cpu_group if dst is None: dst = (self.rank_in_group + 1) % self.world_size assert dst < self.world_size, f"Invalid dst rank ({dst})" if self.use_cpu_custom_send_recv: if self.device_communicator is None: raise ValueError("No device communicator found") self.device_communicator.send_tensor_dict( # type: ignore tensor_dict, dst ) return None metadata_list: list[tuple[Any, Any]] = [] assert isinstance(tensor_dict, dict), ( f"Expecting a dictionary, got {type(tensor_dict)}" ) metadata_list, tensor_list = _split_tensor_dict(tensor_dict) # `metadata_list` lives in CPU memory. # `send_object_list` has serialization & deserialization, # all happening on CPU. Therefore, we can use the CPU group. self.send_object(metadata_list, dst=dst) tensor_keys = [k for k, v in tensor_dict.items() if isinstance(v, torch.Tensor)] assert len(tensor_keys) == len(tensor_list) for key, tensor in zip(tensor_keys, tensor_list): if tensor.numel() == 0: # Skip sending empty tensors. continue # send-allgather: send only a slice, then do allgather. use_all_gather = ( all_gather_group is not None and tensor.numel() % all_gather_size == 0 ) use_all_gather = ( all_gather_tensors.get(key, use_all_gather) if all_gather_tensors else use_all_gather ) if use_all_gather: tensor = tensor.reshape(all_gather_size, -1)[all_gather_rank] if tensor.is_cpu: # use metadata_group for CPU tensors torch.distributed.send( tensor, dst=self.ranks[dst], group=metadata_group ) else: # use group for GPU tensors torch.distributed.send(tensor, dst=self.ranks[dst], group=group) return None def recv_tensor_dict( self, src: int | None = None, all_gather_group: Optional["GroupCoordinator"] = None, all_gather_tensors: dict[str, bool] | None = None, ) -> dict[str, torch.Tensor | Any] | None: """Recv the input tensor dictionary. NOTE: `src` is the local rank of the source rank. all_gather_group: The group for the all-gather operation. If provided, an optimization is enabled where each rank in the group sends a slice of a tensor and the receiver reconstructs it using an
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/__init__.py
vllm/distributed/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from .communication_op import * from .parallel_state import * from .utils import *
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/communication_op.py
vllm/distributed/communication_op.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import Any import torch import torch.distributed from .parallel_state import get_tp_group def tensor_model_parallel_all_reduce(input_: torch.Tensor) -> torch.Tensor: """All-reduce the input tensor across model parallel group.""" return get_tp_group().all_reduce(input_) def tensor_model_parallel_all_gather( input_: torch.Tensor, dim: int = -1 ) -> torch.Tensor: """All-gather the input tensor across model parallel group.""" return get_tp_group().all_gather(input_, dim) def tensor_model_parallel_reduce_scatter( input_: torch.Tensor, dim: int = -1 ) -> torch.Tensor: """Reduce-Scatter the input tensor across model parallel group.""" return get_tp_group().reduce_scatter(input_, dim) def tensor_model_parallel_gather( input_: torch.Tensor, dst: int = 0, dim: int = -1 ) -> torch.Tensor | None: """Gather the input tensor across model parallel group.""" return get_tp_group().gather(input_, dst, dim) def broadcast_tensor_dict( tensor_dict: dict[Any, torch.Tensor | Any] | None = None, src: int = 0 ): if not torch.distributed.is_initialized(): return tensor_dict return get_tp_group().broadcast_tensor_dict(tensor_dict, src)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/ec_transfer/ec_transfer_state.py
vllm/distributed/ec_transfer/ec_transfer_state.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import TYPE_CHECKING from vllm.distributed.ec_transfer.ec_connector.base import ( ECConnectorBase, ECConnectorRole, ) from vllm.distributed.ec_transfer.ec_connector.factory import ECConnectorFactory if TYPE_CHECKING: from vllm.config import VllmConfig _EC_CONNECTOR_AGENT: ECConnectorBase | None = None def get_ec_transfer() -> ECConnectorBase: assert _EC_CONNECTOR_AGENT is not None, "disaggregated EC cache is not initialized" return _EC_CONNECTOR_AGENT def has_ec_transfer() -> bool: return _EC_CONNECTOR_AGENT is not None def ensure_ec_transfer_initialized(vllm_config: "VllmConfig") -> None: """ Initialize EC cache connector. """ global _EC_CONNECTOR_AGENT if vllm_config.ec_transfer_config is None: return if ( vllm_config.ec_transfer_config.is_ec_transfer_instance and _EC_CONNECTOR_AGENT is None ): _EC_CONNECTOR_AGENT = ECConnectorFactory.create_connector( config=vllm_config, role=ECConnectorRole.WORKER )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/ec_transfer/__init__.py
vllm/distributed/ec_transfer/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.distributed.ec_transfer.ec_transfer_state import ( ensure_ec_transfer_initialized, get_ec_transfer, has_ec_transfer, ) __all__ = [ "get_ec_transfer", "ensure_ec_transfer_initialized", "has_ec_transfer", ]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/ec_transfer/ec_connector/example_connector.py
vllm/distributed/ec_transfer/ec_connector/example_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os from dataclasses import dataclass from typing import TYPE_CHECKING import safetensors from vllm.config import VllmConfig from vllm.distributed.ec_transfer.ec_connector.base import ( ECConnectorBase, ECConnectorMetadata, ECConnectorRole, ) from vllm.logger import init_logger from vllm.v1.core.sched.output import SchedulerOutput if TYPE_CHECKING: from vllm.v1.request import Request logger = init_logger(__name__) @dataclass class MMMeta: mm_hash: str num_token: int @staticmethod def make_meta(mm_hash, num_token) -> "MMMeta": return MMMeta(mm_hash=mm_hash, num_token=num_token) @dataclass class ECExampleConnectorMetadata(ECConnectorMetadata): mm_datas: list[MMMeta] def __init__(self): self.mm_datas = [] def add_mm_data(self, mm_data: MMMeta): self.mm_datas.append(mm_data) class ECExampleConnector(ECConnectorBase): # NOTE: This is Simple debug implementation of the EC connector. # It save / load the EC cache to / from the disk. def __init__(self, vllm_config: "VllmConfig", role: ECConnectorRole): super().__init__(vllm_config=vllm_config, role=role) # req_id -> index self._mm_datas_need_loads: dict[str, int] = {} transfer_config = vllm_config.ec_transfer_config if transfer_config is not None: self._storage_path = transfer_config.get_from_extra_config( "shared_storage_path", "/tmp" ) logger.debug(transfer_config) logger.debug("Shared storage path is %s", self._storage_path) else: raise ValueError("ec_transfer_config must be set for ECConnectorBase") def start_load_caches(self, encoder_cache, **kwargs) -> None: """ Start loading the cache from the connector into vLLM's encoder cache. This method loads the encoder cache based on metadata provided by the scheduler. It is called before `_gather_mm_embeddings` for the EC Connector. For EC, the `encoder_cache` and `mm_hash` are stored in `kwargs`. Args: encoder_cache (dict[str, torch.Tensor]): A dictionary mapping multimodal data hashes (`mm_hash`) to encoder cache tensors. kwargs (dict): Additional keyword arguments for the connector. """ from vllm.platforms import current_platform # Get the metadata metadata: ECConnectorMetadata = self._get_connector_metadata() assert isinstance(metadata, ECExampleConnectorMetadata) assert encoder_cache is not None if metadata is None: logger.warning( "In connector.start_load_caches, but the connector metadata is None" ) return # Load the EC for each mm data for mm_data in metadata.mm_datas: if mm_data.mm_hash in encoder_cache: continue filename = self._generate_filename_debug(mm_data.mm_hash) ec_cache = safetensors.torch.load_file( filename, device=current_platform.device_type )["ec_cache"] encoder_cache[mm_data.mm_hash] = ec_cache logger.debug("Success load encoder cache for hash %s", mm_data.mm_hash) def save_caches(self, encoder_cache, mm_hash, **kwargs) -> None: """ Save the encoder cache to the connector. This method saves the encoder cache from the worker's local storage to shared storage or another external connector. Args: encoder_cache (dict[str, torch.Tensor]): A dictionary mapping multimodal data hashes (`mm_hash`) to encoder cache tensors. mm_hash (str): The hash of the multimodal data whose cache is being saved. kwargs (dict): Additional keyword arguments for the connector. """ # Return if it is PD Instance if not self.is_producer: return filename = self._generate_filename_debug(mm_hash) ec_cache = encoder_cache[mm_hash] tensors = {"ec_cache": ec_cache.detach().cpu()} safetensors.torch.save_file(tensors, filename) logger.debug("Save cache successful for mm_hash %s", mm_hash) def has_caches( self, request: "Request", ) -> list[bool]: """ Check if cache exist externally for each mm_data of request Args: request (Request): the request object. Returns: List of bool indicate that ith mm_data exist in cache or not """ result = [] for feature in request.mm_features: result.append(self._found_match_for_mm_data(feature.identifier)) return result def update_state_after_alloc( self, request: "Request", index: int, ) -> None: """ Update ECConnector state after encoder cache allocation. """ mm_hash = request.mm_features[index].identifier num_encoder_token = request.get_num_encoder_embeds(index) # Insert mm_hash only if this block has not been recorded yet. self._mm_datas_need_loads[mm_hash] = num_encoder_token def build_connector_meta( self, scheduler_output: SchedulerOutput, ) -> ECConnectorMetadata: """Build the connector metadata for this step. This function should NOT modify any fields in the scheduler_output. Also, calling this function will reset the state of the connector. This only build for load mm_data only Args: scheduler_output (SchedulerOutput): the scheduler output object. """ meta = ECExampleConnectorMetadata() for mm_hash, num_encoder_token in self._mm_datas_need_loads.items(): meta.add_mm_data(MMMeta.make_meta(mm_hash, num_encoder_token)) self._mm_datas_need_loads.clear() return meta # ============================== # Helper functions # ============================== def _found_match_for_mm_data(self, mm_hash) -> bool: """Check if the cache is hit for the request.""" filename = self._generate_filename_debug(mm_hash) return os.path.exists(filename) def _generate_foldername_debug( self, mm_hash: str, create_folder: bool = True, # <- now defaults to True ) -> str: """ Return the folder in which the cache for this mm_hash lives. If `create_folder` is True (default) the directory is created recursively the first time it is needed. """ foldername = os.path.join(self._storage_path, mm_hash) if create_folder: os.makedirs(foldername, exist_ok=True) return foldername def _generate_filename_debug(self, mm_hash: str) -> str: """ Return the full path of the safetensors file for this mm_hash. Ensures the parent directory exists because `_generate_foldername_debug` is called with its default (`create_folder=True`). """ foldername = self._generate_foldername_debug(mm_hash) # <- folder auto-created return os.path.join(foldername, "encoder_cache.safetensors")
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/ec_transfer/ec_connector/factory.py
vllm/distributed/ec_transfer/ec_connector/factory.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import importlib from collections.abc import Callable from typing import TYPE_CHECKING from vllm.distributed.ec_transfer.ec_connector.base import ( ECConnectorBase, ECConnectorRole, ) from vllm.logger import init_logger if TYPE_CHECKING: from vllm.config import ECTransferConfig, VllmConfig logger = init_logger(__name__) class ECConnectorFactory: _registry: dict[str, Callable[[], type[ECConnectorBase]]] = {} @classmethod def register_connector(cls, name: str, module_path: str, class_name: str) -> None: """Register a connector with a lazy-loading module and class name.""" if name in cls._registry: raise ValueError(f"Connector '{name}' is already registered.") def loader() -> type[ECConnectorBase]: module = importlib.import_module(module_path) return getattr(module, class_name) cls._registry[name] = loader @classmethod def create_connector( cls, config: "VllmConfig", role: ECConnectorRole, ) -> ECConnectorBase: ec_transfer_config = config.ec_transfer_config if ec_transfer_config is None: raise ValueError("ec_transfer_config must be set to create a connector") connector_cls = cls.get_connector_class(ec_transfer_config) logger.info( "Creating connector with name: %s and engine_id: %s", connector_cls.__name__, ec_transfer_config.engine_id, ) # Connector is explicitly separated into two roles. # Scheduler connector: # - Co-locate with scheduler process # - Should only be used inside the Scheduler class # Worker connector: # - Co-locate with worker process return connector_cls(config, role) @classmethod def get_connector_class( cls, ec_transfer_config: "ECTransferConfig" ) -> type[ECConnectorBase]: """Get the connector class by name.""" connector_name = ec_transfer_config.ec_connector if connector_name is None: raise ValueError("EC connect must not be None") elif connector_name in cls._registry: connector_cls = cls._registry[connector_name]() else: connector_module_path = ec_transfer_config.ec_connector_module_path if connector_module_path is None: raise ValueError(f"Unsupported connector type: {connector_name}") connector_module = importlib.import_module(connector_module_path) connector_cls = getattr(connector_module, connector_name) return connector_cls # Register various connectors here. # The registration should not be done in each individual file, as we want to # only load the files corresponding to the current connector. ECConnectorFactory.register_connector( "ECExampleConnector", "vllm.distributed.ec_transfer.ec_connector.example_connector", "ECExampleConnector", )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/ec_transfer/ec_connector/__init__.py
vllm/distributed/ec_transfer/ec_connector/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/ec_transfer/ec_connector/base.py
vllm/distributed/ec_transfer/ec_connector/base.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ ECConnectorBase Class for Distributed Encoder Cache & P2P Encoder cache communication in V1 The class provides the following primitives: Scheduler-side: runs in the scheduler, binds metadata, which is used by the worker-side to load/save Encoder cache. check_caches_exist() - Check whether Encoder cache of requests exist update_state_after_alloc() - update ECConnector state after allocate. This will decide to load the cache or not request_finished() - called when a request is finished, free the cache with the requests Worker-side: runs in each worker, loads/saves Encoder Cache to/from the Connector based on the metadata. start_load_ec() - starts loading all ECs (maybe async) wait_for_save() - blocks until all saves are done get_finished() - called with ids of finished requests, returns ids of requests that have completed async sending/recving. """ import enum from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any import torch from vllm.logger import init_logger from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.outputs import ECConnectorOutput if TYPE_CHECKING: from vllm.config import VllmConfig from vllm.v1.request import Request logger = init_logger(__name__) class ECConnectorRole(enum.Enum): # Connector running in the scheduler process SCHEDULER = 0 # Connector running in the worker process WORKER = 1 class ECConnectorMetadata(ABC): # noqa: B024 """ Abstract Metadata used to communicate between the Scheduler ECConnector and Worker ECConnector. """ pass class ECConnectorBase(ABC): def __init__(self, vllm_config: "VllmConfig", role: ECConnectorRole): self._connector_metadata: ECConnectorMetadata | None = None self._vllm_config = vllm_config self._role = role if vllm_config.ec_transfer_config is not None: self._is_producer = vllm_config.ec_transfer_config.is_ec_producer else: raise ValueError("ec_transfer_config must be set for ECConnectorBase") @property def role(self) -> ECConnectorRole: return self._role @property def is_producer(self) -> bool: return self._is_producer # ============================== # Worker-side methods # ============================== def bind_connector_metadata(self, connector_metadata: ECConnectorMetadata) -> None: """Set the connector metadata from the scheduler. This function should be called by the model runner every time before the model execution. The metadata will be used for runtime EC cache loading. Args: connector_metadata (dict): the connector metadata. """ self._connector_metadata = connector_metadata def clear_connector_metadata(self) -> None: """Clear the connector metadata. This function should be called by the model runner every time after the model execution. """ self._connector_metadata = None def _get_connector_metadata(self) -> ECConnectorMetadata: """Get the connector metadata. This function should only be called inside the connector. Returns: ConnectorMetadata: the connector metadata. """ # Should only be called while set to valid metadata. assert self._connector_metadata is not None return self._connector_metadata def register_caches( self, ec_caches: dict[str, torch.Tensor], ): """ Initialize with the EC caches. Args: ec_caches: dictionary of encoder cache """ # TODO: Implement this later for P2P feature return @abstractmethod def start_load_caches( self, encoder_cache: dict[str, torch.Tensor], **kwargs ) -> None: """ Start loading the cache from the connector into vLLM's encoder cache. This method loads the encoder cache based on metadata provided by the scheduler. It is called before `_gather_mm_embeddings` for the EC Connector. For EC, the `encoder_cache` and `mm_hash` are stored in `kwargs`. Args: encoder_cache (dict[str, torch.Tensor]): A dictionary mapping multimodal data hashes (`mm_hash`) to encoder cache tensors. kwargs (dict): Additional keyword arguments for the connector. """ pass @abstractmethod def save_caches( self, encoder_cache: dict[str, torch.Tensor], mm_hash: str, **kwargs ) -> None: """ Save the encoder cache to the connector. This method saves the encoder cache from the worker's local storage to shared storage or another external connector. Args: encoder_cache (dict[str, torch.Tensor]): A dictionary mapping multimodal data hashes (`mm_hash`) to encoder cache tensors. mm_hash (str): The hash of the multimodal data whose cache is being saved. kwargs (dict): Additional keyword arguments for the connector. """ pass def get_finished( self, finished_req_ids: set[str] ) -> tuple[set[str] | None, set[str] | None]: """ Notifies worker-side connector ids of requests that have finished generating tokens on the worker. The scheduler process (via the Executors) will use this output to track which workers are done. Returns: ids of requests that have finished asynchronous transfer (requests that previously returned True from request_finished()), tuple of (sending/saving ids, recving/loading ids). The finished saves/sends req ids must belong to a set provided in a call to this method (this call or a prior one). """ return None, None # ============================== # Scheduler-side methods # ============================== @abstractmethod def has_caches( self, request: "Request", ) -> list[bool]: """ Check if encoder cache exists for each mm data of requests Args: request (Request): the request object. Returns: A list bool where ith value is True if cache exist for ith mm_data of requests """ pass @abstractmethod def update_state_after_alloc(self, request: "Request", index: int): """ Update ECConnector state to decide allocate cache for requests Args: request (Request): the request object. """ pass @abstractmethod def build_connector_meta( self, scheduler_output: SchedulerOutput ) -> ECConnectorMetadata: """ Build the connector metadata for this step. This function should NOT modify fields in the scheduler_output. Also, calling this function will reset the state of the connector. Args: scheduler_output (SchedulerOutput): the scheduler output object. """ pass def update_connector_output(self, connector_output: ECConnectorOutput): """ Update ECConnector state from worker-side connectors output. Args: connector_output (ECConnectorOutput): the worker-side connectors output. """ return def request_finished( self, request: "Request" ) -> tuple[bool, dict[str, Any] | None]: """ Called when a request has finished, before its encoder cache is freed. Returns: True if the request is being saved/sent asynchronously and cached should not be freed until the request_id is returned from get_finished(). """ return False, None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/cuda_communicator.py
vllm/distributed/device_communicators/cuda_communicator.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch from torch.distributed import ProcessGroup import vllm.envs as envs from vllm.distributed.device_communicators.all_reduce_utils import ( should_nccl_symm_mem_allreduce, ) from vllm.distributed.device_communicators.pynccl import register_nccl_symmetric_ops from vllm.distributed.device_communicators.pynccl_allocator import ( is_symmetric_memory_enabled, ) from vllm.logger import init_logger from vllm.platforms import current_platform from .base_device_communicator import DeviceCommunicatorBase logger = init_logger(__name__) class CudaCommunicator(DeviceCommunicatorBase): def __init__( self, cpu_group: ProcessGroup, device: torch.device | None = None, device_group: ProcessGroup | None = None, unique_name: str = "", ): super().__init__(cpu_group, device, device_group, unique_name) if "tp" not in unique_name: # custom allreduce or torch symm mem can be used only by tp use_custom_allreduce = False use_torch_symm_mem = False else: from vllm.distributed.parallel_state import _ENABLE_CUSTOM_ALL_REDUCE use_custom_allreduce = _ENABLE_CUSTOM_ALL_REDUCE use_torch_symm_mem = envs.VLLM_ALLREDUCE_USE_SYMM_MEM self.use_custom_allreduce = use_custom_allreduce self.use_torch_symm_mem = use_torch_symm_mem # lazy import to avoid documentation build error from vllm.distributed.device_communicators.custom_all_reduce import ( CustomAllreduce, ) from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator from vllm.distributed.device_communicators.quick_all_reduce import ( QuickAllReduce, ) from vllm.distributed.device_communicators.symm_mem import SymmMemCommunicator self.pynccl_comm: PyNcclCommunicator | None = None if self.world_size > 1: self.pynccl_comm = PyNcclCommunicator( group=self.cpu_group, device=self.device, ) if is_symmetric_memory_enabled(): register_nccl_symmetric_ops(self.pynccl_comm) self.ca_comm: CustomAllreduce | None = None self.qr_comm: QuickAllReduce | None = None self.symm_mem_comm: SymmMemCommunicator | None = None if use_torch_symm_mem and current_platform.is_cuda(): self.symm_mem_comm = SymmMemCommunicator( group=self.cpu_group, device=self.device, ) if use_custom_allreduce and self.world_size > 1: # Initialize a custom fast all-reduce implementation. self.ca_comm = CustomAllreduce( group=self.cpu_group, device=self.device, symm_mem_enabled=( self.symm_mem_comm is not None and not self.symm_mem_comm.disabled ), ) if current_platform.is_rocm(): # Initialize a custom quick all-reduce implementation for AMD. # Quick reduce is designed as a complement to custom allreduce. # Based on quickreduce (https://github.com/mk1-project/quickreduce). # If it's a rocm, 'use_custom_allreduce==True' means it must # currently be an MI300 series. self.qr_comm = QuickAllReduce(group=self.cpu_group, device=self.device) if self.use_all2all: if self.all2all_backend == "naive": from .all2all import NaiveAll2AllManager self.all2all_manager = NaiveAll2AllManager(self.cpu_group) elif self.all2all_backend == "allgather_reducescatter": from .all2all import AgRsAll2AllManager self.all2all_manager = AgRsAll2AllManager(self.cpu_group) elif self.all2all_backend == "pplx": from .all2all import PPLXAll2AllManager self.all2all_manager = PPLXAll2AllManager(self.cpu_group) elif self.all2all_backend == "deepep_high_throughput": from .all2all import DeepEPHTAll2AllManager self.all2all_manager = DeepEPHTAll2AllManager(self.cpu_group) elif self.all2all_backend == "deepep_low_latency": from .all2all import DeepEPLLAll2AllManager self.all2all_manager = DeepEPLLAll2AllManager(self.cpu_group) elif self.all2all_backend == "flashinfer_all2allv": from .all2all import FlashInferAllToAllManager self.all2all_manager = FlashInferAllToAllManager(self.cpu_group) else: raise ValueError(f"Unknown all2all backend: {self.all2all_backend}") logger.info_once( "Using %s all2all manager.", self.all2all_manager.__class__.__name__, scope="global", ) def all_reduce(self, input_): # since currently we perform copy input -> symm_input -> out-of-place AR # return symm_output, we don't need to check if input is symmetric if self.pynccl_comm is not None and should_nccl_symm_mem_allreduce( self.pynccl_comm.world_size, input_ ): out = torch.ops.vllm.all_reduce_symmetric_with_copy(input_) if out is not None: return out # always try quick reduce first, then custom allreduce, # and then pynccl. (quick reduce just for ROCM MI3*) qr_comm = self.qr_comm if ( qr_comm is not None and not qr_comm.disabled and qr_comm.should_quick_allreduce(input_) ): out = qr_comm.quick_all_reduce(input_) assert out is not None return out ca_comm = self.ca_comm if ( ca_comm is not None and not ca_comm.disabled and ca_comm.should_custom_ar(input_) ): out = ca_comm.custom_all_reduce(input_) assert out is not None return out symm_mem_comm = self.symm_mem_comm if symm_mem_comm is not None and symm_mem_comm.should_use_symm_mem(input_): out = symm_mem_comm.all_reduce(input_) assert out is not None return out pynccl_comm = self.pynccl_comm if pynccl_comm is None or pynccl_comm.disabled: out = input_.clone() torch.distributed.all_reduce(out, group=self.device_group) return out assert pynccl_comm is not None out = pynccl_comm.all_reduce(input_) if out is None: # fall back to the default all-reduce using PyTorch. # this usually happens during testing. # when we run the model, allreduce only happens for the TP # group, where we always have either custom allreduce or pynccl. out = input_.clone() torch.distributed.all_reduce(out, group=self.device_group) return out def reduce_scatter(self, input_: torch.Tensor, dim: int = -1): world_size = self.world_size pynccl_comm = self.pynccl_comm assert pynccl_comm is not None if dim < 0: # Convert negative dim to positive. dim += input_.dim() # Note: This will produce an incorrect answer if we don't make # the input_tensor contiguous. Possible bug in reduce_scatter_tensor? input_tensor = input_.movedim(0, dim).contiguous() assert input_tensor.shape[0] % world_size == 0 chunk_size = input_tensor.shape[0] // world_size output_shape = (chunk_size,) + input_tensor.shape[1:] output = torch.empty( output_shape, dtype=input_tensor.dtype, device=input_tensor.device ) pynccl_comm.reduce_scatter(output, input_tensor) # Reshape before returning return output.movedim(0, dim).contiguous() def reduce_scatterv( self, input_: torch.Tensor, dim: int = -1, sizes: list[int] | None = None ): world_size = self.world_size pynccl_comm = self.pynccl_comm assert pynccl_comm is not None if dim < 0: # Convert negative dim to positive. dim += input_.dim() # Note: This will produce an incorrect answer if we don't make # the input_tensor contiguous. Possible bug in reduce_scatter_tensor? input_tensor = input_.movedim(0, dim).contiguous() if sizes is not None: assert len(sizes) == world_size assert input_tensor.shape[0] == sum(sizes) chunk_size = sizes[self.rank_in_group] else: assert input_tensor.shape[0] % world_size == 0 chunk_size = input_tensor.shape[0] // world_size output_shape = (chunk_size,) + input_tensor.shape[1:] output = torch.empty( output_shape, dtype=input_tensor.dtype, device=input_tensor.device ) if sizes is not None and sizes.count(sizes[0]) != len(sizes): pynccl_comm.reduce_scatterv(output, input_tensor, sizes=sizes) else: pynccl_comm.reduce_scatter(output, input_tensor) # Reshape before returning return output.movedim(0, dim).contiguous() def send(self, tensor: torch.Tensor, dst: int | None = None) -> None: """Sends a tensor to the destination rank in a blocking way""" """NOTE: `dst` is the local rank of the destination rank.""" if dst is None: dst = (self.rank_in_group + 1) % self.world_size pynccl_comm = self.pynccl_comm if pynccl_comm is not None and not pynccl_comm.disabled: pynccl_comm.send(tensor, dst) else: torch.distributed.send(tensor, self.ranks[dst], self.device_group) def recv( self, size: torch.Size, dtype: torch.dtype, src: int | None = None ) -> torch.Tensor: """Receives a tensor from the source rank.""" """NOTE: `src` is the local rank of the source rank.""" if src is None: src = (self.rank_in_group - 1) % self.world_size tensor = torch.empty(size, dtype=dtype, device=self.device) pynccl_comm = self.pynccl_comm if pynccl_comm is not None and not pynccl_comm.disabled: pynccl_comm.recv(tensor, src) else: torch.distributed.recv(tensor, self.ranks[src], self.device_group) return tensor def destroy(self): if self.pynccl_comm is not None: self.pynccl_comm = None if self.ca_comm is not None: self.ca_comm = None if self.all2all_manager is not None: self.all2all_manager.destroy() self.all2all_manager = None def all_gatherv( self, input_: torch.Tensor | list[torch.Tensor], dim: int = 0, sizes: list[int] | None = None, ): if dim != 0: raise NotImplementedError("only dim 0 all-gatherv is supported") world_size = self.world_size pynccl_comm = self.pynccl_comm assert pynccl_comm is not None and not pynccl_comm.disabled # 'sizes' is not needed if all inputs in the same group have the same # shape if sizes is not None and all(s == sizes[0] for s in sizes): sizes = None def _all_gather_single(input_: torch.Tensor, sizes: list[int] | None = None): input_size = input_.size() if sizes is not None: assert len(sizes) == world_size assert input_.shape[dim] == sizes[self.rank_in_group], ( f"{input_.shape[dim]} != {sizes[self.rank_in_group]}" ) output_size = (sum(sizes),) + input_size[1:] else: output_size = (input_size[0] * world_size,) + input_size[1:] # Allocate output tensor. output_tensor = torch.empty( output_size, dtype=input_.dtype, device=input_.device ) if sizes is not None: pynccl_comm.all_gatherv(output_tensor, input_, sizes=sizes) else: pynccl_comm.all_gather(output_tensor, input_) return output_tensor if isinstance(input_, torch.Tensor): return _all_gather_single(input_, sizes) output_list = [] pynccl_comm.group_start() for inp in input_: output_list.append(_all_gather_single(inp, sizes=sizes)) pynccl_comm.group_end() return output_list def dispatch( # type: ignore[override] self, hidden_states: torch.Tensor, router_logits: torch.Tensor, is_sequence_parallel: bool = False, extra_tensors: list[torch.Tensor] | None = None, ) -> ( tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, list[torch.Tensor]] ): assert self.all2all_manager is not None return self.all2all_manager.dispatch( hidden_states, router_logits, is_sequence_parallel, extra_tensors, # type: ignore[call-arg] ) def combine( self, hidden_states: torch.Tensor, is_sequence_parallel: bool = False ) -> torch.Tensor: assert self.all2all_manager is not None hidden_states = self.all2all_manager.combine( hidden_states, is_sequence_parallel ) return hidden_states
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/symm_mem.py
vllm/distributed/device_communicators/symm_mem.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch import torch.distributed as dist from torch.distributed import ProcessGroup from vllm.distributed.device_communicators.all_reduce_utils import ( SYMM_MEM_ALL_REDUCE_MAX_SIZES, ) from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.platforms import current_platform try: import torch.distributed._symmetric_memory as torch_symm_mem symm_mem_available = True except ImportError: symm_mem_available = False logger = init_logger(__name__) class SymmMemCommunicator: _WORLD_SIZES_MULTIMEM = { "9.0": [4, 6, 8], "10.0": [6, 8], } def __init__( self, group: ProcessGroup, device: int | str | torch.device, # add options for testing force_multimem: bool | None = None, max_size_override: int | None = None, ): self.disabled = True if not symm_mem_available: return if not current_platform.is_cuda(): logger.warning("SymmMemCommunicator: symmetric memory is not available.") return if isinstance(device, int): device = torch.device(f"cuda:{device}") elif isinstance(device, str): device = torch.device(device) torch.cuda.set_device(device) self.dtype = torch.bfloat16 self.device = device self.group = group self.world_size = dist.get_world_size(self.group) capability = current_platform.get_device_capability() if capability is None: logger.warning( "SymmMemCommunicator: device capability is unknown, " "communicator is not available." ) return self.device_capability = capability.as_version_str() if self.device_capability not in SYMM_MEM_ALL_REDUCE_MAX_SIZES: logger.warning( "SymmMemCommunicator: Device capability %s not supported, " "communicator is not available.", self.device_capability, ) return if self.world_size not in SYMM_MEM_ALL_REDUCE_MAX_SIZES[self.device_capability]: logger.warning( "SymmMemCommunicator: World size %d not supported, " "communicator is not available.", self.world_size, ) return # Use override max_size if provided, otherwise use default if max_size_override is not None: self.max_size = max_size_override logger.info( "SymmMemCommunicator: Using override max_size: %s bytes", self.max_size, ) else: self.max_size = SYMM_MEM_ALL_REDUCE_MAX_SIZES[self.device_capability][ self.world_size ] try: self.buffer = torch_symm_mem.empty( self.max_size // self.dtype.itemsize, device=self.device, dtype=self.dtype, ) handle = torch_symm_mem.rendezvous(self.buffer, self.group.group_name) except RuntimeError as e: logger.warning_once( "SymmMemCommunicator: symmetric memory initialization failed: %s " "Communicator is not available. To suppress this warning set " "VLLM_ALLREDUCE_USE_SYMM_MEM=0", str(e), ) return if handle.multicast_ptr == 0: logger.warning( "SymmMemCommunicator: symmetric memory " "multicast operations are not supported." ) return self.force_multimem = force_multimem self.disabled = False if vllm_is_batch_invariant(): self.disabled = True def should_use_symm_mem(self, inp: torch.Tensor): if self.disabled: return False if inp.dtype != self.dtype: return False inp_size = inp.numel() * inp.element_size() if inp_size % 4 != 0: return False return inp_size < self.max_size def all_reduce( self, inp: torch.Tensor, *, out: torch.Tensor | None = None ) -> torch.Tensor | None: if not self.should_use_symm_mem(inp): return None if out is None: out = torch.empty_like(inp) self.buffer[: inp.numel()].copy_(inp.view(-1)) # Determine which algorithm to use use_multimem = False if self.force_multimem is not None: # Test override: use forced setting use_multimem = self.force_multimem else: # Normal logic: use multimem for supported world sizes use_multimem = ( self.world_size in self._WORLD_SIZES_MULTIMEM[self.device_capability] ) if use_multimem: torch.ops.symm_mem.multimem_all_reduce_( self.buffer[: inp.numel()], "sum", self.group.group_name ) else: torch.ops.symm_mem.two_shot_all_reduce_( self.buffer[: inp.numel()], "sum", self.group.group_name ) out.copy_(self.buffer[: inp.numel()].view(out.shape)) return out
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/xpu_communicator.py
vllm/distributed/device_communicators/xpu_communicator.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch import torch.distributed as dist from torch.distributed import ProcessGroup from vllm.logger import init_logger from .base_device_communicator import DeviceCommunicatorBase logger = init_logger(__name__) class XpuCommunicator(DeviceCommunicatorBase): def __init__( self, cpu_group: ProcessGroup, device: torch.device | None = None, device_group: ProcessGroup | None = None, unique_name: str = "", ): super().__init__(cpu_group, device, device_group, unique_name) if self.use_all2all: if self.all2all_backend != "naive": logger.warning( "`%s` all2all manager is not supported on XPU. " "Falling back to `naive` all2all manager for XPU.", self.all2all_backend, ) self.all2all_backend = "naive" if self.all2all_backend == "naive": from .all2all import NaiveAll2AllManager self.all2all_manager = NaiveAll2AllManager(self.cpu_group) logger.info("Using naive all2all manager.") def all_reduce(self, input_) -> torch.Tensor: dist.all_reduce(input_, group=self.device_group) return input_ def gather( self, input_: torch.Tensor, dst: int = 0, dim: int = -1 ) -> torch.Tensor | None: assert -input_.dim() <= dim < input_.dim(), ( f"Invalid dim ({dim}) for input tensor with shape {input_.size()}" ) if dim < 0: # Convert negative dim to positive. dim += input_.dim() # For xpu path, gather doesn't work properly together with ray # cluster so we use all_gather instead for now. input_size = input_.size() # Allocate output tensor. output_tensor = torch.empty( (self.world_size,) + input_size, dtype=input_.dtype, device=input_.device ) # All-gather. dist.all_gather_into_tensor(output_tensor, input_, group=self.device_group) if self.rank_in_group == dst: # Reshape output_tensor = output_tensor.movedim(0, dim) output_tensor = output_tensor.reshape( input_size[:dim] + (self.world_size * input_size[dim],) + input_size[dim + 1 :] ) else: output_tensor = None return output_tensor def broadcast(self, input_: torch.Tensor, src: int = 0) -> None: dist.broadcast(input_, src=src, group=self.device_group) def dispatch( self, hidden_states: torch.Tensor, router_logits: torch.Tensor, is_sequence_parallel: bool = False, ) -> tuple[torch.Tensor, torch.Tensor]: assert self.all2all_manager is not None hidden_states, router_logits = self.all2all_manager.dispatch( hidden_states, router_logits, is_sequence_parallel ) return hidden_states, router_logits def combine( self, hidden_states: torch.Tensor, is_sequence_parallel: bool = False ) -> torch.Tensor: assert self.all2all_manager is not None hidden_states = self.all2all_manager.combine( hidden_states, is_sequence_parallel ) return hidden_states
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/shm_broadcast.py
vllm/distributed/device_communicators/shm_broadcast.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import functools import pickle import threading import time from contextlib import contextmanager from dataclasses import dataclass, field from multiprocessing import shared_memory from pickle import PickleBuffer from threading import Event from typing import TYPE_CHECKING, Any, cast from unittest.mock import patch import torch import torch.distributed as dist import zmq from torch.distributed import ProcessGroup from zmq import ( # type: ignore IPV6, # type: ignore SUB, SUBSCRIBE, XPUB, XPUB_VERBOSE, Context, ) import vllm.envs as envs from vllm.distributed.utils import StatelessProcessGroup, sched_yield from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.utils.network_utils import ( get_ip, get_open_port, get_open_zmq_ipc_path, is_valid_ipv6_address, ) if TYPE_CHECKING: from _typeshed import SizedBuffer VLLM_RINGBUFFER_WARNING_INTERVAL = envs.VLLM_RINGBUFFER_WARNING_INTERVAL from_bytes_big = functools.partial(int.from_bytes, byteorder="big") # Memory fence for cross-process shared memory visibility. # Required for correct producer-consumer synchronization when using # shared memory without locks. _memory_fence_lock = threading.Lock() def memory_fence(): """ Full memory barrier for shared memory synchronization. Ensures all prior memory writes are visible to other processes before any subsequent reads. This is critical for lock-free producer-consumer patterns using shared memory. Implementation acquires and immediately releases a lock. Python's threading.Lock provides sequentially consistent memory barrier semantics across all major platforms (POSIX, Windows). This is a lightweight operation (~20ns) that guarantees: - All stores before the barrier are visible to other threads/processes - All loads after the barrier see the latest values """ # Lock acquire/release provides full memory barrier semantics. # Using context manager ensures lock release even on exceptions. with _memory_fence_lock: pass def to_bytes_big(value: int, size: int) -> bytes: return value.to_bytes(size, byteorder="big") logger = init_logger(__name__) def long_wait_time_msg(threshold: int) -> str: return ( "No available shared memory broadcast block found " f"in {threshold} seconds. This typically happens " "when some processes are hanging or doing some " "time-consuming work (e.g. compilation, " "weight/kv cache quantization)." ) class SpinTimer: def record_activity(self): pass def spin(self): sched_yield() class SpinSleepTimer(SpinTimer): """ In setups which have long inactivity periods it is desirable to reduce system power consumption when vllm does nothing. This would lead to more CPU thermal headroom when a request eventually comes, especially when multiple GPUs are connected as each GPU would otherwise pin one thread at 100% CPU usage. The simplest solution is to reduce polling frequency when there is no activity for a certain period of time. """ def __init__(self, busy_loop_s: float = 3.0, wait_sleep_s: float = 0.1): self.last_activity = time.monotonic() self.busy_loop_s = busy_loop_s self.wait_sleep_s = wait_sleep_s def record_activity(self): self.last_activity = time.monotonic() def spin(self): curr_time = time.monotonic() if curr_time >= self.last_activity + self.busy_loop_s: time.sleep(self.wait_sleep_s) else: sched_yield() class ShmRingBuffer: def __init__( self, n_reader: int, max_chunk_bytes: int, max_chunks: int, name: str | None = None, ): """ A shared memory ring buffer implementation for broadcast communication. Essentially, it is a queue where only one will `enqueue` and multiple will `dequeue`. The max size of each item, together with the max number of items that can be stored in the buffer are known in advance. In this case, we don't need to synchronize the access to the buffer. Buffer memory layout: data metadata | | | (current_idx) | (current_idx) v v +-------------------------------+----------------------------------------+ | chunk0 | chunk1 | ... | chunk | metadata0 | metadata1 | ... | metadata | +-------------------------------+----------------------------------------+ | max_chunks x max_chunk_bytes | max_chunks x (1 + n_reader) bytes | metadata memory layout: each byte is a flag, the first byte is the written flag, and the rest are reader flags. The flags are set to 0 by default. +--------------+--------------+--------------+-----+--------------+ | written_flag | reader0_flag | reader1_flag | ... | readerN_flag | +--------------+--------------+--------------+-----+--------------+ The state of metadata is as follows: (case 1) 0???...???: the block is not written yet, cannot read, can write (case 2) 1000...000: the block is just written, can read, cannot write (case 3) 1???...???: the block is written and read by some readers, can read if not read, cannot write (case 4) 1111...111: the block is written and read by all readers, cannot read, can write State transition for readers: When a reader finds a block that it can read (case 2 or 3), it can yield the block for caller to read. Only after the caller finishes reading the block, the reader can mark the block as read. Readers only mark the block as read (from 0 to 1), the writer marks the block as ready to read (from 1 to 0). State transition for writer: When the writer writes to a block (case 1 or 4), it first resets the written flag to 0, converting either case to case 1. Then it can yield the block for caller to write. After the caller finishes writing the block, the writer can reset the reader flags to 0, and mark the block as written (from 0 to 1). NOTE: the order is important here, first reset the reader flags (so that we are still in case 1), then mark the block as written. The state transition is atomic. If we do it in the reverse order, it will go through case 3 and then back to case 2, and readers might read the intermediate case 3, which is not correct. During creation, `name` is None and the buffer is created. We can pass the created object to other processes by pickling it. The other processes will get the name of the shared memory and open it, so that they can access the same shared memory buffer. """ # noqa self.n_reader = n_reader self.metadata_size = 1 + n_reader self.max_chunk_bytes = max_chunk_bytes self.max_chunks = max_chunks self.total_bytes_of_buffer = ( self.max_chunk_bytes + self.metadata_size ) * self.max_chunks self.data_offset = 0 self.metadata_offset = self.max_chunk_bytes * self.max_chunks if name is None: # we are creating a buffer self.is_creator = True self.shared_memory = shared_memory.SharedMemory( create=True, size=self.total_bytes_of_buffer ) # initialize the metadata section to 0 with self.shared_memory.buf[self.metadata_offset :] as metadata_buffer: torch.frombuffer(metadata_buffer, dtype=torch.uint8).fill_(0) else: # we are opening an existing buffer self.is_creator = False # fix to https://stackoverflow.com/q/62748654/9191338 # Python incorrectly tracks shared memory even if it is not # created by the process. The following patch is a workaround. with patch( "multiprocessing.resource_tracker.register", lambda *args, **kwargs: None, ): try: self.shared_memory = shared_memory.SharedMemory(name=name) # See https://docs.python.org/3/library/multiprocessing.shared_memory.html # noqa # Some platforms allocate memory based on page size, # so the shared memory block size may be larger or equal # to the requested size. The size parameter is ignored # when attaching to an existing block. assert self.shared_memory.size >= self.total_bytes_of_buffer except FileNotFoundError: # we might deserialize the object in a different node # in this case, this object is not used, # and we should suppress the error pass def handle(self): return ( self.n_reader, self.max_chunk_bytes, self.max_chunks, self.shared_memory.name, ) def __reduce__(self): return ( self.__class__, self.handle(), ) def __del__(self): if hasattr(self, "shared_memory"): self.shared_memory.close() if self.is_creator: self.shared_memory.unlink() @contextmanager def get_data(self, current_idx: int): start = self.data_offset + current_idx * self.max_chunk_bytes end = start + self.max_chunk_bytes with self.shared_memory.buf[start:end] as buf: yield buf @contextmanager def get_metadata(self, current_idx: int): start = self.metadata_offset + current_idx * self.metadata_size end = start + self.metadata_size with self.shared_memory.buf[start:end] as buf: yield buf @dataclass class Handle: local_reader_ranks: list[int] = field(default_factory=list) buffer_handle: tuple[int, int, int, str] | None = None local_subscribe_addr: str | None = None remote_subscribe_addr: str | None = None remote_addr_ipv6: bool = False class MessageQueue: def __init__( self, n_reader, # number of all readers n_local_reader, # number of local readers through shared memory local_reader_ranks: list[int] | None = None, # Default of 24MiB chosen to be large enough to accommodate grammar # bitmask tensors for large batches (1024 requests). max_chunk_bytes: int = 1024 * 1024 * 24, max_chunks: int = 10, connect_ip: str | None = None, ): if local_reader_ranks is None: local_reader_ranks = list(range(n_local_reader)) else: assert len(local_reader_ranks) == n_local_reader self.n_local_reader = n_local_reader n_remote_reader = n_reader - n_local_reader self.n_remote_reader = n_remote_reader context = Context() if n_local_reader > 0: # for local readers, we will: # 1. create a shared memory ring buffer to communicate small data # 2. create a publish-subscribe socket to communicate large data self.buffer = ShmRingBuffer(n_local_reader, max_chunk_bytes, max_chunks) # XPUB is very similar to PUB, # except that it can receive subscription messages # to confirm the number of subscribers self.local_socket = context.socket(XPUB) # set the verbose option so that we can receive every subscription # message. otherwise, we will only receive the first subscription # see http://api.zeromq.org/3-3:zmq-setsockopt for more details self.local_socket.setsockopt(XPUB_VERBOSE, True) local_subscribe_addr = get_open_zmq_ipc_path() logger.debug("Binding to %s", local_subscribe_addr) self.local_socket.bind(local_subscribe_addr) self.current_idx = 0 else: self.buffer = None # type: ignore local_subscribe_addr = None self.local_socket = None self.current_idx = -1 remote_addr_ipv6 = False if n_remote_reader > 0: # for remote readers, we will: # create a publish-subscribe socket to communicate large data if not connect_ip: connect_ip = get_ip() self.remote_socket = context.socket(XPUB) self.remote_socket.setsockopt(XPUB_VERBOSE, True) remote_subscribe_port = get_open_port() if is_valid_ipv6_address(connect_ip): self.remote_socket.setsockopt(IPV6, 1) remote_addr_ipv6 = True connect_ip = f"[{connect_ip}]" socket_addr = f"tcp://{connect_ip}:{remote_subscribe_port}" self.remote_socket.bind(socket_addr) remote_subscribe_addr = f"tcp://{connect_ip}:{remote_subscribe_port}" else: remote_subscribe_addr = None self.remote_socket = None self._is_writer = True self._is_local_reader = False self.local_reader_rank = -1 # rank does not matter for remote readers self._is_remote_reader = False self._read_spin_timer = SpinTimer() self.handle = Handle( local_reader_ranks=local_reader_ranks, buffer_handle=self.buffer.handle() if self.buffer is not None else None, local_subscribe_addr=local_subscribe_addr, remote_subscribe_addr=remote_subscribe_addr, remote_addr_ipv6=remote_addr_ipv6, ) logger.debug("vLLM message queue communication handle: %s", self.handle) def export_handle(self) -> Handle: return self.handle @staticmethod def create_from_handle(handle: Handle, rank) -> "MessageQueue": self = MessageQueue.__new__(MessageQueue) self.handle = handle self._is_writer = False context = Context() if rank in handle.local_reader_ranks: assert handle.buffer_handle is not None self.buffer = ShmRingBuffer(*handle.buffer_handle) self.current_idx = 0 self.local_reader_rank = handle.local_reader_ranks.index(rank) self._is_local_reader = True self._is_remote_reader = False self.local_socket = context.socket(SUB) self.local_socket.setsockopt_string(SUBSCRIBE, "") socket_addr = handle.local_subscribe_addr logger.debug("Connecting to %s", socket_addr) self.local_socket.connect(socket_addr) self.remote_socket = None self._read_spin_timer = ( SpinSleepTimer() if envs.VLLM_SLEEP_WHEN_IDLE else SpinTimer() ) else: self.buffer = None # type: ignore self.current_idx = -1 self.local_reader_rank = -1 self._is_local_reader = False self._is_remote_reader = True self.local_socket = None self.remote_socket = context.socket(SUB) self.remote_socket.setsockopt_string(SUBSCRIBE, "") if handle.remote_addr_ipv6: self.remote_socket.setsockopt(IPV6, 1) socket_addr = handle.remote_subscribe_addr logger.debug("Connecting to %s", socket_addr) self.remote_socket.connect(socket_addr) return self def wait_until_ready(self): """This is a collective operation. All processes (including the readers and the writer) should call this function. """ if self._is_writer: # wait for all readers to connect # local readers for i in range(self.n_local_reader): # wait for subscription messages from all local readers self.local_socket.recv() if self.n_local_reader > 0: # send a message to all local readers # to make sure the publish channel is working self.local_socket.send(b"READY") # remote readers for i in range(self.n_remote_reader): # wait for subscription messages from all remote readers self.remote_socket.recv() if self.n_remote_reader > 0: # send a message to all remote readers # to make sure the publish channel is working self.remote_socket.send(b"READY") elif self._is_local_reader: # wait for the writer to send a message recv = self.local_socket.recv() assert recv == b"READY" elif self._is_remote_reader: # wait for the writer to send a message recv = self.remote_socket.recv() assert recv == b"READY" @contextmanager def acquire_write(self, timeout: float | None = None): assert self._is_writer, "Only writers can acquire write" start_time = time.monotonic() n_warning = 1 while True: with self.buffer.get_metadata(self.current_idx) as metadata_buffer: # Memory fence ensures we see the latest read flags from readers. # Without this, we may read stale flags from our CPU cache and # spin indefinitely even though readers have completed. memory_fence() read_count = sum(metadata_buffer[1:]) written_flag = metadata_buffer[0] if written_flag and read_count != self.buffer.n_reader: # this block is written and not read by all readers # for writers, `self.current_idx` is the next block to write # if this block is not ready to write, # we need to wait until it is read by all readers # Release the processor to other threads sched_yield() # if we time out, raise an exception elapsed = time.monotonic() - start_time if timeout is not None and elapsed > timeout: raise TimeoutError # if we wait for a long time, log a message if elapsed > VLLM_RINGBUFFER_WARNING_INTERVAL * n_warning: logger.info( long_wait_time_msg(VLLM_RINGBUFFER_WARNING_INTERVAL) ) n_warning += 1 continue # found a block that is either # (1) not written # (2) read by all readers # mark the block as not written metadata_buffer[0] = 0 # let caller write to the buffer with self.buffer.get_data(self.current_idx) as buf: yield buf # caller has written to the buffer # NOTE: order is important here # first set the read flags to 0 # then set the written flag to 1 # otherwise, the readers may think they already read the block for i in range(1, self.buffer.n_reader + 1): # set read flag to 0, meaning it is not read yet metadata_buffer[i] = 0 # mark the block as written metadata_buffer[0] = 1 # Memory fence ensures the write is visible to readers on other cores # before we proceed. Without this, readers may spin indefinitely # waiting for a write that's stuck in our CPU's store buffer. memory_fence() self.current_idx = (self.current_idx + 1) % self.buffer.max_chunks break @contextmanager def acquire_read( self, timeout: float | None = None, cancel: Event | None = None, indefinite: bool = False, ): assert self._is_local_reader, "Only readers can acquire read" start_time = time.monotonic() n_warning = 1 while True: with self.buffer.get_metadata(self.current_idx) as metadata_buffer: # Memory fence ensures we see the latest writes from the writer. # Without this, we may read stale flags from our CPU cache # and spin indefinitely even though writer has updated them. memory_fence() read_flag = metadata_buffer[self.local_reader_rank + 1] written_flag = metadata_buffer[0] if not written_flag or read_flag: # this block is either # (1) not written # (2) already read by this reader # for readers, `self.current_idx` is the next block to read # if this block is not ready, # we need to wait until it is written # Release the processor to other threads self._read_spin_timer.spin() if cancel is not None and cancel.is_set(): raise RuntimeError("cancelled") # if we time out, raise an exception elapsed = time.monotonic() - start_time if timeout is not None and elapsed > timeout: raise TimeoutError # if we wait for a long time, log a message if not indefinite and ( elapsed > VLLM_RINGBUFFER_WARNING_INTERVAL * n_warning ): logger.info( long_wait_time_msg(VLLM_RINGBUFFER_WARNING_INTERVAL) ) n_warning += 1 continue # found a block that is not read by this reader # let caller read from the buffer with self.buffer.get_data(self.current_idx) as buf: yield buf # caller has read from the buffer # set the read flag metadata_buffer[self.local_reader_rank + 1] = 1 # Memory fence ensures the read flag is visible to the writer. # Without this, writer may not see our read completion and # could wait indefinitely for all readers to finish. memory_fence() self.current_idx = (self.current_idx + 1) % self.buffer.max_chunks self._read_spin_timer.record_activity() break def enqueue(self, obj, timeout: float | None = None): """Write to message queue with optional timeout (in seconds)""" assert self._is_writer, "Only writers can enqueue" all_buffers: list[SizedBuffer] = [b""] total_bytes = 6 # 2 bytes for oob buffer count, 4 for main buffer size def oob_callback(buf: PickleBuffer) -> bool: raw_buf = buf.raw() if len(raw_buf) < 1024 * 1024: # In-line buffers smaller than 1MiB. return True all_buffers.append(raw_buf) nonlocal total_bytes total_bytes += len(raw_buf) + 4 return False all_buffers[0] = pickle.dumps( obj, protocol=pickle.HIGHEST_PROTOCOL, buffer_callback=oob_callback ) if self.n_local_reader > 0: if total_bytes + len(all_buffers[0]) >= self.buffer.max_chunk_bytes: with self.acquire_write(timeout) as buf: buf[0] = 1 # overflow self.local_socket.send_multipart(all_buffers, copy=False) else: # Byte 0: 0 # Bytes 1-2: Count of buffers # Then each buffer follows, preceded by 4 bytes containing its length: # [4 byte int L][L bytes of buffer content] ... with self.acquire_write(timeout) as buf: buf[0] = 0 # not overflow offset = 3 buf[1:offset] = to_bytes_big(len(all_buffers), 2) # oob buf count for buffer in all_buffers: buf_len = len(buffer) # prepend each buffer with 4 bytes containing its size. buf_offset = offset + 4 buf[offset:buf_offset] = to_bytes_big(buf_len, 4) buf[buf_offset : (offset := buf_offset + buf_len)] = buffer if self.n_remote_reader > 0: self.remote_socket.send_multipart(all_buffers, copy=False) def dequeue( self, timeout: float | None = None, cancel: Event | None = None, indefinite: bool = False, ): """Read from message queue with optional timeout (in seconds)""" if self._is_local_reader: with self.acquire_read(timeout, cancel, indefinite) as buf: overflow = buf[0] == 1 if not overflow: offset = 3 buf_count = from_bytes_big(buf[1:offset]) all_buffers = [] for i in range(buf_count): buf_offset = offset + 4 buf_len = from_bytes_big(buf[offset:buf_offset]) offset = buf_offset + buf_len all_buffers.append(buf[buf_offset:offset]) obj = pickle.loads(all_buffers[0], buffers=all_buffers[1:]) if overflow: obj = MessageQueue.recv(self.local_socket, timeout) elif self._is_remote_reader: obj = MessageQueue.recv(self.remote_socket, timeout) else: raise RuntimeError("Only readers can dequeue") return obj @staticmethod def recv(socket: zmq.Socket, timeout: float | None) -> Any: timeout_ms = None if timeout is None else int(timeout * 1000) if not socket.poll(timeout=timeout_ms): raise TimeoutError recv, *recv_oob = socket.recv_multipart(copy=False) return pickle.loads(recv, buffers=recv_oob) def broadcast_object(self, obj=None): if self._is_writer: self.enqueue(obj) return obj return self.dequeue() @staticmethod def create_from_process_group_single_reader( pg: ProcessGroup, max_chunk_bytes, max_chunks, reader_rank: int = 0, blocking: bool = False, ) -> tuple["MessageQueue", list[Handle]]: """ Creates a MessageQueue for a process group with a single reader. This method is designed for scenarios where only one process (the reader) will consume messages, and all other processes are writers. It sets up the shared memory buffer and communication handles accordingly, and gathers the handles from all processes to the reader. Args: pg (ProcessGroup): The torch distributed process group. max_chunk_bytes (int): Maximum size in bytes for each chunk in the buffer. max_chunks (int): Maximum number of chunks in the buffer. reader_rank (int, optional): The global rank that will act as the reader. Defaults to 0. blocking (bool, optional): If True, blocks until all processes are ready. Defaults to False. Returns: tuple[MessageQueue, list[Handle]]: The MessageQueue instance for the calling process, and a list of handles (only non-empty for the reader process). """ local_size = current_platform.device_count() rank = dist.get_rank() same_node = rank // local_size == reader_rank // local_size buffer_io = MessageQueue( n_reader=1, n_local_reader=1 if same_node else 0, max_chunk_bytes=max_chunk_bytes, max_chunks=max_chunks, ) handle = buffer_io.export_handle() handles = [None] * dist.get_world_size(pg) if rank == reader_rank else None dist.gather_object(handle, handles, dst=reader_rank, group=pg) if blocking: buffer_io.wait_until_ready() return buffer_io, cast(list[Handle], handles or []) @staticmethod def create_from_process_group( pg: ProcessGroup | StatelessProcessGroup, max_chunk_bytes, max_chunks, writer_rank: int = 0, external_writer_handle=None, blocking: bool = True, ) -> "MessageQueue": """ Creates a MessageQueue for a distributed process group with one writer and multiple readers. This method is designed for scenarios where one process (the writer) sends messages, and all other processes (the readers) receive messages. It sets up the shared memory buffer and socket communication handles accordingly, and broadcasts the handle from the writer to all readers. Args: pg (ProcessGroup | StatelessProcessGroup): The torch distributed process group. max_chunk_bytes (int): Maximum size in bytes for each chunk in the buffer. max_chunks (int): Maximum number of chunks in the buffer. writer_rank (int, optional): The global rank that will act as the writer. Defaults to 0. external_writer_handle (Handle, optional): Used when there is a handle from an external Message Queue. If provided, use this handle to init PG writer message queue instead of creating a new one. Defaults to None. blocking (bool, optional): If True, blocks until all processes are ready. Defaults to True. Returns: MessageQueue: The MessageQueue instance for the calling process. """ if isinstance(pg, ProcessGroup): group_rank = dist.get_rank(pg) group_world_size = dist.get_world_size(pg) global_ranks = dist.get_process_group_ranks(pg) else: group_rank = pg.rank group_world_size = pg.world_size global_ranks = list(range(pg.world_size)) from vllm.distributed.parallel_state import in_the_same_node_as status = in_the_same_node_as(pg, source_rank=writer_rank) if group_rank == writer_rank: if external_writer_handle is not None: buffer_io = MessageQueue.create_from_handle( external_writer_handle, group_rank ) else: same_node_ranks = [i for i, s in enumerate(status) if s] n_reader = group_world_size - 1 n_local_reader = len(same_node_ranks) - 1 local_reader_ranks = [i for i in same_node_ranks if i != writer_rank] buffer_io = MessageQueue( n_reader=n_reader, n_local_reader=n_local_reader, local_reader_ranks=local_reader_ranks, max_chunk_bytes=max_chunk_bytes, max_chunks=max_chunks, ) handle = buffer_io.export_handle() if isinstance(pg, ProcessGroup): dist.broadcast_object_list( [handle], src=global_ranks[writer_rank], group=pg ) else: pg.broadcast_obj(handle, writer_rank) else: if isinstance(pg, ProcessGroup): recv = [None] dist.broadcast_object_list( recv, src=global_ranks[writer_rank], group=pg ) handle = recv[0] # type: ignore else: handle = pg.broadcast_obj(None, writer_rank) buffer_io = MessageQueue.create_from_handle(handle, group_rank) if blocking: buffer_io.wait_until_ready() return buffer_io
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/pynccl_wrapper.py
vllm/distributed/device_communicators/pynccl_wrapper.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # This file is a pure Python wrapper for the NCCL library. # The main purpose is to use NCCL combined with CUDA graph. # Before writing this script, we tried the following approach: # 1. We tried to use `cupy`, it calls NCCL correctly, but `cupy` itself # often gets stuck when initializing the NCCL communicator. # 2. We tried to use `torch.distributed`, but `torch.distributed.all_reduce` # contains many other potential cuda APIs, that are not allowed during # capturing the CUDA graph. For further details, please check # https://discuss.pytorch.org/t/pytorch-cudagraph-with-nccl-operation-failed/ . # # Another rejected idea is to write a C/C++ binding for NCCL. It is usually # doable, but we often encounter issues related with nccl versions, and need # to switch between different versions of NCCL. See # https://github.com/NVIDIA/nccl/issues/1234 for more details. # A C/C++ binding is not flexible enough to handle this. It requires # recompilation of the code every time we want to switch between different # versions. This current implementation, with a **pure** Python wrapper, is # more flexible. We can easily switch between different versions of NCCL by # changing the environment variable `VLLM_NCCL_SO_PATH`, or the `so_file` # variable in the code. import ctypes import platform from dataclasses import dataclass from typing import Any import torch from torch.distributed import ReduceOp from vllm import envs from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.utils.nccl import find_nccl_library logger = init_logger(__name__) # === export types and functions from nccl to Python === # for the original nccl definition, please check # https://github.com/NVIDIA/nccl/blob/master/src/nccl.h.in ncclResult_t = ctypes.c_int ncclComm_t = ctypes.c_void_p ncclWindow_t = ctypes.c_void_p class ncclUniqueId(ctypes.Structure): _fields_ = [("internal", ctypes.c_byte * 128)] cudaStream_t = ctypes.c_void_p buffer_type = ctypes.c_void_p ncclDataType_t = ctypes.c_int class ncclDataTypeEnum: ncclInt8 = 0 ncclChar = 0 ncclUint8 = 1 ncclInt32 = 2 ncclInt = 2 ncclUint32 = 3 ncclInt64 = 4 ncclUint64 = 5 ncclFloat16 = 6 ncclHalf = 6 ncclFloat32 = 7 ncclFloat = 7 ncclFloat64 = 8 ncclDouble = 8 ncclBfloat16 = 9 ncclNumTypes = 10 @classmethod def from_torch(cls, dtype: torch.dtype) -> int: if dtype == torch.int8: return cls.ncclInt8 if dtype == torch.uint8: return cls.ncclUint8 if dtype == torch.int32: return cls.ncclInt32 if dtype == torch.int64: return cls.ncclInt64 if dtype == torch.float16: return cls.ncclFloat16 if dtype == torch.float32: return cls.ncclFloat32 if dtype == torch.float64: return cls.ncclFloat64 if dtype == torch.bfloat16: return cls.ncclBfloat16 raise ValueError(f"Unsupported dtype: {dtype}") ncclRedOp_t = ctypes.c_int class ncclRedOpTypeEnum: ncclSum = 0 ncclProd = 1 ncclMax = 2 ncclMin = 3 ncclAvg = 4 ncclNumOps = 5 @classmethod def from_torch(cls, op: ReduceOp) -> int: if op == ReduceOp.SUM: return cls.ncclSum if op == ReduceOp.PRODUCT: return cls.ncclProd if op == ReduceOp.MAX: return cls.ncclMax if op == ReduceOp.MIN: return cls.ncclMin if op == ReduceOp.AVG: return cls.ncclAvg raise ValueError(f"Unsupported op: {op}") @dataclass class Function: name: str restype: Any argtypes: list[Any] class NCCLLibrary: exported_functions = [ # const char* ncclGetErrorString(ncclResult_t result) Function("ncclGetErrorString", ctypes.c_char_p, [ncclResult_t]), # ncclResult_t ncclGetVersion(int *version); Function("ncclGetVersion", ncclResult_t, [ctypes.POINTER(ctypes.c_int)]), # ncclResult_t ncclGetUniqueId(ncclUniqueId* uniqueId); Function("ncclGetUniqueId", ncclResult_t, [ctypes.POINTER(ncclUniqueId)]), # ncclResult_t ncclCommInitRank( # ncclComm_t* comm, int nranks, ncclUniqueId commId, int rank); # note that ncclComm_t is a pointer type, so the first argument # is a pointer to a pointer Function( "ncclCommInitRank", ncclResult_t, [ctypes.POINTER(ncclComm_t), ctypes.c_int, ncclUniqueId, ctypes.c_int], ), # ncclResult_t ncclAllReduce( # const void* sendbuff, void* recvbuff, size_t count, # ncclDataType_t datatype, ncclRedOp_t op, ncclComm_t comm, # cudaStream_t stream); # note that cudaStream_t is a pointer type, so the last argument # is a pointer Function( "ncclAllReduce", ncclResult_t, [ buffer_type, buffer_type, ctypes.c_size_t, ncclDataType_t, ncclRedOp_t, ncclComm_t, cudaStream_t, ], ), # ncclResult_t ncclReduce( # const void* sendbuff, void* recvbuff, size_t count, # ncclDataType_t datatype, ncclRedOp_t op, int root, # ncclComm_t comm, cudaStream_t stream); # note that cudaStream_t is a pointer type, so the last argument # is a pointer Function( "ncclReduce", ncclResult_t, [ buffer_type, buffer_type, ctypes.c_size_t, ncclDataType_t, ncclRedOp_t, ctypes.c_int, ncclComm_t, cudaStream_t, ], ), # ncclResult_t ncclAllGather( # const void* sendbuff, void* recvbuff, size_t count, # ncclDataType_t datatype, ncclComm_t comm, # cudaStream_t stream); # note that cudaStream_t is a pointer type, so the last argument # is a pointer Function( "ncclAllGather", ncclResult_t, [ buffer_type, buffer_type, ctypes.c_size_t, ncclDataType_t, ncclComm_t, cudaStream_t, ], ), # ncclResult_t ncclReduceScatter( # const void* sendbuff, void* recvbuff, size_t count, # ncclDataType_t datatype, ncclRedOp_t op, ncclComm_t comm, # cudaStream_t stream); # note that cudaStream_t is a pointer type, so the last argument # is a pointer Function( "ncclReduceScatter", ncclResult_t, [ buffer_type, buffer_type, ctypes.c_size_t, ncclDataType_t, ncclRedOp_t, ncclComm_t, cudaStream_t, ], ), # ncclResult_t ncclSend( # const void* sendbuff, size_t count, ncclDataType_t datatype, # int dest, ncclComm_t comm, cudaStream_t stream); Function( "ncclSend", ncclResult_t, [ buffer_type, ctypes.c_size_t, ncclDataType_t, ctypes.c_int, ncclComm_t, cudaStream_t, ], ), # ncclResult_t ncclRecv( # void* recvbuff, size_t count, ncclDataType_t datatype, # int src, ncclComm_t comm, cudaStream_t stream); Function( "ncclRecv", ncclResult_t, [ buffer_type, ctypes.c_size_t, ncclDataType_t, ctypes.c_int, ncclComm_t, cudaStream_t, ], ), # ncclResult_t ncclBroadcast( # const void* sendbuff, void* recvbuff, size_t count, # ncclDataType_t datatype, int root, ncclComm_t comm, # cudaStream_t stream); Function( "ncclBroadcast", ncclResult_t, [ buffer_type, buffer_type, ctypes.c_size_t, ncclDataType_t, ctypes.c_int, ncclComm_t, cudaStream_t, ], ), # be cautious! this is a collective call, it will block until all # processes in the communicator have called this function. # because Python object destruction can happen in random order, # it is better not to call it at all. # ncclResult_t ncclCommDestroy(ncclComm_t comm); Function("ncclCommDestroy", ncclResult_t, [ncclComm_t]), # ncclResult_t ncclGroupStart(); Function("ncclGroupStart", ncclResult_t, []), # ncclResult_t ncclGroupEnd(); Function("ncclGroupEnd", ncclResult_t, []), # ncclResult_t ncclCommWindowRegister( # ncclComm_t comm, void* buff, size_t size, # ncclWindow_t* win, int winFlags); Function( "ncclCommWindowRegister", ncclResult_t, [ ncclComm_t, buffer_type, ctypes.c_size_t, ctypes.POINTER(ncclWindow_t), ctypes.c_int, ], ), # ncclResult_t ncclCommWindowDeregister( # ncclComm_t comm, ncclWindow_t win); Function("ncclCommWindowDeregister", ncclResult_t, [ncclComm_t, ncclWindow_t]), ] # class attribute to store the mapping from the path to the library # to avoid loading the same library multiple times path_to_library_cache: dict[str, Any] = {} # class attribute to store the mapping from library path # to the corresponding dictionary path_to_dict_mapping: dict[str, dict[str, Any]] = {} def __init__(self, so_file: str | None = None): so_file = so_file or find_nccl_library() try: if so_file not in NCCLLibrary.path_to_dict_mapping: lib = ctypes.CDLL(so_file) NCCLLibrary.path_to_library_cache[so_file] = lib self.lib = NCCLLibrary.path_to_library_cache[so_file] except Exception as e: logger.error( "Failed to load NCCL library from %s. " "It is expected if you are not running on NVIDIA/AMD GPUs." "Otherwise, the nccl library might not exist, be corrupted " "or it does not support the current platform %s. " "If you already have the library, please set the " "environment variable VLLM_NCCL_SO_PATH" " to point to the correct nccl library path.", so_file, platform.platform(), ) raise e if so_file not in NCCLLibrary.path_to_dict_mapping: _funcs: dict[str, Any] = {} for func in NCCLLibrary.exported_functions: try: f = getattr(self.lib, func.name) f.restype = func.restype f.argtypes = func.argtypes _funcs[func.name] = f except AttributeError: if func.name in [ "ncclCommWindowRegister", "ncclCommWindowDeregister", ]: if envs.VLLM_USE_NCCL_SYMM_MEM: logger.warning_once( "The symbol %s is not found in the NCCL " "library %s. To enable VLLM_USE_NCCL_SYMM_MEM " " please update your NCCL version to >= " "2.27.03.", func.name, so_file, ) if current_platform.is_rocm(): # Having an exception here on ROCm platform is # not allowed during graph capturing continue raise NCCLLibrary.path_to_dict_mapping[so_file] = _funcs self._funcs = NCCLLibrary.path_to_dict_mapping[so_file] def ncclGetErrorString(self, result: ncclResult_t) -> str: return self._funcs["ncclGetErrorString"](result).decode("utf-8") def NCCL_CHECK(self, result: ncclResult_t) -> None: if result != 0: error_str = self.ncclGetErrorString(result) raise RuntimeError(f"NCCL error: {error_str}") def ncclGetRawVersion(self) -> int: version = ctypes.c_int() self.NCCL_CHECK(self._funcs["ncclGetVersion"](ctypes.byref(version))) # something like 21903 return version.value def ncclGetVersion(self) -> str: version_str = str(self.ncclGetRawVersion()) # something like 21903 --> "2.19.3" major = version_str[0].lstrip("0") minor = version_str[1:3].lstrip("0") patch = version_str[3:].lstrip("0") return f"{major}.{minor}.{patch}" def ncclGetUniqueId(self) -> ncclUniqueId: unique_id = ncclUniqueId() self.NCCL_CHECK(self._funcs["ncclGetUniqueId"](ctypes.byref(unique_id))) return unique_id def unique_id_from_bytes(self, data: bytes) -> ncclUniqueId: if len(data) != 128: raise ValueError( f"Expected 128 bytes for ncclUniqueId, got {len(data)} bytes" ) unique_id = ncclUniqueId() ctypes.memmove(ctypes.addressof(unique_id.internal), data, 128) return unique_id def ncclCommInitRank( self, world_size: int, unique_id: ncclUniqueId, rank: int ) -> ncclComm_t: comm = ncclComm_t() self.NCCL_CHECK( self._funcs["ncclCommInitRank"]( ctypes.byref(comm), world_size, unique_id, rank ) ) return comm def ncclAllReduce( self, sendbuff: buffer_type, recvbuff: buffer_type, count: int, datatype: int, op: int, comm: ncclComm_t, stream: cudaStream_t, ) -> None: # `datatype` actually should be `ncclDataType_t` # and `op` should be `ncclRedOp_t` # both are aliases of `ctypes.c_int` # when we pass int to a function, it will be converted to `ctypes.c_int` # by ctypes automatically self.NCCL_CHECK( self._funcs["ncclAllReduce"]( sendbuff, recvbuff, count, datatype, op, comm, stream ) ) def ncclReduce( self, sendbuff: buffer_type, recvbuff: buffer_type, count: int, datatype: int, op: int, root: int, comm: ncclComm_t, stream: cudaStream_t, ) -> None: # `datatype` actually should be `ncclDataType_t` # and `op` should be `ncclRedOp_t` # both are aliases of `ctypes.c_int` # when we pass int to a function, it will be converted to `ctypes.c_int` # by ctypes automatically self.NCCL_CHECK( self._funcs["ncclReduce"]( sendbuff, recvbuff, count, datatype, op, root, comm, stream ) ) def ncclReduceScatter( self, sendbuff: buffer_type, recvbuff: buffer_type, count: int, datatype: int, op: int, comm: ncclComm_t, stream: cudaStream_t, ) -> None: # `datatype` actually should be `ncclDataType_t` # and `op` should be `ncclRedOp_t` # both are aliases of `ctypes.c_int` # when we pass int to a function, it will be converted to `ctypes.c_int` # by ctypes automatically self.NCCL_CHECK( self._funcs["ncclReduceScatter"]( sendbuff, recvbuff, count, datatype, op, comm, stream ) ) def ncclAllGather( self, sendbuff: buffer_type, recvbuff: buffer_type, count: int, datatype: int, comm: ncclComm_t, stream: cudaStream_t, ) -> None: # `datatype` actually should be `ncclDataType_t` # which is an aliases of `ctypes.c_int` # when we pass int to a function, it will be converted to `ctypes.c_int` # by ctypes automatically self.NCCL_CHECK( self._funcs["ncclAllGather"]( sendbuff, recvbuff, count, datatype, comm, stream ) ) def ncclSend( self, sendbuff: buffer_type, count: int, datatype: int, dest: int, comm: ncclComm_t, stream: cudaStream_t, ) -> None: self.NCCL_CHECK( self._funcs["ncclSend"](sendbuff, count, datatype, dest, comm, stream) ) def ncclRecv( self, recvbuff: buffer_type, count: int, datatype: int, src: int, comm: ncclComm_t, stream: cudaStream_t, ) -> None: self.NCCL_CHECK( self._funcs["ncclRecv"](recvbuff, count, datatype, src, comm, stream) ) def ncclBroadcast( self, sendbuff: buffer_type, recvbuff: buffer_type, count: int, datatype: int, root: int, comm: ncclComm_t, stream: cudaStream_t, ) -> None: self.NCCL_CHECK( self._funcs["ncclBroadcast"]( sendbuff, recvbuff, count, datatype, root, comm, stream ) ) def ncclCommDestroy(self, comm: ncclComm_t) -> None: self.NCCL_CHECK(self._funcs["ncclCommDestroy"](comm)) def ncclGroupStart(self) -> None: self.NCCL_CHECK(self._funcs["ncclGroupStart"]()) def ncclGroupEnd(self) -> None: self.NCCL_CHECK(self._funcs["ncclGroupEnd"]()) def ncclCommWindowRegister( self, comm: ncclComm_t, buff: buffer_type, size: int, win_flags: int ) -> ncclWindow_t: window = ncclWindow_t() self.NCCL_CHECK( self._funcs["ncclCommWindowRegister"]( comm, buff, size, ctypes.byref(window), win_flags ) ) return window def ncclCommWindowDeregister(self, comm: ncclComm_t, window: ncclWindow_t) -> None: self.NCCL_CHECK(self._funcs["ncclCommWindowDeregister"](comm, window)) __all__ = [ "NCCLLibrary", "ncclDataTypeEnum", "ncclRedOpTypeEnum", "ncclUniqueId", "ncclComm_t", "cudaStream_t", "buffer_type", ]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/mnnvl_compat.py
vllm/distributed/device_communicators/mnnvl_compat.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch.distributed as dist from flashinfer.comm.mnnvl import CommBackend as CommBackend from vllm.utils.flashinfer import has_flashinfer_all2all assert has_flashinfer_all2all(), "Flashinfer alltoallv module cannot be found" class CustomCommunicator(CommBackend): def __init__(self, group): self._group = group def Get_rank(self) -> int: return self._group.rank() def Get_size(self) -> int: return self._group.size() def allgather(self, data: int): gathered = [None] * self.Get_size() dist.all_gather_object(gathered, data, group=self._group) return gathered def Split(self, color: int, key: int) -> "CustomCommunicator": return self
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/shm_object_storage.py
vllm/distributed/device_communicators/shm_object_storage.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import pickle from abc import ABC, abstractmethod from collections.abc import Callable, Iterable from contextlib import contextmanager from dataclasses import dataclass from itertools import chain from multiprocessing import shared_memory from multiprocessing.synchronize import Lock as LockType from typing import Any from unittest.mock import patch import torch from vllm.logger import init_logger logger = init_logger(__name__) class SingleWriterShmRingBuffer: """ A single-writer, multiple-reader ring buffer implementation using shared memory. This class provides a thread-safe ring buffer where one process can write data while multiple processes/threads can read from it. Architecture: - Uses shared memory for cross-process communication - Maintains metadata for each allocated buffer chunk in the writer process - Supports custom "is_free_fn" functions to determine when buffers can be reused - Each buffer chunk contains: `[4-byte id][4-byte size][actual_data]` Key Concepts: - monotonic_id_start/end: Track the range of active buffer IDs - data_buffer_start/end: Track the physical memory range in use - Automatic wraparound when reaching buffer end - Lazy garbage collection based on is_free_fn checks Example Usage Scenarios: Scenario 1: Simple Linear Allocation ``` Buffer size: 100 bytes Initial state: [................................................. ] ^start=end(0) After allocating 20 bytes (id=0): [id:0|size:20|data........][...................................] ^start(0) ^end(28) After allocating 30 bytes (id=1): [id:0|size:20|data........][id:1|size:30|data..............][..] ^start(0) ^end(66) ``` Scenario 2: Memory Reclamation ``` Before freeing (both buffers still in use): [id:0|size:20|data........][id:1|size:30|data..............][..] ^start(0) ^end(66) After id:0 is marked free by readers: [FREED.................... ][id:1|size:30|data..............][..] ^start(28) ^end(66) After both are freed: [FREED..............................................][..] ^start=end(66) ``` Scenario 3: Wraparound Allocation (continuing from Scenario 2) ``` Starting from after memory reclamation in Scenario 2: [FREED..............................................][..] ^start=end(66) Allocate 40 bytes (id=2) - only 34 bytes available at end, so wraparound: [id:2|size:40|data........................][FREED.............][..] ^end(148) ^start(66) ``` Scenario 4: Error Handling - Out of Space ``` Starting from after wraparound allocation in Scenario 3: [id:2|size:40|data........................][FREED.............][..] ^end(148) ^start(66) Trying to allocate 20 more bytes: occupied_size_new = end + size - start = 148 + 28 - 66 > buffer_size(100) -> Raises MemoryError: "Not enough space in the data buffer" ``` Thread Safety: - Single writer: Only one process/thread should write (allocate_buf) - Multiple readers: Multiple processes/threads can read (access_buf) - Reader synchronization handled by is_free_fn callback - Writer handles garbage collection (free_buf) based on reader feedback Memory Layout per Buffer Chunk: `[4-byte monotonic_id][4-byte chunk_size][actual_data...]` ^metadata_start ^data_start The monotonic_id ensures data integrity - readers can verify they're accessing the correct data even after buffer wraparound or reuse. """ def __init__( self, data_buffer_size: int, name: str | None = None, create: bool = False, ): self.data_buffer_size = data_buffer_size self.is_writer = create self.ID_NBYTES = 4 self.ID_MAX = 2**31 # exclusive, so 2**31 - 1 is the max value self.SIZE_NBYTES = 4 # 4 bytes for id, 4 bytes for buffer size self.MD_SIZE = self.ID_NBYTES + self.SIZE_NBYTES self.monotonic_id_end = 0 self.monotonic_id_start = 0 self.data_buffer_start = 0 self.data_buffer_end = 0 if create: # we are creating a buffer self.metadata: dict[int, int] = {} # monotonic_id -> start address self.shared_memory = shared_memory.SharedMemory( create=True, size=self.data_buffer_size, name=name ) else: # we are opening an existing buffer # fix to https://stackoverflow.com/q/62748654/9191338 # Python incorrectly tracks shared memory even if it is not # created by the process. The following patch is a workaround. with patch( "multiprocessing.resource_tracker.register", lambda *args, **kwargs: None, ): self.shared_memory = shared_memory.SharedMemory(name=name) # See https://docs.python.org/3/library/multiprocessing.shared_memory.html # noqa # Some platforms allocate memory based on page size, # so the shared memory block size may be larger or equal # to the requested size. The size parameter is ignored # when attaching to an existing block. assert self.shared_memory.size >= self.data_buffer_size logger.debug( "Shared memory created/opened with name: %s, size: %d", self.shared_memory.name, self.data_buffer_size, ) def handle(self): return ( self.data_buffer_size, self.shared_memory.name, ) def clear(self) -> None: """Clear the ring buffer.""" assert self.is_writer, "Only the writer can clear the buffer." self.metadata.clear() self.monotonic_id_end = 0 self.monotonic_id_start = 0 self.data_buffer_start = 0 self.data_buffer_end = 0 def __del__(self): if hasattr(self, "shared_memory"): self.shared_memory.close() if self.is_writer: self.shared_memory.unlink() def int2byte(self, integer: int) -> bytes: """Convert an integer to bytes.""" return integer.to_bytes(self.ID_NBYTES, "little", signed=True) def byte2int(self, byte_data: bytes) -> int: """Convert bytes back to an integer.""" return int.from_bytes(byte_data, "little", signed=True) def allocate_buf(self, size: int) -> tuple[int, int]: """ Allocate a buffer `MD_SIZE` + `size` bytes in the shared memory. Memory layout: `[4-byte monotonic_id][4-byte size][buffer data...]` """ assert self.is_writer, "Only the writer can allocate buffers." assert size > 0, "Size must be greater than 0" size += self.MD_SIZE # add metadata size to the buffer size # reset to beginning if the buffer does have enough contiguous space buffer_end_reset = self.data_buffer_end % self.data_buffer_size if buffer_end_reset + size > self.data_buffer_size: buffer_end_reset = ( self.data_buffer_end // self.data_buffer_size + 1 ) * self.data_buffer_size else: # no reset needed buffer_end_reset = self.data_buffer_end # check if we have enough space in the data buffer # i.e. if the new end (self.data_buffer_end + size) # exceeds the start of the data buffer occupied_size_new = buffer_end_reset + size - self.data_buffer_start if occupied_size_new > self.data_buffer_size: raise MemoryError( "Not enough space in the data buffer, " "try calling free_buf() to free up space" ) self.data_buffer_end = buffer_end_reset # first 4 bytes as the monotonic id buf_idx = self.data_buffer_end % self.data_buffer_size self.shared_memory.buf[buf_idx : buf_idx + self.ID_NBYTES] = self.int2byte( self.monotonic_id_end ) # next 4 bytes as the size of the data buffer self.shared_memory.buf[buf_idx + self.ID_NBYTES : buf_idx + self.MD_SIZE] = ( self.int2byte(size) ) # record metadata self.metadata[self.monotonic_id_end % self.ID_MAX] = self.data_buffer_end # update buffer and monotonic id indices current_buffer_end = self.data_buffer_end current_id_end = self.monotonic_id_end self.data_buffer_end += size self.monotonic_id_end = (self.monotonic_id_end + 1) % self.ID_MAX return current_buffer_end, current_id_end @contextmanager def access_buf(self, address: int): buf_idx = address % self.data_buffer_size # read metadata metadata_buff = self.shared_memory.buf[buf_idx : buf_idx + self.MD_SIZE] id = self.byte2int(metadata_buff[: self.ID_NBYTES]) size = self.byte2int(metadata_buff[self.ID_NBYTES : self.MD_SIZE]) # yield the data buffer and metadata data_buff = self.shared_memory.buf[buf_idx + self.MD_SIZE : buf_idx + size] with ( memoryview(data_buff) as data_view, ): yield data_view, (id, size) def free_buf( self, is_free_fn: Callable[[int, memoryview], bool], nbytes: int | None = None, ) -> Iterable[int]: """ Free a buffer of the given size. This is a no-op in shared memory, but we need to keep track of the metadata. If freed memory spreads across the end and start of the ring buffer, the actual freed memory will be in two segments. In this case there still might not be a contiguous space of `nbytes` available. Args: nbytes (int, optional): The size of the buffer to free. If None, frees the maximum size of the ring buffer. """ assert self.is_writer, "Only the writer can free buffers." logger.debug( "Freeing up space in the ring buffer, " "monotonic_id_start: %d, monotonic_id_end: %d", self.monotonic_id_start, self.monotonic_id_end, ) monotonic_id_before = self.monotonic_id_start # if nbytes is None, free up the maximum size of the ring buffer if nbytes is None: nbytes = self.data_buffer_size freed_bytes = 0 while self.monotonic_id_start in self.metadata and freed_bytes < nbytes: address = self.metadata[self.monotonic_id_start] with self.access_buf(address) as (data_buff, metadata): if is_free_fn(self.monotonic_id_start, data_buff): # check passed, we can free the buffer del self.metadata[self.monotonic_id_start] self.monotonic_id_start = ( self.monotonic_id_start + 1 ) % self.ID_MAX if self.monotonic_id_start in self.metadata: # pointing to the start addr of next allocation self.data_buffer_start += ( self.metadata[self.monotonic_id_start] - self.data_buffer_start ) % self.data_buffer_size else: # no remaining allocation, reset to zero self.data_buffer_start = self.data_buffer_end = 0 freed_bytes += metadata[1] else: # there are still readers, we cannot free the buffer break logger.debug( "Freed %d bytes from the ring buffer, " "monotonic_id_start: %d, monotonic_id_end: %d", freed_bytes, self.monotonic_id_start, self.monotonic_id_end, ) # buffer wrap around if self.data_buffer_start >= self.data_buffer_size: self.data_buffer_start -= self.data_buffer_size self.data_buffer_end -= self.data_buffer_size monotonic_id_after = self.monotonic_id_start # id wrap around if monotonic_id_after >= monotonic_id_before: return range(monotonic_id_before, monotonic_id_after) else: return chain( range(monotonic_id_before, self.ID_MAX), range(0, monotonic_id_after) ) class ObjectSerde(ABC): @abstractmethod def serialize(self, value: Any) -> tuple[Any, int, bytes, int]: """Serialize an object to bytes.""" raise NotImplementedError @abstractmethod def deserialize(self, data: memoryview) -> Any: """Deserialize bytes back to an object.""" raise NotImplementedError class MsgpackSerde(ObjectSerde): def __init__(self): # Delayed import to avoid circular dependency from vllm.multimodal.inputs import MultiModalKwargsItem from vllm.v1.serial_utils import MsgpackDecoder, MsgpackEncoder self.encoder = MsgpackEncoder() self.tensor_decoder = MsgpackDecoder(torch.Tensor, share_mem=False) self.mm_decoder = MsgpackDecoder(MultiModalKwargsItem, share_mem=False) self._mm_kwargs_item_cls = MultiModalKwargsItem def serialize(self, value: Any) -> tuple[bytes | list[bytes], int, bytes, int]: len_arr = None if isinstance(value, (torch.Tensor, self._mm_kwargs_item_cls)): type_name = type(value).__name__ value = self.encoder.encode(value) len_arr = [len(s) for s in value] nbytes = sum(len_arr) else: value = pickle.dumps(value, protocol=pickle.HIGHEST_PROTOCOL) type_name = type(value).__name__ nbytes = len(value) object_metadata = (type_name, nbytes, len_arr) serialized_metadata = pickle.dumps( object_metadata, protocol=pickle.HIGHEST_PROTOCOL ) return value, nbytes, serialized_metadata, len(serialized_metadata) def deserialize(self, data_view: memoryview) -> Any: # pickle.loads do not read past the end of a pickled object # within a large buffer, so we can skip storing the metadata size type_name, nbytes, len_arr = pickle.loads(data_view) serialized_data = data_view[-nbytes:] if type_name == torch.Tensor.__name__: obj = [] start_idx = 0 for length in len_arr: item_bytes = serialized_data[start_idx : start_idx + length] obj.append(item_bytes) start_idx += length obj = self.tensor_decoder.decode(obj) elif type_name == self._mm_kwargs_item_cls.__name__: obj = [] start_idx = 0 for length in len_arr: item_bytes = serialized_data[start_idx : start_idx + length] obj.append(item_bytes) start_idx += length obj = self.mm_decoder.decode(obj) elif type_name == bytes.__name__: obj = pickle.loads(serialized_data) else: raise ValueError(f"Unsupported object type '{type_name}' in metadata") return obj @dataclass class ShmObjectStorageHandle: max_object_size: int n_readers: int ring_buffer_handle: tuple[int, str] serde_class: type[ObjectSerde] reader_lock: LockType | None class SingleWriterShmObjectStorage: """ A single-writer, multiple-reader object storage system built on top of a shared memory ring buffer. Provides key-value storage with automatic memory management and cross-process serialization support. This storage system follows a FIFO (First-In-First-Out) eviction policy where the oldest objects are automatically freed when memory runs low. Memory is reclaimed based on reader reference counting - objects are only freed when all readers have finished accessing them. Architecture: - Single writer process can put(key, value) objects - Multiple reader processes can get(address, monotonic_id) objects - Built on SingleWriterShmRingBuffer for efficient shared memory management - Thread-safe operations with reader synchronization via locks Key Features: - FIFO Eviction: Oldest objects are evicted first when memory is full - Reference Counting: Objects are only freed when no readers are accessing them - Duplicate Key Handling: Existing keys are not overwritten, just re-referenced - Customized Serialization: By default uses Msgpack for efficient serialization of Python objects, but can be extended for custom types - Cross-Process Safety: Uses shared memory with proper synchronization - Automatic Cleanup: Garbage collection happens transparently during allocation Memory Layout per Object: `[4-byte reference_count][metadata_size][serialized_object_data]` Thread Safety: - Writer operations (put, clear) are single-threaded by design - Reader operations (get) are thread-safe with lock-based reference counting - Memory reclamation is handled exclusively by the writer process """ def __init__( self, max_object_size: int, n_readers: int, ring_buffer: SingleWriterShmRingBuffer, serde_class: type[ObjectSerde] = MsgpackSerde, reader_lock: LockType | None = None, ): """ Initialize the object storage. Args: max_object_size: Maximum size for a single object in bytes. n_readers: Number of reader processes that can access the storage. ring_buffer: The shared memory ring buffer for storing objects. serde_class: Serializer/deserializer for objects. reader_lock: Optional lock for synchronizing reader access. Raises: ValueError: If reader_lock is None for readers. """ self.max_object_size = max_object_size self.n_readers = n_readers self.serde_class = serde_class self.ser_de = serde_class() self.ring_buffer = ring_buffer self.is_writer = self.ring_buffer.is_writer self.flag_bytes = 4 # for in-use flag if self.is_writer: # Key-value mapping: key -> (address, monotonic_id) self.key_index: dict[str, tuple[int, int]] = {} # Reverse mapping: monotonic_id -> key self.id_index: dict[int, str] = {} # Writer flag to track in-use status: monotonic_id -> count self.writer_flag: dict[int, int] = {} else: if reader_lock is None: raise ValueError("Lock must be provided for readers.") self._reader_lock = reader_lock def clear(self) -> None: """Clear the object storage.""" if self.is_writer: self.ring_buffer.clear() self.key_index.clear() self.id_index.clear() self.writer_flag.clear() logger.debug("Object storage cleared and reinitialized.") def copy_to_buffer( self, data: bytes | list[bytes], data_bytes: int, metadata: bytes, md_bytes: int, data_view: memoryview, ) -> None: data_view[self.flag_bytes : self.flag_bytes + md_bytes] = metadata if isinstance(data, bytes): data_view[-data_bytes:] = data elif isinstance(data, list): start_idx = self.flag_bytes + md_bytes for item_bytes in data: item_size = len(item_bytes) data_view[start_idx : start_idx + item_size] = item_bytes start_idx += item_size else: raise ValueError(f"Unsupported data type for serialization: {type(data)}") def increment_writer_flag(self, id: int) -> None: """Set the in-use flag for the writer.""" self.writer_flag[id] = self.writer_flag.get(id, 0) + 1 def increment_reader_flag(self, data_view: memoryview) -> None: """Set the in-use flag for the reader.""" # >0 for in-use flag reader_count = self.ring_buffer.byte2int(data_view) data_view[:] = self.ring_buffer.int2byte(reader_count + 1) def free_unused(self) -> None: """Free unused buffers in the ring buffer.""" # try to free up 2*max_object_size bytes of space in the ring buffer, # since the buffer might be fragmented freed_ids = self.ring_buffer.free_buf( self.default_is_free_check, 2 * self.max_object_size ) # update the metadata after freeing up space for freed_id in freed_ids: key_to_free = self.id_index[freed_id] del self.key_index[key_to_free] del self.id_index[freed_id] del self.writer_flag[freed_id] def is_cached(self, key: str) -> bool: """ Check if the object with the given key is cached. """ return key in self.key_index def get_cached(self, key: str) -> tuple[int, int]: """ Get the cached object by key if it exists. """ address, monotonic_id = self.key_index[key] self.increment_writer_flag(monotonic_id) return address, monotonic_id def put(self, key: str, value: Any) -> tuple[int, int]: """ Store a key-value pair in the object storage. Attempts to free max_object_size bytes using FIFO order when the ring buffer runs out of space during a put() operation. Args: key: String key to identify the object value: Any serializable Python object Raises: MemoryError: If there's not enough space in the buffer ValueError: If the serialized object is too large ValueError: If the key already exists in the storage """ if key in self.key_index: raise ValueError(f"Key '{key}' already exists in the storage.") object_data, data_bytes, object_metadata, md_bytes = self.ser_de.serialize( value ) buffer_size = self.flag_bytes + data_bytes + md_bytes # Sanity checks if buffer_size > self.max_object_size: raise ValueError( f"Serialized object size ({buffer_size} bytes) exceeds " f"max object size ({self.max_object_size} bytes)" ) # Allocate new buffer try: address, monotonic_id = self.ring_buffer.allocate_buf(buffer_size) except MemoryError: self.free_unused() # try again after freeing up space address, monotonic_id = self.ring_buffer.allocate_buf(buffer_size) # Write data to buffer with self.ring_buffer.access_buf(address) as (data_view, metadata): data_view[: self.flag_bytes] = self.ring_buffer.int2byte(0) self.copy_to_buffer( object_data, data_bytes, object_metadata, md_bytes, data_view ) self.increment_writer_flag(monotonic_id) # Update key index self.key_index[key] = (address, monotonic_id) self.id_index[monotonic_id] = key return address, monotonic_id def get(self, address: int, monotonic_id: int) -> Any: # Read data from buffer with self.ring_buffer.access_buf(address) as (data_view, buf_metadata): # check id from metadata if buf_metadata[0] != monotonic_id: raise ValueError( f"Data for address:id '{address}:{monotonic_id}'" " has been modified or is invalid." ) obj = self.ser_de.deserialize(data_view[self.flag_bytes :]) # decrease the in-use flag for reader reads if self._reader_lock is not None: with self._reader_lock: self.increment_reader_flag(data_view[: self.flag_bytes]) else: # if self._reader_lock is None, it means we are the writer # in this case, we do not need to decrease the reader count assert self.is_writer return obj def touch( self, key: str, address: int = 0, monotonic_id: int = 0, ) -> None: """ Touch an existing cached item to update its eviction status. For writers (ShmObjectStoreSenderCache): Increment writer_flag For readers (ShmObjectStoreReceiverCache): Increment reader_count Args: key: String key of the object to touch address: Address of the object (only for readers) monotonic_id: Monotonic ID of the object (only for readers) """ if self._reader_lock is None: if key not in self.key_index: return None address, monotonic_id = self.key_index[key] # Writer side: increment writer_flag to raise eviction threshold self.increment_writer_flag(monotonic_id) else: with ( self._reader_lock, self.ring_buffer.access_buf(address) as (data_view, _), ): reader_count = self.ring_buffer.byte2int(data_view[: self.flag_bytes]) # NOTE(Long): # Avoid increasing flag on newly added item (sync with sender) # Since when a new item is added # pre-touch has no effect on writer side if reader_count >= self.n_readers: self.increment_reader_flag(data_view[: self.flag_bytes]) def handle(self): """Get handle for sharing across processes.""" return ShmObjectStorageHandle( max_object_size=self.max_object_size, n_readers=self.n_readers, ring_buffer_handle=self.ring_buffer.handle(), serde_class=self.serde_class, reader_lock=self._reader_lock, ) @staticmethod def create_from_handle( handle: ShmObjectStorageHandle, ) -> "SingleWriterShmObjectStorage": logger.debug("Creating storage from handle: %s", handle) ring_buffer = SingleWriterShmRingBuffer(*handle.ring_buffer_handle) return SingleWriterShmObjectStorage( max_object_size=handle.max_object_size, n_readers=handle.n_readers, ring_buffer=ring_buffer, serde_class=handle.serde_class, reader_lock=handle.reader_lock, ) def default_is_free_check(self, id: int, buf: memoryview) -> bool: """ Default is_free function that checks if the first 4 bytes are zero. This indicates that the buffer is free. """ reader_count = int.from_bytes(buf[0:4], "little", signed=True) writer_count = self.writer_flag[id] return reader_count >= writer_count * self.n_readers
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/pynccl.py
vllm/distributed/device_communicators/pynccl.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # ===================== import region ===================== import torch import torch.distributed as dist from torch.distributed import ProcessGroup, ReduceOp import vllm.envs as envs from vllm.distributed.device_communicators.pynccl_wrapper import ( NCCLLibrary, buffer_type, cudaStream_t, ncclComm_t, ncclDataTypeEnum, ncclRedOpTypeEnum, ncclUniqueId, ) from vllm.distributed.utils import StatelessProcessGroup from vllm.logger import init_logger from vllm.utils.torch_utils import current_stream logger = init_logger(__name__) _NCCL_SYMM_OPS_REGISTERED = False def register_nccl_symmetric_ops(pynccl_comm): from vllm.distributed.device_communicators.pynccl_allocator import ( nccl_symm_mem_context, ) from vllm.utils.torch_utils import direct_register_custom_op global _NCCL_SYMM_OPS_REGISTERED if _NCCL_SYMM_OPS_REGISTERED: return _NCCL_SYMM_OPS_REGISTERED = True def all_reduce_symmetric_with_copy_impl(input_tensor: torch.Tensor) -> torch.Tensor: with nccl_symm_mem_context(pynccl_comm): symm_input = torch.empty_like(input_tensor) symm_output = torch.empty_like(input_tensor) symm_input.copy_(input_tensor) symm_output = pynccl_comm.all_reduce(symm_input, symm_output) return symm_output def all_reduce_symmetric_with_copy_fake(input_tensor: torch.Tensor) -> torch.Tensor: return torch.empty_like(input_tensor) direct_register_custom_op( op_name="all_reduce_symmetric_with_copy", op_func=all_reduce_symmetric_with_copy_impl, fake_impl=all_reduce_symmetric_with_copy_fake, ) class PyNcclCommunicator: def __init__( self, group: ProcessGroup | StatelessProcessGroup, device: int | str | torch.device, library_path: str | None = None, ): """ Args: group: the process group to work on. If None, it will use the default process group. device: the device to bind the PyNcclCommunicator to. If None, it will be bound to f"cuda:{local_rank}". library_path: the path to the NCCL library. If None, it will use the default library path. It is the caller's responsibility to make sure each communicator is bind to a unique device. """ if not isinstance(group, StatelessProcessGroup): assert dist.is_initialized() assert dist.get_backend(group) != dist.Backend.NCCL, ( "PyNcclCommunicator should be attached to a non-NCCL group." ) # note: this rank is the rank in the group self.rank = dist.get_rank(group) self.world_size = dist.get_world_size(group) else: self.rank = group.rank self.world_size = group.world_size self.group = group # if world_size == 1, no need to create communicator if self.world_size == 1 or envs.VLLM_DISABLE_PYNCCL: self.available = False self.disabled = True return try: self.nccl = NCCLLibrary(library_path) except Exception: # disable because of missing NCCL library # e.g. in a non-GPU environment self.available = False self.disabled = True return self.available = True self.disabled = False self.nccl_version = self.nccl.ncclGetRawVersion() if self.rank == 0: # get the unique id from NCCL self.unique_id = self.nccl.ncclGetUniqueId() logger.info_once( "vLLM is using nccl==%s", self.nccl.ncclGetVersion(), scope="local" ) else: # construct an empty unique id self.unique_id = ncclUniqueId() if not isinstance(group, StatelessProcessGroup): tensor = torch.ByteTensor(list(self.unique_id.internal)) ranks = dist.get_process_group_ranks(group) # arg `src` in `broadcast` is the global rank dist.broadcast(tensor, src=ranks[0], group=group) byte_list = tensor.tolist() for i, byte in enumerate(byte_list): self.unique_id.internal[i] = byte else: self.unique_id = group.broadcast_obj(self.unique_id, src=0) if isinstance(device, int): device = torch.device(f"cuda:{device}") elif isinstance(device, str): device = torch.device(device) # now `device` is a `torch.device` object assert isinstance(device, torch.device) self.device = device # nccl communicator and stream will use this device # `torch.cuda.device` is a context manager that changes the # current cuda device to the specified one with torch.cuda.device(device): self.comm: ncclComm_t = self.nccl.ncclCommInitRank( self.world_size, self.unique_id, self.rank ) stream = current_stream() # A small all_reduce for warmup. data = torch.zeros(1, device=device) self.all_reduce(data) stream.synchronize() del data def all_reduce( self, in_tensor: torch.Tensor, out_tensor: torch.Tensor = None, op: ReduceOp = ReduceOp.SUM, stream=None, ) -> torch.Tensor: if self.disabled: return None # nccl communicator created on a specific device # will only work on tensors on the same device # otherwise it will cause "illegal memory access" assert in_tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {in_tensor.device}" ) if out_tensor is None: out_tensor = torch.empty_like(in_tensor) if stream is None: stream = current_stream() self.nccl.ncclAllReduce( buffer_type(in_tensor.data_ptr()), buffer_type(out_tensor.data_ptr()), in_tensor.numel(), ncclDataTypeEnum.from_torch(in_tensor.dtype), ncclRedOpTypeEnum.from_torch(op), self.comm, cudaStream_t(stream.cuda_stream), ) return out_tensor def all_gather( self, output_tensor: torch.Tensor, input_tensor: torch.Tensor, stream=None ): if self.disabled: return # nccl communicator created on a specific device # will only work on tensors on the same device # otherwise it will cause "illegal memory access" assert input_tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {input_tensor.device}" ) if stream is None: stream = current_stream() self.nccl.ncclAllGather( buffer_type(input_tensor.data_ptr()), buffer_type(output_tensor.data_ptr()), input_tensor.numel(), ncclDataTypeEnum.from_torch(input_tensor.dtype), self.comm, cudaStream_t(stream.cuda_stream), ) def all_gatherv( self, output_tensor: torch.Tensor, input_tensor: torch.Tensor, sizes: list[int], stream=None, ): if self.disabled: return # nccl communicator created on a specific device # will only work on tensors on the same device # otherwise it will cause "illegal memory access" assert input_tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {input_tensor.device}" ) if stream is None: stream = current_stream() assert output_tensor.shape[0] == sum(sizes) split_offset = 0 self.nccl.ncclGroupStart() for root, split_size in enumerate(sizes): dst_slice = output_tensor[split_offset : split_offset + split_size] self.nccl.ncclBroadcast( buffer_type(input_tensor.data_ptr()), buffer_type(dst_slice.data_ptr()), dst_slice.numel(), ncclDataTypeEnum.from_torch(input_tensor.dtype), root, self.comm, cudaStream_t(stream.cuda_stream), ) split_offset += split_size self.nccl.ncclGroupEnd() def reduce_scatter( self, output_tensor: torch.Tensor, input_tensor: torch.Tensor, op: ReduceOp = ReduceOp.SUM, stream=None, ): if self.disabled: return # nccl communicator created on a specific device # will only work on tensors on the same device # otherwise it will cause "illegal memory access" assert input_tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {input_tensor.device}" ) if stream is None: stream = current_stream() self.nccl.ncclReduceScatter( buffer_type(input_tensor.data_ptr()), buffer_type(output_tensor.data_ptr()), output_tensor.numel(), ncclDataTypeEnum.from_torch(input_tensor.dtype), ncclRedOpTypeEnum.from_torch(op), self.comm, cudaStream_t(stream.cuda_stream), ) def reduce_scatterv( self, output_tensor: torch.Tensor, input_tensor: torch.Tensor, sizes: list[int], op: ReduceOp = ReduceOp.SUM, stream=None, ): if self.disabled: return # nccl communicator created on a specific device # will only work on tensors on the same device # otherwise it will cause "illegal memory access" assert input_tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {input_tensor.device}" ) if stream is None: stream = current_stream() split_offset = 0 self.nccl.ncclGroupStart() for root, split_size in enumerate(sizes): chunk = input_tensor[split_offset : split_offset + split_size, ...] self.nccl.ncclReduce( buffer_type(chunk.data_ptr()), buffer_type(output_tensor.data_ptr()), chunk.numel(), ncclDataTypeEnum.from_torch(input_tensor.dtype), ncclRedOpTypeEnum.from_torch(op), root, self.comm, cudaStream_t(stream.cuda_stream), ) split_offset += split_size self.nccl.ncclGroupEnd() def send(self, tensor: torch.Tensor, dst: int, stream=None): if self.disabled: return assert tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {tensor.device}" ) if stream is None: stream = current_stream() self.nccl.ncclSend( buffer_type(tensor.data_ptr()), tensor.numel(), ncclDataTypeEnum.from_torch(tensor.dtype), dst, self.comm, cudaStream_t(stream.cuda_stream), ) def recv(self, tensor: torch.Tensor, src: int, stream=None): if self.disabled: return assert tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {tensor.device}" ) if stream is None: stream = current_stream() self.nccl.ncclRecv( buffer_type(tensor.data_ptr()), tensor.numel(), ncclDataTypeEnum.from_torch(tensor.dtype), src, self.comm, cudaStream_t(stream.cuda_stream), ) def broadcast(self, tensor: torch.Tensor, src: int, stream=None): if self.disabled: return assert tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {tensor.device}" ) if stream is None: stream = current_stream() if src == self.rank: sendbuff = buffer_type(tensor.data_ptr()) # NCCL requires the sender also to have a receive buffer recvbuff = buffer_type(tensor.data_ptr()) else: sendbuff = buffer_type() recvbuff = buffer_type(tensor.data_ptr()) self.nccl.ncclBroadcast( sendbuff, recvbuff, tensor.numel(), ncclDataTypeEnum.from_torch(tensor.dtype), src, self.comm, cudaStream_t(stream.cuda_stream), ) def group_start(self): self.nccl.ncclGroupStart() def group_end(self): self.nccl.ncclGroupEnd() def register_comm_window(self, tensor: torch.Tensor): return self.nccl.ncclCommWindowRegister( self.comm, buffer_type(tensor.data_ptr()), tensor.numel() * tensor.element_size(), 1, ) def register_comm_window_raw(self, ptr: int, size: int): return self.nccl.ncclCommWindowRegister(self.comm, buffer_type(ptr), size, 1) def deregister_comm_window(self, window): return self.nccl.ncclCommWindowDeregister(self.comm, window)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/quick_all_reduce.py
vllm/distributed/device_communicators/quick_all_reduce.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from enum import Enum import torch import torch.distributed as dist from torch.distributed import ProcessGroup import vllm.envs as envs from vllm import _custom_ops as ops from vllm.config import get_current_vllm_config from vllm.distributed.parallel_state import in_the_same_node_as from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.utils.torch_utils import cuda_device_count_stateless logger = init_logger(__name__) try: ops.qr_max_size() quick_ar = True except Exception: # For CPUs and CUDA quick_ar = False def is_weak_contiguous(inp: torch.Tensor): return inp.is_contiguous() or ( inp.storage().nbytes() - inp.storage_offset() * inp.element_size() == inp.numel() * inp.element_size() ) class QuickReduceRegime(Enum): FP = 0 INT8 = 1 INT6 = 2 INT4 = 3 NONE = 4 MB = 1024 * 1024 class QuickAllReduce: _SUPPORTED_WORLD_SIZES = [2, 4, 8] _SUPPORTED_DTYPES = [torch.float16, torch.bfloat16] # The following data is based on kernel tests. # In this order [FP, INT8, INT6, INT4]. _QR_MIN_SIZE = { (torch.float16, 2): [1 * MB, 2 * MB, 2 * MB, 1 * MB], (torch.float16, 4): [1 * MB, 16 * MB, 4 * MB, 2 * MB], (torch.float16, 8): [16 * MB, 4 * MB, 4 * MB, 2 * MB], (torch.bfloat16, 2): [2 * MB, 8 * MB, 8 * MB, 8 * MB], (torch.bfloat16, 4): [8 * MB, 64 * MB, 64 * MB, 16 * MB], (torch.bfloat16, 8): [16 * MB, 2048 * MB, 2048 * MB, 2048 * MB], } def __init__(self, group: ProcessGroup, device: int | str | torch.device) -> None: """ Custom allreduce provides non-destructive acceleration and is available for CUDA and ROCm MI300 series. Custom quick allreduce leverages quantization for further acceleration on ROCm. It currently supports Q8, Q6, and Q4 quantization formats and FP(float16, bfloat16). Quick allreduce is designed as a complement to custom allreduce. Its initialization requires even stricter conditions. Only the ROCm MI300 series is supported for quick allreduce at this time. Args: group: the process group to work on. If None, it will use the default process group. device: the device to bind the CustomAllreduce to. If None, it will be bound to f"cuda:{local_rank}". It is the caller's responsibility to make sure each communicator is bind to a unique device, and all communicators in this group are in the same node. """ self.disabled = True if not self._rocm_arch_available(): logger.debug( "Custom quick allreduce is only supported on ROCm MI300 series." ) return if not quick_ar: # disable because of missing quick reduce library # e.g. in a cuda environment logger.info( "Custom quick allreduce is disabled because " "of missing custom quick allreduce library" ) return self.group = group assert dist.get_backend(group) != dist.Backend.NCCL, ( "Custom quick allreduce should be attached to a non-NCCL group." ) if not all(in_the_same_node_as(group, source_rank=0)): # No need to initialize custom quick allreduce for # multi-node case. logger.warning( "Custom quick allreduce is disabled because this " "process group spans across nodes." ) return rank = dist.get_rank(group=self.group) world_size = dist.get_world_size(group=self.group) self.rank = rank self.world_size = world_size if world_size == 1: # No need to initialize QuickReduce for single GPU case. return if world_size not in QuickAllReduce._SUPPORTED_WORLD_SIZES: logger.warning( "Custom quick allreduce is disabled due to an " "unsupported world size: %d. Supported world sizes: %s.", world_size, str(QuickAllReduce._SUPPORTED_WORLD_SIZES), ) return if isinstance(device, int): device = torch.device(f"cuda:{device}") elif isinstance(device, str): device = torch.device(device) assert isinstance(device, torch.device) self.device = device cuda_visible_devices = envs.CUDA_VISIBLE_DEVICES if cuda_visible_devices: device_ids = list(map(int, cuda_visible_devices.split(","))) else: device_ids = list(range(cuda_device_count_stateless())) physical_device_id = device_ids[device.index] tensor = torch.tensor([physical_device_id], dtype=torch.int, device="cpu") gather_list = [ torch.tensor([0], dtype=torch.int, device="cpu") for _ in range(self.world_size) ] dist.all_gather(gather_list, tensor, group=self.group) physical_device_ids = [t.item() for t in gather_list] # test nvlink first, this will filter out most of the cases # where custom quick allreduce is not supported # this checks hardware and driver support for NVLink assert current_platform.is_cuda_alike() self.fully_connected = current_platform.is_fully_connected(physical_device_ids) if self.world_size > 2 and not self.fully_connected: logger.debug( "Custom quick allreduce is disabled because it's not supported " "on more than two PCIe-only GPUs. " ) return self.init_quick_all_reduce() def init_quick_all_reduce(self): # On RocM, bfloat16 kernels are slower than fp16 # due to slower match operations # If environment variable is set to 1, we convert input to fp16 self.use_fp16_kernels = envs.VLLM_ROCM_QUICK_REDUCE_CAST_BF16_TO_FP16 regime_str = envs.VLLM_ROCM_QUICK_REDUCE_QUANTIZATION if regime_str not in QuickReduceRegime.__members__: logger.warning( "Custom quick allreduce:", f"Invalid quantization level: {regime_str}. " "Supported levels: " f"{list(QuickReduceRegime.__members__.keys())}", ) return if regime_str == "NONE": logger.debug( "Custom quick allreduce is disabled based " "on env variable " "VLLM_ROCM_QUICK_REDUCE_QUANTIZATION='NONE'" ) return self.qr_quant_level = QuickReduceRegime[regime_str] vllm_config = get_current_vllm_config() if ( vllm_config is not None and hasattr(vllm_config, "model_config") and hasattr(vllm_config.model_config, "dtype") ): dtype = vllm_config.model_config.dtype if dtype not in [torch.float16, torch.bfloat16]: logger.debug( "Custom quick allreduce disabled: only supports " "float16 and float16, but get %s.", dtype, ) return if dtype == torch.bfloat16 and self.use_fp16_kernels: logger.info( "Custom quick allreduce: BF16 inputs will be converted " "to FP16 to improve performance. set " "envs.VLLM_ROCM_QUICK_REDUCE_CAST_BF16_TO_FP16=0 " "to turn off." ) # VLLM_ROCM_QUICK_REDUCE_MAX_SIZE_BYTES_MB is specified in MB qr_max_size = envs.VLLM_ROCM_QUICK_REDUCE_MAX_SIZE_BYTES_MB if qr_max_size is not None: if qr_max_size < 1: logger.info( "You should not set a max_size smaller than 1MB, which can " "lead to error or degradation to custom allreduce or rccl." ) qr_max_size = qr_max_size * MB self._ptr = ops.init_custom_qr(self.rank, self.world_size, qr_max_size) self.qr_max_size = qr_max_size if qr_max_size is not None else ops.qr_max_size() self.create_shared_buffer() self.disabled = False def _rocm_arch_available(self): if not current_platform.is_rocm(): return False try: props = torch.cuda.get_device_properties(0) gcn_arch = getattr(props, "gcnArchName", "") supported_archs = ["gfx94", "gfx95"] return any(gfx in gcn_arch for gfx in supported_archs) except Exception as e: logger.warning("Failed to determine ROCm for quick allreduce: %s", e) return False def create_shared_buffer(self): """ Creates a shared buffer for quickreduce. Has to be called after init_custom_qr """ handle = ops.qr_get_handle(self._ptr) world_size = dist.get_world_size(group=self.group) handles = [None] * world_size dist.all_gather_object(handles, handle, group=self.group) ops.qr_open_handles(self._ptr, handles) def should_quick_allreduce(self, inp: torch.Tensor): """ Check if quickreduce is available """ if self.disabled: return False if inp.dtype not in self._SUPPORTED_DTYPES: return False inp_size = inp.numel() * inp.element_size() # custom quick allreduce requires input byte size to be # multiples of 16 if inp_size % 16 != 0: return False if not is_weak_contiguous(inp): return False dtype = inp.dtype if self.use_fp16_kernels: dtype = torch.float16 return ( inp_size <= self.qr_max_size and inp_size >= self._QR_MIN_SIZE[(dtype, self.world_size)][self.qr_quant_level.value] ) def quick_all_reduce(self, inp: torch.Tensor, *, out: torch.Tensor = None): """Performs an out-of-place custom quick all reduce.""" # quick allreduce doesn't require a separate graph mode, # as QR uses static IPC buffer. if out is None: out = torch.empty_like(inp) ops.qr_all_reduce( self._ptr, inp, out, self.qr_quant_level.value, self.use_fp16_kernels ) return out def close(self): if not self.disabled and getattr(self, "_ptr", None): if ops is not None: ops.qr_destroy(self._ptr) self._ptr = 0 self.disabled = True def __del__(self): self.close()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/all2all.py
vllm/distributed/device_communicators/all2all.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import Any import torch import torch.distributed as dist import vllm.envs as envs from vllm.distributed import get_dp_group, get_ep_group from vllm.forward_context import get_forward_context from vllm.logger import init_logger from vllm.utils.flashinfer import has_flashinfer_all2all from vllm.utils.import_utils import has_deep_ep, has_pplx from .base_device_communicator import All2AllManagerBase, Cache if has_flashinfer_all2all(): from flashinfer.comm import Mapping # type: ignore[import-not-found] from flashinfer.comm.mnnvl import MnnvlConfig # type: ignore[import-not-found] from flashinfer.comm.trtllm_alltoall import ( MnnvlMoe, # type: ignore[import-not-found] ) logger = init_logger(__name__) class NaiveAll2AllManager(All2AllManagerBase): """ A naive implementation of all2all communication. It uses all-reduce under the hood, which is not efficient at all. The main purpose is for testing and debugging. """ def __init__(self, cpu_group): super().__init__(cpu_group) def naive_multicast( self, x: torch.Tensor, cu_tokens_across_sp_cpu: torch.Tensor, is_sequence_parallel: bool, ) -> torch.Tensor: assert len(x.shape) == 2 buffer = torch.empty( (cu_tokens_across_sp_cpu[-1], x.size(1)), device=x.device, dtype=x.dtype ) rank = self.rank if is_sequence_parallel else self.dp_rank world_size = self.world_size if is_sequence_parallel else self.dp_world_size start = 0 if rank == 0 else cu_tokens_across_sp_cpu[rank - 1] end = cu_tokens_across_sp_cpu[rank] buffer[start:end, :].copy_(x) for idx in range(world_size): start = 0 if idx == 0 else cu_tokens_across_sp_cpu[idx - 1] end = cu_tokens_across_sp_cpu[idx] get_ep_group().broadcast(buffer[start:end, :], idx) return buffer def dispatch( self, hidden_states: torch.Tensor, router_logits: torch.Tensor, is_sequence_parallel: bool = False, extra_tensors: list[torch.Tensor] | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: if extra_tensors is not None: raise NotImplementedError( "extra_tensors is not supported for NaiveAll2AllManager" ) sp_size = self.tp_group.world_size if is_sequence_parallel else 1 dp_metadata = get_forward_context().dp_metadata assert dp_metadata is not None cu_tokens_across_sp_cpu = dp_metadata.cu_tokens_across_sp(sp_size) hidden_states = self.naive_multicast( hidden_states, cu_tokens_across_sp_cpu, is_sequence_parallel ) router_logits = self.naive_multicast( router_logits, cu_tokens_across_sp_cpu, is_sequence_parallel ) return hidden_states, router_logits def combine( self, hidden_states: torch.Tensor, is_sequence_parallel: bool = False ) -> torch.Tensor: ep_rank = self.rank if is_sequence_parallel else self.dp_rank dp_metadata = get_forward_context().dp_metadata assert dp_metadata is not None sp_size = self.tp_group.world_size if is_sequence_parallel else 1 cu_tokens_across_sp_cpu = dp_metadata.cu_tokens_across_sp(sp_size) start = 0 if ep_rank == 0 else cu_tokens_across_sp_cpu[ep_rank - 1] end = cu_tokens_across_sp_cpu[ep_rank] all_hidden_states = get_ep_group().all_reduce(hidden_states) hidden_states = all_hidden_states[start:end, :] return hidden_states def destroy(self): pass class AgRsAll2AllManager(All2AllManagerBase): """ An implementation of all2all communication based on all-gather (dispatch) and reduce-scatter (combine). """ def __init__(self, cpu_group): super().__init__(cpu_group) def dispatch( self, hidden_states: torch.Tensor, router_logits: torch.Tensor, is_sequence_parallel: bool = False, extra_tensors: list[torch.Tensor] | None = None, ) -> ( tuple[torch.Tensor, torch.Tensor] | tuple[torch.Tensor, torch.Tensor, list[torch.Tensor]] ): """ Gather hidden_states and router_logits from all dp ranks. """ dp_metadata = get_forward_context().dp_metadata assert dp_metadata is not None sizes = dp_metadata.get_chunk_sizes_across_dp_rank() assert sizes is not None dist_group = get_ep_group() if is_sequence_parallel else get_dp_group() assert sizes[dist_group.rank_in_group] == hidden_states.shape[0] tensors_to_gather = [hidden_states, router_logits] if extra_tensors is not None: tensors_to_gather.extend(extra_tensors) gathered_tensors = dist_group.all_gatherv( tensors_to_gather, dim=0, sizes=sizes, ) if extra_tensors is not None: return (gathered_tensors[0], gathered_tensors[1], gathered_tensors[2:]) return gathered_tensors[0], gathered_tensors[1] def combine( self, hidden_states: torch.Tensor, is_sequence_parallel: bool = False ) -> torch.Tensor: """ Reduce-scatter hidden_states across all dp ranks. """ dp_metadata = get_forward_context().dp_metadata assert dp_metadata is not None sizes = dp_metadata.get_chunk_sizes_across_dp_rank() assert sizes is not None dist_group = get_ep_group() if is_sequence_parallel else get_dp_group() hidden_states = dist_group.reduce_scatterv(hidden_states, dim=0, sizes=sizes) return hidden_states def destroy(self): pass class PPLXAll2AllManager(All2AllManagerBase): """ All2All communication based on PPLX kernels. """ def __init__(self, cpu_group): assert has_pplx(), ( "pplx_kernels not found. Please follow https://github.com/vllm-project/vllm/blob/main/tools/ep_kernels/README.md" " to install pplx_kernels." ) super().__init__(cpu_group) if self.internode: # inter-node communication needs nvshmem, # intra-node communication uses p2p mapping directly from pplx_kernels.nvshmem import ( # type: ignore[import-not-found] nvshmem_alloc_empty_unique_id, nvshmem_get_unique_id, nvshmem_init, ) logger.debug( "Initialize NVSHMEM for pplx_kernels: rank=%d, world size=%d", self.rank, self.world_size, ) uid = ( nvshmem_get_unique_id() if self.rank == 0 else nvshmem_alloc_empty_unique_id() ) dist.broadcast( uid, src=dist.get_process_group_ranks(self.cpu_group)[0], group=self.cpu_group, ) logger.debug("PPLX NVSHMEM UID = %s", uid) nvshmem_init(uid, self.rank, self.world_size) self.handle_cache = Cache() def get_handle(self, kwargs): import pplx_kernels as pplx # type: ignore[import-not-found] return self.handle_cache.get_or_create( kwargs, pplx.AllToAll.internode if self.internode else pplx.AllToAll.intranode, ) def dispatch( self, hidden_states: torch.Tensor, router_logits: torch.Tensor, is_sequence_parallel: bool = False, extra_tensors: list[torch.Tensor] | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: raise NotImplementedError def combine( self, hidden_states: torch.Tensor, is_sequence_parallel: bool = False ) -> torch.Tensor: raise NotImplementedError def destroy(self): with self.handle_cache._lock: for _, handle in self.handle_cache._cache.items(): handle.destroy() if self.internode: from pplx_kernels.nvshmem import ( nvshmem_finalize, # type: ignore[import-not-found] ) logger.debug("PPLX NVSHMEM finalize") nvshmem_finalize() class DeepEPAll2AllManagerBase(All2AllManagerBase): """ All2All communication based on DeepEP High-Throughput kernels. """ def __init__(self, cpu_group): assert has_deep_ep(), ( "DeepEP kernels not found. Please follow https://github.com/vllm-project/vllm/blob/main/tools/ep_kernels/README.md" " to install DeepEP kernels." ) # noqa super().__init__(cpu_group) self.handle_cache = Cache() # This is the DeepEP default. Stick to it till we can establish # reasonable defaults based on profiling. self.num_sms = 20 def get_handle(self, kwargs): raise NotImplementedError def dispatch( self, hidden_states: torch.Tensor, router_logits: torch.Tensor, is_sequence_parallel: bool = False, extra_tensors: list[torch.Tensor] | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: raise NotImplementedError def combine( self, hidden_states: torch.Tensor, is_sequence_parallel: bool = False ) -> torch.Tensor: raise NotImplementedError def destroy(self): pass class DeepEPHTAll2AllManager(DeepEPAll2AllManagerBase): """ All2All communication based on DeepEP High-Throughput kernels. """ def __init__(self, cpu_group): super().__init__(cpu_group) def _make_all2all_kwargs(self) -> dict[Any, Any]: # Defaults for internode and intranode are taken from DeepEP tests. num_nvl_bytes = envs.VLLM_DEEPEP_BUFFER_SIZE_MB * 1024 * 1024 num_rdma_bytes = None num_qps_per_rank = None if self.internode and not envs.VLLM_DEEPEP_HIGH_THROUGHPUT_FORCE_INTRA_NODE: num_rdma_bytes = envs.VLLM_DEEPEP_BUFFER_SIZE_MB * 1024 * 1024 num_qps_per_rank = self.num_sms // 2 else: num_rdma_bytes = 0 num_qps_per_rank = 1 assert num_rdma_bytes is not None assert num_qps_per_rank is not None return dict( group=self.cpu_group, num_nvl_bytes=num_nvl_bytes, num_rdma_bytes=num_rdma_bytes, low_latency_mode=False, num_qps_per_rank=num_qps_per_rank, ) def get_handle(self, kwargs): assert len(kwargs) == 0, ( "DeepEPHTAll2AllManager expects no arguments. All the required " "args are computed in the Manager itself." ) import deep_ep # type: ignore[import-not-found] buffer_kwargs = self._make_all2all_kwargs() logger.debug("DeepEP all2all args %s", buffer_kwargs) handle: deep_ep.Buffer = self.handle_cache.get_or_create( buffer_kwargs, deep_ep.Buffer ) return handle def set_num_sms(self, num_sms: int): import deep_ep # type: ignore[import-not-found] # Right now the buffers are sized for only what the kernels were # created with. So we can only reduce the number of SMS used # but not increase it. if num_sms > self.num_sms: num_sms = self.num_sms deep_ep.Buffer.set_num_sms(num_sms) class DeepEPLLAll2AllManager(DeepEPAll2AllManagerBase): """ All2All communication based on DeepEP Low-Latency kernels. """ def __init__(self, cpu_group): super().__init__(cpu_group) def _make_all2all_kwargs( self, max_num_tokens_per_dp_rank: int, token_hidden_size: int, num_ep_ranks: int, num_global_experts: int, num_local_experts: int, ) -> dict[Any, Any]: """ max_num_tokens_per_dp_rank : the maximum number of tokens a DP rank can dispatch all the ranks must hold the same value. token_hidden_size: the hidden dimension of each token. num_ep_ranks: the number of EP group ranks. num_global_experts: Number of experts in the model. num_local_experts: Number of experts in an EP rank. """ import deep_ep # type: ignore[import-not-found] # Defaults for internode and intranode are taken from DeepEP tests. num_nvl_bytes = envs.VLLM_DEEPEP_BUFFER_SIZE_MB * 1024 * 1024 num_qps_per_rank = num_local_experts num_rdma_bytes = deep_ep.Buffer.get_low_latency_rdma_size_hint( num_max_dispatch_tokens_per_rank=max_num_tokens_per_dp_rank, hidden=token_hidden_size, num_ranks=num_ep_ranks, num_experts=num_global_experts, ) assert num_rdma_bytes is not None return dict( group=self.cpu_group, num_nvl_bytes=num_nvl_bytes, num_rdma_bytes=num_rdma_bytes, low_latency_mode=True, num_qps_per_rank=num_qps_per_rank, allow_nvlink_for_low_latency_mode=True, allow_mnnvl=envs.VLLM_DEEPEP_LOW_LATENCY_USE_MNNVL, ) def get_handle(self, kwargs): """ The kwargs for DeepEPLLAll2AllManager is dictated by _make_all2all_kwargs. """ import deep_ep # type: ignore[import-not-found] buffer_kwargs = self._make_all2all_kwargs(**kwargs) logger.debug("DeepEP all2all args %s", buffer_kwargs) handle: deep_ep.Buffer = self.handle_cache.get_or_create( buffer_kwargs, deep_ep.Buffer ) return handle # DeepEP LL uses RDMA so no SMs are used for communication def max_sms_used(self) -> int | None: return 0 class FlashInferAllToAllManager(All2AllManagerBase): """ All2All communication based on flashinfer kernels. """ # This type lint could be removed after all of the work in # https://github.com/vllm-project/vllm/issues/26533 done. rank: int world_size: int def __init__(self, cpu_group): assert has_flashinfer_all2all(), ( "flashinfer all2all module not found. Please install/check flashinfer" ) # noqa super().__init__(cpu_group) logger.debug( "Initialize for flashinfer All2All rank=%d, world size=%d", self.rank, self.world_size, ) self.initialized = False self.alltoall_info = None def initialize( self, world_size: int, rank: int, gpus_per_node: int, ): """Initialize workspace""" if self.initialized: return self.cleanup() logger.debug("making map: rank=%d, world size=%d", rank, world_size) self.mapping = Mapping( world_size, rank, gpus_per_node, tp_size=world_size, ) from vllm.distributed.device_communicators.mnnvl_compat import ( CustomCommunicator, ) dp_config = MnnvlConfig( comm_backend=CustomCommunicator(get_dp_group().cpu_group), fabric_page_size=1 << 29, # 512MB allocation_granularity=0, # Auto-detect ) self.workspace_tensor = MnnvlMoe.get_moe_workspaces(self.mapping, dp_config) self.prepare_workspace_tensor = MnnvlMoe.get_moe_prepare_workspace( self.mapping, dp_config ) self.world_size = world_size self.rank = rank self.gpus_per_node = gpus_per_node self.initialized = True logger.info( "FlashInfer All2All initialized for rank %s, size %s", rank, world_size ) def ensure_alltoall_workspace_initialized(self): """Ensure workspace is initialized""" if not has_flashinfer_all2all(): return False if self.world_size <= 1: return False if not self.initialized: self.initialize( world_size=self.world_size, rank=self.rank, gpus_per_node=torch.cuda.device_count, ) return self.initialized def get_handle(self, kwargs): return self def cleanup(self): """Clean up workspace""" if ( self.initialized and self.workspace_tensor is not None and self.prepare_workspace_tensor is not None ): try: del self.workspace_tensor del self.prepare_workspace_tensor except Exception as e: logger.warning("Failed to cleanup FlashInfer workspace: %s", e) finally: self.workspace_tensor = None self.prepare_workspace_tensor = None self.mapping = None self.initialized = False
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/base_device_communicator.py
vllm/distributed/device_communicators/base_device_communicator.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import threading from typing import Any from weakref import WeakValueDictionary import torch import torch.distributed as dist from torch.distributed import ProcessGroup class Cache: def __init__(self): self._cache: WeakValueDictionary = WeakValueDictionary() self._lock = threading.RLock() # Reentrant lock for thread safety def get_or_create(self, kwargs, func): # Create a hashable key from the kwargs key = tuple(sorted((k, v) for k, v in kwargs.items())) with self._lock: instance = self._cache.get(key) if instance is None: instance = func(**kwargs) self._cache[key] = instance return instance class All2AllManagerBase: rank: int world_size: int def __init__(self, cpu_group): self.cpu_group = cpu_group # compute some common properties from vllm.distributed.parallel_state import ( get_dp_group, get_tp_group, in_the_same_node_as, ) # all2all lives in ep group, which is merged from dp and tp group self.dp_group = get_dp_group() self.tp_group = get_tp_group() # no self.ep_group since self.ep_group is still in construction # when we create this object self.dp_rank = self.dp_group.rank_in_group self.dp_world_size = self.dp_group.world_size self.rank = dist.get_rank(cpu_group) self.world_size = dist.get_world_size(cpu_group) # all2all communication often has separate implementations for # intra-node and inter-node communication self.internode = not all(in_the_same_node_as(cpu_group, source_rank=0)) def get_handle(self, kwargs): # get a handle for the all2all communication, # based on the kwargs. # different layers can have different configs, # e.g. one layer has hidden size 1024, another has 2048. # usually the underlying implementation caches the handle # and reuse it for the same config. raise NotImplementedError def dispatch( self, hidden_states: torch.Tensor, router_logits: torch.Tensor, is_sequence_parallel: bool = False, extra_tensors: list[torch.Tensor] | None = None, ) -> Any: # Subclasses should either: # - implement handling for extra_tensors, or # - raise a clear error if extra_tensors is not supported. raise NotImplementedError def set_num_sms(self, num_sms: int): pass def max_sms_used(self) -> int | None: return None # None means it could use the whole GPU def combine(self, hidden_states: torch.Tensor, is_sequence_parallel: bool = False): raise NotImplementedError def destroy(self): pass class DeviceCommunicatorBase: """ Base class for device-specific communicator. It can use the `cpu_group` to initialize the communicator. If the device has PyTorch integration (PyTorch can recognize its communication backend), the `device_group` will also be given. """ def __init__( self, cpu_group: ProcessGroup, device: torch.device | None = None, device_group: ProcessGroup | None = None, unique_name: str = "", ): self.device = device or torch.device("cpu") self.cpu_group = cpu_group self.device_group = device_group self.unique_name = unique_name self.rank = dist.get_rank(cpu_group) self.world_size = dist.get_world_size(cpu_group) self.ranks = dist.get_process_group_ranks(cpu_group) self.global_rank = dist.get_rank() self.global_world_size = dist.get_world_size() self.rank_in_group = dist.get_group_rank(self.cpu_group, self.global_rank) use_ep = False all2all_backend = None from vllm.config import get_current_vllm_config config = get_current_vllm_config() if config is not None: # as long as we use data parallel (coupled data parallel # where all data parallel ranks execute forward together), # we initialize the all2all manager used in expert parallel. use_ep = config.parallel_config.data_parallel_size > 1 all2all_backend = config.parallel_config.all2all_backend self.is_ep_communicator = "ep" in unique_name self.use_all2all = self.is_ep_communicator and use_ep self.all2all_backend = all2all_backend self.all2all_manager: All2AllManagerBase | None = None def all_reduce(self, input_: torch.Tensor) -> torch.Tensor: dist.all_reduce(input_, group=self.device_group) return input_ def all_gather(self, input_: torch.Tensor, dim: int = -1) -> torch.Tensor: if dim < 0: # Convert negative dim to positive. dim += input_.dim() input_size = input_.size() # NOTE: we have to use concat-style all-gather here, # stack-style all-gather has compatibility issues with # torch.compile . see https://github.com/pytorch/pytorch/issues/138795 output_size = (input_size[0] * self.world_size,) + input_size[1:] # Allocate output tensor. output_tensor = torch.empty( output_size, dtype=input_.dtype, device=input_.device ) # All-gather. dist.all_gather_into_tensor(output_tensor, input_, group=self.device_group) # Reshape output_tensor = output_tensor.reshape((self.world_size,) + input_size) output_tensor = output_tensor.movedim(0, dim) output_tensor = output_tensor.reshape( input_size[:dim] + (self.world_size * input_size[dim],) + input_size[dim + 1 :] ) return output_tensor def all_gatherv( self, input_: torch.Tensor | list[torch.Tensor], dim: int = 0, sizes: list[int] | None = None, ) -> torch.Tensor | list[torch.Tensor]: raise NotImplementedError def reduce_scatter(self, input_: torch.Tensor, dim: int = -1) -> torch.Tensor: world_size = self.world_size # Bypass the function if we are using only 1 GPU. if world_size == 1: return input_ assert -input_.dim() <= dim < input_.dim(), ( f"Invalid dim ({dim}) for input tensor with shape {input_.size()}" ) if dim < 0: # Convert negative dim to positive. dim += input_.dim() # Note: This will produce an incorrect answer if we don't make # the input_tensor contiguous. Possible bug in reduce_scatter_tensor? input_tensor = input_.movedim(0, dim).contiguous() assert input_tensor.shape[0] % world_size == 0 chunk_size = input_tensor.shape[0] // world_size output_shape = (chunk_size,) + input_tensor.shape[1:] output_tensor = torch.empty( output_shape, dtype=input_tensor.dtype, device=input_tensor.device ) # Perform reduce-scatter operation torch.distributed.reduce_scatter_tensor( output_tensor, input_tensor, group=self.device_group ) # Reshape before returning return output_tensor.movedim(0, dim).contiguous() def reduce_scatterv( self, input_: torch.Tensor, dim: int = -1, sizes: list[int] | None = None ) -> torch.Tensor: raise NotImplementedError def gather( self, input_: torch.Tensor, dst: int = 0, dim: int = -1 ) -> torch.Tensor | None: """ NOTE: We assume that the input tensor is on the same device across all the ranks. NOTE: `dst` is the local rank of the destination rank. """ world_size = self.world_size assert -input_.dim() <= dim < input_.dim(), ( f"Invalid dim ({dim}) for input tensor with shape {input_.size()}" ) if dim < 0: # Convert negative dim to positive. dim += input_.dim() # Allocate output tensor. if self.rank_in_group == dst: gather_list = [torch.empty_like(input_) for _ in range(world_size)] else: gather_list = None # Gather. torch.distributed.gather( input_, gather_list, dst=self.ranks[dst], group=self.device_group ) if self.rank_in_group == dst: output_tensor = torch.cat(gather_list, dim=dim) else: output_tensor = None return output_tensor def send(self, tensor: torch.Tensor, dst: int | None = None) -> None: """Sends a tensor to the destination rank in a blocking way""" """NOTE: `dst` is the local rank of the destination rank.""" if dst is None: dst = (self.rank_in_group + 1) % self.world_size torch.distributed.send(tensor, self.ranks[dst], self.device_group) def recv( self, size: torch.Size, dtype: torch.dtype, src: int | None = None ) -> torch.Tensor: """Receives a tensor from the source rank.""" """NOTE: `src` is the local rank of the source rank.""" if src is None: src = (self.rank_in_group - 1) % self.world_size tensor = torch.empty(size, dtype=dtype, device=self.device) torch.distributed.recv(tensor, self.ranks[src], self.device_group) return tensor def destroy(self): pass def prepare_communication_buffer_for_model(self, model: torch.nn.Module) -> None: """ Prepare the communication buffer for the model. """ if not self.is_ep_communicator: return moe_modules = [ module for module in model.modules() # TODO(bnell): Should use isinstance but can't. Maybe search for # presence of quant_method.maybe_init_modular_kernel? if ( module.__class__.__name__ == "FusedMoE" or module.__class__.__name__ == "SharedFusedMoE" ) ] for module in moe_modules: module.maybe_init_modular_kernel() def dispatch( self, hidden_states: torch.Tensor, router_logits: torch.Tensor, is_sequence_parallel: bool = False, ) -> tuple[torch.Tensor, torch.Tensor]: """ Dispatch the hidden states and router logits to the appropriate device. This is a no-op in the base class. """ return hidden_states, router_logits def combine( self, hidden_states: torch.Tensor, is_sequence_parallel: bool = False ) -> torch.Tensor: """ Combine the hidden states and router logits from the appropriate device. This is a no-op in the base class. """ return hidden_states
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/pynccl_allocator.py
vllm/distributed/device_communicators/pynccl_allocator.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import atexit import contextlib import tempfile from typing import Any import torch from packaging import version from torch.cuda.memory import CUDAPluggableAllocator from torch.utils.cpp_extension import load_inline from vllm import envs from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.utils.nccl import find_nccl_include_paths logger = init_logger(__name__) nccl_allocator_source = """ #include <nccl.h> extern "C" { void* nccl_alloc_plug(size_t size, int device, void* stream) { void* ptr; ncclResult_t err = ncclMemAlloc(&ptr, size); return ptr; } void nccl_free_plug(void* ptr, size_t size, int device, void* stream) { ncclResult_t err = ncclMemFree(ptr); } } """ _allocator = None _allocator_wrapper = None _mem_pool = None _registered_base_addrs = set() _graph_pool_id = None _nccl_allocator_failed_to_compile = False _cached_pool_snapshot = None def is_symmetric_memory_enabled(): global _nccl_allocator_failed_to_compile return envs.VLLM_USE_NCCL_SYMM_MEM and not _nccl_allocator_failed_to_compile def is_symmetric_memory_tensor(tensor: torch.Tensor): if not is_symmetric_memory_enabled() or _cached_pool_snapshot is None: return False for segment in _cached_pool_snapshot: for block in segment["blocks"]: if block["address"] == tensor.untyped_storage().data_ptr(): return True return False def set_graph_pool_id(graph_pool_id): global _graph_pool_id _graph_pool_id = graph_pool_id def compile_nccl_allocator(): global _allocator, _allocator_wrapper, _nccl_allocator_failed_to_compile if not current_platform.is_cuda(): _nccl_allocator_failed_to_compile = True return try: out_dir = tempfile.gettempdir() nccl_allocator_libname = "nccl_allocator" nccl_include_paths = find_nccl_include_paths() load_inline( name=nccl_allocator_libname, cpp_sources=nccl_allocator_source, with_cuda=True, extra_ldflags=["-lnccl"], verbose=envs.VLLM_LOGGING_LEVEL == "DEBUG", is_python_module=False, build_directory=out_dir, extra_include_paths=nccl_include_paths, ) _allocator_wrapper = CUDAPluggableAllocator( f"{out_dir}/{nccl_allocator_libname}.so", "nccl_alloc_plug", "nccl_free_plug", ) _allocator = _allocator_wrapper.allocator() except Exception as e: _nccl_allocator_failed_to_compile = True logger.warning( "Failed to compile NCCL memory allocator. " "Symmetric memory will be disabled. " "This is expected if NCCL headers are not available. " "optionally set VLLM_NCCL_INCLUDE_PATH to point to a directory " "containing the NCCL header. " "Error: %s", str(e), ) def get_nccl_mem_pool(): global _mem_pool, _nccl_allocator_failed_to_compile if _mem_pool is None and not _nccl_allocator_failed_to_compile: compile_nccl_allocator() if _allocator is not None: _mem_pool = torch.cuda.MemPool(_allocator) return _mem_pool def _cleanup_nccl_mem_pool(): global _mem_pool _mem_pool = None def _cleanup_nccl_allocator_wrapper(): global _allocator_wrapper _allocator_wrapper = None atexit.register(_cleanup_nccl_mem_pool) atexit.register(_cleanup_nccl_allocator_wrapper) class nccl_symm_mem_context: def __init__( self, pynccl_comm: PyNcclCommunicator, disabled: bool = False, ): self.disabled = ( disabled or not is_symmetric_memory_enabled() or pynccl_comm.world_size == 1 or not current_platform.is_cuda() or get_nccl_mem_pool() is None or version.parse(torch.__version__) < version.parse("2.8.0.a0") ) if self.disabled: self.pynccl_comm: PyNcclCommunicator | None = None self._mem_pool_ctx: contextlib.AbstractContextManager[Any] = ( contextlib.nullcontext() ) self.is_graph_capture = None self.device = None else: self.pynccl_comm = pynccl_comm self._mem_pool_ctx = torch.cuda.use_mem_pool(get_nccl_mem_pool()) self.is_graph_capture = torch.cuda.is_current_stream_capturing() self.device = torch.cuda.current_device() def __enter__(self): if self.disabled: return self assert self.pynccl_comm is not None, ( "Symmetric memory requires pynccl to be initialized" ) assert self.pynccl_comm.nccl_version >= 22703, ( "NCCL version 2.27.3 or higher is required for NCCL symmetric memory" ) if self.is_graph_capture: assert _graph_pool_id is not None, ( "graph_pool_id is not set under graph capture" ) # Pause graph memory pool to use symmetric memory with cuda graph torch._C._cuda_endAllocateToPool(self.device, _graph_pool_id) self._mem_pool_ctx.__enter__() return self def __exit__(self, exc_type, exc_val, exc_tb): if self.disabled: return global _cached_pool_snapshot global _registered_base_addrs self._mem_pool_ctx.__exit__(exc_type, exc_val, exc_tb) _pool = get_nccl_mem_pool() assert _pool is not None _cached_pool_snapshot = _pool.snapshot() assert self.pynccl_comm is not None for segment in _cached_pool_snapshot: if segment["address"] not in _registered_base_addrs: self.pynccl_comm.register_comm_window_raw( segment["address"], segment["total_size"] ) _registered_base_addrs.add(segment["address"]) if self.is_graph_capture: torch._C._cuda_beginAllocateCurrentThreadToPool(self.device, _graph_pool_id)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/cuda_wrapper.py
vllm/distributed/device_communicators/cuda_wrapper.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """This file is a pure Python wrapper for the cudart library. It avoids the need to compile a separate shared library, and is convenient for use when we just need to call a few functions. """ import ctypes from dataclasses import dataclass from typing import Any # this line makes it possible to directly load `libcudart.so` using `ctypes` import torch # noqa import vllm.envs as envs from vllm.logger import init_logger from vllm.platforms import current_platform logger = init_logger(__name__) # === export types and functions from cudart to Python === # for the original cudart definition, please check # https://docs.nvidia.com/cuda/cuda-runtime-api/index.html cudaError_t = ctypes.c_int cudaMemcpyKind = ctypes.c_int class cudaIpcMemHandle_t(ctypes.Structure): _fields_ = [("internal", ctypes.c_byte * 128)] @dataclass class Function: name: str restype: Any argtypes: list[Any] def find_loaded_library(lib_name) -> str | None: """ According to according to https://man7.org/linux/man-pages/man5/proc_pid_maps.5.html, the file `/proc/self/maps` contains the memory maps of the process, which includes the shared libraries loaded by the process. We can use this file to find the path of the a loaded library. """ # noqa found = False with open("/proc/self/maps") as f: for line in f: if lib_name in line: found = True break if not found: # the library is not loaded in the current process return None # if lib_name is libcudart, we need to match a line with: # address /path/to/libcudart-hash.so.11.0 start = line.index("/") path = line[start:].strip() filename = path.split("/")[-1] assert filename.rpartition(".so")[0].startswith(lib_name), ( f"Unexpected filename: {filename} for library {lib_name}" ) return path class CudaRTLibrary: exported_functions = [ # ​cudaError_t cudaSetDevice ( int device ) Function("cudaSetDevice", cudaError_t, [ctypes.c_int]), # cudaError_t cudaDeviceSynchronize ( void ) Function("cudaDeviceSynchronize", cudaError_t, []), # ​cudaError_t cudaDeviceReset ( void ) Function("cudaDeviceReset", cudaError_t, []), # const char* cudaGetErrorString ( cudaError_t error ) Function("cudaGetErrorString", ctypes.c_char_p, [cudaError_t]), # ​cudaError_t cudaMalloc ( void** devPtr, size_t size ) Function( "cudaMalloc", cudaError_t, [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t], ), # ​cudaError_t cudaFree ( void* devPtr ) Function("cudaFree", cudaError_t, [ctypes.c_void_p]), # ​cudaError_t cudaMemset ( void* devPtr, int value, size_t count ) Function( "cudaMemset", cudaError_t, [ctypes.c_void_p, ctypes.c_int, ctypes.c_size_t] ), # ​cudaError_t cudaMemcpy ( void* dst, const void* src, size_t count, cudaMemcpyKind kind ) # noqa Function( "cudaMemcpy", cudaError_t, [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, cudaMemcpyKind], ), # cudaError_t cudaIpcGetMemHandle ( cudaIpcMemHandle_t* handle, void* devPtr ) # noqa Function( "cudaIpcGetMemHandle", cudaError_t, [ctypes.POINTER(cudaIpcMemHandle_t), ctypes.c_void_p], ), # ​cudaError_t cudaIpcOpenMemHandle ( void** devPtr, cudaIpcMemHandle_t handle, unsigned int flags ) # noqa Function( "cudaIpcOpenMemHandle", cudaError_t, [ctypes.POINTER(ctypes.c_void_p), cudaIpcMemHandle_t, ctypes.c_uint], ), ] # https://rocm.docs.amd.com/projects/HIPIFY/en/latest/tables/CUDA_Runtime_API_functions_supported_by_HIP.html # noqa cuda_to_hip_mapping = { "cudaSetDevice": "hipSetDevice", "cudaDeviceSynchronize": "hipDeviceSynchronize", "cudaDeviceReset": "hipDeviceReset", "cudaGetErrorString": "hipGetErrorString", "cudaMalloc": "hipMalloc", "cudaFree": "hipFree", "cudaMemset": "hipMemset", "cudaMemcpy": "hipMemcpy", "cudaIpcGetMemHandle": "hipIpcGetMemHandle", "cudaIpcOpenMemHandle": "hipIpcOpenMemHandle", } # class attribute to store the mapping from the path to the library # to avoid loading the same library multiple times path_to_library_cache: dict[str, Any] = {} # class attribute to store the mapping from library path # to the corresponding dictionary path_to_dict_mapping: dict[str, dict[str, Any]] = {} def __init__(self, so_file: str | None = None): if so_file is None: so_file = find_loaded_library("libcudart") if so_file is None: # libcudart is not loaded in the current process, try hip so_file = find_loaded_library("libamdhip64") # should be safe to assume now that we are using ROCm # as the following assertion should error out if the # libhiprtc library is also not loaded if so_file is None: so_file = envs.VLLM_CUDART_SO_PATH # fallback to env var assert so_file is not None, ( "libcudart is not loaded in the current process, " "try setting VLLM_CUDART_SO_PATH" ) if so_file not in CudaRTLibrary.path_to_library_cache: lib = ctypes.CDLL(so_file) CudaRTLibrary.path_to_library_cache[so_file] = lib self.lib = CudaRTLibrary.path_to_library_cache[so_file] if so_file not in CudaRTLibrary.path_to_dict_mapping: _funcs = {} for func in CudaRTLibrary.exported_functions: f = getattr( self.lib, CudaRTLibrary.cuda_to_hip_mapping[func.name] if current_platform.is_rocm() else func.name, ) f.restype = func.restype f.argtypes = func.argtypes _funcs[func.name] = f CudaRTLibrary.path_to_dict_mapping[so_file] = _funcs self.funcs = CudaRTLibrary.path_to_dict_mapping[so_file] def CUDART_CHECK(self, result: cudaError_t) -> None: if result != 0: error_str = self.cudaGetErrorString(result) raise RuntimeError(f"CUDART error: {error_str}") def cudaGetErrorString(self, error: cudaError_t) -> str: return self.funcs["cudaGetErrorString"](error).decode("utf-8") def cudaSetDevice(self, device: int) -> None: self.CUDART_CHECK(self.funcs["cudaSetDevice"](device)) def cudaDeviceSynchronize(self) -> None: self.CUDART_CHECK(self.funcs["cudaDeviceSynchronize"]()) def cudaDeviceReset(self) -> None: self.CUDART_CHECK(self.funcs["cudaDeviceReset"]()) def cudaMalloc(self, size: int) -> ctypes.c_void_p: devPtr = ctypes.c_void_p() self.CUDART_CHECK(self.funcs["cudaMalloc"](ctypes.byref(devPtr), size)) return devPtr def cudaFree(self, devPtr: ctypes.c_void_p) -> None: self.CUDART_CHECK(self.funcs["cudaFree"](devPtr)) def cudaMemset(self, devPtr: ctypes.c_void_p, value: int, count: int) -> None: self.CUDART_CHECK(self.funcs["cudaMemset"](devPtr, value, count)) def cudaMemcpy( self, dst: ctypes.c_void_p, src: ctypes.c_void_p, count: int ) -> None: cudaMemcpyDefault = 4 kind = cudaMemcpyDefault self.CUDART_CHECK(self.funcs["cudaMemcpy"](dst, src, count, kind)) def cudaIpcGetMemHandle(self, devPtr: ctypes.c_void_p) -> cudaIpcMemHandle_t: handle = cudaIpcMemHandle_t() self.CUDART_CHECK( self.funcs["cudaIpcGetMemHandle"](ctypes.byref(handle), devPtr) ) return handle def cudaIpcOpenMemHandle(self, handle: cudaIpcMemHandle_t) -> ctypes.c_void_p: cudaIpcMemLazyEnablePeerAccess = 1 devPtr = ctypes.c_void_p() self.CUDART_CHECK( self.funcs["cudaIpcOpenMemHandle"]( ctypes.byref(devPtr), handle, cudaIpcMemLazyEnablePeerAccess ) ) return devPtr
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/all_reduce_utils.py
vllm/distributed/device_communicators/all_reduce_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import ctypes import json import os import pickle import subprocess import sys import tempfile from collections.abc import Sequence from itertools import product from typing import Any import torch import torch.distributed as dist import torch.multiprocessing as mp import vllm.envs as envs from vllm.distributed.device_communicators.cuda_wrapper import CudaRTLibrary from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.utils.system_utils import update_environment_variables from vllm.utils.torch_utils import cuda_device_count_stateless logger = init_logger(__name__) MiB = 1024 * 1024 # Max size for each world size in case symmetric memory is available # For different SM architectures CUSTOM_ALL_REDUCE_MAX_SIZES = { "9.0": { 2: 64 * MiB, # 64 MB 4: 32 * MiB, # 32 MB 6: MiB // 2, # 512 KB 8: MiB // 4, # 256 KB }, "10.0": { 2: 2 * MiB, # 2 MB 4: 2 * MiB, # 2 MB 6: 1 * MiB, # 1 MB 8: 1 * MiB, # 1 MB }, } SYMM_MEM_ALL_REDUCE_MAX_SIZES = { "9.0": { 2: 64 * MiB, # 64 MB 4: 32 * MiB, # 32 MB 6: 64 * MiB, # 64 MB 8: 64 * MiB, # 64 MB }, "10.0": { 2: 8 * MiB, # 8 MB 4: 32 * MiB, # 32 MB 6: 128 * MiB, # 128 MB 8: 128 * MiB, # 128 MB }, } NCCL_SYMM_MEM_ALL_REDUCE_CONFIG: dict[str, Any] = { "min_world_size": 4, "thresholds": { 4: 2 * MiB, # 2 MB 8: 1 * MiB, # 1 MB }, "always_use_above_world_size": 8, # Always use symm mem for world_size > 8 } def should_nccl_symm_mem_allreduce(world_size: int, input_tensor: torch.Tensor) -> bool: from vllm.distributed.device_communicators.pynccl_allocator import ( is_symmetric_memory_enabled, ) if vllm_is_batch_invariant(): return False if not is_symmetric_memory_enabled(): return False if world_size < NCCL_SYMM_MEM_ALL_REDUCE_CONFIG["min_world_size"]: return False threshold = NCCL_SYMM_MEM_ALL_REDUCE_CONFIG["thresholds"].get(world_size) if threshold is not None and input_tensor.nbytes >= threshold: return True return world_size > NCCL_SYMM_MEM_ALL_REDUCE_CONFIG["always_use_above_world_size"] def producer( batch_src: Sequence[int], producer_queue, consumer_queue, result_queue, cuda_visible_devices: str | None = None, ): if cuda_visible_devices is not None: update_environment_variables({"CUDA_VISIBLE_DEVICES": cuda_visible_devices}) lib = CudaRTLibrary() for i in batch_src: lib.cudaSetDevice(i) pointer = lib.cudaMalloc(1024) lib.cudaMemset(pointer, 1, 1024) lib.cudaDeviceSynchronize() handle = lib.cudaIpcGetMemHandle(pointer) producer_queue.put(handle) open_success = consumer_queue.get() if open_success: # use two queues to simulate barrier producer_queue.put(0) consumer_queue.get() # check if the memory is modified host_data = (ctypes.c_char * 1024)() lib.cudaMemcpy(host_data, pointer, 1024) # type: ignore for i in range(1024): if ord(host_data[i]) != 2: open_success = False break result_queue.put(open_success) lib.cudaDeviceReset() def consumer( batch_tgt: Sequence[int], producer_queue, consumer_queue, result_queue, cuda_visible_devices: str | None = None, ): if cuda_visible_devices is not None: update_environment_variables({"CUDA_VISIBLE_DEVICES": cuda_visible_devices}) lib = CudaRTLibrary() for j in batch_tgt: lib.cudaSetDevice(j) handle = producer_queue.get() open_success = False try: pointer = lib.cudaIpcOpenMemHandle(handle) # type: ignore open_success = True except RuntimeError: # cannot error out here, because the producer process # is still waiting for the response. pass consumer_queue.put(open_success) if open_success: # modify the memory lib.cudaMemset(pointer, 2, 1024) lib.cudaDeviceSynchronize() # use two queues to simulate barrier producer_queue.get() consumer_queue.put(0) # check if the memory is modified host_data = (ctypes.c_char * 1024)() lib.cudaMemcpy(host_data, pointer, 1024) # type: ignore for i in range(1024): if ord(host_data[i]) != 2: open_success = False break result_queue.put(open_success) lib.cudaDeviceReset() def can_actually_p2p( batch_src: Sequence[int], batch_tgt: Sequence[int], ) -> Sequence[bool]: """ Usually, checking if P2P access is enabled can be done by `torch.cuda.can_device_access_peer(src, tgt)`. However, sometimes the driver might be broken, and `torch.cuda.can_device_access_peer(src, tgt)` returns `True` even if P2P access is not actually possible. See https://github.com/vllm-project/vllm/issues/2728 and https://forums.developer.nvidia.com/t/direct-gpu-gpu-communication-does-not-seem-to-work-properly/283264/10 Therefore, we have to perform a real P2P access to check if it is actually possible. Note on p2p and cuda IPC: Usually, one process uses one GPU: GPU src --> cuda context src --> tensor src --> process src We need to combine p2p and cuda IPC, so that: GPU src --> cuda context src --> tensor src --> process src |shared| GPU tgt --> cuda context tgt --> tensor tgt --> process tgt That is to say, process src creates a tensor in GPU src, passes IPC handle to process tgt, and process tgt accesses the tensor in GPU tgt. Any operation on the tensor in process tgt will be reflected in the tensor in process src, because they are the same memory segment. It is important to note that process tgt accesses the tensor in GPU tgt, not GPU src. That's why we need p2p access. The most time-consuming part is the process creation. To avoid creating processes for every pair of GPUs, we use batched testing. We create two processes for testing all pairs of GPUs in batch. The trick is to reset the device after each test (which is not available in PyTorch). """ # noqa cuda_visible_devices = envs.CUDA_VISIBLE_DEVICES # pass the CUDA_VISIBLE_DEVICES to the child process # to make sure they see the same set of GPUs # make sure the processes are spawned smp = mp.get_context("spawn") producer_queue = smp.Queue() consumer_queue = smp.Queue() result_queue = smp.Queue() p_src = smp.Process( target=producer, args=( batch_src, producer_queue, consumer_queue, result_queue, cuda_visible_devices, ), ) p_tgt = smp.Process( target=consumer, args=( batch_tgt, producer_queue, consumer_queue, result_queue, cuda_visible_devices, ), ) p_src.start() p_tgt.start() p_src.join() p_tgt.join() assert p_src.exitcode == 0 and p_tgt.exitcode == 0 result: list[bool] = [] for src, tgt in zip(batch_src, batch_tgt): a = result_queue.get() b = result_queue.get() if a != b: logger.warning( "Two processes do not agree on the P2P access" " status on %d -> %d, treat as disabled.", src, tgt, ) result.append(False) else: result.append(a) return result # why do we need this cache? # we are testing peer-to-peer (p2p) access between GPUs,across processes. # if we test it every time, it will be very slow, because we need to create # N * N * 2 processes, where N is the world size. This is very slow. # to reduce the time, we use a cache file to store the p2p access status. # the cache file is generated by the master process if it does not exist. # then all the processes can read the cache file to check the p2p access status. # Note that the cache file is suffixed by the CUDA_VISIBLE_DEVICES, so that we # can have different cache files for different CUDA_VISIBLE_DEVICES settings, # e.g. used by different vllm engines. The device id in the cache file is a # **local** device id, i.e. from 0 to num_dev-1, where num_dev is the number # of visible devices in the vllm engine. _gpu_p2p_access_cache: dict[str, bool] | None = None def gpu_p2p_access_check(src: int, tgt: int) -> bool: """Check if GPU src can access GPU tgt.""" # if the cache variable is already calculated, # read from the cache instead of checking it again global _gpu_p2p_access_cache if _gpu_p2p_access_cache is not None: return _gpu_p2p_access_cache[f"{src}->{tgt}"] is_distributed = dist.is_initialized() num_dev = cuda_device_count_stateless() cuda_visible_devices = envs.CUDA_VISIBLE_DEVICES if cuda_visible_devices is None: cuda_visible_devices = ",".join(str(i) for i in range(num_dev)) path = os.path.join( envs.VLLM_CACHE_ROOT, f"gpu_p2p_access_cache_for_{cuda_visible_devices}.json" ) os.makedirs(os.path.dirname(path), exist_ok=True) from vllm.distributed.parallel_state import get_world_group if (not is_distributed or get_world_group().local_rank == 0) and ( not os.path.exists(path) ): # only the local master process (with local_rank == 0) can # enter this block to calculate the cache logger.info("generating GPU P2P access cache in %s", path) cache: dict[str, bool] = {} ids = list(range(num_dev)) # batch of all pairs of GPUs batch_src, batch_tgt = zip(*list(product(ids, ids))) # NOTE: we use `subprocess` rather than `multiprocessing` here # because the caller might not have `if __name__ == "__main__":`, # in that case we cannot use spawn method in multiprocessing. # However, `can_actually_p2p` requires spawn method. # The fix is, we use `subprocess` to call the function, # where we have `if __name__ == "__main__":` in this file. # use a temporary file to store the result # we don't use the output of the subprocess directly, # because the subprocess might produce logging output with tempfile.NamedTemporaryFile() as output_file: input_bytes = pickle.dumps((batch_src, batch_tgt, output_file.name)) returned = subprocess.run( [sys.executable, __file__], input=input_bytes, capture_output=True ) # check if the subprocess is successful try: returned.check_returncode() except Exception as e: # wrap raised exception to provide more information raise RuntimeError( f"Error happened when batch testing " f"peer-to-peer access from {batch_src} to {batch_tgt}:\n" f"{returned.stderr.decode()}" ) from e with open(output_file.name, "rb") as f: result = pickle.load(f) for _i, _j, r in zip(batch_src, batch_tgt, result): cache[f"{_i}->{_j}"] = r with open(path, "w") as f: json.dump(cache, f, indent=4) if is_distributed: get_world_group().barrier() logger.info("reading GPU P2P access cache from %s", path) with open(path) as f: cache = json.load(f) _gpu_p2p_access_cache = cache return _gpu_p2p_access_cache[f"{src}->{tgt}"] __all__ = ["gpu_p2p_access_check"] if __name__ == "__main__": batch_src, batch_tgt, output_file = pickle.loads(sys.stdin.buffer.read()) result = can_actually_p2p(batch_src, batch_tgt) with open(output_file, "wb") as f: f.write(pickle.dumps(result))
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/__init__.py
vllm/distributed/device_communicators/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/tpu_communicator.py
vllm/distributed/device_communicators/tpu_communicator.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os import torch from torch.distributed import ProcessGroup from vllm.config import get_current_vllm_config from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.platforms.tpu import USE_TPU_INFERENCE from .base_device_communicator import DeviceCommunicatorBase USE_RAY = parallel_config = ( get_current_vllm_config().parallel_config.distributed_executor_backend == "ray" ) logger = init_logger(__name__) if not USE_TPU_INFERENCE: logger.info("tpu_inference not found, using vLLM's TpuCommunicator") if current_platform.is_tpu(): import torch_xla import torch_xla.core.xla_model as xm import torch_xla.runtime as xr from torch_xla._internal import pjrt from torch_xla.distributed.xla_multiprocessing import ( create_optimized_replica_groups, ) if USE_RAY: from vllm.v1.executor import ray_utils class TpuCommunicator(DeviceCommunicatorBase): def __init__( self, cpu_group: ProcessGroup, device: torch.device | None = None, device_group: ProcessGroup | None = None, unique_name: str = "", ): super().__init__(cpu_group, device, device_group, unique_name) # NOTE(woosuk): When using TP > 1 on TPUs, every TPU on the same node # must be used together. Therefore, the local rank and world size can # be simply calculated as follows. global_rank = self.global_rank global_world_size = self.global_world_size if USE_RAY: logger.info("TpuCommunicator initialized with RAY") # Calculate how many TPU nodes are in the current deployment. This # is the Ray placement group if it is deployed with Ray. Default # to the number of TPU nodes in the Ray cluster. The number of TPU # nodes is computed by the total number of TPUs divided by the # number of TPU accelerators per node, to account for clusters # with both CPUs and TPUs. num_nodes = ray_utils.get_num_tpu_nodes() num_nodes_in_pg = ray_utils.get_num_nodes_in_placement_group() if num_nodes_in_pg > 0: num_nodes = num_nodes_in_pg local_world_size = global_world_size // num_nodes local_rank = global_rank % local_world_size else: logger.info("TpuCommunicator initialized with MP") # Sanity: Verify we run on a single host num_hosts = torch_xla.tpu.num_tpu_workers() assert num_hosts == 1 # Get the current number of TPUs (we have locally) local_world_size = torch_xla.tpu.num_available_chips() # Get current rank local_rank = global_rank % local_world_size # Ensure environment variables are set for multihost deployments. # On GKE, this is needed for libtpu and TPU driver to know which TPU # chip is actually visible. Otherwise the TPU driver will fail to # initialize because the number of devices would be different from # the number of visible worker addresses. os.environ["CLOUD_TPU_TASK_ID"] = str(global_rank) os.environ["TPU_VISIBLE_CHIPS"] = str(local_rank) pjrt.initialize_multiprocess(local_rank, local_world_size) xr._init_world_size_ordinal() self.groups = create_optimized_replica_groups() def all_reduce(self, input_: torch.Tensor) -> torch.Tensor: # TODO: Remove the groups specification after XLA compiler can support # auto-reordering the ring order for all-reduce. return xm.all_reduce(xm.REDUCE_SUM, input_, groups=self.groups) def all_gather(self, input_: torch.Tensor, dim: int = -1) -> torch.Tensor: assert dim == -1, "TPUs only support dim=-1 for all-gather." return xm.all_gather(input_, dim=dim)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/custom_all_reduce.py
vllm/distributed/device_communicators/custom_all_reduce.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from contextlib import contextmanager from typing import cast import torch import torch.distributed as dist from torch.distributed import ProcessGroup import vllm.envs as envs from vllm import _custom_ops as ops from vllm.distributed.device_communicators.all_reduce_utils import ( CUSTOM_ALL_REDUCE_MAX_SIZES, gpu_p2p_access_check, ) from vllm.distributed.parallel_state import in_the_same_node_as from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.utils.torch_utils import cuda_device_count_stateless try: ops.meta_size() custom_ar = True except Exception: # For CPUs custom_ar = False logger = init_logger(__name__) def _can_p2p(rank: int, world_size: int) -> bool: for i in range(world_size): if i == rank: continue if envs.VLLM_SKIP_P2P_CHECK: logger.debug("Skipping P2P check and trusting the driver's P2P report.") return torch.cuda.can_device_access_peer(rank, i) if not gpu_p2p_access_check(rank, i): return False return True def is_weak_contiguous(inp: torch.Tensor): return inp.is_contiguous() or ( inp.storage().nbytes() - inp.storage_offset() * inp.element_size() == inp.numel() * inp.element_size() ) class CustomAllreduce: _SUPPORTED_WORLD_SIZES = [2, 4, 6, 8] # max_size: max supported allreduce size def __init__( self, group: ProcessGroup, device: int | str | torch.device, max_size=8192 * 1024, symm_mem_enabled=False, ) -> None: """ Args: group: the process group to work on. If None, it will use the default process group. device: the device to bind the CustomAllreduce to. If None, it will be bound to f"cuda:{local_rank}". It is the caller's responsibility to make sure each communicator is bind to a unique device, and all communicators in this group are in the same node. """ self._IS_CAPTURING = False self.disabled = True if not custom_ar: # disable because of missing custom allreduce library # e.g. in a non-GPU environment logger.info( "Custom allreduce is disabled because " "of missing custom allreduce library" ) return self.group = group assert dist.get_backend(group) != dist.Backend.NCCL, ( "CustomAllreduce should be attached to a non-NCCL group." ) if not all(in_the_same_node_as(group, source_rank=0)): # No need to initialize custom allreduce for multi-node case. logger.warning( "Custom allreduce is disabled because this process group" " spans across nodes." ) return rank = dist.get_rank(group=self.group) self.rank = rank world_size = dist.get_world_size(group=self.group) if world_size == 1: # No need to initialize custom allreduce for single GPU case. return if world_size not in CustomAllreduce._SUPPORTED_WORLD_SIZES: logger.warning( "Custom allreduce is disabled due to an unsupported world" " size: %d. Supported world sizes: %s. To silence this " "warning, specify disable_custom_all_reduce=True explicitly.", world_size, str(CustomAllreduce._SUPPORTED_WORLD_SIZES), ) return if isinstance(device, int): device = torch.device(f"cuda:{device}") elif isinstance(device, str): device = torch.device(device) # now `device` is a `torch.device` object assert isinstance(device, torch.device) self.device = device device_capability = current_platform.get_device_capability() if ( current_platform.is_cuda() and symm_mem_enabled and device_capability is not None ): device_capability_str = device_capability.as_version_str() if device_capability_str in CUSTOM_ALL_REDUCE_MAX_SIZES: max_size = min( CUSTOM_ALL_REDUCE_MAX_SIZES[device_capability_str][world_size], max_size, ) cuda_visible_devices = envs.CUDA_VISIBLE_DEVICES if cuda_visible_devices: device_ids = list(map(int, cuda_visible_devices.split(","))) else: device_ids = list(range(cuda_device_count_stateless())) physical_device_id = device_ids[device.index] tensor = torch.tensor([physical_device_id], dtype=torch.int, device="cpu") gather_list = [ torch.tensor([0], dtype=torch.int, device="cpu") for _ in range(world_size) ] dist.all_gather(gather_list, tensor, group=self.group) physical_device_ids = [t.item() for t in gather_list] # test nvlink first, this will filter out most of the cases # where custom allreduce is not supported # this checks hardware and driver support for NVLink assert current_platform.is_cuda_alike() fully_connected = current_platform.is_fully_connected(physical_device_ids) if world_size > 2 and not fully_connected: logger.warning( "Custom allreduce is disabled because it's not supported on" " more than two PCIe-only GPUs. To silence this warning, " "specify disable_custom_all_reduce=True explicitly." ) return # test P2P capability, this checks software/cudaruntime support # this is expensive to compute at the first time # then we cache the result # On AMD GPU, p2p is always enabled between XGMI connected GPUs if not current_platform.is_rocm() and not _can_p2p(rank, world_size): logger.warning( "Custom allreduce is disabled because your platform lacks " "GPU P2P capability or P2P test failed. To silence this " "warning, specify disable_custom_all_reduce=True explicitly." ) return self.disabled = False # Buffers memory are owned by this Python class and passed to C++. # Metadata composes of two parts: metadata for synchronization and a # temporary buffer for storing intermediate allreduce results. self.meta_ptrs = self.create_shared_buffer( ops.meta_size() + max_size, group=group, uncached=True ) # This is a pre-registered IPC buffer. In eager mode, input tensors # are first copied into this buffer before allreduce is performed self.buffer_ptrs = self.create_shared_buffer(max_size, group=group) # This is a buffer for storing the tuples of pointers pointing to # IPC buffers from all ranks. Each registered tuple has size of # 8*world_size bytes where world_size is at most 8. Allocating 8MB # is enough for 131072 such tuples. The largest model I've seen only # needs less than 10000 of registered tuples. self.rank_data = torch.empty( 8 * 1024 * 1024, dtype=torch.uint8, device=self.device ) self.max_size = max_size self.rank = rank self.world_size = world_size self.fully_connected = fully_connected self._ptr = ops.init_custom_ar( self.meta_ptrs, self.rank_data, rank, self.fully_connected ) ops.register_buffer(self._ptr, self.buffer_ptrs) @contextmanager def capture(self): """ The main responsibility of this context manager is the `register_graph_buffers` call at the end of the context. It records all the buffer addresses used in the CUDA graph. """ try: self._IS_CAPTURING = True yield finally: self._IS_CAPTURING = False if not self.disabled: self.register_graph_buffers() def register_graph_buffers(self): handle, offset = ops.get_graph_buffer_ipc_meta(self._ptr) logger.info("Registering %d cuda graph addresses", len(offset)) # We cannot directly use `dist.all_gather_object` here # because it is incompatible with `gloo` backend under inference mode. # see https://github.com/pytorch/pytorch/issues/126032 for details. all_data: list[list[list[int] | None]] all_data = [[None, None] for _ in range(dist.get_world_size(group=self.group))] all_data[self.rank] = [handle, offset] ranks = sorted(dist.get_process_group_ranks(group=self.group)) for i, rank in enumerate(ranks): dist.broadcast_object_list( all_data[i], src=rank, group=self.group, device="cpu" ) # Unpack list of tuples to tuple of lists. handles = cast(list[list[int]], [d[0] for d in all_data]) offsets = cast(list[list[int]], [d[1] for d in all_data]) ops.register_graph_buffers(self._ptr, handles, offsets) def should_custom_ar(self, inp: torch.Tensor): if self.disabled: return False inp_size = inp.numel() * inp.element_size() # custom allreduce requires input byte size to be multiples of 16 if inp_size % 16 != 0: return False if not is_weak_contiguous(inp): return False # for 4 or more non NVLink-capable GPUs, custom allreduce provides # little performance improvement over NCCL. if self.world_size == 2 or self.fully_connected: return inp_size < self.max_size return False def all_reduce( self, inp: torch.Tensor, *, out: torch.Tensor = None, registered: bool = False ): """Performs an out-of-place all reduce. If registered is True, this assumes inp's pointer is already IPC-registered. Otherwise, inp is first copied into a pre-registered buffer. """ if out is None: out = torch.empty_like(inp) if registered: ops.all_reduce(self._ptr, inp, out, 0, 0) else: ops.all_reduce( self._ptr, inp, out, self.buffer_ptrs[self.rank], self.max_size ) return out def custom_all_reduce(self, input: torch.Tensor) -> torch.Tensor | None: """The main allreduce API that provides support for cuda graph.""" # When custom allreduce is disabled, this will be None. if self.disabled or not self.should_custom_ar(input): return None if self._IS_CAPTURING: if torch.cuda.is_current_stream_capturing(): return self.all_reduce(input, registered=True) else: # If warm up, mimic the allocation pattern since custom # allreduce is out-of-place. return torch.empty_like(input) else: # Note: outside of cuda graph context, custom allreduce incurs a # cost of cudaMemcpy, which should be small (<=1% of overall # latency) compared to the performance gain of using custom kernels return self.all_reduce(input, registered=False) def close(self): if not self.disabled and self._ptr: if ops is not None: ops.dispose(self._ptr) self._ptr = 0 self.free_shared_buffer(self.meta_ptrs, rank=self.rank) self.free_shared_buffer(self.buffer_ptrs, rank=self.rank) def __del__(self): self.close() @staticmethod def create_shared_buffer( size_in_bytes: int, group: ProcessGroup | None = None, uncached: bool | None = False, ) -> list[int]: pointer, handle = ops.allocate_shared_buffer_and_handle(size_in_bytes) world_size = dist.get_world_size(group=group) rank = dist.get_rank(group=group) handles = [None] * world_size dist.all_gather_object(handles, handle, group=group) pointers: list[int] = [] for i, h in enumerate(handles): if i == rank: pointers.append(pointer) # type: ignore else: pointers.append(ops.open_mem_handle(h)) return pointers @staticmethod def free_shared_buffer( pointers: list[int], group: ProcessGroup | None = None, rank: int | None = None, ) -> None: if rank is None: rank = dist.get_rank(group=group) if ops is not None: ops.free_shared_buffer(pointers[rank])
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/ray_communicator.py
vllm/distributed/device_communicators/ray_communicator.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import uuid from typing import Any import ray import torch from ray.exceptions import RayChannelError from ray.experimental.channel.communicator import Communicator, TorchTensorAllocator from torch.distributed import ReduceOp from vllm.distributed.device_communicators.base_device_communicator import ( DeviceCommunicatorBase, ) from vllm.distributed.parallel_state import get_pp_group from vllm.logger import init_logger from vllm.utils.torch_utils import current_stream logger = init_logger(__name__) class RayPPCommunicator(Communicator): """ Communicator to be used for pipeline parallelism in Ray Compiled Graph. This is wraps around the vLLM _PP GroupCoordinator. This class is not thread-safe. """ _comm: DeviceCommunicatorBase | None def __init__( self, world_size: int, comm_id: Any, rank: int | None, actor_handles: list["ray.actor.ActorHandle"], cuda_stream: torch.cuda.Stream | None, use_communication_streams: bool = False, ): """ Initialize a RayPPCommunicator that can be used to communicate with other Ray Compiled Graph actors for pipeline parallelism. Args: world_size: The number of participating actors. comm_id: A unique communicator ID. This is just to conform with the Ray Communicator API and is not used. rank: The rank of this actor. If None, then the caller is not a participant of the RayPPCommunicator group (e.g., the Ray driver). actor_handles: A list of actor handles. cuda_stream: A CUDA stream to dispatch communication ops to. This is not supported. use_communication_streams: Whether to use communication streams. This is not supported. """ self._world_size = world_size self._rank: int | None = None self._actor_handles = actor_handles if use_communication_streams: raise NotImplementedError("use_communication_streams is not supported") if cuda_stream is not None and cuda_stream != current_stream(): raise ValueError( "cuda_stream other than the current stream is not supported" ) if rank is not None: # Rank is not None, this is Ray worker assert ray.get_gpu_ids(), "RayPPCommunicator has no GPUs assigned" self._comm = get_pp_group().device_communicator assert self._comm is not None # Since we wrap around the vLLM _PP communicator, we use # the rank from the vLLM communicator, and ignore the rank # passed in from Ray. # TODO(rui): refactor the Ray Communicator API so that # it also supports no rank passed in. self._rank = self._comm.rank_in_group self._build_actor_rank_mapping() else: # Rank is None, this is Ray driver self._comm = None self._closed = False def _build_actor_rank_mapping(self): """ Use collective communication to build a mapping from actor IDs to ranks. This should be called once during initialization. """ if self._comm is None: return {} current_actor = ray.get_runtime_context().current_actor actor_id_str = current_actor._actor_id.hex() # Ray actor IDs are 32-character hex strings (128 bits) ACTOR_ID_LEN = 32 actor_id_bytes = bytearray(actor_id_str.encode("utf-8")) assert len(actor_id_bytes) == ACTOR_ID_LEN, ( f"Unexpected actor ID length: {len(actor_id_bytes)}" ) actor_id_tensor = torch.frombuffer(actor_id_bytes, dtype=torch.uint8).to( self._comm.device ) # All-gather full actor IDs from all actors gathered_ids = self._comm.all_gather(actor_id_tensor, dim=0) # Build mapping: actor_id -> device_comm_rank self._actor_id_to_rank = {} for rank in range(self._world_size): start_idx = rank * ACTOR_ID_LEN end_idx = (rank + 1) * ACTOR_ID_LEN actor_bytes = gathered_ids[start_idx:end_idx].cpu().numpy().tobytes() actor_id = actor_bytes.decode("utf-8") self._actor_id_to_rank[actor_id] = rank def initialize(self, rank: int) -> None: # No additional initialization is needed. pass def get_actor_handles(self) -> list["ray.actor.ActorHandle"]: return self._actor_handles def get_rank(self, actor: ray.actor.ActorHandle) -> int: """ Return the given actor's rank using device communicator collective ops. """ assert hasattr(self, "_actor_id_to_rank"), ( "Actor rank mapping not built. " "This should have been done during initialization." ) actor_id_str = actor._actor_id.hex() if actor_id_str in self._actor_id_to_rank: return self._actor_id_to_rank[actor_id_str] # type: ignore else: raise ValueError(f"Actor {actor} not found in communicator group") def get_self_rank(self) -> int | None: """ Return this actor's rank. """ return self._rank def get_world_size(self) -> int: """ Return the number of ranks in the RayPPCommunicator group. """ return self._world_size def send(self, buf: "torch.Tensor", peer_rank: int) -> None: """ Send a torch.Tensor to a peer. This returns when the send kernel has been queued, but the kernel may not have completed. Therefore, the caller should ensure that there are no concurrent writes to the sent `buf` until the send has finished. That is, either all writes should be submitted on the current stream (self._cuda_stream) or, if on a different stream, that stream should synchronize with the current stream. Args: buf: The torch.Tensor to send. It should already be on this actor's default device. peer_rank: The rank of the actor to send to. """ if self._closed: raise RayChannelError("RayPPCommunicator has been destroyed.") assert self._comm is not None self._comm.send(buf, peer_rank) def recv( self, shape: tuple[int, ...], dtype: "torch.dtype", peer_rank: int, allocator: TorchTensorAllocator, ) -> "torch.Tensor": """ Receive a torch.Tensor from a peer and synchronize the current stream. After this call returns, the receive buffer is safe to read from any stream. An RayChannelError will be raised if an error occurred (e.g., remote actor died), and the buffer is not safe to read. Args: shape: The shape of the tensor to receive. dtype: The dtype of the tensor to receive. peer_rank: The rank of the actor to receive from. allocator: The allocator to use to create the received tensor. This is ignored for this implementation. """ if self._closed: raise RayChannelError("RayPPCommunicator has been destroyed.") assert self._comm is not None size = torch.Size(shape) buf = self._comm.recv(size, dtype, src=peer_rank) # Buffer values are undefined if NCCL ops are aborted. Therefore, we # need to synchronize here and check that the channel is still # open to ensure that the receive buffer is valid. # TODO(swang): Avoid CUDA synchronization. current_stream().synchronize() if self._closed: raise RayChannelError("RayPPCommunicator has been destroyed.") return buf def allgather( self, send_buf: "torch.Tensor", recv_buf: "torch.Tensor", ): raise NotImplementedError("allgather is not supported") def allreduce( self, send_buf: "torch.Tensor", recv_buf: "torch.Tensor", op: ReduceOp = ReduceOp.SUM, ): raise NotImplementedError("allreduce is not supported") def reducescatter( self, send_buf: "torch.Tensor", recv_buf: "torch.Tensor", op: ReduceOp = ReduceOp.SUM, ): raise NotImplementedError("reducescatter is not supported") @property def recv_stream(self): return torch.cuda.StreamContext(current_stream()) @property def send_stream(self): return torch.cuda.StreamContext(current_stream()) def destroy(self) -> None: # Just sets a flag, vLLM manages the lifecycle of the underlying # _PP GroupCoordinator. self._closed = True def get_transport_name(self) -> str: return "nccl" @classmethod def generate_communicator_id(cls) -> Any: return uuid.uuid4()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/device_communicators/cpu_communicator.py
vllm/distributed/device_communicators/cpu_communicator.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os from typing import Any import torch from torch.distributed import ProcessGroup from vllm.distributed.utils import pickle from vllm.platforms import current_platform from vllm.platforms.interface import CpuArchEnum from .base_device_communicator import DeviceCommunicatorBase class CpuCommunicator(DeviceCommunicatorBase): def __init__( self, cpu_group: ProcessGroup, device: torch.device | None = None, device_group: ProcessGroup | None = None, unique_name: str = "", ): super().__init__(cpu_group, device, device_group, unique_name) self.dist_module = torch.distributed if ( (current_platform.get_cpu_architecture() == CpuArchEnum.X86) and hasattr(torch.ops._C, "init_shm_manager") and (unique_name.startswith("tp") or unique_name.startswith("pp")) ): self.dist_module = _CPUSHMDistributed(self) def all_reduce(self, input_): self.dist_module.all_reduce(input_, group=self.device_group) return input_ def gather( self, input_: torch.Tensor, dst: int = 0, dim: int = -1 ) -> torch.Tensor | None: """ NOTE: We assume that the input tensor is on the same device across all the ranks. NOTE: `dst` is the local rank of the destination rank. """ world_size = self.world_size assert -input_.dim() <= dim < input_.dim(), ( f"Invalid dim ({dim}) for input tensor with shape {input_.size()}" ) if dim < 0: # Convert negative dim to positive. dim += input_.dim() # Allocate output tensor. if self.rank_in_group == dst: gather_list = [torch.empty_like(input_) for _ in range(world_size)] else: gather_list = None # Gather. self.dist_module.gather( input_, gather_list, dst=self.ranks[dst], group=self.device_group ) if self.rank_in_group == dst: output_tensor = torch.cat(gather_list, dim=dim) else: output_tensor = None return output_tensor def all_gather(self, input_: torch.Tensor, dim: int = -1) -> torch.Tensor: if dim < 0: # Convert negative dim to positive. dim += input_.dim() input_size = input_.size() # NOTE: we have to use concat-style all-gather here, # stack-style all-gather has compatibility issues with # torch.compile . see https://github.com/pytorch/pytorch/issues/138795 output_size = (input_size[0] * self.world_size,) + input_size[1:] # Allocate output tensor. output_tensor = torch.empty( output_size, dtype=input_.dtype, device=input_.device ) # All-gather. self.dist_module.all_gather_into_tensor( output_tensor, input_, group=self.device_group ) # Reshape output_tensor = output_tensor.reshape((self.world_size,) + input_size) output_tensor = output_tensor.movedim(0, dim) output_tensor = output_tensor.reshape( input_size[:dim] + (self.world_size * input_size[dim],) + input_size[dim + 1 :] ) return output_tensor def send_tensor_dict( self, tensor_dict: dict[str, torch.Tensor | Any], dst: int, ) -> None: return self.dist_module.send_tensor_dict(tensor_dict, dst) def recv_tensor_dict( self, src: int, ) -> dict[str, torch.Tensor | Any]: return self.dist_module.recv_tensor_dict(src) class _CPUSHMDistributed: def __init__(self, communicator: CpuCommunicator): instance_identifier = os.environ["VLLM_DIST_IDENT"] unique_name = communicator.unique_name instance_identifier = f"{instance_identifier}-{unique_name}" self.communicator = communicator group_ranks = [str(rank) for rank in self.communicator.ranks] shm_group_identifier = f"[{'-'.join(group_ranks)}]" self.group_name = f"{instance_identifier}-{shm_group_identifier}-cpushm" self.handle = self._init_cpu_shm() def _init_cpu_shm(self) -> int: handle = torch.ops._C.init_shm_manager( self.group_name, self.communicator.world_size, self.communicator.rank, ) torch.distributed.barrier(self.communicator.device_group) torch.ops._C.join_shm_manager( handle, self.group_name, ) torch.distributed.barrier(self.communicator.device_group) return handle def all_reduce( self, input: torch.Tensor, group: ProcessGroup | None = None ) -> None: torch.ops._C.shm_allreduce(self.handle, input) def gather( self, input: torch.Tensor, gather_list: list[torch.Tensor] | None, dst: int = -1, group: ProcessGroup | None = None, ) -> None: # Note: different from the torch gather, here we use local dst rank. torch.ops._C.shm_gather( self.handle, input, gather_list, torch.distributed.get_group_rank(group, dst), ) def all_gather_into_tensor( self, output: torch.Tensor, input: torch.Tensor, group: ProcessGroup | None = None, ) -> None: torch.ops._C.shm_all_gather(self.handle, input, output) def send_tensor_dict( self, tensor_dict: dict[str, torch.Tensor | Any], dst: int, ) -> None: key_list = list(tensor_dict.keys()) value_list = list(tensor_dict.values()) size_list = [] for v in value_list: if not isinstance(v, torch.Tensor): raise RuntimeError("CpuCommunicator only supports sending tensors.") size_list.append(v.size()) key_size_tensor = torch.frombuffer( pickle.dumps([key_list, size_list]), dtype=torch.uint8 ) value_list.append(key_size_tensor) torch.ops._C.shm_send_tensor_list(self.handle, value_list, dst) return None def recv_tensor_dict( self, src: int, ) -> dict[str, torch.Tensor | Any]: tensor_list = torch.ops._C.shm_recv_tensor_list(self.handle, src) value_list: list[torch.Tensor] = tensor_list[:-1] key_size_tensor = tensor_list[-1] key_size = pickle.loads(key_size_tensor.numpy().tobytes()) key_list = key_size[0] size_list = key_size[1] assert len(key_list) == len(size_list) assert len(key_list) == len(value_list) tensor_dict: dict[str, torch.Tensor] = {} for key, size, t in zip(key_list, size_list, value_list): tensor_dict[key] = t.view(size) return tensor_dict
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/eplb/async_worker.py
vllm/distributed/eplb/async_worker.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ The async worker that transfers experts in the background. """ import asyncio import threading from typing import TYPE_CHECKING import torch from torch.distributed import ProcessGroup from vllm.distributed.parallel_state import get_ep_group from vllm.logger import init_logger from .rebalance_execute import transfer_layer if TYPE_CHECKING: from .eplb_state import EplbState logger = init_logger(__name__) def start_async_worker( state: "EplbState", rank_mapping: dict[int, int] | None = None, is_profile: bool = False, ) -> threading.Thread: ep_group = get_ep_group().device_group rank = ep_group.rank() device_index = state.cuda_device_index def thread_target() -> None: assert device_index is not None torch.cuda.set_device(device_index) cuda_stream = torch.cuda.Stream(device=device_index) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: loop.run_until_complete( transfer_run_periodically( state=state, ep_group=ep_group, is_profile=is_profile, rank_mapping=rank_mapping, cuda_stream=cuda_stream, ) ) except Exception as exc: # pragma: no cover - diagnostic path logger.exception("async loop error (Rank %d): %s", rank, str(exc)) finally: loop.close() thread = threading.Thread(target=thread_target, daemon=True) thread.start() return thread async def transfer_run_periodically( state: "EplbState", ep_group: ProcessGroup, is_profile: bool = False, rank_mapping: dict[int, int] | None = None, cuda_stream: torch.cuda.Stream = None, ) -> None: while True: await asyncio.to_thread(state.rearrange_event.wait) logger.info("async worker woke up for EPLB transfer") for model_state in state.model_states.values(): if not model_state.is_async_enabled: continue current_num_layers = model_state.model.num_moe_layers while ( model_state.rebalanced and model_state.layer_to_transfer < current_num_layers ): if ( not model_state.ep_buffer_ready and model_state.rebalanced and model_state.new_physical_to_logical_map is not None ): await asyncio.to_thread(model_state.buffer_lock.acquire) try: if model_state.layer_to_transfer >= current_num_layers: break ( model_state.is_unchanged, model_state.is_received_locally, model_state.experts_recv_loc, ) = await transfer_layer( old_global_expert_indices=model_state.physical_to_logical_map, new_global_expert_indices=model_state.new_physical_to_logical_map, expert_weights=model_state.model.expert_weights, expert_weights_buffer=model_state.expert_buffer, ep_group=ep_group, is_profile=is_profile, layer=model_state.layer_to_transfer, cuda_stream=cuda_stream, rank_mapping=rank_mapping, ) event = torch.cuda.Event(blocking=False) cuda_stream.record_event(event) model_state.buffer_ready_event = event model_state.ep_buffer_ready = 1 finally: model_state.buffer_lock.release() else: if not model_state.rebalanced: break await asyncio.sleep(0.001) state.rearrange_event.clear()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/eplb/rebalance_execute.py
vllm/distributed/eplb/rebalance_execute.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ The actual execution of the rearrangement. This involves the exchange of expert weights between GPUs. """ from collections.abc import Iterable, MutableSequence, Sequence from functools import partial import torch from torch.distributed import ( P2POp, ProcessGroup, all_gather, batch_isend_irecv, get_global_rank, ) def idx_local_to_global( local_idx: int, local_cnt: int, ep_rank: int, ) -> int: """ Convert a local expert index to a global expert index. """ return ep_rank * local_cnt + local_idx def idx_global_to_local( global_idx: int, local_cnt: int, ep_rank: int, ) -> int: """ Convert a global expert index to a local expert index. """ return global_idx - ep_rank * local_cnt def global_idx_to_rank( global_idx: int, local_cnt: int, ) -> int: """ Convert a global expert index to a rank index. """ return global_idx // local_cnt def get_ep_ranks_with_expert( idx: int, num_local_experts: int, old_indices: Sequence[int], new_indices: Sequence[int], ) -> tuple[MutableSequence[int], MutableSequence[int]]: """ Get the ranks of the experts that need to be exchanged. Args: idx: The index of the expert. num_local_experts: The number of local experts. old_indices: The old indices of the experts. new_indices: The new indices of the experts. Returns: A tuple of two lists: - The ranks of the experts that need to be sent. - The ranks of the experts that need to be received. """ global2rank = partial( global_idx_to_rank, local_cnt=num_local_experts, ) ranks_to_send: list[int] = [] ranks_to_recv: list[int] = [] for i, e in enumerate(old_indices): if e == idx: rank = global2rank(i) if not ranks_to_send or ranks_to_send[-1] != rank: ranks_to_send.append(rank) for i, e in enumerate(new_indices): if e == idx: rank = global2rank(i) if not ranks_to_recv or ranks_to_recv[-1] != rank: ranks_to_recv.append(rank) # Remove those ranks that can get this expert locally. ranks_to_send_set = set(ranks_to_send) ranks_to_recv_actual = [ rank for rank in ranks_to_recv if rank not in ranks_to_send_set ] return ranks_to_send, ranks_to_recv_actual def move_to_buffer( num_local_experts: int, old_indices: Sequence[int], new_indices: Sequence[int], expert_weights: Iterable[torch.Tensor], expert_weights_buffer: Sequence[torch.Tensor], cuda_stream: torch.cuda.Stream | None, ep_group: ProcessGroup, ) -> tuple[list[bool], list[bool], dict[int, int]]: """ Perform expert weights rearrangement of one layer. """ ep_rank = ep_group.rank() local2global = partial( idx_local_to_global, local_cnt=num_local_experts, ep_rank=ep_rank, ) # 0. Do nothing for experts that did not change. is_unchanged = [ old_indices[local2global(i)] == new_indices[local2global(i)] for i in range(num_local_experts) ] # 1. Perform weight copy inside the local rank. is_received_locally = is_unchanged[:] for src in range(num_local_experts): src_global = local2global(src) for dst in range(num_local_experts): dst_global = local2global(dst) if is_received_locally[dst]: continue if old_indices[src_global] == -1 or new_indices[dst_global] == -1: continue if old_indices[src_global] == new_indices[dst_global]: is_received_locally[dst] = True for weight, buffer in zip(expert_weights, expert_weights_buffer): with torch.cuda.stream(cuda_stream): buffer[dst].copy_(weight[src], non_blocking=True) p2p_ops: list[P2POp] = [] # 2. Initiate sending of weights. experts_send_loc: dict[int, int] = {} for src in range(num_local_experts): expert = old_indices[local2global(src)] if expert == -1: continue if expert in experts_send_loc: continue experts_send_loc[expert] = src # We need to sort here to match send/recv for expert, src in sorted(experts_send_loc.items()): ranks_to_send, ranks_to_recv = get_ep_ranks_with_expert( expert, num_local_experts, old_indices, new_indices, ) # Calculate the ranks to send by this rank num_dst_per_sender = len(ranks_to_recv) // len(ranks_to_send) sender_pos = ranks_to_send.index(ep_rank) recv_begin = sender_pos * num_dst_per_sender recv_end = recv_begin + num_dst_per_sender recv_ranks = ranks_to_recv[recv_begin:recv_end] # Tackle remainders remainder_start = len(ranks_to_send) * num_dst_per_sender recver_pos = remainder_start + sender_pos if recver_pos < len(ranks_to_recv): recv_ranks.append(ranks_to_recv[recver_pos]) for dst in recv_ranks: dst_global = get_global_rank(ep_group, dst) p2p_ops += [ P2POp( torch.distributed.isend, weight[src], dst_global, ) for weight in expert_weights ] # 3. Initiate receiving of weights. experts_recv_loc: dict[int, int] = {} for dst in range(num_local_experts): if is_received_locally[dst]: continue expert = new_indices[local2global(dst)] if expert == -1: continue if expert in experts_recv_loc: continue experts_recv_loc[expert] = dst # We need to sort here to match send/recv for expert, dst in sorted(experts_recv_loc.items()): ranks_to_send, ranks_to_recv = get_ep_ranks_with_expert( expert, num_local_experts, old_indices, new_indices, ) # Calculate the rank to recv by this rank num_dst_per_sender = len(ranks_to_recv) // len(ranks_to_send) recver_pos = ranks_to_recv.index(ep_rank) remainder_start = len(ranks_to_send) * num_dst_per_sender if recver_pos < remainder_start: src = ranks_to_send[recver_pos // num_dst_per_sender] else: src = ranks_to_send[recver_pos - remainder_start] src_global = get_global_rank(ep_group, src) p2p_ops += [ P2POp( torch.distributed.irecv, weight[dst], src_global, ) for weight in expert_weights_buffer ] # 4. Execute the P2P operations. The real communication happens here. if p2p_ops and cuda_stream is not None: with torch.cuda.stream(cuda_stream): reqs = batch_isend_irecv(p2p_ops) for req in reqs: req.wait() elif p2p_ops: reqs = batch_isend_irecv(p2p_ops) for req in reqs: req.wait() # wait for the communication to finish return is_unchanged, is_received_locally, experts_recv_loc def move_from_buffer( expert_weights: Iterable[torch.Tensor], expert_weights_buffer: list[torch.Tensor], is_unchanged: list[bool], is_received_locally: list[bool], experts_recv_loc: dict[int, int], new_indices: Sequence[int], ep_group: ProcessGroup, ) -> None: ep_rank = ep_group.rank() num_local_experts = len(is_unchanged) local2global = partial( idx_local_to_global, local_cnt=num_local_experts, ep_rank=ep_rank ) for dst in range(num_local_experts): if is_unchanged[dst]: continue if is_received_locally[dst]: for weight, buffer in zip(expert_weights, expert_weights_buffer): weight[dst].copy_(buffer[dst], non_blocking=True) else: expert = new_indices[local2global(dst)] if expert == -1: continue src = experts_recv_loc[expert] for weight, buffer in zip(expert_weights, expert_weights_buffer): weight[dst].copy_(buffer[src], non_blocking=True) async def transfer_layer( old_global_expert_indices: torch.Tensor, new_global_expert_indices: torch.Tensor, expert_weights: Sequence[Iterable[torch.Tensor]], expert_weights_buffer: Sequence[torch.Tensor], ep_group: ProcessGroup, is_profile: bool = False, layer: int = 0, cuda_stream: torch.cuda.Stream | None = None, rank_mapping: dict[int, int] | None = None, ) -> tuple[list[bool], list[bool], dict[int, int]]: """ Rearranges the expert weights in place according to the new expert indices. The value of the indices arguments are logical indices of the experts, while keys are physical. Args: old_global_expert_indices: Shape (num_moe_layers, num_physical_experts). new_global_expert_indices: Shape (num_moe_layers, num_physical_experts). expert_weights: A sequence of shape (num_moe_layers)(weight_count) of tensors of shape (num_local_physical_experts, hidden_size_i). For example, a linear layer may have up and down projection, so weight_count = 2. Each weight's hidden size can be different. ep_group: The device process group for expert parallelism. 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. """ ep_size = ep_group.size() if rank_mapping is not None: if len(rank_mapping) == ep_group.size(): # scale down new_global_expert_indices = _map_new_expert_indices_with_rank_mapping( new_global_expert_indices, rank_mapping, ) else: # scale up old_global_expert_indices = _map_old_expert_indices_with_rank_mapping( old_global_expert_indices, rank_mapping, ep_group.size(), ) assert old_global_expert_indices.shape[1] == new_global_expert_indices.shape[1] num_moe_layers, num_physical_experts = old_global_expert_indices.shape assert len(expert_weights) == num_moe_layers num_local_physical_experts = next(iter(expert_weights[0])).shape[0] assert new_global_expert_indices.shape == (num_moe_layers, num_physical_experts) assert num_physical_experts == ep_size * num_local_physical_experts is_unchanged, is_received_locally, experts_recv_loc = move_to_buffer( num_local_experts=num_local_physical_experts, old_indices=old_global_expert_indices[layer].tolist(), new_indices=new_global_expert_indices[layer].tolist(), expert_weights=expert_weights[layer], expert_weights_buffer=expert_weights_buffer, cuda_stream=cuda_stream, ep_group=ep_group, ) return is_unchanged, is_received_locally, experts_recv_loc def rearrange_expert_weights_inplace( old_global_expert_indices: torch.Tensor, new_global_expert_indices: torch.Tensor, expert_weights: Sequence[Iterable[torch.Tensor]], ep_group: ProcessGroup, is_profile: bool = False, rank_mapping: dict[int, int] | None = None, ) -> None: """ Rearranges the expert weights in place according to the new expert indices. The value of the indices arguments are logical indices of the experts, while keys are physical. Args: old_global_expert_indices: Shape (num_moe_layers, num_physical_experts). new_global_expert_indices: Shape (num_moe_layers, num_physical_experts). expert_weights: A sequence of shape (num_moe_layers)(weight_count) of tensors of shape (num_local_physical_experts, hidden_size_i). For example, a linear layer may have up and down projection, so weight_count = 2. Each weight's hidden size can be different. ep_group: The device process group for expert parallelism. 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. rank_mapping: A dictionary mapping old rank to new rank. """ if rank_mapping is not None: if len(rank_mapping) == ep_group.size(): # scale down new_global_expert_indices = _map_new_expert_indices_with_rank_mapping( new_global_expert_indices, rank_mapping, ) else: # scale up old_global_expert_indices = _map_old_expert_indices_with_rank_mapping( old_global_expert_indices, rank_mapping, ep_group.size(), ) assert old_global_expert_indices.shape[1] == new_global_expert_indices.shape[1] num_moe_layers, num_physical_experts = old_global_expert_indices.shape assert len(expert_weights) == num_moe_layers num_local_physical_experts = next(iter(expert_weights[0])).shape[0] assert new_global_expert_indices.shape == (num_moe_layers, num_physical_experts) ep_size = ep_group.size() assert num_physical_experts == ep_size * num_local_physical_experts # A buffer to hold the expert weights in one layer during the exchange. # NOTE: Currently we assume the same weights across different layers # have the same shape. expert_weights_buffer = [torch.empty_like(w) for w in expert_weights[0]] if is_profile: # Maximum send size is to send all local experts to all ranks, # So we use a dummy `all_gather` to reserve enough communication buffer for weight, buffer in zip(expert_weights[0], expert_weights_buffer): # A `/dev/null`-like buffer to avoid real memory allocation dummy_recv_buffer = [buffer for _ in range(ep_size)] # NOTE(bowen): Needed this barrier to avoid OOM during actual # execution. I'm not very sure why this is needed torch.distributed.barrier() all_gather( dummy_recv_buffer, weight, group=ep_group, ) return old_global_expert_indices_cpu = old_global_expert_indices.cpu() new_global_expert_indices_cpu = new_global_expert_indices.cpu() # NOTE(bowen): We need this synchronize to run, but I don't know why. # If you figure out the reason, please let me know -- thank you! torch.cuda.synchronize() for layer in range(num_moe_layers): is_unchanged, is_received_locally, experts_recv_loc = move_to_buffer( num_local_experts=num_local_physical_experts, old_indices=old_global_expert_indices_cpu[layer].tolist(), new_indices=new_global_expert_indices_cpu[layer].tolist(), expert_weights=expert_weights[layer], expert_weights_buffer=expert_weights_buffer, cuda_stream=None, ep_group=ep_group, ) move_from_buffer( expert_weights=expert_weights[layer], expert_weights_buffer=expert_weights_buffer, is_unchanged=is_unchanged, is_received_locally=is_received_locally, experts_recv_loc=experts_recv_loc, new_indices=new_global_expert_indices[layer].tolist(), ep_group=ep_group, ) def _map_old_expert_indices_with_rank_mapping( old_global_expert_indices: torch.Tensor, rank_mapping: dict[int, int], new_ep_size: int, ) -> torch.Tensor: """ Map the old global expert indices to the new global expert indices. Args: old_global_expert_indices: Shape (num_layers, old_ep_size * num_local_physical_experts). rank_mapping: Mapping from old rank to new rank. new_ep_size: New expert parallelism size. Returns: Mapped expert indices with shape (num_layers, new_ep_size * num_local_physical_experts). """ num_layers, old_num_physical_experts = old_global_expert_indices.shape assert rank_mapping, "Rank mapping is required" # Get sizes from parameters and rank_mapping old_ep_size = len(rank_mapping) num_local_physical_experts = old_num_physical_experts // old_ep_size new_num_physical_experts = new_ep_size * num_local_physical_experts # Create mapped tensor with new shape, initialized to -1 mapped_expert_indices = torch.full( (num_layers, new_num_physical_experts), fill_value=-1, dtype=old_global_expert_indices.dtype, device=old_global_expert_indices.device, ) # Handle rank mapping (scale up/down with rank changes) for old_rank in range(old_ep_size): new_rank = rank_mapping.get(old_rank) if new_rank is not None and new_rank >= 0 and new_rank < new_ep_size: # This old rank exists in the new configuration old_start_idx = old_rank * num_local_physical_experts old_end_idx = (old_rank + 1) * num_local_physical_experts new_start_idx = new_rank * num_local_physical_experts new_end_idx = (new_rank + 1) * num_local_physical_experts mapped_expert_indices[:, new_start_idx:new_end_idx] = ( old_global_expert_indices[:, old_start_idx:old_end_idx] ) # If new_rank is None or >= new_ep_size, the experts remain -1 # (scale down case) return mapped_expert_indices def _map_new_expert_indices_with_rank_mapping( new_global_expert_indices: torch.Tensor, rank_mapping: dict[int, int], ) -> torch.Tensor: num_layers, new_num_physical_experts = new_global_expert_indices.shape assert rank_mapping, "Rank mapping is required" # Get sizes from parameters and rank_mapping old_ep_size = len(rank_mapping) new_ep_size = sum(new_rank != -1 for new_rank in rank_mapping.values()) num_local_physical_experts = new_num_physical_experts // new_ep_size old_num_physical_experts = old_ep_size * num_local_physical_experts mapped_expert_indices = torch.full( (num_layers, old_num_physical_experts), fill_value=-1, dtype=new_global_expert_indices.dtype, device=new_global_expert_indices.device, ) for old_rank in range(old_ep_size): new_rank = rank_mapping[old_rank] if new_rank >= 0 and new_rank < new_ep_size: old_start_idx = old_rank * num_local_physical_experts old_end_idx = (old_rank + 1) * num_local_physical_experts new_start_idx = new_rank * num_local_physical_experts new_end_idx = (new_rank + 1) * num_local_physical_experts mapped_expert_indices[:, old_start_idx:old_end_idx] = ( new_global_expert_indices[:, new_start_idx:new_end_idx] ) return mapped_expert_indices __all__ = ["transfer_layer", "move_from_buffer"]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/eplb/eplb_state.py
vllm/distributed/eplb/eplb_state.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Expert parallelism load balancer (EPLB) metrics and states. # Glossary - **Logical Expert**: An expert that is part of the model's logical structure. It holds a set of weights and is replicated across multiple physical experts. - **Redundant Expert**: To achieve load balancing, for some popular logical experts, we create additional copies of the expert weights. During inference, each of these copies can be routed to by the same set of tokens. - **Physical Expert**: An expert that is instantiated on a specific device. It is a replica of a logical expert and can be rearranged across devices. I.e., one logical expert may have multiple sets of weights initialized on different devices, and each of these sets is a physical expert. - **Local Physical Expert**: A physical expert that is instantiated on the current device. For example: DeepSeek-R1 has 256 logical experts, so each MoE layer has 256 sets of linear layer weights in the model parameters. If we add 32 redundant experts, DeepSeek-R1 will have 256 + 32 = 288 physical experts in total. And when deploying, we'll have 288 sets of linear layer weights for each MoE layer. If we have 32 EP ranks, then each GPU will hold 288 / 32 = 9 local physical experts. """ import threading import time from collections.abc import Sequence from dataclasses import dataclass import torch from torch.distributed import ProcessGroup, all_reduce from vllm.config import ModelConfig, ParallelConfig from vllm.distributed.parallel_state import ( get_ep_group, get_node_count, in_the_same_node_as, ) from vllm.distributed.utils import StatelessProcessGroup from vllm.logger import init_logger from vllm.model_executor.models.interfaces import MixtureOfExperts from .async_worker import start_async_worker from .policy import EPLB_POLICIES, AbstractEplbPolicy, DefaultEplbPolicy from .rebalance_execute import move_from_buffer, rearrange_expert_weights_inplace logger = init_logger(__name__) @dataclass class EplbModelState: """EPLB metrics.""" physical_to_logical_map: torch.Tensor """ Mapping from physical experts to logical experts. Shape: (num_moe_layers, num_physical_experts) # Example For a 2-layer MoE model with 6 physical experts and 4 logical experts on 3 EP ranks, the mapping could look like this: ``` [[0, 1, 2, 3, 0, 1], [0, 2, 0, 1, 0, 3]] ``` """ logical_to_physical_map: torch.Tensor """ Mapping from logical experts to physical experts. This is a sparse matrix, where -1 indicates no mapping. Shape: (num_moe_layers, num_logical_experts, num_redundant_experts + 1) # Example For a 2-layer MoE model with 6 physical experts and 4 logical experts on 3 EP ranks, the mapping could look like this: ``` [[[0, 4, -1], [1, 5, -1], [2, -1, -1], [3, -1, -1]], [[0, 2, 4], [3, -1, -1], [1, -1, -1], [5, -1, -1]]] ``` """ logical_replica_count: torch.Tensor """ Number of replicas for each logical expert. This is exactly the non-`-1` count in the `logical_to_physical_map`. Shape: (num_moe_layers, num_logical_experts) # Example For a 2-layer MoE model with 6 physical experts and 4 logical experts on 3 EP ranks, the count could look like this: ``` [[2, 2, 1, 1], [3, 1, 1, 1]] """ expert_load_pass: torch.Tensor """ Expert load during this forward pass. We use the token count each expert processes as the load. Shape: (num_moe_layers, num_physical_experts) """ expert_load_window: torch.Tensor """ A sliding window of expert load. Shape: (window_size, num_moe_layers, num_physical_experts) NOTE: The expert_load_view now records load for all physical experts rather than just local experts. This ensures consistent load statistics across different dispatch methods (naive all-to-all, DeepEP, pplx-kernels). The recorded load will be multiplied by dp_size when using naive all-to-all due to each DP rank contributing the same token set to the calculation. See: https://github.com/vllm-project/vllm/pull/22167#pullrequestreview-3086143856 """ model_name: str model: MixtureOfExperts expert_buffer: list[torch.Tensor] """ The buffer to store the expert weights during transfer. """ buffer_lock: threading.Lock """ The lock to protect the expert buffer. """ buffer_ready_event: torch.cuda.Event | None """ CUDA event recorded when the async worker finishes filling the buffer. The main thread waits on this before consuming the buffer. """ ep_buffer_ready: int """ The flag indicates whether the expert buffer is ready for transfer. 0 or 1. """ layer_to_transfer: int """ The layer index to transfer in async mode. """ rebalanced: bool """ The flag indicates whether the experts rebalance have been computed. """ pending_global_ready_check: bool """ Whether the async EPLB needs to poll peers for buffer readiness. """ is_unchanged: list[bool] """ intermediate variable between `move_to_buffer` and `move_to_workspace`. The size is same as the num of physical experts in the current layer. """ is_received_locally: list[bool] """ intermediate variable between `move_to_buffer` and `move_to_workspace`. The size is same as the num of physical experts in the current layer. """ experts_recv_loc: dict[int, int] """ intermediate variable between `move_to_buffer` and `move_to_workspace`. The size is same as the num of physical experts in the current layer. """ is_async_enabled: bool """ The flag indicates whether the EPLB is running in async mode. """ cuda_device_index: int | None """ CUDA device index for the async EPLB worker thread. """ new_physical_to_logical_map: torch.Tensor | None = None """ intermediate variable between `move_to_buffer` and `move_to_workspace`. the size is same as physical_to_logical_map """ new_logical_to_physical_map: torch.Tensor | None = None """ intermediate variable between `move_to_buffer` and `move_to_workspace`. the size is same as logical_to_physical_map """ new_logical_replica_count: torch.Tensor | None = None """ intermediate variable between `move_to_buffer` and `move_to_workspace`. the size is same as logical_replica_count """ class EplbState: """ EplbState of each expert parallel model. Key is the model config hash. """ def __init__(self, parallel_config: ParallelConfig, device: torch.device): self.parallel_config = parallel_config self.device = device self.model_states: dict[str, EplbModelState] = {} self.policy: type[AbstractEplbPolicy] = DefaultEplbPolicy """ Selected EPLB algorithm class """ self.expert_load_window_step: int = 0 """ Current step in the sliding window. Different from `expert_rearrangement_step`, each EP rank may have its own `expert_load_window_step`. """ self.expert_load_window_size: int = 0 """ Size of the expert load sliding window. This is a constant and is taken from the config. """ self.expert_rearrangement_step: int = 0 """ Steps after last rearrangement. Will trigger a rearrangement if it exceeds the threshold. NOTE: Keep in mind that all EP ranks need to have the same `expert_rearrangement_step` value to ensure synchronization. Otherwise, the rearrangement will hang at collective communication calls. """ self.expert_rearrangement_step_interval: int = 0 """ Interval for expert rearrangement steps. This is a constant and is taken from the config. """ self.is_async: bool = False """ The flag indicates whether the EPLB is running in async mode. """ self.rearrange_event = threading.Event() """ Event to signal when a new rearrangement is needed for the async thread. """ self.async_worker: threading.Thread | None = None """ Background thread handling async transfers. """ self.cuda_device_index: int | None = None """ CUDA 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.cuda.current_device() @staticmethod def build_initial_global_physical_to_logical_map( num_routed_experts: int, num_redundant_experts: int, ) -> Sequence[int]: """ Build an initial expert arrangement using the following structure: [original routed experts, redundant experts] Returns: physical_to_logical_map (Sequence[int]): A list of integers, where each integer is the index of the logical expert that the corresponding physical expert maps to. """ global_physical_to_logical_map = list(range(num_routed_experts)) global_physical_to_logical_map += [ i % num_routed_experts for i in range(num_redundant_experts) ] return global_physical_to_logical_map def validate_ep_configuration(self, new_model: MixtureOfExperts): """ Validate that the expert parallel configuration of the new model is the same as the existing models. """ if len(self.model_states) > 0: model = next(iter(self.model_states.values())).model if ( model.num_routed_experts != new_model.num_routed_experts or model.num_redundant_experts != new_model.num_redundant_experts or model.num_physical_experts != new_model.num_physical_experts or model.num_logical_experts != new_model.num_logical_experts or model.num_expert_groups != new_model.num_expert_groups ): raise RuntimeError( "Model: {} " "with config {} " "{} {} {} {} " "mismatch with new model {} " "with config {} " "{} {} {} {}".format( type(model), model.num_routed_experts, model.num_redundant_experts, model.num_physical_experts, model.num_logical_experts, model.num_expert_groups, type(new_model), new_model.num_routed_experts, new_model.num_redundant_experts, new_model.num_physical_experts, new_model.num_logical_experts, new_model.num_expert_groups, ) ) def add_model( self, model: MixtureOfExperts, model_config: ModelConfig, global_expert_load: torch.Tensor | None = None, old_global_expert_indices: torch.Tensor | None = None, rank_mapping: dict[int, int] | None = None, ): """ Build the initial EPLB state. """ self.validate_ep_configuration(model) self.is_async = self.parallel_config.eplb_config.use_async physical_to_logical_map_list = ( EplbState.build_initial_global_physical_to_logical_map( model.num_routed_experts, model.num_redundant_experts, ) ) physical_to_logical_map = torch.tensor( physical_to_logical_map_list, device=self.device, ) # Assuming 8 GPUs per node, this supports up to # (1023 + 1) / 8 = 128 nodes for now. # TODO(rui): make this configurable MAX_EXPERT_REDUNDANCY = 1023 assert model.num_redundant_experts <= MAX_EXPERT_REDUNDANCY, ( f"num_redundant_experts {model.num_redundant_experts} " f"must be less than or equal to {MAX_EXPERT_REDUNDANCY}" ) max_slots_per_logical_expert = MAX_EXPERT_REDUNDANCY + 1 logical_to_physical_map = torch.full( (model.num_logical_experts, max_slots_per_logical_expert), -1, device=self.device, ) logical_replica_count = torch.zeros( (model.num_logical_experts,), device=self.device, dtype=torch.long, ) for i in range(model.num_physical_experts): logical_idx = physical_to_logical_map[i] logical_to_physical_map[logical_idx, logical_replica_count[logical_idx]] = i logical_replica_count[logical_idx] += 1 # Duplicate initial mapping for all layers physical_to_logical_map = ( physical_to_logical_map.unsqueeze(0) .expand( model.num_moe_layers, -1, ) .contiguous() ) logical_to_physical_map = ( logical_to_physical_map.unsqueeze(0) .expand( model.num_moe_layers, -1, -1, ) .contiguous() ) logical_replica_count = ( logical_replica_count.unsqueeze(0) .expand( model.num_moe_layers, -1, ) .contiguous() ) expert_load_pass = torch.zeros( (model.num_moe_layers, model.num_physical_experts), dtype=torch.int32, device=self.device, ) self.expert_load_window_size = self.parallel_config.eplb_config.window_size expert_load_window = torch.zeros( ( self.expert_load_window_size, model.num_moe_layers, model.num_physical_experts, ), dtype=torch.int32, device=self.device, ) # Set the initial progress of rearrangement to 3/4 eplb_step_interval = self.parallel_config.eplb_config.step_interval self.expert_rearrangement_step = max( 0, eplb_step_interval - eplb_step_interval // 4 ) self.expert_rearrangement_step_interval = eplb_step_interval # Set the policy based on the selected eplb algorithm type. policy_type = self.parallel_config.eplb_config.policy self.policy = EPLB_POLICIES[policy_type] logger.debug("Selected EPLB policy: %d", policy_type) if global_expert_load is not None: ep_group = get_ep_group().device_group assert global_expert_load.shape == ( model.num_moe_layers, model.num_logical_experts, ) assert global_expert_load.dtype == torch.int64 num_replicas = model.num_physical_experts num_groups = model.num_expert_groups num_nodes = get_node_count() num_gpus = ep_group.size() if num_gpus % num_nodes != 0: num_nodes = 1 logger.warning_once( f"num_gpus % num_nodes != 0, " "not using hierarchical rearrangement algorithm.\n" f"{num_gpus=}, {num_nodes=}" ) # Get new expert mappings ( new_physical_to_logical_map, new_logical_to_physical_map, new_logical_replica_count, ) = self.policy.rebalance_experts( global_expert_load, num_replicas, num_groups, num_nodes, num_gpus, ) max_physical_slots = new_logical_to_physical_map.shape[-1] assert max_physical_slots <= logical_to_physical_map.shape[-1] new_logical_to_physical_map = torch.nn.functional.pad( new_logical_to_physical_map, (0, logical_to_physical_map.shape[-1] - max_physical_slots), value=-1, ) physical_to_logical_map = new_physical_to_logical_map.to(self.device) logical_to_physical_map.copy_(new_logical_to_physical_map) logical_replica_count.copy_(new_logical_replica_count) else: new_physical_to_logical_map = None new_logical_to_physical_map = None new_logical_replica_count = None model.set_eplb_state( expert_load_pass, logical_to_physical_map, logical_replica_count, ) if global_expert_load is not None: rearrange_expert_weights_inplace( old_global_expert_indices, new_physical_to_logical_map, model.expert_weights, ep_group, False, rank_mapping, ) self.expert_rearrangement_step = 0 expert_buffer = [torch.empty_like(w) for w in model.expert_weights[0]] model_state = EplbModelState( physical_to_logical_map=physical_to_logical_map, logical_to_physical_map=logical_to_physical_map, logical_replica_count=logical_replica_count, expert_load_pass=expert_load_pass, expert_load_window=expert_load_window, model_name=model_config.model, model=model, expert_buffer=expert_buffer, buffer_lock=threading.Lock(), buffer_ready_event=None, ep_buffer_ready=0, layer_to_transfer=0, rebalanced=False, pending_global_ready_check=False, is_unchanged=[], is_received_locally=[], experts_recv_loc={}, is_async_enabled=self.is_async, cuda_device_index=self.cuda_device_index, new_physical_to_logical_map=new_physical_to_logical_map, new_logical_to_physical_map=new_logical_to_physical_map, new_logical_replica_count=new_logical_replica_count, ) self.model_states[model_config.compute_hash()] = model_state def step( self, is_dummy: bool = False, is_profile: bool = False, log_stats: bool = False, ) -> None: """ Step the EPLB state. Args: is_dummy (bool): If `True`, this is a dummy step and the load metrics recorded in this forward pass will not count. Defaults to `False`. is_profile (bool): If `True`, perform a dummy rearrangement with maximum communication cost. This is used in `profile_run` to reserve enough memory for the communication buffer. log_stats (bool): If `True`, log the expert load metrics. # Stats The metrics are all summed up across layers. - `avg_tokens`: The average load across ranks. - `max_tokens`: The maximum load across ranks. - `balancedness`: The ratio of average load to maximum load. """ ep_group = get_ep_group().device_group if is_profile: self.rearrange(is_profile=True) return if is_dummy: # Do not record load metrics for dummy steps for eplb_model_state in self.model_states.values(): eplb_model_state.expert_load_pass.zero_() if log_stats: # Sync the expert load pass for each model (main and drafter). # expert_load_pass: (num_moe_layers, num_physical_experts) expert_load_pass_list = self._sync_load_pass() ep_group = get_ep_group().device_group for expert_load_pass, eplb_model_state in zip( expert_load_pass_list, self.model_states.values() ): # num_tokens_per_rank: (num_moe_layers, num_ranks) num_tokens_per_rank = ( expert_load_pass.reshape( expert_load_pass.shape[0], ep_group.size(), -1 ) .sum(dim=-1) .float() ) # Compute balancedness ratio: # for each layer: # (mean load across ranks) / (max load across ranks) avg_tokens_tensor = num_tokens_per_rank.mean(dim=0).sum(dim=0) max_tokens_tensor = num_tokens_per_rank.max(dim=0).values.sum(dim=0) # Just to make type checker happy tokens_tensors: list[float] = torch.stack( [avg_tokens_tensor, max_tokens_tensor] ).tolist() avg_tokens, max_tokens = tokens_tensors balancedness = avg_tokens / max_tokens if max_tokens > 0 else 0.0 if ep_group.rank() == 0: logger.info( "EPLB step: %d for model %s: avg_tokens=%.2f, " "max_tokens=%d, balancedness=%.4f", self.expert_rearrangement_step, eplb_model_state.model_name, avg_tokens, max_tokens, balancedness, ) # Update the expert load sliding window if not is_dummy: for eplb_model_state in self.model_states.values(): eplb_model_state.expert_load_window[self.expert_load_window_step] = ( eplb_model_state.expert_load_pass.clone() ) eplb_model_state.expert_load_pass.zero_() self.expert_load_window_step += 1 if self.expert_load_window_step >= self.expert_load_window_size: self.expert_load_window_step = 0 # Step the expert rearrangement step # Note that even if this is a dummy step, we still increment the # rearrangement step and perform rearrangement to ensure all ranks are # performing collective communication. self.expert_rearrangement_step += 1 if self.is_async: for eplb_model_state in self.model_states.values(): if not eplb_model_state.is_async_enabled: continue all_ranks_buffer_ready = False if eplb_model_state.pending_global_ready_check: all_ranks_buffer_ready = self._all_ranks_buffer_ready( eplb_model_state ) if ( eplb_model_state.is_async_enabled and eplb_model_state.ep_buffer_ready and all_ranks_buffer_ready ): self.move_to_workspace( model_state=eplb_model_state, ep_group=ep_group, is_profile=is_profile, ) if ( eplb_model_state.layer_to_transfer >= eplb_model_state.model.num_moe_layers ): self.post_eplb(eplb_model_state, is_profile) eplb_model_state.rebalanced = False eplb_model_state.layer_to_transfer = 0 eplb_model_state.pending_global_ready_check = False logger.info( "finish async transfer for model %s rank %d layer %d", eplb_model_state.model_name, ep_group.rank(), eplb_model_state.model.num_moe_layers, ) if self.expert_rearrangement_step >= self.expert_rearrangement_step_interval: if any( eplb_model_state.is_async_enabled and eplb_model_state.rebalanced for eplb_model_state in self.model_states.values() ): # Still performing asynchronous rearrangement return self.expert_rearrangement_step = 0 self.rearrange() def rearrange( self, is_profile: bool = False, execute_shuffle: bool = True, global_expert_loads: list[torch.Tensor] | None = None, rank_mapping: dict[int, int] | None = None, ) -> torch.Tensor | None: """ Rearrange the experts according to the current load. Args: is_profile (bool): If `True`, perform a dummy rearrangement. This is used in `profile_run` to reserve enough memory, no memory movement will be performed. Default is False. execute_shuffle (bool): If `True`, execute the shuffle in elastic expert parallel (EEP). Default is True. global_expert_loads (list[torch.Tensor] | None): The global expert loads when scaling is done in EEP. List of expert loads for the main and drafter (when spec decode is used) models. rank_mapping (dict[int, int] | None): The rank mapping when scaling is done in EEP. """ ep_group = get_ep_group().device_group ep_rank = ep_group.rank() time_start = None is_main_rank = ep_rank == 0 if is_main_rank: torch.cuda.synchronize() time_start = time.perf_counter() logger.info( "Rearranging experts %s %s...", "(async mode)" if self.is_async else "sync mode", "(profile)" if is_profile else "", ) if global_expert_loads is None: # Map the physical expert load to global logical experts global_expert_load_windows = [] if not execute_shuffle: num_models = torch.tensor( [len(self.model_states)], dtype=torch.int32, device="cpu" ) torch.distributed.broadcast( num_models, group=get_ep_group().cpu_group, group_src=0 ) for eplb_model_state in self.model_states.values(): logical_expert_load_window = torch.zeros( self.expert_load_window_size, eplb_model_state.model.num_moe_layers, eplb_model_state.model.num_logical_experts, dtype=eplb_model_state.expert_load_window.dtype, device=eplb_model_state.expert_load_window.device, ) logical_expert_load_window.scatter_add_( dim=-1, index=eplb_model_state.physical_to_logical_map.unsqueeze(0) .expand_as(eplb_model_state.expert_load_window) .long(), src=eplb_model_state.expert_load_window, ) if not execute_shuffle: metadata = torch.tensor( [ eplb_model_state.model.num_moe_layers, eplb_model_state.model.num_logical_experts, eplb_model_state.physical_to_logical_map.shape[1], ], dtype=torch.int32, device="cpu", ) torch.distributed.broadcast( metadata, group=get_ep_group().cpu_group, group_src=0 ) global_expert_load_window = logical_expert_load_window.sum(dim=0) global_expert_load_windows.append(global_expert_load_window) # Perform all-reduce to get the expert load across all ranks for each model global_expert_load_windows = self._allreduce_list( global_expert_load_windows ) if not execute_shuffle: for eplb_model_state, global_expert_load_window in zip( self.model_states.values(), global_expert_load_windows ): # (num_moe_layers, old_num_physical_experts) old_global_expert_indices = eplb_model_state.physical_to_logical_map torch.distributed.broadcast( old_global_expert_indices, group=ep_group, group_src=0 ) if not execute_shuffle: return global_expert_load_windows else: assert execute_shuffle global_expert_load_windows = global_expert_loads # TODO(bowen): Treat differently for prefill and decode nodes eplb_model_state = next(iter(self.model_states.values())) model = eplb_model_state.model num_replicas = model.num_physical_experts num_groups = model.num_expert_groups if rank_mapping is not None and len(rank_mapping) == ep_group.size(): # NOTE(yongji): scale down, we need to rebalance the experts on # remaining GPUs, transfer the experts while we haven't shutdown # the GPUs to be released. cpu_group = get_ep_group().cpu_group num_nodes = _node_count_with_rank_mapping(cpu_group, rank_mapping) num_gpus = sum(new_rank != -1 for new_rank in rank_mapping.values()) num_replicas = ( num_replicas // ep_group.size() * num_gpus ) # handle num replicas change else: num_nodes = get_node_count() num_gpus = ep_group.size() if num_gpus % num_nodes != 0: num_nodes = 1 logger.warning_once( f"num_gpus % num_nodes != 0, " "not using hierarchical rearrangement algorithm.\n" f"{num_gpus=}, {num_nodes=}" ) # Get new expert mappings for eplb_model_state, global_expert_load_window in zip( self.model_states.values(), global_expert_load_windows ): # Get new expert mappings for the model ( new_physical_to_logical_map, new_logical_to_physical_map, new_logical_replica_count, ) = self.policy.rebalance_experts( global_expert_load_window, num_replicas, num_groups, num_nodes, num_gpus, ) if not eplb_model_state.is_async_enabled or is_profile: # Update expert weights rearrange_expert_weights_inplace( eplb_model_state.physical_to_logical_map, new_physical_to_logical_map, eplb_model_state.model.expert_weights, ep_group, is_profile, rank_mapping, ) if not is_profile: if ( eplb_model_state.physical_to_logical_map.shape[1] != new_physical_to_logical_map.shape[1] ): eplb_model_state.physical_to_logical_map = ( new_physical_to_logical_map.to( eplb_model_state.physical_to_logical_map.device ) ) else: eplb_model_state.physical_to_logical_map.copy_( new_physical_to_logical_map ) max_physical_slots = new_logical_to_physical_map.shape[-1] assert ( max_physical_slots <= eplb_model_state.logical_to_physical_map.shape[-1] ) new_logical_to_physical_map = torch.nn.functional.pad( new_logical_to_physical_map, ( 0, eplb_model_state.logical_to_physical_map.shape[-1] - max_physical_slots, ), value=-1, ) eplb_model_state.logical_to_physical_map.copy_(
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/eplb/__init__.py
vllm/distributed/eplb/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Expert parallelism load balancer (EPLB)."""
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/eplb/policy/abstract.py
vllm/distributed/eplb/policy/abstract.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from abc import ABC, abstractmethod import torch class AbstractEplbPolicy(ABC): @classmethod @abstractmethod def rebalance_experts( cls, weight: torch.Tensor, num_replicas: int, num_groups: int, num_nodes: int, num_ranks: int, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Entry point for expert-parallelism load balancer. Parameters: weight: [layers, num_logical_experts], the load statistics for all logical experts num_replicas: number of physical experts, must be a multiple of `num_ranks` num_groups: number of expert groups num_nodes: number of server nodes num_ranks: number of ranks, must be a multiple of `num_nodes` Returns: physical_to_logical_map: [layers, num_replicas], the expert index of each replica logical_to_physical_map: [layers, num_logical_experts, X], the replica indices for each expert expert_count: [layers, num_logical_experts], number of physical replicas for each logical expert """ raise NotImplementedError
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/eplb/policy/default.py
vllm/distributed/eplb/policy/default.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Expert parallelism load balancer (EPLB) for vLLM. This module implements the core rearrangement algorithm. The rearrangement algorithm is adapted from [DeepSeek EPLB](https://github.com/deepseek-ai/eplb). Please find at [#12](https://github.com/deepseek-ai/EPLB/issues/12) an example on how the EPLB algorithm works. """ import numpy as np import torch from .abstract import AbstractEplbPolicy class DefaultEplbPolicy(AbstractEplbPolicy): @classmethod def balanced_packing( cls, weight: torch.Tensor, num_packs: int ) -> tuple[torch.Tensor, torch.Tensor]: """ Pack n weighted objects to m packs, such that each bin contains exactly n/m objects and the weights of all packs are as balanced as possible. Parameters: weight: [X, n], the weight of each item num_packs: number of packs Returns: pack_index: [X, n], the pack index of each item rank_in_pack: [X, n], the rank of the item in the pack """ num_layers, num_groups = weight.shape assert num_groups % num_packs == 0 groups_per_pack = num_groups // num_packs device = weight.device if groups_per_pack == 1: pack_index = torch.arange( weight.size(-1), dtype=torch.int64, device=device ).expand(weight.shape) rank_in_pack = torch.zeros_like(weight, dtype=torch.int64, device=device) return pack_index, rank_in_pack weight_np = weight.cpu().numpy() # Sort and get indices in decending order indices_np = np.argsort(-weight_np, axis=-1) pack_index_np = np.full((num_layers, num_groups), -1, dtype=np.int64) rank_in_pack_np = np.full((num_layers, num_groups), -1, dtype=np.int64) # Run the packing algorithm for i in range(num_layers): pack_weights = [0.0] * num_packs pack_items = [0] * num_packs for group in indices_np[i]: # Find a pack with capacity that has the lowest weight pack = min( (j for j in range(num_packs) if pack_items[j] < groups_per_pack), key=pack_weights.__getitem__, ) assert pack_items[pack] < groups_per_pack pack_index_np[i, group] = pack rank_in_pack_np[i, group] = pack_items[pack] pack_weights[pack] += weight_np[i, group] pack_items[pack] += 1 pack_index = torch.from_numpy(pack_index_np).to(device) rank_in_pack = torch.from_numpy(rank_in_pack_np).to(device) return pack_index, rank_in_pack @classmethod def replicate_experts( cls, weight: torch.Tensor, num_phy: int ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Replicate `num_log` experts to `num_phy` replicas, such that the maximum load of all replicas is minimized. Parameters: weight: [X, num_log] num_phy: total number of experts after replication Returns: phy2log: [X, num_phy], logical expert id of each physical expert rank: [X, num_phy], the replica rank logcnt: [X, num_log], number of replicas for each logical expert """ n, num_log = weight.shape num_redundant = num_phy - num_log assert num_redundant >= 0 device = weight.device phy2log = torch.arange(num_phy, dtype=torch.int64, device=device).repeat(n, 1) rank = torch.zeros(n, num_phy, dtype=torch.int64, device=device) logcnt = torch.ones(n, num_log, dtype=torch.int64, device=device) arangen = torch.arange(n, dtype=torch.int64, device=device) for i in range(num_log, num_phy): redundant_indices = (weight / logcnt).max(dim=-1).indices phy2log[:, i] = redundant_indices rank[:, i] = logcnt[arangen, redundant_indices] logcnt[arangen, redundant_indices] += 1 return phy2log, rank, logcnt @classmethod def rebalance_experts_hierarchical( cls, weight: torch.Tensor, num_physical_experts: int, num_groups: int, num_nodes: int, num_gpus: int, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Parameters: weight: [num_moe_layers, num_logical_experts] num_physical_experts: number of physical experts after replication num_groups: number of expert groups num_nodes: number of server nodes, where the intra-node network (e.g, NVLink) is faster num_gpus: number of GPUs, must be a multiple of `num_nodes` Returns: phy2log: [layers, num_replicas], the expert index of each replica log2phy: [layers, num_logical_experts, X], the replica indices for each expert logcnt: [layers, num_logical_experts], number of physical replicas for each logical expert """ num_layers, num_logical_experts = weight.shape assert num_logical_experts % num_groups == 0 group_size = num_logical_experts // num_groups assert num_groups % num_nodes == 0 groups_per_node = num_groups // num_nodes assert num_gpus % num_nodes == 0 assert num_physical_experts % num_gpus == 0 phy_experts_per_gpu = num_physical_experts // num_gpus def inverse(perm: torch.Tensor) -> torch.Tensor: inv = torch.empty_like(perm) inv.scatter_( 1, perm, torch.arange( perm.size(1), dtype=torch.int64, device=perm.device ).expand(perm.shape), ) return inv # Step 1: pack groups to nodes tokens_per_group = weight.unflatten(-1, (num_groups, group_size)).sum(-1) group_pack_index, group_rank_in_pack = cls.balanced_packing( tokens_per_group, num_nodes ) log2mlog = ( ( (group_pack_index * groups_per_node + group_rank_in_pack) * group_size ).unsqueeze(-1) + torch.arange( group_size, dtype=torch.int64, device=group_pack_index.device ) ).flatten(-2) mlog2log = inverse(log2mlog) # Step 2: construct redundant experts within nodes # [num_layers * num_nodes, num_logical_experts // num_nodes] tokens_per_mlog = weight.gather(-1, mlog2log).view( -1, num_logical_experts // num_nodes ) phy2mlog, phyrank, mlogcnt = cls.replicate_experts( tokens_per_mlog, num_physical_experts // num_nodes ) # Step 3: pack physical_experts to GPUs # [num_layers * num_nodes, num_physical_experts // num_nodes] tokens_per_phy = (tokens_per_mlog / mlogcnt).gather(-1, phy2mlog) pack_index, rank_in_pack = cls.balanced_packing( tokens_per_phy, num_gpus // num_nodes ) phy2pphy = pack_index * phy_experts_per_gpu + rank_in_pack pphy2phy = inverse(phy2pphy) pphy2mlog = phy2mlog.gather( -1, pphy2phy ) # [num_layers * num_nodes, num_log_per_nodes] pphy2mlog = ( pphy2mlog.view(num_layers, num_nodes, -1) + torch.arange( 0, num_logical_experts, num_logical_experts // num_nodes, device=group_pack_index.device, ).view(1, -1, 1) ).flatten(-2) pphy2log = mlog2log.gather(-1, pphy2mlog) pphyrank = phyrank.gather(-1, pphy2phy).view(num_layers, -1) logcnt = mlogcnt.view(num_layers, -1).gather(-1, log2mlog) return pphy2log, pphyrank, logcnt @classmethod def rebalance_experts( cls, weight: torch.Tensor, num_replicas: int, num_groups: int, num_nodes: int, num_ranks: int, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Entry point for expert-parallelism load balancer. Parameters: weight: [layers, num_logical_experts], the load statistics for all logical experts num_replicas: number of physical experts, must be a multiple of `num_gpus` num_groups: number of expert groups num_nodes: number of server nodes, where the intra-node network (e.g, NVLink) is faster num_ranks: number of ranks, must be a multiple of `num_nodes` Returns: phy2log: [layers, num_replicas], the expert index of each replica log2phy: [layers, num_logical_experts, X], the replica indices for each expert logcnt: [layers, num_logical_experts], number of physical replicas for each logical expert """ num_layers, num_logical_experts = weight.shape weight = weight.float() if num_groups % num_nodes == 0: # use hierarchical load-balance policy phy2log, phyrank, logcnt = cls.rebalance_experts_hierarchical( weight, num_replicas, num_groups, num_nodes, num_ranks ) else: # use global load-balance policy phy2log, phyrank, logcnt = cls.rebalance_experts_hierarchical( weight, num_replicas, 1, 1, num_ranks ) num_redundant_experts = num_replicas - num_logical_experts maxlogcnt = num_redundant_experts + 1 log2phy: torch.Tensor = torch.full( (num_layers, num_logical_experts, maxlogcnt), -1, dtype=torch.int64, device=logcnt.device, ) log2phy.view(num_layers, -1).scatter_( -1, phy2log * maxlogcnt + phyrank, torch.arange(num_replicas, dtype=torch.int64, device=log2phy.device).expand( num_layers, -1 ), ) return phy2log, log2phy, logcnt
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/eplb/policy/__init__.py
vllm/distributed/eplb/policy/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import get_args from vllm.config.parallel import EPLBPolicyOption from .abstract import AbstractEplbPolicy from .default import DefaultEplbPolicy EPLB_POLICIES = {"default": DefaultEplbPolicy} # Ensure that the EPLB_POLICIES keys match the EPLBPolicyOption values assert set(EPLB_POLICIES.keys()) == set(get_args(EPLBPolicyOption)) __all__ = [ "AbstractEplbPolicy", "DefaultEplbPolicy", "EPLB_POLICIES", ]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_transfer_state.py
vllm/distributed/kv_transfer/kv_transfer_state.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import TYPE_CHECKING, Optional from vllm.distributed.kv_transfer.kv_connector.base import KVConnectorBaseType from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory from vllm.distributed.kv_transfer.kv_connector.v1 import ( KVConnectorBase_V1, KVConnectorRole, ) if TYPE_CHECKING: from vllm.config import VllmConfig from vllm.v1.kv_cache_interface import KVCacheConfig _KV_CONNECTOR_AGENT: KVConnectorBaseType | None = None def get_kv_transfer_group() -> KVConnectorBaseType: assert _KV_CONNECTOR_AGENT is not None, ( "disaggregated KV cache transfer parallel group is not initialized" ) return _KV_CONNECTOR_AGENT def has_kv_transfer_group() -> bool: return _KV_CONNECTOR_AGENT is not None def is_v1_kv_transfer_group(connector: KVConnectorBaseType | None = None) -> bool: """Check if the KV connector is the v1 connector. If the argument is None, it will check the global KV connector Args: connector: The KV connector to check. If None, it will check the global KV connector. Note: This function will no-longer be needed after the v1 KV connector becomes the default. """ if connector is None: connector = _KV_CONNECTOR_AGENT if connector is None: return False return isinstance(connector, KVConnectorBase_V1) def ensure_kv_transfer_initialized( vllm_config: "VllmConfig", kv_cache_config: Optional["KVCacheConfig"] = None ) -> None: """ Initialize KV cache transfer parallel group. """ global _KV_CONNECTOR_AGENT if vllm_config.kv_transfer_config is None: return if ( vllm_config.kv_transfer_config.is_kv_transfer_instance and _KV_CONNECTOR_AGENT is None ): _KV_CONNECTOR_AGENT = KVConnectorFactory.create_connector( config=vllm_config, role=KVConnectorRole.WORKER, kv_cache_config=kv_cache_config, ) def ensure_kv_transfer_shutdown() -> None: global _KV_CONNECTOR_AGENT if _KV_CONNECTOR_AGENT is not None: _KV_CONNECTOR_AGENT.shutdown() _KV_CONNECTOR_AGENT = None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/__init__.py
vllm/distributed/kv_transfer/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.distributed.kv_transfer.kv_transfer_state import ( KVConnectorBaseType, ensure_kv_transfer_initialized, ensure_kv_transfer_shutdown, get_kv_transfer_group, has_kv_transfer_group, is_v1_kv_transfer_group, ) __all__ = [ "get_kv_transfer_group", "has_kv_transfer_group", "is_v1_kv_transfer_group", "ensure_kv_transfer_initialized", "ensure_kv_transfer_shutdown", "KVConnectorBaseType", ]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/utils.py
vllm/distributed/kv_transfer/kv_connector/utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ KV cache helper for store. """ from collections.abc import Iterator from dataclasses import dataclass from typing import TYPE_CHECKING, Literal import torch from vllm.attention.backends.abstract import AttentionBackend from vllm.attention.backends.registry import AttentionBackendEnum from vllm.config import get_current_vllm_config from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory from vllm.logger import init_logger from vllm.v1.outputs import KVConnectorOutput, ModelRunnerOutput if TYPE_CHECKING: from vllm.distributed.kv_transfer.kv_connector.base import KVConnectorBase logger = init_logger(__name__) EngineId = str def get_kv_connector_cache_layout(): # NOTE (NickLucche) When running disaggregated PD with NIXL, HND layout is # used for faster transfer. vllm_config = get_current_vllm_config() kv_config = vllm_config.kv_transfer_config if kv_config is not None: connector_cls = KVConnectorFactory.get_connector_class(kv_config) required_kvcache_layout = connector_cls.get_required_kvcache_layout(vllm_config) if required_kvcache_layout is not None: return required_kvcache_layout logger.info_once( "Connectors do not specify a kv cache layout, defaulting to NHD." ) return "NHD" class KVOutputAggregator: """Utility class to aggregate the output of all workers into a single output corresponding to Rank 0 for scheduler.""" def __init__(self, expected_finished_count: int): # Complete transfer tracker. Used to track finished requests # [req_id -> n_remaining_workers] self._recv_remaining_count = dict[str, int]() self._send_remaining_count = dict[str, int]() self._expected_finished_count = expected_finished_count @classmethod def from_connector(cls, connector: "KVConnectorBase", world_size: int): return cls(connector.get_finished_count() or world_size) def aggregate( self, outputs: list[ModelRunnerOutput | None], output_rank: int = 0 ) -> ModelRunnerOutput | None: if not outputs[output_rank]: return None # Aggregate kv_connector_output from all workers def update_finished_set( req_ids: set[str] | None, remaining_count_dict: dict[str, int], finished_set: set[str], ) -> None: for req_id in req_ids or (): remaining_count = remaining_count_dict.get( req_id, self._expected_finished_count ) remaining_count_dict[req_id] = remaining_count - 1 if remaining_count_dict[req_id] == 0: finished_set.add(req_id) del remaining_count_dict[req_id] finished_sending = set[str]() finished_recving = set[str]() aggregated_kv_connector_stats = None combined_kv_cache_events = None invalid_block_ids = set[int]() for model_runner_output in outputs: assert model_runner_output is not None kv_output = model_runner_output.kv_connector_output if not kv_output: continue # Allow the worker to dynamically update the expected number of # finished sending/recving for new requests. if ( kv_output.expected_finished_count > 0 and kv_output.expected_finished_count != self._expected_finished_count ): logger.debug( "Expected finished requests updated from %d to %d", self._expected_finished_count, kv_output.expected_finished_count, ) self._expected_finished_count = kv_output.expected_finished_count update_finished_set( kv_output.finished_sending, self._send_remaining_count, finished_sending ) update_finished_set( kv_output.finished_recving, self._recv_remaining_count, finished_recving ) # Aggregate kv_connector_stats from all workers. if aggregated_kv_connector_stats is None: # Use the first worker's kv_connector_stats as accumulator. aggregated_kv_connector_stats = kv_output.kv_connector_stats elif kv_connector_stats := kv_output.kv_connector_stats: if aggregated_kv_connector_stats is None: aggregated_kv_connector_stats = kv_connector_stats else: assert isinstance( aggregated_kv_connector_stats, type(kv_connector_stats) ) aggregated_kv_connector_stats = ( aggregated_kv_connector_stats.aggregate(kv_connector_stats) ) # Combine kv_cache_events from all workers. if combined_kv_cache_events is None: # Use the first worker's kv_cache events as start event list. combined_kv_cache_events = kv_output.kv_cache_events elif kv_cache_events := kv_output.kv_cache_events: assert isinstance( combined_kv_cache_events, type(kv_cache_events), ) worker_kv_cache_events = kv_cache_events.get_all_events() combined_kv_cache_events.add_events(worker_kv_cache_events) combined_kv_cache_events.increment_workers(1) invalid_block_ids |= kv_output.invalid_block_ids # select output of the worker specified by output_rank output = outputs[output_rank] assert output is not None output.kv_connector_output = KVConnectorOutput( finished_sending=finished_sending or None, finished_recving=finished_recving or None, kv_connector_stats=aggregated_kv_connector_stats or None, kv_cache_events=combined_kv_cache_events or None, invalid_block_ids=invalid_block_ids, expected_finished_count=self._expected_finished_count, ) return output def _make_src_and_dst_indices( src_block_ids: list[int], dst_block_ids: list[int], src_device: torch.device | str, dst_device: torch.device | str, ) -> tuple[torch.Tensor, torch.Tensor]: src_indices = torch.tensor(src_block_ids, device=src_device, dtype=torch.int64) dst_indices = torch.tensor(dst_block_ids, device=dst_device, dtype=torch.int64) return src_indices, dst_indices def copy_kv_blocks( src_kv_caches: dict[str, torch.Tensor], dst_kv_caches: dict[str, torch.Tensor], src_block_ids: list[int], dst_block_ids: list[int], direction: Literal["h2d", "d2h"], ) -> None: """Copy kv blocks between different buffers.""" if ( not src_kv_caches or not dst_kv_caches or not src_block_ids or not dst_block_ids or len(src_block_ids) != len(dst_block_ids) ): return src_device = next(iter(src_kv_caches.values())).device dst_device = next(iter(dst_kv_caches.values())).device src_indices, dst_indices = _make_src_and_dst_indices( src_block_ids=src_block_ids, dst_block_ids=dst_block_ids, src_device=src_device, dst_device=dst_device, ) from vllm.platforms import current_platform if direction == "h2d": copy_fn = current_platform.insert_blocks_to_device else: copy_fn = current_platform.swap_out_blocks_to_host for layer_name in src_kv_caches: src_tensor = src_kv_caches[layer_name] dst_tensor = dst_kv_caches[layer_name] copy_fn(src_tensor, dst_tensor, src_indices, dst_indices) def yield_req_data( scheduler_output, ) -> Iterator[tuple[str, tuple[list[int], ...], bool]]: """ Yields: (req_id, new_block_id_groups, preempted) """ # new requests for req_data in scheduler_output.scheduled_new_reqs: yield req_data.req_id, req_data.block_ids, False # cached requests cached_reqs = scheduler_output.scheduled_cached_reqs yield from zip( cached_reqs.req_ids, cached_reqs.new_block_ids, (req_id in cached_reqs.resumed_req_ids for req_id in cached_reqs.req_ids), ) @dataclass class TpKVTopology: """ Helper class for tensor parallel and KV topology information for mapping between local and remote TP workers. """ tp_rank: int remote_tp_size: dict[EngineId, int] is_mla: bool total_num_kv_heads: int attn_backend: type[AttentionBackend] engine_id: EngineId remote_block_size: dict[EngineId, int] def __post_init__(self): # Figure out whether the first dimension of the cache is K/V # or num_blocks. This is used to register the memory regions correctly. kv_cache_shape = self.attn_backend.get_kv_cache_shape( num_blocks=1, block_size=16, num_kv_heads=1, head_size=1 ) # Non-MLA backends caches have 5 dims [2, num_blocks, H,N,D], # we just mock num_blocks to 1 for the dimension check below. self._is_kv_layout_blocks_first = ( len(kv_cache_shape) == 5 and kv_cache_shape[0] == 1 ) attn_backend = AttentionBackendEnum[self.attn_backend.get_name()] self._use_pallas = attn_backend == AttentionBackendEnum.PALLAS @property def is_kv_layout_blocks_first(self) -> bool: return self._is_kv_layout_blocks_first @property def split_k_and_v(self) -> bool: # Whether to register regions for K and V separately (when present). return not (self.is_mla or self._use_pallas or self.is_kv_layout_blocks_first) @property def tp_size(self) -> int: return self.remote_tp_size[self.engine_id] @property def block_size(self) -> int: return self.remote_block_size[self.engine_id] def tp_ratio( self, remote_tp_size: int, ) -> int: """ Calculate the tensor parallel ratio between local and remote TP. We can think of it as the number of local TP workers-per-remote TP workers. Local workers will read from the same remote TP worker in groups of size `tp_ratio`.If remote tp_size > local tp_size, the ratio is flipped (remote_size/local_size) and the returned value is negative. """ if self.tp_size >= remote_tp_size: assert self.tp_size % remote_tp_size == 0, ( f"Local tensor parallel size {self.tp_size} is not divisible " f"by remote tensor parallel size {remote_tp_size}." ) return self.tp_size // remote_tp_size assert remote_tp_size % self.tp_size == 0, ( f"Remote tensor parallel size {remote_tp_size} is not divisible " f"by local tensor parallel size {self.tp_size}." ) # P TP > D TP case, return the ratio as negative return -remote_tp_size // self.tp_size def block_size_ratio( self, remote_block_size: int, ) -> int: """ Calculate the block size ratio between local and remote TP. """ assert self.block_size % remote_block_size == 0, ( f"Local block size {self.block_size} is not divisible " f"by remote block size {remote_block_size} or vice versa." ) return self.block_size // remote_block_size def tp_ratio_from_engine_id( self, remote_engine_id: EngineId, ) -> int: remote_tp_size = self.remote_tp_size[remote_engine_id] return self.tp_ratio(remote_tp_size) def block_size_ratio_from_engine_id( self, remote_engine_id: EngineId, ) -> int: remote_block_size = self.remote_block_size[remote_engine_id] return self.block_size_ratio(remote_block_size) def is_kv_replicated(self, engine_id: EngineId) -> bool: """ Whether the KV cache is replicated across TP workers due to the number of TP workers being greater than the number of KV heads. """ tp_size = self.remote_tp_size[engine_id] return tp_size // self.total_num_kv_heads >= 1 def replicates_kv_cache(self, remote_engine_id: EngineId) -> bool: # MLA is always replicated as the hidden dim can't be split. return self.is_mla or self.is_kv_replicated(remote_engine_id) def get_target_remote_ranks( self, remote_tp_size: int, ) -> list[int]: """ Get the remote TP rank (on P) that the current local TP rank (on D) will read from. When remote tp_size > local tp_size, we read from multiple remote ranks. """ tp_ratio = self.tp_ratio(remote_tp_size) if tp_ratio > 0: return [self.tp_rank // tp_ratio] # P TP > D TP case, D reads from |tp_ratio| remote workers. tp_ratio = -tp_ratio return [self.tp_rank * tp_ratio + i for i in range(tp_ratio)] def get_target_remote_ranks_from_engine_id( self, remote_engine_id: EngineId, ) -> list[int]: remote_tp_size = self.remote_tp_size[remote_engine_id] return self.get_target_remote_ranks(remote_tp_size)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/factory.py
vllm/distributed/kv_transfer/kv_connector/factory.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import importlib from collections.abc import Callable from typing import TYPE_CHECKING, Optional, cast from vllm.distributed.kv_transfer.kv_connector.base import ( KVConnectorBase, KVConnectorBaseType, ) from vllm.distributed.kv_transfer.kv_connector.v1 import ( KVConnectorRole, supports_hma, ) from vllm.logger import init_logger from vllm.utils.func_utils import supports_kw if TYPE_CHECKING: from vllm.config import VllmConfig from vllm.config.kv_transfer import KVTransferConfig from vllm.v1.kv_cache_interface import KVCacheConfig logger = init_logger(__name__) class KVConnectorFactory: _registry: dict[str, Callable[[], type[KVConnectorBase]]] = {} @classmethod def register_connector(cls, name: str, module_path: str, class_name: str) -> None: """Register a connector with a lazy-loading module and class name.""" if name in cls._registry: raise ValueError(f"Connector '{name}' is already registered.") def loader() -> type[KVConnectorBase]: module = importlib.import_module(module_path) return getattr(module, class_name) cls._registry[name] = loader @classmethod def create_connector( cls, config: "VllmConfig", role: KVConnectorRole, kv_cache_config: Optional["KVCacheConfig"] = None, ) -> KVConnectorBase: kv_transfer_config = config.kv_transfer_config if kv_transfer_config is None: raise ValueError("kv_transfer_config must be set to create a connector") connector_cls, compat_sig = cls._get_connector_class_with_compat( kv_transfer_config ) # check if the connector supports HMA hma_enabled = not config.scheduler_config.disable_hybrid_kv_cache_manager if hma_enabled and not supports_hma(connector_cls): raise ValueError( f"Connector {connector_cls.__name__} does not support HMA but " f"HMA is enabled. Please set `--disable-hybrid-kv-cache-manager`." ) logger.info( "Creating v1 connector with name: %s and engine_id: %s", connector_cls.__name__, kv_transfer_config.engine_id, ) # NOTE(Kuntai): v1 connector is explicitly separated into two roles. # Scheduler connector: # - Co-locate with scheduler process # - Should only be used inside the Scheduler class # Worker connector: # - Co-locate with worker process # - Should only be used inside the forward context & attention layer # We build separately to enforce strict separation if compat_sig: # Old signature: __init__(self, vllm_config, role) return connector_cls(config, role) else: # New signature: __init__(self, vllm_config, role, kv_cache_config) return connector_cls(config, role, kv_cache_config) @classmethod def get_connector_class_by_name( cls, connector_name: str ) -> type[KVConnectorBaseType]: """Get a registered connector class by name. Raises ValueError if the connector is not registered. Args: connector_name: Name of the registered connector. Returns: The connector class. """ if connector_name not in cls._registry: raise ValueError(f"Connector '{connector_name}' is not registered.") return cls._registry[connector_name]() @classmethod def _get_connector_class_with_compat( cls, kv_transfer_config: "KVTransferConfig" ) -> tuple[type[KVConnectorBaseType], bool]: connector_name = kv_transfer_config.kv_connector if connector_name is None: raise ValueError("Connector name is not set in KVTransferConfig") compat_sig = False if connector_name in cls._registry: connector_cls = cls._registry[connector_name]() else: connector_module_path = kv_transfer_config.kv_connector_module_path if connector_module_path is None: raise ValueError(f"Unsupported connector type: {connector_name}") connector_module = importlib.import_module(connector_module_path) try: connector_cls = getattr(connector_module, connector_name) except AttributeError as e: raise AttributeError( f"Class {connector_name} not found in {connector_module_path}" ) from e connector_cls = cast(type[KVConnectorBaseType], connector_cls) if not supports_kw(connector_cls, "kv_cache_config"): compat_sig = True logger.warning( "Connector %s uses deprecated signature with 2 required arguments. " "Please update to include kv_cache_config as the second argument.", connector_cls.__name__, ) return connector_cls, compat_sig @classmethod def get_connector_class( cls, kv_transfer_config: "KVTransferConfig" ) -> type[KVConnectorBaseType]: """Get the connector class by name.""" connector_cls, _ = cls._get_connector_class_with_compat(kv_transfer_config) return connector_cls # Register various connectors here. # The registration should not be done in each individual file, as we want to # only load the files corresponding to the current connector. KVConnectorFactory.register_connector( "ExampleConnector", "vllm.distributed.kv_transfer.kv_connector.v1.example_connector", "ExampleConnector", ) KVConnectorFactory.register_connector( "P2pNcclConnector", "vllm.distributed.kv_transfer.kv_connector.v1.p2p.p2p_nccl_connector", "P2pNcclConnector", ) KVConnectorFactory.register_connector( "LMCacheConnectorV1", "vllm.distributed.kv_transfer.kv_connector.v1.lmcache_connector", "LMCacheConnectorV1", ) KVConnectorFactory.register_connector( "LMCacheMPConnector", "vllm.distributed.kv_transfer.kv_connector.v1.lmcache_mp_connector", "LMCacheMPConnector", ) KVConnectorFactory.register_connector( "NixlConnector", "vllm.distributed.kv_transfer.kv_connector.v1.nixl_connector", "NixlConnector", ) KVConnectorFactory.register_connector( "MultiConnector", "vllm.distributed.kv_transfer.kv_connector.v1.multi_connector", "MultiConnector", ) KVConnectorFactory.register_connector( "OffloadingConnector", "vllm.distributed.kv_transfer.kv_connector.v1.offloading_connector", "OffloadingConnector", ) KVConnectorFactory.register_connector( "DecodeBenchConnector", "vllm.distributed.kv_transfer.kv_connector.v1.decode_bench_connector", "DecodeBenchConnector", ) KVConnectorFactory.register_connector( "MooncakeConnector", "vllm.distributed.kv_transfer.kv_connector.v1.mooncake_connector", "MooncakeConnector", )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/__init__.py
vllm/distributed/kv_transfer/kv_connector/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/base.py
vllm/distributed/kv_transfer/kv_connector/base.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Defines the base type for KV cache connectors.""" from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorBase_V1 KVConnectorBase = KVConnectorBase_V1 KVConnectorBaseType = KVConnectorBase_V1 __all__ = ["KVConnectorBase", "KVConnectorBaseType"]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/lmcache_mp_connector.py
vllm/distributed/kv_transfer/kv_connector/v1/lmcache_mp_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import enum from collections.abc import Iterable from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Literal, Optional, cast import torch import zmq from lmcache.integration.vllm.utils import mla_enabled from lmcache.utils import init_logger as lmcache_init_logger from vllm.attention.backends.abstract import AttentionMetadata from vllm.config import VllmConfig from vllm.distributed.kv_transfer.kv_connector.v1.base import ( KVConnectorBase_V1, KVConnectorMetadata, KVConnectorRole, ) from vllm.distributed.kv_transfer.kv_connector.v1.lmcache_integration import ( LMCacheMPSchedulerAdapter, LMCacheMPWorkerAdapter, LoadStoreOp, ) from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.outputs import KVConnectorOutput from vllm.v1.request import RequestStatus from vllm.v1.utils import ConstantList if TYPE_CHECKING: from vllm.config import VllmConfig from vllm.distributed.kv_events import KVCacheEvent from vllm.distributed.kv_transfer.kv_connector.v1.metrics import ( KVConnectorPromMetrics, KVConnectorStats, PromMetric, PromMetricT, ) from vllm.forward_context import ForwardContext from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.core.kv_cache_utils import BlockHash from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request logger = lmcache_init_logger(__name__) # Helper functions def reformat_block_ids(block_ids: tuple[list[int], ...] | None) -> list[int]: if block_ids is None: return [] assert isinstance(block_ids, tuple), ( f"Expected block_ids to be a tuple of lists, but got {type(block_ids)}" ) if len(block_ids) > 1: raise RuntimeError( "LMCacheMPConnector only works without hybrid kv cache manager. " "Please pass --disable-hybrid-kv-cache-manager when starting vllm" ) return block_ids[0] def extract_world_size_and_kv_rank( world_size: int, rank: int, vllm_config: VllmConfig, ) -> tuple[int, int]: """ Convert the rank for the MLA. """ use_mla = mla_enabled(vllm_config.model_config) if not use_mla: return world_size, rank else: # Tensor parallel does not change the KV caches for MLA models. # So we need to "exclude" the effect of TP on rank and world size tp_size = vllm_config.parallel_config.tensor_parallel_size # vLLM constructs TP groups first, and then construct other # parallel groups on top of TP groups. # for example, TP=4, PP=2, # TP group: [0, 1, 2, 3], [4, 5, 6, 7] # PP group: [0, 4], [1, 5], [2, 6], [3, 7] # So we can "exclude" the effect of TP by rank // tp_size. return world_size // tp_size, rank // tp_size def create_scheduler_adapter( server_url: str, zmq_context: zmq.Context, vllm_config: VllmConfig ) -> LMCacheMPSchedulerAdapter: world_size, kv_rank = extract_world_size_and_kv_rank( vllm_config.parallel_config.world_size, vllm_config.parallel_config.rank, vllm_config, ) return LMCacheMPSchedulerAdapter( server_url, zmq_context, vllm_config.model_config.model, world_size, kv_rank, vllm_config.cache_config.block_size, ) def create_worker_adapter( server_url: str, zmq_context: zmq.Context, vllm_config: VllmConfig ) -> LMCacheMPWorkerAdapter: world_size, kv_rank = extract_world_size_and_kv_rank( vllm_config.parallel_config.world_size, vllm_config.parallel_config.rank, vllm_config, ) return LMCacheMPWorkerAdapter( server_url, zmq_context, vllm_config.model_config.model, world_size, kv_rank, vllm_config.cache_config.block_size, ) def convert_block_hashes_to_bytes( block_hashes: list["BlockHash"], ) -> list[bytes]: return cast(list[bytes], block_hashes) class LMCacheMPRequestState(enum.Enum): """ State machine: PREFETCHING -- update_state_after_alloc --> WAITING_FOR_LOAD WAITING_FOR_LOAD -- process_loading_requests --> READY """ PREFETCHING = enum.auto() WAITING_FOR_LOAD = enum.auto() READY = enum.auto() @dataclass class LMCacheMPRequestTracker: # NOTE: this class used vLLM data structures, should be part of # vLLM integration code request_id: str # Read-only lists to track the token ids and block hashes all_token_ids: ConstantList[int] block_hashes: ConstantList["BlockHash"] # Block ids and hashes will be updated at update_states_after_alloc and # during the generation allocated_block_ids: list[int] = field(default_factory=list) # Number of scheduled tokens in this request. We keep tracking this to # avoid saving half-full blocks. num_scheduled_tokens: int = 0 # Number of blocks stored will be initialized when lookup the external # hit tokens and will be updated when processing new requests and cached # requests. num_stored_blocks: int = 0 # Staging load operation -- save vllm and lmcache hit tokens during lookup num_vllm_hit_blocks: int = 0 num_lmcache_hit_blocks: int = 0 # Main state state: LMCacheMPRequestState = LMCacheMPRequestState.PREFETCHING def __init__(self, request: "Request"): self.request_id = request.request_id self.all_token_ids = request.all_token_ids self.block_hashes = ConstantList(request.block_hashes) self.allocated_block_ids = [] self.num_stored_blocks = 0 self.num_vllm_hit_blocks = 0 self.num_lmcache_hit_blocks = 0 self.state = LMCacheMPRequestState.PREFETCHING #### # Check the state of the request #### def needs_retrieve(self) -> bool: """Check whether the current request needs retrieve, will be used update_stage_after_alloc""" return ( self.num_lmcache_hit_blocks > self.num_vllm_hit_blocks and self.state != LMCacheMPRequestState.READY ) def is_ready_for_retrieving(self) -> bool: """Check whether the current request is ready for retrieving, will be used in process_loading_requests""" return ( self.state == LMCacheMPRequestState.WAITING_FOR_LOAD and self.needs_retrieve() ) #### # Update internal states #### def increase_num_scheduled_tokens(self, num_new_tokens: int): self.num_scheduled_tokens += num_new_tokens def increase_num_stored_blocks(self, num_new_blocks: int): """Increase the number of stored blocks for the current request This function will be called when processing the cached requests. """ self.num_stored_blocks += num_new_blocks def append_block_ids( self, new_block_ids: list[int], ): """Update the block ids for the current request This function will be called when processing the cached requests. """ self.allocated_block_ids.extend(new_block_ids) #### # For debugging #### def __repr__(self) -> str: return ( f"LMCacheMPRequestTracker(request_id={self.request_id}, " f"num_tokens={len(self.all_token_ids)}, " f"num_block_hashes={len(self.block_hashes)}, " f"num_allocated_blocks={len(self.allocated_block_ids)}, " f"num_stored_blocks={self.num_stored_blocks}, " f"vllm_hit_blocks={self.num_vllm_hit_blocks}, " f"lmcache_hit_blocks={self.num_lmcache_hit_blocks}, " f"state={self.state})" ) def __str__(self) -> str: return self.__repr__() @dataclass class LMCacheMPRequestMetadata: request_id: str direction: Literal["STORE", "RETRIEVE"] op: LoadStoreOp @staticmethod def GetStoreMetadata( tracker: LMCacheMPRequestTracker, blocks_in_chunk: int, vllm_block_size: int, ) -> "LMCacheMPRequestMetadata | None": """ Generate the store metadata for the current request tracker. Args: tracker: The request tracker to generate the metadata from. blocks_in_chunk: the number of blocks in a LMCache data chunk """ # Store the blocks that has block hashes # NOTE: the invariant here is that `num_stored_blocks` should # always be a multiple of `blocks_in_chunk` # TODO: This should be checked everytime we update the num_stored_blocks min_available_blocks = min( len(tracker.block_hashes), len(tracker.allocated_block_ids), tracker.num_scheduled_tokens // vllm_block_size, ) num_staging_blocks = min_available_blocks - tracker.num_stored_blocks num_chunks = num_staging_blocks // blocks_in_chunk if num_chunks >= 1: start = tracker.num_stored_blocks end = start + num_chunks * blocks_in_chunk block_hashes = convert_block_hashes_to_bytes( tracker.block_hashes[start:end] ) block_ids = tracker.allocated_block_ids[start:end] ret = LMCacheMPRequestMetadata( request_id=tracker.request_id, direction="STORE", op=LoadStoreOp(block_hashes=block_hashes, block_ids=block_ids), ) # Update the request tracker tracker.increase_num_stored_blocks(end - start) return ret return None @staticmethod def GetRetrieveMetadata( tracker: LMCacheMPRequestTracker, blocks_in_chunk: int, ) -> "LMCacheMPRequestMetadata | None": """ Generate the retrieve metadata for the current request tracker. Args: tracker: The request tracker to generate the metadata from. blocks_in_chunk: the number of blocks in a LMCache data chunk """ if not tracker.is_ready_for_retrieving(): return None # |---------------------|-----------------|----------------| # | num_vllm_hit_blocks | # | lmcache chunk 1 | lmcache chunk 2 | # | need to retrieve | start = tracker.num_vllm_hit_blocks // blocks_in_chunk * blocks_in_chunk end = tracker.num_lmcache_hit_blocks assert end % blocks_in_chunk == 0, ( "The number of LMCache hit blocks should be a multiple of the " "number of blocks in a lmcache chunk. " ) assert len(tracker.block_hashes) >= end, ( "The number of block hashes should be greater than or equal to the " "number of LMCache hit blocks. " ) if end > start: block_hashes = convert_block_hashes_to_bytes( tracker.block_hashes[start:end] ) block_ids = tracker.allocated_block_ids[start:end] ret = LMCacheMPRequestMetadata( request_id=tracker.request_id, direction="RETRIEVE", op=LoadStoreOp(block_hashes=block_hashes, block_ids=block_ids), ) return ret return None class LMCacheMPConnectorMetadata(KVConnectorMetadata): def __init__(self): super().__init__() self.requests: list[LMCacheMPRequestMetadata] = [] def add_request_metadata(self, request_metadata: LMCacheMPRequestMetadata): self.requests.append(request_metadata) def __len__(self): return len(self.requests) # For debugging def __str__(self): request_strs = [] for req_meta in self.requests: request_strs.append( f"RequestMetadata(request_id={req_meta.request_id}, " f"direction={req_meta.direction}, " f"num_blocks={len(req_meta.op)}, " f"block_ids={req_meta.op.block_ids})" ) return "[" + "\n".join(request_strs) + "]" def __repr__(self): return self.__str__() class LMCacheMPConnector(KVConnectorBase_V1): """ The connector for LMCache multi-process mode. Extra configs (kv_transfer_config.extra_config): - lmcache.mp.host: the host of the LMCache server. - lmcache.mp.port: the port of the LMCache server. """ def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, kv_cache_config: Optional["KVCacheConfig"] = None, ): super().__init__(vllm_config, role, kv_cache_config) assert vllm_config.kv_transfer_config is not None server_host = vllm_config.kv_transfer_config.get_from_extra_config( "lmcache.mp.host", "tcp://localhost" ) server_port = vllm_config.kv_transfer_config.get_from_extra_config( "lmcache.mp.port", 5555 ) server_url = f"{server_host}:{server_port}" zmq_context = zmq.Context.instance() if self.role == KVConnectorRole.SCHEDULER: self.scheduler_adapter = create_scheduler_adapter( server_url, zmq_context, vllm_config ) self.request_trackers: dict[str, LMCacheMPRequestTracker] = {} elif self.role == KVConnectorRole.WORKER: self.worker_adapter = create_worker_adapter( server_url, zmq_context, vllm_config ) else: raise ValueError(f"Unknown KVConnectorRole: {self.role}") self.vllm_block_size = vllm_config.cache_config.block_size @property def role(self) -> KVConnectorRole: return self._role # ============================== # Worker-side methods # ============================== def _get_connector_metadata(self) -> KVConnectorMetadata: """Get the connector metadata. This function should only be called inside the connector. Returns: ConnectorMetadata: the connector metadata. """ # Should only be called while set to valid metadata. assert self._connector_metadata is not None return self._connector_metadata def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): """ Initialize with the KV caches. Useful for pre-registering the KV Caches in the KVConnector (e.g. for NIXL). Args: kv_caches: dictionary of layer names, kv cache """ logger.info("Registering kv caches!") self.worker_adapter.register_kv_caches(kv_caches) return def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None: """ Start loading the KV cache from the connector to vLLM's paged KV buffer. This is called from the forward context before the forward pass to enable async loading during model execution. Args: forward_context (ForwardContext): the forward context. **kwargs: additional arguments for the load operation Note: The number of elements in kv_caches and layer_names should be the same. """ metadata = self._get_connector_metadata() assert isinstance(metadata, LMCacheMPConnectorMetadata) request_ids = [] ops = [] for meta in metadata.requests: if meta.direction != "RETRIEVE": continue request_ids.append(meta.request_id) ops.append(meta.op) if len(request_ids) == 0: return with torch.cuda.stream(torch.cuda.current_stream()): event = torch.cuda.Event(interprocess=True) event.record() self.worker_adapter.batched_submit_retrieve_requests(request_ids, ops, event) def wait_for_layer_load(self, layer_name: str) -> None: """ Block until the KV for a specific layer is loaded into vLLM's paged buffer. This is called from within attention layer to ensure async copying from start_load_kv is complete. This interface will be useful for layer-by-layer pipelining. Args: layer_name: the name of that layer """ return def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: AttentionMetadata, **kwargs: Any, ) -> None: """ Start saving a layer of KV cache from vLLM's paged buffer to the connector. This is called from within attention layer to enable async copying during execution. Args: layer_name (str): the name of the layer. kv_layer (torch.Tensor): the paged KV buffer of the current layer in vLLM. attn_metadata (AttentionMetadata): the attention metadata. **kwargs: additional arguments for the save operation. """ return def wait_for_save(self): """ Block until all the save operations is done. This is called as the forward context exits to ensure that the async saving from save_kv_layer is complete before finishing the forward. This prevents overwrites of paged KV buffer before saving done. """ metadata = self._get_connector_metadata() assert isinstance(metadata, LMCacheMPConnectorMetadata) request_ids = [] ops = [] for meta in metadata.requests: if meta.direction != "STORE": continue request_ids.append(meta.request_id) ops.append(meta.op) if len(request_ids) == 0: return with torch.cuda.stream(torch.cuda.current_stream()): event = torch.cuda.Event(interprocess=True) event.record() self.worker_adapter.batched_submit_store_requests(request_ids, ops, event) def get_finished( self, finished_req_ids: set[str] ) -> tuple[set[str] | None, set[str] | None]: """ Notifies worker-side connector ids of requests that have finished generating tokens on the worker. The scheduler process (via the Executors) will use this output to track which workers are done. Returns: ids of requests that have finished asynchronous transfer (requests that previously returned True from request_finished()), tuple of (sending/saving ids, recving/loading ids). The finished saves/sends req ids must belong to a set provided in a call to this method (this call or a prior one). """ val = self.worker_adapter.get_finished(finished_req_ids) # logger.error("Finished req ids: %s, %s", val[0], val[1]) return val def get_block_ids_with_load_errors(self) -> set[int]: """ Get the set of block IDs that failed to load. Returns: Set of block IDs that encountered load errors. Empty set if no load errors occurred. Notes: - Applies to both sync- and async-loading requests. - Async loading: failed blocks may be reported in any forward pass up to and including the pass where the request ID is returned by `get_finished()`. Even if failures occur, the request must still be reported via `get_finished()`, and the failed block IDs must appear here no later than that same pass. - Sync loading: failed blocks should be reported in the forward pass in which they are detected. """ # TODO: add error tracking return set() def shutdown(self): """ Shutdown the connector. This is called when the worker process is shutting down to ensure that all the async operations are completed and the connector is cleaned up properly. """ if hasattr(self, "worker_adapter"): self.worker_adapter.shutdown() return None def get_kv_connector_stats(self) -> Optional["KVConnectorStats"]: """ Get the KV connector stats collected during the last interval. """ return None # ============================== # Scheduler-side methods # ============================== def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int | None, bool]: """ Get number of new tokens that can be loaded from the external KV cache beyond the num_computed_tokens. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: A tuple with the following elements: - An optional number of tokens that can be loaded from the external KV cache beyond what is already computed. If None, it means that the connector needs more time to determine the number of matched tokens, and the scheduler should query for this request again later. - `True` if external KV cache tokens will be loaded asynchronously (between scheduler steps). Must be 'False' if the first element is 0. Notes: The connector should only consider the largest prefix of prompt- tokens for which KV cache is actually available at the time of the call. If the cache cannot be loaded for some tokens (e.g., due to connectivity issues or eviction), those tokens must not be taken into account. """ tracker = self._get_or_create_request_tracker(request) # TODO: support loading KV for preempted requests in the future if request.status == RequestStatus.PREEMPTED: return 0, False self.scheduler_adapter.maybe_submit_lookup_request( request.request_id, convert_block_hashes_to_bytes(request.block_hashes) ) ret = self.scheduler_adapter.check_lookup_result(request.request_id) if ret is None: return None, True if ret == 0: return 0, False assert ( ret % (self.scheduler_adapter.num_blocks_per_chunk() * self.vllm_block_size) == 0 ) # Update num stored blocks for the tracker num_vllm_blocks = num_computed_tokens // self.vllm_block_size num_lmcache_blocks = ret // self.vllm_block_size tracker.increase_num_stored_blocks(num_lmcache_blocks) # Save the vllm and lmcache hit tokens tracker.num_vllm_hit_blocks = num_vllm_blocks tracker.num_lmcache_hit_blocks = num_lmcache_blocks need_to_load = max(0, ret - num_computed_tokens) logger.debug( "vLLM hit is: %d, Need to load is %d", num_computed_tokens, need_to_load ) return need_to_load, need_to_load > 0 def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): """ Update KVConnector state after block allocation. If get_num_new_matched_tokens previously returned True for a request, this function may be called twice for that same request - first when blocks are allocated for the connector tokens to be asynchronously loaded into, and second when any additional blocks are allocated, after the load/transfer is complete. Args: request (Request): the request object. blocks (KVCacheBlocks): the blocks allocated for the request. num_external_tokens (int): the number of tokens that will be loaded from the external KV cache. """ # NOTE: the `blocks` are NEW BLOCKS allocated for this request. tracker = self._get_request_tracker(request.request_id) block_ids = reformat_block_ids(blocks.get_block_ids()) # No matter we need to retrieve or not, we need to update # the block ids into the tracker tracker.append_block_ids(block_ids) # Update the state of the tracker condition = tracker.needs_retrieve() if tracker.state == LMCacheMPRequestState.PREFETCHING: # If need to retrieve, change to WAITING_FOR_LOAD # Otherwise, change to READY tracker.state = ( LMCacheMPRequestState.WAITING_FOR_LOAD if condition else LMCacheMPRequestState.READY ) # Clean up lookup future in scheduler adapter self.scheduler_adapter._cleanup_lookup_result(request.request_id) def build_connector_meta( self, scheduler_output: SchedulerOutput ) -> KVConnectorMetadata: """ Build the connector metadata for this step. This function should NOT modify fields in the scheduler_output. Also, calling this function will reset the state of the connector. Args: scheduler_output (SchedulerOutput): the scheduler output object. """ metadata = LMCacheMPConnectorMetadata() self._process_retrieve_requests(metadata) self._process_new_requests(scheduler_output, metadata) self._process_cached_requests(scheduler_output, metadata) if len(metadata) > 0: logger.debug("Final connector metadata: %s", metadata) return metadata def update_connector_output(self, connector_output: KVConnectorOutput): """ Update KVConnector state from worker-side connectors output. Args: connector_output (KVConnectorOutput): the worker-side connectors output. """ return def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: """ Called exactly once when a request has finished, before its blocks are freed. The connector may assumes responsibility for freeing the blocks asynchronously by returning True. Returns: True if the request is being saved/sent asynchronously and blocks should not be freed until the request_id is returned from get_finished(). Optional KVTransferParams to be included in the request outputs returned by the engine. """ # Clean up request tracker to prevent memory leak self._cleanup_request_tracker(request.request_id) return True, None def take_events(self) -> Iterable["KVCacheEvent"]: """ Take the KV cache events from the connector. Yields: New KV cache events since the last call. """ return () @classmethod def get_required_kvcache_layout(cls, vllm_config: "VllmConfig") -> str | None: """ Get the required KV cache layout for this connector. Args: vllm_config (VllmConfig): the vllm config. Returns: str: the required KV cache layout. e.g. HND, or NHD. None if the connector does not require a specific layout. """ if cls is KVConnectorBase_V1: raise TypeError( "get_required_kvcache_layout should not be called " "on the abstract base class" ) return None def get_finished_count(self) -> int | None: """ Get the count of requests expected to complete send/receive operations via this connector. This method is used to initialize the KVOutputAggregator, overwriting the default world_size. Returns: int: expected sending or receiving completion count. """ return None @classmethod def build_kv_connector_stats( cls, data: dict[str, Any] | None = None ) -> Optional["KVConnectorStats"]: """ KVConnectorStats resolution method. This method allows dynamically registered connectors to return their own KVConnectorStats object, which can implement custom aggregation logic on the data dict. """ return None @classmethod def build_prom_metrics( cls, vllm_config: "VllmConfig", metric_types: dict[type["PromMetric"], type["PromMetricT"]], labelnames: list[str], per_engine_labelvalues: dict[int, list[object]], ) -> Optional["KVConnectorPromMetrics"]: """ Create a KVConnectorPromMetrics subclass which should register per-connector Prometheus metrics and implement observe() to expose connector transfer stats via Prometheus. """ return None ############################## # Helper functions ############################## def _process_retrieve_requests( self, metadata: LMCacheMPConnectorMetadata, ) -> None: blocks_per_chunk = self.scheduler_adapter.num_blocks_per_chunk() for request_tracker in self.request_trackers.values(): if request_tracker.state != LMCacheMPRequestState.WAITING_FOR_LOAD: continue r_metadata = LMCacheMPRequestMetadata.GetRetrieveMetadata( request_tracker, blocks_per_chunk ) if r_metadata is not None: metadata.add_request_metadata(r_metadata) request_tracker.state = LMCacheMPRequestState.READY def _process_new_requests( self, scheduler_output: SchedulerOutput, metadata: LMCacheMPConnectorMetadata, ) -> None: blocks_per_chunk = self.scheduler_adapter.num_blocks_per_chunk() for new_request in scheduler_output.scheduled_new_reqs: request_tracker = self._get_request_tracker(new_request.req_id) num_new_tokens = scheduler_output.num_scheduled_tokens[new_request.req_id] request_tracker.increase_num_scheduled_tokens(num_new_tokens) r_meta = LMCacheMPRequestMetadata.GetStoreMetadata( request_tracker, blocks_per_chunk, self.vllm_block_size ) if r_meta is not None: metadata.add_request_metadata(r_meta) def _process_cached_requests( self, scheduler_output: SchedulerOutput, metadata: LMCacheMPConnectorMetadata, ) -> None: blocks_per_chunk = self.scheduler_adapter.num_blocks_per_chunk() cached_reqs = scheduler_output.scheduled_cached_reqs for idx, request_id in enumerate(cached_reqs.req_ids): request_tracker = self._get_request_tracker(request_id) # Update block ids new_block_ids = reformat_block_ids(cached_reqs.new_block_ids[idx]) if request_id not in cached_reqs.resumed_req_ids: request_tracker.append_block_ids(new_block_ids) # Update new scheduled tokens num_new_tokens = cached_reqs.num_computed_tokens[idx] request_tracker.increase_num_scheduled_tokens(num_new_tokens) r_meta = LMCacheMPRequestMetadata.GetStoreMetadata( request_tracker, blocks_per_chunk, self.vllm_block_size ) if r_meta is not None: metadata.add_request_metadata(r_meta) def _get_request_tracker(self, request_id: str) -> LMCacheMPRequestTracker: assert request_id in self.request_trackers, ( f"Request tracker for request_id {request_id} not found. " ) return self.request_trackers[request_id] def _get_or_create_request_tracker( self, request: "Request" ) -> LMCacheMPRequestTracker: request_id = request.request_id # Remove the old trackers that is created before the preemption if ( request.status == RequestStatus.PREEMPTED and request_id in self.request_trackers ): tracker = self.request_trackers[request_id] # NOTE: since this function may be called multiple times # for a single request (because get_num_new_matched_tokens # may be called multiple times) for the same request, we # will only do the remove if the tracker is not in the "fresh" # state, i.e., PREFETCHING if tracker.state != LMCacheMPRequestState.PREFETCHING: self.request_trackers.pop(request_id)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/metrics.py
vllm/distributed/kv_transfer/kv_connector/v1/metrics.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass, field from typing import Any, TypeAlias, TypeVar from prometheus_client import Counter, Gauge, Histogram from vllm.config import KVTransferConfig, VllmConfig from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory from vllm.logger import init_logger PromMetric: TypeAlias = Gauge | Counter | Histogram PromMetricT = TypeVar("PromMetricT", bound=PromMetric) logger = init_logger(__name__) @dataclass class KVConnectorStats: """ Base class for KV 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. """ data: dict[str, Any] = field(default_factory=dict) def reset(self): """Reset the stats, clear the state.""" raise NotImplementedError def aggregate(self, other: "KVConnectorStats") -> "KVConnectorStats": """ Aggregate stats with another `KVConnectorStats` object. """ raise NotImplementedError def reduce(self) -> dict[str, int | float]: """ 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. """ raise NotImplementedError def is_empty(self) -> bool: """Return True if the stats are empty.""" raise NotImplementedError class KVConnectorLogging: def __init__(self, kv_transfer_config: KVTransferConfig | None): # Instantiate the connector's stats class. if kv_transfer_config and kv_transfer_config.kv_connector: self.connector_cls = KVConnectorFactory.get_connector_class( kv_transfer_config ) self.reset() def reset(self): self.transfer_stats_accumulator: KVConnectorStats | None = None def observe(self, transfer_stats_data: dict[str, Any]): # Should not be called when a KVConnector is not configured. assert self.connector_cls is not None # Called periodically when connector syncs with the scheduler. # Note that this is not the same as the logging interval. # We expect transfer_stats_data to be aggregated across all workers and # consist of observations from a single connector or a MultiConnector. transfer_stats = self.connector_cls.build_kv_connector_stats( transfer_stats_data ) if transfer_stats is None: logger.warning_once( "The connector %s is collecting stats but " "does not implement the " "`build_kv_connector_stats` method. " "Stats will not be logged.", self.connector_cls, ) return if self.transfer_stats_accumulator is None: self.transfer_stats_accumulator = transfer_stats else: # Accumulate last interval stats. self.transfer_stats_accumulator = self.transfer_stats_accumulator.aggregate( transfer_stats ) def log(self, log_fn=logger.info): """Log transfer metrics periodically, similar to throughput logging""" if ( self.transfer_stats_accumulator and not self.transfer_stats_accumulator.is_empty() ): # Produce a single cumulative stats object for the last time # interval from the recorded observations. xfer_metrics = self.transfer_stats_accumulator.reduce() xfer_metrics_str = ", ".join(f"{k}={v}" for k, v in xfer_metrics.items()) log_fn("KV Transfer metrics: %s", xfer_metrics_str) # Reset metrics for next interval self.reset() class KVConnectorPromMetrics: """ A base class for per-connector Prometheus metric registration and recording. """ def __init__( self, vllm_config: VllmConfig, metric_types: dict[type[PromMetric], type[PromMetricT]], labelnames: list[str], per_engine_labelvalues: dict[int, list[object]], ): self._kv_transfer_config = vllm_config.kv_transfer_config self._gauge_cls = metric_types[Gauge] self._counter_cls = metric_types[Counter] self._histogram_cls = metric_types[Histogram] self._labelnames = labelnames self._per_engine_labelvalues = per_engine_labelvalues def make_per_engine(self, metric: PromMetric) -> dict[int, PromMetric]: """ Create a per-engine child of a prometheus_client.Metric with the appropriate labels set. The parent metric must be created using the labelnames list. """ return { idx: metric.labels(*labelvalues) for idx, labelvalues in self._per_engine_labelvalues.items() } def observe(self, transfer_stats_data: dict[str, Any], engine_idx: int = 0): """ 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 make_per_engine() helper method. """ raise NotImplementedError class KVConnectorPrometheus: """ Support for registering per-connector Prometheus metrics, and recording transfer statistics to those metrics. Uses KVConnectorBase.build_prom_metrics(). """ _gauge_cls = Gauge _counter_cls = Counter _histogram_cls = Histogram def __init__( self, vllm_config: VllmConfig, labelnames: list[str], per_engine_labelvalues: dict[int, list[object]], ): self.prom_metrics: KVConnectorPromMetrics | None = None kv_transfer_config = vllm_config.kv_transfer_config if kv_transfer_config and kv_transfer_config.kv_connector: connector_cls = KVConnectorFactory.get_connector_class(kv_transfer_config) metric_types = { Gauge: self._gauge_cls, Counter: self._counter_cls, Histogram: self._histogram_cls, } self.prom_metrics = connector_cls.build_prom_metrics( vllm_config, metric_types, labelnames, per_engine_labelvalues, ) def observe(self, transfer_stats_data: dict[str, Any], engine_idx: int = 0): if self.prom_metrics is None: return self.prom_metrics.observe(transfer_stats_data, engine_idx)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/mooncake_connector.py
vllm/distributed/kv_transfer/kv_connector/v1/mooncake_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import asyncio import threading import time import uuid from collections import defaultdict from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Optional import msgspec import numpy as np import torch import zmq import zmq.asyncio from vllm import envs from vllm.attention.backends.abstract import AttentionMetadata from vllm.attention.selector import get_attn_backend from vllm.config import VllmConfig from vllm.distributed.kv_transfer.kv_connector.utils import TpKVTopology from vllm.distributed.kv_transfer.kv_connector.v1.base import ( KVConnectorBase_V1, KVConnectorMetadata, KVConnectorRole, ) from vllm.distributed.parallel_state import ( get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size, get_tp_group, ) from vllm.forward_context import ForwardContext from vllm.logger import init_logger from vllm.utils.network_utils import get_ip, make_zmq_path, make_zmq_socket from vllm.v1.attention.backends.utils import get_kv_cache_layout from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.request import RequestStatus try: from mooncake.engine import TransferEngine except ImportError as e: raise ImportError( "Please install mooncake by following the instructions at " "https://github.com/kvcache-ai/Mooncake/blob/main/doc/en/build.md " # noqa: E501 "to run VLLM with MooncakeTransferEngine." ) from e if TYPE_CHECKING: from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request EngineId = str ReqId = str TRANS_DONE = b"trans_done" TRANS_ERROR = b"trans_error" logger = init_logger(__name__) class MooncakeAgentMetadata( msgspec.Struct, omit_defaults=True, # type: ignore[call-arg] # required for @cached_property. dict=True, ): remote_hostname: str remote_port: int request_ids: list[ReqId] kv_caches_base_addr: list[int] block_ids: list[list[int]] @dataclass class RecvReqMeta: local_block_ids: list[int] remote_host: str remote_port: int @dataclass class SendBlockMeta: local_block_ids: list[int] ready: threading.Event expire_time: float = float("inf") @dataclass class SendReqMeta: reqs: dict[ReqId, SendBlockMeta] lock: threading.Lock @dataclass class FinishedSendReqSet: set: set[ReqId] lock: threading.Lock @dataclass class FinishedReceiveReqSet: set: set[ReqId] lock: asyncio.Lock class MooncakeConnectorMetadata(KVConnectorMetadata): def __init__(self): self.reqs_to_recv: dict[ReqId, RecvReqMeta] = {} self.reqs_to_send: dict[ReqId, list[int]] = {} def add_new_req( self, request_id: ReqId, local_block_ids: list[int], kv_transfer_params: dict[str, Any], load_remote_cache: bool = True, ): if load_remote_cache: self.reqs_to_recv[request_id] = RecvReqMeta( local_block_ids=local_block_ids, remote_host=kv_transfer_params["remote_host"], remote_port=kv_transfer_params["remote_port"], ) else: self.reqs_to_send[request_id] = local_block_ids class MooncakeConnector(KVConnectorBase_V1): def __init__( self, vllm_config: VllmConfig, role: KVConnectorRole, kv_cache_config: Optional["KVCacheConfig"] = None, ): super().__init__(vllm_config, role, kv_cache_config) assert vllm_config.kv_transfer_config is not None assert vllm_config.kv_transfer_config.engine_id is not None self.engine_id: EngineId = vllm_config.kv_transfer_config.engine_id if role == KVConnectorRole.SCHEDULER: self.connector_scheduler: MooncakeConnectorScheduler | None = ( MooncakeConnectorScheduler(vllm_config, self.engine_id) ) self.connector_worker: MooncakeConnectorWorker | None = None elif role == KVConnectorRole.WORKER: self.connector_scheduler = None self.connector_worker = MooncakeConnectorWorker(vllm_config, self.engine_id) ############################################################ # Scheduler Side Methods ############################################################ def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int ) -> tuple[int, bool]: assert self.connector_scheduler is not None return self.connector_scheduler.get_num_new_matched_tokens( request, num_computed_tokens ) def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): assert self.connector_scheduler is not None return self.connector_scheduler.update_state_after_alloc( request, blocks, num_external_tokens ) def build_connector_meta( self, scheduler_output: SchedulerOutput, ) -> KVConnectorMetadata: assert self.connector_scheduler is not None return self.connector_scheduler.build_connector_meta(scheduler_output) def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: assert self.connector_scheduler is not None return self.connector_scheduler.request_finished(request, block_ids) ############################################################ # Worker Side Methods ############################################################ def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): assert self.connector_worker is not None self.connector_worker.register_kv_caches(kv_caches) def get_finished( self, finished_req_ids: set[str] ) -> tuple[set[str] | None, set[str] | None]: """Get the finished recving and sending requests.""" assert self.connector_worker is not None return self.connector_worker.get_finished() def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None: assert self.connector_worker is not None assert isinstance(self._connector_metadata, MooncakeConnectorMetadata) self.connector_worker.start_load_kv(self._connector_metadata) def wait_for_layer_load(self, layer_name: str) -> None: """MooncakeConnector does not do layerwise saving.""" pass def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: AttentionMetadata, **kwargs, ) -> None: """MooncakeConnector does not save explicitly.""" pass def wait_for_save(self): pass class MooncakeConnectorScheduler: """Implementation of Scheduler side methods""" def __init__(self, vllm_config: VllmConfig, engine_id: str): self.vllm_config = vllm_config self.engine_id: EngineId = engine_id self.side_channel_host = get_ip() self.side_channel_port = get_mooncake_side_channel_port(vllm_config) assert vllm_config.kv_transfer_config self.kv_role = vllm_config.kv_transfer_config.kv_role logger.info("Initializing Mooncake Transfer Engine Scheduler %s", engine_id) # Requests that need to start recv/send. # New requests are added by update_state_after_alloc in # the scheduler. Used to make metadata passed to Worker. self._reqs_need_recv: dict[ReqId, tuple[Request, list[int]]] = {} self._reqs_need_send: dict[ReqId, list[int]] = {} def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int ) -> tuple[int, bool]: """ For remote prefill, pull all prompt blocks from remote asynchronously relative to engine execution. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: * the number of tokens that can be loaded from the external KV cache beyond what is already computed. * true if the external KV cache tokens will be loaded asynchronously (between scheduler steps). """ params = request.kv_transfer_params logger.debug( "MooncakeConnector get_num_new_matched_tokens: " "num_computed_tokens=%s, kv_transfer_params=%s", num_computed_tokens, params, ) if params is not None and params.get("do_remote_prefill"): # Remote prefill: get all prompt blocks from remote. token_ids = request.prompt_token_ids or [] count = len(token_ids) - num_computed_tokens if count > 0: return count, True # No remote prefill for this request. return 0, False def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): params = request.kv_transfer_params logger.debug( "MooncakeConnector update_state_after_alloc: " "num_external_tokens=%s, kv_transfer_params=%s", num_external_tokens, params, ) if not params: return if params.get("do_remote_prefill"): assert self.kv_role != "kv_producer" if all(p in params for p in ("remote_host", "remote_port")): # If remote_blocks and num_external_tokens = 0, we have # a full prefix cache hit on the D worker. We need to call # send_notif in _read_blocks to free the memory on the P. local_block_ids = ( blocks.get_unhashed_block_ids() if num_external_tokens > 0 else [] ) # Get unhashed blocks to pull from remote. self._reqs_need_recv[request.request_id] = (request, local_block_ids) else: logger.warning( "Got invalid KVTransferParams: %s. This " "request will not utilize KVTransfer", params, ) # Only trigger 1 KV transfer per request. params["do_remote_prefill"] = False elif params.get("do_remote_decode"): # Add an empty list to worker to create event. self._reqs_need_send[request.request_id] = [] def build_connector_meta( self, scheduler_output: SchedulerOutput, ) -> KVConnectorMetadata: meta = MooncakeConnectorMetadata() # Loop through scheduled reqs and convert to RecvReqMeta. if self.kv_role != "kv_producer": for req_id, (req, block_ids) in self._reqs_need_recv.items(): assert req.kv_transfer_params is not None meta.add_new_req( request_id=req_id, local_block_ids=block_ids, kv_transfer_params=req.kv_transfer_params, ) self._reqs_need_recv.clear() if self.kv_role != "kv_consumer": for req_id, block_ids in self._reqs_need_send.items(): meta.add_new_req( request_id=req_id, local_block_ids=block_ids, kv_transfer_params={}, load_remote_cache=False, ) self._reqs_need_send.clear() return meta def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: """ Once a request is finished, determine whether request blocks should be freed now or will be sent asynchronously and freed later. """ params = request.kv_transfer_params logger.debug( "MooncakeConnector request_finished, request_status=%s, " "kv_transfer_params=%s", request.status, params, ) if not params: return False, None if params.get("do_remote_prefill"): # If do_remote_prefill is still True when the request is finished, # update_state_after_alloc must not have been called (the request # must have been aborted before it was scheduled). # To avoid stranding the prefill blocks in the prefill instance, # we must add empty block_ids to _reqs_need_recv so that our # worker side will notify and free blocks in the prefill instance. assert self.kv_role != "kv_producer" self._reqs_need_recv[request.request_id] = (request, []) params["do_remote_prefill"] = False return False, None if ( not params.get("do_remote_decode") or request.status != RequestStatus.FINISHED_LENGTH_CAPPED ): return False, None assert self.kv_role != "kv_consumer" # TODO: check whether block_ids actually ever be 0. If not we could # remove the conditional below delay_free_blocks = len(block_ids) > 0 if delay_free_blocks: self._reqs_need_send[request.request_id] = block_ids return delay_free_blocks, dict( do_remote_prefill=True, do_remote_decode=False, remote_host=self.side_channel_host, remote_port=self.side_channel_port, ) class MooncakeConnectorWorker: """Implementation of Worker side methods""" def __init__(self, vllm_config: VllmConfig, engine_id: str): logger.info("Initializing Mooncake Transfer Engine worker %s", engine_id) self.vllm_config = vllm_config self.engine = TransferEngine() self.hostname = get_ip() protocol = self.vllm_config.kv_transfer_config.kv_connector_extra_config.get( # type: ignore[union-attr] "mooncake_protocol", "rdma" ) logger.info( "The Mooncake Transfer Engine is using %s as its protocol.", protocol ) ret_value = self.engine.initialize(self.hostname, "P2PHANDSHAKE", protocol, "") if ret_value != 0: raise RuntimeError("Mooncake Transfer Engine initialization failed.") self.rpc_port = self.engine.get_rpc_port() logger.debug( "Mooncake Transfer Engine initialized at %s:%d", self.hostname, self.rpc_port, ) # Mooncake handshake port. self.side_channel_port: int = get_mooncake_side_channel_port(vllm_config) self.engine_id: EngineId = engine_id self.tp_rank = get_tensor_model_parallel_rank() self.world_size = get_tensor_model_parallel_world_size() self.tp_group = get_tp_group() self.num_blocks = 0 assert vllm_config.kv_transfer_config self.kv_role = vllm_config.kv_transfer_config.kv_role self.num_workers = vllm_config.kv_transfer_config.kv_connector_extra_config.get( "num_workers", 10 ) self.kv_caches_base_addr: list[int] = [] self.device_kv_caches: dict[str, torch.Tensor] = {} self.reqs_need_send: SendReqMeta = SendReqMeta(reqs={}, lock=threading.Lock()) # For kv_both, we will act both prefiller and decoder. if self.kv_role != "kv_consumer": # Background thread for sending kvcaches to D. self._mooncake_sender_t: threading.Thread | None = None # Background thread for processing new sending requests. self._sender_executor = ThreadPoolExecutor( max_workers=self.num_workers, thread_name_prefix="vllm-mooncake-sender" ) logger.debug( "Mooncake Prefiller: use %d workers to send kvcaches", self.num_workers ) if self.kv_role != "kv_producer": self.receiver_loop = asyncio.new_event_loop() self._mooncake_receiver_t = threading.Thread( target=self._receiver_loop, args=(self.receiver_loop,), daemon=True ) self._mooncake_receiver_t.start() logger.debug("Mooncake Decoder: start receiver thread") self.finished_sending_reqs: FinishedSendReqSet = FinishedSendReqSet( set(), threading.Lock() ) self.finished_recving_reqs: FinishedReceiveReqSet = FinishedReceiveReqSet( set(), asyncio.Lock() ) self.block_size = vllm_config.cache_config.block_size self.model_config = vllm_config.model_config self.cache_config = vllm_config.cache_config self.use_mla = self.model_config.use_mla backend = get_attn_backend( self.model_config.get_head_size(), self.model_config.dtype, self.cache_config.cache_dtype, self.block_size, use_mla=self.use_mla, ) self.backend_name = backend.get_name() self.kv_cache_layout = get_kv_cache_layout() logger.debug("Detected attention backend %s", self.backend_name) logger.debug("Detected kv cache layout %s", self.kv_cache_layout) self._tp_size: dict[EngineId, int] = {self.engine_id: self.world_size} self._block_size: dict[EngineId, int] = {self.engine_id: self.block_size} self.kv_topo = TpKVTopology( tp_rank=self.tp_rank, engine_id=self.engine_id, remote_tp_size=self._tp_size, # shared state remote_block_size=self._block_size, # shared state is_mla=self.use_mla, total_num_kv_heads=self.model_config.get_total_num_kv_heads(), attn_backend=backend, ) self._use_pallas = self.kv_topo._use_pallas self.zmq_ctx = zmq.Context() self.async_zmq_ctx = zmq.asyncio.Context() self._encoder = msgspec.msgpack.Encoder() self._decoder = msgspec.msgpack.Decoder(MooncakeAgentMetadata) def __del__(self): self.shutdown() def shutdown(self): """Cleanup background threads on destruction.""" self.zmq_ctx.term() self.async_zmq_ctx.term() if self.kv_role != "kv_consumer": self._sender_executor.shutdown(wait=False) if self._mooncake_sender_t: self._mooncake_sender_t.join() if self.kv_role != "kv_producer" and self.receiver_loop.is_running(): self.receiver_loop.call_soon_threadsafe(self.receiver_loop.stop) self._mooncake_receiver_t.join() def _receiver_loop(self, loop: asyncio.AbstractEventLoop): asyncio.set_event_loop(loop) loop.run_forever() def _mooncake_sender( self, ready_event: threading.Event, base_port: int, tp_rank: int ): """ Background thread that listens for Mooncake requests, dispatches them to a thread pool, and sends acknowledgments upon completion. """ frontend_path = make_zmq_path("tcp", self.hostname, base_port + tp_rank) frontend = make_zmq_socket(self.zmq_ctx, frontend_path, zmq.ROUTER) logger.debug("Mooncake sender starting listening on path: %s", frontend_path) backend_path = make_zmq_path("inproc", str(uuid.uuid4())) backend = make_zmq_socket(self.zmq_ctx, backend_path, zmq.PULL) poller = zmq.Poller() poller.register(frontend, zmq.POLLIN) poller.register(backend, zmq.POLLIN) ready_event.set() try: while True: sockets = dict(poller.poll()) if frontend in sockets: identity, _, metadata_bytes = frontend.recv_multipart() self._sender_executor.submit( self._sender_worker, identity, metadata_bytes, backend_path, ) if backend in sockets: identity, status = backend.recv_multipart() frontend.send_multipart((identity, b"", status)) except zmq.ContextTerminated: logger.debug("ZMQ context terminated, exiting Mooncake sender thread.") except Exception as e: logger.error("Error in Mooncake sender thread: %s. Exiting thread.", str(e)) finally: frontend.close() backend.close() def _sender_worker( self, identity: bytes, metadata_bytes: bytes, worker_channel_path: str ): status = TRANS_ERROR try: metadata = self._decoder.decode(metadata_bytes) self.send_kv_to_decode(metadata) status = TRANS_DONE except Exception as e: logger.error("Error processing Mooncake handshake: %s", e) finally: pusher = make_zmq_socket(self.zmq_ctx, worker_channel_path, zmq.PUSH) try: pusher.send_multipart((identity, status)) except zmq.ZMQError as e: logger.warning( "Internal error, maybe the server is shutting down. Error: %s", e, ) finally: pusher.close() def send_kv_to_decode(self, meta: MooncakeAgentMetadata): send_reqs: list[tuple[ReqId, SendBlockMeta]] = [] with self.reqs_need_send.lock: for req_id in meta.request_ids: send_meta = self.reqs_need_send.reqs.get(req_id) if send_meta is None: logger.warning("Request %s not found in reqs_need_send", req_id) return # Mark it as not expired. We will send it now. send_meta.expire_time = float("inf") send_reqs.append((req_id, send_meta)) self._send_blocks(send_reqs, meta) with self.reqs_need_send.lock: for req_id in meta.request_ids: del self.reqs_need_send.reqs[req_id] with self.finished_sending_reqs.lock: self.finished_sending_reqs.set.update(meta.request_ids) def _send_blocks( self, send_reqs: list[tuple[ReqId, SendBlockMeta]], agent_meta: MooncakeAgentMetadata, ): src_ptrs = [] dst_ptrs = [] lengths = [] local_base_addr = self.kv_caches_base_addr remote_base_addr = agent_meta.kv_caches_base_addr block_len = self.block_len remote_session = f"{agent_meta.remote_hostname}:{agent_meta.remote_port}" assert len(send_reqs) == len(agent_meta.block_ids) for (req_id, send_meta), remote_block_ids in zip( send_reqs, agent_meta.block_ids ): send_meta.ready.wait() num_remote_blocks = len(remote_block_ids) if num_remote_blocks == 0: continue local_block_ids = send_meta.local_block_ids # Partial prefix cache hit: just read uncomputed blocks. num_local_blocks = len(local_block_ids) assert num_local_blocks >= num_remote_blocks if num_local_blocks > num_remote_blocks: local_block_ids = local_block_ids[-num_remote_blocks:] # Group by indices group_local_block_ids, group_remote_block_ids = group_concurrent_contiguous( local_block_ids, remote_block_ids ) for local_layer_addr, remote_layer_addr in zip( local_base_addr, remote_base_addr ): for group_local_block_id, group_remote_block_id in zip( group_local_block_ids, group_remote_block_ids ): src_ptrs.append( local_layer_addr + group_local_block_id[0] * block_len ) dst_ptrs.append( remote_layer_addr + group_remote_block_id[0] * block_len ) lengths.append(block_len * len(group_local_block_id)) logger.debug( "Sending kv_caches for request %s (%d blocks) to %s", req_id, num_remote_blocks, remote_session, ) start_time = time.perf_counter() ret_value = self.engine.batch_transfer_sync_write( remote_session, src_ptrs, dst_ptrs, lengths ) if ret_value != 0: raise RuntimeError(f"Error in batch_transfer_sync_write: {ret_value}") logger.debug( "Sending to %s done, took %s", remote_session, time.perf_counter() - start_time, ) def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): """Register the KV Cache data in mooncake.""" logger.info("Registering KV_Caches. use_mla: %s", self.use_mla) kv_data_ptrs = [] kv_data_lens = [] seen_base_addresses = [] split_k_and_v = self.kv_topo.split_k_and_v tensor_size_bytes = None for layer_name, cache_or_caches in kv_caches.items(): logger.debug( "registering layer %s with shape %s", layer_name, cache_or_caches.shape ) cache_list = cache_or_caches if split_k_and_v else [cache_or_caches] for cache in cache_list: base_addr = cache.data_ptr() if base_addr in seen_base_addresses: continue seen_base_addresses.append(base_addr) curr_tensor_size_bytes = cache.nbytes if tensor_size_bytes is None: tensor_size_bytes = curr_tensor_size_bytes self.num_blocks = cache.shape[0] assert tensor_size_bytes == curr_tensor_size_bytes, ( "All kv cache tensors must have the same size" ) kernel_block_size = cache.shape[-2 if self.use_mla else -3] assert self.block_size == kernel_block_size kv_data_ptrs.append(base_addr) kv_data_lens.append(tensor_size_bytes) self.kv_caches_base_addr = seen_base_addresses ret_value = self.engine.batch_register_memory(kv_data_ptrs, kv_data_lens) if ret_value != 0: raise RuntimeError("Mooncake batch memory registration failed.") assert tensor_size_bytes is not None assert self.num_blocks != 0 assert tensor_size_bytes % self.num_blocks == 0 self.block_len = tensor_size_bytes // self.num_blocks self.device_kv_caches = kv_caches logger.debug( "registered num_blocks=%d block_len=%d", self.num_blocks, self.block_len ) # No need to launch server for D node. if self.kv_role == "kv_consumer": return ready_event = threading.Event() self._mooncake_sender_t = threading.Thread( target=self._mooncake_sender, args=(ready_event, self.side_channel_port, self.tp_rank), daemon=True, name="mooncake_sender", ) self._mooncake_sender_t.start() ready_event.wait() # Wait for listener ZMQ socket to be ready. async def fetch_finished_recving_reqs(self) -> set[ReqId]: async with self.finished_recving_reqs.lock: finished_recving_reqs = self.finished_recving_reqs.set self.finished_recving_reqs.set = set() return finished_recving_reqs def get_finished(self) -> tuple[set[str] | None, set[str] | None]: """ Get requests that are done sending or recving on this specific worker. The scheduler process (via the MultiprocExecutor) will use this output to track which workers are done. """ fut = None if self.kv_role != "kv_producer": fut = asyncio.run_coroutine_threadsafe( self.fetch_finished_recving_reqs(), self.receiver_loop ) if self.kv_role != "kv_consumer": with self.finished_sending_reqs.lock: finished_sending_reqs = self.finished_sending_reqs.set self.finished_sending_reqs.set = set() else: finished_sending_reqs = set() finished_recving_reqs = fut.result() if fut else set() if finished_sending_reqs or finished_recving_reqs: logger.debug( "Rank %s, get_finished: %s requests done sending " "and %s requests done recving", self.tp_rank, len(finished_sending_reqs), len(finished_recving_reqs), ) # Handle timeout to avoid stranding blocks on remote. now = time.perf_counter() with self.reqs_need_send.lock: expired_reqs = [ req_id for req_id, send_meta in self.reqs_need_send.reqs.items() if send_meta.expire_time < now ] for req_id in expired_reqs: logger.warning( "Request %s timed out after %d seconds without " "being sent. Freeing its blocks on the producer side.", req_id, envs.VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT, ) del self.reqs_need_send.reqs[req_id] if expired_reqs: finished_sending_reqs.update(expired_reqs) return finished_sending_reqs or None, finished_recving_reqs or None async def receive_kv(self, path: str, req_blocks: list[tuple[str, list[int]]]): req_ids, block_ids = map(list, zip(*req_blocks)) metadata = MooncakeAgentMetadata( remote_hostname=self.hostname, remote_port=self.rpc_port, request_ids=req_ids, kv_caches_base_addr=self.kv_caches_base_addr, block_ids=block_ids, ) encoded_data = self._encoder.encode(metadata) logger.debug( "Size of encoded MooncakeAgentMetadata: %d bytes", len(encoded_data) ) logger.debug("Sending kv transfer request for %s on path: %s", req_ids, path) # Send query for the request. sock: zmq.asyncio.Socket = make_zmq_socket( self.async_zmq_ctx, path, zmq.REQ, bind=False, linger=0 ) sock.setsockopt(zmq.RCVTIMEO, 60000) try: await sock.send(encoded_data) ret_msg = await sock.recv() if ret_msg != TRANS_DONE: logger.error( "Error happens during tranfering kvcache for %s, see logs in prefiller.", # noqa: E501 req_ids, ) return except zmq.ContextTerminated: logger.debug("ZMQ context terminated, exiting Mooncake receiver thread.") except Exception as e: logger.error("MooncakeAgentMetadata transfer failed for %s: %s", req_ids, e) return finally: sock.close() async with self.finished_recving_reqs.lock: self.finished_recving_reqs.set.update(req_ids) logger.debug("pulling kv_caches for %s finished", req_ids) def group_kv_pull(self, metadata: MooncakeConnectorMetadata): kv_pulls = defaultdict(list) for req_id, meta in metadata.reqs_to_recv.items(): logger.debug( "start_load_kv for request %s from remote engine. " "Num local_block_ids: %s.", req_id, len(meta.local_block_ids), ) path = make_zmq_path( "tcp", meta.remote_host, meta.remote_port + self.tp_rank ) kv_pulls[path].append((req_id, meta.local_block_ids)) return kv_pulls def start_load_kv(self, metadata: MooncakeConnectorMetadata): if self.kv_role != "kv_producer": kv_pulls = self.group_kv_pull(metadata) for path, req_blocks in kv_pulls.items(): asyncio.run_coroutine_threadsafe( self.receive_kv(path, req_blocks), self.receiver_loop ) if self.kv_role != "kv_consumer": with self.reqs_need_send.lock: for req_id, block_ids in metadata.reqs_to_send.items(): if block_ids: # Already gone through request_finished()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/decode_bench_connector.py
vllm/distributed/kv_transfer/kv_connector/v1/decode_bench_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ DecodeBenchConnector: A KV Connector for decode instance performance testing. This connector emulates a prefill-decode disaggregated setting by filling the KV cache with dummy values, allowing measurement of decoder performance under larger input sequence lengths (ISL) in resource-limited environments. Usage: To use this connector for benchmarking, configure it in the kv_transfer_config: Example: vllm serve <model> --kv-transfer-config '{ "kv_connector": "DecodeBenchConnector", "kv_role": "kv_both", "kv_connector_extra_config": { "fill_mean": 0.015, "fill_std": 0.0 } }' Then run your benchmark with desired input/output lengths: vllm bench serve --base-url http://127.0.0.1:8000 --model <model> \\ --dataset-name random --random-input-len 40000 \\ --random-output-len 100 --max-concurrency 10 Configuration options (via kv_connector_extra_config): - fill_mean (float): Mean value for random normal fill (default: 0.015) - fill_std (float): Standard deviation for random fill (default: 0.0) Set to 0 for constant values, >0 for random sampling """ from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Optional import torch from vllm.attention.backends.abstract import AttentionMetadata from vllm.distributed.kv_transfer.kv_connector.v1 import ( KVConnectorBase_V1, KVConnectorRole, ) from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorMetadata from vllm.logger import init_logger from vllm.utils.math_utils import cdiv if TYPE_CHECKING: from vllm.config import VllmConfig from vllm.forward_context import ForwardContext from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request logger = init_logger(__name__) @dataclass class DecodeBenchConnectorMetadata(KVConnectorMetadata): """Metadata for DecodeBenchConnector. Contains information about which requests need their KV cache filled with dummy values for benchmarking purposes. """ # request_id -> (block_ids_per_group, num_tokens_to_fill) # block_ids_per_group is a tuple of lists, one per KV cache group # For standard attention: single group, e.g., ([1, 2, 3],) # For MLA: multiple groups, e.g., ([1, 2], [1, 2]) reqs_to_fill: dict[str, tuple[tuple[list[int], ...], int]] class DecodeBenchConnector(KVConnectorBase_V1): """ A KV Connector for decode instance performance testing. This connector fills the KV cache with dummy (non-zero) values to emulate a prefill-decode disaggregated setting, enabling performance testing of the decoder with larger input sequence lengths. """ def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, kv_cache_config: Optional["KVCacheConfig"] = None, ): super().__init__(vllm_config, role, kv_cache_config) self.connector_scheduler: DecodeBenchConnectorScheduler | None = None self.connector_worker: DecodeBenchConnectorWorker | None = None if role == KVConnectorRole.SCHEDULER: self.connector_scheduler = DecodeBenchConnectorScheduler(vllm_config) elif role == KVConnectorRole.WORKER: self.connector_worker = DecodeBenchConnectorWorker(vllm_config) # ============================== # Worker-side methods # ============================== def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): assert self.connector_worker is not None self.connector_worker.register_kv_caches(kv_caches) def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None: assert self.connector_worker is not None assert isinstance(self._connector_metadata, DecodeBenchConnectorMetadata) self.connector_worker.start_fill_kv(self._connector_metadata) def wait_for_layer_load(self, layer_name: str) -> None: # All operations are synchronous, so nothing to wait for pass def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: AttentionMetadata, **kwargs: Any, ) -> None: # This connector doesn't save KV cache (benchmarking only) pass def wait_for_save(self): # This connector doesn't save KV cache (benchmarking only) pass # ============================== # Scheduler-side methods # ============================== def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int | None, bool]: assert self.connector_scheduler is not None return self.connector_scheduler.get_num_new_matched_tokens( request, num_computed_tokens ) def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): assert self.connector_scheduler is not None return self.connector_scheduler.update_state_after_alloc( request, blocks, num_external_tokens ) def build_connector_meta( self, scheduler_output: "SchedulerOutput" ) -> KVConnectorMetadata: assert self.connector_scheduler is not None return self.connector_scheduler.build_connector_meta(scheduler_output) def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: assert self.connector_scheduler is not None self.connector_scheduler.request_finished(request) return False, None class DecodeBenchConnectorScheduler: """Scheduler-side implementation for DecodeBenchConnector.""" def __init__(self, vllm_config: "VllmConfig"): self.vllm_config = vllm_config self.block_size = vllm_config.cache_config.block_size # Track which requests have already been filled self._filled_requests: set[str] = set() # Track pending fills for the current scheduler step # request_id -> (block_ids_per_group, num_tokens_to_fill) # Note: _pending_fills doesn't need explicit cleanup - it's cleared # after build_connector_meta() is called in the same scheduler step self._pending_fills: dict[str, tuple[tuple[list[int], ...], int]] = {} def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int, bool]: """ For new requests, return the number of tokens that should be filled with dummy KV cache values. Returns: (num_tokens_to_fill, is_async) - num_tokens_to_fill: number of uncomputed tokens minus 1 (we fill everything except the last token for decode) - is_async: False (synchronous filling) """ req_id = request.request_id # Only fill once per request on first scheduling if req_id in self._filled_requests: return 0, False # Calculate how many tokens we need to fill # Fill all uncomputed tokens except the last one (which will be decoded) # This simulates having processed a long prefill num_uncomputed_tokens = request.num_tokens - num_computed_tokens num_tokens_to_fill = max(0, num_uncomputed_tokens - 1) if num_tokens_to_fill == 0: return 0, False # Return False for synchronous operation - the fill is fast enough # that async overhead isn't worth it return num_tokens_to_fill, False def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): """ Called after blocks are allocated. Store the block IDs so we can fill them with dummy values. Supports both standard attention (single KV cache group) and MLA (multiple KV cache groups). """ req_id = request.request_id if num_external_tokens == 0: return # Get the block IDs that were allocated # block_groups is a tuple of lists, one per KV cache group # For standard attention: 1 group # For MLA: multiple groups (one per attention type) block_groups = blocks.get_block_ids() # Calculate how many blocks we need to fill # num_external_tokens are the tokens we said we'd provide num_blocks_to_fill = cdiv(num_external_tokens, self.block_size) # Extract the first num_blocks_to_fill blocks from each group # All groups should have the same block IDs for the same request block_ids_per_group = tuple( group_blocks[:num_blocks_to_fill] for group_blocks in block_groups ) # Store the blocks to fill for all group. _pending_fills doesn't need cleanup # as it's cleared after build_connector_meta self._pending_fills[req_id] = ( block_ids_per_group, num_external_tokens, ) self._filled_requests.add(req_id) logger.debug( "DecodeBenchConnector: Allocated %d blocks across %d KV cache groups " "for request %s", num_blocks_to_fill, len(block_groups), req_id, ) def build_connector_meta( self, scheduler_output: "SchedulerOutput" ) -> KVConnectorMetadata: """ Build metadata containing information about which blocks to fill with dummy KV values. """ meta = DecodeBenchConnectorMetadata(reqs_to_fill=self._pending_fills.copy()) # Clear pending fills after building metadata self._pending_fills.clear() return meta def request_finished(self, request: "Request"): """ Called when a request has finished. Clean up any state. """ self._filled_requests.discard(request.request_id) class DecodeBenchConnectorWorker: """Worker-side implementation for DecodeBenchConnector.""" def __init__(self, vllm_config: "VllmConfig"): self.vllm_config = vllm_config self.block_size = vllm_config.cache_config.block_size # Get fill parameters from extra config kv_transfer_config = vllm_config.kv_transfer_config assert kv_transfer_config is not None self.fill_mean = kv_transfer_config.get_from_extra_config("fill_mean", 0.015) self.fill_std = kv_transfer_config.get_from_extra_config("fill_std", 0.0) # Will be populated via register_kv_caches self.kv_caches: dict[str, torch.Tensor] | None = None # Mapping from KV cache group index to list of layer names in that group self.group_to_layers: dict[int, list[str]] | None = None def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): """Store references to the KV cache tensors and build group mapping.""" self.kv_caches = kv_caches # For simplicity, assume all layers belong to group 0 (standard attention) # For MLA models with multiple groups, the metadata will handle the mapping # We just need to fill the blocks specified in the metadata self.group_to_layers = {0: list(kv_caches.keys())} logger.debug( "DecodeBenchConnector: Registered %d KV cache layers", len(kv_caches), ) def start_fill_kv(self, metadata: DecodeBenchConnectorMetadata): """ Fill the allocated KV cache blocks with dummy (non-zero) values. This simulates having a populated KV cache from a prefill phase, allowing decode performance testing with larger context sizes. Supports both standard attention (single group) and MLA (multiple groups). """ if not metadata.reqs_to_fill: return assert self.kv_caches is not None, "KV caches must be registered before filling" assert self.group_to_layers is not None, "Group mapping must be initialized" for req_id, (block_ids_per_group, num_tokens) in metadata.reqs_to_fill.items(): # Fill blocks for each KV cache group for group_idx, block_ids in enumerate(block_ids_per_group): self._fill_blocks(group_idx, block_ids, num_tokens) logger.debug( "DecodeBenchConnector: Filled %d blocks (%d tokens) across %d groups " "for request %s", len(block_ids_per_group[0]) if block_ids_per_group else 0, num_tokens, len(block_ids_per_group), req_id, ) def _fill_blocks(self, group_idx: int, block_ids: list[int], num_tokens: int): """ Fill specified blocks with dummy non-zero values for a specific KV cache group. Args: group_idx: The KV cache group index to fill block_ids: List of block IDs to fill in this group num_tokens: Total number of tokens to fill across these blocks """ if not block_ids: return assert self.kv_caches is not None assert self.group_to_layers is not None # Get the layers that belong to this group layer_names = self.group_to_layers.get(group_idx, []) # Fill only the layers in this group for layer_name in layer_names: if layer_name not in self.kv_caches: logger.warning( "DecodeBenchConnector: Layer %s not found in KV caches", layer_name ) continue kv_cache = self.kv_caches[layer_name] # Convert block_ids to tensor on device block_ids_tensor = torch.tensor( block_ids, dtype=torch.long, device=kv_cache.device ) # Filter invalid block IDs valid_mask = block_ids_tensor < kv_cache.shape[0] valid_block_ids = block_ids_tensor[valid_mask] if len(valid_block_ids) == 0: continue # Create fill values - either constant or random block_shape = kv_cache.shape[1:] if self.fill_std > 0: # Random normal sampling fill_values = torch.normal( mean=self.fill_mean, std=self.fill_std, size=(len(valid_block_ids),) + block_shape, dtype=kv_cache.dtype, device=kv_cache.device, ) else: # Constant fill value fill_values = torch.full( (len(valid_block_ids),) + block_shape, self.fill_mean, dtype=kv_cache.dtype, device=kv_cache.device, ) # Batch fill operation kv_cache[valid_block_ids] = fill_values logger.debug( "DecodeBenchConnector: Filled %d blocks in group %d with %s values " "(mean=%.3f, std=%.3f)", len(block_ids), group_idx, "random" if self.fill_std > 0 else "constant", self.fill_mean, self.fill_std, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/example_connector.py
vllm/distributed/kv_transfer/kv_connector/v1/example_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Optional import safetensors import torch from vllm.attention.backends.abstract import AttentionMetadata from vllm.config import VllmConfig from vllm.distributed.kv_transfer.kv_connector.v1.base import ( KVConnectorBase_V1, KVConnectorMetadata, KVConnectorRole, ) from vllm.logger import init_logger from vllm.utils.hashing import safe_hash from vllm.v1.attention.backends.mla.common import MLACommonMetadata from vllm.v1.core.sched.output import SchedulerOutput if TYPE_CHECKING: from vllm.forward_context import ForwardContext from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request logger = init_logger(__name__) @dataclass class ReqMeta: # Request tokens token_ids: torch.Tensor # Slot mappings, should have the same length as token_ids slot_mapping: torch.Tensor # Is store or load is_store: bool mm_hashes: list[str] @staticmethod def make_meta( token_ids: list[int], block_ids: list[int], block_size: int, is_store: bool, mm_hashes: list[str], ) -> "ReqMeta": valid_num_tokens = align_to_block_size(len(token_ids), block_size) token_ids_tensor = torch.tensor(token_ids)[:valid_num_tokens] block_ids_tensor = torch.tensor(block_ids) num_blocks = block_ids_tensor.shape[0] block_offsets = torch.arange(0, block_size) slot_mapping = ( block_offsets.reshape((1, block_size)) + block_ids_tensor.reshape((num_blocks, 1)) * block_size ) slot_mapping = slot_mapping.flatten()[:valid_num_tokens] return ReqMeta( token_ids=token_ids_tensor, slot_mapping=slot_mapping, is_store=is_store, mm_hashes=mm_hashes, ) @dataclass class ExampleConnectorMetadata(KVConnectorMetadata): requests: list[ReqMeta] = field(default_factory=list) def add_request( self, token_ids: list[int], block_ids: list[int], block_size: int, is_store: bool, mm_hashes: list[str], ) -> None: self.requests.append( ReqMeta.make_meta(token_ids, block_ids, block_size, is_store, mm_hashes) ) class ExampleConnector(KVConnectorBase_V1): # NOTE: This is Simple debug implementation of the KV connector. # It save / load the KV cache to / from the disk. # It does extra work which will overwrite the existing prefix-cache in GPU # - to remove the overhead, need to add some "mask" in the ReqMeta class def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, kv_cache_config: Optional["KVCacheConfig"] = None, ): super().__init__( vllm_config=vllm_config, role=role, kv_cache_config=kv_cache_config, ) self._block_size = vllm_config.cache_config.block_size self._requests_need_load: dict[str, Request] = {} self._storage_path = self._kv_transfer_config.get_from_extra_config( "shared_storage_path", "/tmp" ) logger.info(self._kv_transfer_config) logger.info("Shared storage path is %s", self._storage_path) def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None: """Start loading the KV cache from the connector buffer to vLLM's paged KV buffer. Args: forward_context (ForwardContext): the forward context. **kwargs: additional arguments for the load operation Note: The number of elements in kv_caches and layer_names should be the same. """ attn_metadata = forward_context.attn_metadata def inject_kv_into_layer( dst_kv_cache_layer: torch.Tensor, src_kv_cache: torch.Tensor, slot_mapping: torch.Tensor, ) -> None: """Inject the KV cache into the layer. Args: dst_kv_cache_layer (torch.Tensor): the destination KV cache layer. In shape [2, num_pages, page_size, xxx] if not using MLA, [num_pages, page_size, xxx] otherwise. src_kv_cache (torch.Tensor): the source KV cache. In shape [2, num_tokens, xxx] if not using MLA, [num_tokens, xxx] otherwise. slot_mapping (torch.Tensor): the slot mapping. In shape [num_tokens]. """ dst_kv_cache_layer_shape = dst_kv_cache_layer.shape if isinstance(attn_metadata, MLACommonMetadata): num_pages = dst_kv_cache_layer_shape[0] page_size = dst_kv_cache_layer_shape[1] dst_kv_cache_layer = dst_kv_cache_layer.reshape( num_pages * page_size, -1 ) dst_kv_cache_layer[slot_mapping, ...] = src_kv_cache dst_kv_cache_layer.reshape(dst_kv_cache_layer_shape) else: num_pages = dst_kv_cache_layer_shape[1] page_size = dst_kv_cache_layer_shape[2] dst_kv_cache_layer = dst_kv_cache_layer.reshape( 2, num_pages * page_size, -1 ) dst_kv_cache_layer[:, slot_mapping, ...] = src_kv_cache dst_kv_cache_layer.reshape(dst_kv_cache_layer_shape) # Get the metadata metadata: KVConnectorMetadata = self._get_connector_metadata() assert isinstance(metadata, ExampleConnectorMetadata) if metadata is None: logger.warning( "In connector.start_load_kv, but the connector metadata is None" ) return attn_metadata = forward_context.attn_metadata if attn_metadata is None: logger.warning("In connector.start_load_kv, but the attn_metadata is None") return # Load the KV for each request each layer for request in metadata.requests: if request.is_store: continue logger.info( "Inject KV cache of %d tokens to the paged memory", len(request.slot_mapping), ) for layer_name in forward_context.no_compile_layers: layer = forward_context.no_compile_layers[layer_name] # Only process layers that have kv_cache # attribute (attention layers) Skip non-attention # layers like FusedMoE/MLP etc. kv_cache_attr = getattr(layer, "kv_cache", None) if kv_cache_attr is None: continue kv_cache_layer = kv_cache_attr[forward_context.virtual_engine] filename = self._generate_filename_debug( layer_name, request.token_ids, request.mm_hashes ) kv_cache = safetensors.torch.load_file(filename)["kv_cache"].cuda() inject_kv_into_layer(kv_cache_layer, kv_cache, request.slot_mapping) def wait_for_layer_load(self, layer_name: str) -> None: """Blocking until the KV for a specific layer is loaded into vLLM's paged buffer. This interface will be useful for layer-by-layer pipelining. Args: layer_name: the name of that layer """ return def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: AttentionMetadata, **kwargs: Any, ) -> None: """Start saving the KV cache of the layer from vLLM's paged buffer to the connector. Args: layer_name (str): the name of the layer. kv_layer (torch.Tensor): the paged KV buffer of the current layer in vLLM. attn_metadata (AttentionMetadata): the attention metadata. **kwargs: additional arguments for the save operation. """ def extract_kv_from_layer( layer: torch.Tensor, slot_mapping: torch.Tensor, ) -> torch.Tensor: """Extract the KV cache from the layer. Assume the shape of the layer is (2, num_pages, page_size, xxx) if MLA is not used, and (num_pages, page_size, xxx) otherwise. """ if isinstance(attn_metadata, MLACommonMetadata): num_pages, page_size = layer.shape[0], layer.shape[1] return layer.reshape(num_pages * page_size, -1)[slot_mapping, ...] num_pages, page_size = layer.shape[1], layer.shape[2] return layer.reshape(2, num_pages * page_size, -1)[:, slot_mapping, ...] connector_metadata = self._get_connector_metadata() assert isinstance(connector_metadata, ExampleConnectorMetadata) for request in connector_metadata.requests: if request.is_store: filename = self._generate_filename_debug( layer_name, request.token_ids, request.mm_hashes ) kv_cache = extract_kv_from_layer(kv_layer, request.slot_mapping) tensors = {"kv_cache": kv_cache.detach().cpu()} safetensors.torch.save_file(tensors, filename) def wait_for_save(self): return def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int | None, bool]: """ Get number of new tokens that can be loaded from the external KV cache beyond the num_computed_tokens. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: the number of tokens that can be loaded from the external KV cache beyond what is already computed. """ # NOTE: in this debug implementation, we assume that the prompt is # cached_prompt + newly_generated_single_token # Therefore, we use prompt_token_ids[:-1] to determine the folder name # NOTE: in current v1 scheduler, the num_computed_tokens is aligned # with the block granularity. And it expects the returned blocks and # num_computed_tokens to also be aligned with the block granularity. if not self._found_match_for_request(request): return 0, False logger.info("External Cache Hit!") # Now, first num_tokens_to_check tokens are hit, we need to prepare # the metadata for the worker connector to correctly load the KV token_ids = request.prompt_token_ids or [] num_tokens_to_check = align_to_block_size(len(token_ids) - 1, self._block_size) return num_tokens_to_check - num_computed_tokens, False def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): """ Update KVConnector state after block allocation. If blocks were allocated, add to _requests_need_load, such that we load the KVs in the next forward pass. """ if num_external_tokens > 0: self._requests_need_load[request.request_id] = request def build_connector_meta( self, scheduler_output: SchedulerOutput, ) -> KVConnectorMetadata: """Build the connector metadata for this step. This function should NOT modify any fields in the scheduler_output. Also, calling this function will reset the state of the connector. Args: scheduler_output (SchedulerOutput): the scheduler output object. """ meta = ExampleConnectorMetadata() total_need_load = 0 for new_req in scheduler_output.scheduled_new_reqs: token_ids = new_req.prompt_token_ids or [] mm_hashes = [f.identifier for f in new_req.mm_features] if new_req.req_id in self._requests_need_load: meta.add_request( token_ids=token_ids, block_ids=new_req.block_ids[0], block_size=self._block_size, is_store=False, mm_hashes=mm_hashes, ) total_need_load += 1 else: # NOTE: here, we set the store and load being exclusive, # but a single request can have both store and load. # NOTE(rob): for this debug implementation, we only cache # the original prompt tokens. if not self._found_match_for_prompt(token_ids, mm_hashes): meta.add_request( token_ids=token_ids, block_ids=new_req.block_ids[0], block_size=self._block_size, is_store=True, mm_hashes=mm_hashes, ) cached_reqs = scheduler_output.scheduled_cached_reqs for i, req_id in enumerate(cached_reqs.req_ids): resumed_from_preemption = req_id in cached_reqs.resumed_req_ids if not resumed_from_preemption or req_id not in self._requests_need_load: continue num_computed_tokens = cached_reqs.num_computed_tokens[i] num_new_tokens = scheduler_output.num_scheduled_tokens[req_id] new_block_ids = cached_reqs.new_block_ids[i] # NOTE(rob): cached_req_data does not have the full # list of token ids (only new tokens). So we look it # up in the actual request object. request = self._requests_need_load[req_id] total_tokens = num_computed_tokens + num_new_tokens token_ids = request.all_token_ids[:total_tokens] # NOTE(rob): For resumed req, new_block_ids is all # of the block_ids for the request. assert new_block_ids is not None block_ids = new_block_ids[0] meta.add_request( token_ids=token_ids, block_ids=block_ids, block_size=self._block_size, is_store=False, mm_hashes=[f.identifier for f in request.mm_features], ) total_need_load += 1 assert total_need_load == len(self._requests_need_load) self._requests_need_load.clear() return meta # ============================== # Helper functions # ============================== def _found_match_for_request( self, request: "Request", ) -> bool: """Check if the cache is hit for the request.""" return self._found_match_for_prompt( list(request.prompt_token_ids or []), [f.identifier for f in request.mm_features], ) def _found_match_for_prompt( self, prompt_token_ids: list[int], mm_hashes: list[str], ) -> bool: num_tokens_to_check = align_to_block_size( len(prompt_token_ids) - 1, self._block_size ) foldername = self._generate_foldername_debug( torch.tensor(prompt_token_ids)[:num_tokens_to_check], mm_hashes, create_folder=False, ) return os.path.exists(foldername) def _generate_foldername_debug( self, token_ids: torch.Tensor, mm_hashes: list[str], create_folder=False, ) -> str: """Generate a folder name based on the hash of the bytes of the input ids. """ token_bytes = token_ids.numpy().tobytes() # Add mm_hashes to the bytes being hashed to avoid path traversal and # to create a canonical key. if mm_hashes: mm_str = "-".join(mm_hashes) token_bytes += mm_str.encode("utf-8") input_ids_hash = safe_hash(token_bytes, usedforsecurity=False).hexdigest() foldername = os.path.join(self._storage_path, input_ids_hash) if create_folder: os.makedirs(foldername, exist_ok=True) return foldername def _generate_filename_debug( self, layer_name: str, token_ids: torch.Tensor, mm_hashes: list[str], ) -> str: """Generate a file name based on the layer name and the hash of the bytes of the input ids. """ foldername = self._generate_foldername_debug( token_ids, mm_hashes=mm_hashes, create_folder=True ) return os.path.join(foldername, f"{layer_name}.safetensors") def align_to_block_size(num_tokens: int, block_size) -> int: """Align the number of tokens to the block size.""" return (num_tokens - 1) // block_size * block_size
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/nixl_connector.py
vllm/distributed/kv_transfer/kv_connector/v1/nixl_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib import copy import logging import math import queue import threading import time import uuid from collections import defaultdict from collections.abc import Iterator from concurrent.futures import Future, ThreadPoolExecutor from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Optional import msgspec import numpy as np import torch import zmq from vllm import envs from vllm.attention.backends.abstract import AttentionMetadata from vllm.attention.selector import get_attn_backend from vllm.config import VllmConfig from vllm.distributed.kv_transfer.kv_connector.utils import ( EngineId, TpKVTopology, yield_req_data, ) from vllm.distributed.kv_transfer.kv_connector.v1.base import ( CopyBlocksOp, KVConnectorBase_V1, KVConnectorHandshakeMetadata, KVConnectorMetadata, KVConnectorRole, ) from vllm.distributed.kv_transfer.kv_connector.v1.metrics import ( KVConnectorPromMetrics, KVConnectorStats, PromMetric, PromMetricT, ) from vllm.distributed.parallel_state import ( get_tensor_model_parallel_rank, get_tensor_model_parallel_world_size, get_tp_group, ) from vllm.forward_context import ForwardContext from vllm.logger import init_logger from vllm.platforms import current_platform from vllm.utils.network_utils import make_zmq_path, make_zmq_socket from vllm.v1.attention.backends.utils import get_kv_cache_layout from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.worker.block_table import BlockTable if TYPE_CHECKING: from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request TransferHandle = int ReqId = str # # NIXL Connector Version # # Increment this version whenever there is an incompatible change to: # - NixlAgentMetadata schema # - kv_transfer_params schema or semantics # - NIXL transfer protocol or wire format # - KV cache memory layout or block organization # - Any other change that breaks P/D interoperability # # Version History: # 1: Initial version with compatibility checking # 2: Add remote_request_id to kv_transfer_params # NIXL_CONNECTOR_VERSION: int = 2 GET_META_MSG = b"get_meta_msg" logger = init_logger(__name__) # Lazy import nixl_wrapper to avoid loading nixl_bindings if nixl is not used try: if not current_platform.is_rocm(): from nixl._api import nixl_agent as NixlWrapper from nixl._bindings import nixlXferTelemetry else: from rixl._api import nixl_agent as NixlWrapper from rixl._bindings import nixlXferTelemetry logger.info("NIXL is available") except ImportError: logger.warning("NIXL is not available") NixlWrapper = None nixlXferTelemetry = None try: if not current_platform.is_rocm(): from nixl._api import nixl_agent_config else: from rixl._api import nixl_agent_config except ImportError: nixl_agent_config = None logger.warning("NIXL agent config is not available") # Supported platforms and types of kv transfer buffer. # {device: tuple of supported kv buffer types} _NIXL_SUPPORTED_DEVICE = { "cuda": ( "cuda", "cpu", ), "tpu": ("cpu",), "xpu": ("cpu",), "cpu": ("cpu",), } # support for oot platform by providing mapping in current_platform _NIXL_SUPPORTED_DEVICE.update(current_platform.get_nixl_supported_devices()) @dataclass class NixlAgentMetadata: engine_id: str agent_metadata: bytes kv_caches_base_addr: list[int] device_id: int num_blocks: int block_lens: list[int] kv_cache_layout: str block_size: int @dataclass class NixlHandshakePayload(KVConnectorHandshakeMetadata): """ Wrapper for NIXL handshake sent over the wire. Enables two-phase decoding for graceful compatibility checking: 1. Decode NixlHandshakePayload to get compatibility_hash 2. Compute local hash and compare 3. Only if hashes match, decode agent_metadata_bytes This prevents decoder errors when NixlAgentMetadata schema is incompatible, allowing graceful failure with clear error message. """ compatibility_hash: str agent_metadata_bytes: bytes # NixlAgentMetadata encoded def compute_nixl_compatibility_hash( vllm_config: VllmConfig, attn_backend_name: str ) -> str: """ Compute compatibility hash for NIXL KV transfer. Hash only the factors that affect whether two NIXL instances can successfully transfer KV cache data. Factors included: - vLLM version and NIXL connector version - Model architecture (name, dtype, KV heads, layers) - KV cache format (dtype, sliding window) - Attention backend Note: Factors like tensor_parallel_size, block_size, and kv_cache_layout are validated at runtime in _validate_remote_agent_handshake and are not included in this hash to support heterogeneous deployments. Note - the set of factors are likely to evolve significantly over time to be more or less permissive. Returns: SHA-256 hex digest """ from vllm import __version__ as vllm_version from vllm.config.utils import hash_factors model_config = vllm_config.model_config cache_config = vllm_config.cache_config factors = { # Version compatibility "vllm_version": vllm_version, "nixl_connector_version": NIXL_CONNECTOR_VERSION, # Model architecture - affects KV cache shape "model": model_config.model, "dtype": str(model_config.dtype), "num_kv_heads": model_config.get_total_num_kv_heads(), "head_size": model_config.get_head_size(), "num_hidden_layers": model_config.get_total_num_hidden_layers(), # Attention backend and KV cache dtype affect memory layout "attn_backend_name": attn_backend_name, "cache_dtype": str(cache_config.cache_dtype), } compat_hash = hash_factors(factors) logger.debug( "NIXL compatibility hash: %s (model=%s, dtype=%s, num_kv_heads=%d, " "cache_dtype=%s, attn_backend=%s)", compat_hash, factors["model"], factors["dtype"], factors["num_kv_heads"], factors["cache_dtype"], attn_backend_name, ) return compat_hash @dataclass class RemoteMeta: block_ids: list[int] host: str port: int engine_id: str request_id: str @dataclass class ReqMeta: local_block_ids: list[int] # To be used when logical block size does not match the kernel block size local_physical_block_ids: list[int] tp_size: int remote: RemoteMeta | None = None class NixlConnectorMetadata(KVConnectorMetadata): def __init__(self): self.reqs_to_recv: dict[ReqId, ReqMeta] = {} self.reqs_to_save: dict[ReqId, ReqMeta] = {} self.reqs_to_send: dict[ReqId, float] = {} self.reqs_in_batch: set[ReqId] = set() self.reqs_not_processed: set[ReqId] = set() def _add_new_req( self, local_block_ids: list[int], kv_transfer_params: dict[str, Any], ) -> ReqMeta: return ReqMeta( local_block_ids=local_block_ids, local_physical_block_ids=local_block_ids, # P workers don't need to receive tp_size from proxy here. tp_size=kv_transfer_params.get("tp_size", 1), ) def add_new_req_to_save( self, request_id: ReqId, local_block_ids: list[int], kv_transfer_params: dict[str, Any], ): self.reqs_to_save[request_id] = self._add_new_req( local_block_ids, kv_transfer_params ) def add_new_req_to_recv( self, request_id: ReqId, local_block_ids: list[int], kv_transfer_params: dict[str, Any], ): req = self._add_new_req(local_block_ids, kv_transfer_params) req.remote = RemoteMeta( block_ids=kv_transfer_params["remote_block_ids"], engine_id=kv_transfer_params["remote_engine_id"], request_id=kv_transfer_params["remote_request_id"], host=kv_transfer_params["remote_host"], port=kv_transfer_params["remote_port"], ) self.reqs_to_recv[request_id] = req class NixlConnector(KVConnectorBase_V1): def __init__( self, vllm_config: VllmConfig, role: KVConnectorRole, kv_cache_config: Optional["KVCacheConfig"] = None, ): super().__init__(vllm_config, role, kv_cache_config) assert vllm_config.kv_transfer_config is not None assert vllm_config.kv_transfer_config.engine_id is not None self.engine_id: EngineId = vllm_config.kv_transfer_config.engine_id if role == KVConnectorRole.SCHEDULER: self.connector_scheduler: NixlConnectorScheduler | None = ( NixlConnectorScheduler(vllm_config, self.engine_id) ) self.connector_worker: NixlConnectorWorker | None = None elif role == KVConnectorRole.WORKER: self.connector_scheduler = None self.connector_worker = NixlConnectorWorker(vllm_config, self.engine_id) ############################################################ # Class Methods ############################################################ @classmethod def get_required_kvcache_layout(cls, vllm_config: VllmConfig): if vllm_config.model_config is None: logger.warning_once( "Unable to detect current VLLM config. " "Fallback to default kv cache layout." ) return None use_mla = vllm_config.model_config.use_mla if use_mla: # return None when we have mla # as the layout should not matter in that case, # which fallback to the default behavior. return None logger.info_once( "NixlConnector setting KV cache layout to HND for better xfer performance." ) return "HND" ############################################################ # Scheduler Side Methods ############################################################ def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int ) -> tuple[int | None, bool]: assert self.connector_scheduler is not None return self.connector_scheduler.get_num_new_matched_tokens( request, num_computed_tokens ) def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): assert self.connector_scheduler is not None return self.connector_scheduler.update_state_after_alloc( request, blocks, num_external_tokens ) def build_connector_meta( self, scheduler_output: SchedulerOutput, ) -> KVConnectorMetadata: assert self.connector_scheduler is not None return self.connector_scheduler.build_connector_meta(scheduler_output) def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: assert self.connector_scheduler is not None return self.connector_scheduler.request_finished(request, block_ids) def set_xfer_handshake_metadata( self, metadata: dict[int, KVConnectorHandshakeMetadata] ) -> None: """ Set the KV connector handshake metadata for this connector. Args: metadata (dict): the handshake metadata to set. """ assert self.connector_scheduler is not None self.connector_scheduler.set_xfer_handshake_metadata(metadata) ############################################################ # Worker Side Methods ############################################################ def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): assert self.connector_worker is not None self.connector_worker.register_kv_caches(kv_caches) def set_host_xfer_buffer_ops(self, copy_operation: CopyBlocksOp): assert self.connector_worker is not None self.connector_worker.set_host_xfer_buffer_ops(copy_operation) def get_finished(self, finished_req_ids: set[str]) -> tuple[set[str], set[str]]: """Get the finished recving and sending requests.""" assert self.connector_worker is not None return self.connector_worker.get_finished() def get_block_ids_with_load_errors(self) -> set[int]: """Get block IDs that failed to load via NIXL.""" assert self.connector_worker is not None return self.connector_worker.get_block_ids_with_load_errors() def get_kv_connector_stats(self) -> KVConnectorStats | None: if self.connector_worker is None: return None return self.connector_worker.get_kv_connector_stats() @classmethod def build_kv_connector_stats( cls, data: dict[str, Any] | None = None ) -> KVConnectorStats | None: return ( NixlKVConnectorStats(data=data) if data is not None else NixlKVConnectorStats() ) @classmethod def build_prom_metrics( cls, vllm_config: VllmConfig, metric_types: dict[type[PromMetric], type[PromMetricT]], labelnames: list[str], per_engine_labelvalues: dict[int, list[object]], ) -> KVConnectorPromMetrics: return NixlPromMetrics( vllm_config, metric_types, labelnames, per_engine_labelvalues ) def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None: assert self.connector_worker is not None assert isinstance(self._connector_metadata, NixlConnectorMetadata) self.connector_worker.start_load_kv(self._connector_metadata) def wait_for_layer_load(self, layer_name: str) -> None: """NixlConnector does not do layerwise saving.""" pass def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: AttentionMetadata, **kwargs, ) -> None: """NixlConnector does not save explicitly.""" pass def wait_for_save(self): assert self.connector_worker is not None assert isinstance(self._connector_metadata, NixlConnectorMetadata) if self.connector_worker.use_host_buffer and self.connector_worker.copy_blocks: self.connector_worker.save_kv_to_host(self._connector_metadata) def shutdown(self): if self.connector_worker is not None: self.connector_worker.shutdown() if self.connector_scheduler is not None: self.connector_scheduler.shutdown() def get_handshake_metadata(self) -> KVConnectorHandshakeMetadata | None: """ Get the KVConnector handshake metadata for this connector. This metadata is used for out-of-band connector handshake between P/D workers. Returns: KVConnectorHandshakeMetadata: the handshake metadata. None if no handshake metadata is available. """ assert self.connector_worker is not None return self.connector_worker.xfer_handshake_metadata class NixlConnectorScheduler: """Implementation of Scheduler side methods""" def __init__(self, vllm_config: VllmConfig, engine_id: str): self.vllm_config = vllm_config self.block_size = vllm_config.cache_config.block_size self.engine_id: EngineId = engine_id self.side_channel_host = envs.VLLM_NIXL_SIDE_CHANNEL_HOST self.side_channel_port = ( envs.VLLM_NIXL_SIDE_CHANNEL_PORT + vllm_config.parallel_config.data_parallel_index ) assert vllm_config.kv_transfer_config is not None if current_platform.device_type == "cpu": self.use_host_buffer = False else: self.use_host_buffer = ( vllm_config.kv_transfer_config.kv_buffer_device == "cpu" ) logger.info("Initializing NIXL Scheduler %s", engine_id) # Background thread for handling new handshake requests. self._nixl_handshake_listener_t: threading.Thread | None = None self._encoded_xfer_handshake_metadata: dict[int, Any] = {} self._stop_event = threading.Event() # Requests that need to start recv/send. # New requests are added by update_state_after_alloc in # the scheduler. Used to make metadata passed to Worker. self._reqs_need_recv: dict[ReqId, tuple[Request, list[int]]] = {} self._reqs_need_save: dict[ReqId, Request] = {} # Reqs to send and their expiration time self._reqs_need_send: dict[ReqId, float] = {} self._reqs_in_batch: set[ReqId] = set() # Reqs to remove from processed set because they're not to send after # remote prefill or aborted. self._reqs_not_processed: set[ReqId] = set() def shutdown(self): self._stop_event.set() if self._nixl_handshake_listener_t is not None: self._nixl_handshake_listener_t.join() self._nixl_handshake_listener_t = None def set_xfer_handshake_metadata( self, metadata: dict[int, KVConnectorHandshakeMetadata] ) -> None: """ Set the KV connector handshake metadata for this connector. Args: metadata (dict): the handshake metadata to set. """ encoded_data: dict[int, bytes] = {} encoder = msgspec.msgpack.Encoder() for tp_rank, rank_metadata in metadata.items(): if not isinstance(rank_metadata, NixlHandshakePayload): raise ValueError( "NixlConnectorScheduler expects NixlHandshakePayload for " "handshake metadata." ) encoded_data[tp_rank] = encoder.encode(rank_metadata) logger.debug( "Tp rank %d: encoded NixlHandshakePayload size: %s bytes", tp_rank, str(len(encoded_data[tp_rank])), ) self._encoded_xfer_handshake_metadata = encoded_data # Only start the listener when we have metadata to serve. if self._nixl_handshake_listener_t is None: ready_event = threading.Event() self._nixl_handshake_listener_t = threading.Thread( target=self._nixl_handshake_listener, args=( encoded_data, ready_event, self._stop_event, self.side_channel_port, ), daemon=True, name="nixl_handshake_listener", ) self._nixl_handshake_listener_t.start() ready_event.wait() # Wait for listener ZMQ socket to be ready. @staticmethod def _nixl_handshake_listener( encoded_data: dict[int, Any], ready_event: threading.Event, stop_event: threading.Event, port: int, ): """Background thread for getting new NIXL handshakes.""" # NOTE(rob): this is a simple implementation. We will move # to a better approach via HTTP endpoint soon. # Listen for new requests for metadata. host = envs.VLLM_NIXL_SIDE_CHANNEL_HOST path = make_zmq_path("tcp", host, port) logger.debug("Starting listening on path: %s", path) with zmq_ctx(zmq.ROUTER, path) as sock: sock.setsockopt(zmq.RCVTIMEO, 1000) ready_event.set() while True: try: identity, _, msg = sock.recv_multipart() except zmq.Again: if stop_event.is_set(): break continue # Decode the message which contains (GET_META_MSG, rank) msg, target_tp_rank = msgspec.msgpack.decode(msg) logger.debug( "Received message for tp rank %s", target_tp_rank, ) if msg != GET_META_MSG: logger.warning("Connection listener got unexpected message %s", msg) sock.send_multipart((identity, b"", encoded_data[target_tp_rank])) def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int ) -> tuple[int, bool]: """ For remote prefill, pull all prompt blocks from remote asynchronously relative to engine execution. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: * the number of tokens that can be loaded from the external KV cache beyond what is already computed. * true if the external KV cache tokens will be loaded asynchronously (between scheduler steps). """ params = request.kv_transfer_params logger.debug( "NIXLConnector get_num_new_matched_tokens: " "num_computed_tokens=%s, kv_transfer_params=%s", num_computed_tokens, params, ) if params is not None and params.get("do_remote_prefill"): # Remote prefill: get all prompt blocks from remote. token_ids = request.prompt_token_ids or [] count = len(token_ids) - num_computed_tokens if count > 0: return count, True # No remote prefill for this request. return 0, False def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): params = request.kv_transfer_params logger.debug( "NIXLConnector update_state_after_alloc: " "num_external_tokens=%s, kv_transfer_params=%s", num_external_tokens, params, ) if not params: return if params.get("do_remote_decode"): self._reqs_in_batch.add(request.request_id) if self.use_host_buffer and params.get("do_remote_decode"): # NOTE: when accelerator is not directly supported by Nixl, # prefilled blocks need to be saved to host memory before transfer. self._reqs_need_save[request.request_id] = request elif params.get("do_remote_prefill"): if params.get("remote_block_ids"): if all( p in params for p in ( "remote_engine_id", "remote_request_id", "remote_host", "remote_port", ) ): # If remote_blocks and num_external_tokens = 0, we have # a full prefix cache hit on the D worker. We need to call # send_notif in _read_blocks to free the memory on the P. local_block_ids = ( blocks.get_unhashed_block_ids() if num_external_tokens > 0 else [] ) # Get unhashed blocks to pull from remote. self._reqs_need_recv[request.request_id] = ( request, local_block_ids, ) else: logger.warning( "Got invalid KVTransferParams: %s. This " "request will not utilize KVTransfer", params, ) else: assert num_external_tokens == 0 # Only trigger 1 KV transfer per request. params["do_remote_prefill"] = False def build_connector_meta( self, scheduler_output: SchedulerOutput, ) -> KVConnectorMetadata: meta = NixlConnectorMetadata() # Loop through scheduled reqs and convert to ReqMeta. for req_id, (req, block_ids) in self._reqs_need_recv.items(): assert req.kv_transfer_params is not None meta.add_new_req_to_recv( request_id=req_id, local_block_ids=block_ids, kv_transfer_params=req.kv_transfer_params, ) # NOTE: For the prefill side, there might be a chance that an early added # request is a chunked prefill, so we need to check if new blocks are added for req_id, new_block_id_groups, _ in yield_req_data(scheduler_output): req_to_save = self._reqs_need_save.get(req_id) if req_to_save is None or new_block_id_groups is None: continue req = req_to_save assert req.kv_transfer_params is not None meta.add_new_req_to_save( request_id=req_id, local_block_ids=new_block_id_groups[0], kv_transfer_params=req.kv_transfer_params, ) assert scheduler_output.num_scheduled_tokens is not None num_scheduled_tokens = scheduler_output.num_scheduled_tokens[req_id] is_partial = ( req.num_computed_tokens + num_scheduled_tokens ) < req.num_prompt_tokens if not is_partial: # For non-partial prefills, once new req_meta is scheduled, it # can be removed from _reqs_need_save. # For partial prefill case, we will retain the request in # _reqs_need_save until all blocks are scheduled with req_meta. # Therefore, only pop if `not is_partial`. self._reqs_need_save.pop(req_id) meta.reqs_to_send = self._reqs_need_send meta.reqs_in_batch = self._reqs_in_batch meta.reqs_not_processed = self._reqs_not_processed # Clear the list once workers start the transfers self._reqs_need_recv.clear() self._reqs_in_batch = set() self._reqs_not_processed = set() self._reqs_need_send = {} return meta def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: """ Once a request is finished, determine whether request blocks should be freed now or will be sent asynchronously and freed later. """ from vllm.v1.request import RequestStatus params = request.kv_transfer_params logger.debug( "NIXLConnector request_finished(%s), request_status=%s, " "kv_transfer_params=%s", request.request_id, request.status, params, ) if not params: return False, None if params.get("do_remote_prefill"): # If do_remote_prefill is still True when the request is finished, # update_state_after_alloc must not have been called (the request # must have been aborted before it was scheduled). # To avoid stranding the prefill blocks in the prefill instance, # we must add empty block_ids to _reqs_need_recv so that our # worker side will notify and free blocks in the prefill instance. self._reqs_need_recv[request.request_id] = (request, []) params["do_remote_prefill"] = False return False, None if not params.get("do_remote_decode"): return False, None if request.status != RequestStatus.FINISHED_LENGTH_CAPPED: # Also include the case of a P/D Prefill request with immediate # block free (eg abort). Stop tracking this request. self._reqs_not_processed.add(request.request_id) # Clear _reqs_need_save if a request is aborted as partial prefill. self._reqs_need_save.pop(request.request_id, None) return False, None # TODO: check whether block_ids actually ever be 0. If not we could # remove the conditional below delay_free_blocks = len(block_ids) > 0 if delay_free_blocks: # Prefill request on remote. It will be read from D upon completion logger.debug( "NIXLConnector request_finished(%s) waiting for %d seconds " "for remote decode to fetch blocks", request.request_id, envs.VLLM_NIXL_ABORT_REQUEST_TIMEOUT, ) self._reqs_need_send[request.request_id] = ( time.perf_counter() + envs.VLLM_NIXL_ABORT_REQUEST_TIMEOUT ) return delay_free_blocks, dict( do_remote_prefill=True, do_remote_decode=False, remote_block_ids=block_ids, remote_engine_id=self.engine_id, remote_request_id=request.request_id, remote_host=self.side_channel_host, remote_port=self.side_channel_port, tp_size=self.vllm_config.parallel_config.tensor_parallel_size, ) class NixlConnectorWorker: """Implementation of Worker side methods""" def __init__(self, vllm_config: VllmConfig, engine_id: str): if NixlWrapper is None: logger.error("NIXL is not available") raise RuntimeError("NIXL is not available") logger.info("Initializing NIXL wrapper") logger.info("Initializing NIXL worker %s", engine_id) # Config. self.vllm_config = vllm_config self.block_size = vllm_config.cache_config.block_size if vllm_config.kv_transfer_config is None: raise ValueError("kv_transfer_config must be set for NixlConnector") self.kv_transfer_config = vllm_config.kv_transfer_config self.nixl_backends = vllm_config.kv_transfer_config.get_from_extra_config( "backends", ["UCX"] ) # Agent. non_ucx_backends = [b for b in self.nixl_backends if b != "UCX"] # Configure NIXL num_threads to avoid UAR exhaustion on Mellanox NICs. # Each UCX thread allocates UARs (doorbell pages) via DevX, and # excessive NIXL UAR usage can exhaust NIC UAR space. This can cause # components like NVSHMEM (used by DeepEP kernels) to fail during RDMA # initialization with "mlx5dv_devx_alloc_uar" errors. # Ref: https://network.nvidia.com/files/doc-2020/ethernet-adapters-programming-manual.pdf#page=63 num_threads = vllm_config.kv_transfer_config.get_from_extra_config( "num_threads", 4 ) if nixl_agent_config is None: config = None else: # Enable telemetry by default for NIXL 0.7.1 and above. config = ( nixl_agent_config(backends=self.nixl_backends, capture_telemetry=True) if len(non_ucx_backends) > 0 else nixl_agent_config(num_threads=num_threads, capture_telemetry=True) ) self.nixl_wrapper = NixlWrapper(str(uuid.uuid4()), config) # Map of engine_id -> {rank0: agent_name0, rank1: agent_name1..}. self._remote_agents: dict[EngineId, dict[int, str]] = defaultdict(dict) # Metadata. self.engine_id: EngineId = engine_id self.tp_rank = get_tensor_model_parallel_rank() self.world_size = get_tensor_model_parallel_world_size() self.tp_group = get_tp_group() self.num_blocks = 0 self.enable_permute_local_kv = False # KV Caches and nixl tracking data. self.device_type = current_platform.device_type self.kv_buffer_device: str = vllm_config.kv_transfer_config.kv_buffer_device if self.device_type not in _NIXL_SUPPORTED_DEVICE: raise RuntimeError(f"{self.device_type} is not supported.") elif self.kv_buffer_device not in _NIXL_SUPPORTED_DEVICE[self.device_type]: raise RuntimeError( f"{self.device_type} with {self.kv_buffer_device} kv_buffer " "is not supported." ) self.device_kv_caches: dict[str, torch.Tensor] = {} # cpu kv buffer for xfer # used when device memory can not be registered under nixl self.host_xfer_buffers: dict[str, torch.Tensor] = {} if self.device_type == "cpu": self.use_host_buffer = False else: self.use_host_buffer = self.kv_buffer_device == "cpu"
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/__init__.py
vllm/distributed/kv_transfer/kv_connector/v1/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.distributed.kv_transfer.kv_connector.v1.base import ( KVConnectorBase_V1, KVConnectorRole, SupportsHMA, supports_hma, ) from vllm.distributed.kv_transfer.kv_connector.v1.decode_bench_connector import ( # noqa E:501 DecodeBenchConnector, ) __all__ = [ "KVConnectorRole", "KVConnectorBase_V1", "supports_hma", "SupportsHMA", "DecodeBenchConnector", ]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/base.py
vllm/distributed/kv_transfer/kv_connector/v1/base.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ KVConnectorBase_V1 Class for Distributed KV Cache & Hidden State communication in vLLM v1 The class provides the following primitives: Scheduler-side: runs in the scheduler, binds metadata, which is used by the worker-side to load/save KV cache. get_num_new_matched_tokens() - get number of new tokens that exist in the remote KV cache. Might be called multiple times for a given request and should be side-effect free. update_state_after_alloc() - update KVConnector state after temporary buffer alloc by the CacheManager. update_connector_output() - update KVConnector state after output is received from worker-side connectors. request_finished() - called once when a request is finished, with the computed kv cache blocks for the request. Returns whether KV cache should be freed now or if the connector now assumes responsibility for freeing the the blocks asynchronously. Also optionally returns KV transfer params. take_events() - returns new KV events that were collected by the connector since the last call. Worker-side: runs in each worker, loads/saves KV cache to/from the Connector based on the metadata. start_load_kv() - starts loading all KVs (maybe async) wait_for_layer_load() - blocks until layer i load is done save_kv_layer() - starts saving KV for layer i (maybe async) wait_for_save() - blocks until all saves are done get_finished() - called with ids of finished requests, returns ids of requests that have completed async sending/recving. """ import enum from abc import ABC, abstractmethod from collections.abc import Callable, Iterable from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional import torch from vllm.attention.backends.abstract import AttentionBackend, AttentionMetadata from vllm.logger import init_logger from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.outputs import KVConnectorOutput if TYPE_CHECKING: from vllm.config import VllmConfig from vllm.distributed.kv_events import KVCacheEvent, KVConnectorKVEvents from vllm.distributed.kv_transfer.kv_connector.v1.metrics import ( KVConnectorPromMetrics, KVConnectorStats, PromMetric, PromMetricT, ) from vllm.forward_context import ForwardContext from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request # s_tensor_list, d_tensor_list, s_indices, d_indices, direction CopyBlocksOp = Callable[ [ dict[str, torch.Tensor], dict[str, torch.Tensor], list[int], list[int], Literal["h2d", "d2h"], ], None, ] logger = init_logger(__name__) class SupportsHMA(ABC): """ The class that indicates the corresponding connector supports hybrid memory allocator (HMA). This is required to use the connector together with hybrid memory allocator. """ @abstractmethod def request_finished_all_groups( self, request: "Request", block_ids: tuple[list[int], ...], ) -> tuple[bool, dict[str, Any] | None]: """ Called exactly once when a request has finished for all kv cache groups, before its blocks are freed for each group. NOTE(Kuntai): This function is only supported by connectors that support HMA. The connector may assumes responsibility for freeing the blocks asynchronously by returning True. Returns: True if the request is being saved/sent asynchronously and blocks should not be freed until the request_id is returned from get_finished(). Optional KVTransferParams to be included in the request outputs returned by the engine. """ raise NotImplementedError def supports_hma(connector: Any) -> bool: if isinstance(connector, type): return issubclass(connector, SupportsHMA) else: return isinstance(connector, SupportsHMA) class KVConnectorRole(enum.Enum): # Connector running in the scheduler process SCHEDULER = 0 # Connector running in the worker process WORKER = 1 class KVConnectorHandshakeMetadata(ABC): # noqa: B024 """ Metadata used for out of band connector handshake between P/D workers. This needs to serializeable. """ pass class KVConnectorMetadata(ABC): # noqa: B024 """ Abstract Metadata used to communicate between the Scheduler KVConnector and Worker KVConnector. """ pass class KVConnectorBase_V1(ABC): """ Base class for KV connectors. Attributes: prefer_cross_layer_blocks (bool): Indicates whether this connector prefers KV blocks that hold KV data for all layers (for speeding up KV data transfers). Defaults to False. """ prefer_cross_layer_blocks: ClassVar[bool] = False def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, kv_cache_config: Optional["KVCacheConfig"] = None, ): logger.warning( "Initializing KVConnectorBase_V1. This API is experimental and " "subject to change in the future as we iterate the design." ) self._connector_metadata: KVConnectorMetadata | None = None self._vllm_config = vllm_config if vllm_config.kv_transfer_config is not None: self._kv_transfer_config = vllm_config.kv_transfer_config else: raise ValueError("kv_transfer_config must be set for KVConnectorBase_V1") self._kv_cache_config = kv_cache_config if self._kv_cache_config is None: logger.warning( "KVConnectorBase_V1 initialized without kv_cache_config. " "This is deprecated - please update your connector to accept " "kv_cache_config as the third constructor argument and pass it " "to super().__init__()." ) self._role = role @property def role(self) -> KVConnectorRole: return self._role # ============================== # Worker-side methods # ============================== def bind_connector_metadata(self, connector_metadata: KVConnectorMetadata) -> None: """Set the connector metadata from the scheduler. This function should be called by the model runner every time before the model execution. The metadata will be used for runtime KV cache loading and saving. Args: connector_metadata (dict): the connector metadata. """ self._connector_metadata = connector_metadata def clear_connector_metadata(self) -> None: """Clear the connector metadata. This function should be called by the model runner every time after the model execution. """ self._connector_metadata = None def _get_connector_metadata(self) -> KVConnectorMetadata: """Get the connector metadata. This function should only be called inside the connector. Returns: ConnectorMetadata: the connector metadata. """ # Should only be called while set to valid metadata. assert self._connector_metadata is not None return self._connector_metadata def has_connector_metadata(self) -> bool: """Check whether the connector metadata is currently set. Returns: bool: True if connector metadata exists, False otherwise. """ return self._connector_metadata is not None def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): """ Initialize with the KV caches. Useful for pre-registering the KV Caches in the KVConnector (e.g. for NIXL). Args: kv_caches: dictionary of layer names, kv cache """ return def register_cross_layers_kv_cache( self, kv_cache: torch.Tensor, attn_backend: type["AttentionBackend"] ): """ Initialize with a single KV cache tensor used by all layers. The first dimension should be num_layers. This function will only be called for models with uniform layers, and only if the prefers_cross_layer_blocks is set to True. Only one of the functions {register_kv_caches, register_cross_layers_kv_cache} will be called. Args: kv_cache: a cross-layers kv cache tensor attn_backend: The attention backend that corresponds to all layers """ return def set_host_xfer_buffer_ops(self, copy_operation: CopyBlocksOp): """ Set the xPU-specific ops for copying KV between host and device. Needed when host buffer is used for kv transfer (e.g., in NixlConnector) """ return @abstractmethod def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None: """ Start loading the KV cache from the connector to vLLM's paged KV buffer. This is called from the forward context before the forward pass to enable async loading during model execution. Args: forward_context (ForwardContext): the forward context. **kwargs: additional arguments for the load operation Note: The number of elements in kv_caches and layer_names should be the same. """ pass @abstractmethod def wait_for_layer_load(self, layer_name: str) -> None: """ Block until the KV for a specific layer is loaded into vLLM's paged buffer. This is called from within attention layer to ensure async copying from start_load_kv is complete. This interface will be useful for layer-by-layer pipelining. Args: layer_name: the name of that layer """ pass @abstractmethod def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: "AttentionMetadata", **kwargs: Any, ) -> None: """ Start saving a layer of KV cache from vLLM's paged buffer to the connector. This is called from within attention layer to enable async copying during execution. Args: layer_name (str): the name of the layer. kv_layer (torch.Tensor): the paged KV buffer of the current layer in vLLM. attn_metadata (AttentionMetadata): the attention metadata. **kwargs: additional arguments for the save operation. """ pass @abstractmethod def wait_for_save(self): """ Block until all the save operations is done. This is called as the forward context exits to ensure that the async saving from save_kv_layer is complete before finishing the forward. This prevents overwrites of paged KV buffer before saving done. """ pass def get_finished( self, finished_req_ids: set[str] ) -> tuple[set[str] | None, set[str] | None]: """ Notifies worker-side connector ids of requests that have finished generating tokens on the worker. The scheduler process (via the Executors) will use this output to track which workers are done. Returns: ids of requests that have finished asynchronous transfer (requests that previously returned True from request_finished()), tuple of (sending/saving ids, recving/loading ids). The finished saves/sends req ids must belong to a set provided in a call to this method (this call or a prior one). """ return None, None def get_block_ids_with_load_errors(self) -> set[int]: """ Get the set of block IDs that failed to load. Returns: Set of block IDs that encountered load errors. Empty set if no load errors occurred. Notes: - Applies to both sync- and async-loading requests. - Async loading: failed blocks may be reported in any forward pass up to and including the pass where the request ID is returned by `get_finished()`. Even if failures occur, the request must still be reported via `get_finished()`, and the failed block IDs must appear here no later than that same pass. - Sync loading: failed blocks should be reported in the forward pass in which they are detected. """ return set() def shutdown(self): """ Shutdown the connector. This is called when the worker process is shutting down to ensure that all the async operations are completed and the connector is cleaned up properly. """ return None def get_kv_connector_stats(self) -> Optional["KVConnectorStats"]: """ Get the KV connector stats collected during the last interval. """ return None def get_kv_connector_kv_cache_events(self) -> Optional["KVConnectorKVEvents"]: """ Get the KV connector kv cache events collected during the last interval. This function should be called by the model runner every time after the model execution and before cleanup. """ return None def get_handshake_metadata(self) -> KVConnectorHandshakeMetadata | None: """ Get the KVConnector handshake metadata for this connector. This metadata is used for out-of-band connector handshake between P/D workers. Returns: KVConnectorHandshakeMetadata: the handshake metadata. None if no handshake metadata is available. """ return None # ============================== # Scheduler-side methods # ============================== @abstractmethod def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int | None, bool]: """ Get number of new tokens that can be loaded from the external KV cache beyond the num_computed_tokens. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: A tuple with the following elements: - An optional number of tokens that can be loaded from the external KV cache beyond what is already computed. If None, it means that the connector needs more time to determine the number of matched tokens, and the scheduler should query for this request again later. - `True` if external KV cache tokens will be loaded asynchronously (between scheduler steps). Must be 'False' if the first element is 0. Notes: The connector should only consider the largest prefix of prompt- tokens for which KV cache is actually available at the time of the call. If the cache cannot be loaded for some tokens (e.g., due to connectivity issues or eviction), those tokens must not be taken into account. """ pass @abstractmethod def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): """ Update KVConnector state after block allocation. If get_num_new_matched_tokens previously returned True for a request, this function may be called twice for that same request - first when blocks are allocated for the connector tokens to be asynchronously loaded into, and second when any additional blocks are allocated, after the load/transfer is complete. Args: request (Request): the request object. blocks (KVCacheBlocks): the blocks allocated for the request. num_external_tokens (int): the number of tokens that will be loaded from the external KV cache. """ pass @abstractmethod def build_connector_meta( self, scheduler_output: SchedulerOutput ) -> KVConnectorMetadata: """ Build the connector metadata for this step. This function should NOT modify fields in the scheduler_output. Also, calling this function will reset the state of the connector. Args: scheduler_output (SchedulerOutput): the scheduler output object. """ pass def update_connector_output(self, connector_output: KVConnectorOutput): """ Update KVConnector state from worker-side connectors output. Args: connector_output (KVConnectorOutput): the worker-side connectors output. """ return def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: """ Called exactly once when a request has finished, before its blocks are freed. The connector may assumes responsibility for freeing the blocks asynchronously by returning True. Returns: True if the request is being saved/sent asynchronously and blocks should not be freed until the request_id is returned from get_finished(). Optional KVTransferParams to be included in the request outputs returned by the engine. """ return False, None def take_events(self) -> Iterable["KVCacheEvent"]: """ Take the KV cache events from the connector. Yields: New KV cache events since the last call. """ return () @classmethod def get_required_kvcache_layout(cls, vllm_config: "VllmConfig") -> str | None: """ Get the required KV cache layout for this connector. Args: vllm_config (VllmConfig): the vllm config. Returns: str: the required KV cache layout. e.g. HND, or NHD. None if the connector does not require a specific layout. """ if cls is KVConnectorBase_V1: raise TypeError( "get_required_kvcache_layout should not be called " "on the abstract base class" ) return None def get_finished_count(self) -> int | None: """ Get the count of requests expected to complete send/receive operations via this connector. This method is used to initialize the KVOutputAggregator, overwriting the default world_size. Returns: int: expected sending or receiving completion count. """ return None @classmethod def build_kv_connector_stats( cls, data: dict[str, Any] | None = None ) -> Optional["KVConnectorStats"]: """ KVConnectorStats resolution method. This method allows dynamically registered connectors to return their own KVConnectorStats object, which can implement custom aggregation logic on the data dict. """ return None def set_xfer_handshake_metadata( self, metadata: dict[int, KVConnectorHandshakeMetadata] ) -> None: """ Set the KV connector handshake metadata for this connector. Args: metadata (KVConnectorHandshakeMetadata): the handshake metadata to set. """ return None @classmethod def build_prom_metrics( cls, vllm_config: "VllmConfig", metric_types: dict[type["PromMetric"], type["PromMetricT"]], labelnames: list[str], per_engine_labelvalues: dict[int, list[object]], ) -> Optional["KVConnectorPromMetrics"]: """ Create a KVConnectorPromMetrics subclass which should register per-connector Prometheus metrics and implement observe() to expose connector transfer stats via Prometheus. """ return None def reset_cache(self) -> bool | None: """ Reset the connector's internal cache. Returns: bool: True if the cache was successfully reset, False otherwise. """ logger.debug( "Connector cache reset requested, but %s does not implement reset_cache().", type(self).__name__, ) return None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/offloading_connector.py
vllm/distributed/kv_transfer/kv_connector/v1/offloading_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections import defaultdict from collections.abc import Iterable from dataclasses import dataclass from itertools import islice from typing import Any, ClassVar import torch from vllm.attention.backends.abstract import AttentionBackend, AttentionMetadata from vllm.attention.layer import Attention from vllm.config import VllmConfig, get_layers_from_vllm_config from vllm.distributed.kv_events import BlockRemoved, BlockStored, KVCacheEvent from vllm.distributed.kv_transfer.kv_connector.utils import yield_req_data from vllm.distributed.kv_transfer.kv_connector.v1 import ( KVConnectorBase_V1, KVConnectorRole, ) from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorMetadata from vllm.forward_context import ForwardContext from vllm.logger import init_logger from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.core.kv_cache_utils import BlockHash from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.kv_offload.abstract import OffloadingManager from vllm.v1.kv_offload.factory import OffloadingSpecFactory from vllm.v1.kv_offload.mediums import GPULoadStoreSpec from vllm.v1.kv_offload.spec import OffloadingSpec from vllm.v1.kv_offload.worker.worker import OffloadingWorker, TransferSpec from vllm.v1.outputs import KVConnectorOutput from vllm.v1.request import Request ReqId = str logger = init_logger(__name__) @dataclass class OffloadingConnectorMetadata(KVConnectorMetadata): reqs_to_load: dict[ReqId, TransferSpec] reqs_to_store: dict[ReqId, TransferSpec] class OffloadingConnector(KVConnectorBase_V1): prefer_cross_layer_blocks: ClassVar[bool] = True def __init__( self, vllm_config: VllmConfig, role: KVConnectorRole, kv_cache_config: KVCacheConfig | None = None, ): super().__init__(vllm_config, role, kv_cache_config) spec = OffloadingSpecFactory.create_spec(vllm_config) self.connector_scheduler: OffloadingConnectorScheduler | None = None self.connector_worker: OffloadingConnectorWorker | None = None if role == KVConnectorRole.SCHEDULER: self.connector_scheduler = OffloadingConnectorScheduler(spec) elif role == KVConnectorRole.WORKER: self.connector_worker = OffloadingConnectorWorker(spec) def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): assert self.connector_worker is not None self.connector_worker.register_kv_caches(kv_caches) def register_cross_layers_kv_cache( self, kv_cache: torch.Tensor, attn_backend: type[AttentionBackend] ): assert self.connector_worker is not None self.connector_worker.register_cross_layers_kv_cache(kv_cache, attn_backend) def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None: assert self.connector_worker is not None assert isinstance(self._connector_metadata, OffloadingConnectorMetadata) self.connector_worker.start_load_kv(self._connector_metadata) def wait_for_layer_load(self, layer_name: str) -> None: pass def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: "AttentionMetadata", **kwargs, ) -> None: pass def wait_for_save(self): assert self.connector_worker is not None assert isinstance(self._connector_metadata, OffloadingConnectorMetadata) self.connector_worker.start_store_kv(self._connector_metadata) def get_finished(self, finished_req_ids: set[str]) -> tuple[set[str], set[str]]: assert self.connector_worker is not None return self.connector_worker.get_finished(finished_req_ids) def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int ) -> tuple[int, bool]: assert self.connector_scheduler is not None return self.connector_scheduler.get_num_new_matched_tokens( request, num_computed_tokens ) def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): assert self.connector_scheduler is not None return self.connector_scheduler.update_state_after_alloc( request, blocks, num_external_tokens ) def build_connector_meta( self, scheduler_output: SchedulerOutput ) -> KVConnectorMetadata: assert self.connector_scheduler is not None return self.connector_scheduler.build_connector_meta(scheduler_output) def update_connector_output(self, connector_output: KVConnectorOutput): assert self.connector_scheduler is not None self.connector_scheduler.update_connector_output(connector_output) def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: assert self.connector_scheduler is not None return self.connector_scheduler.request_finished(request, block_ids) def take_events(self) -> Iterable[KVCacheEvent]: assert self.connector_scheduler is not None return self.connector_scheduler.take_events() class OffloadingConnectorScheduler: """Implementation of Scheduler side methods""" def __init__(self, spec: OffloadingSpec): self.gpu_block_size = spec.gpu_block_size self.offloaded_block_size = spec.offloaded_block_size self.block_size_factor = self.offloaded_block_size // self.gpu_block_size self.manager: OffloadingManager = spec.get_manager() self._requests: dict[ReqId, Request] = {} # list of GPU block IDs per request self._request_block_ids: dict[ReqId, list[int]] = {} # requests to load for the current scheduler step self._reqs_to_load: dict[ReqId, TransferSpec] = {} # request blocks are stored in order # index of next block (of size offloaded_block_size) to offload self._next_stored_block_idx: dict[ReqId, int] = {} # request ID -> set(block hashes being stored/load) self._reqs_being_stored = defaultdict[ReqId, set[BlockHash]](set) self._reqs_being_loaded = defaultdict[ReqId, set[BlockHash]](set) def _get_block_hashes( self, req: Request, start_idx: int = 0, end_idx: int | None = None, ) -> Iterable[BlockHash]: return islice( req.block_hashes, self.block_size_factor * start_idx + self.block_size_factor - 1, self.block_size_factor * end_idx if end_idx else None, self.block_size_factor, ) def get_num_new_matched_tokens( self, request: Request, num_computed_tokens: int ) -> tuple[int, bool]: """ Get number of new tokens that can be loaded beyond the num_computed_tokens. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: A tuple with the following elements: - The number of tokens that can be loaded beyond what is already computed. - `True` if tokens will be loaded asynchronously (between scheduler steps). """ num_blocks = request.num_tokens // self.offloaded_block_size assert len(request.block_hashes) // self.block_size_factor == num_blocks block_hashes = self._get_block_hashes(request) self.manager.touch(block_hashes) full_block_tokens = self.offloaded_block_size * num_blocks if full_block_tokens - num_computed_tokens < self.offloaded_block_size: # we can load less than a block, skip return 0, False start_block_idx = num_computed_tokens // self.offloaded_block_size hits = self.manager.lookup( self._get_block_hashes(request, start_idx=start_block_idx) ) if hits == 0: return 0, False num_hit_tokens = ( self.offloaded_block_size * (start_block_idx + hits) - num_computed_tokens ) logger.debug( "Request %s hit %s offloaded tokens after %s GPU hit tokens", request.request_id, num_hit_tokens, num_computed_tokens, ) if num_hit_tokens < self.offloaded_block_size: return 0, False return num_hit_tokens, True def update_state_after_alloc( self, request: Request, blocks: KVCacheBlocks, num_external_tokens: int ): self._requests[request.request_id] = request # the block ids are updated in _get_reqs_to_store self._request_block_ids[request.request_id] = [] if num_external_tokens == 0: return block_groups = blocks.get_block_ids() block_ids = block_groups[0] num_computed_gpu_blocks = sum( block.block_hash is not None for block in blocks.blocks[0] ) num_computed_tokens = num_computed_gpu_blocks * self.gpu_block_size full_block_tokens = num_computed_tokens + num_external_tokens assert full_block_tokens % self.offloaded_block_size == 0 num_pending_gpu_blocks = len(block_ids) - num_computed_gpu_blocks assert num_external_tokens == num_pending_gpu_blocks * self.gpu_block_size start_block_idx = num_computed_tokens // self.offloaded_block_size num_blocks = full_block_tokens // self.offloaded_block_size assert len(request.block_hashes) // self.block_size_factor >= num_blocks block_hashes = self._get_block_hashes( request, start_idx=start_block_idx, end_idx=num_blocks ) src_spec = self.manager.prepare_load(block_hashes) dst_spec = GPULoadStoreSpec(block_ids[num_computed_gpu_blocks:]) block_hashes = self._get_block_hashes( request, start_idx=start_block_idx, end_idx=num_blocks ) self._reqs_to_load[request.request_id] = (src_spec, dst_spec) self._reqs_being_loaded[request.request_id].update(block_hashes) self._next_stored_block_idx[request.request_id] = num_blocks def _get_reqs_to_store(self, scheduler_output: SchedulerOutput): reqs_to_store: dict[ReqId, TransferSpec] = {} # iterate over both new and cached requests for req_id, new_block_id_groups, preempted in yield_req_data(scheduler_output): if preempted: self._request_block_ids[req_id] = [] if new_block_id_groups: new_block_ids = new_block_id_groups[0] self._request_block_ids[req_id] += new_block_ids block_ids = self._request_block_ids[req_id] req = self._requests[req_id] new_tokens = scheduler_output.num_scheduled_tokens[req_id] total_tokens = req.num_computed_tokens + new_tokens num_blocks = total_tokens // self.offloaded_block_size start_block_idx = self._next_stored_block_idx.get(req_id, 0) num_new_blocks = num_blocks - start_block_idx if num_new_blocks <= 0: continue # NOTE: In async scheduling, placeholders may temporarily make # len(req.block_hashes) < num_blocks * self.block_size_factor. new_block_hashes = self._get_block_hashes( req, start_idx=start_block_idx, end_idx=num_blocks ) store_output = self.manager.prepare_store(new_block_hashes) if store_output is None: logger.warning( "Request %s: cannot store %s blocks", req_id, num_new_blocks ) continue self._next_stored_block_idx[req_id] = num_blocks if not store_output.block_hashes_to_store: continue block_hashes_to_store = set(store_output.block_hashes_to_store) block_hashes = self._get_block_hashes(req, end_idx=num_blocks) self.manager.touch(block_hashes) new_block_hashes = self._get_block_hashes( req, start_idx=start_block_idx, end_idx=num_blocks ) dst_spec = store_output.store_spec src_block_ids: list[int] = [] for idx, blk_hash in enumerate(new_block_hashes): if blk_hash not in block_hashes_to_store: continue offloaded_block_idx = start_block_idx + idx gpu_block_idx = offloaded_block_idx * self.block_size_factor for i in range(self.block_size_factor): src_block_ids.append(block_ids[gpu_block_idx + i]) src_spec = GPULoadStoreSpec(src_block_ids) reqs_to_store[req_id] = (src_spec, dst_spec) self._reqs_being_stored[req_id] |= block_hashes_to_store logger.debug( "Request %s offloading %s blocks starting from block #%d", req_id, len(block_hashes_to_store), start_block_idx, ) return reqs_to_store def build_connector_meta( self, scheduler_output: SchedulerOutput ) -> KVConnectorMetadata: meta = OffloadingConnectorMetadata( reqs_to_load=self._reqs_to_load, reqs_to_store=self._get_reqs_to_store(scheduler_output), ) self._reqs_to_load = {} return meta def update_connector_output(self, connector_output: KVConnectorOutput): """ Update KVConnector state from worker-side connectors output. Args: connector_output (KVConnectorOutput): the worker-side connectors output. """ for req_id in connector_output.finished_sending or []: block_hashes = self._reqs_being_stored.pop(req_id, None) if block_hashes: self.manager.complete_store(block_hashes) for req_id in connector_output.finished_recving or []: block_hashes = self._reqs_being_loaded.pop(req_id, None) if block_hashes: self.manager.complete_load(block_hashes) def request_finished( self, request: Request, block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: """ Called when a request has finished, before its blocks are freed. Returns: True if the request is being saved/sent asynchronously and blocks should not be freed until the request_id is returned from get_finished(). Optional KVTransferParams to be included in the request outputs returned by the engine. """ req_id = request.request_id self._requests.pop(req_id, None) self._request_block_ids.pop(req_id, None) self._next_stored_block_idx.pop(req_id, None) request_being_stored = req_id in self._reqs_being_stored return request_being_stored, None def take_events(self) -> Iterable[KVCacheEvent]: """Take the KV cache events from the connector. Returns: A list of KV cache events. """ for event in self.manager.take_events(): if event.removed: yield BlockRemoved(block_hashes=event.block_hashes, medium=event.medium) else: yield BlockStored( block_hashes=event.block_hashes, parent_block_hash=None, token_ids=[], lora_id=None, block_size=event.block_size, medium=event.medium, lora_name=None, ) class OffloadingConnectorWorker: """Implementation of Worker side methods""" def __init__(self, spec: OffloadingSpec): self.spec = spec self.worker = OffloadingWorker() self._job_counter = 0 # req_id -> (job_id, store) self._jobs: dict[int, tuple[ReqId, bool]] = {} # req_id -> active job IDs self._load_job: dict[ReqId, int] = {} # req_id -> set(active job IDs) self._store_jobs = defaultdict[ReqId, set[int]](set) self._finished_reqs_waiting_for_store: set[ReqId] = set() def _generate_job_id(self) -> int: job_id = self._job_counter self._job_counter = job_id + 1 return job_id def _register_handlers( self, kv_caches: dict[str, torch.Tensor], attn_backends: dict[str, type[AttentionBackend]], ): for src_cls, dst_cls, handler in self.spec.get_handlers( kv_caches, attn_backends ): self.worker.register_handler(src_cls, dst_cls, handler) def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): layer_names = list(kv_caches.keys()) layers = get_layers_from_vllm_config( self.spec.vllm_config, Attention, layer_names ) attn_backends = { layer_name: layers[layer_name].get_attn_backend() for layer_name in layer_names } self._register_handlers(kv_caches, attn_backends) def register_cross_layers_kv_cache( self, kv_cache: torch.Tensor, attn_backend: type[AttentionBackend] ): cross_layer_name = "ALL_LAYERS" kv_caches = {cross_layer_name: kv_cache} attn_backends = {cross_layer_name: attn_backend} self._register_handlers(kv_caches, attn_backends) def start_load_kv(self, metadata: OffloadingConnectorMetadata): for req_id, transfer_spec in metadata.reqs_to_load.items(): job_id = self._generate_job_id() self._jobs[job_id] = (req_id, False) assert req_id not in self._load_job self._load_job[req_id] = job_id assert self.worker.transfer_async(job_id, transfer_spec) def start_store_kv(self, metadata: OffloadingConnectorMetadata): for req_id, transfer_spec in metadata.reqs_to_store.items(): job_id = self._generate_job_id() self._jobs[job_id] = (req_id, True) self._store_jobs[req_id].add(job_id) assert self.worker.transfer_async(job_id, transfer_spec) def get_finished(self, finished_req_ids: set[str]) -> tuple[set[str], set[str]]: """ Notifies worker-side connector ids of requests that have finished generating tokens. Returns a list of request IDs that finished loading or storing. Returns: ids of requests that have finished asynchronous transfer tuple of (sending/saving ids, recving/loading ids). """ finished_sending = set() finished_recving = set() for job_id, success in self.worker.get_finished(): # we currently do not support job failures assert success req_id, store = self._jobs.pop(job_id) if store: req_jobs = self._store_jobs[req_id] req_jobs.remove(job_id) if req_jobs: continue if req_id in self._finished_reqs_waiting_for_store: self._finished_reqs_waiting_for_store.remove(req_id) finished_sending.add(req_id) del self._store_jobs[req_id] else: req_job = self._load_job[req_id] assert job_id == req_job del self._load_job[req_id] finished_recving.add(req_id) for req_id in finished_req_ids: pending_req_jobs = self._store_jobs.get(req_id) if pending_req_jobs: self._finished_reqs_waiting_for_store.add(req_id) elif pending_req_jobs is not None: finished_sending.add(req_id) del self._store_jobs[req_id] return finished_sending, finished_recving
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/multi_connector.py
vllm/distributed/kv_transfer/kv_connector/v1/multi_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import copy from collections.abc import Iterable from dataclasses import dataclass from typing import TYPE_CHECKING, Any import torch from vllm.attention.backends.abstract import AttentionMetadata from vllm.config import VllmConfig from vllm.config.kv_transfer import KVTransferConfig from vllm.distributed.kv_transfer.kv_connector.base import KVConnectorBaseType from vllm.distributed.kv_transfer.kv_connector.factory import KVConnectorFactory from vllm.distributed.kv_transfer.kv_connector.v1.base import ( KVConnectorBase_V1, KVConnectorMetadata, KVConnectorRole, ) from vllm.distributed.kv_transfer.kv_connector.v1.metrics import ( KVConnectorPromMetrics, KVConnectorStats, PromMetric, PromMetricT, ) from vllm.logger import init_logger from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.outputs import KVConnectorOutput if TYPE_CHECKING: from vllm.distributed.kv_events import KVCacheEvent from vllm.forward_context import ForwardContext from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request logger = init_logger(__name__) @dataclass class MultiKVConnectorMetadata(KVConnectorMetadata): metadata: tuple[KVConnectorMetadata, ...] extra_async_saves: dict[str, int] | None = None @dataclass class MultiKVConnectorStats(KVConnectorStats): """ Maintain a dict of KVConnectorStats objects, one for each connector. This is used to aggregate the stats from all connectors separately. """ def aggregate(self, other: KVConnectorStats) -> KVConnectorStats: for connector_id, stats in other.data.items(): if connector_id not in self.data: self[connector_id] = stats else: assert isinstance(stats, type(self.data[connector_id])) self[connector_id] = self[connector_id].aggregate(stats) return self def reset(self): for stats in self.data.values(): stats.reset() def reduce(self) -> dict[str, Any]: # TODO (NickLucche) Adjust for logging on separate lines return { connector_id: stats.reduce() for connector_id, stats in self.data.items() } def is_empty(self) -> bool: return all(stats.is_empty() for stats in self.data.values()) def __getitem__(self, connector_id: str) -> KVConnectorStats: return self.data[connector_id] def __setitem__(self, connector_id: str, stats: KVConnectorStats): self.data[connector_id] = stats class MultiKVConnectorPromMetrics(KVConnectorPromMetrics): def __init__( self, vllm_config: "VllmConfig", metric_types: dict[type[PromMetric], type[PromMetricT]], labelnames: list[str], per_engine_labelvalues: dict[int, list[object]], prom_metrics: dict[str, KVConnectorPromMetrics], ): super().__init__(vllm_config, metric_types, labelnames, per_engine_labelvalues) self._prom_metrics = prom_metrics def observe(self, transfer_stats_data: dict[str, Any], engine_idx: int = 0): for connector_id, stats_data in transfer_stats_data.items(): assert connector_id in self._prom_metrics, ( f"{connector_id} is not contained in the list of registered connectors " f"with Prometheus metrics support: {self._prom_metrics.keys()}" ) self._prom_metrics[connector_id].observe(stats_data["data"], engine_idx) class MultiConnector(KVConnectorBase_V1): """ A wrapper for using multiple KVConnectors at the same time. The current logic is: - Load KV from the first connector that advertises available tokens from get_num_new_matched_tokens(), based on the order in the config. - Save to all connectors. """ def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, kv_cache_config: "KVCacheConfig", ): super().__init__( vllm_config=vllm_config, role=role, kv_cache_config=kv_cache_config ) self._connectors: list[KVConnectorBase_V1] = [] self._ktc_kv_transfer_config = [] for connector_cls, temp_config in self._get_connector_classes_and_configs( vllm_config ): self._connectors.append(connector_cls(temp_config, role, kv_cache_config)) self._ktc_kv_transfer_config.append(temp_config.kv_transfer_config) # A mapping from request id to the index of the connector chosen to # load the request from (if any). self._requests_to_connector: dict[str, int] = {} # Keeps track of *additional* remaining async saves (beyond 1) to be # finished per request. Not needed for async loads since we only allow # a single connector to load. # Propagated from scheduler to worker side via the connector metadata. self._extra_async_saves: dict[str, int] = {} @classmethod def _get_connector_classes_and_configs( cls, vllm_config: "VllmConfig" ) -> list[tuple[type[KVConnectorBaseType], "VllmConfig"]]: assert vllm_config.kv_transfer_config is not None ktcs = vllm_config.kv_transfer_config.kv_connector_extra_config.get( "connectors" ) assert ktcs is not None ret: list[tuple[type[KVConnectorBaseType], VllmConfig]] = [] for ktc in ktcs: temp_config = copy.copy(vllm_config) engine_id = ktc.get("engine_id", vllm_config.kv_transfer_config.engine_id) temp_config.kv_transfer_config = KVTransferConfig( **ktc, engine_id=engine_id ) ret.append( ( KVConnectorFactory.get_connector_class( temp_config.kv_transfer_config ), temp_config, ) ) return ret def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): for c in self._connectors: c.register_kv_caches(kv_caches) # We must override the base class method here because we need to bind # the metadata to each connector in the order of the connectors in the # MultiKVConnectorMetadata. # # Note: Call the base class method to ensure metadata is also set on the # MultiConnector instance itself; otherwise, `has_connector_metadata()` will # always return False. def bind_connector_metadata(self, connector_metadata: KVConnectorMetadata) -> None: assert isinstance(connector_metadata, MultiKVConnectorMetadata) if connector_metadata.extra_async_saves: self._extra_async_saves.update(connector_metadata.extra_async_saves) for c, cm in zip(self._connectors, connector_metadata.metadata): c.bind_connector_metadata(cm) super().bind_connector_metadata(connector_metadata) def clear_connector_metadata(self) -> None: for c in self._connectors: c.clear_connector_metadata() super().clear_connector_metadata() def shutdown(self): exception: Exception | None = None for c in self._connectors: try: c.shutdown() except Exception as e: logger.exception( "Exception during connector %s shutdown.", c.__class__.__name__ ) exception = e if exception: raise exception # ============================== # Worker-side methods # ============================== def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None: for c in self._connectors: c.start_load_kv(forward_context, **kwargs) def wait_for_layer_load(self, layer_name: str) -> None: for c in self._connectors: c.wait_for_layer_load(layer_name) def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: AttentionMetadata, **kwargs, ) -> None: for c in self._connectors: c.save_kv_layer(layer_name, kv_layer, attn_metadata, **kwargs) def wait_for_save(self): for c in self._connectors: c.wait_for_save() def get_finished( self, finished_req_ids: set[str] ) -> tuple[set[str] | None, set[str] | None]: finished_sending: set[str] = set() finished_recving: set[str] = set() for c in self._connectors: sending, recving = c.get_finished(finished_req_ids) if not recving and not sending: continue # Aggregate finished recving request ids. finished_recving.update(recving or ()) # Aggregate finished sending request ids - only include # once we've drained the "extra" count (for cases where # more than one connector is async-saving the same request). for req_id in sending or (): extra_pending = self._extra_async_saves.get(req_id) if extra_pending is None: finished_sending.add(req_id) continue assert extra_pending > 0 if extra_pending == 1: del self._extra_async_saves[req_id] else: self._extra_async_saves[req_id] = extra_pending - 1 return finished_sending or None, finished_recving or None def get_block_ids_with_load_errors(self) -> set[int]: agg_block_ids: set[int] = set() for c in self._connectors: agg_block_ids |= c.get_block_ids_with_load_errors() return agg_block_ids # TODO: Add a generic implementation of 'get_kv_connector_kv_cache_events' method # for the MultiConnector. It should be able to get events from multiple # connectors, handling the case where only a subset of the requested connectors # implements the 'get_kv_connector_kv_cache_events' # Follow on PR from https://github.com/vllm-project/vllm/pull/28309#pullrequestreview-3566351082 # ============================== # Scheduler-side methods # ============================== def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int | None, bool]: to_return = (0, False) for i, c in enumerate(self._connectors): toks, load_async = c.get_num_new_matched_tokens( request, num_computed_tokens ) # If there is a connector still looking up the matches, # we return None to indicate that we are not done yet. if toks is None: return (None, False) # The first connector that has new matched tokens will be assigned # to this request. if to_return[0] == 0 and toks > 0: self._requests_to_connector[request.request_id] = i to_return = (toks, load_async) return to_return def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): chosen_connector = self._requests_to_connector.get(request.request_id, -1) empty_blocks = blocks.new_empty() for i, c in enumerate(self._connectors): if i == chosen_connector: # Forward call to the chosen connector (if any). c.update_state_after_alloc(request, blocks, num_external_tokens) else: # Call with empty blocks for other connectors. c.update_state_after_alloc(request, empty_blocks, 0) def build_connector_meta( self, scheduler_output: SchedulerOutput ) -> MultiKVConnectorMetadata: metadata = MultiKVConnectorMetadata( metadata=tuple( c.build_connector_meta(scheduler_output) for c in self._connectors ) ) if self._extra_async_saves: metadata.extra_async_saves = self._extra_async_saves self._extra_async_saves = {} return metadata def update_connector_output(self, connector_output: KVConnectorOutput): for c in self._connectors: c.update_connector_output(connector_output) def request_finished( self, request: "Request", blocks: list[int], ) -> tuple[bool, dict[str, Any] | None]: async_saves = 0 kv_txfer_params = None for c in self._connectors: async_save, txfer_params = c.request_finished(request, blocks) if async_save: async_saves += 1 if txfer_params is not None: if kv_txfer_params is not None: # TODO we can probably change this to merge the dicts here, # checking for key clashes. raise RuntimeError( "Only one connector can produce KV transfer params" ) kv_txfer_params = txfer_params if async_saves > 1: self._extra_async_saves[request.request_id] = async_saves - 1 # Clean up other state for this request. self._requests_to_connector.pop(request.request_id, None) return async_saves > 0, kv_txfer_params def take_events(self) -> Iterable["KVCacheEvent"]: for c in self._connectors: yield from c.take_events() @classmethod def get_required_kvcache_layout(cls, vllm_config: "VllmConfig") -> str | None: """ Get the required KV cache layout for this connector. Args: vllm_config (VllmConfig): the vllm config. Returns: str: the required KV cache layout. e.g. HND, or NHD. None if the connector does not require a specific layout. """ assert vllm_config.kv_transfer_config is not None layouts: set[str] = set() for connector_cls, temp_config in cls._get_connector_classes_and_configs( vllm_config ): required_kvcache_layout = connector_cls.get_required_kvcache_layout( temp_config ) if required_kvcache_layout is not None: layouts.add(required_kvcache_layout) if len(layouts) > 1: raise ValueError( f"KV cache layout mismatch: " f"found {len(layouts)} different layouts " f"({', '.join(layouts)})." f"All connectors must use the same layout." ) return next(iter(layouts), None) @classmethod def build_kv_connector_stats( cls, data: dict[str, Any] | None = None ) -> KVConnectorStats | None: if data is None: return MultiKVConnectorStats() # data is a dict mapping connector name to their stats data. # The stats data can be either: # 1. Already-instantiated KVConnectorStats objects (same process) # 2. Serialized dicts (cross-process after serialization) # We need to reconstruct proper KVConnectorStats objects from dicts reconstructed_data = {} for connector_name, stats_value in data.items(): # If already a KVConnectorStats object, use it directly if isinstance(stats_value, KVConnectorStats): reconstructed_data[connector_name] = stats_value continue # Otherwise, reconstruct from serialized dict # Get the connector class to reconstruct its stats connector_cls = KVConnectorFactory.get_connector_class_by_name( connector_name ) # stats_value is the serialized dataclass which contains {'data': {...}} # We need to extract the inner 'data' field to avoid double-nesting assert isinstance(stats_value, dict) and "data" in stats_value, ( f"Expected a dict with a 'data' field, got {stats_value}" ) inner_data = stats_value["data"] # Use the connector's build_kv_connector_stats to reconstruct if reconstructed_stats := connector_cls.build_kv_connector_stats( data=inner_data ): reconstructed_data[connector_name] = reconstructed_stats return MultiKVConnectorStats(data=reconstructed_data) def get_kv_connector_stats(self) -> MultiKVConnectorStats | None: # Group connector stats by connector type. stats_by_connector: MultiKVConnectorStats | None = None for c in self._connectors: stats = c.get_kv_connector_stats() if stats is None: continue if stats_by_connector is None: # Lazy init to allow optional return value. stats_by_connector = MultiKVConnectorStats() stats_by_connector[c.__class__.__name__] = stats return stats_by_connector @classmethod def build_prom_metrics( cls, vllm_config: "VllmConfig", metric_types: dict[type["PromMetric"], type["PromMetricT"]], labelnames: list[str], per_engine_labelvalues: dict[int, list[object]], ) -> KVConnectorPromMetrics: prom_metrics: dict[str, KVConnectorPromMetrics] = {} for connector_cls, temp_config in cls._get_connector_classes_and_configs( vllm_config ): connector_prom = connector_cls.build_prom_metrics( temp_config, metric_types, labelnames, per_engine_labelvalues ) if connector_prom is not None: prom_metrics[connector_cls.__name__] = connector_prom return MultiKVConnectorPromMetrics( vllm_config, metric_types, labelnames, per_engine_labelvalues, prom_metrics, ) def reset_cache(self) -> bool: results = [c.reset_cache() is not False for c in self._connectors] return all(results)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/lmcache_connector.py
vllm/distributed/kv_transfer/kv_connector/v1/lmcache_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Iterable from typing import TYPE_CHECKING, Any import torch from vllm.attention.backends.abstract import AttentionMetadata from vllm.config import VllmConfig from vllm.distributed.kv_events import ( BlockStored, KVCacheEvent, KVConnectorKVEvents, KVEventAggregator, ) from vllm.distributed.kv_transfer.kv_connector.v1.base import ( KVConnectorBase_V1, KVConnectorMetadata, KVConnectorRole, ) from vllm.logger import init_logger from vllm.v1.core.sched.output import SchedulerOutput from vllm.v1.outputs import KVConnectorOutput if TYPE_CHECKING: from vllm.forward_context import ForwardContext from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request logger = init_logger(__name__) class LMCacheKVEvents(KVConnectorKVEvents): """ Concrete implementation of KVConnectorKVEvents using KVEventAggregator. """ def __init__(self, num_workers: int) -> None: self._aggregator = KVEventAggregator(num_workers) def add_events(self, events: list[KVCacheEvent]) -> None: self._aggregator.add_events(events) def aggregate(self) -> "LMCacheKVEvents": """ Aggregate KV events and retain only common events. """ common_events = self._aggregator.get_common_events() self._aggregator.clear_events() self._aggregator.add_events(common_events) self._aggregator.reset_workers() return self def increment_workers(self, count: int = 1) -> None: self._aggregator.increment_workers(count) def get_all_events(self) -> list[KVCacheEvent]: return self._aggregator.get_all_events() def get_number_of_workers(self) -> int: return self._aggregator.get_number_of_workers() def clear_events(self) -> None: self._aggregator.clear_events() self._aggregator.reset_workers() def __repr__(self) -> str: return f"<LMCacheKVEvents events={self.get_all_events()}>" class LMCacheConnectorV1(KVConnectorBase_V1): def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, kv_cache_config: "KVCacheConfig", ): super().__init__( vllm_config=vllm_config, role=role, kv_cache_config=kv_cache_config ) assert vllm_config.kv_transfer_config is not None use_native = vllm_config.kv_transfer_config.get_from_extra_config( "use_native", False ) if use_native: logger.info("Initializing native LMCache connector") # lazy import from vllm.distributed.kv_transfer.kv_connector.v1 import lmcache_integration _adapter = lmcache_integration.vllm_v1_adapter cls = _adapter.LMCacheConnectorV1Impl else: logger.info("Initializing latest dev LMCache connector") # lazy import from lmcache.integration.vllm.vllm_v1_adapter import ( LMCacheConnectorV1Impl as LMCacheConnectorLatestImpl, ) cls = LMCacheConnectorLatestImpl self._lmcache_engine = cls(vllm_config, role, self) self._kv_cache_events: LMCacheKVEvents | None = None # ============================== # Worker-side methods # ============================== def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): """ Initialize with the KV caches. Useful for pre-registering the KV Caches in the KVConnector (e.g. for NIXL). Args: kv_caches: dictionary of layer names, kv cache """ if hasattr(self._lmcache_engine, "register_kv_caches"): self._lmcache_engine.register_kv_caches(kv_caches) else: logger.warning( "LMCache engine does not support register_kv_caches, " "please check and use the latest version" ) def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None: """ Start loading the KV cache from the connector to vLLM's paged KV buffer. This is called from the forward context before the forward pass to enable async loading during model execution. Args: forward_context (ForwardContext): the forward context. **kwargs: additional arguments for the load operation Note: The number of elements in kv_caches and layer_names should be the same. """ self._lmcache_engine.start_load_kv(forward_context, **kwargs) def wait_for_layer_load(self, layer_name: str) -> None: """ Block until the KV for a specific layer is loaded into vLLM's paged buffer. This is called from within attention layer to ensure async copying from start_load_kv is complete. This interface will be useful for layer-by-layer pipelining. Args: layer_name: the name of that layer """ self._lmcache_engine.wait_for_layer_load(layer_name) def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: AttentionMetadata, **kwargs: Any, ) -> None: """ Start saving the a layer of KV cache from vLLM's paged buffer to the connector. This is called from within attention layer to enable async copying during execution. Args: layer_name (str): the name of the layer. kv_layer (torch.Tensor): the paged KV buffer of the current layer in vLLM. attn_metadata (AttentionMetadata): the attention metadata. **kwargs: additional arguments for the save operation. """ self._lmcache_engine.save_kv_layer( layer_name, kv_layer, attn_metadata, **kwargs ) def wait_for_save(self): """ Block until all the save operations is done. This is called as the forward context exits to ensure that the async saving from save_kv_layer is complete before finishing the forward. This prevents overwrites of paged KV buffer before saving done. """ self._lmcache_engine.wait_for_save() def get_finished( self, finished_req_ids: set[str] ) -> tuple[set[str] | None, set[str] | None]: """ Notifies worker-side connector ids of requests that have finished generating tokens. Returns: ids of requests that have finished asynchronous transfer (requests that previously returned True from request_finished()), tuple of (sending/saving ids, recving/loading ids). The finished saves/sends req ids must belong to a set provided in a call to this method (this call or a prior one). """ return self._lmcache_engine.get_finished(finished_req_ids) def get_block_ids_with_load_errors(self) -> set[int]: """ Get the set of block IDs that failed to load. Returns: Set of block IDs that encountered load errors. Empty set if no load errors occurred. """ method = getattr(self._lmcache_engine, "get_block_ids_with_load_errors", None) if callable(method): return method() # Fallback for older versions that don't support this method return set() def get_kv_connector_kv_cache_events(self) -> LMCacheKVEvents | None: """ Get the KV connector kv cache events collected during the last interval. """ events = self._lmcache_engine.get_kv_events() # type: ignore [attr-defined] if not events: return None blocks: list[BlockStored] = [ BlockStored( block_hashes=e.block_hashes, parent_block_hash=e.parent_block_hash, token_ids=e.token_ids, lora_id=e.lora_id, block_size=e.block_size, medium=e.medium, lora_name=e.lora_name, ) for e in events ] lmcache_kv_events = LMCacheKVEvents(num_workers=1) lmcache_kv_events.add_events(blocks) return lmcache_kv_events # ============================== # Scheduler-side methods # ============================== def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int | None, bool]: """ Get number of new tokens that can be loaded from the external KV cache beyond the num_computed_tokens. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: the number of tokens that can be loaded from the external KV cache beyond what is already computed. """ return self._lmcache_engine.get_num_new_matched_tokens( request, num_computed_tokens ), False def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): """ Update KVConnector state after block allocation. """ self._lmcache_engine.update_state_after_alloc(request, num_external_tokens) def build_connector_meta( self, scheduler_output: SchedulerOutput ) -> KVConnectorMetadata: """ Build the connector metadata for this step. This function should NOT modify fields in the scheduler_output. Also, calling this function will reset the state of the connector. Args: scheduler_output (SchedulerOutput): the scheduler output object. """ return self._lmcache_engine.build_connector_meta(scheduler_output) def update_connector_output(self, connector_output: KVConnectorOutput): """ Update KVConnector state from worker-side connectors output. Args: connector_output (KVConnectorOutput): the worker-side connectors output. """ # Get the KV events kv_cache_events = connector_output.kv_cache_events if not kv_cache_events or not isinstance(kv_cache_events, LMCacheKVEvents): return if self._kv_cache_events is None: self._kv_cache_events = kv_cache_events else: self._kv_cache_events.add_events(kv_cache_events.get_all_events()) self._kv_cache_events.increment_workers( kv_cache_events.get_number_of_workers() ) return def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: """ Called when a request has finished, before its blocks are freed. Returns: True if the request is being saved/sent asynchronously and blocks should not be freed until the request_id is returned from get_finished(). Optional KVTransferParams to be included in the request outputs returned by the engine. """ return self._lmcache_engine.request_finished(request, block_ids) def take_events(self) -> Iterable["KVCacheEvent"]: """ Take the KV cache events from the connector. Yields: New KV cache events since the last call. """ if self._kv_cache_events is not None: self._kv_cache_events.aggregate() kv_cache_events = self._kv_cache_events.get_all_events() yield from kv_cache_events self._kv_cache_events.clear_events() self._kv_cache_events = None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/vllm_v1_adapter.py
vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/vllm_v1_adapter.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Standard import os import uuid from collections.abc import Generator from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Optional import torch from lmcache import utils from lmcache.config import LMCacheEngineMetadata from lmcache.logging import init_logger from lmcache.observability import LMCStatsMonitor from lmcache.utils import _lmcache_nvtx_annotate from lmcache.v1.cache_engine import LMCacheEngine, LMCacheEngineBuilder from lmcache.v1.compute.blend import LMCBlenderBuilder from lmcache.v1.config import LMCacheEngineConfig, _validate_and_set_config_value from lmcache.v1.gpu_connector import ( VLLMBufferLayerwiseGPUConnector, VLLMPagedMemGPUConnectorV2, VLLMPagedMemLayerwiseGPUConnector, ) from lmcache.v1.internal_api_server.api_server import InternalAPIServer from lmcache.v1.lookup_client import LookupClientFactory from lmcache.v1.lookup_client.lmcache_async_lookup_client import ( LMCacheAsyncLookupServer, ) from lmcache.v1.offload_server.zmq_server import ZMQOffloadServer try: from lmcache.v1.plugin.runtime_plugin_launcher import RuntimePluginLauncher except ImportError: # Backwards compatibility for lmcache <= 0.3.10-post1 from lmcache.v1.plugin.plugin_launcher import ( PluginLauncher as RuntimePluginLauncher, ) from vllm.attention.backends.abstract import AttentionMetadata from vllm.config import VllmConfig from vllm.distributed.kv_transfer.kv_connector.v1.base import ( KVConnectorBase_V1, KVConnectorMetadata, KVConnectorRole, ) from vllm.distributed.kv_transfer.kv_connector.v1.lmcache_integration.utils import ( ENGINE_NAME, apply_mm_hashes_to_token_ids, extract_mm_features, lmcache_get_or_create_config, mla_enabled, ) from vllm.distributed.parallel_state import get_tensor_model_parallel_rank, get_tp_group from vllm.sampling_params import SamplingParams from vllm.utils.math_utils import cdiv from vllm.utils.torch_utils import get_kv_cache_torch_dtype from vllm.v1.core.sched.output import SchedulerOutput from vllm.version import __version__ as VLLM_VERSION if TYPE_CHECKING: from vllm.forward_context import ForwardContext from vllm.multimodal.inputs import PlaceholderRange from vllm.v1.core.kv_cache_manager import KVCacheManager from vllm.v1.core.sched.output import NewRequestData from vllm.v1.request import Request logger = init_logger(__name__) @dataclass class LoadSpec: # Number of tokens cached in vLLM vllm_cached_tokens: int # Number of tokens that are cached in LMCache lmcache_cached_tokens: int # Whether the scheduler allow us to load the tokens can_load: bool @dataclass class SaveSpec: # Skip already saved tokens skip_leading_tokens: int # Whether the scheduler allow us to save the tokens can_save: bool @dataclass class DisaggSpec: req_id: str receiver_id: str receiver_host: str receiver_init_port: int receiver_alloc_port: int is_last_prefill: bool = False num_transferred_tokens: int = 0 tmp_disagg_tracker: dict[str, DisaggSpec] = {} def extract_request_configs(sampling_params: SamplingParams) -> dict | None: request_configs = None if ( sampling_params.extra_args is not None and "kv_transfer_params" in sampling_params.extra_args ): kv_transfer_params = sampling_params.extra_args.get("kv_transfer_params") if kv_transfer_params is None: return None assert isinstance(kv_transfer_params, dict) for k, v in kv_transfer_params.items(): if k.startswith("lmcache."): if request_configs is None: request_configs = {} request_configs[k] = v return request_configs @dataclass class RequestTracker: # Request id req_id: str # Total prompt token length prompt_len: int # The token ids that has been scheduled so far token_ids: list[int] # The block ids that has been allocated so far # NOTE: allocated blocks could be more than the number of tokens allocated_block_ids: list[int] # The number of tokens that has been saved num_saved_tokens: int = 0 # Disagg spec for the request disagg_spec: DisaggSpec | None = None # Multimodal hashes and positions mm_hashes: list[str] | None = None mm_positions: list["PlaceholderRange"] | None = None # The configs of the request, includes tags and other configs request_configs: dict | None = None # Whether the request is in decode phase is_decode_phase = False # Whether the request cache should be saved skip_save: bool = False @_lmcache_nvtx_annotate @staticmethod def from_new_request( lmcache_config: LMCacheEngineConfig, new_request: "NewRequestData", num_tokens_to_compute: int, lmcache_cached_tokens: int, skip_save: bool, ) -> "RequestTracker": """Create the request tracker from a new request. Args: lmcache_config (LMCacheEngineConfig): the LMCache engine config. new_request (NewRequestData): the new request data. num_tokens_to_compute (int): the number of tokens that will be 'computed', including the `num_computed_tokens` (vLLM's local cache hit) and new tokens that will be scheduled. lmcache_cached_tokens (int): the number of tokens that are cached in LMCache. skip_save (bool): whether the request cache should be saved """ # vLLM 0.9.0 update: request.block_ids changed from list[int] to # list[list[int]] # Need to check the type of request.block_ids unfolded_block_ids = [] if not isinstance(new_request.block_ids[0], list): unfolded_block_ids = new_request.block_ids.copy() else: # According to the vLLM code # (https://github.com/vllm-project/vllm/blob/main/vllm/v1/core/ # sched/scheduler.py#L943), # only one KVCacheGroup is supported in connector for now. unfolded_block_ids = new_request.block_ids[0].copy() # NOTE: Initialized in `update_state_after_alloc` disagg_spec = tmp_disagg_tracker.pop(new_request.req_id, None) if new_request.sampling_params: request_configs = extract_request_configs(new_request.sampling_params) else: request_configs = None mm_hashes, mm_positions = extract_mm_features(new_request, modify=True) assert new_request.prompt_token_ids is not None return RequestTracker( req_id=new_request.req_id, prompt_len=len(new_request.prompt_token_ids), token_ids=new_request.prompt_token_ids[:num_tokens_to_compute].copy(), allocated_block_ids=unfolded_block_ids, num_saved_tokens=lmcache_cached_tokens, disagg_spec=disagg_spec, mm_hashes=mm_hashes, mm_positions=mm_positions, skip_save=skip_save, request_configs=request_configs, ) def update( self, new_token_ids: list[int], new_block_ids: tuple[list[int], ...] | None | list[int], ) -> None: """Update the request tracker when a running request is scheduled again """ self.token_ids.extend(new_token_ids) if new_block_ids is None: # https://github.com/vllm-project/vllm/commit/ # b029de9902aa3ac58806c8c17776c7074175b6db new_block_ids = [] elif len(new_block_ids) == 0: new_block_ids = [] elif isinstance(new_block_ids, tuple): new_block_ids = new_block_ids[0] elif isinstance(new_block_ids, list): pass else: raise ValueError(f"Unsupported new_block_ids type {type(new_block_ids)}") self.allocated_block_ids.extend(new_block_ids) # When a request is scheduled again, and the number of new tokens # is 1 (excluding chunked prefill), the request is in decode phase. if len(new_token_ids) == 1: self.is_decode_phase = True @dataclass class ReqMeta: # Request id req_id: str # Request tokens token_ids: list[int] # torch.Tensor # Slot mapping slot_mapping: torch.Tensor # Whether is last prefill or not is_last_prefill: bool = False # Skip save or not save_spec: SaveSpec | None = None # load_spec load_spec: LoadSpec | None = None # disagg spec disagg_spec: DisaggSpec | None = None # the configs of the request request_configs: dict | None = None @staticmethod def from_request_tracker( tracker: RequestTracker, block_size: int, lmcache_chunk_size: int = 256, load_spec: LoadSpec | None = None, discard_partial_chunks: bool = True, save_decode_cache: bool = False, ) -> Optional["ReqMeta"]: """Create the request metadata from a request tracker. Args: tracker (RequestTracker): the request tracker. block_size (int): the block size in vLLM. lmcache_chunk_size (int): the chunk size for LMCache. load_spec (Optional[LoadSpec]): the load spec for KV cache loading. discard_partial_chunks (bool): whether to discard partial chunks. save_decode_cache (bool): whether to save the cache in decode phase. Returns: the request metadata if we need to perform load/save operations, None otherwise. """ input_token_ids = tracker.token_ids input_token_len = len(input_token_ids) is_last_prefill = False if input_token_len == tracker.prompt_len: is_last_prefill = True # For save operation: do not save if the following condition is met # 1. has already been saved before (num_saved_tokens > 0) # 2. number of unsaved tokens is not reached the chunk boundary # 3. if save_decode_cache is False and it is in decode phase skip_leading_tokens = tracker.num_saved_tokens chunk_boundary = ( cdiv(tracker.num_saved_tokens + 1, lmcache_chunk_size) * lmcache_chunk_size ) # NOTE(vladnosiv): for disagg, you cannot skip saving, as saving is a # trqansfer. Check if request_configs has lmcache.skip_save set to True request_skip = (tracker.request_configs or {}).get("lmcache.skip_save", False) skip_save = tracker.disagg_spec is None and ( tracker.skip_save or (tracker.num_saved_tokens > 0 and input_token_len < chunk_boundary) or (tracker.is_decode_phase and not save_decode_cache) or request_skip ) if skip_save and load_spec is None: return None # Calculate number of tokens to save based on discard_partial_chunks # setting # NOTE(vladnosiv): for the input_token_len chunk prefill, # we are required to discard partial chunks, # as new tokens will be added in the next iteration. num_tokens_to_save = ( (input_token_len // lmcache_chunk_size * lmcache_chunk_size) if not is_last_prefill or discard_partial_chunks else input_token_len ) # If we need to save, update the number of saved tokens if not skip_save: tracker.num_saved_tokens = num_tokens_to_save save_spec = SaveSpec(skip_leading_tokens, not skip_save) # Calculate the token ids and slot mappings for load and save token_ids = input_token_ids[:num_tokens_to_save] # If the request has multimodal hashes, apply them to the token ids if tracker.mm_hashes: token_ids_tensor = torch.tensor(token_ids) assert tracker.mm_positions is not None, ( "tracker got mm_hashes but no mm_positions" ) apply_mm_hashes_to_token_ids( token_ids_tensor, tracker.mm_hashes, tracker.mm_positions ) token_ids = token_ids_tensor.tolist() num_blocks = len(tracker.allocated_block_ids) if len(token_ids) > num_blocks * block_size: logger.error( "The number of tokens is more than the number of blocks." "Something might be wrong in scheduling logic!" ) logger.error( "Num tokens: %d, num blocks: %d, block size: %d", len(token_ids), num_blocks, block_size, ) block_ids = torch.tensor(tracker.allocated_block_ids, dtype=torch.long) block_offsets = torch.arange(0, block_size, dtype=torch.long) slot_mapping = ( block_offsets.reshape((1, block_size)) + block_ids.reshape((num_blocks, 1)) * block_size ) slot_mapping = slot_mapping.flatten()[: len(token_ids)] assert slot_mapping.dtype == torch.long # For load operation: check whether the request is scheduled to load if load_spec is not None and load_spec.can_load: logger.debug( "Scheduled to load %d tokens for request %s", load_spec.lmcache_cached_tokens, tracker.req_id, ) else: # Do not load if not in `can_load` state load_spec = None return ReqMeta( req_id=tracker.req_id, token_ids=token_ids, slot_mapping=slot_mapping, is_last_prefill=is_last_prefill, save_spec=save_spec, load_spec=load_spec, disagg_spec=tracker.disagg_spec, request_configs=tracker.request_configs, ) def need_gpu_interm_buffer(lmcache_config: LMCacheEngineConfig): return not lmcache_config.enable_pd def _calculate_mtp_layers(vllm_config, model_config): num_mtp_layers = 0 if vllm_config is not None and vllm_config.speculative_config is not None: logger.info( "vllm_config.speculative_config: %s", vllm_config.speculative_config ) # TODO(baoloongmao): Support other MTP methods if vllm_config.speculative_config.method == "deepseek_mtp": num_mtp_layers = getattr( model_config.hf_config, "num_nextn_predict_layers", 0 ) elif vllm_config.speculative_config.use_eagle(): try: draft_model_config = vllm_config.speculative_config.draft_model_config num_mtp_layers = draft_model_config.get_num_layers( vllm_config.parallel_config ) logger.info("EAGLE detected %d extra layer(s)", num_mtp_layers) except Exception: logger.info( "EAGLE detected, but failed to get the number of extra layers" "falling back to 1" ) num_mtp_layers = 1 return num_mtp_layers def _init_lmcache_engine( lmcache_config: LMCacheEngineConfig, vllm_config: "VllmConfig", ) -> LMCacheEngine: """Initialize the LMCache engine by the given model config and parallel config. This function will check the environment variable `LMCACHE_CONFIG_FILE` to load the configuration file. If that environment variable is not set, this function will return None. :param lmcache_config: The LMCache configuration. :type lmcache_config: LMCacheEngineConfig :param vllm_config: The vLLM configuration. :type vllm_config: VllmConfig :return: The initialized LMCache engine :rtype: LMCacheEngine """ if curr_engine := LMCacheEngineBuilder.get(ENGINE_NAME): return curr_engine model_config = vllm_config.model_config parallel_config = vllm_config.parallel_config cache_config = vllm_config.cache_config assert isinstance(lmcache_config, LMCacheEngineConfig), ( "LMCache v1 configuration is should be passed." ) kv_dtype = get_kv_cache_torch_dtype(cache_config.cache_dtype, model_config.dtype) use_mla = mla_enabled(model_config) if use_mla and ( lmcache_config.remote_serde != "naive" and lmcache_config.remote_serde is not None ): raise ValueError("MLA only works with naive serde mode..") # construct kv shape (for mem pool) num_layer = model_config.get_num_layers(parallel_config) num_mtp_layers = _calculate_mtp_layers(vllm_config, model_config) num_layer += num_mtp_layers chunk_size = lmcache_config.chunk_size num_kv_head = model_config.get_num_kv_heads(parallel_config) head_size = model_config.get_head_size() kv_shape = (num_layer, 1 if use_mla else 2, chunk_size, num_kv_head, head_size) logger.info( "use mla: %s, kv shape: %s, num_mtp_layers: %s", use_mla, kv_shape, num_mtp_layers, ) # Change current device. num_gpus = torch.cuda.device_count() local_rank = parallel_config.rank % num_gpus torch.cuda.set_device(local_rank) device = torch.device(f"cuda:{local_rank}") metadata = LMCacheEngineMetadata( model_config.model, parallel_config.world_size, parallel_config.rank, "vllm", kv_dtype, kv_shape, use_mla, ) use_gpu = need_gpu_interm_buffer(lmcache_config) vllm_gpu_connector: ( VLLMBufferLayerwiseGPUConnector | VLLMPagedMemGPUConnectorV2 | VLLMPagedMemLayerwiseGPUConnector ) if use_mla and lmcache_config.use_layerwise: raise ValueError("layerwise MLA connector is not supported yet") # When use_mla is True, num_kv_head is 1 hidden_dim_size = num_kv_head * head_size if lmcache_config.use_layerwise: if lmcache_config.enable_blending: # Use layerwise connector for blending vllm_gpu_connector = VLLMBufferLayerwiseGPUConnector( hidden_dim_size, num_layer, use_gpu=use_gpu, chunk_size=chunk_size, dtype=kv_dtype, device=device, ) else: vllm_gpu_connector = VLLMPagedMemLayerwiseGPUConnector( hidden_dim_size, num_layer, use_gpu=use_gpu, chunk_size=chunk_size, dtype=kv_dtype, device=device, ) else: vllm_gpu_connector = VLLMPagedMemGPUConnectorV2( hidden_dim_size, num_layer, use_gpu=use_gpu, chunk_size=chunk_size, dtype=kv_dtype, device=device, use_mla=use_mla, ) tpg = get_tp_group() engine = LMCacheEngineBuilder.get_or_create( ENGINE_NAME, lmcache_config, metadata, vllm_gpu_connector, tpg.broadcast, tpg.broadcast_object, ) return engine @dataclass class LMCacheConnectorMetadata(KVConnectorMetadata): requests: list[ReqMeta] = field(default_factory=list) lookup_requests_in_step: list[str] = field(default_factory=list) @_lmcache_nvtx_annotate def add_request(self, req_meta: ReqMeta) -> None: """Add a request to the metadata. Args: req_meta (ReqMeta): the request metadata. """ self.requests.append(req_meta) class LMCacheConnectorV1Impl: def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, parent: KVConnectorBase_V1, ): assert vllm_config.kv_transfer_config is not None self._parent = parent self._vllm_config = vllm_config self.kv_role = vllm_config.kv_transfer_config.kv_role self.worker_count = vllm_config.parallel_config.tensor_parallel_size config = lmcache_get_or_create_config() assert isinstance(config, LMCacheEngineConfig), ( "LMCache v1 configuration is should be passed for vLLM v1." ) # Put the leading with "lmcache." and matched configs from # vllm extra_config to the config kv_connector_extra_config = ( vllm_config.kv_transfer_config.kv_connector_extra_config ) if kv_connector_extra_config: for key, value in kv_connector_extra_config.items(): if key.startswith("lmcache."): config_key = key[8:] # Remove "lmcache." prefix if _validate_and_set_config_value(config, config_key, value): logger.info( "Updated config %s from vLLM extra config: %s", config_key, value, ) self.config = config self.async_loading = config.enable_async_loading self.layerwise_retrievers: list[Generator[torch.Tensor | None, None, None]] = [] self._stats_monitor = LMCStatsMonitor.GetOrCreate() if role == KVConnectorRole.SCHEDULER: # Create lookup client using factory self.lookup_client = LookupClientFactory.create_lookup_client( vllm_config, config ) self._unfinished_requests: dict[str, Request] = {} self._lookup_requests_in_step: list[str] = [] self.lmcache_engine = None else: self.lmcache_engine = _init_lmcache_engine( config, vllm_config, ) self.use_layerwise = config.use_layerwise self.enable_blending = config.enable_blending if self.enable_blending: self.blender = LMCBlenderBuilder.get_or_create( ENGINE_NAME, self.lmcache_engine, self.lmcache_engine.gpu_connector, config, ) # Create lookup server using factory assert self.lmcache_engine is not None self.lookup_server = LookupClientFactory.create_lookup_server( self.lmcache_engine, vllm_config ) self.offload_server = ZMQOffloadServer( self.lmcache_engine, vllm_config, get_tensor_model_parallel_rank(), ) # In case of MLA, the lookup server is only created on worker 0 if self.async_loading and self.lookup_server is not None: assert isinstance(self.lookup_server, LMCacheAsyncLookupServer) self.lmcache_engine.post_init(async_lookup_server=self.lookup_server) self.kv_caches: dict[str, torch.Tensor] = {} self._block_size = vllm_config.cache_config.block_size # request_id -> (vllm cached tokens, lmcache cached tokens) self.load_specs: dict[str, LoadSpec] = {} self.kv_cache_manager: KVCacheManager | None = None # request_id -> full_token_ids self._request_trackers: dict[str, RequestTracker] = {} # Whether to discard partial chunks self._discard_partial_chunks = ( vllm_config.kv_transfer_config.get_from_extra_config( "discard_partial_chunks", False ) or not config.save_unfull_chunk ) self._lmcache_chunk_size = config.chunk_size self._save_decode_cache = config.save_decode_cache self.skip_last_n_tokens = vllm_config.kv_transfer_config.get_from_extra_config( "skip_last_n_tokens", 0 ) self.num_layers = vllm_config.model_config.get_num_layers( vllm_config.parallel_config ) self.current_layer = 0 self.force_skip_save = bool(os.environ.get("LMCACHE_FORCE_SKIP_SAVE", False)) self._requests_priority: dict[str, int] = {} # TODO(baoloongmao): Internal api server & plugin framework support # dp > 1 if ( vllm_config.parallel_config.data_parallel_size_local == 1 or vllm_config.parallel_config.data_parallel_rank_local == 0 ): # Start internal API server if enabled # The enabled check is in the InternalAPIServer constructor self.api_server = InternalAPIServer(self) self.api_server.start() # Launch plugins self.plugin_launcher = RuntimePluginLauncher( self.config, role, self.worker_count, -1 if self.lmcache_engine is None # scheduler side else self.lmcache_engine.metadata.worker_id, ) self.plugin_launcher.launch_plugins() else: self.api_server = None # type: ignore[assignment] self.plugin_launcher = None # type: ignore[assignment] logger.info( "LMCache initialized for role %s with version %s, " "vllm version %s, lmcache cache_engine metadata: %s", role, utils.get_version(), VLLM_VERSION, getattr(self.lmcache_engine, "metadata", None), ) def get_inference_info(self) -> dict: """Get inference information including vLLM config and related details. Returns: dict: Dictionary containing inference information """ # Get vLLM config information vllm_config = self._vllm_config # Use vLLM config's string representation and add specific configs inference_info = { "vllm_version": VLLM_VERSION, "lmcache_version": utils.get_version(), "vllm_config": str(vllm_config), "model_config": { "model": getattr(vllm_config.model_config, "model", None), "dtype": str(getattr(vllm_config.model_config, "dtype", None)), "max_model_len": getattr( vllm_config.model_config, "max_model_len", None ), "vocab_size": vllm_config.model_config.get_vocab_size(), "num_layers": getattr( vllm_config.model_config, "get_num_layers", lambda _: None )(vllm_config.parallel_config), "num_attention_heads": getattr( vllm_config.model_config, "get_num_attention_heads", lambda _: None )(vllm_config.parallel_config), "num_kv_heads": getattr( vllm_config.model_config, "get_num_kv_heads", lambda _: None )(vllm_config.parallel_config), "head_size": getattr( vllm_config.model_config, "get_head_size", lambda: None )(), }, "cache_config": { "block_size": getattr(vllm_config.cache_config, "block_size", None), "cache_dtype": str( getattr(vllm_config.cache_config, "cache_dtype", None) ), "gpu_memory_utilization": getattr( vllm_config.cache_config, "gpu_memory_utilization", None ), }, } return inference_info def get_inference_version(self) -> str: """Get vLLM version information. Returns: str: vLLM version string """ return VLLM_VERSION @_lmcache_nvtx_annotate def _init_kv_caches_from_forward_context(self, forward_context: "ForwardContext"): for layer_name in forward_context.no_compile_layers: attn_layer = forward_context.no_compile_layers[layer_name] if not hasattr(attn_layer, "kv_cache"): logger.debug("The layer %s does not have kv_cache, skip it", layer_name) continue if layer_name not in self.kv_caches: self.kv_caches[layer_name] = attn_layer.kv_cache[ forward_context.virtual_engine ] #################### # Worker side APIs #################### @_lmcache_nvtx_annotate def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]): logger.info("Registering KV caches") # TODO(chunxiaozheng): `_init_kv_caches_from_forward_context` is # not called, we should consider removing it. assert len(self.kv_caches) == 0 and len(kv_caches) > 0 self.kv_caches = kv_caches if self.lmcache_engine is not None: kvcaches = list(self.kv_caches.values()) self.lmcache_engine.post_init(kvcaches=kvcaches) @_lmcache_nvtx_annotate def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None: """Start loading the KV cache from the connector buffer to vLLM's paged KV buffer. Args: forward_context (ForwardContext): the forward context. Note: The number of elements in kv_caches and layer_names should be the same. """ self.current_layer = 0 if len(self.kv_caches) == 0: self._init_kv_caches_from_forward_context(forward_context) metadata = self._parent._get_connector_metadata() assert isinstance(metadata, LMCacheConnectorMetadata) assert len(self.kv_caches) > 0 kvcaches = list(self.kv_caches.values()) attn_metadata = forward_context.attn_metadata if attn_metadata is None: logger.debug("In connector.start_load_kv, but the attn_metadata is None") return assert self.lmcache_engine is not None self.lmcache_engine.post_init(kvcaches=kvcaches) self.layerwise_retrievers = [] for idx, request in enumerate(metadata.requests): if request.load_spec is None: continue last_idx = idx for idx, request in enumerate(metadata.requests): if request.load_spec is None: continue tokens = request.token_ids # TODO: have a pre-allocated buffer to hold the slot_mappings slot_mapping = request.slot_mapping.cuda() assert len(tokens) == len(slot_mapping) self._stats_monitor.update_interval_vllm_hit_tokens( request.load_spec.vllm_cached_tokens ) token_mask = torch.ones(len(tokens), dtype=torch.bool) masked_token_count = ( request.load_spec.vllm_cached_tokens // self._lmcache_chunk_size * self._lmcache_chunk_size ) token_mask[:masked_token_count] = False lmcache_cached_tokens = request.load_spec.lmcache_cached_tokens if self.use_layerwise: sync = idx == last_idx # NOTE(Jiayi): Perform blending before layerwise prefix caching if self.enable_blending: # TODO(Jiayi): Need to make prefix caching and blending # compatible self.blender.blend( tokens[:lmcache_cached_tokens], token_mask[:lmcache_cached_tokens], kvcaches=kvcaches, slot_mapping=slot_mapping[:lmcache_cached_tokens], ) else: layerwise_retriever = self.lmcache_engine.retrieve_layer( tokens[:lmcache_cached_tokens], token_mask[:lmcache_cached_tokens], kvcaches=kvcaches, slot_mapping=slot_mapping[:lmcache_cached_tokens], sync=sync, ) # NOTE: retrieve for two layers at the first layer next(layerwise_retriever) next(layerwise_retriever) self.layerwise_retrievers.append(layerwise_retriever) else: ret_token_mask = self.lmcache_engine.retrieve( tokens[:lmcache_cached_tokens], token_mask[:lmcache_cached_tokens], kvcaches=kvcaches, slot_mapping=slot_mapping[:lmcache_cached_tokens], request_configs=request.request_configs, req_id=request.req_id, ) # Check the result num_retrieved_tokens = ret_token_mask.sum().item() num_expected_tokens = (
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
true
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/utils.py
vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Standard import os import threading from typing import TYPE_CHECKING, Union import torch from lmcache.config import LMCacheEngineConfig as Config from lmcache.logging import init_logger from lmcache.v1.config import LMCacheEngineConfig as V1Config if TYPE_CHECKING: from vllm.config import ModelConfig from vllm.multimodal.inputs import PlaceholderRange from vllm.v1.core.sched.output import NewRequestData from vllm.v1.request import Request logger = init_logger(__name__) ENGINE_NAME = "vllm-instance" # Thread-safe singleton storage _config_instance: Config | V1Config | None = None _config_lock = threading.Lock() def is_false(value: str) -> bool: """Check if the given string value is equivalent to 'false'.""" return value.lower() in ("false", "0", "no", "n", "off") def lmcache_get_or_create_config() -> Config | V1Config: """Get the LMCache configuration from the environment variable `LMCACHE_CONFIG_FILE`. If the environment variable is not set, this function will return the default configuration. This function is thread-safe and implements singleton pattern, ensuring the configuration is loaded only once. """ global _config_instance # Double-checked locking for thread-safe singleton if _config_instance is None: with _config_lock: if _config_instance is None: # Check again within lock if is_false(os.getenv("LMCACHE_USE_EXPERIMENTAL", "True")): logger.warning( "Detected LMCACHE_USE_EXPERIMENTAL is set to False. " "Using legacy configuration is deprecated and will " "be remove soon! Please set LMCACHE_USE_EXPERIMENTAL " "to True." ) LMCacheEngineConfig = Config # type: ignore[assignment] else: LMCacheEngineConfig = V1Config # type: ignore[assignment] if "LMCACHE_CONFIG_FILE" not in os.environ: logger.warning( "No LMCache configuration file is set. Trying to read" " configurations from the environment variables." ) logger.warning( "You can set the configuration file through " "the environment variable: LMCACHE_CONFIG_FILE" ) _config_instance = LMCacheEngineConfig.from_env() else: config_file = os.environ["LMCACHE_CONFIG_FILE"] logger.info("Loading LMCache config file %s", config_file) _config_instance = LMCacheEngineConfig.from_file(config_file) # Update config from environment variables _config_instance.update_config_from_env() return _config_instance def hex_hash_to_int16(s: str) -> int: """ Convert a hex hash string to a 16-bit integer. """ return int(s, 16) & 0xFFFF def apply_mm_hashes_to_token_ids( token_ids: torch.Tensor, mm_hashes: list[str], mm_positions: list["PlaceholderRange"], ) -> torch.Tensor: """ Overwrite token_ids in-place for multimodal placeholders using efficient slice assignments. """ n = token_ids.size(0) for hash_str, placeholder in zip(mm_hashes, mm_positions): start, length = placeholder.offset, placeholder.length if start >= n: continue end = min(start + length, n) token_ids[start:end] = hex_hash_to_int16(hash_str) return token_ids def mla_enabled(model_config: "ModelConfig") -> bool: return ( hasattr(model_config, "use_mla") and isinstance(model_config.use_mla, bool) and model_config.use_mla ) def create_lmcache_metadata( vllm_config=None, model_config=None, parallel_config=None, cache_config=None ): """ Create LMCacheEngineMetadata from vLLM configuration. This function extracts common metadata creation logic that was duplicated across multiple files. Args: vllm_config (VllmConfig): vLLM configuration object containing model, parallel, and cache configs (alternative to individual config parameters) model_config (ModelConfig): Model configuration (alternative to vllm_config) parallel_config (ParallelConfig): Parallel configuration (alternative to vllm_config) cache_config (CacheConfig): Cache configuration (alternative to vllm_config) """ # Third Party # First Party from lmcache.config import LMCacheEngineMetadata from vllm.utils.torch_utils import get_kv_cache_torch_dtype config = lmcache_get_or_create_config() # Support both vllm_config object and individual config parameters if vllm_config is not None: model_cfg = vllm_config.model_config parallel_cfg = vllm_config.parallel_config cache_cfg = vllm_config.cache_config else: if model_config is None or parallel_config is None or cache_config is None: raise ValueError( "Either vllm_config must be provided, or all of " "model_config, parallel_config, and cache_config must be provided." ) model_cfg = model_config parallel_cfg = parallel_config cache_cfg = cache_config # Get KV cache dtype kv_dtype = get_kv_cache_torch_dtype(cache_cfg.cache_dtype, model_cfg.dtype) # Check if MLA is enabled use_mla = mla_enabled(model_cfg) # Construct KV shape (for memory pool) num_layer = model_cfg.get_num_layers(parallel_cfg) chunk_size = config.chunk_size num_kv_head = model_cfg.get_num_kv_heads(parallel_cfg) head_size = model_cfg.get_head_size() kv_shape = (num_layer, 1 if use_mla else 2, chunk_size, num_kv_head, head_size) # Create metadata metadata = LMCacheEngineMetadata( model_cfg.model, parallel_cfg.world_size, parallel_cfg.rank, "vllm", kv_dtype, kv_shape, use_mla, ) return metadata, config def extract_mm_features( request: Union["Request", "NewRequestData"], modify: bool = False ) -> tuple[list[str], list["PlaceholderRange"]]: """ Normalize multimodal information from a Request into parallel lists. This helper reads either: 1) `request.mm_features` (objects each exposing `.identifier` and `.mm_position`), or 2) legacy fields `request.mm_hashes` and `request.mm_positions`. It returns two equally sized lists: the multimodal hash identifiers and their corresponding positions. If the request contains no multimodal info, it returns `([], [])`. Args: request (Request): The source object. modify (bool): Controls copy semantics for the legacy-path return values. - If True and legacy fields are used, shallow-copies are returned so the caller can mutate the lists without affecting `request`. - If False, the original legacy sequences are returned as-is (zero-copy); treat them as read-only. Returns: tuple[list[str], list[PlaceholderRange]]: (`mm_hashes`, `mm_positions`). May be `([], [])` when no multimodal data is present. """ if getattr(request, "mm_features", None): mm_hashes, mm_positions = zip( *((f.identifier, f.mm_position) for f in request.mm_features) ) return (list(mm_hashes), list(mm_positions)) elif getattr(request, "mm_hashes", None): if modify: return ( request.mm_hashes.copy(), # type: ignore request.mm_positions.copy(), # type: ignore ) else: return (request.mm_hashes, request.mm_positions) # type: ignore else: return ([], [])
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/__init__.py
vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from . import multi_process_adapter, vllm_v1_adapter from .multi_process_adapter import ( LMCacheMPSchedulerAdapter, LMCacheMPWorkerAdapter, LoadStoreOp, ) __all__ = [ "vllm_v1_adapter", "multi_process_adapter", "LMCacheMPSchedulerAdapter", "LMCacheMPWorkerAdapter", "LoadStoreOp", ]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/multi_process_adapter.py
vllm/distributed/kv_transfer/kv_connector/v1/lmcache_integration/multi_process_adapter.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import os from collections.abc import Iterable from dataclasses import dataclass from itertools import islice from typing import Any import torch import zmq from lmcache.utils import _lmcache_nvtx_annotate, init_logger from lmcache.v1.multiprocess.custom_types import ( CudaIPCWrapper, IPCCacheEngineKey, KVCache, ) from lmcache.v1.multiprocess.mq import MessageQueueClient, MessagingFuture from lmcache.v1.multiprocess.protocol import RequestType, get_response_class logger = init_logger(__name__) def wrap_kv_caches(kv_caches: dict[str, KVCache]) -> KVCache: logger.info("KV caches keys are %s", list(kv_caches.keys())) return [CudaIPCWrapper(tensor) for tensor in kv_caches.values()] def send_lmcache_request( mq_client: MessageQueueClient, request_type: RequestType, payloads: list[Any], ) -> MessagingFuture[Any]: future = mq_client.submit_request( request_type, payloads, get_response_class(request_type) ) return future def get_lmcache_chunk_size( mq_client: MessageQueueClient, ) -> int: future = send_lmcache_request(mq_client, RequestType.GET_CHUNK_SIZE, []) chunk_size = future.result() return chunk_size def striding_block_hashes( block_hashes: list[bytes], blocks_in_chunk, ) -> Iterable[bytes]: """Striding the block hashes to get the block hashes for each chunk. For example, if blocks_in_chunk is 16, then we will get the block hashes for the 16th, 32nd, 48th, ... blocks. """ return islice(block_hashes, blocks_in_chunk - 1, None, blocks_in_chunk) @dataclass class LoadStoreOp: block_hashes: list[bytes] block_ids: list[int] def __len__(self) -> int: return len(self.block_hashes) def __post_init__(self): assert len(self.block_hashes) == len(self.block_ids), ( "The number of block hashes should be equal to the number of block ids " f"But got {len(self.block_hashes)} and {len(self.block_ids)}" ) StoreResult = bool RetrieveResult = list[bool] LookupResult = list[bool] class LMCacheMPSchedulerAdapter: def __init__( self, server_url: str, context: zmq.Context, model_name: str, world_size: int, kv_rank: int, vllm_block_size: int, ): """ Args: server_url: The server URL for the LMCache message queue context: The ZMQ context model_name: The model name used for LMCache keys world_size: The world size used for LMCache keys kv_rank: The kv rank used for LMCache keys vllm_block_size: The block size used in vLLM """ self.mq_client = MessageQueueClient(server_url, context) # Request futures self.lookup_futures: dict[str, MessagingFuture[LookupResult]] = {} self.model_name = model_name self.world_size = world_size self.worker_id = kv_rank # Read chunk size from lmcache self.chunk_size = get_lmcache_chunk_size(self.mq_client) assert self.chunk_size % vllm_block_size == 0, ( "LMCache chunk size should be a multiple of vLLM block size" ) self.blocks_in_chunk = self.chunk_size // vllm_block_size @_lmcache_nvtx_annotate def maybe_submit_lookup_request(self, request_id: str, block_hashes: list[bytes]): if request_id in self.lookup_futures: # Skip if there is already a lookup request return s = striding_block_hashes(block_hashes, self.blocks_in_chunk) keys = [self._create_key(block_hash) for block_hash in s] future = send_lmcache_request( self.mq_client, RequestType.LOOKUP, [keys, True], ) self.lookup_futures[request_id] = future @_lmcache_nvtx_annotate def check_lookup_result(self, request_id: str) -> int | None: assert request_id in self.lookup_futures, ( f"Lookup request for request_id={request_id} has not been submitted" ) future = self.lookup_futures[request_id] if not future.query(): return None result = future.result() num_chunks = sum(result) return num_chunks * self.chunk_size def num_blocks_per_chunk(self) -> int: """ Returns: The number of vllm blocks in a LMCache data chunk """ return self.blocks_in_chunk def _cleanup_lookup_result(self, request_id: str) -> None: """ Clean up lookup future for a finished request to prevent memory leak. Args: request_id: The ID of the finished request. """ self.lookup_futures.pop(request_id, None) # Helper functions def _create_key(self, block_hash: bytes) -> IPCCacheEngineKey: """Convert a block hash to an IPC cache engine key""" return IPCCacheEngineKey( model_name=self.model_name, world_size=self.world_size, worker_id=self.worker_id, chunk_hash=block_hash, ) class LMCacheMPWorkerAdapter: def __init__( self, server_url: str, context: zmq.Context, model_name: str, world_size: int, kv_rank: int, vllm_block_size: int, ): self.mq_client = MessageQueueClient(server_url, context) # Instance id for GPU worker self.instance_id = os.getpid() # Registered kv caches from vLLM self.kv_caches: dict[str, torch.Tensor] = {} # Request futures # request_id -> (future, other merged requests) self.store_futures: dict[ str, tuple[MessagingFuture[StoreResult], list[str]] ] = {} self.retrieve_futures: dict[ str, tuple[MessagingFuture[RetrieveResult], list[str]] ] = {} self.finished_stores: set[str] = set() self.previously_finished: set[str] = set() self.model_name = model_name self.world_size = world_size self.worker_id = kv_rank # Read chunk size from lmcache chunk_size = get_lmcache_chunk_size(self.mq_client) assert chunk_size % vllm_block_size == 0, ( "LMCache chunk size should be a multiple of vLLM block size" ) self.blocks_in_chunk = chunk_size // vllm_block_size def register_kv_caches(self, kv_caches: dict[str, KVCache]): # Register kv cache and send the request self.kv_caches = kv_caches logger.info("Registering kv caches") future = send_lmcache_request( self.mq_client, RequestType.REGISTER_KV_CACHE, [self.instance_id, wrap_kv_caches(kv_caches)], ) future.result() @_lmcache_nvtx_annotate def submit_store_request( self, request_id: str, op: LoadStoreOp, event: torch.cuda.Event ): keys = self._block_hashes_to_keys(op.block_hashes) future = send_lmcache_request( self.mq_client, RequestType.STORE, [keys, self.instance_id, op.block_ids, event.ipc_handle()], ).to_cuda_future() self.store_futures[request_id] = (future, []) @_lmcache_nvtx_annotate def submit_retrieve_request( self, request_id: str, op: LoadStoreOp, event: torch.cuda.Event ): keys = self._block_hashes_to_keys(op.block_hashes) future = send_lmcache_request( self.mq_client, RequestType.RETRIEVE, [keys, self.instance_id, op.block_ids, event.ipc_handle()], ).to_cuda_future() self.retrieve_futures[request_id] = (future, []) @_lmcache_nvtx_annotate def batched_submit_store_requests( self, request_ids: list[str], ops: list[LoadStoreOp], event: torch.cuda.Event, ): keys = [] block_ids = [] for op in ops: keys.extend(self._block_hashes_to_keys(op.block_hashes)) block_ids.extend(op.block_ids) future = send_lmcache_request( self.mq_client, RequestType.STORE, [keys, self.instance_id, block_ids, event.ipc_handle()], ).to_cuda_future() self.store_futures[request_ids[0]] = (future, request_ids[1:]) @_lmcache_nvtx_annotate def batched_submit_retrieve_requests( self, request_ids: list[str], ops: list[LoadStoreOp], event: torch.cuda.Event, ): keys = [] block_ids = [] for op in ops: keys.extend(self._block_hashes_to_keys(op.block_hashes)) block_ids.extend(op.block_ids) future = send_lmcache_request( self.mq_client, RequestType.RETRIEVE, [keys, self.instance_id, block_ids, event.ipc_handle()], ).to_cuda_future() self.retrieve_futures[request_ids[0]] = (future, request_ids[1:]) @_lmcache_nvtx_annotate def get_finished( self, finished_req_ids: set[str] ) -> tuple[set[str] | None, set[str] | None]: finished_stores = set() finished_retrieves = set() for request_id, (future, other_reqs) in self.store_futures.items(): if not future.query(): continue result = future.result() finished_stores.add(request_id) finished_stores.update(other_reqs) if not result: # TODO: add error handling here logger.error( "Something went wrong when processing the " "store request for request_id=%s", request_id, ) for request_id, (future, other_reqs) in self.retrieve_futures.items(): if not future.query(): continue result = future.result() finished_retrieves.add(request_id) finished_retrieves.update(other_reqs) if not all(result): # TODO: add error handing here logger.error( "Something went wrong when processing the " "retrieve request for request_id=%s, result=%s", request_id, result, ) # Remove the finished requests from the tracking dicts for request_id in finished_stores: self.store_futures.pop(request_id, None) for request_id in finished_retrieves: self.retrieve_futures.pop(request_id, None) # Update the internal states self.finished_stores.update(finished_stores) ret_stores = set() for req_id in finished_req_ids: if req_id in self.finished_stores or req_id in self.store_futures: self.previously_finished.add(req_id) else: ret_stores.add(req_id) # Calculate the final finished stores ret_stores.update(self._update_and_get_finished_store()) return ret_stores, finished_retrieves def num_blocks_per_chunk(self) -> int: """ Returns: The number of vllm blocks in a LMCache data chunk """ return self.blocks_in_chunk def shutdown(self): # Unregister kv cache logger.info("Unregistering kv caches") send_lmcache_request( self.mq_client, RequestType.UNREGISTER_KV_CACHE, [self.instance_id] ).result() self.mq_client.close() # Helper functions def _update_and_get_finished_store( self, ) -> set[str]: """Converge the internal states about finished stores and returns the 'safe finished store request ids' back """ safe_finished_s = self.finished_stores.intersection(self.previously_finished) self.finished_stores.difference_update(self.previously_finished) self.previously_finished.difference_update(safe_finished_s) return safe_finished_s def _create_key(self, block_hash: bytes) -> IPCCacheEngineKey: """Convert a block hash to an IPC cache engine key""" return IPCCacheEngineKey( model_name=self.model_name, world_size=self.world_size, worker_id=self.worker_id, chunk_hash=block_hash, ) def _block_hashes_to_keys( self, block_hashes: list[bytes] ) -> list[IPCCacheEngineKey]: """Convert block hashes to IPC cache engine keys""" s = striding_block_hashes(block_hashes, self.blocks_in_chunk) return [self._create_key(block_hash) for block_hash in s]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/p2p/tensor_memory_pool.py
vllm/distributed/kv_transfer/kv_connector/v1/p2p/tensor_memory_pool.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import atexit import ctypes import math from dataclasses import dataclass import torch from vllm.logger import init_logger logger = init_logger(__name__) @dataclass class MemoryBlock: size: int addr: int """A memory pool for managing pinned host memory allocations for tensors. This class implements a buddy allocation system to efficiently manage pinned host memory for tensor storage. It supports allocation, deallocation, and tensor storage/retrieval operations. Key Features: - Uses power-of-two block sizes for efficient buddy allocation - Supports splitting and merging of memory blocks - Provides methods to store CUDA tensors in pinned host memory - Allows loading tensors from pinned memory back to device - Automatically cleans up memory on destruction Attributes: max_block_size (int): Maximum block size (rounded to nearest power of two) min_block_size (int): Minimum block size (rounded to nearest power of two) free_lists (dict): Dictionary of free memory blocks by size allocated_blocks (dict): Dictionary of currently allocated blocks base_tensor (torch.Tensor): Base pinned memory tensor base_address (int): Base memory address of the pinned memory region Example: >>> pool = TensorMemoryPool(max_block_size=1024*1024) >>> tensor = torch.randn(100, device='cuda') >>> addr = pool.store_tensor(tensor) >>> loaded_tensor = pool.load_tensor(addr, tensor.dtype, ... tensor.shape, 'cuda') >>> pool.free(addr) """ class TensorMemoryPool: """Initializes the memory pool with given size constraints. Args: max_block_size (int): Maximum size of memory blocks to manage min_block_size (int, optional): Minimum size of memory blocks to manage. Defaults to 512. Raises: ValueError: If block sizes are invalid or max_block_size is less than min_block_size """ def __init__(self, max_block_size: int, min_block_size: int = 512): if max_block_size <= 0 or min_block_size <= 0: raise ValueError("Block sizes must be positive") if max_block_size < min_block_size: raise ValueError("Max block size must be greater than min block size") self.max_block_size = self._round_to_power_of_two(max_block_size) self.min_block_size = self._round_to_power_of_two(min_block_size) self.free_lists: dict[int, dict[int, MemoryBlock]] = {} self.allocated_blocks: dict[int, MemoryBlock] = {} self._initialize_free_lists() self._allocate_pinned_memory() atexit.register(self.cleanup) def _round_to_power_of_two(self, size: int) -> int: return 1 << (size - 1).bit_length() def _initialize_free_lists(self): size = self.max_block_size while size >= self.min_block_size: self.free_lists[size] = {} size //= 2 def _allocate_pinned_memory(self): self.base_tensor = torch.empty( self.max_block_size // 4, dtype=torch.float32, pin_memory=True ) self.base_address = self.base_tensor.data_ptr() initial_block = MemoryBlock(size=self.max_block_size, addr=self.base_address) self.free_lists[self.max_block_size][initial_block.addr] = initial_block logger.debug( "TensorMemoryPool, base_address:%d, max_block_size:%d", self.base_address, self.max_block_size, ) def allocate(self, size: int) -> int: """Allocates a memory block of at least the requested size. Args: size (int): Minimum size of memory to allocate Returns: int: Address of the allocated memory block Raises: ValueError: If size is invalid or insufficient memory is available """ if size <= 0: raise ValueError("Allocation size must be positive") required_size = self._round_to_power_of_two(max(size, self.min_block_size)) if required_size > self.max_block_size: raise ValueError("Requested size exceeds maximum block size") current_size = required_size while current_size <= self.max_block_size: if self.free_lists[current_size]: _, block = self.free_lists[current_size].popitem() self._split_block(block, required_size) self.allocated_blocks[block.addr] = block return block.addr current_size *= 2 raise ValueError("Insufficient memory") def _split_block(self, block: MemoryBlock, required_size: int): while block.size > required_size and block.size // 2 >= self.min_block_size: buddy_size = block.size // 2 buddy_addr = block.addr + buddy_size buddy = MemoryBlock(size=buddy_size, addr=buddy_addr) block.size = buddy_size self.free_lists[buddy_size][buddy.addr] = buddy def free(self, addr: int): """Frees an allocated memory block. Args: addr (int): Address of the block to free Raises: ValueError: If address is invalid or not allocated """ if addr not in self.allocated_blocks: raise ValueError("Invalid address to free") block = self.allocated_blocks.pop(addr) self._merge_buddies(block) def _merge_buddies(self, block: MemoryBlock): MAX_MERGE_DEPTH = 30 depth = 0 while depth < MAX_MERGE_DEPTH: buddy_offset = ( block.size if (block.addr - self.base_address) % (2 * block.size) == 0 else -block.size ) buddy_addr = block.addr + buddy_offset buddy = self.free_lists[block.size].get(buddy_addr) if buddy: del self.free_lists[buddy.size][buddy.addr] merged_addr = min(block.addr, buddy.addr) merged_size = block.size * 2 block = MemoryBlock(size=merged_size, addr=merged_addr) depth += 1 else: break self.free_lists[block.size][block.addr] = block def store_tensor(self, tensor: torch.Tensor) -> int: """Stores a CUDA tensor in pinned host memory. Args: tensor (torch.Tensor): CUDA tensor to store Returns: int: Address where the tensor is stored Raises: ValueError: If tensor is not on CUDA or allocation fails """ if not tensor.is_cuda: raise ValueError("Only CUDA tensors can be stored") size = tensor.element_size() * tensor.numel() addr = self.allocate(size) block = self.allocated_blocks[addr] if block.size < size: self.free(addr) raise ValueError( f"Allocated block size {block.size} is smaller than " f"required size {size}" ) try: buffer = (ctypes.c_byte * block.size).from_address(block.addr) cpu_tensor = torch.frombuffer( buffer, dtype=tensor.dtype, count=tensor.numel() ).reshape(tensor.shape) except ValueError as err: self.free(addr) raise ValueError(f"Failed to create tensor view: {err}") from err cpu_tensor.copy_(tensor) return addr def load_tensor( self, addr: int, dtype: torch.dtype, shape: tuple[int, ...], device: torch.device, ) -> torch.Tensor: """Loads a tensor from pinned host memory to the specified device. Args: addr (int): Address where tensor is stored dtype (torch.dtype): Data type of the tensor shape (tuple[int, ...]): Shape of the tensor device: Target device for the loaded tensor Returns: torch.Tensor: The loaded tensor on the specified device Raises: ValueError: If address is invalid or sizes don't match """ if addr not in self.allocated_blocks: raise ValueError("Invalid address to load") block = self.allocated_blocks[addr] num_elements = math.prod(shape) dtype_size = torch.tensor([], dtype=dtype).element_size() required_size = num_elements * dtype_size if required_size > block.size: raise ValueError("Requested tensor size exceeds block size") buffer = (ctypes.c_byte * block.size).from_address(block.addr) cpu_tensor = torch.frombuffer(buffer, dtype=dtype, count=num_elements).reshape( shape ) cuda_tensor = torch.empty(shape, dtype=dtype, device=device) cuda_tensor.copy_(cpu_tensor) return cuda_tensor def cleanup(self): """Cleans up all memory resources and resets the pool state.""" self.free_lists.clear() self.allocated_blocks.clear() if hasattr(self, "base_tensor"): del self.base_tensor def __del__(self): self.cleanup()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_connector.py
vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_connector.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Optional import regex as re import torch from vllm.attention.backends.abstract import AttentionMetadata from vllm.config import VllmConfig from vllm.distributed.kv_transfer.kv_connector.v1.base import ( KVConnectorBase_V1, KVConnectorMetadata, KVConnectorRole, ) from vllm.distributed.kv_transfer.kv_connector.v1.p2p.p2p_nccl_engine import ( P2pNcclEngine, ) from vllm.distributed.parallel_state import get_world_group from vllm.logger import init_logger from vllm.v1.attention.backends.mla.common import MLACommonMetadata from vllm.v1.core.sched.output import SchedulerOutput if TYPE_CHECKING: from vllm.forward_context import ForwardContext from vllm.v1.core.kv_cache_manager import KVCacheBlocks from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.request import Request logger = init_logger(__name__) @dataclass class ReqMeta: # Request Id request_id: str # Request block ids block_ids: torch.Tensor # Request num tokens num_tokens: int @staticmethod def make_meta( request_id: str, token_ids: list[int], block_ids: list[int], block_size: int ) -> "ReqMeta": block_ids_tensor = torch.tensor(block_ids) return ReqMeta( request_id=request_id, block_ids=block_ids_tensor, num_tokens=len(token_ids), ) @dataclass class P2pNcclConnectorMetadata(KVConnectorMetadata): requests: list[ReqMeta] def __init__(self): self.requests = [] def add_request( self, request_id: str, token_ids: list[int], block_ids: list[int], block_size: int, ) -> None: self.requests.append( ReqMeta.make_meta(request_id, token_ids, block_ids, block_size) ) class P2pNcclConnector(KVConnectorBase_V1): def __init__( self, vllm_config: "VllmConfig", role: KVConnectorRole, kv_cache_config: Optional["KVCacheConfig"] = None, ): super().__init__( vllm_config=vllm_config, role=role, kv_cache_config=kv_cache_config, ) self._block_size = vllm_config.cache_config.block_size self._requests_need_load: dict[str, Any] = {} self.is_producer = self._kv_transfer_config.is_kv_producer self.chunked_prefill: dict[str, tuple[list[int], list[int] | None]] = {} self._rank = get_world_group().rank if role == KVConnectorRole.WORKER else 0 self._local_rank = ( get_world_group().local_rank if role == KVConnectorRole.WORKER else 0 ) self.p2p_nccl_engine = ( P2pNcclEngine( local_rank=self._local_rank, config=self._kv_transfer_config, hostname="", port_offset=self._rank, ) if role == KVConnectorRole.WORKER else None ) # ============================== # Worker-side methods # ============================== def start_load_kv(self, forward_context: "ForwardContext", **kwargs: Any) -> None: """Start loading the KV cache from the connector buffer to vLLM's paged KV buffer. Args: forward_context (ForwardContext): the forward context. **kwargs: additional arguments for the load operation Note: The number of elements in kv_caches and layer_names should be the same. """ # Only consumer/decode loads KV Cache if self.is_producer: return assert self.p2p_nccl_engine is not None attn_metadata = forward_context.attn_metadata if attn_metadata is None: return def inject_kv_into_layer( layer: torch.Tensor, kv_cache: torch.Tensor, block_ids: torch.Tensor, request_id: str, ) -> None: """ Inject KV cache data into a given attention layer tensor. This function updates `layer` in-place with values from `kv_cache`, handling different backend layouts: - MLA (Multi-Linear Attention) or FlashInfer: KV tensors are indexed along the first dimension. - FlashAttention: KV tensors are indexed along the second dimension. If the number of provided block IDs does not match the number of KV blocks, only the overlapping portion is updated, and a warning is logged. Args: layer (torch.Tensor): The attention layer KV tensor to update. kv_cache (torch.Tensor): The KV cache tensor to inject. block_ids (torch.Tensor): Indices of the blocks to update. request_id (str): Request identifier used for logging. Returns: None. The function modifies `layer` in-place. """ if ( isinstance(attn_metadata, MLACommonMetadata) or layer.shape[1] == 2 ): # MLA or FlashInfer num_block = kv_cache.shape[0] self.check_tensors_except_dim(layer, kv_cache, 0) if len(block_ids) == num_block: layer[block_ids, ...] = kv_cache else: layer[block_ids[:num_block], ...] = kv_cache logger.warning( "🚧kv_cache does not match, block_ids:%d, " "num_block:%d, request_id:%s", len(block_ids), num_block, request_id, ) elif layer.shape[0] == 2: # FlashAttention num_block = kv_cache.shape[1] self.check_tensors_except_dim(layer, kv_cache, 1) if len(block_ids) == num_block: layer[:, block_ids, ...] = kv_cache else: layer[:, block_ids[:num_block], ...] = kv_cache logger.warning( "🚧kv_cache does not match, block_ids:%d, " "num_block:%d, request_id:%s", len(block_ids), num_block, request_id, ) # Get the metadata metadata: KVConnectorMetadata = self._get_connector_metadata() assert isinstance(metadata, P2pNcclConnectorMetadata) if metadata is None: return # Load the KV for each request each layer for request in metadata.requests: request_id = request.request_id ip, port = self.parse_request_id(request_id, False) remote_address = ip + ":" + str(port + self._rank) for layer_name in forward_context.no_compile_layers: layer = forward_context.no_compile_layers[layer_name] # Only process layers that have kv_cache # attribute (attention layers) Skip non-attention # layers like FusedMoE kv_cache = getattr(layer, "kv_cache", None) if kv_cache is None: continue layer = kv_cache[forward_context.virtual_engine] kv_cache = self.p2p_nccl_engine.recv_tensor( request.request_id + "#" + layer_name, remote_address ) if kv_cache is None: logger.warning("🚧kv_cache is None, %s", request.request_id) continue inject_kv_into_layer( layer, kv_cache, request.block_ids, request.request_id ) def wait_for_layer_load(self, layer_name: str) -> None: """Blocking until the KV for a specific layer is loaded into vLLM's paged buffer. This interface will be useful for layer-by-layer pipelining. Args: layer_name: the name of that layer """ return def save_kv_layer( self, layer_name: str, kv_layer: torch.Tensor, attn_metadata: AttentionMetadata, **kwargs: Any, ) -> None: """Start saving the KV cache of the layer from vLLM's paged buffer to the connector. Args: layer_name (str): the name of the layer. kv_layer (torch.Tensor): the paged KV buffer of the current layer in vLLM. attn_metadata (AttentionMetadata): the attention metadata. **kwargs: additional arguments for the save operation. """ # Only producer/prefill saves KV Cache if not self.is_producer: return assert self.p2p_nccl_engine is not None def extract_kv_from_layer( layer: torch.Tensor, block_ids: torch.Tensor, ) -> torch.Tensor: """ Extract KV cache slices from a given attention layer tensor. This function handles multiple backend layouts: - MLA (Multi-Linear Attention) or FlashInfer: KV tensors are indexed along the first dimension. - FlashAttention: KV tensors are indexed along the second dimension. Args: layer (torch.Tensor): The KV cache from the attention layer. block_ids (torch.Tensor): Indices of blocks to extract. Returns: torch.Tensor: A tensor containing the extracted KV slices. Returns None if the layout is unsupported. """ if ( isinstance(attn_metadata, MLACommonMetadata) or layer.shape[1] == 2 ): # MLA or FlashInfer return layer[block_ids, ...] if layer.shape[0] == 2: # FlashAttention return layer[:, block_ids, ...] return None connector_metadata = self._get_connector_metadata() assert isinstance(connector_metadata, P2pNcclConnectorMetadata) for request in connector_metadata.requests: request_id = request.request_id ip, port = self.parse_request_id(request_id, True) remote_address = ip + ":" + str(port + self._rank) kv_cache = extract_kv_from_layer(kv_layer, request.block_ids) self.p2p_nccl_engine.send_tensor( request_id + "#" + layer_name, kv_cache, remote_address ) def wait_for_save(self): if self.is_producer: assert self.p2p_nccl_engine is not None self.p2p_nccl_engine.wait_for_sent() def get_finished( self, finished_req_ids: set[str], **kwargs: Any ) -> tuple[set[str] | None, set[str] | None]: """ Notifies worker-side connector ids of requests that have finished generating tokens. Returns: ids of requests that have finished asynchronous transfer, tuple of (sending/saving ids, recving/loading ids). The finished saves/sends req ids must belong to a set provided in a call to this method (this call or a prior one). """ assert self.p2p_nccl_engine is not None no_compile_layers = self._vllm_config.compilation_config.static_forward_context return self.p2p_nccl_engine.get_finished(finished_req_ids, no_compile_layers) # ============================== # Scheduler-side methods # ============================== def get_num_new_matched_tokens( self, request: "Request", num_computed_tokens: int, ) -> tuple[int, bool]: """ Get number of new tokens that can be loaded from the external KV cache beyond the num_computed_tokens. Args: request (Request): the request object. num_computed_tokens (int): the number of locally computed tokens for this request Returns: the number of tokens that can be loaded from the external KV cache beyond what is already computed. """ if self.is_producer: return 0, False prompt_token_ids = request.prompt_token_ids or [] num_external_tokens = len(prompt_token_ids) - 1 - num_computed_tokens if num_external_tokens < 0: num_external_tokens = 0 return num_external_tokens, False def update_state_after_alloc( self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int ): """ Update KVConnector state after block allocation. """ if not self.is_producer and num_external_tokens > 0: self._requests_need_load[request.request_id] = ( request, blocks.get_block_ids()[0], ) def build_connector_meta( self, scheduler_output: SchedulerOutput, ) -> KVConnectorMetadata: """Build the connector metadata for this step. This function should NOT modify any fields in the scheduler_output. Also, calling this function will reset the state of the connector. Args: scheduler_output (SchedulerOutput): the scheduler output object. """ meta = P2pNcclConnectorMetadata() for new_req in scheduler_output.scheduled_new_reqs: if self.is_producer: num_scheduled_tokens = (scheduler_output.num_scheduled_tokens)[ new_req.req_id ] num_tokens = num_scheduled_tokens + new_req.num_computed_tokens # the request's prompt is chunked prefill if num_tokens < len(new_req.prompt_token_ids or []): # 'CachedRequestData' has no attribute 'prompt_token_ids' self.chunked_prefill[new_req.req_id] = ( new_req.block_ids[0], new_req.prompt_token_ids, ) continue # the request's prompt is not chunked prefill meta.add_request( request_id=new_req.req_id, token_ids=new_req.prompt_token_ids or [], block_ids=new_req.block_ids[0], block_size=self._block_size, ) continue if new_req.req_id in self._requests_need_load: meta.add_request( request_id=new_req.req_id, token_ids=new_req.prompt_token_ids or [], block_ids=new_req.block_ids[0], block_size=self._block_size, ) self._requests_need_load.pop(new_req.req_id) cached_reqs = scheduler_output.scheduled_cached_reqs for i, req_id in enumerate(cached_reqs.req_ids): num_computed_tokens = cached_reqs.num_computed_tokens[i] new_block_ids = cached_reqs.new_block_ids[i] resumed_from_preemption = req_id in cached_reqs.resumed_req_ids if self.is_producer: num_scheduled_tokens = scheduler_output.num_scheduled_tokens[req_id] num_tokens = num_scheduled_tokens + num_computed_tokens assert req_id in self.chunked_prefill assert new_block_ids is not None block_ids = new_block_ids[0] if not resumed_from_preemption: block_ids = self.chunked_prefill[req_id][0] + block_ids prompt_token_ids = self.chunked_prefill[req_id][1] assert prompt_token_ids is not None # the request's prompt is chunked prefill again if num_tokens < len(prompt_token_ids): self.chunked_prefill[req_id] = (block_ids, prompt_token_ids) continue # the request's prompt is all prefilled finally meta.add_request( request_id=req_id, token_ids=prompt_token_ids, block_ids=block_ids, block_size=self._block_size, ) self.chunked_prefill.pop(req_id, None) continue # NOTE(rob): here we rely on the resumed requests being # the first N requests in the list scheduled_cache_reqs. if not resumed_from_preemption: break if req_id in self._requests_need_load: request, _ = self._requests_need_load.pop(req_id) total_tokens = num_computed_tokens + 1 token_ids = request.all_token_ids[:total_tokens] # NOTE(rob): For resumed req, new_block_ids is all # of the block_ids for the request. assert new_block_ids is not None block_ids = new_block_ids[0] meta.add_request( request_id=req_id, token_ids=token_ids, block_ids=block_ids, block_size=self._block_size, ) self._requests_need_load.clear() return meta def request_finished( self, request: "Request", block_ids: list[int], ) -> tuple[bool, dict[str, Any] | None]: """ Called when a request has finished, before its blocks are freed. Returns: True if the request is being saved/sent asynchronously and blocks should not be freed until the request_id is returned from get_finished(). Optional KVTransferParams to be included in the request outputs returned by the engine. """ self.chunked_prefill.pop(request.request_id, None) return False, None # ============================== # Static methods # ============================== @staticmethod def parse_request_id(request_id: str, is_prefill=True) -> tuple[str, int]: # Regular expression to match the string hostname and integer port if is_prefill: pattern = r"___decode_addr_(.*):(\d+)" else: pattern = r"___prefill_addr_(.*):(\d+)___" # Use re.search to find the pattern in the request_id match = re.search(pattern, request_id) if match: # Extract the ranks ip = match.group(1) port = int(match.group(2)) return ip, port raise ValueError(f"Request id {request_id} does not contain hostname and port") @staticmethod def check_tensors_except_dim(tensor1, tensor2, dim): shape1 = tensor1.size() shape2 = tensor2.size() if len(shape1) != len(shape2) or not all( s1 == s2 for i, (s1, s2) in enumerate(zip(shape1, shape2)) if i != dim ): raise NotImplementedError( "Currently, only symmetric TP is supported. Asymmetric TP, PP," "and others will be supported in future PRs." )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/p2p/__init__.py
vllm/distributed/kv_transfer/kv_connector/v1/p2p/__init__.py
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_engine.py
vllm/distributed/kv_transfer/kv_connector/v1/p2p/p2p_nccl_engine.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import json import logging import os import threading import time from collections import deque from contextlib import contextmanager from dataclasses import dataclass from typing import Any import msgpack import torch import zmq from vllm.config.kv_transfer import KVTransferConfig from vllm.distributed.device_communicators.pynccl_wrapper import ( NCCLLibrary, buffer_type, cudaStream_t, ncclComm_t, ncclDataTypeEnum, ) from vllm.distributed.kv_transfer.kv_connector.v1.p2p.tensor_memory_pool import ( # noqa: E501 TensorMemoryPool, ) from vllm.utils.network_utils import get_ip from vllm.utils.torch_utils import current_stream logger = logging.getLogger(__name__) DEFAULT_MEM_POOL_SIZE_GB = 32 @contextmanager def set_p2p_nccl_context(num_channels: str): original_values: dict[str, Any] = {} env_vars = [ "NCCL_MAX_NCHANNELS", "NCCL_MIN_NCHANNELS", "NCCL_CUMEM_ENABLE", "NCCL_BUFFSIZE", "NCCL_PROTO", # LL,LL128,SIMPLE "NCCL_ALGO", # RING,TREE ] for var in env_vars: original_values[var] = os.environ.get(var) logger.info("set_p2p_nccl_context, original_values: %s", original_values) try: os.environ["NCCL_MAX_NCHANNELS"] = num_channels os.environ["NCCL_MIN_NCHANNELS"] = num_channels os.environ["NCCL_CUMEM_ENABLE"] = "1" yield finally: for var in env_vars: if original_values[var] is not None: os.environ[var] = original_values[var] else: os.environ.pop(var, None) @dataclass class SendQueueItem: tensor_id: str remote_address: str tensor: torch.Tensor class P2pNcclEngine: def __init__( self, local_rank: int, config: KVTransferConfig, hostname: str = "", port_offset: int = 0, library_path: str | None = None, ) -> None: self.config = config self.rank = port_offset self.local_rank = local_rank self.device = torch.device(f"cuda:{self.local_rank}") self.nccl = NCCLLibrary(library_path) if not hostname: hostname = get_ip() port = int(self.config.kv_port) + port_offset if port == 0: raise ValueError("Port cannot be 0") self._hostname = hostname self._port = port # Each card corresponds to a ZMQ address. self.zmq_address = f"{self._hostname}:{self._port}" # If `proxy_ip` or `proxy_port` is `""`, # then the ping thread will not be enabled. proxy_ip = self.config.get_from_extra_config("proxy_ip", "") proxy_port = self.config.get_from_extra_config("proxy_port", "") if proxy_ip == "" or proxy_port == "": self.proxy_address = "" self.http_address = "" else: self.proxy_address = proxy_ip + ":" + proxy_port # the `http_port` must be consistent with the port of OpenAI. http_port = self.config.get_from_extra_config("http_port", None) if http_port is None: example_cfg = { "kv_connector": "P2pNcclConnector", "kv_connector_extra_config": {"http_port": 8000}, } example = ( f"--port=8000 --kv-transfer-config='{json.dumps(example_cfg)}'" ) raise ValueError( "kv_connector_extra_config.http_port is required. " f"Example: {example}" ) self.http_address = f"{self._hostname}:{http_port}" self.context = zmq.Context() self.router_socket = self.context.socket(zmq.ROUTER) self.router_socket.bind(f"tcp://{self.zmq_address}") self.poller = zmq.Poller() self.poller.register(self.router_socket, zmq.POLLIN) self.send_store_cv = threading.Condition() self.send_queue_cv = threading.Condition() self.recv_store_cv = threading.Condition() self.send_stream = torch.cuda.Stream() self.recv_stream = torch.cuda.Stream() mem_pool_size_gb = float( self.config.get_from_extra_config( "mem_pool_size_gb", DEFAULT_MEM_POOL_SIZE_GB ) ) self.pool = TensorMemoryPool( max_block_size=int(mem_pool_size_gb * 1024**3) ) # GB # The sending type includes tree mutually exclusive options: # PUT, GET, PUT_ASYNC. self.send_type = self.config.get_from_extra_config("send_type", "PUT_ASYNC") if self.send_type == "GET": # tensor_id: torch.Tensor self.send_store: dict[str, torch.Tensor] = {} else: # PUT or PUT_ASYNC # tensor_id: torch.Tensor self.send_queue: deque[SendQueueItem] = deque() if self.send_type == "PUT_ASYNC": self._send_thread = threading.Thread( target=self.send_async, daemon=True ) self._send_thread.start() # tensor_id: torch.Tensor/(addr, dtype, shape) self.recv_store: dict[str, Any] = {} self.recv_request_id_to_tensor_ids: dict[str, set[str]] = {} self.send_request_id_to_tensor_ids: dict[str, set[str]] = {} self.socks: dict[str, Any] = {} # remote_address: client socket self.comms: dict[str, Any] = {} # remote_address: (ncclComm_t, rank) self.buffer_size = 0 self.buffer_size_threshold = float(self.config.kv_buffer_size) self.nccl_num_channels = self.config.get_from_extra_config( "nccl_num_channels", "8" ) self._listener_thread = threading.Thread( target=self.listen_for_requests, daemon=True ) self._listener_thread.start() self._ping_thread = None if port_offset == 0 and self.proxy_address != "": self._ping_thread = threading.Thread(target=self.ping, daemon=True) self._ping_thread.start() logger.info( "💯P2pNcclEngine init, rank:%d, local_rank:%d, http_address:%s, " "zmq_address:%s, proxy_address:%s, send_type:%s, buffer_size_" "threshold:%.2f, nccl_num_channels:%s", self.rank, self.local_rank, self.http_address, self.zmq_address, self.proxy_address, self.send_type, self.buffer_size_threshold, self.nccl_num_channels, ) def create_connect(self, remote_address: str | None = None): assert remote_address is not None if remote_address not in self.socks: sock = self.context.socket(zmq.DEALER) sock.setsockopt_string(zmq.IDENTITY, self.zmq_address) sock.connect(f"tcp://{remote_address}") self.socks[remote_address] = sock if remote_address in self.comms: logger.info( "👋comm exists, remote_address:%s, comms:%s", remote_address, self.comms, ) return sock, self.comms[remote_address] unique_id = self.nccl.ncclGetUniqueId() data = {"cmd": "NEW", "unique_id": bytes(unique_id.internal)} sock.send(msgpack.dumps(data)) with torch.cuda.device(self.device): rank = 0 with set_p2p_nccl_context(self.nccl_num_channels): comm: ncclComm_t = self.nccl.ncclCommInitRank(2, unique_id, rank) self.comms[remote_address] = (comm, rank) logger.info( "🤝ncclCommInitRank Success, %s👉%s, MyRank:%s", self.zmq_address, remote_address, rank, ) return self.socks[remote_address], self.comms[remote_address] def send_tensor( self, tensor_id: str, tensor: torch.Tensor, remote_address: str | None = None, ) -> bool: if remote_address is None: with self.recv_store_cv: self.recv_store[tensor_id] = tensor self.recv_store_cv.notify() return True item = SendQueueItem( tensor_id=tensor_id, remote_address=remote_address, tensor=tensor ) if self.send_type == "PUT": return self.send_sync(item) if self.send_type == "PUT_ASYNC": with self.send_queue_cv: self.send_queue.append(item) self.send_queue_cv.notify() return True # GET with self.send_store_cv: tensor_size = tensor.element_size() * tensor.numel() if tensor_size > self.buffer_size_threshold: logger.warning( "❗[GET]tensor_id:%s, tensor_size:%d, is greater than" "buffer size threshold :%d, skip send to %s, rank:%d", tensor_id, tensor_size, self.buffer_size_threshold, remote_address, self.rank, ) return False while self.buffer_size + tensor_size > self.buffer_size_threshold: assert len(self.send_store) > 0 oldest_tensor_id = next(iter(self.send_store)) oldest_tensor = self.send_store.pop(oldest_tensor_id) oldest_tensor_size = ( oldest_tensor.element_size() * oldest_tensor.numel() ) self.buffer_size -= oldest_tensor_size logger.debug( "⛔[GET]Send to %s, tensor_id:%s, tensor_size:%d," " buffer_size:%d, oldest_tensor_size:%d, rank:%d", remote_address, tensor_id, tensor_size, self.buffer_size, oldest_tensor_size, self.rank, ) self.send_store[tensor_id] = tensor self.buffer_size += tensor_size logger.debug( "🔵[GET]Send to %s, tensor_id:%s, tensor_size:%d, " "shape:%s, rank:%d, buffer_size:%d(%.2f%%)", remote_address, tensor_id, tensor_size, tensor.shape, self.rank, self.buffer_size, self.buffer_size / self.buffer_size_threshold * 100, ) return True def recv_tensor( self, tensor_id: str, remote_address: str | None = None, ) -> torch.Tensor: if self.send_type == "PUT" or self.send_type == "PUT_ASYNC": start_time = time.time() with self.recv_store_cv: while tensor_id not in self.recv_store: self.recv_store_cv.wait() tensor = self.recv_store[tensor_id] if tensor is not None: if isinstance(tensor, tuple): addr, dtype, shape = tensor tensor = self.pool.load_tensor(addr, dtype, shape, self.device) else: self.buffer_size -= tensor.element_size() * tensor.numel() else: duration = time.time() - start_time logger.warning( "🔴[PUT]Recv From %s, tensor_id:%s, duration:%.3fms, rank:%d", remote_address, tensor_id, duration * 1000, self.rank, ) return tensor # GET if remote_address is None: return None if remote_address not in self.socks: self.create_connect(remote_address) sock = self.socks[remote_address] comm, rank = self.comms[remote_address] data = {"cmd": "GET", "tensor_id": tensor_id} sock.send(msgpack.dumps(data)) message = sock.recv() data = msgpack.loads(message) if data["ret"] != 0: logger.warning( "🔴[GET]Recv From %s, tensor_id: %s, ret: %d", remote_address, tensor_id, data["ret"], ) return None with torch.cuda.stream(self.recv_stream): tensor = torch.empty( data["shape"], dtype=getattr(torch, data["dtype"]), device=self.device ) self.recv(comm, tensor, rank ^ 1, self.recv_stream) return tensor def listen_for_requests(self): while True: socks = dict(self.poller.poll()) if self.router_socket not in socks: continue remote_address, message = self.router_socket.recv_multipart() data = msgpack.loads(message) if data["cmd"] == "NEW": unique_id = self.nccl.unique_id_from_bytes(bytes(data["unique_id"])) with torch.cuda.device(self.device): rank = 1 with set_p2p_nccl_context(self.nccl_num_channels): comm: ncclComm_t = self.nccl.ncclCommInitRank( 2, unique_id, rank ) self.comms[remote_address.decode()] = (comm, rank) logger.info( "🤝ncclCommInitRank Success, %s👈%s, MyRank:%s", self.zmq_address, remote_address.decode(), rank, ) elif data["cmd"] == "PUT": tensor_id = data["tensor_id"] try: with torch.cuda.stream(self.recv_stream): tensor = torch.empty( data["shape"], dtype=getattr(torch, data["dtype"]), device=self.device, ) self.router_socket.send_multipart([remote_address, b"0"]) comm, rank = self.comms[remote_address.decode()] self.recv(comm, tensor, rank ^ 1, self.recv_stream) tensor_size = tensor.element_size() * tensor.numel() if self.buffer_size + tensor_size > self.buffer_size_threshold: # Store Tensor in memory pool addr = self.pool.store_tensor(tensor) tensor = (addr, tensor.dtype, tensor.shape) logger.warning( "🔴[PUT]Recv Tensor, Out Of Threshold, " "%s👈%s, data:%s, addr:%d", self.zmq_address, remote_address.decode(), data, addr, ) else: self.buffer_size += tensor_size except torch.cuda.OutOfMemoryError: self.router_socket.send_multipart([remote_address, b"1"]) tensor = None logger.warning( "🔴[PUT]Recv Tensor, Out Of Memory, %s👈%s, data:%s", self.zmq_address, remote_address.decode(), data, ) with self.recv_store_cv: self.recv_store[tensor_id] = tensor self.have_received_tensor_id(tensor_id) self.recv_store_cv.notify() elif data["cmd"] == "GET": tensor_id = data["tensor_id"] with self.send_store_cv: tensor = self.send_store.pop(tensor_id, None) if tensor is not None: data = { "ret": 0, "shape": tensor.shape, "dtype": str(tensor.dtype).replace("torch.", ""), } # LRU self.send_store[tensor_id] = tensor self.have_sent_tensor_id(tensor_id) else: data = {"ret": 1} self.router_socket.send_multipart([remote_address, msgpack.dumps(data)]) if data["ret"] == 0: comm, rank = self.comms[remote_address.decode()] self.send(comm, tensor.to(self.device), rank ^ 1, self.send_stream) else: logger.warning( "🚧Unexpected, Received message from %s, data:%s", remote_address, data, ) def have_sent_tensor_id(self, tensor_id: str): request_id = tensor_id.split("#")[0] if request_id not in self.send_request_id_to_tensor_ids: self.send_request_id_to_tensor_ids[request_id] = set() self.send_request_id_to_tensor_ids[request_id].add(tensor_id) def have_received_tensor_id(self, tensor_id: str): request_id = tensor_id.split("#")[0] if request_id not in self.recv_request_id_to_tensor_ids: self.recv_request_id_to_tensor_ids[request_id] = set() self.recv_request_id_to_tensor_ids[request_id].add(tensor_id) def send_async(self): while True: with self.send_queue_cv: while not self.send_queue: self.send_queue_cv.wait() item = self.send_queue.popleft() if not self.send_queue: self.send_queue_cv.notify() self.send_sync(item) def wait_for_sent(self): if self.send_type == "PUT_ASYNC": start_time = time.time() with self.send_queue_cv: while self.send_queue: self.send_queue_cv.wait() duration = time.time() - start_time logger.debug( "🚧[PUT_ASYNC]It took %.3fms to wait for the send_queue" " to be empty, rank:%d", duration * 1000, self.rank, ) def send_sync(self, item: SendQueueItem) -> bool: if item.remote_address is None: return False if item.remote_address not in self.socks: self.create_connect(item.remote_address) tensor = item.tensor sock = self.socks[item.remote_address] comm, rank = self.comms[item.remote_address] data = { "cmd": "PUT", "tensor_id": item.tensor_id, "shape": tensor.shape, "dtype": str(tensor.dtype).replace("torch.", ""), } sock.send(msgpack.dumps(data)) response = sock.recv() if response != b"0": logger.error( "🔴Send Tensor, Peer Out Of Memory/Threshold, %s 👉 %s, " "MyRank:%s, data:%s, tensor:%s, size:%fGB, response:%s", self.zmq_address, item.remote_address, rank, data, tensor.shape, tensor.element_size() * tensor.numel() / 1024**3, response.decode(), ) return False self.send(comm, tensor.to(self.device), rank ^ 1, self.send_stream) if self.send_type == "PUT_ASYNC": self.have_sent_tensor_id(item.tensor_id) return True def get_finished( self, finished_req_ids: set[str], no_compile_layers ) -> tuple[set[str] | None, set[str] | None]: """ Notifies worker-side connector ids of requests that have finished generating tokens. Returns: ids of requests that have finished asynchronous transfer, tuple of (sending/saving ids, recving/loading ids). The finished saves/sends req ids must belong to a set provided in a call to this method (this call or a prior one). """ # Clear the buffer upon request completion. for request_id in finished_req_ids: for layer_name in no_compile_layers: tensor_id = request_id + "#" + layer_name if tensor_id in self.recv_store: with self.recv_store_cv: tensor = self.recv_store.pop(tensor_id, None) self.send_request_id_to_tensor_ids.pop(request_id, None) self.recv_request_id_to_tensor_ids.pop(request_id, None) if isinstance(tensor, tuple): addr, _, _ = tensor self.pool.free(addr) # TODO:Retrieve requests that have already sent the KV cache. finished_sending: set[str] = set() # TODO:Retrieve requests that have already received the KV cache. finished_recving: set[str] = set() return finished_sending or None, finished_recving or None def ping(self): sock = self.context.socket(zmq.DEALER) sock.setsockopt_string(zmq.IDENTITY, self.zmq_address) logger.debug("ping start, zmq_address:%s", self.zmq_address) sock.connect(f"tcp://{self.proxy_address}") data = { "type": "P" if self.config.is_kv_producer else "D", "http_address": self.http_address, "zmq_address": self.zmq_address, } while True: sock.send(msgpack.dumps(data)) time.sleep(3) def send(self, comm, tensor: torch.Tensor, dst: int, stream=None): assert tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {tensor.device}" ) if stream is None: stream = current_stream() with torch.cuda.stream(stream): self.nccl.ncclSend( buffer_type(tensor.data_ptr()), tensor.numel(), ncclDataTypeEnum.from_torch(tensor.dtype), dst, comm, cudaStream_t(stream.cuda_stream), ) stream.synchronize() def recv(self, comm, tensor: torch.Tensor, src: int, stream=None): assert tensor.device == self.device, ( f"this nccl communicator is created to work on {self.device}, " f"but the input tensor is on {tensor.device}" ) if stream is None: stream = current_stream() with torch.cuda.stream(stream): self.nccl.ncclRecv( buffer_type(tensor.data_ptr()), tensor.numel(), ncclDataTypeEnum.from_torch(tensor.dtype), src, comm, cudaStream_t(stream.cuda_stream), ) stream.synchronize() def close(self) -> None: self._listener_thread.join() if self.send_type == "PUT_ASYNC": self._send_thread.join() if self._ping_thread is not None: self._ping_thread.join()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/collection_utils.py
vllm/utils/collection_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Contains helpers that are applied to collections. This is similar in concept to the `collections` module. """ from collections import defaultdict from collections.abc import Callable, Generator, Hashable, Iterable, Mapping from typing import Generic, Literal, TypeVar from typing_extensions import TypeIs, assert_never T = TypeVar("T") _K = TypeVar("_K", bound=Hashable) _V = TypeVar("_V") class LazyDict(Mapping[str, _V], Generic[_V]): """ Evaluates dictionary items only when they are accessed. Adapted from: https://stackoverflow.com/a/47212782/5082708 """ def __init__(self, factory: dict[str, Callable[[], _V]]): self._factory = factory self._dict: dict[str, _V] = {} def __getitem__(self, key: str) -> _V: if key not in self._dict: if key not in self._factory: raise KeyError(key) self._dict[key] = self._factory[key]() return self._dict[key] def __setitem__(self, key: str, value: Callable[[], _V]): self._factory[key] = value def __iter__(self): return iter(self._factory) def __len__(self): return len(self._factory) def as_list(maybe_list: Iterable[T]) -> list[T]: """Convert iterable to list, unless it's already a list.""" return maybe_list if isinstance(maybe_list, list) else list(maybe_list) def as_iter(obj: T | Iterable[T]) -> Iterable[T]: if isinstance(obj, str) or not isinstance(obj, Iterable): return [obj] # type: ignore[list-item] return obj def is_list_of( value: object, typ: type[T] | tuple[type[T], ...], *, check: Literal["first", "all"] = "first", ) -> TypeIs[list[T]]: if not isinstance(value, list): return False if check == "first": return len(value) == 0 or isinstance(value[0], typ) elif check == "all": return all(isinstance(v, typ) for v in value) assert_never(check) def chunk_list(lst: list[T], chunk_size: int) -> Generator[list[T]]: """Yield successive chunk_size chunks from lst.""" for i in range(0, len(lst), chunk_size): yield lst[i : i + chunk_size] def flatten_2d_lists(lists: Iterable[Iterable[T]]) -> list[T]: """Flatten a list of lists to a single list.""" return [item for sublist in lists for item in sublist] def full_groupby(values: Iterable[_V], *, key: Callable[[_V], _K]): """ Unlike [`itertools.groupby`][], groups are not broken by non-contiguous data. """ groups = defaultdict[_K, list[_V]](list) for value in values: groups[key(value)].append(value) return groups.items() def swap_dict_values(obj: dict[_K, _V], key1: _K, key2: _K) -> None: """Swap values between two keys.""" v1 = obj.get(key1) v2 = obj.get(key2) if v1 is not None: obj[key2] = v1 else: obj.pop(key2, None) if v2 is not None: obj[key1] = v2 else: obj.pop(key1, None)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/torch_utils.py
vllm/utils/torch_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib import importlib.metadata import os import threading from collections.abc import Callable, Collection from functools import lru_cache from typing import TYPE_CHECKING, Any, TypeVar import numpy as np import numpy.typing as npt import torch from packaging import version from packaging.version import Version from torch.library import Library, infer_schema import vllm.envs as envs if TYPE_CHECKING: from vllm.config import ModelConfig from vllm.sequence import IntermediateTensors else: ModelConfig = object IntermediateTensors = object import logging logger = logging.getLogger(__name__) STR_DTYPE_TO_TORCH_DTYPE = { "float32": torch.float32, "half": torch.half, "float16": torch.float16, "bfloat16": torch.bfloat16, "float": torch.float, "fp8": torch.uint8, "fp8_e4m3": torch.uint8, "fp8_e5m2": torch.uint8, "int8": torch.int8, "fp8_inc": torch.float8_e4m3fn, "fp8_ds_mla": torch.uint8, } TORCH_DTYPE_TO_NUMPY_DTYPE = { torch.float16: np.float16, torch.float32: np.float32, torch.float64: np.float64, torch.uint8: np.uint8, torch.int32: np.int32, torch.int64: np.int64, } MODELOPT_TO_VLLM_KV_CACHE_DTYPE_MAP = { # TODO: Add more modelopt kv cache dtype # mappings here when it supported by some attention backend # (for example supports nvfp4). "fp8": "fp8_e4m3", } T = TypeVar("T") @contextlib.contextmanager def set_default_torch_dtype(dtype: torch.dtype): """Sets the default torch dtype to the given dtype.""" old_dtype = torch.get_default_dtype() torch.set_default_dtype(dtype) yield torch.set_default_dtype(old_dtype) @contextlib.contextmanager def set_default_torch_num_threads(num_threads: int): """Sets the default number of threads for PyTorch to the given value.""" old_num_threads = torch.get_num_threads() torch.set_num_threads(num_threads) yield torch.set_num_threads(old_num_threads) @contextlib.contextmanager def guard_cuda_initialization(): """Avoid unexpected CUDA initialization.""" from vllm.platforms import current_platform if not current_platform.is_cuda(): yield return old_value = os.environ.get("CUDA_VISIBLE_DEVICES") os.environ["CUDA_VISIBLE_DEVICES"] = "" try: yield except Exception as e: if "No CUDA GPUs are available" in str(e): err_msg = "CUDA initialization is blocked." else: err_msg = str(e) raise RuntimeError(err_msg) from e finally: if old_value is None: del os.environ["CUDA_VISIBLE_DEVICES"] else: os.environ["CUDA_VISIBLE_DEVICES"] = old_value def get_dtype_size(dtype: torch.dtype) -> int: """Get the size of the data type in bytes.""" return torch.tensor([], dtype=dtype).element_size() # bool = 0, int = 1, float = 2, complex = 3 def _get_precision_level(dtype: torch.dtype) -> int: # NOTE: Complex dtypes return `is_floating_point=False` return (dtype != torch.bool) + dtype.is_floating_point + dtype.is_complex * 2 def is_lossless_cast(src_dtype: torch.dtype, tgt_dtype: torch.dtype): """ Test whether it is lossless to cast a tensor from `src_dtype` to `tgt_dtype`. """ if src_dtype == tgt_dtype: return True src_level = _get_precision_level(src_dtype) tgt_level = _get_precision_level(tgt_dtype) if src_level < tgt_level: return True if src_level > tgt_level: return False # Compare integral types if not src_dtype.is_floating_point and not src_dtype.is_complex: src_info = torch.iinfo(src_dtype) tgt_info = torch.iinfo(tgt_dtype) return src_info.min >= tgt_info.min and src_info.max <= tgt_info.max # Compare floating-point types src_info = torch.finfo(src_dtype) tgt_info = torch.finfo(tgt_dtype) return ( src_info.min >= tgt_info.min and src_info.max <= tgt_info.max and src_info.resolution >= tgt_info.resolution ) def common_broadcastable_dtype(dtypes: Collection[torch.dtype]): """ Get the common `dtype` where all of the other `dtypes` can be cast to it without losing any information. """ return max( dtypes, key=lambda dtype: sum(is_lossless_cast(dt, dtype) for dt in dtypes), ) def _generate_random_fp8( tensor: torch.Tensor, low: float, high: float, ) -> None: # NOTE(zhaoyang): Due to NaN and Inf representation for fp8 data type, # it may occur Inf or NaN if we directly use torch.randint # to generate random data for fp8 data. # For example, s.11111.00 in fp8e5m2 format represents Inf. # | E4M3 | E5M2 # -----|-------------|------------------- # Inf | N/A | s.11111.00 # NaN | s.1111.111 | s.11111.{01,10,11} from vllm import _custom_ops as ops tensor_tmp = torch.empty_like(tensor, dtype=torch.float16) tensor_tmp.uniform_(low, high) ops.convert_fp8(tensor, tensor_tmp) del tensor_tmp def get_kv_cache_torch_dtype( cache_dtype: str | torch.dtype | None, model_dtype: str | torch.dtype | None = None, ) -> torch.dtype: if isinstance(cache_dtype, str): if cache_dtype == "auto": if isinstance(model_dtype, str) and model_dtype in STR_DTYPE_TO_TORCH_DTYPE: torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[model_dtype] elif isinstance(model_dtype, torch.dtype): torch_dtype = model_dtype else: raise ValueError(f"Invalid model dtype: {model_dtype}") elif cache_dtype in STR_DTYPE_TO_TORCH_DTYPE: torch_dtype = STR_DTYPE_TO_TORCH_DTYPE[cache_dtype] else: raise ValueError(f"Invalid kv cache dtype: {cache_dtype}") elif isinstance(cache_dtype, torch.dtype): torch_dtype = cache_dtype else: raise ValueError(f"Invalid kv cache dtype: {cache_dtype}") return torch_dtype def get_kv_cache_quant_algo_string(quant_cfg: dict[str, Any]) -> str | None: """Get the KV cache quantization algorithm string from the quantization config. Maps various FP8 format names to vLLM's standard cache dtype strings. Returns None if no kv_cache_quant_algo is specified. Returns "auto" if the value is not recognized/supported. """ # Mapping from model config values to vLLM cache_dtype strings quant_method = quant_cfg.get("quant_method", "") if quant_method.startswith("modelopt"): quantization_inner = quant_cfg.get("quantization", quant_cfg) # Check if quant config is specified and use kv cache quant algo kv_algo = quantization_inner.get("kv_cache_quant_algo") or quant_cfg.get( "kv_cache_quant_algo" ) if isinstance(kv_algo, str): kv_algo_lower = kv_algo.lower() # Try to map to vLLM's standard format if kv_algo_lower in MODELOPT_TO_VLLM_KV_CACHE_DTYPE_MAP: return MODELOPT_TO_VLLM_KV_CACHE_DTYPE_MAP[kv_algo_lower] else: # Unknown/unsupported format - return "auto" as safe fallback logger.warning( "WARNING: Unknown kv_cache_quant_algo '%s' in model " "config. Supported values: %s. Falling back to 'auto'.", kv_algo, list(MODELOPT_TO_VLLM_KV_CACHE_DTYPE_MAP.keys()), ) return "auto" return None def get_kv_cache_quant_algo_dtype(quant_cfg: dict[str, Any]) -> torch.dtype | None: """Get the KV cache quantization algorithm dtype from the quantization config.""" kv_algo_str = get_kv_cache_quant_algo_string(quant_cfg) if kv_algo_str is not None and kv_algo_str != "auto": # Only convert if we have a valid dtype string (not "auto" fallback) return STR_DTYPE_TO_TORCH_DTYPE[kv_algo_str] return None def resolve_kv_cache_dtype_string( kv_cache_dtype: str, model_config: ModelConfig ) -> str: """Resolve 'auto' kv_cache_dtype to the actual string value from model config. Returns the resolved cache_dtype string. """ if kv_cache_dtype != "auto": return kv_cache_dtype hf_cfg = getattr(model_config, "hf_config", None) if hf_cfg is not None: quant_cfg = getattr(hf_cfg, "quantization_config", None) if quant_cfg is not None: kv_algo_str = get_kv_cache_quant_algo_string(quant_cfg) if kv_algo_str is not None: return kv_algo_str # Default to auto (will be handled by downstream code) return "auto" def kv_cache_dtype_str_to_dtype( kv_cache_dtype: str, model_config: ModelConfig ) -> torch.dtype: if kv_cache_dtype == "auto": # Model config may not be specified for unit tests, default to float16 return model_config.dtype if model_config else torch.half return STR_DTYPE_TO_TORCH_DTYPE[kv_cache_dtype] def create_kv_caches_with_random_flash( num_blocks: int, block_size: int, num_layers: int, num_heads: int, head_size: int, cache_dtype: str | torch.dtype | None, model_dtype: str | torch.dtype | None = None, seed: int | None = None, device: str | None = "cuda", cache_layout: str | None = "NHD", ) -> tuple[list[torch.Tensor], list[torch.Tensor]]: from vllm.platforms import current_platform current_platform.seed_everything(seed) dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype) generic_kv_cache_shape = (num_blocks, 2, block_size, num_heads, head_size) assert cache_layout in ("NHD", "HND") stride_order = (0, 1, 2, 3, 4) if cache_layout == "NHD" else (0, 1, 3, 2, 4) kv_cache_allocation_shape = tuple(generic_kv_cache_shape[i] for i in stride_order) scale = head_size**-0.5 key_caches: list[torch.Tensor] = [] value_caches: list[torch.Tensor] = [] for _ in range(num_layers): key_value_cache = torch.empty( size=kv_cache_allocation_shape, dtype=dtype, device=device ).permute(*stride_order) if cache_dtype in ["auto", "half", "bfloat16", "float"]: key_value_cache.uniform_(-scale, scale) elif cache_dtype == "fp8": _generate_random_fp8(key_value_cache, -scale, scale) else: raise ValueError(f"Does not support key cache of type {cache_dtype}") key_caches.append(key_value_cache[:, 0]) value_caches.append(key_value_cache[:, 1]) return key_caches, value_caches def create_kv_caches_with_random( num_blocks: int, block_size: int, num_layers: int, num_heads: int, head_size: int, cache_dtype: str | torch.dtype | None, model_dtype: str | torch.dtype | None = None, seed: int | None = None, device: str | None = "cuda", ) -> tuple[list[torch.Tensor], list[torch.Tensor]]: if cache_dtype == "fp8" and head_size % 16: raise ValueError( f"Does not support key cache of type fp8 with head_size {head_size}" ) from vllm.platforms import current_platform current_platform.seed_everything(seed) dtype = get_kv_cache_torch_dtype(cache_dtype, model_dtype) scale = head_size**-0.5 x = 16 // torch.tensor([], dtype=dtype).element_size() key_cache_shape = (num_blocks, num_heads, head_size // x, block_size, x) key_caches: list[torch.Tensor] = [] for _ in range(num_layers): key_cache = torch.empty(size=key_cache_shape, dtype=dtype, device=device) if cache_dtype in ["auto", "half", "bfloat16", "float"]: key_cache.uniform_(-scale, scale) elif cache_dtype == "fp8": _generate_random_fp8(key_cache, -scale, scale) else: raise ValueError(f"Does not support key cache of type {cache_dtype}") key_caches.append(key_cache) value_cache_shape = (num_blocks, num_heads, head_size, block_size) value_caches: list[torch.Tensor] = [] for _ in range(num_layers): value_cache = torch.empty(size=value_cache_shape, dtype=dtype, device=device) if cache_dtype in ["auto", "half", "bfloat16", "float"]: value_cache.uniform_(-scale, scale) elif cache_dtype == "fp8": _generate_random_fp8(value_cache, -scale, scale) else: raise ValueError(f"Does not support value cache of type {cache_dtype}") value_caches.append(value_cache) return key_caches, value_caches def async_tensor_h2d( data: list, dtype: torch.dtype, target_device: str | torch.device, pin_memory: bool, ) -> torch.Tensor: """Asynchronously create a tensor and copy it from host to device.""" t = torch.tensor(data, dtype=dtype, pin_memory=pin_memory, device="cpu") return t.to(device=target_device, non_blocking=True) def make_ndarray_with_pad( x: list[list[T]], pad: T, dtype: npt.DTypeLike, *, max_len: int | None = None, ) -> npt.NDArray: """ Make a padded array from 2D inputs. The padding is applied to the end of each inner list until it reaches `max_len`. """ if max_len is None: # Unlike for most functions, map is faster than a genexpr over `len` max_len = max(map(len, x), default=0) padded_x = np.full((len(x), max_len), pad, dtype=dtype) for ind, blocktb in enumerate(x): assert len(blocktb) <= max_len padded_x[ind, : len(blocktb)] = blocktb return padded_x def make_tensor_with_pad( x: list[list[T]], pad: T, dtype: torch.dtype, *, max_len: int | None = None, device: str | torch.device | None = None, pin_memory: bool = False, ) -> torch.Tensor: """ Make a padded tensor from 2D inputs. The padding is applied to the end of each inner list until it reaches `max_len`. """ np_dtype = TORCH_DTYPE_TO_NUMPY_DTYPE[dtype] padded_x = make_ndarray_with_pad(x, pad, np_dtype, max_len=max_len) tensor = torch.from_numpy(padded_x).to(device) if pin_memory: tensor = tensor.pin_memory() return tensor prev_set_stream = torch.cuda.set_stream _current_stream_tls = threading.local() def _patched_set_stream(stream: torch.cuda.Stream) -> None: _current_stream_tls.value = stream prev_set_stream(stream) torch.cuda.set_stream = _patched_set_stream class _StreamPlaceholder: def __init__(self): self.synchronize = lambda: None def current_stream() -> torch.cuda.Stream: """ replace `torch.cuda.current_stream()` with `vllm.utils.current_stream()`. it turns out that `torch.cuda.current_stream()` is quite expensive, as it will construct a new stream object at each call. here we patch `torch.cuda.set_stream` to keep track of the current stream directly, so that we can avoid calling `torch.cuda.current_stream()`. the underlying hypothesis is that we do not call `torch._C._cuda_setStream` from C/C++ code. """ from vllm.platforms import current_platform if not hasattr(_current_stream_tls, "value") or _current_stream_tls.value is None: # when this function is called before any stream is set, # we return the default stream. # On ROCm using the default 0 stream in combination with RCCL # is hurting performance. # On CUDA, we capture and replay cudagraph on the same stream, # so we need to avoid using the default stream as well. The default # stream cannot be used for cudagraph capture, see # https://github.com/pytorch/pytorch/blob/42ad9edfb754743fdae3276ade43de000beb4f60/aten/src/ATen/cuda/CUDAGraph.cpp#L77 # for more details. Therefore, we create a dedicated stream per process. if current_platform.is_rocm() or current_platform.is_cuda(): # torch.cuda.set_stream here is the alias of _pathed_set_stream torch.cuda.set_stream(torch.cuda.Stream()) elif current_platform.is_cpu(): _current_stream_tls.value = _StreamPlaceholder() else: current_stream = current_platform.current_stream if current_stream is not None: _current_stream_tls.value = current_stream() else: raise ValueError( "Fail to set current stream, current platform " "may not support current_stream with torch API" ) return _current_stream_tls.value # Global auxilary stream for running operations in background streams. # We have single global auxilary stream to avoid an explosion of streams # for every layer (and make profiling look sane). # # aux_stream() is currently used for: # - MoE shared_expert overlap with router _aux_stream: torch.cuda.Stream | None = None def aux_stream() -> torch.cuda.Stream | None: """ Ensures aux_stream is initialized only once """ global _aux_stream from vllm.platforms import current_platform if _aux_stream is None and current_platform.is_cuda_alike(): _aux_stream = torch.cuda.Stream() return _aux_stream @lru_cache(maxsize=8) def _cuda_device_count_stateless(cuda_visible_devices: str | None = None) -> int: # Note: cuda_visible_devices is not used, but we keep it as an argument for # LRU Cache purposes. # Code below is based on # https://github.com/pytorch/pytorch/blob/ # c1cd946818442aca8c7f812b16d187ce1586c3bc/ # torch/cuda/__init__.py#L831C1-L831C17 import torch.cuda import torch.version from vllm.platforms import current_platform if not torch.cuda._is_compiled(): return 0 if current_platform.is_rocm(): # ROCm uses amdsmi instead of nvml for stateless device count # This requires a sufficiently modern version of Torch 2.4.0 raw_count = ( torch.cuda._device_count_amdsmi() if (hasattr(torch.cuda, "_device_count_amdsmi")) else -1 ) else: raw_count = torch.cuda._device_count_nvml() r = torch._C._cuda_getDeviceCount() if raw_count < 0 else raw_count return r def cuda_device_count_stateless() -> int: """Get number of CUDA devices, caching based on the value of CUDA_VISIBLE_DEVICES at the time of call. This should be used instead of torch.cuda.device_count() unless CUDA_VISIBLE_DEVICES has already been set to the desired value.""" # This can be removed and simply replaced with torch.cuda.get_device_count # after https://github.com/pytorch/pytorch/pull/122815 is released. return _cuda_device_count_stateless(envs.CUDA_VISIBLE_DEVICES) def weak_ref_tensor(tensor: Any) -> Any: """ Create a weak reference to a tensor. The new tensor will share the same data as the original tensor, but will not keep the original tensor alive. """ if isinstance(tensor, torch.Tensor): return torch.ops._C.weak_ref_tensor(tensor) else: return tensor def weak_ref_tensors( tensors: torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor] | IntermediateTensors, ) -> torch.Tensor | list[Any] | tuple[Any] | Any: """ Convenience function to create weak references to tensors, for single tensor, list of tensors or tuple of tensors. """ if isinstance(tensors, torch.Tensor): return weak_ref_tensor(tensors) if isinstance(tensors, list): return [weak_ref_tensor(t) for t in tensors] if isinstance(tensors, tuple): return tuple(weak_ref_tensor(t) for t in tensors) # For IntermediateTensors used in pipeline parallelism from vllm.sequence import IntermediateTensors if isinstance(tensors, IntermediateTensors): ret = IntermediateTensors( {key: weak_ref_tensor(val) for key, val in tensors.tensors.items()} ) return ret raise ValueError("Invalid type for tensors") def get_cuda_view_from_cpu_tensor(cpu_tensor: torch.Tensor) -> torch.Tensor: """ Get a CUDA view of a CPU tensor using Unified Virtual Addressing (UVA). """ assert cpu_tensor.is_pinned(), "CPU tensor must be pinned" return torch.ops._C.get_cuda_view_from_cpu_tensor(cpu_tensor) # Helper function used in testing. def _is_torch_equal_or_newer(torch_version: str, target: str) -> bool: return version.parse(torch_version) >= version.parse(target) def is_torch_equal_or_newer(target: str) -> bool: """Check if the installed torch version is >= the target version. Args: target: a version string, like "2.6.0". Returns: Whether the condition meets. """ try: return _is_torch_equal_or_newer(str(torch.__version__), target) except Exception: # Fallback to PKG-INFO to load the package info, needed by the doc gen. return Version(importlib.metadata.version("torch")) >= Version(target) def _is_torch_equal(target: str) -> bool: assert target.count(".") == 2 torch_version = str(torch.__version__) torch_version = version.parse(torch_version) # torch version is like "2.6.0.dev20240101" or "2.6.0.dev20240101+cpu" # or "2.6.0+cu128" but never "2.6.0.1" return ( torch_version >= version.parse(target) and version.parse(target + ".1") > torch_version ) def is_torch_equal(target: str) -> bool: """Check if the installed torch version is == the target version. Args: target: a version string, like "2.6.0". Returns: Whether the condition meets. """ try: return _is_torch_equal(target) except Exception: return Version(importlib.metadata.version("torch")) == Version(target) # Using dynamo with vLLM doesn't really work well with PyTorch versions < 2.4.0. # In particular, the FakeScalarType is not supported for earlier versions of # PyTorch which breaks dynamo for any ops registered using ScalarType. def supports_dynamo() -> bool: return is_torch_equal_or_newer("2.4.0") # Supports xccl with PyTorch versions >= 2.8.0.dev for XPU platform def supports_xccl() -> bool: return ( is_torch_equal_or_newer("2.8.0.dev") and torch.distributed.is_xccl_available() ) # Some backends use pytorch version < 2.4.0 which doesn't # support `torch.library.custom_op`. def supports_custom_op() -> bool: return hasattr(torch.library, "custom_op") # create a library to hold the custom op vllm_lib = Library("vllm", "FRAGMENT") # noqa def direct_register_custom_op( op_name: str, op_func: Callable, mutates_args: list[str] | None = None, fake_impl: Callable | None = None, target_lib: Library | None = None, dispatch_key: str | None = None, tags: tuple[torch.Tag, ...] = (), ): """ `torch.library.custom_op` can have significant overhead because it needs to consider complicated dispatching logic. This function directly registers a custom op and dispatches it to the CUDA backend. See https://gist.github.com/youkaichao/ecbea9ec9fc79a45d2adce1784d7a9a5 for more details. By default, the custom op is registered to the vLLM library. If you want to register it to a different library, you can pass the library object to the `target_lib` argument. IMPORTANT: the lifetime of the operator is tied to the lifetime of the library object. If you want to bind the operator to a different library, make sure the library object is alive when the operator is used. """ if not supports_custom_op(): from vllm.platforms import current_platform assert not current_platform.is_cuda_alike(), ( "cuda platform needs torch>=2.4 to support custom op, " "chances are you are using an old version of pytorch " "or a custom build of pytorch. It is recommended to " "use vLLM in a fresh new environment and let it install " "the required dependencies." ) return if mutates_args is None: mutates_args = [] if dispatch_key is None: from vllm.platforms import current_platform dispatch_key = current_platform.dispatch_key schema_str = infer_schema(op_func, mutates_args=mutates_args) my_lib = target_lib or vllm_lib my_lib.define(op_name + schema_str, tags=tags) my_lib.impl(op_name, op_func, dispatch_key=dispatch_key) if fake_impl is not None: my_lib._register_fake(op_name, fake_impl)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/async_utils.py
vllm/utils/async_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Contains helpers related to asynchronous code. This is similar in concept to the `asyncio` module. """ import asyncio import contextlib from asyncio import FIRST_COMPLETED, AbstractEventLoop, Future, Task from collections.abc import AsyncGenerator, Awaitable, Callable from concurrent.futures import Executor, ThreadPoolExecutor from functools import partial from typing import TYPE_CHECKING, TypeVar from transformers.tokenization_utils_base import BatchEncoding from typing_extensions import ParamSpec P = ParamSpec("P") T = TypeVar("T") class AsyncMicrobatchTokenizer: """Asynchronous tokenizer with micro-batching. Pulls pending encode/decode requests from a queue and batches them up to reduce overhead. A single-thread ThreadPoolExecutor is used so the event loop stays responsive. """ def __init__( self, tokenizer, max_batch_size: int = 32, batch_wait_timeout_s: float = 0.002, ) -> None: self.tokenizer = tokenizer self.max_batch_size = max_batch_size self.batch_wait_timeout_s = batch_wait_timeout_s self._loop = asyncio.get_running_loop() self._queues: dict[ tuple, asyncio.Queue[tuple[str, dict, Future] | tuple[list[int], Future]], ] = {} self._batcher_tasks: list[Task] = [] # Single-thread executor for blocking tokenizer calls. self._executor = ThreadPoolExecutor(max_workers=1) # === Public async API === async def __call__(self, prompt, **kwargs): result_future: Future = self._loop.create_future() key = self._queue_key("encode", kwargs) queue = self._get_queue(self._loop, key) await queue.put((prompt, kwargs, result_future)) return await result_future async def decode(self, token_ids, **kwargs): result_future: Future = self._loop.create_future() key = self._queue_key("decode", kwargs) queue = self._get_queue(self._loop, key) await queue.put((token_ids, result_future)) return await result_future # === Internal helpers === def _get_queue( self, loop: asyncio.AbstractEventLoop, key: tuple ) -> asyncio.Queue[tuple[str, dict, Future] | tuple[list[int], Future]]: """Get the request queue for the given operation key, creating a new queue and batcher task if needed.""" queue = self._queues.get(key) if queue is None: self._queues[key] = queue = asyncio.Queue() if key[0] == "encode": can_batch = key[1] != "other" coro = self._batch_encode_loop(queue, can_batch) else: assert key[0] == "decode", f"Unknown operation type: {key[0]}." coro = self._batch_decode_loop(queue) self._batcher_tasks.append(loop.create_task(coro)) return queue async def _batch_encode_loop(self, queue: asyncio.Queue, can_batch: bool): """Batch incoming encode requests for efficiency.""" while True: prompt, kwargs, result_future = await queue.get() prompts = [prompt] kwargs_list = [kwargs] result_futures = [result_future] deadline = self._loop.time() + self.batch_wait_timeout_s while len(prompts) < self.max_batch_size: timeout = deadline - self._loop.time() if timeout <= 0: break try: prompt, kwargs, result_future = await asyncio.wait_for( queue.get(), timeout ) prompts.append(prompt) result_futures.append(result_future) if not can_batch: kwargs_list.append(kwargs) except asyncio.TimeoutError: break try: # If every request uses identical kwargs we can run a single # batched tokenizer call for a big speed-up. if can_batch and len(prompts) > 1: batch_encode_fn = partial(self.tokenizer, prompts, **kwargs) results = await self._loop.run_in_executor( self._executor, batch_encode_fn ) for i, fut in enumerate(result_futures): if not fut.done(): data = {k: v[i] for k, v in results.items()} fut.set_result(BatchEncoding(data)) else: encode_fn = lambda prompts=prompts, kwargs=kwargs_list: [ self.tokenizer(p, **kw) for p, kw in zip(prompts, kwargs) ] results = await self._loop.run_in_executor( self._executor, encode_fn ) for fut, res in zip(result_futures, results): if not fut.done(): fut.set_result(res) except Exception as e: for fut in result_futures: if not fut.done(): fut.set_exception(e) async def _batch_decode_loop(self, queue: asyncio.Queue): """Batch incoming decode requests for efficiency.""" while True: token_ids, result_future = await queue.get() token_ids_list = [token_ids] result_futures = [result_future] deadline = self._loop.time() + self.batch_wait_timeout_s while len(token_ids_list) < self.max_batch_size: timeout = deadline - self._loop.time() if timeout <= 0: break try: token_ids, result_future = await asyncio.wait_for( queue.get(), timeout ) token_ids_list.append(token_ids) result_futures.append(result_future) except asyncio.TimeoutError: break try: # Perform a single batched decode call for all requests results = await self._loop.run_in_executor( self._executor, self.tokenizer.batch_decode, token_ids_list ) for fut, res in zip(result_futures, results): if not fut.done(): fut.set_result(res) except Exception as e: for fut in result_futures: if not fut.done(): fut.set_exception(e) def _queue_key(self, op: str, kwargs: dict) -> tuple: """ Return a normalized key describing operation + kwargs. - `add_special_tokens`: {True/False} - `truncation`: {True/False} - If `truncation` is False (`max_length` is None), returns a key for a can_batch queue. - If `truncation` is True and `max_length` is None or equals `tokenizer.model_max_length`, returns a key for a can_batch queue. - Otherwise, returns a key for a cannot_batch queue. Examples: - Decode: ("decode",) - Encode typical: ("encode", add_special_tokens, bool_truncation, max_length_label) - Fallback: ("encode", "other") """ if op == "decode": return ("decode",) add_special_tokens = kwargs.get("add_special_tokens", True) truncation = kwargs.get("truncation", False) max_length = kwargs.get("max_length") if not truncation: return "encode", add_special_tokens, False, None model_max = getattr(self.tokenizer, "model_max_length", None) if max_length is None or (model_max is not None and max_length == model_max): return "encode", add_special_tokens, True, "model_max" return "encode", "other" def __del__(self): if ( (tasks := getattr(self, "_batcher_tasks", None)) and (loop := getattr(self, "_loop", None)) and not loop.is_closed() ): def cancel_tasks(): for task in tasks: task.cancel() loop.call_soon_threadsafe(cancel_tasks) def cancel_task_threadsafe(task: Task): if task and not task.done(): run_in_loop(task.get_loop(), task.cancel) def make_async( func: Callable[P, T], executor: Executor | None = None, ) -> Callable[P, Awaitable[T]]: """ Take a blocking function, and run it on in an executor thread. This function prevents the blocking function from blocking the asyncio event loop. The code in this function needs to be thread safe. """ def _async_wrapper(*args: P.args, **kwargs: P.kwargs) -> Future[T]: loop = asyncio.get_event_loop() p_func = partial(func, *args, **kwargs) return loop.run_in_executor(executor=executor, func=p_func) return _async_wrapper def run_in_loop(loop: AbstractEventLoop, function: Callable, *args): if in_loop(loop): function(*args) elif not loop.is_closed(): loop.call_soon_threadsafe(function, *args) def in_loop(event_loop: AbstractEventLoop) -> bool: try: return asyncio.get_running_loop() == event_loop except RuntimeError: return False # A hack to pass mypy if TYPE_CHECKING: def anext(it: AsyncGenerator[T, None]): return it.__anext__() async def merge_async_iterators( *iterators: AsyncGenerator[T, None], ) -> AsyncGenerator[tuple[int, T], None]: """Merge multiple asynchronous iterators into a single iterator. This method handle the case where some iterators finish before others. When it yields, it yields a tuple (i, item) where i is the index of the iterator that yields the item. """ if len(iterators) == 1: # Fast-path single iterator case. async for item in iterators[0]: yield 0, item return loop = asyncio.get_running_loop() awaits = {loop.create_task(anext(it)): (i, it) for i, it in enumerate(iterators)} try: while awaits: done, _ = await asyncio.wait(awaits.keys(), return_when=FIRST_COMPLETED) for d in done: pair = awaits.pop(d) try: item = await d i, it = pair awaits[loop.create_task(anext(it))] = pair yield i, item except StopAsyncIteration: pass finally: # Cancel any remaining iterators for f, (_, it) in awaits.items(): with contextlib.suppress(BaseException): f.cancel() await it.aclose() async def collect_from_async_generator(iterator: AsyncGenerator[T, None]) -> list[T]: """Collect all items from an async generator into a list.""" items = [] async for item in iterator: items.append(item) return items
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/jsontree.py
vllm/utils/jsontree.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Helper functions to work with nested JSON structures.""" from collections.abc import Callable, Iterable from functools import reduce from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar, overload if TYPE_CHECKING: import torch from vllm.multimodal.inputs import BatchedTensorInputs _T = TypeVar("_T") _U = TypeVar("_U") JSONTree: TypeAlias = ( dict[str, "JSONTree[_T]"] | list["JSONTree[_T]"] | tuple["JSONTree[_T]", ...] | _T ) """A nested JSON structure where the leaves need not be JSON-serializable.""" _JSONTree: TypeAlias = ( dict[str, "JSONTree[_T]"] | list["JSONTree[_T]"] | tuple["JSONTree[_T]", ...] | dict[str, _T] | list[_T] | tuple[_T, ...] | _T ) """ Same as `JSONTree` but with additional `Union` members to satisfy overloads. """ def json_iter_leaves(value: JSONTree[_T]) -> Iterable[_T]: """Iterate through each leaf in a nested JSON structure.""" if isinstance(value, dict): for v in value.values(): yield from json_iter_leaves(v) elif isinstance(value, (list, tuple)): for v in value: yield from json_iter_leaves(v) else: yield value @overload def json_map_leaves( func: Callable[["torch.Tensor"], "torch.Tensor"], value: "BatchedTensorInputs", ) -> "BatchedTensorInputs": ... @overload def json_map_leaves( func: Callable[[_T], _U], value: _T | dict[str, _T], ) -> _U | dict[str, _U]: ... @overload def json_map_leaves( func: Callable[[_T], _U], value: _T | list[_T], ) -> _U | list[_U]: ... @overload def json_map_leaves( func: Callable[[_T], _U], value: _T | tuple[_T, ...], ) -> _U | tuple[_U, ...]: ... @overload def json_map_leaves( func: Callable[[_T], _U], value: JSONTree[_T], ) -> JSONTree[_U]: ... def json_map_leaves( func: Callable[[_T], _U], value: Any, ) -> "BatchedTensorInputs" | _JSONTree[_U]: """Apply a function to each leaf in a nested JSON structure.""" if isinstance(value, dict): return {k: json_map_leaves(func, v) for k, v in value.items()} # type: ignore elif isinstance(value, list): return [json_map_leaves(func, v) for v in value] # type: ignore elif isinstance(value, tuple): return tuple(json_map_leaves(func, v) for v in value) else: return func(value) @overload def json_reduce_leaves( func: Callable[[_T, _T], _T], value: _T | dict[str, _T], /, ) -> _T: ... @overload def json_reduce_leaves( func: Callable[[_T, _T], _T], value: _T | list[_T], /, ) -> _T: ... @overload def json_reduce_leaves( func: Callable[[_T, _T], _T], value: _T | tuple[_T, ...], /, ) -> _T: ... @overload def json_reduce_leaves( func: Callable[[_T, _T], _T], value: JSONTree[_T], /, ) -> _T: ... @overload def json_reduce_leaves( func: Callable[[_U, _T], _U], value: JSONTree[_T], initial: _U, /, ) -> _U: ... def json_reduce_leaves( func: Callable[[_T, _T], _T] | Callable[[_U, _T], _U], value: _JSONTree[_T], initial: _U = ..., # type: ignore[assignment] /, ) -> _T | _U: """ Apply a function of two arguments cumulatively to each leaf in a nested JSON structure, from left to right, so as to reduce the sequence to a single value. """ if initial is ...: return reduce(func, json_iter_leaves(value)) # type: ignore return reduce(func, json_iter_leaves(value), initial) # type: ignore def json_count_leaves(value: JSONTree[_T]) -> int: """Count the number of leaves in a nested JSON structure.""" return sum(1 for _ in json_iter_leaves(value))
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/serial_utils.py
vllm/utils/serial_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import base64 import io import math import sys from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Literal import numpy as np import torch from typing_extensions import assert_never if TYPE_CHECKING: from vllm import PoolingRequestOutput else: PoolingRequestOutput = Any sys_byteorder = sys.byteorder EMBED_DTYPE_TO_TORCH_DTYPE = { "float32": torch.float32, "float16": torch.float16, "bfloat16": torch.bfloat16, # I'm not sure if other platforms' CPUs support the fp8 data format. # EMBED_DTYPE only uses the fp8 data representation, # does not use fp8 computation, and only occurs on the CPU. # Apologize for any possible break. "fp8_e4m3": torch.float8_e4m3fn, "fp8_e5m2": torch.float8_e5m2, } EMBED_DTYPE_TO_N_BYTES = { "float32": 4, "float16": 2, "bfloat16": 2, "fp8_e4m3": 1, "fp8_e5m2": 1, } EMBED_DTYPE_TO_TORCH_DTYPE_VIEW = { "float32": torch.float32, "float16": torch.float16, # numpy does not support bfloat16 and fp8 "bfloat16": torch.float16, "fp8_e4m3": torch.uint8, "fp8_e5m2": torch.uint8, } EMBED_DTYPE_TO_NUMPY_DTYPE_VIEW = { "float32": np.float32, "float16": np.float16, # numpy does not support bfloat16 and fp8 "bfloat16": np.float16, "fp8_e4m3": np.uint8, "fp8_e5m2": np.uint8, } ENDIANNESS = ["native", "big", "little"] EmbedDType = Literal["float32", "float16", "bfloat16", "fp8_e4m3", "fp8_e5m2"] Endianness = Literal["native", "big", "little"] EncodingFormat = Literal["float", "base64", "bytes", "bytes_only"] def tensor2base64(x: torch.Tensor) -> str: with io.BytesIO() as buf: torch.save(x, buf) buf.seek(0) binary_data = buf.read() return base64.b64encode(binary_data).decode("utf-8") def tensor2binary( tensor: torch.Tensor, embed_dtype: EmbedDType, endianness: Endianness ) -> bytes: assert isinstance(tensor, torch.Tensor) assert embed_dtype in EMBED_DTYPE_TO_TORCH_DTYPE assert endianness in ENDIANNESS torch_dtype = EMBED_DTYPE_TO_TORCH_DTYPE[embed_dtype] torch_view_dtype = EMBED_DTYPE_TO_TORCH_DTYPE_VIEW[embed_dtype] np_array = ( tensor.to(torch_dtype).flatten().contiguous().view(torch_view_dtype).numpy() ) if endianness != "native" and endianness != sys_byteorder: np_array = np_array.byteswap() return np_array.tobytes() def binary2tensor( binary: bytes, shape: tuple[int, ...], embed_dtype: EmbedDType, endianness: Endianness, ) -> torch.Tensor: assert embed_dtype in EMBED_DTYPE_TO_TORCH_DTYPE assert embed_dtype in EMBED_DTYPE_TO_NUMPY_DTYPE_VIEW assert endianness in ENDIANNESS torch_dtype = EMBED_DTYPE_TO_TORCH_DTYPE[embed_dtype] np_dtype = EMBED_DTYPE_TO_NUMPY_DTYPE_VIEW[embed_dtype] np_array = np.frombuffer(binary, dtype=np_dtype).reshape(shape) if endianness != "native" and endianness != sys_byteorder: np_array = np_array.byteswap() return torch.from_numpy(np_array).view(torch_dtype) def encode_pooling_output( output: PoolingRequestOutput, encoding_format: EncodingFormat, embed_dtype: EmbedDType, endianness: Endianness, ) -> list[float] | str | bytes: if encoding_format == "float": return output.outputs.data.tolist() elif encoding_format == "base64": embedding_bytes = tensor2binary(output.outputs.data, embed_dtype, endianness) return base64.b64encode(embedding_bytes).decode("utf-8") elif encoding_format == "bytes" or encoding_format == "bytes_only": return tensor2binary(output.outputs.data, embed_dtype, endianness) assert_never(encoding_format) @dataclass class MetadataItem: index: int embed_dtype: EmbedDType endianness: Endianness start: int end: int shape: tuple[int, ...] def build_metadata_items( embed_dtype: EmbedDType, endianness: Endianness, shape: tuple[int, ...], n_request: int, ): n_bytes = EMBED_DTYPE_TO_N_BYTES[embed_dtype] size = math.prod(shape) items = [ MetadataItem( index=i, embed_dtype=embed_dtype, endianness=endianness, start=i * size * n_bytes, end=(i + 1) * size * n_bytes, shape=shape, ) for i in range(n_request) ] return items def encode_pooling_bytes( pooling_outputs: list[PoolingRequestOutput], embed_dtype: EmbedDType, endianness: Endianness, ): num_prompt_tokens = 0 items: list[dict[str, MetadataItem]] = [] body = [] offset = 0 for idx, output in enumerate(pooling_outputs): binary = tensor2binary( tensor=output.outputs.data, embed_dtype=embed_dtype, endianness=endianness, ) size = len(binary) item = { "index": idx, "embed_dtype": embed_dtype, "endianness": endianness, "start": offset, "end": offset + size, "shape": output.outputs.data.shape, } body.append(binary) items.append(item) prompt_token_ids = output.prompt_token_ids num_prompt_tokens += len(prompt_token_ids) offset += size usage = { "prompt_tokens": num_prompt_tokens, "total_tokens": num_prompt_tokens, } return body, items, usage def decode_pooling_output(items: list[MetadataItem], body: bytes) -> list[torch.Tensor]: items.sort(key=lambda x: x.index) tensor_list: list[torch.Tensor] = [] for item in items: binary = body[item.start : item.end] tensor = binary2tensor(binary, item.shape, item.embed_dtype, item.endianness) tensor_list.append(tensor) return tensor_list
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/mem_utils.py
vllm/utils/mem_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib import gc import time from collections.abc import Generator from dataclasses import dataclass, field from functools import cache import psutil import torch import torch.types from .mem_constants import GiB_bytes @cache def get_max_shared_memory_bytes(gpu: int = 0) -> int: """Returns the maximum shared memory per thread block in bytes.""" from vllm import _custom_ops as ops max_shared_mem = ops.get_max_shared_memory_per_block_device_attribute(gpu) # value 0 will cause MAX_SEQ_LEN become negative and test_attention.py # will fail assert max_shared_mem > 0, "max_shared_mem can not be zero" return int(max_shared_mem) def get_cpu_memory() -> int: """Returns the total CPU memory of the node in bytes.""" return psutil.virtual_memory().total class DeviceMemoryProfiler: def __init__(self, device: torch.types.Device | None = None): self.device = device def current_memory_usage(self) -> float: # Return the memory usage in bytes. from vllm.platforms import current_platform gc.collect() return current_platform.get_current_memory_usage(self.device) def __enter__(self): self.initial_memory = self.current_memory_usage() # This allows us to call methods of the context manager if needed return self def __exit__(self, exc_type, exc_val, exc_tb): self.final_memory = self.current_memory_usage() self.consumed_memory = self.final_memory - self.initial_memory # Force garbage collection gc.collect() @dataclass class MemorySnapshot: """Memory snapshot.""" torch_peak: int = 0 free_memory: int = 0 total_memory: int = 0 cuda_memory: int = 0 torch_memory: int = 0 non_torch_memory: int = 0 timestamp: float = 0.0 device: torch.types.Device = None auto_measure: bool = True def __post_init__(self) -> None: if self.device is None: from vllm.platforms import current_platform device_fn = current_platform.current_device assert device_fn is not None self.device_ = torch.device(device_fn()) else: self.device_ = torch.device(self.device) if self.auto_measure: self.measure() def measure(self) -> None: from vllm.platforms import current_platform device = self.device_ # we measure the torch peak memory usage via allocated_bytes, # rather than `torch.cuda.memory_reserved()` . # After `torch.cuda.reset_peak_memory_stats()`, # `torch.cuda.memory_reserved()` will keep growing, and only shrink # when we call `torch.cuda.empty_cache()` or OOM happens. self.torch_peak = torch.cuda.memory_stats(device).get( "allocated_bytes.all.peak", 0 ) self.free_memory, self.total_memory = torch.cuda.mem_get_info(device) shared_sysmem_device_mem_sms = ((8, 7), (11, 0), (12, 1)) # Orin, Thor, Spark if ( current_platform.is_cuda() and current_platform.get_device_capability(device.index) in shared_sysmem_device_mem_sms ): # On UMA (Orin, Thor and Spark) platform, # where both CPU and GPU rely on system memory, # the cudaMemGetInfo function shows the amount of free system memory # rather than what’s actually available. # In the case, # torch.cuda.mem_get_info() only reports "free" memory, # which can be lower than what is actually # available due to not including cache memory. # There’s also a comprehensive reference page # that explains how you can compute the proper value yourself. # https://docs.nvidia.com/cuda/cuda-for-tegra-appnote/#estimating-total-allocatable-device-memory-on-an-integrated-gpu-device self.free_memory = psutil.virtual_memory().available self.cuda_memory = self.total_memory - self.free_memory # torch.cuda.memory_reserved() is how many bytes # PyTorch gets from cuda (by calling cudaMalloc, etc.) # this is used to measure the non-torch memory usage self.torch_memory = torch.cuda.memory_reserved(device) self.non_torch_memory = self.cuda_memory - self.torch_memory self.timestamp = time.time() def __sub__(self, other: "MemorySnapshot") -> "MemorySnapshot": if self.device_ != other.device_: raise ValueError( "The two snapshots should be from the same device! " f"Found: {self.device_} vs. {other.device_}" ) return MemorySnapshot( torch_peak=self.torch_peak - other.torch_peak, free_memory=self.free_memory - other.free_memory, total_memory=self.total_memory - other.total_memory, cuda_memory=self.cuda_memory - other.cuda_memory, torch_memory=self.torch_memory - other.torch_memory, non_torch_memory=self.non_torch_memory - other.non_torch_memory, timestamp=self.timestamp - other.timestamp, device=self.device_, auto_measure=False, ) @dataclass class MemoryProfilingResult: """Memory profiling result. All numbers are in bytes.""" non_kv_cache_memory: int = 0 torch_peak_increase: int = 0 non_torch_increase: int = 0 weights_memory: float = 0 before_create: MemorySnapshot = field(default_factory=MemorySnapshot) before_profile: MemorySnapshot = field(default_factory=MemorySnapshot) after_profile: MemorySnapshot = field(default_factory=MemorySnapshot) profile_time: float = 0.0 def __repr__(self) -> str: return ( f"Memory profiling takes {self.profile_time:.2f} seconds. " f"Total non KV cache memory: " f"{(self.non_kv_cache_memory / GiB_bytes):.2f}GiB; " f"torch peak memory increase: " f"{(self.torch_peak_increase / GiB_bytes):.2f}GiB; " f"non-torch forward increase memory: " f"{(self.non_torch_increase / GiB_bytes):.2f}GiB; " f"weights memory: {(self.weights_memory / GiB_bytes):.2f}GiB." ) @contextlib.contextmanager def memory_profiling( baseline_snapshot: MemorySnapshot, weights_memory: int ) -> Generator[MemoryProfilingResult, None, None]: """Memory profiling context manager. baseline_snapshot: the memory snapshot before the current vLLM instance. weights_memory: memory used by PyTorch when loading the model weights. Note that, before loading the model weights, we also initialize the device and distributed environment, which may consume some memory. This part is not included in the weights_memory because PyTorch does not control it. The memory in one GPU can be classified into 3 categories: 1. memory used by anything other than the current vLLM instance. 2. memory used by torch in the current vLLM instance. 3. memory used in the current vLLM instance, but not by torch. A quantitive example: Before creating the current vLLM instance: category 1: 1 GiB category 2: 0 GiB category 3: 0 GiB After creating the current vLLM instance and loading the model, (i.e. before profiling): category 1: 1 GiB category 2: 2 GiB (model weights take 2 GiB) category 3: 0.5 GiB (memory used by NCCL) During profiling (peak): category 1: 1 GiB category 2: 4 GiB (peak activation tensors take 2 GiB) category 3: 1 GiB (memory used by NCCL + buffers for some attention backends) After profiling: category 1: 1 GiB category 2: 3 GiB (after garbage-collecting activation tensors) category 3: 1 GiB (memory used by NCCL + buffers for some attention backends) In this case, non-kv cache takes 5 GiB in total, including: a. 2 GiB used by the model weights (category 2) b. 2 GiB reserved for the peak activation tensors (category 2) c. 1 GiB used by non-torch components (category 3) The memory used for loading weights (a.) is directly given from the argument `weights_memory`. The increase of `torch.cuda.memory_stats()["allocated_bytes.all.peak"]` during profiling gives (b.). The increase of `non_torch_memory` from creating the current vLLM instance until after profiling to get (c.). """ # noqa gc.collect() torch.cuda.empty_cache() torch.cuda.reset_peak_memory_stats() result = MemoryProfilingResult() result.before_create = baseline_snapshot # the part of memory used for holding the model weights result.weights_memory = weights_memory result.before_profile.measure() yield result gc.collect() torch.cuda.empty_cache() result.after_profile.measure() diff_profile = result.after_profile - result.before_profile diff_from_create = result.after_profile - result.before_create result.torch_peak_increase = diff_profile.torch_peak result.non_torch_increase = diff_from_create.non_torch_memory result.profile_time = diff_profile.timestamp non_torch_memory = result.non_torch_increase peak_activation_memory = result.torch_peak_increase result.non_kv_cache_memory = ( non_torch_memory + peak_activation_memory + result.weights_memory ) # noqa
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/counter.py
vllm/utils/counter.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import threading class Counter: def __init__(self, start: int = 0) -> None: super().__init__() self.counter = start def __next__(self) -> int: i = self.counter self.counter += 1 return i def reset(self) -> None: self.counter = 0 class AtomicCounter: """An atomic, thread-safe counter""" def __init__(self, initial: int = 0) -> None: """Initialize a new atomic counter to given initial value""" super().__init__() self._value = initial self._lock = threading.Lock() @property def value(self) -> int: return self._value def inc(self, num: int = 1) -> int: """Atomically increment the counter by num and return the new value""" with self._lock: self._value += num return self._value def dec(self, num: int = 1) -> int: """Atomically decrement the counter by num and return the new value""" with self._lock: self._value -= num return self._value
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/registry.py
vllm/utils/registry.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from typing import Any, TypeVar _T = TypeVar("_T", bound=type) class ExtensionManager: """ A registry for managing pluggable extension classes. This class provides a simple mechanism to register and instantiate extension classes by name. It is commonly used to implement plugin systems where different implementations can be swapped at runtime. Examples: Basic usage with a registry instance: >>> FOO_REGISTRY = ExtensionManager() >>> @FOO_REGISTRY.register("my_foo_impl") ... class MyFooImpl(Foo): ... def __init__(self, value): ... self.value = value >>> foo_impl = FOO_REGISTRY.load("my_foo_impl", value=123) """ def __init__(self) -> None: """ Initialize an empty extension registry. """ self.name2class: dict[str, type] = {} def register(self, name: str): """ Decorator to register a class with the given name. """ def wrap(cls_to_register: _T) -> _T: self.name2class[name] = cls_to_register return cls_to_register return wrap def load(self, cls_name: str, *args, **kwargs) -> Any: """ Instantiate and return a registered extension class by name. """ cls = self.name2class.get(cls_name) assert cls is not None, f"Extension class {cls_name} not found" return cls(*args, **kwargs)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/platform_utils.py
vllm/utils/platform_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import multiprocessing from collections.abc import Sequence from concurrent.futures.process import ProcessPoolExecutor from functools import cache from typing import Any import torch def cuda_is_initialized() -> bool: """Check if CUDA is initialized.""" if not torch.cuda._is_compiled(): return False return torch.cuda.is_initialized() def xpu_is_initialized() -> bool: """Check if XPU is initialized.""" if not torch.xpu._is_compiled(): return False return torch.xpu.is_initialized() def get_cu_count(device_id: int = 0) -> int: """Returns the total number of compute units (CU) on single GPU.""" return torch.cuda.get_device_properties(device_id).multi_processor_count def cuda_get_device_properties( device, names: Sequence[str], init_cuda=False ) -> tuple[Any, ...]: """Get specified CUDA device property values without initializing CUDA in the current process.""" if init_cuda or cuda_is_initialized(): props = torch.cuda.get_device_properties(device) return tuple(getattr(props, name) for name in names) # Run in subprocess to avoid initializing CUDA as a side effect. mp_ctx = multiprocessing.get_context("fork") with ProcessPoolExecutor(max_workers=1, mp_context=mp_ctx) as executor: return executor.submit(cuda_get_device_properties, device, names, True).result() @cache def is_pin_memory_available() -> bool: from vllm.platforms import current_platform return current_platform.is_pin_memory_available() @cache def is_uva_available() -> bool: """Check if Unified Virtual Addressing (UVA) is available.""" # UVA requires pinned memory. # TODO: Add more requirements for UVA if needed. return is_pin_memory_available()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/system_utils.py
vllm/utils/system_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from __future__ import annotations import contextlib import multiprocessing import os import signal import sys from collections.abc import Callable, Iterator from pathlib import Path from typing import TextIO import psutil import vllm.envs as envs from vllm.logger import init_logger from vllm.ray.lazy_utils import is_in_ray_actor from .platform_utils import cuda_is_initialized, xpu_is_initialized logger = init_logger(__name__) CYAN = "\033[0;36m" RESET = "\033[0;0m" # Environment variable utilities def update_environment_variables(envs_dict: dict[str, str]): """Update multiple environment variables with logging.""" for k, v in envs_dict.items(): if k in os.environ and os.environ[k] != v: logger.warning( "Overwriting environment variable %s from '%s' to '%s'", k, os.environ[k], v, ) os.environ[k] = v @contextlib.contextmanager def set_env_var(key: str, value: str) -> Iterator[None]: """Temporarily set an environment variable.""" old = os.environ.get(key) os.environ[key] = value try: yield finally: if old is None: os.environ.pop(key, None) else: os.environ[key] = old @contextlib.contextmanager def suppress_stdout(): """ Suppress stdout from C libraries at the file descriptor level. Only suppresses stdout, not stderr, to preserve error messages. Suppression is disabled when VLLM_LOGGING_LEVEL is set to DEBUG. Example: with suppress_stdout(): # C library calls that would normally print to stdout torch.distributed.new_group(ranks, backend="gloo") """ # Don't suppress if logging level is DEBUG if envs.VLLM_LOGGING_LEVEL == "DEBUG": yield return stdout_fd = sys.stdout.fileno() stdout_dup = os.dup(stdout_fd) devnull_fd = os.open(os.devnull, os.O_WRONLY) try: sys.stdout.flush() os.dup2(devnull_fd, stdout_fd) yield finally: sys.stdout.flush() os.dup2(stdout_dup, stdout_fd) os.close(stdout_dup) os.close(devnull_fd) # File path utilities def unique_filepath(fn: Callable[[int], Path]) -> Path: """Generate a unique file path by trying incrementing integers. Note: This function has a TOCTOU race condition. Caller should use atomic operations (e.g., open with 'x' mode) when creating the file to ensure thread safety. """ i = 0 while True: p = fn(i) if not p.exists(): return p i += 1 # Process management utilities def _maybe_force_spawn(): """Check if we need to force the use of the `spawn` multiprocessing start method. """ if os.environ.get("VLLM_WORKER_MULTIPROC_METHOD") == "spawn": return reasons = [] if is_in_ray_actor(): # even if we choose to spawn, we need to pass the ray address # to the subprocess so that it knows how to connect to the ray cluster. # env vars are inherited by subprocesses, even if we use spawn. import ray os.environ["RAY_ADDRESS"] = ray.get_runtime_context().gcs_address reasons.append("In a Ray actor and can only be spawned") if cuda_is_initialized(): reasons.append("CUDA is initialized") elif xpu_is_initialized(): reasons.append("XPU is initialized") if reasons: logger.warning( "We must use the `spawn` multiprocessing start method. " "Overriding VLLM_WORKER_MULTIPROC_METHOD to 'spawn'. " "See https://docs.vllm.ai/en/latest/usage/" "troubleshooting.html#python-multiprocessing " "for more information. Reasons: %s", "; ".join(reasons), ) os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn" def get_mp_context(): """Get a multiprocessing context with a particular method (spawn or fork). By default we follow the value of the VLLM_WORKER_MULTIPROC_METHOD to determine the multiprocessing method (default is fork). However, under certain conditions, we may enforce spawn and override the value of VLLM_WORKER_MULTIPROC_METHOD. """ _maybe_force_spawn() mp_method = envs.VLLM_WORKER_MULTIPROC_METHOD return multiprocessing.get_context(mp_method) def set_process_title( name: str, suffix: str = "", prefix: str = envs.VLLM_PROCESS_NAME_PREFIX, ) -> None: """Set the current process title with optional suffix.""" try: import setproctitle except ImportError: return if suffix: name = f"{name}_{suffix}" setproctitle.setproctitle(f"{prefix}::{name}") def _add_prefix(file: TextIO, worker_name: str, pid: int) -> None: """Add colored prefix to file output for log decoration.""" if envs.NO_COLOR: prefix = f"({worker_name} pid={pid}) " else: prefix = f"{CYAN}({worker_name} pid={pid}){RESET} " file_write = file.write def write_with_prefix(s: str): if not s: return if file.start_new_line: # type: ignore[attr-defined] file_write(prefix) idx = 0 while (next_idx := s.find("\n", idx)) != -1: next_idx += 1 file_write(s[idx:next_idx]) if next_idx == len(s): file.start_new_line = True # type: ignore[attr-defined] return file_write(prefix) idx = next_idx file_write(s[idx:]) file.start_new_line = False # type: ignore[attr-defined] file.start_new_line = True # type: ignore[attr-defined] file.write = write_with_prefix # type: ignore[method-assign] def decorate_logs(process_name: str | None = None) -> None: """Decorate stdout/stderr with process name and PID prefix.""" # Respect VLLM_CONFIGURE_LOGGING environment variable if not envs.VLLM_CONFIGURE_LOGGING: return if process_name is None: process_name = get_mp_context().current_process().name pid = os.getpid() _add_prefix(sys.stdout, process_name, pid) _add_prefix(sys.stderr, process_name, pid) def kill_process_tree(pid: int): """ Kills all descendant processes of the given pid by sending SIGKILL. Args: pid (int): Process ID of the parent process """ try: parent = psutil.Process(pid) except psutil.NoSuchProcess: return # Get all children recursively children = parent.children(recursive=True) # Send SIGKILL to all children first for child in children: with contextlib.suppress(ProcessLookupError): os.kill(child.pid, signal.SIGKILL) # Finally kill the parent with contextlib.suppress(ProcessLookupError): os.kill(pid, signal.SIGKILL) # Resource utilities # Adapted from: https://github.com/sgl-project/sglang/blob/v0.4.1/python/sglang/srt/utils.py#L630 def set_ulimit(target_soft_limit: int = 65535): if sys.platform.startswith("win"): logger.info("Windows detected, skipping ulimit adjustment.") return import resource resource_type = resource.RLIMIT_NOFILE current_soft, current_hard = resource.getrlimit(resource_type) if current_soft < target_soft_limit: try: resource.setrlimit(resource_type, (target_soft_limit, current_hard)) except ValueError as e: logger.warning( "Found ulimit of %s and failed to automatically increase " "with error %s. This can cause fd limit errors like " "`OSError: [Errno 24] Too many open files`. Consider " "increasing with ulimit -n", current_soft, e, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/argparse_utils.py
vllm/utils/argparse_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Argument parsing utilities for vLLM.""" import json import sys import textwrap from argparse import ( Action, ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError, Namespace, RawDescriptionHelpFormatter, _ArgumentGroup, ) from collections import defaultdict from typing import Any import regex as re import yaml from vllm.logger import init_logger logger = init_logger(__name__) class SortedHelpFormatter(ArgumentDefaultsHelpFormatter, RawDescriptionHelpFormatter): """SortedHelpFormatter that sorts arguments by their option strings.""" def _split_lines(self, text, width): """ 1. Sentences split across lines have their single newlines removed. 2. Paragraphs and explicit newlines are split into separate lines. 3. Each line is wrapped to the specified width (width of terminal). """ # The patterns also include whitespace after the newline single_newline = re.compile(r"(?<!\n)\n(?!\n)\s*") multiple_newlines = re.compile(r"\n{2,}\s*") text = single_newline.sub(" ", text) lines = re.split(multiple_newlines, text) return sum([textwrap.wrap(line, width) for line in lines], []) def add_arguments(self, actions): actions = sorted(actions, key=lambda x: x.option_strings) super().add_arguments(actions) class FlexibleArgumentParser(ArgumentParser): """ArgumentParser that allows both underscore and dash in names.""" _deprecated: set[Action] = set() _json_tip: str = ( "When passing JSON CLI arguments, the following sets of arguments " "are equivalent:\n" ' --json-arg \'{"key1": "value1", "key2": {"key3": "value2"}}\'\n' " --json-arg.key1 value1 --json-arg.key2.key3 value2\n\n" "Additionally, list elements can be passed individually using +:\n" ' --json-arg \'{"key4": ["value3", "value4", "value5"]}\'\n' " --json-arg.key4+ value3 --json-arg.key4+='value4,value5'\n\n" ) _search_keyword: str | None = None def __init__(self, *args, **kwargs): # Set the default "formatter_class" to SortedHelpFormatter if "formatter_class" not in kwargs: kwargs["formatter_class"] = SortedHelpFormatter # Pop kwarg "add_json_tip" to control whether to add the JSON tip self.add_json_tip = kwargs.pop("add_json_tip", True) super().__init__(*args, **kwargs) if sys.version_info < (3, 13): # Enable the deprecated kwarg for Python 3.12 and below def parse_known_args(self, args=None, namespace=None): namespace, args = super().parse_known_args(args, namespace) for action in FlexibleArgumentParser._deprecated: if ( hasattr(namespace, dest := action.dest) and getattr(namespace, dest) != action.default ): logger.warning_once("argument '%s' is deprecated", dest) return namespace, args def add_argument(self, *args, **kwargs): deprecated = kwargs.pop("deprecated", False) action = super().add_argument(*args, **kwargs) if deprecated: FlexibleArgumentParser._deprecated.add(action) return action class _FlexibleArgumentGroup(_ArgumentGroup): def add_argument(self, *args, **kwargs): deprecated = kwargs.pop("deprecated", False) action = super().add_argument(*args, **kwargs) if deprecated: FlexibleArgumentParser._deprecated.add(action) return action def add_argument_group(self, *args, **kwargs): group = self._FlexibleArgumentGroup(self, *args, **kwargs) self._action_groups.append(group) return group def format_help(self): # Only use custom help formatting for bottom level parsers if self._subparsers is not None: return super().format_help() formatter = self._get_formatter() # Handle keyword search of the args if (search_keyword := self._search_keyword) is not None: # Normalise the search keyword search_keyword = search_keyword.lower().replace("_", "-") # Return full help if searching for 'all' if search_keyword == "all": self.epilog = self._json_tip return super().format_help() # Return group help if searching for a group title for group in self._action_groups: if group.title and group.title.lower() == search_keyword: formatter.start_section(group.title) formatter.add_text(group.description) formatter.add_arguments(group._group_actions) formatter.end_section() formatter.add_text(self._json_tip) return formatter.format_help() # Return matched args if searching for an arg name matched_actions = [] for group in self._action_groups: for action in group._group_actions: # search option name if any( search_keyword in opt.lower() for opt in action.option_strings ): matched_actions.append(action) if matched_actions: formatter.start_section(f"Arguments matching '{search_keyword}'") formatter.add_arguments(matched_actions) formatter.end_section() formatter.add_text(self._json_tip) return formatter.format_help() # No match found formatter.add_text( f"No group or arguments matching '{search_keyword}'.\n" "Use '--help' to see available groups or " "'--help=all' to see all available parameters." ) return formatter.format_help() # usage formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups) # description formatter.add_text(self.description) # positionals, optionals and user-defined groups formatter.start_section("Config Groups") config_groups = "" for group in self._action_groups: if not group._group_actions: continue title = group.title description = group.description or "" config_groups += f"{title: <24}{description}\n" formatter.add_text(config_groups) formatter.end_section() # epilog formatter.add_text(self.epilog) # determine help from format above return formatter.format_help() def parse_args( # type: ignore[override] self, args: list[str] | None = None, namespace: Namespace | None = None, ): if args is None: args = sys.argv[1:] # Check for --model in command line arguments first if args and args[0] == "serve": try: model_idx = next( i for i, arg in enumerate(args) if arg == "--model" or arg.startswith("--model=") ) logger.warning( "With `vllm serve`, you should provide the model as a " "positional argument or in a config file instead of via " "the `--model` option. " "The `--model` option will be removed in v0.13." ) if args[model_idx] == "--model": model_tag = args[model_idx + 1] rest_start_idx = model_idx + 2 else: model_tag = args[model_idx].removeprefix("--model=") rest_start_idx = model_idx + 1 # Move <model> to the front, e,g: # [Before] # vllm serve -tp 2 --model <model> --enforce-eager --port 8001 # [After] # vllm serve <model> -tp 2 --enforce-eager --port 8001 args = [ "serve", model_tag, *args[1:model_idx], *args[rest_start_idx:], ] except StopIteration: pass if "--config" in args: args = self._pull_args_from_config(args) def repl(match: re.Match) -> str: """Replaces underscores with dashes in the matched string.""" return match.group(0).replace("_", "-") # Everything between the first -- and the first . pattern = re.compile(r"(?<=--)[^\.]*") # Convert underscores to dashes and vice versa in argument names processed_args = list[str]() for i, arg in enumerate(args): if arg.startswith("--help="): FlexibleArgumentParser._search_keyword = arg.split("=", 1)[-1].lower() processed_args.append("--help") elif arg.startswith("--"): if "=" in arg: key, value = arg.split("=", 1) key = pattern.sub(repl, key, count=1) processed_args.append(f"{key}={value}") else: key = pattern.sub(repl, arg, count=1) processed_args.append(key) elif arg.startswith("-O") and arg != "-O": # allow -O flag to be used without space, e.g. -O3 or -Odecode # also handle -O=<optimization_level> here optimization_level = arg[3:] if arg[2] == "=" else arg[2:] processed_args += ["--optimization-level", optimization_level] elif ( arg == "-O" and i + 1 < len(args) and args[i + 1] in {"0", "1", "2", "3"} ): # Convert -O <n> to --optimization-level <n> processed_args.append("--optimization-level") else: processed_args.append(arg) def create_nested_dict(keys: list[str], value: str) -> dict[str, Any]: """Creates a nested dictionary from a list of keys and a value. For example, `keys = ["a", "b", "c"]` and `value = 1` will create: `{"a": {"b": {"c": 1}}}` """ nested_dict: Any = value for key in reversed(keys): nested_dict = {key: nested_dict} return nested_dict def recursive_dict_update( original: dict[str, Any], update: dict[str, Any], ) -> set[str]: """Recursively updates a dictionary with another dictionary. Returns a set of duplicate keys that were overwritten. """ duplicates = set[str]() for k, v in update.items(): if isinstance(v, dict) and isinstance(original.get(k), dict): nested_duplicates = recursive_dict_update(original[k], v) duplicates |= {f"{k}.{d}" for d in nested_duplicates} elif isinstance(v, list) and isinstance(original.get(k), list): original[k] += v else: if k in original: duplicates.add(k) original[k] = v return duplicates delete = set[int]() dict_args = defaultdict[str, dict[str, Any]](dict) duplicates = set[str]() # Track regular arguments (non-dict args) for duplicate detection regular_args_seen = set[str]() for i, processed_arg in enumerate(processed_args): if i in delete: # skip if value from previous arg continue if processed_arg.startswith("--") and "." not in processed_arg: if "=" in processed_arg: arg_name = processed_arg.split("=", 1)[0] else: arg_name = processed_arg if arg_name in regular_args_seen: duplicates.add(arg_name) else: regular_args_seen.add(arg_name) continue if processed_arg.startswith("-") and "." in processed_arg: if "=" in processed_arg: processed_arg, value_str = processed_arg.split("=", 1) if "." not in processed_arg: # False positive, '.' was only in the value continue else: value_str = processed_args[i + 1] delete.add(i + 1) if processed_arg.endswith("+"): processed_arg = processed_arg[:-1] value_str = json.dumps(list(value_str.split(","))) key, *keys = processed_arg.split(".") try: value = json.loads(value_str) except json.decoder.JSONDecodeError: value = value_str # Merge all values with the same key into a single dict arg_dict = create_nested_dict(keys, value) arg_duplicates = recursive_dict_update(dict_args[key], arg_dict) duplicates |= {f"{key}.{d}" for d in arg_duplicates} delete.add(i) # Filter out the dict args we set to None processed_args = [a for i, a in enumerate(processed_args) if i not in delete] if duplicates: logger.warning("Found duplicate keys %s", ", ".join(duplicates)) # Add the dict args back as if they were originally passed as JSON for dict_arg, dict_value in dict_args.items(): processed_args.append(dict_arg) processed_args.append(json.dumps(dict_value)) return super().parse_args(processed_args, namespace) def check_port(self, value): try: value = int(value) except ValueError: msg = "Port must be an integer" raise ArgumentTypeError(msg) from None if not (1024 <= value <= 65535): raise ArgumentTypeError("Port must be between 1024 and 65535") return value def _pull_args_from_config(self, args: list[str]) -> list[str]: """Method to pull arguments specified in the config file into the command-line args variable. The arguments in config file will be inserted between the argument list. example: ```yaml port: 12323 tensor-parallel-size: 4 ``` ```python $: vllm {serve,chat,complete} "facebook/opt-12B" \ --config config.yaml -tp 2 $: args = [ "serve,chat,complete", "facebook/opt-12B", '--config', 'config.yaml', '-tp', '2' ] $: args = [ "serve,chat,complete", "facebook/opt-12B", '--port', '12323', '--tensor-parallel-size', '4', '-tp', '2' ] ``` Please note how the config args are inserted after the sub command. this way the order of priorities is maintained when these are args parsed by super(). """ assert args.count("--config") <= 1, "More than one config file specified!" index = args.index("--config") if index == len(args) - 1: raise ValueError( "No config file specified! \ Please check your command-line arguments." ) file_path = args[index + 1] config_args = self.load_config_file(file_path) # 0th index might be the sub command {serve,chat,complete,...} # optionally followed by model_tag (only for serve) # followed by config args # followed by rest of cli args. # maintaining this order will enforce the precedence # of cli > config > defaults if args[0].startswith("-"): # No sub command (e.g., api_server entry point) args = config_args + args[0:index] + args[index + 2 :] elif args[0] == "serve": model_in_cli = len(args) > 1 and not args[1].startswith("-") model_in_config = any(arg == "--model" for arg in config_args) if not model_in_cli and not model_in_config: raise ValueError( "No model specified! Please specify model either " "as a positional argument or in a config file." ) if model_in_cli: # Model specified as positional arg, keep CLI version args = ( [args[0]] + [args[1]] + config_args + args[2:index] + args[index + 2 :] ) else: # No model in CLI, use config if available args = [args[0]] + config_args + args[1:index] + args[index + 2 :] else: args = [args[0]] + config_args + args[1:index] + args[index + 2 :] return args def load_config_file(self, file_path: str) -> list[str]: """Loads a yaml file and returns the key value pairs as a flattened list with argparse like pattern ```yaml port: 12323 tensor-parallel-size: 4 ``` returns: processed_args: list[str] = [ '--port': '12323', '--tensor-parallel-size': '4' ] """ extension: str = file_path.split(".")[-1] if extension not in ("yaml", "yml"): raise ValueError( f"Config file must be of a yaml/yml type. {extension} supplied" ) # only expecting a flat dictionary of atomic types processed_args: list[str] = [] config: dict[str, int | str] = {} try: with open(file_path) as config_file: config = yaml.safe_load(config_file) except Exception as ex: logger.error( "Unable to read the config file at %s. Check path correctness", file_path, ) raise ex for key, value in config.items(): if isinstance(value, bool): if value: processed_args.append("--" + key) elif isinstance(value, list): if value: processed_args.append("--" + key) for item in value: processed_args.append(str(item)) else: processed_args.append("--" + key) processed_args.append(str(value)) return processed_args
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/gc_utils.py
vllm/utils/gc_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import gc import json import time from collections import Counter from contextlib import suppress from typing import Any import vllm.envs as envs from vllm.logger import init_logger logger = init_logger(__name__) class GCDebugConfig: """ Config for GC Debugger. - 0: disable GC debugger - 1: enable GC debugger with gc.collect elapsed times - '{"top_objects":5}': enable GC debugger with top 5 collected objects """ def __init__(self, gc_debug_conf: str | None = None) -> None: self.enabled: bool = False self.top_objects: int = -1 if not gc_debug_conf or gc_debug_conf == "0": pass elif gc_debug_conf == "1": self.enabled = True else: try: json_conf = json.loads(gc_debug_conf) self.enabled = True self.top_objects = json_conf.get("top_objects", -1) except Exception: self.enabled = False logger.error("Failed to parse VLLM_GC_DEBUG(%s)", envs.VLLM_GC_DEBUG) logger.debug("GC Debug Config. %s", str(self)) def __repr__(self) -> str: return f"enabled:{self.enabled},top_objects:{self.top_objects}" class GCDebugger: """ Debugger for GC which logs helpful information for GC understanding. To enable, you should call maybe_attach_gc_debug_callback in the process. """ def __init__(self, config: GCDebugConfig) -> None: self.config = config # Start time in micro second of this GC cycle self.start_time_ns: int = time.monotonic_ns() self.num_objects: int = 0 # If config.top_objects is positive, # compute top collected objects by object types self.gc_top_collected_objects: str = "" def handle(self, phase: str, info: dict[str, int]) -> None: """ Handles a GC event (e.g. GC start or GC finish) """ generation = info.get("generation") if generation is None: return if phase == "start": # Before GC started, record GC start time # and top collected objects self.start_time_ns = time.monotonic_ns() objects = gc.get_objects(generation) self.num_objects = len(objects) self.gc_top_collected_objects = _compute_top_gc_collected_objects( objects, self.config.top_objects ) elif phase == "stop": # After GC finished, Record GC elapsed time and # optionally top collected objects elpased_ms = (time.monotonic_ns() - self.start_time_ns) / 1e6 logger.info( "GC took %.3fms to complete. " "Collected %s objects (out of %d) in GC generation %d.%s", elpased_ms, str(info.get("collected", "?")), self.num_objects, generation, ( f" Top collected objects: \n{self.gc_top_collected_objects}" if self.gc_top_collected_objects else "" ), ) def freeze_gc_heap() -> None: """ Freeze all objects tracked by the garbage collector. It should be invoked after server init / warmup, to reduce GC overhead from static objects during serving time. """ # Ensure all static objects are pushed down to the oldest generation for # freeze gc.collect(0) gc.collect(1) gc.collect(2) # Freeze all GC tracked objects gc.freeze() def maybe_attach_gc_debug_callback() -> None: """ Attached a callback for GC debug when VLLM_GC_DEBUG is enabled. """ config = GCDebugConfig(envs.VLLM_GC_DEBUG) if config.enabled: debugger: GCDebugger = GCDebugger(config) def gc_callback(phase: str, info: dict[str, int]) -> None: debugger.handle(phase, info) gc.callbacks.append(gc_callback) def _compute_detailed_type(o: Any) -> str: """ Detailed object type. TODO(Jialin): Further enhance the detailed type with element types for easier debugging. We tried but occasionally it would run into signals which kills the engine. """ size_str: str = "" # Object doesn't support len() - this can happen with type objects # or other objects that don't implement __len__ properly with suppress(Exception): size_str = f"(size:{len(o)})" return f"{str(type(o))}{size_str}" def _compute_top_gc_collected_objects(objects: list[Any], top: int) -> str: """ Group collected objects by types. """ if top <= 0: return "" object_types = [_compute_detailed_type(o) for o in objects] return "\n".join( f"{count:>5}:{object_type}" for object_type, count in Counter(object_types).most_common(top) )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/deep_gemm.py
vllm/utils/deep_gemm.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Compatibility wrapper for DeepGEMM API changes. Users of vLLM should always import **only** these wrappers. """ import functools import importlib import os from collections.abc import Callable from enum import Enum from typing import Any, NoReturn import torch import vllm.envs as envs from vllm.logger import logger from vllm.platforms import current_platform from vllm.utils.import_utils import has_deep_gemm from vllm.utils.math_utils import cdiv class DeepGemmQuantScaleFMT(Enum): # Float32 scales in Float32 tensor FLOAT32 = 0 # Compute float32 scales and ceil the scales to UE8M0. # Keep the scales in Float32 tensor. FLOAT32_CEIL_UE8M0 = 1 # Compute float32 scales and ceil the scales to UE8M0. # Pack the scales into a int32 tensor where each int32 # element contains 4 scale values. UE8M0 = 2 @classmethod def init_oracle_cache(cls) -> None: """Initialize the oracle decision and store it in the class cache""" cached = getattr(cls, "_oracle_cache", None) if cached is not None: return use_e8m0 = ( envs.VLLM_USE_DEEP_GEMM_E8M0 and is_deep_gemm_supported() and (_fp8_gemm_nt_impl is not None) ) if not use_e8m0: cls._oracle_cache = cls.FLOAT32 # type: ignore return cls._oracle_cache = ( # type: ignore cls.UE8M0 if current_platform.is_device_capability_family(100) else cls.FLOAT32_CEIL_UE8M0 ) @classmethod def from_oracle(cls) -> "DeepGemmQuantScaleFMT": """Return the pre-initialized oracle decision""" cached = getattr(cls, "_oracle_cache", None) assert cached is not None, "DeepGemmQuantScaleFMT oracle cache not initialized" return cached @functools.cache def is_deep_gemm_supported() -> bool: """Return `True` if DeepGEMM is supported on the current platform. Currently, only Hopper and Blackwell GPUs are supported. """ is_supported_arch = current_platform.is_cuda() and ( current_platform.is_device_capability(90) or current_platform.is_device_capability_family(100) ) return envs.VLLM_USE_DEEP_GEMM and has_deep_gemm() and is_supported_arch @functools.cache def is_deep_gemm_e8m0_used() -> bool: """Return `True` if vLLM is configured to use DeepGEMM " "E8M0 scale on a Hopper or Blackwell-class GPU. """ if not is_deep_gemm_supported(): logger.debug_once( "DeepGEMM E8M0 disabled: DeepGEMM not supported on this system." ) return False _lazy_init() if _fp8_gemm_nt_impl is None: logger.info_once("DeepGEMM E8M0 disabled: _fp8_gemm_nt_impl not found") return False if envs.VLLM_USE_DEEP_GEMM_E8M0: logger.info_once("DeepGEMM E8M0 enabled on current platform.") return True logger.info_once("DeepGEMM E8M0 disabled on current configuration.") return False def _missing(*_: Any, **__: Any) -> NoReturn: """Placeholder for unavailable DeepGEMM backend.""" raise RuntimeError( "DeepGEMM backend is not available or outdated. Please install or " "update the `deep_gemm` to a newer version to enable FP8 kernels." ) _fp8_gemm_nt_impl: Callable[..., Any] | None = None _grouped_impl: Callable[..., Any] | None = None _grouped_masked_impl: Callable[..., Any] | None = None _fp8_mqa_logits_impl: Callable[..., Any] | None = None _fp8_paged_mqa_logits_impl: Callable[..., Any] | None = None _get_paged_mqa_logits_metadata_impl: Callable[..., Any] | None = None _get_mn_major_tma_aligned_tensor_impl: Callable[..., Any] | None = None _get_mk_alignment_for_contiguous_layout_impl: Callable[..., Any] | None = None _transform_sf_into_required_layout_impl: Callable[..., Any] | None = None def _lazy_init() -> None: """Import deep_gemm and resolve symbols on first use.""" global _fp8_gemm_nt_impl, _grouped_impl, _grouped_masked_impl global _fp8_mqa_logits_impl, _fp8_paged_mqa_logits_impl global _get_paged_mqa_logits_metadata_impl global _get_mn_major_tma_aligned_tensor_impl global _get_mk_alignment_for_contiguous_layout_impl global _transform_sf_into_required_layout_impl # fast path if ( _fp8_gemm_nt_impl is not None or _grouped_impl is not None or _grouped_masked_impl is not None or _fp8_mqa_logits_impl is not None or _fp8_paged_mqa_logits_impl is not None or _get_paged_mqa_logits_metadata_impl is not None or _get_mk_alignment_for_contiguous_layout_impl is not None or _transform_sf_into_required_layout_impl is not None ): return if not has_deep_gemm(): return # Set up deep_gemm cache path DEEP_GEMM_JIT_CACHE_ENV_NAME = "DG_JIT_CACHE_DIR" if not os.environ.get(DEEP_GEMM_JIT_CACHE_ENV_NAME, None): os.environ[DEEP_GEMM_JIT_CACHE_ENV_NAME] = os.path.join( envs.VLLM_CACHE_ROOT, "deep_gemm" ) _dg = importlib.import_module("deep_gemm") _fp8_gemm_nt_impl = getattr(_dg, "fp8_gemm_nt", None) _grouped_impl = getattr(_dg, "m_grouped_fp8_gemm_nt_contiguous", None) _grouped_masked_impl = getattr(_dg, "fp8_m_grouped_gemm_nt_masked", None) _fp8_mqa_logits_impl = getattr(_dg, "fp8_mqa_logits", None) _fp8_paged_mqa_logits_impl = getattr(_dg, "fp8_paged_mqa_logits", None) _get_paged_mqa_logits_metadata_impl = getattr( _dg, "get_paged_mqa_logits_metadata", None ) _get_mn_major_tma_aligned_tensor_impl = getattr( _dg, "get_mn_major_tma_aligned_tensor", None ) _get_mk_alignment_for_contiguous_layout_impl = getattr( _dg, "get_mk_alignment_for_contiguous_layout", None ) _transform_sf_into_required_layout_impl = getattr( _dg, "transform_sf_into_required_layout", None ) DeepGemmQuantScaleFMT.init_oracle_cache() def get_num_sms() -> int: _lazy_init() _dg = importlib.import_module("deep_gemm") return int(_dg.get_num_sms()) @functools.cache def get_mk_alignment_for_contiguous_layout() -> list[int]: _lazy_init() if _get_mk_alignment_for_contiguous_layout_impl is None: return _missing() mk_align_size = _get_mk_alignment_for_contiguous_layout_impl() return [mk_align_size, mk_align_size] def get_col_major_tma_aligned_tensor(x: torch.Tensor) -> torch.Tensor: """Wrapper for DeepGEMM's get_mn_major_tma_aligned_tensor""" _lazy_init() if _get_mn_major_tma_aligned_tensor_impl is None: return _missing() return _get_mn_major_tma_aligned_tensor_impl(x) def fp8_gemm_nt(*args, **kwargs): _lazy_init() if _fp8_gemm_nt_impl is None: return _missing(*args, **kwargs) if "is_deep_gemm_e8m0_used" in kwargs: use_ue8m0 = kwargs["is_deep_gemm_e8m0_used"] del kwargs["is_deep_gemm_e8m0_used"] else: use_ue8m0 = is_deep_gemm_e8m0_used() return _fp8_gemm_nt_impl(*args, disable_ue8m0_cast=not use_ue8m0, **kwargs) def m_grouped_fp8_gemm_nt_contiguous(*args, **kwargs): _lazy_init() if _grouped_impl is None: return _missing(*args, **kwargs) return _grouped_impl( *args, disable_ue8m0_cast=not is_deep_gemm_e8m0_used(), **kwargs ) def fp8_m_grouped_gemm_nt_masked(*args, **kwargs): _lazy_init() if _grouped_masked_impl is None: return _missing(*args, **kwargs) return _grouped_masked_impl( *args, disable_ue8m0_cast=not is_deep_gemm_e8m0_used(), **kwargs ) def transform_sf_into_required_layout(*args, **kwargs): _lazy_init() if _transform_sf_into_required_layout_impl is None: return _missing(*args, **kwargs) return _transform_sf_into_required_layout_impl( *args, disable_ue8m0_cast=not is_deep_gemm_e8m0_used(), **kwargs ) def fp8_mqa_logits( q: torch.Tensor, kv: tuple[torch.Tensor, torch.Tensor], weights: torch.Tensor, cu_seqlen_ks: torch.Tensor, cu_seqlen_ke: torch.Tensor, ) -> torch.Tensor: """Compute FP8 MQA logits for a single sequence without KV paging. Args: q: Query tensor of shape [M, H, D]. Casted to `torch.float8_e4m3fn` by caller. kv: Tuple `(k_fp8, k_scales)` where `k_fp8` has shape [N, D] with dtype `torch.float8_e4m3fn` and `k_scales` has shape [N] (or [N, 1]) with dtype `torch.float32`. weights: weights of shape [M, H], dtype `torch.float32`. cu_seqlen_ks: Start indices (inclusive) for valid K per query position, shape [M], dtype int32. cu_seqlen_ke: End indices (exclusive) for valid K per query position, shape [M], dtype int32. Returns: Logits tensor of shape [M, N], dtype `torch.float32`. """ _lazy_init() if _fp8_mqa_logits_impl is None: return _missing() return _fp8_mqa_logits_impl(q, kv, weights, cu_seqlen_ks, cu_seqlen_ke) def get_paged_mqa_logits_metadata( context_lens: torch.Tensor, block_size: int, num_sms: int ) -> torch.Tensor: """Build scheduling metadata for paged MQA logits. Args: context_lens: Tensor of shape [B], dtype int32; effective context length per batch element. block_size: KV-cache block size in tokens (e.g., 64). num_sms: Number of SMs available. 132 for Hopper Returns: Backend-specific tensor consumed by `fp8_paged_mqa_logits` to schedule work across SMs. """ _lazy_init() if _get_paged_mqa_logits_metadata_impl is None: return _missing() return _get_paged_mqa_logits_metadata_impl(context_lens, block_size, num_sms) def fp8_paged_mqa_logits( q_fp8: torch.Tensor, kv_cache_fp8: torch.Tensor, weights: torch.Tensor, context_lens: torch.Tensor, block_tables: torch.Tensor, schedule_metadata: torch.Tensor, max_model_len: int, ) -> torch.Tensor: """Compute FP8 MQA logits using paged KV-cache. Args: q_fp8: Query tensor of shape [B, next_n, H, D]. Casted to `torch.float8_e4m3fn` by caller. kv_cache_fp8: Paged KV-cache in packed FP8+scale layout with shape [num_blocks, block_size, 1, D+4], dtype `torch.uint8`. The last 4 bytes per (block,pos) store the `float` dequant scale. weights: Tensor of shape [B * next_n, H], dtype `torch.float32`. context_lens: Tensor of shape [B], dtype int32; effective context length for each batch element. block_tables: Tensor of shape [B, max_blocks], dtype int32; maps logical block indices to physical blocks in the paged cache. schedule_metadata: Returned by `get_paged_mqa_logits_metadata`; used to distribute work across SMs. max_model_len: Maximum sequence length used to size the logits output. Returns: Logits tensor of shape [B * next_n, max_model_len], dtype `torch.float32`. """ _lazy_init() if _fp8_paged_mqa_logits_impl is None: return _missing() return _fp8_paged_mqa_logits_impl( q_fp8, kv_cache_fp8, weights, context_lens, block_tables, schedule_metadata, max_model_len, clean_logits=True, ) def _ceil_to_ue8m0(x: torch.Tensor): return torch.pow(2.0, torch.ceil(torch.log2(x.abs()))) def _align(x: int, y: int) -> int: return cdiv(x, y) * y DEFAULT_BLOCK_SIZE = [128, 128] # Taken from https://github.com/deepseek-ai/DeepGEMM/blob/dd6ed14acbc7445dcef224248a77ab4d22b5f240/deep_gemm/utils/math.py#L38 @torch.compile(dynamic=True, backend=current_platform.simple_compile_backend) def per_block_cast_to_fp8( x: torch.Tensor, block_size: list[int] = DEFAULT_BLOCK_SIZE, use_ue8m0: bool = False ) -> tuple[torch.Tensor, torch.Tensor]: fp8_dtype = current_platform.fp8_dtype() assert x.dim() == 2 m, n = x.shape block_m, block_n = block_size x_padded = torch.zeros( (_align(m, block_m), _align(n, block_n)), dtype=x.dtype, device=x.device ) x_padded[:m, :n] = x x_view = x_padded.view(-1, block_m, x_padded.size(1) // block_n, block_n) x_amax = x_view.abs().float().amax(dim=(1, 3), keepdim=True).clamp(1e-4) sf = x_amax / 224.0 if current_platform.is_fp8_fnuz() else x_amax / 448.0 sf = _ceil_to_ue8m0(sf) if use_ue8m0 else sf x_scaled = (x_view * (1.0 / sf)).to(fp8_dtype) return x_scaled.view_as(x_padded)[:m, :n].contiguous(), sf.view( x_view.size(0), x_view.size(2) ) def calc_diff(x: torch.Tensor, y: torch.Tensor): """Return a global difference metric for unit tests. DeepGEMM kernels on Blackwell/B200 currently exhibit noticeable per-element error, causing `torch.testing.assert_close` to fail. Instead of checking every element, we compute a cosine-style similarity over the whole tensor and report `1 - sim`. Once kernel accuracy improves this helper can be removed. """ x, y = x.double(), y.double() denominator = (x * x + y * y).sum() sim = 2 * (x * y).sum() / denominator return 1 - sim def should_use_deepgemm_for_fp8_linear( output_dtype: torch.dtype, weight: torch.Tensor, supports_deep_gemm: bool | None = None, ): if supports_deep_gemm is None: supports_deep_gemm = is_deep_gemm_supported() # Verify DeepGEMM N/K dims requirements # NOTE: Also synchronized with test_w8a8_block_fp8_deep_gemm_matmul # test inside kernels/quantization/test_block_fp8.py N_MULTIPLE = 64 K_MULTIPLE = 128 return ( supports_deep_gemm and output_dtype == torch.bfloat16 and weight.shape[0] % N_MULTIPLE == 0 and weight.shape[1] % K_MULTIPLE == 0 ) __all__ = [ "calc_diff", "DeepGemmQuantScaleFMT", "fp8_gemm_nt", "m_grouped_fp8_gemm_nt_contiguous", "fp8_m_grouped_gemm_nt_masked", "fp8_mqa_logits", "fp8_paged_mqa_logits", "get_paged_mqa_logits_metadata", "per_block_cast_to_fp8", "is_deep_gemm_e8m0_used", "is_deep_gemm_supported", "get_num_sms", "should_use_deepgemm_for_fp8_linear", "get_col_major_tma_aligned_tensor", "get_mk_alignment_for_contiguous_layout", ]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/math_utils.py
vllm/utils/math_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Math utility functions for vLLM.""" def cdiv(a: int, b: int) -> int: """Ceiling division.""" return -(a // -b) def next_power_of_2(n: int) -> int: """The next power of 2 (inclusive)""" if n < 1: return 1 return 1 << (n - 1).bit_length() def prev_power_of_2(n: int) -> int: """The previous power of 2 (inclusive)""" if n <= 0: return 0 return 1 << (n.bit_length() - 1) def round_up(x: int, y: int) -> int: """Round up x to the nearest multiple of y.""" return ((x + y - 1) // y) * y def round_down(x: int, y: int) -> int: """Round down x to the nearest multiple of y.""" return (x // y) * y
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/func_utils.py
vllm/utils/func_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Contains helpers that are applied to functions. This is similar in concept to the `functools` module. """ import inspect import threading import warnings from collections.abc import Callable, Mapping from functools import lru_cache, partial, wraps from typing import Any, TypeVar from typing_extensions import ParamSpec from vllm.logger import init_logger logger = init_logger(__name__) P = ParamSpec("P") T = TypeVar("T") F = TypeVar("F", bound=Callable[..., Any]) def identity(value: T, **kwargs) -> T: """Returns the first provided value.""" return value def run_once(f: Callable[P, None]) -> Callable[P, None]: def wrapper(*args: P.args, **kwargs: P.kwargs) -> None: if wrapper.has_run: # type: ignore[attr-defined] return with wrapper.lock: # type: ignore[attr-defined] if not wrapper.has_run: # type: ignore[attr-defined] wrapper.has_run = True # type: ignore[attr-defined] return f(*args, **kwargs) wrapper.has_run = False # type: ignore[attr-defined] wrapper.lock = threading.Lock() # type: ignore[attr-defined] return wrapper def deprecate_args( start_index: int, is_deprecated: bool | Callable[[], bool] = True, additional_message: str | None = None, ) -> Callable[[F], F]: if not callable(is_deprecated): is_deprecated = partial(identity, is_deprecated) def wrapper(fn: F) -> F: params = inspect.signature(fn).parameters pos_types = ( inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD, ) pos_kws = [kw for kw, param in params.items() if param.kind in pos_types] @wraps(fn) def inner(*args, **kwargs): if is_deprecated(): deprecated_args = pos_kws[start_index : len(args)] if deprecated_args: msg = ( f"The positional arguments {deprecated_args} are " "deprecated and will be removed in a future update." ) if additional_message is not None: msg += f" {additional_message}" warnings.warn( DeprecationWarning(msg), stacklevel=3, # The inner function takes up one level ) return fn(*args, **kwargs) return inner # type: ignore return wrapper def deprecate_kwargs( *kws: str, is_deprecated: bool | Callable[[], bool] = True, additional_message: str | None = None, ) -> Callable[[F], F]: deprecated_kws = set(kws) if not callable(is_deprecated): is_deprecated = partial(identity, is_deprecated) def wrapper(fn: F) -> F: @wraps(fn) def inner(*args, **kwargs): if is_deprecated(): deprecated_kwargs = kwargs.keys() & deprecated_kws if deprecated_kwargs: msg = ( f"The keyword arguments {deprecated_kwargs} are " "deprecated and will be removed in a future update." ) if additional_message is not None: msg += f" {additional_message}" warnings.warn( DeprecationWarning(msg), stacklevel=3, # The inner function takes up one level ) return fn(*args, **kwargs) return inner # type: ignore return wrapper @lru_cache def supports_kw( callable: Callable[..., object], kw_name: str, *, requires_kw_only: bool = False, allow_var_kwargs: bool = True, ) -> bool: """Check if a keyword is a valid kwarg for a callable; if requires_kw_only disallows kwargs names that can also be positional arguments. """ params = inspect.signature(callable).parameters if not params: return False param_val = params.get(kw_name) # Types where the it may be valid, i.e., explicitly defined & nonvariadic passable_kw_types = set( ( inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY, ) ) if param_val: is_sig_param = param_val.kind in passable_kw_types # We want kwargs only, but this is passable as a positional arg if ( requires_kw_only and is_sig_param and param_val.kind != inspect.Parameter.KEYWORD_ONLY ): return False if (requires_kw_only and param_val.kind == inspect.Parameter.KEYWORD_ONLY) or ( not requires_kw_only and is_sig_param ): return True # If we're okay with var-kwargs, it's supported as long as # the kw_name isn't something like *args, **kwargs if allow_var_kwargs: # Get the last param; type is ignored here because params is a proxy # mapping, but it wraps an ordered dict, and they appear in order. # Ref: https://docs.python.org/3/library/inspect.html#inspect.Signature.parameters last_param = params[next(reversed(params))] # type: ignore return ( last_param.kind == inspect.Parameter.VAR_KEYWORD and last_param.name != kw_name ) return False def get_allowed_kwarg_only_overrides( callable: Callable[..., object], overrides: Mapping[str, object] | None, *, requires_kw_only: bool = True, allow_var_kwargs: bool = False, ) -> dict[str, Any]: """ Given a callable which has one or more keyword only params and a dict mapping param names to values, drop values that can be not be kwarg expanded to overwrite one or more keyword-only args. This is used in a few places to handle custom processor overrides for multimodal models, e.g., for profiling when processor options provided by the user may affect the number of mm tokens per instance. Args: callable: Callable which takes 0 or more keyword only arguments. If None is provided, all overrides names are allowed. overrides: Potential overrides to be used when invoking the callable. allow_var_kwargs: Allows overrides that are expandable for var kwargs. Returns: Dictionary containing the kwargs to be leveraged which may be used to overwrite one or more keyword only arguments when invoking the callable. """ if not overrides: return {} # Drop any mm_processor_kwargs provided by the user that # are not kwargs, unless it can fit it var_kwargs param filtered_overrides = { kwarg_name: val for kwarg_name, val in overrides.items() if supports_kw( callable, kwarg_name, requires_kw_only=requires_kw_only, allow_var_kwargs=allow_var_kwargs, ) } # If anything is dropped, log a warning dropped_keys = overrides.keys() - filtered_overrides.keys() if dropped_keys: if requires_kw_only: logger.warning( "The following intended overrides are not keyword-only args " "and will be dropped: %s", dropped_keys, ) else: logger.warning( "The following intended overrides are not keyword args " "and will be dropped: %s", dropped_keys, ) return filtered_overrides
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/nvtx_pytorch_hooks.py
vllm/utils/nvtx_pytorch_hooks.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from contextlib import contextmanager import torch import torch.cuda.nvtx as nvtx def print_tensor(tensor_obj, prefix, tensor_list=None): """Descends iterators that contains Tensors and prints the Tensor. Recursive function that descends iterator type arguments until it finds a Tensor object. """ if tensor_list is None: tensor_list = [] if isinstance(tensor_obj, (list, tuple)): for ten in tensor_obj: tensor_list = print_tensor(ten, prefix, tensor_list) elif isinstance(tensor_obj, torch.Tensor): tensor_dims = list(tensor_obj.size()) tensor_list.append(tensor_dims) return tensor_list def process_layer_params(module_obj): """Extract the static parameters from LLM and VLM relevant layer types""" param_info = {} # Extract parameters for layers commonly used in LLMs and VLMs if isinstance(module_obj, (torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d)): conv_params = {} conv_params["in_chan"] = module_obj.in_channels conv_params["out_chan"] = module_obj.out_channels conv_params["filter_dim"] = module_obj.kernel_size conv_params["stride"] = module_obj.stride conv_params["padding"] = module_obj.padding conv_params["dilation"] = module_obj.dilation conv_params["transposed"] = module_obj.transposed conv_params["output_padding"] = module_obj.output_padding conv_params["groups"] = module_obj.groups conv_params["padding_mode"] = module_obj.padding_mode param_info = conv_params elif isinstance( module_obj, ( torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d, ), ): convtranspose_params = {} convtranspose_params["in_chan"] = module_obj.in_channels convtranspose_params["out_chan"] = module_obj.out_channels convtranspose_params["filter_dim"] = module_obj.kernel_size convtranspose_params["stride"] = module_obj.stride convtranspose_params["padding"] = module_obj.padding convtranspose_params["dilation"] = module_obj.dilation convtranspose_params["transposed"] = module_obj.transposed convtranspose_params["output_padding"] = module_obj.output_padding convtranspose_params["groups"] = module_obj.groups convtranspose_params["padding_mode"] = module_obj.padding_mode param_info = convtranspose_params elif isinstance( module_obj, (torch.nn.MaxPool1d, torch.nn.MaxPool2d, torch.nn.MaxPool3d) ): def _handle_int_or_tuple(parameter): if isinstance(parameter, tuple): return list(parameter) elif isinstance(parameter, int): return [parameter, parameter] pooling_params = {} pooling_params["filter_dim"] = _handle_int_or_tuple(module_obj.kernel_size) pooling_params["stride"] = _handle_int_or_tuple(module_obj.stride) pooling_params["padding"] = _handle_int_or_tuple(module_obj.padding) pooling_params["dilation"] = _handle_int_or_tuple(module_obj.dilation) param_info = pooling_params elif isinstance( module_obj, (torch.nn.AvgPool1d, torch.nn.AvgPool2d, torch.nn.AvgPool3d) ): pooling_params = {} pooling_params["filter_dim"] = [ module_obj.kernel_size, module_obj.kernel_size, ] pooling_params["stride"] = [module_obj.stride, module_obj.stride] pooling_params["padding"] = [module_obj.padding, module_obj.padding] pooling_params["ceil_mode"] = module_obj.ceil_mode pooling_params["count_include_pad"] = module_obj.count_include_pad param_info = pooling_params elif isinstance( module_obj, ( torch.nn.AdaptiveAvgPool1d, torch.nn.AdaptiveAvgPool2d, torch.nn.AdaptiveAvgPool3d, ), ): pooling_params = {} pooling_params["output_size"] = [ module_obj.output_size, module_obj.output_size, ] param_info = pooling_params elif isinstance(module_obj, torch.nn.Linear): param_info["in_features"] = module_obj.in_features param_info["out_features"] = module_obj.out_features elif isinstance( module_obj, (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d), ): param_info["num_features"] = module_obj.num_features param_info["epsilon"] = module_obj.eps param_info["momentum"] = module_obj.momentum elif isinstance(module_obj, torch.nn.ReLU): param_info["in_place"] = module_obj.inplace elif isinstance(module_obj, torch.nn.Dropout): param_info["p"] = module_obj.p param_info["in_place"] = module_obj.inplace elif isinstance(module_obj, torch.nn.Embedding): param_info["num_embeddings"] = module_obj.num_embeddings param_info["embedding_dim"] = module_obj.embedding_dim elif isinstance( module_obj, ( torch.nn.Upsample, torch.nn.UpsamplingNearest2d, torch.nn.UpsamplingBilinear2d, ), ): param_info["scale_factor"] = module_obj.scale_factor return param_info def construct_marker_dict_and_push( module_name, module_obj, in_tensor, kwargs=None, out_tensor=None ): marker_dict = {} marker_dict["Module"] = module_name ## Get trainable parameters like weights and bias module_params = module_obj.named_parameters(recurse=False) for idx, (param_name, param_obj) in enumerate(module_params): if idx == 0: marker_dict["TrainableParams"] = {} marker_dict["TrainableParams"][param_name] = list(param_obj.size()) in_tensor_list = print_tensor(in_tensor, "Input") if in_tensor_list: marker_dict["Inputs"] = in_tensor_list out_tensor_list = print_tensor(out_tensor, "Output") if out_tensor_list: marker_dict["Outputs"] = out_tensor_list ## Get Kwargs like input_ids and positions for the top module if kwargs: for key, value in kwargs.items(): if isinstance(value, (torch.Tensor, list, tuple)): tensor_list = print_tensor(value, key) if tensor_list: marker_dict[key] = tensor_list param_info = process_layer_params(module_obj) if param_info: marker_dict["StaticParams"] = param_info nvtx.range_push("{}".format(marker_dict)) class ResultHolder: """Holder for storing results from within a context manager.""" result = None @contextmanager def layerwise_nvtx_marker_context(module_name, module_obj, in_tensor=None, kwargs=None): """Context manager for NVTX markers that automatically pushes on enter and pops on exit. Example: with nvtx_marker_context("Module:MyModule", module, in_tensor=args, kwargs=kwargs) as ctx: ctx.result = module(*args, **kwargs) return ctx.result """ holder = ResultHolder() # Push input marker construct_marker_dict_and_push( module_name, module_obj, in_tensor=in_tensor, kwargs=kwargs, ) try: yield holder finally: # Pop input marker nvtx.range_pop() # Push and pop output marker output_name = module_name.replace("(input)", "(output)") construct_marker_dict_and_push( output_name, module_obj, in_tensor=None, kwargs=None, out_tensor=holder.result, ) nvtx.range_pop() class PytHooks: """This module contains all the code needed to enable forward hooks in a pytorch network. To register the hooks for a given network, the user needs to instantiate a PytHook object. Then call the register_hooks method. Example: my_hook = PytHook() my_hook.register_hooks(my_network_model) """ def __init__(self): """Initialize module variables.""" super().__init__() self.module_to_name_map = {} def _process_layer_params(self, module_obj): return process_layer_params(module_obj) def module_fwd_hook(self, module_obj, in_tensor, out_tensor): """Callback function that ends the NVTX marker. Records the module name and tensor information. Called after the module executes the forward method. """ nvtx.range_pop() module_name = self.module_to_name_map.get(module_obj, "unknown") construct_marker_dict_and_push( module_name, module_obj, in_tensor=None, kwargs=None, out_tensor=out_tensor ) nvtx.range_pop() return def module_fwd_pre_hook(self, module_obj, in_tensor, kwargs): """Creates an NVTX marker with the module name in it. This function is called before the module executes. """ module_name = self.module_to_name_map.get(module_obj, "unknown") construct_marker_dict_and_push( module_name, module_obj, in_tensor=in_tensor, kwargs=kwargs, out_tensor=None ) return def register_hooks(self, network_model, module_prefix="top"): """User level function that activates all the hooks. The user needs to call this method from the network source code. The code descends all the modules in the network and registers their respective hooks. """ # Module types to skip (simple operations that don't need detailed profiling) skip_types = ( torch.nn.Identity, torch.nn.Dropout, torch.nn.Dropout1d, torch.nn.Dropout2d, torch.nn.Dropout3d, ) for name, module in network_model.named_modules(prefix=module_prefix): # Skip certain module types to reduce profiling overhead if isinstance(module, skip_types): continue module.register_forward_pre_hook(self.module_fwd_pre_hook, with_kwargs=True) module.register_forward_hook(self.module_fwd_hook) if module not in self.module_to_name_map: self.module_to_name_map[module] = name else: raise ValueError("Module instance {} is not unique ".format(module)) return
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/flashinfer.py
vllm/utils/flashinfer.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """Compatibility wrapper for FlashInfer API changes. Users of vLLM should always import **only** these wrappers. """ import contextlib import functools import importlib import importlib.util import os import shutil from collections.abc import Callable from typing import Any, NoReturn import requests import torch import vllm.envs as envs from vllm.logger import init_logger from vllm.model_executor.layers.batch_invariant import ( vllm_is_batch_invariant, ) from vllm.platforms import current_platform logger = init_logger(__name__) # This is the storage path for the cubins, it can be replaced # with a local path for testing. # Referenced from https://github.com/flashinfer-ai/flashinfer/blob/0c9a92c3d9a7e043ab6f3f7b2273269caf6ab044/flashinfer/jit/cubin_loader.py#L35 # noqa: E501 FLASHINFER_CUBINS_REPOSITORY = os.environ.get( "FLASHINFER_CUBINS_REPOSITORY", "https://edge.urm.nvidia.com/artifactory/sw-kernelinferencelibrary-public-generic-local/", # noqa: E501 ) @functools.cache def has_flashinfer_cubin() -> bool: """Return `True` if flashinfer-cubin package is available.""" if envs.VLLM_HAS_FLASHINFER_CUBIN: return True if importlib.util.find_spec("flashinfer_cubin") is not None: return True logger.debug_once("flashinfer-cubin package was not found") return False @functools.cache def has_flashinfer() -> bool: """Return `True` if flashinfer-python package is available.""" # Use find_spec to check if the module exists without importing it # This avoids potential CUDA initialization side effects if importlib.util.find_spec("flashinfer") is None: logger.debug_once("FlashInfer unavailable since package was not found") return False # When not using flashinfer cubin, # Also check if nvcc is available since it's required to JIT compile flashinfer if not has_flashinfer_cubin() and shutil.which("nvcc") is None: logger.debug_once( "FlashInfer unavailable since nvcc was not found " "and not using pre-downloaded cubins" ) return False return True def _missing(*_: Any, **__: Any) -> NoReturn: """Placeholder for unavailable FlashInfer backend.""" raise RuntimeError( "FlashInfer backend is not available. Please install the package " "to enable FlashInfer kernels: " "https://github.com/flashinfer-ai/flashinfer" ) def _get_submodule(module_name: str) -> Any | None: """Safely import a submodule and return it, or None if not available.""" try: return importlib.import_module(module_name) except (ImportError, ModuleNotFoundError): return None # General lazy import wrapper def _lazy_import_wrapper( module_name: str, attr_name: str, fallback_fn: Callable[..., Any] = _missing ): """Create a lazy import wrapper for a specific function.""" @functools.cache def _get_impl(): if not has_flashinfer(): return None mod = _get_submodule(module_name) return getattr(mod, attr_name, None) if mod else None def wrapper(*args, **kwargs): impl = _get_impl() if impl is None: return fallback_fn(*args, **kwargs) return impl(*args, **kwargs) return wrapper # Create lazy wrappers for each function flashinfer_trtllm_fp8_block_scale_moe = _lazy_import_wrapper( "flashinfer.fused_moe", "trtllm_fp8_block_scale_moe" ) flashinfer_trtllm_fp8_per_tensor_scale_moe = _lazy_import_wrapper( "flashinfer.fused_moe", "trtllm_fp8_per_tensor_scale_moe" ) flashinfer_cutlass_fused_moe = _lazy_import_wrapper( "flashinfer.fused_moe", "cutlass_fused_moe" ) flashinfer_cutedsl_grouped_gemm_nt_masked = _lazy_import_wrapper( "flashinfer.cute_dsl.blockscaled_gemm", "grouped_gemm_nt_masked" ) flashinfer_fp4_quantize = _lazy_import_wrapper("flashinfer", "fp4_quantize") nvfp4_batched_quantize = _lazy_import_wrapper("flashinfer", "nvfp4_batched_quantize") silu_and_mul_scaled_nvfp4_experts_quantize = _lazy_import_wrapper( "flashinfer", "silu_and_mul_scaled_nvfp4_experts_quantize" ) scaled_fp4_grouped_quantize = _lazy_import_wrapper( "flashinfer", "scaled_fp4_grouped_quantize" ) nvfp4_block_scale_interleave = _lazy_import_wrapper( "flashinfer", "nvfp4_block_scale_interleave" ) trtllm_fp4_block_scale_moe = _lazy_import_wrapper( "flashinfer", "trtllm_fp4_block_scale_moe" ) # Special case for autotune since it returns a context manager autotune = _lazy_import_wrapper( "flashinfer.autotuner", "autotune", fallback_fn=lambda *args, **kwargs: contextlib.nullcontext(), ) @functools.cache def has_flashinfer_comm() -> bool: """Return `True` if FlashInfer comm module is available.""" return has_flashinfer() and importlib.util.find_spec("flashinfer.comm") is not None @functools.cache def has_flashinfer_all2all() -> bool: """Return `True` if FlashInfer mnnvl all2all is available.""" if not has_flashinfer_comm(): return False # Check if all required functions are available required_functions = [ ("flashinfer.comm", "Mapping"), ("flashinfer.comm.mnnvl", "MnnvlMemory"), ("flashinfer.comm.trtllm_alltoall", "MnnvlMoe"), ("flashinfer.comm.trtllm_alltoall", "MoEAlltoallInfo"), ] for module_name, attr_name in required_functions: mod = _get_submodule(module_name) if not mod or not hasattr(mod, attr_name): return False return True @functools.cache def has_flashinfer_moe() -> bool: """Return `True` if FlashInfer MoE module is available.""" return ( has_flashinfer() and importlib.util.find_spec("flashinfer.fused_moe") is not None ) @functools.cache def has_flashinfer_cutedsl() -> bool: """Return ``True`` if FlashInfer cutedsl module is available.""" return ( has_flashinfer() and importlib.util.find_spec("flashinfer.cute_dsl") is not None ) @functools.cache def has_flashinfer_trtllm_fused_moe() -> bool: """Return `True` if FlashInfer TRTLLM fused MoE is available.""" if not has_flashinfer_moe(): return False required_functions = [ ("flashinfer.fused_moe", "trtllm_fp8_block_scale_moe"), ("flashinfer.fused_moe", "trtllm_fp8_per_tensor_scale_moe"), ("flashinfer.fused_moe", "trtllm_fp4_block_scale_moe"), ] for module_name, attr_name in required_functions: mod = _get_submodule(module_name) if not mod or not hasattr(mod, attr_name): return False return True @functools.cache def has_flashinfer_cutlass_fused_moe() -> bool: """Return `True` if FlashInfer CUTLASS fused MoE is available.""" if not has_flashinfer_moe(): return False # Check if all required functions are available required_functions = [ ("flashinfer.fused_moe", "cutlass_fused_moe"), ("flashinfer", "fp4_quantize"), ("flashinfer", "nvfp4_block_scale_interleave"), ("flashinfer.fused_moe", "trtllm_fp4_block_scale_moe"), ] for module_name, attr_name in required_functions: mod = _get_submodule(module_name) if not mod or not hasattr(mod, attr_name): return False return True @functools.cache def has_flashinfer_cutedsl_grouped_gemm_nt_masked() -> bool: """Return ``True`` if FlashInfer CUTLASS fused MoE is available.""" if not has_flashinfer_cutedsl(): return False # Check if all required functions are available required_functions = [ ("flashinfer.cute_dsl.blockscaled_gemm", "grouped_gemm_nt_masked"), ("flashinfer", "scaled_fp4_grouped_quantize"), ("flashinfer", "silu_and_scaled_nvfp4_experts_quantize"), ] for module_name, attr_name in required_functions: mod = _get_submodule(module_name) if not mod or not hasattr(mod, attr_name): return False return True @functools.cache def has_nvidia_artifactory() -> bool: """Return `True` if NVIDIA's artifactory is accessible. This checks connectivity to the kernel inference library artifactory which is required for downloading certain cubin kernels like TRTLLM FHMA. """ # If we have pre-downloaded cubins, we can assume the cubins are available. if has_flashinfer_cubin(): return True try: # Use a short timeout to avoid blocking for too long response = requests.get(FLASHINFER_CUBINS_REPOSITORY, timeout=5) accessible = response.status_code == 200 if accessible: logger.debug_once("NVIDIA artifactory is accessible") else: logger.warning_once( "NVIDIA artifactory returned failed status code: %d", response.status_code, ) return accessible except Exception as e: logger.warning_once("Failed to connect to NVIDIA artifactory: %s", e) return False @functools.cache def supports_trtllm_attention() -> bool: """ TRTLLM attention is supported if the platform is SM100, NVIDIA artifactory is accessible, and batch-invariant mode is not enabled. """ # Batch-invariant mode disables TRTLLM attention if vllm_is_batch_invariant(): return False # Requires SM100 and NVIDIA artifactory to be accessible to download cubins return ( current_platform.is_device_capability_family(100) and has_nvidia_artifactory() ) def force_use_trtllm_attention() -> bool | None: """ This function should only be called during initialization stage when vllm config is set. Return `None` if --attention-config.use_trtllm_attention is not set, return `True` if TRTLLM attention is forced to be used, return `False` if TRTLLM attention is forced to be not used. """ from vllm.config import get_current_vllm_config vllm_config = get_current_vllm_config() return vllm_config.attention_config.use_trtllm_attention def can_use_trtllm_attention(num_qo_heads: int, num_kv_heads: int) -> bool: """Check if the current configuration supports TRTLLM attention.""" if force_use_trtllm_attention() is False: return False has_trtllm = supports_trtllm_attention() # num_kv_heads=1 is not supported due to TMA descriptor building limitations. # When num_kv_heads=1, the KV cache strides become degenerate (stride_heads == # stride_batch), which causes CUDA's cuTensorMapEncodeTiled to fail because # TMA descriptors cannot handle degenerate 4D tensors with singleton dimensions. # See: https://fburl.com/352mrydz if has_trtllm and num_kv_heads == 1: logger.warning_once( "TRTLLM attention does not support num_kv_heads=1. " "This configuration causes TMA descriptor building to fail due to " "degenerate tensor strides. Falling back to FlashInfer attention." ) return has_trtllm and (num_qo_heads % num_kv_heads == 0) and (num_kv_heads != 1) def use_trtllm_attention( num_qo_heads: int, num_kv_heads: int, num_tokens: int, max_seq_len: int, dcp_world_size: int, kv_cache_dtype: str, q_dtype: torch.dtype, is_prefill: bool, # None means auto-detection, True means force on, False means force off force_use_trtllm: bool | None = None, has_sinks: bool = False, has_spec: bool = False, ) -> bool: """Return `True` if TRTLLM attention is used.""" # CLI argument is set to 0 - respect it if force_use_trtllm is not None and not force_use_trtllm: return False # Decode context parallel is not supported if dcp_world_size > 1: logger.warning_once( "Trtllm does not support returning LSE and as a result " "does not support DCP, reverting to FlashInfer" ) return False # The platform is not supported if not supports_trtllm_attention(): if force_use_trtllm: logger.warning_once( "TRTLLM attention is not supported on this platform, " "but --attention-config.use_trtllm_attention is set to 1" ) return False # The combination of query and key heads is not supported if num_qo_heads % num_kv_heads != 0: if force_use_trtllm: logger.warning_once( "TRTLLM attention is not supported for this combination of " "query and key heads, but --attention-config.use_trtllm_attention is " "set to 1" ) return False # num_kv_heads=1 is not supported if num_kv_heads == 1: if force_use_trtllm: logger.warning_once( "TRTLLM attention does not support num_kv_heads=1, " "but --attention-config.use_trtllm_attention is set to 1" ) return False if has_spec and not is_prefill: # Speculative decoding requires TRTLLM attention for decodes logger.info_once("Using TRTLLM attention (enabled for speculative decoding).") return True # Must use TRTLLM attention if query is FP8 quantized if q_dtype == current_platform.fp8_dtype(): logger.info_once("Using TRTLLM attention (query is quantized).") return True # If sinks are being used, we must use TRTLLM attention as it's # the only backend that supports them if has_sinks: logger.info_once("Using TRTLLM attention (required for attention sinks).") return True if force_use_trtllm is None: # CLI argument not set - use auto-detection if is_prefill: # Prefill auto-detection use_trtllm = kv_cache_dtype == "auto" if use_trtllm: logger.warning_once("Using TRTLLM prefill attention (auto-detected).") else: # Decode auto-detection use_trtllm = num_tokens <= 256 and kv_cache_dtype == "auto" if use_trtllm: logger.warning_once("Using TRTLLM decode attention (auto-detected).") return use_trtllm # CLI argument is set to 1 - respect it logger.info_once( "Using TRTLLM attention (--attention-config.use_trtllm_attention is set to 1)" ) return True if has_flashinfer(): @torch.library.custom_op( "vllm::flashinfer_mm_fp4", mutates_args=[], device_types="cuda", ) def flashinfer_mm_fp4( A: torch.Tensor, B: torch.Tensor, A_scale: torch.Tensor, B_scale: torch.Tensor, g_scale: torch.Tensor, dtype: torch.dtype, backend: str, ) -> torch.Tensor: from flashinfer import mm_fp4 as flashinfer_mm_fp4_ return flashinfer_mm_fp4_( A, B, A_scale, B_scale, g_scale, dtype, block_size=16, backend=backend ) @torch.library.register_fake( "vllm::flashinfer_mm_fp4", ) def flashinfer_mm_fp4_fake( A: torch.Tensor, B: torch.Tensor, A_scale: torch.Tensor, B_scale: torch.Tensor, g_scale: torch.Tensor, dtype: torch.dtype, backend: str, ) -> torch.Tensor: return torch.empty(A.shape[0], B.shape[1], dtype=dtype, device=A.device) @torch.library.custom_op( "vllm::bmm_fp8", mutates_args=[], device_types="cuda", ) def bmm_fp8( A: torch.Tensor, B: torch.Tensor, A_scale: torch.Tensor, B_scale: torch.Tensor, dtype: torch.dtype, backend: str, ) -> torch.Tensor: from flashinfer import bmm_fp8 as bmm_fp8_ return bmm_fp8_(A, B, A_scale, B_scale, dtype, None, backend) @torch.library.register_fake( "vllm::bmm_fp8", ) def bmm_fp8_fake( A: torch.Tensor, B: torch.Tensor, A_scale: torch.Tensor, B_scale: torch.Tensor, dtype: torch.dtype, backend: str, ) -> torch.Tensor: return torch.empty( A.shape[0], A.shape[1], B.shape[2], dtype=dtype, device=A.device ) def flashinfer_scaled_fp4_mm( a: torch.Tensor, b: torch.Tensor, block_scale_a: torch.Tensor, block_scale_b: torch.Tensor, alpha: torch.Tensor, out_dtype: torch.dtype, backend: str, ) -> torch.Tensor: assert a.ndim == 2 and b.ndim == 2 assert block_scale_a.ndim == 2 and block_scale_b.ndim == 2 assert a.stride(-1) == 1 and b.stride(-1) == 1 assert a.shape[1] == b.shape[1] if backend == "cutlass": block_scale_a = block_scale_a.view(torch.uint8) block_scale_b = block_scale_b.view(torch.uint8) return flashinfer_mm_fp4( a, b.t(), block_scale_a, block_scale_b.t(), alpha, out_dtype, backend=backend, ) def flashinfer_scaled_fp8_mm( a: torch.Tensor, b: torch.Tensor, scale_a: torch.Tensor, scale_b: torch.Tensor, out_dtype: torch.dtype, bias: torch.Tensor | None = None, ) -> torch.Tensor: assert a.ndim == 2 and b.ndim == 2 assert a.shape[1] == b.shape[0] assert scale_a.numel() == 1 and scale_b.numel() == 1 assert a.dtype == torch.float8_e4m3fn and b.dtype == torch.float8_e4m3fn assert a.device.type == "cuda" and b.device.type == "cuda" assert scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32 assert scale_a.device.type == "cuda" and scale_b.device.type == "cuda" output = bmm_fp8( a.unsqueeze(0), b.unsqueeze(0), scale_a, scale_b, out_dtype, "auto", ).view(a.shape[0], b.shape[1]) if bias is not None: output = output + bias return output __all__ = [ "has_flashinfer", "flashinfer_trtllm_fp8_block_scale_moe", "flashinfer_cutlass_fused_moe", "flashinfer_cutedsl_grouped_gemm_nt_masked", "flashinfer_fp4_quantize", "silu_and_mul_scaled_nvfp4_experts_quantize", "scaled_fp4_grouped_quantize", "nvfp4_block_scale_interleave", "trtllm_fp4_block_scale_moe", "autotune", "has_flashinfer_moe", "has_flashinfer_comm", "has_flashinfer_all2all", "has_flashinfer_cutlass_fused_moe", "has_flashinfer_cutedsl_grouped_gemm_nt_masked", "has_nvidia_artifactory", "supports_trtllm_attention", "can_use_trtllm_attention", "use_trtllm_attention", "flashinfer_scaled_fp4_mm", "flashinfer_scaled_fp8_mm", ]
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/network_utils.py
vllm/utils/network_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import contextlib import ipaddress import os import socket import sys import warnings from collections.abc import ( Iterator, Sequence, ) from typing import Any from urllib.parse import urlparse from uuid import uuid4 import psutil import zmq import zmq.asyncio import vllm.envs as envs from vllm.logger import init_logger logger = init_logger(__name__) def close_sockets(sockets: Sequence[zmq.Socket | zmq.asyncio.Socket]): for sock in sockets: if sock is not None: sock.close(linger=0) def get_ip() -> str: host_ip = envs.VLLM_HOST_IP if "HOST_IP" in os.environ and "VLLM_HOST_IP" not in os.environ: logger.warning( "The environment variable HOST_IP is deprecated and ignored, as" " it is often used by Docker and other software to" " interact with the container's network stack. Please " "use VLLM_HOST_IP instead to set the IP address for vLLM processes" " to communicate with each other." ) if host_ip: return host_ip # IP is not set, try to get it from the network interface # try ipv4 try: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.connect(("8.8.8.8", 80)) # Doesn't need to be reachable return s.getsockname()[0] except Exception: pass # try ipv6 try: with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as s: # Google's public DNS server, see # https://developers.google.com/speed/public-dns/docs/using#addresses s.connect(("2001:4860:4860::8888", 80)) # Doesn't need to be reachable return s.getsockname()[0] except Exception: pass warnings.warn( "Failed to get the IP address, using 0.0.0.0 by default." "The value can be set by the environment variable" " VLLM_HOST_IP or HOST_IP.", stacklevel=2, ) return "0.0.0.0" def test_loopback_bind(address: str, family: int) -> bool: try: s = socket.socket(family, socket.SOCK_DGRAM) s.bind((address, 0)) # Port 0 = auto assign s.close() return True except OSError: return False def get_loopback_ip() -> str: loopback_ip = envs.VLLM_LOOPBACK_IP if loopback_ip: return loopback_ip # VLLM_LOOPBACK_IP is not set, try to get it based on network interface if test_loopback_bind("127.0.0.1", socket.AF_INET): return "127.0.0.1" elif test_loopback_bind("::1", socket.AF_INET6): return "::1" else: raise RuntimeError( "Neither 127.0.0.1 nor ::1 are bound to a local interface. " "Set the VLLM_LOOPBACK_IP environment variable explicitly." ) def is_valid_ipv6_address(address: str) -> bool: try: ipaddress.IPv6Address(address) return True except ValueError: return False def split_host_port(host_port: str) -> tuple[str, int]: # ipv6 if host_port.startswith("["): host, port = host_port.rsplit("]", 1) host = host[1:] port = port.split(":")[1] return host, int(port) else: host, port = host_port.split(":") return host, int(port) def join_host_port(host: str, port: int) -> str: if is_valid_ipv6_address(host): return f"[{host}]:{port}" else: return f"{host}:{port}" def get_distributed_init_method(ip: str, port: int) -> str: return get_tcp_uri(ip, port) def get_tcp_uri(ip: str, port: int) -> str: if is_valid_ipv6_address(ip): return f"tcp://[{ip}]:{port}" else: return f"tcp://{ip}:{port}" def get_open_zmq_ipc_path() -> str: base_rpc_path = envs.VLLM_RPC_BASE_PATH return f"ipc://{base_rpc_path}/{uuid4()}" def get_open_zmq_inproc_path() -> str: return f"inproc://{uuid4()}" def get_open_port() -> int: """ Get an open port for the vLLM process to listen on. An edge case to handle, is when we run data parallel, we need to avoid ports that are potentially used by the data parallel master process. Right now we reserve 10 ports for the data parallel master process. Currently it uses 2 ports. """ if "VLLM_DP_MASTER_PORT" in os.environ: dp_master_port = envs.VLLM_DP_MASTER_PORT reserved_port_range = range(dp_master_port, dp_master_port + 10) while True: candidate_port = _get_open_port() if candidate_port not in reserved_port_range: return candidate_port return _get_open_port() def get_open_ports_list(count: int = 5) -> list[int]: """Get a list of open ports.""" ports = set[int]() while len(ports) < count: ports.add(get_open_port()) return list(ports) def _get_open_port() -> int: port = envs.VLLM_PORT if port is not None: while True: try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("", port)) return port except OSError: port += 1 # Increment port number if already in use logger.info("Port %d is already in use, trying port %d", port - 1, port) # try ipv4 try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("", 0)) return s.getsockname()[1] except OSError: # try ipv6 with socket.socket(socket.AF_INET6, socket.SOCK_STREAM) as s: s.bind(("", 0)) return s.getsockname()[1] def find_process_using_port(port: int) -> psutil.Process | None: # TODO: We can not check for running processes with network # port on macOS. Therefore, we can not have a full graceful shutdown # of vLLM. For now, let's not look for processes in this case. # Ref: https://www.florianreinhard.de/accessdenied-in-psutil/ if sys.platform.startswith("darwin"): return None our_pid = os.getpid() for conn in psutil.net_connections(): if conn.laddr.port == port and (conn.pid is not None and conn.pid != our_pid): try: return psutil.Process(conn.pid) except psutil.NoSuchProcess: return None return None def split_zmq_path(path: str) -> tuple[str, str, str]: """Split a zmq path into its parts.""" parsed = urlparse(path) if not parsed.scheme: raise ValueError(f"Invalid zmq path: {path}") scheme = parsed.scheme host = parsed.hostname or "" port = str(parsed.port or "") if scheme == "tcp" and not all((host, port)): # The host and port fields are required for tcp raise ValueError(f"Invalid zmq path: {path}") if scheme != "tcp" and port: # port only makes sense with tcp raise ValueError(f"Invalid zmq path: {path}") return scheme, host, port def make_zmq_path(scheme: str, host: str, port: int | None = None) -> str: """Make a ZMQ path from its parts. Args: scheme: The ZMQ transport scheme (e.g. tcp, ipc, inproc). host: The host - can be an IPv4 address, IPv6 address, or hostname. port: Optional port number, only used for TCP sockets. Returns: A properly formatted ZMQ path string. """ if port is None: return f"{scheme}://{host}" if is_valid_ipv6_address(host): return f"{scheme}://[{host}]:{port}" return f"{scheme}://{host}:{port}" # Adapted from: https://github.com/sgl-project/sglang/blob/v0.4.1/python/sglang/srt/utils.py#L783 # noqa: E501 def make_zmq_socket( ctx: zmq.asyncio.Context | zmq.Context, # type: ignore[name-defined] path: str, socket_type: Any, bind: bool | None = None, identity: bytes | None = None, linger: int | None = None, ) -> zmq.Socket | zmq.asyncio.Socket: # type: ignore[name-defined] """Make a ZMQ socket with the proper bind/connect semantics.""" mem = psutil.virtual_memory() socket = ctx.socket(socket_type) # Calculate buffer size based on system memory total_mem = mem.total / 1024**3 available_mem = mem.available / 1024**3 # For systems with substantial memory (>32GB total, >16GB available): # - Set a large 0.5GB buffer to improve throughput # For systems with less memory: # - Use system default (-1) to avoid excessive memory consumption buf_size = int(0.5 * 1024**3) if total_mem > 32 and available_mem > 16 else -1 if bind is None: bind = socket_type not in (zmq.PUSH, zmq.SUB, zmq.XSUB) if socket_type in (zmq.PULL, zmq.DEALER, zmq.ROUTER): socket.setsockopt(zmq.RCVHWM, 0) socket.setsockopt(zmq.RCVBUF, buf_size) if socket_type in (zmq.PUSH, zmq.DEALER, zmq.ROUTER): socket.setsockopt(zmq.SNDHWM, 0) socket.setsockopt(zmq.SNDBUF, buf_size) if identity is not None: socket.setsockopt(zmq.IDENTITY, identity) if linger is not None: socket.setsockopt(zmq.LINGER, linger) if socket_type == zmq.XPUB: socket.setsockopt(zmq.XPUB_VERBOSE, True) # Determine if the path is a TCP socket with an IPv6 address. # Enable IPv6 on the zmq socket if so. scheme, host, _ = split_zmq_path(path) if scheme == "tcp" and is_valid_ipv6_address(host): socket.setsockopt(zmq.IPV6, 1) if bind: socket.bind(path) else: socket.connect(path) return socket @contextlib.contextmanager def zmq_socket_ctx( path: str, socket_type: Any, bind: bool | None = None, linger: int = 0, identity: bytes | None = None, ) -> Iterator[zmq.Socket]: """Context manager for a ZMQ socket""" ctx = zmq.Context() # type: ignore[attr-defined] try: yield make_zmq_socket(ctx, path, socket_type, bind=bind, identity=identity) except KeyboardInterrupt: logger.debug("Got Keyboard Interrupt.") finally: ctx.destroy(linger=linger)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/tensor_schema.py
vllm/utils/tensor_schema.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from types import UnionType from typing import Annotated, Any, Union, get_args, get_origin, get_type_hints import torch from vllm.logger import init_logger logger = init_logger(__name__) class TensorShape: def __init__( self, *dims: int | str, dynamic_dims: set[str] | None = None, ) -> None: super().__init__() self.dims = dims self.dynamic_dims = dynamic_dims if dynamic_dims else set() def resolve(self, **bindings: int) -> tuple[int | str, ...]: resolved = list[int | str]() for dim in self.dims: if isinstance(dim, str) and dim in bindings: resolved.append(bindings[dim]) else: resolved.append(dim) return tuple(resolved) def __str__(self) -> str: """Return a string representation of the tensor shape.""" dim_strs = [] for dim in self.dims: if isinstance(dim, str): if dim in self.dynamic_dims: dim_strs.append(f"{dim}*") # Mark dynamic dimensions with * else: dim_strs.append(dim) else: dim_strs.append(str(dim)) return f"({', '.join(dim_strs)})" class TensorSchema: def __init__( self, *, validate: bool = True, resolve_bindings: dict[str, int] | None = None, **kwargs: Any, ) -> None: super().__init__() self._resolve_bindings = resolve_bindings if resolve_bindings else {} for key, value in kwargs.items(): setattr(self, key, value) if validate: self.validate() def __getitem__(self, key: str) -> Any: return getattr(self, key) def get(self, key: str, default: Any = None) -> Any: return getattr(self, key, default) def _match_shape_with_dynamic( self, actual: tuple[int, ...], reference: tuple[int, ...], expected_shape: tuple[int | str, ...], dynamic_dims: set[str], ) -> bool: if len(actual) != len(reference) or len(actual) > len(expected_shape): return False for i, (a, r) in enumerate(zip(actual, reference)): # When validating list inputs, we match shape suffixes only # (e.g. "p", 3, "h", "w"), assuming the list length corresponds # to the leading symbolic dim (e.g. "bn"). This allows comparing # only the trailing dimensions of each element in the list. dim = expected_shape[-len(actual) + i] # Skip this dimension if it's marked dynamic if dim in dynamic_dims: continue if a != r: return False return True def _fmt_indexer(self, idxs: tuple[int, ...]) -> str: if not idxs: return "" return str(list(idxs)) def _validate_field( self, value: object, field_name: str, expected_shape: tuple[int | str, ...], dynamic_dims: set[str], leading_idxs: tuple[int, ...] = (), ) -> tuple[int, ...]: """Validate a field and return the actual shape.""" if isinstance(value, (int, float)): return () # Scalar if isinstance(value, torch.Tensor): return value.shape if not isinstance(value, (list, tuple)): raise TypeError( f"{field_name}{self._fmt_indexer(leading_idxs)} is not " f"one of the expected types: int, float, Tensor, list, tuple. " f"Got: {type(value)}" ) if len(value) == 0: raise ValueError( f"{field_name}{self._fmt_indexer(leading_idxs)} is an empty sequence" ) # Ensure all tensors in the list have the same # shape, besides dynamic dimensions for i, v in enumerate(value): shape = self._validate_field( v, field_name, expected_shape[1:], dynamic_dims, leading_idxs=leading_idxs + (i,), ) if i == 0: first_shape = shape elif not self._match_shape_with_dynamic( shape, first_shape, expected_shape, dynamic_dims, ): raise ValueError( f"{field_name}{self._fmt_indexer(leading_idxs)} " f"contains inconsistent shapes: {first_shape} " f"(index 0) vs {shape} (index {i})" ) # Treat the list as a stacked tensor: # shape = (len(list), *tensor.shape) return (len(value),) + first_shape def _validate_tensor_shape_expected( self, actual_shape: tuple[int, ...], expected_shape: tuple[int | str, ...], field_name: str, shape_env: dict[str, int], dynamic_dims: set[str], ) -> None: """Validate that the actual tensor shape matches the expected shape.""" if len(actual_shape) != len(expected_shape): raise ValueError( f"{field_name} has rank {len(actual_shape)} " f"but expected {len(expected_shape)}. " f"Expected shape: {expected_shape}, " f"but got {actual_shape}" ) for i, dim in enumerate(expected_shape): if dim in dynamic_dims: continue elif isinstance(dim, int): if actual_shape[i] != dim: raise ValueError( f"{field_name} dim[{i}] expected " f"{dim}, got {actual_shape[i]}. " f"Expected shape: {expected_shape}, " f"but got {actual_shape}" ) elif isinstance(dim, str): if dim in shape_env: if actual_shape[i] != shape_env[dim]: raise ValueError( f"{field_name} dim[{i}] expected " f"'{dim}'={shape_env[dim]}, got " f"{actual_shape[i]}" ) else: shape_env[dim] = actual_shape[i] else: raise TypeError( f"{field_name} dim[{i}] has unsupported type: {type(dim)}" ) def validate(self) -> None: type_hints = get_type_hints(self.__class__, include_extras=True) shape_env = dict[str, int]() for field_name, field_type in type_hints.items(): # Check if field is missing if not hasattr(self, field_name) or getattr(self, field_name) is None: # Check if field is marked as optional actual_type = field_type if get_origin(field_type) is Annotated: args = get_args(field_type) actual_type = args[0] # Check arg was provided as Union if get_origin(actual_type) in {Union, UnionType}: # Union for Union[X, Y] and UnionType for X | Y args = get_args(actual_type) # Skip validation when Union contains None if type(None) in args: continue # Otherwise field is required, raise error raise ValueError(f"Required field '{field_name}' is missing") # Field exists, proceed with validation value = getattr(self, field_name) if get_origin(field_type) is not None: args = get_args(field_type) for arg in args: if isinstance(arg, TensorShape): expected_shape = arg.resolve(**self._resolve_bindings) actual_shape = self._validate_field( value, field_name, expected_shape, arg.dynamic_dims, ) self._validate_tensor_shape_expected( actual_shape, expected_shape, field_name, shape_env, arg.dynamic_dims, ) def print_shapes(self) -> None: """Print TensorShape annotations for debugging.""" logger.debug("Shapes in %s:", self.__class__.__name__) type_hints = get_type_hints(self.__class__, include_extras=True) for field_name, field_type in type_hints.items(): if get_origin(field_type) is not None: args = get_args(field_type) for arg in args: if isinstance(arg, TensorShape): logger.debug(" %s: %s", field_name, str(arg))
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/nccl.py
vllm/utils/nccl.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from __future__ import annotations import importlib.util import os import torch import vllm.envs as envs from vllm.logger import init_logger logger = init_logger(__name__) def find_nccl_library() -> str: """Return NCCL/RCCL shared library name to load. Uses `VLLM_NCCL_SO_PATH` if set; otherwise chooses by torch backend. """ so_file = envs.VLLM_NCCL_SO_PATH if so_file: logger.info( "Found nccl from environment variable VLLM_NCCL_SO_PATH=%s", so_file ) else: if torch.version.cuda is not None: so_file = "libnccl.so.2" elif torch.version.hip is not None: so_file = "librccl.so.1" else: raise ValueError("NCCL only supports CUDA and ROCm backends.") logger.debug_once("Found nccl from library %s", so_file) return so_file def find_nccl_include_paths() -> list[str] | None: """Return possible include paths containing `nccl.h`. Considers `VLLM_NCCL_INCLUDE_PATH` and the `nvidia-nccl-cuXX` package. """ paths: list[str] = [] inc = envs.VLLM_NCCL_INCLUDE_PATH if inc and os.path.isdir(inc): paths.append(inc) try: spec = importlib.util.find_spec("nvidia.nccl") if spec and (locs := getattr(spec, "submodule_search_locations", None)): for loc in locs: inc_dir = os.path.join(loc, "include") if os.path.exists(os.path.join(inc_dir, "nccl.h")): paths.append(inc_dir) except Exception as e: logger.debug("Failed to find nccl include path from nvidia.nccl package: %s", e) seen: set[str] = set() out: list[str] = [] for p in paths: if p and p not in seen: out.append(p) seen.add(p) return out or None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/__init__.py
vllm/utils/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import uuid import torch MASK_64_BITS = (1 << 64) - 1 def random_uuid() -> str: return f"{uuid.uuid4().int & MASK_64_BITS:016x}" # 16 hex chars def length_from_prompt_token_ids_or_embeds( prompt_token_ids: list[int] | None, prompt_embeds: torch.Tensor | None, ) -> int: """Calculate the request length (in number of tokens) give either prompt_token_ids or prompt_embeds. """ prompt_token_len = None if prompt_token_ids is None else len(prompt_token_ids) prompt_embeds_len = None if prompt_embeds is None else len(prompt_embeds) if prompt_token_len is None: if prompt_embeds_len is None: raise ValueError("Neither prompt_token_ids nor prompt_embeds were defined.") return prompt_embeds_len else: if prompt_embeds_len is not None and prompt_embeds_len != prompt_token_len: raise ValueError( "Prompt token ids and prompt embeds had different lengths" f" prompt_token_ids={prompt_token_len}" f" prompt_embeds={prompt_embeds_len}" ) return prompt_token_len
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/import_utils.py
vllm/utils/import_utils.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # SPDX-FileCopyrightText: Copyright contributors to the vLLM project """ Contains helpers related to importing modules. This is similar in concept to the `importlib` module. """ import importlib.metadata import importlib.util import os import sys from functools import cache from types import ModuleType from typing import Any import regex as re from typing_extensions import Never from vllm.logger import init_logger logger = init_logger(__name__) # TODO: This function can be removed if transformer_modules classes are # serialized by value when communicating between processes def init_cached_hf_modules() -> None: """ Lazy initialization of the Hugging Face modules. """ from transformers.dynamic_module_utils import init_hf_modules init_hf_modules() def import_pynvml(): """ Historical comments: libnvml.so is the library behind nvidia-smi, and pynvml is a Python wrapper around it. We use it to get GPU status without initializing CUDA context in the current process. Historically, there are two packages that provide pynvml: - `nvidia-ml-py` (https://pypi.org/project/nvidia-ml-py/): The official wrapper. It is a dependency of vLLM, and is installed when users install vLLM. It provides a Python module named `pynvml`. - `pynvml` (https://pypi.org/project/pynvml/): An unofficial wrapper. Prior to version 12.0, it also provides a Python module `pynvml`, and therefore conflicts with the official one. What's worse, the module is a Python package, and has higher priority than the official one which is a standalone Python file. This causes errors when both of them are installed. Starting from version 12.0, it migrates to a new module named `pynvml_utils` to avoid the conflict. It is so confusing that many packages in the community use the unofficial one by mistake, and we have to handle this case. For example, `nvcr.io/nvidia/pytorch:24.12-py3` uses the unofficial one, and it will cause errors, see the issue https://github.com/vllm-project/vllm/issues/12847 for example. After all the troubles, we decide to copy the official `pynvml` module to our codebase, and use it directly. """ import vllm.third_party.pynvml as pynvml return pynvml @cache def import_triton_kernels(): """ For convenience, prioritize triton_kernels that is available in `site-packages`. Use `vllm.third_party.triton_kernels` as a fall-back. """ if _has_module("triton_kernels"): import triton_kernels logger.debug_once( f"Loading module triton_kernels from {triton_kernels.__file__}.", scope="local", ) elif _has_module("vllm.third_party.triton_kernels"): import vllm.third_party.triton_kernels as triton_kernels logger.debug_once( f"Loading module triton_kernels from {triton_kernels.__file__}.", scope="local", ) sys.modules["triton_kernels"] = triton_kernels else: logger.info_once( "triton_kernels unavailable in this build. " "Please consider installing triton_kernels from " "https://github.com/triton-lang/triton/tree/main/python/triton_kernels" ) def import_from_path(module_name: str, file_path: str | os.PathLike): """ Import a Python file according to its file path. Based on the official recipe: https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly """ spec = importlib.util.spec_from_file_location(module_name, file_path) if spec is None: raise ModuleNotFoundError(f"No module named {module_name!r}") assert spec.loader is not None module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) return module def resolve_obj_by_qualname(qualname: str) -> Any: """ Resolve an object by its fully-qualified class name. """ module_name, obj_name = qualname.rsplit(".", 1) module = importlib.import_module(module_name) return getattr(module, obj_name) @cache def get_vllm_optional_dependencies(): metadata = importlib.metadata.metadata("vllm") requirements = metadata.get_all("Requires-Dist", []) extras = metadata.get_all("Provides-Extra", []) return { extra: [ re.split(r";|>=|<=|==", req)[0] for req in requirements if req.endswith(f'extra == "{extra}"') ] for extra in extras } class _PlaceholderBase: """ Disallows downstream usage of placeholder modules. We need to explicitly override each dunder method because [`__getattr__`][vllm.utils.import_utils._PlaceholderBase.__getattr__] is not called when they are accessed. Info: [Special method lookup](https://docs.python.org/3/reference/datamodel.html#special-lookup) """ def __getattr__(self, key: str) -> Never: """ The main class should implement this to throw an error for attribute accesses representing downstream usage. """ raise NotImplementedError # [Basic customization] def __lt__(self, other: object): return self.__getattr__("__lt__") def __le__(self, other: object): return self.__getattr__("__le__") def __eq__(self, other: object): return self.__getattr__("__eq__") def __ne__(self, other: object): return self.__getattr__("__ne__") def __gt__(self, other: object): return self.__getattr__("__gt__") def __ge__(self, other: object): return self.__getattr__("__ge__") def __hash__(self): return self.__getattr__("__hash__") def __bool__(self): return self.__getattr__("__bool__") # [Callable objects] def __call__(self, *args: object, **kwargs: object): return self.__getattr__("__call__") # [Container types] def __len__(self): return self.__getattr__("__len__") def __getitem__(self, key: object): return self.__getattr__("__getitem__") def __setitem__(self, key: object, value: object): return self.__getattr__("__setitem__") def __delitem__(self, key: object): return self.__getattr__("__delitem__") # __missing__ is optional according to __getitem__ specification, # so it is skipped # __iter__ and __reversed__ have a default implementation # based on __len__ and __getitem__, so they are skipped. # [Numeric Types] def __add__(self, other: object): return self.__getattr__("__add__") def __sub__(self, other: object): return self.__getattr__("__sub__") def __mul__(self, other: object): return self.__getattr__("__mul__") def __matmul__(self, other: object): return self.__getattr__("__matmul__") def __truediv__(self, other: object): return self.__getattr__("__truediv__") def __floordiv__(self, other: object): return self.__getattr__("__floordiv__") def __mod__(self, other: object): return self.__getattr__("__mod__") def __divmod__(self, other: object): return self.__getattr__("__divmod__") def __pow__(self, other: object, modulo: object = ...): return self.__getattr__("__pow__") def __lshift__(self, other: object): return self.__getattr__("__lshift__") def __rshift__(self, other: object): return self.__getattr__("__rshift__") def __and__(self, other: object): return self.__getattr__("__and__") def __xor__(self, other: object): return self.__getattr__("__xor__") def __or__(self, other: object): return self.__getattr__("__or__") # r* and i* methods have lower priority than # the methods for left operand so they are skipped def __neg__(self): return self.__getattr__("__neg__") def __pos__(self): return self.__getattr__("__pos__") def __abs__(self): return self.__getattr__("__abs__") def __invert__(self): return self.__getattr__("__invert__") # __complex__, __int__ and __float__ have a default implementation # based on __index__, so they are skipped. def __index__(self): return self.__getattr__("__index__") def __round__(self, ndigits: object = ...): return self.__getattr__("__round__") def __trunc__(self): return self.__getattr__("__trunc__") def __floor__(self): return self.__getattr__("__floor__") def __ceil__(self): return self.__getattr__("__ceil__") # [Context managers] def __enter__(self): return self.__getattr__("__enter__") def __exit__(self, *args: object, **kwargs: object): return self.__getattr__("__exit__") class PlaceholderModule(_PlaceholderBase): """ A placeholder object to use when a module does not exist. This enables more informative errors when trying to access attributes of a module that does not exist. """ def __init__(self, name: str) -> None: super().__init__() # Apply name mangling to avoid conflicting with module attributes self.__name = name def placeholder_attr(self, attr_path: str): return _PlaceholderModuleAttr(self, attr_path) def __getattr__(self, key: str) -> Never: name = self.__name try: importlib.import_module(name) except ImportError as exc: for extra, names in get_vllm_optional_dependencies().items(): if name in names: msg = f"Please install vllm[{extra}] for {extra} support" raise ImportError(msg) from exc raise exc raise AssertionError( "PlaceholderModule should not be used " "when the original module can be imported" ) class _PlaceholderModuleAttr(_PlaceholderBase): def __init__(self, module: PlaceholderModule, attr_path: str) -> None: super().__init__() # Apply name mangling to avoid conflicting with module attributes self.__module = module self.__attr_path = attr_path def placeholder_attr(self, attr_path: str): return _PlaceholderModuleAttr(self.__module, f"{self.__attr_path}.{attr_path}") def __getattr__(self, key: str) -> Never: getattr(self.__module, f"{self.__attr_path}.{key}") raise AssertionError( "PlaceholderModule should not be used " "when the original module can be imported" ) class LazyLoader(ModuleType): """ `LazyLoader` module borrowed from [Tensorflow] (https://github.com/tensorflow/tensorflow/blob/main/tensorflow/python/util/lazy_loader.py) with an addition of "module caching". Lazily import a module, mainly to avoid pulling in large dependencies. Modules such as `xgrammar` might do additional side effects, so we only want to use this when it is needed, delaying all eager effects. """ def __init__( self, local_name: str, parent_module_globals: dict[str, Any], name: str, ): self._local_name = local_name self._parent_module_globals = parent_module_globals self._module: ModuleType | None = None super().__init__(str(name)) def _load(self) -> ModuleType: # Import the target module and insert it into the parent's namespace try: module = importlib.import_module(self.__name__) self._parent_module_globals[self._local_name] = module # The additional add to sys.modules # ensures library is actually loaded. sys.modules[self._local_name] = module except ModuleNotFoundError as err: raise err from None # Update this object's dict so that if someone keeps a # reference to the LazyLoader, lookups are efficient # (__getattr__ is only called on lookups that fail). self.__dict__.update(module.__dict__) return module def __getattr__(self, item: Any) -> Any: if self._module is None: self._module = self._load() return getattr(self._module, item) def __dir__(self) -> list[str]: if self._module is None: self._module = self._load() return dir(self._module) # Optional dependency detection utilities @cache def _has_module(module_name: str) -> bool: """Return True if *module_name* can be found in the current environment. The result is cached so that subsequent queries for the same module incur no additional overhead. """ return importlib.util.find_spec(module_name) is not None def has_pplx() -> bool: """Whether the optional `pplx_kernels` package is available.""" return _has_module("pplx_kernels") def has_deep_ep() -> bool: """Whether the optional `deep_ep` package is available.""" return _has_module("deep_ep") def has_deep_gemm() -> bool: """Whether the optional `deep_gemm` package is available.""" return _has_module("deep_gemm") def has_triton_kernels() -> bool: """Whether the optional `triton_kernels` package is available.""" is_available = _has_module("triton_kernels") or _has_module( "vllm.third_party.triton_kernels" ) if is_available: import_triton_kernels() return is_available def has_tilelang() -> bool: """Whether the optional `tilelang` package is available.""" return _has_module("tilelang") def has_arctic_inference() -> bool: """Whether the optional `arctic_inference` package is available.""" return _has_module("arctic_inference")
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/hashing.py
vllm/utils/hashing.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from __future__ import annotations import hashlib import pickle from _hashlib import HASH, UnsupportedDigestmodError from collections.abc import Callable from typing import Any import cbor2 try: # It is important that this remains an optional dependency. # It would not be allowed in environments with strict security controls, # so it's best not to have it installed when not in use. import xxhash as _xxhash if not hasattr(_xxhash, "xxh3_128_digest"): _xxhash = None except ImportError: # pragma: no cover _xxhash = None def sha256(input: Any) -> bytes: """Hash any picklable Python object using SHA-256. The input is serialized using pickle before hashing, which allows arbitrary Python objects to be used. Note that this function does not use a hash seed—if you need one, prepend it explicitly to the input. Args: input: Any picklable Python object. Returns: Bytes representing the SHA-256 hash of the serialized input. """ input_bytes = pickle.dumps(input, protocol=pickle.HIGHEST_PROTOCOL) return hashlib.sha256(input_bytes).digest() def sha256_cbor(input: Any) -> bytes: """Hash objects using CBOR serialization and SHA-256. This option is useful for non-Python-dependent serialization and hashing. Args: input: Object to be serialized and hashed. Supported types include basic Python types and complex structures like lists, tuples, and dictionaries. Custom classes must implement CBOR serialization methods. Returns: Bytes representing the SHA-256 hash of the CBOR serialized input. """ input_bytes = cbor2.dumps(input, canonical=True) return hashlib.sha256(input_bytes).digest() def _xxhash_digest(input_bytes: bytes) -> bytes: if _xxhash is None: raise ModuleNotFoundError( "xxhash is required for the 'xxhash' prefix caching hash algorithms. " "Install it via `pip install xxhash`." ) return _xxhash.xxh3_128_digest(input_bytes) def xxhash(input: Any) -> bytes: """Hash picklable objects using xxHash.""" input_bytes = pickle.dumps(input, protocol=pickle.HIGHEST_PROTOCOL) return _xxhash_digest(input_bytes) def xxhash_cbor(input: Any) -> bytes: """Hash objects serialized with CBOR using xxHash.""" input_bytes = cbor2.dumps(input, canonical=True) return _xxhash_digest(input_bytes) def get_hash_fn_by_name(hash_fn_name: str) -> Callable[[Any], bytes]: """Get a hash function by name, or raise an error if the function is not found. Args: hash_fn_name: Name of the hash function. Returns: A hash function. """ if hash_fn_name == "sha256": return sha256 if hash_fn_name == "sha256_cbor": return sha256_cbor if hash_fn_name == "xxhash": return xxhash if hash_fn_name == "xxhash_cbor": return xxhash_cbor raise ValueError(f"Unsupported hash function: {hash_fn_name}") def safe_hash(data: bytes, usedforsecurity: bool = True) -> HASH: """Hash for configs, defaulting to md5 but falling back to sha256 in FIPS constrained environments. Args: data: bytes usedforsecurity: Whether the hash is used for security purposes Returns: Hash object """ try: return hashlib.md5(data, usedforsecurity=usedforsecurity) except (UnsupportedDigestmodError, ValueError): return hashlib.sha256(data)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/cache.py
vllm/utils/cache.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections import UserDict from collections.abc import Callable, Hashable, Iterator, KeysView, Mapping from types import MappingProxyType from typing import NamedTuple, TypeVar, cast, overload import cachetools _K = TypeVar("_K", bound=Hashable) _V = TypeVar("_V") _T = TypeVar("_T") class _Sentinel: ... ALL_PINNED_SENTINEL = _Sentinel() class _MappingOrderCacheView(UserDict[_K, _V]): def __init__(self, data: Mapping[_K, _V], ordered_keys: Mapping[_K, None]): super().__init__(data) self.ordered_keys = ordered_keys def __iter__(self) -> Iterator[_K]: return iter(self.ordered_keys) def keys(self) -> KeysView[_K]: return KeysView(self.ordered_keys) class CacheInfo(NamedTuple): hits: int total: int @property def hit_ratio(self) -> float: if self.total == 0: return 0 return self.hits / self.total def __sub__(self, other: "CacheInfo"): return CacheInfo( hits=self.hits - other.hits, total=self.total - other.total, ) class LRUCache(cachetools.LRUCache[_K, _V]): def __init__(self, capacity: float, getsizeof: Callable[[_V], float] | None = None): super().__init__(capacity, getsizeof) self.pinned_items = set[_K]() self._hits = 0 self._total = 0 self._last_info = CacheInfo(hits=0, total=0) def __getitem__(self, key: _K, *, update_info: bool = True) -> _V: value = super().__getitem__(key) if update_info: self._hits += 1 self._total += 1 return value def __delitem__(self, key: _K) -> None: run_on_remove = key in self value = self.__getitem__(key, update_info=False) # type: ignore[call-arg] super().__delitem__(key) if key in self.pinned_items: # Todo: add warning to inform that del pinned item self._unpin(key) if run_on_remove: self._on_remove(key, value) @property def cache(self) -> Mapping[_K, _V]: """Return the internal cache dictionary in order (read-only).""" return _MappingOrderCacheView( self._Cache__data, # type: ignore self.order, ) @property def order(self) -> Mapping[_K, None]: """Return the internal order dictionary (read-only).""" return MappingProxyType(self._LRUCache__order) # type: ignore @property def capacity(self) -> float: return self.maxsize @property def usage(self) -> float: if self.maxsize == 0: return 0 return self.currsize / self.maxsize def stat(self, *, delta: bool = False) -> CacheInfo: """ Gets the cumulative number of hits and queries against this cache. If `delta=True`, instead gets these statistics since the last call that also passed `delta=True`. """ info = CacheInfo(hits=self._hits, total=self._total) if delta: info_delta = info - self._last_info self._last_info = info info = info_delta return info def touch(self, key: _K) -> None: try: self._LRUCache__order.move_to_end(key) # type: ignore except KeyError: self._LRUCache__order[key] = None # type: ignore @overload def get(self, key: _K, /) -> _V | None: ... @overload def get(self, key: _K, /, default: _V | _T) -> _V | _T: ... def get(self, key: _K, /, default: _V | _T | None = None) -> _V | _T | None: value: _V | _T | None if key in self: value = self.__getitem__(key, update_info=False) # type: ignore[call-arg] self._hits += 1 else: value = default self._total += 1 return value @overload def pop(self, key: _K) -> _V: ... @overload def pop(self, key: _K, default: _V | _T) -> _V | _T: ... def pop(self, key: _K, default: _V | _T | None = None) -> _V | _T | None: value: _V | _T | None if key not in self: return default value = self.__getitem__(key, update_info=False) # type: ignore[call-arg] self.__delitem__(key) return value def put(self, key: _K, value: _V) -> None: self.__setitem__(key, value) def pin(self, key: _K) -> None: """ Pins a key in the cache preventing it from being evicted in the LRU order. """ if key not in self: raise ValueError(f"Cannot pin key: {key} not in cache.") self.pinned_items.add(key) def _unpin(self, key: _K) -> None: """ Unpins a key in the cache allowing it to be evicted in the LRU order. """ self.pinned_items.remove(key) def _on_remove(self, key: _K, value: _V | None) -> None: pass def remove_oldest(self, *, remove_pinned: bool = False) -> None: if len(self) == 0: return self.popitem(remove_pinned=remove_pinned) def _remove_old_if_needed(self) -> None: while self.currsize > self.capacity: self.remove_oldest() def popitem(self, remove_pinned: bool = False): """Remove and return the `(key, value)` pair least recently used.""" if not remove_pinned: # pop the oldest item in the cache that is not pinned lru_key = next( (key for key in self.order if key not in self.pinned_items), ALL_PINNED_SENTINEL, ) if lru_key is ALL_PINNED_SENTINEL: raise RuntimeError( "All items are pinned, cannot remove oldest from the cache." ) else: lru_key = next(iter(self.order)) value = self.pop(cast(_K, lru_key)) return (lru_key, value) def clear(self) -> None: while len(self) > 0: self.remove_oldest(remove_pinned=True) self._hits = 0 self._total = 0 self._last_info = CacheInfo(hits=0, total=0)
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/profiling.py
vllm/utils/profiling.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from __future__ import annotations import contextlib from collections.abc import Callable from functools import wraps from typing import Any @contextlib.contextmanager def cprofile_context(save_file: str | None = None): """Run a cprofile Args: save_file: path to save the profile result. "1" or None will result in printing to stdout. """ import cProfile prof = cProfile.Profile() prof.enable() try: yield finally: prof.disable() if save_file and save_file != "1": prof.dump_stats(save_file) else: prof.print_stats(sort="cumtime") def cprofile(save_file: str | None = None, enabled: bool = True): """Decorator to profile a Python method using cProfile. Args: save_file: Path to save the profile result. If "1", None, or "", results will be printed to stdout. enabled: Set to false to turn this into a no-op """ def decorator(func: Callable): @wraps(func) def wrapper(*args: Any, **kwargs: Any): if not enabled: # If profiling is disabled, just call the function directly. return func(*args, **kwargs) with cprofile_context(save_file): return func(*args, **kwargs) return wrapper return decorator
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/utils/mem_constants.py
vllm/utils/mem_constants.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project MB_bytes = 1_000_000 """The number of bytes in one megabyte (MB).""" MiB_bytes = 1 << 20 """The number of bytes in one mebibyte (MiB).""" GB_bytes = 1_000_000_000 """The number of bytes in one gigabyte (GB).""" GiB_bytes = 1 << 30 """The number of bytes in one gibibyte (GiB)."""
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/minimax_m2_reasoning_parser.py
vllm/reasoning/minimax_m2_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Sequence from vllm.entrypoints.openai.protocol import ( ChatCompletionRequest, DeltaMessage, ResponsesRequest, ) from vllm.logger import init_logger from vllm.reasoning.abs_reasoning_parsers import ReasoningParser from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser from vllm.tokenizers import TokenizerLike logger = init_logger(__name__) class MiniMaxM2ReasoningParser(BaseThinkingReasoningParser): """ Reasoning parser for MiniMax M2 model. MiniMax M2 models don't generate <think> start token, only </think> end token. All content before </think> is reasoning, content after is the actual response. """ @property def start_token(self) -> str: """The token that starts reasoning content.""" return "<think>" @property def end_token(self) -> str: """The token that ends reasoning content.""" return "</think>" def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: """ Extract reasoning content from a delta message for streaming. MiniMax M2 models don't generate <think> start token, so we assume all content is reasoning until we encounter the </think> end token. """ # Skip single end token if len(delta_token_ids) == 1 and delta_token_ids[0] == self.end_token_id: return None # Check if end token has already appeared in previous tokens # meaning we're past the reasoning phase if self.end_token_id in previous_token_ids: # We're past the reasoning phase, this is content return DeltaMessage(content=delta_text) # Check if end token is in delta tokens if self.end_token_id in delta_token_ids: # End token in delta, split reasoning and content end_index = delta_text.find(self.end_token) reasoning = delta_text[:end_index] content = delta_text[end_index + len(self.end_token) :] return DeltaMessage( reasoning=reasoning if reasoning else None, content=content if content else None, ) # No end token yet, all content is reasoning return DeltaMessage(reasoning=delta_text) class MiniMaxM2AppendThinkReasoningParser(ReasoningParser): """ Reasoning parser for MiniMax M2 model. """ def __init__(self, tokenizer: TokenizerLike, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) self.end_token_id = self.vocab.get("</think>") def is_reasoning_end(self, input_ids: list[int]) -> bool: end_token_id = self.end_token_id return any(input_id == end_token_id for input_id in reversed(input_ids)) def extract_content_ids(self, input_ids: list[int]) -> list[int]: return input_ids def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: if len(previous_token_ids) == 0: delta_text = "<think>" + delta_text return DeltaMessage(content=delta_text) def extract_reasoning( self, model_output: str, request: ChatCompletionRequest | ResponsesRequest ) -> tuple[str | None, str | None]: return None, "<think>" + model_output
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/glm4_moe_reasoning_parser.py
vllm/reasoning/glm4_moe_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser class Glm4MoeModelReasoningParser(DeepSeekR1ReasoningParser): """ Reasoning parser for the Glm4MoeModel model is same as DeepSeekR1ReasoningParser. """ pass
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/granite_reasoning_parser.py
vllm/reasoning/granite_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Sequence import regex as re from transformers import PreTrainedTokenizerBase from vllm.entrypoints.openai.protocol import ChatCompletionRequest, DeltaMessage from vllm.logger import init_logger from vllm.reasoning import ReasoningParser logger = init_logger(__name__) class GraniteReasoningParser(ReasoningParser): """ Reasoning parser for IBM Granite. IBM granite models currently use "Here is my thought process:" and "Here is my response:" to separate its thinking / response outputs. """ def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) # NOTE: There have been some observed occurrences of quantized # instances of the current models using "Here's" instead of "Here is", # so to be safe, we match on both. self.think_start_expr = r"(?:Here's|Here is) my thought process:" self.response_start_expr = r"(?:Here's|Here is) my response:" self.reasoning_regex = re.compile( rf"{self.think_start_expr}(.*?){self.response_start_expr}(.*)", re.DOTALL ) self.valid_think_starts = [ "Here's my thought process:", "Here is my thought process:", ] self.valid_response_starts = ["Here's my response:", "Here is my response:"] # Substrings to match for sequence boundaries on raw text self.seq_boundary_end = ":" self.seq_boundary_start = "Here" # The longest any thinking / start of response message can be self.longest_think_start = max( len(think_start) for think_start in self.valid_think_starts ) def extract_reasoning( self, model_output: str, request: ChatCompletionRequest ) -> tuple[str | None, str | None]: """Extract the reasoning content & content sections, respectively. If the sequence doesn't match what we expect, i.e., the model generates something else, all content is considered non-reasoning content. Args: model_output (str): Output of the model to be parsed. request (ChatCompletionRequest): Request being processed. Returns: tuple[Optional[str], Optional[str]]: Tuple pair containing the reasoning content and non-reasoning content. """ re_match = self.reasoning_regex.findall(model_output) if not re_match: return None, model_output reasoning, response_content = re_match[0] if not response_content: return reasoning, None return reasoning, response_content def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: """Extract the reasoning content / content emitted by granite models; If the sequence doesn't match what we expect, i.e., the model generates something else, all content is considered non-reasoning content. NOTE: Granite models do not use a special token to start their reasoning and response sections; instead they have token sequences, e.g., Here is my thought process: Foo Here is my response: Bar This increases the complexity of correctly handling streams, since we need to watch for specific sequences and correctly parse them without dropping content that is potentially overlapping & spanning multiple delta messages. Args: previous_text (str): Previous text outside of this delta message. current_text (str): Previous text + delta text. delta_text (str): Text to consider and parse content from. previous_token_ids (Sequence[int]): Token IDs of previous_text. current_token_ids (Sequence[int]): Token IDs of current_text. delta_token_ids (Sequence[int]): Token IDs of delta_text. Returns: Union[DeltaMessage, None] DeltaMessage with either reasoning content or content, or None. """ reasoning, resp_seq_len, content = self._get_content_sections(current_text) # Either we haven't finished the start of the reasoning sequence, # or the model is generating something unexpected. if not reasoning: delta_message = self._get_delta_message_with_no_reasoning_bounds( current_text, delta_text ) # We have a start of reasoning message, but have not yet finished # the start of response sequence. elif not content: delta_message = self._get_delta_message_with_no_response_bounds( current_text, reasoning, delta_text ) # We've finished both the start of reasoning and start of response seq. else: # This should never happen since we matched on the response assert resp_seq_len is not None delta_message = self._get_delta_message_with_both_bounds( delta_text, reasoning, content, current_text, resp_seq_len ) if not delta_message.content and not delta_message.reasoning: return None return delta_message #### Implementation details of stream parsing for granite models def _is_reasoning_start_substr(self, text: str) -> bool: """Check if a text matches one of the possible start reasoning seqs. Args: text (str): Text to check for leading substr. Returns: bool: True if any of the possible reasoning start seqs match. """ return any( think_start.startswith(text) for think_start in self.valid_think_starts ) def _is_response_start_substr(self, text: str) -> bool: """Check if a text matches one of the possible start response seqs. Args: text (str): Text to check for leading substr. Returns: bool: True if any of the possible response start seqs match. """ return any( response_start.startswith(text) for response_start in self.valid_response_starts ) def _get_delta_message_with_no_reasoning_bounds( self, current_text: str, delta_text: str, ) -> DeltaMessage: """Parse the delta message when the current text has not yet completed its start of reasoning sequence. Args: current_text (str): The full previous + delta text. delta_text (str): Text to consider and parse content from. Returns: DeltaMessage: Message containing the parsed content. """ prev_longest_length = len(current_text) - len(delta_text) is_substr = self._is_reasoning_start_substr(current_text) was_substr = self._is_reasoning_start_substr(current_text[:prev_longest_length]) # Check if we just generated something NOT in the special token seq; # if so, add everything that we previously skipped with this delta # message and append everything to content in the future. if was_substr and not is_substr: return DeltaMessage( reasoning=None, content=current_text, ) if is_substr: # Might still be in the special token sequence; return nothing return DeltaMessage(reasoning=None, content=None) # Otherwise the sequence has already been broken and we already # corrected; just return the delta text as normal content. return DeltaMessage(reasoning=None, content=delta_text) def _get_delta_message_with_no_response_bounds( self, current_text: str, reasoning: str, delta_text: str, ) -> DeltaMessage: """Parse the delta message when the current text has both reasoning content with no (response) content. NOTE that we may have overlapping tokens with the start of reasoning / start of response sequences on either side of the delta text. Args: current_text (str): The full previous + delta text. reasoning (str): reasoning content from current_text. delta_text (str): Text to consider and parse content from. Returns: DeltaMessage: Message containing the parsed content. """ # If we have no reasoning content or explicitly end with the start of # response sequence, we are in transition to the response; need to be # careful here, since the final token (:) will match the reasoning # content and fully parse it out; we should not pass the : back. ends_with_start_response_seq = any( current_text.endswith(response_start) for response_start in self.valid_response_starts ) if reasoning is None or ends_with_start_response_seq: return DeltaMessage(reasoning=None, content=None) # Consider previous / current text only within context of the reasoning previous_text = reasoning[: -len(delta_text)] current_text = reasoning # We need to be careful about adding unfinished response sequences; # Find the place at which we MIGHT be starting a response sequence prev_idx = previous_text.rfind(self.seq_boundary_start) delta_idx = delta_text.rfind(self.seq_boundary_start) # Check the state of potential start of response substring matches. prev_was_substr = ( self._is_response_start_substr(previous_text[prev_idx:]) if prev_idx >= 0 else False ) delta_continues_substr = ( self._is_response_start_substr(current_text[prev_idx:]) if prev_idx >= 0 else False ) delta_new_substr = ( self._is_response_start_substr(delta_text[delta_idx:]) if delta_idx >= 0 else False ) # Delta only contains potential continued response sequence text. if delta_continues_substr: return DeltaMessage(reasoning=None, content=None) if not prev_was_substr: # Delta may be starting a new response seq but has other text too. if delta_new_substr: return DeltaMessage(reasoning=delta_text[:delta_idx], content=None) # Normal case for most reasoning text (no potential special seqs). return DeltaMessage(reasoning=delta_text, content=None) # The substring that previously seemed to be a potential response # seq wasn't one; we need to add the content to the delta message, # and also slice off the potential response sequence elif delta_new_substr: reasoning = previous_text[prev_idx:] + delta_text[:delta_idx] return DeltaMessage(reasoning=reasoning, content=None) # No new substring yet, and we broke our old one; take the whole delta return DeltaMessage( reasoning=previous_text[prev_idx:] + delta_text, content=None, ) def _get_delta_message_with_both_bounds( self, delta_text: str, reasoning: str, response_content: str, current_text: str, response_seq_len: int, ) -> DeltaMessage: """Parse the delta message when the current text has both reasoning content and normal (response) content. Args: delta_text: Text to consider and parse content from. reasoning: reasoning content from current_text. response_content: response content from current_text. current_text: The full previous + delta text. response_seq_len: Len of the complete response sequence used. Returns: DeltaMessage: Message containing the parsed content. """ # Always have content; take length to the end delta_content = delta_text[-len(response_content) :] reasoning_end_idx = len(delta_text) - (len(response_content) + response_seq_len) if reasoning_end_idx < 0: delta_reasoning = None else: # Get the starting offset start_reasoning_idx = ( len(reasoning) + response_seq_len + len(response_content) - 1 ) delta_offset = len(current_text) - len(delta_text) start_offset = start_reasoning_idx - delta_offset if start_offset < 0: start_offset = 0 delta_reasoning = delta_text[start_offset:reasoning_end_idx] return DeltaMessage( reasoning=delta_reasoning, content=delta_content, ) def _get_content_sections( self, current_text: str ) -> tuple[str | None, int | None, str | None]: """Parse the text to extract the reasoning content / content if we have them. Args: current_text (str): The full previous + delta text. Returns: tuple[Optional[str], Optional[int], Optional[str]]: Tuple of len 3 containing the reasoning content, the length of the response seq (if there is one) and the non-reasoning content. """ current_chunk_start = 0 start_reasoning = None parsed_content = False delimiter_idxs = [ idx for idx, char in enumerate(current_text) if char == self.seq_boundary_end ] for current_chunk_end in delimiter_idxs: current_chunk = current_text[current_chunk_start:current_chunk_end] # Check to see if the start of reasoning seq if complete if start_reasoning is None: for think_start in self.valid_think_starts: if current_chunk == think_start[:-1]: start_reasoning = current_chunk_end + 1 current_chunk_start = current_chunk_end + 1 break # Check to see if the start of response seq if complete elif not parsed_content: for response_start in self.valid_response_starts: if current_chunk[-len(response_start) + 1 :] == response_start[:-1]: # Mark end of reasoning and start response content # after the start of response sequence. end_reasoning = current_chunk_end - len(response_start) reasoning = current_text[start_reasoning:end_reasoning] response_content = current_text[current_chunk_end + 1 :] return reasoning, len(response_start), response_content if start_reasoning and not parsed_content: return current_text[start_reasoning:], None, None return None, None, None
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/identity_reasoning_parser.py
vllm/reasoning/identity_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Sequence from transformers import PreTrainedTokenizerBase from vllm.entrypoints.openai.protocol import ChatCompletionRequest, DeltaMessage from vllm.logger import init_logger from vllm.reasoning import ReasoningParser logger = init_logger(__name__) class IdentityReasoningParser(ReasoningParser): """ Identity reasoning parser. This parser does not attempt to parse or strip out reasoning tokens. It treats the entire model output as content and ignores reasoning. """ def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) if not self.model_tokenizer: raise ValueError( "The model tokenizer must be passed to the ReasoningParser " "constructor during construction." ) def is_reasoning_end(self, input_ids: list[int]) -> bool: # Always return True, since we never treat reasoning specially return True def is_reasoning_end_streaming( self, input_ids: list[int], delta_ids: list[int] ) -> bool: return True def extract_content_ids(self, input_ids: list[int]) -> list[int]: # Identity: return all tokens as content return input_ids def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: # Just wrap delta_text as content, ignore reasoning if delta_text: return DeltaMessage(content=delta_text) return None def extract_reasoning( self, model_output: str, request: ChatCompletionRequest ) -> tuple[str | None, str | None]: # No reasoning separation: return None for reasoning, # and full model_output as content return None, model_output
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/deepseek_r1_reasoning_parser.py
vllm/reasoning/deepseek_r1_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Sequence from vllm.entrypoints.openai.protocol import DeltaMessage from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser class DeepSeekR1ReasoningParser(BaseThinkingReasoningParser): """ Reasoning parser for DeepSeek R1 model. The DeepSeek R1 model uses <think>...</think> tokens to denote reasoning text. This parser extracts the reasoning content from the model output. """ @property def start_token(self) -> str: """The token that starts reasoning content.""" return "<think>" @property def end_token(self) -> str: """The token that ends reasoning content.""" return "</think>" def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: ret = super().extract_reasoning_streaming( previous_text, current_text, delta_text, previous_token_ids, current_token_ids, delta_token_ids, ) if ( ret is not None and self.start_token_id not in previous_token_ids and self.start_token_id not in delta_token_ids ): if self.end_token_id in delta_token_ids: # end token in delta with more tokens, # extract reasoning content and content end_index = delta_text.find(self.end_token) reasoning = delta_text[:end_index] content = delta_text[end_index + len(self.end_token) :] return DeltaMessage( reasoning=reasoning, content=content if content else None, ) elif self.end_token_id in previous_token_ids: # end token in previous, thinking content ends return DeltaMessage(content=delta_text) else: # no end token in previous or delta, reasoning content continues return DeltaMessage(reasoning=delta_text) return ret
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/deepseek_v3_reasoning_parser.py
vllm/reasoning/deepseek_v3_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Sequence from transformers import PreTrainedTokenizerBase from vllm.entrypoints.openai.protocol import ChatCompletionRequest, DeltaMessage from vllm.logger import init_logger from vllm.reasoning import ReasoningParser from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser from .identity_reasoning_parser import IdentityReasoningParser logger = init_logger(__name__) class DeepSeekV3ReasoningParser(ReasoningParser): """ V3 parser that delegates to either DeepSeekR1ReasoningParser or IdentityReasoningParser based on `thinking` and `separate_reasoning`. """ def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) chat_kwargs = kwargs.pop("chat_template_kwargs", {}) or {} thinking = bool(chat_kwargs.pop("thinking", False)) enable_thinking = bool(chat_kwargs.pop("enable_thinking", False)) thinking = thinking or enable_thinking if thinking: self._parser = DeepSeekR1ReasoningParser(tokenizer, *args, **kwargs) else: self._parser = IdentityReasoningParser(tokenizer, *args, **kwargs) def is_reasoning_end(self, input_ids: Sequence[int]) -> bool: return self._parser.is_reasoning_end(input_ids) def is_reasoning_end_streaming( self, input_ids: list[int], delta_ids: list[int] ) -> bool: return self._parser.is_reasoning_end_streaming(input_ids, delta_ids) def extract_content_ids(self, input_ids: list[int]) -> list[int]: return self._parser.extract_content_ids(input_ids) def extract_reasoning( self, model_output: str, request: ChatCompletionRequest ) -> tuple[str | None, str | None]: return self._parser.extract_reasoning(model_output, request) def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: return self._parser.extract_reasoning_streaming( previous_text, current_text, delta_text, previous_token_ids, current_token_ids, delta_token_ids, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/basic_parsers.py
vllm/reasoning/basic_parsers.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from abc import abstractmethod from collections.abc import Sequence from typing import TYPE_CHECKING, Any from vllm.entrypoints.openai.protocol import DeltaMessage from vllm.reasoning.abs_reasoning_parsers import ReasoningParser from vllm.tokenizers import TokenizerLike if TYPE_CHECKING: from vllm.entrypoints.openai.protocol import ( ChatCompletionRequest, ResponsesRequest, ) else: ChatCompletionRequest = Any ResponsesRequest = Any class BaseThinkingReasoningParser(ReasoningParser): """ Base class for reasoning parsers that use thinking tokens. This class provides common functionality for parsers that use start and end tokens to delimit reasoning content ( e.g., <think>...</think>, <seed:think>...</seed:think>). Subclasses must implement the start and end tokens via abstract properties. """ @property @abstractmethod def start_token(self) -> str: """The token that starts reasoning content.""" raise NotImplementedError @property @abstractmethod def end_token(self) -> str: """The token that ends reasoning content.""" raise NotImplementedError def __init__(self, tokenizer: TokenizerLike, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) if not self.model_tokenizer: raise ValueError( "The model tokenizer must be passed to the ReasoningParser " "constructor during construction." ) if not self.start_token or not self.end_token: raise ValueError("start_token and end_token must be defined in subclasses") self.start_token_id = self.vocab.get(self.start_token) self.end_token_id = self.vocab.get(self.end_token) if self.start_token_id is None or self.end_token_id is None: raise RuntimeError( f"{self.__class__.__name__} reasoning parser could not locate " "think start/end tokens in the tokenizer!" ) def is_reasoning_end(self, input_ids: list[int]) -> bool: start_token_id = self.start_token_id end_token_id = self.end_token_id for i in range(len(input_ids) - 1, -1, -1): if input_ids[i] == start_token_id: return False if input_ids[i] == end_token_id: return True return False def is_reasoning_end_streaming( self, input_ids: list[int], delta_ids: list[int] ) -> bool: end_token_id = self.end_token_id return end_token_id in delta_ids def extract_content_ids(self, input_ids: list[int]) -> list[int]: """ Extract the content after the end tokens """ if self.end_token_id not in input_ids[:-1]: return [] else: return input_ids[input_ids.index(self.end_token_id) + 1 :] def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: """ Extract reasoning content from a delta message. Handles streaming output where previous + delta = current. Uses token IDs for faster processing. """ # Skip single special tokens if len(delta_token_ids) == 1 and ( delta_token_ids[0] in [self.start_token_id, self.end_token_id] ): return None # Check if start token is present in previous or delta. # Keep compatibility with models that don't generate start tokens. if self.start_token_id in previous_token_ids: if self.end_token_id in delta_token_ids: # start token in previous, end token in delta, # extract reasoning content end_index = delta_text.find(self.end_token) reasoning = delta_text[:end_index] content = delta_text[end_index + len(self.end_token) :] return DeltaMessage( reasoning=reasoning, content=content if content else None ) elif self.end_token_id in previous_token_ids: # start token in previous, end token in previous, # reasoning content continues return DeltaMessage(content=delta_text) else: # start token in previous, no end token in previous or delta, # reasoning content continues return DeltaMessage(reasoning=delta_text) elif self.start_token_id in delta_token_ids: if self.end_token_id in delta_token_ids: # start token in delta, end token in delta, # extract reasoning content start_index = delta_text.find(self.start_token) end_index = delta_text.find(self.end_token) reasoning = delta_text[start_index + len(self.start_token) : end_index] content = delta_text[end_index + len(self.end_token) :] return DeltaMessage( reasoning=reasoning, content=content if content else None ) else: # start token in delta, no end token in delta, # reasoning content continues return DeltaMessage(reasoning=delta_text) else: # not find thinking start token return DeltaMessage(content=delta_text) def extract_reasoning( self, model_output: str, request: ChatCompletionRequest | ResponsesRequest ) -> tuple[str | None, str | None]: """ Extract reasoning content from the model output. This is the base implementation that works for most models. Subclasses can override this method for specific behavior. """ # Check if the start token is present in the model output, remove it # if it is present. model_output_parts = model_output.partition(self.start_token) model_output = ( model_output_parts[2] if model_output_parts[1] else model_output_parts[0] ) # For models that may not generate start token, # assume the reasoning content is always at the start. if self.end_token not in model_output: return model_output, None else: reasoning, _, content = model_output.partition(self.end_token) # If generation stops right after end-of-think, return null content final_content = content or None return reasoning, final_content
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/ernie45_reasoning_parser.py
vllm/reasoning/ernie45_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Sequence from transformers import PreTrainedTokenizerBase from vllm.entrypoints.openai.protocol import ChatCompletionRequest, DeltaMessage from vllm.logger import init_logger from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser logger = init_logger(__name__) class Ernie45ReasoningParser(BaseThinkingReasoningParser): """ Reasoning parser for Ernie45 thinking model. The Ernie45 thinking model ouput format is abc\n</think>\n\n<response>\ndef\n</response>\n or abc\n</think>\ndef """ response_start_token: str = "<response>" response_end_token: str = "</response>" newline_token: str = "<0x0A>" @property def start_token(self) -> str: """The token that starts reasoning content.""" return "<think>" @property def end_token(self) -> str: """The token that ends reasoning content.""" return "</think>" def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) if not self.model_tokenizer: raise ValueError( "The model tokenizer must be passed to the ReasoningParser " "constructor during construction." ) self.start_token_id = self.vocab.get(self.start_token) self.end_token_id = self.vocab.get(self.end_token) self.response_start_token_id = self.vocab.get(self.response_start_token) self.response_end_token_id = self.vocab.get(self.response_end_token) self.newline_token_id = self.vocab.get(self.newline_token) self.parser_token_ids = [self.end_token_id, self.response_end_token_id] if self.start_token_id is None or self.end_token_id is None: raise RuntimeError( "Ernie45 reasoning parser could not locate think start/end " "tokens in the tokenizer!" ) def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: """ Extract reasoning content from a delta message. Handles streaming output where previous + delta = current. Uses token IDs for faster processing. The Ernie45 thinking model ouput format is abc\n</think>\n\n<response>\ndef\n</response>\n or abc\n</think>\ndef - 'abc' goes to reasoning - 'def' goes to content """ # Skip single special tokens if len(delta_token_ids) == 1 and ( delta_token_ids[0] in [ self.start_token_id, self.end_token_id, self.response_start_token_id, self.response_end_token_id, ] ): return None # No <think> in previous or delta, also need to check for </think>. # Because the model may have generated </think> without <think> if self.end_token_id in delta_token_ids: # </think> in delta with more tokens, # extract reasoning content and content think_end_index = delta_text.find(self.end_token) reasoning = delta_text[:think_end_index] content = delta_text[think_end_index + len(self.end_token) :] content = content.lstrip("\n") response_start_idx = content.find(self.response_start_token) response_end_idx = content.rfind(self.response_end_token) if response_start_idx != -1: content = content[response_start_idx + len(self.response_start_token) :] if response_end_idx != -1: content = content[:response_end_idx] return DeltaMessage( reasoning=reasoning, content=content if content else None, ) elif self.end_token_id in previous_token_ids: # </think> in previous, thinking content ends content = delta_text if self.response_start_token_id in delta_token_ids: content = content.lstrip("\n") response_start_idx = content.find(self.response_start_token) content = content[response_start_idx + len(self.response_start_token) :] # if have </response>, remove it response_end_idx = content.rfind(self.response_end_token) if response_end_idx != -1: content = content[:response_end_idx] elif self.response_end_token_id in delta_token_ids: response_end_idx = content.rfind(self.response_end_token) content = content[:response_end_idx] # remove \n after </think> or </response> if previous_token_ids[-1] in self.parser_token_ids and ( len(delta_token_ids) > 0 and delta_token_ids[0] == self.newline_token_id ): content = content.lstrip("\n") # remove \n after </think>\n if ( len(previous_token_ids) > 1 and previous_token_ids[-2] == self.end_token_id ) and ( len(delta_token_ids) > 0 and delta_token_ids[0] == self.newline_token_id ): content = content.lstrip("\n") return DeltaMessage(content=content if content else None) else: # no </think> in previous or delta, reasoning content continues return DeltaMessage(reasoning=delta_text) def extract_reasoning( self, model_output: str, request: ChatCompletionRequest ) -> tuple[str | None, str | None]: """ Extract reasoning content from the model output. The Ernie45 thinking model ouput format is abc\n</think>\n\n\n<response>\ndef\n</response>\n or abc\n</think>\ndef - 'abc' goes to reasoning - 'def' goes to content Returns: tuple[Optional[str], Optional[str]]: reasoning content and content """ reasoning, content = super().extract_reasoning(model_output, request) if content: start_idx = content.find(self.response_start_token) end_idx = content.rfind(self.response_end_token) # Simultaneously existing and in the correct order if start_idx != -1 and end_idx != -1 and start_idx < end_idx: content = content[start_idx + len(self.response_start_token) : end_idx] final_content = content or None return reasoning, final_content
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/qwen3_reasoning_parser.py
vllm/reasoning/qwen3_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.entrypoints.openai.protocol import ChatCompletionRequest, ResponsesRequest from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser class Qwen3ReasoningParser(BaseThinkingReasoningParser): """ Reasoning parser for the Qwen3 model. The Qwen3 model uses <think>...</think> tokens to denote reasoning text within its output. The model provides a strict switch to disable reasoning output via the 'enable_thinking=False' parameter. This parser extracts the reasoning content enclosed by <think> and </think> tokens from the model's output. """ @property def start_token(self) -> str: """The token that starts reasoning content.""" return "<think>" @property def end_token(self) -> str: """The token that ends reasoning content.""" return "</think>" def extract_reasoning( self, model_output: str, request: ChatCompletionRequest | ResponsesRequest ) -> tuple[str | None, str | None]: """ Extract reasoning content from the model output. Qwen3 has stricter requirements - it needs both start and end tokens to be present, unlike other models that work with just the end token. For text <think>abc</think>xyz: - 'abc' goes to reasoning - 'xyz' goes to content Returns: tuple[Optional[str], Optional[str]]: reasoning content and content """ # Check if the model output contains both <think> and </think> tokens. if self.start_token not in model_output or self.end_token not in model_output: return None, model_output # Check if the <think> is present in the model output, remove it # if it is present. model_output_parts = model_output.partition(self.start_token) model_output = ( model_output_parts[2] if model_output_parts[1] else model_output_parts[0] ) # Check if the model output contains the </think> tokens. # If the end token is not found, return the model output as is. if self.end_token not in model_output: return None, model_output # Extract reasoning content from the model output. reasoning, _, content = model_output.partition(self.end_token) final_content = content or None return reasoning, final_content
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/olmo3_reasoning_parser.py
vllm/reasoning/olmo3_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import dataclasses as dt import enum from collections.abc import Sequence from typing import TYPE_CHECKING import regex as re if TYPE_CHECKING: from vllm.tokenizers import TokenizerLike from vllm.entrypoints.openai.protocol import ( ChatCompletionRequest, DeltaMessage, ResponsesRequest, ) from vllm.logger import init_logger from vllm.reasoning import ReasoningParser logger = init_logger(__name__) class Olmo3ReasoningState(enum.Enum): REASONING = 1 CONTENT = 2 @dt.dataclass(frozen=True) class Indices: start: int end: int def __len__(self): return self.end - self.start def string_overlap(a: str, b: str) -> tuple[Indices | None, Indices | None]: """ Find the longest overlap where the end of string a matches the start of string b. Args: a: First string b: Second string Returns: Tuple of IndicesTuples representing the overlapping portions in each string, or a tuple of None if no overlap exists """ # swap so a is always the shorter string a, b, swap = (a, b, False) if len(a) < len(b) else (b, a, True) # first check: is a fully contained in b? if a in b: ind_a = Indices(0, len(a)) ind_b = Indices(b.index(a), b.index(a) + len(a)) return (ind_b, ind_a) if swap else (ind_a, ind_b) # second check: does the end of a overlap with the # beginning of b? for i in range(len(a) - 1, 0, -1): if a[-i:] == b[:i]: ind_a = Indices(len(a) - i, len(a)) ind_b = Indices(0, i) return (ind_b, ind_a) if swap else (ind_a, ind_b) # third check: does the beginning of a overlap with # the end of b? for i in range(len(a) - 1, 0, -1): if b[-i:] == a[:i]: ind_a = Indices(0, i) ind_b = Indices(len(b) - i, len(b)) return (ind_b, ind_a) if swap else (ind_a, ind_b) return None, None @dt.dataclass class Olmo3ReasoningBuffer: think_start: str = "<think>" think_end: str = "</think>" buffer: str = "" # we start in reasoning state to support cases where we hardcode # <think> as the start of the reasoning block. # In those cases, the only token we will see is </think>, which # is when we switch to content state. state: Olmo3ReasoningState = Olmo3ReasoningState.REASONING def process_buffer(self) -> DeltaMessage | None: start_think_idx = self.buffer.find(self.think_start) if start_think_idx >= 0: self.state = Olmo3ReasoningState.REASONING pretext, self.buffer = ( self.buffer[:start_think_idx], self.buffer[start_think_idx + len(self.think_start) :], ) if start_think_idx > 0: # this covers the case there's content before # the start of the reasoning block return DeltaMessage(content=pretext) end_think_idx = self.buffer.rfind(self.think_end) if end_think_idx >= 0: self.state = Olmo3ReasoningState.CONTENT pretext, self.buffer = ( self.buffer[:end_think_idx], self.buffer[end_think_idx + len(self.think_end) :], ) if end_think_idx > 0: # this covers the case there's content before # the end of the reasoning block return DeltaMessage(reasoning=pretext) if self.state == Olmo3ReasoningState.REASONING: # we are inside reasoning block, return and empty # the text buffer ( text_buffer, self.buffer, ) = self.buffer, "" return DeltaMessage(reasoning=text_buffer) if self.state == Olmo3ReasoningState.CONTENT: # we are outside reasoning block, return and empty # the text buffer ( text_buffer, self.buffer, ) = self.buffer, "" return DeltaMessage(content=text_buffer) # nothing to return unless we are in reasoning or content state return None def __len__(self): # is the length of the text buffer return len(self.buffer) def add_text(self, delta_text: str) -> DeltaMessage | None: # we start by adding the delta text to the buffer self.buffer += delta_text # setting this to empty before starting delta_message: DeltaMessage | None = None # we start by computing the overlap between the delta_text # and start/end of think tokens. _, overlap_think_start = string_overlap(delta_text, self.think_start) _, overlap_think_end = string_overlap(delta_text, self.think_end) partial_overlap_start = overlap_think_start is not None and len( overlap_think_start ) < len(self.think_start) partial_overlap_end = overlap_think_end is not None and len( overlap_think_end ) < len(self.think_end) if ( partial_overlap_start and self.think_start in self.buffer and not partial_overlap_end ): # we can only process the buffer if partial overlap # is the last part of think token (thus causing # text_buffer to contain the start of think token) # and there are no partial overlaps with end think delta_message = self.process_buffer() elif partial_overlap_end and self.think_end in self.buffer: # same as before (partial overlap only allowed) # if the buffer contains the end think token, # but we don't have to check for partial overlap # with start think token because they are handled # by the previous condition delta_message = self.process_buffer() elif partial_overlap_start or partial_overlap_end: # in general, if there are overlaps, we don't # process the buffer because we want to wait until # the think token is fully completed. return None else: # we process the buffer as normal delta_message = self.process_buffer() return delta_message class Olmo3ReasoningParser(ReasoningParser): """ Reasoning parser for Olmo 3 model Olmo3ReasoningParser This class implements a reasoning parser specifically designed for the Olmo 3 family of models. Olmo 3 models do not use special tokens to indicate reasoning; rather, reasoning trace is wrapped in `<think>` and `</think>`, which are tokenized using standard vocabulary entries. Because of this, the parser operates in string space, accumulating the characters in a buffer until it sees `<think>` or `</think>`. tokens to switch modes. Key Features: - For non-stream output, Recognizes and extracts reasoning (text bracketed by `<think>` and `</think>`) and content (everything after the first `</think>`). - For stream process, it uses a buffer to accumulate delta text, and output progressive delta messages as soon as thinking starts or ends. - For reliability, some Olmo 3 models may hardcode the first `<think>` token is the input text (similar to Deepseek R1, or reasoning-only Qwen models). To support such variants, the parser can optionally work in cases where the first `<think>` token is missing from generation. """ def __init__(self, tokenizer: "TokenizerLike", *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) self.think_start = r"<think>" self.think_end = r"</think>" # notice that the first think is optional; this allows template to # work in cases when we hardcode a <think> at the beginning of the # reasoning template. reasoning_expr = ( rf"^(?:{self.think_start})?(?P<reasoning>.*?)" + rf"{self.think_end}(?P<content>.*)$" ) self.reasoning_regex = re.compile(reasoning_expr, re.DOTALL) self.buffer = Olmo3ReasoningBuffer( think_start=self.think_start, think_end=self.think_end ) def is_reasoning_end(self, input_ids: list[int]) -> bool: text = self.model_tokenizer.decode(input_ids) return self.think_end in text def extract_content_ids(self, input_ids: list[int]) -> list[int]: # for Olmo 3 streaming reason parsing, the stream parse # will call first, and the same token will be called in # is_reasoning_end and extract_content_ids # this id is not part of content, so just return [] here. return [] def extract_reasoning( self, model_output: str, request: ChatCompletionRequest | ResponsesRequest, ) -> tuple[str | None, str | None]: """Extract the reasoning content & content sections, respectively. If the sequence doesn't match what we expect, i.e., the model generates something else, all content is considered non-reasoning content. Args: model_output (str): Output of the model to be parsed. request (ChatCompletionRequest | ResponsesRequest): Request being processed. Returns: tuple[Optional[str], Optional[str]]: Tuple pair containing the reasoning content and non-reasoning content. """ re_match = self.reasoning_regex.match(model_output) if re_match: reasoning = re_match.group("reasoning") or None content = re_match.group("content") or None return reasoning, content # no reasoning content return None, model_output def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: """Extract content using token ID sequence state machine""" delta_message = self.buffer.add_text(delta_text) if delta_message is None and self.buffer.think_end in self.buffer.buffer: # this is a bit hacky, but, because of how the buffer is # constructed, if the last delta_text contains characters that # marks the end of thinking tokens, then messages in the buffer # would never be processed because we get no other turn. To get # around that, we check if the text buffer contains the end of # thinking tokens, and, if so, we reprocess the buffer again. delta_message = self.buffer.process_buffer() return delta_message
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/gptoss_reasoning_parser.py
vllm/reasoning/gptoss_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import json from collections.abc import Sequence from transformers import PreTrainedTokenizerBase from vllm.entrypoints.openai.parser.harmony_utils import parse_chat_output from vllm.entrypoints.openai.protocol import ChatCompletionRequest, DeltaMessage from vllm.entrypoints.tool_server import ToolServer from vllm.logger import init_logger from vllm.reasoning import ReasoningParser logger = init_logger(__name__) no_func_reaonsing_tag = { "type": "structural_tag", "format": { "type": "triggered_tags", "tags": [ { "begin": "<|channel|>analysis<|message|>", "content": {"type": "any_text"}, "end": "<|end|>", } ], "triggers": ["<|channel|>analysis"], "stop_after_first": False, }, } def from_builtin_tool_to_tag(tool: str) -> list[dict]: tag = [ { "begin": f"<|channel|>commentary to={tool}", "content": {"type": "any_text"}, "end": "<|end|>", }, { "begin": f"<|channel|>analysis to={tool}", "content": {"type": "any_text"}, "end": "<|end|>", }, ] return tag def tag_with_builtin_funcs(no_func_reaonsing_tag, builtin_tool_list: list[str]) -> dict: import copy new_tag = copy.deepcopy(no_func_reaonsing_tag) new_tag["format"]["triggers"].append("<|channel|>commentary to=") for tool in builtin_tool_list: new_tag["format"]["tags"].extend(from_builtin_tool_to_tag(tool)) return new_tag class GptOssReasoningParser(ReasoningParser): """ Reasoning parser for GptOss model. The GptOss model uses harmony to extract reasoning content and this parser is only used for detecting the end of the reasoning content. """ def __init__(self, tokenizer: PreTrainedTokenizerBase, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) # The model can output some special tokens between "final" and "<|message|>" # So we need to look for both sequences to determine the end of reasoning. self.reasoning_end_token_ids_prefix = self.model_tokenizer.encode( "<|channel|>final" ) self.reasoning_end_token_ids_suffix = self.model_tokenizer.encode("<|message|>") self.reasoning_max_num_between_tokens = 20 def is_reasoning_end(self, input_ids: list[int]) -> bool: end_token_ids_prefix = self.reasoning_end_token_ids_prefix end_token_ids_suffix = self.reasoning_end_token_ids_suffix assert len(end_token_ids_prefix) > 0, "reasoning_end_token_ids_prefix is empty" assert len(end_token_ids_suffix) > 0, "reasoning_end_token_ids_suffix is empty" # Check if the end sequence is present in the input_ids. # We search from the end of input_ids to find the last match. for i in range(len(input_ids) - len(end_token_ids_prefix), -1, -1): if input_ids[i : i + len(end_token_ids_prefix)] == end_token_ids_prefix: # We have found the prefix, now we look for the suffix after the prefix. suffix_start = i + len(end_token_ids_prefix) for j in range( suffix_start, len(input_ids) - len(end_token_ids_suffix) + 1 ): if j - suffix_start >= self.reasoning_max_num_between_tokens: break if ( input_ids[j : j + len(end_token_ids_suffix)] == end_token_ids_suffix ): return True return False def extract_content_ids(self, input_ids: list[int]) -> list[int]: _, content, _ = parse_chat_output(input_ids) if content is None: return [] return self.model_tokenizer.encode(content) def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: prev_reasoning, prev_content, _ = parse_chat_output(list(previous_token_ids)) cur_reasoning, cur_content, _ = parse_chat_output(list(current_token_ids)) reasoning_delta = None content_delta = None if cur_reasoning is not None: prev_r = prev_reasoning or "" if cur_reasoning.startswith(prev_r): reasoning_delta = cur_reasoning[len(prev_r) :] or None else: reasoning_delta = cur_reasoning if cur_content is not None: prev_c = prev_content or "" if cur_content.startswith(prev_c): content_delta = cur_content[len(prev_c) :] or None else: content_delta = cur_content if reasoning_delta is None and content_delta is None: return None return DeltaMessage(reasoning=reasoning_delta, content=content_delta) def extract_reasoning( self, model_output: str, request: ChatCompletionRequest, ) -> tuple[str | None, str | None]: raise NotImplementedError( "gpt-oss has a special branch for parsing reasoning in non-streaming mode. This method shouldn't be used." # noqa: E501 ) # This function prepares the structural tag to format reasoning output def prepare_structured_tag( self, original_tag: str | None, tool_server: ToolServer | None ) -> str | None: if original_tag is None: if tool_server is None: return json.dumps(no_func_reaonsing_tag) else: builtin_tool_list: list[str] = [] if tool_server.has_tool("browser"): builtin_tool_list.append("browser") if tool_server.has_tool("python"): builtin_tool_list.append("python") if tool_server.has_tool("container"): builtin_tool_list.append("container") if len(builtin_tool_list) > 0: logger.info("Builtin_tool_list: %s", builtin_tool_list) func_tag = json.dumps( tag_with_builtin_funcs(no_func_reaonsing_tag, builtin_tool_list) ) else: logger.info("Builtin_tool_list is empty") func_tag = json.dumps(no_func_reaonsing_tag) return func_tag else: # There is potential risk for appending the tag to the original tag return original_tag
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/__init__.py
vllm/reasoning/__init__.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.reasoning.abs_reasoning_parsers import ReasoningParser, ReasoningParserManager __all__ = [ "ReasoningParser", "ReasoningParserManager", ] """ Register a lazy module mapping. Example: ReasoningParserManager.register_lazy_module( name="qwen3", module_path="vllm.reasoning.qwen3_reasoning_parser", class_name="Qwen3ReasoningParser", ) """ _REASONING_PARSERS_TO_REGISTER = { "deepseek_r1": ( # name "deepseek_r1_reasoning_parser", # filename "DeepSeekR1ReasoningParser", # class_name ), "deepseek_v3": ( "deepseek_v3_reasoning_parser", "DeepSeekV3ReasoningParser", ), "ernie45": ( "ernie45_reasoning_parser", "Ernie45ReasoningParser", ), "glm45": ( "glm4_moe_reasoning_parser", "Glm4MoeModelReasoningParser", ), "openai_gptoss": ( "gptoss_reasoning_parser", "GptOssReasoningParser", ), "granite": ( "granite_reasoning_parser", "GraniteReasoningParser", ), "holo2": ( "holo2_reasoning_parser", "Holo2ReasoningParser", ), "hunyuan_a13b": ( "hunyuan_a13b_reasoning_parser", "HunyuanA13BReasoningParser", ), "kimi_k2": ( "deepseek_r1_reasoning_parser", "DeepSeekR1ReasoningParser", ), "minimax_m2": ( "minimax_m2_reasoning_parser", "MiniMaxM2ReasoningParser", ), "minimax_m2_append_think": ( "minimax_m2_reasoning_parser", "MiniMaxM2AppendThinkReasoningParser", ), "mistral": ( "mistral_reasoning_parser", "MistralReasoningParser", ), "olmo3": ( "olmo3_reasoning_parser", "Olmo3ReasoningParser", ), "qwen3": ( "qwen3_reasoning_parser", "Qwen3ReasoningParser", ), "seed_oss": ( "seedoss_reasoning_parser", "SeedOSSReasoningParser", ), "step3": ( "step3_reasoning_parser", "Step3ReasoningParser", ), } def register_lazy_reasoning_parsers(): for name, (file_name, class_name) in _REASONING_PARSERS_TO_REGISTER.items(): module_path = f"vllm.reasoning.{file_name}" ReasoningParserManager.register_lazy_module(name, module_path, class_name) register_lazy_reasoning_parsers()
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/holo2_reasoning_parser.py
vllm/reasoning/holo2_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from collections.abc import Sequence from vllm.entrypoints.openai.protocol import ChatCompletionRequest, DeltaMessage from vllm.logger import init_logger from vllm.reasoning import ( ReasoningParser, ) from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser from vllm.reasoning.identity_reasoning_parser import IdentityReasoningParser from vllm.tokenizers import TokenizerLike logger = init_logger(__name__) class Holo2ReasoningParser(ReasoningParser): """ Reasoning parser for the Holo2 models which are based on Qwen3. The Holo2 model uses <think>...</think> tokens to denote reasoning text but <think> is part of the chat template. This parser extracts the reasoning content until </think> in the model's output. The model provides a switch to enable or disable reasoning output via the 'thinking=False' parameter. Chat template args: - thinking: Whether to enable reasoning output (default: True) Parsing rules on model output: - thinking == False -> Model output is treated as purely the content |content| - thinking == True -> Model output is |reasoning_content|</think>|content| """ def __init__(self, tokenizer: TokenizerLike, *args, **kwargs): super().__init__(tokenizer, *args, **kwargs) chat_kwargs = kwargs.get("chat_template_kwargs", {}) or {} # Deepseek V3 and Holo2 are similar. However, Holo2 models think by default. # this parser without user specified chat template args is initiated once for # all requests in the structured output manager. So it is important that without # user specified chat template args, the default thinking is True. enable_thinking = bool(chat_kwargs.get("thinking", True)) if enable_thinking: self._parser = DeepSeekR1ReasoningParser(tokenizer, *args, **kwargs) else: self._parser = IdentityReasoningParser(tokenizer, *args, **kwargs) def is_reasoning_end(self, input_ids: Sequence[int]) -> bool: return self._parser.is_reasoning_end(input_ids) def is_reasoning_end_streaming( self, input_ids: list[int], delta_ids: list[int] ) -> bool: return self._parser.is_reasoning_end_streaming(input_ids, delta_ids) def extract_content_ids(self, input_ids: list[int]) -> list[int]: return self._parser.extract_content_ids(input_ids) def extract_reasoning( self, model_output: str, request: ChatCompletionRequest ) -> tuple[str | None, str | None]: return self._parser.extract_reasoning(model_output, request) def extract_reasoning_streaming( self, previous_text: str, current_text: str, delta_text: str, previous_token_ids: Sequence[int], current_token_ids: Sequence[int], delta_token_ids: Sequence[int], ) -> DeltaMessage | None: return self._parser.extract_reasoning_streaming( previous_text, current_text, delta_text, previous_token_ids, current_token_ids, delta_token_ids, )
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false
vllm-project/vllm
https://github.com/vllm-project/vllm/blob/0d4044edd85de30d7d4558aeea4d1e95c7c556d6/vllm/reasoning/seedoss_reasoning_parser.py
vllm/reasoning/seedoss_reasoning_parser.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from vllm.reasoning.basic_parsers import BaseThinkingReasoningParser class SeedOSSReasoningParser(BaseThinkingReasoningParser): """ Reasoning parser for SeedOSS model. The SeedOSS model uses <seed:think>...</seed:think> tokens to denote reasoning content text. This parser extracts the reasoning content from the model output. Similar to DeepSeek R1, it supports cases where the model doesn't generate the start token. """ @property def start_token(self) -> str: """The token that starts reasoning content.""" return "<seed:think>" @property def end_token(self) -> str: """The token that ends reasoning content.""" return "</seed:think>"
python
Apache-2.0
0d4044edd85de30d7d4558aeea4d1e95c7c556d6
2026-01-04T14:38:19.902011Z
false