[Model] Support Qwen3.8-Flash-Next (#53896)
Signed-off-by: huanghaoyan.hhy <huanghaoyan.hhy@alibaba-inc.com> Signed-off-by: andyluo7 <andy.luo@amd.com> Signed-off-by: lishunyang12 <lishunyang03@gmail.com> Signed-off-by: Harry Huang <huanghaoyan.hhy@alibaba-inc.com> Signed-off-by: Thien Tran <gau.nernst@yahoo.com.sg> Signed-off-by: Isotr0py <Isotr0py@outlook.com> Signed-off-by: Lucas Wilkinson <lwilkins@redhat.com> Signed-off-by: Yifan Qiao <yifanqiao@inferact.ai> Signed-off-by: zjy0516 <riverclouds.zhu@qq.com> Co-authored-by: zjy0516 <riverclouds.zhu@qq.com> Co-authored-by: KungYork <firelikest@163.com> Co-authored-by: Thien Tran <gau.nernst@yahoo.com.sg> Co-authored-by: Yifan Qiao <yifanqiao@inferact.ai> Co-authored-by: andyluo7 <43718156+andyluo7@users.noreply.github.com> Co-authored-by: Isotr0py <mozf@inferact.ai> Co-authored-by: andyluo7 <andy.luo@amd.com> Co-authored-by: OpenAI Codex <noreply@openai.com> Co-authored-by: lishunyang12 <lishunyang03@gmail.com> Co-authored-by: Vadim Gimpelson <156319763+vadiklyutiy@users.noreply.github.com> Co-authored-by: Isotr0py <Isotr0py@outlook.com> Co-authored-by: Lucas Wilkinson <lwilkins@redhat.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
co-authored by
zjy0516
KungYork
Thien Tran
Yifan Qiao
andyluo7
Isotr0py
andyluo7
OpenAI Codex
lishunyang12
Vadim Gimpelson
Isotr0py
Lucas Wilkinson
Claude Opus 5
OpenAI Codex
parent
687db59744
commit
e126687a9a
@@ -9,23 +9,34 @@ block dim (a contiguous region per layer) or inside it (all layers' pages within
|
||||
block); the allocation is the same either way.
|
||||
"""
|
||||
|
||||
from dataclasses import replace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.config import CacheConfig
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheManager
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
_get_kv_cache_bytes_per_block,
|
||||
_get_packed_kv_cache_groups,
|
||||
_pool_bytes_per_block,
|
||||
generate_scheduler_kv_cache_config,
|
||||
get_kv_cache_config_from_groups,
|
||||
get_kv_cache_groups,
|
||||
resolve_kv_cache_block_sizes,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheSpec,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
SlidingWindowMLASpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
iter_layer_specs,
|
||||
)
|
||||
from vllm.v1.worker.utils import allocate_kv_cache
|
||||
|
||||
@@ -86,6 +97,307 @@ def _bind(config, layout: str):
|
||||
return allocate_kv_cache(config, torch.device("cpu"), KVCacheLayout[layout], None)
|
||||
|
||||
|
||||
MAIN_KV_PAGE_BYTES = 2_048
|
||||
COMPRESSED_PAGE_BYTES = 128
|
||||
NUM_CACHE_TUPLES = 3
|
||||
BYTES_PER_BLOCK = NUM_CACHE_TUPLES * (MAIN_KV_PAGE_BYTES + COMPRESSED_PAGE_BYTES)
|
||||
|
||||
|
||||
def _main_kv_name(layer_index: int) -> str:
|
||||
return f"model.layers.{layer_index}.self_attn"
|
||||
|
||||
|
||||
def _compressed_name(layer_index: int) -> str:
|
||||
return f"model.layers.{layer_index}.self_attn.indexer.compressed_key_cache"
|
||||
|
||||
|
||||
def _compressor_state_name(layer_index: int) -> str:
|
||||
return f"model.layers.{layer_index}.self_attn.indexer.raw_key_cache"
|
||||
|
||||
|
||||
def _make_csa_linear_specs(
|
||||
num_mamba: int = 7,
|
||||
num_tuples: int = NUM_CACHE_TUPLES,
|
||||
) -> dict[str, KVCacheSpec]:
|
||||
specs: dict[str, KVCacheSpec] = {}
|
||||
for layer_index in range(num_mamba):
|
||||
specs[f"model.layers.{layer_index}.linear_attn"] = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((32,),),
|
||||
dtypes=(torch.bfloat16,),
|
||||
)
|
||||
specs["model.layers.0.ple"] = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((24,),),
|
||||
dtypes=(torch.bfloat16,),
|
||||
tp_replicated=True,
|
||||
)
|
||||
for layer_index in range(num_tuples):
|
||||
specs[_main_kv_name(layer_index)] = FullAttentionSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=2,
|
||||
head_size=16,
|
||||
head_size_v=16,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
specs[_compressed_name(layer_index)] = MLAAttentionSpec(
|
||||
block_size=16,
|
||||
num_kv_heads=1,
|
||||
head_size=16,
|
||||
dtype=torch.bfloat16,
|
||||
tokens_per_state=4,
|
||||
)
|
||||
specs[_compressor_state_name(layer_index)] = CircularBufferSpec(
|
||||
block_size=4,
|
||||
num_kv_heads=1,
|
||||
head_size=8,
|
||||
head_size_v=0,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
return specs
|
||||
|
||||
|
||||
def _shared_layout_config():
|
||||
config = _mock_vllm_config("BLNHC")
|
||||
config.scheduler_config.disable_hybrid_kv_cache_manager = False
|
||||
config.speculative_config = None
|
||||
config.model_config.max_model_len = 16
|
||||
config.model_config.get_total_num_hidden_layers.return_value = 64
|
||||
config.model_config.get_total_num_kv_heads.return_value = 2
|
||||
config.model_config.get_num_kv_heads.return_value = 2
|
||||
config.parallel_config.pipeline_parallel_size = 1
|
||||
config.parallel_config.decode_context_parallel_size = 1
|
||||
config.cache_config.block_size = 16
|
||||
config.cache_config.enable_prefix_caching = False
|
||||
config.cache_config.prefix_match_unit = None
|
||||
config.cache_config.mamba_cache_mode = "none"
|
||||
return config
|
||||
|
||||
|
||||
class TestCSALinearGrouping:
|
||||
"""A CSA + linear-attention model (sparse attention with a compressor ring,
|
||||
plus sharded GDN and one TP-replicated PLE state) goes through the generic
|
||||
packed-group path; no model-specific branch is involved."""
|
||||
|
||||
@staticmethod
|
||||
def _mamba_groups(groups):
|
||||
"""(group, per-layer mamba spec) for every group holding mamba state."""
|
||||
out = []
|
||||
for group in groups:
|
||||
spec = next(iter(iter_layer_specs(group.kv_cache_spec)))
|
||||
if isinstance(spec, MambaSpec):
|
||||
out.append((group, spec))
|
||||
return out
|
||||
|
||||
def test_replicated_state_gets_its_own_group(self):
|
||||
"""The PLE state is TP-replicated and a different size, so it must not
|
||||
share a manager group with the sharded GDN states (the NIXL worker
|
||||
requires exactly one single-layer replicated group)."""
|
||||
groups = get_kv_cache_groups(_shared_layout_config(), _make_csa_linear_specs())
|
||||
|
||||
mamba_groups = self._mamba_groups(groups)
|
||||
replicated = [g for g, spec in mamba_groups if spec.tp_replicated]
|
||||
assert len(replicated) == 1
|
||||
assert replicated[0].layer_names == ["model.layers.0.ple"]
|
||||
sharded = [g for g, spec in mamba_groups if not spec.tp_replicated]
|
||||
assert sharded, "GDN states must keep their own groups"
|
||||
assert sorted(n for g in sharded for n in g.layer_names) == sorted(
|
||||
f"model.layers.{i}.linear_attn" for i in range(7)
|
||||
)
|
||||
|
||||
def test_roles_land_in_separate_groups(self):
|
||||
groups = get_kv_cache_groups(_shared_layout_config(), _make_csa_linear_specs())
|
||||
|
||||
owner = next(g for g in groups if _main_kv_name(0) in g.layer_names)
|
||||
assert sorted(owner.layer_names) == sorted(
|
||||
[
|
||||
*(_main_kv_name(i) for i in range(NUM_CACHE_TUPLES)),
|
||||
*(_compressed_name(i) for i in range(NUM_CACHE_TUPLES)),
|
||||
]
|
||||
)
|
||||
assert owner.kv_cache_spec.prefix_cacheable
|
||||
|
||||
scratch = next(g for g in groups if _compressor_state_name(0) in g.layer_names)
|
||||
assert scratch.layer_names == [
|
||||
_compressor_state_name(i) for i in range(NUM_CACHE_TUPLES)
|
||||
]
|
||||
assert not scratch.kv_cache_spec.prefix_cacheable
|
||||
|
||||
def test_every_group_fits_one_packed_block(self):
|
||||
config = _shared_layout_config()
|
||||
groups = get_kv_cache_groups(config, _make_csa_linear_specs())
|
||||
bytes_per_block = _get_kv_cache_bytes_per_block(groups)
|
||||
|
||||
pages = _pages(groups)
|
||||
for group in groups:
|
||||
assert sum(pages[n] for n in group.layer_names) <= bytes_per_block
|
||||
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=bytes_per_block * 32
|
||||
)
|
||||
assert kv_cache_config.num_blocks == 32
|
||||
# Groups overlay from byte 0 of each block, so a layer never addresses
|
||||
# past the block it belongs to.
|
||||
for tensor in kv_cache_config.kv_cache_tensors:
|
||||
assert tensor.block_stride == bytes_per_block
|
||||
assert tensor.offset < bytes_per_block
|
||||
|
||||
def test_scratch_group_survives_computed_block_truncation(self):
|
||||
"""The scratch group contributes no computed blocks, so truncating a
|
||||
lookup result must skip it: its block size is the ring capacity, which
|
||||
neither divides the hit length nor bounds the (empty) block list."""
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
groups = get_kv_cache_groups(config, _make_csa_linear_specs())
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=BYTES_PER_BLOCK * 64
|
||||
)
|
||||
scheduler_config = generate_scheduler_kv_cache_config([kv_cache_config])
|
||||
manager = KVCacheManager(
|
||||
scheduler_config,
|
||||
max_model_len=8192,
|
||||
enable_caching=True,
|
||||
hash_block_size=16,
|
||||
scheduler_block_size=16,
|
||||
)
|
||||
blocks = manager.create_kv_cache_blocks(
|
||||
tuple(
|
||||
manager.block_pool.get_new_blocks(3)
|
||||
if group.kv_cache_spec.prefix_cacheable
|
||||
else []
|
||||
for group in scheduler_config.kv_cache_groups
|
||||
)
|
||||
)
|
||||
truncated = manager.truncate_computed_blocks(blocks, 48)
|
||||
scratch_index = next(
|
||||
i
|
||||
for i, group in enumerate(scheduler_config.kv_cache_groups)
|
||||
if not group.kv_cache_spec.prefix_cacheable
|
||||
)
|
||||
assert truncated.blocks[scratch_index] == []
|
||||
|
||||
def test_prefix_hits_respect_compression_alignment(self):
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
config.cache_config.prefix_match_unit = 16
|
||||
config.cache_config.mamba_cache_mode = "align"
|
||||
specs = {
|
||||
name: replace(spec, mamba_cache_mode="align")
|
||||
if isinstance(spec, MambaSpec)
|
||||
else spec
|
||||
for name, spec in _make_csa_linear_specs(num_tuples=1).items()
|
||||
}
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=8 * MAIN_KV_PAGE_BYTES
|
||||
)
|
||||
assert resolve_kv_cache_block_sizes(kv_cache_config, config) == (16, 16)
|
||||
|
||||
# 2 tokens is not a multiple of the compression ratio 4: a prefix hit
|
||||
# could land inside a partially filled compressed state.
|
||||
config.cache_config.prefix_match_unit = 2
|
||||
with pytest.raises(ValueError, match="per-state compression"):
|
||||
resolve_kv_cache_block_sizes(kv_cache_config, config)
|
||||
|
||||
def test_scratch_ring_does_not_drag_hash_granularity(self):
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
config.cache_config.mamba_cache_mode = "align"
|
||||
specs = {
|
||||
name: replace(spec, mamba_cache_mode="align")
|
||||
if isinstance(spec, MambaSpec)
|
||||
else spec
|
||||
for name, spec in _make_csa_linear_specs(num_tuples=1).items()
|
||||
}
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=8 * MAIN_KV_PAGE_BYTES
|
||||
)
|
||||
# The hash granularity is the GCD over prefix-cacheable groups only;
|
||||
# the 4-token scratch ring is excluded (it would drag it to 4).
|
||||
assert resolve_kv_cache_block_sizes(kv_cache_config, config) == (16, 16)
|
||||
|
||||
def test_compressed_attention_hashes_can_be_finer_than_cache_hits(self):
|
||||
config = _shared_layout_config()
|
||||
config.cache_config.enable_prefix_caching = True
|
||||
specs = {
|
||||
"compressed.4": MLAAttentionSpec(
|
||||
block_size=256,
|
||||
num_kv_heads=1,
|
||||
head_size=16,
|
||||
dtype=torch.bfloat16,
|
||||
tokens_per_state=4,
|
||||
),
|
||||
"compressed.128": MLAAttentionSpec(
|
||||
block_size=256,
|
||||
num_kv_heads=1,
|
||||
head_size=16,
|
||||
dtype=torch.bfloat16,
|
||||
tokens_per_state=128,
|
||||
),
|
||||
"compressor_state.4": SlidingWindowMLASpec(
|
||||
block_size=4,
|
||||
num_kv_heads=1,
|
||||
head_size=8,
|
||||
head_size_v=0,
|
||||
dtype=torch.bfloat16,
|
||||
sliding_window=8,
|
||||
),
|
||||
}
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
config, groups, available_memory=8 * MAIN_KV_PAGE_BYTES
|
||||
)
|
||||
|
||||
# Hashes are computed every 4 tokens, but without an align-mode Mamba
|
||||
# group cache hits remain on the 256-token scheduler boundary.
|
||||
assert resolve_kv_cache_block_sizes(kv_cache_config, config) == (256, 4)
|
||||
|
||||
@pytest.mark.parametrize("wide", ["unbalanced_attention", "unsplittable_state"])
|
||||
def test_mamba_split_measures_the_block_the_other_groups_already_force(self, wide):
|
||||
"""Whatever fixes the block stride -- a bucket with unequal layer counts
|
||||
per page size, which is emitted whole, or a single-layer state that
|
||||
cannot be split at all -- the mamba layers must be sized against it.
|
||||
Sizing them against a narrower bucket splits them past what the block
|
||||
already fits, spending a pool block per extra group for no saving."""
|
||||
config = _mock_vllm_config("BLNHC")
|
||||
config.speculative_config = None
|
||||
specs = {}
|
||||
if wide == "unbalanced_attention":
|
||||
for i in range(3):
|
||||
specs[f"wide.{i}"] = _mla(1024)
|
||||
specs["wide.odd"] = _mla(800)
|
||||
else:
|
||||
specs["wide.state"] = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((51_200,),),
|
||||
dtypes=(torch.bfloat16,),
|
||||
tp_replicated=True,
|
||||
)
|
||||
# Mixed and balanced, but far narrower than the bucket above.
|
||||
for i in range(10):
|
||||
specs[f"narrow.a.{i}"] = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=8, dtype=torch.uint8
|
||||
)
|
||||
specs[f"narrow.b.{i}"] = FullAttentionSpec(
|
||||
block_size=16, num_kv_heads=1, head_size=16, dtype=torch.uint8
|
||||
)
|
||||
for i in range(100):
|
||||
specs[f"gdn.{i}"] = MambaSpec(
|
||||
block_size=16, shapes=((512,),), dtypes=(torch.bfloat16,)
|
||||
)
|
||||
|
||||
groups = _get_packed_kv_cache_groups(config, specs)
|
||||
gdn = [g for g in groups if g.layer_names[0].startswith("gdn.")]
|
||||
|
||||
assert _get_kv_cache_bytes_per_block(groups) == sum(
|
||||
specs[name].page_size_bytes for name in specs if name.startswith("wide.")
|
||||
)
|
||||
# That block holds every GDN state at once, so the repeat pattern alone
|
||||
# decides the split; the cap must not add groups on top of it.
|
||||
assert len(gdn) == 10
|
||||
|
||||
|
||||
class TestDensePacking:
|
||||
def test_bytes_per_block_is_largest_group(self):
|
||||
groups, g1, g2 = _mixed_page_groups()
|
||||
|
||||
@@ -12,7 +12,7 @@ import pytest
|
||||
import torch
|
||||
|
||||
import vllm.v1.core.kv_cache_utils as kv_cache_utils
|
||||
from vllm.config import ModelConfig, SchedulerConfig, VllmConfig
|
||||
from vllm.config import CacheConfig, ModelConfig, SchedulerConfig, VllmConfig
|
||||
from vllm.config.kv_events import KVEventsConfig
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.multimodal.inputs import (
|
||||
@@ -37,7 +37,6 @@ from vllm.v1.core.kv_cache_utils import (
|
||||
get_kv_cache_groups,
|
||||
get_max_concurrency_for_kv_cache_config,
|
||||
get_request_block_hasher,
|
||||
group_and_unify_kv_cache_specs,
|
||||
hash_block_tokens,
|
||||
init_none_hash,
|
||||
is_kv_cache_spec_uniform,
|
||||
@@ -2226,38 +2225,6 @@ def new_swa_mla_spec(head_size=576, sliding_window=128, model_version=None):
|
||||
)
|
||||
|
||||
|
||||
def test_group_and_unify_kv_cache_specs_no_swa_mla_returns_none():
|
||||
# Without any SlidingWindowMLASpec the function does not apply.
|
||||
specs = {"mla.0": new_mla_spec(), "mla.1": new_mla_spec()}
|
||||
assert group_and_unify_kv_cache_specs(specs) is None
|
||||
|
||||
|
||||
def test_group_and_unify_kv_cache_specs_uniform_page_size_returns_none():
|
||||
# A non-DeepseekV4 model that mixes full MLA and sliding-window MLA layers
|
||||
# with a uniform page size must not fall into the DeepseekV4 tuple-packing
|
||||
# path; it should defer to the generic uniform-page-size grouping instead.
|
||||
mla_spec = new_mla_spec()
|
||||
swa_spec = new_swa_mla_spec()
|
||||
assert mla_spec.page_size_bytes == swa_spec.page_size_bytes
|
||||
specs = {"mla.0": mla_spec, "mla.1": new_mla_spec(), "swa.0": swa_spec}
|
||||
assert group_and_unify_kv_cache_specs(specs) is None
|
||||
|
||||
|
||||
def test_group_and_unify_kv_cache_specs_mixed_page_size_groups():
|
||||
# DeepseekV4-style: differing page sizes across MLA and sliding-window MLA
|
||||
# layers do require tuple packing, so grouping must still be produced.
|
||||
mla_spec = new_mla_spec()
|
||||
swa_spec = new_swa_mla_spec(head_size=1024)
|
||||
assert mla_spec.page_size_bytes != swa_spec.page_size_bytes
|
||||
specs = {"mla.0": mla_spec, "mla.1": new_mla_spec(), "swa.0": swa_spec}
|
||||
grouped = group_and_unify_kv_cache_specs(specs)
|
||||
assert grouped is not None
|
||||
# One MLA group plus one sliding-window MLA group.
|
||||
assert len(grouped) == 2
|
||||
layer_names = {name for g in grouped for name in g.kv_cache_specs}
|
||||
assert layer_names == {"mla.0", "mla.1", "swa.0"}
|
||||
|
||||
|
||||
def new_indexer_mla_spec(block_size=16):
|
||||
# Sparse-attention indexer k_cache: an MLAAttentionSpec with a much smaller
|
||||
# page size than the main MLA attention (uint8, small head), so their pages
|
||||
@@ -2270,10 +2237,30 @@ def new_indexer_mla_spec(block_size=16):
|
||||
)
|
||||
|
||||
|
||||
def test_mixed_page_size_groups_use_spec_compatibility():
|
||||
specs = {}
|
||||
for i in range(3):
|
||||
specs[f"mla.{i}"] = new_mla_spec()
|
||||
specs[f"indexer.{i}"] = new_indexer_mla_spec()
|
||||
specs.update({f"swa.{i}": new_swa_mla_spec(head_size=1024) for i in range(5)})
|
||||
|
||||
config = _grouping_config()
|
||||
config.cache_config = CacheConfig()
|
||||
config.cache_config.kv_cache_layout = "BLNHC"
|
||||
groups = get_kv_cache_groups(config, specs)
|
||||
|
||||
assert len(groups) == 3
|
||||
assert {name for group in groups for name in group.layer_names} == set(specs)
|
||||
assert sorted(len(group.layer_names) for group in groups) == [2, 3, 6]
|
||||
|
||||
|
||||
def _grouping_config():
|
||||
cache_config = CacheConfig()
|
||||
cache_config.kv_cache_layout = "LBNHC"
|
||||
return SimpleNamespace(
|
||||
scheduler_config=SimpleNamespace(disable_hybrid_kv_cache_manager=False),
|
||||
speculative_config=None,
|
||||
cache_config=cache_config,
|
||||
)
|
||||
|
||||
|
||||
@@ -3281,10 +3268,16 @@ def test_iter_layer_specs_returns_group_members():
|
||||
assert list(iter_layer_specs(wrapped)) == [full, mla]
|
||||
|
||||
|
||||
def _spec_decode_grouping_config(method="dspark"):
|
||||
def _spec_decode_grouping_config(method="dspark", model_type=None):
|
||||
"""Grouping config with an EAGLE-family speculative method enabled."""
|
||||
return SimpleNamespace(
|
||||
scheduler_config=SimpleNamespace(disable_hybrid_kv_cache_manager=False),
|
||||
cache_config=SimpleNamespace(
|
||||
get_resolved_kv_cache_layout=lambda: SimpleNamespace(
|
||||
is_block_outermost=True
|
||||
)
|
||||
),
|
||||
model_config=SimpleNamespace(hf_config=SimpleNamespace(model_type=model_type)),
|
||||
speculative_config=SimpleNamespace(
|
||||
method=method,
|
||||
use_eagle=lambda: True,
|
||||
@@ -3322,13 +3315,12 @@ def test_draft_group_annotated_on_hybrid_general_path():
|
||||
|
||||
flagged = [g for g in groups if g.is_eagle_group]
|
||||
assert len(flagged) == 1
|
||||
assert flagged[0].layer_names == ["draft.attn.0"]
|
||||
assert "draft.attn.0" in flagged[0].layer_names
|
||||
|
||||
|
||||
def test_mamba_groups_never_flagged_even_when_draft_shares_a_group():
|
||||
# MLAAttentionSpec.merge ORs non_causal_multi_token_decode rather than
|
||||
# requiring equality, so a draft layer can share a group with target
|
||||
# layers; that combined group still holds volatile draft KV and must be
|
||||
# Packed uniform-type groups can contain distinct target and draft layer
|
||||
# specs; the combined group still holds volatile draft KV and must be
|
||||
# flagged. What must never happen is a Mamba group being flagged: that
|
||||
# widens its lookup window to two consecutive chunks, which align-mode
|
||||
# checkpointing never produces, zeroing every lookup.
|
||||
@@ -3347,10 +3339,8 @@ def test_mamba_groups_never_flagged_even_when_draft_shares_a_group():
|
||||
def test_draft_group_not_annotated_without_spec_decode():
|
||||
# The marker alone must not flag anything; the eagle semantics only apply
|
||||
# when a speculative method is actually enabled.
|
||||
config = SimpleNamespace(
|
||||
scheduler_config=SimpleNamespace(disable_hybrid_kv_cache_manager=False),
|
||||
speculative_config=None,
|
||||
)
|
||||
config = _spec_decode_grouping_config()
|
||||
config.speculative_config = None
|
||||
groups = get_kv_cache_groups(config, _hybrid_specs_with_draft(draft=True))
|
||||
|
||||
assert not any(g.is_eagle_group for g in groups)
|
||||
@@ -3396,12 +3386,13 @@ def _deepseek_v4_specs(model_version="deepseek_v4"):
|
||||
}
|
||||
|
||||
|
||||
def test_deepseek_v4_draft_group_annotated_on_group_and_unify_path():
|
||||
def test_deepseek_v4_draft_group_annotated_on_packed_path():
|
||||
# DeepseekV4's MTP block reuses the target's decoder layer, so its spec
|
||||
# carries no draft marker and only the positional rule can find it. This
|
||||
# pins the pre-existing behaviour that the unified annotator must preserve.
|
||||
groups = get_kv_cache_groups(
|
||||
_spec_decode_grouping_config(method="mtp"), _deepseek_v4_specs()
|
||||
_spec_decode_grouping_config(method="mtp", model_type="deepseek_v4"),
|
||||
_deepseek_v4_specs(model_version=None),
|
||||
)
|
||||
|
||||
flagged = [g for g in groups if g.is_eagle_group]
|
||||
@@ -3409,13 +3400,13 @@ def test_deepseek_v4_draft_group_annotated_on_group_and_unify_path():
|
||||
assert "model.layers.3.self_attn.attn" in flagged[0].layer_names
|
||||
|
||||
|
||||
def test_deepseek_v4_annotation_requires_model_version():
|
||||
def test_deepseek_v4_annotation_requires_model_type():
|
||||
# The positional rule is only sound for DeepseekV4, where the draft layer
|
||||
# is known to be registered last. Without that model gate nothing may be
|
||||
# flagged, however the grouping happens to fall out.
|
||||
groups = get_kv_cache_groups(
|
||||
_spec_decode_grouping_config(method="mtp"),
|
||||
_deepseek_v4_specs(model_version=None),
|
||||
_spec_decode_grouping_config(method="mtp", model_type="other"),
|
||||
_deepseek_v4_specs(),
|
||||
)
|
||||
|
||||
assert not any(g.is_eagle_group for g in groups)
|
||||
|
||||
@@ -1761,6 +1761,52 @@ def test_spec_decode_padding_skipped_for_diffusion():
|
||||
assert r2.request_id not in out.scheduled_spec_decode_tokens
|
||||
|
||||
|
||||
@pytest.mark.parametrize("aligned_tokens", [1, 2, 3])
|
||||
def test_spec_decode_padding_dropped_when_recurrent_alignment_clips(
|
||||
aligned_tokens: int,
|
||||
):
|
||||
"""A clipped padded request must drop its padding, not shorten it.
|
||||
|
||||
The sampler derives a request's row window from its draft count, so a
|
||||
padded request that keeps fewer than 1 + num_spec query rows would select
|
||||
the preceding request's hidden states.
|
||||
"""
|
||||
num_spec = 3
|
||||
scheduler = create_scheduler(
|
||||
num_speculative_tokens=num_spec,
|
||||
enable_prefix_caching=True,
|
||||
block_size=16,
|
||||
)
|
||||
r1, r2 = create_requests(
|
||||
num_requests=2, num_tokens=33, same_prompt=True, max_tokens=16
|
||||
)
|
||||
|
||||
scheduler.add_request(r1)
|
||||
out = scheduler.schedule()
|
||||
assert out.num_scheduled_tokens[r1.request_id] == 33
|
||||
_model_output(scheduler, out, [[100]])
|
||||
scheduler.update_draft_token_ids(DraftTokenIds([r1.request_id], [[1, 2, 3]]))
|
||||
|
||||
# Model the recurrent align split that clips a padded 1+3 prompt tail at
|
||||
# the next cache boundary. The real QSA block size produces all three cases
|
||||
# depending on prompt length modulo four.
|
||||
scheduler.need_mamba_block_aligned_split = True
|
||||
original_split = scheduler._mamba_block_aligned_split
|
||||
|
||||
def align_prompt_tail(request, num_new_tokens, *args):
|
||||
if request is r2:
|
||||
return aligned_tokens
|
||||
return original_split(request, num_new_tokens, *args)
|
||||
|
||||
scheduler._mamba_block_aligned_split = align_prompt_tail
|
||||
scheduler.add_request(r2)
|
||||
out = scheduler.schedule()
|
||||
|
||||
assert out.scheduled_spec_decode_tokens[r1.request_id] == [1, 2, 3]
|
||||
assert out.num_scheduled_tokens[r2.request_id] == 1
|
||||
assert r2.request_id not in out.scheduled_spec_decode_tokens
|
||||
|
||||
|
||||
def test_spec_decode_padding_skipped_with_prefill_in_batch():
|
||||
"""Padding is skipped when the batch contains a prefill chunk: the batch is
|
||||
already mixed/non-uniform, so padding a new decode request buys nothing.
|
||||
|
||||
@@ -14,6 +14,7 @@ from vllm.v1.core.kv_cache_utils import (
|
||||
)
|
||||
from vllm.v1.core.single_type_kv_cache_manager import (
|
||||
ChunkedLocalAttentionManager,
|
||||
CircularBufferManager,
|
||||
FullAttentionManager,
|
||||
MambaManager,
|
||||
RSWAManager,
|
||||
@@ -21,6 +22,7 @@ from vllm.v1.core.single_type_kv_cache_manager import (
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
ChunkedLocalAttentionSpec,
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
MambaSpec,
|
||||
RSWASpec,
|
||||
@@ -136,6 +138,67 @@ def get_chunked_local_attention_manager(
|
||||
)
|
||||
|
||||
|
||||
def test_circular_buffer_allocates_one_block_for_the_request_lifetime():
|
||||
block_size = 4
|
||||
spec = CircularBufferSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=8,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
block_pool = BlockPool(
|
||||
num_gpu_blocks=10, enable_caching=True, hash_block_size=block_size
|
||||
)
|
||||
manager = CircularBufferManager(
|
||||
spec,
|
||||
block_pool=block_pool,
|
||||
enable_caching=True,
|
||||
kv_cache_group_id=0,
|
||||
scheduler_block_size=block_size,
|
||||
needs_kv_cache_zeroing=True,
|
||||
max_admission_blocks_per_request=1,
|
||||
)
|
||||
request_id = "request"
|
||||
|
||||
assert (
|
||||
manager.get_num_blocks_to_allocate(
|
||||
request_id,
|
||||
num_tokens=128,
|
||||
new_computed_blocks=[block_pool.blocks[1]],
|
||||
total_computed_tokens=0,
|
||||
num_local_computed_tokens=0,
|
||||
num_tokens_main_model=128,
|
||||
)
|
||||
== 1
|
||||
)
|
||||
blocks = manager.allocate_new_blocks(
|
||||
request_id, num_tokens=128, num_tokens_main_model=128
|
||||
)
|
||||
assert len(blocks) == 1
|
||||
assert not manager.records_new_block_ids
|
||||
assert manager.take_new_block_ids() == []
|
||||
|
||||
for num_tokens in (256, 1024):
|
||||
assert (
|
||||
manager.get_num_blocks_to_allocate(
|
||||
request_id,
|
||||
num_tokens,
|
||||
[],
|
||||
total_computed_tokens=num_tokens - 1,
|
||||
num_local_computed_tokens=0,
|
||||
num_tokens_main_model=num_tokens,
|
||||
)
|
||||
== 0
|
||||
)
|
||||
assert manager.allocate_new_blocks(request_id, num_tokens, num_tokens) == []
|
||||
|
||||
manager.cache_blocks(request_id, 1024)
|
||||
manager.remove_skipped_blocks(request_id, 1024)
|
||||
assert manager.get_num_common_prefix_blocks(request_id) == 0
|
||||
assert manager.get_num_skipped_tokens(1024) == 0
|
||||
assert manager.req_to_blocks[request_id] == blocks
|
||||
|
||||
|
||||
def test_sliding_window_records_new_blocks_for_zeroing():
|
||||
block_size = 2
|
||||
spec = SlidingWindowSpec(
|
||||
|
||||
@@ -234,7 +234,8 @@ def get_fake_execute_model_fn(original_execute_model_fn: Callable):
|
||||
iter(scheduler_output.num_scheduled_tokens.values())
|
||||
)
|
||||
assert num_scheduled_tokens == cur_step_action.num_scheduled_tokens
|
||||
mamba_group_ids, mamba_spec = get_mamba_groups(self.kv_cache_config)
|
||||
mamba_groups = get_mamba_groups(self.kv_cache_config)
|
||||
mamba_spec, mamba_group_ids = next(iter(mamba_groups.items()))
|
||||
mamba_group_id = mamba_group_ids[0]
|
||||
mamba_layer_name = self.kv_cache_config.kv_cache_groups[
|
||||
mamba_group_id
|
||||
@@ -321,7 +322,8 @@ def get_fake_process_mamba_fn(
|
||||
assert len(copy_info[0]) == len(copy_info[1]) == len(copy_info[2]) == 0
|
||||
else:
|
||||
assert len(copy_info[0]) == len(copy_info[1]) == len(copy_info[2]) == 2
|
||||
mamba_group_ids, mamba_spec = get_mamba_groups(kv_cache_config)
|
||||
mamba_groups = get_mamba_groups(kv_cache_config)
|
||||
mamba_spec, mamba_group_ids = next(iter(mamba_groups.items()))
|
||||
mamba_group_id = mamba_group_ids[0]
|
||||
mamba_layer_name = kv_cache_config.kv_cache_groups[
|
||||
mamba_group_id
|
||||
@@ -936,12 +938,12 @@ def _run_mamba_prefix_cache_mrv1(
|
||||
cleanup_dist_env_and_memory()
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
@create_new_process_for_each_test("spawn")
|
||||
def test_mamba_prefix_cache_mrv1(monkeypatch: pytest.MonkeyPatch):
|
||||
_run_mamba_prefix_cache_mrv1(monkeypatch, async_scheduling=False)
|
||||
|
||||
|
||||
@create_new_process_for_each_test()
|
||||
@create_new_process_for_each_test("spawn")
|
||||
def test_mamba_prefix_cache_mrv1_async(monkeypatch: pytest.MonkeyPatch):
|
||||
_run_mamba_prefix_cache_mrv1(monkeypatch, async_scheduling=True)
|
||||
|
||||
@@ -975,11 +977,12 @@ def _run_mamba_prefix_cache_mrv2(
|
||||
forward_context = (
|
||||
model_state.vllm_config.compilation_config.static_forward_context
|
||||
)
|
||||
group_ids, _ = get_mamba_groups(kv_cache_config)
|
||||
for group_id in group_ids:
|
||||
block_table = block_tables[group_id]
|
||||
for layer_name in kv_cache_config.kv_cache_groups[group_id].layer_names:
|
||||
yield forward_context[layer_name].kv_cache[-1], block_table
|
||||
mamba_groups = get_mamba_groups(kv_cache_config)
|
||||
for group_ids in mamba_groups.values():
|
||||
for group_id in group_ids:
|
||||
block_table = block_tables[group_id]
|
||||
for layer_name in kv_cache_config.kv_cache_groups[group_id].layer_names:
|
||||
yield forward_context[layer_name].kv_cache[-1], block_table
|
||||
|
||||
def temporal_block(temporal_state, block_table, col):
|
||||
# Resolving the block id for assertions is a deliberate D2H.
|
||||
|
||||
@@ -15,6 +15,8 @@ from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
HiddenStateCacheSpec,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
SlidingWindowMLASpec,
|
||||
)
|
||||
@@ -99,12 +101,12 @@ def test_get_block_size_falls_back_to_cache_config_when_no_kv_cache_config():
|
||||
assert block_size == 16
|
||||
|
||||
|
||||
# ---- MLA-verifier absorption ------------------------------------------------
|
||||
# ---- Packed MLA grouping ----------------------------------------------------
|
||||
|
||||
|
||||
def test_find_group_id_errors_clearly_when_absorbed_by_mla_swa_verifier():
|
||||
# HiddenStateCacheSpec subclasses MLAAttentionSpec, so an MLA + sliding-
|
||||
# window MLA verifier absorbs it into the MLA group instead of isolating it.
|
||||
def test_hidden_state_group_isolated_from_packed_mla_groups():
|
||||
# HiddenStateCacheSpec subclasses MLAAttentionSpec, but grouping must pull
|
||||
# it out before packing compatible MLA cache specs.
|
||||
dt = torch.bfloat16
|
||||
spec = {
|
||||
"layers.0.mla": MLAAttentionSpec(
|
||||
@@ -116,11 +118,54 @@ def test_find_group_id_errors_clearly_when_absorbed_by_mla_swa_verifier():
|
||||
"cache_only_layers.61": _hidden(64),
|
||||
}
|
||||
vllm_config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(
|
||||
get_resolved_kv_cache_layout=lambda: KVCacheLayout.BLHNC
|
||||
),
|
||||
scheduler_config=SimpleNamespace(disable_hybrid_kv_cache_manager=False),
|
||||
speculative_config=None,
|
||||
)
|
||||
groups = get_kv_cache_groups(vllm_config, spec)
|
||||
assert not any(isinstance(g.kv_cache_spec, HiddenStateCacheSpec) for g in groups)
|
||||
hidden_group_ids = [
|
||||
i
|
||||
for i, group in enumerate(groups)
|
||||
if isinstance(group.kv_cache_spec, HiddenStateCacheSpec)
|
||||
]
|
||||
assert len(hidden_group_ids) == 1
|
||||
cfg = SimpleNamespace(kv_cache_groups=groups)
|
||||
with pytest.raises(ValueError, match="MLA verifiers are unsupported"):
|
||||
ExampleHiddenStatesConnector._find_cache_kv_group_id(cfg)
|
||||
assert (
|
||||
ExampleHiddenStatesConnector._find_cache_kv_group_id(cfg) == hidden_group_ids[0]
|
||||
)
|
||||
|
||||
|
||||
def test_hidden_state_group_isolated_from_packed_mixed_page_groups():
|
||||
# Packed grouping keeps groups with unequal page sizes (blocks are strided
|
||||
# by the widest group), so the hidden group is appended without padding.
|
||||
hidden = _hidden(16)
|
||||
spec = {
|
||||
"layers.0.attn": _full(16),
|
||||
"layers.1.mamba": MambaSpec(
|
||||
block_size=16, shapes=((1024,),), dtypes=(torch.float32,)
|
||||
),
|
||||
"cache_only_layers.61": hidden,
|
||||
}
|
||||
vllm_config = SimpleNamespace(
|
||||
cache_config=SimpleNamespace(
|
||||
get_resolved_kv_cache_layout=lambda: KVCacheLayout.BLHNC
|
||||
),
|
||||
scheduler_config=SimpleNamespace(disable_hybrid_kv_cache_manager=False),
|
||||
speculative_config=None,
|
||||
)
|
||||
groups = get_kv_cache_groups(vllm_config, spec)
|
||||
page_sizes = {g.kv_cache_spec.page_size_bytes for g in groups}
|
||||
assert len(page_sizes) > 1, "spec must exercise the packed grouping path"
|
||||
hidden_group_ids = [
|
||||
i
|
||||
for i, group in enumerate(groups)
|
||||
if isinstance(group.kv_cache_spec, HiddenStateCacheSpec)
|
||||
]
|
||||
assert len(hidden_group_ids) == 1
|
||||
assert groups[hidden_group_ids[0]].kv_cache_spec == hidden
|
||||
cfg = SimpleNamespace(kv_cache_groups=groups)
|
||||
assert (
|
||||
ExampleHiddenStatesConnector._find_cache_kv_group_id(cfg) == hidden_group_ids[0]
|
||||
)
|
||||
|
||||
@@ -865,6 +865,10 @@ def _make_mock_worker_for_desc_ids(
|
||||
worker._group_spec_types = group_spec_types
|
||||
worker.block_len_per_layer = block_len_per_layer or [100]
|
||||
worker._conv_decomp = None
|
||||
worker._is_csa_linear = False
|
||||
worker._ssm_region_indices = [0] if has_mamba else []
|
||||
worker._ple_group_index = None
|
||||
worker._ple_region_index = None
|
||||
if has_mamba:
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.ssm_conv_transfer_utils import ( # noqa: E501
|
||||
MambaConvSplitInfo,
|
||||
@@ -1823,6 +1827,7 @@ def test_push_write_hybrid_mla_replicates_attention():
|
||||
worker.shutdown = lambda: None # skeleton worker: silence __del__
|
||||
worker.use_mla = True
|
||||
worker._has_mamba = True
|
||||
worker._is_csa_linear = False
|
||||
worker._group_spec_types = (MLAAttentionSpec, MambaSpec)
|
||||
worker.transfer_topo = MagicMock()
|
||||
worker.transfer_topo.tp_ratio.return_value = -2
|
||||
|
||||
@@ -645,3 +645,302 @@ def test_mismatched_mla_kernel_page_rejected_for_mla_hybrid():
|
||||
meta_r.block_lens = [x // 2 for x in worker.block_len_per_layer]
|
||||
with pytest.raises((AssertionError, RuntimeError)):
|
||||
worker.add_remote_agent(meta_r, remote_tp_rank=0, remote_tp_size=2)
|
||||
|
||||
|
||||
def _make_csa_linear_ple_worker(scratch_aliases: str = "compressed"):
|
||||
"""``scratch_aliases`` selects which pages the compressor ring overlays."""
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl import base_worker as bw
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
|
||||
NixlConnectorWorker,
|
||||
)
|
||||
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheTensor,
|
||||
MambaSpec,
|
||||
MLAAttentionSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
)
|
||||
|
||||
main_kv_specs = {
|
||||
f"main_kv.{index}": FullAttentionSpec(
|
||||
block_size=4,
|
||||
num_kv_heads=1,
|
||||
head_size=16,
|
||||
dtype=torch.float16,
|
||||
)
|
||||
for index in range(2)
|
||||
}
|
||||
compressed_specs = {
|
||||
f"compressed.{index}": MLAAttentionSpec(
|
||||
block_size=4,
|
||||
num_kv_heads=1,
|
||||
head_size=64,
|
||||
dtype=torch.float16,
|
||||
tokens_per_state=2,
|
||||
)
|
||||
for index in range(2)
|
||||
}
|
||||
compressor_state_specs = {
|
||||
f"compressor_state.{index}": CircularBufferSpec(
|
||||
block_size=2,
|
||||
num_kv_heads=1,
|
||||
head_size=32,
|
||||
dtype=torch.float16,
|
||||
)
|
||||
for index in range(2)
|
||||
}
|
||||
sharded_mamba_spec = MambaSpec(
|
||||
block_size=1,
|
||||
shapes=((8, 3), (1, 4, 4)),
|
||||
dtypes=(torch.float16, torch.float32),
|
||||
page_size_padded=256,
|
||||
mamba_type=MambaAttentionBackendEnum.GDN_ATTN,
|
||||
)
|
||||
ple_spec = MambaSpec(
|
||||
block_size=1,
|
||||
shapes=((6, 3),),
|
||||
dtypes=(torch.float16,),
|
||||
page_size_padded=256,
|
||||
mamba_type=MambaAttentionBackendEnum.SHORT_CONV,
|
||||
tp_replicated=True,
|
||||
)
|
||||
compressed_sparse_specs = {
|
||||
name: spec
|
||||
for index in range(2)
|
||||
for name, spec in (
|
||||
(f"main_kv.{index}", main_kv_specs[f"main_kv.{index}"]),
|
||||
(f"compressed.{index}", compressed_specs[f"compressed.{index}"]),
|
||||
)
|
||||
}
|
||||
|
||||
def group(specs):
|
||||
uniform = UniformTypeKVCacheSpecs.from_specs(specs)
|
||||
assert uniform is not None
|
||||
return KVCacheGroupSpec(list(specs), uniform)
|
||||
|
||||
tensor_regions: tuple[tuple[str, ...], ...]
|
||||
if scratch_aliases == "compressed":
|
||||
tensor_regions = (
|
||||
("main_kv.0", "mamba.sharded", "mamba.ple"),
|
||||
("main_kv.1",),
|
||||
("compressed.0", "compressor_state.0"),
|
||||
("compressed.1", "compressor_state.1"),
|
||||
)
|
||||
else:
|
||||
assert scratch_aliases == "main_kv"
|
||||
tensor_regions = (
|
||||
("main_kv.0", "mamba.sharded", "mamba.ple", "compressor_state.0"),
|
||||
("main_kv.1", "compressor_state.1"),
|
||||
("compressed.0",),
|
||||
("compressed.1",),
|
||||
)
|
||||
region_size = 512
|
||||
page_size = 256
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=2,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=len(tensor_regions) * region_size,
|
||||
layers=[layer_name],
|
||||
layer_stride=region_size,
|
||||
block_stride=page_size,
|
||||
offset=region_index * region_size,
|
||||
)
|
||||
for region_index, layer_names in enumerate(tensor_regions)
|
||||
for layer_name in layer_names
|
||||
],
|
||||
kv_cache_groups=[
|
||||
group(compressed_sparse_specs),
|
||||
group(compressor_state_specs),
|
||||
KVCacheGroupSpec(["mamba.sharded"], sharded_mamba_spec),
|
||||
KVCacheGroupSpec(["mamba.ple"], ple_spec),
|
||||
],
|
||||
)
|
||||
|
||||
vllm_config = create_vllm_config(block_size=4)
|
||||
vllm_config.cache_config.enable_prefix_caching = False
|
||||
vllm_config.kv_transfer_config.kv_buffer_device = "cuda"
|
||||
fake_backend = MagicMock()
|
||||
fake_backend.get_supported_kernel_block_sizes.return_value = [4]
|
||||
fake_backend.get_name.return_value = "TEST_ATTN"
|
||||
fake_backend.full_cls_name.return_value = "test.AttentionBackend"
|
||||
fake_platform = MagicMock()
|
||||
fake_platform.device_type = "cuda"
|
||||
fake_platform.get_nixl_memory_type.return_value = "VRAM"
|
||||
|
||||
with (
|
||||
patch.object(bw, "NixlWrapper", _RecordingNixl),
|
||||
patch.object(bw, "get_tensor_model_parallel_rank", return_value=0),
|
||||
patch.object(bw, "get_tensor_model_parallel_world_size", return_value=1),
|
||||
patch.object(bw, "get_current_attn_backends", return_value=[fake_backend]),
|
||||
patch.object(bw, "current_platform", fake_platform),
|
||||
patch(
|
||||
"vllm.model_executor.layers.mamba.mamba_utils.get_conv_state_layout",
|
||||
return_value="DS",
|
||||
),
|
||||
set_current_vllm_config(vllm_config),
|
||||
):
|
||||
worker = NixlConnectorWorker(vllm_config, "local-engine", kv_cache_config)
|
||||
tensors = [torch.zeros((2, 256), dtype=torch.uint8) for _ in range(4)]
|
||||
worker.register_kv_caches(
|
||||
{
|
||||
layer_name: tensors[region_index]
|
||||
for region_index, layer_names in enumerate(tensor_regions)
|
||||
for layer_name in layer_names
|
||||
}
|
||||
)
|
||||
return worker
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_csa_linear_registration_discovers_shared_regions():
|
||||
worker = _make_csa_linear_ple_worker()
|
||||
|
||||
assert worker._ssm_region_indices == [0]
|
||||
assert worker._ple_group_index == 3
|
||||
assert worker._ple_region_index == 0
|
||||
assert worker._region_is_mla == [False, False, True, True]
|
||||
assert worker._scratch_region_indices == [2, 3]
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_csa_linear_scratch_descs_follow_the_pages_they_overlay():
|
||||
"""The scratch ring is addressed by the regions it actually registered in,
|
||||
not by inferring that it must sit on the MLA pages: overlaying the main KV
|
||||
pages instead moves its descriptors with it."""
|
||||
worker = _make_csa_linear_ple_worker(scratch_aliases="main_kv")
|
||||
|
||||
# Same MLA regions as before, but the ring now lives in the non-MLA ones.
|
||||
assert worker._region_is_mla == [False, False, True, True]
|
||||
assert worker._scratch_region_indices == [0, 1]
|
||||
|
||||
desc_ids = worker._compute_desc_ids(
|
||||
block_ids=([1], [0], [1], [1]),
|
||||
dst_num_blocks=2,
|
||||
block_size_ratio=None,
|
||||
physical_blocks_per_logical=1,
|
||||
)
|
||||
# Scratch group (block 0) now maps to regions 0 and 1 -> descs 0 and 2,
|
||||
# where the compressed-page placement gave 4 and 6.
|
||||
assert desc_ids.tolist()[4:6] == [0, 2]
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_csa_linear_selects_compressed_sparse_compressor_state_and_mamba_regions():
|
||||
worker = _make_csa_linear_ple_worker()
|
||||
|
||||
desc_ids = worker._compute_desc_ids(
|
||||
block_ids=([1], [0], [1], [1]),
|
||||
dst_num_blocks=2,
|
||||
block_size_ratio=None,
|
||||
physical_blocks_per_logical=1,
|
||||
)
|
||||
assert desc_ids.tolist() == [
|
||||
1,
|
||||
3,
|
||||
5,
|
||||
7,
|
||||
4,
|
||||
6,
|
||||
9,
|
||||
11,
|
||||
13,
|
||||
15,
|
||||
17,
|
||||
]
|
||||
|
||||
mamba_only = worker._compute_desc_ids(
|
||||
block_ids=([], [], [1], [1]),
|
||||
dst_num_blocks=2,
|
||||
block_size_ratio=None,
|
||||
physical_blocks_per_logical=1,
|
||||
)
|
||||
assert mamba_only.tolist() == [9, 11, 13, 15, 17]
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_csa_linear_ple_descriptor_is_not_split():
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.tp_mapping import (
|
||||
TPMapping,
|
||||
)
|
||||
|
||||
worker = _make_csa_linear_ple_worker()
|
||||
bases = [0x10000, 0x20000, 0x30000, 0x40000]
|
||||
attention = worker._build_fa_local(bases, block_size_ratio=1)
|
||||
mamba = worker._build_mamba_local(bases)
|
||||
assert attention.shape == (8, 3)
|
||||
assert mamba.shape == (10, 3)
|
||||
assert mamba[-2:, 0].tolist() == [0x10000, 0x10100]
|
||||
assert mamba[-2:, 1].tolist() == [256, 256]
|
||||
|
||||
mapping = TPMapping(
|
||||
source_ranks_per_group=((0,), (0,), (0, 1), (0, 1)),
|
||||
all_source_ranks=(0, 1),
|
||||
rank_to_attention_slot={0: 0, 1: 0},
|
||||
rank_offset_factor=0,
|
||||
)
|
||||
splits = list(
|
||||
worker._build_local_splits_from_plan(
|
||||
mapping,
|
||||
np.concatenate([attention, mamba]),
|
||||
num_fa_descs=len(attention),
|
||||
)
|
||||
)
|
||||
assert len(splits) == 2
|
||||
assert [row[1] for row in splits[0][-2:]] == [256, 256]
|
||||
assert [row[1] for row in splits[1][-2:]] == [256, 256]
|
||||
assert splits[0][-3][1] * 2 == mamba[-3, 1]
|
||||
assert splits[1][-3][1] * 2 == mamba[-3, 1]
|
||||
|
||||
|
||||
@pytest.mark.cpu_test
|
||||
def test_csa_linear_remote_ple_is_copied_whole():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
|
||||
NixlAgentMetadata,
|
||||
)
|
||||
|
||||
worker = _make_csa_linear_ple_worker()
|
||||
metadata = NixlAgentMetadata(
|
||||
engine_id="remote",
|
||||
agent_metadata=b"agent",
|
||||
kv_caches_base_addr=[
|
||||
0x10000,
|
||||
0x20000,
|
||||
0x30000,
|
||||
0x40000,
|
||||
],
|
||||
device_id=0,
|
||||
num_blocks=2,
|
||||
block_lens=[256] * 4,
|
||||
block_strides=[256] * 4,
|
||||
kv_cache_layout="HND",
|
||||
block_size=4,
|
||||
ssm_sizes=(24, 32),
|
||||
attn_backend_name="test",
|
||||
physical_blocks_per_logical_kv_block=1,
|
||||
)
|
||||
descriptors = worker._build_mamba_remote(
|
||||
metadata,
|
||||
tp_ratio=-2,
|
||||
transfer_info=SimpleNamespace(remote_physical_blocks_per_logical=1),
|
||||
)
|
||||
assert descriptors.shape == (10, 3)
|
||||
assert descriptors[-2:, 0].tolist() == [0x10000, 0x10100]
|
||||
assert descriptors[-2:, 1].tolist() == [256, 256]
|
||||
|
||||
metadata.block_lens[0] = 128
|
||||
with pytest.raises(ValueError, match="PLE pages require identical"):
|
||||
worker._build_mamba_remote(
|
||||
metadata,
|
||||
tp_ratio=-2,
|
||||
transfer_info=SimpleNamespace(remote_physical_blocks_per_logical=1),
|
||||
)
|
||||
|
||||
@@ -359,6 +359,7 @@ class _StubWriterWorker(NixlPushConnectorWorker):
|
||||
w._physical_blocks_per_logical_kv_block = 1
|
||||
# Single non-hybrid attention group, matching the stub block id lists.
|
||||
w._has_mamba = False
|
||||
w._is_csa_linear = False
|
||||
w._group_spec_types = (FullAttentionSpec,)
|
||||
w._engine_ttl = 0.0
|
||||
w._engine_last_active = {}
|
||||
@@ -1198,6 +1199,75 @@ class TestPushWriterMlaReplication:
|
||||
# engine thread never sees a partial set and double-frees the request.
|
||||
assert sorted(w._sending_transfers["p-req"]) == [1000, 1001]
|
||||
|
||||
def test_csa_linear_writes_every_group_to_each_target(self):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
|
||||
RemoteMeta,
|
||||
ReqMeta,
|
||||
)
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.tp_mapping import (
|
||||
TPMapping,
|
||||
)
|
||||
|
||||
engine_id = "decode-engine"
|
||||
w = _StubWriterWorker.fresh()
|
||||
w.world_size = 2
|
||||
w.use_mla = False
|
||||
w._has_mamba = True
|
||||
w._is_csa_linear = True
|
||||
w.nixl_wrapper = MagicMock()
|
||||
w.transfer_topo = MagicMock()
|
||||
w.transfer_topo.get_engine_info.return_value = SimpleNamespace(
|
||||
remote_tp_size=4,
|
||||
remote_block_size=16,
|
||||
remote_physical_blocks_per_logical=1,
|
||||
)
|
||||
w.transfer_topo.tp_ratio.return_value = -2
|
||||
w.transfer_topo.handshake_target_ranks.return_value = (0, 1)
|
||||
w.tp_mappings = {
|
||||
engine_id: TPMapping(
|
||||
source_ranks_per_group=((0,), (0,), (0, 1), (0, 1)),
|
||||
all_source_ranks=(0, 1),
|
||||
rank_to_attention_slot={0: 0, 1: 0},
|
||||
rank_offset_factor=0,
|
||||
)
|
||||
}
|
||||
w._logical_to_kernel_block_ids = lambda block_ids, ratio: block_ids
|
||||
w.dst_xfer_side_handles = {engine_id: {0: 1000, 1: 1001}}
|
||||
w.src_xfer_handles_by_tp_ratio = {(-2, 16): [2000, 2001]}
|
||||
|
||||
writes = []
|
||||
|
||||
def _fake_xfer(**kwargs):
|
||||
writes.append(kwargs)
|
||||
return 3000 + kwargs["read_spec"].remote_rank
|
||||
|
||||
w._xfer_blocks = _fake_xfer
|
||||
block_ids = ([10], [20], [30], [40])
|
||||
meta = ReqMeta(
|
||||
local_block_ids=block_ids,
|
||||
local_physical_block_ids=block_ids,
|
||||
tp_size=2,
|
||||
remote=RemoteMeta(
|
||||
block_ids=([50], [60], [70], [80]),
|
||||
host="",
|
||||
port=0,
|
||||
engine_id=engine_id,
|
||||
request_id="d-req",
|
||||
),
|
||||
)
|
||||
|
||||
w._xfer_blocks_for_req(req_id="p-req", meta=meta)
|
||||
|
||||
assert [write["read_spec"].remote_rank for write in writes] == [0, 1]
|
||||
assert [write["read_spec"].local_block_ids for write in writes] == [
|
||||
list(block_ids),
|
||||
list(block_ids),
|
||||
]
|
||||
assert [write["local_xfer_side_handle"] for write in writes] == [2000, 2001]
|
||||
assert sorted(w._sending_transfers["p-req"]) == [3000, 3001]
|
||||
|
||||
|
||||
class TestPushPrefixCaching:
|
||||
"""Partial prefix-cache hit on D: D preallocates only its *uncomputed*
|
||||
|
||||
@@ -154,6 +154,9 @@ def _make_mock_worker_for_splits(group_spec_types):
|
||||
worker.block_len_per_layer = []
|
||||
worker.num_regions = 0
|
||||
worker._region_is_mla = []
|
||||
worker._conv_decomp = SimpleNamespace(local_conv_offsets=())
|
||||
worker._ssm_region_indices = [0] if MambaSpec in group_spec_types else []
|
||||
worker._ple_region_index = None
|
||||
return worker
|
||||
|
||||
|
||||
@@ -282,3 +285,31 @@ class TestMambaPlanSplitHandles:
|
||||
|
||||
with pytest.raises(AssertionError, match="Head-sharded"):
|
||||
list(worker._build_local_splits_from_plan(plan, src_blocks_data, 2, 2))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("total_kv_heads", "local_tp", "remote_tp", "compatible"),
|
||||
[
|
||||
# 2 heads: TP1 packs both heads into a page, TP >= 2 packs one.
|
||||
(2, 1, 2, False),
|
||||
(2, 2, 1, False),
|
||||
(2, 1, 1, True),
|
||||
(2, 2, 4, True),
|
||||
(2, 4, 2, True),
|
||||
# 4 heads: the boundary moves with the head count.
|
||||
(4, 2, 4, False),
|
||||
(4, 2, 2, True),
|
||||
(4, 4, 8, True),
|
||||
],
|
||||
)
|
||||
def test_csa_linear_tp_layout_boundary(total_kv_heads, local_tp, remote_tp, compatible):
|
||||
worker = object.__new__(NixlConnectorWorker)
|
||||
worker.world_size = local_tp
|
||||
worker._is_csa_linear = True
|
||||
worker.transfer_topo = SimpleNamespace(total_num_kv_heads=total_kv_heads)
|
||||
|
||||
if compatible:
|
||||
worker._validate_csa_linear_tp_layout(remote_tp)
|
||||
else:
|
||||
with pytest.raises(ValueError, match="KV-head sharding boundary"):
|
||||
worker._validate_csa_linear_tp_layout(remote_tp)
|
||||
|
||||
@@ -104,6 +104,47 @@ def _make_speculator(
|
||||
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",
|
||||
)
|
||||
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,
|
||||
),
|
||||
)
|
||||
|
||||
speculator = _TestSpeculator(vllm_config, torch.device("cpu"))
|
||||
|
||||
assert speculator.hidden_size == expected
|
||||
|
||||
|
||||
def test_mm_support_configured_after_model_load(monkeypatch):
|
||||
target_model_config = object()
|
||||
draft_model_config = object()
|
||||
@@ -197,9 +238,11 @@ def test_load_model_disables_mm_support_for_text_only_drafter(monkeypatch):
|
||||
|
||||
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."
|
||||
(
|
||||
"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."
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -132,6 +132,42 @@ def test_block_tables_apply_staged_writes_single_group():
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
kernel_block_sizes=[8, 262144],
|
||||
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_with_smaller_kernel_blocks(cp_rank: int):
|
||||
"""DCP interleave is expressed in logical-block token coordinates."""
|
||||
|
||||
@@ -8,15 +8,107 @@ import torch
|
||||
|
||||
import vllm.v1.worker.gpu.model_runner as model_runner_module
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
MambaSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
)
|
||||
from vllm.v1.worker.gpu.block_table import BlockTables
|
||||
from vllm.v1.worker.gpu.model_runner import GPUModelRunner
|
||||
|
||||
|
||||
def test_qsa_circular_group_uses_custom_slot_mapping(monkeypatch):
|
||||
runner = GPUModelRunner.__new__(GPUModelRunner)
|
||||
runner.max_model_len = 262144
|
||||
runner.is_encoder_decoder = False
|
||||
runner.dcp_size = 1
|
||||
runner.dcp_rank = 0
|
||||
runner.cp_interleave = 1
|
||||
runner.cache_config = SimpleNamespace(enable_prefix_caching=True)
|
||||
parallel_config = SimpleNamespace(
|
||||
decode_context_parallel_size=1,
|
||||
cp_kv_cache_interleave_size=1,
|
||||
)
|
||||
runner.parallel_config = parallel_config
|
||||
runner.vllm_config = SimpleNamespace(
|
||||
parallel_config=parallel_config,
|
||||
cache_config=SimpleNamespace(mamba_cache_mode="none"),
|
||||
)
|
||||
runner.model_state = SimpleNamespace(
|
||||
get_additional_cg_support=lambda: (),
|
||||
num_new_sampled_tokens_per_step=1,
|
||||
)
|
||||
runner.speculator = None
|
||||
runner.req_states = []
|
||||
runner.input_buffers = SimpleNamespace(query_start_loc=None)
|
||||
runner.vocab_size = 1
|
||||
runner.max_num_reqs = 1
|
||||
runner.max_num_tokens = 2
|
||||
runner.device = torch.device("cuda")
|
||||
|
||||
raw_spec = CircularBufferSpec(
|
||||
block_size=8,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
compressed_spec = FullAttentionSpec(
|
||||
block_size=262144,
|
||||
num_kv_heads=1,
|
||||
head_size=128,
|
||||
dtype=torch.bfloat16,
|
||||
)
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=1,
|
||||
kv_cache_tensors=[],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(
|
||||
layer_names=["raw"],
|
||||
kv_cache_spec=UniformTypeKVCacheSpecs(
|
||||
block_size=8,
|
||||
kv_cache_specs={"raw": raw_spec},
|
||||
),
|
||||
),
|
||||
KVCacheGroupSpec(layer_names=["compressed"], kv_cache_spec=compressed_spec),
|
||||
],
|
||||
)
|
||||
|
||||
class FakeAttnCGSupport:
|
||||
def narrow(self, *args):
|
||||
return self
|
||||
|
||||
attn_cg_support = FakeAttnCGSupport()
|
||||
monkeypatch.setattr(
|
||||
model_runner_module,
|
||||
"init_attn_backend",
|
||||
lambda *args: ([], attn_cg_support, [8, 262144]),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
model_runner_module,
|
||||
"maybe_create_adaptive_verification_manager",
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
|
||||
captured = {}
|
||||
|
||||
class BlockTablesCaptured(Exception):
|
||||
pass
|
||||
|
||||
def capture_block_tables(**kwargs):
|
||||
captured.update(kwargs)
|
||||
raise BlockTablesCaptured
|
||||
|
||||
monkeypatch.setattr(model_runner_module, "BlockTables", capture_block_tables)
|
||||
|
||||
with pytest.raises(BlockTablesCaptured):
|
||||
runner.initialize_kv_cache(kv_cache_config)
|
||||
|
||||
assert captured["max_num_blocks_per_group"] == [1, 1]
|
||||
assert captured["slot_mapping_enabled"] == [False, True]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("mamba_cache_mode", "num_speculative_blocks", "expected"),
|
||||
[
|
||||
|
||||
@@ -20,6 +20,7 @@ from vllm.config.vllm import VllmConfig
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
CircularBufferSpec,
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
@@ -53,6 +54,18 @@ def _attention_group() -> KVCacheGroupSpec:
|
||||
)
|
||||
|
||||
|
||||
def _circular_group() -> KVCacheGroupSpec:
|
||||
return KVCacheGroupSpec(
|
||||
["circular"],
|
||||
CircularBufferSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=1,
|
||||
head_size=1,
|
||||
dtype=torch.float32,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _mamba_group(mamba_cache_mode: str) -> KVCacheGroupSpec:
|
||||
# Name carries the mode so several groups can coexist in one config.
|
||||
return KVCacheGroupSpec(
|
||||
@@ -212,8 +225,7 @@ def test_warmup_reserves_mamba_speculative_blocks(mamba_cache_mode):
|
||||
|
||||
|
||||
def _hybrid_kv_cache_config(num_blocks: int) -> KVCacheConfig:
|
||||
"""Full attention plus one Mamba group per cache mode, so a single manager
|
||||
exercises every branch `_reserved_block_count` has.
|
||||
"""Attention, circular, and Mamba groups exercise every reservation branch.
|
||||
|
||||
"none" and "all" reach the same branch of both `_reserved_block_count` and
|
||||
`MambaManager`, which tests only for "align". They are still both listed:
|
||||
@@ -226,6 +238,7 @@ def _hybrid_kv_cache_config(num_blocks: int) -> KVCacheConfig:
|
||||
kv_cache_tensors=[],
|
||||
kv_cache_groups=[
|
||||
_attention_group(),
|
||||
_circular_group(),
|
||||
_mamba_group("none"),
|
||||
_mamba_group("all"),
|
||||
_mamba_group("align"),
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
@@ -10,11 +9,20 @@ import pytest
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import (
|
||||
MambaStateCopyFunc,
|
||||
MambaStateCopyFuncsByType,
|
||||
get_conv_copy_spec,
|
||||
get_temporal_copy_spec,
|
||||
)
|
||||
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.core.sched.output import CachedRequestData, SchedulerOutput
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, KVCacheGroupSpec, MambaSpec
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
MambaSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
)
|
||||
from vllm.v1.worker.gpu.model_states.mamba_hybrid import MambaHybridModelState
|
||||
from vllm.v1.worker.mamba_utils import (
|
||||
MambaCopyBuffers,
|
||||
MambaSpecDecodeGPUContext,
|
||||
@@ -22,17 +30,21 @@ from vllm.v1.worker.mamba_utils import (
|
||||
batch_memcpy,
|
||||
collect_mamba_copy_meta,
|
||||
do_mamba_copy_block,
|
||||
get_mamba_groups,
|
||||
preprocess_mamba,
|
||||
stage_postprocess_inputs_to_gpu,
|
||||
)
|
||||
|
||||
MambaStateCopyFunc = Callable[..., Any]
|
||||
|
||||
# Conv + temporal copy specs, in the order the tests' MambaSpec shapes expect.
|
||||
_COPY_FUNCS: tuple[MambaStateCopyFunc, ...] = (
|
||||
_DEFAULT_COPY_FUNCS: tuple[MambaStateCopyFunc, ...] = (
|
||||
get_conv_copy_spec,
|
||||
get_temporal_copy_spec,
|
||||
)
|
||||
_COPY_FUNCS: MambaStateCopyFuncsByType = {
|
||||
MambaAttentionBackendEnum.MAMBA2: _DEFAULT_COPY_FUNCS,
|
||||
MambaAttentionBackendEnum.GDN_ATTN: _DEFAULT_COPY_FUNCS,
|
||||
MambaAttentionBackendEnum.SHORT_CONV: (get_conv_copy_spec,),
|
||||
}
|
||||
|
||||
|
||||
def postprocess_mamba(
|
||||
@@ -41,7 +53,7 @@ def postprocess_mamba(
|
||||
input_batch: Any,
|
||||
requests: dict[str, Any],
|
||||
forward_context: dict[str, Any],
|
||||
mamba_state_copy_funcs: tuple[MambaStateCopyFunc, ...],
|
||||
mamba_state_copy_funcs: MambaStateCopyFuncsByType,
|
||||
copy_bufs: "MambaCopyBuffers",
|
||||
):
|
||||
"""CPU reference for the align-mode postprocess.
|
||||
@@ -147,7 +159,7 @@ def test_resumed_req_ids_cleared_from_mamba_state_idx():
|
||||
input_batch,
|
||||
{}, # requests
|
||||
{}, # forward_context
|
||||
(), # mamba_state_copy_funcs
|
||||
{}, # mamba_state_copy_funcs
|
||||
copy_bufs,
|
||||
)
|
||||
|
||||
@@ -430,7 +442,10 @@ def _make_requests(
|
||||
|
||||
|
||||
def _make_copy_bufs(
|
||||
cfg: _TestConfig, kv_cache_config: KVCacheConfig, device: torch.device
|
||||
cfg: _TestConfig,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
device: torch.device,
|
||||
copy_funcs: MambaStateCopyFuncsByType = _COPY_FUNCS,
|
||||
) -> MambaCopyBuffers:
|
||||
"""Create MambaCopyBuffers for the Python path."""
|
||||
|
||||
@@ -440,13 +455,16 @@ def _make_copy_bufs(
|
||||
return MambaCopyBuffers.create(
|
||||
max_num_reqs=cfg.max_num_reqs,
|
||||
kv_cache_config=kv_cache_config,
|
||||
copy_funcs=(get_conv_copy_spec, get_temporal_copy_spec),
|
||||
copy_funcs=copy_funcs,
|
||||
make_buffer=make_buffer,
|
||||
)
|
||||
|
||||
|
||||
def _make_gpu_ctx(
|
||||
cfg: _TestConfig, kv_cache_config: KVCacheConfig, device: torch.device
|
||||
cfg: _TestConfig,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
device: torch.device,
|
||||
copy_funcs: MambaStateCopyFuncsByType = _COPY_FUNCS,
|
||||
) -> MambaSpecDecodeGPUContext:
|
||||
"""Create MambaSpecDecodeGPUContext for the GPU path."""
|
||||
|
||||
@@ -456,12 +474,170 @@ def _make_gpu_ctx(
|
||||
return MambaSpecDecodeGPUContext.create(
|
||||
max_num_reqs=cfg.max_num_reqs,
|
||||
kv_cache_config=kv_cache_config,
|
||||
num_state_types=2,
|
||||
copy_funcs=copy_funcs,
|
||||
device=device,
|
||||
make_buffer=make_buffer,
|
||||
)
|
||||
|
||||
|
||||
def test_mamba_groups_support_different_state_specs():
|
||||
gdn_spec = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((4, 4), (2, 4, 4)),
|
||||
dtypes=(torch.float16, torch.float32),
|
||||
mamba_type=MambaAttentionBackendEnum.GDN_ATTN,
|
||||
mamba_cache_mode="align",
|
||||
num_speculative_blocks=3,
|
||||
)
|
||||
short_conv_spec = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((12, 8),),
|
||||
dtypes=(torch.float16,),
|
||||
mamba_type=MambaAttentionBackendEnum.SHORT_CONV,
|
||||
mamba_cache_mode="align",
|
||||
num_speculative_blocks=3,
|
||||
)
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=8,
|
||||
kv_cache_tensors=[],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(["gdn.0", "gdn.1"], gdn_spec),
|
||||
KVCacheGroupSpec(["ple.0"], short_conv_spec),
|
||||
],
|
||||
)
|
||||
|
||||
mamba_groups = get_mamba_groups(kv_cache_config)
|
||||
assert mamba_groups == {gdn_spec: [0], short_conv_spec: [1]}
|
||||
|
||||
model_state = object.__new__(MambaHybridModelState)
|
||||
model_state._mamba_group_ids = []
|
||||
model_state._mamba_spec = None
|
||||
group_ids, representative_spec = model_state._get_mamba_group_info(kv_cache_config)
|
||||
assert group_ids == [0, 1]
|
||||
assert representative_spec is gdn_spec
|
||||
|
||||
cfg = _TestConfig()
|
||||
copy_bufs = _make_copy_bufs(cfg, kv_cache_config, torch.device("cpu"))
|
||||
assert copy_bufs.src_ptrs.cpu.numel() == cfg.max_num_reqs * 5
|
||||
assert copy_bufs.dst_ptrs.cpu.numel() == cfg.max_num_reqs * 5
|
||||
assert copy_bufs.sizes.cpu.numel() == cfg.max_num_reqs * 5
|
||||
|
||||
ctx = _make_gpu_ctx(cfg, kv_cache_config, torch.device("cpu"))
|
||||
assert ctx.num_states == 5
|
||||
|
||||
forward_context = {}
|
||||
gdn_spec_layer_names = ["gdn.0", "gdn.1"]
|
||||
for layer_name in gdn_spec_layer_names:
|
||||
attention = MagicMock()
|
||||
attention.kv_cache = (
|
||||
torch.empty(8, 4, 4, dtype=torch.float16),
|
||||
torch.empty(8, 2, 4, 4, dtype=torch.float32),
|
||||
)
|
||||
forward_context[layer_name] = attention
|
||||
ple_attention = MagicMock()
|
||||
ple_attention.kv_cache = (torch.empty(8, 12, 8, dtype=torch.float16),)
|
||||
forward_context["ple.0"] = ple_attention
|
||||
assert gdn_spec_layer_names == kv_cache_config.kv_cache_groups[0].layer_names
|
||||
|
||||
block_tables = [
|
||||
torch.zeros(4, 8, dtype=torch.int32),
|
||||
torch.zeros(4, 8, dtype=torch.int32),
|
||||
]
|
||||
ctx.initialize_from_forward_context(
|
||||
kv_cache_config,
|
||||
forward_context,
|
||||
_COPY_FUNCS,
|
||||
block_tables,
|
||||
)
|
||||
assert ctx.is_initialized
|
||||
assert ctx.state_group_indices.tolist() == [0, 0, 0, 0, 1]
|
||||
assert ctx.state_conv_widths.tolist() == [4, 0, 4, 0, 12]
|
||||
|
||||
|
||||
def test_mamba_groups_support_mixed_specs_in_uniform_group():
|
||||
gdn_spec = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((4, 4), (2, 4, 4)),
|
||||
dtypes=(torch.float16, torch.float32),
|
||||
mamba_type=MambaAttentionBackendEnum.GDN_ATTN,
|
||||
mamba_cache_mode="align",
|
||||
num_speculative_blocks=3,
|
||||
)
|
||||
short_conv_spec = MambaSpec(
|
||||
block_size=16,
|
||||
shapes=((12, 8),),
|
||||
dtypes=(torch.float16,),
|
||||
mamba_type=MambaAttentionBackendEnum.SHORT_CONV,
|
||||
mamba_cache_mode="align",
|
||||
num_speculative_blocks=3,
|
||||
)
|
||||
layer_specs = {
|
||||
"gdn.0": gdn_spec,
|
||||
"gdn.1": gdn_spec,
|
||||
"ple.0": short_conv_spec,
|
||||
}
|
||||
kv_cache_config = KVCacheConfig(
|
||||
num_blocks=8,
|
||||
kv_cache_tensors=[],
|
||||
kv_cache_groups=[
|
||||
KVCacheGroupSpec(
|
||||
list(layer_specs),
|
||||
UniformTypeKVCacheSpecs(
|
||||
block_size=16,
|
||||
kv_cache_specs=layer_specs,
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
assert kv_cache_config.has_mamba_layers
|
||||
assert get_mamba_groups(kv_cache_config) == {
|
||||
gdn_spec: [0],
|
||||
short_conv_spec: [0],
|
||||
}
|
||||
|
||||
# The group is listed once per spec, so its id must not be repeated.
|
||||
model_state = object.__new__(MambaHybridModelState)
|
||||
model_state._mamba_group_ids = []
|
||||
model_state._mamba_spec = None
|
||||
group_ids, representative_spec = model_state._get_mamba_group_info(kv_cache_config)
|
||||
assert group_ids == [0]
|
||||
assert representative_spec is gdn_spec
|
||||
|
||||
cfg = _TestConfig()
|
||||
copy_bufs = _make_copy_bufs(cfg, kv_cache_config, torch.device("cpu"))
|
||||
assert copy_bufs.mamba_group_ids == [0]
|
||||
assert copy_bufs.src_ptrs.cpu.numel() == cfg.max_num_reqs * 5
|
||||
|
||||
ctx = _make_gpu_ctx(cfg, kv_cache_config, torch.device("cpu"))
|
||||
assert ctx.mamba_group_ids == [0]
|
||||
assert ctx.num_states == 5
|
||||
|
||||
forward_context = {
|
||||
"gdn.0": MagicMock(
|
||||
kv_cache=(
|
||||
torch.empty(8, 4, 4, dtype=torch.float16),
|
||||
torch.empty(8, 2, 4, 4, dtype=torch.float32),
|
||||
)
|
||||
),
|
||||
"gdn.1": MagicMock(
|
||||
kv_cache=(
|
||||
torch.empty(8, 4, 4, dtype=torch.float16),
|
||||
torch.empty(8, 2, 4, 4, dtype=torch.float32),
|
||||
)
|
||||
),
|
||||
"ple.0": MagicMock(kv_cache=(torch.empty(8, 12, 8, dtype=torch.float16),)),
|
||||
}
|
||||
ctx.initialize_from_forward_context(
|
||||
kv_cache_config,
|
||||
forward_context,
|
||||
_COPY_FUNCS,
|
||||
[torch.zeros(4, 8, dtype=torch.int32)],
|
||||
)
|
||||
assert ctx.state_group_indices.tolist() == [0, 0, 0, 0, 0]
|
||||
assert ctx.state_conv_widths.tolist() == [4, 0, 4, 0, 12]
|
||||
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# stage_postprocess_inputs_to_gpu: single-pass staging into pinned views
|
||||
# -----------------------------------------------------------------------------
|
||||
@@ -620,7 +796,7 @@ def _run_gpu_postprocess(
|
||||
*,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
forward_context: dict[str, Any],
|
||||
copy_funcs: tuple,
|
||||
copy_funcs: MambaStateCopyFuncsByType,
|
||||
block_table: torch.Tensor,
|
||||
req_ids: list[str],
|
||||
num_accepted_tokens: list[int],
|
||||
|
||||
Reference in New Issue
Block a user