[Mini-vLLM] SM86-only cut: models, backends, Rust, tests

- Keep only Qwen3.5, Qwen3.5-MTP and Qwen4Exp model paths; trim the model registry to 41 entries
- Delete idle attention backends (MLA, FlashInfer, ROCm-only, quant backends) and dead GDN CuTeDSL kernels
- Remove inc/quark quant loaders; keep compressed-tensors and Marlin
- Drop the Rust frontend, pooling entrypoints, and idle test suites
- Rebuild kernels for sm_80;sm_86 and strip the extensions
- Verified: full import sweep clean (optional deps only) and a dummy-load Qwen3.5 engine run on RTX 3090 via the Triton GDN path

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-18 19:19:56 +07:00
co-authored by Hinata
parent c5ab42bc0f
commit e61dcb9143
2728 changed files with 159 additions and 950401 deletions
-884
View File
@@ -1,884 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Padded-page handling in create_kv_cache_views.
Guards that a page_size_padded spec strides the block dimension by the padded page
while keeping per-block content compact, so padding bytes at the end of each page are
never addressed by the logical view.
"""
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock
import numpy as np
import pytest
import torch
import vllm.v1.hisparse.binding as attn_utils_module
import vllm.v1.hisparse.runtime as hisparse_runtime_module
from tests.v1.attention.utils import (
BatchSpec,
create_common_attn_metadata,
dense_kv_cache_views,
)
from vllm.config.compilation import CompilationConfig, CUDAGraphMode
from vllm.v1.attention.backend import AttentionBackend, AttentionCGSupport, MultipleOf
from vllm.v1.core.kv_cache_utils import KVCacheBlockCopy
from vllm.v1.hisparse.binding import allocate_hisparse_kv_caches
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
HiSparseResidentSpec,
KVCacheConfig,
KVCacheGroupSpec,
KVCacheLayout,
KVCacheTensor,
MLAAttentionSpec,
SparseCacheRole,
compute_layout_strides,
)
from vllm.v1.worker.gpu import attn_utils
from vllm.v1.worker.gpu.attn_utils import (
FastPrefillHelper,
get_attn_cg_support,
get_query_lens_mismatch_unsupported_backend,
)
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
from vllm.v1.worker.utils import (
AttentionGroup,
allocate_kv_cache,
copy_kv_cache_blocks_inplace,
customize_attention_spec,
map_kv_caches_to_kernel_blocks,
)
@pytest.mark.parametrize(
("enabled", "block_size", "main_sizes", "indexer_sizes", "expected"),
[
(True, 256, [64], [64], 64),
(True, 64, [32, 64], [16, 32], 32),
(True, 64, [MultipleOf(16)], [32], 32),
(True, 64, [64], [32], None),
(False, 256, [64], [64], 256),
],
)
def test_get_kv_cache_spec_resolves_hisparse_block_size(
monkeypatch, enabled, block_size, main_sizes, indexer_sizes, expected
):
"""Resolve shared MLA geometry before planning; leave other specs alone."""
specs = {
"main": MLAAttentionSpec(
block_size=block_size, num_kv_heads=1, head_size=576, dtype=torch.bfloat16
),
"indexer": MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
cache_role=SparseCacheRole.INDEXER,
),
"dense": FullAttentionSpec(
block_size=block_size, num_kv_heads=1, head_size=128, dtype=torch.bfloat16
),
}
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 _=None, sizes=sizes: sizes,
)
layers[name] = SimpleNamespace(
get_kv_cache_spec=lambda _, spec=specs[name]: spec,
get_attn_backend=lambda backend=backend: backend,
is_draft_layer=False,
)
monkeypatch.setattr(attn_utils, "get_layers_from_vllm_config", lambda *_: layers)
monkeypatch.setattr(
attn_utils_module, "get_hisparse_kv_cache_groups", lambda *_: []
)
config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=object() if enabled else None)
)
if expected is None:
with pytest.raises(ValueError, match="supported by every sparse"):
attn_utils.get_kv_cache_spec(config)
return
resolved = attn_utils.get_kv_cache_spec(config)
assert resolved["main"].block_size == resolved["indexer"].block_size == expected
dense_backend = layers["dense"].get_attn_backend()
assert resolved["dense"] == customize_attention_spec(dense_backend, specs["dense"])
assert all(spec.block_size == block_size for spec in specs.values())
def test_get_kv_cache_spec_tags_draft_layers(monkeypatch):
spec = FullAttentionSpec(
block_size=16, num_kv_heads=1, head_size=128, dtype=torch.bfloat16
)
backend = SimpleNamespace(
customize_spec=AttentionBackend.customize_spec,
get_supported_kernel_block_sizes=lambda _=None: [16],
)
layers = {
name: SimpleNamespace(
get_kv_cache_spec=lambda _: spec,
get_attn_backend=lambda: backend,
is_draft_layer=name == "draft",
)
for name in ("target", "draft")
}
monkeypatch.setattr(attn_utils, "get_layers_from_vllm_config", lambda *_: layers)
config = SimpleNamespace(attention_config=SimpleNamespace(hisparse_config=None))
specs = attn_utils.get_kv_cache_spec(config)
assert specs["draft"].is_draft and not specs["target"].is_draft
class _FakeMetadataBuilder:
def __init__(self, support: AttentionCGSupport, varlen_bound: int | None = None):
self.support = support
self.varlen_bound = varlen_bound
def get_cudagraph_support(self, *_args):
return self.support
def get_varlen_cudagraph_max_query_len(self, *_args):
return self.varlen_bound
class _TargetBackend:
@classmethod
def supports_device_cpu_query_lens_mismatch(cls) -> bool:
return True
class _DraftBackend:
@classmethod
def supports_device_cpu_query_lens_mismatch(cls) -> bool:
return False
def test_attention_checks_preserve_global_and_target_scoped_support():
spec = FullAttentionSpec(
block_size=16,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
)
target_group = AttentionGroup(
_TargetBackend,
["target"],
spec,
0,
)
target_group.metadata_builders = [
_FakeMetadataBuilder(AttentionCGSupport.ALWAYS) # type: ignore[list-item]
]
draft_group = AttentionGroup(
_DraftBackend,
["draft"],
spec,
0,
)
draft_group.metadata_builders = [
_FakeMetadataBuilder(AttentionCGSupport.UNIFORM_BATCH) # type: ignore[list-item]
]
groups = [[target_group, draft_group]]
# The runner-wide execution mode must still honor the drafter's limit.
unfiltered = get_attn_cg_support(groups, None)
assert unfiltered.min_cg_support == AttentionCGSupport.UNIFORM_BATCH
assert unfiltered.min_cg_attn_backend == "_DraftBackend"
# Adaptive verification validates only the target's varlen graphs.
target_only = get_attn_cg_support(
groups,
None,
checked_layer_names={"target"},
)
assert target_only.min_cg_support == AttentionCGSupport.ALWAYS
assert target_only.min_cg_attn_backend is None
assert (
get_query_lens_mismatch_unsupported_backend(
groups,
checked_layer_names={"target"},
)
is None
)
# Shared target/draft groups still participate in target-scoped checks.
draft_group.layer_names.append("target")
target_with_shared_group = get_attn_cg_support(
groups,
None,
checked_layer_names={"target"},
)
assert target_with_shared_group.min_cg_support == AttentionCGSupport.UNIFORM_BATCH
assert (
get_query_lens_mismatch_unsupported_backend(
groups,
checked_layer_names={"target"},
)
== "_DraftBackend"
)
def test_varlen_cudagraph_unsupported_backend_checks_scoped_bounds():
"""ALWAYS passes without a bound, other builders need one at least as wide as
the requested length, and NEVER fails whatever bound a builder reports."""
config: Any = SimpleNamespace()
spec = FullAttentionSpec(
block_size=16,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
)
def group(
backend: Any,
layer_name: str,
support: AttentionCGSupport,
bound: int | None = None,
):
builder: Any = _FakeMetadataBuilder(support, bound)
attn_group = AttentionGroup(backend, [layer_name], spec, 0)
attn_group.metadata_builders = [builder]
return attn_group
target = group(_TargetBackend, "target", AttentionCGSupport.ALWAYS)
draft = group(_DraftBackend, "draft", AttentionCGSupport.UNIFORM_BATCH, 8)
never = group(_DraftBackend, "never", AttentionCGSupport.NEVER, 8)
unsupported = attn_utils.get_varlen_cudagraph_unsupported_backend
assert unsupported([[target, draft]], config, 8) is None
assert unsupported([[target, draft]], config, 9) == ("_DraftBackend", 8)
assert (
unsupported([[target, draft]], config, 9, checked_layer_names={"target"})
is None
)
assert unsupported([[target, never]], config, 1) == ("_DraftBackend", None)
@pytest.mark.parametrize("num_speculative_tokens", [0, 7])
def test_flashinfer_sparse_full_graphs_exclude_prefill_keep_varlen_decode(
num_speculative_tokens,
):
"""Prefill must fall back without disabling adaptive verification graphs."""
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseTRTLLMBackend,
)
backend = FlashInferMLASparseTRTLLMBackend
config: Any = SimpleNamespace(
speculative_config=SimpleNamespace(
num_speculative_tokens=num_speculative_tokens, parallel_drafting=False
),
use_v2_model_runner=True,
)
spec = MLAAttentionSpec(
block_size=64, num_kv_heads=1, head_size=576, dtype=torch.bfloat16
)
group = AttentionGroup(backend, ["target"], spec, 0)
group.metadata_builders = [object.__new__(backend.get_builder_cls())]
groups = [[group]]
support = get_attn_cg_support(groups, config)
compilation = CompilationConfig(cudagraph_mode=CUDAGraphMode.FULL)
mode = compilation.resolve_cudagraph_mode_and_sizes(
support.min_cg_support,
support.min_cg_attn_backend,
uniform_decode_query_len=1 + num_speculative_tokens,
use_v2_model_runner=True,
)
assert mode.mixed_mode() != CUDAGraphMode.FULL
assert mode.decode_mode() == CUDAGraphMode.FULL
assert get_query_lens_mismatch_unsupported_backend(groups) is None
unsupported = attn_utils.get_varlen_cudagraph_unsupported_backend
assert unsupported(groups, config, 1 + num_speculative_tokens) is None
assert unsupported(groups, config, 2 + num_speculative_tokens) == (
backend.__name__,
1 + num_speculative_tokens,
)
def test_get_kv_sharing_fast_prefill_eligible_layers(monkeypatch: pytest.MonkeyPatch):
"""Fast prefill applies to the contiguous suffix of KV-sharing layers.
Draft-model layers register after the target model's and may share KV, so
they must not extend (or break) the target's eligible suffix.
"""
def check(
layer_names: list[str],
shared: dict[str, str],
draft_layer_names: set[str] | None = None,
) -> set[str]:
monkeypatch.setattr(
attn_utils,
"get_layers_from_vllm_config",
lambda *a, **k: {name: None for name in layer_names},
)
monkeypatch.setattr(attn_utils, "get_shared_kv_cache_layers", lambda *a: shared)
vllm_config = SimpleNamespace(
cache_config=SimpleNamespace(kv_sharing_fast_prefill=True)
)
return attn_utils.get_kv_sharing_fast_prefill_eligible_layers(
vllm_config, draft_layer_names
)
# No KV sharing: nothing is eligible.
assert check(["t0", "t1"], {}) == set()
# Trailing run of sharing layers (YOCO-style second half).
assert check(["t0", "t1", "t2", "t3"], {"t2": "t1", "t3": "t1"}) == {"t2", "t3"}
# A non-sharing layer after a sharing one breaks the suffix.
assert check(["t0", "t1", "t2", "t3"], {"t1": "t0", "t3": "t0"}) == {"t3"}
# KV-sharing draft layers at the end are collected without an exclusion...
assert check(
["t0", "t1", "t2", "t3", "d0", "d1"],
{"t2": "t1", "t3": "t1", "d0": "t1", "d1": "t1"},
) == {"t2", "t3", "d0", "d1"}
# ...so the runner excludes them: skipped, not collected, and they do not
# break the target's trailing run.
assert check(
["t0", "t1", "t2", "t3", "d0", "d1"],
{"t2": "t1", "t3": "t1", "d0": "t1", "d1": "t1"},
draft_layer_names={"d0", "d1"},
) == {"t2", "t3"}
# Feature flag off: nothing is eligible even with sharing layers.
monkeypatch.setattr(
attn_utils, "get_layers_from_vllm_config", lambda *a, **k: {"t0": None}
)
monkeypatch.setattr(
attn_utils, "get_shared_kv_cache_layers", lambda *a: {"t0": "t0"}
)
vllm_config = SimpleNamespace(
cache_config=SimpleNamespace(kv_sharing_fast_prefill=False)
)
assert attn_utils.get_kv_sharing_fast_prefill_eligible_layers(vllm_config) == set()
@pytest.mark.parametrize(
"num_tokens", [1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128]
)
@pytest.mark.parametrize("num_active_loras", [1, 2, 4])
def test_fast_prefill_dispatch_preserves_active_lora_count(
num_tokens: int, num_active_loras: int
):
"""Fast-prefill padding must match the main dispatch's LoRA variant."""
class FakeCudaGraphManager:
device = "cpu"
def __init__(self):
self.dispatch_calls = []
def dispatch(self, **kwargs):
self.dispatch_calls.append(kwargs)
# A captured no-LoRA graph is padded to 8 tokens, while the
# active-LoRA path stays eager at the unpadded token count.
if kwargs["num_active_loras"] == 0:
num_tokens = 8
mode = CUDAGraphMode.PIECEWISE
else:
num_tokens = kwargs["num_tokens"]
mode = CUDAGraphMode.NONE
return BatchExecutionDescriptor(
cg_mode=mode,
num_tokens=num_tokens,
num_reqs=kwargs["num_reqs"],
num_active_loras=kwargs["num_active_loras"],
num_ubatches=1,
)
manager = FakeCudaGraphManager()
helper = FastPrefillHelper(manager, max_num_tokens=max(32, num_tokens))
metadata = helper.prepare(
torch.arange(num_tokens, dtype=torch.int32),
num_reqs=1,
cu_num_logits_np=np.array([0, num_tokens], dtype=np.int32),
has_prefill=True,
batch_desc=BatchExecutionDescriptor(
cg_mode=CUDAGraphMode.NONE,
num_tokens=num_tokens,
num_reqs=1,
num_active_loras=num_active_loras,
num_ubatches=1,
),
num_active_loras=num_active_loras,
)
assert metadata is not None
assert metadata.num_logits_indices == num_tokens
assert metadata.logits_indices_padded.shape[0] == num_tokens
assert metadata.max_logits_per_req == num_tokens
assert manager.dispatch_calls[-1]["num_active_loras"] == num_active_loras
class _FakeSharedHostRegion:
def __init__(self) -> None:
self.cleanup_calls = 0
self.base_tensor = torch.empty(1, dtype=torch.int8)
def cleanup(self) -> None:
self.cleanup_calls += 1
def test_profiling_cleanup_keeps_host_pool_for_real_kv_cache(monkeypatch):
"""The real KV cache must reuse the profiling host pool, not pin it again."""
pinned = torch.empty(8, dtype=torch.int8)
allocate_pinned = MagicMock(return_value=(pinned, pinned))
monkeypatch.setattr(
hisparse_runtime_module, "allocate_pinned_host_pool", allocate_pinned
)
monkeypatch.setattr(
hisparse_runtime_module, "check_hisparse_host_memory", lambda size: None
)
vllm_config = SimpleNamespace(instance_id="profiling-reuse")
kv_cache_config = SimpleNamespace(hisparse_shared_host_pool=False)
pool = attn_utils_module.get_hisparse_host_pool(vllm_config, kv_cache_config)
backing = pool.allocate(8)
runtime = SimpleNamespace(
_host_cache=backing, registered_host_pool=pinned, hot_backing=object()
)
forward_context = {
"layer": SimpleNamespace(hisparse_cache=SimpleNamespace(runtime=runtime))
}
attn_utils_module.release_hisparse_profiling_cache(forward_context)
assert not hasattr(runtime, "_host_cache")
reused = attn_utils_module.get_hisparse_host_pool(vllm_config, kv_cache_config)
assert reused is pool
assert reused.allocate(8) is backing
allocate_pinned.assert_called_once_with(8)
hisparse_runtime_module.drop_hisparse_host_pool(vllm_config)
@pytest.mark.parametrize("failure_phase", ["allocation", "binding", "buffers"])
@pytest.mark.parametrize("shared", [False, True])
def test_init_hisparse_rolls_back_host_pool(monkeypatch, failure_phase, shared):
"""Failed initialization must release shared or private registrations."""
region = _FakeSharedHostRegion()
registered = torch.empty(4096, dtype=torch.int8)
cudart = MagicMock()
cudart.cudaHostUnregister.return_value.value = 0
monkeypatch.setattr(torch.accelerator, "synchronize", lambda: None)
monkeypatch.setattr(torch.cuda, "cudart", lambda: cudart)
vllm_config = SimpleNamespace(
cache_config=SimpleNamespace(
get_resolved_kv_cache_layout=lambda: KVCacheLayout.BLHNC
),
scheduler_config=SimpleNamespace(max_num_seqs=1),
instance_id="rollback",
)
pools = []
def allocate(*args):
pools.append(args[-1])
if shared:
args[-1].shared_region = region
else:
args[-1].registered = registered
args[-1].backing = registered[:8]
if failure_phase == "allocation":
raise RuntimeError("initialization failed")
return {}
def bind(**kwargs):
if failure_phase == "binding":
raise RuntimeError("initialization failed")
return []
def buffers(*args, **kwargs):
raise RuntimeError("initialization failed")
monkeypatch.setattr(attn_utils_module, "allocate_hisparse_kv_caches", allocate)
monkeypatch.setattr(attn_utils_module, "bind_hisparse_kv_caches", bind)
monkeypatch.setattr(
attn_utils_module, "initialize_hisparse_runtime_buffers", buffers
)
with pytest.raises(RuntimeError, match="initialization failed"):
attn_utils_module.init_hisparse_kv_cache(
SimpleNamespace(),
torch.device("cpu"),
[],
vllm_config,
{},
SimpleNamespace(),
)
assert region.cleanup_calls == int(shared)
if shared:
cudart.cudaHostUnregister.assert_not_called()
else:
cudart.cudaHostUnregister.assert_called_once_with(registered.data_ptr())
assert attn_utils_module.get_hisparse_host_pool(vllm_config, None) is not pools[0]
hisparse_runtime_module.drop_hisparse_host_pool(vllm_config)
def test_reshape_padded_kv_cache_strides_by_padded_page():
num_blocks = 3
spec = FullAttentionSpec(
block_size=16,
num_kv_heads=1,
head_size=2,
dtype=torch.float32,
page_size_padded=384,
)
assert spec.real_page_size_bytes == 256
raw = torch.zeros(spec.page_size_bytes * num_blocks, dtype=torch.int8)
(kv_cache,) = dense_kv_cache_views(raw, spec, num_blocks, 1, KVCacheLayout.LBHNC)
elem_size = 4 # float32
# Content dim packs K and V: 2 * head_size.
assert kv_cache.shape == (num_blocks, 1, 16, 2 * spec.head_size)
assert kv_cache.dtype == spec.dtype
assert kv_cache.stride(0) == spec.page_size_padded // elem_size
assert kv_cache[1].storage_offset() == spec.page_size_padded // elem_size
# Within one block the (unpadded) content stays compact.
assert kv_cache[0].is_contiguous()
@pytest.mark.parametrize(
(
"kernel_block_sizes",
"expected_num_blocks",
"expected_num_states",
),
[
(None, 4, 64),
([256], 4, 64),
([64], 16, 16),
],
)
def test_allocate_compressed_mla_cache(
kernel_block_sizes: list[int] | None,
expected_num_blocks: int,
expected_num_states: int,
):
spec = MLAAttentionSpec(
block_size=256,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
tokens_per_state=4,
)
num_pages = 4
config = KVCacheConfig(
num_blocks=num_pages,
kv_cache_tensors=[
KVCacheTensor(
size=num_pages * spec.page_size_bytes,
layers=["layer.0"],
layer_stride=num_pages * spec.page_size_bytes,
block_stride=spec.page_size_bytes,
)
],
kv_cache_groups=[KVCacheGroupSpec(["layer.0"], spec)],
)
caches = allocate_kv_cache(
config, torch.device("cpu"), KVCacheLayout.LBHNC, kernel_block_sizes
)
assert caches["layer.0"].shape == (expected_num_blocks, 1, expected_num_states, 128)
@pytest.mark.parametrize("layout", list(KVCacheLayout))
def test_copy_kv_cache_blocks_shared_storage(layout: KVCacheLayout):
num_blocks = 4
num_layers = 2
spec = FullAttentionSpec(
block_size=2,
num_kv_heads=2,
head_size=2,
dtype=torch.float32,
)
raw = torch.zeros(num_blocks * num_layers * spec.page_size_bytes, dtype=torch.int8)
caches = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
for layer_idx, cache in enumerate(caches):
for block_idx in range(num_blocks):
cache[block_idx].fill_(10 * layer_idx + block_idx)
expected = [[cache[i].clone() for i in range(num_blocks)] for cache in caches]
copies = [KVCacheBlockCopy(src_block_id=0, dst_block_id=2)]
copy_kv_cache_blocks_inplace(caches, num_blocks, copies)
for layer_idx, cache in enumerate(caches):
torch.testing.assert_close(cache[2], expected[layer_idx][0])
torch.testing.assert_close(cache[1], expected[layer_idx][1])
def test_fixed_block_stride_propagates_outward_in_lhbnc():
num_blocks = 3
num_layers = 2
spec = FullAttentionSpec(
block_size=2,
num_kv_heads=2,
head_size=2,
dtype=torch.float32,
)
natural = compute_layout_strides(spec, num_blocks, num_layers, KVCacheLayout.LHBNC)
block_stride = natural[1] + 8
strides = compute_layout_strides(
spec,
num_blocks,
num_layers,
KVCacheLayout.LHBNC,
fixed_strides=(None, block_stride, None, None, None),
)
assert strides[1] == block_stride
assert strides[2] == block_stride * num_blocks
assert strides[0] == strides[2] * spec.num_heads
def test_copy_kv_cache_blocks_separate_head_groups():
# LHBNC stores each head group separately, so a block's bytes are scattered
# across L*H regions.
layout = KVCacheLayout.LHBNC
num_blocks = 4
num_layers = 2
spec = FullAttentionSpec(
block_size=2,
num_kv_heads=2,
head_size=2,
dtype=torch.float32,
num_head_slots=2,
state_content_bytes=2 * 2 * 4,
)
raw = torch.zeros(num_blocks * num_layers * spec.page_size_bytes, dtype=torch.int8)
caches = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
for layer_idx, cache in enumerate(caches):
for block_idx in range(num_blocks):
for head_idx in range(cache.shape[1]):
cache[block_idx, head_idx].fill_(
100 * layer_idx + 10 * head_idx + block_idx
)
expected = [[cache[i].clone() for i in range(num_blocks)] for cache in caches]
copy_kv_cache_blocks_inplace(
caches,
num_blocks,
[KVCacheBlockCopy(src_block_id=0, dst_block_id=2)],
)
for layer_idx, cache in enumerate(caches):
torch.testing.assert_close(cache[2], expected[layer_idx][0])
torch.testing.assert_close(cache[1], expected[layer_idx][1])
@pytest.mark.parametrize(
"layout,num_layers",
[
(KVCacheLayout.LBHNC, 2),
# Splitting needs a manager block to be one dense page, which a
# block-outermost layout only gives when the block holds one layer.
(KVCacheLayout.BLHNC, 1),
],
)
def test_copy_kv_cache_blocks_with_virtual_block_splitting(
layout: KVCacheLayout, num_layers: int
):
num_blocks = 4
physical_per_logical = 2
spec = FullAttentionSpec(
block_size=4,
num_kv_heads=1,
head_size=2,
dtype=torch.float32,
)
raw = torch.zeros(num_blocks * num_layers * spec.page_size_bytes, dtype=torch.int8)
caches = dense_kv_cache_views(
raw,
spec,
num_blocks,
num_layers,
layout,
kernel_block_size=spec.block_size // physical_per_logical,
)
for layer_idx, cache in enumerate(caches):
for block_idx in range(cache.shape[0]):
cache[block_idx].fill_(100 * layer_idx + block_idx)
expected = [[cache[i].clone() for i in range(cache.shape[0])] for cache in caches]
copy_kv_cache_blocks_inplace(
caches,
num_blocks,
[KVCacheBlockCopy(src_block_id=0, dst_block_id=2)],
)
dst_start = 2 * physical_per_logical
for layer_idx, cache in enumerate(caches):
for physical_idx in range(physical_per_logical):
torch.testing.assert_close(
cache[dst_start + physical_idx], expected[layer_idx][physical_idx]
)
def test_allocate_hisparse_kv_caches_host_pool_and_view_less_specs():
"""Host tensors get their own backing; view-less specs keep the raw one."""
spec = FullAttentionSpec(
block_size=2, num_kv_heads=1, head_size=4, dtype=torch.float32
)
page = spec.page_size_bytes
resident_spec = HiSparseResidentSpec(block_size=2, page_size=page)
device_size = 4 * page
config = KVCacheConfig(
num_blocks=4,
hisparse_host_num_blocks=3,
kv_cache_tensors=[
KVCacheTensor(
size=3 * page,
layers=["source"],
layer_stride=3 * page,
block_stride=page,
host_resident=True,
),
KVCacheTensor(
size=device_size,
layers=["indexer"],
layer_stride=device_size,
block_stride=page,
),
KVCacheTensor(
size=device_size,
layers=["resident"],
layer_stride=device_size,
block_stride=page,
),
],
kv_cache_groups=[
KVCacheGroupSpec(["source"], spec, host_resident=True),
KVCacheGroupSpec(["indexer"], spec),
KVCacheGroupSpec(["resident"], resident_spec),
],
)
host_buffers: list[torch.Tensor] = []
def host_allocator(size: int) -> torch.Tensor:
host_buffers.append(torch.zeros(size, dtype=torch.int8))
return host_buffers[-1]
caches = allocate_hisparse_kv_caches(
config,
torch.device("cpu"),
KVCacheLayout.LBHNC,
[2, 2, 2],
SimpleNamespace(allocate=host_allocator),
)
assert len(config.kv_cache_tensors) == 3
assert [buf.numel() for buf in host_buffers] == [3 * page]
assert caches["source"].shape[0] == 3
assert (
caches["source"].untyped_storage().data_ptr()
== host_buffers[0].untyped_storage().data_ptr()
)
assert caches["indexer"].shape[0] == 4
backing = caches["resident"]
assert backing.dtype == torch.int8 and backing.numel() >= device_size
assert (
backing.untyped_storage().data_ptr()
== caches["indexer"].untyped_storage().data_ptr()
)
class _TableBuilder:
requires_block_table_width = False
supports_update_block_table = False
def __init__(self, kv_cache_spec, layer_names, vllm_config, device):
self.kv_cache_spec = kv_cache_spec
def build(self, common_prefix_len, common_attn_metadata, fast_build=False):
return common_attn_metadata.block_table_tensor
_VLLM_CONFIG = SimpleNamespace(
model_config=SimpleNamespace(max_model_len=8192),
scheduler_config=SimpleNamespace(max_num_seqs=4),
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
)
def _packed_group(tokens_per_state, row_bytes, supported_sizes):
spec = MLAAttentionSpec(
block_size=1024,
num_kv_heads=1,
head_size=128,
dtype=torch.uint8,
state_content_bytes=row_bytes,
tokens_per_state=tokens_per_state,
)
backend = SimpleNamespace(
get_builder_cls=lambda: _TableBuilder,
get_supported_kernel_block_sizes=lambda _=None: supported_sizes,
get_name=lambda: "FAKE",
customize_spec=lambda spec: spec,
)
return AttentionGroup(backend, ["layer.0"], spec, 0)
def test_packed_compressed_group_gets_kernel_block_table():
"""A packed indexer cache whose kernel needs 64-state pages gets a table and
a bound view in kernel blocks that address the same packed-block rows."""
row, stride_rows = 132, 5 * 64
group = _packed_group(4, row, [128, 256])
group.create_metadata_builders(_VLLM_CONFIG, "cpu", kernel_block_size=1024)
assert group.get_metadata_builder().kv_cache_spec.block_size == 256
backing = torch.arange(3 * stride_rows).repeat_interleave(row)
manager = backing.view(3, 1, stride_rows, row)[:, :, :256]
pages = map_kv_caches_to_kernel_blocks({"layer.0": manager}, [group])["layer.0"]
metadata = create_common_attn_metadata(BatchSpec([2048], [1]), 1024, "cpu")
metadata.block_table_tensor = torch.tensor([[0, 2]], dtype=torch.int32)
table = group.build_metadata(metadata)
assert table.tolist() == [[0, 1, 2, 3, 10, 11, 12, 13]]
assert torch.equal(pages[table[0, 4:], 0].flatten(0, 1), manager[2, 0])
def test_split_group_maps_manager_block_table():
"""Groups split in a dense layout keep manager block tables; builders get
b * blocks_per_kv_block + j against the view allocated in kernel blocks."""
group = _packed_group(4, 132, [128, 256])
group.create_metadata_builders(_VLLM_CONFIG, "cpu", kernel_block_size=256)
kernel_view = torch.zeros(12, 1, 64, 132)
bound = map_kv_caches_to_kernel_blocks({"layer.0": kernel_view}, [group])
assert bound["layer.0"] is kernel_view
metadata = create_common_attn_metadata(BatchSpec([2048], [1]), 1024, "cpu")
metadata.block_table_tensor = torch.tensor([[0, 2]], dtype=torch.int32)
table = group.build_metadata(metadata)
assert table.tolist() == [[0, 1, 2, 3, 8, 9, 10, 11]]
@pytest.mark.parametrize(
("block_size", "page_states"), [(1024, 64), (384, 32), (256, 0)]
)
def test_split_blocks_align_to_kernel_blocks(block_size, page_states):
"""Backends taking only fixed kernel blocks align packed blocks to the kernel
block the final block size is split into, and not at all when unsplit."""
group = _packed_group(4, 132, [128, 256])
spec = customize_attention_spec(group.backend, group.kv_cache_spec)
spec = spec.copy_with_new_block_size(block_size)
assert spec.get_block_stride_alignment() == max(page_states * 132, 1)
def test_packed_token_cache_cannot_be_split():
group = _packed_group(1, 1152, [64])
group.create_metadata_builders(_VLLM_CONFIG, "cpu", kernel_block_size=1024)
packed = torch.zeros(3, 1, 2048, 1152, dtype=torch.uint8)[:, :, :1024]
with pytest.raises(ValueError, match="cannot be split"):
map_kv_caches_to_kernel_blocks({"layer.0": packed}, [group])
@@ -1,206 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from vllm.distributed import parallel_state
from vllm.model_executor.models.interfaces import EagleModelMixin
from vllm.model_executor.models.mimo import MiMoModel
from vllm.models.minimax_m3.nvidia import model as minimax_m3
from vllm.sequence import IntermediateTensors
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
requires_aux_hidden_states,
reserve_aux_intermediate_tensor_slots,
verify_supports_aux_hidden_states_over_pp,
)
@pytest.mark.parametrize(
("method", "hf_config", "expected"),
[
("eagle3", {"eagle_config": {"use_aux_hidden_state": False}}, False),
("eagle3", {"eagle_config": {"use_aux_hidden_state": True}}, True),
("eagle3", {"eagle_config": {}}, True),
("eagle3", {"eagle_config": None}, True),
("eagle3", {}, True),
("dflash", {"eagle_config": {"use_aux_hidden_state": False}}, True),
("dspark", {"eagle_config": {"use_aux_hidden_state": False}}, True),
("extract_hidden_states", {}, True),
("mtp", {}, False),
],
)
def test_aux_hidden_state_requirement_respects_eagle3_config(
method, hf_config, expected
):
spec_config = SimpleNamespace(
method=method,
draft_model_config=SimpleNamespace(hf_config=SimpleNamespace(**hf_config)),
)
assert requires_aux_hidden_states(spec_config) is expected
def test_aux_layers_are_sorted_and_deduplicated():
model = EagleModelMixin()
model._set_aux_hidden_state_layers((48, 3, 90, 24, 48))
assert model.aux_hidden_state_layers == (3, 24, 48, 90)
def test_mimo_does_not_inherit_aux_hidden_state_pp_support():
inner = MiMoModel.__new__(MiMoModel)
target = SimpleNamespace(model=inner)
assert not inner.supports_aux_hidden_states_over_pp
with pytest.raises(ValueError, match="does not support eagle3"):
verify_supports_aux_hidden_states_over_pp(target, "eagle3")
class _PPAuxLayer(torch.nn.Module):
"""Aliases and mutates residual in place like MiniMaxM3DecoderLayer."""
ffn_all_reduce_deferred = False
def __init__(self, index):
super().__init__()
self.index = index
def forward(self, positions, hidden_states, residual):
total = hidden_states if residual is None else hidden_states + residual
residual = hidden_states if residual is None else residual
residual.copy_(total + self.index + 1)
return torch.full_like(hidden_states, 10 * (self.index + 1)), residual
class _PPAuxNorm(torch.nn.Module):
"""Clobbers its inputs so aux taps that alias them would fail."""
def forward(self, hidden_states, residual):
output = hidden_states + residual
hidden_states.fill_(-101)
residual.fill_(-103)
return output, residual
@pytest.fixture
def minimax_pp_stage(monkeypatch):
"""Use the real MiniMax constructor/forward and aux helpers on CPU tensors."""
group = SimpleNamespace(world_size=2, is_first_rank=True, is_last_rank=False)
bounds = [0, 3]
monkeypatch.setattr(minimax_m3, "get_pp_group", lambda: group)
monkeypatch.setattr(parallel_state, "get_pp_group", lambda: group)
monkeypatch.setattr(parallel_state, "model_parallel_is_initialized", lambda: True)
monkeypatch.setattr(
minimax_m3,
"VocabParallelEmbedding",
lambda *args, **kwargs: torch.nn.Identity(),
)
monkeypatch.setattr(
minimax_m3, "MiniMAXGemmaRMSNorm", lambda *args, **kwargs: _PPAuxNorm()
)
monkeypatch.setattr(
minimax_m3,
"MiniMaxM3DecoderLayer",
lambda **kwargs: _PPAuxLayer(int(kwargs["prefix"].rsplit(".", 1)[1])),
)
def make_layers(num_layers, build, prefix):
return (
*bounds,
torch.nn.ModuleList(
build(f"{prefix}.{index}")
if bounds[0] <= index < bounds[1]
else torch.nn.Identity()
for index in range(num_layers)
),
)
monkeypatch.setattr(minimax_m3, "make_layers", make_layers)
def make_stage(start, end, taps, world_size=2):
bounds[:] = [start, end]
group.world_size = world_size
group.is_first_rank = start == 0
group.is_last_rank = end == 6
config = SimpleNamespace(
vocab_size=16, hidden_size=6144, num_hidden_layers=6, rms_norm_eps=1e-6
)
model = minimax_m3.MiniMaxM3Model(
vllm_config=SimpleNamespace(
model_config=SimpleNamespace(hf_text_config=config),
quant_config=None,
speculative_config=None,
use_v2_model_runner=True,
)
)
model._set_aux_hidden_state_layers(taps)
target = SimpleNamespace(
model=model,
make_empty_intermediate_tensors=model.make_empty_intermediate_tensors,
)
reserve_aux_intermediate_tensor_slots(target)
return model, target
return make_stage
# Input 7; _PPAuxLayer i adds 11 * (i + 1) to hidden + residual.
def _expected_aux_value(tap):
return 7 + 11 * tap * (tap + 1) // 2
def _pp_aux_state(value):
return torch.full((2, 6144), float(value), device="cpu")
@pytest.mark.parametrize("taps", [(0, 3, 6), (0, 1, 3), (4, 5, 6)])
def test_minimax_pp2_preserves_ordered_global_aux_taps(minimax_pp_stage, taps):
first, _ = minimax_pp_stage(0, 3, taps)
sent = first(None, None, None, _pp_aux_state(7))
last, target = minimax_pp_stage(3, 6, taps)
reserved = target.make_empty_intermediate_tensors(2, torch.float32, "cpu")
assert set(sent.tensors) == set(reserved.tensors)
result = last(None, None, sent)
assert isinstance(result, tuple)
output, aux = result
torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6)))
for hidden, tap in zip(aux, taps, strict=True):
torch.testing.assert_close(hidden, _pp_aux_state(_expected_aux_value(tap)))
def test_minimax_missing_upstream_aux_slot_is_not_silently_dropped(minimax_pp_stage):
model, _ = minimax_pp_stage(3, 6, (0, 3, 6))
incoming = IntermediateTensors(
{
"hidden_states": _pp_aux_state(30),
"residual": _pp_aux_state(43),
"aux_hidden_states_0": _pp_aux_state(7),
}
)
with pytest.raises(RuntimeError, match="Missing aux_hidden_states_1"):
model(None, None, incoming)
@pytest.mark.parametrize("taps", [(), (0, 3, 6)])
def test_minimax_pp1_output_and_aux_taps(minimax_pp_stage, taps):
model, _ = minimax_pp_stage(0, 6, taps, world_size=1)
output = model(None, None, None, _pp_aux_state(7))
if taps:
output, aux = output
for hidden, tap in zip(aux, taps, strict=True):
torch.testing.assert_close(hidden, _pp_aux_state(_expected_aux_value(tap)))
torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6)))
def test_minimax_pp2_without_aux_keeps_hidden_and_residual_transport(minimax_pp_stage):
first, _ = minimax_pp_stage(0, 3, ())
sent = first(None, None, None, _pp_aux_state(7))
assert set(sent.tensors) == {"hidden_states", "residual"}
torch.testing.assert_close(sent["hidden_states"], _pp_aux_state(30))
torch.testing.assert_close(sent["residual"], _pp_aux_state(43))
last, target = minimax_pp_stage(3, 6, ())
assert set(
target.make_empty_intermediate_tensors(12, torch.bfloat16, "cpu").tensors
) == {"hidden_states", "residual"}
output = last(None, None, sent)
torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6)))
-408
View File
@@ -1,408 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
from vllm.platforms import current_platform
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
from vllm.v1.worker.gpu.block_table import BlockTables
pytestmark = pytest.mark.skipif(
not current_platform.is_cuda(),
reason="requires CUDA",
)
def test_block_tables_apply_staged_writes_fuses_kv_groups(monkeypatch):
device = torch.device("cuda")
block_tables = BlockTables(
block_sizes=[16, 32, 8],
max_num_reqs=4,
max_num_batched_tokens=64,
max_num_blocks_per_group=[8, 8, 8],
device=device,
)
def fail_if_apply_write_called():
pytest.fail("multi-group writes should use the fused apply kernel")
for block_table in block_tables.block_tables:
monkeypatch.setattr(block_table, "apply_write", fail_if_apply_write_called)
block_tables.append_block_ids(
req_index=0,
new_block_ids=([1, 2], [10, 11], []),
overwrite=True,
)
block_tables.append_block_ids(
req_index=1,
new_block_ids=([3], [12], [5, 6]),
overwrite=True,
)
block_tables.apply_staged_writes()
torch.accelerator.synchronize()
assert torch.equal(
block_tables.block_tables[0].gpu[0, :2],
torch.tensor([1, 2], dtype=torch.int32, device=device),
)
assert torch.equal(
block_tables.block_tables[1].gpu[0, :2],
torch.tensor([10, 11], dtype=torch.int32, device=device),
)
assert torch.equal(
block_tables.block_tables[0].gpu[1, :1],
torch.tensor([3], dtype=torch.int32, device=device),
)
assert torch.equal(
block_tables.block_tables[1].gpu[1, :1],
torch.tensor([12], dtype=torch.int32, device=device),
)
assert torch.equal(
block_tables.block_tables[2].gpu[1, :2],
torch.tensor([5, 6], dtype=torch.int32, device=device),
)
assert block_tables.num_blocks.np[0, 0] == 2
assert block_tables.num_blocks.np[1, 0] == 2
assert block_tables.num_blocks.np[2, 0] == 0
assert block_tables.num_blocks.np[0, 1] == 1
assert block_tables.num_blocks.np[1, 1] == 1
assert block_tables.num_blocks.np[2, 1] == 2
assert torch.equal(
block_tables.num_blocks.gpu[:, :2],
torch.tensor([[2, 1], [2, 1], [0, 2]], dtype=torch.int32, device=device),
)
for block_table in block_tables.block_tables:
assert not block_table._staged_write_indices
assert not block_table._staged_write_starts
assert not block_table._staged_write_contents
assert not block_table._staged_write_cu_lens
block_tables.append_block_ids(
req_index=0,
new_block_ids=([7], [13], [8]),
overwrite=False,
)
block_tables.apply_staged_writes()
torch.accelerator.synchronize()
assert torch.equal(
block_tables.block_tables[0].gpu[0, :3],
torch.tensor([1, 2, 7], dtype=torch.int32, device=device),
)
assert torch.equal(
block_tables.block_tables[1].gpu[0, :3],
torch.tensor([10, 11, 13], dtype=torch.int32, device=device),
)
assert torch.equal(
block_tables.block_tables[2].gpu[0, :1],
torch.tensor([8], dtype=torch.int32, device=device),
)
assert block_tables.num_blocks.np[0, 0] == 3
assert block_tables.num_blocks.np[1, 0] == 3
assert block_tables.num_blocks.np[2, 0] == 1
def test_block_tables_apply_staged_writes_single_group():
device = torch.device("cuda")
block_tables = BlockTables(
block_sizes=[16],
max_num_reqs=2,
max_num_batched_tokens=16,
max_num_blocks_per_group=[4],
device=device,
)
block_tables.append_block_ids(
req_index=0,
new_block_ids=([1, 2],),
overwrite=True,
)
block_tables.apply_staged_writes()
torch.accelerator.synchronize()
assert torch.equal(
block_tables.block_tables[0].gpu[0, :2],
torch.tensor([1, 2], dtype=torch.int32, device=device),
)
def test_block_tables_skip_custom_slot_mapping_groups():
device = torch.device("cuda")
block_tables = BlockTables(
block_sizes=[8, 262144],
max_num_reqs=1,
max_num_batched_tokens=4,
max_num_blocks_per_group=[1, 1],
device=device,
slot_mapping_enabled=[False, True],
)
block_tables.append_block_ids(
req_index=0,
new_block_ids=([7], [12]),
overwrite=True,
)
block_tables.apply_staged_writes()
idx_mapping = torch.tensor([0], dtype=torch.int32, device=device)
query_start_loc = torch.tensor([0, 2], dtype=torch.int32, device=device)
positions = torch.tensor([153797, 165757], dtype=torch.int64, device=device)
slot_mappings = block_tables.compute_slot_mappings(
idx_mapping,
query_start_loc,
positions,
num_tokens_padded=2,
)
torch.accelerator.synchronize()
assert slot_mappings[0].tolist() == [-1, -1]
assert slot_mappings[1].tolist() == [
12 * 262144 + 153797,
12 * 262144 + 165757,
]
@pytest.mark.parametrize("cp_rank", range(4))
def test_dcp_slot_mapping_only_shards_sharded_groups(cp_rank: int):
"""Only sharded groups use DCP interleave in logical-block coordinates."""
device = torch.device("cuda")
block_tables = BlockTables(
block_sizes=[128, 128],
max_num_reqs=1,
max_num_batched_tokens=1024,
max_num_blocks_per_group=[2, 8],
device=device,
dcp_sharded=[True, False],
cp_size=4,
cp_rank=cp_rank,
cp_interleave=128,
)
block_tables.append_block_ids(
req_index=0,
new_block_ids=([5, 9], list(range(10, 18))),
overwrite=True,
)
block_tables.apply_staged_writes()
idx_mapping = torch.zeros(1, dtype=torch.int32, device=device)
query_start_loc = torch.tensor([0, 1024], dtype=torch.int32, device=device)
positions = torch.arange(1024, dtype=torch.int64, device=device)
actual = block_tables.compute_slot_mappings(
idx_mapping,
query_start_loc,
positions,
num_tokens_padded=1024,
)
expected = torch.full((1024,), -1, dtype=torch.int64, device=device)
first_start = cp_rank * 128
second_start = 512 + first_start
expected[first_start : first_start + 128] = torch.arange(
5 * 128, 6 * 128, dtype=torch.int64, device=device
)
expected[second_start : second_start + 128] = torch.arange(
9 * 128, 10 * 128, dtype=torch.int64, device=device
)
assert torch.equal(actual[0], expected)
assert torch.equal(actual[1], positions + 10 * 128)
def test_v1_block_table_move_row_clears_vacated_row():
"""condense() moves the last row into a freed slot; the vacated row must
not keep stale block ids. Padded dummy-run batches dereference stale rows
as mamba state slots (bypassing the NULL_BLOCK_ID fill of real decode
padding) and write state in place there — corrupting the blocks' new
owner once they are reallocated, e.g. to an in-flight NIXL load."""
from vllm.v1.worker.block_table import BlockTable
block_table = BlockTable(
block_size=16,
max_num_reqs=4,
max_num_blocks_per_req=8,
max_num_batched_tokens=64,
pin_memory=False,
device=torch.device("cuda"),
cp_kv_cache_interleave_size=1,
)
block_table.add_row([7, 8, 9], row_idx=0)
block_table.add_row([4, 5], row_idx=1)
block_table.move_row(1, 0)
assert block_table.block_table.np[0, :2].tolist() == [4, 5]
assert block_table.num_blocks_per_row[0] == 2
# The vacated source row routes to the reserved null block.
assert block_table.num_blocks_per_row[1] == 0
assert (block_table.block_table.np[1] == 0).all()
def test_get_dummy_block_tables_returns_zeroed_rows():
"""Dummy runs bypass the gather, so the persistent input_block_tables
hold the previous real step's rows. Mamba/GDN metadata routes in-place
state writes through block_table[:, 0] (dummy slot mappings are
PAD-filled, state indices are not), so stale rows would direct dummy
state writes at freed — possibly reallocated — blocks.
get_dummy_block_tables must hand out zeroed (null block) rows while
preserving the persistent storage address for CUDA graphs."""
device = torch.device("cuda")
block_tables = BlockTables(
block_sizes=[16],
max_num_reqs=4,
max_num_batched_tokens=64,
max_num_blocks_per_group=[8],
device=device,
)
# Simulate a real step: stage a request's blocks and gather them into
# the persistent input block tables.
block_tables.append_block_ids(req_index=0, new_block_ids=([1, 2],), overwrite=True)
block_tables.apply_staged_writes()
idx_mapping = torch.zeros(1, dtype=torch.int32, device=device)
block_tables.gather_block_tables(idx_mapping, num_reqs_padded=1)
torch.accelerator.synchronize()
assert block_tables.input_block_tables[0][0, 0].item() == 1
dummy = block_tables.get_dummy_block_tables(num_reqs=1)
torch.accelerator.synchronize()
assert (dummy[0] == 0).all()
# CUDA graph invariant: same persistent tensor, not a fresh allocation.
assert dummy[0].data_ptr() == block_tables.input_block_tables[0].data_ptr()
def test_dummy_request_slot_mapping_is_pad():
"""idx_mapping == -1 marks a dummy (or CUDA-graph padding) request.
A dummy draft decode step must not resolve slots through the persistent
block-table row of a real request slot, which may be stale and point at
blocks that are now in the prefix cache.
"""
device = torch.device("cuda")
block_tables = BlockTables(
block_sizes=[4],
max_num_reqs=2,
max_num_batched_tokens=16,
max_num_blocks_per_group=[4],
device=device,
)
block_tables.append_block_ids(req_index=0, new_block_ids=([7, 8],), overwrite=True)
block_tables.apply_staged_writes()
query_start_loc = torch.tensor([0, 3], dtype=torch.int32, device=device)
positions = torch.tensor([1, 2, 3], dtype=torch.int64, device=device)
real = block_tables.compute_slot_mappings(
torch.tensor([0], dtype=torch.int32, device=device),
query_start_loc,
positions,
num_tokens_padded=3,
)
assert real[0].tolist() == [7 * 4 + 1, 7 * 4 + 2, 7 * 4 + 3]
dummy = block_tables.compute_slot_mappings(
torch.tensor([-1], dtype=torch.int32, device=device),
query_start_loc,
positions,
num_tokens_padded=3,
)
assert dummy[0].tolist() == [PAD_SLOT_ID] * 3
@pytest.fixture
def populated_block_tables():
tables = BlockTables([16, 32], 8, 64, [3, 5], torch.device("cuda"))
for req_index in range(8):
tables.append_block_ids(
req_index, ([req_index + 1] * 3, [req_index + 1] * 5), overwrite=True
)
tables.apply_staged_writes()
tables.gather_block_tables(torch.arange(8, device="cuda"), num_reqs_padded=8)
return tables
@pytest.mark.parametrize("previous_dummy", [False, True])
@pytest.mark.parametrize("next_dummy", [False, True])
def test_shared_block_tables_clear_rows_from_larger_batch(
populated_block_tables, previous_dummy, next_dummy
):
"""A smaller target batch must leave no stale rows for larger draft graphs."""
tables = populated_block_tables
if previous_dummy:
for table in tables.get_dummy_block_tables(8):
table.fill_(99) # Profiling supplies valid context/state slots.
ptrs = [table.data_ptr() for table in tables.input_block_tables]
idx = torch.tensor([7, 2, 0, 5, 1], device="cuda")
for num_reqs in (3, 5, 0):
if next_dummy:
out = tables.get_dummy_block_tables(num_reqs)
num_rows = num_reqs
else:
num_rows = num_reqs + 1
out = tables.gather_block_tables(idx[:num_reqs], num_rows)
for table, view, ptr in zip(tables.input_block_tables, out, ptrs):
assert view.shape == (num_rows, table.shape[1])
assert table.data_ptr() == ptr
if num_rows:
assert view.data_ptr() == ptr
assert torch.count_nonzero(table[num_reqs:]).item() == 0
if next_dummy:
assert torch.count_nonzero(view).item() == 0
view.fill_(99)
else:
expected = (idx[:num_reqs, None] + 1).expand(-1, table.shape[1])
torch.testing.assert_close(view[:num_reqs], expected.to(torch.int32))
def test_external_block_table_output_preserves_shared_rows(populated_block_tables):
"""PCP-local gathers must neither clear shared rows nor reset their tracking."""
tables = populated_block_tables
previous = [table.clone() for table in tables.input_block_tables]
out = tuple(torch.full_like(table[:3], -1) for table in previous)
out_ptrs = torch.tensor(
[table.data_ptr() for table in out], dtype=torch.uint64, device="cuda"
)
idx = torch.tensor([7, 2], device="cuda")
result = tables.gather_block_tables(idx, 3, out=out, out_ptrs=out_ptrs)
for table, before, view in zip(tables.input_block_tables, previous, result):
torch.testing.assert_close(table, before)
assert view[:, 0].tolist() == [8, 3, 0]
tables.gather_block_tables(idx[:1], num_reqs_padded=1)
for table in tables.input_block_tables:
assert torch.count_nonzero(table[1:]).item() == 0
@pytest.mark.parametrize("use_cuda_graph", [False, True])
def test_larger_draft_batch_uses_null_kpool_slots(
populated_block_tables, use_cuda_graph
):
"""Draft padding must not resolve to another request's physical KPool slots."""
from vllm.v1.attention.backends.mla.indexer import compute_kpool_tail_slot_mapping
tables = populated_block_tables
idx = torch.tensor([2, 0, 4, 1, 3], device="cuda")
query_start_loc = torch.arange(9, dtype=torch.int32, device="cuda").clamp_max_(5)
slot_mapping = torch.full((8,), -1, dtype=torch.int64, device="cuda")
positions = torch.arange(8, dtype=torch.int64, device="cuda")
def compute_slots():
return compute_kpool_tail_slot_mapping(
slot_mapping,
tables.input_block_tables[0],
query_start_loc,
positions,
num_actual_tokens=8,
num_reqs=8,
kpool=8,
)
if use_cuda_graph:
compute_slots()
torch.accelerator.synchronize()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
slots = compute_slots()
tables.gather_block_tables(idx, num_reqs_padded=5)
if use_cuda_graph:
graph.replay()
else:
slots = compute_slots()
assert slots.tolist() == [24, 9, 42, 19, 36, -1, -1, -1]
File diff suppressed because it is too large Load Diff
@@ -1,668 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from contextlib import nullcontext
from types import SimpleNamespace
from unittest.mock import Mock
import pytest
import torch
from vllm.config.compilation import CUDAGraphMode
from vllm.model_executor.models import supports_multimodal_embeddings
from vllm.model_executor.models.exaone4_5_mtp import Exaone4_5_MTP
from vllm.model_executor.models.llama4_eagle import EagleLlama4ForCausalLM
from vllm.model_executor.models.llama_eagle3 import Eagle3LlamaForCausalLM
from vllm.model_executor.models.mistral_eagle import EagleMistralForCausalLM
from vllm.model_executor.models.mistral_large_3_eagle import (
EagleMistralLarge3ForCausalLM,
)
from vllm.v1.attention.backends import flash_attn as flash_attn_module
from vllm.v1.attention.backends.flash_attn import FlashAttentionMetadata
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
from vllm.v1.kv_cache_interface import MLAAttentionSpec
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
from vllm.v1.worker.gpu.pcp_manager import PCPManager
from vllm.v1.worker.gpu.spec_decode import speculator as base_spec_module
from vllm.v1.worker.gpu.spec_decode.multi_module_mtp.speculator import (
MultiModuleMTPSpeculator,
)
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar import speculator as spec_module
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.speculator import (
TargetDependentARSpeculator,
)
from vllm.v1.worker.utils import AttentionGroup
class _TestSpeculator(TargetDependentARSpeculator):
def load_draft_model(self, target_model, target_attn_layer_names):
return self.test_draft_model
class _DraftModel(torch.nn.Module):
def __init__(self, output: torch.Tensor | tuple[torch.Tensor, torch.Tensor]):
super().__init__()
self.output = output
def forward(self, **kwargs):
return self.output
class _MultimodalDraftModel(torch.nn.Module):
supports_multimodal_embeddings = True
def embed_input_ids(
self,
input_ids,
multimodal_embeddings=None,
*,
is_multimodal=None,
):
raise AssertionError("embed_input_ids should not be called during loading")
class _TextOnlyDraftModel(torch.nn.Module):
def embed_input_ids(
self,
input_ids,
multimodal_embeddings=None,
*,
is_multimodal=None,
):
raise AssertionError("embed_input_ids should not be called during loading")
@pytest.mark.parametrize("cg_mode", [CUDAGraphMode.NONE, CUDAGraphMode.FULL])
def test_pcp_draft_metadata_keeps_graph_padding_in_decode(cg_mode):
def build(common_prefix_len, common_attn_metadata):
return split_decodes_and_prefills(
common_attn_metadata,
decode_threshold=1,
require_uniform=True,
treat_short_extends_as_decodes=False,
)
speculator = object.__new__(_TestSpeculator)
speculator.arange_np = torch.arange(5, dtype=torch.int32).numpy()
speculator.max_model_len = speculator.draft_max_seq_len = 32
speculator.draft_is_prefilling = torch.zeros(4, dtype=torch.bool)
speculator.input_buffers = SimpleNamespace(
positions=torch.arange(4, dtype=torch.int64),
query_start_loc=torch.tensor([0, 1, 2, 2, 2], dtype=torch.int32),
seq_lens=torch.tensor([11, 21, 0, 0], dtype=torch.int32),
)
speculator.dcp_size = 1
speculator.block_tables = SimpleNamespace(
cp_size=1,
input_block_tables=[torch.zeros(4, 1, dtype=torch.int32)],
slot_mappings=torch.tensor([[10, 20, -1, -1]]),
)
speculator.kv_cache_config = SimpleNamespace(kv_cache_groups=[object()])
speculator.attn_groups = [
[
SimpleNamespace(
get_metadata_builder=lambda _: SimpleNamespace(
build=build, supports_update_block_table=False
),
build_metadata=lambda cm, ubatch_idx=0, **_: build(0, cm),
layer_names=["draft"],
)
]
]
num_reqs_padded = 4 if cg_mode == CUDAGraphMode.FULL else 2
metadata = speculator._build_uniform_attn_metadata(
batch_desc=BatchExecutionDescriptor(cg_mode, 4, num_reqs_padded),
num_reqs=2,
num_query_per_req=1,
seq_lens_cpu_upper_bound=torch.tensor([10, 20], dtype=torch.int32),
step=1,
)
assert metadata["draft"] == (num_reqs_padded, 0, num_reqs_padded, 0)
def _mock_base_model_load(monkeypatch):
monkeypatch.setattr(
base_spec_module,
"get_layers_from_vllm_config",
lambda *args, **kwargs: {},
)
monkeypatch.setattr(
DraftModelSpeculator,
"_validate_local_argmax_reduction",
lambda self: None,
)
def _make_speculator(
monkeypatch,
output: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
) -> _TestSpeculator:
monkeypatch.setattr(
spec_module,
"set_forward_context",
lambda *args, **kwargs: nullcontext(),
)
speculator = object.__new__(_TestSpeculator)
speculator.supports_mm_inputs = False
speculator.pcp_manager = None
speculator.vllm_config = None
speculator.input_buffers = SimpleNamespace(
input_ids=torch.arange(4),
positions=torch.arange(4),
)
speculator.hidden_states = torch.zeros(4, 3)
speculator.model = _DraftModel(output)
return speculator
@pytest.mark.parametrize(("hc_mult", "expected"), [(None, 64), (4, 256)])
def test_speculator_uses_draft_model_hidden_size(monkeypatch, hc_mult, expected):
# Qwen4Exp targets expose multi-stream HC residuals to the drafter.
monkeypatch.setattr(base_spec_module, "_target_feeds_hc_residual", lambda _: True)
hf_config = SimpleNamespace()
if hc_mult is not None:
hf_config.hc_mult = hc_mult
draft_model_config = SimpleNamespace(
hf_config=hf_config,
get_hidden_size=lambda: 64,
get_vocab_size=lambda: 32,
)
speculative_config = SimpleNamespace(
method="mtp",
num_speculative_tokens=3,
draft_model_config=draft_model_config,
use_local_argmax_reduction=False,
draft_sample_method="greedy",
enable_adaptive_verification=False,
)
vllm_config = SimpleNamespace(
speculative_config=speculative_config,
scheduler_config=SimpleNamespace(
max_num_seqs=2,
max_num_batched_tokens=8,
),
model_config=SimpleNamespace(
max_model_len=32,
dtype=torch.float32,
use_fp64_gumbel=False,
),
parallel_config=SimpleNamespace(
data_parallel_size=1,
data_parallel_rank=0,
decode_context_parallel_size=1,
),
)
speculator = _TestSpeculator(vllm_config, torch.device("cpu"))
assert speculator.hidden_size == expected
def test_mm_support_configured_after_model_load(monkeypatch):
checked_configs = []
class _ModelConfig:
@property
def supports_multimodal_inputs(self):
checked_configs.append(self)
return True
target_model_config = _ModelConfig()
draft_model_config = _ModelConfig()
vllm_config = SimpleNamespace(model_config=target_model_config)
draft_model = _MultimodalDraftModel()
def init_base(speculator, vllm_config, device):
speculator.vllm_config = vllm_config
speculator.device = device
speculator.max_num_tokens = 4
speculator.max_num_reqs = 2
speculator.hidden_size = 3
speculator.dtype = torch.float32
speculator.draft_model_config = draft_model_config
speculator.supports_mm_inputs = False
speculator.use_acceptance_estimator = False
monkeypatch.setattr(DraftModelSpeculator, "__init__", init_base)
_mock_base_model_load(monkeypatch)
speculator = _TestSpeculator(vllm_config, torch.device("cpu"))
assert checked_configs == []
assert not speculator.supports_mm_inputs
assert speculator.inputs_embeds is None
speculator.test_draft_model = draft_model
speculator.load_model(torch.nn.Module())
assert checked_configs == [target_model_config]
assert speculator.supports_mm_inputs
assert speculator.inputs_embeds is not None
assert speculator.inputs_embeds.shape == (4, 3)
def test_load_model_keeps_mm_support_for_capable_drafter(monkeypatch):
speculator = object.__new__(_TestSpeculator)
speculator.supports_mm_inputs = False
speculator.inputs_embeds = None
speculator.use_acceptance_estimator = False
speculator.vllm_config = SimpleNamespace(
model_config=SimpleNamespace(supports_multimodal_inputs=True)
)
speculator.max_num_tokens = 4
speculator.hidden_size = 3
speculator.dtype = torch.float32
speculator.device = torch.device("cpu")
draft_model = _MultimodalDraftModel()
speculator.test_draft_model = draft_model
_mock_base_model_load(monkeypatch)
speculator.load_model(torch.nn.Module())
assert speculator.supports_mm_inputs
assert speculator.inputs_embeds is not None
def test_load_model_disables_mm_support_for_text_only_drafter(monkeypatch):
speculator = object.__new__(_TestSpeculator)
speculator.supports_mm_inputs = False
speculator.inputs_embeds = None
speculator.use_acceptance_estimator = False
speculator.vllm_config = SimpleNamespace(
model_config=SimpleNamespace(supports_multimodal_inputs=True)
)
draft_model = _TextOnlyDraftModel()
speculator.test_draft_model = draft_model
warning_messages = []
_mock_base_model_load(monkeypatch)
monkeypatch.setattr(
base_spec_module.logger,
"warning_once",
lambda message, *args: warning_messages.append(message % args),
)
speculator.load_model(torch.nn.Module())
assert not speculator.supports_mm_inputs
assert warning_messages == [
(
"Draft model _TextOnlyDraftModel does not support external multimodal "
"embeddings. Embeddings from the target model will not be passed to the "
"drafter; using text-only draft inputs instead."
)
]
def test_multi_module_mm_support_configured_after_model_load(monkeypatch):
speculator = object.__new__(MultiModuleMTPSpeculator)
speculator.supports_mm_inputs = False
speculator.inputs_embeds = None
speculator.use_acceptance_estimator = False
speculator.cached_draft_input_embeds = None
speculator.vllm_config = SimpleNamespace(
model_config=SimpleNamespace(supports_multimodal_inputs=True)
)
speculator.max_num_tokens = 4
speculator.max_num_reqs = 2
speculator.num_speculative_steps = 3
speculator.hidden_size = 3
speculator.dtype = torch.float32
speculator.device = torch.device("cpu")
draft_model = _MultimodalDraftModel()
_mock_base_model_load(monkeypatch)
monkeypatch.setattr(
MultiModuleMTPSpeculator,
"load_draft_model",
lambda self, target_model, target_attn_layer_names: draft_model,
)
speculator.load_model(torch.nn.Module())
assert speculator.supports_mm_inputs
assert speculator.inputs_embeds is not None
assert speculator.inputs_embeds.shape == (4, 3)
assert speculator.cached_draft_input_embeds is not None
assert speculator.cached_draft_input_embeds.shape == (2, 2, 3)
@pytest.mark.parametrize(
("model_cls", "expected"),
[
(EagleLlama4ForCausalLM, True),
(EagleMistralForCausalLM, True),
(EagleMistralLarge3ForCausalLM, True),
(Exaone4_5_MTP, True),
(Eagle3LlamaForCausalLM, False),
],
)
def test_draft_model_multimodal_embedding_capability(model_cls, expected):
assert supports_multimodal_embeddings(model_cls) is expected
@pytest.mark.parametrize(
"model_cls", [EagleLlama4ForCausalLM, EagleMistralLarge3ForCausalLM]
)
def test_mm_capable_drafter_merges_multimodal_embeddings(model_cls):
"""Drafters advertising multimodal embeddings must embed text ids and
scatter the multimodal embeddings themselves; they do not inherit
SupportsMultiModal's helpers."""
table = torch.arange(8, dtype=torch.float32).repeat(3, 1).T # [8, 3]
drafter = object.__new__(model_cls)
drafter.model = SimpleNamespace(embed_input_ids=lambda ids: table[ids])
input_ids = torch.tensor([1, 5, 6, 2])
text_only = model_cls.embed_input_ids(drafter, input_ids)
assert torch.equal(text_only, table[input_ids])
mm_embeds = [torch.full((2, 3), -1.0)]
is_multimodal = torch.tensor([False, True, True, False])
merged = model_cls.embed_input_ids(
drafter, input_ids, mm_embeds, is_multimodal=is_multimodal
)
assert torch.equal(merged[[0, 3]], table[[1, 2]])
assert torch.equal(merged[[1, 2]], mm_embeds[0])
def test_run_model_unpacks_tuple_return_for_mtp(monkeypatch):
logits_hidden = torch.full((4, 3), 1.0)
feedback_hidden = torch.full((4, 3), 2.0)
speculator = _make_speculator(monkeypatch, (logits_hidden, feedback_hidden))
actual_logits_hidden, actual_feedback_hidden = speculator._run_model(
4,
attn_metadata=None,
slot_mappings=None,
num_tokens_across_dp=None,
cudagraph_runtime_mode=CUDAGraphMode.NONE,
)
assert actual_logits_hidden is logits_hidden
assert actual_feedback_hidden is feedback_hidden
def test_run_model_reuses_tensor_return_for_mtp(monkeypatch):
hidden = torch.full((4, 3), 1.0)
speculator = _make_speculator(monkeypatch, hidden)
actual_logits_hidden, actual_feedback_hidden = speculator._run_model(
4,
attn_metadata=None,
slot_mappings=None,
num_tokens_across_dp=None,
cudagraph_runtime_mode=CUDAGraphMode.NONE,
)
assert actual_logits_hidden is hidden
assert actual_feedback_hidden is hidden
@pytest.mark.parametrize("partitioned", [False, True])
def test_run_model_uses_complete_pcp_padding(monkeypatch, partitioned):
hidden = torch.full((4, 3), 1.0)
speculator = _make_speculator(monkeypatch, hidden)
gathered_is_padding = torch.tensor(
[False, False, False, True, False, False, True, True]
)
manager = PCPManager(
pcp_world_size=2,
pcp_rank=0,
device=torch.device("cpu"),
shard_decode_requests=True,
max_num_tokens=4,
moe_gathers_tokens=True,
)
if partitioned:
manager.draft_prefill_batch = SimpleNamespace(
input_ids=torch.arange(4),
positions=torch.arange(4),
is_padding=gathered_is_padding,
)
else:
local_is_padding = torch.tensor([False, False, False, True])
speculator.input_buffers.is_padding = local_is_padding
gathered_is_padding = torch.cat([local_is_padding, local_is_padding])
seen = {}
monkeypatch.setattr(
spec_module,
"set_forward_context",
lambda *args, **kwargs: (seen.update(kwargs), nullcontext())[1],
)
speculator.pcp_manager = manager
speculator._run_model(
4,
attn_metadata=None,
slot_mappings=None,
num_tokens_across_dp=None,
cudagraph_runtime_mode=CUDAGraphMode.NONE,
)
torch.testing.assert_close(seen["is_padding"], gathered_is_padding)
if partitioned:
assert seen["is_padding"] is gathered_is_padding
@pytest.mark.parametrize(
(
"method_name",
"cg_mode",
"num_speculative_steps",
"expected_eager_calls",
"expected_graph_replays",
),
[
("_multi_step_decode", CUDAGraphMode.NONE, 4, 3, 0),
("_multi_step_decode", CUDAGraphMode.FULL, 4, 0, 3),
("_fused_multi_step_decode", CUDAGraphMode.NONE, 4, 3, 0),
("_fused_multi_step_decode", CUDAGraphMode.FULL, 4, 0, 1),
("_multi_step_decode", CUDAGraphMode.FULL, 3, 0, 2),
],
)
def test_multi_step_decode_replays_captured_graph_as_expected(
method_name,
cg_mode,
num_speculative_steps,
expected_eager_calls,
expected_graph_replays,
):
speculator = object.__new__(_TestSpeculator)
speculator.num_speculative_steps = 4
speculator.current_draft_step = torch.tensor(0)
speculator.slot_mapping_observer = None
speculator.host_mirror_forward_observer = None
speculator.input_buffers = SimpleNamespace(
positions=torch.arange(2),
query_start_loc=torch.arange(3),
)
speculator.idx_mapping = torch.arange(2)
speculator.attn_groups = []
speculator.block_tables = SimpleNamespace(input_block_tables=[])
generate_draft = Mock()
speculator._generate_draft = generate_draft
run_fullgraph = Mock()
speculator.decode_cudagraph_manager = SimpleNamespace(run_fullgraph=run_fullgraph)
batch_desc = BatchExecutionDescriptor(
cg_mode=cg_mode,
num_tokens=2,
num_reqs=2,
)
getattr(speculator, method_name)(
num_reqs=2,
skip_attn=True,
batch_desc=batch_desc,
seq_lens_cpu_upper_bound=None,
num_tokens_across_dp=None,
num_speculative_steps=num_speculative_steps,
)
assert generate_draft.call_count == expected_eager_calls
assert run_fullgraph.call_count == expected_graph_replays
def test_fused_full_graph_maps_split_group_block_tables():
"""The fused FULL replay skips build(), so split groups' tables are mapped first."""
spec = MLAAttentionSpec(
block_size=1024, num_kv_heads=1, head_size=128, dtype=torch.uint8
)
group = AttentionGroup(
SimpleNamespace(),
["layer.0"],
spec,
0,
kernel_block_size=256,
kernel_block_table=torch.zeros(1, 4, 32, dtype=torch.int32),
kernel_block_offsets=torch.arange(4, dtype=torch.int32),
)
speculator = object.__new__(_TestSpeculator)
speculator.input_buffers = SimpleNamespace(
positions=torch.arange(2), query_start_loc=torch.arange(3)
)
speculator.idx_mapping = torch.arange(2)
speculator.attn_groups = [[group]]
speculator.block_tables = SimpleNamespace(
input_block_tables=[torch.tensor([[1, 2], [0, 3]], dtype=torch.int32)]
)
replayed_tables = []
speculator.decode_cudagraph_manager = SimpleNamespace(
run_fullgraph=lambda _: replayed_tables.append(
group.kernel_block_table[0, :2, :8].tolist()
)
)
speculator._fused_multi_step_decode(
num_reqs=2,
skip_attn=False,
batch_desc=BatchExecutionDescriptor(
cg_mode=CUDAGraphMode.FULL, num_tokens=2, num_reqs=2
),
num_tokens_across_dp=None,
seq_lens_cpu_upper_bound=None,
num_speculative_steps=4,
)
assert replayed_tables == [
[[4, 5, 6, 7, 8, 9, 10, 11], [0, 1, 2, 3, 12, 13, 14, 15]]
]
def test_update_draft_decode_metadata_updates_fa3_scheduler_metadata(
monkeypatch,
):
builder = object.__new__(flash_attn_module.FlashAttentionMetadataBuilder)
builder.aot_schedule = True
builder.use_full_cuda_graph = True
builder.scheduler_metadata = torch.zeros(8, dtype=torch.int32)
builder.cache_config = SimpleNamespace(cache_dtype="bfloat16")
builder.kv_cache_dtype = torch.bfloat16
builder.num_heads_q = 2
builder.num_heads_kv = 1
builder.headdim = 128
builder.block_size = 16
builder.dcp_world_size = 1
builder.dcp_rank = 0
builder.cp_kv_cache_interleave_size = 1
builder.aot_sliding_window = None
expected = torch.tensor([7, 8, 9], dtype=torch.int32)
def fake_get_scheduler_metadata(**kwargs):
return expected
monkeypatch.setattr(builder, "_get_scheduler_metadata", fake_get_scheduler_metadata)
metadata = FlashAttentionMetadata(
num_actual_tokens=3,
max_query_len=2,
query_start_loc=torch.tensor([0, 1, 3], dtype=torch.int32),
max_seq_len=8,
seq_lens=torch.tensor([5, 6], dtype=torch.int32),
block_table=torch.zeros((2, 1), dtype=torch.int32),
slot_mapping=torch.zeros(3, dtype=torch.int32),
max_dcp_context_kv_len=None,
dcp_context_kv_lens=None,
num_decode_reqs=2,
num_prefill_reqs=0,
num_decode_tokens=3,
num_prefill_tokens=0,
scheduler_metadata=torch.tensor([-1, -1, -1], dtype=torch.int32),
max_num_splits=4,
causal=True,
mm_prefix_query_range_tensor=None,
rswa_prefix_lens=None,
rswa_window=None,
rswa_window_tensor=None,
)
builder.update_draft_decode_metadata(metadata)
assert torch.equal(metadata.scheduler_metadata, expected)
assert torch.equal(builder.scheduler_metadata[:3], expected)
def test_update_draft_decode_metadata_skips_without_scheduler_metadata(monkeypatch):
builder = object.__new__(flash_attn_module.FlashAttentionMetadataBuilder)
builder.aot_schedule = True
builder.use_full_cuda_graph = True
builder.scheduler_metadata = torch.zeros(4, dtype=torch.int32)
called = False
def fake_get_scheduler_metadata(**kwargs):
nonlocal called
called = True
return torch.tensor([1], dtype=torch.int32)
monkeypatch.setattr(builder, "_get_scheduler_metadata", fake_get_scheduler_metadata)
metadata = FlashAttentionMetadata(
num_actual_tokens=1,
max_query_len=1,
query_start_loc=torch.tensor([0, 1], dtype=torch.int32),
max_seq_len=1,
seq_lens=torch.tensor([1], dtype=torch.int32),
block_table=torch.zeros((1, 1), dtype=torch.int32),
slot_mapping=torch.zeros(1, dtype=torch.int32),
max_dcp_context_kv_len=None,
dcp_context_kv_lens=None,
num_decode_reqs=1,
num_prefill_reqs=0,
num_decode_tokens=1,
num_prefill_tokens=0,
scheduler_metadata=None,
max_num_splits=1,
causal=True,
mm_prefix_query_range_tensor=None,
rswa_prefix_lens=None,
rswa_window=None,
rswa_window_tensor=None,
)
builder.update_draft_decode_metadata(metadata)
assert not called
assert metadata.scheduler_metadata is None
@pytest.mark.parametrize(("num_speculative_steps", "expected"), [(1, False), (3, True)])
def test_decode_metadata_update_needs_draft_decode_steps(
num_speculative_steps, expected
):
"""One speculative step runs no draft decodes, so the in-place metadata
update (and its fallback log) does not apply even on a capable backend."""
speculator = object.__new__(_TestSpeculator)
speculator.num_speculative_steps = num_speculative_steps
speculator.attn_groups = [
[
SimpleNamespace(
supports_draft_decode_metadata_update=True,
backend=SimpleNamespace(get_name=lambda: "CAPABLE"),
)
]
]
speculator._configure_decode_metadata_update()
assert speculator.supports_decode_metadata_update is expected
-468
View File
@@ -1,468 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from contextlib import nullcontext
from types import SimpleNamespace
from unittest.mock import patch
import pytest
import torch
from tests.utils import create_new_process_for_each_test
from vllm.platforms import current_platform
from vllm.utils.mem_constants import GiB_bytes
from vllm.v1.worker import gpu_worker, startup_plan
from vllm.v1.worker.gpu_worker import maybe_rocm_profiling_fallback
from vllm.v1.worker.startup_plan import (
maybe_apply_startup_plan,
maybe_save_startup_plan,
)
def test_sleep_preservation_restores_private_draft_not_shared_target():
target = torch.nn.Linear(2, 2, bias=False)
draft = torch.nn.Module()
draft.private = torch.nn.Linear(2, 2, bias=False)
draft.shared = target.weight
expected = draft.private.weight.detach().clone()
pointer = draft.private.weight.data_ptr()
worker = object.__new__(gpu_worker.Worker)
worker.get_draft_model = lambda: draft
assert set(worker._get_sleep_parameters(target)) == {
"weight",
"draft.private.weight",
}
worker._sleep_saved_parameters = {"draft.private.weight": expected}
with torch.no_grad():
target.weight.fill_(3.0)
draft.private.weight.zero_()
worker._restore_sleep_parameters(target)
torch.testing.assert_close(draft.private.weight, expected)
assert draft.private.weight.data_ptr() == pointer
assert torch.all(target.weight == 3.0)
assert worker._sleep_saved_parameters == {}
@pytest.mark.parametrize("has_shared_draft", [False, True])
def test_sleep_preservation_allows_empty_draft_but_rejects_target_typo(
has_shared_draft,
):
target = torch.nn.Linear(2, 2, bias=False)
draft = torch.nn.Module() if has_shared_draft else None
if draft is not None:
draft.shared = target.weight
worker = object.__new__(gpu_worker.Worker)
worker.get_draft_model = lambda: draft
worker.model_config = SimpleNamespace(sleep_preserve_parameter_names=["draft.*"])
worker._save_sleep_parameters(target)
assert worker._sleep_saved_parameters == {}
worker.model_config.sleep_preserve_parameter_names = ["missing"]
with pytest.raises(ValueError, match="No parameter matches sleep retention"):
worker._save_sleep_parameters(target)
def test_load_model_preserves_compiled_graphs_at_runtime(monkeypatch):
"""Profiling must use serving's thread count to keep Dynamo guards valid."""
from torch._dynamo.testing import CompileCounter
monkeypatch.delenv("OMP_NUM_THREADS", raising=False)
monkeypatch.setattr(gpu_worker, "has_ec_transfer", lambda: False)
monkeypatch.setattr(
gpu_worker, "set_current_vllm_config", lambda config: nullcontext()
)
loading_threads = []
worker = SimpleNamespace(
vllm_config=SimpleNamespace(weight_transfer_config=None),
model_runner=SimpleNamespace(
load_model=lambda **kwargs: loading_threads.append(torch.get_num_threads())
),
_maybe_get_memory_pool_context=lambda **kwargs: nullcontext(),
_scoped_allocator_max_split=lambda **kwargs: nullcontext(),
)
original_threads = torch.get_num_threads()
try:
torch.set_num_threads(2)
gpu_worker.Worker.load_model(worker)
assert loading_threads == [2]
counter = CompileCounter()
compiled = torch.compile(lambda x: x + 1, backend=counter, fullgraph=True)
x = torch.ones(2)
compiled(x)
gpu_worker.set_torch_threads_for_runtime()
torch.testing.assert_close(compiled(x), x + 1)
assert counter.frame_count == 1
finally:
torch.set_num_threads(original_threads)
@pytest.mark.skipif(
not current_platform.is_cuda_alike()
or not torch.accelerator.is_available()
or torch.cuda.memory.get_allocator_backend() != "native",
reason="needs the native CUDA or ROCm allocator",
)
# A fresh allocator: blocks cached by earlier tests could serve the large buffer.
@create_new_process_for_each_test("spawn")
def test_scoped_max_split_keeps_freed_large_blocks_releasable():
"""A small allocation made after a large buffer is freed must not pin the
buffer's segment: the profiling run (determine_available_memory) grows
workspaces this way, and a pinned segment survives empty_cache() and is
counted as consumed memory."""
large = 512 * 1024 * 1024
small = 2 * 1024 * 1024 # large pool, so it is served by splitting cached blocks
def reserved_while_small_is_live(scope) -> int:
torch.accelerator.empty_cache()
with scope:
buf = torch.empty(large, dtype=torch.uint8, device="cuda")
del buf
tensor = torch.empty(small, dtype=torch.uint8, device="cuda")
torch.accelerator.empty_cache()
reserved = torch.accelerator.memory_reserved()
del tensor
torch.accelerator.empty_cache()
return reserved
baseline = torch.accelerator.memory_reserved()
# Without the limit the small tensor is split off the freed block and pins it.
assert reserved_while_small_is_live(nullcontext()) - baseline >= large
scoped = gpu_worker.Worker._scoped_allocator_max_split(
SimpleNamespace(), max_split_size_mb=20
)
assert reserved_while_small_is_live(scoped) - baseline < large
@pytest.mark.skipif(
not current_platform.is_cuda_alike()
or not torch.accelerator.is_available()
or torch.cuda.memory.get_allocator_backend() != "native",
reason="needs the native CUDA or ROCm allocator",
)
@pytest.mark.parametrize("fail", [False, True])
@pytest.mark.parametrize("snapshot_fallback", [False, True])
@pytest.mark.parametrize("suffix", ["", ", "])
def test_scoped_max_split_preserves_allocator_settings(
monkeypatch, fail, snapshot_fallback, suffix
):
"""Preserve allocator settings across successful and failed profiling runs."""
if snapshot_fallback:
monkeypatch.delattr(
torch._C, "_accelerator_getAllocatorSettings", raising=False
)
def settings():
return torch.cuda.memory._snapshot()["allocator_settings"]
original = settings()["PYTORCH_CUDA_ALLOC_CONF"]
configured = (
"max_split_size_mb:128,garbage_collection_threshold:0.8,"
"roundup_power2_divisions:[256:1,512:2,>:4],max_non_split_rounding_mb:32"
)
try:
torch._C._accelerator_setAllocatorSettings(configured + suffix)
before = settings()
expected_error = pytest.raises(RuntimeError, match="profiling failed")
with (
expected_error if fail else nullcontext(),
gpu_worker.Worker._scoped_allocator_max_split(SimpleNamespace(), 20),
):
scoped = settings()
assert scoped["max_split_size"] == 20 * 1024 * 1024
for key in ("garbage_collection_threshold", "roundup_power2_divisions"):
assert scoped[key] == before[key]
if fail:
raise RuntimeError("profiling failed")
assert settings() == before
finally:
torch._C._accelerator_setAllocatorSettings(original)
def test_scoped_max_split_ignores_async_allocator(monkeypatch):
"""Async allocators ignore max_split and may not support memory snapshots."""
monkeypatch.setattr(current_platform, "is_cuda_alike", lambda: True)
monkeypatch.setattr(
torch.cuda.memory, "get_allocator_backend", lambda: "cudaMallocAsync"
)
with (
patch.object(torch.cuda.memory, "_snapshot") as snapshot,
patch.object(torch._C, "_accelerator_setAllocatorSettings") as set_settings,
gpu_worker.Worker._scoped_allocator_max_split(SimpleNamespace(), 20),
):
pass
snapshot.assert_not_called()
set_settings.assert_not_called()
@pytest.mark.parametrize("kv_cache_memory_bytes", [None, 1])
def test_memory_profile_bounds_decode_logits_rows(monkeypatch, kv_cache_memory_bytes):
"""ROCm decode workspace uses max_num_seqs during startup profiling."""
from vllm.config import get_current_vllm_config_or_none
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _max_decode_logits_rows
config = SimpleNamespace(
scheduler_config=SimpleNamespace(max_num_seqs=16),
speculative_config=SimpleNamespace(num_speculative_tokens=5),
)
class Profiled(Exception):
pass
def profile_run(*, randomize_inputs=False):
assert randomize_inputs is True
# Without the config context, the helper falls back to all 32768
# batched tokens, which would reserve 128 GiB at 1M context.
assert _max_decode_logits_rows(32768) == 16 * (1 + 5)
raise Profiled
worker = SimpleNamespace(
vllm_config=config,
randomize_dummy_inputs=True,
cache_config=SimpleNamespace(kv_cache_memory_bytes=kv_cache_memory_bytes),
model_runner=SimpleNamespace(profile_run=profile_run, model_memory_usage=0),
init_snapshot=SimpleNamespace(free_memory=2),
_scoped_allocator_max_split=lambda **kwargs: nullcontext(),
)
monkeypatch.setattr(gpu_worker, "maybe_apply_startup_plan", lambda _: None)
monkeypatch.setattr(
gpu_worker, "memory_profiling", lambda *args, **kwargs: nullcontext()
)
assert get_current_vllm_config_or_none() is None
with pytest.raises(Profiled):
gpu_worker.Worker.determine_available_memory(worker)
assert get_current_vllm_config_or_none() is None
# Startup-plan persistence (vllm/v1/worker/startup_plan.py), applied and
# saved by Worker.determine_available_memory / compile_or_warm_up_model.
def _plan_worker(config_hash="abc123", free_memory=78 * GiB_bytes, kv_bytes=None):
"""The minimal Worker surface the startup-plan entry points touch."""
return SimpleNamespace(
vllm_config=SimpleNamespace(compute_hash=lambda: config_hash),
rank=0,
parallel_config=SimpleNamespace(world_size=1),
init_snapshot=SimpleNamespace(free_memory=free_memory),
cache_config=SimpleNamespace(kv_cache_memory_bytes=kv_bytes),
)
def _plan_platform(name="NVIDIA H100 PCIe"):
return SimpleNamespace(
get_device_name=lambda device_id=0: name,
get_device_total_memory=lambda device_id=0: 80 * GiB_bytes,
get_device_capability=lambda device_id=0: (9, 0),
)
@pytest.fixture
def plan_env(monkeypatch: pytest.MonkeyPatch, tmp_path):
"""Enable the startup plan, isolated under a tmp cache root."""
monkeypatch.setenv("VLLM_ENABLE_STARTUP_PLAN", "1")
monkeypatch.setenv("VLLM_CACHE_ROOT", str(tmp_path))
with patch.object(startup_plan, "current_platform", _plan_platform()):
yield
def test_startup_plan_fingerprint_sensitivity(plan_env):
"""The fingerprint is the OOM-safety key: stable for identical inputs,
different for anything the profiled value depends on."""
fp = startup_plan.compute_plan_fingerprint
base = fp(_plan_worker().vllm_config, 0, 1)
assert base == fp(_plan_worker().vllm_config, 0, 1)
assert base != fp(_plan_worker("other").vllm_config, 0, 1)
assert base != fp(_plan_worker().vllm_config, 1, 2)
with patch.object(startup_plan, "current_platform", _plan_platform("NVIDIA A100")):
assert base != fp(_plan_worker().vllm_config, 0, 1)
with patch("vllm.__version__", "0.0.0+plan-test"):
assert base != fp(_plan_worker().vllm_config, 0, 1)
def test_startup_plan_apply_gate(plan_env):
"""Only a fingerprint-matching, memory-safe plan is ever applied."""
maybe_save_startup_plan(_plan_worker(), 50 * GiB_bytes)
applied = _plan_worker()
maybe_apply_startup_plan(applied)
assert applied.cache_config.kv_cache_memory_bytes == 50 * GiB_bytes
less_memory = _plan_worker(free_memory=60 * GiB_bytes)
other_config = _plan_worker(config_hash="zzz999")
for refused in (less_memory, other_config):
maybe_apply_startup_plan(refused)
assert refused.cache_config.kv_cache_memory_bytes is None
# An explicit --kv-cache-memory is never overridden.
explicit = _plan_worker(kv_bytes=7 * GiB_bytes)
maybe_apply_startup_plan(explicit)
assert explicit.cache_config.kv_cache_memory_bytes == 7 * GiB_bytes
# Memory accounting of the profiling run (Worker.determine_available_memory).
# The fallback reads only the sign of the measured drop and this process's torch
# reservation; free memory is only logged, so no amount here is a device size.
ANY_FREE_MEMORY = 8 * GiB_bytes
MEASURED_DROP = 4 * GiB_bytes
TORCH_RESERVED = 3 * GiB_bytes
RELEASED_BY_OTHERS = 2 * GiB_bytes
def _snapshot(free_memory, torch_memory=0):
return SimpleNamespace(free_memory=free_memory, torch_memory=torch_memory)
def _profile_result(consumed, reserved_before=0, reserved_after=0):
"""A result whose free-memory readings agree with `consumed`, which
`memory_profiling` derives as the drop in free memory, negative when it grew."""
return SimpleNamespace(
total_consumed=consumed,
transient_peak_headroom=0,
before_create=_snapshot(ANY_FREE_MEMORY, reserved_before),
after_profile=_snapshot(ANY_FREE_MEMORY - consumed, reserved_after),
)
@pytest.fixture
def rocm(request):
with patch.object(
gpu_worker, "current_platform", SimpleNamespace(is_rocm=lambda: request.param)
):
yield request.param
@pytest.mark.parametrize("rocm", [True, False], indirect=True)
def test_profiling_fallback_declines_when_free_memory_dropped(rocm):
"""The profiling measurement is kept as-is whenever free memory dropped."""
result = _profile_result(consumed=MEASURED_DROP)
assert maybe_rocm_profiling_fallback(result) is None
@pytest.mark.parametrize("rocm", [True], indirect=True)
def test_profiling_fallback_replaces_a_released_measurement(rocm):
"""A negative measurement describes the rest of the device, so it is replaced
by this process's reservation, which the rest of the device cannot move."""
result = _profile_result(
consumed=-RELEASED_BY_OTHERS,
reserved_after=TORCH_RESERVED,
)
assert maybe_rocm_profiling_fallback(result) == TORCH_RESERVED
@pytest.mark.parametrize("rocm", [True], indirect=True)
def test_profiling_fallback_never_returns_a_negative_amount(rocm):
"""A reservation that shrank across the run cannot become negative usage."""
result = _profile_result(
consumed=-RELEASED_BY_OTHERS,
reserved_before=TORCH_RESERVED,
reserved_after=0,
)
assert maybe_rocm_profiling_fallback(result) == 0
@pytest.mark.parametrize("rocm", [False], indirect=True)
def test_profiling_fallback_declines_off_rocm(rocm):
"""Platforms that account frees eagerly keep reporting the error, so the
caller's assertion stays reachable there."""
result = _profile_result(consumed=-RELEASED_BY_OTHERS)
assert maybe_rocm_profiling_fallback(result) is None
class _OrderedHandle:
"""Send handle that logs when it is waited."""
def __init__(self, log: list[str], name: str):
self.log = log
self.name = name
def is_completed(self) -> bool:
return True
def wait(self) -> None:
self.log.append(f"wait:{self.name}")
def test_execute_model_waits_previous_pp_send_before_forward(
monkeypatch: pytest.MonkeyPatch,
):
"""Previous device handles are waited before the forward pass; the
metadata handle is left to the GroupCoordinator's reaper."""
import torch
from vllm.sequence import IntermediateTensors
log: list[str] = []
previous_tensor_send = _OrderedHandle(log, "prev-tensor")
metadata_handle = _OrderedHandle(log, "meta")
tensor_handle = _OrderedHandle(log, "tensor")
def isend_tensor_dict(tensors, all_gather_group=None, all_gather_tensors=None):
log.append("isend")
return [metadata_handle, tensor_handle]
pp_group = SimpleNamespace(
is_first_rank=True,
is_last_rank=False,
isend_tensor_dict=isend_tensor_dict,
)
monkeypatch.setattr(gpu_worker, "get_pp_group", lambda: pp_group)
monkeypatch.setattr(gpu_worker, "get_tp_group", lambda: SimpleNamespace())
def run_model(scheduler_output, intermediate_tensors):
log.append("forward")
return IntermediateTensors({"hidden_states": torch.zeros(1)})
worker = SimpleNamespace(
vllm_config=SimpleNamespace(
parallel_config=SimpleNamespace(
pipeline_parallel_size=2, distributed_executor_backend="mp"
),
),
use_v2_model_runner=True,
model_runner=SimpleNamespace(execute_model=run_model, is_pooling_model=False),
annotate_profile=lambda scheduler_output: nullcontext(),
_pp_send_work=[previous_tensor_send],
)
scheduler_output = SimpleNamespace(
total_num_scheduled_tokens=4, num_scheduled_tokens={"r0": 4}
)
assert gpu_worker.Worker.execute_model(worker, scheduler_output) is None
assert log == ["wait:prev-tensor", "forward", "isend"]
assert worker._pp_send_work == [tensor_handle]
def test_jit_monitor_activation_follows_enable_jit_warmup(
monkeypatch: pytest.MonkeyPatch,
):
"""The post-warmup JIT monitor must stay off when JIT warmup is disabled
(e.g. by enforce_eager): runtime compilation is then expected, and
warning/erroring on it would be noise."""
from vllm.utils import jit_monitor
calls = []
monkeypatch.setattr(jit_monitor, "activate", lambda **kwargs: calls.append(kwargs))
def worker(enable_jit_warmup):
return SimpleNamespace(
vllm_config=SimpleNamespace(
kernel_config=SimpleNamespace(enable_jit_warmup=enable_jit_warmup)
),
observability_config=SimpleNamespace(
jit_monitor_mode="warn", jit_monitor_verbose=False
),
)
gpu_worker.Worker._maybe_activate_jit_monitor(worker(True))
assert calls == [{"mode": "warn", "verbose": False}]
calls.clear()
gpu_worker.Worker._maybe_activate_jit_monitor(worker(False))
assert calls == []
@@ -1,172 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from contextlib import AbstractContextManager
from types import SimpleNamespace
from typing import Any, cast
import pytest
import torch
import vllm.v1.hisparse.binding as hisparse_binding
import vllm.v1.worker.gpu.attn_utils as attn_utils
import vllm.v1.worker.gpu_model_runner as gpu_model_runner
from vllm.v1.worker.gpu_worker import Worker
class _AllocationScope(AbstractContextManager):
def __init__(self) -> None:
self.active = False
def __enter__(self):
assert not self.active
self.active = True
return self
def __exit__(self, *args: Any) -> None:
assert self.active
self.active = False
@pytest.mark.parametrize("hisparse", [False, True])
def test_mrv2_kv_pool_only_wraps_backing_allocation(monkeypatch, hisparse) -> None:
scope = _AllocationScope()
kv_caches = {"layer": torch.empty(0)}
def allocate(*args, **kwargs):
assert scope.active
return kv_caches
def bind(*args, **kwargs):
assert not scope.active
monkeypatch.setattr(attn_utils, "allocate_kv_cache", allocate)
monkeypatch.setattr(attn_utils, "bind_kv_cache_to_layers", bind)
monkeypatch.setattr(attn_utils, "get_shared_kv_cache_layers", lambda config: {})
hisparse_bindings = []
if hisparse:
host_pool = SimpleNamespace()
def bind_hisparse(**kwargs):
hisparse_bindings.append(kwargs)
assert scope.active
assert kwargs["kv_caches"] is kv_caches
assert kwargs["host_pool"] is host_pool
return [
SimpleNamespace(
view=SimpleNamespace(cache=torch.empty(1, 1, 1), block_size=1),
runtime=SimpleNamespace(),
)
]
monkeypatch.setattr(
hisparse_binding,
"get_hisparse_host_pool",
lambda vllm_config, kv_cache_config: host_pool,
)
monkeypatch.setattr(hisparse_binding, "allocate_hisparse_kv_caches", allocate)
monkeypatch.setattr(hisparse_binding, "bind_hisparse_kv_caches", bind_hisparse)
config = SimpleNamespace(
attention_config=SimpleNamespace(
hisparse_config=object() if hisparse else None
),
scheduler_config=SimpleNamespace(max_num_seqs=1, max_num_batched_tokens=1),
cache_config=SimpleNamespace(get_resolved_kv_cache_layout=lambda: None),
model_config=SimpleNamespace(hf_config=SimpleNamespace(model_type="test")),
)
result = attn_utils.init_kv_cache(
{},
SimpleNamespace(kv_cache_groups=[]),
torch.device("cpu"),
[],
config,
kv_cache_allocation_context=scope,
block_tables=SimpleNamespace(),
)
assert len(hisparse_bindings) == int(hisparse)
assert result is kv_caches
assert not scope.active
def test_mrv1_kv_pool_only_wraps_backing_allocation(monkeypatch) -> None:
scope = _AllocationScope()
kv_caches = {"layer": torch.empty(0)}
def allocate(*args, **kwargs):
assert scope.active
return kv_caches
def bind(*args, **kwargs):
assert not scope.active
monkeypatch.setattr(gpu_model_runner, "allocate_kv_cache", allocate)
monkeypatch.setattr(gpu_model_runner, "bind_kv_cache", bind)
runner = SimpleNamespace(
device=torch.device("cpu"),
cache_config=SimpleNamespace(get_resolved_kv_cache_layout=lambda: None),
shared_kv_cache_layers={},
model_config=SimpleNamespace(hf_config=SimpleNamespace(model_type="test")),
compilation_config=SimpleNamespace(static_forward_context={}),
kv_caches=[],
attn_groups=[],
speculative_config=None,
)
result = gpu_model_runner.GPUModelRunner.initialize_kv_cache_tensors(
runner,
SimpleNamespace(kv_cache_groups=[]),
[],
kv_cache_allocation_context=scope,
)
assert result is kv_caches
assert not scope.active
def test_kv_wake_does_not_run_model_runner_recovery() -> None:
model = torch.nn.Module()
model.register_buffer("_k_scale", torch.tensor(0.5))
model.register_buffer("_v_scale", torch.tensor(0.25))
class Runner:
def __init__(self) -> None:
self.model = model
self.layout_tensors = tuple(torch.tensor([i]) for i in range(5))
self.recovery_calls = 0
def post_kv_cache_wake_up(self) -> None:
self.recovery_calls += 1
self.model.get_buffer("_k_scale").fill_(1.0)
self.model.get_buffer("_v_scale").fill_(1.0)
self.layout_tensors = tuple(torch.tensor([i]) for i in range(5))
runner = Runner()
worker = cast(
Worker,
SimpleNamespace(
sleep_mode_backend=SimpleNamespace(resume=lambda tags: None),
_sleep_saved_buffers={},
_sleep_saved_draft_buffers={},
model_runner=runner,
synchronize_device=lambda: None,
vllm_config=SimpleNamespace(
model_config=SimpleNamespace(enable_nccl_comm_suspend=False)
),
),
)
layout_tensors = runner.layout_tensors
layout_ptrs = tuple(t.data_ptr() for t in layout_tensors)
Worker.wake_up(worker, tags=["kv_cache"])
assert runner.recovery_calls == 0
assert model.get_buffer("_k_scale").item() == 0.5
assert model.get_buffer("_v_scale").item() == 0.25
assert all(
actual is expected
for actual, expected in zip(runner.layout_tensors, layout_tensors, strict=True)
)
assert tuple(t.data_ptr() for t in runner.layout_tensors) == layout_ptrs
@@ -1,305 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
from vllm.entrypoints.pooling.scoring.utils import compute_maxsim_score
from vllm.pooling_params import LateInteractionParams, PoolingParams
from vllm.v1.pool.late_interaction import (
LATE_INTERACTION_MODE_CACHE_QUERY,
build_late_interaction_doc_params,
build_late_interaction_query_params,
compute_maxsim_score_batched,
)
from vllm.v1.pool.late_interaction_runner import LateInteractionRunner
def _make_pooling_params(
late_interaction_params: LateInteractionParams,
) -> PoolingParams:
return PoolingParams(
task="token_embed",
late_interaction_params=late_interaction_params,
)
def test_postprocess_scores_and_releases_query_cache():
runner = LateInteractionRunner()
query_key = "query-0"
query_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
doc_emb = torch.tensor([[1.0, 0.0], [0.5, 0.5], [0.0, 1.0]], dtype=torch.float32)
query_params = _make_pooling_params(
build_late_interaction_query_params(query_key=query_key, query_uses=1)
)
query_output = runner.postprocess_pooler_output(
raw_pooler_output=[query_emb],
pooling_params=[query_params],
req_ids=["query-req"],
finished_mask=[True],
)
assert isinstance(query_output, list)
assert query_output[0] is not None
assert query_output[0].shape == torch.Size([])
doc_params = _make_pooling_params(
build_late_interaction_doc_params(query_key=query_key)
)
doc_output = runner.postprocess_pooler_output(
raw_pooler_output=[doc_emb],
pooling_params=[doc_params],
req_ids=["doc-req"],
finished_mask=[True],
)
assert isinstance(doc_output, list)
assert doc_output[0] is not None
assert torch.allclose(doc_output[0], compute_maxsim_score(query_emb, doc_emb))
with pytest.raises(ValueError, match="query cache miss"):
runner.postprocess_pooler_output(
raw_pooler_output=[doc_emb],
pooling_params=[doc_params],
req_ids=["doc-req-2"],
finished_mask=[True],
)
def test_postprocess_scores_docs_in_batch():
runner = LateInteractionRunner()
query_key = "query-batch"
query_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
doc_emb_1 = torch.tensor([[1.0, 0.0], [0.5, 0.5]], dtype=torch.float32)
doc_emb_2 = torch.tensor([[0.0, 1.0], [0.3, 0.7], [1.0, 0.0]], dtype=torch.float32)
query_params = _make_pooling_params(
build_late_interaction_query_params(query_key=query_key, query_uses=2)
)
runner.postprocess_pooler_output(
raw_pooler_output=[query_emb],
pooling_params=[query_params],
req_ids=["query-req"],
finished_mask=[True],
)
doc_params = _make_pooling_params(
build_late_interaction_doc_params(query_key=query_key)
)
doc_output = runner.postprocess_pooler_output(
raw_pooler_output=[doc_emb_1, doc_emb_2],
pooling_params=[doc_params, doc_params],
req_ids=["doc-req-1", "doc-req-2"],
finished_mask=[True, True],
)
assert isinstance(doc_output, list)
assert doc_output[0] is not None
assert doc_output[1] is not None
assert torch.allclose(doc_output[0], compute_maxsim_score(query_emb, doc_emb_1))
assert torch.allclose(doc_output[1], compute_maxsim_score(query_emb, doc_emb_2))
with pytest.raises(ValueError, match="query cache miss"):
runner.postprocess_pooler_output(
raw_pooler_output=[doc_emb_1],
pooling_params=[doc_params],
req_ids=["doc-req-3"],
finished_mask=[True],
)
def test_finished_request_releases_unscored_doc_use():
runner = LateInteractionRunner()
query_key = "query-cancel"
query_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
doc_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
query_params = _make_pooling_params(
build_late_interaction_query_params(query_key=query_key, query_uses=1)
)
runner.postprocess_pooler_output(
raw_pooler_output=[query_emb],
pooling_params=[query_params],
req_ids=["query-req"],
finished_mask=[True],
)
doc_params = _make_pooling_params(
build_late_interaction_doc_params(query_key=query_key)
)
runner.register_request("doc-req", doc_params)
runner.on_requests_finished({"doc-req"})
with pytest.raises(ValueError, match="query cache miss"):
runner.postprocess_pooler_output(
raw_pooler_output=[doc_emb],
pooling_params=[doc_params],
req_ids=["doc-req-retry"],
finished_mask=[True],
)
@pytest.mark.skip_global_cleanup
def test_release_queries_is_targeted_and_idempotent():
runner = LateInteractionRunner()
query_emb = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float32)
for query_key in ("query-release", "query-keep"):
query_params = _make_pooling_params(
build_late_interaction_query_params(query_key=query_key, query_uses=1)
)
runner.postprocess_pooler_output(
raw_pooler_output=[query_emb],
pooling_params=[query_params],
req_ids=[f"{query_key}-req"],
finished_mask=[True],
)
released_doc_params = _make_pooling_params(
build_late_interaction_doc_params(query_key="query-release")
)
kept_doc_params = _make_pooling_params(
build_late_interaction_doc_params(query_key="query-keep")
)
runner.register_request("released-doc", released_doc_params)
runner.register_request("kept-doc", kept_doc_params)
runner.release_queries(["query-release"])
runner.release_queries(["query-release"])
with pytest.raises(ValueError, match="query cache miss"):
runner.postprocess_pooler_output(
raw_pooler_output=[query_emb],
pooling_params=[released_doc_params],
req_ids=["released-doc"],
finished_mask=[True],
)
kept_output = runner.postprocess_pooler_output(
raw_pooler_output=[query_emb],
pooling_params=[kept_doc_params],
req_ids=["kept-doc"],
finished_mask=[True],
)
assert isinstance(kept_output, list)
assert kept_output[0] is not None
def test_invalid_query_uses_raises():
runner = LateInteractionRunner()
bad_meta = LateInteractionParams(
mode=LATE_INTERACTION_MODE_CACHE_QUERY,
query_key="query-bad",
)
bad_meta.query_uses = "bad-int"
bad_query_params = _make_pooling_params(bad_meta)
with pytest.raises(ValueError, match="must be an integer value"):
runner.postprocess_pooler_output(
raw_pooler_output=[torch.ones((2, 2), dtype=torch.float32)],
pooling_params=[bad_query_params],
req_ids=["query-req"],
finished_mask=[True],
)
# ---------------------------------------------------------------------------
# Fused Triton scoring path (PR #40337).
# ---------------------------------------------------------------------------
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
def test_score_flash_matches_fp64_oracle():
"""Shared-query scoring through the fused kernel must match a per-pair
fp64 MaxSim oracle on ragged doc lengths, including length-1 docs."""
torch.manual_seed(0)
d = 128
q = torch.randn(32, d, device="cuda", dtype=torch.float16)
doc_lengths = [180, 37, 512, 1, 300, 64, 1030, 256]
docs = [
torch.randn(ld, d, device="cuda", dtype=torch.float16) for ld in doc_lengths
]
runner = LateInteractionRunner()
assert runner._flash_enabled
scores = runner._score([q] * len(docs), docs)
assert runner._flash_enabled, "kernel path must not have fallen back"
for i, doc in enumerate(docs):
ref = (q.double() @ doc.double().T).max(dim=1).values.sum().float()
torch.testing.assert_close(
scores[i].to(torch.float32), ref, atol=5e-2, rtol=1e-3
)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
def test_score_multi_query_uses_reference_path():
"""Distinct queries per pair route to the reference scorer and agree
with it exactly (no kernel dispatch for the N:N pattern)."""
torch.manual_seed(1)
d = 128
queries = [torch.randn(16, d, device="cuda") for _ in range(3)]
docs = [torch.randn(ld, d, device="cuda") for ld in (50, 3, 77)]
runner = LateInteractionRunner()
scores = runner._score(queries, docs)
ref = compute_maxsim_score_batched(queries, docs)
for s, r in zip(scores, ref):
torch.testing.assert_close(s, r)
def test_score_flash_failure_disables_and_falls_back(monkeypatch):
"""A kernel failure must serve the batch via the reference scorer and
disable the kernel path for the rest of the process."""
runner = LateInteractionRunner()
runner._flash_enabled = True
def _boom(query, docs):
raise RuntimeError("synthetic kernel failure")
monkeypatch.setattr(runner, "_score_flash_shared_query", _boom)
q = torch.randn(8, 32)
docs = [torch.randn(5, 32), torch.randn(7, 32)]
# CPU tensors already skip the kernel; force the dispatch condition.
monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))
scores = runner._score([q, q], docs)
assert not runner._flash_enabled
ref = compute_maxsim_score_batched([q, q], docs)
for s, r in zip(scores, ref):
torch.testing.assert_close(s, r)
def test_disabled_flag_uses_reference_path():
runner = LateInteractionRunner(enable_flash=False)
assert not runner._flash_enabled
# ---------------------------------------------------------------------------
# Autotune config pruning.
# ---------------------------------------------------------------------------
def _prune(monkeypatch, budget: int, named_args: dict):
from vllm.v1.pool.flash_maxsim import _common
monkeypatch.setattr(_common, "_smem_budget", lambda: budget)
return _common._prune_configs(_common._get_configs(), named_args)
def _est(cfg, d_pad: int) -> int:
bq, bd = cfg.kwargs["BLOCK_Q"], cfg.kwargs["BLOCK_D"]
return (bq * d_pad + bd * d_pad) * 2 + bq * bd * 4
def test_prune_configs_uses_padded_dim(monkeypatch):
"""d=513 pads to 1024: survivors must fit the budget at d_pad, not at
the un-padded d (which would admit ~2x-oversized tiles)."""
budget = 166_912 # A100 opt-in
survivors = _prune(monkeypatch, budget, {"Lq": 1024, "d": 513, "d_pad": 1024})
assert survivors
assert all(_est(c, 1024) <= budget for c in survivors)
def test_prune_configs_no_rejected_fallback(monkeypatch):
"""When nothing fits, the fallback is the single smallest-footprint
config — never a slice of rejected configs."""
from vllm.v1.pool.flash_maxsim import _common
survivors = _prune(monkeypatch, 10_000, {"Lq": 1024, "d_pad": 1024})
assert len(survivors) == 1
smallest = min(_common._get_configs(), key=lambda c: _est(c, 1024))
assert survivors[0].kwargs == smallest.kwargs
File diff suppressed because it is too large Load Diff