[XPU] Enable XPU eplb (#44987)
Signed-off-by: mayuyuace <qiming1.zhang@intel.com> Signed-off-by: Qiming Zhang <qiming1.zhang@intel.com>
This commit is contained in:
@@ -10,7 +10,7 @@ import torch
|
||||
from vllm.distributed.parallel_state import get_eplb_group
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from .eplb_utils import CpuGpuEvent
|
||||
from .eplb_utils import CpuGpuEvent, device_stream
|
||||
from .rebalance_execute import AsyncEplbLayerResult, transfer_layer
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -24,17 +24,17 @@ def start_async_worker(
|
||||
is_profile: bool = False,
|
||||
) -> threading.Thread:
|
||||
rank = get_eplb_group().device_group.rank()
|
||||
device_index = state.cuda_device_index
|
||||
device_index = state.device_index
|
||||
assert state.is_async
|
||||
|
||||
def thread_target() -> None:
|
||||
assert device_index is not None
|
||||
torch.accelerator.set_device_index(device_index)
|
||||
cuda_stream = torch.cuda.Stream(device=device_index)
|
||||
stream = torch.Stream(device=torch.accelerator.current_accelerator())
|
||||
try:
|
||||
transfer_run_periodically(
|
||||
state=state,
|
||||
cuda_stream=cuda_stream,
|
||||
stream=stream,
|
||||
is_profile=is_profile,
|
||||
)
|
||||
except Exception as exc: # pragma: no cover - diagnostic path
|
||||
@@ -49,13 +49,13 @@ def run_rebalance_experts(
|
||||
model_state: "EplbModelState",
|
||||
eplb_state: "EplbState",
|
||||
physical_to_logical_map_cpu: torch.Tensor,
|
||||
cuda_stream: torch.cuda.Stream,
|
||||
stream: torch.Stream,
|
||||
) -> torch.Tensor:
|
||||
assert model_state.eplb_stats is not None
|
||||
eplb_stats = model_state.eplb_stats
|
||||
|
||||
# Move the global expert load window to CPU for computation.
|
||||
with torch.cuda.stream(cuda_stream):
|
||||
with device_stream(stream):
|
||||
global_expert_load_window = eplb_stats.global_expert_load_window.cpu()
|
||||
# Compute new expert mappings for the model
|
||||
new_physical_to_logical_map = eplb_state.policy.rebalance_experts(
|
||||
@@ -73,11 +73,11 @@ def run_rebalance_experts(
|
||||
|
||||
def transfer_run_periodically(
|
||||
state: "EplbState",
|
||||
cuda_stream: torch.cuda.Stream,
|
||||
stream: torch.Stream,
|
||||
is_profile: bool = False,
|
||||
) -> None:
|
||||
while True:
|
||||
state.rearrange_event.wait(stream=cuda_stream)
|
||||
state.rearrange_event.wait(stream=stream)
|
||||
|
||||
eplb_group = get_eplb_group().device_group
|
||||
eplb_cpu_group = get_eplb_group().cpu_group
|
||||
@@ -87,16 +87,16 @@ def transfer_run_periodically(
|
||||
for model_state in state.model_states.values():
|
||||
layer_idx = 0
|
||||
# Set the async worker's CUDA stream on the communicator
|
||||
model_state.communicator.set_stream(cuda_stream)
|
||||
model_state.communicator.set_stream(stream)
|
||||
num_layers = model_state.model.num_moe_layers
|
||||
|
||||
# Snapshot the physical_to_logical_map (synchronized with
|
||||
# rearrange_event) and copy it to CPU
|
||||
with torch.cuda.stream(cuda_stream):
|
||||
with device_stream(stream):
|
||||
physical_to_logical_map_cpu = model_state.physical_to_logical_map.cpu()
|
||||
|
||||
new_physical_to_logical_map = run_rebalance_experts(
|
||||
model_state, state, physical_to_logical_map_cpu, cuda_stream
|
||||
model_state, state, physical_to_logical_map_cpu, stream
|
||||
)
|
||||
|
||||
# Execute one EPLB layer transfer per model forward pass. Each iteration
|
||||
@@ -132,13 +132,13 @@ def transfer_run_periodically(
|
||||
communicator=model_state.communicator,
|
||||
ep_group=eplb_group,
|
||||
is_profile=is_profile,
|
||||
cuda_stream=cuda_stream,
|
||||
stream=stream,
|
||||
layer_idx=layer_idx,
|
||||
)
|
||||
|
||||
# Wait until all writes to expert_buffer have finished before making the
|
||||
# AsyncEplbLayerResult visible to the main thread.
|
||||
cuda_stream.synchronize()
|
||||
stream.synchronize()
|
||||
|
||||
# This event guarantees that expert_buffer will not be overwritten by
|
||||
# subsequent iterations of this loop until the main thread has consumed
|
||||
@@ -155,6 +155,6 @@ def transfer_run_periodically(
|
||||
# Block this thread until the main thread and main stream
|
||||
# finish copying model_state.expert_buffer into
|
||||
# model_state.model.expert_weights[layer_idx]
|
||||
consumed_event.wait(stream=cuda_stream)
|
||||
consumed_event.wait(stream=stream)
|
||||
assert model_state.pending_result is None
|
||||
layer_idx += 1
|
||||
|
||||
@@ -22,6 +22,7 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
|
||||
from vllm.distributed.device_communicators.pynccl_wrapper import (
|
||||
ncclDataTypeEnum,
|
||||
)
|
||||
from vllm.distributed.eplb.eplb_utils import device_stream
|
||||
from vllm.distributed.parallel_state import (
|
||||
GroupCoordinator,
|
||||
get_pp_group,
|
||||
@@ -87,8 +88,8 @@ class EplbCommunicator(ABC):
|
||||
communication buffers."""
|
||||
return True
|
||||
|
||||
def set_stream(self, cuda_stream: torch.cuda.Stream | None) -> None:
|
||||
self._cuda_stream = cuda_stream
|
||||
def set_stream(self, stream: torch.Stream | None) -> None:
|
||||
self._stream = stream
|
||||
|
||||
def _log_initialized(self) -> None:
|
||||
if is_local_first_rank():
|
||||
@@ -101,10 +102,10 @@ class TorchDistNcclEplbCommunicator(EplbCommunicator):
|
||||
def __init__(
|
||||
self,
|
||||
ep_group: ProcessGroup,
|
||||
cuda_stream: torch.cuda.Stream | None = None,
|
||||
stream: torch.Stream | None = None,
|
||||
) -> None:
|
||||
self._ep_group = ep_group
|
||||
self._cuda_stream = cuda_stream
|
||||
self._stream = stream
|
||||
self._p2p_ops: list[P2POp] = []
|
||||
self._log_initialized()
|
||||
|
||||
@@ -144,7 +145,7 @@ class TorchDistNcclEplbCommunicator(EplbCommunicator):
|
||||
if not self._p2p_ops:
|
||||
return
|
||||
try:
|
||||
with torch.cuda.stream(self._cuda_stream):
|
||||
with device_stream(self._stream):
|
||||
reqs = batch_isend_irecv(self._p2p_ops)
|
||||
for req in reqs:
|
||||
req.wait()
|
||||
@@ -158,10 +159,10 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
def __init__(
|
||||
self,
|
||||
cpu_group: ProcessGroup,
|
||||
cuda_stream: torch.cuda.Stream | None = None,
|
||||
stream: torch.Stream | None = None,
|
||||
) -> None:
|
||||
self._cpu_group = cpu_group
|
||||
self._cuda_stream = cuda_stream
|
||||
self._stream = stream
|
||||
self._ops: list[tuple[str, torch.Tensor, int]] = []
|
||||
self._log_initialized()
|
||||
|
||||
@@ -217,7 +218,7 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
recv_staging.append((tensor, cpu_tensor))
|
||||
|
||||
try:
|
||||
with torch.cuda.stream(self._cuda_stream):
|
||||
with device_stream(self._stream):
|
||||
build_ops()
|
||||
finally:
|
||||
self._ops.clear()
|
||||
@@ -225,10 +226,10 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
# Wait for all D2H copies to finish
|
||||
# before issuing gloo batch_isend_irecv operations.
|
||||
with gpu_sync_allowed():
|
||||
if self._cuda_stream is not None:
|
||||
self._cuda_stream.synchronize()
|
||||
if self._stream is not None:
|
||||
self._stream.synchronize()
|
||||
else:
|
||||
torch.cuda.current_stream().synchronize()
|
||||
torch.accelerator.current_stream().synchronize()
|
||||
|
||||
reqs = batch_isend_irecv(p2p_ops)
|
||||
for req in reqs:
|
||||
@@ -236,11 +237,69 @@ class TorchDistGlooStagedEplbCommunicator(EplbCommunicator):
|
||||
|
||||
if not recv_staging:
|
||||
return
|
||||
with torch.cuda.stream(self._cuda_stream):
|
||||
with device_stream(self._stream):
|
||||
for dst_tensor, cpu_tensor in recv_staging:
|
||||
dst_tensor.copy_(cpu_tensor, non_blocking=True)
|
||||
|
||||
|
||||
class TorchDistXCCLStagedEplbCommunicator(EplbCommunicator):
|
||||
"""EPLB communicator using XCCL device-to-device P2P on XPU."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ep_group: ProcessGroup,
|
||||
stream: torch.Stream | None = None,
|
||||
) -> None:
|
||||
self._ep_group = ep_group
|
||||
self._stream = stream
|
||||
self._ops: list[tuple[str, torch.Tensor, int]] = []
|
||||
self._log_initialized()
|
||||
|
||||
def add_send(
|
||||
self,
|
||||
tensors: list[torch.Tensor],
|
||||
dst_rank: int,
|
||||
expert_id: int, # unused by this backend
|
||||
) -> None:
|
||||
for tensor in tensors:
|
||||
self._ops.append(("send", tensor, dst_rank))
|
||||
|
||||
def add_recv(
|
||||
self,
|
||||
tensors: list[torch.Tensor],
|
||||
src_rank: int,
|
||||
expert_id: int, # unused by this backend
|
||||
) -> None:
|
||||
for tensor in tensors:
|
||||
self._ops.append(("recv", tensor, src_rank))
|
||||
|
||||
def execute(self) -> None:
|
||||
if not self._ops:
|
||||
return
|
||||
|
||||
p2p_ops: list[P2POp] = []
|
||||
try:
|
||||
for op, tensor, peer_rank in self._ops:
|
||||
send_or_recv = (
|
||||
torch.distributed.isend if op == "send" else torch.distributed.irecv
|
||||
)
|
||||
p2p_ops.append(
|
||||
P2POp(
|
||||
send_or_recv,
|
||||
tensor,
|
||||
peer_rank,
|
||||
self._ep_group,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
self._ops.clear()
|
||||
|
||||
with device_stream(self._stream):
|
||||
reqs = batch_isend_irecv(p2p_ops)
|
||||
for req in reqs:
|
||||
req.wait()
|
||||
|
||||
|
||||
class NixlEplbCommunicator(EplbCommunicator):
|
||||
"""EPLB communicator backed by NIXL READ transfers."""
|
||||
|
||||
@@ -343,7 +402,7 @@ class NixlEplbCommunicator(EplbCommunicator):
|
||||
uid = uuid.uuid4().hex[:8]
|
||||
return f"eplb-{self._rank}{pp_suffix}-{uid}"
|
||||
|
||||
def set_stream(self, cuda_stream: torch.cuda.Stream | None) -> None:
|
||||
def set_stream(self, stream: torch.Stream | None) -> None:
|
||||
pass
|
||||
|
||||
def add_send(
|
||||
@@ -602,10 +661,10 @@ class PyNcclEplbCommunicator(EplbCommunicator):
|
||||
def __init__(
|
||||
self,
|
||||
pynccl_comm: PyNcclCommunicator,
|
||||
cuda_stream: torch.cuda.Stream | None = None,
|
||||
stream: torch.Stream | None = None,
|
||||
) -> None:
|
||||
self._pynccl_comm = pynccl_comm
|
||||
self._cuda_stream = cuda_stream
|
||||
self._stream = stream
|
||||
self._group_started = False
|
||||
self._log_initialized()
|
||||
|
||||
@@ -622,7 +681,7 @@ class PyNcclEplbCommunicator(EplbCommunicator):
|
||||
) -> None:
|
||||
self._ensure_group_started()
|
||||
for tensor in tensors:
|
||||
self._pynccl_comm.send(tensor, dst_rank, stream=self._cuda_stream)
|
||||
self._pynccl_comm.send(tensor, dst_rank, stream=self._stream)
|
||||
|
||||
def add_recv(
|
||||
self,
|
||||
@@ -632,7 +691,7 @@ class PyNcclEplbCommunicator(EplbCommunicator):
|
||||
) -> None:
|
||||
self._ensure_group_started()
|
||||
for tensor in tensors:
|
||||
self._pynccl_comm.recv(tensor, src_rank, stream=self._cuda_stream)
|
||||
self._pynccl_comm.recv(tensor, src_rank, stream=self._stream)
|
||||
|
||||
def execute(self) -> None:
|
||||
if self._group_started:
|
||||
@@ -750,6 +809,8 @@ def create_eplb_communicator(
|
||||
return TorchDistGlooStagedEplbCommunicator(
|
||||
cpu_group=group_coordinator.cpu_group,
|
||||
)
|
||||
elif backend == "torch_xccl":
|
||||
return TorchDistXCCLStagedEplbCommunicator(ep_group=torch_group)
|
||||
elif backend == "torch_nccl":
|
||||
return TorchDistNcclEplbCommunicator(ep_group=torch_group)
|
||||
elif backend == "pynccl":
|
||||
|
||||
@@ -203,9 +203,9 @@ class EplbModelState:
|
||||
"""
|
||||
EPLB stats for the model.
|
||||
"""
|
||||
cuda_device_index: int | None
|
||||
device_index: int | None
|
||||
"""
|
||||
CUDA device index for the async EPLB worker thread.
|
||||
Device index for the async EPLB worker thread.
|
||||
"""
|
||||
communicator: EplbCommunicator
|
||||
"""
|
||||
@@ -286,14 +286,14 @@ class EplbState:
|
||||
"""
|
||||
Background thread handling async transfers.
|
||||
"""
|
||||
self.cuda_device_index: int | None = None
|
||||
self.device_index: int | None = None
|
||||
"""
|
||||
CUDA device index for the async EPLB worker thread.
|
||||
Device index for the async EPLB worker thread.
|
||||
"""
|
||||
if self.device.type == "cuda":
|
||||
self.cuda_device_index = self.device.index
|
||||
if self.cuda_device_index is None and torch.cuda.is_available():
|
||||
self.cuda_device_index = torch.accelerator.current_device_index()
|
||||
if self.device.type in ("cuda", "xpu"):
|
||||
self.device_index = self.device.index
|
||||
if self.device_index is None and torch.accelerator.is_available():
|
||||
self.device_index = torch.accelerator.current_device_index()
|
||||
|
||||
@staticmethod
|
||||
def build_initial_global_physical_to_logical_map(
|
||||
@@ -504,7 +504,7 @@ class EplbState:
|
||||
expert_buffer=expert_buffer,
|
||||
rebalanced=False,
|
||||
eplb_stats=None,
|
||||
cuda_device_index=self.cuda_device_index,
|
||||
device_index=self.device_index,
|
||||
communicator=communicator,
|
||||
num_unpadded_tokens_tensors=num_unpadded_tokens_tensors,
|
||||
)
|
||||
@@ -763,8 +763,8 @@ class EplbState:
|
||||
is_main_rank = ep_rank == 0
|
||||
if is_main_rank:
|
||||
if not self.is_async or is_profile:
|
||||
start_event = torch.cuda.Event(enable_timing=True)
|
||||
end_event = torch.cuda.Event(enable_timing=True)
|
||||
start_event = torch.Event(enable_timing=True)
|
||||
end_event = torch.Event(enable_timing=True)
|
||||
start_event.record()
|
||||
logger.info(
|
||||
"Rearranging experts %s %s...",
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Utility functions for EPLB (Expert Parallel Load Balancing)."""
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import threading
|
||||
|
||||
@@ -13,6 +14,22 @@ from vllm.logger import init_logger
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def device_stream(stream: torch.Stream | None):
|
||||
"""Platform-agnostic context manager that activates *stream* as the
|
||||
current accelerator stream for the duration of the ``with`` block.
|
||||
A no-op when *stream* is ``None``."""
|
||||
if stream is None:
|
||||
yield
|
||||
return
|
||||
prev = torch.accelerator.current_stream()
|
||||
torch.accelerator.set_stream(stream)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
torch.accelerator.set_stream(prev)
|
||||
|
||||
|
||||
class CpuGpuEvent:
|
||||
"""Combines a CUDA event with a CPU threading event to enforce record->wait
|
||||
ordering across two threads.
|
||||
@@ -30,10 +47,10 @@ class CpuGpuEvent:
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._event = torch.cuda.Event()
|
||||
self._event = torch.Event()
|
||||
self._recorded = threading.Event()
|
||||
|
||||
def wait(self, stream: torch.cuda.Stream | None = None):
|
||||
def wait(self, stream: torch.Stream | None = None):
|
||||
"""Blocks the calling thread until record finishes. Used to guarantee that the
|
||||
record kernel is called before wait.
|
||||
|
||||
@@ -43,7 +60,7 @@ class CpuGpuEvent:
|
||||
self._event.wait(stream)
|
||||
self._recorded.clear()
|
||||
|
||||
def record(self, stream: torch.cuda.Stream | None = None):
|
||||
def record(self, stream: torch.Stream | None = None):
|
||||
"""Unblocks the waiting thread after calling event.record().
|
||||
|
||||
Should only be called by the main thread.
|
||||
@@ -53,7 +70,7 @@ class CpuGpuEvent:
|
||||
"CpuGpuEvent.record() called before the previous event was "
|
||||
"consumed by wait()"
|
||||
)
|
||||
self._event = torch.cuda.Event()
|
||||
self._event = torch.Event()
|
||||
self._event.record(stream)
|
||||
self._recorded.set()
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import torch
|
||||
from torch.distributed import ProcessGroup, all_gather
|
||||
|
||||
from vllm.distributed.eplb.eplb_communicator import EplbCommunicator
|
||||
from vllm.distributed.eplb.eplb_utils import CpuGpuEvent
|
||||
from vllm.distributed.eplb.eplb_utils import CpuGpuEvent, device_stream
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
|
||||
|
||||
@@ -173,7 +173,7 @@ def move_to_buffer(
|
||||
new_indices: np.ndarray,
|
||||
expert_weights: Sequence[torch.Tensor],
|
||||
expert_weights_buffers: Sequence[torch.Tensor],
|
||||
cuda_stream: torch.cuda.Stream | None,
|
||||
stream: torch.Stream | None,
|
||||
ep_rank: int,
|
||||
communicator: EplbCommunicator,
|
||||
layer_idx: int = 0,
|
||||
@@ -183,12 +183,12 @@ def move_to_buffer(
|
||||
Args:
|
||||
num_local_experts: Number of local experts.
|
||||
old_indices: (num_experts_total,) ndarray of current (old)
|
||||
global-to-local expert assignments.
|
||||
global-to-locals expert assignments.
|
||||
new_indices: (num_experts_total,) ndarray of desired (new)
|
||||
global-to-local assignments after rebalance.
|
||||
expert_weights: Original expert weights for the layer.
|
||||
expert_weights_buffers: Intermediate buffers (one per tensor).
|
||||
cuda_stream: CUDA stream for async copies (can be None for sync mode).
|
||||
stream: CUDA/XPU stream for async copies (can be None for sync mode).
|
||||
ep_rank: Rank of this process in expert parallel group.
|
||||
communicator: EplbCommunicator instance for P2P communication.
|
||||
layer_idx: Index of the MoE layer being transferred.
|
||||
@@ -261,10 +261,9 @@ def move_to_buffer(
|
||||
expert = new_local_expert_ids[dst]
|
||||
src_local = expert_to_src_map.get(expert, -1)
|
||||
if src_local != -1:
|
||||
with torch.cuda.stream(cuda_stream):
|
||||
with device_stream(stream):
|
||||
for w, b in zip(expert_weights, expert_weights_buffers):
|
||||
b[dst].copy_(w[src_local], non_blocking=True)
|
||||
|
||||
communicator.set_transfer_context(old_indices, layer_idx)
|
||||
|
||||
# 2. Post sends
|
||||
@@ -430,7 +429,7 @@ def transfer_layer(
|
||||
ep_group: ProcessGroup,
|
||||
communicator: EplbCommunicator,
|
||||
is_profile: bool = False,
|
||||
cuda_stream: torch.cuda.Stream | None = None,
|
||||
stream: torch.Stream | None = None,
|
||||
rank_mapping: dict[int, int] | None = None,
|
||||
layer_idx: int = 0,
|
||||
) -> TransferMetadata:
|
||||
@@ -451,7 +450,7 @@ def transfer_layer(
|
||||
is_profile (bool): If `True`, do not perform any actual weight copy.
|
||||
This is used during profile run, where we only perform dummy
|
||||
communications to reserve enough memory for the buffers.
|
||||
cuda_stream: CUDA stream for async copies (can be None for sync mode).
|
||||
stream: CUDA stream for async copies (can be None for sync mode).
|
||||
rank_mapping: Optional rank mapping for elastic expert parallelism.
|
||||
layer_idx: Index of the MoE layer being transferred.
|
||||
|
||||
@@ -499,7 +498,7 @@ def transfer_layer(
|
||||
new_indices=new_layer_indices_np,
|
||||
expert_weights=expert_weights,
|
||||
expert_weights_buffers=expert_weights_buffer,
|
||||
cuda_stream=cuda_stream,
|
||||
stream=stream,
|
||||
ep_rank=ep_group.rank(),
|
||||
communicator=communicator,
|
||||
layer_idx=layer_idx,
|
||||
@@ -601,7 +600,7 @@ def rearrange_expert_weights_inplace(
|
||||
new_indices=new_global_expert_indices_cpu[layer_idx],
|
||||
expert_weights=expert_weights[layer_idx],
|
||||
expert_weights_buffers=weights_buffer,
|
||||
cuda_stream=None,
|
||||
stream=None,
|
||||
ep_rank=ep_rank,
|
||||
communicator=communicator,
|
||||
layer_idx=layer_idx,
|
||||
|
||||
Reference in New Issue
Block a user