[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:
Harry Huang
2026-08-31 05:57:56 +00:00
committed by GitHub
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
124 changed files with 19424 additions and 450 deletions
+312
View File
@@ -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()
+39 -48
View File
@@ -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)
+46
View File
@@ -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(