第 18 篇 主流推理引擎第 2 讲 / 共 6 讲

第136讲vLLM 的分布式服务

第 135 讲读的是“一个 EngineCore”:一个调度器、一个执行器、几张卡。真实的线上服务往往大得多:模型要跨好几张卡做张量并行;为了吞吐,同一个模型要部署好几个副本,分布在多台机器上;做 PD 分离时,prefill 和 decode 还是两组不同的实例,KV 要在它们之间搬运。

这一讲把视野放大到整个服务,跟着一条 curl 请求走一遍:它先到哪台机器、怎么在几个副本里挑一个、在副本里怎么分给几张卡、MoE 模型的副本之间为什么要“锁步”、PD 分离时 KV 怎么从一个实例到另一个实例。每一层都对应第 14 篇讲过的一个原理(数据并行、专家并行、PD 分离、KV 传输、缓存感知路由),这一讲看它们在 vLLM 里是怎么写出来的。

第一层:一个副本里的几张卡

先回到单个副本。第 135 讲提到,EngineCore 通过执行器(Executor)让 worker 跑模型。一个副本用 4 张卡做张量并行时,执行器是 MultiprocExecutor:每张卡一个 worker 进程,EngineCore 每一步把调度结果广播给它们。

这件事 nano-vllm 也做过(第 133 讲):rank 0 把“方法名 + 参数”pickle 后写进 1 MiB 的共享内存,再用事件通知其他进程。vLLM 的做法是同一个思路的工程化版本:

third_party/vllm/vllm/v1/executor/multiproc_executor.py 第 471–540 行 / 共 1294 行
    def collective_rpc(  # type: ignore[override]
        self,
        method: str | Callable,
        timeout: float | None = None,
        args: tuple = (),
        kwargs: dict | None = None,
        non_block: bool = False,
        unique_reply_rank: int | None = None,
        kv_output_aggregator: KVOutputAggregator | None = None,
        ec_output_aggregator: ECOutputAggregator | None = None,
    ) -> Any:
        """Returns single result if unique_reply_rank and/or an output
        aggregator is provided, otherwise list."""
        assert self.rpc_broadcast_mq is not None, (
            "collective_rpc should not be called on follower node"
        )
        if self.is_failed:
            raise RuntimeError("Executor failed.")

        deadline = None if timeout is None else time.monotonic() + timeout
        kwargs = kwargs or {}

        aggregators = [a for a in (kv_output_aggregator, ec_output_aggregator) if a]
        aggregate: Callable[[Any], Any]
        if aggregators:
            output_rank = None

            def _aggregate(outputs: Any) -> Any:
                # Each aggregator merges its own connector's output onto
                # outputs[output_rank] in place and returns it, so chaining is safe.
                rank = unique_reply_rank or 0
                result = outputs[rank]
                for a in aggregators:
                    result = a.aggregate(outputs, output_rank=rank)
                return result

            aggregate = _aggregate
        else:
            output_rank = unique_reply_rank
            aggregate = lambda x: x

        if isinstance(method, str):
            send_method = method
        else:
            send_method = cloudpickle.dumps(method, protocol=pickle.HIGHEST_PROTOCOL)
        self.rpc_broadcast_mq.enqueue((send_method, args, kwargs, output_rank))

        response_mqs: Sequence[MessageQueue] = self.response_mqs
        if output_rank is not None:
            response_mqs = (response_mqs[output_rank],)

        def get_response():
            responses = []
            has_failure = False

            for mq in response_mqs:
                dequeue_timeout = (
                    None if deadline is None else max(0.0, deadline - time.monotonic())
                )
                try:
                    status, result = mq.dequeue(timeout=dequeue_timeout)
                except TimeoutError as e:
                    raise TimeoutError(f"RPC call to {method} timed out.") from e

                if status == WorkerProc.ResponseStatus.FAILURE_WITH_KV_OUTPUT:
                    if (
                        not self.vllm_config.parallel_config.enable_fault_tolerance
                        or self.is_failed
                    ):
                        raise RuntimeError("Worker failed with KV connector output")
  1. collective_rpc 让所有 worker 执行同一个方法(execute_model、sample_tokens 等都是通过它调用的)。unique_reply_rank 指定只要哪个 worker 的返回值。

  2. 通常只需要一个 worker 的结果(张量并行时各卡算出的 token 一样)。但如果配置了 KV connector,每个 worker 各自负责自己那部分 KV 的传输,传输状态要从所有 worker 收齐再合并,这时就要等所有 worker 回复。

  3. 方法名、参数和“由谁回复”打包成一个元组,写进 rpc_broadcast_mq。这是一个基于共享内存的环形消息队列(vllm/distributed/device_communicators/shm_broadcast.py):一次写入,所有 worker 都能读到,不用逐个发送。

  4. 每个 worker 有自己的回复队列。只需要一个结果时,只读那一个队列,其余 worker 算完了也不回复,省掉了把同样的结果序列化好几遍。

谁来回复?第 683–697 行的 _get_output_rank 给出了答案:最后一个流水线阶段里张量并行编号为 0 的那个 worker。只有最后一个流水线阶段算出了打分,而同一阶段里各张卡的结果相同,取第一张就够了。worker 那边是一个死循环(第 1188–1218 行):从广播队列取出调用,执行,如果自己就是指定回复的那一个,就把结果写进自己的回复队列。

和 nano-vllm 相比,差别在细节上:环形队列让 EngineCore 可以连续发出几步(流水线并行、异步调度时需要),不用等上一步的读者读完;回复只走一条队列;所有 worker 共享同一个广播写入,而不是 pickle 一次、通知 N 次。

第二层:多个副本

模型放进 4 张卡以后,想要更高的吞吐,就部署更多副本:数据并行(DP)。博客里的例子是两台 8 卡的机器、4 个副本、每个副本张量并行 4 卡。在 vLLM 里这样启动(两台机器各运行一次):

# 节点 A:带 API 服务器,副本 0、1
vllm serve <model> --tensor-parallel-size 4 --data-parallel-size 4 --data-parallel-size-local 2 \
  --data-parallel-start-rank 0 --data-parallel-address <节点 A 的 IP> --data-parallel-rpc-port 13345
# 节点 B:只跑引擎,副本 2、3
vllm serve <model> --tensor-parallel-size 4 --data-parallel-size 4 --data-parallel-size-local 2 \
  --data-parallel-start-rank 2 --data-parallel-address <节点 A 的 IP> --data-parallel-rpc-port 13345 --headless
两个节点、4 个数据并行副本:一个请求怎么找到它的引擎
图 136-1 两个节点、4 个数据并行副本。节点 A 上有 API 服务器、负载均衡的客户端和 DP 协调器;节点 B 不带 API 服务器(headless),只跑两个副本。点“下一步”看一个请求的路径。

非 MoE 和 MoE 是两回事

博客写作时,vLLM 的数据并行副本一律“锁步”运行(下一节讲锁步是什么)。现在的代码把两种情况分开了:

third_party/vllm/vllm/v1/engine/core.py 第 1718–1728 行 / 共 3143 行
            parallel_config.data_parallel_index = dp_rank
            if data_parallel and vllm_config.model_config.is_moe:
                # Set data parallel rank for this engine process.
                parallel_config.data_parallel_rank = dp_rank
                engine_core = DPEngineCoreProc(*args, **kwargs)
            else:
                # Non-MoE DP ranks are completely independent, so treat like DP=1.
                # Note that parallel_config.data_parallel_index will still reflect
                # the original DP rank.
                parallel_config.reconfigure_for_independent_dp_rank()
                engine_core = EngineCoreProc(*args, engine_index=dp_rank, **kwargs)
  1. MoE 模型的专家层要跨副本做专家并行(第 108、111 讲):每一步前向里都有 All-to-All,所有副本必须一起参加。所以 MoE 模型的每个副本是一个 DPEngineCoreProc,它们之间有一个通信组,步调一致。

  2. 普通的稠密模型,各副本之间没有任何通信,所以直接当成数据并行度为 1 的独立引擎(reconfigure_for_independent_dp_rank),只保留一个编号用于负载均衡。这和“启动几个互不相干的 vLLM 实例,前面放一个负载均衡器”在效果上是一样的,只是由 vLLM 自己来管。

前端用哪种客户端

API 服务器里的 AsyncLLM 通过一个“引擎核心客户端”和 EngineCore 通信(第 135 讲)。数据并行时,选哪种客户端决定了谁来做负载均衡:

third_party/vllm/vllm/v1/engine/core_client.py 第 153–186 行 / 共 2252 行
    def make_async_mp_client(
        vllm_config: VllmConfig,
        executor_class: type[Executor],
        log_stats: bool,
        client_addresses: dict[str, Any] | None = None,
        client_count: int = 1,
        client_index: int = 0,
        renderer: BaseRenderer | None = None,
    ) -> "AsyncMPClient":
        parallel_config = vllm_config.parallel_config
        client_args = (
            vllm_config,
            executor_class,
            log_stats,
            client_addresses,
            client_count,
            client_index,
        )
        if parallel_config.data_parallel_size > 1:
            if parallel_config.data_parallel_external_lb:
                # External load balancer - client per DP rank.
                return DPAsyncMPClient(
                    *client_args,
                    renderer=renderer,
                )
            # Internal load balancer - client balances to all DP ranks.
            return DPLBAsyncMPClient(
                *client_args,
                renderer=renderer,
            )
        return AsyncMPClient(
            *client_args,
            renderer=renderer,
        )
  1. --data-parallel-external-lb:每个副本配一个自己的 API 服务器,由 vLLM 之外的负载均衡器(比如 Kubernetes 的 Service)在副本之间分请求。适合“一个 Pod 一个副本”的大规模 MoE 部署。

  2. DPLBAsyncMPClient:一个前端连着所有副本,自己决定每个请求发给谁。上面的两节点例子就是这种。

    两者之间还有一种“混合”模式(--data-parallel-hybrid-lb):每个节点一个前端,只在本节点的副本之间分;节点之间再由外部负载均衡器分。

  3. 没有数据并行时就是普通的 AsyncMPClient。

第三层:挑哪个副本

内部负载均衡要回答一个问题:新请求来了,发给哪个副本?前端自己不知道各副本有多忙,需要有人告诉它。这个人就是 DP 协调器,一个单独的进程:

third_party/vllm/vllm/v1/engine/coordinator.py 第 23–54 行 / 共 464 行
class DPCoordinator:
    """Coordinator process used for data-parallel deployments (DP>1).

    Intermediates between multiple DP engine rank processes and one or more
    front-end API server processes.

    * Collects stats from each DP engine (currently just waiting and running
      queue lengths), and publishes these to all front-ends for use in
      load-balancing decisions.

    * Keeps track of the current DP "request wave" number and running state
      of the engines. This is received from the DP rank 0 engine and published
      to the front-end processes along with the current load stats.

      The engines alternate between a global running/paused state. The global
      "request wave" number is a count of the number of times that the workers
      collectively move from a running state to a paused state. This transition
      is synchronized via the all-reduce operation performed in the
      DPEngineCoreProc._has_global_unfinished_reqs method.

    * Broadcasts the START_DP_WAVE message to engines to move them from paused
      to running state when an idle engine receives a new request and notifies
      the coordinator. Only the engines start waves: a front-end's view of the
      running state can be stale, and a paused engine discards START_DP_WAVE.

    Engines will move into running state when receiving a new request or
    START_DP_WAVE message.

    Note that when deployed in External LB mode, no stats will be published by
    the engines and thus updates will only be sent to front-ends when the
    request wave / running state changes.
    """
  1. 每个副本把自己的等待数、运行数(以及 KV 占用率)发给协调器,协调器合并后发布给所有前端。发布的间隔最小 100 ms(min_stats_update_interval_ms)。

  2. MoE 的副本们要么一起运行、要么一起暂停。从“运行”到“全部空闲、暂停”算一个波次。新请求到达一个暂停中的副本时,由这个副本通知协调器,协调器再广播 START_DP_WAVE,把其余副本叫醒。下一节细讲。

前端订阅协调器的发布(core_client.py 第 1599–1674 行的 run_engine_stats_update_task):它总是把积压的消息读空,只保留最新的一份快照,存在 self.lb_engines 里。每来一个请求,add_request_async(第 1676–1687 行)先挑副本,再把请求发过去。挑副本的代码:

third_party/vllm/vllm/v1/engine/core_client.py 第 1818–1879 行 / 共 2252 行
    def get_core_engine_for_request(self, request: EngineCoreRequest) -> EngineIdentity:
        if request.resumable:
            self.streaming_reqs.add(request.request_id)
        else:
            # Also removes a session on its final (end-of-stream) request.
            self.streaming_reqs.discard(request.request_id)

        if (engine := self.reqs_in_flight.get(request.request_id)) is not None:
            # This is for streaming-input session affinity.
            return engine

        # Engines are in rank order.
        if (eng_index := request.data_parallel_rank) is None and (
            eng_index := get_late_interaction_engine_index(
                request.pooling_params, len(self.core_engines)
            )
        ) is None:
            current_counts = self.lb_engines
            # TODO use P2C alg for larger DP sizes
            num_engines = len(current_counts)
            min_score: float = sys.maxsize
            eng_index = 0
            for i in range(num_engines):
                # Start from client_index to help with balancing when engines
                # are empty.
                idx = (self.eng_start_index + i) % num_engines
                waiting, running, kv_cache_usage = current_counts[idx]
                # Estimate engine load as the greater of the coordinator's
                # latest (waiting + running) snapshot and this client's own
                # in-flight count (scaled by the number of clients). The
                # in-flight floor is exact and can't be erased by a snapshot
                # rebind, so a burst spreads round-robin even when snapshots
                # race with routing decisions; the snapshot raises the score
                # when other clients or stale requests load the engine.
                inflight = self.engine_inflight[self.core_engines[idx]]
                score: float = max(self.client_count * inflight, waiting + running)
                if waiting:
                    # Waiting requests are penalized in proportion to KV cache
                    # pressure: a queue on a KV-bound engine drains slowly, so
                    # new requests should strongly prefer other engines. With
                    # low KV usage the queue is transient (e.g. mid-burst) and
                    # the penalty stays off, preserving exact round-robin.
                    # Ramps from 0 at <=50% usage to 3x waiting at 100%.
                    score += waiting * 6.0 * max(0.0, kv_cache_usage - 0.5)
                if score < min_score:
                    min_score = score
                    eng_index = idx
            # Increment local waiting count for better balancing between stats
            # updates from the coordinator (which happen every 100ms).
            current_counts[eng_index][0] += self.client_count
            # Rotate the scan start so that ties (equal scores, e.g. right
            # after a coordinator stats reset when engines look equally loaded)
            # don't systematically favor the same engine. This removes the
            # fixed tie-break bias without affecting load-aware decisions when
            # scores actually differ.
            self.eng_start_index = (self.eng_start_index + 1) % num_engines

        chosen_engine = self.core_engines[eng_index]
        # Record which engine is chosen for this request, to handle aborts.
        self.reqs_in_flight[request.request_id] = chosen_engine
        self.engine_inflight[chosen_engine] += 1
        return chosen_engine
  1. 流式输入的会话(请求分几次送进来)要一直发给同一个副本,它的 KV 在那里。

  2. current_counts 是协调器最近一次发来的快照:每个副本的 [等待数, 运行数, KV 占用率]。从一个轮转的起点开始,逐个打分。

  3. 基础分是两个数里较大的那个:快照里的“等待 + 运行”,以及这个前端自己发给这个副本、还没完成的请求数(乘以前端的个数,粗略地代表所有前端)。

    为什么要后者:快照最快 100 ms 才更新一次,而且在某些时刻会被整体重置(注释里说的 snapshot rebind)。自己记的在途数是精确的、不会被重置,保证一阵突发至少能按轮询的方式摊开。

  4. 副本有排队时,按 KV 占用率加罚分:占用率 50% 以下不罚,到 100% 时罚到等待数的 3 倍。道理写在注释里:KV 快满的副本,队列消化得慢(新请求要等别人的块释放),新请求应该尽量去别处;KV 还很空时排队只是暂时的,不罚,保持轮询。

    博客里的公式是 等待数 × 4 + 运行数,现在的规则是在实践中一步步改出来的。

  5. 选中的副本,在本地快照里把等待数加上前端的个数。下一份快照到来之前,后面的请求就会看到这个副本“又多了一个”,不会都扎堆过去。

    最后轮转起点:分数相同时(比如所有副本都空闲),不会总是偏向同一个副本。

  6. 取消请求时要发给对的副本;在途计数也在这里加一。

这几条规则各自防的是什么,用一个小模型看得最清楚:

前端怎么在 4 个副本之间分请求
图 136-2 4 个副本、两阵突发的简化模型(不是 vLLM 的实测,规则见组件说明)。点“只看快照”:同一份快照里最空的副本会在 100 ms 内吃下整阵突发,平均排队 497 ms;打开“本地计数”就降到 123 ms。再把快照间隔拉长,看两种设置各自怎么变化。

在这个模型里,作用最大的是本地计数:它消除了“一份旧快照被用很多次”带来的扎堆。在途下限和 KV 罚分的作用在这里不明显,因为模型只有一个前端、快照从不被重置,各副本的请求组成也差不多;它们针对的是多个前端同时分请求、快照和路由决策互相赛跑、个别副本 KV 吃紧这些真实部署里的情况。这也是读这类代码的一个经验:每一条看起来多余的规则,背后往往对应一个线上出过的问题,去翻它的提交记录(第 139 讲)就能找到。

第四层:MoE 副本的锁步

对稠密模型,副本选好就结束了。MoE 模型多了一个约束:所有副本必须一起前向。专家层的 All-to-All 是一个集合通信,每个副本都必须参加;只要有一个副本在算,其余副本就算没有请求,也要跑一个“空批次”陪着,否则正在算的副本会卡在 All-to-All 上等。

third_party/vllm/vllm/v1/engine/core.py 第 2745–2830 行 / 共 3143 行
    def run_busy_loop(self):
        """Core busy loop of the EngineCore for data parallel case."""
        # Loop until process is sent a SIGINT or SIGTERM
        while self._handle_shutdown():
            # 1) Poll the input queue until there is work to do.
            was_running = self.engines_running
            self._process_input_queue()
            # Publish request counts before and after GPU step to ensure freshness.
            self._maybe_publish_request_counts()

            if self.eep_scaling_state is not None:
                state = self.eep_scaling_state
                if state.commit_requested or not state.is_ready_for_switch():
                    state.progress()
                if state.is_complete():
                    if state.worker_type == "removing":
                        raise SystemExit
                    if (
                        state.worker_type == "new"
                        and self.vllm_config.parallel_config.data_parallel_external_lb
                    ):
                        # An independently launched rank has no external utility
                        # caller to join the post-commit resume barrier.
                        self.resume_scheduler()
                    self.process_input_queue_block = True
                    self.eep_scaling_state = None
                elif not state.commit_requested and state.is_ready_for_switch():
                    self.process_input_queue_block = True

            executed = self._process_engine_step()
            self._maybe_publish_request_counts()

            local_unfinished_reqs = self.scheduler.has_unfinished_requests()
            if not executed:
                if not local_unfinished_reqs and not self.engines_running:
                    # All engines are idle.
                    continue

                # Execute a dummy pass when no ready requests ran, unless the
                # engine is sleeping.
                elif not self.model_executor.is_sleeping:
                    with self.capture_iteration_details(None) as iteration_details:
                        self.execute_dummy_batch()
                    if iteration_details is not None and not self.has_coordinator:
                        stats = self._make_iteration_details_stats(iteration_details)
                        self.output_queue.put_nowait(
                            (0, EngineCoreOutputs(scheduler_stats=stats))
                        )

            # 3) All-reduce operation to determine global unfinished reqs.
            self.engines_running = self._has_global_unfinished_reqs(
                local_unfinished_reqs
            )

            if not self.engines_running:
                if self.dp_rank == 0 or not self.has_coordinator:
                    # Notify client that we are pausing the loop.
                    logger.debug(
                        "Wave %d finished, pausing engine loop.", self.current_wave
                    )
                    # In the coordinator case, dp rank 0 sends updates to the
                    # coordinator. Otherwise (offline spmd case), each rank
                    # sends the update to its colocated front-end process.
                    client_index = -1 if self.has_coordinator else 0
                    self.output_queue.put_nowait(
                        (
                            client_index,
                            EngineCoreOutputs(wave_complete=self.current_wave),
                        )
                    )
                # Increment wave count and reset step counter.
                self.current_wave += 1
                self.step_counter = 0
            elif (
                not was_running
                and self.has_coordinator
                and self.dp_rank == 0
                and not self.pending_pause
            ):
                # Mirror of the wave_complete notification above: the
                # coordinator must observe this edge too rather than assume
                # that a START_DP_WAVE it sent was acted upon, since a paused
                # engine discards it.
                self.output_queue.put_nowait(
                    (-1, EngineCoreOutputs(start_wave=self.current_wave))
                )
  1. 和普通的 EngineCore 一样(第 135 讲),先处理输入队列,再执行一步。发布负载的数字给协调器用。

  2. 这一步没有执行任何请求时:如果自己没有未完成的请求、整个组也处于暂停状态,就什么都不做;否则(别的副本还在跑)执行一个空批次 execute_dummy_batch,参与这一步的集合通信。

  3. 用一次 All-Reduce 问所有副本:还有谁有未完成的请求?见下面的 sync_dp_state。

  4. 全部副本都空闲了:暂停循环,由 0 号副本通知协调器“第 N 波结束”,波次编号加一。之后各副本停在等待输入的地方,不再陪跑空批次,GPU 就真正空闲下来。

  5. 从暂停变成运行时(某个副本收到了新请求),0 号副本告诉协调器新波次开始了。协调器再广播 START_DP_WAVE,叫醒还在暂停的副本。

“大家都空了吗”这个问题本身也有代价:每次都要做一次跨副本的 All-Reduce。现在的代码不再每一步都问:

third_party/vllm/vllm/config/parallel.py 第 966–991 行 / 共 1443 行
    def sync_dp_state(
        self, dp_group: ProcessGroup, has_unfinished: bool, pending_pause: bool
    ) -> tuple[bool, bool]:
        """Combined all-reduce for DP state synchronization.

        Uses a single SUM all-reduce on a 2-element tensor:
          [0] = 1 if this rank has unfinished work, else 0.
                SUM > 0 ≡ logical OR across ranks → any rank has work.
          [1] = 1 if this rank has a pending pause request, else 0.
                SUM == dp_size ≡ all ranks reached pause consensus.

        has_unfinished_global is true if any rank has unfinished work,
        or if some ranks are waiting for a pause consensus.

        Returns:
            (has_unfinished_global, pause_consensus)

        """
        tensor = torch.tensor(
            [int(has_unfinished), int(pending_pause)], dtype=torch.int32, device="cpu"
        )
        cpu_all_reduce_(tensor, dp_group, timeout=self.cpu_distributed_timeout)
        dp_size = dp_group.size()
        pause_count = tensor[1].item()
        has_unfinished_global = tensor[0].item() > 0 or pause_count % dp_size != 0
        return has_unfinished_global, pause_count == dp_size
  1. 一个两元素的张量做求和:第 0 个元素是“我有没有未完成的请求”,求和大于 0 就说明有人在忙;第 1 个元素是“我是否想暂停”(比如要重新加载权重),求和等于副本数才算全体同意。两件事合成一次通信。

  2. 这个 All-Reduce 走 CPU 的通信组(cpu_all_reduce_),不占 GPU 的通信资源。

调用它的 _has_global_unfinished_reqs(core.py 第 2834 行起)只在一个波次的第 1 步和之后每 dp_sync_interval 步(默认 16)真正同步一次,其余步直接当作“还有人在忙”。代价是:所有副本都空闲后,最多还要多陪跑十几个空批次才停下来;换来的是正常运行时每 16 步才同步一次,而不是每一步都多一次跨机器的通信。

第五层:PD 分离时,KV 从哪里来

第 112 讲讲了 PD 分离的原理,第 113 讲讲了 KV 的传输和分层存储。在 vLLM 里,这些都通过一个接口接进来:KV connector。它的接口文件开头就把全部方法列了出来:

third_party/vllm/vllm/distributed/kv_transfer/kv_connector/v1/base.py 第 3–40 行 / 共 824 行
"""KVConnectorBase_V1 Class for Distributed KV Cache & Hidden State
communication in vLLM v1

The class provides the following primitives:
    Scheduler-side: runs in the scheduler, binds metadata, which
    is used by the worker-side to load/save KV cache.
        get_num_new_matched_tokens() - get number of new tokens
            that exist in the remote KV cache. Might be called multiple
            times for a given request and should be side-effect free.
        update_state_after_alloc() - update KVConnector state after
            temporary buffer alloc by the CacheManager.
        update_connector_output() - update KVConnector state after
            output is received from worker-side connectors.
        request_finished() - called once when a request is finished,
            with the computed kv cache blocks for the request.
            Returns whether KV cache should be freed now or if the
            connector now assumes responsibility for freeing the
            the blocks asynchronously. Also optionally returns KV
            transfer params.
        take_events() - returns new KV events that were collected
            by the connector since the last call.

    Worker-side: runs in each worker, loads/saves KV cache to/from
    the Connector based on the metadata.
        handle_preemptions() - called for handling preempted requests
            or request evicted blocks before they are overwritten

        start_load_kv() - starts loading all KVs (maybe async)
        wait_for_layer_load() - blocks until layer i load is done

        save_kv_layer() - starts saving KV for layer i (maybe async)
        wait_for_save() - submits saves and performs required synchronization

        get_transfer_results() - returns async send/receive completions and
            receive failures in one snapshot.
        build_connector_worker_meta() - builds metadata to be sent
            back to the scheduler-side connector
"""
  1. 在 EngineCore 进程里,和调度器一起工作:

    • get_num_new_matched_tokens:这个请求在外部(另一个实例、CPU 内存、远端存储)还有多少个 token 的 KV。可能被调用多次,必须没有副作用。
    • update_state_after_alloc:调度器为这些外部 token 分好块之后,告诉 connector 往哪些块里写。
    • request_finished:请求结束时决定块是马上释放,还是由 connector 负责稍后释放(等对方把 KV 取走),并可返回 KV 的位置信息。

    此外还有 build_connector_meta(第 602 行):每一步调度结束时,把这一步要加载、要保存的信息打包进 SchedulerOutput,随调度结果一起发给 worker。

  2. 在每个 worker 进程里,真正搬运数据:

    • start_load_kv / wait_for_layer_load:把外部的 KV 读进本地的块,可以整体读,也可以逐层等待(第 i 层的注意力算之前,只要第 i 层的 KV 到了就行)。
    • save_kv_layer / wait_for_save:把本地算出的 KV 发出去,同样可以逐层流水。
    • get_transfer_results:哪些请求的发送、接收已经完成,哪些失败了,汇报给调度器一侧。
PD 分离:KV 怎么从 prefill 实例到 decode 实例
图 136-3 PD 分离时一个请求的路径。prefill 实例和 decode 实例都是普通的 vLLM,只是配置了不同角色的 KV connector。

调度器一侧的调用点在 scheduler.py 里,等待队列放一个新请求进来时:

third_party/vllm/vllm/v1/core/sched/scheduler.py 第 1170–1190 行 / 共 3934 行
                        # Present a block-aligned local hit to the connector so
                        # a strictly longer remote hit can supersede a local
                        # sub-block tail without racing its copy-on-write.
                        partial_tail = num_new_local_computed_tokens % self.block_size
                        block_aligned_local = (
                            num_new_local_computed_tokens - partial_tail
                        )
                        ext_tokens, load_kv_async = (
                            self.connector.get_num_new_matched_tokens(
                                request, block_aligned_local
                            )
                        )
                        if request.skip_reading_external_kv:
                            ext_tokens, load_kv_async = 0, False

                        if ext_tokens is None:
                            # The request cannot be scheduled because
                            # the KVConnector couldn't determine
                            # the number of matched tokens.
                            skip_request(request_queue)
                            continue
  1. 先在本地前缀缓存里查到命中的部分(按块对齐),再问 connector:除了本地命中的,外部还能提供多少个 token 的 KV,以及要不要异步加载。PD 分离时,decode 实例在这里得知“整个提示的 KV 都在 prefill 实例那边”。

  2. connector 一时给不出答案(比如远端还没回复),这个请求这一步先不调度,留在队列里。

接下来,allocate_slots 的 num_external_computed_tokens 参数(第 135 讲那张块布局图里的 ext_comp 段)为这些外部 token 分好块,connector.update_state_after_alloc(第 1544 行)记下要写进哪些块;异步加载的请求进入“等远端 KV”的状态,加载完成后才进入运行队列。worker 一侧,在 GPU worker 里由一个小类包着:

third_party/vllm/vllm/v1/worker/gpu/kv_connector.py 第 62–166 行 / 共 194 行
class ActiveKVConnector(KVConnector):
    def __init__(
        self, vllm_config: VllmConfig, kv_caches_dict: dict[str, torch.Tensor]
    ):
        self.vllm_config = vllm_config
        self.kv_connector = get_kv_transfer_group()
        # Register kv caches with KV Connector if applicable.
        self.kv_connector.register_kv_caches(kv_caches_dict)
        self.kv_connector.set_host_xfer_buffer_ops(copy_kv_blocks)

        self._pending_load_kwargs: dict[str, Any] | None = None
        self._disabled = False

    def pre_forward(
        self,
        scheduler_output: "SchedulerOutput",
        input_batch: "InputBatch | None" = None,
        attn_metadata: dict[str, Any] | None = None,
    ) -> None:
        if self._disabled:
            return

        kv_connector_metadata = scheduler_output.kv_connector_metadata
        assert kv_connector_metadata is not None
        self.kv_connector.handle_preemptions(kv_connector_metadata)
        self.kv_connector.bind_connector_metadata(kv_connector_metadata)
        self._pending_load_kwargs = self._build_load_kwargs(
            scheduler_output, input_batch, attn_metadata
        )

        if scheduler_output.has_sync_kv_loads:
            # Sync loads need to run before this step's forward.
            self._start_load_kv()
        # Otherwise start the async load after forward to keep submission
        # off the critical path.

    @staticmethod
    def _build_load_kwargs(
        scheduler_output: "SchedulerOutput",
        input_batch: "InputBatch | None",
        attn_metadata: dict[str, Any] | None,
    ) -> dict[str, Any]:
        """Keyword args for the connector's start_load_kv()."""
        if input_batch is None:
            # No forward this step.
            return {}
        load_kwargs: dict[str, Any] = dict(
            scheduler_output=scheduler_output,
            request_state_indices=input_batch.idx_mapping,
            request_ids=input_batch.req_ids,
            num_tokens=input_batch.num_tokens,
        )
        if attn_metadata is not None:
            load_kwargs["attn_metadata"] = attn_metadata
        return load_kwargs

    def _start_load_kv(self) -> None:
        load_kwargs = self._pending_load_kwargs
        assert load_kwargs is not None
        self._pending_load_kwargs = None
        # TODO: sort out KV Connectors' use of forward_context
        if is_forward_context_available():
            self.kv_connector.start_load_kv(get_forward_context(), **load_kwargs)
        else:
            with set_forward_context(None, self.vllm_config):
                self.kv_connector.start_load_kv(get_forward_context(), **load_kwargs)

    def finish_forward(self) -> None:
        if not self._disabled:
            self.kv_connector.finish_forward()

    def reset_capture_state(self) -> None:
        self.kv_connector.reset_capture_state()

    def post_forward(
        self, finished_req_ids: set[str], defer_finalize: bool = False
    ) -> KVConnectorOutput | None:
        if self._disabled:
            return None

        if self._pending_load_kwargs is not None:
            self._start_load_kv()

        output = KVConnectorOutput()
        if not defer_finalize:
            self.kv_connector.wait_for_save()
        transfer_results = self.kv_connector.get_transfer_results(finished_req_ids)
        output.finished_sending = transfer_results.finished_sending or None
        output.finished_recving = transfer_results.finished_recving or None
        output.failed_recving = transfer_results.failed_recving
        output.invalid_block_ids = self.kv_connector.get_block_ids_with_load_errors()
        output.kv_connector_stats = self.kv_connector.get_kv_connector_stats()
        output.kv_cache_events = self.kv_connector.get_kv_connector_kv_cache_events()
        output.kv_connector_worker_meta = (
            self.kv_connector.build_connector_worker_meta()
        )
        if not defer_finalize:
            self.kv_connector.clear_connector_metadata()
        return output

    def finalize_step(self) -> None:
        if self._disabled:
            return
        self.kv_connector.wait_for_save()
        self.kv_connector.clear_connector_metadata()
  1. 初始化时,把每一层 KV Cache 的张量注册给 connector。传输后端(例如 NIXL)要知道这些显存的地址,才能直接用 RDMA 读写。

  2. 先处理被抢占的请求(它们的块马上要被别人覆盖,正在进行的传输要处理掉),再绑定这一步的 connector 元数据。

    同步加载(这一步就要用的 KV)在前向之前开始;异步加载(请求在等待 KV 期间不参与这一步)放到前向之后再发起,“让提交不挡在关键路径上”。博客描述的是进入前向时统一开始加载、退出时等待保存,现在按同步、异步分开处理了。

  3. 发起推迟的异步加载;wait_for_save 确认这一步该发出去的 KV 都已提交;再收集传输结果:哪些请求发完了、收完了、哪些失败了、哪些块加载出错。这些放进 KVConnectorOutput,随模型输出一起回到调度器,调度器据此把等 KV 的请求放进运行队列,或者释放 prefill 一侧的块。

具体的传输方式是不同的 connector 实现,都在 vllm/distributed/kv_transfer/kv_connector/v1/ 下:nixl/(NVIDIA 的 NIXL,GPU 之间点对点 RDMA)、mooncake/(Mooncake 的传输引擎)、lmcache_mp_connector.py(LMCache 的 KV 缓存层)、offloading_connector.py(卸载到 CPU 内存,即第 113 讲的分层存储)、multi_connector.py(同时用几种),以及一个用来理解接口的最简实现 example_connector.py(把 KV 存成本地文件)。博客里用的 SharedStorageConnector 在这个提交里已经不存在了,作用相同的是 example_connector.py。

合起来:一条 curl 的全程

把五层串起来,一条请求在“两个节点、4 个 MoE 副本、每副本 4 卡”的部署里:

  1. API 服务器(entrypoints/openai/completion/serving.py 的 create_completion)收到请求,AsyncLLM.generate 分词、建输出流。
  2. 挑副本:DPLBAsyncMPClient.get_core_engine_for_request 用协调器的快照、本地计数、在途数和 KV 压力打分,选中比如副本 2;本地快照里副本 2 的等待数加一。
  3. 发过去:经 ZMQ 发到节点 B 上副本 2 的输入线程,放进输入队列。如果副本组正处于暂停,副本 2 醒来并通知协调器,协调器广播 START_DP_WAVE 叫醒其余副本。
  4. 调度:副本 2 的调度器为它分配 token 和块(第 135 讲);PD 分离时先问 connector 外部有多少 KV。
  5. 执行:MultiprocExecutor 把调度结果写进共享内存广播队列,4 个 worker 一起前向;MoE 的专家层和其他 3 个副本做 All-to-All(没有请求的副本跑空批次陪着);输出 rank 把采样结果写回。
  6. 更新:调度器接上新 token、判断结束;副本把新的负载数字发给协调器,协调器发布给前端。
  7. 返回:副本 2 的输出线程把结果发回节点 A,AsyncLLM 的输出任务反分词、分发到这个请求的输出流,FastAPI 流式推给客户端。

回顾

这一讲从一个副本的几张卡,一路放大到多节点、多副本和 PD 分离。几个要记住的取舍:回复只走一个 worker,省掉重复的序列化;稠密模型的副本互不通信,MoE 的副本必须锁步;负载均衡依赖 100 ms 一次的旧快照,靠本地计数和在途数补偿;全局同步每 16 步一次,用少量空跑换掉大量通信;异步的 KV 加载挪到前向之后,不挡关键路径。这些细节和一年前的博客已经不同,读源码时要以手上的那个提交为准。

下一讲换一个引擎:SGLang 怎么用一棵基数树做前缀缓存,怎么让调度和执行重叠。下一讲:SGLang 的架构。