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

第135讲vLLM 的架构

第 17 篇读的 nano-vllm 约 1200 行,是 vLLM 核心思想的一个小样。这一讲读 vLLM 本身。规模先摆出来:

$ .venv/bin/python bench/engine_loc.py
nano-vllm    vLLM  SGLang  文件
       80    3569    6176  调度器
      102     823     721  块 / 前缀缓存
       65     401    3204  请求状态
      235    2368    2460  执行器

vLLM vllm/v1/ 整个目录:170876 行
SGLang srt/managers/ 整个目录:43063 行
nano-vllm 全部:1197 行
图 135-1 三个引擎几个关键文件的行数(不算空行)。vLLM 的调度器一个文件就有 3569 行,是 nano-vllm 整个仓库的三倍;vllm/v1/ 一个目录就有 17 万行。SGLang 只统计了取下来的几个目录。

17 万行不可能逐行读,也没有必要。这一讲的读法是:抓住一个请求的路径,在路径上的每个关键点停下来,看它和 nano-vllm、miniinfer 的做法有什么不同、为什么不同。多出来的代码大部分是在支持更多的模型、硬件、并行方式和功能(多模态、LoRA、PD 分离、几十种注意力后端),核心的骨架并不大。

取下同样的代码:

cd miniinfer/third_party
git clone --filter=blob:none --sparse https://github.com/vllm-project/vllm && cd vllm
git checkout 821851e && git sparse-checkout set --no-cone '/vllm/v1/' '/vllm/engine/' '/vllm/config/' '/vllm/entrypoints/llm.py' '/vllm/entrypoints/openai/'

三个进程

vLLM V1:一个请求经过的三个进程
图 135-2 vLLM V1 的进程结构。点“下一步”看一个请求经过哪些模块,点模块看它在哪个文件。

nano-vllm 只有一个主进程(张量并行时再加几个 worker),调度、分词、执行模型都在主进程里轮流做。vLLM V1 把它们拆到三类进程里:

  1. API 服务器进程:HTTP 接口、分词、反分词、流式输出。这些都是纯 CPU 的 Python 代码,而且量很大:一个高并发的服务每秒要处理成千上万个 token 的反分词。
  2. EngineCore 进程:只做调度和驱动执行。它是一个死循环:收请求 → 调度 → 让 worker 执行 → 更新状态 → 发输出。
  3. Worker 进程:每张卡一个,执行模型。

为什么拆?第 89 讲引过 vLLM 团队对 v0.6.0 的剖析:API 服务器和调度一度占了一步时间的六成,GPU 大部分时间在等 Python。拆成多个进程以后,分词、反分词和调度跑在不同的 CPU 核上,互不阻塞;Python 的全局解释器锁(GIL)也只锁住各自的进程。进程之间用 ZMQ 传消息、msgpack 序列化;EngineCore 里收和发又各放在一个后台线程,主循环只管调度。

third_party/vllm/vllm/v1/engine/core.py 第 1794–1873 行 / 共 3143 行
    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()
            # Publish request counts before and after GPU step to ensure freshness.
            self._maybe_publish_request_counts()
            # 2) Step the engine core and return the outputs.
            self._process_engine_step()
            self._maybe_publish_request_counts()

        raise SystemExit

    def _maybe_publish_request_counts(self):
        if not self.publish_dp_lb_stats:
            return

        # Publish our request counts (if they've changed).
        counts = self.scheduler.get_request_counts()
        if counts != self.last_counts:
            self.last_counts = counts
            stats = SchedulerStats(
                *counts, kv_cache_usage=self.scheduler.get_kv_cache_usage()
            )
            self.output_queue.put_nowait((-1, EngineCoreOutputs(scheduler_stats=stats)))

    def _process_input_queue(self):
        """Exits when an engine step needs to be performed."""
        # Inputs deferred during the last step precede anything still queued.
        while self._deferred_inputs:
            self._handle_client_request(*self._deferred_inputs.popleft())

        waited = False
        while not self.has_work() and self.is_running():
            # Notify callbacks waiting for engine to become idle.
            self._notify_idle_state_callbacks()
            if self.input_queue.empty():
                # Drain aborts queue; all aborts are also processed via input_queue.
                with self.aborts_queue.mutex:
                    self.aborts_queue.queue.clear()
                if logger.isEnabledFor(DEBUG):
                    logger.debug("EngineCore waiting for work.")
                    waited = True
            block = self.process_input_queue_block
            try:
                with get_watch_dog().disable():
                    req = self.input_queue.get(block=block)
                self._handle_client_request(*req)
            except queue.Empty:
                break
            if not block:
                break

        if waited:
            logger.debug("EngineCore loop active.")

        # Handle any more client requests.
        while not self.input_queue.empty():
            req = self.input_queue.get_nowait()
            self._handle_client_request(*req)

    def _process_engine_step(self) -> bool:
        """Called only when there are unfinished local requests."""
        get_watch_dog().feed()

        # Step the engine core.
        outputs, model_executed = self.step_fn()
        # Put EngineCoreOutputs into the output queue.
        for output in outputs.items() if outputs else ():
            self.output_queue.put_nowait(output)
        # Post-step hook.
        self.post_step(model_executed)

        # If no model execution happened but there is still scheduler work
        # (e.g. WAITING_FOR_REMOTE_KVS or delayed KV connector frees), yield
        # the GIL briefly to allow background transfer threads to make progress.
        if not model_executed and self.scheduler.has_requests():
            time.sleep(0.001)

        return model_executed
  1. 两件事交替:处理输入队列里的请求(新请求、取消、控制命令),执行一步。和 nano-vllm 的 generate() 循环是一回事,只是这里永不退出,请求随时从外面来。

  2. 没有任何未完成的请求时,阻塞在输入队列上,不空转占 CPU;有活时把队列里已有的消息全部处理掉,再去执行一步。输入队列由后台线程从 ZMQ 填充。

  3. step_fn 是 step 或 step_with_batch_queue(流水线并行、异步调度时用,允许同时有几步在飞)。输出放进输出队列,由后台线程序列化后发回前端进程。

third_party/vllm/vllm/v1/engine/core.py 第 713–743 行 / 共 3143 行
    def step(self) -> tuple[dict[int, EngineCoreOutputs], bool]:
        """Schedule, execute, and make output.

        Returns tuple of outputs and a flag indicating whether the model
        was executed.
        """
        # Check for any requests remaining in the scheduler - unfinished,
        # or finished and not yet removed from the batch.
        if not self.scheduler.has_requests():
            return {}, False
        scheduler_output = self.scheduler.schedule(self._should_throttle_prefills())
        future = self.model_executor.execute_model(scheduler_output, non_block=True)
        grammar_output = self.scheduler.get_grammar_bitmask(scheduler_output)
        with (
            self.capture_iteration_details(scheduler_output) as iteration_details,
            self.log_error_detail(scheduler_output),
        ):
            model_output = self._wait_for_output(future)
            if model_output is None:
                model_output = self.model_executor.sample_tokens(grammar_output)

        # Before processing the model output, process any aborts that happened
        # during the model execution.
        self._process_aborts_queue()
        engine_core_outputs = self.scheduler.update_from_output(
            scheduler_output, model_output
        )
        self._attach_iteration_details(engine_core_outputs, iteration_details)
        self._attach_weight_version(engine_core_outputs)

        return engine_core_outputs, scheduler_output.total_num_scheduled_tokens > 0
  1. 和 nano-vllm 一样的三段:调度 → 执行 → 更新。schedule() 返回一个 SchedulerOutput,下面细讲。

  2. execute_model(…, non_block=True) 把这一步交给执行器,立刻返回一个 future。等待的同时,主线程顺手算约束解码要用的 grammar bitmask(第 80 讲),两件事重叠。然后等前向的结果,再让 worker 采样(采样要用 bitmask,所以放在后面)。

  3. 先处理执行期间到达的取消请求,再 update_from_output:接上新 token、回滚被拒的草稿、判断结束、释放块,生成每个请求的输出。

启动:KV Cache 有多大,是量出来的

请求进来之前,EngineCore 要先把 worker 准备好。顺序和 nano-vllm 一样(第 133 讲):建模型、装权重、量显存、分 KV、录 CUDA Graph;不同的是,这些步骤由 EngineCore 进程通过执行器指挥所有 worker 一起做,而“能分多少个块”的决定,是在 EngineCore 里统一做出的。

third_party/vllm/vllm/v1/engine/core.py 第 273–407 行 / 共 3143 行
    def _initialize_kv_caches(self, vllm_config: VllmConfig) -> KVCacheConfig:
        start = time.time()

        # register all kvcache specs in enginecore process.
        register_all_kvcache_specs(vllm_config)

        # Get all kv cache needed by the model
        kv_cache_specs = self.model_executor.get_kv_cache_specs()

        # Some layers (e.g. Prefix LM attention) run non-causally and tag their
        # KV cache spec with ``non_causal=True``. The specs are collected here in
        # the engine-core process (the same process that builds the scheduler),
        # so this is the multiproc-safe place to translate that layer-level
        # signal into a scheduling policy: chunked prefill and prefix caching
        # both assume causal attention and would corrupt non-causal prefill.
        if any(
            getattr(spec, "non_causal", False)
            for worker_specs in kv_cache_specs
            for spec in worker_specs.values()
        ):
            if vllm_config.scheduler_config.enable_chunked_prefill:
                logger.info(
                    "Disabling chunked prefill: model has non-causal attention layers."
                )
                vllm_config.scheduler_config.enable_chunked_prefill = False
            if vllm_config.cache_config.enable_prefix_caching:
                logger.info(
                    "Disabling prefix caching: model has non-causal attention layers."
                )
                vllm_config.cache_config.enable_prefix_caching = False

        # Resolve the KV cache layout before memory profiling: workers that
        # capture full cudagraphs initialize a minimal KV cache during it.
        # Attention-free models resolve the default so layout reads never precede
        # resolution.
        if vllm_config.cache_config.enable_extensible_kv_cache:
            # Disable it, everywhere, where it cannot be used.
            executor = self.model_executor
            reason = executor.extensible_kv_cache_unsupported_reason(kv_cache_specs)
            if reason is not None:
                executor.disable_extensible_kv_cache(reason)
        layout = resolve_kv_cache_layout(
            vllm_config,
            self.model_executor.get_supported_kv_cache_layouts(),
            [s for specs in kv_cache_specs for s in specs.values()],
        )

        global_kv_cache_groups = get_global_kv_cache_groups(vllm_config, kv_cache_specs)
        vllm_config.adjust_dcp_kv_cache_interleave_size(global_kv_cache_groups)
        self.model_executor.set_kv_cache_layout(
            layout.name, vllm_config.parallel_config.cp_kv_cache_interleave_size
        )

        has_kv_cache = any(kv_cache_spec for kv_cache_spec in kv_cache_specs)
        if has_kv_cache:
            if envs.VLLM_ELASTIC_EP_SCALE_UP_LAUNCH:
                # NOTE(yongji): should already be set
                # during _eep_scale_up_before_kv_init
                assert self.available_gpu_memory_for_kv_cache > 0
                available_gpu_memory = [self.available_gpu_memory_for_kv_cache] * len(
                    kv_cache_specs
                )
            else:
                # Profiles the peak memory usage of the model to determine how
                # much memory can be allocated for kv cache.
                available_gpu_memory = self.model_executor.determine_available_memory()
                self.available_gpu_memory_for_kv_cache = available_gpu_memory[0]
        else:
            # Attention free models don't need memory for kv cache
            available_gpu_memory = [0] * len(kv_cache_specs)

        assert len(kv_cache_specs) == len(available_gpu_memory)

        # Track max_model_len before KV cache config to detect auto-fit changes
        max_model_len_before = vllm_config.model_config.max_model_len

        kv_cache_configs = get_kv_cache_configs(
            vllm_config, kv_cache_specs, available_gpu_memory, global_kv_cache_groups
        )
        for kv_cache_config in kv_cache_configs:
            kv_cache_config.kv_cache_layout = vllm_config.cache_config.kv_cache_layout

        # If auto-fit reduced max_model_len, sync the new value to workers.
        # This is needed because workers were spawned before memory profiling
        # and have the original (larger) max_model_len cached.
        max_model_len_after = vllm_config.model_config.max_model_len
        if max_model_len_after != max_model_len_before:
            self.collective_rpc("update_max_model_len", args=(max_model_len_after,))

        scheduler_kv_cache_config = generate_scheduler_kv_cache_config(kv_cache_configs)
        vllm_config.cache_config.num_gpu_blocks = scheduler_kv_cache_config.num_blocks
        kv_cache_groups = scheduler_kv_cache_config.kv_cache_groups
        if kv_cache_groups:
            # Exclude groups that opt out of prefix caching (e.g. a circular
            # buffer, a 1-block/req scratch buffer with a small ring block):
            # their small block_size would otherwise drag the global block_size
            # below the real allocator block size and desync it from mamba.
            participating = [
                g.kv_cache_spec.block_size
                for g in kv_cache_groups
                if g.kv_cache_spec.prefix_cacheable
            ]
            vllm_config.cache_config.block_size = min(
                participating
                if participating
                else [g.kv_cache_spec.block_size for g in kv_cache_groups]
            )
        # With an extensible KV cache, `num_blocks` is the reserved capacity
        # until the post-warmup measurement below.
        extensible = vllm_config.cache_config.enable_extensible_kv_cache
        if kv_cache_groups and not extensible:
            update_kv_cache_capacity(vllm_config, scheduler_kv_cache_config)

        vllm_config.validate_block_size()

        scheduler_block_size, hash_block_size = resolve_kv_cache_block_sizes(
            scheduler_kv_cache_config, vllm_config
        )
        cache_hit_alignment_tokens = resolve_cache_hit_alignment_tokens(
            scheduler_kv_cache_config,
            vllm_config,
            scheduler_block_size,
            hash_block_size,
        )
        # The scheduler's config is a deep copy taken before these are resolved,
        # so set them there too: the KV connector's scheduler side reads the same
        # fields as its workers.
        for kv_cache_config in (*kv_cache_configs, scheduler_kv_cache_config):
            kv_cache_config.hash_block_size = hash_block_size
            kv_cache_config.cache_hit_alignment_tokens = cache_hit_alignment_tokens

        self.model_executor.initialize_from_config(kv_cache_configs)
        compilation_times = []
        if not envs.VLLM_ELASTIC_EP_SCALE_UP_LAUNCH:
            compilation_times = self.model_executor.compile_or_warm_up_model()
  1. 每个 worker 返回自己模型里每一层的 KV 规格(KVCacheSpec):普通的全注意力层、滑动窗口层、MLA 层、Mamba 这类状态空间层的规格各不相同。混合架构的模型(一部分层是滑动窗口、一部分是全注意力)就是在这里被识别出来的。

  2. 两者都假定注意力是因果的(第 76、77 讲)。如果模型里有双向注意力的层,就在这里统一关掉,免得悄悄算错。这是在 EngineCore 进程里做的,因为调度器也在这个进程。

  3. determine_available_memory(v1/worker/gpu_worker.py 第 675 行)让每个 worker 用最坏情况的输入跑一次前向,量出激活的峰值,算出在 gpu_memory_utilization(默认 0.92)之内还能留给 KV 的字节数。和 nano-vllm 的 allocate_kv_cache 是一回事,只是每张卡各量各的。

  4. 按各层的规格和各卡的可用显存,算出每张卡的 KV 配置,块数统一成所有卡里最小的那个(v1/core/kv_cache_planning.py 第 1658–1673 行),再生成调度器用的那一份,记进 num_gpu_blocks。张量并行时各卡必须用同样的块号,所以只能按最紧的那张卡来。如果显存连一个最长的请求都放不下,还会自动调小 max_model_len 并通知所有 worker。

  5. initialize_from_config 让每个 worker 按配置分配 KV 张量、挂到各层的注意力上;compile_or_warm_up_model 做 torch.compile 和 CUDA Graph 的捕获(第 133 讲)。这两步之后,调度器才建立起来,开始接请求。

调度:没有 prefill 阶段,也没有 decode 阶段

第 132 讲看到,nano-vllm 一步要么全做 prefill、要么全做 decode。vLLM V1 的调度器开头有一段注释,说清了它的做法:

third_party/vllm/vllm/v1/core/sched/scheduler.py 第 716–742 行 / 共 3934 行
    def schedule(self, throttle_prefills: bool = False) -> SchedulerOutput:
        self.current_step += 1
        # NOTE(woosuk) on the scheduling algorithm:
        # There's no "decoding phase" nor "prefill phase" in the scheduler.
        # Each request just has the num_computed_tokens and
        # num_tokens_with_spec. num_tokens_with_spec =
        # len(prompt_token_ids) + len(output_token_ids) + len(spec_token_ids).
        # At each step, the scheduler tries to assign tokens to the requests
        # so that each request's num_computed_tokens can catch up its
        # num_tokens_with_spec. This is general enough to cover
        # chunked prefills, prefix caching, speculative decoding,
        # and the "jump decoding" optimization in the future.

        scheduled_new_reqs: list[Request] = []
        scheduled_running_reqs: list[Request] = []
        preempted_reqs: list[Request] = []

        req_to_new_blocks: dict[str, KVCacheBlocks] = {}
        num_scheduled_tokens: dict[str, int] = {}
        token_budget = self.max_num_scheduled_tokens
        spec = self.vllm_config.speculative_config
        draft_slots = spec.max_num_new_slots_for_drafting if spec is not None else 0
        input_budget = self.scheduler_config.max_num_batched_tokens
        if self._pause_state == PauseState.PAUSED_ALL:
            # Do not schedule any requests when paused.
            token_budget = 0
  1. 调度器里没有“prefill 阶段”和“decode 阶段”。每个请求只有两个数:num_computed_tokens(KV 已经算好的位置数)和 num_tokens_with_spec(提示 + 已生成 + 草稿)。每一步,调度器给请求分配 token,让前者去追后者。

    这一句话就统一了几件事:新请求的 prefill 差额是整个提示;分块 prefill 是差额太大、一步只给一部分;前缀缓存是 num_computed_tokens 一开始就不是 0;decode 的差额是 1;投机解码的差额是 1 + 草稿数。

  2. num_scheduled_tokens:每个请求这一步分到几个 token。token_budget:这一步总共能算多少个 token(max_num_batched_tokens)。还有新分配的块、草稿、被抢占的请求。最后这些打包成 SchedulerOutput。

一步的 token 预算怎么分
图 135-3 统一的 token 预算(简化版)。A、B 在 decode(B 带 2 个草稿),C 在分块 prefill,D、E 在等待。每步先给运行中的请求补差额,再放新请求,直到预算用完。演示里把 long_prefill_token_threshold 设成了 512;vLLM 的默认值是 0(不限),调成“不限”看长提示 C 怎么把整步的预算吃光。

一步的调度分两轮。第一轮是运行中的请求:

third_party/vllm/vllm/v1/core/sched/scheduler.py 第 809–1041 行 / 共 3934 行
        # First, schedule the RUNNING requests.
        req_index = 0
        while req_index < len(self.running) and token_budget > 0:
            request = self.running[req_index]
            if input_budget <= draft_slots:
                break

            if (
                request.num_output_placeholders > 0
                # This is (num_computed_tokens + 1) - (num_output_placeholders - 1).
                # Since output placeholders are also included in the computed tokens
                # count, we subtract (num_output_placeholders - 1) to remove any draft
                # tokens, so that we can be sure no further steps are needed even if
                # they are all rejected.
                and request.num_computed_tokens + 2 - request.num_output_placeholders
                >= request.num_prompt_tokens + request.max_tokens
            ):
                # Async scheduling: Avoid scheduling an extra step when we are sure that
                # the previous step has reached request.max_tokens. We don't schedule
                # partial draft tokens since this prevents uniform decode optimizations.
                req_index += 1
                continue

            if self.current_step < request.next_decode_eligible_step:
                # PP+async: enforce `pp_size` steps between same-req decodes
                # to match worker-side sampled-tokens broadcast slot ring cadence.
                req_index += 1
                continue

            if defer_prefills and request.is_prefill_chunk:
                # DP prefill balancing: defer this in-progress prefill chunk to a
                # cadence-aligned step; decodes still run to fill this step.
                req_index += 1
                continue

            if (
                self.ec_connector is not None
                and request.mm_features
                and not self.ec_connector.ensure_cache_available(
                    request,
                    request.num_computed_tokens - request.num_output_placeholders,
                )
            ):
                req_index += 1
                continue

            num_new_tokens = (
                request.num_tokens_with_spec
                + request.num_output_placeholders
                - request.num_computed_tokens
            )
            if 0 < long_prefill_token_threshold < num_new_tokens:
                num_new_tokens = long_prefill_token_threshold
            num_new_tokens = min(
                num_new_tokens, token_budget, input_budget - draft_slots
            )

            # Make sure the input position does not exceed the max model len.
            # This is necessary when using spec decoding.
            num_new_tokens = min(
                num_new_tokens,
                self.max_model_len
                - request.num_computed_tokens
                - self.num_sampled_tokens_per_step,
            )

            # Apply Mamba alignment before encoder caps.
            if self.need_mamba_block_aligned_split:
                num_new_tokens = self._mamba_block_aligned_split(
                    request, num_new_tokens
                )

            # Schedule encoder inputs.
            encoder_inputs_to_schedule = None
            external_load_encoder_input: list[int] = []
            duplicate_encoder_inputs: list[int] = []
            new_encoder_compute_budget = encoder_compute_budget
            if request.has_encoder_inputs:
                (
                    encoder_inputs_to_schedule,
                    num_new_tokens,
                    new_encoder_compute_budget,
                    external_load_encoder_input,
                    duplicate_encoder_inputs,
                ) = self._try_schedule_encoder_inputs(
                    request,
                    request.num_computed_tokens,
                    num_new_tokens,
                    encoder_compute_budget,
                    shift_computed_tokens=self.num_prefill_lookahead,
                )

            # Multi-module MTP: avoid ending a prefill chunk within
            # num_prefill_lookahead of the prefill end.
            num_new_tokens = self._reserve_prefill_lookahead(
                request, request.num_computed_tokens, num_new_tokens
            )

            if num_new_tokens == 0:
                # The request cannot be scheduled because one of the following
                # reasons:
                # 1. No new tokens to schedule. This may happen when
                #    (1) PP>1 and we have already scheduled all prompt tokens
                #    but they are not finished yet.
                #    (2) Async scheduling and the request has reached to either
                #    its max_total_tokens or max_model_len.
                # 2. The encoder budget is exhausted.
                # 3. The encoder cache is exhausted.
                # 4. Insufficient budget for a block-aligned chunk in hybrid
                #    models with mamba cache mode \"align\".
                # 5. Insufficient budget to keep a multi-module MTP prefill
                #    chunk out of the prefill-lookahead window.
                # NOTE(woosuk): Here, by doing `continue` instead of `break`,
                # we do not strictly follow the FCFS scheduling policy and
                # allow the lower-priority requests to be scheduled.
                req_index += 1
                continue

            # Schedule newly needed KV blocks for the request.
            with record_function_or_nullcontext("schedule: allocate_slots"):
                while True:
                    new_blocks = self.kv_cache_manager.allocate_slots(
                        request,
                        num_new_tokens,
                        num_lookahead_tokens=self.num_lookahead_tokens,
                    )

                    if new_blocks is not None:
                        # The request can be scheduled.
                        break

                    if (
                        self.connector is not None
                        and self.connector.has_pending_block_frees()
                    ):
                        break

                    # The request cannot be scheduled.
                    # Preempt the lowest-priority request.
                    if self.policy == SchedulingPolicy.PRIORITY:
                        preempted_req = max(
                            self.running,
                            key=lambda r: (r.priority, r.arrival_time),
                        )
                    else:
                        preempted_req = self.running[-1]

                    # A deferred free will not help with immediate allocation.
                    if not self._request_blocks_can_be_freed(preempted_req):
                        break

                    if self.policy == SchedulingPolicy.PRIORITY:
                        victim_index = self.running.index(preempted_req)
                        del self.running[victim_index]
                        if victim_index < req_index:
                            req_index -= 1

                        if preempted_req in scheduled_running_reqs:
                            preempted_req_id = preempted_req.request_id
                            scheduled_running_reqs.remove(preempted_req)
                            restored = num_scheduled_tokens.pop(preempted_req_id)
                            token_budget += restored
                            input_budget += restored + draft_slots
                            req_to_new_blocks.pop(preempted_req_id)
                            scheduled_spec_decode_tokens.pop(preempted_req_id, None)
                            preempted_encoder_inputs = scheduled_encoder_inputs.pop(
                                preempted_req_id, None
                            )
                            if preempted_encoder_inputs:
                                # Restore encoder compute budget if the preempted
                                # request had encoder inputs scheduled in this step.
                                num_embeds_to_restore = sum(
                                    preempted_req.get_num_encoder_embeds(i)
                                    for i in preempted_encoder_inputs
                                )
                                encoder_compute_budget += num_embeds_to_restore
                    else:
                        preempted_req = self.running.pop()

                    self._preempt_request(
                        preempted_req,
                        scheduled_timestamp,
                        drop_stale_output=self.requires_kv_delivery,
                    )
                    preempted_reqs.append(preempted_req)
                    if preempted_req == request:
                        # No more request to preempt. Cannot schedule this request.
                        break

            if new_blocks is None:
                if (
                    self.policy == SchedulingPolicy.PRIORITY
                    and request.status == RequestStatus.PREEMPTED
                ):
                    # The request was the lowest-priority running request and
                    # preempted itself. The requests after it have higher
                    # priority and may still fit (it just freed its blocks);
                    # it was removed from `self.running`, so `req_index`
                    # already points at the next one.
                    continue
                # Cannot schedule this request.
                break

            # Schedule the request.
            scheduled_running_reqs.append(request)
            prefill_scheduled |= request.is_prefill_chunk
            request_id = request.request_id
            req_to_new_blocks[request_id] = new_blocks
            num_scheduled_tokens[request_id] = num_new_tokens
            token_budget -= num_new_tokens
            input_budget -= num_new_tokens + draft_slots
            req_index += 1
            drafts_needed = drafts_needed or not self._drafts_unused(
                request, request.num_computed_tokens, num_new_tokens
            )

            # Speculative decode related.
            if request.spec_token_ids:
                num_scheduled_spec_tokens = (
                    num_new_tokens
                    + request.num_computed_tokens
                    - request.num_tokens
                    - request.num_output_placeholders
                )
                if num_scheduled_spec_tokens > 0:
                    spec_token_ids = request.spec_token_ids
                    if len(spec_token_ids) > num_scheduled_spec_tokens:
                        spec_token_ids = spec_token_ids[:num_scheduled_spec_tokens]
                    scheduled_spec_decode_tokens[request.request_id] = spec_token_ids

                # New spec tokens will be set in `update_draft_token_ids` before the
                # next step when applicable.
                request.spec_token_ids = []
  1. 按运行队列的顺序,预算用完就停。运行中的请求里既有在 decode 的,也有在分块 prefill 的(提示还没算完的请求也在运行队列里)。

  2. 差额 = num_tokens_with_spec + 占位数 − num_computed_tokens(占位数用于异步调度,见下文)。三个上限:长提示一步最多 long_prefill_token_threshold 个,免得一个长 prefill 把整步占满、让 decode 的请求等太久(第 77 讲;这个上限默认是 0,即不限,要手动设;只有一个请求时也不限,第 770–779 行);不超过剩下的预算;位置不超过模型的最大长度。

  3. 注释里写明了:这里用 continue 而不是 break,不严格遵守先来先到,让后面的请求有机会。

  4. 为这 num_new_tokens 个 token(加上投机解码要预留的位置)分配 KV 块。拿到了就可以调度。

  5. 默认策略:抢占运行队列末尾的请求(最晚进来的),释放它的块,再试。和 nano-vllm、miniinfer v3 一样。按优先级调度时,抢占优先级最低的那个;如果它这一步已经被分到 token,要把预算还回去。抢到自己就放弃。

  6. 记下分到的 token 数和新块,扣预算。

  7. 如果请求带着草稿(上一步的起草器给出的),这一步分到的 token 里超出“真实 token”的部分就是要验证的草稿,记进 scheduled_spec_decode_tokens。预算不够时,草稿可能只验证一部分。

第二轮是等待中的请求(第 1065 行起,500 多行,大部分在处理 PD 分离、多模态、LoRA 等情况)。主干和 nano-vllm 一样:查前缀缓存(get_computed_blocks,第 1246 行),差额 = 总长 − 命中的部分(第 1356 行),长提示同样受上限约束(第 1382 行),allocate_slots 拿块(第 1497 行),拿不到就停(第 1523 行);拿到了就移进运行队列,num_computed_tokens 设成命中的位置数(第 1609–1637 行)。

和 nano-vllm 相比,最关键的差别是:新请求的 prefill 和老请求的 decode 在同一步里。一步里可能有 30 个请求各 decode 1 个 token,加上一个新请求 prefill 了 1500 个 token。这对执行一侧提出了要求:注意力 kernel 必须能处理“每个请求查询长度不同”的 batch,CUDA Graph 也要能录这种混合的步。vLLM 的注意力后端统一用“变长查询 + 块表”的接口(第 133 讲的 flash_attn_varlen_func 就是这种接口),CUDA Graph 用两种模式:整步录(只适合纯 decode 这类规整的步)和分段录(注意力之外的部分录成图,注意力单独执行,混合的步也能用)。

KV 管理:块池、哈希、LRU

third_party/vllm/vllm/v1/core/kv_cache_utils.py 第 703–733 行 / 共 1284 行
def hash_block_tokens(
    hash_function: Callable[[Any], bytes],
    parent_block_hash: BlockHash | None,
    curr_block_token_ids: Sequence[int],
    extra_keys: tuple[Any, ...] | None = None,
) -> BlockHash:
    """Computes a hash value corresponding to the contents of a block and
    the contents of the preceding block(s). The hash value is used for
    prefix caching. We use LRU cache for this function to avoid recomputing
    hash values for the same block contents.

    Args:
        hash_function: The hash function used to compute block hash.
        parent_block_hash: The hash of the parent block. None
            if this is the first block.
        curr_block_token_ids: A list of token ids in the current
            block. The current block is assumed to be full.
        extra_keys: Extra keys for the block.

    Returns:
        The hash value of the block and the token ids in the block.
        The entire tuple is used as the hash key of the block.

    """
    if not parent_block_hash:
        parent_block_hash = NONE_HASH

    curr_block_token_ids_tuple = tuple(curr_block_token_ids)
    return BlockHash(
        hash_function((parent_block_hash, curr_block_token_ids_tuple, extra_keys))
    )
  1. 和第 128 讲、nano-vllm 一样是链式哈希。多了一个 extra_keys:LoRA 适配器的编号、多模态输入(图片)的哈希、缓存的“盐”。两个请求的 token 一样,但用了不同的 LoRA,或者同一位置是不同的图片,KV 就不同,不能共用。

    默认的哈希函数是 SHA-256(vllm/config/cache.py 的 prefix_caching_hash_algo):慢一点,但碰撞的概率可以忽略,而且结果跨进程、跨机器稳定,KV 可以在多台机器之间共享(第 113 讲)。nano-vllm 用 xxhash 再比一遍 token,是另一种取舍。

third_party/vllm/vllm/v1/core/kv_cache_utils.py 第 254–275 行 / 共 1284 行
class FreeKVCacheBlockQueue:
    """This class organizes a list of KVCacheBlock objects to a doubly linked
    list of free blocks. We implement this class instead of using Python
    builtin deque to support removing a block in the middle of the queue
    in O(1) time. To close the performance gap to the builtin deque which is
    implemented in C++, this class does not allocate any Python objects when
    manipulating the linked list. Instead, this class manipulates the
    prev_free_block and next_free_block attributes of the given blocks.

    The queue is ordered by block ID in the beginning. When a block is allocated
    and then freed, it will be appended back with the eviction order:
    1. The least recent used block is at the front (LRU).
    2. If two blocks have the same last accessed time (allocated by the
       same sequence), the one with more hash tokens (the tail of a block
       chain) is at the front.
    Note that we maintain this order by reversing the block order when free
    blocks of a request. This operation is outside of this class.

    Args:
        blocks: A list of KVCacheBlock objects.

    """
  1. nano-vllm 的空闲块是 deque,前缀命中一个躺在空闲队列中间的块时,deque.remove 要 O(n)。vLLM 自己写了一个双向链表,直接改块对象上的前后指针,从中间摘掉一块是 O(1),而且不创建任何 Python 对象。

    顺序就是淘汰顺序:最久没用的在前面;同一个请求释放的块,链尾的块(含更多 token 的哈希)在前。这和 nano-vllm、miniinfer 倒着还块的道理一样:让开头的块在缓存里留得更久。

third_party/vllm/vllm/v1/core/block_pool.py 第 798–837 行 / 共 936 行
    def free_blocks(
        self, ordered_blocks: Iterable[KVCacheBlock], evict_first: bool = False
    ) -> None:
        """Free a list of blocks. The blocks should be ordered by their
        eviction priority, where the first block will be evicted first.

        Args:
            ordered_blocks: A list of blocks to free ordered by their eviction
                priority.
            evict_first: Also put freed cached blocks at the front of the free
                queue, so they are evicted before other cached blocks. For
                blocks whose contents another tier already holds.

        """
        # Identify blocks with hash (LRU cache) and without it (never match APC)
        blocks_to_evict_last = []
        blocks_to_evict_first = []
        other_pools: dict[BlockPool, list[KVCacheBlock]] = {}
        for block in ordered_blocks:
            if block.is_null:  # never pooled; its ref_cnt is not maintained
                continue
            if block.pool is not None and block.pool is not self._weak_self:
                pool = block.pool()
                if pool is not None:
                    other_pools.setdefault(pool, []).append(block)
                continue
            block.ref_cnt -= 1
            if block.ref_cnt == 0:
                if block.block_hash is None or not self.enable_caching or evict_first:
                    # LIFO reuse of non-cached blocks for better GPU locality,
                    # and of cached ones when asked to evict them first.
                    blocks_to_evict_first.append(block)
                else:
                    # FIFO reuse of cached blocks for LRU eviction behavior.
                    blocks_to_evict_last.append(block)

        # Blocks to reuse first are prepended to the front of the free queue.
        self.free_block_queue.prepend_n(blocks_to_evict_first)
        # Blocks to reuse last are appended to the end of the free queue.
        self.free_block_queue.append_n(blocks_to_evict_last)
  1. 引用计数减到 0 的块:没有哈希的(内容不会被命中)放到空闲链表的前面,最先被重新使用(刚用过,还在 GPU 的缓存里);有哈希的放到后面,按 LRU 留着等命中。

    miniinfer 和 nano-vllm 不区分这两类,可能先把一个还能被命中的块覆盖掉。

KVCacheManager.allocate_slots(v1/core/kv_cache_manager.py 第 401 行起)的注释里有一张图,把一个请求的块分成几段:已缓存的、这一步命中的、外部(PD 分离时从别的机器搬来的)、这一步要算的、为投机解码预留的。和 miniinfer 相比,多出来的两段正好对应第 14 篇讲的 PD 分离和 KV 传输。

投机解码:和我们的回滚是同一个式子

vLLM 的投机解码有十几种起草方式(n-gram、EAGLE、MTP、独立的小模型等,在 v1/worker/gpu/spec_decode/),但调度器里的处理很简单。草稿只是让 num_tokens_with_spec 多了几个,验证后被拒的草稿这样回滚:

third_party/vllm/vllm/v1/core/sched/scheduler.py 第 2387–2410 行 / 共 3934 行
            req_index = req_indices[req_id]
            generated_token_ids = (
                sampled_token_ids[req_index] if sampled_token_ids else []
            )

            scheduled_spec_token_ids = (
                scheduler_output.scheduled_spec_decode_tokens.get(req_id)
            )
            if scheduled_spec_token_ids and (
                generated_token_ids or self.num_sampled_tokens_per_step == 0
            ):
                num_draft_tokens = len(scheduled_spec_token_ids)
                num_sampled = self.num_sampled_tokens_per_step
                num_accepted = max(len(generated_token_ids) - num_sampled, 0)
                num_rejected = num_draft_tokens - num_accepted
                # Rejections roll back num_computed_tokens (and, under async
                # scheduling, num_output_placeholders, which covers the spec
                # tokens). A stale rejection count predates the preemption
                # rollback and must not apply.
                if not output_is_stale:
                    if request.num_computed_tokens > 0:
                        request.num_computed_tokens -= num_rejected
                    if request.num_output_placeholders > 0:
                        request.num_output_placeholders -= num_rejected
  1. worker 返回这个请求这一步生成的 token(被接受的草稿加上采样的那个)。生成数减去每步必然采样的数量,就是接受的草稿数,其余是被拒的。

  2. num_computed_tokens -= 被拒的草稿数。被拒草稿的 KV 写在块里,但不算数,下一步会被覆盖。这和第 130 讲 miniinfer v5 的回滚、第 134 讲给 nano-vllm 写的回滚是同一件事。

不同在执行一侧:验证在 worker 里用拒绝采样(第 96 讲),支持任意温度;起草器有自己的 KV Cache 时,allocate_slots 的 num_lookahead_tokens 为它预留位置;为了让整步仍能用 CUDA Graph,调度器会把没有草稿的 decode 请求也补齐到 1 + k 个 token(第 1358–1380 行)。第 134 讲的移植里,验证步放弃了 CUDA Graph,正是这里要解决的问题。

结构化输出:语法在哪里编译,掩码在哪里加

第 80 讲讲了约束解码的原理,第 137 讲会看 SGLang 的做法。vLLM 把它分成三个时机,都由 EngineCore 里的 StructuredOutputManager(v1/structured_output/__init__.py)管理:

third_party/vllm/vllm/v1/structured_output/__init__.py 第 134–205 行 / 共 548 行
    def grammar_init(self, request: "Request") -> None:
        if request.structured_output_request is None:
            return

        sampling_params = request.sampling_params
        assert sampling_params is not None
        structured_outputs = sampling_params.structured_outputs
        assert structured_outputs is not None
        request_backend = structured_outputs._backend
        assert request_backend is not None
        if self.backend_name is not None and request_backend != self.backend_name:
            raise VLLMValidationError(
                "Structured output processing only supports one backend per engine. "
                f"The engine is already using '{self.backend_name}', but this "
                f"request resolved to '{request_backend}'. Configure "
                "`structured_outputs_config.backend` explicitly or use schemas "
                "supported by the initialized backend."
            )

        # Initialize the backend the first time it is needed.
        #
        # NOTE: We only support a single backend. We do NOT support different
        # backends on a per-request basis in V1 (for now, anyway...).
        # _backend is set in Processor._validate_structured_output
        if self.backend is None:
            vocab_size = self.vllm_config.model_config.get_vocab_size()
            if request_backend == "xgrammar":
                self.backend = XgrammarBackend(
                    self.vllm_config,
                    tokenizer=self.tokenizer,
                    vocab_size=vocab_size,
                )
            elif request_backend == "guidance":
                self.backend = GuidanceBackend(
                    self.vllm_config,
                    tokenizer=self.tokenizer,
                    vocab_size=vocab_size,
                )
            elif request_backend == "outlines":
                from vllm.v1.structured_output.backend_outlines import OutlinesBackend

                self.backend = OutlinesBackend(
                    self.vllm_config,
                    tokenizer=self.tokenizer,
                    vocab_size=vocab_size,
                )
            elif request_backend == "lm-format-enforcer":
                from vllm.v1.structured_output.backend_lm_format_enforcer import (  # noqa: E501
                    LMFormatEnforcerBackend,
                )

                self.backend = LMFormatEnforcerBackend(
                    self.vllm_config,
                    tokenizer=self.tokenizer,
                    vocab_size=vocab_size,
                )
            else:
                raise ValueError(
                    f"Unsupported structured output backend: {request_backend}"
                )
            self.backend_name = request_backend

        grammar: Future[StructuredOutputGrammar] | StructuredOutputGrammar
        if self._use_async_grammar_compilation:
            grammar = self.executor.submit(self._create_grammar, request)
        else:
            try:
                grammar = self._create_grammar(request)
            except Exception as e:
                grammar = Future()
                grammar.set_exception(e)
        request.structured_output_request.grammar = grammar
  1. xgrammar、guidance(llguidance)、outlines、lm-format-enforcer 四种后端,第一次遇到结构化输出的请求时才初始化,之后整个引擎都用它。

  2. 把 JSON Schema 或正则编译成状态机可能要花不少时间,不能挡住调度循环。所以默认交给一个线程池异步编译(只有 external_launcher 这种要求各卡完全确定的启动方式才同步编译),请求先拿到一个 future。编译失败时 future 里装的是异常,只让这一个请求失败。

请求进来时状态是 WAITING_FOR_STRUCTURED_OUTPUT_GRAMMAR。调度器每一步检查(scheduler.py 第 3685–3697 行):语法编译好了,就改成普通的 WAITING,进入正常的调度;还没好,这一步跳过它,其他请求照常跑。

掩码在每一步计算:上面 EngineCore.step() 第 724–725 行,调度结果交给执行器之后,主线程马上调 get_grammar_bitmask,让后端按每个请求当前的状态算出“下一个 token 允许哪些”,写成一个位图(每个 token 一位,用 32 位整数存)。这一步和 GPU 的前向同时进行,前向算完、采样之前,worker 把位图展开、把不允许的 token 的打分设成 −∞。采样出 token 后,accept_tokens(第 515 行)推进每个请求的状态机。

投机解码和结构化输出同时打开时,还要多一步:草稿 token 也必须符合语法,trim_spec_tokens(第 358 行)把不符合语法的草稿截掉,免得验证一个注定被拒的 token。

异步调度:让 CPU 的工作藏在 GPU 后面

即使拆成了多个进程,EngineCore 里“调度 → 等 GPU → 处理结果”仍然是串行的:GPU 算的时候 CPU 在等,CPU 调度的时候 GPU 在等。decode 一步只有几毫秒时,调度和处理结果的那一两毫秒就占了可观的比例。

让 CPU 的调度藏在 GPU 计算的后面
图 135-4 串行和重叠两种方式。重叠时,发射第 i 步之后不等它算完,就处理第 i − 1 步的结果、调度第 i + 1 步。GPU 一步 12 ms、CPU 共 5 ms 时,吞吐提高到 1.42 倍;CPU 比 GPU 还慢时,瓶颈就变成了 CPU。

异步调度(SchedulerConfig.async_scheduling,这个提交里默认打开,设成 False 才关掉)时,调度器在不知道上一步采样结果的情况下就开始调度下一步。难点是:下一步要送进模型的 token 正是上一步刚采样出来的,调度器还不知道它是什么。vLLM 的办法是占位:

third_party/vllm/vllm/v1/core/sched/async_scheduler.py 共 45 行
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

import vllm.envs as envs
from vllm.platforms import current_platform
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.core.sched.scheduler import Scheduler


class AsyncScheduler(Scheduler):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        # Only XPU can disable PP decode microbatching via VLLM_XPU_PP_MICROBATCH.
        self.decode_stagger = self.parallel_config.pipeline_parallel_size
        if current_platform.is_xpu() and not envs.VLLM_XPU_PP_MICROBATCH:
            self.decode_stagger = 1

    def _update_after_schedule(self, scheduler_output: SchedulerOutput) -> None:
        super()._update_after_schedule(scheduler_output)
        spec_decode_tokens = scheduler_output.scheduled_spec_decode_tokens
        # Use the latest num of scheduled draft tokens in next step as placeholder.
        spec_token_placeholders = [-1] * scheduler_output.num_spec_tokens_to_schedule
        for req_id in scheduler_output.num_scheduled_tokens:
            request = self.requests[req_id]
            if request.is_prefill_chunk:
                continue

            scheduler_output.pending_structured_output_tokens |= (
                request.use_structured_output and request.num_output_placeholders > 0
            )
            # The request will generate num_sampled_tokens_per_step new tokens
            # plus num_spec_tokens in this scheduling step. Diffusion has no AR
            # bonus token (num_sampled_tokens_per_step == 0) — only the canvas
            # (spec) tokens.
            cur_num_spec_tokens = len(spec_decode_tokens.get(req_id, ()))
            request.num_output_placeholders += (
                self.num_sampled_tokens_per_step + cur_num_spec_tokens
            )
            # Add placeholders for the new draft/spec tokens.
            # We will update the actual spec token ids in the worker process.
            request.spec_token_ids = spec_token_placeholders

            # Set the next step index in which this request is eligible to be
            # scheduled for decode (for PP microbatching).
            request.next_decode_eligible_step = self.current_step + self.decode_stagger
  1. 调度完一步,每个 decode 的请求将会多出 1 个采样的 token,再加上这一步的草稿数。调度器不知道它们是什么,先给 num_output_placeholders 加上这个数,下一步就把它们当作“已有的 token”去调度。真正的 token 由 worker 自己保存,下一步直接从 GPU 上取,不经过调度器。草稿同理,用 −1 占位,worker 里再填上真实的。

    代价在调度器的其他地方:比如请求已经到了长度上限,调度器要晚一步才知道(第 816–830 行专门处理这种情况,避免多跑一步)。

SGLang 更早就把同样的机制作为默认(它称之为“零开销调度”),第 137 讲细看。

SchedulerOutput:只发增量

调度器和 worker 在不同的进程里,每一步都要把调度结果发过去。nano-vllm 每步把整个请求列表 pickle 一次(第 133 讲)。vLLM 的 SchedulerOutput(v1/core/sched/output.py 第 220 行)把请求分成两类:

  • 新请求(scheduled_new_reqs):发完整的信息,提示的全部 token、采样参数、块表。worker 收到后缓存起来。
  • 老请求(scheduled_cached_reqs):只发这一步的变化,新增的块号、这一步算几个 token。

worker 里的 GPUModelRunner 维护一个持久的 batch:每个请求在固定的大张量里占一行(token、块表等;有的放在显存里,有的放在 GPU 能直接访问的锁页内存里,见 v1/worker/gpu/states.py),每一步只按增量修改其中几行,而不是像 nano-vllm 那样每步从 Python 列表重新拼出全部输入张量。batch 很大(几百个请求)时,这一步省下的 CPU 时间很可观。

回顾

一个请求在 vLLM V1 里的路径:API 服务器分词 → ZMQ 发给 EngineCore → 调度器在 token 预算内给它分配 token(查前缀缓存、按块分配 KV,块不够就抢占最晚进来的请求)→ 执行器把 SchedulerOutput 的增量广播给每张卡 → worker 更新持久 batch、跑模型、采样 → 调度器接上新 token、回滚被拒的草稿、释放结束的请求 → 输出发回前端,反分词,流式返回。

和 nano-vllm 比,最根本的变化是调度不再区分 prefill 和 decode:这要求注意力 kernel 能处理变长查询,CUDA Graph 能录混合的步,也换来了更平稳的 decode 延迟。

这一讲停在“一个 EngineCore”的边界上。真实的服务往往有多个 API 服务器、跨多个节点的多个引擎副本,PD 分离时还有两种实例之间的 KV 搬运。下一讲把视野放大到整个服务:一条 curl 请求怎么在多节点的 vLLM 里找到它的引擎、跑完、返回。下一讲:vLLM 的分布式服务。