Skip to content

vllm.entrypoints.serve.flash_epscale.api_router

_PostResizeError

Bases: RuntimeError

A failure after the resize is live: the new EP topology is serving, only the post-resume memory release failed. Callers must not roll back routing to the old size.

Source code in vllm/entrypoints/serve/flash_epscale/api_router.py
class _PostResizeError(RuntimeError):
    """A failure after the resize is live: the new EP topology is serving,
    only the post-resume memory release failed. Callers must not roll back
    routing to the old size."""

_paused(client, timing) async

Stop-the-world only around the steps that require global quiescence (NCCL split, EPLB remap/refill, NIXL reconnect). Always attempts resume on exit; resume failures propagate so the endpoint cannot report false success.

Source code in vllm/entrypoints/serve/flash_epscale/api_router.py
@asynccontextmanager
async def _paused(client: EngineClient, timing: dict[str, float]):
    """Stop-the-world only around the steps that require global quiescence
    (NCCL split, EPLB remap/refill, NIXL reconnect). Always attempts resume
    on exit; resume failures propagate so the endpoint cannot report false
    success."""
    logger.info("flash_epscale: entering pause_generation(mode=wait)")
    async with _timed(timing, "pause"):
        await client.pause_generation(mode="wait", clear_cache=False)
    # Free cached-but-unused activation blocks so the weight transfers in
    # the window have headroom. Best-effort: the cache refills lazily.
    try:
        await _rpc(client, timing, "empty_cache", "empty_cache")
    except Exception:
        logger.warning("flash_epscale: empty_cache failed (ignored)", exc_info=True)
    try:
        yield
    finally:
        logger.info("flash_epscale: entering resume_generation")
        async with _timed(timing, "resume"):
            await client.resume_generation()

_scale_down(client, *, target_ep_size, active_ep_size, target_sleeping, current_sleeping, tags, drain_timeout, timing, level=1) async

Shrink the active EP set.

Routing shrinks first so active ranks keep serving while the soon-to-sleep ranks drain; only the collective steps run inside the pause window (see _transition).

Source code in vllm/entrypoints/serve/flash_epscale/api_router.py
async def _scale_down(
    client: EngineClient,
    *,
    target_ep_size: int,
    active_ep_size: int,
    target_sleeping: list[int],
    current_sleeping: list[int],
    tags: list[str],
    drain_timeout: float,
    timing: dict[str, float],
    level: int = 1,
) -> None:
    """Shrink the active EP set.

    Routing shrinks first so active ranks keep serving while the
    soon-to-sleep ranks drain; only the collective steps run inside the
    pause window (see ``_transition``).
    """
    try:
        async with _timed(timing, "route_shrink"):
            client.set_active_data_parallel_size(target_ep_size)
        # Reroute eligible in-flight requests off the soon-to-sleep ranks
        # onto the active prefix. Best-effort: requests that cannot be
        # safely re-issued (n>1, pooling, streaming input, non-DELTA
        # output) fall through to the drain step below.
        async with _timed(timing, "reroute"):
            rerouted = await client.reroute_inflight_to_active(target_sleeping)
        timing["reroute_count"] = float(len(rerouted))
        async with _timed(timing, "drain"):
            await client.wait_for_dp_ranks_to_drain(target_sleeping, drain_timeout)
        await _transition(
            client,
            current_sleeping=current_sleeping,
            target_sleeping=target_sleeping,
            tags=tags,
            level=level,
            timing=timing,
        )
    except Exception as e:
        # Restore routing so requests are not stranded — unless the resize
        # is already live, in which case the shrunk routing is correct.
        if not isinstance(e, _PostResizeError):
            try:
                client.set_active_data_parallel_size(active_ep_size)
            except Exception:
                logger.exception("flash_epscale scale_down route restore failed")
        logger.exception("flash_epscale scale_down failed")
        raise HTTPException(
            status_code=500, detail=f"flash_epscale scale_down failed: {e}"
        ) from e

_scale_up(client, *, target_ep_size, target_sleeping, current_sleeping, tags, timing, level=1) async

Grow the active EP set.

Routing opens to the new ranks only after the transition completes, so requests never reach a rank that is not ready.

Source code in vllm/entrypoints/serve/flash_epscale/api_router.py
async def _scale_up(
    client: EngineClient,
    *,
    target_ep_size: int,
    target_sleeping: list[int],
    current_sleeping: list[int],
    tags: list[str],
    timing: dict[str, float],
    level: int = 1,
) -> None:
    """Grow the active EP set.

    Routing opens to the new ranks only after the transition completes, so
    requests never reach a rank that is not ready.
    """
    try:
        await _transition(
            client,
            current_sleeping=current_sleeping,
            target_sleeping=target_sleeping,
            tags=tags,
            level=level,
            timing=timing,
        )
    except Exception as e:
        logger.exception("flash_epscale scale_up failed")
        raise HTTPException(
            status_code=500, detail=f"flash_epscale scale_up failed: {e}"
        ) from e

    async with _timed(timing, "route_grow"):
        client.set_active_data_parallel_size(target_ep_size)

_transition(client, *, current_sleeping, target_sleeping, tags, level, timing) async

Move the EP sleep state from current_sleeping to target_sleeping (either direction).

Phases
  1. Pre-pause: rank-local CuMem wake of the currently sleeping ranks. No collectives, so active ranks keep serving; the woken ranks stay logically slept (and skip forwards) until the resize below.
  2. Pause window: everything that must not interleave with forward collectives — NIXL reconnect, L2 dense/EPLB-map refill, EPLB expert remap + DP NCCL split, NIXL disconnect from new sleepers.
  3. Post-resume: rank-local CuMem sleep + NIXL buffer destroy on the new sleeping ranks. They are masked and skipped by then, so active ranks serve while the memory is released.

Failures in phase 1/2 roll back to current_sleeping best-effort. Phase 3 failures raise _PostResizeError: the resize is live and must not be rolled back; only the memory release failed.

Source code in vllm/entrypoints/serve/flash_epscale/api_router.py
async def _transition(
    client: EngineClient,
    *,
    current_sleeping: list[int],
    target_sleeping: list[int],
    tags: list[str],
    level: int,
    timing: dict[str, float],
) -> None:
    """Move the EP sleep state from ``current_sleeping`` to
    ``target_sleeping`` (either direction).

    Phases:
      1. Pre-pause: rank-local CuMem wake of the currently sleeping ranks.
         No collectives, so active ranks keep serving; the woken ranks stay
         logically slept (and skip forwards) until the resize below.
      2. Pause window: everything that must not interleave with forward
         collectives — NIXL reconnect, L2 dense/EPLB-map refill, EPLB
         expert remap + DP NCCL split, NIXL disconnect from new sleepers.
      3. Post-resume: rank-local CuMem sleep + NIXL buffer destroy on the
         new sleeping ranks. They are masked and skipped by then, so
         active ranks serve while the memory is released.

    Failures in phase 1/2 roll back to ``current_sleeping`` best-effort.
    Phase 3 failures raise ``_PostResizeError``: the resize is live and
    must not be rolled back; only the memory release failed.
    """
    if current_sleeping:
        try:
            await _rpc(
                client,
                timing,
                "wake",
                "wake_up_ep_ranks",
                sleeping_ep_ranks=current_sleeping,
                tags=tags,
                level=level,
            )
        except Exception:
            try:
                await _sleep_ranks(
                    client, timing, "rollback_sleep", current_sleeping, tags, level
                )
            except Exception:
                logger.exception("flash_epscale wake rollback failed")
            raise

    if target_sleeping:
        # Pre-pin the host backup buffers the post-resume sleep will
        # offload into, while the soon-to-sleep ranks are already drained.
        # Best-effort: the sleep itself pins on demand if this fails.
        try:
            await _rpc(
                client,
                timing,
                "warm_backup",
                "warm_sleep_backup",
                sleeping_ep_ranks=target_sleeping,
                tags=tags,
                level=level,
            )
        except Exception:
            logger.warning(
                "flash_epscale: warm_sleep_backup failed (ignored)", exc_info=True
            )

    async with _paused(client, timing):
        try:
            if current_sleeping:
                # Restore NIXL all2all state before the refill/resize:
                # destroyed-buffer ranks rebuild, live ranks reconnect.
                await _rpc(
                    client,
                    timing,
                    "nixl_ensure",
                    "ensure_nixl_buffer",
                    sleeping_ep_ranks=current_sleeping,
                )
                if level == 2:
                    # L2 discarded weights with no CPU backup; refill dense
                    # weights and EPLB maps from active peers (collective).
                    await _rpc(
                        client,
                        timing,
                        "l2_refill",
                        "finalize_l2_wake",
                        sleeping_ep_ranks=current_sleeping,
                    )
            await _rpc(
                client,
                timing,
                "resize",
                "resize_sleep_ep_ranks",
                sleeping_ep_ranks=target_sleeping,
            )
            if target_sleeping:
                # Alive ranks must forget the sleeping peers' NIXL endpoints
                # now, or a later wake hangs in the connect handshake. Cheap
                # and touches the live agents, so it stays in the window.
                await _rpc(
                    client,
                    timing,
                    "nixl_disconnect",
                    "disconnect_nixl_from_sleeping",
                    sleeping_ep_ranks=target_sleeping,
                )
        except Exception:
            # Still inside the pause window: collectives are safe here.
            try:
                async with _timed(timing, "rollback"):
                    await client.collective_rpc(
                        "resize_sleep_ep_ranks",
                        kwargs={"sleeping_ep_ranks": current_sleeping},
                    )
                    if current_sleeping:
                        await client.collective_rpc(
                            "sleep_ep_ranks_by_tags",
                            kwargs={
                                "sleeping_ep_ranks": current_sleeping,
                                "tags": tags,
                                "level": level,
                            },
                        )
            except Exception:
                logger.exception("flash_epscale rollback failed")
            raise

    if not target_sleeping:
        return
    try:
        await _sleep_ranks(client, timing, "sleep", target_sleeping, tags, level)
        if os.environ.get("VLLM_FLASH_EPSCALE_SKIP_NIXL_TEARDOWN") == "1":
            logger.info(
                "flash_epscale: skipping NIXL buffer destroy (env override); "
                "disconnect already applied"
            )
        else:
            try:
                await _rpc(
                    client,
                    timing,
                    "nixl_destroy",
                    "destroy_nixl_buffer",
                    sleeping_ep_ranks=target_sleeping,
                )
            except Exception:
                logger.warning(
                    "flash_epscale: nixl destroy failed (ignored)", exc_info=True
                )
    except Exception as e:
        raise _PostResizeError(
            f"resize to sleeping={target_sleeping} is live, but releasing "
            f"memory on the sleeping ranks failed: {e}"
        ) from e