diff --git a/vllm/config/parallel.py b/vllm/config/parallel.py index 6ba392802e31..914b3e46cf75 100644 --- a/vllm/config/parallel.py +++ b/vllm/config/parallel.py @@ -191,6 +191,24 @@ class ParallelConfig: enable_elastic_ep: bool = False """Enable elastic expert parallelism with stateless NCCL groups for DP/EP.""" + enable_ep_fault_tolerance: bool = False + """Enable EP fault tolerance. When a DP engine process dies, the redesign's + fault-tolerance supervisor publishes ``FaultInfo(DEAD)`` on its bus; an + external orchestrator (or operator) can then ``POST /fault_tolerance/apply`` + with ``instruction="scale_down"`` to recover. Requires + ``enable_elastic_ep=True``, ``data_parallel_backend="ray"``, + ``tensor_parallel_size=1``, and ``enable_fault_tolerance=True`` (the master + FT switch).""" + + enable_fault_tolerance: bool = False + """Master switch for the fault-tolerance framework. Enables the + :class:`~vllm.v1.fault_tolerance.default_supervisor.DefaultFaultSupervisor` + on each engine, registers HTTP endpoints under ``/fault_tolerance/*``, and + activates the typed ``FaultSignal`` path on ``ModelRunnerOutput``. This + flag is orthogonal to ``enable_ep_fault_tolerance``: it provides the + framework; ``enable_ep_fault_tolerance`` gates the EP-specific + scale-down plan.""" + enable_dbo: bool = False """Enable dual batch overlap for the model executor.""" ubatch_size: int = 0 @@ -653,13 +671,26 @@ def local_world_size(self) -> int: return self.world_size // self.nnodes_within_dp @staticmethod - def has_unfinished_dp(dp_group: ProcessGroup, has_unfinished: bool) -> bool: + def has_unfinished_dp( + dp_group: ProcessGroup, + has_unfinished: bool, + fault_tolerant: bool = False, + ) -> bool: tensor = torch.tensor([has_unfinished], dtype=torch.int32, device="cpu") # dp rank 0: has_unfinished_seqs=True # dp rank 1: has_unfinished_seqs=False # aggregated: has_unfinished_seqs=True # so this is an OR operation, i.e. MAX in integers - torch.distributed.all_reduce(tensor, op=ReduceOp.MAX, group=dp_group) + try: + torch.distributed.all_reduce(tensor, op=ReduceOp.MAX, group=dp_group) + except Exception: + if not fault_tolerant: + raise + logger.warning( + "DP all-reduce timed out — a peer may be dead. " + "Continuing in fault-tolerant mode." + ) + return True aggregated_has_unfinished = bool(tensor.item()) return aggregated_has_unfinished @@ -782,6 +813,17 @@ def __post_init__(self) -> None: "server and core client to coordinate scale up/down." ) + if self.enable_ep_fault_tolerance: + if not self.enable_elastic_ep: + raise ValueError("EP fault tolerance requires enable_elastic_ep=True.") + if self.tensor_parallel_size > 1: + raise ValueError( + "EP fault tolerance requires tensor_parallel_size=1. " + "With TP>1, a dead process would hang the NCCL TP group." + ) + if self.data_parallel_size <= 1: + raise ValueError("EP fault tolerance requires data_parallel_size > 1.") + if self.data_parallel_size > 1 or self.data_parallel_size_local == 0: # Data parallel was specified in the engine args. if self.distributed_executor_backend == "external_launcher": diff --git a/vllm/distributed/device_communicators/all2all.py b/vllm/distributed/device_communicators/all2all.py index 340b6ff1cf29..7e94a9490d68 100644 --- a/vllm/distributed/device_communicators/all2all.py +++ b/vllm/distributed/device_communicators/all2all.py @@ -257,10 +257,14 @@ def set_num_sms(self, num_sms: int): class DeepEPLLAll2AllManager(DeepEPAll2AllManagerBase): """ All2All communication based on DeepEP Low-Latency kernels. + + Implements the :class:`vllm.v1.fault_tolerance.maskable.FTMaskBuffer` + capability for FT-aware backends — see ``query_mask`` / ``clean_mask``. """ def __init__(self, cpu_group, tcp_store_group=None): super().__init__(cpu_group, tcp_store_group) + self._buffer: Any = None def _make_all2all_kwargs( self, @@ -317,17 +321,44 @@ def get_handle(self, kwargs): handle: deep_ep.Buffer = self.handle_cache.get_or_create( buffer_kwargs, deep_ep.Buffer ) + # Remember the buffer so query_mask / clean_mask can reach it. + self._buffer = handle return handle # DeepEP LL uses RDMA so no SMs are used for communication def max_sms_used(self) -> int | None: return 0 + # ---- FTMaskBuffer capability (vllm.v1.fault_tolerance.maskable) -------- + + def query_mask(self, mask: torch.Tensor) -> torch.Tensor: + """Read the per-peer fault mask. See FTMaskBuffer protocol.""" + import deep_ep # type: ignore[import-not-found] + + if not isinstance(self._buffer, deep_ep.Buffer): + raise RuntimeError( + "DeepEPLLAll2AllManager.query_mask called before get_handle" + ) + return self._buffer.low_latency_query_mask_buffer(mask) + + def clean_mask(self) -> None: + """Reset the per-peer fault mask to zero. See FTMaskBuffer protocol.""" + import deep_ep # type: ignore[import-not-found] + + if not isinstance(self._buffer, deep_ep.Buffer): + raise RuntimeError( + "DeepEPLLAll2AllManager.clean_mask called before get_handle" + ) + self._buffer.low_latency_clean_mask_buffer() + class NixlEPAll2AllManager(All2AllManagerBase): """ All2All communication based on NIXL EP kernels. This backend supports elastic EP with dynamic rank connection/disconnection. + + Implements the :class:`vllm.v1.fault_tolerance.maskable.FTMaskBuffer` + capability for FT-aware backends — see ``query_mask`` / ``clean_mask``. """ # (nixl_ep_buffer, ep_size) @@ -438,6 +469,24 @@ def destroy(self): def max_sms_used(self) -> int | None: return 0 + # ---- FTMaskBuffer capability (vllm.v1.fault_tolerance.maskable) -------- + + def query_mask(self, mask: torch.Tensor) -> torch.Tensor: + """Read the per-peer fault mask. See FTMaskBuffer protocol.""" + if NixlEPAll2AllManager._buffer is None: + raise RuntimeError( + "NixlEPAll2AllManager.query_mask called before buffer init" + ) + return NixlEPAll2AllManager._buffer[0].query_mask_buffer(mask) + + def clean_mask(self) -> None: + """Reset the per-peer fault mask to zero. See FTMaskBuffer protocol.""" + if NixlEPAll2AllManager._buffer is None: + raise RuntimeError( + "NixlEPAll2AllManager.clean_mask called before buffer init" + ) + NixlEPAll2AllManager._buffer[0].clean_mask_buffer() + class FlashInferNVLinkTwoSidedManager(All2AllManagerBase): """ diff --git a/vllm/distributed/device_communicators/base_device_communicator.py b/vllm/distributed/device_communicators/base_device_communicator.py index 0b4b81f93bb4..edf57440fc59 100644 --- a/vllm/distributed/device_communicators/base_device_communicator.py +++ b/vllm/distributed/device_communicators/base_device_communicator.py @@ -114,6 +114,15 @@ def combine(self, hidden_states: torch.Tensor, is_sequence_parallel: bool = Fals def destroy(self): pass + def abort(self): + """Forcefully abort without waiting for peers. + + No NCCL comms in the base class. Subclasses that introduce NCCL + communicators must override this to call ncclCommAbort instead of + ncclCommDestroy to avoid hanging when a peer rank has died. + """ + pass + class DeviceCommunicatorBase: """ @@ -312,6 +321,15 @@ def broadcast(self, tensor: torch.Tensor, src: int = 0) -> torch.Tensor: def destroy(self): pass + def abort(self): + """Forcefully abort the communicator without waiting for peers. + + Subclasses that wrap NCCL communicators must override this to + call ncclCommAbort instead of ncclCommDestroy to avoid hanging + when a peer rank has died. + """ + pass + def prepare_communication_buffer_for_model(self, model: torch.nn.Module) -> None: """ Prepare the communication buffer for the model. diff --git a/vllm/distributed/device_communicators/cuda_communicator.py b/vllm/distributed/device_communicators/cuda_communicator.py index 74056134c095..c495860feca7 100644 --- a/vllm/distributed/device_communicators/cuda_communicator.py +++ b/vllm/distributed/device_communicators/cuda_communicator.py @@ -343,6 +343,29 @@ def destroy(self): self.all2all_manager.destroy() self.all2all_manager = None # type: ignore[assignment] + def abort(self): + """Forcefully abort the NCCL communicator via ncclCommAbort. + + Unlike destroy() (which calls ncclCommDestroy and may trigger an + implicit ncclCommFinalize collective that hangs when a peer is + dead), abort is unconditionally safe in fault scenarios. + + Sub-communicators (fi_ar_comm, all2all_manager) don't wrap NCCL + comms today, but we call abort() for consistency so that the + fault path stays correct if they ever gain NCCL dependencies. + """ + if self.pynccl_comm is not None: + self.pynccl_comm.abort() + self.pynccl_comm = None + if self.ca_comm is not None: + self.ca_comm = None + if self.fi_ar_comm is not None: + self.fi_ar_comm.abort() + self.fi_ar_comm = None + if self.all2all_manager is not None: + self.all2all_manager.abort() + self.all2all_manager = None # type: ignore[assignment] + def all_gatherv( self, input_: torch.Tensor | list[torch.Tensor], diff --git a/vllm/distributed/device_communicators/flashinfer_all_reduce.py b/vllm/distributed/device_communicators/flashinfer_all_reduce.py index a65789a28338..bec912475b63 100644 --- a/vllm/distributed/device_communicators/flashinfer_all_reduce.py +++ b/vllm/distributed/device_communicators/flashinfer_all_reduce.py @@ -330,3 +330,12 @@ def all_reduce(self, input_tensor: torch.Tensor) -> torch.Tensor: def destroy(self): if not self.disabled: destroy_fi_ar_workspace() + + def abort(self): + """Forcefully abort without waiting for peers. + + No NCCL comms here. If NCCL communicators are ever added, this + must call ncclCommAbort instead of ncclCommDestroy to avoid + hanging when a peer rank has died. + """ + self.destroy() diff --git a/vllm/distributed/device_communicators/pynccl.py b/vllm/distributed/device_communicators/pynccl.py index 990c808a9831..1d25adec0da8 100644 --- a/vllm/distributed/device_communicators/pynccl.py +++ b/vllm/distributed/device_communicators/pynccl.py @@ -150,6 +150,19 @@ def destroy(self): self.available = False self.disabled = True + def abort(self): + """Forcefully abort the NCCL communicator via ncclCommAbort. + + Unlike destroy() (which calls ncclCommDestroy and may trigger an + implicit ncclCommFinalize collective), abort is safe to call when + a peer rank has died and would otherwise cause destroy to hang. + """ + if self.available and not self.disabled: + with torch.accelerator.device_index(self.device.index): + self.nccl.ncclCommAbort(self.comm) + self.available = False + self.disabled = True + def all_reduce( self, in_tensor: torch.Tensor, diff --git a/vllm/distributed/device_communicators/pynccl_wrapper.py b/vllm/distributed/device_communicators/pynccl_wrapper.py index 57c7397e01b6..5aed19296816 100644 --- a/vllm/distributed/device_communicators/pynccl_wrapper.py +++ b/vllm/distributed/device_communicators/pynccl_wrapper.py @@ -290,6 +290,8 @@ class NCCLLibrary: # it is better not to call it at all. # ncclResult_t ncclCommDestroy(ncclComm_t comm); Function("ncclCommDestroy", ncclResult_t, [ncclComm_t]), + # ncclResult_t ncclCommAbort(ncclComm_t comm); + Function("ncclCommAbort", ncclResult_t, [ncclComm_t]), # ncclResult_t ncclGroupStart(); Function("ncclGroupStart", ncclResult_t, []), # ncclResult_t ncclGroupEnd(); @@ -548,6 +550,9 @@ def ncclBroadcast( def ncclCommDestroy(self, comm: ncclComm_t) -> None: self.NCCL_CHECK(self._funcs["ncclCommDestroy"](comm)) + def ncclCommAbort(self, comm: ncclComm_t) -> None: + self.NCCL_CHECK(self._funcs["ncclCommAbort"](comm)) + def ncclGroupStart(self) -> None: self.NCCL_CHECK(self._funcs["ncclGroupStart"]()) diff --git a/vllm/distributed/elastic_ep/elastic_execute.py b/vllm/distributed/elastic_ep/elastic_execute.py index 24979b62af6d..d8741799aee6 100644 --- a/vllm/distributed/elastic_ep/elastic_execute.py +++ b/vllm/distributed/elastic_ep/elastic_execute.py @@ -4,6 +4,7 @@ import gc import weakref from collections.abc import Iterable, Sequence +from typing import TYPE_CHECKING import torch import torch.nn as nn @@ -31,6 +32,7 @@ ) from vllm.distributed.eplb.eplb_communicator import create_eplb_communicator from vllm.distributed.parallel_state import ( + _abort_and_replace_active_groups, _replace_active_groups, get_eplb_group, prepare_communication_buffer_for_model, @@ -43,9 +45,68 @@ from vllm.v1.worker.gpu_ubatch_wrapper import UBatchWrapper from vllm.v1.worker.workspace import lock_workspace, unlock_workspace +if TYPE_CHECKING: + from vllm.distributed.eplb.eplb_state import EplbModelState + logger = init_logger(__name__) +def dead_dp_to_ep_ranks( + dead_dp_ranks: set[int] | list[int], + tp_size: int, +) -> set[int]: + """Expand dead DP ranks to the corresponding dead EP ranks.""" + dead_ep: set[int] = set() + for dp_rank in dead_dp_ranks: + for tp_offset in range(tp_size): + dead_ep.add(dp_rank * tp_size + tp_offset) + return dead_ep + + +def strip_dead_columns( + p2l: torch.Tensor, + dead_ep_ranks: set[int], + num_local: int, +) -> torch.Tensor: + """Remove dead EP rank columns from physical_to_logical_map. + + Returns a new contiguous tensor with only the surviving ranks' + columns, preserving order. + """ + old_ep_size = p2l.shape[1] // num_local + surviving_cols: list[int] = [] + for ep_r in range(old_ep_size): + if ep_r not in dead_ep_ranks: + start = ep_r * num_local + surviving_cols.extend(range(start, start + num_local)) + col_idx = torch.tensor(surviving_cols, device=p2l.device) + return p2l[:, col_idx].contiguous() + + +def rebuild_eplb_derived_maps( + eplb_model_state: "EplbModelState", +) -> None: + """Rebuild logical_to_physical_map and logical_replica_count + from physical_to_logical_map. + + Call after any modification to physical_to_logical_map (compaction, + reassignment) to keep the derived maps consistent. Modifies the + tensors in-place so existing views (held by FusedMoE layers) see + the updates. + """ + p2l = eplb_model_state.physical_to_logical_map + num_moe_layers, num_physical = p2l.shape + eplb_model_state.logical_replica_count.zero_() + eplb_model_state.logical_to_physical_map.fill_(-1) + for layer_idx in range(num_moe_layers): + for phys_idx in range(num_physical): + lid = p2l[layer_idx, phys_idx].item() + if lid >= 0: + c = eplb_model_state.logical_replica_count[layer_idx, lid].item() + eplb_model_state.logical_to_physical_map[layer_idx, lid, c] = phys_idx + eplb_model_state.logical_replica_count[layer_idx, lid] += 1 + + def batch_transfer_weights( model: nn.Module, is_sender: bool, @@ -174,7 +235,9 @@ def load_model(self) -> None: self._set_eplb_suppressed(True) def create_standby_groups( - self, reconfig_request: ReconfigureDistributedRequest + self, + reconfig_request: ReconfigureDistributedRequest, + dead_dp_ranks: set[int] | None = None, ) -> None: self.reconfig_request = reconfig_request new_dp_size = reconfig_request.new_data_parallel_size @@ -193,6 +256,7 @@ def create_standby_groups( master_ip=reconfig_request.new_data_parallel_master_ip, coord_store_port=reconfig_request.coord_store_port, enable_eplb=updated_config.parallel_config.enable_eplb, + dead_dp_ranks=dead_dp_ranks, ) if new_dp_size > old_dp_size: self._set_eplb_suppressed(True) @@ -283,19 +347,52 @@ def switch_and_remove(self) -> None: self._release_cuda_graphs() _replace_active_groups(world=None, dp=None, ep=None, eplb=None, node_count=None) - def switch_and_prepare(self) -> None: + def abort_and_switch(self) -> None: + """Abort old NCCL groups and switch to standby groups. + + Used for fault-triggered scale-down where a peer rank has died + and normal collective teardown would hang. Identical to + switch_and_prepare but uses abort instead of destroy. + + TODO: Currently abort() is called here in the recovery path, + which requires all surviving ranks to reach this point first. + If a worker is stuck in a collective (e.g. all2all mid-forward), + it can never reach here — deadlock. A more robust approach is + to call abort() from a separate sentinel thread that monitors + rank health independently. The sentinel would abort the local + communicators immediately on death detection, unblocking the + main thread's hung collective so it can enter recovery. + """ old_dp_size = get_dp_group().world_size old_ep_size = get_ep_group().world_size + self._release_cuda_graphs() + _abort_and_replace_active_groups(**pop_standby_groups()) + self._apply_new_config(old_dp_size, old_ep_size) + def switch_and_prepare(self) -> None: + old_dp_size = get_dp_group().world_size + old_ep_size = get_ep_group().world_size self._release_cuda_graphs() _replace_active_groups(**pop_standby_groups()) + self._apply_new_config(old_dp_size, old_ep_size) + def _apply_new_config(self, old_dp_size: int, old_ep_size: int) -> None: + """Apply reconfigure request to parallel config, MoE modules, + EPLB state, and communication buffers after group replacement.""" parallel_config = self.worker.vllm_config.parallel_config reconfig_request = self.reconfig_request assert reconfig_request is not None new_dp_size = reconfig_request.new_data_parallel_size new_ep_size = get_ep_group().world_size + logger.debug( + "[Elastic EP] _apply_new_config: DP %d→%d, EP %d→%d", + old_dp_size, + new_dp_size, + old_ep_size, + new_ep_size, + ) + parallel_config.data_parallel_size = new_dp_size if ( reconfig_request.new_data_parallel_rank @@ -341,6 +438,11 @@ def switch_and_prepare(self) -> None: vllm_parallel_config=parallel_config, ) module.moe_config.moe_parallel_config = module.moe_parallel_config + # Rebuild _expert_map for the new EP size/rank. Without this, + # the map has the old size (e.g. 96 entries for 3 ranks) and + # indexing with new expert IDs causes out-of-bounds access. + if hasattr(module, "update_expert_map") and module._expert_map is not None: + module.update_expert_map() # Update EPLB state eplb_state = self.worker.model_runner.eplb_state @@ -391,6 +493,27 @@ def switch_and_prepare(self) -> None: ] eplb_state.num_valid_physical_experts = num_physical_experts + # Trim physical_to_logical_map to match the new EP size. + # For fault-triggered scale-down, dead rank columns are in + # the middle — strip them. For graceful, the highest columns + # are removed — simple slice works too. + dead_dp = ( + set(reconfig_request.dead_dp_ranks) + if reconfig_request.dead_dp_ranks + else set() + ) + if dead_dp: + dead_ep = dead_dp_to_ep_ranks(dead_dp, get_tp_group().world_size) + eplb_model_state.physical_to_logical_map = strip_dead_columns( + old_physical_to_logical, dead_ep, num_local_experts + ) + else: + eplb_model_state.physical_to_logical_map = old_physical_to_logical[ + :, :num_physical_experts + ] + + rebuild_eplb_derived_maps(eplb_model_state) + model = self.worker.model_runner.get_model() model.expert_weights = [] with set_current_vllm_config(self.worker.vllm_config): @@ -440,6 +563,18 @@ def switch_and_prepare(self) -> None: ) multi_block_table.clear() + # For fault-triggered scale-down, reassign missing experts + # BEFORE warmup. The warmup does a real forward pass (for CUDA + # graph capture), which will crash if logical experts are missing + # from the p2l map (router produces expert IDs that map to -1). + reconfig_request = self.reconfig_request + if ( + reconfig_request + and reconfig_request.dead_dp_ranks + and new_dp_size < old_dp_size + ): + self.reassign_missing_experts() + unlock_workspace() self.worker.compile_or_warm_up_model() lock_workspace() @@ -484,16 +619,240 @@ def perform_eplb_reshuffle(self) -> None: self._perform_eplb_reshuffle() self._set_eplb_suppressed(False) - def perform_scale_down_eplb_reshuffle(self, new_dp_size: int) -> None: + def reassign_missing_experts(self) -> None: + """Reassign logical experts that lost all replicas after a fault. + + After a fault-triggered scale-down, _apply_new_config has already + compacted physical_to_logical_map (stripped dead rank columns). + This method: + 1. Identifies which logical experts have zero replicas. + 2. Replaces the most-redundant replicas with missing experts. + 3. Rebuilds the derived EPLB maps in-place. + 4. Transfers actual expert weights via NCCL P2P. + + All tensors are already sized for the new EP topology when this + method runs (p2l, expert_load_pass, expert_load_window all have + new_ep_size * num_local columns). + """ + eplb_state = self.worker.model_runner.eplb_state + if eplb_state is None: + return + + model_config = self.worker.model_runner.model_config + eplb_model_state = eplb_state.model_states[model_config.compute_hash()] + p2l = eplb_model_state.physical_to_logical_map + num_moe_layers = p2l.shape[0] + num_physical = p2l.shape[1] + num_logical = eplb_model_state.logical_replica_count.shape[1] + + ep_group = get_ep_group() + ep_rank = ep_group.rank + new_ep_size = ep_group.world_size + + # Save the current map — this reflects the true state of expert + # weights in GPU memory (before reassignment modifies it). + old_p2l = p2l.clone() + + logger.debug( + "[Elastic EP] reassign_missing_experts: p2l shape=%s, " + "%d logical experts, %d physical slots", + list(p2l.shape), + num_logical, + num_physical, + ) + + # --- 1 & 2. Identify missing experts and reassign ----------------- + all_logical = set(range(num_logical)) + any_reassigned = False + + for layer_idx in range(num_moe_layers): + layer_map = p2l[layer_idx] + + replica_count: dict[int, int] = {} + global_redundant: list[tuple[int, int]] = [] + for phys_idx in range(num_physical): + lid = layer_map[phys_idx].item() + if lid >= 0: + replica_count[lid] = replica_count.get(lid, 0) + 1 + + missing = sorted(all_logical - set(replica_count.keys())) + if not missing: + continue + + any_reassigned = True + + for phys_idx in range(num_physical): + lid = layer_map[phys_idx].item() + if lid >= 0 and replica_count.get(lid, 0) > 1: + global_redundant.append((replica_count[lid], phys_idx)) + global_redundant.sort(reverse=True) + + slot_iter = iter(global_redundant) + for logical_id in missing: + # Find a redundant slot whose donor still has >1 replica. + placed = False + while True: + candidate = next(slot_iter, None) + if candidate is None: + raise RuntimeError( + f"[Fault Tolerance] Layer {layer_idx}: no " + f"redundant slot available to place missing " + f"logical expert {logical_id}. This should " + f"not happen — the capacity check in " + f"_on_engine_process_died should have " + f"prevented scale-down." + ) + _, global_slot = candidate + old_lid = layer_map[global_slot].item() + if replica_count.get(old_lid, 0) > 1: + p2l[layer_idx, global_slot] = logical_id + replica_count[old_lid] -= 1 + placed = True + break + if not placed: + raise RuntimeError( + f"[Fault Tolerance] Layer {layer_idx}: failed " + f"to place missing logical expert {logical_id}." + ) + + if not any_reassigned: + if ep_rank == 0: + logger.info( + "[Fault Tolerance] All %d logical experts have at " + "least one replica in every layer — no " + "reassignment needed.", + num_logical, + ) + return + + if ep_rank == 0: + logger.info( + "[Fault Tolerance] Replaced redundant expert slots " + "with missing experts across %d layers.", + num_moe_layers, + ) + + # --- 3. Rebuild derived maps in-place -------------------------------- + rebuild_eplb_derived_maps(eplb_model_state) + + # --- 4. Transfer actual expert weights via NCCL P2P --------------- + # old_p2l reflects what's actually in GPU memory (pre-reassignment). + # p2l reflects the desired state (post-reassignment). + # rearrange_expert_weights_inplace sees the diff and transfers + # weights from ranks that hold the needed expert. + # + # Split experts into two groups: + # - reachable: have a surviving replica in old_p2l → NCCL P2P + # - unreachable: no surviving replica → reload from disk + old_present = set(old_p2l[old_p2l >= 0].tolist()) + new_required = set(p2l[p2l >= 0].tolist()) + unreachable = new_required - old_present + + from vllm.distributed.eplb.rebalance_execute import ( + rearrange_expert_weights_inplace, + ) + + model = self.worker.model_runner.get_model() + ep_group_pg = get_ep_group().device_group + rearrange_expert_weights_inplace( + old_global_expert_indices=old_p2l, + new_global_expert_indices=p2l, + expert_weights=model.expert_weights, + ep_group=ep_group_pg, + communicator=eplb_model_state.communicator, + ) + + # Reload unreachable experts from disk. + if unreachable: + if ep_rank == 0: + logger.info( + "[Fault Tolerance] Reloading %d experts from disk: %s", + len(unreachable), + sorted(unreachable), + ) + self._reload_expert_weights_from_disk(unreachable) + + if ep_rank == 0: + logger.info( + "[Fault Tolerance] Expert weight transfer complete. " + "%d physical experts across %d EP ranks.", + num_physical, + new_ep_size, + ) + + def _reload_expert_weights_from_disk(self, unreachable_experts: set[int]) -> None: + """Reload expert weights from the model checkpoint for experts + that have no surviving replica in GPU memory. + + Uses the existing model.load_weights() pipeline. The FusedMoE + weight_loader consults logical_to_physical_map (already updated + by reassign_missing_experts) to route each expert's weights to + the correct reassigned physical slot. + """ + from vllm.model_executor.model_loader.default_loader import ( + DefaultModelLoader, + ) + from vllm.model_executor.model_loader.ep_weight_filter import ( + parse_expert_id, + ) + + model = self.worker.model_runner.get_model() + model_config = self.worker.model_runner.model_config + load_config = self.worker.vllm_config.load_config + + loader = DefaultModelLoader(load_config) + all_weights = loader.get_all_weights(model_config, model) + filtered = ( + (name, tensor) + for name, tensor in all_weights + if parse_expert_id(name) in unreachable_experts + ) + model.load_weights(filtered) + + def abort_eplb_group_for_dead_ranks(self) -> None: + """Abort the EPLB NCCL process group so that pending/future NCCL + ops involving dead ranks don't hang indefinitely. After this call + the old EPLB communicator is unusable — a new standby group must be + created before any further EPLB operations.""" + from vllm.distributed.parallel_state import get_eplb_group + + eplb_group = get_eplb_group() + logger.info( + "[Elastic EP] Aborting old EPLB process group (rank %d) " + "to unblock operations involving dead ranks.", + eplb_group.rank, + ) + eplb_group.device_group.abort() + + def perform_scale_down_eplb_reshuffle( + self, + new_dp_size: int, + dead_dp_ranks: list[int] | None = None, + ) -> None: self._set_eplb_suppressed(True) parallel_config = self.worker.vllm_config.parallel_config tp_size = parallel_config.tensor_parallel_size old_ep_size = parallel_config.data_parallel_size * tp_size new_ep_size = new_dp_size * tp_size - rank_mapping = { - old_ep_rank: old_ep_rank if old_ep_rank < new_ep_size else -1 - for old_ep_rank in range(old_ep_size) - } + + if dead_dp_ranks: + # Fault-triggered: map dead ranks' experts to -1, compact + # surviving ranks to contiguous 0..new_ep_size-1. + dead_ep = dead_dp_to_ep_ranks(dead_dp_ranks, tp_size) + rank_mapping = {} + new_rank = 0 + for old_ep_rank in range(old_ep_size): + if old_ep_rank in dead_ep: + rank_mapping[old_ep_rank] = -1 + else: + rank_mapping[old_ep_rank] = new_rank + new_rank += 1 + else: + # Graceful: remove the highest-ranked engines. + rank_mapping = { + old_ep_rank: old_ep_rank if old_ep_rank < new_ep_size else -1 + for old_ep_rank in range(old_ep_size) + } self._perform_eplb_reshuffle(rank_mapping=rank_mapping) def receive_weights(self) -> None: diff --git a/vllm/distributed/elastic_ep/elastic_state.py b/vllm/distributed/elastic_ep/elastic_state.py index bace771a2ab6..b4f2f3a258a6 100644 --- a/vllm/distributed/elastic_ep/elastic_state.py +++ b/vllm/distributed/elastic_ep/elastic_state.py @@ -102,6 +102,10 @@ def __init__( self.scale_type = scale_type self.reconfig_request = reconfig_request + self.dead_dp_ranks: set[int] = set() + if reconfig_request is not None and reconfig_request.dead_dp_ranks: + self.dead_dp_ranks = set(reconfig_request.dead_dp_ranks) + self.state: EngineState if scale_type == "scale_up": self.state = ( @@ -150,15 +154,25 @@ def run_pre_kv_init_states(self) -> None: assert self.state == ScaleUpNewEngineState.PREPARE def _execute_tcp_store_barrier( - self, dp_store, group_rank, group_size, barrier_id, timeout=None + self, + dp_store, + group_rank, + group_size, + barrier_id, + timeout=None, + skip_ranks: set[int] | None = None, ): + if skip_ranks is None: + skip_ranks = set() + expected_count = group_size - len(skip_ranks) + arrival_key = f"arrival_{barrier_id}_{group_rank}" dp_store.set(arrival_key, b"1") start_time = time.time() processes_arrived: set[int] = set() - while len(processes_arrived) < group_size: + while len(processes_arrived) < expected_count: if ( timeout is not None and time.time() - start_time > timeout.total_seconds() @@ -168,7 +182,7 @@ def _execute_tcp_store_barrier( ) for i in range(group_size): - if i in processes_arrived: + if i in processes_arrived or i in skip_ranks: continue key = f"arrival_{barrier_id}_{i}" @@ -176,7 +190,7 @@ def _execute_tcp_store_barrier( if present: processes_arrived.add(i) - if len(processes_arrived) < group_size: + if len(processes_arrived) < expected_count: sched_yield() def _staged_barrier(self, use_new_group: bool, barrier_name: str) -> bool: @@ -208,15 +222,28 @@ def _staged_barrier(self, use_new_group: bool, barrier_name: str) -> bool: # TODO(yongji): figure out appropriate timeout for the barrier timeout = None if dp_store.check([sync_key]) else timedelta(seconds=5) + # When ranks are dead, the gloo-based torch.distributed.barrier + # would hang. Use TCP store barrier only for synchronization. + has_dead_ranks = len(self.dead_dp_ranks) > 0 + try: self._execute_tcp_store_barrier( - dp_store, group_rank, group_size, barrier_id, timeout=timeout + dp_store, + group_rank, + group_size, + barrier_id, + timeout=timeout, + skip_ranks=self.dead_dp_ranks, ) - torch.distributed.barrier(dp_group) - if group_rank == 0: + if not has_dead_ranks: + torch.distributed.barrier(dp_group) + + alive_rank_0 = self._first_alive_rank() + if group_rank == alive_rank_0: dp_store.delete_key(sync_key) for i in range(group_size): - dp_store.delete_key(f"arrival_{barrier_id}_{i}") + if i not in self.dead_dp_ranks: + dp_store.delete_key(f"arrival_{barrier_id}_{i}") return True except _BarrierTimeoutError as e: if timeout is None: @@ -224,6 +251,14 @@ def _staged_barrier(self, use_new_group: bool, barrier_name: str) -> bool: dp_store.compare_set(sync_key, "", b"1") return False + def _first_alive_rank(self) -> int: + """Return the lowest-numbered rank that is not dead.""" + assert self.old_dp_group is not None + for i in range(self.old_dp_group.size()): + if i not in self.dead_dp_ranks: + return i + raise RuntimeError("All ranks are dead") + def _progress_existing_engine(self) -> bool: state = self.state assert self.old_dp_group is not None and self.old_dp_store is not None @@ -360,11 +395,31 @@ def _progress_new_engine(self) -> bool: assert self.state == ScaleUpNewEngineState.COMPLETE return True + def _alive_group_size(self) -> int: + """Number of ranks expected to participate in barriers.""" + assert self.old_dp_group is not None + return self.old_dp_group.size() - len(self.dead_dp_ranks) + + def _abort_eplb_group_for_dead_ranks(self): + """Abort the old EPLB NCCL process group so operations involving + dead ranks don't hang. Must be called from the worker via + collective_rpc so it runs on every surviving rank.""" + self.model_executor.collective_rpc( + "elastic_ep_execute", + args=("abort_eplb_group_for_dead_ranks",), + ) + def _progress_remaining_engine(self) -> bool: state = self.state assert self.old_dp_group is not None and self.old_dp_store is not None if state == ScaleDownRemainingEngineState.PREPARE: + if self.dead_dp_ranks: + # Abort the old EPLB NCCL process group so that any + # pending/future NCCL ops involving the dead rank don't + # hang. The standby groups (created later) will provide + # a new communicator for the surviving ranks. + self._abort_eplb_group_for_dead_ranks() self.state = ScaleDownRemainingEngineState.EPLB_RESHUFFLE self.old_dp_store.add("eep_barrier_engine_count", 1) return True @@ -372,27 +427,32 @@ def _progress_remaining_engine(self) -> bool: elif state == ScaleDownRemainingEngineState.EPLB_RESHUFFLE: if ( int(self.old_dp_store.get("eep_barrier_engine_count")) - < self.old_dp_group.size() + < self._alive_group_size() ): return False if not self._staged_barrier( use_new_group=False, barrier_name="eplb_reshuffle" ): return False - if self.old_dp_group.rank() == 0: + alive_rank_0 = self._first_alive_rank() + if self.old_dp_group.rank() == alive_rank_0: self.old_dp_store.delete_key("eep_barrier_engine_count") - self._eplb_reshuffle_before_scale_down() + + if self.dead_dp_ranks: + if self.old_dp_group.rank() == alive_rank_0: + logger.info( + "[Elastic EP] Skipping EPLB reshuffle (fault-" + "triggered, dead ranks: %s)", + self.dead_dp_ranks, + ) + else: + self._eplb_reshuffle_before_scale_down() + self.state = ScaleDownRemainingEngineState.SWITCH_AND_PREPARE - # NOTE(yongji): currently, after EPLB reshuffle - # that redistributes experts to remaining workers, workers - # to be removed will immediately initiate shutdown; - # existing workers can no longer execute forward steps using - # the old setup. In the future, we may keep - # the removing workers alive a bit longer, - # e.g., to drain in-batch requests. self._create_standby_groups() self._switch_and_prepare() self._update_parallel_config() + self.state = ScaleDownRemainingEngineState.COMPLETE return True @@ -412,7 +472,7 @@ def _progress_removing_engine(self) -> bool: if state == ScaleDownRemovingEngineState.EPLB_RESHUFFLE: if ( int(self.old_dp_store.get("eep_barrier_engine_count")) - < self.old_dp_group.size() + < self._alive_group_size() ): return False if not self._staged_barrier( @@ -468,7 +528,12 @@ def _create_standby_groups(self): self.new_parallel_config.stateless_init_dp_group(return_store=True) ) self.model_executor.collective_rpc( - "elastic_ep_execute", args=("create_standby_groups", self.reconfig_request) + "elastic_ep_execute", + args=( + "create_standby_groups", + self.reconfig_request, + self.dead_dp_ranks or None, + ), ) if self.old_dp_group.rank() == 0: logger.info("[Elastic EP] Created standby communication groups") @@ -503,11 +568,25 @@ def _sync_kv_cache_memory_size(self): logger.info("[Elastic EP] Synced KV cache memory size to new workers") def _switch_and_prepare(self): - self.model_executor.collective_rpc( - "elastic_ep_execute", args=("switch_and_prepare",) - ) - old_dp_group = self.old_dp_group - stateless_destroy_torch_distributed_process_group(old_dp_group) + has_dead = len(self.dead_dp_ranks) > 0 + if has_dead: + # Fault-triggered: abort the old groups to avoid NCCL hang. + self.model_executor.collective_rpc( + "elastic_ep_execute", args=("abort_and_switch",) + ) + from vllm.distributed.utils import ( + stateless_abort_torch_distributed_process_group, + ) + + old_dp_group = self.old_dp_group + stateless_abort_torch_distributed_process_group(old_dp_group) + else: + self.model_executor.collective_rpc( + "elastic_ep_execute", args=("switch_and_prepare",) + ) + old_dp_group = self.old_dp_group + stateless_destroy_torch_distributed_process_group(old_dp_group) + assert self.new_dp_group is not None new_dp_group = self.new_dp_group self.engine_core.dp_group = new_dp_group @@ -542,6 +621,16 @@ def _eplb_reshuffle(self): if self.new_dp_group.rank() == 0: logger.info("[Elastic EP] EPLB reshuffle completed") + def _reload_missing_experts(self): + """Reload logical experts that lost all replicas due to a fault.""" + self.model_executor.collective_rpc( + "elastic_ep_execute", + args=("reassign_missing_experts",), + ) + assert self.new_dp_group is not None + if self.new_dp_group.rank() == 0: + logger.info("[Elastic EP] Missing expert reload completed") + def _eplb_reshuffle_before_scale_down(self): assert self.reconfig_request is not None and self.old_dp_group is not None self.model_executor.collective_rpc( @@ -549,6 +638,7 @@ def _eplb_reshuffle_before_scale_down(self): args=( "perform_scale_down_eplb_reshuffle", self.reconfig_request.new_data_parallel_size, + self.reconfig_request.dead_dp_ranks or None, ), ) if self.old_dp_group.rank() == 0: diff --git a/vllm/distributed/elastic_ep/standby_state.py b/vllm/distributed/elastic_ep/standby_state.py index 846793a955f6..d4fc043b2970 100644 --- a/vllm/distributed/elastic_ep/standby_state.py +++ b/vllm/distributed/elastic_ep/standby_state.py @@ -34,6 +34,33 @@ def get_standby_world_group() -> StatelessGroupCoordinator | None: return _STANDBY_WORLD +def _build_surviving_rank_tensor( + new_dp_size: int, + pp_size: int, + tp_size: int, + dead_dp_ranks: set[int], + current_world_ranks: list[int] | None = None, +) -> torch.Tensor: + """Build a rank tensor containing only the surviving world ranks. + + Returns a tensor of shape (*, new_dp_size, pp_size, tp_size) with the + actual world-rank values of the surviving engines, preserving the + original ordering and skipping dead DP ranks. + + Args: + current_world_ranks: The actual world ranks of the current group. + If None, fetched from get_world_group().ranks. After previous + scale-downs these may be non-contiguous (e.g. [0, 2, 3]). + """ + old_dp_size = new_dp_size + len(dead_dp_ranks) + if current_world_ranks is None: + current_world_ranks = get_world_group().ranks + full = torch.tensor(current_world_ranks).reshape(-1, old_dp_size, pp_size, tp_size) + surviving_dp_indices = [i for i in range(old_dp_size) if i not in dead_dp_ranks] + assert len(surviving_dp_indices) == new_dp_size + return full[:, surviving_dp_indices, :, :] + + def create_standby_groups( new_dp_size: int, new_world_size_across_dp: int, @@ -41,6 +68,7 @@ def create_standby_groups( coord_store_port: int, enable_eplb: bool = True, backend: str | None = None, + dead_dp_ranks: set[int] | None = None, ) -> None: global \ _STANDBY_WORLD, \ @@ -51,14 +79,31 @@ def create_standby_groups( from vllm.distributed.utils import get_cached_tcp_store_client - assert new_world_size_across_dp == torch.distributed.get_world_size() * new_dp_size world_group = get_world_group() assert isinstance(world_group, StatelessGroupCoordinator) backend = backend or world_group.backend coord_store = get_cached_tcp_store_client(master_ip, coord_store_port) - standby_world_ranks = [list(range(new_world_size_across_dp))] + tp_size = get_tp_group().world_size + pp_size = get_pp_group().world_size + + if dead_dp_ranks: + # Fault-triggered: surviving world ranks are non-contiguous. + all_ranks = _build_surviving_rank_tensor( + new_dp_size, pp_size, tp_size, dead_dp_ranks + ) + surviving_world_ranks = sorted(all_ranks.flatten().tolist()) + else: + assert new_world_size_across_dp == ( + torch.distributed.get_world_size() * new_dp_size + ) + all_ranks = torch.arange(new_world_size_across_dp).reshape( + -1, new_dp_size, pp_size, tp_size + ) + surviving_world_ranks = list(range(new_world_size_across_dp)) + + standby_world_ranks = [surviving_world_ranks] _STANDBY_WORLD = _init_stateless_group( standby_world_ranks, "world", @@ -69,12 +114,6 @@ def create_standby_groups( ) _STANDBY_WORLD_NODE_COUNT = _node_count(_STANDBY_WORLD.tcp_store_group) - tp_size = get_tp_group().world_size - pp_size = get_pp_group().world_size - - all_ranks = torch.arange(new_world_size_across_dp).reshape( - -1, new_dp_size, pp_size, tp_size - ) standby_dp_ranks = all_ranks.transpose(1, 3).reshape(-1, new_dp_size).unbind(0) standby_dp_ranks = [x.tolist() for x in standby_dp_ranks] _STANDBY_DP = _init_stateless_group( diff --git a/vllm/distributed/parallel_state.py b/vllm/distributed/parallel_state.py index 473acb908b28..2ec022e20982 100644 --- a/vllm/distributed/parallel_state.py +++ b/vllm/distributed/parallel_state.py @@ -1215,6 +1215,80 @@ def _replace_active_groups( _NODE_COUNT = node_count +def _abort_and_replace_active_groups( + *, + world: GroupCoordinator | None, + dp: GroupCoordinator | None, + ep: GroupCoordinator | None, + eplb: GroupCoordinator | None, + node_count: int | None, +) -> None: + """Abort the current DP/EP/WORLD/EPLB groups and replace them. + + Unlike _replace_active_groups, this uses abort() instead of destroy() + to avoid hanging when a peer rank has died. + + TODO: This is called from the main worker thread during recovery, + which means the worker must not be stuck in a collective to reach + here. For robustness, abort() should be callable from a sentinel + thread so that workers stuck in mid-forward collectives can be + unblocked immediately on fault detection. + """ + global _WORLD, _DP, _EP, _EPLB, _NODE_COUNT + for group in (_DP, _EP, _WORLD, _EPLB): + if group is not None: + # Abort underlying ProcessGroups to unblock pending NCCL/Gloo + # ops involving dead ranks. Wrapped in try/except because the + # group may have already been aborted (e.g. EPLB group aborted + # early to unblock barriers). + try: + if hasattr(group, "device_group") and group.device_group: + group.device_group.abort() + except Exception: + logger.warning( + "[Fault Tolerance] Failed to abort device_group", + exc_info=True, + ) + try: + if hasattr(group, "cpu_group") and group.cpu_group: + group.cpu_group.abort() + except Exception: + logger.warning( + "[Fault Tolerance] Failed to abort cpu_group", + exc_info=True, + ) + # Abort device communicator last — uses ncclCommAbort + # (not ncclCommDestroy) to avoid triggering an implicit + # ncclCommFinalize collective that would hang. + try: + if hasattr(group, "device_communicator") and group.device_communicator: + group.device_communicator.abort() + except Exception: + logger.warning( + "[Fault Tolerance] Failed to abort device_communicator", + exc_info=True, + ) + # Synchronize to surface any async CUDA errors from the aborts + # immediately, rather than having them appear later during + # unrelated operations (per NCCL team recommendation). + try: + import torch + + # Use the platform-agnostic accelerator API per + # https://github.com/vllm-project/vllm/issues/30679. + torch.accelerator.synchronize() + except Exception: + logger.warning( + "[Fault Tolerance] accelerator sync after abort raised an error", + exc_info=True, + ) + _WORLD = world + _DP = dp + _EP = ep + _EPLB = eplb + _NODE_COUNT = node_count + + _TP: GroupCoordinator | None = None diff --git a/vllm/distributed/stateless_coordinator.py b/vllm/distributed/stateless_coordinator.py index 549284df32df..7ecc31f8454f 100644 --- a/vllm/distributed/stateless_coordinator.py +++ b/vllm/distributed/stateless_coordinator.py @@ -192,6 +192,23 @@ def destroy(self): if self.cpu_group: stateless_destroy_torch_distributed_process_group(self.cpu_group) + def abort(self): + """Abort all underlying process groups without waiting for peers. + + Use instead of destroy() when a peer rank in this group has died + and normal collective teardown would hang. + """ + from vllm.distributed.utils import ( + stateless_abort_torch_distributed_process_group, + ) + + if self.device_communicator: + self.device_communicator.abort() + if self.device_group: + stateless_abort_torch_distributed_process_group(self.device_group) + if self.cpu_group: + stateless_abort_torch_distributed_process_group(self.cpu_group) + def size(self) -> int: """Return the world size of this group.""" return self.world_size diff --git a/vllm/distributed/utils.py b/vllm/distributed/utils.py index 9991ab1ddc23..f50a83444d82 100644 --- a/vllm/distributed/utils.py +++ b/vllm/distributed/utils.py @@ -633,6 +633,18 @@ def stateless_destroy_torch_distributed_process_group(pg: ProcessGroup) -> None: _unregister_process_group(pg.group_name) +def stateless_abort_torch_distributed_process_group(pg: ProcessGroup) -> None: + """Abort a process group without waiting for pending operations. + + Unlike destroy (which calls shutdown and may block if a peer is dead), + abort forces the underlying communicator to release immediately. + Use this when a rank in the group has died and normal teardown would hang. + Works with any backend (NCCL, Gloo, etc.). + """ + pg.abort() + _unregister_process_group(pg.group_name) + + def get_worker_rank_suffix(global_rank: int | None = None) -> str: """Generate a descriptive rank suffix for worker identification. diff --git a/vllm/engine/arg_utils.py b/vllm/engine/arg_utils.py index cd9551003339..7c779bbc90b8 100644 --- a/vllm/engine/arg_utils.py +++ b/vllm/engine/arg_utils.py @@ -468,6 +468,7 @@ class EngineArgs: moe_backend: MoEBackend = KernelConfig.moe_backend all2all_backend: All2AllBackend = ParallelConfig.all2all_backend enable_elastic_ep: bool = ParallelConfig.enable_elastic_ep + enable_ep_fault_tolerance: bool = ParallelConfig.enable_ep_fault_tolerance enable_dbo: bool = ParallelConfig.enable_dbo ubatch_size: int = ParallelConfig.ubatch_size dbo_decode_token_threshold: int = ParallelConfig.dbo_decode_token_threshold @@ -1025,6 +1026,10 @@ def add_cli_args(parser: FlexibleArgumentParser) -> FlexibleArgumentParser: parallel_group.add_argument( "--enable-elastic-ep", **parallel_kwargs["enable_elastic_ep"] ) + parallel_group.add_argument( + "--enable-ep-fault-tolerance", + **parallel_kwargs["enable_ep_fault_tolerance"], + ) parallel_group.add_argument( "--dbo-decode-token-threshold", **parallel_kwargs["dbo_decode_token_threshold"], @@ -1905,6 +1910,7 @@ def create_engine_config( enable_ep_weight_filter=self.enable_ep_weight_filter, all2all_backend=self.all2all_backend, enable_elastic_ep=self.enable_elastic_ep, + enable_ep_fault_tolerance=self.enable_ep_fault_tolerance, enable_dbo=self.enable_dbo, ubatch_size=self.ubatch_size, dbo_decode_token_threshold=self.dbo_decode_token_threshold, diff --git a/vllm/entrypoints/openai/api_server.py b/vllm/entrypoints/openai/api_server.py index 9aac19e2fda5..57f8a404fd9a 100644 --- a/vllm/entrypoints/openai/api_server.py +++ b/vllm/entrypoints/openai/api_server.py @@ -220,6 +220,12 @@ def build_app( elastic_ep_attach_router(app) + from vllm.entrypoints.serve.fault_tolerance.api_router import ( + attach_router as fault_tolerance_attach_router, + ) + + fault_tolerance_attach_router(app) + from vllm.entrypoints.openai.generative_scoring.api_router import ( register_generative_scoring_api_router, ) diff --git a/vllm/entrypoints/serve/fault_tolerance/__init__.py b/vllm/entrypoints/serve/fault_tolerance/__init__.py new file mode 100644 index 000000000000..208f01a7cb5e --- /dev/null +++ b/vllm/entrypoints/serve/fault_tolerance/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project diff --git a/vllm/entrypoints/serve/fault_tolerance/api_router.py b/vllm/entrypoints/serve/fault_tolerance/api_router.py new file mode 100644 index 000000000000..8031012b24c4 --- /dev/null +++ b/vllm/entrypoints/serve/fault_tolerance/api_router.py @@ -0,0 +1,195 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""HTTP endpoints for the fault tolerance framework. + +Three endpoints: + +* ``GET /fault_tolerance/status`` — return current per-engine health. +* ``POST /fault_tolerance/apply`` — dispatch a recovery instruction. +* ``GET /fault_tolerance/health`` — quick readiness probe. + +The endpoints are thin: they look up the registered supervisor / plan and +delegate. Plans live in ``vllm.v1.fault_tolerance.plans``; the wire format +of the status response is preserved-compatible with the format established +in vllm-project/vllm#34833. +""" + +from __future__ import annotations + +import json +import uuid +from http import HTTPStatus + +from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request +from fastapi.responses import JSONResponse + +from vllm.entrypoints.openai.utils import validate_json_request +from vllm.logger import init_logger +from vllm.v1.fault_tolerance import ( + FaultStatus, + FaultToleranceRequest, + FaultToleranceResult, + get_plan, + list_plans, +) +from vllm.v1.fault_tolerance.registry import _SUPERVISORS + +logger = init_logger(__name__) + +router = APIRouter(prefix="/fault_tolerance") + + +def _engine_client(request: Request): + return request.app.state.engine_client + + +def _wire_status_payload(status_dict: dict[int, FaultStatus]) -> dict: + """Format the engine-status dict for the wire. + + Schema mirrors vllm-project/vllm#34833 so external subscribers (Dynamo, + monitoring, etc.) work without modification: + + .. code-block:: json + + { + "schema_version": 1, + "total_engines": 4, + "engines": [ + {"id": 0, "status": "healthy"}, + {"id": 1, "status": "paused"}, + ... + ] + } + """ + engines = [ + {"id": idx, "status": status.name.lower()} + for idx, status in sorted(status_dict.items()) + ] + return { + "schema_version": 1, + "total_engines": len(engines), + "engines": engines, + } + + +@router.get("/status") +async def fault_tolerance_status(raw_request: Request): + """Return the current per-engine health snapshot.""" + client = _engine_client(raw_request) + fetch = getattr(client, "get_fault_status", None) + if fetch is None: + # FT not enabled or no supervisor configured. + return JSONResponse(_wire_status_payload({})) + try: + status_dict = await fetch() + except Exception as e: + logger.exception("Failed to fetch fault status: %s", e) + raise HTTPException( + status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, + detail="Failed to fetch fault status", + ) from e + return JSONResponse(_wire_status_payload(status_dict)) + + +@router.post( + "/apply", + dependencies=[Depends(validate_json_request)], + responses={ + HTTPStatus.OK.value: {"model": dict}, + HTTPStatus.BAD_REQUEST.value: {"model": dict}, + HTTPStatus.NOT_IMPLEMENTED.value: {"model": dict}, + HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": dict}, + }, +) +async def fault_tolerance_apply(raw_request: Request): + """Dispatch a recovery instruction (pause / retry / scale_down / etc.). + + Body schema:: + + { + "instruction": "pause" | "retry" | "scale_down" | "scale_up" | ..., + "params": {...}, # optional, plan-specific + "request_id": "...", # optional; auto-generated if absent + } + """ + if not _SUPERVISORS: + raise HTTPException( + status_code=HTTPStatus.NOT_IMPLEMENTED.value, + detail="No fault supervisor is registered. Pass --enable-fault-tolerance " + "and select a supervisor with --fault-supervisor.", + ) + try: + body = await raw_request.json() + except json.JSONDecodeError as e: + raise HTTPException( + status_code=HTTPStatus.BAD_REQUEST.value, detail="Invalid JSON" + ) from e + + instruction = body.get("instruction") + if not isinstance(instruction, str) or not instruction: + raise HTTPException( + status_code=HTTPStatus.BAD_REQUEST.value, + detail="'instruction' must be a non-empty string", + ) + if instruction not in list_plans(): + raise HTTPException( + status_code=HTTPStatus.BAD_REQUEST.value, + detail=(f"Unknown instruction '{instruction}'. Registered: {list_plans()}"), + ) + params = body.get("params") or {} + if not isinstance(params, dict): + raise HTTPException( + status_code=HTTPStatus.BAD_REQUEST.value, + detail="'params' must be a JSON object if provided", + ) + request_id = body.get("request_id") or str(uuid.uuid4()) + + ft_request = FaultToleranceRequest( + instruction=instruction, params=params, request_id=request_id + ) + + client = _engine_client(raw_request) + apply_fn = getattr(client, "apply_fault_instruction", None) + if apply_fn is None: + # Default supervisor not wired in (Phase 0). Indicate that a plan is + # registered but no execution path exists yet. + plan = get_plan(instruction) + return JSONResponse( + FaultToleranceResult( + success=False, + reason=( + "No supervisor execution path is wired into the engine " + "client. Plan '{}' is registered but cannot be invoked " + "from HTTP yet.".format(type(plan).__name__) + ), + request_id=request_id, + ).__dict__, + status_code=HTTPStatus.NOT_IMPLEMENTED.value, + ) + + try: + result: FaultToleranceResult = await apply_fn(ft_request) + except Exception as e: + logger.exception("apply_fault_instruction failed: %s", e) + raise HTTPException( + status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, + detail=f"apply failed: {e}", + ) from e + + return JSONResponse( + result.__dict__, + status_code=HTTPStatus.OK.value + if result.success + else HTTPStatus.BAD_REQUEST.value, + ) + + +@router.get("/health") +async def fault_tolerance_health(raw_request: Request): + """Lightweight readiness probe for the FT subsystem itself.""" + return JSONResponse({"ok": True, "registered_plans": list_plans()}) + + +def attach_router(app: FastAPI): + """Register the fault-tolerance routes with the app.""" + app.include_router(router) diff --git a/vllm/model_executor/layers/fused_moe/layer.py b/vllm/model_executor/layers/fused_moe/layer.py index 577f9a986790..60b4ee7dde7c 100644 --- a/vllm/model_executor/layers/fused_moe/layer.py +++ b/vllm/model_executor/layers/fused_moe/layer.py @@ -1119,7 +1119,29 @@ def weight_loader( quant_method_name = self.quant_method.__class__.__name__ global_expert_id = expert_id - expert_id = self._map_global_expert_id_to_local_expert_id(global_expert_id) + + # When EPLB is active, the logical-to-physical mapping may differ + # from the static EP partition in expert_map. Use l2p to find + # the local physical slot for this logical expert. + eplb = getattr(self, "eplb_state", None) + if ( + eplb is not None + and getattr(eplb, "logical_to_physical_map", None) is not None + and global_expert_id < eplb.logical_to_physical_map.shape[0] + ): + l2p = eplb.logical_to_physical_map + replica_count = eplb.logical_replica_count + num_replicas = replica_count[global_expert_id].item() + local_start = self.ep_rank * self.local_num_experts + local_end = local_start + self.local_num_experts + expert_id = -1 + for r in range(num_replicas): + phys = l2p[global_expert_id, r].item() + if local_start <= phys < local_end: + expert_id = phys - local_start + break + else: + expert_id = self._map_global_expert_id_to_local_expert_id(global_expert_id) use_global_sf = ( getattr(self.quant_method, "use_global_sf", False) diff --git a/vllm/v1/engine/__init__.py b/vllm/v1/engine/__init__.py index d5c5dba63475..1352be97ecb3 100644 --- a/vllm/v1/engine/__init__.py +++ b/vllm/v1/engine/__init__.py @@ -251,6 +251,7 @@ class ReconfigureDistributedRequest(msgspec.Struct): new_data_parallel_master_port: int new_data_parallel_master_port_list: list[int] coord_store_port: int + dead_dp_ranks: list[int] = [] class ReconfigureRankType(enum.IntEnum): diff --git a/vllm/v1/engine/async_llm.py b/vllm/v1/engine/async_llm.py index 45ae416529ec..cdbd0d1a63ca 100644 --- a/vllm/v1/engine/async_llm.py +++ b/vllm/v1/engine/async_llm.py @@ -152,6 +152,12 @@ def __init__( client_index=client_index, ) + if hasattr(self.engine_core, "register_ft_abort_callback"): + output_processor = self.output_processor + self.engine_core.register_ft_abort_callback( + lambda req_ids: output_processor.abort_requests(req_ids, internal=True) + ) + # Loggers. self.logger_manager: StatLoggerManager | None = None if self.log_stats: diff --git a/vllm/v1/engine/coordinator.py b/vllm/v1/engine/coordinator.py index 8ebf976c5fa1..e98d4a574e95 100644 --- a/vllm/v1/engine/coordinator.py +++ b/vllm/v1/engine/coordinator.py @@ -312,11 +312,11 @@ def process_input_socket( decoded = msgspec.msgpack.decode(buffer) if ( isinstance(decoded, (list, tuple)) - and len(decoded) == 2 + and len(decoded) >= 2 and decoded[0] == "SCALE_ELASTIC_EP" ): - # Handle scale up notification new_engine_count = decoded[1] + removed_ranks = set(decoded[2]) if len(decoded) >= 3 else set() current_count = len(self.engines) if new_engine_count > current_count: for _ in range(new_engine_count - current_count): @@ -336,6 +336,20 @@ def process_input_socket( current_count, new_engine_count, ) + elif removed_ranks: + # Remove specific engine entries (fault-triggered). + self.engines = [ + e + for i, e in enumerate(self.engines) + if i not in removed_ranks + ] + logger.info( + "DPCoordinator scaled down from %s to %s " + "engines (removed ranks: %s)", + current_count, + new_engine_count, + sorted(removed_ranks), + ) else: self.engines = self.engines[:new_engine_count] logger.info( diff --git a/vllm/v1/engine/core.py b/vllm/v1/engine/core.py index 11c5ee19a664..2d8c64421ff4 100644 --- a/vllm/v1/engine/core.py +++ b/vllm/v1/engine/core.py @@ -72,6 +72,11 @@ get_device_indices, ) from vllm.v1.executor import Executor +from vllm.v1.fault_tolerance import ( + Disposition, + FaultToleranceHooks, + get_fault_hooks, +) from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.metrics.stats import SchedulerStats from vllm.v1.outputs import ModelRunnerOutput @@ -918,6 +923,52 @@ def __init__( assert addresses.coordinator_input is not None logger.info("Waiting for READY message from DP Coordinator...") + # Instantiate the fault-tolerance supervisor when the master FT + # switch is on. This is what `self.hooks` resolves to (otherwise + # `GLOBAL_NOOP_HOOKS`). Plans dispatched via the HTTP API or via + # `fault_supervisor_apply` utility method run through this object. + if getattr(vllm_config.parallel_config, "enable_fault_tolerance", False): + # Touch the plans package so its `@register_recovery_plan` + # decorators populate the registry before any HTTP traffic + # arrives. + import vllm.v1.fault_tolerance.plans # noqa: F401 + from vllm.v1.fault_tolerance.default_supervisor import ( + DefaultFaultSupervisor, + ) + + self.fault_supervisor = DefaultFaultSupervisor(vllm_config, engine=self) + logger.info( + "Fault-tolerance supervisor active for engine %d.", + self.engine_index, + ) + + def fault_supervisor_apply(self, ft_request: Any) -> Any: + """Utility hook so the client can dispatch a recovery instruction. + + Reachable from ``MPClient.call_utility_async("fault_supervisor_apply", + ft_request)``. Returns a :class:`FaultToleranceResult`. When FT is + off this is a no-op that returns failure with a helpful message. + """ + if self.fault_supervisor is None: + from vllm.v1.fault_tolerance import FaultToleranceResult + + return FaultToleranceResult( + success=False, + reason=( + "Fault tolerance is not enabled for this engine. " + "Pass --enable-fault-tolerance to use the recovery API." + ), + ) + return self.fault_supervisor.apply(ft_request) + + def fault_supervisor_status(self) -> dict[int, str]: + """Utility hook returning the engine's current status snapshot.""" + if self.fault_supervisor is None: + return {} + # Convert FaultStatus enum values to lowercase wire strings. + snapshot = self.fault_supervisor.get_status() + return {idx: status.name.lower() for idx, status in snapshot.items()} + @contextmanager def _perform_handshakes( self, @@ -1161,16 +1212,53 @@ def is_running(self) -> bool: """Returns true if shutdown has not been requested.""" return self.shutdown_state == EngineShutdownState.RUNNING + @property + def hooks(self) -> FaultToleranceHooks: + """Active fault-tolerance hooks. No-op singleton when FT is off.""" + return get_fault_hooks(self.vllm_config, self) + def run_busy_loop(self): """Core busy loop of the EngineCore.""" while self._handle_shutdown(): - # 1) Poll the input queue until there is work to do. - self._process_input_queue() - # 2) Step the engine core and return the outputs. - self._process_engine_step() + try: + # 1) Poll the input queue until there is work to do. + self._process_input_queue() + self.hooks.before_step(self) + # 2) Step the engine core and return the outputs. + self._process_engine_step() + self.hooks.after_step(self, self._last_step_output) + except BaseException as exc: + disp = self.hooks.on_step_error(self, exc) + if disp is Disposition.PROPAGATE: + raise + if disp is Disposition.PAUSE_LOOP: + self._block_until_resumed() + if ( + disp is Disposition.SCHEDULE_RETRY + and self.fault_supervisor is not None + ): + self.fault_supervisor.run_retry_plan(self) + # CONTINUE: swallow; treat as logged-only. raise SystemExit + # Set by the supervisor (when FT is enabled) so plans can be dispatched + # without an extra lookup. None when FT is off. + fault_supervisor: Any = None + # Latest output passed to `after_step`. Subclasses populate this in + # `_process_engine_step`. None if the most recent step did not execute. + _last_step_output: Any = None + + def _block_until_resumed(self) -> None: + """Default block when supervisor returns PAUSE_LOOP. Subclasses with + a richer pause condition can override; `DefaultFaultSupervisor` + signals via its own condition variable.""" + if self.fault_supervisor is None: + return + wait_fn = getattr(self.fault_supervisor, "wait_until_resumed", None) + if wait_fn is not None: + wait_fn() + def _process_input_queue(self): """Exits when an engine step needs to be performed.""" @@ -1792,19 +1880,36 @@ def run_busy_loop(self): # Loop until process is sent a SIGINT or SIGTERM while self._handle_shutdown(): - # 1) Poll the input queue until there is work to do. - self._process_input_queue() - - if self.eep_scaling_state is not None: - _ = self.eep_scaling_state.progress() - if self.eep_scaling_state.is_complete(): - if self.eep_scaling_state.worker_type == "removing": - raise SystemExit - self.process_input_queue_block = True - self.eep_scaling_state = None - - executed = self._process_engine_step() - self._maybe_publish_request_counts() + try: + # 1) Poll the input queue until there is work to do. + self._process_input_queue() + + if self.eep_scaling_state is not None: + _ = self.eep_scaling_state.progress() + if self.eep_scaling_state.is_complete(): + if self.eep_scaling_state.worker_type == "removing": + raise SystemExit + self.process_input_queue_block = True + self.eep_scaling_state = None + + self.hooks.before_step(self) + executed = self._process_engine_step() + self.hooks.after_step(self, self._last_step_output) + self._maybe_publish_request_counts() + except SystemExit: + raise + except BaseException as exc: + disp = self.hooks.on_step_error(self, exc) + if disp is Disposition.PROPAGATE: + raise + if disp is Disposition.PAUSE_LOOP: + self._block_until_resumed() + if ( + disp is Disposition.SCHEDULE_RETRY + and self.fault_supervisor is not None + ): + self.fault_supervisor.run_retry_plan(self) + continue local_unfinished_reqs = self.scheduler.has_unfinished_requests() if not executed: diff --git a/vllm/v1/engine/core_client.py b/vllm/v1/engine/core_client.py index 2f2c15d246f8..9eae54f69c9e 100644 --- a/vllm/v1/engine/core_client.py +++ b/vllm/v1/engine/core_client.py @@ -638,6 +638,10 @@ def free_pending_messages(self): def dp_engines_running(self) -> bool: return self.engines_running + def _is_fault_tolerant(self) -> bool: + """Whether this client supports single-engine fault tolerance.""" + return False + def start_engine_core_monitor(self): """Start a monitor thread for engine core processes.""" engine_manager = self.resources.engine_manager @@ -647,8 +651,12 @@ def start_engine_core_monitor(self): self_ref = weakref.ref(self) - # Monitor engine core process liveness. If any die unexpectedly, - # marks the engine as dead, and shuts down the client. + if self._is_fault_tolerant(): + self._start_fault_tolerant_monitor(engine_manager, self_ref) + else: + self._start_standard_monitor(engine_manager, self_ref) + + def _start_standard_monitor(self, engine_manager, self_ref): def monitor_engine_cores(): engine_manager.monitor_engine_liveness() _self = self_ref() @@ -656,9 +664,6 @@ def monitor_engine_cores(): return _self.resources.engine_dead = True _self.shutdown() - # Note: For MPClient, we don't have a failure callback mechanism - # like MultiprocExecutor, but we set engine_dead flag which will - # cause subsequent operations to raise EngineDeadError Thread( target=monitor_engine_cores, daemon=True, name="MPClientEngineMonitor" @@ -690,6 +695,34 @@ def _apply_ready_response(self, payload: bytes) -> None: else: assert response.dp_stats_address == self.stats_update_address + def _start_fault_tolerant_monitor(self, engine_manager, self_ref): + def on_engine_died(proc_name: str, dp_rank: int) -> bool: + _self = self_ref() + if not _self or not _self._finalizer.alive or _self.resources.engine_dead: + return False + return _self._on_engine_process_died(proc_name, dp_rank) + + def monitor_engine_cores_ft(): + engine_manager.monitor_engine_liveness_fault_tolerant(on_engine_died) + _self = self_ref() + if not _self or not _self._finalizer.alive or _self.resources.engine_dead: + return + _self.resources.engine_dead = True + _self.shutdown() + + Thread( + target=monitor_engine_cores_ft, + daemon=True, + name="MPClientFTEngineMonitor", + ).start() + + def _on_engine_process_died(self, proc_name: str, dp_rank: int) -> bool: + """Handle a single engine process death. Returns True to keep + monitoring, False to stop. Default: stop everything.""" + self.resources.engine_dead = True + self.shutdown() + return False + def _process_utility_output( output: UtilityOutput, utility_results: dict[int, AnyFuture] @@ -1138,6 +1171,11 @@ class DPAsyncMPClient(AsyncMPClient): """Asyncio-compatible client for multi-proc, multi-engine (data parallel) EngineCore. Assumes external load-balancing by default.""" + # Declared at the base class so subclasses can assign None during + # __init__ before the loop is captured. The FT monitor thread reads + # this lazily; subclasses without FT support never assign it. + _ft_event_loop: asyncio.AbstractEventLoop | None = None + def __init__( self, vllm_config: VllmConfig, @@ -1217,12 +1255,13 @@ async def run_engine_stats_update_task(): decoded = msgspec.msgpack.decode(buf) if ( isinstance(decoded, (list, tuple)) - and len(decoded) == 2 + and len(decoded) >= 2 and decoded[0] == "SCALE_ELASTIC_EP" ): - # Extract new engine count from the decoded message new_engine_count = decoded[1] - # Update engine_ranks_managed and count_slice + removed_ranks = ( + set(decoded[2]) if len(decoded) >= 3 else set() + ) parallel_config = self.vllm_config.parallel_config dp_size = parallel_config.data_parallel_size dp_rank = parallel_config.data_parallel_rank @@ -1243,11 +1282,21 @@ async def run_engine_stats_update_task(): new_engine_count - len(self.lb_engines) ) ] + elif removed_ranks: + self.lb_engines = [ + lb + for i, lb in enumerate(self.lb_engines) + if i not in removed_ranks + ] else: self.lb_engines = self.lb_engines[:new_engine_count] - # Send scale up notification to coordinator + # Forward to coordinator (include removed ranks). scale_msg = msgspec.msgpack.encode( - ("SCALE_ELASTIC_EP", new_engine_count) + ( + "SCALE_ELASTIC_EP", + new_engine_count, + sorted(removed_ranks), + ) ) await socket.send(scale_msg) continue @@ -1296,6 +1345,12 @@ async def run_engine_stats_update_task(): async def add_request_async(self, request: EngineCoreRequest) -> None: self._ensure_stats_update_task() + # Lazily capture the event loop for the FT monitor thread. + if ( + getattr(self, "_ft_event_loop", "missing") is None + ): # subclass attribute exists and is None + self._ft_event_loop = asyncio.get_running_loop() + request.current_wave = self.current_wave request.client_index = self.client_index @@ -1347,7 +1402,219 @@ def __init__( len(self.core_engines) * self.client_index ) // client_count + # Fault tolerance state. + self._ft_scaling_in_progress = False + self._dead_engine_identities: set[EngineIdentity] = set() + self._initial_dp_size = len(self.core_engines) + self._ft_abort_callback: Callable[[list[str]], None] | None = None + # Capture the event loop for scheduling async scale-down from + # the monitor thread. May be None if __init__ runs outside an + # async context; updated lazily when add_request_async is called. + # `type: ignore` because the parent class re-narrows this attribute + # on its first non-None assignment in add_request_async; the + # declaration on DPAsyncMPClient widens it back to Optional but + # mypy has trouble seeing through the inheritance chain. + try: + self._ft_event_loop = asyncio.get_running_loop() + except RuntimeError: + self._ft_event_loop = None # type: ignore[assignment] + + # Client-side fault bus. The supervisor on each engine has its own + # bus for engine-internal faults; the client owns this one for + # engine-PROCESS deaths detected from outside (Ray actor failures, + # process exits). External subscribers connect via ZMQ SUB; the + # in-process DPRoutingPolicy subscribes via callback. + self._fault_bus = None + self._dp_routing_policy = None + if getattr(vllm_config.parallel_config, "enable_fault_tolerance", False): + # Touch plans so HTTP `apply` can resolve them. + import vllm.v1.fault_tolerance.plans # noqa: F401 + from vllm.v1.fault_tolerance.dp_routing_policy import DPRoutingPolicy + from vllm.v1.fault_tolerance.fault_state_bus import FaultStateBus + + self._fault_bus = FaultStateBus(vllm_config) + self._dp_routing_policy = DPRoutingPolicy( + self._fault_bus, total_engines=len(self.core_engines) + ) + + # ------------------------------------------------------------------ + # Fault-tolerant engine monitoring + # ------------------------------------------------------------------ + + def _is_fault_tolerant(self) -> bool: + pc = self.vllm_config.parallel_config + return pc.enable_ep_fault_tolerance + + def _on_engine_process_died(self, proc_name: str, dp_rank: int) -> bool: + """Handle a single DP engine death. + + Advisory only — publishes ``FaultInfo(DEAD)`` on the client-side + fault bus so external orchestrators (Dynamo, k8s controllers) and + the in-process ``DPRoutingPolicy`` can react. Returns True to keep + monitoring surviving engines. + + The redesign deliberately does **not** auto-trigger scale-down + here. Recovery decisions are policy and live in the orchestrator; + callers invoke ``POST /fault_tolerance/apply`` with + ``instruction="scale_down"`` (or ``"abort"``) to act on the death. + """ + # Deduplicate: Ray may report the same actor death multiple times. + dead_identity = dp_rank.to_bytes(2, "little") + if dead_identity in self._dead_engine_identities: + logger.warning( + "[Fault Tolerance] Engine %s (dp_rank=%d) death already " + "handled. Ignoring duplicate notification.", + proc_name, + dp_rank, + ) + return True + + # Track the dead rank so client-side routing can avoid it and so + # `_fail_inflight_requests_for_engine` can be invoked by the + # `abort` / `scale_down` plans. + self._dead_engine_identities.add(dead_identity) + + cur_dp_size = len(self.core_engines) + logger.warning( + "[Fault Tolerance] Engine %s (dp_rank=%d) died " + "(%d engines remain). Publishing FaultInfo(DEAD); orchestrator " + "should POST /fault_tolerance/apply to act.", + proc_name, + dp_rank, + cur_dp_size - 1, + ) + + if cur_dp_size <= 1: + # No survivors — orchestrator can't recover from this; bail. + logger.error( + "[Fault Tolerance] No surviving engines remain. Shutting down." + ) + self.resources.engine_dead = True + self.shutdown() + return False + + # Publish to the client-side fault bus (best-effort; bus may not + # be configured if the master FT switch is off). + bus = getattr(self, "_fault_bus", None) + if bus is not None: + from vllm.v1.fault_tolerance import FaultInfo, FaultStatus + + bus.publish( + FaultInfo( + engine_index=dp_rank, + status=FaultStatus.DEAD, + kind="engine_process_died", + detail=proc_name, + ) + ) + + return True + + async def _fault_triggered_scale_down(self, dead_dp_rank: int) -> None: + """Scale down after a DP engine process died unexpectedly. + + Args: + dead_dp_rank: The ORIGINAL dp_rank from the process name. + After previous scale-downs, this may differ from the + current list index in core_engines. + """ + try: + # Translate original dp_rank → current list index. + # After previous scale-downs with rank compaction, the + # original rank number may not match the list position. + dead_engine_identity = dead_dp_rank.to_bytes(2, "little") + try: + dead_index = self.core_engines.index(dead_engine_identity) + except ValueError: + logger.warning( + "[Fault Tolerance] Engine dp_rank=%d (identity=%s) " + "not found in core_engines. Already removed?", + dead_dp_rank, + dead_engine_identity, + ) + return + + cur_dp_size = len(self.core_engines) + new_dp_size = cur_dp_size - 1 + + logger.info( + "[Fault Tolerance] Starting fault-triggered scale-down: " + "original_dp_rank=%d, current_index=%d, %d -> %d engines.", + dead_dp_rank, + dead_index, + cur_dp_size, + new_dp_size, + ) + + dead_req_ids = self._fail_inflight_requests_for_engine(dead_engine_identity) + if dead_req_ids and self._ft_abort_callback is not None: + self._ft_abort_callback(dead_req_ids) + + await self._scale_down_elastic_ep( + cur_dp_size, + new_dp_size, + dead_dp_ranks={dead_index}, + ) + + logger.info( + "[Fault Tolerance] Fault-triggered scale-down complete. " + "Now running with %d engines.", + new_dp_size, + ) + except Exception: + logger.exception( + "[Fault Tolerance] Fault-triggered scale-down failed. Shutting down." + ) + self.resources.engine_dead = True + self.shutdown() + finally: + self._ft_scaling_in_progress = False + self._dead_engine_identities.clear() + + def _fail_inflight_requests_for_engine( + self, dead_engine: EngineIdentity + ) -> list[str]: + """Remove in-flight requests that were assigned to a dead engine. + + Returns the list of dropped request IDs so callers can propagate + errors to waiting clients (e.g. via OutputProcessor.abort_requests). + """ + dead_req_ids = [ + req_id + for req_id, engine in self.reqs_in_flight.items() + if engine == dead_engine + ] + for req_id in dead_req_ids: + self.reqs_in_flight.pop(req_id, None) + if dead_req_ids: + logger.warning( + "[Fault Tolerance] Dropped %d in-flight requests that " + "were assigned to the dead engine.", + len(dead_req_ids), + ) + return dead_req_ids + + def register_ft_abort_callback(self, callback: Callable[[list[str]], None]) -> None: + """Register a callback to abort requests when an engine dies. + + AsyncLLM sets this so that dead-engine requests go through the + proper OutputProcessor.abort_requests() path (LoRA cleanup, + pooling handling, parent/child tracking) rather than pushing + synthetic EngineCoreOutput objects through the inference pipeline. + """ + self._ft_abort_callback = callback + def get_core_engine_for_request(self, request: EngineCoreRequest) -> EngineIdentity: + # Routing eligibility comes from two sources: + # - `_dead_engine_identities`: client-detected process deaths (set + # immediately by `_on_engine_process_died`, before the bus has + # propagated). + # - `_dp_routing_policy.eligible_engines()`: bus-driven view that + # also covers PAUSED, UNHEALTHY, RECOVERING. None when FT is off. + eligible: frozenset[int] | None = None + if self._dp_routing_policy is not None: + eligible = self._dp_routing_policy.eligible_engines() + # Engines are in rank order. if (eng_index := request.data_parallel_rank) is None and ( eng_index := get_late_interaction_engine_index( @@ -1355,6 +1622,7 @@ def get_core_engine_for_request(self, request: EngineCoreRequest) -> EngineIdent ) ) is None: current_counts = self.lb_engines + dead = self._dead_engine_identities # TODO use P2C alg for larger DP sizes num_engines = len(current_counts) min_score = sys.maxsize @@ -1363,6 +1631,11 @@ def get_core_engine_for_request(self, request: EngineCoreRequest) -> EngineIdent # Start from client_index to help with balancing when engines # are empty. idx = (self.eng_start_index + i) % num_engines + if dead and self.core_engines[idx] in dead: + continue + if eligible is not None and idx not in eligible: + # PAUSED / UNHEALTHY / RECOVERING per the bus. + continue waiting, running = current_counts[idx] score = waiting * 4 + running if score < min_score: @@ -1373,6 +1646,20 @@ def get_core_engine_for_request(self, request: EngineCoreRequest) -> EngineIdent current_counts[eng_index][0] += self.client_count chosen_engine = self.core_engines[eng_index] + if ( + self._dead_engine_identities + and chosen_engine in self._dead_engine_identities + ): + raise ValueError( + f"Request targets DP rank {eng_index} which is dead. " + "Retry without specifying data_parallel_rank." + ) + if eligible is not None and eng_index not in eligible: + raise ValueError( + f"Request targets DP rank {eng_index} which is not eligible " + "(paused, unhealthy, or recovering). " + "Retry without specifying data_parallel_rank." + ) # Record which engine is chosen for this request, to handle aborts. self.reqs_in_flight[request.request_id] = chosen_engine return chosen_engine @@ -1388,6 +1675,100 @@ async def call_utility_async(self, method: str, *args) -> Any: ) )[0] + # ------------------------------------------------------------------ + # Fault tolerance API surface (called by the HTTP router under + # ``/fault_tolerance/*``). See vllm.v1.fault_tolerance for the + # framework, vllm.entrypoints.serve.fault_tolerance for the routes. + # ------------------------------------------------------------------ + + async def apply_fault_instruction(self, ft_request: Any) -> Any: + """Dispatch a recovery instruction. + + Cluster-scope plans (``scale_down``, ``abort``) execute here on + the client's event loop because they need access to the + ``CoreEngineActorManager`` and in-flight request map. Engine-local + plans (``pause``, ``retry``, ``abort_communicator``) are + round-tripped to the engine via the existing utility-async path. + """ + from vllm.v1.fault_tolerance import ( + ClusterRecoveryPlan, + FaultToleranceResult, + get_plan, + ) + from vllm.v1.fault_tolerance.cluster import get_cluster_coordinator + + try: + plan = get_plan(ft_request.instruction) + except KeyError as e: + return FaultToleranceResult( + success=False, + reason=str(e), + request_id=getattr(ft_request, "request_id", None), + ) + if not plan.is_applicable(self.vllm_config): + return FaultToleranceResult( + success=False, + reason=( + f"Plan '{ft_request.instruction}' is not applicable to " + "this vllm_config." + ), + request_id=getattr(ft_request, "request_id", None), + ) + + if isinstance(plan, ClusterRecoveryPlan): + coord = get_cluster_coordinator(self) + if coord is None: + return FaultToleranceResult( + success=False, + reason=( + "No ClusterCoordinator available; cluster-scope plans " + "require a multi-engine deployment." + ), + request_id=getattr(ft_request, "request_id", None), + ) + # Plan execute is sync; run it off the event loop so we don't + # block other client coroutines while scale_down churns. + return await asyncio.get_running_loop().run_in_executor( + None, plan.execute, coord, ft_request.params or {} + ) + + # Engine-local plan: forward to the engine via collective utility. + return await self.call_utility_async("fault_supervisor_apply", ft_request) + + async def get_fault_status(self) -> dict[int, str]: + """Return per-engine status as ``{engine_index: status_lower}``.""" + try: + results = await asyncio.gather( + *[ + self._call_utility_async("fault_supervisor_status", engine=engine) + for engine in self.core_engines + ] + ) + except Exception as e: + logger.warning("get_fault_status failed: %s", e) + return {} + merged: dict[int, str] = {} + for r in results: + if isinstance(r, dict): + merged.update(r) + # Mark deaths the client has observed — those engines won't reply to + # the utility call but the client knows they're DEAD. + for ident in self._dead_engine_identities: + idx = int.from_bytes(ident, "little") + merged[idx] = "dead" + return merged + + def publish_fault_event(self, info: Any) -> None: + """Publish a FaultInfo to the client-side bus. + + Called by `_on_engine_process_died` after process death is + detected. External orchestrators (Dynamo, etc.) receive this via + ZMQ SUB; the in-process DPRoutingPolicy receives it via callback. + """ + if self._fault_bus is None: + return + self._fault_bus.publish(info) + @staticmethod async def process_engine_outputs( self: "DPLBAsyncMPClient", outputs: EngineCoreOutputs @@ -1436,8 +1817,15 @@ async def eep_process_engine_core_notification( assert cache.num_new_core_engines < 0 old_dp_size = len(cache.existing_core_engines) new_dp_size = old_dp_size + cache.num_new_core_engines + # Collect the ranks that were removed (dead or gracefully + # shut down) so the actor manager removes the right entries. + removed_ranks = cache.pending_notifications.get( + notification_type, set() + ) self.resources.engine_manager.scale_down_elastic_ep( - old_dp_size, new_dp_size + old_dp_size, + new_dp_size, + removed_dp_ranks=removed_ranks, ) else: await asyncio.gather( @@ -1633,10 +2021,22 @@ async def _scale_up_elastic_ep( ) async def _scale_down_elastic_ep( - self, cur_data_parallel_size: int, new_data_parallel_size: int + self, + cur_data_parallel_size: int, + new_data_parallel_size: int, + dead_dp_ranks: set[int] | None = None, ) -> None: """Scale down the data parallel size by shutting down and - reconfiguring existing engine cores.""" + reconfiguring existing engine cores. + + Args: + dead_dp_ranks: DP ranks that are already dead (fault-triggered). + Reconfigure messages are skipped for these ranks, and the + elastic EP state machine on surviving ranks will use + fault-tolerant barriers that don't wait for them. + """ + if dead_dp_ranks is None: + dead_dp_ranks = set() cur_data_parallel_size = len(self.core_engines) self.eep_scaling_cache = ElasticScalingCache( @@ -1648,11 +2048,38 @@ async def _scale_down_elastic_ep( parallel_config = self.vllm_config.parallel_config ip, coord_store_port = self._setup_elastic_ep_reconfig_bootstrap() - removed_dp_size = cur_data_parallel_size - new_data_parallel_size + # For graceful scale-down, the highest-ranked engines are removed. + # For fault-triggered scale-down, the dead engines are removed. + if dead_dp_ranks: + ranks_to_remove = dead_dp_ranks + else: + ranks_to_remove = set(range(new_data_parallel_size, cur_data_parallel_size)) + + # Compute rank compaction: surviving ranks get new contiguous IDs. + surviving_ranks = [ + r for r in range(cur_data_parallel_size) if r not in ranks_to_remove + ] + new_rank_map = {old: new for new, old in enumerate(surviving_ranks)} + assert isinstance(self.resources.engine_manager, CoreEngineActorManager) - self.resources.engine_manager.remove_run_refs_for_scale_down(removed_dp_size) + + # Count how many removed engines are local BEFORE lists are modified. + mgr = self.resources.engine_manager + self._local_engines_removed = sum( + 1 + for r in ranks_to_remove + if r < len(mgr.placement_group_is_local) and mgr.placement_group_is_local[r] + ) + + mgr.remove_run_refs_for_scale_down( + len(ranks_to_remove), + ranks_to_remove=ranks_to_remove, + ) reconfig_futures = [] for cur_dp_rank, engine in enumerate(self.core_engines): + if cur_dp_rank in dead_dp_ranks: + continue + reconfig_request = ReconfigureDistributedRequest( new_data_parallel_size=new_data_parallel_size, new_data_parallel_rank=ReconfigureRankType.KEEP_CURRENT_RANK, @@ -1661,35 +2088,83 @@ async def _scale_down_elastic_ep( new_data_parallel_master_port=parallel_config.data_parallel_master_port, new_data_parallel_master_port_list=parallel_config._data_parallel_master_port_list, coord_store_port=coord_store_port, + dead_dp_ranks=list(dead_dp_ranks), ) - if cur_dp_rank >= new_data_parallel_size: + if cur_dp_rank in ranks_to_remove: reconfig_request.new_data_parallel_rank = ( ReconfigureRankType.SHUTDOWN_CURRENT_RANK ) + elif dead_dp_ranks: + # Fault-triggered: assign compacted rank so surviving + # engines form a contiguous group 0..N-1. + reconfig_request.new_data_parallel_rank = new_rank_map[cur_dp_rank] coro = self._call_utility_async( "reinitialize_distributed", reconfig_request, engine=engine ) reconfig_futures.append(asyncio.create_task(coro)) - # NOTE(yongji): Immediately stop sending requests to the removing engines. - self.core_engines = self.core_engines[:new_data_parallel_size] - self.lb_engines = self.lb_engines[:new_data_parallel_size] + # Immediately stop sending requests to the removed engines. + # Look up actual identities from current core_engines list + # (indices may differ from original rank numbers after previous + # scale-downs). + dead_identities = { + self.core_engines[i] for i in ranks_to_remove if i < len(self.core_engines) + } + self.core_engines = [e for e in self.core_engines if e not in dead_identities] + self.lb_engines = [ + lb for i, lb in enumerate(self.lb_engines) if i not in ranks_to_remove + ] wait_future = self._eep_wait_for_setup_switch_complete() await asyncio.gather(*reconfig_futures) + if dead_dp_ranks: + # The dead engines can't send SHUTDOWN_COMPLETE, so we + # simulate it to unblock the notification handling. + self._synthesize_shutdown_complete_for_dead_ranks(dead_dp_ranks) + self.vllm_config.parallel_config.data_parallel_size = new_data_parallel_size + local_removed = getattr(self, "_local_engines_removed", 0) + if local_removed > 0: + self.vllm_config.parallel_config.data_parallel_size_local -= local_removed self._ensure_stats_update_task() scale_down_marker = msgspec.msgpack.encode( - ("SCALE_ELASTIC_EP", new_data_parallel_size) + ("SCALE_ELASTIC_EP", new_data_parallel_size, sorted(ranks_to_remove)) ) await self.first_req_send_socket.send(scale_down_marker) - # NOTE(yongji): Unlike scaling up, - # here we don't actually need to wait for the setup switch to complete. - # We may want to remove it in the future. await wait_future logger.info( "[Elastic EP] Scale down completed, new data parallel size: %s", new_data_parallel_size, ) + + def _synthesize_shutdown_complete_for_dead_ranks( + self, dead_dp_ranks: set[int] + ) -> None: + """Inject synthetic SHUTDOWN_COMPLETE notifications for dead ranks + so the notification handler doesn't wait forever.""" + cache = self.eep_scaling_cache + if cache is None: + return + + notification_type = EEPNotificationType.SHUTDOWN_COMPLETE + if notification_type not in cache.pending_notifications: + cache.pending_notifications[notification_type] = set() + for dp_rank in dead_dp_ranks: + cache.pending_notifications[notification_type].add(dp_rank) + + if len(cache.pending_notifications[notification_type]) >= abs( + cache.num_new_core_engines + ): + assert isinstance(self.resources.engine_manager, CoreEngineActorManager) + old_dp_size = len(cache.existing_core_engines) + new_dp_size = old_dp_size + cache.num_new_core_engines + removed_ranks = cache.pending_notifications.get(notification_type, set()) + self.resources.engine_manager.scale_down_elastic_ep( + old_dp_size, + new_dp_size, + removed_dp_ranks=removed_ranks, + ) + cache.pending_notifications[notification_type] = set() + self.eep_scaling_cache = None diff --git a/vllm/v1/engine/utils.py b/vllm/v1/engine/utils.py index 7b0f00d14c8a..02ba2b86ab80 100644 --- a/vllm/v1/engine/utils.py +++ b/vllm/v1/engine/utils.py @@ -218,6 +218,44 @@ def monitor_engine_liveness(self) -> None: self.shutdown() + def monitor_engine_liveness_fault_tolerant( + self, + on_engine_died: Callable[[str, int], bool], + ) -> None: + """Monitor engine liveness, reporting individual failures. + + Args: + on_engine_died: Called with (proc_name, dp_rank) when a process + dies unexpectedly. Return True to continue monitoring + surviving engines, False to stop. + """ + sentinel_to_proc = {proc.sentinel: proc for proc in self.processes} + sentinels = set(sentinel_to_proc.keys()) + + while sentinels and not self.manager_stopped.is_set(): + died_sentinels = connection.wait(sentinels, timeout=1) + + for sentinel in died_sentinels: + sentinels.discard(cast(int, sentinel)) + proc = sentinel_to_proc.pop(cast(int, sentinel)) + exitcode = proc.exitcode or 0 + if exitcode != 0 and not self.manager_stopped.is_set(): + self.failed_proc_name = proc.name + dp_rank = self._dp_rank_from_proc_name(proc.name) + should_continue = on_engine_died(proc.name, dp_rank) + if not should_continue: + self.shutdown() + return + + self.shutdown() + + @staticmethod + def _dp_rank_from_proc_name(name: str) -> int: + prefix = "EngineCore_DP" + if name.startswith(prefix): + return int(name[len(prefix) :]) + return -1 + def sentinels(self) -> list: return [proc.sentinel for proc in self.processes] @@ -455,10 +493,13 @@ def __init__( ray.get(refs) self.run_refs = [] self.actor_run_ref_dict = dict() - for actor in self.local_engine_actors + self.remote_engine_actors: + self.run_ref_to_dp_rank: dict = {} + all_actors = self.local_engine_actors + self.remote_engine_actors + for dp_rank_idx, actor in enumerate(all_actors): ref = actor.run.remote() self.run_refs.append(ref) self.actor_run_ref_dict[actor] = ref + self.run_ref_to_dp_rank[ref] = dp_rank_idx @staticmethod def create_dp_placement_groups( @@ -860,9 +901,27 @@ def scale_up_elastic_ep( new_local_engines ) + def _actor_at_rank(self, dp_rank: int): + """Return the actor at the given DP rank.""" + is_local = self.placement_group_is_local[dp_rank] + if is_local: + local_idx = sum( + 1 for i in range(dp_rank) if self.placement_group_is_local[i] + ) + return self.local_engine_actors[local_idx] + else: + remote_idx = sum( + 1 for i in range(dp_rank) if not self.placement_group_is_local[i] + ) + return self.remote_engine_actors[remote_idx] + def scale_down_elastic_ep( - self, cur_data_parallel_size: int, new_data_parallel_size: int - ) -> None: + self, + cur_data_parallel_size: int, + new_data_parallel_size: int, + removed_dp_ranks: set[int] | None = None, + ) -> int: + """Remove engines for scale-down. Returns count of local engines removed.""" import ray assert cur_data_parallel_size > new_data_parallel_size, ( @@ -870,30 +929,61 @@ def scale_down_elastic_ep( f"than new_data_parallel_size {new_data_parallel_size} " "for scale down" ) - for _ in range(cur_data_parallel_size - new_data_parallel_size): - pg = self.created_placement_groups.pop() - is_local = self.placement_group_is_local.pop() + if removed_dp_ranks is None: + removed_dp_ranks = set( + range(new_data_parallel_size, cur_data_parallel_size) + ) + + local_removed = 0 + # Remove in reverse order so indices remain valid. + for rank in sorted(removed_dp_ranks, reverse=True): + pg = self.created_placement_groups.pop(rank) + is_local = self.placement_group_is_local.pop(rank) if is_local: - self.local_engine_actors.pop() + local_removed += 1 + local_idx = sum( + 1 for i in range(rank) if self.placement_group_is_local[i] + ) + self.local_engine_actors.pop(local_idx) else: - self.remote_engine_actors.pop() + remote_idx = sum( + 1 for i in range(rank) if not self.placement_group_is_local[i] + ) + self.remote_engine_actors.pop(remote_idx) ray.util.remove_placement_group(pg) + return local_removed - def remove_run_refs_for_scale_down(self, removed_dp_size: int) -> None: + def remove_run_refs_for_scale_down( + self, + removed_dp_size: int, + ranks_to_remove: set[int] | None = None, + ) -> None: if removed_dp_size <= 0: return - flags = self.placement_group_is_local[-removed_dp_size:] - li = len(self.local_engine_actors) - 1 - ri = len(self.remote_engine_actors) - 1 - for is_local in reversed(flags): - if is_local: - actor = self.local_engine_actors[li] - li -= 1 - else: - actor = self.remote_engine_actors[ri] - ri -= 1 - ref = self.actor_run_ref_dict.pop(actor) - self.run_refs.remove(ref) + + if ranks_to_remove is None: + # Default: remove from the end (graceful scale-down). + flags = self.placement_group_is_local[-removed_dp_size:] + li = len(self.local_engine_actors) - 1 + ri = len(self.remote_engine_actors) - 1 + for is_local in reversed(flags): + if is_local: + actor = self.local_engine_actors[li] + li -= 1 + else: + actor = self.remote_engine_actors[ri] + ri -= 1 + ref = self.actor_run_ref_dict.pop(actor) + self.run_refs.remove(ref) + self.run_ref_to_dp_rank.pop(ref, None) + else: + # Fault-triggered: remove specific ranks. + for rank in sorted(ranks_to_remove, reverse=True): + actor = self._actor_at_rank(rank) + ref = self.actor_run_ref_dict.pop(actor, None) + if ref is not None: + self.run_refs.remove(ref) + self.run_ref_to_dp_rank.pop(ref, None) def get_run_refs(self): return self.run_refs @@ -928,6 +1018,46 @@ def monitor_engine_liveness(self) -> None: self.shutdown() + def monitor_engine_liveness_fault_tolerant( + self, + on_engine_died: Callable[[str, int], bool], + ) -> None: + """Monitor engine liveness, reporting individual failures. + + Args: + on_engine_died: Called with (actor_name, dp_rank) when an actor + dies unexpectedly. Return True to continue monitoring + surviving engines, False to stop. + """ + import ray + + while not self.manager_stopped.is_set(): + actor_run_refs = list(self.get_run_refs()) + if not actor_run_refs: + logger.info( + "There are no actors to monitor currently. " + "The monitoring function is about to terminate." + ) + break + actor_done_refs, _ = ray.wait(actor_run_refs, timeout=5) + for actor_ref in actor_done_refs: + if self.manager_stopped.is_set(): + break + if actor_ref not in self.get_run_refs(): + continue + try: + ray.get(actor_ref) + except ray.exceptions.RayActorError: + actor_name = f"Actor {actor_ref}" + self.failed_proc_name = actor_name + dp_rank = self.run_ref_to_dp_rank.get(actor_ref, -1) + should_continue = on_engine_died(actor_name, dp_rank) + if not should_continue: + self.shutdown() + return + + self.shutdown() + def shutdown(self, timeout: float | None = None) -> None: import ray diff --git a/vllm/v1/fault_tolerance/__init__.py b/vllm/v1/fault_tolerance/__init__.py new file mode 100644 index 000000000000..7a0e70ae1e19 --- /dev/null +++ b/vllm/v1/fault_tolerance/__init__.py @@ -0,0 +1,66 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""vLLM fault tolerance framework. + +The public surface intentionally mirrors `register_model_loader` so +orchestrators (Dynamo, k8s controllers, custom platforms) can extend FT +without forking vLLM. Three things are exposed: + +1. `FaultToleranceHooks` (Protocol) — what `EngineCoreProc.run_busy_loop` + calls on every iteration. Default is `NoOpFaultHooks` when FT is off. +2. `register_fault_supervisor(name)` — register a hooks implementation. +3. `register_recovery_plan(instruction)` — register a plan for one + `/fault_tolerance/apply` instruction. + +See `vllm/v1/fault_tolerance/types.py` for the full type surface. +""" + +from vllm.v1.fault_tolerance.registry import ( + get_fault_hooks, + get_plan, + get_supervisor_class, + list_plans, + register_fault_supervisor, + register_recovery_plan, +) +from vllm.v1.fault_tolerance.types import ( + GLOBAL_NOOP_HOOKS, + BaseRecoveryPlan, + ClusterRecoveryPlan, + Disposition, + EngineLocalRecoveryPlan, + FaultInfo, + FaultSignal, + FaultStatus, + FaultToleranceHooks, + FaultToleranceRequest, + FaultToleranceResult, + InterruptCommand, + KvAction, + NoOpFaultHooks, +) + +__all__ = [ + # Types + "BaseRecoveryPlan", + "ClusterRecoveryPlan", + "Disposition", + "EngineLocalRecoveryPlan", + "FaultInfo", + "FaultSignal", + "FaultStatus", + "FaultToleranceHooks", + "FaultToleranceRequest", + "FaultToleranceResult", + "GLOBAL_NOOP_HOOKS", + "InterruptCommand", + "KvAction", + "NoOpFaultHooks", + # Registry + "get_fault_hooks", + "get_plan", + "get_supervisor_class", + "list_plans", + "register_fault_supervisor", + "register_recovery_plan", +] diff --git a/vllm/v1/fault_tolerance/cluster.py b/vllm/v1/fault_tolerance/cluster.py new file mode 100644 index 000000000000..8b0f2c53e669 --- /dev/null +++ b/vllm/v1/fault_tolerance/cluster.py @@ -0,0 +1,128 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""ClusterCoordinator — protocol over the multi-engine manager. + +Wraps whatever multi-engine manager the deployment uses (Ray actor manager +or the multiprocessing equivalent) so cluster-scope recovery plans can be +written backend-agnostically. + +Cluster-scope plans (``scale_down``, ``abort``, future ``scale_up``) call +methods on this protocol rather than reaching into Ray-specific code. +""" + +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable + +from vllm.logger import init_logger + +if TYPE_CHECKING: + from vllm.v1.engine.core_client import MPClient + +logger = init_logger(__name__) + + +@runtime_checkable +class ClusterCoordinator(Protocol): + """Protocol over the multi-engine manager.""" + + def alive_engine_indices(self) -> list[int]: + """Engine indices currently considered alive.""" + ... + + def scale_down(self, dead_index: int) -> None: + """Drop ``dead_index`` from the topology and rebuild communicators.""" + ... + + def abort_inflight_on(self, dead_index: int) -> int: + """Fail every in-flight request assigned to ``dead_index``. + + Returns the number of requests aborted (or ``-1`` if the count is + unavailable). + """ + ... + + +class RayClusterCoordinator: + """Coordinator backed by an ``MPClient`` running on Ray DP backend. + + Delegates to existing helpers on the client so we don't re-implement + elastic EP — we just expose them through the supervisor-friendly + protocol. + """ + + def __init__(self, client: MPClient): + self._client = client + + def alive_engine_indices(self) -> list[int]: + # The client tracks live engines via core_engines (ordered by current + # list index, not original dp_rank). Translate to ints. + return list(range(len(self._client.core_engines))) + + def scale_down(self, dead_index: int) -> None: + """Run the existing fault-triggered scale-down on the client's loop. + + The client already has ``_fault_triggered_scale_down`` (an async + method that orchestrates fail-inflight + scale_down_elastic_ep). + We schedule it on the client's event loop and wait for it. + """ + fn = getattr(self._client, "_fault_triggered_scale_down", None) + if fn is None: + raise RuntimeError( + "client does not expose _fault_triggered_scale_down; the " + "deployment is not configured for fault-tolerant scale-down." + ) + + loop = getattr(self._client, "_ft_event_loop", None) + if loop is None or loop.is_closed(): + raise RuntimeError("client's _ft_event_loop is unavailable") + + # Schedule on the client's loop and block until the coroutine is done. + future = asyncio.run_coroutine_threadsafe(fn(dead_index), loop) + future.result() + + def abort_inflight_on(self, dead_index: int) -> int: + """Fail in-flight requests assigned to engine ``dead_index``. + + Resolves dp_rank → engine identity, then calls the existing + ``_fail_inflight_requests_for_engine`` helper. Returns the count + of dropped request IDs. + """ + fail_fn = getattr(self._client, "_fail_inflight_requests_for_engine", None) + if fail_fn is None: + logger.warning( + "client does not expose _fail_inflight_requests_for_engine; " + "abort cannot reach in-flight requests." + ) + return -1 + + # The client uses a 2-byte little-endian identity for engines. + engine_identity = dead_index.to_bytes(2, "little") + dead_req_ids = fail_fn(engine_identity) + count = len(dead_req_ids) if dead_req_ids else 0 + + # If a higher-level abort callback is registered, propagate so the + # OutputProcessor sends FinishReason.ABORT to clients (LoRA cleanup, + # pooling handling, etc.). See `register_ft_abort_callback`. + cb = getattr(self._client, "_ft_abort_callback", None) + if cb is not None and dead_req_ids: + try: + cb(dead_req_ids) + except Exception as e: + logger.warning("ft_abort_callback raised: %s", e) + + return count + + +def get_cluster_coordinator(client: Any) -> ClusterCoordinator | None: + """Resolve a coordinator from an engine client. + + Returns ``None`` if the client isn't an MPClient with the elastic-EP + helpers, in which case cluster-scope plans aren't applicable. + """ + if client is None: + return None + if not hasattr(client, "_fault_triggered_scale_down"): + return None + return RayClusterCoordinator(client) diff --git a/vllm/v1/fault_tolerance/default_supervisor.py b/vllm/v1/fault_tolerance/default_supervisor.py new file mode 100644 index 000000000000..96dae7f347df --- /dev/null +++ b/vllm/v1/fault_tolerance/default_supervisor.py @@ -0,0 +1,270 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DefaultFaultSupervisor — the supervisor vLLM ships out of the box. + +One instance per engine process. Owns: + +* the per-engine FaultStatus state machine, +* a non-blocking publish path (queue + daemon thread → FaultStateBus), +* a small interrupt PUB socket scoped to operations that genuinely need an + aux thread (e.g., `ncclCommAbort` on a stuck worker — see §9.4 / §9.11 + of the architecture doc), +* dispatch from `/fault_tolerance/apply` to registered RecoveryPlans. + +The supervisor is registered by name (``"default"``) so orchestrators can +override it with their own implementation via ``@register_fault_supervisor``. +""" + +from __future__ import annotations + +import queue +import threading +from contextlib import suppress +from typing import TYPE_CHECKING, Any + +import zmq + +from vllm.logger import init_logger +from vllm.utils.network_utils import make_zmq_socket +from vllm.v1.fault_tolerance.errors import FaultToleranceError +from vllm.v1.fault_tolerance.fault_state_bus import FaultStateBus +from vllm.v1.fault_tolerance.registry import ( + get_plan, + register_fault_supervisor, +) +from vllm.v1.fault_tolerance.types import ( + Disposition, + EngineLocalRecoveryPlan, + FaultInfo, + FaultStatus, + FaultToleranceHooks, + FaultToleranceRequest, + FaultToleranceResult, + InterruptCommand, +) + +if TYPE_CHECKING: + from vllm.config import VllmConfig + from vllm.v1.outputs import ModelRunnerOutput + +logger = init_logger(__name__) + + +_PUBLISH_QUEUE_MAX = 1024 +_PUBLISH_LOOP_TIMEOUT_SEC = 1.0 + + +@register_fault_supervisor("default") +class DefaultFaultSupervisor(FaultToleranceHooks): + """Reference supervisor implementation.""" + + def __init__(self, vllm_config: VllmConfig, engine: Any | None = None): + self.vllm_config = vllm_config + self.engine = engine + self.engine_index = engine.engine_index if engine is not None else 0 + + self.bus = FaultStateBus(vllm_config) + + self._state: FaultStatus = FaultStatus.HEALTHY + self._engine_status: dict[int, FaultStatus] = {self.engine_index: self._state} + self._state_lock = threading.Lock() + self._pause_cv = threading.Condition(self._state_lock) + + self._queue: queue.Queue[FaultInfo] = queue.Queue(maxsize=_PUBLISH_QUEUE_MAX) + self._shutdown = False + self._publish_thread = threading.Thread( + target=self._publish_loop, + daemon=True, + name=f"DefaultFaultSupervisorPublishThread_{self.engine_index}", + ) + self._publish_thread.start() + + # Small interrupt PUB socket (§9.4 / §9.11). Used ONLY for operations + # that need an aux thread on the worker side (e.g. + # ncclCommAbort). Common pause / retry actions go via + # `executor.collective_rpc` and don't touch this socket. + self._interrupt_pub = self._init_interrupt_pub() + + def _init_interrupt_pub(self): + # `fault_tolerance_config` may not exist on configs predating #34833. + ft_cfg = getattr(self.vllm_config, "fault_tolerance_config", None) + addr = getattr(ft_cfg, "interrupt_addr", None) if ft_cfg else None + if addr is None: + return None + try: + return make_zmq_socket( + ctx=zmq.Context.instance(), + path=addr, + socket_type=zmq.PUB, + bind=True, + ) + except Exception as e: + logger.warning("Failed to bind interrupt PUB at %s: %s", addr, e) + return None + + # ---- engine-thread hooks (must not block) ------------------------------ + + def before_step(self, engine: Any) -> None: + with self._state_lock: + while self._state is FaultStatus.PAUSED and not self._shutdown: + self._pause_cv.wait() + + def after_step(self, engine: Any, output: ModelRunnerOutput | None) -> None: + if output is None or output.fault_signal is None: + return + info = FaultInfo.from_signal(self.engine_index, output.fault_signal) + self._set_status(info.status) + self._enqueue(info) + + def on_step_error(self, engine: Any, exc: BaseException) -> Disposition: + # Typed FT exceptions carry a structured signal; fall back to + # FaultInfo.from_exception for everything else. + if isinstance(exc, FaultToleranceError) and exc.signal is not None: + info = FaultInfo.from_signal(self.engine_index, exc.signal) + else: + info = FaultInfo.from_exception(self.engine_index, exc) + self._set_status(info.status) + self._enqueue(info) + # Default policy: pause and let the orchestrator decide what to do. + # Orchestrators that want propagate-on-first-error can register a + # different supervisor. + return Disposition.PAUSE_LOOP + + # ---- public surface for HTTP / engine ---------------------------------- + + def apply(self, ft_request: FaultToleranceRequest) -> FaultToleranceResult: + """Dispatch an instruction to its registered plan.""" + try: + plan = get_plan(ft_request.instruction) + except KeyError as e: + return FaultToleranceResult( + success=False, reason=str(e), request_id=ft_request.request_id + ) + if not plan.is_applicable(self.vllm_config): + return FaultToleranceResult( + success=False, + reason=( + f"Plan '{ft_request.instruction}' is not applicable " + "to this vllm_config." + ), + request_id=ft_request.request_id, + ) + + if isinstance(plan, EngineLocalRecoveryPlan): + if self.engine is None: + return FaultToleranceResult( + success=False, + reason="No engine attached to supervisor; cannot run plan.", + request_id=ft_request.request_id, + ) + try: + result = plan.execute(self.engine.executor, ft_request.params) + except Exception as e: + logger.exception("Plan %s failed: %s", ft_request.instruction, e) + return FaultToleranceResult( + success=False, + reason=f"plan raised: {e}", + request_id=ft_request.request_id, + ) + if result.request_id is None: + result.request_id = ft_request.request_id + return result + + # Cluster plans are not dispatched per-engine; the API layer routes + # them through the ClusterCoordinator instead. + return FaultToleranceResult( + success=False, + reason=( + f"Plan '{ft_request.instruction}' is a ClusterRecoveryPlan; " + "must be dispatched at the API layer with a ClusterCoordinator." + ), + request_id=ft_request.request_id, + ) + + def get_status(self) -> dict[int, FaultStatus]: + with self._state_lock: + return dict(self._engine_status) + + def run_retry_plan(self, engine: Any) -> FaultToleranceResult: + self._set_status(FaultStatus.RECOVERING) + result = self.apply(FaultToleranceRequest(instruction="retry", params={})) + if result.success: + self.resume() + return result + + def resume(self) -> None: + """Move from PAUSED/RECOVERING back to HEALTHY and wake before_step.""" + with self._state_lock: + self._state = FaultStatus.HEALTHY + self._engine_status[self.engine_index] = FaultStatus.HEALTHY + self._pause_cv.notify_all() + self._enqueue( + FaultInfo(engine_index=self.engine_index, status=FaultStatus.HEALTHY) + ) + + def wait_until_resumed(self) -> None: + with self._state_lock: + while self._state is FaultStatus.PAUSED and not self._shutdown: + self._pause_cv.wait() + + def send_interrupt(self, target: int | str, command: InterruptCommand) -> None: + """Fire a one-way interrupt to a worker's aux thread (§9.11). + + ``target`` is either a worker local rank or the literal string ``"all"``. + ``command`` is one of the typed ``InterruptCommand`` values the + worker's `_ft_interrupt_loop` understands. + """ + if self._interrupt_pub is None: + logger.warning( + "send_interrupt called but interrupt PUB socket is not bound" + ) + return + topic = f"worker_{target}" if target != "all" else "all" + try: + self._interrupt_pub.send_multipart( + [topic.encode("utf-8"), command.value.encode("utf-8")] + ) + except Exception as e: + logger.warning("send_interrupt failed: %s", e) + + # ---- internal ---------------------------------------------------------- + + def _set_status(self, status: FaultStatus) -> None: + with self._state_lock: + self._state = status + self._engine_status[self.engine_index] = status + + def _enqueue(self, info: FaultInfo) -> None: + try: + self._queue.put_nowait(info) + except queue.Full: + logger.warning( + "fault publish queue full; dropping %s for engine %d", + info.kind or info.status.name, + info.engine_index, + ) + + def _publish_loop(self) -> None: + while not self._shutdown: + try: + info = self._queue.get(timeout=_PUBLISH_LOOP_TIMEOUT_SEC) + except queue.Empty: + # Natural extension point for a future heartbeat / liveness + # probe (see vLLM FT design §10.2 Mode B). + continue + try: + self.bus.publish(info) + except Exception as e: + logger.warning("Bus publish failed: %s", e) + + def shutdown(self) -> None: + self._shutdown = True + with self._state_lock: + self._pause_cv.notify_all() + with suppress(Exception): + self._publish_thread.join(timeout=2.0) + self.bus.close() + if self._interrupt_pub is not None: + with suppress(Exception): + self._interrupt_pub.close(linger=0) + self._interrupt_pub = None diff --git a/vllm/v1/fault_tolerance/dp_routing_policy.py b/vllm/v1/fault_tolerance/dp_routing_policy.py new file mode 100644 index 000000000000..73c69fb89a50 --- /dev/null +++ b/vllm/v1/fault_tolerance/dp_routing_policy.py @@ -0,0 +1,75 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""DP routing policy — derives an "eligible engines" set from the fault bus. + +Used by the load-balancing client (`DPLBAsyncMPClient`) to steer requests +away from engines that are PAUSED, UNHEALTHY, RECOVERING or DEAD. Today's +existing PRs only avoid DEAD engines (#38862's `_dead_engine_identities`); +this generalizes that to all non-HEALTHY states by subscribing to the bus. +""" + +from __future__ import annotations + +import threading +from contextlib import suppress +from typing import TYPE_CHECKING + +from vllm.logger import init_logger +from vllm.v1.fault_tolerance.types import FaultInfo, FaultStatus + +if TYPE_CHECKING: + from vllm.v1.fault_tolerance.fault_state_bus import FaultStateBus + +logger = init_logger(__name__) + + +_INELIGIBLE_STATES = frozenset( + { + FaultStatus.DEAD, + FaultStatus.UNHEALTHY, + FaultStatus.PAUSED, + FaultStatus.RECOVERING, + } +) + + +class DPRoutingPolicy: + """Subscribe to the bus, expose ``eligible_engines()`` to the LB client. + + The LB client should call ``eligible_engines()`` when picking a target. + The policy auto-updates whenever the bus publishes a status change. + """ + + def __init__(self, bus: FaultStateBus, total_engines: int): + self._lock = threading.Lock() + self._eligible: set[int] = set(range(total_engines)) + self._bus = bus + bus.subscribe(self._on_event) + + def eligible_engines(self) -> frozenset[int]: + with self._lock: + return frozenset(self._eligible) + + def _on_event(self, info: FaultInfo) -> None: + with self._lock: + if info.status in _INELIGIBLE_STATES: + if info.engine_index in self._eligible: + logger.info( + "DP rank %d → ineligible (status=%s)", + info.engine_index, + info.status.name, + ) + self._eligible.discard(info.engine_index) + elif ( + info.status is FaultStatus.HEALTHY + and info.engine_index not in self._eligible + ): + logger.info( + "DP rank %d → eligible again (status=HEALTHY)", + info.engine_index, + ) + self._eligible.add(info.engine_index) + + def close(self) -> None: + with suppress(Exception): + self._bus.unsubscribe(self._on_event) diff --git a/vllm/v1/fault_tolerance/errors.py b/vllm/v1/fault_tolerance/errors.py new file mode 100644 index 000000000000..02e1c86c2584 --- /dev/null +++ b/vllm/v1/fault_tolerance/errors.py @@ -0,0 +1,60 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Exception types used by the fault tolerance framework. + +These exist so callers that detect a fault on a hot path (e.g., +`dp_utils._run_ar`) can raise a typed exception that the supervisor's +`on_step_error` hook can recognize without resorting to string parsing. + +This is intentionally small. Most cross-process signals travel through +typed fields on the existing output objects (e.g., +`ModelRunnerOutput.fault_signal`), not exceptions. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from vllm.v1.fault_tolerance.types import FaultSignal + + +class FaultToleranceError(Exception): + """Base class for fault-tolerance exceptions. + + The optional `signal` attribute carries a typed `FaultSignal` so the + supervisor's `on_step_error` hook can read structured detail (kind + + payload) without parsing the exception message. + """ + + def __init__( + self, + message: str = "", + signal: FaultSignal | None = None, + ) -> None: + super().__init__(message) + self.signal = signal + + +class DpAllReduceFaultError(FaultToleranceError): + """Raised by `vllm.v1.worker.dp_utils._run_ar` when the DP synchronization + all-reduce fails. + + The supervisor's `on_step_error` hook can read `self.signal` to surface + the failure as a `FaultInfo` on the bus. + """ + + def __init__(self, signal: FaultSignal | None = None) -> None: + detail = signal.detail if signal is not None else "" + super().__init__(f"DP all-reduce failed: {detail}", signal=signal) + + +class EngineLoopPausedError(FaultToleranceError): + """Raised by the busy loop when a paused state has propagated across DP + ranks (e.g., one rank failed; healthy ranks must pause coordinated). + + Compatibility shim: existing PR #38534 raises an exception with this + name and pattern-matches its prefix in the executor. The redesign uses + typed exceptions instead — callers read `self.signal` rather than the + message text. + """ diff --git a/vllm/v1/fault_tolerance/fault_state_bus.py b/vllm/v1/fault_tolerance/fault_state_bus.py new file mode 100644 index 000000000000..d8ba2992e968 --- /dev/null +++ b/vllm/v1/fault_tolerance/fault_state_bus.py @@ -0,0 +1,139 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FaultStateBus — thin pub/sub surface for fault events. + +Wraps a ZMQ PUB socket (the wire format established by vllm-project/vllm#34833) +plus an in-process callback list so subscribers in the same process can +consume the same events without setting up their own SUB socket. + +External subscribers (Dynamo, monitoring tools) receive via ZMQ PUB exactly +as they did with #34833. In-process subscribers (e.g., the DP routing +policy) receive via the callback list. +""" + +from __future__ import annotations + +import threading +from collections.abc import Callable +from contextlib import suppress +from typing import TYPE_CHECKING + +import msgspec.msgpack +import zmq + +from vllm.logger import init_logger +from vllm.utils.network_utils import make_zmq_socket +from vllm.v1.fault_tolerance.types import FaultInfo + +if TYPE_CHECKING: + from vllm.config import VllmConfig + +logger = init_logger(__name__) + + +# Topic byte-string used on the ZMQ PUB topic frame. Matches the constant +# the existing fault-reporting work has used (preserve external compat). +FAULT_STATE_PUB_TOPIC = b"vllm_fault" + + +class FaultStateBus: + """ZMQ PUB + in-process subscribe. + + The PUB socket is bound at construction time; subscribers can attach via + ``subscribe(cb)`` to receive events synchronously when ``publish`` is + called. The PUB delivery is fire-and-forget (PUB sockets never block on + a slow subscriber). + """ + + def __init__(self, vllm_config: VllmConfig): + self._vllm_config = vllm_config + self._subscribers: list[Callable[[FaultInfo], None]] = [] + self._sub_lock = threading.Lock() + self._pub_socket = None + self._closed = False + self._init_pub_socket() + + def _init_pub_socket(self) -> None: + """Create the ZMQ PUB socket if the FT config provides a bind target.""" + # `fault_tolerance_config` may not exist on configs predating #34833. + ft_cfg = getattr(self._vllm_config, "fault_tolerance_config", None) + port = getattr(ft_cfg, "external_fault_notify_port", None) if ft_cfg else None + if port is None: + return + host = getattr(ft_cfg, "external_fault_notify_host", "0.0.0.0") + path = f"tcp://{host}:{port}" + try: + self._pub_socket = make_zmq_socket( + ctx=zmq.Context.instance(), + path=path, + socket_type=zmq.PUB, + bind=True, + ) + except Exception as e: + logger.warning("Failed to bind FaultStateBus PUB at %s: %s", path, e) + self._pub_socket = None + + # ---- subscribe surface (in-process) ------------------------------------ + + def subscribe(self, cb: Callable[[FaultInfo], None]) -> None: + """Register an in-process callback. Callback is invoked synchronously + on the publishing thread; keep it fast.""" + with self._sub_lock: + self._subscribers.append(cb) + + def unsubscribe(self, cb: Callable[[FaultInfo], None]) -> None: + with self._sub_lock, suppress(ValueError): + self._subscribers.remove(cb) + + # ---- publish surface --------------------------------------------------- + + def publish(self, info: FaultInfo) -> None: + """Fan out an event. PUB delivery is best-effort; callback delivery + is synchronous.""" + if self._closed: + return + # Out-of-process subscribers (Dynamo, monitoring, etc.). + if self._pub_socket is not None: + try: + self._pub_socket.send_multipart( + [FAULT_STATE_PUB_TOPIC, _encode_fault_info(info)] + ) + except Exception as e: + logger.debug("FaultStateBus PUB send failed: %s", e) + # In-process subscribers. + with self._sub_lock: + cbs = list(self._subscribers) + for cb in cbs: + try: + cb(info) + except Exception as e: + logger.warning("FaultStateBus subscriber raised: %s", e) + + # ---- lifecycle --------------------------------------------------------- + + def close(self) -> None: + if self._closed: + return + self._closed = True + if self._pub_socket is not None: + with suppress(Exception): + self._pub_socket.close(linger=0) + self._pub_socket = None + + +def _encode_fault_info(info: FaultInfo) -> bytes: + """Encode a FaultInfo for the wire using msgpack via msgspec. + + Wire format matches what vllm-project/vllm#34833 established so + external subscribers (e.g., Dynamo) work without modification. + """ + payload = { + "schema_version": 1, + "engine_index": info.engine_index, + "status": info.status.name.lower(), + "kind": info.kind, + "detail": info.detail + if isinstance(info.detail, (str, type(None))) + else str(info.detail), + } + return msgspec.msgpack.encode(payload) diff --git a/vllm/v1/fault_tolerance/maskable.py b/vllm/v1/fault_tolerance/maskable.py new file mode 100644 index 000000000000..87b8c2b49a87 --- /dev/null +++ b/vllm/v1/fault_tolerance/maskable.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""FTMaskBuffer — capability mixin for FT-capable collective backends. + +Some collective backends (DeepEP-LL, NIXL-EP, FT NCCL) expose a per-peer +mask buffer that the kernel auto-sets when a peer is detected to have +faulted. ``query_mask`` reads which peers are flagged; ``clean_mask`` +resets the buffer. + +This is a CAPABILITY mixin, not a base class. It lives separately from +``BaseDeviceCommunicator`` / ``All2AllManagerBase`` so that non-FT-capable +backends don't carry methods they can never implement, and so callers can +ask "does this backend support FT masking?" via ``isinstance(x, FTMaskBuffer)``. + +See vLLM FT design doc §7.2 for the lifecycle (when ``query_mask`` is +called and when ``clean_mask`` is called). +""" + +from __future__ import annotations + +from typing import Protocol, runtime_checkable + +import torch + + +@runtime_checkable +class FTMaskBuffer(Protocol): + """Capability contract for backends that expose an FT mask buffer. + + Implemented today by ``DeepEPLLAll2AllManager`` and + ``NixlEPAll2AllManager``. FT NCCL collectives (cf. + ``vllm/distributed/eplb/ft_nccl_wrapper.py``) are the natural future + implementer. + + Any caller that needs the mask should gate on + ``isinstance(x, FTMaskBuffer)`` rather than calling the methods + unconditionally and catching ``NotImplementedError``. + """ + + def query_mask(self, mask: torch.Tensor) -> torch.Tensor: + """Read which peers are currently flagged as faulty into ``mask``. + + ``mask`` is a 1-D ``int32`` tensor with length equal to the EP + group's world size. The kernel writes 1 for any peer it has + detected as faulty, 0 otherwise. + """ + ... + + def clean_mask(self) -> None: + """Reset the buffer to zeros. Used during retry/recovery once the + EP group is otherwise quiesced.""" + ... diff --git a/vllm/v1/fault_tolerance/plans/__init__.py b/vllm/v1/fault_tolerance/plans/__init__.py new file mode 100644 index 000000000000..b36db3ab021a --- /dev/null +++ b/vllm/v1/fault_tolerance/plans/__init__.py @@ -0,0 +1,21 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Recovery plans bundled with vLLM. + +Each plan is a small subclass of ``BaseRecoveryPlan`` registered via +``@register_recovery_plan(...)``. New plans are added by writing one file +in this directory; no edits to existing classes are required. + +Importing this module registers the bundled plans so they can be looked up +by name from ``/fault_tolerance/apply``. +""" + +# Importing the plan modules executes their module-scope ``@register_*`` +# decorators, populating the registry. +from vllm.v1.fault_tolerance.plans import ( # noqa: F401 + abort, + abort_communicator, + pause, + retry, + scale_down, +) diff --git a/vllm/v1/fault_tolerance/plans/_common.py b/vllm/v1/fault_tolerance/plans/_common.py new file mode 100644 index 000000000000..fc475ed5e487 --- /dev/null +++ b/vllm/v1/fault_tolerance/plans/_common.py @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Shared helpers for engine-local recovery plans. + +Plans like ``pause`` and ``retry`` follow the same shape: invoke a worker +method via ``executor.collective_rpc``, aggregate per-worker results, and +return a single ``FaultToleranceResult`` to the supervisor. The aggregation +logic lives here so adding a new ``EngineLocalRecoveryPlan`` is one line in +``execute`` rather than a copy-paste of the boilerplate. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from vllm.logger import init_logger +from vllm.v1.fault_tolerance.types import FaultToleranceResult + +if TYPE_CHECKING: + from vllm.v1.executor.abstract import Executor + +logger = init_logger(__name__) + + +def run_collective_plan( + executor: Executor, + method: str, + params: dict[str, Any] | None, +) -> FaultToleranceResult: + """Invoke ``method`` on every worker via ``collective_rpc`` and aggregate. + + Each worker is contracted to return a ``FaultToleranceResult``; this + helper trusts that contract and lets ``AttributeError`` propagate as a + real bug if a worker returns the wrong shape. The supervisor's caller + converts any uncaught exception into an HTTP-friendly result, so we do + not need an extra defensive layer here. + """ + try: + results: list[FaultToleranceResult] = executor.collective_rpc( + method, kwargs=params or {} + ) + except Exception as e: + logger.exception("%s collective_rpc failed: %s", method, e) + return FaultToleranceResult(success=False, reason=f"collective_rpc raised: {e}") + + failed = [(i, r) for i, r in enumerate(results) if not r.success] + return FaultToleranceResult( + success=not failed, + reason=( + "\n".join( + f"worker {i}: {r.reason}" for i, r in failed if r.reason is not None + ) + or None + ), + ) diff --git a/vllm/v1/fault_tolerance/plans/abort.py b/vllm/v1/fault_tolerance/plans/abort.py new file mode 100644 index 000000000000..4e5dace9da7d --- /dev/null +++ b/vllm/v1/fault_tolerance/plans/abort.py @@ -0,0 +1,80 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""AbortRequestsPlan — fail in-flight requests on a target engine. + +Cluster-scope. Different from :class:`AbortCommunicatorPlan` (low-level +``ncclCommAbort`` interrupt). This plan walks the client's in-flight +request map for the target engine and routes each one through +``OutputProcessor.abort_requests`` (or equivalent) so clients receive +``FinishReason.ABORT`` instead of hanging. + +Typical orchestrator flow: + +1. Engine death detected → client publishes ``FaultInfo(DEAD)`` on bus. +2. Orchestrator decides "fail any in-flight on the dead rank, but don't + yet scale down" (e.g. while diagnosing whether the death is permanent). +3. ``POST /fault_tolerance/apply {"instruction": "abort", "params": + {"engine_index": N}}`` runs this plan. +4. Later, orchestrator may follow with ``scale_down`` if recovery is + warranted, or ``resume`` if the engine recovers. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from vllm.logger import init_logger +from vllm.v1.fault_tolerance.registry import register_recovery_plan +from vllm.v1.fault_tolerance.types import ( + ClusterRecoveryPlan, + FaultToleranceResult, + KvAction, +) + +if TYPE_CHECKING: + from vllm.v1.fault_tolerance.cluster import ClusterCoordinator + +logger = init_logger(__name__) + + +@register_recovery_plan("abort") +class AbortRequestsPlan(ClusterRecoveryPlan): + """Abort all in-flight requests on a target engine. + + KV cache: ``KvAction.NONE`` — aborted requests' KV is freed by the + scheduler when the abort lands on the engine, but no surviving engine's + KV is touched. + + Required params: + ``engine_index`` (int): The DP rank to abort. + """ + + instruction = "abort" + kv_action = KvAction.NONE + + def execute( # type: ignore[override] + self, coord: ClusterCoordinator, params: dict[str, Any] + ) -> FaultToleranceResult: + engine_index = (params or {}).get("engine_index") + if not isinstance(engine_index, int): + return FaultToleranceResult( + success=False, + reason="abort requires params.engine_index (int)", + ) + + try: + num_aborted = coord.abort_inflight_on(engine_index) + except Exception as e: + logger.exception("abort_inflight_on(%d) failed: %s", engine_index, e) + return FaultToleranceResult( + success=False, reason=f"abort_inflight_on failed: {e}" + ) + + return FaultToleranceResult( + success=True, + reason=( + f"Aborted {num_aborted} in-flight requests on engine {engine_index}" + if isinstance(num_aborted, int) + else None + ), + ) diff --git a/vllm/v1/fault_tolerance/plans/abort_communicator.py b/vllm/v1/fault_tolerance/plans/abort_communicator.py new file mode 100644 index 000000000000..c1a028827b63 --- /dev/null +++ b/vllm/v1/fault_tolerance/plans/abort_communicator.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""AbortCommunicatorPlan — interrupt a worker stuck in NCCL. + +Used when ``executor.collective_rpc`` cannot reach the worker because its +main thread is blocked in NCCL. The supervisor's interrupt PUB socket +(see ``DefaultFaultSupervisor._interrupt_pub``) is the only way to reach +the worker's auxiliary thread, which calls ``ncclCommAbort`` from outside +the blocked main thread. + +After the abort, the worker's main thread errors out of NCCL and becomes +responsive again — at which point a subsequent ``pause`` or ``retry`` +instruction will reach it via ``collective_rpc`` normally. +""" + +from __future__ import annotations + +from typing import Any + +from vllm.logger import init_logger +from vllm.v1.fault_tolerance.registry import register_recovery_plan +from vllm.v1.fault_tolerance.types import ( + BaseRecoveryPlan, + FaultToleranceResult, + InterruptCommand, + KvAction, +) + +logger = init_logger(__name__) + + +@register_recovery_plan(InterruptCommand.ABORT_COMMUNICATOR.value) +class AbortCommunicatorPlan(BaseRecoveryPlan): + """Fire a one-way interrupt to a worker's aux thread. + + Unlike most plans, this one calls into the supervisor (rather than the + executor) because it uses the supervisor's interrupt PUB socket, not + the executor's RPC channel. The plan's ``execute`` therefore takes a + supervisor instance. + + KV cache: ``KvAction.NONE`` — the abort just unblocks the worker so + subsequent plans can run; no KV state is touched. + """ + + instruction = InterruptCommand.ABORT_COMMUNICATOR.value + kv_action = KvAction.NONE + + def execute( # type: ignore[override] + self, supervisor: Any, params: dict[str, Any] + ) -> FaultToleranceResult: + target = (params or {}).get("worker_index", "all") + send_interrupt = getattr(supervisor, "send_interrupt", None) + if send_interrupt is None: + return FaultToleranceResult( + success=False, + reason=( + "Supervisor does not expose send_interrupt; cannot " + "deliver abort_communicator. Use the default supervisor " + "or implement send_interrupt in your custom supervisor." + ), + ) + try: + send_interrupt(target, InterruptCommand.ABORT_COMMUNICATOR) + except Exception as e: + logger.exception("send_interrupt failed: %s", e) + return FaultToleranceResult( + success=False, reason=f"send_interrupt raised: {e}" + ) + # Fire-and-forget; aux thread does the abort and the caller is + # expected to follow with `pause` or `retry` after a grace period. + return FaultToleranceResult(success=True) diff --git a/vllm/v1/fault_tolerance/plans/pause.py b/vllm/v1/fault_tolerance/plans/pause.py new file mode 100644 index 000000000000..25e9dafd06c7 --- /dev/null +++ b/vllm/v1/fault_tolerance/plans/pause.py @@ -0,0 +1,40 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""PauseRecoveryPlan — stop healthy workers cleanly via collective_rpc.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from vllm.v1.fault_tolerance.plans._common import run_collective_plan +from vllm.v1.fault_tolerance.registry import register_recovery_plan +from vllm.v1.fault_tolerance.types import ( + EngineLocalRecoveryPlan, + FaultToleranceResult, + KvAction, +) + +if TYPE_CHECKING: + from vllm.v1.executor.abstract import Executor + + +@register_recovery_plan("pause") +class PauseRecoveryPlan(EngineLocalRecoveryPlan): + """Pause an engine's workers via ``executor.collective_rpc("ft_pause")``. + + Used when the worker main threads are responsive (either between steps + on a healthy engine, or after an FT-capable kernel has timed out and + returned control to the main thread). For the case where the worker is + blocked in NCCL and unresponsive, see ``AbortCommunicatorPlan``. + + KV cache: ``KvAction.NONE`` — running requests' allocated blocks remain; + on resume work continues. + """ + + instruction = "pause" + kv_action = KvAction.NONE + + def execute( # type: ignore[override] + self, executor: Executor, params: dict[str, Any] + ) -> FaultToleranceResult: + return run_collective_plan(executor, "ft_pause", params) diff --git a/vllm/v1/fault_tolerance/plans/retry.py b/vllm/v1/fault_tolerance/plans/retry.py new file mode 100644 index 000000000000..97b29675f4ab --- /dev/null +++ b/vllm/v1/fault_tolerance/plans/retry.py @@ -0,0 +1,45 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""RetryRecoveryPlan — clean up worker state and resume after a transient +fault. + +Worker-side cleanup (clear input batch, clean FT mask, rebuild DP gloo +group) lives in ``Worker.ft_resume_after_retry`` and is invoked here via +``executor.collective_rpc``. Result aggregation is automatic — no separate +dispatcher to maintain. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from vllm.v1.fault_tolerance.plans._common import run_collective_plan +from vllm.v1.fault_tolerance.registry import register_recovery_plan +from vllm.v1.fault_tolerance.types import ( + EngineLocalRecoveryPlan, + FaultToleranceResult, + KvAction, +) + +if TYPE_CHECKING: + from vllm.v1.executor.abstract import Executor + + +@register_recovery_plan("retry") +class RetryRecoveryPlan(EngineLocalRecoveryPlan): + """Cleanup-and-retry for transient errors. + + KV cache: ``KvAction.PREEMPT_LOGICAL_FREE`` — the scheduler preempts + running requests back to the waiting queue and logically frees their KV + blocks. The blocks themselves are not zeroed, so prefix-cache hits on + re-add cover most already-computed prefixes; only the tail tokens + recompute (similar to a chunked prefill). + """ + + instruction = "retry" + kv_action = KvAction.PREEMPT_LOGICAL_FREE + + def execute( # type: ignore[override] + self, executor: Executor, params: dict[str, Any] + ) -> FaultToleranceResult: + return run_collective_plan(executor, "ft_resume_after_retry", params) diff --git a/vllm/v1/fault_tolerance/plans/scale_down.py b/vllm/v1/fault_tolerance/plans/scale_down.py new file mode 100644 index 000000000000..ce53038befe4 --- /dev/null +++ b/vllm/v1/fault_tolerance/plans/scale_down.py @@ -0,0 +1,76 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""ScaleDownRecoveryPlan — cluster-scope recovery for a dead DP engine. + +Delegates to the existing elastic EP machinery in +``vllm/distributed/elastic_ep`` (which is upstream from PR #38862). The +plan itself is a thin façade so ``/fault_tolerance/apply`` becomes the +single instruction surface for ``pause``, ``retry``, ``scale_down``, etc. + +Nothing in ``vllm/distributed/elastic_ep`` is rewritten — only the trigger +path changes from "detector calls scale-down directly" to +"orchestrator POSTs scale_down to the FT API". +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from vllm.logger import init_logger +from vllm.v1.fault_tolerance.registry import register_recovery_plan +from vllm.v1.fault_tolerance.types import ( + ClusterRecoveryPlan, + FaultToleranceResult, + KvAction, +) + +if TYPE_CHECKING: + from vllm.config import VllmConfig + from vllm.v1.fault_tolerance.cluster import ClusterCoordinator + +logger = init_logger(__name__) + + +@register_recovery_plan("scale_down") +class ScaleDownRecoveryPlan(ClusterRecoveryPlan): + """Drop a dead DP engine and rebuild the cluster topology. + + Backend constraints (Ray + EP fault tolerance + TP=1, etc.) are the + same as the existing PR #38862 stack documents. ``is_applicable`` checks + them so the registry refuses the plan on incompatible deployments. + + KV cache: ``KvAction.LOSE_DEAD_ENGINE_BLOCKS`` — the dead engine's KV + is unrecoverable. In-flight requests on the dead engine are aborted + with ``FinishReason.ABORT``; surviving engines' KV is untouched. + CUDA-graph recapture across survivors does not affect KV memory. + """ + + instruction = "scale_down" + kv_action = KvAction.LOSE_DEAD_ENGINE_BLOCKS + + def is_applicable(self, vllm_config: VllmConfig) -> bool: + pc = vllm_config.parallel_config + # `enable_ep_fault_tolerance` and `data_parallel_backend` are added + # by #38862; tolerate older configs that don't carry them. + if not getattr(pc, "enable_ep_fault_tolerance", False): + return False + if pc.tensor_parallel_size != 1: + return False + return getattr(pc, "data_parallel_backend", "") == "ray" + + def execute( # type: ignore[override] + self, coord: ClusterCoordinator, params: dict[str, Any] + ) -> FaultToleranceResult: + dead_index = (params or {}).get("dead_engine_index") + if not isinstance(dead_index, int): + return FaultToleranceResult( + success=False, + reason="scale_down requires params.dead_engine_index (int)", + ) + + try: + coord.scale_down(dead_index) + except Exception as e: + logger.exception("scale_down(%d) failed: %s", dead_index, e) + return FaultToleranceResult(success=False, reason=f"scale_down failed: {e}") + return FaultToleranceResult(success=True) diff --git a/vllm/v1/fault_tolerance/registry.py b/vllm/v1/fault_tolerance/registry.py new file mode 100644 index 000000000000..68c19518113a --- /dev/null +++ b/vllm/v1/fault_tolerance/registry.py @@ -0,0 +1,129 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Registry for fault tolerance supervisors and recovery plans. + +Mirrors the shape of `vllm.model_executor.model_loader.register_model_loader` +so orchestrators (Dynamo, k8s controllers, custom platforms) can plug their +own supervisor in via a decorator without forking vLLM. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, TypeVar + +from vllm.v1.fault_tolerance.types import ( + GLOBAL_NOOP_HOOKS, + BaseRecoveryPlan, + FaultToleranceHooks, +) + +if TYPE_CHECKING: + from vllm.config import VllmConfig + +_S = TypeVar("_S", bound=type) +_P = TypeVar("_P", bound=type[BaseRecoveryPlan]) + + +# Registries are module-globals: small, write-only at import time, read-only +# at runtime. Mirrors how `register_model_loader` works for GMS et al. +_SUPERVISORS: dict[str, type[FaultToleranceHooks]] = {} +_PLANS: dict[str, BaseRecoveryPlan] = {} + + +def register_fault_supervisor(name: str) -> Callable[[_S], _S]: + """Register a fault-tolerance supervisor implementation. + + Usage:: + + @register_fault_supervisor("dynamo") + class DynamoFaultSupervisor(FaultToleranceHooks): ... + + User selects with ``--fault-supervisor dynamo`` (mirrors GMS's + ``--load-format gms`` pattern). + """ + + def deco(cls: _S) -> _S: + if name in _SUPERVISORS: + raise ValueError( + f"Fault supervisor '{name}' is already registered " + f"by {_SUPERVISORS[name].__module__}.{_SUPERVISORS[name].__name__}" + ) + _SUPERVISORS[name] = cls # type: ignore[assignment] + return cls + + return deco + + +def register_recovery_plan(instruction: str) -> Callable[[_P], _P]: + """Register a recovery plan for a `/fault_tolerance/apply` instruction. + + Usage:: + + @register_recovery_plan("pause") + class PauseRecoveryPlan(EngineLocalRecoveryPlan): ... + """ + + def deco(cls: _P) -> _P: + if instruction in _PLANS: + raise ValueError( + f"Recovery plan '{instruction}' is already registered " + f"by {type(_PLANS[instruction]).__name__}" + ) + # Plans are stateless; instantiate once at registration time. + _PLANS[instruction] = cls() # type: ignore[call-arg] + return cls + + return deco + + +def get_supervisor_class(name: str) -> type[FaultToleranceHooks]: + """Look up a registered supervisor class by name.""" + if name not in _SUPERVISORS: + raise KeyError( + f"Unknown fault supervisor '{name}'. Registered: {sorted(_SUPERVISORS)}" + ) + return _SUPERVISORS[name] + + +def get_plan(instruction: str) -> BaseRecoveryPlan: + """Look up a registered recovery plan by instruction name.""" + if instruction not in _PLANS: + raise KeyError( + f"Unknown recovery instruction '{instruction}'. " + f"Registered: {sorted(_PLANS)}" + ) + return _PLANS[instruction] + + +def list_plans() -> list[str]: + """List currently registered recovery instructions.""" + return sorted(_PLANS) + + +def get_fault_hooks( + vllm_config: VllmConfig | None, + engine: Any | None = None, +) -> FaultToleranceHooks: + """Get the active hooks implementation. + + Returns the no-op singleton when FT is disabled or when no engine instance + is available yet (e.g., during early init). Otherwise returns the engine's + supervisor instance. + """ + if vllm_config is None or not getattr( + vllm_config.parallel_config, "enable_fault_tolerance", False + ): + return GLOBAL_NOOP_HOOKS + if engine is None: + return GLOBAL_NOOP_HOOKS + supervisor = getattr(engine, "fault_supervisor", None) + if supervisor is None: + return GLOBAL_NOOP_HOOKS + return supervisor + + +def reset_for_testing() -> None: + """Clear all registries. Tests only.""" + _SUPERVISORS.clear() + _PLANS.clear() diff --git a/vllm/v1/fault_tolerance/types.py b/vllm/v1/fault_tolerance/types.py new file mode 100644 index 000000000000..ad1380e6ee34 --- /dev/null +++ b/vllm/v1/fault_tolerance/types.py @@ -0,0 +1,243 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright contributors to the vLLM project +"""Core types for the fault tolerance framework. + +This module defines the primitives that cross hot-path code (typed signals +on the existing output object) and the extension points that orchestrators +plug into. Everything else in `vllm.v1.fault_tolerance` builds on these. +""" + +from __future__ import annotations + +import enum +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable + +if TYPE_CHECKING: + from vllm.config import VllmConfig + from vllm.v1.executor.abstract import Executor + from vllm.v1.outputs import ModelRunnerOutput + + +class FaultStatus(enum.IntEnum): + """Per-engine health status published on the fault state bus. + + Integer values are the wire format and must remain stable across renames + or insertions; new values must be APPENDED, never inserted. + """ + + HEALTHY = 0 + UNHEALTHY = 1 + PAUSED = 2 + RECOVERING = 3 + DEAD = 4 + + +class Disposition(enum.Enum): + """How the engine busy loop should react to a fault.""" + + CONTINUE = "continue" + PAUSE_LOOP = "pause_loop" + PROPAGATE = "propagate" + SCHEDULE_RETRY = "schedule_retry" + + +class InterruptCommand(str, enum.Enum): + """Worker-side aux-thread interrupt commands. + + Sent by ``DefaultFaultSupervisor.send_interrupt`` over the supervisor's + interrupt PUB; received by ``Worker._ft_interrupt_loop`` on the SUB. + The wire payload is the enum's ``.value`` so msgpack/JSON encodings + don't need a custom resolver. Use the enum everywhere in code. + + Inherits from ``str`` so an enum member is interchangeable with its + string value at the wire boundary, and ``InterruptCommand(cmd_str)`` + raises ``ValueError`` for unknown commands rather than dispatching + them to the wrong handler. + """ + + ABORT_COMMUNICATOR = "abort_communicator" + + +class KvAction(enum.Enum): + """KV cache lifecycle effect of a recovery action. + + Each `BaseRecoveryPlan` declares one of these so the KV impact is part of + the plan's contract, not a side effect. + """ + + NONE = "none" + """KV unchanged (e.g., pause).""" + + PREEMPT_LOGICAL_FREE = "preempt_logical_free" + """Preempt running requests; logically free blocks; rely on prefix cache + on re-add. Used by `retry`.""" + + LOSE_DEAD_ENGINE_BLOCKS = "lose_dead_engine_blocks" + """Dead engine's KV is unrecoverable. In-flight on dead engine is aborted; + survivors keep their KV. Used by `scale_down`.""" + + ADD_NEW_ENGINE_BLOCKS = "add_new_engine_blocks" + """New engine starts with empty KV pool; no migration. Used by `scale_up`.""" + + +@dataclass +class FaultSignal: + """Typed signal carried on the success path of `ModelRunnerOutput`. + + The worker writes this when execution surfaces a fault that the engine + needs to know about (e.g., DP all-reduce timeout, mask change, paused). + The engine reads it via the supervisor's `after_step` hook. + + This replaces the existing pattern of raising `EngineLoopPausedError` and + pattern-matching exception text in the executor — typed field on success + path instead of string matching on error path. + """ + + kind: str + """Discriminator. Conventional values: 'paused', 'dp_allreduce_failed', + 'ep_mask_changed'. Plans may add their own.""" + + detail: Any = None + """Optional payload. Kept untyped so callers can attach context without + forcing a schema change.""" + + +@dataclass +class FaultInfo: + """Status update published on `FaultStateBus`. + + Wire-compatible with the `engine_status_dict` payload established by the + fault-reporting work (see vllm-project/vllm#34833): each engine reports + its current `FaultStatus` plus optional discriminator and detail. + """ + + engine_index: int + status: FaultStatus + kind: str | None = None + detail: Any = None + + @classmethod + def from_signal(cls, engine_index: int, signal: FaultSignal) -> FaultInfo: + # Default mapping; supervisors can override based on signal.kind. + status = ( + FaultStatus.PAUSED if signal.kind == "paused" else FaultStatus.UNHEALTHY + ) + return cls( + engine_index=engine_index, + status=status, + kind=signal.kind, + detail=signal.detail, + ) + + @classmethod + def from_exception(cls, engine_index: int, exc: BaseException) -> FaultInfo: + return cls( + engine_index=engine_index, + status=FaultStatus.UNHEALTHY, + kind=type(exc).__name__, + detail=str(exc), + ) + + +@dataclass +class FaultToleranceRequest: + """Request body for `/fault_tolerance/apply`.""" + + instruction: str + params: dict[str, Any] = field(default_factory=dict) + request_id: str | None = None + + +@dataclass +class FaultToleranceResult: + """Result returned from a `BaseRecoveryPlan.execute` call.""" + + success: bool + reason: str | None = None + request_id: str | None = None + + +@runtime_checkable +class FaultToleranceHooks(Protocol): + """Contract that engine hot-path code sees. + + Default implementation (`NoOpFaultHooks`) is a no-op singleton installed + when fault tolerance is disabled, so the hook calls in `run_busy_loop` + pay only the cost of empty method dispatch when FT is off. + """ + + def before_step(self, engine: Any) -> None: ... + + def after_step(self, engine: Any, output: ModelRunnerOutput | None) -> None: ... + + def on_step_error(self, engine: Any, exc: BaseException) -> Disposition: ... + + +class NoOpFaultHooks: + """No-op hooks installed when fault tolerance is disabled.""" + + def before_step(self, engine: Any) -> None: + return + + def after_step(self, engine: Any, output: ModelRunnerOutput | None) -> None: + return + + def on_step_error(self, engine: Any, exc: BaseException) -> Disposition: + return Disposition.PROPAGATE + + +# Module-level singleton, used by `get_fault_hooks` when FT is disabled. +GLOBAL_NOOP_HOOKS = NoOpFaultHooks() + + +class BaseRecoveryPlan(ABC): + """Strategy for one fault tolerance instruction. + + Subclasses declare their `instruction` name (registered via + `@register_recovery_plan`), their `kv_action` (the KV-cache lifecycle + effect, see `KvAction`), and their `execute` method. + + Two scopes: engine-local plans take `(executor, params)`; cluster plans + take `(coord, params)` where `coord` is a `ClusterCoordinator`. Subclasses + pick which by inheriting from `EngineLocalRecoveryPlan` or + `ClusterRecoveryPlan` (defined alongside the registry). + """ + + instruction: str + kv_action: KvAction = KvAction.NONE + + def is_applicable(self, vllm_config: VllmConfig) -> bool: + """Backend / config preconditions. Default: always applicable. + + Plans with backend constraints (e.g., `ScaleDownRecoveryPlan` requires + Ray + EP fault tolerance + TP=1) override this so the registry can + refuse to run them on incompatible configs. + """ + return True + + @abstractmethod + def execute(self, *args: Any, **kwargs: Any) -> FaultToleranceResult: + """Run the plan. Subclasses should narrow the signature.""" + + +class EngineLocalRecoveryPlan(BaseRecoveryPlan): + """Engine-local plan: takes the engine's executor for `collective_rpc`.""" + + @abstractmethod + def execute( # type: ignore[override] + self, executor: Executor, params: dict[str, Any] + ) -> FaultToleranceResult: ... + + +class ClusterRecoveryPlan(BaseRecoveryPlan): + """Cluster-scope plan: takes a `ClusterCoordinator` (defined in cluster.py) + for cross-engine RPC. Used by `scale_down` (PR #38862) and future + `scale_up`. + """ + + @abstractmethod + def execute( # type: ignore[override] + self, coord: Any, params: dict[str, Any] + ) -> FaultToleranceResult: ... diff --git a/vllm/v1/outputs.py b/vllm/v1/outputs.py index 1f102ec61783..844edfc0939c 100644 --- a/vllm/v1/outputs.py +++ b/vllm/v1/outputs.py @@ -17,10 +17,12 @@ KVConnectorWorkerMetadata, ) from vllm.distributed.kv_transfer.kv_connector.v1.metrics import KVConnectorStats + from vllm.v1.fault_tolerance import FaultSignal else: KVConnectorStats = object KVConnectorWorkerMetadata = object KVConnectorKVEvents = object + FaultSignal = object class LogprobsLists(NamedTuple): @@ -201,6 +203,14 @@ class ModelRunnerOutput: # information related to cudagraph execution cudagraph_stats: CUDAGraphStat | None = None + # Fault tolerance signal carried on the success path. Workers set this + # when execution surfaces a fault that the engine's supervisor needs to + # know about (e.g., paused, dp_allreduce_failed). The engine reads it via + # the supervisor's `after_step` hook. Replaces the previous pattern of + # raising `EngineLoopPausedError` and pattern-matching exception text. + # See `vllm.v1.fault_tolerance.FaultSignal`. + fault_signal: FaultSignal | None = None + # ModelRunnerOutput wrapper for async scheduling. class AsyncModelRunnerOutput(ABC): diff --git a/vllm/v1/worker/dp_utils.py b/vllm/v1/worker/dp_utils.py index 64f4e59031e6..e51cb4b3c24c 100644 --- a/vllm/v1/worker/dp_utils.py +++ b/vllm/v1/worker/dp_utils.py @@ -7,6 +7,8 @@ from vllm.config import ParallelConfig from vllm.distributed.parallel_state import get_dp_group from vllm.logger import init_logger +from vllm.v1.fault_tolerance import FaultSignal +from vllm.v1.fault_tolerance.errors import DpAllReduceFaultError from vllm.v1.worker.ubatch_utils import ( check_ubatch_thresholds, is_last_ubatch_empty, @@ -40,6 +42,12 @@ def _run_ar( cudagraph_mode: int, parallel_config: ParallelConfig, ) -> torch.Tensor: + """Run the DP synchronization all-reduce. + + Raises ``DpAllReduceFaultError`` (carrying a typed ``FaultSignal``) on + collective failure so the supervisor's ``on_step_error`` hook can surface + the fault via ``exc.signal`` without parsing the exception message. + """ dp_size = parallel_config.data_parallel_size dp_rank = parallel_config.data_parallel_rank device, group = _get_device_and_group(parallel_config) @@ -48,7 +56,12 @@ def _run_ar( tensor[1][dp_rank] = padded_num_tokens_per_ubatch tensor[2][dp_rank] = 1 if should_ubatch else 0 tensor[3][dp_rank] = cudagraph_mode - dist.all_reduce(tensor, group=group) + try: + dist.all_reduce(tensor, group=group) + except RuntimeError as e: + raise DpAllReduceFaultError( + signal=FaultSignal(kind="dp_allreduce_failed", detail=str(e)) + ) from e return tensor diff --git a/vllm/v1/worker/gpu_worker.py b/vllm/v1/worker/gpu_worker.py index 36dd5ed7fc65..7d65f5cc63c9 100644 --- a/vllm/v1/worker/gpu_worker.py +++ b/vllm/v1/worker/gpu_worker.py @@ -4,8 +4,9 @@ import gc import os +import threading from collections.abc import Callable -from contextlib import AbstractContextManager, contextmanager, nullcontext +from contextlib import AbstractContextManager, contextmanager, nullcontext, suppress from datetime import timedelta from types import NoneType from typing import TYPE_CHECKING, Any @@ -14,12 +15,15 @@ import regex as re import torch import torch.nn as nn +import zmq import vllm.envs as envs from vllm.config import CUDAGraphMode, VllmConfig, set_current_vllm_config from vllm.config.compilation import CompilationMode from vllm.distributed import ( ensure_model_parallel_initialized, + get_dp_group, + get_ep_group, init_distributed_environment, set_custom_all_reduce, ) @@ -49,6 +53,12 @@ from vllm.utils.mem_utils import MemorySnapshot, format_gib, memory_profiling from vllm.utils.torch_utils import set_random_seed from vllm.v1.core.sched.output import GrammarOutput, SchedulerOutput +from vllm.v1.fault_tolerance import ( + FaultSignal, + FaultToleranceResult, + InterruptCommand, +) +from vllm.v1.fault_tolerance.maskable import FTMaskBuffer from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheSpec from vllm.v1.outputs import ( AsyncModelRunnerOutput, @@ -773,6 +783,17 @@ def sample_tokens( def execute_model( self, scheduler_output: "SchedulerOutput" ) -> ModelRunnerOutput | AsyncModelRunnerOutput | None: + # Fault tolerance: short-circuit when the worker has been paused via + # `ft_pause`. The engine's supervisor reads the typed `fault_signal` + # field on the success path (no exception, no string match) and + # decides whether to keep the loop paused or to move to RECOVERING. + if self._ft_paused: + return ModelRunnerOutput( + req_ids=[], + req_id_to_index={}, + fault_signal=FaultSignal(kind="paused"), + ) + # ensure any previous non-blocking PP sends are complete if self._pp_send_work: for handle in self._pp_send_work: @@ -1040,9 +1061,168 @@ def shutdown(self) -> None: if model_runner := getattr(self, "model_runner", None): model_runner.shutdown() + # Stop the FT aux thread (if started). The thread is a daemon so it + # will exit on its own when the process exits, but signal it so it + # can clean up its socket cleanly. + self._ft_shutdown = True + def elastic_ep_execute(self, execute_method: str, *args, **kwargs): return self.elastic_ep_executor.execute(execute_method, *args, **kwargs) + # ------------------------------------------------------------------ + # Fault tolerance — main-thread methods (invoked via collective_rpc). + # See ``vllm.v1.fault_tolerance.plans.pause`` and ``...plans.retry``. + # ------------------------------------------------------------------ + + # Class-level defaults so reads work on workers that never enabled FT. + _ft_paused: bool = False + _ft_shutdown: bool = False + _ft_interrupt_thread: Any = None + + def ft_pause(self) -> FaultToleranceResult: + """Pause this worker. Called via collective_rpc between iterations. + + Sets a flag the next ``execute_model`` call observes; it then + returns a ``ModelRunnerOutput`` with ``fault_signal=FaultSignal( + kind="paused")`` so the engine's supervisor sees the state change + on the success path (no exceptions over IPC). + """ + self._ft_paused = True + return FaultToleranceResult(success=True) + + def ft_resume_after_retry(self, **params: Any) -> FaultToleranceResult: + """Clean up worker state and resume. + + - Clears any in-flight input batch (KvAction.PREEMPT_LOGICAL_FREE). + - Calls ``clean_mask`` on the all2all manager iff the backend + implements ``FTMaskBuffer``. + + Order matters: ``_ft_paused`` is only cleared after every cleanup + step succeeds. If any step fails, the worker stays paused so the + next iteration doesn't run on inconsistent state, and the returned + result carries the failure reason for the supervisor. + """ + cleanup_errors: list[str] = [] + + # Clear in-flight input batch — equivalent to today's + # ``clear_input_batch_callback`` body. + if model_runner := getattr(self, "model_runner", None): + input_batch = getattr(model_runner, "input_batch", None) + if input_batch is not None: + cached = list(input_batch.req_id_to_index.keys()) + for req_id in cached: + input_batch.remove_request(req_id) + + # Clean FT mask if the backend supports it. EP group is only created + # for MoE models, so absence is normal — silently skip in that case. + try: + ep_group = get_ep_group() + except AssertionError: + ep_group = None + if ep_group is not None: + mgr = getattr(ep_group.device_communicator, "all2all_manager", None) + if isinstance(mgr, FTMaskBuffer): + try: + mgr.clean_mask() + except Exception as e: + logger.exception("ft_resume_after_retry: clean_mask failed") + cleanup_errors.append(f"clean_mask: {e}") + + if cleanup_errors: + return FaultToleranceResult( + success=False, + reason="; ".join(cleanup_errors), + ) + + self._ft_paused = False + return FaultToleranceResult(success=True) + + # ------------------------------------------------------------------ + # Fault tolerance — interrupt aux thread. + # Runs while the main thread is blocked (e.g. in NCCL); only handles + # operations that genuinely need an aux thread (ncclCommAbort). + # See ``vllm.v1.fault_tolerance.plans.abort_communicator``. + # ------------------------------------------------------------------ + + def ensure_ft_interrupt_thread(self, addr: str) -> None: + """Start the FT interrupt aux thread (idempotent). + + Called by the engine after construction when FT is enabled. + """ + if self._ft_interrupt_thread is not None: + return + + self._ft_interrupt_addr = addr + self._ft_shutdown = False + self._ft_interrupt_thread = threading.Thread( + target=self._ft_interrupt_loop, + daemon=True, + name=f"FTInterruptThread_{self.local_rank}", + ) + self._ft_interrupt_thread.start() + + def _ft_interrupt_loop(self) -> None: + """Tiny daemon. Handles only operations that must run while the + main thread is blocked (e.g. NCCL hang). Pause / retry come + through ``collective_rpc`` to the main thread, not here. + + SUB socket connect failures propagate so the daemon thread crashes + loudly with a logged traceback rather than silently leaving the + worker without an abort path. + """ + ctx = zmq.Context.instance() + sock = ctx.socket(zmq.SUB) + sock.connect(self._ft_interrupt_addr) + topic_self = f"worker_{self.local_rank}".encode() + sock.setsockopt(zmq.SUBSCRIBE, topic_self) + sock.setsockopt(zmq.SUBSCRIBE, b"all") + sock.setsockopt(zmq.RCVTIMEO, 1000) + + while not self._ft_shutdown: + try: + _, payload = sock.recv_multipart() + except zmq.Again: + continue + except zmq.ZMQError: + break + cmd_str = payload.decode("utf-8", errors="replace") + try: + cmd = InterruptCommand(cmd_str) + except ValueError: + logger.warning("unknown FT interrupt cmd: %s", cmd_str) + continue + if cmd is InterruptCommand.ABORT_COMMUNICATOR: + self._abort_nccl_communicators() + + with suppress(Exception): + sock.close(linger=0) + + def _abort_nccl_communicators(self) -> None: + """Abort all FT-aware comm groups so the main thread errors out + of NCCL and becomes responsive again. Called from the aux thread. + + Best-effort: a failure on one group does not stop the others — we + only need ANY communicator to abort to unstick the main thread. + """ + groups = [] + for fn in (get_dp_group, get_ep_group, get_tp_group): + try: + groups.append(fn()) + except AssertionError: + # Group not initialized on this worker (EP only for MoE). + continue + for group in groups: + comm = getattr(group, "device_communicator", None) + if comm is None: + continue + abort = getattr(comm, "abort", None) + if abort is None: + continue + try: + abort() + except RuntimeError: + logger.exception("communicator abort failed; continuing") + def init_worker_distributed_environment( vllm_config: VllmConfig,