Merge remote-tracking branch 'upstream/main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Routing/selection tests for the AITER ASM cprr DCP-verify route.
|
||||
|
||||
Companion to the upstream segmented-verify tests. Everything here is pure CPU:
|
||||
it pins the *decisions* (which route a KV group takes, which head count the
|
||||
kernel runs at, which configurations are refused) rather than kernel numerics.
|
||||
The numerics parity test against the segmented route needs a GPU and both
|
||||
routes built; it is marked and skipped when unavailable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
rocm_aiter_mla = pytest.importorskip(
|
||||
"vllm.v1.attention.backends.mla.rocm_aiter_mla",
|
||||
reason="ROCm AITER MLA backend not available",
|
||||
)
|
||||
|
||||
_heads = rocm_aiter_mla._asm_dcp_verify_heads
|
||||
_configured = rocm_aiter_mla._asm_dcp_verify_configured
|
||||
_select_route = rocm_aiter_mla._select_dcp_decode_route
|
||||
Route = rocm_aiter_mla._DCPDecodeRoute
|
||||
NATIVE = rocm_aiter_mla._NATIVE_CPRR_HEADS
|
||||
MIN_QLEN = rocm_aiter_mla._MIN_CPRR_QLEN
|
||||
|
||||
|
||||
def test_dcp_verify_env_defaults_to_segmented(monkeypatch):
|
||||
monkeypatch.delenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", raising=False)
|
||||
assert rocm_aiter_mla.envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY == "segmented"
|
||||
|
||||
|
||||
def test_dcp_verify_env_rejects_unknown_route(monkeypatch):
|
||||
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", "unknown")
|
||||
with pytest.raises(ValueError, match="Invalid value"):
|
||||
_ = rocm_aiter_mla.envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# _asm_dcp_verify_heads -- which head count the cprr kernel runs at
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("n", NATIVE)
|
||||
def test_native_head_counts_are_used_as_is(n):
|
||||
assert _heads(n) == n
|
||||
|
||||
|
||||
def test_non_native_head_count_pads_up_to_the_next_native():
|
||||
"""K3 at TP8/DCP8 gathers 96 heads for the target; the kernel has no 96
|
||||
variant, so it must run at 128, not silently fall out of the asm path."""
|
||||
assert _heads(96) == 128
|
||||
assert _heads(1) == 16
|
||||
assert _heads(17) == 32
|
||||
assert _heads(65) == 128
|
||||
|
||||
|
||||
def test_head_count_above_the_largest_native_is_unservable():
|
||||
"""0 means 'cannot serve'; anything else would route a shape the kernel
|
||||
has no build for."""
|
||||
assert _heads(max(NATIVE) + 1) == 0
|
||||
assert _heads(256) == 0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# _asm_dcp_verify_configured -- reachability
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def on_gfx950(monkeypatch):
|
||||
"""The cprr kernels are built only for gfx950, so the gate checks the arch.
|
||||
Patched rather than detected, so both branches run on any runner."""
|
||||
import vllm.platforms.rocm as rocm
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx950", lambda: True)
|
||||
|
||||
|
||||
def test_route_needs_dcp(on_gfx950):
|
||||
assert _configured(dcp_world_size=1, cp_interleave=1, multi_token_decode=True) is (
|
||||
False
|
||||
)
|
||||
assert _configured(dcp_world_size=8, cp_interleave=1, multi_token_decode=True) is (
|
||||
True
|
||||
)
|
||||
|
||||
|
||||
def test_round_robin_interleave_other_than_one_is_excluded(on_gfx950):
|
||||
"""The kernel's global-position causal window assumes interleave 1, the
|
||||
same restriction the segmented gate carries."""
|
||||
assert _configured(dcp_world_size=8, cp_interleave=2, multi_token_decode=True) is (
|
||||
False
|
||||
)
|
||||
assert _configured(dcp_world_size=8, cp_interleave=16, multi_token_decode=True) is (
|
||||
False
|
||||
)
|
||||
|
||||
|
||||
def test_route_needs_multi_token_decode(on_gfx950):
|
||||
"""Single-token decode is already served. Enabling the route for it would
|
||||
pad the head count on every step and buy nothing."""
|
||||
assert _configured(dcp_world_size=8, cp_interleave=1, multi_token_decode=False) is (
|
||||
False
|
||||
)
|
||||
|
||||
|
||||
def test_route_needs_gfx950(monkeypatch):
|
||||
"""hsa/gfx942/mla and hsa/gfx1250/mla carry no cprr rows, so off gfx950 the
|
||||
kernel lookup fails at the first verify step rather than falling back."""
|
||||
import vllm.platforms.rocm as rocm
|
||||
|
||||
monkeypatch.setattr(rocm, "on_gfx950", lambda: False)
|
||||
assert _configured(dcp_world_size=8, cp_interleave=1, multi_token_decode=True) is (
|
||||
False
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# qlen floor
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_min_cprr_qlen_is_above_two():
|
||||
"""Qlen 2 is below CPRR's floor and must use segmented verification."""
|
||||
assert MIN_QLEN > 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"supports,causal,qlen,asm,expected",
|
||||
[
|
||||
(True, True, 1, True, Route.PLAIN),
|
||||
(True, True, 2, True, Route.SEGMENTED),
|
||||
(True, True, 3, True, Route.CPRR),
|
||||
(True, True, 4, True, Route.CPRR),
|
||||
(True, True, 4, False, Route.SEGMENTED),
|
||||
(True, False, 2, True, Route.PLAIN),
|
||||
(True, False, 4, False, Route.PLAIN),
|
||||
(False, True, 3, True, Route.CPRR),
|
||||
],
|
||||
)
|
||||
def test_dcp_decode_route(supports, causal, qlen, asm, expected):
|
||||
assert _select_route(supports, causal, qlen, asm) is expected
|
||||
|
||||
|
||||
def test_causal_multi_token_batch_without_a_valid_route_fails():
|
||||
with pytest.raises(RuntimeError, match="requires either segmented MLA"):
|
||||
_select_route(False, True, 2, True)
|
||||
|
||||
|
||||
# Kernel numerics live in test_rocm_aiter_mla_dcp_cprr_numerics.py, which runs
|
||||
# the real builder and the real asm kernel on a gfx950 GPU.
|
||||
@@ -0,0 +1,540 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""GPU numerics for the AITER ASM cprr DCP-verify route.
|
||||
|
||||
Runs the REAL metadata builder (``AiterMLAMetadataBuilder.build``, so
|
||||
``get_mla_metadata_v1`` is exercised with the cprr kwargs and the persistent
|
||||
schedule buffers are produced) and the REAL asm kernel, on ONE GPU with the DCP
|
||||
ranks simulated one after another.
|
||||
|
||||
That is legitimate because the aiter MLA backend contains no collective on this
|
||||
path: the query all-gather happens in the *layer*, strictly before
|
||||
``forward_mqa``, so the head fold, the round-robin kernel call and the un-fold
|
||||
are pure per-rank local arithmetic in which ``cp_world_size``/``cp_rank`` are
|
||||
just numbers feeding the causal-mask maths. Restricting a shard to a residue
|
||||
class of global positions is exactly what DCP rank r sees.
|
||||
|
||||
Three properties are checked:
|
||||
* each shard matches an exact torch reference over the positions it holds,
|
||||
with causality applied on the GLOBAL position (the thing cprr reconstructs
|
||||
in-kernel and the segmented route instead carries in per-row lengths);
|
||||
* the LSE merge of all shards reproduces full-context attention;
|
||||
* a shard told the wrong ``cp_rank`` fails both -- without this positive
|
||||
control a passing run proves nothing, since a kernel that ignored global
|
||||
positions still produces plausible-looking output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
pytest.skip("ROCm AITER MLA tests", allow_module_level=True)
|
||||
|
||||
from vllm._aiter_ops import is_aiter_found # noqa: E402
|
||||
from vllm.v1.attention.backends.mla import rocm_aiter_mla # noqa: E402
|
||||
|
||||
KV_LORA_RANK = 512
|
||||
QK_ROPE_HEAD_DIM = 64
|
||||
QK_NOPE_HEAD_DIM = 128
|
||||
HEAD_SIZE = KV_LORA_RANK + QK_ROPE_HEAD_DIM
|
||||
SCALE = (QK_NOPE_HEAD_DIM + QK_ROPE_HEAD_DIM) ** -0.5
|
||||
|
||||
DCP = 8
|
||||
NUM_REQS = 8
|
||||
CTX = 256
|
||||
QLEN = 5 # 1 + num_speculative_tokens; must clear _MIN_CPRR_QLEN
|
||||
|
||||
# fp8-e4m3 keeps 3 mantissa bits, so the relative error floor is ~6.2e-2. Gates
|
||||
# are relative for the same reason: an absolute bound would just be a bound on
|
||||
# the output magnitude.
|
||||
SHARD_RTOL = 1.0e-1
|
||||
MERGE_RTOL = 5.0e-2
|
||||
|
||||
MODEL = "deepseek-ai/DeepSeek-R1"
|
||||
|
||||
|
||||
def _gpu_available() -> bool:
|
||||
return is_aiter_found() and torch.accelerator.is_available()
|
||||
|
||||
|
||||
def _on_gfx950() -> bool:
|
||||
if not is_aiter_found():
|
||||
return False
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
|
||||
return on_gfx950()
|
||||
|
||||
|
||||
requires_cprr = pytest.mark.skipif(
|
||||
not (_gpu_available() and _on_gfx950()),
|
||||
reason="cprr DCP verify needs ROCm + AITER on gfx950",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def select_asm_route(monkeypatch):
|
||||
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", "asm")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# reference maths
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _torch_reference(q_f32, kv_f32, ctx, qlen, scale, positions):
|
||||
"""Exact absorbed-MLA decode over an explicit set of GLOBAL KV positions.
|
||||
|
||||
A shard sees only ``positions``, but causality still uses the global
|
||||
position: query token i (global position ctx + i) may attend to any p in
|
||||
positions with p <= ctx + i. Restricting ``positions`` to a round-robin
|
||||
residue class is precisely DCP rank r's view.
|
||||
"""
|
||||
nr, _, heads, _ = q_f32.shape
|
||||
dev = q_f32.device
|
||||
o = torch.zeros(nr, qlen, heads, KV_LORA_RANK, dtype=torch.float32, device=dev)
|
||||
lse = torch.full((nr, qlen, heads), float("-inf"), dtype=torch.float32, device=dev)
|
||||
for r in range(nr):
|
||||
kv_sel = kv_f32[r].index_select(0, positions)
|
||||
for i in range(qlen):
|
||||
valid = positions <= (ctx + i)
|
||||
if not bool(valid.any()):
|
||||
continue
|
||||
k = kv_sel[valid]
|
||||
s = (q_f32[r, i] @ k.T) * scale
|
||||
m = s.max(dim=-1, keepdim=True).values
|
||||
p = torch.exp(s - m)
|
||||
denom = p.sum(dim=-1, keepdim=True)
|
||||
o[r, i] = (p / denom) @ k[:, :KV_LORA_RANK]
|
||||
lse[r, i] = m.squeeze(-1) + torch.log(denom.squeeze(-1))
|
||||
return o, lse
|
||||
|
||||
|
||||
def _merge_partials(os_, lses):
|
||||
"""Cross-shard softmax merge (natural-log LSE)."""
|
||||
stack_lse = torch.stack(lses)
|
||||
m = stack_lse.max(dim=0).values
|
||||
w = torch.exp(stack_lse - m)
|
||||
num = (w.unsqueeze(-1) * torch.stack(os_)).sum(dim=0)
|
||||
den = w.sum(dim=0).unsqueeze(-1)
|
||||
return num / den, m + torch.log(w.sum(dim=0))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# single-process rank simulation
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _FakeGroup:
|
||||
def __init__(self, world_size: int, rank: int):
|
||||
self.world_size = world_size
|
||||
self.rank_in_group = rank
|
||||
self.rank = rank
|
||||
self.local_rank = rank
|
||||
|
||||
def all_gather(self, tensor, dim=0):
|
||||
raise RuntimeError(
|
||||
"collective called in a single-process test -- the path under test "
|
||||
"is supposed to be collective-free; this indicates a real change"
|
||||
)
|
||||
|
||||
|
||||
def _install_fake_groups(dcp_size: int, cp_rank: int, tp_size: int = 1) -> None:
|
||||
"""Point vLLM's parallel_state at rank-simulating stubs (no NCCL)."""
|
||||
import vllm.distributed.parallel_state as ps
|
||||
import vllm.model_executor.layers.attention.mla_attention as mla_attention
|
||||
import vllm.v1.attention.backends.mla.rocm_aiter_mla as backend
|
||||
|
||||
dcp = _FakeGroup(dcp_size, cp_rank)
|
||||
tp = _FakeGroup(tp_size, cp_rank)
|
||||
ps.get_dcp_group = lambda: dcp
|
||||
ps.get_tp_group = lambda: tp
|
||||
# Both of these imported the symbol directly at module import time, so
|
||||
# patching parallel_state alone leaves them resolving the real group (and
|
||||
# the builder then reports dcp_world_size 1, silently skipping the route).
|
||||
backend.get_dcp_group = lambda: dcp
|
||||
mla_attention.get_dcp_group = lambda: dcp
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _restore_parallel_groups():
|
||||
"""Undo _install_fake_groups after every test.
|
||||
|
||||
It patches module globals in three modules, so without this the fake DCP
|
||||
group leaks into the rest of the pytest session and silently breaks
|
||||
unrelated tests that expect a real (or absent) group.
|
||||
"""
|
||||
import vllm.distributed.parallel_state as ps
|
||||
import vllm.model_executor.layers.attention.mla_attention as mla_attention
|
||||
import vllm.v1.attention.backends.mla.rocm_aiter_mla as backend
|
||||
|
||||
saved = [
|
||||
(mod, name, getattr(mod, name))
|
||||
for mod, name in (
|
||||
(ps, "get_dcp_group"),
|
||||
(ps, "get_tp_group"),
|
||||
(backend, "get_dcp_group"),
|
||||
(mla_attention, "get_dcp_group"),
|
||||
)
|
||||
]
|
||||
yield
|
||||
for mod, name, value in saved:
|
||||
setattr(mod, name, value)
|
||||
|
||||
|
||||
class _PrefillBackendStub:
|
||||
"""The base builder does ``attention_layer.prefill_backend.clone()``.
|
||||
|
||||
prefill_backend is consulted only from the chunked-context prefill path,
|
||||
which a decode-only test never enters.
|
||||
"""
|
||||
|
||||
def clone(self):
|
||||
return self
|
||||
|
||||
|
||||
def _make_ctx_layer(vllm_config):
|
||||
"""Stand-in for the registered attention layer in static_forward_context.
|
||||
|
||||
``MLACommonMetadataBuilder.__init__`` reads the MLA dims, ``dcp_manager``
|
||||
and ``prefill_backend`` off this object. ``dcp_manager`` is the Direct-DCP
|
||||
symmetric-memory workspace, used ONLY by the chunked-prefill KV all-gather;
|
||||
it is constructed without running __init__ so no peer pointers are exchanged
|
||||
and no collective is issued. That is what keeps this test single-process.
|
||||
"""
|
||||
from vllm.v1.attention.ops.dcp import MLADCPManager
|
||||
|
||||
mgr = object.__new__(MLADCPManager)
|
||||
mgr.init_kv_gather = lambda *a, **k: None
|
||||
|
||||
return SimpleNamespace(
|
||||
non_causal_multi_token_decode=False,
|
||||
q_lora_rank=None,
|
||||
kv_lora_rank=KV_LORA_RANK,
|
||||
qk_nope_head_dim=QK_NOPE_HEAD_DIM,
|
||||
qk_rope_head_dim=QK_ROPE_HEAD_DIM,
|
||||
v_head_dim=QK_NOPE_HEAD_DIM,
|
||||
dcp_manager=mgr,
|
||||
prefill_backend=_PrefillBackendStub(),
|
||||
)
|
||||
|
||||
|
||||
def _ensure_workspace_manager(device: torch.device) -> None:
|
||||
"""Init the global workspace manager, which GPUModelRunner does in production.
|
||||
|
||||
``AiterMLAMetadataBuilder.__init__`` reserves the fp8 prefill
|
||||
persistent-scheduling scratch through ``current_workspace_manager()``, so
|
||||
merely constructing a builder outside a serve trips its assert. Idempotent:
|
||||
one builder is constructed per DCP shard. Deliberately does NOT lock the
|
||||
workspace -- production locks only after warmup, and this keeps allocating
|
||||
across shards.
|
||||
"""
|
||||
from vllm.v1.worker.workspace import (
|
||||
init_workspace_manager,
|
||||
is_workspace_manager_initialized,
|
||||
)
|
||||
|
||||
if not is_workspace_manager_initialized():
|
||||
init_workspace_manager(device)
|
||||
|
||||
|
||||
class _Layer:
|
||||
def __init__(self, device):
|
||||
self._q_scale = torch.tensor(1.0, device=device)
|
||||
self._k_scale = torch.tensor(1.0, device=device)
|
||||
self._v_scale = torch.tensor(1.0, device=device)
|
||||
|
||||
|
||||
def _build_impl(num_heads: int, dcp: int, cp_rank: int):
|
||||
"""Real AiterMLAImpl.forward_mqa bound to a minimally-populated instance.
|
||||
|
||||
Constructing the full impl would drag in kv_b_proj and the rest of the
|
||||
weight-dependent MLA setup -- i.e. model loading, which this test exists to
|
||||
avoid. forward_mqa's fold path reads only the attributes set below.
|
||||
"""
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAImpl
|
||||
|
||||
impl = object.__new__(AiterMLAImpl)
|
||||
impl.kv_lora_rank = KV_LORA_RANK
|
||||
impl.qk_rope_head_dim = QK_ROPE_HEAD_DIM
|
||||
impl.num_heads = num_heads
|
||||
impl.dcp_world_size = dcp
|
||||
impl.dcp_rank = cp_rank
|
||||
impl.pcp_world_size = 1
|
||||
impl.kv_cache_dtype = "fp8"
|
||||
impl.scale = SCALE
|
||||
# `_decode_num_heads` is a read-only property deriving num_heads *
|
||||
# dcp_world_size, both set above; assert rather than assign.
|
||||
assert impl._decode_num_heads == num_heads * dcp
|
||||
return impl
|
||||
|
||||
|
||||
def _make_vllm_config(heads_per_rank: int):
|
||||
"""A DCP8 MLA config with no weights and no distributed init.
|
||||
|
||||
DeepSeek-R1's config supplies the MLA dims (kv_lora_rank 512, rope 64,
|
||||
nope 128) that the aiter asm kernel is built for; only the head count is
|
||||
overridden, to place the GATHERED count (heads_per_rank * DCP) on the
|
||||
kernel variant under test. ``get_num_attention_heads`` reads
|
||||
model_arch_config, a snapshot taken at config-creation time, so patching
|
||||
hf_config alone would be inert.
|
||||
"""
|
||||
from tests.v1.attention.utils import create_vllm_config
|
||||
|
||||
vllm_config = create_vllm_config(
|
||||
model_name=MODEL,
|
||||
tensor_parallel_size=1,
|
||||
max_model_len=2048,
|
||||
max_num_seqs=NUM_REQS * 2,
|
||||
max_num_batched_tokens=4096,
|
||||
)
|
||||
vllm_config.model_config.model_arch_config.total_num_attention_heads = (
|
||||
heads_per_rank
|
||||
)
|
||||
# Without a speculative config the batch reorder threshold stays at 1 and a
|
||||
# qlen-QLEN row is classified as a PREFILL, so the decode path under test is
|
||||
# never reached. _init_reorder_batch_threshold reads exactly these two
|
||||
# fields, so a stand-in is enough and avoids pulling in a draft model.
|
||||
vllm_config.speculative_config = SimpleNamespace(
|
||||
num_speculative_tokens=QLEN - 1, parallel_drafting=False
|
||||
)
|
||||
vllm_config.cache_config.cache_dtype = "fp8"
|
||||
vllm_config.parallel_config.decode_context_parallel_size = DCP
|
||||
vllm_config.parallel_config.cp_kv_cache_interleave_size = 1
|
||||
return vllm_config
|
||||
|
||||
|
||||
def _run_shard(
|
||||
vllm_config,
|
||||
spec,
|
||||
layer_name,
|
||||
device,
|
||||
cp_rank,
|
||||
kern_rank,
|
||||
q_flat,
|
||||
kv_flat,
|
||||
nr,
|
||||
qlen,
|
||||
ctx,
|
||||
dcp,
|
||||
pos,
|
||||
):
|
||||
"""Build real metadata for one DCP rank and run the real asm kernel.
|
||||
|
||||
``kern_rank`` is separate from ``cp_rank`` so the positive control can hand
|
||||
rank r's pages to the kernel while telling it that it is rank r+1.
|
||||
"""
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAMetadataBuilder
|
||||
|
||||
L = ctx + qlen
|
||||
local_len = int(pos.numel())
|
||||
|
||||
# One GLOBAL kv cache: page (req*L + p) holds request req position p. Shards
|
||||
# select pages by residue class, so every shard reads the same underlying
|
||||
# bytes and no re-quantisation noise is introduced between arms.
|
||||
block_table = (
|
||||
torch.arange(nr, device=device).view(nr, 1) * L + pos.view(1, -1)
|
||||
).to(torch.int32)
|
||||
|
||||
# seq_lens is the GLOBAL context; dcp_local_seq_lens is what this rank
|
||||
# actually holds. Passing the global length as the local one walks the
|
||||
# kernel off the end of the page table.
|
||||
seq_lens_cpu = torch.full((nr,), L, dtype=torch.int32)
|
||||
local_cpu = torch.full((nr,), local_len, dtype=torch.int32)
|
||||
|
||||
common = CommonAttentionMetadata(
|
||||
query_start_loc=torch.arange(
|
||||
0, nr * qlen + 1, qlen, dtype=torch.int32, device=device
|
||||
),
|
||||
query_start_loc_cpu=torch.arange(0, nr * qlen + 1, qlen, dtype=torch.int32),
|
||||
seq_lens=seq_lens_cpu.to(device),
|
||||
num_reqs=nr,
|
||||
num_actual_tokens=nr * qlen,
|
||||
max_query_len=qlen,
|
||||
max_seq_len=L,
|
||||
block_table_tensor=block_table,
|
||||
slot_mapping=torch.arange(nr * qlen, dtype=torch.int64, device=device),
|
||||
causal=True,
|
||||
dcp_local_seq_lens=local_cpu.to(device),
|
||||
dcp_local_seq_lens_cpu_upper_bound=local_cpu,
|
||||
)
|
||||
|
||||
_install_fake_groups(dcp, kern_rank)
|
||||
builder = AiterMLAMetadataBuilder(spec, [layer_name], vllm_config, device)
|
||||
md = builder.build(0, common)
|
||||
|
||||
impl = _build_impl(builder.num_heads, dcp, kern_rank)
|
||||
o, lse = impl.forward_mqa(q_flat, kv_flat, md, _Layer(device))
|
||||
torch.accelerator.synchronize()
|
||||
return md, o, lse, local_len
|
||||
|
||||
|
||||
def _numerics(heads_per_rank: int, sabotage: bool = False):
|
||||
"""Run every DCP shard and return (per-shard max rel err, merged rel err)."""
|
||||
import aiter
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
|
||||
device = torch.device("cuda", 0)
|
||||
torch.accelerator.set_device_index(device.index)
|
||||
torch.manual_seed(0)
|
||||
_ensure_workspace_manager(device)
|
||||
|
||||
_install_fake_groups(DCP, 0)
|
||||
vllm_config = _make_vllm_config(heads_per_rank)
|
||||
|
||||
with set_current_vllm_config(vllm_config):
|
||||
from vllm.v1.kv_cache_interface import MLAAttentionSpec
|
||||
|
||||
layer_name = "model.layers.0.self_attn.attn"
|
||||
vllm_config.compilation_config.static_forward_context[layer_name] = (
|
||||
_make_ctx_layer(vllm_config)
|
||||
)
|
||||
# block_size 1: one page per token, so page ids are positions and the
|
||||
# residue-class page table is expressible directly.
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=1,
|
||||
num_kv_heads=1,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=vllm_config.model_config.dtype,
|
||||
non_causal_multi_token_decode=False,
|
||||
)
|
||||
|
||||
nr, ctx, qlen = NUM_REQS, CTX, QLEN
|
||||
L = ctx + qlen
|
||||
gathered_heads = heads_per_rank * DCP
|
||||
kv_dtype = aiter.dtypes.fp8
|
||||
|
||||
kv_flat = torch.randn(
|
||||
nr * L, 1, HEAD_SIZE, dtype=torch.float32, device=device
|
||||
).to(kv_dtype)
|
||||
q_flat = (
|
||||
torch.randn(
|
||||
nr * qlen,
|
||||
gathered_heads,
|
||||
HEAD_SIZE,
|
||||
dtype=torch.float32,
|
||||
device=device,
|
||||
)
|
||||
.mul_(0.5)
|
||||
.to(kv_dtype)
|
||||
)
|
||||
# Dequantise for the reference so the comparison measures the kernel,
|
||||
# not the fp8 cast that both sides share.
|
||||
kv_f32 = kv_flat.float().view(nr, L, HEAD_SIZE)
|
||||
q_f32 = q_flat.float().view(nr, qlen, gathered_heads, HEAD_SIZE)
|
||||
|
||||
ref_o, _ = _torch_reference(
|
||||
q_f32, kv_f32, ctx, qlen, SCALE, torch.arange(L, device=device)
|
||||
)
|
||||
|
||||
shard_o, shard_lse = [], []
|
||||
max_shard_rel = 0.0
|
||||
for r in range(DCP):
|
||||
pos = torch.arange(r, L, DCP, device=device) # residue class r
|
||||
kern_rank = (r + 1) % DCP if sabotage else r
|
||||
md, o, lse, _ = _run_shard(
|
||||
vllm_config,
|
||||
spec,
|
||||
layer_name,
|
||||
device,
|
||||
r,
|
||||
kern_rank,
|
||||
q_flat,
|
||||
kv_flat,
|
||||
nr,
|
||||
qlen,
|
||||
ctx,
|
||||
DCP,
|
||||
pos,
|
||||
)
|
||||
# The route actually under test must have been taken; a silent
|
||||
# fall-out to Triton/segmented would otherwise pass quietly.
|
||||
assert md.decode.dcp_route is rocm_aiter_mla._DCPDecodeRoute.CPRR
|
||||
assert md.decode.asm_decode_num_heads, "cprr asm route was not taken"
|
||||
|
||||
o = o.float().view(nr, qlen, gathered_heads, KV_LORA_RANK)
|
||||
shard_lse.append(lse.float().view(nr, qlen, gathered_heads))
|
||||
shard_o.append(o)
|
||||
|
||||
po, _ = _torch_reference(q_f32, kv_f32, ctx, qlen, SCALE, pos)
|
||||
rel = (o - po).abs().max().item() / max(po.abs().max().item(), 1e-6)
|
||||
max_shard_rel = max(max_shard_rel, rel)
|
||||
|
||||
merged, _ = _merge_partials(shard_o, shard_lse)
|
||||
merge_rel = (merged - ref_o).abs().max().item() / max(
|
||||
ref_o.abs().max().item(), 1e-6
|
||||
)
|
||||
return max_shard_rel, merge_rel
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# tests
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@requires_cprr
|
||||
@pytest.mark.parametrize(
|
||||
"heads_per_rank",
|
||||
[
|
||||
16, # 128 gathered heads -- a NATIVE cprr kernel, no padding
|
||||
12, # 96 gathered heads -- K3's DSpark target, must pad up to 128
|
||||
],
|
||||
ids=["native-128", "padded-96-to-128"],
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_cprr_shards_match_reference_and_merge_to_full_context(heads_per_rank):
|
||||
"""Every DCP shard must be right, and their LSE merge must reproduce
|
||||
full-context attention.
|
||||
|
||||
A shard that ignored global positions (applying a local causal tail
|
||||
instead) still produces plausible-looking output; it only diverges from the
|
||||
reference on the tokens whose causal window is truncated. Checking the merge
|
||||
alone would hide that, so both are asserted.
|
||||
"""
|
||||
shard_rel, merge_rel = _numerics(heads_per_rank)
|
||||
assert shard_rel < SHARD_RTOL, f"per-shard rel err {shard_rel:.3e}"
|
||||
assert merge_rel < MERGE_RTOL, f"merged rel err {merge_rel:.3e}"
|
||||
|
||||
|
||||
@requires_cprr
|
||||
@torch.inference_mode()
|
||||
def test_wrong_cp_rank_breaks_the_result():
|
||||
"""Positive control: without it, a passing run above proves nothing.
|
||||
|
||||
Feeding shard r's pages to the kernel while telling it that it is rank r+1
|
||||
shifts every reconstructed global position by one, so both the causal mask
|
||||
and the round-robin reconstruction are wrong. If the error does NOT blow up,
|
||||
the kernel is not using cp_rank and the test above has no power.
|
||||
"""
|
||||
shard_rel, merge_rel = _numerics(16, sabotage=True)
|
||||
assert shard_rel > SHARD_RTOL or merge_rel > MERGE_RTOL, (
|
||||
f"sabotaged run still passed (shard {shard_rel:.3e}, merge "
|
||||
f"{merge_rel:.3e}) -- cp_rank is not reaching the kernel"
|
||||
)
|
||||
|
||||
|
||||
@requires_cprr
|
||||
def test_cprr_kernel_is_selected_for_the_k3_shape():
|
||||
"""The K3 DSpark target shape must actually reach the cprr route.
|
||||
|
||||
Guards against a silent fall-out to segmented/Triton, which is what the
|
||||
stock configuration does and what this route exists to avoid.
|
||||
"""
|
||||
from vllm.v1.attention.backends.mla import rocm_aiter_mla as m
|
||||
|
||||
assert (
|
||||
m._asm_dcp_verify_configured(
|
||||
dcp_world_size=DCP, cp_interleave=1, multi_token_decode=True
|
||||
)
|
||||
is True
|
||||
)
|
||||
assert QLEN >= m._MIN_CPRR_QLEN
|
||||
assert m._select_dcp_decode_route(True, True, QLEN, True) is m._DCPDecodeRoute.CPRR
|
||||
assert m._asm_dcp_verify_heads(96) in m._NATIVE_CPRR_HEADS
|
||||
@@ -87,21 +87,31 @@ def _builder(
|
||||
kv_cache_dtype: str = "auto",
|
||||
dcp_world_size: int = 1,
|
||||
dcp_rank: int = 0,
|
||||
asm_dcp_verify: bool = False,
|
||||
decode_causal: bool = True,
|
||||
supports_segmented_dcp_verify: bool | None = None,
|
||||
):
|
||||
decode_num_heads = num_heads * dcp_world_size
|
||||
asm_heads = (
|
||||
rocm_aiter_mla._asm_dcp_verify_heads(decode_num_heads) if asm_dcp_verify else 0
|
||||
)
|
||||
if supports_segmented_dcp_verify is None:
|
||||
supports_segmented_dcp_verify = rocm_aiter_mla._segmented_dcp_verify_supported(
|
||||
dcp_world_size, 1
|
||||
)
|
||||
stub = SimpleNamespace(
|
||||
device=torch.device("cpu"),
|
||||
num_heads=num_heads,
|
||||
# DCP gathers every rank's head shard before decode, and the routing
|
||||
# predicates read the gathered count.
|
||||
_decode_num_heads=num_heads * dcp_world_size,
|
||||
_decode_num_heads=decode_num_heads,
|
||||
dcp_world_size=dcp_world_size,
|
||||
dcp_rank=dcp_rank,
|
||||
cp_kv_cache_interleave_size=1,
|
||||
# Mirrors the production constructor: configuration decides whether the
|
||||
# segmented route is available, query length decides per batch.
|
||||
_supports_segmented_dcp_verify=rocm_aiter_mla._segmented_dcp_verify_supported(
|
||||
dcp_world_size, 1
|
||||
),
|
||||
# segmented route is available, query length decides per batch. CPRR
|
||||
# preferred still keeps this True so qlen < _MIN_CPRR_QLEN can fall back.
|
||||
_supports_segmented_dcp_verify=supports_segmented_dcp_verify,
|
||||
# Derived once in the real constructor, so derive it once here too.
|
||||
_segmented_page_size=rocm_aiter_mla._segmented_mla_page_size(kernel_block_size),
|
||||
_dcp_verify_buffers=None,
|
||||
@@ -122,7 +132,11 @@ def _builder(
|
||||
_uniform_padded_mtp_qo_len=(AiterMLAMetadataBuilder._uniform_padded_mtp_qo_len),
|
||||
_use_persistent_metadata=False,
|
||||
kernel_block_size=kernel_block_size,
|
||||
_num_attention_heads=AiterMLAHelper.get_actual_mla_num_heads(num_heads),
|
||||
_num_attention_heads=(
|
||||
asm_heads
|
||||
if asm_dcp_verify
|
||||
else AiterMLAHelper.get_actual_mla_num_heads(num_heads)
|
||||
),
|
||||
_mla_work_meta_data=torch.empty(1, dtype=torch.int32),
|
||||
_mla_work_info_set=torch.empty(1, dtype=torch.int32),
|
||||
_mla_work_indptr=torch.empty(1, dtype=torch.int32),
|
||||
@@ -132,7 +146,19 @@ def _builder(
|
||||
_mla_q_dtype=torch.bfloat16,
|
||||
_mla_kv_dtype=torch.bfloat16,
|
||||
decode_attn_out_dtype=torch.bfloat16,
|
||||
_decode_causal=True,
|
||||
_decode_causal=decode_causal,
|
||||
# Default off so existing cases keep exercising segmented/persistent.
|
||||
# Pass asm_dcp_verify=True for the CPRR route and its qlen-floor fallback.
|
||||
_asm_dcp_verify=asm_dcp_verify,
|
||||
_asm_dcp_verify_heads=asm_heads,
|
||||
_g_kv_indptr_buf=(
|
||||
torch.zeros(max_decode_rows + 1, dtype=torch.int32)
|
||||
if asm_dcp_verify and dcp_world_size > 1
|
||||
else None
|
||||
),
|
||||
# Only read when the asm route is on; the real builder derives it from
|
||||
# the device CU count.
|
||||
_mla_max_split_per_batch=256,
|
||||
)
|
||||
# Bound to the stub rather than faked: the verify flatten's per-row view is
|
||||
# part of what _build_decode is being tested for.
|
||||
@@ -287,6 +313,209 @@ def test_dcp_fp8_verify_build_uses_segmented(monkeypatch):
|
||||
assert metadata.dcp_verify is not None
|
||||
|
||||
|
||||
def _cprr_decode_batch(builder, *, qlen: int, num_reqs: int = 1):
|
||||
seq_lens = torch.full((num_reqs,), 16, dtype=torch.int32)
|
||||
query_start_loc = torch.arange(0, (num_reqs + 1) * qlen, qlen, dtype=torch.int32)
|
||||
return AiterMLAMetadataBuilder._build_decode(
|
||||
builder,
|
||||
block_table_tensor=torch.zeros(num_reqs, 8, dtype=torch.int32),
|
||||
seq_lens_device=seq_lens,
|
||||
max_seq_len=16,
|
||||
query_start_loc_cpu=query_start_loc,
|
||||
query_start_loc_device=query_start_loc,
|
||||
num_decode_tokens=num_reqs * qlen,
|
||||
max_query_len=qlen,
|
||||
dcp_tot_seq_lens_device=seq_lens * 8,
|
||||
)
|
||||
|
||||
|
||||
def test_asm_preferred_qlen2_falls_back_to_segmented(monkeypatch):
|
||||
"""K=4 can clamp to qlen 2; CPRR has no kernel, so use segmented MLA."""
|
||||
monkeypatch.setattr(rocm_aiter_mla, "_segmented_mla_decode_supported", lambda: True)
|
||||
get_mla_metadata_v1 = mock.MagicMock()
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"aiter",
|
||||
SimpleNamespace(get_mla_metadata_v1=get_mla_metadata_v1),
|
||||
)
|
||||
|
||||
metadata = _cprr_decode_batch(
|
||||
_builder(
|
||||
mtp_decode_qlen=5,
|
||||
dcp_world_size=8,
|
||||
num_heads=12,
|
||||
asm_dcp_verify=True,
|
||||
kernel_block_size=2,
|
||||
),
|
||||
qlen=2,
|
||||
)
|
||||
|
||||
assert metadata.dcp_verify is not None
|
||||
assert metadata.g_kv_indptr is None
|
||||
assert not metadata.has_persistent_metadata
|
||||
get_mla_metadata_v1.assert_not_called()
|
||||
|
||||
|
||||
def test_asm_preferred_qlen_at_cprr_floor_stays_on_cprr(monkeypatch):
|
||||
monkeypatch.setattr(rocm_aiter_mla, "_segmented_mla_decode_supported", lambda: True)
|
||||
get_mla_metadata_v1 = mock.MagicMock()
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"aiter",
|
||||
SimpleNamespace(get_mla_metadata_v1=get_mla_metadata_v1),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_mla, "_expand_page_indices_kernel", _NoOpTritonKernel()
|
||||
)
|
||||
|
||||
metadata = _cprr_decode_batch(
|
||||
_builder(
|
||||
mtp_decode_qlen=5,
|
||||
dcp_world_size=8,
|
||||
num_heads=12,
|
||||
asm_dcp_verify=True,
|
||||
),
|
||||
qlen=rocm_aiter_mla._MIN_CPRR_QLEN,
|
||||
)
|
||||
|
||||
assert metadata.dcp_verify is None
|
||||
assert metadata.g_kv_indptr is not None
|
||||
assert metadata.has_persistent_metadata
|
||||
assert get_mla_metadata_v1.call_args.kwargs.get("is_cp_round_robin") is True
|
||||
|
||||
|
||||
def test_cprr_capable_single_token_decode_keeps_persistent_metadata(monkeypatch):
|
||||
"""The CPRR qlen floor must not suppress the ordinary qlen-1 schedule."""
|
||||
get_mla_metadata_v1 = mock.MagicMock()
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"aiter",
|
||||
SimpleNamespace(get_mla_metadata_v1=get_mla_metadata_v1),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_mla, "_expand_page_indices_kernel", _NoOpTritonKernel()
|
||||
)
|
||||
|
||||
metadata = _cprr_decode_batch(
|
||||
_builder(
|
||||
mtp_decode_qlen=5,
|
||||
dcp_world_size=8,
|
||||
num_heads=12,
|
||||
asm_dcp_verify=True,
|
||||
),
|
||||
qlen=1,
|
||||
)
|
||||
|
||||
assert metadata.g_kv_indptr is None
|
||||
assert metadata.has_persistent_metadata
|
||||
assert get_mla_metadata_v1.call_args.kwargs.get("is_cp_round_robin") is None
|
||||
|
||||
|
||||
def test_non_causal_dcp_block_uses_plain_mask0_metadata(monkeypatch):
|
||||
"""A non-causal block needs no CPRR global-position window or head pad."""
|
||||
get_mla_metadata_v1 = mock.MagicMock()
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"aiter",
|
||||
SimpleNamespace(get_mla_metadata_v1=get_mla_metadata_v1),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_mla, "_expand_page_indices_kernel", _NoOpTritonKernel()
|
||||
)
|
||||
builder = _builder(
|
||||
mtp_decode_qlen=5,
|
||||
dcp_world_size=8,
|
||||
num_heads=12,
|
||||
asm_dcp_verify=True,
|
||||
)
|
||||
builder._decode_causal = False
|
||||
|
||||
metadata = _cprr_decode_batch(builder, qlen=4)
|
||||
|
||||
assert metadata.dcp_verify is None
|
||||
assert metadata.g_kv_indptr is None
|
||||
assert metadata.has_persistent_metadata
|
||||
assert get_mla_metadata_v1.call_args.args[3] == 96
|
||||
assert get_mla_metadata_v1.call_args.args[5] is False
|
||||
assert get_mla_metadata_v1.call_args.kwargs.get("is_cp_round_robin") is None
|
||||
|
||||
|
||||
def test_asm_qlen2_without_segmented_fails_during_build(monkeypatch):
|
||||
monkeypatch.setitem(
|
||||
sys.modules,
|
||||
"aiter",
|
||||
SimpleNamespace(get_mla_metadata_v1=mock.MagicMock()),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_mla, "_expand_page_indices_kernel", _NoOpTritonKernel()
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="requires either segmented MLA"):
|
||||
_cprr_decode_batch(
|
||||
_builder(
|
||||
mtp_decode_qlen=5,
|
||||
dcp_world_size=8,
|
||||
num_heads=12,
|
||||
asm_dcp_verify=True,
|
||||
supports_segmented_dcp_verify=False,
|
||||
),
|
||||
qlen=2,
|
||||
)
|
||||
|
||||
|
||||
def test_non_causal_dcp_block_bypasses_cprr_in_forward(monkeypatch):
|
||||
"""Process-level CPRR capability must not pad or route a non-causal batch."""
|
||||
captured = {}
|
||||
|
||||
def fake_aiter_decode(q, kv_buffer, out, *args, **kwargs):
|
||||
captured["q_heads"] = q.shape[1]
|
||||
captured["kwargs"] = kwargs
|
||||
return None, torch.zeros(q.shape[0], q.shape[1])
|
||||
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_mla, "_get_aiter_mla_decode", lambda: fake_aiter_decode
|
||||
)
|
||||
|
||||
impl = object.__new__(AiterMLAImpl)
|
||||
impl.num_heads = 12
|
||||
impl.dcp_world_size = 8
|
||||
impl.kv_cache_dtype = "auto"
|
||||
impl.kv_lora_rank = 512
|
||||
impl.qk_rope_head_dim = 64
|
||||
impl.scale = 576**-0.5
|
||||
decode = SimpleNamespace(
|
||||
max_qo_len=4,
|
||||
qo_indptr=torch.tensor([0, 4], dtype=torch.int32),
|
||||
paged_kv_indptr=torch.tensor([0, 1], dtype=torch.int32),
|
||||
paged_kv_indices=torch.zeros(1, dtype=torch.int32),
|
||||
paged_kv_last_page_len=torch.ones(1, dtype=torch.int32),
|
||||
use_gluon_decode=False,
|
||||
use_gluon_verify=False,
|
||||
dcp_route=rocm_aiter_mla._DCPDecodeRoute.PLAIN,
|
||||
dcp_verify=None,
|
||||
g_kv_indptr=None,
|
||||
has_persistent_metadata=False,
|
||||
attn_out_dtype=torch.bfloat16,
|
||||
asm_decode_num_heads=0,
|
||||
mla_num_kv_splits=0,
|
||||
cp_world_size=8,
|
||||
cp_rank=0,
|
||||
min_kv_seq_len=1,
|
||||
)
|
||||
attn_metadata = SimpleNamespace(decode=decode, causal=False, work_meta_data=None)
|
||||
layer = SimpleNamespace(_q_scale=torch.tensor(1.0), _k_scale=torch.tensor(1.0))
|
||||
q = torch.zeros(4, 96, 576, dtype=torch.bfloat16)
|
||||
|
||||
output, lse = impl.forward_mqa(q, torch.zeros(1, 1, 576), attn_metadata, layer)
|
||||
|
||||
assert captured["q_heads"] == 96
|
||||
assert captured["kwargs"]["causal"] is False
|
||||
assert "g_kv_indptr" not in captured["kwargs"]
|
||||
assert "num_kv_splits" not in captured["kwargs"]
|
||||
assert output.shape[1] == 96
|
||||
assert lse is not None and lse.shape == (4, 96)
|
||||
|
||||
|
||||
def test_single_token_dcp_decode_returns_unpadded_lse(monkeypatch):
|
||||
"""Single-token DCP decode must come back with an LSE the merge can use.
|
||||
|
||||
@@ -325,9 +554,14 @@ def test_single_token_dcp_decode_returns_unpadded_lse(monkeypatch):
|
||||
paged_kv_last_page_len=torch.ones(num_tokens, dtype=torch.int32),
|
||||
use_gluon_decode=False,
|
||||
use_gluon_verify=False,
|
||||
dcp_route=rocm_aiter_mla._DCPDecodeRoute.PLAIN,
|
||||
dcp_verify=None,
|
||||
has_persistent_metadata=False,
|
||||
attn_out_dtype=torch.bfloat16,
|
||||
# 0 == the round-robin (cprr) asm route is off, this rank's decode takes
|
||||
# the existing path. Mirrors the AiterMLADecodeMetadata default.
|
||||
asm_decode_num_heads=0,
|
||||
g_kv_indptr=None,
|
||||
)
|
||||
attn_metadata = SimpleNamespace(decode=decode, causal=True, work_meta_data=None)
|
||||
layer = SimpleNamespace(_q_scale=torch.tensor(1.0), _k_scale=torch.tensor(1.0))
|
||||
@@ -453,6 +687,7 @@ def test_segmented_dcp_verify_matches_causal_attention(monkeypatch):
|
||||
),
|
||||
use_gluon_decode=False,
|
||||
use_gluon_verify=False,
|
||||
dcp_route=rocm_aiter_mla._DCPDecodeRoute.SEGMENTED,
|
||||
dcp_verify=view,
|
||||
attn_out_dtype=torch.bfloat16,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not current_platform.is_rocm(), reason="ROCm-only aiter path"
|
||||
)
|
||||
|
||||
|
||||
def _rows_from_ragged(indices: torch.Tensor, indptr: torch.Tensor) -> list[list[int]]:
|
||||
ends = indptr.tolist()
|
||||
return [indices[s:e].tolist() for s, e in zip(ends, ends[1:])]
|
||||
|
||||
|
||||
def test_triton_sparse_mla_gate(monkeypatch) -> None:
|
||||
import vllm._aiter_ops as aiter_ops
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
|
||||
warnings: list[str] = []
|
||||
monkeypatch.setattr(
|
||||
aiter_ops.logger,
|
||||
"warning_once",
|
||||
lambda msg, *args, **kwargs: warnings.append(msg % args),
|
||||
)
|
||||
|
||||
def enabled(aiter: bool, flag: bool) -> bool:
|
||||
monkeypatch.setenv("VLLM_ROCM_USE_AITER", str(int(aiter)))
|
||||
monkeypatch.setenv("VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA", str(int(flag)))
|
||||
rocm_aiter_ops.refresh_env_variables()
|
||||
return bool(rocm_aiter_ops.is_triton_sparse_mla_enabled())
|
||||
|
||||
try:
|
||||
assert not enabled(aiter=True, flag=False) and not warnings
|
||||
assert not enabled(aiter=False, flag=True)
|
||||
assert "VLLM_ROCM_USE_AITER is off" in warnings.pop()
|
||||
# On gfx950 the flag takes effect; elsewhere it warns and falls back.
|
||||
assert enabled(aiter=True, flag=True) == on_gfx950()
|
||||
if not on_gfx950():
|
||||
assert "gfx950" in warnings.pop()
|
||||
finally:
|
||||
monkeypatch.undo()
|
||||
rocm_aiter_ops.refresh_env_variables()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rope_dim",
|
||||
[0, 64],
|
||||
ids=["rope_free", "appended_rope"], # GLM-5.3-Flash; GLM-5.1/5.2, V3.2
|
||||
)
|
||||
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"])
|
||||
@torch.inference_mode()
|
||||
def test_forward_mqa_prepares_triton_sparse_mla_inputs(
|
||||
monkeypatch, rope_dim: int, kv_cache_dtype: str
|
||||
) -> None:
|
||||
"""What forward_mqa hands aiter: global slots built from the request-local
|
||||
top-k rows, q quantized with the layer's scale, and the cache as stored."""
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
|
||||
ROCMAiterMLASparseImpl,
|
||||
)
|
||||
|
||||
device = torch.device("cuda")
|
||||
gen = torch.Generator().manual_seed(0)
|
||||
kv_lora_rank, num_heads, topk, block_size = 512, 16, 128, 16
|
||||
head_size = kv_lora_rank + rope_dim
|
||||
fp8 = kv_cache_dtype == "fp8"
|
||||
|
||||
# A decode row, then a short prefill.
|
||||
query_lens, seq_lens = [1, 5], [40, 20]
|
||||
num_tokens = sum(query_lens)
|
||||
block_table = torch.randperm(8, generator=gen).view(2, 4).to(device, torch.int32)
|
||||
topk_indices = torch.full((num_tokens, topk), -1, dtype=torch.int32)
|
||||
req_id_per_token: list[int] = []
|
||||
rows: list[list[int]] = []
|
||||
for req, (query_len, seq_len) in enumerate(zip(query_lens, seq_lens)):
|
||||
for pos in range(seq_len - query_len, seq_len):
|
||||
local = torch.randperm(pos + 1, generator=gen)
|
||||
topk_indices[len(rows), : pos + 1] = local.int()
|
||||
slots = block_table[req, local // block_size].cpu() * block_size
|
||||
rows.append((slots + local % block_size).tolist())
|
||||
req_id_per_token.append(req)
|
||||
indptr = torch.tensor([0] + [len(row) for row in rows]).cumsum(0)
|
||||
|
||||
impl = ROCMAiterMLASparseImpl.__new__(ROCMAiterMLASparseImpl)
|
||||
impl.num_heads = num_heads
|
||||
impl.kv_lora_rank = kv_lora_rank
|
||||
impl.qk_rope_head_dim = rope_dim
|
||||
impl.scale = head_size**-0.5
|
||||
impl.sinks = torch.randn(num_heads, generator=gen).to(device)
|
||||
impl.kv_cache_dtype = kv_cache_dtype
|
||||
impl.topk_indices_buffer = topk_indices.to(device)
|
||||
impl.use_aiter_sparse_mla = True
|
||||
layer = SimpleNamespace(
|
||||
_q_scale=torch.tensor([0.02], device=device),
|
||||
_k_scale=torch.tensor([0.01], device=device),
|
||||
)
|
||||
metadata = SimpleNamespace(
|
||||
num_actual_tokens=num_tokens,
|
||||
topk_tokens=topk,
|
||||
req_id_per_token=torch.tensor(req_id_per_token, dtype=torch.int32).to(device),
|
||||
block_table=block_table,
|
||||
block_size=block_size,
|
||||
paged_kv_indptr=indptr.to(device, torch.int32),
|
||||
paged_kv_indices=torch.zeros(num_tokens * topk, dtype=torch.int32).to(device),
|
||||
attn_out_dtype=torch.bfloat16,
|
||||
)
|
||||
cache_dtype = current_platform.fp8_dtype() if fp8 else torch.bfloat16
|
||||
kv_cache = torch.zeros(8, block_size, head_size, device=device).to(cache_dtype)
|
||||
# Two rows of cudagraph padding past the real tokens.
|
||||
q = torch.randn(num_tokens + 2, num_heads, head_size, generator=gen).to(
|
||||
device, torch.bfloat16
|
||||
)
|
||||
calls = []
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_ops, "triton_sparse_mla_fwd", lambda *a, **k: calls.append((a, k))
|
||||
)
|
||||
|
||||
out, lse = impl.forward_mqa(q, kv_cache, metadata, layer)
|
||||
|
||||
assert len(calls) == 1
|
||||
(q_in, kv_in, o, sm_scale, kv_indptr, kv_indices), kwargs = calls[0]
|
||||
assert _rows_from_ragged(kv_indices, kv_indptr) == rows
|
||||
assert q_in.shape[0] == num_tokens
|
||||
if fp8:
|
||||
assert q_in.dtype == cache_dtype
|
||||
torch.testing.assert_close(
|
||||
q_in.float() * layer._q_scale, q[:num_tokens].float(), atol=1e-3, rtol=0.07
|
||||
)
|
||||
else:
|
||||
assert q_in.data_ptr() == q.data_ptr()
|
||||
assert kv_in.shape == (8 * block_size, 1, 1, head_size)
|
||||
assert kv_in.data_ptr() == kv_cache.data_ptr()
|
||||
assert o.data_ptr() == out.data_ptr() and o.shape[0] == num_tokens
|
||||
assert sm_scale == impl.scale
|
||||
assert kwargs["kv_lora_rank"] == kv_lora_rank
|
||||
assert kwargs["qk_rope_head_dim"] == rope_dim
|
||||
assert kwargs["q_scale"] is layer._q_scale
|
||||
assert kwargs["kv_scale"] is layer._k_scale
|
||||
assert kwargs["attn_sink"] is impl.sinks
|
||||
assert lse is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("model", "compress_ratio"),
|
||||
[("deepseek_v41", 1), ("deepseek_v41", 2), ("deepseek_v4", 4)],
|
||||
)
|
||||
@torch.inference_mode()
|
||||
def test_paged_prefill_indices_match_gathered_prefill(
|
||||
monkeypatch, model: str, compress_ratio: int
|
||||
) -> None:
|
||||
"""The aiter prefill reads the paged caches through the SWA builder's rows
|
||||
and build_prefill_topk_ragged_indices, and must attend exactly the keys the
|
||||
dequantize-and-gather prefill does."""
|
||||
import importlib
|
||||
|
||||
from tests.v1.attention.utils import create_vllm_config
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
|
||||
build_prefill_topk_ragged_indices,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import SlidingWindowMLASpec
|
||||
|
||||
rocm = importlib.import_module(f"vllm.models.{model}.amd.rocm")
|
||||
device = torch.device("cuda")
|
||||
gen = torch.Generator().manual_seed(compress_ratio)
|
||||
window, width, block_size, max_model_len = 16, 32, 16, 128
|
||||
comp_block = block_size // compress_ratio
|
||||
num_compressed = max_model_len // compress_ratio
|
||||
|
||||
# A decode row, then prefills with and without a prefix.
|
||||
prefix_lens, query_lens = [20, 0, 13, 40], [1, 7, 20, 9]
|
||||
seq_lens = [p + q for p, q in zip(prefix_lens, query_lens)]
|
||||
num_decodes = num_decode_tokens = 1
|
||||
num_tokens = sum(query_lens)
|
||||
qsl = torch.tensor([0] + query_lens).cumsum(0).to(torch.int32)
|
||||
positions = torch.cat([torch.arange(p, s) for p, s in zip(prefix_lens, seq_lens)])
|
||||
token_to_req = torch.repeat_interleave(
|
||||
torch.arange(len(query_lens)), torch.tensor(query_lens)
|
||||
)
|
||||
swa_bt = torch.randperm(32, generator=gen)[:16].view(4, 4).to(device, torch.int32)
|
||||
comp_bt = torch.randperm(32, generator=gen)[:16].view(4, 4).to(device, torch.int32)
|
||||
|
||||
vllm_config = create_vllm_config(
|
||||
model_name="facebook/opt-125m",
|
||||
max_model_len=max_model_len,
|
||||
block_size=block_size,
|
||||
max_num_seqs=4,
|
||||
max_num_batched_tokens=64,
|
||||
hf_config_override={
|
||||
"compress_ratios": [compress_ratio],
|
||||
"index_topk": width,
|
||||
"sliding_window": window,
|
||||
},
|
||||
)
|
||||
swa_spec = SlidingWindowMLASpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=512,
|
||||
dtype=torch.bfloat16,
|
||||
sliding_window=window,
|
||||
cache_dtype_str="fp8_ds_mla",
|
||||
model_version="deepseek_v4",
|
||||
)
|
||||
slots = swa_bt.cpu()[token_to_req, positions // block_size] * block_size + (
|
||||
positions % block_size
|
||||
)
|
||||
common = CommonAttentionMetadata(
|
||||
query_start_loc=qsl.to(device),
|
||||
query_start_loc_cpu=qsl,
|
||||
seq_lens=torch.tensor(seq_lens, dtype=torch.int32).to(device),
|
||||
seq_lens_cpu_upper_bound=torch.tensor(seq_lens, dtype=torch.int32),
|
||||
num_reqs=len(query_lens),
|
||||
num_actual_tokens=num_tokens,
|
||||
max_query_len=max(query_lens),
|
||||
max_seq_len=max(seq_lens),
|
||||
block_table_tensor=swa_bt,
|
||||
slot_mapping=slots.to(device, torch.int64),
|
||||
positions=positions.to(device),
|
||||
causal=True,
|
||||
)
|
||||
|
||||
def build(enabled: bool):
|
||||
monkeypatch.setattr(
|
||||
rocm_aiter_ops, "is_triton_sparse_mla_enabled", lambda: enabled
|
||||
)
|
||||
return rocm.DeepseekV4ROCMAiterSparseSWAMetadataBuilder(
|
||||
swa_spec, ["swa"], vllm_config, device
|
||||
).build(0, common)
|
||||
|
||||
assert build(enabled=False).prefill_swa_ragged_indices is None
|
||||
md = build(enabled=True)
|
||||
assert md.num_decode_tokens == num_decode_tokens
|
||||
|
||||
# Local top-k rows. Under each row's causal cap sit a failed candidate and
|
||||
# one past the pool; past the cap, stale values neither path may read.
|
||||
num_prefill_tokens = num_tokens - num_decode_tokens
|
||||
topk = torch.full((num_prefill_tokens, width), -1, dtype=torch.int32)
|
||||
for row in range(num_prefill_tokens):
|
||||
visible = (int(positions[row + num_decode_tokens]) + 1) // compress_ratio
|
||||
cap = min(visible, width)
|
||||
topk[row, :cap] = torch.randperm(visible, generator=gen)[:cap].int()
|
||||
if cap >= 2:
|
||||
topk[row, :2] = torch.tensor([-1, num_compressed + 3])
|
||||
topk[row, cap:] = torch.randint(
|
||||
0, num_compressed, (width - cap,), generator=gen
|
||||
).int()
|
||||
topk = topk.to(device)
|
||||
|
||||
topk_indices, topk_indptr = build_prefill_topk_ragged_indices(
|
||||
topk,
|
||||
md.token_to_req_indices,
|
||||
md.query_start_loc,
|
||||
md.seq_lens,
|
||||
md.is_valid_token,
|
||||
comp_bt,
|
||||
block_size=comp_block,
|
||||
compress_ratio=compress_ratio,
|
||||
num_compressed=num_compressed,
|
||||
token_offset=num_decode_tokens,
|
||||
)
|
||||
paged_keys = [
|
||||
sorted([("s", x) for x in swa if x >= 0] + [("c", x) for x in top if x >= 0])
|
||||
for swa, top in zip(
|
||||
_rows_from_ragged(
|
||||
md.prefill_swa_ragged_indices, md.prefill_swa_ragged_indptr
|
||||
),
|
||||
_rows_from_ragged(topk_indices, topk_indptr),
|
||||
)
|
||||
]
|
||||
|
||||
# The gathered path's combine, mapped from workspace offsets to cache slots.
|
||||
M = num_compressed + window + num_tokens
|
||||
combined, combined_lens = rocm.combine_topk_swa_indices(
|
||||
topk,
|
||||
md.query_start_loc[num_decodes:],
|
||||
md.prefill_seq_lens,
|
||||
md.prefill_gather_lens,
|
||||
window,
|
||||
compress_ratio,
|
||||
width,
|
||||
M,
|
||||
num_compressed,
|
||||
)
|
||||
gather_start = (md.prefill_seq_lens - md.prefill_gather_lens).tolist()
|
||||
swa_bt_cpu, comp_bt_cpu = swa_bt.cpu(), comp_bt.cpu()
|
||||
|
||||
def slot(block_table, req, pos, size):
|
||||
return int(block_table[req, pos // size]) * size + pos % size
|
||||
|
||||
gathered_keys = []
|
||||
for row, (values, n) in enumerate(zip(combined.tolist(), combined_lens.tolist())):
|
||||
req = int(token_to_req[row + num_decode_tokens])
|
||||
chunk_req = req - num_decodes
|
||||
keys = []
|
||||
for value in values[:n]:
|
||||
if value < 0:
|
||||
continue
|
||||
offset = value - chunk_req * M
|
||||
if offset < num_compressed:
|
||||
keys.append(("c", slot(comp_bt_cpu, req, offset, comp_block)))
|
||||
else:
|
||||
pos = gather_start[chunk_req] + offset - num_compressed
|
||||
keys.append(("s", slot(swa_bt_cpu, req, pos, block_size)))
|
||||
gathered_keys.append(sorted(keys))
|
||||
|
||||
assert paged_keys == gathered_keys
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model", ["deepseek_v4", "deepseek_v41"])
|
||||
def test_aiter_sparse_mla_stays_off_with_kv_connector(monkeypatch, model) -> None:
|
||||
import importlib
|
||||
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
|
||||
rocm = importlib.import_module(f"vllm.models.{model}.amd.rocm")
|
||||
monkeypatch.setattr(rocm_aiter_ops, "is_triton_sparse_mla_enabled", lambda: True)
|
||||
assert rocm._aiter_sparse_mla_enabled(has_kv_transfer=False)
|
||||
assert not rocm._aiter_sparse_mla_enabled(has_kv_transfer=True)
|
||||
@@ -13,7 +13,7 @@ from vllm.v1.request import RequestStatus
|
||||
from vllm.v1.structured_output import StructuredOutputGrammar
|
||||
from vllm.v1.utils import ConstantList
|
||||
|
||||
from .utils import create_requests, create_scheduler, mock_kv
|
||||
from .utils import EOS_TOKEN_ID, create_requests, create_scheduler, mock_kv
|
||||
|
||||
pytestmark = pytest.mark.cpu_test
|
||||
|
||||
@@ -766,3 +766,48 @@ def test_kv_pressure_preempt_mid_handoff(kv_role: str, defer_free: bool):
|
||||
else:
|
||||
assert handoff.is_finished()
|
||||
assert handoff.num_output_tokens == 1
|
||||
|
||||
|
||||
def test_resumable_request_handoff():
|
||||
"""New streaming input resumes with the correct context and stale results
|
||||
are ignored.
|
||||
"""
|
||||
scheduler = create_scheduler(
|
||||
async_scheduling=True,
|
||||
use_v2_model_runner=True,
|
||||
)
|
||||
engine = PipelinedEngine(scheduler, queue_size=3)
|
||||
engine._next_token = EOS_TOKEN_ID
|
||||
|
||||
old_prompt_len = 10
|
||||
continuation_len = 12
|
||||
request_id = "resumable-race"
|
||||
|
||||
request = create_requests(
|
||||
1, num_tokens=old_prompt_len, max_tokens=4, req_ids=[request_id]
|
||||
)[0]
|
||||
request.resumable = True
|
||||
continuation = create_requests(
|
||||
1, num_tokens=continuation_len, max_tokens=4, req_ids=[request_id]
|
||||
)[0]
|
||||
continuation.resumable = True
|
||||
|
||||
scheduler.add_request(request)
|
||||
|
||||
for _ in range(3):
|
||||
assert engine._schedule()
|
||||
|
||||
engine._process_oldest_step()
|
||||
scheduler.add_request(continuation)
|
||||
assert engine._schedule()
|
||||
new_step, _ = engine.queue[0]
|
||||
assert new_step.scheduled_new_reqs[0].num_computed_tokens == old_prompt_len
|
||||
|
||||
all_token_ids_before_stale = list(request.all_token_ids)
|
||||
for _ in range(2):
|
||||
engine._process_oldest_step()
|
||||
assert list(request.output_token_ids) == []
|
||||
assert list(request.all_token_ids) == all_token_ids_before_stale
|
||||
|
||||
engine._process_oldest_step()
|
||||
assert len(request.output_token_ids) == 1
|
||||
|
||||
@@ -2273,7 +2273,8 @@ def test_spec_decode_padding_skipped_with_prefill_in_batch():
|
||||
|
||||
|
||||
def test_scheduler_stats_waiting_queues():
|
||||
"""Test that scheduler stats correctly report waiting and skipped_waiting queues."""
|
||||
"""Test that scheduler stats correctly report capacity-bound and blocked
|
||||
waiting requests."""
|
||||
# Create scheduler with limited capacity so we can have waiting requests
|
||||
scheduler = create_scheduler(max_num_batched_tokens=100)
|
||||
|
||||
@@ -2286,18 +2287,18 @@ def test_scheduler_stats_waiting_queues():
|
||||
for request in all_requests[:3]:
|
||||
scheduler.add_request(request)
|
||||
|
||||
# Manually add 2 more to skipped_waiting to simulate constraint-blocked
|
||||
# Add 2 more that are blocked on grammar compilation
|
||||
for request in all_requests[3:]:
|
||||
request.status = RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
scheduler.skipped_waiting.add_request(request)
|
||||
request.status = RequestStatus.WAITING_FOR_STRUCTURED_OUTPUT_GRAMMAR
|
||||
scheduler.add_request(request)
|
||||
|
||||
# Schedule - this will schedule 2 requests, leaving 1 in waiting
|
||||
output = scheduler.schedule()
|
||||
|
||||
# Verify: 2 scheduled, 1 still waiting on capacity, 2 blocked by constraints
|
||||
assert len(output.scheduled_new_reqs) == 2
|
||||
assert len(scheduler.waiting) == 1
|
||||
assert len(scheduler.skipped_waiting) == 2
|
||||
assert len(scheduler.waiting) == 3
|
||||
assert len(scheduler.deferred_waiting) == 2
|
||||
|
||||
# Call update_from_output() to get frontend-facing stat
|
||||
scheduled_req_ids = list(output.num_scheduled_tokens.keys())
|
||||
@@ -2395,7 +2396,7 @@ def _step_until_done(
|
||||
|
||||
|
||||
def _num_waiting_requests(scheduler: Scheduler) -> int:
|
||||
return len(scheduler.waiting) + len(scheduler.skipped_waiting)
|
||||
return len(scheduler.waiting) + len(scheduler.kv_holding_waiting)
|
||||
|
||||
|
||||
def _step_until_kv_transfer_finished(scheduler: Scheduler, req_ids: list[str]):
|
||||
@@ -2944,7 +2945,7 @@ def test_kv_connector_handles_preemption(
|
||||
if is_async:
|
||||
waiting_req_ids = [
|
||||
req.request_id
|
||||
for req in scheduler.skipped_waiting
|
||||
for req in scheduler.kv_holding_waiting
|
||||
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
]
|
||||
assert len(waiting_req_ids) == 1
|
||||
@@ -3807,8 +3808,8 @@ def test_schedule_skip_tokenizer_init_structured_output_request():
|
||||
output = scheduler.schedule()
|
||||
assert len(output.scheduled_new_reqs) == 0
|
||||
assert len(scheduler.running) == 0
|
||||
assert len(scheduler.waiting) == 0
|
||||
assert len(scheduler.skipped_waiting) == 1
|
||||
assert len(scheduler.waiting) == 1
|
||||
assert len(scheduler.deferred_waiting) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("async_grammar", [True, False])
|
||||
@@ -5227,7 +5228,7 @@ def test_prepend_skipped_requests_order():
|
||||
req.status = RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
scheduler.waiting.remove_requests(expected_waiting_reqs[:2])
|
||||
for req in expected_waiting_reqs[:2]:
|
||||
scheduler.skipped_waiting.add_request(req)
|
||||
scheduler.kv_holding_waiting.add_request(req)
|
||||
|
||||
# schedule step
|
||||
# expect the first 2 waiting to be skipped, the third running,
|
||||
@@ -5237,21 +5238,18 @@ def test_prepend_skipped_requests_order():
|
||||
# pop the third request which is expected to be running
|
||||
expected_waiting_reqs.pop(2)
|
||||
|
||||
# verify waiting order is preserved
|
||||
waiting_reqs = list(scheduler.skipped_waiting) + list(scheduler.waiting)
|
||||
# verify waiting order is preserved, with the KV-holding requests first
|
||||
waiting_reqs = list(scheduler.kv_holding_waiting) + list(scheduler.waiting)
|
||||
assert waiting_reqs == expected_waiting_reqs
|
||||
|
||||
|
||||
def test_remote_kv_promotion_keeps_fcfs_with_grammar_prefix():
|
||||
def test_remote_kv_promotion_drains_before_grammar_prefix():
|
||||
scheduler = create_scheduler(max_num_seqs=1)
|
||||
scheduler.connector = Mock()
|
||||
scheduler.connector.get_num_new_matched_tokens.return_value = (0, False)
|
||||
|
||||
requests = create_requests(num_requests=4)
|
||||
for request in requests:
|
||||
scheduler.add_request(request)
|
||||
|
||||
req_grammar_1, req_grammar_2, req_remote, req_tail = list(scheduler.waiting)
|
||||
req_grammar_1, req_grammar_2, req_remote, req_tail = requests
|
||||
|
||||
# simulate two structured-output grammar requests at the waiting head
|
||||
# that become ready now.
|
||||
@@ -5260,31 +5258,28 @@ def test_remote_kv_promotion_keeps_fcfs_with_grammar_prefix():
|
||||
req_grammar_2.status = RequestStatus.WAITING_FOR_STRUCTURED_OUTPUT_GRAMMAR
|
||||
req_grammar_2.structured_output_request = Mock(grammar=object())
|
||||
|
||||
# simulate a remote-KV request that is ready to be promoted now.
|
||||
# simulate a remote-KV request that is ready to be promoted now. Parked
|
||||
# loads hold KV blocks, so they drain ahead of the grammar requests.
|
||||
req_remote.status = RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
scheduler.waiting.remove_requests([req_grammar_1, req_grammar_2, req_remote])
|
||||
scheduler.skipped_waiting.add_request(req_grammar_1)
|
||||
scheduler.skipped_waiting.add_request(req_grammar_2)
|
||||
scheduler.skipped_waiting.add_request(req_remote)
|
||||
for request in requests:
|
||||
scheduler.add_request(request)
|
||||
assert list(scheduler.kv_holding_waiting) == [req_remote]
|
||||
scheduler.finished_recving_kv_req_ids.add(req_remote.request_id)
|
||||
scheduler._update_waiting_for_remote_kv = Mock()
|
||||
|
||||
output = scheduler.schedule()
|
||||
|
||||
assert output.scheduled_new_reqs
|
||||
assert output.scheduled_new_reqs[0].req_id == req_grammar_1.request_id
|
||||
waiting_req_ids = [
|
||||
req.request_id
|
||||
for req in list(scheduler.skipped_waiting) + list(scheduler.waiting)
|
||||
]
|
||||
assert output.scheduled_new_reqs[0].req_id == req_remote.request_id
|
||||
waiting_req_ids = [req.request_id for req in scheduler.waiting]
|
||||
assert waiting_req_ids == [
|
||||
req_grammar_1.request_id,
|
||||
req_grammar_2.request_id,
|
||||
req_remote.request_id,
|
||||
req_tail.request_id,
|
||||
]
|
||||
|
||||
|
||||
def test_fcfs_mixed_skipped_waiting_types_keep_order():
|
||||
def test_fcfs_mixed_blocked_types_remote_load_drains_first():
|
||||
scheduler = create_scheduler(max_num_batched_tokens=20)
|
||||
scheduler._update_waiting_for_remote_kv = Mock()
|
||||
|
||||
@@ -5305,7 +5300,8 @@ def test_fcfs_mixed_skipped_waiting_types_keep_order():
|
||||
for req in (req_grammar, req_remote, req_stream, req_regular, req_tail):
|
||||
scheduler.add_request(req)
|
||||
scheduler.schedule()
|
||||
assert list(scheduler.skipped_waiting) == [req_grammar, req_remote, req_stream]
|
||||
assert list(scheduler.waiting) == [req_grammar, req_stream, req_tail]
|
||||
assert list(scheduler.kv_holding_waiting) == [req_remote]
|
||||
|
||||
scheduler.finish_requests(req_regular.request_id, RequestStatus.FINISHED_ABORTED)
|
||||
assert not scheduler.running
|
||||
@@ -5316,8 +5312,8 @@ def test_fcfs_mixed_skipped_waiting_types_keep_order():
|
||||
|
||||
second_output = scheduler.schedule()
|
||||
expected_order = [
|
||||
req_grammar.request_id,
|
||||
req_remote.request_id,
|
||||
req_grammar.request_id,
|
||||
req_stream.request_id,
|
||||
req_tail.request_id,
|
||||
]
|
||||
|
||||
@@ -105,8 +105,8 @@ def test_streaming_pause_does_not_over_admit_worker_slot():
|
||||
# still holds its slot.
|
||||
scheduler.update_from_output(out, _model_runner_output(["session"], [[STOP_TOKEN]]))
|
||||
assert session.status == RequestStatus.WAITING_FOR_STREAMING_REQ
|
||||
# A blocked waiting status lands in skipped_waiting, not the main queue.
|
||||
assert session in scheduler.skipped_waiting
|
||||
# The paused session keeps its KV blocks, so it lands in kv_holding_waiting.
|
||||
assert session in scheduler.kv_holding_waiting
|
||||
assert scheduler.num_waiting_for_streaming_input == 1
|
||||
|
||||
# A different request arrives while the session is paused.
|
||||
|
||||
@@ -224,7 +224,9 @@ def test_speculator_capture_preserves_decode_query_bounds(
|
||||
)
|
||||
manager = SpeculatorCudaGraphManager.__new__(SpeculatorCudaGraphManager)
|
||||
manager.max_num_reqs = num_reqs
|
||||
manager.dp_size = 1
|
||||
manager.vllm_config = SimpleNamespace(
|
||||
parallel_config=SimpleNamespace(data_parallel_size=1)
|
||||
)
|
||||
buffers = InputBuffers(num_reqs, num_tokens, torch.device("cpu"))
|
||||
block_tables = MagicMock()
|
||||
block_tables.cp_size = 1
|
||||
|
||||
@@ -55,7 +55,10 @@ async_scheduling_mode = False
|
||||
num_accepted_tokens = 1
|
||||
prompt_token_ids: list[int] = []
|
||||
MODEL = "Qwen/Qwen3-Next-80B-A3B-Instruct-FP8"
|
||||
BLOCK_SIZE = 560
|
||||
# Must be a value no platform rewrites, since the step actions below encode
|
||||
# where block boundaries fall. XPU rounds GDN block sizes up to a multiple of 64
|
||||
# (XPUPlatform.update_block_size_for_backend), so use one.
|
||||
BLOCK_SIZE = 576
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
NUM_HIDDEN_LAYERS = 1
|
||||
cur_step_action_idx = 0
|
||||
@@ -541,26 +544,27 @@ def get_mamba_prefix_cache_step_configs(
|
||||
async_scheduling: bool = False,
|
||||
) -> dict[str, TestConfig]:
|
||||
a = async_scheduling
|
||||
B = BLOCK_SIZE
|
||||
tests = {
|
||||
"accept_1": TestConfig(
|
||||
num_prompt_tokens=554,
|
||||
num_prompt_tokens=B - 6,
|
||||
num_generated_tokens=20,
|
||||
num_accepted_tokens=1,
|
||||
step_actions=[
|
||||
StepAction(0, 554, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(554, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(0, B - 6, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 6, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(
|
||||
555, 4, [1, 1, 1, 1, 1] if a else [1, 1, 1, 1], (-1, -1), (-1, -1)
|
||||
B - 5, 4, [1, 1, 1, 1, 1] if a else [1, 1, 1, 1], (-1, -1), (-1, -1)
|
||||
),
|
||||
StepAction(
|
||||
556, 4, [1, 1, 1, 1, 1] if a else [1, 1, 1, 1], (-1, -1), (-1, -1)
|
||||
B - 4, 4, [1, 1, 1, 1, 1] if a else [1, 1, 1, 1], (-1, -1), (-1, -1)
|
||||
),
|
||||
StepAction(557, 4, [1, 1, 1, 1, 1], (0, 1), (-1, -1)),
|
||||
StepAction(558, 4, [1, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(559, 4, [1, 1, 1, 1, 1], (-1, -1), (1, 0)),
|
||||
StepAction(560, 4, [1, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 3, 4, [1, 1, 1, 1, 1], (0, 1), (-1, -1)),
|
||||
StepAction(B - 2, 4, [1, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 1, 4, [1, 1, 1, 1, 1], (-1, -1), (1, 0)),
|
||||
StepAction(B, 4, [1, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(
|
||||
561,
|
||||
B + 1,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
@@ -570,19 +574,19 @@ def get_mamba_prefix_cache_step_configs(
|
||||
),
|
||||
# test case 2.1: no hit, accept 2 tokens
|
||||
"accept_2_1": TestConfig(
|
||||
num_prompt_tokens=554,
|
||||
num_prompt_tokens=B - 6,
|
||||
num_generated_tokens=20,
|
||||
num_accepted_tokens=2,
|
||||
step_actions=[
|
||||
StepAction(0, 554, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(554, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(0, B - 6, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 6, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(
|
||||
556, 4, [1, 1, 1, 1, 1] if a else [1, 1, 1, 1], (-1, -1), (-1, -1)
|
||||
B - 4, 4, [1, 1, 1, 1, 1] if a else [1, 1, 1, 1], (-1, -1), (-1, -1)
|
||||
),
|
||||
StepAction(558, 4, [1, 1, 1, 1, 1], (1, 1), (2, 0)),
|
||||
StepAction(560, 4, [1, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 2, 4, [1, 1, 1, 1, 1], (1, 1), (2, 0)),
|
||||
StepAction(B, 4, [1, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(
|
||||
562,
|
||||
B + 2,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
@@ -592,56 +596,56 @@ def get_mamba_prefix_cache_step_configs(
|
||||
),
|
||||
# test case 2.2: no hit, accept 2 tokens
|
||||
"accept_2_2": TestConfig(
|
||||
num_prompt_tokens=555,
|
||||
num_prompt_tokens=B - 5,
|
||||
num_generated_tokens=20,
|
||||
num_accepted_tokens=2,
|
||||
step_actions=[
|
||||
StepAction(0, 555, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(555, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(557, 4, [1, 1, 1, 1, 1], (1, 1), (-1, -1)),
|
||||
StepAction(559, 4, [1, 1, 1, 1, 1], (-1, -1), (1, 0)),
|
||||
StepAction(0, B - 5, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 5, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 3, 4, [1, 1, 1, 1, 1], (1, 1), (-1, -1)),
|
||||
StepAction(B - 1, 4, [1, 1, 1, 1, 1], (-1, -1), (1, 0)),
|
||||
StepAction(
|
||||
561,
|
||||
B + 1,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
(-1, -1),
|
||||
),
|
||||
StepAction(563, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B + 3, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
],
|
||||
),
|
||||
"accept_3_1": TestConfig(
|
||||
num_prompt_tokens=553,
|
||||
num_prompt_tokens=B - 7,
|
||||
num_generated_tokens=20,
|
||||
num_accepted_tokens=3,
|
||||
step_actions=[
|
||||
StepAction(0, 553, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(553, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(0, B - 7, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 7, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(
|
||||
556, 4, [1, 1, 1, 1, 1] if a else [1, 1, 1, 1], (-1, -1), (-1, -1)
|
||||
B - 4, 4, [1, 1, 1, 1, 1] if a else [1, 1, 1, 1], (-1, -1), (-1, -1)
|
||||
),
|
||||
StepAction(559, 4, [1, 1, 1, 1, 1], (2, 1), (1, 0)),
|
||||
StepAction(B - 1, 4, [1, 1, 1, 1, 1], (2, 1), (1, 0)),
|
||||
StepAction(
|
||||
562,
|
||||
B + 2,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
(-1, -1),
|
||||
),
|
||||
StepAction(565, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B + 5, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
],
|
||||
),
|
||||
"accept_3_2": TestConfig(
|
||||
num_prompt_tokens=554,
|
||||
num_prompt_tokens=B - 6,
|
||||
num_generated_tokens=20,
|
||||
num_accepted_tokens=3,
|
||||
step_actions=[
|
||||
StepAction(0, 554, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(554, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(557, 4, [1, 1, 1, 1, 1], (2, 1), (3, 0)),
|
||||
StepAction(560, 4, [1, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(0, B - 6, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 6, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 3, 4, [1, 1, 1, 1, 1], (2, 1), (3, 0)),
|
||||
StepAction(B, 4, [1, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(
|
||||
563,
|
||||
B + 3,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
@@ -650,87 +654,87 @@ def get_mamba_prefix_cache_step_configs(
|
||||
],
|
||||
),
|
||||
"accept_3_3": TestConfig(
|
||||
num_prompt_tokens=555,
|
||||
num_prompt_tokens=B - 5,
|
||||
num_generated_tokens=20,
|
||||
num_accepted_tokens=3,
|
||||
step_actions=[
|
||||
StepAction(0, 555, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(555, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(558, 4, [1, 1, 1, 1, 1], (2, 1), (2, 0)),
|
||||
StepAction(0, B - 5, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 5, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 2, 4, [1, 1, 1, 1, 1], (2, 1), (2, 0)),
|
||||
StepAction(
|
||||
561,
|
||||
B + 1,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
(-1, -1),
|
||||
),
|
||||
StepAction(564, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B + 4, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
],
|
||||
),
|
||||
"accept_4_1": TestConfig(
|
||||
num_prompt_tokens=553,
|
||||
num_prompt_tokens=B - 7,
|
||||
num_generated_tokens=20,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 553, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(553, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(557, 4, [1, 1, 1, 1, 1], (3, 1), (3, 0)),
|
||||
StepAction(0, B - 7, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 7, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 3, 4, [1, 1, 1, 1, 1], (3, 1), (3, 0)),
|
||||
StepAction(
|
||||
561,
|
||||
B + 1,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
(-1, -1),
|
||||
),
|
||||
StepAction(565, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B + 5, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
],
|
||||
),
|
||||
"accept_4_2": TestConfig(
|
||||
num_prompt_tokens=554,
|
||||
num_prompt_tokens=B - 6,
|
||||
num_generated_tokens=25,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 554, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(554, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(558, 4, [1, 1, 1, 1, 1], (3, 1), (2, 0)),
|
||||
StepAction(0, B - 6, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 6, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 2, 4, [1, 1, 1, 1, 1], (3, 1), (2, 0)),
|
||||
StepAction(
|
||||
562,
|
||||
B + 2,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
(-1, -1),
|
||||
),
|
||||
StepAction(566, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B + 6, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
],
|
||||
),
|
||||
"accept_4_3": TestConfig(
|
||||
num_prompt_tokens=555,
|
||||
num_prompt_tokens=B - 5,
|
||||
num_generated_tokens=25,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 555, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(555, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(559, 4, [1, 1, 1, 1, 1], (3, 1), (1, 0)),
|
||||
StepAction(0, B - 5, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 5, 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 1, 4, [1, 1, 1, 1, 1], (3, 1), (1, 0)),
|
||||
StepAction(
|
||||
563,
|
||||
B + 3,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
(-1, -1),
|
||||
),
|
||||
StepAction(567, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B + 7, 4, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
],
|
||||
),
|
||||
"accept_4_4": TestConfig(
|
||||
num_prompt_tokens=556,
|
||||
num_prompt_tokens=B - 4,
|
||||
num_generated_tokens=25,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 556, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(556, 4, [1, 1, 1, 1], (-1, -1), (3, 0)),
|
||||
StepAction(560, 4, [1, 1, 1, 1, 1], (0, 1), (-1, -1)),
|
||||
StepAction(0, B - 4, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B - 4, 4, [1, 1, 1, 1], (-1, -1), (3, 0)),
|
||||
StepAction(B, 4, [1, 1, 1, 1, 1], (0, 1), (-1, -1)),
|
||||
StepAction(
|
||||
564,
|
||||
B + 4,
|
||||
4,
|
||||
[1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
@@ -739,23 +743,23 @@ def get_mamba_prefix_cache_step_configs(
|
||||
],
|
||||
),
|
||||
"prompt_block_size": TestConfig(
|
||||
num_prompt_tokens=560,
|
||||
num_prompt_tokens=B,
|
||||
num_generated_tokens=10,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 560, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(560, 4, [1, 1, 1, 1, 1], (0, 1), (-1, -1)),
|
||||
StepAction(0, B, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B, 4, [1, 1, 1, 1, 1], (0, 1), (-1, -1)),
|
||||
],
|
||||
),
|
||||
"prompt_2_block_size": TestConfig(
|
||||
num_prompt_tokens=560 * 2,
|
||||
num_prompt_tokens=B * 2,
|
||||
num_generated_tokens=10,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 560, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(560, 560, [1, 1, 1, 1, 1], (0, 1), (-1, -1)),
|
||||
StepAction(0, B, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B, B, [1, 1, 1, 1, 1], (0, 1), (-1, -1)),
|
||||
StepAction(
|
||||
560 * 2,
|
||||
B * 2,
|
||||
4,
|
||||
[1, 1, 1, 1, 1, 1] if a else [0, 1, 1, 1, 1, 1],
|
||||
(1, 2),
|
||||
@@ -764,14 +768,14 @@ def get_mamba_prefix_cache_step_configs(
|
||||
],
|
||||
),
|
||||
"prompt_2_block_size_10": TestConfig(
|
||||
num_prompt_tokens=560 * 2 + 10,
|
||||
num_prompt_tokens=B * 2 + 10,
|
||||
num_generated_tokens=10,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 560, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(560, 570, [1, 0, 1, 1, 1, 1], (0, 2), (-1, -1)),
|
||||
StepAction(0, B, [1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B, B + 10, [1, 0, 1, 1, 1, 1], (0, 2), (-1, -1)),
|
||||
StepAction(
|
||||
560 * 2 + 10,
|
||||
B * 2 + 10,
|
||||
4,
|
||||
[1, 0, 1, 1, 1, 1] if a else [0, 0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
@@ -780,14 +784,14 @@ def get_mamba_prefix_cache_step_configs(
|
||||
],
|
||||
),
|
||||
"prompt_3_block_size": TestConfig(
|
||||
num_prompt_tokens=560 * 3,
|
||||
num_prompt_tokens=B * 3,
|
||||
num_generated_tokens=10,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 560 * 2, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(560 * 2, 560, [0, 1, 1, 1, 1, 1], (1, 2), (-1, -1)),
|
||||
StepAction(0, B * 2, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B * 2, B, [0, 1, 1, 1, 1, 1], (1, 2), (-1, -1)),
|
||||
StepAction(
|
||||
560 * 3,
|
||||
B * 3,
|
||||
4,
|
||||
[0, 1, 1, 1, 1, 1, 1] if a else [0, 0, 1, 1, 1, 1, 1],
|
||||
(2, 3),
|
||||
@@ -796,14 +800,14 @@ def get_mamba_prefix_cache_step_configs(
|
||||
],
|
||||
),
|
||||
"prompt_3_block_size_10": TestConfig(
|
||||
num_prompt_tokens=560 * 3 + 10,
|
||||
num_prompt_tokens=B * 3 + 10,
|
||||
num_generated_tokens=10,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 560 * 2, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(560 * 2, 570, [0, 1, 0, 1, 1, 1, 1], (1, 3), (-1, -1)),
|
||||
StepAction(0, B * 2, [0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(B * 2, B + 10, [0, 1, 0, 1, 1, 1, 1], (1, 3), (-1, -1)),
|
||||
StepAction(
|
||||
560 * 3 + 10,
|
||||
B * 3 + 10,
|
||||
4,
|
||||
[0, 1, 0, 1, 1, 1, 1] if a else [0, 0, 0, 1, 1, 1, 1],
|
||||
(-1, -1),
|
||||
@@ -812,21 +816,21 @@ def get_mamba_prefix_cache_step_configs(
|
||||
],
|
||||
),
|
||||
"prompt_10_block_size": TestConfig(
|
||||
num_prompt_tokens=560 * 10,
|
||||
num_prompt_tokens=B * 10,
|
||||
num_generated_tokens=10,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 560 * 5, [0, 0, 0, 0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(0, B * 5, [0, 0, 0, 0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(
|
||||
560 * 5,
|
||||
560 * 4,
|
||||
B * 5,
|
||||
B * 4,
|
||||
[0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
|
||||
(4, 8),
|
||||
(-1, -1),
|
||||
),
|
||||
StepAction(
|
||||
560 * 9,
|
||||
560,
|
||||
B * 9,
|
||||
B,
|
||||
[0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1]
|
||||
if a
|
||||
else [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
|
||||
@@ -834,7 +838,7 @@ def get_mamba_prefix_cache_step_configs(
|
||||
(-1, -1),
|
||||
),
|
||||
StepAction(
|
||||
560 * 10,
|
||||
B * 10,
|
||||
4,
|
||||
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
|
||||
if a
|
||||
@@ -845,21 +849,21 @@ def get_mamba_prefix_cache_step_configs(
|
||||
],
|
||||
),
|
||||
"prompt_10_block_size_10": TestConfig(
|
||||
num_prompt_tokens=560 * 10 + 10,
|
||||
num_prompt_tokens=B * 10 + 10,
|
||||
num_generated_tokens=10,
|
||||
num_accepted_tokens=4,
|
||||
step_actions=[
|
||||
StepAction(0, 560 * 5, [0, 0, 0, 0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(0, B * 5, [0, 0, 0, 0, 1, 1, 1, 1], (-1, -1), (-1, -1)),
|
||||
StepAction(
|
||||
560 * 5,
|
||||
560 * 4,
|
||||
B * 5,
|
||||
B * 4,
|
||||
[0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
|
||||
(4, 8),
|
||||
(-1, -1),
|
||||
),
|
||||
StepAction(
|
||||
560 * 9,
|
||||
560 + 10,
|
||||
B * 9,
|
||||
B + 10,
|
||||
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1]
|
||||
if a
|
||||
else [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1],
|
||||
|
||||
@@ -215,6 +215,10 @@ def _make_dplb_client(num_engines: int = 3, client_count: int = 1) -> DPLBAsyncM
|
||||
client.lb_engines = [[0, 0, 0.0] for _ in range(num_engines)]
|
||||
client.eng_start_index = 0
|
||||
client._kv_event_sources = {}
|
||||
client.vllm_config = SimpleNamespace(
|
||||
use_v2_model_runner=True,
|
||||
parallel_config=SimpleNamespace(all2all_backend="allgather_reducescatter"),
|
||||
)
|
||||
return client
|
||||
|
||||
|
||||
@@ -248,6 +252,19 @@ def test_dplb_non_late_interaction_still_uses_lb():
|
||||
assert client.lb_engines[1][0] == 1
|
||||
|
||||
|
||||
def test_dplb_in_flight_request_stays_on_same_engine():
|
||||
client = _make_dplb_client()
|
||||
request = make_request(SamplingParams(max_tokens=1))
|
||||
engine = client.core_engines[2]
|
||||
client.reqs_in_flight[request.request_id] = engine
|
||||
client.engine_inflight[engine] = 1
|
||||
|
||||
chosen_engine = client.get_core_engine_for_request(request)
|
||||
|
||||
assert chosen_engine == engine
|
||||
assert client.engine_inflight[engine] == 1
|
||||
|
||||
|
||||
def test_dplb_burst_round_robins_despite_snapshot_rebinds():
|
||||
"""A stats snapshot rebind wipes the optimistic lb_engines increments;
|
||||
the exact in-flight floor must keep a burst spreading round-robin."""
|
||||
|
||||
@@ -11,8 +11,10 @@ row), the trailing positions are populated with sentinel values
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.logprobs import create_sample_logprobs
|
||||
from vllm.v1.engine import EngineCoreOutput
|
||||
from vllm.v1.engine.logprobs import LogprobsProcessor
|
||||
from vllm.v1.outputs import LogprobsLists
|
||||
|
||||
@@ -64,3 +66,24 @@ def test_accepts_exactly_sized_row():
|
||||
|
||||
pos = processor.logprobs[0]
|
||||
assert set(pos.keys()) == {7, 11, 13}
|
||||
|
||||
|
||||
def test_prompt_token_id_logprobs_are_popped_once():
|
||||
"""DELTA outputs carry fixed-ID prompt scores exactly once."""
|
||||
processor = _make_processor(num_logprobs=1)
|
||||
assert processor.pop_prompt_token_id_logprobs() is None
|
||||
|
||||
processor.update_from_output(
|
||||
EngineCoreOutput(
|
||||
request_id="req-0",
|
||||
new_token_ids=[],
|
||||
prompt_token_id_logprobs=torch.tensor(
|
||||
[[-0.5, -1.5], [-2.5, -3.5]], dtype=torch.float32
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
scores = processor.pop_prompt_token_id_logprobs()
|
||||
assert scores is not None
|
||||
assert scores.tolist() == [[-0.5, -1.5], [-2.5, -3.5]]
|
||||
assert processor.pop_prompt_token_id_logprobs() is None
|
||||
|
||||
@@ -119,7 +119,7 @@ def test_error_propagation_async_load(fail_scheduler: Scheduler):
|
||||
|
||||
scheduler_output = fail_scheduler.schedule()
|
||||
|
||||
assert len(fail_scheduler.skipped_waiting) == 1
|
||||
assert len(fail_scheduler.kv_holding_waiting) == 1
|
||||
assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
assert request.num_computed_tokens == num_external_computed_tokens
|
||||
|
||||
@@ -145,4 +145,5 @@ def test_error_propagation_async_load(fail_scheduler: Scheduler):
|
||||
assert output.finish_reason == FinishReason.ERROR
|
||||
|
||||
assert len(fail_scheduler.waiting) == 0
|
||||
assert len(fail_scheduler.skipped_waiting) == 0
|
||||
assert len(fail_scheduler.kv_holding_waiting) == 0
|
||||
assert not fail_scheduler.deferred_waiting
|
||||
|
||||
@@ -333,7 +333,7 @@ def test_async_recompute_blocks_not_cached_when_invalid(
|
||||
scheduler_output = recompute_scheduler.schedule()
|
||||
|
||||
# request should be waiting for remote KVs
|
||||
assert len(recompute_scheduler.skipped_waiting) == 1
|
||||
assert len(recompute_scheduler.kv_holding_waiting) == 1
|
||||
assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
assert request.num_computed_tokens == num_external_computed_tokens
|
||||
|
||||
|
||||
@@ -111,8 +111,8 @@ def test_async_load_failure(
|
||||
scheduler_output = scheduler.schedule()
|
||||
|
||||
assert len(scheduler.waiting) == 0
|
||||
assert len(scheduler.skipped_waiting) == 3
|
||||
for request in scheduler.skipped_waiting:
|
||||
assert len(scheduler.kv_holding_waiting) == 3
|
||||
for request in scheduler.kv_holding_waiting:
|
||||
assert request.num_computed_tokens == num_external_computed_tokens
|
||||
assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
assert scheduler.connector.get_num_new_matched_tokens.call_count == 3
|
||||
@@ -132,8 +132,8 @@ def test_async_load_failure(
|
||||
min_invalid_block_idx = min(invalid_block_idxs)
|
||||
|
||||
assert len(scheduler.waiting) == 0
|
||||
assert len(scheduler.skipped_waiting) == 3
|
||||
for request in scheduler.skipped_waiting:
|
||||
assert len(scheduler.kv_holding_waiting) == 3
|
||||
for request in scheduler.kv_holding_waiting:
|
||||
if request.request_id == request2.request_id:
|
||||
assert request.num_computed_tokens == (
|
||||
min_invalid_block_idx * scheduler.block_size
|
||||
@@ -340,8 +340,9 @@ def test_async_progressive_load_failure(
|
||||
scheduler_output = scheduler.schedule()
|
||||
|
||||
assert len(scheduler.waiting) == 0
|
||||
assert len(scheduler.skipped_waiting) == 1
|
||||
assert scheduler.skipped_waiting.peek_request().request_id == request.request_id
|
||||
assert len(scheduler.kv_holding_waiting) == 1
|
||||
peeked = scheduler.kv_holding_waiting.peek_request()
|
||||
assert peeked.request_id == request.request_id
|
||||
assert request.num_computed_tokens == num_external_computed_tokens
|
||||
assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
assert scheduler.connector.get_num_new_matched_tokens.call_count == 1
|
||||
@@ -363,8 +364,9 @@ def test_async_progressive_load_failure(
|
||||
min_invalid_block_idx = min(min_invalid_block_idx, invalid_block_idx)
|
||||
|
||||
assert len(scheduler.waiting) == 0
|
||||
assert len(scheduler.skipped_waiting) == 1
|
||||
assert scheduler.skipped_waiting.peek_request().request_id == request.request_id
|
||||
assert len(scheduler.kv_holding_waiting) == 1
|
||||
peeked = scheduler.kv_holding_waiting.peek_request()
|
||||
assert peeked.request_id == request.request_id
|
||||
assert request.num_computed_tokens == (
|
||||
min_invalid_block_idx * scheduler.block_size
|
||||
)
|
||||
|
||||
@@ -3026,7 +3026,7 @@ def test_empty_recv_is_reported_only_when_awaited(
|
||||
request is named in neither _recving_transfers nor _failed_recv_reqs and
|
||||
never reaches finished_recving. The scheduler has no other way to release a
|
||||
WAITING_FOR_REMOTE_KVS request, and there is no timeout, so it sits in
|
||||
skipped_waiting holding its blocks for the life of the process.
|
||||
kv_holding_waiting holding its blocks for the life of the process.
|
||||
|
||||
Notify-only (awaiting_kvs=False): request_finished seeding an empty recv to
|
||||
free P's blocks for a request aborted before it was scheduled, or a readback
|
||||
|
||||
@@ -16,10 +16,27 @@ from threading import Event, Lock
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import msgspec
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl import base_worker as bw
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
|
||||
NixlAgentMetadata,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_worker import (
|
||||
NixlPushConnectorWorker,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheTensor,
|
||||
MLAAttentionSpec,
|
||||
create_kv_cache_views,
|
||||
)
|
||||
|
||||
from .utils import create_vllm_config
|
||||
|
||||
|
||||
@@ -102,6 +119,189 @@ class _RecordingNixl:
|
||||
pass
|
||||
|
||||
|
||||
def _make_packed_mla_view_worker(
|
||||
layouts,
|
||||
block_stride,
|
||||
*,
|
||||
num_blocks=4,
|
||||
pp_size=1,
|
||||
backend_names=("FLASHMLA",),
|
||||
):
|
||||
"""Register real strided views; only NIXL and distributed runtime are fake."""
|
||||
block_size = 16
|
||||
raw = torch.zeros(num_blocks * block_stride, dtype=torch.int8)
|
||||
tensors, groups, caches = [], [], {}
|
||||
for name, (offset, page_size) in layouts.items():
|
||||
spec = MLAAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=page_size // block_size,
|
||||
dtype=torch.uint8,
|
||||
)
|
||||
tensor = KVCacheTensor(
|
||||
size=raw.nbytes,
|
||||
layers=[name],
|
||||
layer_stride=page_size,
|
||||
block_stride=block_stride,
|
||||
offset=offset,
|
||||
)
|
||||
tensors.append(tensor)
|
||||
groups.append(KVCacheGroupSpec([name], spec))
|
||||
(caches[name],) = create_kv_cache_views(
|
||||
raw, spec, num_blocks, KVCacheLayout.BLHNC, tensor
|
||||
)
|
||||
|
||||
config = create_vllm_config(block_size=block_size)
|
||||
config.parallel_config.pipeline_parallel_size = pp_size
|
||||
config.kv_transfer_config.kv_role = "kv_producer"
|
||||
config.cache_config.kv_cache_layout = "BLHNC"
|
||||
backends = []
|
||||
for name in backend_names:
|
||||
backend = MagicMock()
|
||||
backend.get_supported_kernel_block_sizes.return_value = [block_size]
|
||||
backend.get_name.return_value = name
|
||||
backend.full_cls_name.return_value = f"fake.{name}"
|
||||
backends.append(backend)
|
||||
with (
|
||||
patch.object(bw, "NixlWrapper", _RecordingNixl),
|
||||
patch.object(bw, "get_tensor_model_parallel_rank", return_value=0),
|
||||
patch.object(bw, "get_tensor_model_parallel_world_size", return_value=1),
|
||||
patch.object(bw, "get_current_attn_backends", return_value=backends),
|
||||
patch("threading.Thread"),
|
||||
):
|
||||
worker = NixlPushConnectorWorker(
|
||||
config,
|
||||
"producer" if pp_size > 1 else "consumer",
|
||||
KVCacheConfig(num_blocks, tensors, groups),
|
||||
)
|
||||
worker.use_mla = True
|
||||
worker.register_kv_caches(caches)
|
||||
return worker, raw
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize("num_layers", [1, 2])
|
||||
def test_packed_mla_pp1_push_peer_transfers_whole_rows(num_layers):
|
||||
layouts = {f"L{i}": (i * 128, 128) for i in range(num_layers)}
|
||||
stride = num_layers * 128
|
||||
worker, raw = _make_packed_mla_view_worker(layouts, stride)
|
||||
assert worker._registered_descs == [[(raw.data_ptr(), raw.nbytes, 0, "")]]
|
||||
assert worker.src_blocks_data.tolist() == [
|
||||
[raw.data_ptr() + block * stride, stride, 0] for block in range(4)
|
||||
]
|
||||
assert worker._transfer_layer_group_ids == ()
|
||||
metadata = msgspec.msgpack.decode(
|
||||
worker.xfer_handshake_metadata.agent_metadata_bytes, type=NixlAgentMetadata
|
||||
)
|
||||
assert metadata.packed_member_layouts == layouts
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize(
|
||||
"remote_backends, compatible",
|
||||
[
|
||||
(("INDEXER", "FLASHMLA"), True),
|
||||
(("FLASHMLA", "OTHER"), False),
|
||||
(("FLASHMLA",), False),
|
||||
],
|
||||
)
|
||||
def test_packed_push_compatibility_hash_uses_all_backends_in_stable_order(
|
||||
remote_backends, compatible
|
||||
):
|
||||
producer, _ = _make_packed_mla_view_worker(
|
||||
{"L0": (0, 128)},
|
||||
128,
|
||||
pp_size=2,
|
||||
backend_names=("FLASHMLA", "INDEXER"),
|
||||
)
|
||||
consumer, _ = _make_packed_mla_view_worker(
|
||||
{"L0": (0, 128)}, 128, backend_names=remote_backends
|
||||
)
|
||||
assert (producer.compat_hash == consumer.compat_hash) is compatible
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize("p_num_blocks, d_num_blocks", [(4, 4), (4, 6), (6, 4)])
|
||||
def test_packed_mla_pp_pairs_asymmetric_strides_and_overlapping_layers(
|
||||
p_num_blocks, d_num_blocks
|
||||
):
|
||||
# Different cache groups overlay pages of different sizes at the same address.
|
||||
# PP also changes both the placement and the stride of the matching D pages.
|
||||
producer, p_raw = _make_packed_mla_view_worker(
|
||||
{"L2": (0, 128), "L2.swa": (0, 64), "L3": (128, 64)},
|
||||
192,
|
||||
num_blocks=p_num_blocks,
|
||||
pp_size=2,
|
||||
)
|
||||
consumer, d_raw = _make_packed_mla_view_worker(
|
||||
{"L0": (0, 128), "L2": (128, 128), "L2.swa": (0, 64), "L3": (64, 64)},
|
||||
256,
|
||||
num_blocks=d_num_blocks,
|
||||
)
|
||||
assert producer.block_len_per_layer == [128, 64, 64]
|
||||
assert producer._transfer_layer_group_ids == (0, 1, 2)
|
||||
assert producer.num_descs == 3 * p_num_blocks
|
||||
local_ids = producer._compute_desc_ids(
|
||||
[[1], [2], [3]],
|
||||
producer.num_blocks,
|
||||
None,
|
||||
1,
|
||||
region_num_blocks=producer.dst_region_num_blocks[producer.engine_id],
|
||||
)
|
||||
assert producer.src_blocks_data[local_ids].tolist() == [
|
||||
[p_raw.data_ptr() + 192, 128, 0],
|
||||
[p_raw.data_ptr() + 2 * 192, 64, 0],
|
||||
[p_raw.data_ptr() + 128 + 3 * 192, 64, 0],
|
||||
]
|
||||
# Each decoder TP rank receives the complete MLA page, without head slicing.
|
||||
for rank in (0, 1):
|
||||
metadata = msgspec.msgpack.decode(
|
||||
consumer.xfer_handshake_metadata.agent_metadata_bytes,
|
||||
type=NixlAgentMetadata,
|
||||
)
|
||||
producer.add_remote_agent(metadata, remote_tp_rank=rank, remote_tp_size=2)
|
||||
assert metadata.region_num_blocks == [d_num_blocks] * 3
|
||||
assert metadata.region_names == ["L2", "L2.swa", "L3"]
|
||||
remote_ids = producer._compute_desc_ids(
|
||||
[[3], [1], [2]],
|
||||
metadata.num_blocks,
|
||||
None,
|
||||
1,
|
||||
region_num_blocks=producer.dst_region_num_blocks[consumer.engine_id],
|
||||
)
|
||||
handle = producer.dst_xfer_side_handles[consumer.engine_id][rank]
|
||||
remote_descs = producer.nixl_wrapper.dlists[handle]
|
||||
assert len(remote_descs) == 3 * d_num_blocks
|
||||
assert remote_descs[remote_ids].tolist() == [
|
||||
[d_raw.data_ptr() + 128 + 3 * 256, 128, 0],
|
||||
[d_raw.data_ptr() + 256, 64, 0],
|
||||
[d_raw.data_ptr() + 64 + 2 * 256, 64, 0],
|
||||
]
|
||||
aligned = msgspec.msgpack.encode(metadata)
|
||||
producer._align_remote_regions_by_layer(metadata)
|
||||
assert msgspec.msgpack.encode(metadata) == aligned
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
@pytest.mark.parametrize("remote_block_size", [8, 32])
|
||||
def test_packed_mla_rejects_unequal_block_sizes_before_peer_registration(
|
||||
remote_block_size,
|
||||
):
|
||||
producer, _ = _make_packed_mla_view_worker({"L0": (0, 128)}, 128, pp_size=2)
|
||||
metadata = msgspec.msgpack.decode(
|
||||
producer.xfer_handshake_metadata.agent_metadata_bytes, type=NixlAgentMetadata
|
||||
)
|
||||
metadata.engine_id = "remote"
|
||||
metadata.block_size = remote_block_size
|
||||
with pytest.raises(NotImplementedError, match="identical P/D block sizes"):
|
||||
producer.add_remote_agent(metadata)
|
||||
assert len(producer.nixl_wrapper.dlists) == 1 # Only the local list exists.
|
||||
assert producer.tp_mappings == {}
|
||||
assert "remote" not in producer.dst_num_blocks
|
||||
with pytest.raises(KeyError):
|
||||
producer.transfer_topo.get_engine_info("remote")
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_local_descriptors_follow_each_region_pool_capacity():
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
|
||||
@@ -200,8 +400,8 @@ def _register_overlaid_mla_worker(
|
||||
worker.src_xfer_handles_by_block_size = {}
|
||||
worker.kv_caches_base_addr = defaultdict(dict)
|
||||
worker._mamba_ssm_size = (0, 0)
|
||||
worker.kv_cache_layout = "NHD"
|
||||
worker.host_buffer_kv_cache_layout = "NHD"
|
||||
worker.kv_cache_layout = "LBNHC"
|
||||
worker.host_buffer_kv_cache_layout = "LBNHC"
|
||||
worker._physical_blocks_per_logical_kv_block = 1
|
||||
worker._logical_num_blocks = num_blocks
|
||||
worker.region_mem_types = []
|
||||
@@ -221,6 +421,7 @@ def _register_overlaid_mla_worker(
|
||||
worker.device_kv_caches = {}
|
||||
worker.pp_size = 2 if push_pp else 1
|
||||
worker._is_hma_required = True
|
||||
worker._has_packed_cache = False
|
||||
worker.dcp_size = 1
|
||||
worker.pcp_size = 1
|
||||
worker.kv_buffer_device = "cuda"
|
||||
|
||||
@@ -368,6 +368,7 @@ class _StubWriterWorker(NixlPushConnectorWorker):
|
||||
w._recving_transfers = defaultdict(list)
|
||||
w._is_hma_required = False
|
||||
w.xfer_stats = NixlKVConnectorStats()
|
||||
w._has_packed_cache = False
|
||||
w._reqs_to_process = set()
|
||||
w._reqs_to_send = {}
|
||||
w.consumer_notification_counts_by_req = defaultdict(int)
|
||||
@@ -1843,6 +1844,40 @@ def test_layer_metadata_round_trip():
|
||||
assert msgspec.msgpack.Decoder(NixlAgentMetadata).decode(encoded) == metadata
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"layouts, error",
|
||||
[
|
||||
({"L0": (-1, 64)}, "escapes its block"),
|
||||
({"L0": (0, 0)}, "escapes its block"),
|
||||
({"L0": (200, 64)}, "escapes its block"),
|
||||
({"L1": (0, 64)}, "has no layout"),
|
||||
({"L0": (0, 32)}, "page sizes must match"),
|
||||
],
|
||||
)
|
||||
def test_packed_layer_alignment_rejects_invalid_page_layout(layouts, error):
|
||||
worker = _layer_routing_worker([["L0"]], {"L0": 0})
|
||||
worker.block_len_per_layer = [64]
|
||||
metadata = _agent_metadata([["L0", "L1"]], [0x10000], [256])
|
||||
metadata.packed_member_layouts = layouts
|
||||
with pytest.raises(AssertionError, match=error):
|
||||
worker._align_remote_regions_by_layer(metadata)
|
||||
|
||||
|
||||
def test_layer_alignment_preserves_nonpacked_regions_alongside_packed_layers():
|
||||
worker = _layer_routing_worker([["a"], ["b"]], {"a": 0, "b": 1})
|
||||
worker.block_len_per_layer = [64, 128]
|
||||
metadata = _agent_metadata(
|
||||
[["a", "other"], ["b"]], [0x1000, 0x2000], [192, 128], [256, 128]
|
||||
)
|
||||
metadata.packed_member_layouts = {"a": (64, 64), "other": (128, 64)}
|
||||
|
||||
worker._align_remote_regions_by_layer(metadata)
|
||||
|
||||
assert metadata.kv_caches_base_addr == [0x1040, 0x2000]
|
||||
assert metadata.block_lens == [64, 128]
|
||||
assert metadata.block_strides == [256, 128]
|
||||
|
||||
|
||||
def test_layer_identity_gate_preserves_the_non_hma_path():
|
||||
assert _layer_routing_worker([["a"]], {"a": 0})._transfer_layer_region_indices == (
|
||||
0,
|
||||
@@ -1850,6 +1885,7 @@ def test_layer_identity_gate_preserves_the_non_hma_path():
|
||||
|
||||
# A base worker (pull) never routes by layer name.
|
||||
pull = object.__new__(NixlBaseConnectorWorker)
|
||||
pull.pp_size = 2
|
||||
pull._transfer_layer_names = ()
|
||||
pull._transfer_layer_region_indices = ()
|
||||
pull._transfer_layer_group_ids = ()
|
||||
|
||||
@@ -25,7 +25,7 @@ pytestmark = pytest.mark.cpu_test
|
||||
|
||||
|
||||
def _num_waiting_requests(scheduler) -> int:
|
||||
return len(scheduler.waiting) + len(scheduler.skipped_waiting)
|
||||
return len(scheduler.waiting) + len(scheduler.kv_holding_waiting)
|
||||
|
||||
|
||||
def test_basic_lifecycle():
|
||||
@@ -64,7 +64,7 @@ def test_basic_lifecycle():
|
||||
|
||||
# Req waiting for KVs with no computed/scheduled toks ...
|
||||
assert _num_waiting_requests(scheduler) == 1
|
||||
assert request in scheduler.skipped_waiting
|
||||
assert request in scheduler.kv_holding_waiting
|
||||
assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
assert request.num_computed_tokens == NUM_TOKENS
|
||||
|
||||
@@ -791,3 +791,71 @@ def test_async_load_reserves_blocks_for_promotion_margin():
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert req_a.status == RequestStatus.RUNNING
|
||||
assert scheduler_output.num_scheduled_tokens[req_a.request_id] > 0
|
||||
|
||||
|
||||
def test_deferred_lookup_does_not_block_parked_load():
|
||||
"""A request with a deferred connector lookup must not strand an async
|
||||
load queued behind it.
|
||||
|
||||
req_a's lookup is deferred (connector returns None), so it is parked in
|
||||
waiting holding no blocks; req_b is then admitted as an async
|
||||
load holding most of the pool. Once req_a's lookup resolves it cannot
|
||||
allocate, and the waiting scan stops at it every step. The parked load
|
||||
must still be promotable: it lives in the KV-holding queue
|
||||
that is drained first, so it runs, finishes, and frees its blocks for
|
||||
req_a.
|
||||
"""
|
||||
vllm_config = create_vllm_config()
|
||||
BLOCK_SIZE = vllm_config.cache_config.block_size
|
||||
scheduler = create_scheduler(vllm_config, num_blocks=8) # usable = 7
|
||||
|
||||
req_a = create_request(
|
||||
request_id=1, block_size=BLOCK_SIZE, num_tokens=BLOCK_SIZE * 4, max_tokens=1
|
||||
)
|
||||
req_b = create_request(
|
||||
request_id=2,
|
||||
block_size=BLOCK_SIZE,
|
||||
num_tokens=BLOCK_SIZE * 5,
|
||||
do_remote_prefill=True,
|
||||
max_tokens=1,
|
||||
)
|
||||
scheduler.add_request(req_a)
|
||||
scheduler.add_request(req_b)
|
||||
|
||||
deferrals = [(None, False)]
|
||||
|
||||
def lookup(request, num_computed_tokens):
|
||||
if request is req_b:
|
||||
return BLOCK_SIZE * 5, True
|
||||
return deferrals.pop() if deferrals else (0, False)
|
||||
|
||||
with patch.object(
|
||||
scheduler.connector, "get_num_new_matched_tokens", side_effect=lookup
|
||||
):
|
||||
# Step 1: req_a's lookup is deferred; req_b is admitted as an async
|
||||
# load holding 5 of 7 usable blocks.
|
||||
scheduler.schedule()
|
||||
assert req_a.status == RequestStatus.WAITING
|
||||
assert req_b.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
|
||||
# req_a's lookup resolves (no hit) while req_b's transfer is in
|
||||
# flight; req_a needs 4 blocks but only 2 are free, so the waiting
|
||||
# scan stops at it. req_b's transfer then finishes.
|
||||
scheduler.update_from_output(
|
||||
scheduler.schedule(),
|
||||
create_model_runner_output([], finished_recving={req_b.request_id}),
|
||||
)
|
||||
|
||||
# req_b must still be reached, promoted, and scheduled despite the
|
||||
# scan stopping at req_a.
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert req_b.status == RequestStatus.RUNNING
|
||||
assert scheduler_output.num_scheduled_tokens[req_b.request_id] > 0
|
||||
|
||||
# req_b finishes and frees its blocks; now req_a fits and runs.
|
||||
scheduler.update_from_output(
|
||||
scheduler_output, create_model_runner_output([req_b])
|
||||
)
|
||||
scheduler_output = scheduler.schedule()
|
||||
assert req_a.status == RequestStatus.RUNNING
|
||||
assert scheduler_output.num_scheduled_tokens[req_a.request_id] > 0
|
||||
|
||||
@@ -54,6 +54,8 @@ def assert_scheduler_empty(scheduler: Scheduler):
|
||||
# Scheduler Metadata.
|
||||
assert len(scheduler.requests) == 0
|
||||
assert len(scheduler.waiting) == 0
|
||||
assert len(scheduler.kv_holding_waiting) == 0
|
||||
assert not scheduler.deferred_waiting
|
||||
assert len(scheduler.running) == 0
|
||||
assert len(scheduler.finished_req_ids) == 0
|
||||
assert len(scheduler.finished_recving_kv_req_ids) == 0
|
||||
|
||||
@@ -6,7 +6,9 @@ import math
|
||||
from collections.abc import Generator
|
||||
from types import SimpleNamespace
|
||||
from typing import get_args
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
@@ -23,6 +25,7 @@ from vllm.config.model import LogprobsMode
|
||||
from vllm.distributed import cleanup_dist_env_and_memory
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.engine.input_processor import InputProcessor
|
||||
|
||||
from ...conftest import HfRunner, VllmRunner
|
||||
|
||||
@@ -81,9 +84,9 @@ def hf_model(hf_runner) -> Generator[HfRunner, None, None]:
|
||||
yield hf_model
|
||||
|
||||
|
||||
def _model_config(vocab_size: int = 10):
|
||||
def _model_config(vocab_size: int = 10, max_logprobs: int = 20):
|
||||
return SimpleNamespace(
|
||||
max_logprobs=20,
|
||||
max_logprobs=max_logprobs,
|
||||
logits_processors=None,
|
||||
is_diffusion=False,
|
||||
get_vocab_size=lambda: vocab_size,
|
||||
@@ -432,6 +435,57 @@ def test_logprob_token_ids_validate_vocab_bounds_invalid(token_ids: list[int]):
|
||||
)
|
||||
|
||||
|
||||
def test_prompt_logprob_token_ids_bounded_by_max_logprobs():
|
||||
"""The candidate count is bounded by max_logprobs."""
|
||||
model_config = _model_config(vocab_size=100, max_logprobs=4)
|
||||
|
||||
def verify(**kwargs):
|
||||
SamplingParams(**kwargs).verify(
|
||||
model_config,
|
||||
speculative_config=None,
|
||||
structured_outputs_config=None,
|
||||
tokenizer=None,
|
||||
)
|
||||
|
||||
verify(prompt_logprob_token_ids=[1, 2, 3, 4])
|
||||
|
||||
# The error names the value to raise max_logprobs to.
|
||||
with pytest.raises(VLLMValidationError, match=r"max_logprobs.*at least 5"):
|
||||
verify(prompt_logprob_token_ids=[1, 2, 3, 4, 5])
|
||||
|
||||
# prompt_logprob_start alone is a caller mistake, not a silent no-op.
|
||||
with pytest.raises(VLLMValidationError, match="requires prompt_logprob_token_ids"):
|
||||
verify(prompt_logprob_start=3)
|
||||
|
||||
|
||||
def test_prompt_logprob_token_ids_require_v2_model_runner():
|
||||
"""Only the V2 runner scores them; the V1 runner would return None, and
|
||||
kv-sharing fast prefill would score rows the cross-decoder never ran."""
|
||||
processor = SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
return_sampling_mask=False, enable_trace_replay=False, is_diffusion=False
|
||||
),
|
||||
vllm_config=SimpleNamespace(
|
||||
reasoning_config=None,
|
||||
use_v2_model_runner=False,
|
||||
cache_config=SimpleNamespace(kv_sharing_fast_prefill=False),
|
||||
),
|
||||
speculative_config=None,
|
||||
structured_outputs_config=None,
|
||||
tokenizer=None,
|
||||
validate_logits_processors_params=lambda params: None,
|
||||
)
|
||||
params = SamplingParams(prompt_logprob_token_ids=[1, 2])
|
||||
with patch.object(SamplingParams, "verify"):
|
||||
with pytest.raises(VLLMValidationError, match="V2 model runner"):
|
||||
InputProcessor._validate_params(processor, params, ("generate",))
|
||||
processor.vllm_config.use_v2_model_runner = True
|
||||
InputProcessor._validate_params(processor, params, ("generate",))
|
||||
processor.vllm_config.cache_config.kv_sharing_fast_prefill = True
|
||||
with pytest.raises(VLLMValidationError, match="fast-prefill"):
|
||||
InputProcessor._validate_params(processor, params, ("generate",))
|
||||
|
||||
|
||||
def test_none_logprobs(vllm_model, example_prompts):
|
||||
"""Engine should return `logprobs` and `prompt_logprobs` as `None`.
|
||||
|
||||
@@ -1298,6 +1352,127 @@ def test_prompt_logprobs_with_chunking_and_preemption():
|
||||
print(f"Test passed with {preemptions} preemptions")
|
||||
|
||||
|
||||
def test_prompt_logprob_token_ids_with_chunking_and_preemption(monkeypatch):
|
||||
"""Fixed-ID scores stay row-aligned across chunked prefill and preemption."""
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
|
||||
prompts = [
|
||||
"The following numbers of the sequence "
|
||||
+ ", ".join(str(i) for i in range(10))
|
||||
+ " are:",
|
||||
"In one word, the capital of France is ",
|
||||
] + [f"Tell me about the number {i}: " for i in range(32)]
|
||||
|
||||
start = 2
|
||||
candidate_ids = [10, 100, 1000, 10000]
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=40,
|
||||
min_tokens=20,
|
||||
prompt_logprob_token_ids=candidate_ids,
|
||||
prompt_logprob_start=start,
|
||||
)
|
||||
|
||||
with VllmRunner(
|
||||
"Qwen/Qwen3-0.6B",
|
||||
max_model_len=512,
|
||||
enable_chunked_prefill=True,
|
||||
max_num_batched_tokens=48, # Force prefill chunking
|
||||
num_gpu_blocks_override=33, # Force preemptions (32 usable + null block)
|
||||
disable_log_stats=False,
|
||||
gpu_memory_utilization=0.25,
|
||||
) as vllm_model:
|
||||
metrics_before = vllm_model.llm.get_metrics()
|
||||
outputs = vllm_model.llm.generate(prompts, sampling_params)
|
||||
|
||||
for i, output in enumerate(outputs):
|
||||
scores = output.prompt_token_id_logprobs
|
||||
assert scores is not None, f"Output {i} missing fixed-ID scores"
|
||||
expected_shape = (
|
||||
len(output.prompt_token_ids) - 1 - start,
|
||||
len(candidate_ids),
|
||||
)
|
||||
assert scores.shape == expected_shape, (
|
||||
f"Output {i} scored {scores.shape}, expected {expected_shape}"
|
||||
)
|
||||
assert math.isfinite(float(scores.min()))
|
||||
assert float(scores.max()) <= 1e-3, "logprobs must be <= 0"
|
||||
|
||||
metrics_after = vllm_model.llm.get_metrics()
|
||||
preemptions_before = next(
|
||||
(m.value for m in metrics_before if m.name == "vllm:num_preemptions"), 0
|
||||
)
|
||||
preemptions_after = next(
|
||||
(m.value for m in metrics_after if m.name == "vllm:num_preemptions"), 0
|
||||
)
|
||||
assert preemptions_after - preemptions_before > 0, (
|
||||
"Test did not trigger any preemptions"
|
||||
)
|
||||
|
||||
# Row alignment is numerical: chunked and preempted scores must match an
|
||||
# unchunked, unpreempted run of the same requests. Batch composition moves
|
||||
# bf16 tail logprobs by a few percent; a misaligned row differs by nats.
|
||||
with VllmRunner(
|
||||
"Qwen/Qwen3-0.6B",
|
||||
max_model_len=512,
|
||||
max_logprobs=64,
|
||||
gpu_memory_utilization=0.25,
|
||||
) as reference:
|
||||
reference_outputs = reference.llm.generate(prompts, sampling_params)
|
||||
own_ids = [list(dict.fromkeys(o.prompt_token_ids)) for o in reference_outputs]
|
||||
self_scored = reference.llm.generate(
|
||||
prompts,
|
||||
[
|
||||
SamplingParams(
|
||||
max_tokens=1, prompt_logprobs=0, prompt_logprob_token_ids=ids
|
||||
)
|
||||
for ids in own_ids
|
||||
],
|
||||
)
|
||||
for output, ref in zip(outputs, reference_outputs):
|
||||
np.testing.assert_allclose(
|
||||
output.prompt_token_id_logprobs, ref.prompt_token_id_logprobs, rtol=0.1
|
||||
)
|
||||
for output, ids in zip(self_scored, own_ids):
|
||||
scores = output.prompt_token_id_logprobs
|
||||
for row, target in enumerate(output.prompt_token_ids[1:]):
|
||||
expected = output.prompt_logprobs[row + 1][target].logprob
|
||||
assert scores[row, ids.index(target)] == pytest.approx(expected, abs=1e-3)
|
||||
|
||||
|
||||
def test_prompt_logprob_token_ids_drop_partially_scored_prefills(monkeypatch):
|
||||
"""A prefill that starts past the first scored row returns no scores.
|
||||
|
||||
Such a prefill (here a prefix-cache hit the caller opted back into) never
|
||||
computes the leading rows, so emitting the buffer would return values the
|
||||
model never produced for them.
|
||||
"""
|
||||
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
|
||||
|
||||
prompt = "The capital of France is Paris. " * 20
|
||||
sampling_params = SamplingParams(
|
||||
temperature=0.0,
|
||||
max_tokens=1,
|
||||
prompt_logprob_token_ids=[10, 100, 1000],
|
||||
skip_reading_prefix_cache=False,
|
||||
)
|
||||
|
||||
with VllmRunner(
|
||||
"Qwen/Qwen3-0.6B",
|
||||
max_model_len=512,
|
||||
enable_prefix_caching=True,
|
||||
gpu_memory_utilization=0.25,
|
||||
) as vllm_model:
|
||||
first = vllm_model.llm.generate([prompt], sampling_params)[0]
|
||||
assert first.prompt_token_id_logprobs is not None
|
||||
assert math.isfinite(float(first.prompt_token_id_logprobs.min()))
|
||||
|
||||
# The re-send is served from the prefix cache, so its prefill starts
|
||||
# past row 0 and the leading rows are never computed.
|
||||
second = vllm_model.llm.generate([prompt], sampling_params)[0]
|
||||
assert second.prompt_token_id_logprobs is None
|
||||
|
||||
|
||||
@large_gpu_mark(min_gb=24)
|
||||
def test_token_logprobs_large_batch_int64_row_offset():
|
||||
"""Regression: logprob kernel row offset (row * vocab_size) must use int64.
|
||||
|
||||
@@ -41,6 +41,14 @@ def test_sampling_params_trace_field_rejects_empty_list():
|
||||
)
|
||||
|
||||
|
||||
def test_sampling_params_trace_field_rejects_prompt_scoring():
|
||||
params = SamplingParams(trace_decode_token_ids=[1], prompt_logprob_token_ids=[2, 3])
|
||||
with pytest.raises(ValueError, match="prompt_logprob_token_ids"):
|
||||
params._validate_trace_replay(
|
||||
_make_model_config(vocab_size=100), speculative_config=None
|
||||
)
|
||||
|
||||
|
||||
def test_sampling_params_trace_field_requires_single_output():
|
||||
params = SamplingParams(n=2, trace_decode_token_ids=[1])
|
||||
with pytest.raises(ValueError, match="requires n=1"):
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""``get_top_tokens`` on the DeepSeek V4 MTP drafter.
|
||||
|
||||
The speculator opts into ``use_local_argmax_reduction`` by probing the draft
|
||||
model for ``get_top_tokens``, and expects it to select the same greedy draft
|
||||
token the full-vocab argmax would. V4 reaches its LM head through hc_head and
|
||||
the shared head's RMSNorm, so both methods have to share that transform.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from transformers import PreTrainedConfig
|
||||
|
||||
from vllm.model_executor.layers.logits_processor import LogitsProcessor
|
||||
from vllm.model_executor.layers.mhc import HCHeadOp
|
||||
from vllm.model_executor.models.deepseek_mtp import SharedHead
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_rocm():
|
||||
pytest.skip(
|
||||
"get_top_tokens is implemented on the ROCm DeepSeek V4 MTP drafter only.",
|
||||
allow_module_level=True,
|
||||
)
|
||||
|
||||
from vllm.models.deepseek_v4.amd.mtp import ( # noqa: E402
|
||||
DeepSeekV4MTP,
|
||||
DeepSeekV4MultiTokenPredictor,
|
||||
)
|
||||
|
||||
DEVICE_TYPE = current_platform.device_type
|
||||
START_LAYER_IDX = 61
|
||||
HIDDEN_SIZE = 4096
|
||||
HC_MULT = 4
|
||||
RMS_NORM_EPS = 1e-6
|
||||
HC_EPS = 1e-6
|
||||
_EMBEDDING = "vllm.model_executor.layers.vocab_parallel_embedding"
|
||||
|
||||
|
||||
def _make_predictor(vocab_size: int) -> DeepSeekV4MultiTokenPredictor:
|
||||
config = PreTrainedConfig()
|
||||
config.hidden_size = HIDDEN_SIZE
|
||||
config.vocab_size = vocab_size
|
||||
config.rms_norm_eps = RMS_NORM_EPS
|
||||
|
||||
# A single vocab shard, so the reduction returns the local argmax without
|
||||
# touching the process group.
|
||||
with (
|
||||
mock.patch(f"{_EMBEDDING}.get_tensor_model_parallel_rank", return_value=0),
|
||||
mock.patch(
|
||||
f"{_EMBEDDING}.get_tensor_model_parallel_world_size", return_value=1
|
||||
),
|
||||
):
|
||||
shared_head = SharedHead(config=config, prefix="shared_head")
|
||||
|
||||
generator = torch.Generator().manual_seed(7)
|
||||
with torch.no_grad():
|
||||
shared_head.head.weight.normal_(0.0, 0.02, generator=generator)
|
||||
# The default norm weight is all ones, and the argmax is invariant to
|
||||
# the norm's per-row rescale, so a uniform gain would hide a skipped
|
||||
# shared_head. Vary it so the comparison below can see one.
|
||||
shared_head.norm.weight.normal_(1.0, 0.5, generator=generator)
|
||||
shared_head = shared_head.to(device=DEVICE_TYPE, dtype=torch.bfloat16)
|
||||
|
||||
hc_head_fn = torch.randn(
|
||||
HC_MULT, HC_MULT * HIDDEN_SIZE, dtype=torch.float32, generator=generator
|
||||
)
|
||||
# Non-trivial gate scale and bias: hc_head mixes the hc_mult streams with
|
||||
# these, and defaults of 0 would make a skipped hc_head harder to see.
|
||||
hc_head_scale = torch.randn(1, dtype=torch.float32, generator=generator) * 0.1
|
||||
hc_head_base = torch.randn(HC_MULT, dtype=torch.float32, generator=generator) * 0.1
|
||||
|
||||
mtp_layer = SimpleNamespace(
|
||||
config=config,
|
||||
hc_mult=HC_MULT,
|
||||
hc_eps=HC_EPS,
|
||||
rms_norm_eps=RMS_NORM_EPS,
|
||||
hc_head_op=HCHeadOp(),
|
||||
hc_head_fn=(hc_head_fn * 1e-4).to(DEVICE_TYPE),
|
||||
hc_head_scale=hc_head_scale.to(DEVICE_TYPE),
|
||||
hc_head_base=hc_head_base.to(DEVICE_TYPE),
|
||||
shared_head=shared_head,
|
||||
)
|
||||
|
||||
# Only the attributes the two methods read; a real predictor would also
|
||||
# build the MLA/MoE draft block, which is irrelevant here.
|
||||
predictor = object.__new__(DeepSeekV4MultiTokenPredictor)
|
||||
torch.nn.Module.__init__(predictor)
|
||||
predictor.layers = {str(START_LAYER_IDX): mtp_layer}
|
||||
predictor.mtp_start_layer_idx = START_LAYER_IDX
|
||||
predictor.num_mtp_layers = 1
|
||||
predictor.logits_processor = LogitsProcessor(vocab_size)
|
||||
return predictor
|
||||
|
||||
|
||||
def _hidden_states(num_tokens: int, seed: int) -> torch.Tensor:
|
||||
"""The flat pre-hc_head residual the MTP layer returns."""
|
||||
generator = torch.Generator().manual_seed(seed)
|
||||
hidden_states = torch.randn(
|
||||
num_tokens, HC_MULT * HIDDEN_SIZE, dtype=torch.float32, generator=generator
|
||||
)
|
||||
return hidden_states.to(device=DEVICE_TYPE, dtype=torch.bfloat16)
|
||||
|
||||
|
||||
def _assert_selects_max_logit(top: torch.Tensor, logits: torch.Tensor) -> None:
|
||||
"""The selected token must carry the row's maximum logit.
|
||||
|
||||
hc_head emits bf16, so rows can tie for the maximum and then no single
|
||||
index is the right answer; compare the values the two paths select.
|
||||
"""
|
||||
assert top.shape == (logits.shape[0],)
|
||||
selected = logits.gather(1, top.unsqueeze(1)).squeeze(1)
|
||||
assert torch.equal(selected, logits.max(dim=-1).values)
|
||||
|
||||
|
||||
def test_get_top_tokens_matches_full_argmax(default_vllm_config):
|
||||
"""Same draft token as the path taken when the reduction is off.
|
||||
|
||||
``get_top_tokens`` has to run the same pre-head transform as
|
||||
``compute_logits``: hc_head over the (T, hc_mult, D) residual, then the
|
||||
shared head's RMSNorm. Dropping either one returns a different draft token
|
||||
instead of failing, which is what this comparison catches.
|
||||
"""
|
||||
predictor = _make_predictor(vocab_size=512)
|
||||
|
||||
for num_tokens in (1, 16, 128):
|
||||
hidden_states = _hidden_states(num_tokens, seed=11)
|
||||
|
||||
logits = predictor.compute_logits(hidden_states)
|
||||
top = predictor.get_top_tokens(hidden_states)
|
||||
|
||||
assert top.dtype == torch.int64
|
||||
_assert_selects_max_logit(top, logits)
|
||||
|
||||
|
||||
def test_get_top_tokens_honors_padded_vocab(default_vllm_config):
|
||||
"""Padding entries above ``org_vocab_size`` must never win the argmax."""
|
||||
vocab_size = 500
|
||||
predictor = _make_predictor(vocab_size)
|
||||
head = predictor.layers[str(START_LAYER_IDX)].shared_head.head
|
||||
assert head.shard_indices.num_org_vocab_padding > 0
|
||||
|
||||
hidden_states = _hidden_states(32, seed=13)
|
||||
logits = predictor.compute_logits(hidden_states)
|
||||
top = predictor.get_top_tokens(hidden_states)
|
||||
|
||||
_assert_selects_max_logit(top, logits)
|
||||
assert (top < vocab_size).all()
|
||||
|
||||
|
||||
def test_wrapper_forwards_spec_step_idx():
|
||||
"""``DeepSeekV4MTP`` is what the speculator probes, so it needs the method."""
|
||||
assert hasattr(DeepSeekV4MTP, "get_top_tokens")
|
||||
|
||||
hidden_states = torch.empty(0)
|
||||
wrapper = object.__new__(DeepSeekV4MTP)
|
||||
wrapper.model = SimpleNamespace(get_top_tokens=lambda *args: args)
|
||||
|
||||
assert DeepSeekV4MTP.get_top_tokens(wrapper, hidden_states, 2) == (hidden_states, 2)
|
||||
assert DeepSeekV4MTP.get_top_tokens(wrapper, hidden_states) == (hidden_states, 0)
|
||||
@@ -126,7 +126,7 @@ def test_dynamic_sd_full_cudagraph_covers_all_uniform_decode_shapes(monkeypatch)
|
||||
num_reqs,
|
||||
num_tokens,
|
||||
max_query_len,
|
||||
has_prefill=False,
|
||||
decode_graph_eligible=True,
|
||||
)
|
||||
|
||||
# The scheduler should mark every one of these shapes as a uniform
|
||||
@@ -262,14 +262,14 @@ def test_prompt_chunks_shaped_like_spec_decode_miss_the_full_graph(monkeypatch):
|
||||
# The batch shape is indistinguishable from a full batch of spec decodes.
|
||||
assert (
|
||||
get_uniform_decode_token_count(
|
||||
num_reqs, num_tokens, decode_query_len, has_prefill=False
|
||||
num_reqs, num_tokens, decode_query_len, decode_graph_eligible=True
|
||||
)
|
||||
== 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, has_prefill=True
|
||||
num_reqs, num_tokens, decode_query_len, decode_graph_eligible=False
|
||||
)
|
||||
assert uniform_tok_count is None
|
||||
desc = manager.dispatch(
|
||||
@@ -283,7 +283,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, has_prefill=False
|
||||
num_reqs, num_tokens, decode_query_len, decode_graph_eligible=True
|
||||
)
|
||||
assert uniform_tok_count == decode_query_len
|
||||
desc = manager.dispatch(
|
||||
@@ -336,7 +336,7 @@ def test_basic_sd_does_not_capture_shorter_full_decode_shapes(monkeypatch):
|
||||
num_reqs,
|
||||
num_tokens,
|
||||
max_query_len,
|
||||
has_prefill=False,
|
||||
decode_graph_eligible=True,
|
||||
)
|
||||
assert uniform_tok_count == max_query_len
|
||||
|
||||
@@ -401,7 +401,7 @@ def test_dynamic_sd_only_captures_scheduled_query_lengths(monkeypatch):
|
||||
num_reqs,
|
||||
num_tokens,
|
||||
max_query_len,
|
||||
has_prefill=False,
|
||||
decode_graph_eligible=True,
|
||||
)
|
||||
assert uniform_tok_count == max_query_len
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import math
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
@@ -10,6 +11,10 @@ from vllm.v1.watermarking import GumbelWatermarker
|
||||
from vllm.v1.watermarking.spec_decode import watermarked_rejection_sample
|
||||
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
|
||||
from vllm.v1.worker.gpu.sample.watermark import philox_gumbel_sample
|
||||
from vllm.v1.worker.gpu.spec_decode.rejection_sampler import (
|
||||
RejectionSampler,
|
||||
gather_draft_sampled,
|
||||
)
|
||||
from vllm.v1.worker.gpu.spec_decode.rejection_sampler_utils import (
|
||||
rejection_sample,
|
||||
)
|
||||
@@ -669,6 +674,81 @@ def test_placeholder_blocks_later_draft_tokens(use_block_verification: bool):
|
||||
)
|
||||
|
||||
|
||||
def test_verify_rejects_unproposed_drafts():
|
||||
"""Zero drafts padded onto a step starting in the prefill must be rejected."""
|
||||
torch.manual_seed(0)
|
||||
device = "cuda"
|
||||
num_trials = 256
|
||||
K = 8
|
||||
|
||||
# Row 0: token 0 is very unlikely. Rows >= 1 follow the zero inputs and
|
||||
# predict token 0. The never-written draft logits row is uniform.
|
||||
target_logits_1d = torch.randn(VOCAB_SIZE, device=device)
|
||||
target_logits_1d[0] = -20.0
|
||||
inputs = _build_rejection_sample_inputs(
|
||||
target_logits_1d,
|
||||
torch.zeros(VOCAB_SIZE, device=device),
|
||||
K,
|
||||
temperature=1.0,
|
||||
num_trials=num_trials,
|
||||
)
|
||||
target_rest = torch.randn(VOCAB_SIZE, device=device)
|
||||
target_rest[0] = 20.0
|
||||
inputs["target_logits"].view(num_trials, K + 1, VOCAB_SIZE)[:, 1:] = target_rest
|
||||
inputs["draft_sampled"].view(num_trials, K + 1)[:, 1:] = 0
|
||||
|
||||
# Each request's first logit is the last prefill token, as in the first
|
||||
# decode step after a P/D remote KV load.
|
||||
first_pos = inputs["pos"].view(num_trials, K + 1)[:, 0]
|
||||
prefill_len = first_pos + 1
|
||||
rejection_sampler = object.__new__(RejectionSampler)
|
||||
rejection_sampler.sampler = SimpleNamespace(
|
||||
apply_sampling_params=lambda logits, *args: logits,
|
||||
sampling_states=SimpleNamespace(
|
||||
temperature=SimpleNamespace(gpu=inputs["temperature"]),
|
||||
seeds=SimpleNamespace(gpu=inputs["seed"]),
|
||||
),
|
||||
use_fp64_gumbel=False,
|
||||
)
|
||||
rejection_sampler.num_speculative_steps = K
|
||||
rejection_sampler.synthetic_conditional_rates = None
|
||||
rejection_sampler.use_block_verification = True
|
||||
rejection_sampler.watermark_key = None
|
||||
|
||||
def verify() -> tuple[torch.Tensor, torch.Tensor]:
|
||||
draft_sampled, pos = gather_draft_sampled(
|
||||
inputs["draft_sampled"],
|
||||
inputs["pos"],
|
||||
torch.arange(num_trials * (K + 1), device=device),
|
||||
inputs["expanded_idx_mapping"],
|
||||
inputs["expanded_local_pos"],
|
||||
prefill_len,
|
||||
)
|
||||
_, sampled, num_sampled = rejection_sampler._verify(
|
||||
inputs["target_logits"],
|
||||
inputs["draft_logits"],
|
||||
draft_sampled,
|
||||
pos,
|
||||
inputs["cu_num_logits"],
|
||||
inputs["idx_mapping"],
|
||||
None,
|
||||
inputs["expanded_idx_mapping"],
|
||||
inputs["expanded_local_pos"],
|
||||
None,
|
||||
)
|
||||
return sampled, num_sampled
|
||||
|
||||
sampled, num_sampled = verify()
|
||||
assert (num_sampled == 1).all()
|
||||
# Resampled from the target at row 0, not from a residual.
|
||||
assert (sampled[:, 0] != 0).all()
|
||||
|
||||
# Once past the prefill, block verification accepts the same zero drafts.
|
||||
prefill_len.copy_(first_pos)
|
||||
_, num_sampled = verify()
|
||||
assert (num_sampled == K + 1).all()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"num_speculative_steps,temperature",
|
||||
[
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
import unittest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.config import DeviceConfig, VllmConfig
|
||||
@@ -20,7 +21,7 @@ from vllm.v1.kv_cache_interface import (
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
)
|
||||
from vllm.v1.outputs import ModelRunnerOutput
|
||||
from vllm.v1.outputs import LogprobsLists, ModelRunnerOutput
|
||||
from vllm.v1.request import Request, RequestStatus, StreamingUpdate
|
||||
from vllm.v1.structured_output import StructuredOutputManager
|
||||
|
||||
@@ -84,6 +85,61 @@ def create_scheduler() -> Scheduler:
|
||||
|
||||
|
||||
class TestStreamingScheduler(unittest.TestCase):
|
||||
def test_chunk_logprobs_do_not_depend_on_continuation_arrival(self):
|
||||
"""A queued continuation must not change the finishing chunk's logprobs."""
|
||||
for continuation_queued in (False, True):
|
||||
with self.subTest(continuation_queued=continuation_queued):
|
||||
scheduler = create_scheduler()
|
||||
session = DummyRequest("session", prompt_token_ids=[1, 2, 3])
|
||||
session.sampling_params = SamplingParams(
|
||||
stop_token_ids=[STOP_TOKEN], max_tokens=16, logprobs=0
|
||||
)
|
||||
scheduler.add_request(session)
|
||||
scheduled = scheduler.schedule()
|
||||
|
||||
continuation = DummyRequest("session", prompt_token_ids=[4, 5])
|
||||
assert continuation.sampling_params.logprobs is None
|
||||
if continuation_queued:
|
||||
scheduler.add_request(continuation)
|
||||
|
||||
logprobs = LogprobsLists(
|
||||
logprob_token_ids=np.array([[STOP_TOKEN]], dtype=np.int32),
|
||||
logprobs=np.array([[-0.25]], dtype=np.float32),
|
||||
sampled_token_ranks=np.array([1], dtype=np.int32),
|
||||
)
|
||||
runner_output = ModelRunnerOutput(
|
||||
req_ids=[session.request_id],
|
||||
req_id_to_index={session.request_id: 0},
|
||||
sampled_token_ids=[[STOP_TOKEN]],
|
||||
logprobs=logprobs,
|
||||
prompt_logprobs_dict={},
|
||||
pooler_output=[],
|
||||
)
|
||||
outputs = scheduler.update_from_output(scheduled, runner_output)
|
||||
[output] = outputs[session.client_index].outputs
|
||||
|
||||
if not continuation_queued:
|
||||
assert session.status == RequestStatus.WAITING_FOR_STREAMING_REQ
|
||||
scheduler.add_request(continuation)
|
||||
assert session.status == RequestStatus.WAITING
|
||||
assert session.sampling_params is continuation.sampling_params
|
||||
assert output.new_token_ids == [STOP_TOKEN]
|
||||
assert output.finish_reason == FinishReason.STOP
|
||||
assert output.new_logprobs is not None, (
|
||||
"The finishing chunk requested logprobs; the continuation's "
|
||||
"settings must not suppress them"
|
||||
)
|
||||
np.testing.assert_array_equal(
|
||||
output.new_logprobs.logprob_token_ids, logprobs.logprob_token_ids
|
||||
)
|
||||
np.testing.assert_array_equal(
|
||||
output.new_logprobs.logprobs, logprobs.logprobs
|
||||
)
|
||||
np.testing.assert_array_equal(
|
||||
output.new_logprobs.sampled_token_ranks,
|
||||
logprobs.sampled_token_ranks,
|
||||
)
|
||||
|
||||
def test_add_request(self):
|
||||
scheduler = create_scheduler()
|
||||
|
||||
@@ -115,8 +171,7 @@ class TestStreamingScheduler(unittest.TestCase):
|
||||
prompt_token_ids=[1, 2, 3],
|
||||
)
|
||||
session.num_computed_tokens = len(session.prompt_token_ids)
|
||||
session.max_tokens = 10 # Initial max_tokens
|
||||
session._output_token_ids = [1] * 10 # reach max_tokens
|
||||
session.max_tokens = 2
|
||||
|
||||
new_request = DummyRequest(
|
||||
request_id="session",
|
||||
@@ -129,26 +184,21 @@ class TestStreamingScheduler(unittest.TestCase):
|
||||
scheduler._update_request_as_session(session, update)
|
||||
|
||||
assert session.sampling_params.max_tokens == 10
|
||||
# _update_request_as_session clears output tokens first, so
|
||||
# max_tokens = num_output_tokens (0) + update.max_tokens (10) = 10
|
||||
assert session.max_tokens == 10
|
||||
|
||||
session.num_computed_tokens = len(session.prompt_token_ids)
|
||||
|
||||
# Simulate generating 5 more output tokens
|
||||
session._output_token_ids = [1] * 5
|
||||
new_request2 = DummyRequest(
|
||||
request_id="session",
|
||||
prompt_token_ids=[7, 8, 9],
|
||||
)
|
||||
new_request2.sampling_params = SamplingParams(max_tokens=10)
|
||||
new_request2.max_tokens = 10
|
||||
new_request2.sampling_params = SamplingParams(max_tokens=4)
|
||||
new_request2.max_tokens = 4
|
||||
update2 = StreamingUpdate.from_request(new_request2)
|
||||
scheduler._update_request_as_session(session, update2)
|
||||
|
||||
assert session.sampling_params.max_tokens == 10
|
||||
# Again, output tokens are cleared first, so max_tokens = 0 + 10 = 10
|
||||
assert session.max_tokens == 10
|
||||
assert session.sampling_params.max_tokens == 4
|
||||
assert session.max_tokens == 4
|
||||
|
||||
def test_update_request_as_session(self):
|
||||
scheduler = create_scheduler()
|
||||
@@ -498,9 +548,9 @@ class TestStreamingScheduler(unittest.TestCase):
|
||||
eco_cycle2 = eco_dict_cycle2[session.client_index].outputs[0]
|
||||
assert eco_cycle2.finish_reason == FinishReason.STOP
|
||||
assert session.status == RequestStatus.WAITING_FOR_STREAMING_REQ
|
||||
# Sessions paused for streaming input are blocked-waiting, so they
|
||||
# live in the skipped_waiting queue rather than the main waiting queue.
|
||||
assert session in scheduler.skipped_waiting
|
||||
# Sessions paused for streaming input keep their KV blocks, so they
|
||||
# live in the kv_holding_waiting queue.
|
||||
assert session in scheduler.kv_holding_waiting
|
||||
assert session._all_token_ids == [1, 2, 3, 10, STOP_TOKEN]
|
||||
|
||||
# CRITICAL ASSERTION: Cached prompt_token_ids STILL must not have changed
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import xgrammar as xgr
|
||||
|
||||
from vllm.config import StructuredOutputsConfig, VllmConfig
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
ChatCompletionToolsParam,
|
||||
)
|
||||
from vllm.parser.plamo3 import (
|
||||
BEGIN_TOOL_ARGUMENTS,
|
||||
BEGIN_TOOL_NAME,
|
||||
BEGIN_TOOL_REQUEST,
|
||||
BEGIN_TOOL_REQUESTS,
|
||||
END_TOOL_ARGUMENTS,
|
||||
END_TOOL_NAME,
|
||||
END_TOOL_REQUEST,
|
||||
END_TOOL_REQUESTS,
|
||||
)
|
||||
from vllm.tool_parsers.structural_tag_registry import get_model_structural_tag
|
||||
from vllm.v1.structured_output.backend_types import StructuredOutputOptions
|
||||
from vllm.v1.structured_output.backend_xgrammar import XgrammarBackend
|
||||
|
||||
|
||||
class Plamo3Tokenizer:
|
||||
"""Minimal stand-in for PLaMo's remote-code PythonBackend tokenizer."""
|
||||
|
||||
eos_token_id = 0
|
||||
|
||||
def __init__(self, tokens: list[str]) -> None:
|
||||
self._vocab = {token: token_id for token_id, token in enumerate(tokens)}
|
||||
|
||||
def get_vocab(self) -> dict[str, int]:
|
||||
return self._vocab
|
||||
|
||||
def init_xgrammar(self):
|
||||
stop_token_ids = [self.eos_token_id]
|
||||
tokenizer_info = xgr.TokenizerInfo(
|
||||
encoded_vocab=list(self._vocab),
|
||||
vocab_type=xgr.VocabType.BYTE_FALLBACK,
|
||||
vocab_size=len(self._vocab),
|
||||
stop_token_ids=stop_token_ids,
|
||||
)
|
||||
return tokenizer_info, stop_token_ids
|
||||
|
||||
|
||||
def make_vllm_config() -> VllmConfig:
|
||||
config = VllmConfig(
|
||||
structured_outputs_config=StructuredOutputsConfig(backend="xgrammar"),
|
||||
)
|
||||
config.model_config = SimpleNamespace(
|
||||
hf_config=SimpleNamespace(model_type="plamo3")
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
def test_plamo3_python_tokenizer_compiles_and_accepts_structural_tag():
|
||||
call_tokens = [
|
||||
BEGIN_TOOL_REQUESTS,
|
||||
BEGIN_TOOL_REQUEST,
|
||||
BEGIN_TOOL_NAME,
|
||||
"get_weather",
|
||||
END_TOOL_NAME,
|
||||
BEGIN_TOOL_ARGUMENTS,
|
||||
'{"city":"Tokyo"}',
|
||||
END_TOOL_ARGUMENTS,
|
||||
END_TOOL_REQUEST,
|
||||
END_TOOL_REQUESTS,
|
||||
]
|
||||
tokenizer = Plamo3Tokenizer(["<eos>", *call_tokens])
|
||||
backend = XgrammarBackend(
|
||||
make_vllm_config(),
|
||||
tokenizer=tokenizer,
|
||||
vocab_size=len(tokenizer.get_vocab()),
|
||||
)
|
||||
tools = [
|
||||
ChatCompletionToolsParam(
|
||||
type="function",
|
||||
function={
|
||||
"name": "get_weather",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"city": {"type": "string"}},
|
||||
"required": ["city"],
|
||||
},
|
||||
"strict": True,
|
||||
},
|
||||
)
|
||||
]
|
||||
tag = get_model_structural_tag("plamo3", tools, "required", reasoning=False)
|
||||
assert tag is not None
|
||||
|
||||
grammar = backend.compile_grammar(
|
||||
StructuredOutputOptions.STRUCTURAL_TAG,
|
||||
tag.model_dump_json(),
|
||||
)
|
||||
token_ids = [tokenizer.get_vocab()[token] for token in call_tokens]
|
||||
assert grammar.accept_tokens("plamo3", token_ids)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ['"', "あ"])
|
||||
def test_plamo3_grammar_matches_decoded_bytes(value):
|
||||
pieces = [f"<0x{byte:02X}>" for byte in value.encode("utf-8")]
|
||||
tokenizer = Plamo3Tokenizer(list(dict.fromkeys(["<eos>", value, *pieces])))
|
||||
backend = XgrammarBackend(
|
||||
make_vllm_config(),
|
||||
tokenizer=tokenizer,
|
||||
vocab_size=len(tokenizer.get_vocab()),
|
||||
)
|
||||
for tokens in ([value], pieces):
|
||||
grammar = backend.compile_grammar(StructuredOutputOptions.REGEX, value)
|
||||
assert grammar.accept_tokens(
|
||||
"plamo3", [tokenizer.get_vocab()[token] for token in tokens]
|
||||
)
|
||||
@@ -77,6 +77,7 @@ def test_get_kv_cache_spec_resolves_hisparse_block_size(
|
||||
layers = {}
|
||||
for name, sizes in zip(specs, [main_sizes, indexer_sizes, [block_size]]):
|
||||
backend = SimpleNamespace(
|
||||
get_name=lambda name=name: name,
|
||||
customize_spec=AttentionBackend.customize_spec,
|
||||
get_supported_kernel_block_sizes=lambda sizes=sizes: sizes,
|
||||
)
|
||||
|
||||
@@ -56,6 +56,7 @@ def _make_runner(
|
||||
runner: Any = GPUModelRunner.__new__(GPUModelRunner)
|
||||
runner.decode_query_len = decode_query_len
|
||||
runner.adaptive_verification = None
|
||||
runner.pcp_manager = None
|
||||
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).
|
||||
@@ -128,6 +129,65 @@ def test_prompt_chunk_of_decode_query_len_is_not_uniform_decode():
|
||||
assert _uniform_token_count({"p0": (0, 8)}, 8) is None
|
||||
|
||||
|
||||
def test_one_new_prompt_token_over_context_runs_as_decode():
|
||||
# A prompt tail padded with placeholder drafts and a one-token mid-prompt
|
||||
# chunk both compute like decodes. A fresh one-token prompt and a real
|
||||
# multi-token chunk don't.
|
||||
batch = {"d0": (16, 16), "tail": (128, 129), "mid": (64, 129)}
|
||||
batch.update({"fresh": (0, 1), "chunk": (120, 129)})
|
||||
runner = _make_runner(batch, decode_query_len=4)
|
||||
scheduler_output = SimpleNamespace(
|
||||
num_scheduled_tokens={"d0": 4, "tail": 4, "mid": 1, "fresh": 1, "chunk": 4},
|
||||
total_num_scheduled_tokens=14,
|
||||
scheduled_spec_decode_tokens={"d0": [1, 2, 3], "tail": [-1] * 3},
|
||||
)
|
||||
state, _ = runner.gather_batch_req_state(scheduler_output, False)
|
||||
assert state is not None
|
||||
runs_as_decode = dict(zip(state.req_ids, state.prefill_runs_as_decode_np))
|
||||
assert runs_as_decode == {
|
||||
"d0": False,
|
||||
"tail": True,
|
||||
"mid": True,
|
||||
"fresh": False,
|
||||
"chunk": False,
|
||||
}
|
||||
|
||||
|
||||
def test_one_token_prompt_tail_with_prior_context_is_uniform_decode():
|
||||
# Replaying the last prompt token over existing context (full prefix-cache
|
||||
# hit or P/D KV import) computes exactly like a decode.
|
||||
batch = {"d0": (16, 16), "d1": (16, 16), "p0": (128, 129)}
|
||||
assert _uniform_token_count(batch, 1) == 1
|
||||
|
||||
# A fresh 1-token prompt alongside it has no prior state.
|
||||
batch["p1"] = (0, 1)
|
||||
assert _uniform_token_count(batch, 1) is None
|
||||
|
||||
# Only one-token tails qualify, not K+1 chunks with prior context.
|
||||
assert _uniform_token_count({"d0": (16, 16), "p0": (120, 129)}, 8) is None
|
||||
|
||||
|
||||
def test_padded_prompt_tail_with_prior_context_is_uniform_decode():
|
||||
# The scheduler pads a one-token prompt tail with K placeholder drafts to
|
||||
# keep the K+1 spec-decode shape; it verifies like any other decode.
|
||||
batch = {"d0": (16, 16), "d1": (16, 16), "p0": (128, 129)}
|
||||
runner = _make_runner(batch, decode_query_len=4)
|
||||
scheduler_output = SimpleNamespace(
|
||||
num_scheduled_tokens={req_id: 4 for req_id in batch},
|
||||
total_num_scheduled_tokens=12,
|
||||
scheduled_spec_decode_tokens={req_id: [-1] * 3 for req_id in batch},
|
||||
)
|
||||
state, uniform_tok_count = runner.gather_batch_req_state(scheduler_output, False)
|
||||
assert state.has_prefill and state.decode_graph_eligible
|
||||
assert uniform_tok_count == 4
|
||||
|
||||
# Without the placeholder drafts, it is a real 4-token prompt chunk.
|
||||
del scheduler_output.scheduled_spec_decode_tokens["p0"]
|
||||
state, uniform_tok_count = runner.gather_batch_req_state(scheduler_output, False)
|
||||
assert not state.decode_graph_eligible
|
||||
assert uniform_tok_count is None
|
||||
|
||||
|
||||
def test_dummy_batches_stay_uniform_decode():
|
||||
# Dummy batches have no request state to consult and must stay classified
|
||||
# by shape alone; rejecting them would make capture and replay disagree.
|
||||
@@ -185,6 +245,7 @@ def test_uniform_decode_uses_state_index_not_batch_position():
|
||||
runner: Any = GPUModelRunner.__new__(GPUModelRunner)
|
||||
runner.decode_query_len = 8
|
||||
runner.adaptive_verification = None
|
||||
runner.pcp_manager = None
|
||||
# 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},
|
||||
@@ -214,11 +275,11 @@ def test_uniform_decode_uses_state_index_not_batch_position():
|
||||
|
||||
|
||||
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
|
||||
# Shape and decode-graph eligibility must both pass.
|
||||
assert get_uniform_decode_token_count(2, 16, 8, True) == 8
|
||||
assert get_uniform_decode_token_count(2, 16, 8, False) is None
|
||||
# 12 tokens over 2 requests is no shared query length.
|
||||
assert get_uniform_decode_token_count(2, 12, 8, False) is None
|
||||
assert get_uniform_decode_token_count(2, 12, 8, True) is None
|
||||
|
||||
|
||||
def test_no_speculator_dispatches_on_query_length_alone():
|
||||
|
||||
@@ -96,6 +96,7 @@ def _make_batch(
|
||||
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,
|
||||
decode_graph_eligible=True,
|
||||
input_ids=torch.zeros(num_tokens, dtype=torch.int32, device=DEVICE),
|
||||
positions=torch.arange(num_tokens, dtype=torch.int64, device=DEVICE),
|
||||
is_padding=torch.zeros(num_tokens, dtype=torch.bool, device=DEVICE),
|
||||
|
||||
@@ -298,6 +298,10 @@ def _make_mock_backend_for_kernel_block_size(
|
||||
supported_sizes: list[int | MultipleOf],
|
||||
):
|
||||
class _MockBackend:
|
||||
@staticmethod
|
||||
def get_name():
|
||||
return "MOCK"
|
||||
|
||||
@staticmethod
|
||||
def get_supported_kernel_block_sizes():
|
||||
return supported_sizes
|
||||
|
||||
@@ -7,6 +7,7 @@ from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import CompilationConfig, CompilationMode
|
||||
from vllm.model_executor.warmup.jit_warmup import JitWarmupRegistry
|
||||
from vllm.v1.outputs import EMPTY_MODEL_RUNNER_OUTPUT
|
||||
from vllm.v1.worker.gpu import eplb_utils as eplb
|
||||
@@ -24,7 +25,6 @@ class FakeMemoryProfiler:
|
||||
|
||||
class FakeEplbState:
|
||||
instances: list["FakeEplbState"] = []
|
||||
from_mapping_kwargs: dict[str, Any] | None = None
|
||||
|
||||
def __init__(self, parallel_config: Any, device: torch.device):
|
||||
self.parallel_config = parallel_config
|
||||
@@ -33,7 +33,7 @@ class FakeEplbState:
|
||||
self.step_calls: list[tuple[bool, bool, bool]] = []
|
||||
self.async_started = False
|
||||
self.is_async = True
|
||||
self.built_from_mapping = False
|
||||
self.update_mapping_calls: list[tuple[Any, torch.Tensor]] = []
|
||||
FakeEplbState.instances.append(self)
|
||||
|
||||
def add_model(self, model: Any, model_config: Any) -> None:
|
||||
@@ -45,12 +45,8 @@ class FakeEplbState:
|
||||
def start_async_loop(self) -> None:
|
||||
self.async_started = True
|
||||
|
||||
@classmethod
|
||||
def from_mapping(cls, **kwargs: Any) -> "FakeEplbState":
|
||||
cls.from_mapping_kwargs = kwargs
|
||||
state = cls(kwargs["parallel_config"], kwargs["device"])
|
||||
state.built_from_mapping = True
|
||||
return state
|
||||
def update_mapping(self, model_config: Any, mapping: torch.Tensor) -> None:
|
||||
self.update_mapping_calls.append((model_config, mapping))
|
||||
|
||||
|
||||
def _make_runner(**overrides: Any) -> Any:
|
||||
@@ -73,7 +69,9 @@ def _make_runner(**overrides: Any) -> Any:
|
||||
enable_batch_sharded_sampling=False,
|
||||
eplb_config=SimpleNamespace(log_balancedness=True),
|
||||
)
|
||||
runner.compilation_config = CompilationConfig(mode=CompilationMode.NONE)
|
||||
runner.vllm_config = SimpleNamespace(
|
||||
compilation_config=runner.compilation_config,
|
||||
load_config=runner.load_config,
|
||||
model_config=runner.model_config,
|
||||
)
|
||||
@@ -136,7 +134,7 @@ def test_v2_load_model_registers_moe_with_eplb(monkeypatch):
|
||||
assert runner.eplb_state.async_started is True
|
||||
|
||||
|
||||
def test_v2_load_model_with_dummy_weights_skips_eplb_registration(monkeypatch):
|
||||
def test_v2_load_model_with_dummy_weights_defers_eplb_async_loop(monkeypatch):
|
||||
FakeEplbState.instances.clear()
|
||||
model = SimpleNamespace(is_moe=True)
|
||||
|
||||
@@ -159,24 +157,20 @@ def test_v2_load_model_with_dummy_weights_skips_eplb_registration(monkeypatch):
|
||||
|
||||
assert runner.load_config.load_format == "dummy"
|
||||
assert runner.eplb_state is not None
|
||||
assert runner.eplb_state.add_model_calls == []
|
||||
# A scaling-up worker registers so it can join the EPLB communicator.
|
||||
assert runner.eplb_state.add_model_calls == [(model, runner.model_config)]
|
||||
assert runner.eplb_state.async_started is False
|
||||
|
||||
|
||||
def test_v2_setup_eplb_from_mapping_rebuilds_state(monkeypatch):
|
||||
FakeEplbState.instances.clear()
|
||||
FakeEplbState.from_mapping_kwargs = None
|
||||
monkeypatch.setattr(eplb, "EplbState", FakeEplbState)
|
||||
monkeypatch.setattr(eplb, "get_mixture_of_experts_model", lambda model: model)
|
||||
|
||||
runner = _make_runner(model=SimpleNamespace(is_moe=True))
|
||||
def test_v2_setup_eplb_from_mapping_updates_state_in_place():
|
||||
runner = _make_runner()
|
||||
state = FakeEplbState(runner.parallel_config, runner.device)
|
||||
runner.eplb_state = state
|
||||
mapping = torch.tensor([[0, 1, 2, 3]], dtype=torch.int64)
|
||||
mrv2.GPUModelRunner.setup_eplb_from_mapping(runner, mapping)
|
||||
|
||||
assert runner.eplb_state is not None
|
||||
assert runner.eplb_state.built_from_mapping is True
|
||||
assert FakeEplbState.from_mapping_kwargs is not None
|
||||
assert FakeEplbState.from_mapping_kwargs["expanded_physical_to_logical"] is mapping
|
||||
assert runner.eplb_state is state
|
||||
assert state.update_mapping_calls == [(runner.model_config, mapping)]
|
||||
|
||||
|
||||
def test_v2_sample_tokens_runs_eplb_on_non_last_pp_rank(monkeypatch):
|
||||
|
||||
@@ -45,6 +45,7 @@ def test_prepare_attn_forwards_positions(monkeypatch: pytest.MonkeyPatch) -> Non
|
||||
seq_lens_cpu_upper_bound=torch.tensor([1537], dtype=torch.int32),
|
||||
seq_lens=torch.tensor([1537], dtype=torch.int32),
|
||||
is_prefilling_np=torch.tensor([False]).numpy(),
|
||||
prefill_runs_as_decode_np=None,
|
||||
dcp_local_seq_lens=None,
|
||||
positions=positions,
|
||||
prompt_lens=torch.tensor([1024], dtype=torch.int32),
|
||||
@@ -102,8 +103,7 @@ def test_padded_prompt_tail_builds_as_spec_decode(
|
||||
seq_lens_cpu_upper_bound=torch.tensor(seq_lens, dtype=torch.int32),
|
||||
seq_lens=torch.tensor(seq_lens, dtype=torch.int32),
|
||||
is_prefilling_np=np.array(is_prefilling),
|
||||
prefill_len_np=np.array([40, 129, 100], dtype=np.int32),
|
||||
num_computed_prefill_tokens_np=np.array([40, 128, 0], dtype=np.int32),
|
||||
prefill_runs_as_decode_np=np.array([False, True, False]),
|
||||
dcp_local_seq_lens=None,
|
||||
positions=torch.zeros(12, dtype=torch.int64),
|
||||
prompt_lens=None,
|
||||
@@ -121,11 +121,12 @@ def test_padded_prompt_tail_builds_as_spec_decode(
|
||||
mamba_metadata = build_attn_metadata.call_args.kwargs[
|
||||
"model_specific_attn_metadata"
|
||||
]
|
||||
assert mamba_metadata.is_prefilling.tolist() == [False, False, True]
|
||||
|
||||
builder = _create_gdn_builder(num_speculative_tokens=k)
|
||||
common = create_common_attn_metadata(
|
||||
BatchSpec(seq_lens=seq_lens, query_lens=query_lens), BLOCK_SIZE, DEVICE
|
||||
).replace(is_prefilling=torch.tensor(is_prefilling))
|
||||
).replace(**mamba_metadata.get_extra_common_attn_kwargs(0, 3))
|
||||
meta = builder.build(
|
||||
common_prefix_len=0,
|
||||
common_attn_metadata=common,
|
||||
|
||||
Reference in New Issue
Block a user