From 731bba9b5a5f99788f871ae40cb72ebc192c6415 Mon Sep 17 00:00:00 2001 From: Rahul Chalamala <22563365+rchalamala@users.noreply.github.com> Date: Thu, 30 Jul 2026 16:12:13 -0700 Subject: [PATCH 1/5] [Bugfix][MRV2] Require all requests to be decoding for uniform-decode dispatch Model runner v2 classified a batch as a uniform decode batch from its shape alone -- num_tokens == num_reqs * max_query_len, `get_uniform_token_count` in vllm/v1/worker/gpu/cudagraph_utils.py -- and nothing about whether the requests were decoding. A prompt chunk of exactly `1 + num_speculative_tokens` tokens has that shape, so a prefill was dispatched with `cg_mode=FULL` and replayed the captured spec-verify decode graph over prompt tokens. Without spec decoding the same collision exists between a 1-token prompt chunk and the q=1 decode graph. Observed on this base with Qwen/Qwen3.5-0.8B (GDN hybrid) + MTP, K=7, FULL_AND_PIECEWISE, VLLM_USE_V2_MODEL_RUNNER=1: an 8-token prompt dispatches `reqs=1 toks=8 uniform_token_count=8 -> FULL` on its prefill step and generates deterministic garbage, while the same request at 4, 5, 6, 7 or 9 prompt tokens dispatches PIECEWISE and is coherent. After this change the 8-token prefill dispatches PIECEWISE and answers the prompt; the control outputs are unchanged byte for byte, and genuine decode steps still replay their FULL graphs (uniform_token_count=8 for the verify step, 1 for the drafter steps). Mechanism, traced at the metadata level on this base: the mis-dispatched batch still builds prefill metadata, because `MambaHybridModelState.prepare_attn` passes is_prefilling and a -1 draft count for the chunk, so `GDNAttentionMetadataBuilder.build` reports num_prefills > 0. Both persistent-buffer refresh blocks in that builder are gated on num_prefills == 0, so neither runs, and the replayed graph reads the state indices its buffers held when the last uniform decode batch was built -- NULL(0) from the capture-time dummy block tables if none has run yet. `state_idx <= 0` makes the fused GDN kernels skip the recurrent state read and the store (third_party/flash_linear_attention/ops/fused_sigmoid_gating.py), so the prompt's conv/SSM state is never created and every later step computes from a zero state. The gate is per batch, not per request, so genuine decodes sharing a batch with such a chunk lose their refresh too: building metadata for 6 spec decodes plus 2 colliding chunks leaves all 8 rows of spec_state_indices_tensor at their capture-time values while the real block table sits elsewhere. Dense models survive the mis-dispatch because spec-verify attention over a fresh sequence is the same computation as prefill attention; only recurrent-state models lose state. Issue #49918 REPORTS this as 0/6 correct control requests, reproduced independently of proposer (MTP and ngram), quantization and batch size, with PIECEWISE or enforce-eager as workarounds. The classification rule existed twice and drifted, which is why fixing it in one runner leaves the other broken. `get_uniform_decode_token_count` in vllm/v1/worker/utils.py is now the single source of truth: every request has the same query length AND no request has prompt tokens left to compute. utils.py is already the module that both gpu_model_runner.py and the gpu/ package import from, so neither runner has to depend on the other. Both v2 call sites use it: the target model in `execute_model`, and the draft prefill graph in `AutoRegressiveSpeculator.propose`, whose comment already claimed "when all requests are decoding" while testing only the shape -- that dispatch also replayed FULL for the 8-token prompt above. Capture paths keep the shape-only test. Dummy batches (DP padding, memory profiling, warmup) are uniform by construction and their synthetic request ids have no state to consult, matching `InputBatch.make_dummy`, which marks every dummy request as not prefilling; the v1 runner expresses the same exemption as `force_uniform_decode`. Startup on the run above exercised the profile run, the warmup steps and prefill/decode graph capture with the stricter predicate in place, and the captured decode graphs are still selected at runtime. Deliberately not done: the v1 site, `GPUModelRunner._is_uniform_decode`, is left untouched. PR #47123 has been open since 2026-06-30 to fix exactly that call site and this change must not supersede it. The helper is shaped so that `_is_uniform_decode` can collapse onto it by passing `input_batch.num_computed_tokens_cpu` and `input_batch.num_prompt_tokens` and comparing the result with uniform_decode_query_len. vllm/v1/worker/gpu/warmup.py also still pads its warmup prompts to `decode_query_len + 1` to dodge the misclassification; that workaround is now redundant, but it is harmless and it keeps the warmup shapes diverse. The added cost is a per-step `np.fromiter` over the scheduled request ids, one dict lookup each, then a gather of two int32 numpy views. No CPU-GPU sync. It duplicates an index vector `prepare_inputs` rebuilds shortly after; folding the two together is a worthwhile follow-up. Tests: with the decoding clause removed from the predicate (i.e. the pre-fix rule), test_prompt_chunks_shaped_like_spec_decode_miss_the_full_graph and test_prompt_chunk_of_decode_query_len_is_not_uniform_decode fail while the uniform-decode and dummy-run cases still pass. AI assistance was used for this change. Co-authored-by: Janelle Cai Signed-off-by: Rahul Chalamala <22563365+rchalamala@users.noreply.github.com> --- tests/v1/spec_decode/test_dynamic_sd_cug.py | 81 ++++++++ tests/v1/worker/test_gpu_batch_ordering.py | 179 +++++++++++++++++- vllm/v1/worker/gpu/cudagraph_utils.py | 11 +- vllm/v1/worker/gpu/model_runner.py | 43 ++++- .../spec_decode/autoregressive/speculator.py | 5 +- vllm/v1/worker/utils.py | 57 ++++++ 6 files changed, 367 insertions(+), 9 deletions(-) diff --git a/tests/v1/spec_decode/test_dynamic_sd_cug.py b/tests/v1/spec_decode/test_dynamic_sd_cug.py index d75495ea606a..5502ca159ea4 100644 --- a/tests/v1/spec_decode/test_dynamic_sd_cug.py +++ b/tests/v1/spec_decode/test_dynamic_sd_cug.py @@ -5,6 +5,7 @@ from types import SimpleNamespace from unittest.mock import MagicMock +import numpy as np import pytest import torch @@ -16,6 +17,7 @@ VllmConfig, ) from vllm.v1.worker.gpu import cudagraph_utils as gpu_cudagraph_utils +from vllm.v1.worker.utils import get_uniform_decode_token_count pytestmark = pytest.mark.cpu_test @@ -196,6 +198,85 @@ def test_dynamic_sd_non_uniform_batch_falls_back_to_piecewise(monkeypatch): assert desc.num_active_loras == 0 +def test_prompt_chunks_shaped_like_spec_decode_miss_the_full_graph(monkeypatch): + """A batch holding K+1-token prompt chunks must not replay a decode graph. + + The FULL spec-verify graph is selected on the batch shape alone + (num_reqs * (K + 1) tokens), which prompt chunks of exactly K + 1 tokens + satisfy by coincidence. Replaying it over prompt tokens corrupts every + request in the batch, not just the chunks, because the captured kernels + read per-request state that a batch containing prefills never refreshes. + See https://github.com/vllm-project/vllm/issues/49918. + """ + + max_spec_tokens = 7 + decode_query_len = max_spec_tokens + 1 + + monkeypatch.setattr( + gpu_cudagraph_utils, + "get_pp_group", + lambda: SimpleNamespace(is_first_rank=True, is_last_rank=True), + ) + + vllm_config = _create_vllm_config_for_dsd( + max_num_seqs=64, + max_spec_tokens=max_spec_tokens, + use_dynamic_sd=False, + ) + manager = gpu_cudagraph_utils.CudaGraphManager( + vllm_config=vllm_config, + device=torch.device("cpu"), + cudagraph_mode=CUDAGraphMode.FULL_AND_PIECEWISE, + decode_query_len=decode_query_len, + ) + manager._graphs_captured = True + + num_decodes, num_chunks = 6, 2 + num_reqs = num_decodes + num_chunks + num_tokens = num_reqs * decode_query_len + # The six decoding requests have their prompts fully computed; the two + # chunks are decode_query_len tokens into a longer, unfinished prompt. + prefill_lens = np.array([16] * num_decodes + [40] * num_chunks, dtype=np.int32) + num_computed = np.array( + [16] * num_decodes + [decode_query_len] * num_chunks, dtype=np.int32 + ) + + # The batch shape is indistinguishable from a full batch of spec decodes. + assert ( + gpu_cudagraph_utils.get_uniform_token_count( + num_reqs, num_tokens, decode_query_len + ) + == decode_query_len + ) + + uniform_tok_count = get_uniform_decode_token_count( + num_reqs, num_tokens, decode_query_len, num_computed, prefill_lens + ) + assert uniform_tok_count is None + desc = manager.dispatch( + num_reqs=num_reqs, + num_tokens=num_tokens, + uniform_token_count=uniform_tok_count, + num_active_loras=0, + ) + assert desc.cg_mode == CUDAGraphMode.PIECEWISE + assert desc.uniform_token_count is None + + # The same shape with every request decoding still gets its FULL graph. + uniform_tok_count = get_uniform_decode_token_count( + num_reqs, num_tokens, decode_query_len, prefill_lens, prefill_lens + ) + assert uniform_tok_count == decode_query_len + desc = manager.dispatch( + num_reqs=num_reqs, + num_tokens=num_tokens, + uniform_token_count=uniform_tok_count, + num_active_loras=0, + ) + assert desc.cg_mode == CUDAGraphMode.FULL + assert desc.uniform_token_count == decode_query_len + + def test_basic_sd_does_not_capture_shorter_full_decode_shapes(monkeypatch): """Without DSD, only the max decode query length should get FULL graphs. diff --git a/tests/v1/worker/test_gpu_batch_ordering.py b/tests/v1/worker/test_gpu_batch_ordering.py index 2c2115dc81eb..5b8986a02d5e 100644 --- a/tests/v1/worker/test_gpu_batch_ordering.py +++ b/tests/v1/worker/test_gpu_batch_ordering.py @@ -1,18 +1,26 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project -"""Batch ordering in Model Runner V2 (vllm.v1.worker.gpu). +"""Batch ordering and classification in Model Runner V2 (vllm.v1.worker.gpu). split_decodes_and_prefills assumes decode -> short_extend -> prefill request ordering. With spec decode (decode_query_len > 1), a shorter chunked-prefill tail sorted in front of the uniform decodes misclassifies every decode as a prefill. + +Conversely, a prompt chunk of exactly decode_query_len tokens has a decode +batch's shape, and must not be classified as a uniform decode batch. """ +from types import SimpleNamespace +from typing import Any + +import numpy as np import torch from vllm.v1.attention.backend import CommonAttentionMetadata from vllm.v1.attention.backends.utils import split_decodes_and_prefills -from vllm.v1.worker.gpu.model_runner import sort_batch_req_ids +from vllm.v1.worker.gpu.model_runner import GPUModelRunner, sort_batch_req_ids +from vllm.v1.worker.utils import get_uniform_decode_token_count def _make_common_attn_metadata(query_lens: list[int]) -> CommonAttentionMetadata: @@ -37,6 +45,79 @@ def _make_common_attn_metadata(query_lens: list[int]) -> CommonAttentionMetadata ) +def _make_runner(req_states: dict[str, tuple[int, int]]) -> Any: + """Build a runner stub from {req_id: (num_computed_tokens, prefill_len)}.""" + prefill_lens = np.array([s[1] for s in req_states.values()], dtype=np.int32) + num_computed = np.array([s[0] for s in req_states.values()], dtype=np.int32) + runner: Any = GPUModelRunner.__new__(GPUModelRunner) + runner.req_states = SimpleNamespace( + req_id_to_index={req_id: i for i, req_id in enumerate(req_states)}, + # The runner keeps this as min(num_computed_tokens, prefill_len). + num_computed_prefill_tokens=np.minimum(num_computed, prefill_lens), + prefill_len=SimpleNamespace(np=prefill_lens), + ) + return runner + + +def _uniform_token_count( + req_states: dict[str, tuple[int, int]], + query_len: int, + dummy_run: bool = False, +) -> int | None: + scheduler_output = SimpleNamespace( + num_scheduled_tokens={req_id: query_len for req_id in req_states}, + total_num_scheduled_tokens=query_len * len(req_states), + ) + return GPUModelRunner._get_uniform_token_count( + _make_runner(req_states), + scheduler_output, + len(req_states), + query_len * len(req_states), + query_len, + dummy_run, + ) + + +def test_spec_decode_batch_is_uniform_decode(): + # decode_query_len == 8 (K=7): every request past its prefill. + decodes = {f"d{i}": (16, 16) for i in range(6)} + assert _uniform_token_count(decodes, 8) == 8 + + +def test_prompt_chunk_of_decode_query_len_is_not_uniform_decode(): + # Two requests are 8 tokens into a 40-token prompt, so their query length + # only coincides with the K+1 spec-decode query length. Replaying the + # decode graph here corrupts the six decodes as well, so the whole batch + # must be rejected. See https://github.com/vllm-project/vllm/issues/49918. + batch = {f"d{i}": (16, 16) for i in range(6)} + batch.update({f"p{i}": (8, 40) for i in range(2)}) + assert _uniform_token_count(batch, 8) is None + + # Same collision without spec decoding: a 1-token prompt looks like a + # 1-token decode step. + assert _uniform_token_count({"p0": (0, 1)}, 1) is None + + # A fresh prompt that happens to be exactly decode_query_len tokens long. + assert _uniform_token_count({"p0": (0, 8)}, 8) is None + + +def test_dummy_batches_stay_uniform_decode(): + # Dummy batches (DP padding, profiling, warmup) are uniform by + # construction and their requests have no state to consult, so they must be + # classified without one: looking one up would raise KeyError here, and + # rejecting them would make graph capture and replay disagree. + scheduler_output = SimpleNamespace( + num_scheduled_tokens={f"_dummy_req_{i}": 8 for i in range(4)}, + total_num_scheduled_tokens=32, + ) + assert ( + GPUModelRunner._get_uniform_token_count( + _make_runner({}), scheduler_output, 4, 32, 8, True + ) + == 8 + ) + + def test_sort_batch_req_ids_no_spec(): # decode_query_len == 1: plain ascending order (decodes first). num_tokens_per_req = {"p1": 100, "d1": 1, "p2": 7, "d2": 1} @@ -68,3 +149,97 @@ def test_spec_decodes_lead_short_prefill_tail(): ) assert (num_decodes, num_prefills) == (8, 1) assert (num_decode_tokens, num_prefill_tokens) == (16, 1) + + +def test_uniform_decode_uses_state_index_not_batch_position(): + """The predicate must read each request's own state, not its batch slot. + + `req_id_to_index` is a persistent map into the runner's state arrays, so a + request's batch position and its state index diverge as requests come and + go. Here the only prefilling request sits at state index 0 while the two + scheduled decodes sit at 1 and 2, so a gather that used batch position + would read the prefilling row and wrongly reject the batch. + """ + runner: Any = GPUModelRunner.__new__(GPUModelRunner) + # State arrays in state-index order: a prefilling request, then two decodes. + runner.req_states = SimpleNamespace( + req_id_to_index={"prefilling": 0, "decode_a": 1, "decode_b": 2}, + num_computed_prefill_tokens=np.array([8, 16, 16], dtype=np.int32), + prefill_len=SimpleNamespace(np=np.array([40, 16, 16], dtype=np.int32)), + ) + scheduler_output = SimpleNamespace( + num_scheduled_tokens={"decode_a": 8, "decode_b": 8}, + total_num_scheduled_tokens=16, + ) + + assert ( + GPUModelRunner._get_uniform_token_count( + runner, scheduler_output, 2, 16, 8, False + ) + == 8 + ) + + # Scheduling the prefilling request alongside them must reject the batch. + scheduler_output.num_scheduled_tokens = { + "decode_a": 8, + "prefilling": 8, + "decode_b": 8, + } + scheduler_output.total_num_scheduled_tokens = 24 + assert ( + GPUModelRunner._get_uniform_token_count( + runner, scheduler_output, 3, 24, 8, False + ) + is None + ) + + +def test_predicate_agrees_with_is_prefilling(): + """The drafter's call site passes `InputBatch`'s two arrays directly. + + `InputBatch.is_prefilling_np` is documented as + `num_computed_prefill_tokens_np < prefill_len_np`, so the shared predicate + must reject a batch exactly when that flag is set for any request. This + pins the contract the drafter relies on without standing up a speculator. + """ + cases = [ + (np.array([16, 16], dtype=np.int32), np.array([16, 16], dtype=np.int32)), + (np.array([8, 16], dtype=np.int32), np.array([40, 16], dtype=np.int32)), + (np.array([0], dtype=np.int32), np.array([1], dtype=np.int32)), + (np.array([5, 5, 5], dtype=np.int32), np.array([5, 5, 5], dtype=np.int32)), + ] + for num_computed_prefill_tokens, prefill_lens in cases: + num_reqs = len(prefill_lens) + is_prefilling = num_computed_prefill_tokens < prefill_lens + result = get_uniform_decode_token_count( + num_reqs, + 8 * num_reqs, + 8, + num_computed_prefill_tokens, + prefill_lens, + ) + assert (result is None) == bool(is_prefilling.any()), ( + f"{num_computed_prefill_tokens} vs {prefill_lens} -> {result}" + ) + + +def test_non_uniform_shape_is_rejected_without_request_state(): + """The shape test must decide on its own, ahead of any state lookup. + + Most batches are mixed prefill/decode and fail on shape alone, so the O(1) + shape test runs before the per-request prefill state is gathered. A token + count that is not `num_reqs * max_query_len` has to be rejected even when + every request has finished prefilling, as they have here. + """ + num_computed_prefill_tokens = np.array([16, 16], dtype=np.int32) + prefill_lens = np.array([16, 16], dtype=np.int32) + assert ( + get_uniform_decode_token_count( + 2, + 12, # No shared query length over 2 requests produces 12 tokens. + 8, + num_computed_prefill_tokens, + prefill_lens, + ) + is None + ) diff --git a/vllm/v1/worker/gpu/cudagraph_utils.py b/vllm/v1/worker/gpu/cudagraph_utils.py index 3a174cba80d7..9d7e70eccf63 100644 --- a/vllm/v1/worker/gpu/cudagraph_utils.py +++ b/vllm/v1/worker/gpu/cudagraph_utils.py @@ -35,7 +35,7 @@ from vllm.v1.worker.gpu.cp_utils import prepare_dcp_local_seq_lens from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers from vllm.v1.worker.gpu.model_states.interface import ModelState -from vllm.v1.worker.utils import AttentionGroup +from vllm.v1.worker.utils import AttentionGroup, is_uniform_query_len logger = init_logger(__name__) @@ -97,10 +97,13 @@ def get_uniform_token_count( """ Return the uniform token count if batch is uniform, else None. A batch is uniform if all requests have the same number of tokens. + + This is a shape test, so it is only valid for batches whose requests are + known to be decoding by construction (e.g. dummy runs, or a drafter step + that emits a fixed number of tokens per request). Batches coming from a + scheduler step must go through `get_uniform_decode_token_count`. """ - if (max_query_len == num_tokens // num_reqs) and ( - num_tokens == max_query_len * num_reqs - ): + if is_uniform_query_len(num_reqs, num_tokens, max_query_len): return max_query_len return None diff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py index 3bf89ee156b1..1d9a898f48c3 100644 --- a/vllm/v1/worker/gpu/model_runner.py +++ b/vllm/v1/worker/gpu/model_runner.py @@ -133,7 +133,11 @@ from vllm.v1.worker.gpu.states import RequestState from vllm.v1.worker.gpu.structured_outputs import StructuredOutputsWorker from vllm.v1.worker.lora_model_runner_mixin import LoRAModelRunnerMixin -from vllm.v1.worker.utils import KVBlockZeroer, copy_kv_cache_blocks_inplace +from vllm.v1.worker.utils import ( + KVBlockZeroer, + copy_kv_cache_blocks_inplace, + get_uniform_decode_token_count, +) logger = init_logger(__name__) @@ -1250,6 +1254,39 @@ def postprocess_sampled( idx_mapping, num_sampled, self.req_states.num_computed_tokens.gpu ) + def _get_uniform_token_count( + self, + scheduler_output: SchedulerOutput, + num_reqs: int, + num_tokens: int, + max_query_len: int, + dummy_run: bool, + ) -> int | None: + """Per-request token count of a uniform decode batch, or None. + + Dummy batches (DP padding, memory profiling, warmup) are uniform by + construction and have no request state to consult, so they are + classified by shape alone. This mirrors `InputBatch.make_dummy`, which + marks every dummy request as not prefilling. + """ + if dummy_run: + return get_uniform_token_count(num_reqs, num_tokens, max_query_len) + idx_mapping_np = np.fromiter( + map( + self.req_states.req_id_to_index.__getitem__, + scheduler_output.num_scheduled_tokens, + ), + dtype=np.intp, + count=num_reqs, + ) + return get_uniform_decode_token_count( + num_reqs, + num_tokens, + max_query_len, + self.req_states.num_computed_prefill_tokens[idx_mapping_np], + self.req_states.prefill_len.np[idx_mapping_np], + ) + @torch.inference_mode() def execute_model( self, @@ -1276,7 +1313,9 @@ def execute_model( num_reqs = len(scheduler_output.num_scheduled_tokens) num_toks = scheduler_output.total_num_scheduled_tokens max_query_len = max(scheduler_output.num_scheduled_tokens.values()) - uniform_tok_count = get_uniform_token_count(num_reqs, num_toks, max_query_len) + uniform_tok_count = self._get_uniform_token_count( + scheduler_output, num_reqs, num_toks, max_query_len, dummy_run + ) num_active_loras = 0 if self.lora_config: diff --git a/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py b/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py index 7d357533e27e..c32b1a8c1b40 100644 --- a/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py @@ -25,6 +25,7 @@ ) from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator from vllm.v1.worker.utils import AttentionGroup +from vllm.v1.worker.utils import get_uniform_decode_token_count logger = init_logger(__name__) @@ -274,12 +275,14 @@ def propose( # When all requests are decoding (no true prefills), each has # num_speculative_steps + 1 tokens, enabling FULL graph replay. - uniform_token_count = get_uniform_token_count( + uniform_token_count = get_uniform_decode_token_count( num_reqs, # Use the actual number of tokens without padding added by # the target model during FULL cudagraph. num_tokens, max_query_len, + input_batch.num_computed_prefill_tokens_np, + input_batch.prefill_len_np, ) prefill_batch_desc, num_tokens_across_dp = dispatch_cg_and_sync_dp( self.prefill_cudagraph_manager, diff --git a/vllm/v1/worker/utils.py b/vllm/v1/worker/utils.py index 3c8630a5e32d..ef168c8f5078 100644 --- a/vllm/v1/worker/utils.py +++ b/vllm/v1/worker/utils.py @@ -611,6 +611,63 @@ def copy_kv_cache_blocks_inplace( blocks[dst_indices] = blocks[src_indices] +def is_uniform_query_len(num_reqs: int, num_tokens: int, max_query_len: int) -> bool: + """Whether every request in the batch has the same query length. + + This tests the batch shape only. Callers classifying a scheduled batch as a + decode batch must use ``get_uniform_decode_token_count`` instead, because a + prompt chunk can have a decode batch's shape. + + Args: + num_reqs: Number of requests in the batch. + num_tokens: Total number of tokens in the batch. + max_query_len: Largest per-request query length in the batch. + """ + return num_reqs > 0 and num_tokens == max_query_len * num_reqs + + +def get_uniform_decode_token_count( + num_reqs: int, + num_tokens: int, + max_query_len: int, + num_computed_tokens: np.ndarray, + prefill_lens: np.ndarray, +) -> int | None: + """Per-request token count of a uniform decode batch, or None. + + A batch is a uniform decode batch only if every request has the same query + length *and* no request is still prefilling. Query length alone is a shape + test that a prompt chunk satisfies by coincidence: a prompt chunk of + ``1 + num_speculative_tokens`` tokens has the shape of a spec-decode step, + and a 1-token chunk has the shape of a plain decode step. Classifying such + a batch as a decode batch replays a decode-captured cudagraph over prompt + tokens, whose captured kernels read per-request state that a prefill + metadata build does not refresh. + + Args: + num_reqs: Number of requests in the batch. + num_tokens: Total number of tokens in the batch. + max_query_len: Largest per-request query length in the batch. + num_computed_tokens: Per-request tokens computed before this step, in + batch order. Must be exactly ``num_reqs`` long; a full + ``max_num_reqs`` state array would compare the wrong requests. + prefill_lens: Per-request prefill length, i.e. the prompt plus any + output tokens recomputed after preemption, in batch order. Same + length requirement. + + Returns: + The shared per-request query length, or None if the batch is not a + uniform decode batch. + """ + if not is_uniform_query_len(num_reqs, num_tokens, max_query_len): + return None + # Equivalent to `InputBatch.is_prefilling_np.any()`, which the drafter's + # call site derives from the same two arrays. + if np.any(num_computed_tokens < prefill_lens): + return None + return max_query_len + + def is_residual_scattered_for_sp( vllm_config: VllmConfig, num_input_tokens: int ) -> bool: From 04ffc392a0deb3f5dac6b61821c274823982a827 Mon Sep 17 00:00:00 2001 From: Rahul Chalamala <22563365+rchalamala@users.noreply.github.com> Date: Thu, 30 Jul 2026 16:12:13 -0700 Subject: [PATCH 2/5] [Perf] Test uniform-decode shape before gathering request state _get_uniform_token_count built a per-request index mapping with a Python dict-lookup loop before calling get_uniform_decode_token_count, which runs the O(1) shape test first and returns None for any mixed prefill/decode batch. Most batches are mixed, so the gather was built and discarded one line later on the common path, where the code it replaced was a single arithmetic comparison. Runs the same shape test in the caller and returns early, so the gather is built only for batches that can still turn out to be uniform decode. The predicate is the one the callee already applies, so classification is unchanged. Co-authored-by: Janelle Cai Signed-off-by: Rahul Chalamala <22563365+rchalamala@users.noreply.github.com> --- vllm/v1/worker/gpu/model_runner.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py index 1d9a898f48c3..5bbb3bccfa1f 100644 --- a/vllm/v1/worker/gpu/model_runner.py +++ b/vllm/v1/worker/gpu/model_runner.py @@ -137,6 +137,7 @@ KVBlockZeroer, copy_kv_cache_blocks_inplace, get_uniform_decode_token_count, + is_uniform_query_len, ) logger = init_logger(__name__) @@ -1271,6 +1272,12 @@ def _get_uniform_token_count( """ if dummy_run: return get_uniform_token_count(num_reqs, num_tokens, max_query_len) + # Shape first. This is the same test get_uniform_decode_token_count + # runs before it looks at any request state, and it rejects every + # mixed prefill/decode batch, which is most of them. Checking it here + # keeps the gather below off the hot path in that case. + if not is_uniform_query_len(num_reqs, num_tokens, max_query_len): + return None idx_mapping_np = np.fromiter( map( self.req_states.req_id_to_index.__getitem__, From 6874d5154666e779b97cd9db24d8ebfe1988ed1b Mon Sep 17 00:00:00 2001 From: Rahul Chalamala <22563365+rchalamala@users.noreply.github.com> Date: Thu, 30 Jul 2026 16:12:13 -0700 Subject: [PATCH 3/5] [Bugfix][MRV2] Cover the multi-module MTP speculator's decode dispatch The multi-module MTP speculator picks its cudagraph with `get_uniform_token_count`, which tests batch shape alone. A prompt chunk of `1 + num_speculative_tokens` tokens has a spec-decode step's shape, so that test classifies it as a decode batch and replays a decode-captured graph over prompt tokens, whose kernels read per-request state a prefill metadata build does not refresh. Route it through `get_uniform_decode_token_count`, which additionally requires that no request is still prefilling. This speculator is a copy of the autoregressive one, comment included, and arrived after the other call sites were already fixed, so the guard added here is written over every speculator in the package rather than over this one. It fails on `multi_module_mtp/speculator.py:201` without the change and passes with it, and will fail again on the next speculator added by copy. Co-authored-by: Janelle Cai Signed-off-by: Rahul Chalamala <22563365+rchalamala@users.noreply.github.com> --- tests/v1/worker/test_gpu_batch_ordering.py | 36 +++++++++++++++++++ .../multi_module_mtp/speculator.py | 8 ++--- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/tests/v1/worker/test_gpu_batch_ordering.py b/tests/v1/worker/test_gpu_batch_ordering.py index 5b8986a02d5e..ac56e1439c92 100644 --- a/tests/v1/worker/test_gpu_batch_ordering.py +++ b/tests/v1/worker/test_gpu_batch_ordering.py @@ -11,6 +11,8 @@ batch's shape, and must not be classified as a uniform decode batch. """ +import ast +from pathlib import Path from types import SimpleNamespace from typing import Any @@ -243,3 +245,37 @@ def test_non_uniform_shape_is_rejected_without_request_state(): ) is None ) + + +def test_no_speculator_dispatches_on_query_length_alone(): + """No speculator may pick its cudagraph from a shape test. + + `get_uniform_token_count` and `is_uniform_query_len` both answer a question + about batch shape, which a prompt chunk satisfies by coincidence whenever it + happens to be `1 + num_speculative_tokens` tokens wide. Dispatching on + either replays a decode-captured graph over prompt tokens. + + This is written over the whole package rather than over the one speculator + that had the bug, because speculators are added by copying an existing one: + the shape-only call reappeared verbatim, comment included, in a speculator + added after the original two call sites were fixed. A per-file test would + pass again the next time that happens. + """ + import vllm.v1.worker.gpu.spec_decode as spec_decode + + shape_only = {"get_uniform_token_count", "is_uniform_query_len"} + root = Path(spec_decode.__file__).parent + offenders = [] + for path in sorted(root.rglob("speculator.py")): + for node in ast.walk(ast.parse(path.read_text())): + if not isinstance(node, ast.Call): + continue + func = node.func + name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", "") + if name in shape_only: + offenders.append(f"{path.relative_to(root)}:{node.lineno} {name}") + + assert not offenders, ( + "these speculators classify a decode batch by query length alone; use " + f"get_uniform_decode_token_count instead: {offenders}" + ) diff --git a/vllm/v1/worker/gpu/spec_decode/multi_module_mtp/speculator.py b/vllm/v1/worker/gpu/spec_decode/multi_module_mtp/speculator.py index 4be22b4474c6..61d1c0003f39 100644 --- a/vllm/v1/worker/gpu/spec_decode/multi_module_mtp/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/multi_module_mtp/speculator.py @@ -12,9 +12,6 @@ from vllm.triton_utils import tl, triton from vllm.v1.attention.backends.utils import PAD_SLOT_ID from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer -from vllm.v1.worker.gpu.cudagraph_utils import ( - get_uniform_token_count, -) from vllm.v1.worker.gpu.dp_utils import dispatch_cg_and_sync_dp from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers from vllm.v1.worker.gpu.spec_decode.autoregressive.cudagraph_utils import ( @@ -22,6 +19,7 @@ ) from vllm.v1.worker.gpu.spec_decode.eagle.utils import load_eagle_model from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator +from vllm.v1.worker.utils import get_uniform_decode_token_count logger = init_logger(__name__) @@ -190,10 +188,12 @@ def propose( # When all requests are decoding (no true prefills), each has # num_speculative_steps + 1 tokens, enabling FULL graph replay. - uniform_token_count = get_uniform_token_count( + uniform_token_count = get_uniform_decode_token_count( num_reqs, num_tokens, max_query_len, + input_batch.num_computed_prefill_tokens_np, + input_batch.prefill_len_np, ) batch_desc, num_tokens_across_dp = dispatch_cg_and_sync_dp( self.cudagraph_manager, From 1fc3a41c46ca8f75d8ee18e1006e8782076bc8b1 Mon Sep 17 00:00:00 2001 From: Rahul Chalamala <22563365+rchalamala@users.noreply.github.com> Date: Tue, 11 Aug 2026 19:39:52 +0000 Subject: [PATCH 4/5] [Bugfix][MRV2] Clean up uniform-decode imports after rebase Keep the main-branch imports required by the autoregressive speculator while removing the replaced shape-only helper. Co-authored-by: Janelle Cai Signed-off-by: Rahul Chalamala <22563365+rchalamala@users.noreply.github.com> --- .../worker/gpu/spec_decode/autoregressive/speculator.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py b/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py index c32b1a8c1b40..2b269a402518 100644 --- a/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py @@ -13,10 +13,7 @@ from vllm.v1.kv_cache_interface import KVCacheConfig from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer from vllm.v1.worker.gpu.block_table import BlockTables -from vllm.v1.worker.gpu.cudagraph_utils import ( - BatchExecutionDescriptor, - get_uniform_token_count, -) +from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor from vllm.v1.worker.gpu.dp_utils import dispatch_cg_and_sync_dp from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers from vllm.v1.worker.gpu.model_states.interface import ModelState @@ -24,8 +21,7 @@ SpeculatorCudaGraphManager, ) from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator -from vllm.v1.worker.utils import AttentionGroup -from vllm.v1.worker.utils import get_uniform_decode_token_count +from vllm.v1.worker.utils import AttentionGroup, get_uniform_decode_token_count logger = init_logger(__name__) From 7201f59250f9dc78ec5dfc00ae98d1fa8e13b5ae Mon Sep 17 00:00:00 2001 From: Nick Hill Date: Fri, 7 Aug 2026 17:25:43 -0700 Subject: [PATCH 5/5] rework Signed-off-by: Nick Hill --- tests/v1/spec_decode/test_dynamic_sd_cug.py | 21 +-- tests/v1/worker/test_gpu_batch_ordering.py | 144 +++++------------ vllm/v1/worker/gpu/cudagraph_utils.py | 11 +- vllm/v1/worker/gpu/input_batch.py | 8 +- vllm/v1/worker/gpu/model_runner.py | 145 ++++++++++-------- vllm/v1/worker/gpu/pcp_manager.py | 1 + .../spec_decode/autoregressive/speculator.py | 3 +- .../multi_module_mtp/speculator.py | 6 +- vllm/v1/worker/utils.py | 53 +------ 9 files changed, 141 insertions(+), 251 deletions(-) diff --git a/tests/v1/spec_decode/test_dynamic_sd_cug.py b/tests/v1/spec_decode/test_dynamic_sd_cug.py index 5502ca159ea4..f47c7d379640 100644 --- a/tests/v1/spec_decode/test_dynamic_sd_cug.py +++ b/tests/v1/spec_decode/test_dynamic_sd_cug.py @@ -5,7 +5,6 @@ from types import SimpleNamespace from unittest.mock import MagicMock -import numpy as np import pytest import torch @@ -201,12 +200,9 @@ def test_dynamic_sd_non_uniform_batch_falls_back_to_piecewise(monkeypatch): def test_prompt_chunks_shaped_like_spec_decode_miss_the_full_graph(monkeypatch): """A batch holding K+1-token prompt chunks must not replay a decode graph. - The FULL spec-verify graph is selected on the batch shape alone - (num_reqs * (K + 1) tokens), which prompt chunks of exactly K + 1 tokens - satisfy by coincidence. Replaying it over prompt tokens corrupts every - request in the batch, not just the chunks, because the captured kernels - read per-request state that a batch containing prefills never refreshes. - See https://github.com/vllm-project/vllm/issues/49918. + Prompt chunks of exactly K + 1 tokens give the batch a spec-decode shape + by coincidence; replaying the FULL graph over them corrupts every request + in the batch. See https://github.com/vllm-project/vllm/issues/49918. """ max_spec_tokens = 7 @@ -234,12 +230,6 @@ def test_prompt_chunks_shaped_like_spec_decode_miss_the_full_graph(monkeypatch): num_decodes, num_chunks = 6, 2 num_reqs = num_decodes + num_chunks num_tokens = num_reqs * decode_query_len - # The six decoding requests have their prompts fully computed; the two - # chunks are decode_query_len tokens into a longer, unfinished prompt. - prefill_lens = np.array([16] * num_decodes + [40] * num_chunks, dtype=np.int32) - num_computed = np.array( - [16] * num_decodes + [decode_query_len] * num_chunks, dtype=np.int32 - ) # The batch shape is indistinguishable from a full batch of spec decodes. assert ( @@ -249,8 +239,9 @@ def test_prompt_chunks_shaped_like_spec_decode_miss_the_full_graph(monkeypatch): == decode_query_len ) + # Two of the requests are decode_query_len tokens into a longer prompt. uniform_tok_count = get_uniform_decode_token_count( - num_reqs, num_tokens, decode_query_len, num_computed, prefill_lens + num_reqs, num_tokens, decode_query_len, has_prefill=True ) assert uniform_tok_count is None desc = manager.dispatch( @@ -264,7 +255,7 @@ def test_prompt_chunks_shaped_like_spec_decode_miss_the_full_graph(monkeypatch): # The same shape with every request decoding still gets its FULL graph. uniform_tok_count = get_uniform_decode_token_count( - num_reqs, num_tokens, decode_query_len, prefill_lens, prefill_lens + num_reqs, num_tokens, decode_query_len, has_prefill=False ) assert uniform_tok_count == decode_query_len desc = manager.dispatch( diff --git a/tests/v1/worker/test_gpu_batch_ordering.py b/tests/v1/worker/test_gpu_batch_ordering.py index ac56e1439c92..d0cd402ce7f2 100644 --- a/tests/v1/worker/test_gpu_batch_ordering.py +++ b/tests/v1/worker/test_gpu_batch_ordering.py @@ -47,11 +47,14 @@ def _make_common_attn_metadata(query_lens: list[int]) -> CommonAttentionMetadata ) -def _make_runner(req_states: dict[str, tuple[int, int]]) -> Any: +def _make_runner( + req_states: dict[str, tuple[int, int]], decode_query_len: int = 8 +) -> Any: """Build a runner stub from {req_id: (num_computed_tokens, prefill_len)}.""" prefill_lens = np.array([s[1] for s in req_states.values()], dtype=np.int32) num_computed = np.array([s[0] for s in req_states.values()], dtype=np.int32) runner: Any = GPUModelRunner.__new__(GPUModelRunner) + runner.decode_query_len = decode_query_len runner.req_states = SimpleNamespace( req_id_to_index={req_id: i for i, req_id in enumerate(req_states)}, # The runner keeps this as min(num_computed_tokens, prefill_len). @@ -66,18 +69,14 @@ def _uniform_token_count( query_len: int, dummy_run: bool = False, ) -> int | None: + """Classify via the runner's pre-dispatch gather, as execute_model does.""" scheduler_output = SimpleNamespace( num_scheduled_tokens={req_id: query_len for req_id in req_states}, total_num_scheduled_tokens=query_len * len(req_states), ) - return GPUModelRunner._get_uniform_token_count( - _make_runner(req_states), - scheduler_output, - len(req_states), - query_len * len(req_states), - query_len, - dummy_run, - ) + runner = _make_runner(req_states, decode_query_len=query_len) + _, uniform_tok_count = runner.gather_batch_req_state(scheduler_output, dummy_run) + return uniform_tok_count def test_spec_decode_batch_is_uniform_decode(): @@ -87,37 +86,31 @@ def test_spec_decode_batch_is_uniform_decode(): def test_prompt_chunk_of_decode_query_len_is_not_uniform_decode(): - # Two requests are 8 tokens into a 40-token prompt, so their query length - # only coincides with the K+1 spec-decode query length. Replaying the - # decode graph here corrupts the six decodes as well, so the whole batch - # must be rejected. See https://github.com/vllm-project/vllm/issues/49918. + # Two prompt chunks whose query length coincides with the K+1 spec-decode + # query length must reject the batch (issue #49918). batch = {f"d{i}": (16, 16) for i in range(6)} batch.update({f"p{i}": (8, 40) for i in range(2)}) assert _uniform_token_count(batch, 8) is None - # Same collision without spec decoding: a 1-token prompt looks like a - # 1-token decode step. + # Same collision without spec decoding: 1-token prompt vs 1-token decode. assert _uniform_token_count({"p0": (0, 1)}, 1) is None - # A fresh prompt that happens to be exactly decode_query_len tokens long. + # A fresh prompt of exactly decode_query_len tokens. assert _uniform_token_count({"p0": (0, 8)}, 8) is None def test_dummy_batches_stay_uniform_decode(): - # Dummy batches (DP padding, profiling, warmup) are uniform by - # construction and their requests have no state to consult, so they must be - # classified without one: looking one up would raise KeyError here, and - # rejecting them would make graph capture and replay disagree. + # Dummy batches have no request state to consult and must stay classified + # by shape alone; rejecting them would make capture and replay disagree. scheduler_output = SimpleNamespace( num_scheduled_tokens={f"_dummy_req_{i}": 8 for i in range(4)}, total_num_scheduled_tokens=32, ) - assert ( - GPUModelRunner._get_uniform_token_count( - _make_runner({}), scheduler_output, 4, 32, 8, True - ) - == 8 + state, uniform_tok_count = _make_runner({}).gather_batch_req_state( + scheduler_output, True ) + assert state is None + assert uniform_tok_count == 8 def test_sort_batch_req_ids_no_spec(): @@ -154,15 +147,14 @@ def test_spec_decodes_lead_short_prefill_tail(): def test_uniform_decode_uses_state_index_not_batch_position(): - """The predicate must read each request's own state, not its batch slot. + """The gather must read each request's own state, not its batch slot. - `req_id_to_index` is a persistent map into the runner's state arrays, so a - request's batch position and its state index diverge as requests come and - go. Here the only prefilling request sits at state index 0 while the two - scheduled decodes sit at 1 and 2, so a gather that used batch position - would read the prefilling row and wrongly reject the batch. + Batch position and state index diverge as requests come and go; here the + only prefilling request sits at state index 0, so a gather keyed on batch + position would read its row and wrongly reject the two decodes. """ runner: Any = GPUModelRunner.__new__(GPUModelRunner) + runner.decode_query_len = 8 # State arrays in state-index order: a prefilling request, then two decodes. runner.req_states = SimpleNamespace( req_id_to_index={"prefilling": 0, "decode_a": 1, "decode_b": 2}, @@ -174,12 +166,9 @@ def test_uniform_decode_uses_state_index_not_batch_position(): total_num_scheduled_tokens=16, ) - assert ( - GPUModelRunner._get_uniform_token_count( - runner, scheduler_output, 2, 16, 8, False - ) - == 8 - ) + state, uniform_tok_count = runner.gather_batch_req_state(scheduler_output, False) + assert not state.has_prefill + assert uniform_tok_count == 8 # Scheduling the prefilling request alongside them must reject the batch. scheduler_output.num_scheduled_tokens = { @@ -188,78 +177,25 @@ def test_uniform_decode_uses_state_index_not_batch_position(): "decode_b": 8, } scheduler_output.total_num_scheduled_tokens = 24 - assert ( - GPUModelRunner._get_uniform_token_count( - runner, scheduler_output, 3, 24, 8, False - ) - is None - ) + state, uniform_tok_count = runner.gather_batch_req_state(scheduler_output, False) + assert state.has_prefill + assert uniform_tok_count is None -def test_predicate_agrees_with_is_prefilling(): - """The drafter's call site passes `InputBatch`'s two arrays directly. - - `InputBatch.is_prefilling_np` is documented as - `num_computed_prefill_tokens_np < prefill_len_np`, so the shared predicate - must reject a batch exactly when that flag is set for any request. This - pins the contract the drafter relies on without standing up a speculator. - """ - cases = [ - (np.array([16, 16], dtype=np.int32), np.array([16, 16], dtype=np.int32)), - (np.array([8, 16], dtype=np.int32), np.array([40, 16], dtype=np.int32)), - (np.array([0], dtype=np.int32), np.array([1], dtype=np.int32)), - (np.array([5, 5, 5], dtype=np.int32), np.array([5, 5, 5], dtype=np.int32)), - ] - for num_computed_prefill_tokens, prefill_lens in cases: - num_reqs = len(prefill_lens) - is_prefilling = num_computed_prefill_tokens < prefill_lens - result = get_uniform_decode_token_count( - num_reqs, - 8 * num_reqs, - 8, - num_computed_prefill_tokens, - prefill_lens, - ) - assert (result is None) == bool(is_prefilling.any()), ( - f"{num_computed_prefill_tokens} vs {prefill_lens} -> {result}" - ) - - -def test_non_uniform_shape_is_rejected_without_request_state(): - """The shape test must decide on its own, ahead of any state lookup. - - Most batches are mixed prefill/decode and fail on shape alone, so the O(1) - shape test runs before the per-request prefill state is gathered. A token - count that is not `num_reqs * max_query_len` has to be rejected even when - every request has finished prefilling, as they have here. - """ - num_computed_prefill_tokens = np.array([16, 16], dtype=np.int32) - prefill_lens = np.array([16, 16], dtype=np.int32) - assert ( - get_uniform_decode_token_count( - 2, - 12, # No shared query length over 2 requests produces 12 tokens. - 8, - num_computed_prefill_tokens, - prefill_lens, - ) - is None - ) +def test_uniform_decode_predicate(): + # Shape and prefill state must both pass. + assert get_uniform_decode_token_count(2, 16, 8, False) == 8 + assert get_uniform_decode_token_count(2, 16, 8, True) is None + # 12 tokens over 2 requests is no shared query length. + assert get_uniform_decode_token_count(2, 12, 8, False) is None def test_no_speculator_dispatches_on_query_length_alone(): - """No speculator may pick its cudagraph from a shape test. - - `get_uniform_token_count` and `is_uniform_query_len` both answer a question - about batch shape, which a prompt chunk satisfies by coincidence whenever it - happens to be `1 + num_speculative_tokens` tokens wide. Dispatching on - either replays a decode-captured graph over prompt tokens. - - This is written over the whole package rather than over the one speculator - that had the bug, because speculators are added by copying an existing one: - the shape-only call reappeared verbatim, comment included, in a speculator - added after the original two call sites were fixed. A per-file test would - pass again the next time that happens. + """No speculator may pick its cudagraph from a shape-only test. + + Written over the whole package because speculators are added by copying an + existing one: the shape-only call already reappeared verbatim in a + speculator added after the original call sites were fixed. """ import vllm.v1.worker.gpu.spec_decode as spec_decode diff --git a/vllm/v1/worker/gpu/cudagraph_utils.py b/vllm/v1/worker/gpu/cudagraph_utils.py index 9d7e70eccf63..b7731b6ada1b 100644 --- a/vllm/v1/worker/gpu/cudagraph_utils.py +++ b/vllm/v1/worker/gpu/cudagraph_utils.py @@ -90,18 +90,15 @@ def _is_compatible( def get_uniform_token_count( - num_reqs: int, - num_tokens: int, - max_query_len: int, + num_reqs: int, num_tokens: int, max_query_len: int ) -> int | None: """ Return the uniform token count if batch is uniform, else None. A batch is uniform if all requests have the same number of tokens. - This is a shape test, so it is only valid for batches whose requests are - known to be decoding by construction (e.g. dummy runs, or a drafter step - that emits a fixed number of tokens per request). Batches coming from a - scheduler step must go through `get_uniform_decode_token_count`. + Shape test only, valid for batches known to be decoding by construction + (e.g. dummy runs). Scheduled batches must use + `get_uniform_decode_token_count`. """ if is_uniform_query_len(num_reqs, num_tokens, max_query_len): return max_query_len diff --git a/vllm/v1/worker/gpu/input_batch.py b/vllm/v1/worker/gpu/input_batch.py index 8a952aa043c2..6362e86c1dfb 100644 --- a/vllm/v1/worker/gpu/input_batch.py +++ b/vllm/v1/worker/gpu/input_batch.py @@ -76,6 +76,8 @@ class InputBatch: num_computed_prefill_tokens_np: np.ndarray # [num_reqs] CPU bool array == (num_computed_prefill_tokens_np < prefill_len_np). is_prefilling_np: np.ndarray + # == np.any(is_prefilling_np) + has_prefill: bool # [num_reqs] only populated when pipeline parallelism is enabled. max_seq_len_np: np.ndarray | None @@ -101,10 +103,7 @@ class InputBatch: @classmethod def make_dummy( - cls, - num_reqs: int, - num_tokens: int, - input_buffers: InputBuffers, + cls, num_reqs: int, num_tokens: int, input_buffers: InputBuffers ) -> "InputBatch": assert 0 < num_reqs <= num_tokens device = input_buffers.device @@ -175,6 +174,7 @@ def make_dummy( prefill_len_np=np.zeros(num_reqs, dtype=np.int32), num_computed_prefill_tokens_np=np.zeros(num_reqs, dtype=np.int32), is_prefilling_np=np.zeros(num_reqs, dtype=np.bool_), + has_prefill=False, max_seq_len_np=None, input_ids=input_ids, positions=positions, diff --git a/vllm/v1/worker/gpu/model_runner.py b/vllm/v1/worker/gpu/model_runner.py index 5bbb3bccfa1f..43477e1ec14c 100644 --- a/vllm/v1/worker/gpu/model_runner.py +++ b/vllm/v1/worker/gpu/model_runner.py @@ -137,7 +137,6 @@ KVBlockZeroer, copy_kv_cache_blocks_inplace, get_uniform_decode_token_count, - is_uniform_query_len, ) logger = init_logger(__name__) @@ -979,21 +978,20 @@ def update_requests(self, scheduler_output: SchedulerOutput) -> None: scheduler_output.kv_cache_block_copies, ) - def prepare_inputs( - self, scheduler_output: SchedulerOutput, batch_desc: BatchExecutionDescriptor - ) -> InputBatch: - num_tokens = scheduler_output.total_num_scheduled_tokens - num_tokens_after_padding = batch_desc.num_tokens - assert num_tokens > 0 - if envs.VLLM_MOE_SKIP_PADDING: - # Mark trailing cudagraph-padding rows so kernels can skip work for - # them when supported. - self.input_buffers.is_padding[:num_tokens].fill_(False) - self.input_buffers.is_padding[num_tokens:num_tokens_after_padding].fill_( - True - ) + def gather_batch_req_state( + self, scheduler_output: SchedulerOutput, dummy_run: bool + ) -> tuple["BatchReqState | None", int | None]: + """Gather CPU request state for the scheduled batch, in batch order. + Returns (batch_state, uniform_decode_token_count) + """ num_tokens_per_req = scheduler_output.num_scheduled_tokens num_reqs = len(num_tokens_per_req) + num_toks = scheduler_output.total_num_scheduled_tokens + max_query_len = max(scheduler_output.num_scheduled_tokens.values()) + + if dummy_run: + # Dummy batches are uniform by construction. + return None, get_uniform_token_count(num_reqs, num_toks, max_query_len) # batch_idx -> req_id req_ids = sort_batch_req_ids(num_tokens_per_req, self.decode_query_len) @@ -1002,7 +1000,46 @@ def prepare_inputs( idx_mapping_iter = map(self.req_states.req_id_to_index.__getitem__, req_ids) idx_mapping_np = np.fromiter(idx_mapping_iter, dtype=np.intp, count=num_reqs) + prefill_len_np = self.req_states.prefill_len.np[idx_mapping_np] + num_computed_prefill_tokens_np = self.req_states.num_computed_prefill_tokens[ + idx_mapping_np + ] + is_prefilling_np = num_computed_prefill_tokens_np < prefill_len_np + + batch_state = BatchReqState( + req_ids=req_ids, + num_scheduled_tokens=num_scheduled_tokens, + idx_mapping_np=idx_mapping_np, + prefill_len_np=prefill_len_np, + num_computed_prefill_tokens_np=num_computed_prefill_tokens_np, + is_prefilling_np=is_prefilling_np, + has_prefill=bool(is_prefilling_np.any()), + ) + return batch_state, get_uniform_decode_token_count( + num_reqs, num_toks, max_query_len, batch_state.has_prefill + ) + + def prepare_inputs( + self, + scheduler_output: SchedulerOutput, + batch_req_state: "BatchReqState", + batch_desc: BatchExecutionDescriptor, + ) -> InputBatch: + num_tokens = scheduler_output.total_num_scheduled_tokens + num_tokens_after_padding = batch_desc.num_tokens + assert num_tokens > 0 + if envs.VLLM_MOE_SKIP_PADDING: + # Mark trailing cudagraph-padding rows so kernels can skip work for + # them when supported. + is_padding = self.input_buffers.is_padding + is_padding[:num_tokens].fill_(False) + is_padding[num_tokens:num_tokens_after_padding].fill_(True) + + req_ids = batch_req_state.req_ids + num_scheduled_tokens_np = batch_req_state.num_scheduled_tokens + idx_mapping_np = batch_req_state.idx_mapping_np idx_mapping = async_copy_to_gpu(idx_mapping_np, device=self.device) + num_reqs = len(req_ids) # Get the number of draft tokens for each request. draft_tokens = scheduler_output.scheduled_spec_decode_tokens @@ -1044,20 +1081,16 @@ def prepare_inputs( num_reqs_padded = batch_desc.num_reqs or num_reqs query_start_loc_np = np.empty(self.max_num_reqs + 1, dtype=np.int32) query_start_loc_np[0] = 0 - np.cumsum(num_scheduled_tokens, out=query_start_loc_np[1 : num_reqs + 1]) + np.cumsum(num_scheduled_tokens_np, out=query_start_loc_np[1 : num_reqs + 1]) # Pad for full CUDA graph mode. # Some attention backends like FA3 require query_start_loc to be non-decreasing. query_start_loc_np[num_reqs + 1 :] = num_tokens async_copy_to_gpu(query_start_loc_np, out=self.input_buffers.query_start_loc) query_start_loc_np = query_start_loc_np[: num_reqs_padded + 1] query_start_loc = self.input_buffers.query_start_loc[: num_reqs_padded + 1] - prefill_len_np = self.req_states.prefill_len.np[idx_mapping_np] - computed_prefill_tokens_np = self.req_states.num_computed_prefill_tokens - num_computed_prefill_tokens_np = computed_prefill_tokens_np[idx_mapping_np] - is_prefilling_np = num_computed_prefill_tokens_np < prefill_len_np # Get prefill tokens if any. - if np.any(is_prefilling_np): + if batch_req_state.has_prefill: prepare_prefill_inputs( self.input_buffers.input_ids, self.req_states.next_prefill_tokens, @@ -1111,7 +1144,7 @@ def prepare_inputs( seq_lens_cpu_upper_bound_np = np.zeros(num_reqs_padded, dtype=np.int32) np.add( num_computed_tokens_np, - num_scheduled_tokens, + num_scheduled_tokens_np, out=seq_lens_cpu_upper_bound_np[:num_reqs], ) seq_lens_cpu_upper_bound = torch.from_numpy(seq_lens_cpu_upper_bound_np) @@ -1134,7 +1167,7 @@ def prepare_inputs( idx_mapping_np=idx_mapping_np, expanded_idx_mapping=expanded_idx_mapping, expanded_local_pos=expanded_local_pos, - num_scheduled_tokens=num_scheduled_tokens, + num_scheduled_tokens=num_scheduled_tokens_np, num_tokens=num_tokens, num_tokens_after_padding=num_tokens_after_padding, num_draft_tokens=total_num_draft_tokens, @@ -1145,9 +1178,10 @@ def prepare_inputs( seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound, dcp_local_seq_lens=dcp_local_seq_lens, num_computed_tokens_np=num_computed_tokens_np, - prefill_len_np=prefill_len_np, - num_computed_prefill_tokens_np=num_computed_prefill_tokens_np, - is_prefilling_np=is_prefilling_np, + prefill_len_np=batch_req_state.prefill_len_np, + num_computed_prefill_tokens_np=batch_req_state.num_computed_prefill_tokens_np, + is_prefilling_np=batch_req_state.is_prefilling_np, + has_prefill=batch_req_state.has_prefill, max_seq_len_np=max_seq_len_np, input_ids=self.input_buffers.input_ids[:num_tokens_after_padding], positions=self.input_buffers.positions[:num_tokens_after_padding], @@ -1255,45 +1289,6 @@ def postprocess_sampled( idx_mapping, num_sampled, self.req_states.num_computed_tokens.gpu ) - def _get_uniform_token_count( - self, - scheduler_output: SchedulerOutput, - num_reqs: int, - num_tokens: int, - max_query_len: int, - dummy_run: bool, - ) -> int | None: - """Per-request token count of a uniform decode batch, or None. - - Dummy batches (DP padding, memory profiling, warmup) are uniform by - construction and have no request state to consult, so they are - classified by shape alone. This mirrors `InputBatch.make_dummy`, which - marks every dummy request as not prefilling. - """ - if dummy_run: - return get_uniform_token_count(num_reqs, num_tokens, max_query_len) - # Shape first. This is the same test get_uniform_decode_token_count - # runs before it looks at any request state, and it rejects every - # mixed prefill/decode batch, which is most of them. Checking it here - # keeps the gather below off the hot path in that case. - if not is_uniform_query_len(num_reqs, num_tokens, max_query_len): - return None - idx_mapping_np = np.fromiter( - map( - self.req_states.req_id_to_index.__getitem__, - scheduler_output.num_scheduled_tokens, - ), - dtype=np.intp, - count=num_reqs, - ) - return get_uniform_decode_token_count( - num_reqs, - num_tokens, - max_query_len, - self.req_states.num_computed_prefill_tokens[idx_mapping_np], - self.req_states.prefill_len.np[idx_mapping_np], - ) - @torch.inference_mode() def execute_model( self, @@ -1319,9 +1314,8 @@ def execute_model( # Get batch descriptor and sync across DP ranks. num_reqs = len(scheduler_output.num_scheduled_tokens) num_toks = scheduler_output.total_num_scheduled_tokens - max_query_len = max(scheduler_output.num_scheduled_tokens.values()) - uniform_tok_count = self._get_uniform_token_count( - scheduler_output, num_reqs, num_toks, max_query_len, dummy_run + batch_req_state, uniform_tok_count = self.gather_batch_req_state( + scheduler_output, dummy_run ) num_active_loras = 0 @@ -1357,7 +1351,10 @@ def execute_model( if not dummy_run: # Common case. # Prepare all the inputs and copy to the input buffers. - input_batch = self.prepare_inputs(scheduler_output, batch_desc) + assert batch_req_state is not None + input_batch = self.prepare_inputs( + scheduler_output, batch_req_state, batch_desc + ) block_tables, slot_mappings = self.prepare_attn(input_batch) # Mamba "align" pre-copy: migrate recurrent state across block # boundaries before the forward. Runs only on real batches, and @@ -1836,6 +1833,18 @@ class ExecuteModelState(NamedTuple): routed_experts: RoutedExpertsTensors | None +class BatchReqState(NamedTuple): + """CPU request state for a scheduled batch, in batch (sorted) order.""" + + req_ids: list[str] + num_scheduled_tokens: np.ndarray # [num_reqs] + idx_mapping_np: np.ndarray # [num_reqs] + prefill_len_np: np.ndarray # [num_reqs] + num_computed_prefill_tokens_np: np.ndarray # [num_reqs] + is_prefilling_np: np.ndarray # [num_reqs] + has_prefill: bool + + def sort_batch_req_ids( num_tokens_per_req: dict[str, int], decode_query_len: int ) -> list[str]: diff --git a/vllm/v1/worker/gpu/pcp_manager.py b/vllm/v1/worker/gpu/pcp_manager.py index 587293471c03..d80e246f17c9 100644 --- a/vllm/v1/worker/gpu/pcp_manager.py +++ b/vllm/v1/worker/gpu/pcp_manager.py @@ -529,6 +529,7 @@ def partition_batch(self, input_batch: InputBatch) -> InputBatch: prefill_len_np=local_prefill_len_np, num_computed_prefill_tokens_np=local_num_computed_prefill_tokens_np, is_prefilling_np=local_is_prefilling_np, + has_prefill=bool(local_is_prefilling_np.any()), max_seq_len_np=global_batch.max_seq_len_np[local_to_global_batch_req_idx_np] if global_batch.max_seq_len_np is not None else None, diff --git a/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py b/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py index 2b269a402518..57430529f61a 100644 --- a/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/autoregressive/speculator.py @@ -277,8 +277,7 @@ def propose( # the target model during FULL cudagraph. num_tokens, max_query_len, - input_batch.num_computed_prefill_tokens_np, - input_batch.prefill_len_np, + input_batch.has_prefill, ) prefill_batch_desc, num_tokens_across_dp = dispatch_cg_and_sync_dp( self.prefill_cudagraph_manager, diff --git a/vllm/v1/worker/gpu/spec_decode/multi_module_mtp/speculator.py b/vllm/v1/worker/gpu/spec_decode/multi_module_mtp/speculator.py index 61d1c0003f39..fc147b3f4915 100644 --- a/vllm/v1/worker/gpu/spec_decode/multi_module_mtp/speculator.py +++ b/vllm/v1/worker/gpu/spec_decode/multi_module_mtp/speculator.py @@ -189,11 +189,7 @@ def propose( # When all requests are decoding (no true prefills), each has # num_speculative_steps + 1 tokens, enabling FULL graph replay. uniform_token_count = get_uniform_decode_token_count( - num_reqs, - num_tokens, - max_query_len, - input_batch.num_computed_prefill_tokens_np, - input_batch.prefill_len_np, + num_reqs, num_tokens, max_query_len, input_batch.has_prefill ) batch_desc, num_tokens_across_dp = dispatch_cg_and_sync_dp( self.cudagraph_manager, diff --git a/vllm/v1/worker/utils.py b/vllm/v1/worker/utils.py index ef168c8f5078..f495579ddb12 100644 --- a/vllm/v1/worker/utils.py +++ b/vllm/v1/worker/utils.py @@ -614,58 +614,19 @@ def copy_kv_cache_blocks_inplace( def is_uniform_query_len(num_reqs: int, num_tokens: int, max_query_len: int) -> bool: """Whether every request in the batch has the same query length. - This tests the batch shape only. Callers classifying a scheduled batch as a - decode batch must use ``get_uniform_decode_token_count`` instead, because a - prompt chunk can have a decode batch's shape. - - Args: - num_reqs: Number of requests in the batch. - num_tokens: Total number of tokens in the batch. - max_query_len: Largest per-request query length in the batch. + Shape test only; use ``get_uniform_decode_token_count`` to classify a + scheduled batch, since a prompt chunk can have a decode batch's shape. """ return num_reqs > 0 and num_tokens == max_query_len * num_reqs def get_uniform_decode_token_count( - num_reqs: int, - num_tokens: int, - max_query_len: int, - num_computed_tokens: np.ndarray, - prefill_lens: np.ndarray, + num_reqs: int, num_tokens: int, max_query_len: int, has_prefill: bool ) -> int | None: - """Per-request token count of a uniform decode batch, or None. - - A batch is a uniform decode batch only if every request has the same query - length *and* no request is still prefilling. Query length alone is a shape - test that a prompt chunk satisfies by coincidence: a prompt chunk of - ``1 + num_speculative_tokens`` tokens has the shape of a spec-decode step, - and a 1-token chunk has the shape of a plain decode step. Classifying such - a batch as a decode batch replays a decode-captured cudagraph over prompt - tokens, whose captured kernels read per-request state that a prefill - metadata build does not refresh. - - Args: - num_reqs: Number of requests in the batch. - num_tokens: Total number of tokens in the batch. - max_query_len: Largest per-request query length in the batch. - num_computed_tokens: Per-request tokens computed before this step, in - batch order. Must be exactly ``num_reqs`` long; a full - ``max_num_reqs`` state array would compare the wrong requests. - prefill_lens: Per-request prefill length, i.e. the prompt plus any - output tokens recomputed after preemption, in batch order. Same - length requirement. - - Returns: - The shared per-request query length, or None if the batch is not a - uniform decode batch. - """ - if not is_uniform_query_len(num_reqs, num_tokens, max_query_len): - return None - # Equivalent to `InputBatch.is_prefilling_np.any()`, which the drafter's - # call site derives from the same two arrays. - if np.any(num_computed_tokens < prefill_lens): - return None - return max_query_len + """Per-request token count of a uniform decode batch, or None.""" + if not has_prefill and is_uniform_query_len(num_reqs, num_tokens, max_query_len): + return max_query_len + return None def is_residual_scattered_for_sp(