mirror of
https://github.com/lightseekorg/tokenspeed.git
synced 2026-12-04 10:26:50 +08:00
## Summary `test/runtime/test_flashmla_cache_groups.py::test_chunked_mla_read_range_checks_planned_virtual_slots` calls `registry.create_paged_router`, but the test module no longer imports `registry`: #3939 removed the module-level import when it unified plugin registration, and #3986 then added this test using it. All three backend cases (`mla`, `trtllm_mla`, `tokenspeed_mla`) fail with `NameError: name 'registry' is not defined` in the B200 `ut-runtime-1gpu-part-ii` job on main. This imports `tokenspeed.runtime.layers.attention.registry` inside the test, next to its other runtime imports. ## Tests - `test/runtime/test_flashmla_cache_groups.py`: 13 passed on a Blackwell GPU (the three cases above failed before). - `pre-commit run --all-files`: passed. Signed-off-by: Nicolas Perrin <nperrin.ai@gmail.com>
373 lines
15 KiB
Python
373 lines
15 KiB
Python
# Copyright (c) 2026 LightSeek Foundation
|
|
#
|
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
# of this software and associated documentation files (the "Software"), to deal
|
|
# in the Software without restriction, including without limitation the rights
|
|
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
# copies of the Software, and to permit persons to whom the Software is
|
|
# furnished to do so, subject to the following conditions:
|
|
#
|
|
# The above copyright notice and this permission notice shall be included in
|
|
# all copies or substantial portions of the Software.
|
|
#
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
# SOFTWARE.
|
|
|
|
"""FlashMLABackend decode metadata behind the cache-group router.
|
|
|
|
The router's GroupTableStacks is now the one place scheduler (logical)
|
|
blocks become kernel pages; the FlashMLA leaf consumes the pre-expanded
|
|
[bs, max_num_pages] table and copies it into its persistent buffers.
|
|
Exercises the metadata math only, with optional vendor kernels and prefill
|
|
wrappers mocked at the import boundary. Runs on CPU and any CUDA/ROCm device.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
from importlib import util
|
|
from types import ModuleType
|
|
from unittest.mock import Mock
|
|
|
|
import pytest
|
|
import torch
|
|
|
|
_TEST_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
sys.path.insert(0, _TEST_DIR)
|
|
sys.path.insert(0, os.path.dirname(_TEST_DIR))
|
|
|
|
from test.runtime.conftest import MLA_KV_LORA_RANK as _KV_LORA_RANK
|
|
from test.runtime.conftest import MLA_LATENT_DIM as _LATENT_DIM
|
|
from test.runtime.conftest import MLA_QK_ROPE_DIM as _QK_ROPE_DIM
|
|
from test.runtime.conftest import make_kimi_pool as _make_pool
|
|
from test.runtime.conftest import requires_cuda
|
|
|
|
from ci_system.ci_register import register_cuda_ci
|
|
|
|
register_cuda_ci(est_time=60, suite="runtime-1gpu")
|
|
|
|
from tokenspeed.runtime.layers.attention.backends.paged.group_tables import (
|
|
GroupTableSpec,
|
|
GroupTableStacks,
|
|
)
|
|
from tokenspeed.runtime.layers.attention.configs.base import AttnConfig
|
|
from tokenspeed.runtime.layers.attention.configs.mla import MLAConfig
|
|
|
|
_KERNEL_PAGE = 64
|
|
_FULL = "full_attention"
|
|
|
|
|
|
@pytest.fixture(params=["cpu", pytest.param("cuda", marks=requires_cuda)])
|
|
def device(request):
|
|
return request.param
|
|
|
|
|
|
@pytest.fixture
|
|
def flashmla(monkeypatch):
|
|
kernel = Mock(
|
|
side_effect=AssertionError("metadata tests must not run attention kernels")
|
|
)
|
|
wrappers = Mock(side_effect=lambda *args, **kwargs: Mock(spec=[]))
|
|
vendor_exports = {
|
|
"tokenspeed_kernel.ops.attention.mha.cuda": {
|
|
"flash_attn_varlen_func": kernel,
|
|
},
|
|
"tokenspeed_kernel.ops.attention.mha.flashinfer": {
|
|
"BatchMLAPagedAttentionWrapper": wrappers,
|
|
"BatchPrefillWithRaggedKVCacheWrapper": wrappers,
|
|
},
|
|
"tokenspeed_kernel.ops.attention.mla.cuda": {
|
|
"flash_mla_with_kvcache": kernel,
|
|
"flash_mla_sparse_fwd": kernel,
|
|
"get_mla_metadata": Mock(side_effect=lambda: (object(), None)),
|
|
},
|
|
}
|
|
path = os.path.join(
|
|
os.path.dirname(_TEST_DIR),
|
|
"python/tokenspeed/runtime/layers/attention/backends/paged/flashmla.py",
|
|
)
|
|
spec = util.spec_from_file_location("_flashmla_cache_groups", path)
|
|
module = util.module_from_spec(spec)
|
|
with monkeypatch.context() as isolated:
|
|
for name, exports in vendor_exports.items():
|
|
vendor = ModuleType(name)
|
|
vendor.__dict__.update(exports)
|
|
isolated.setitem(sys.modules, name, vendor)
|
|
isolated.setitem(sys.modules, spec.name, module)
|
|
spec.loader.exec_module(module)
|
|
monkeypatch.setattr(module, "get_flashinfer_workspace_size", Mock(return_value=1))
|
|
return module
|
|
|
|
|
|
def _mla_spec(backend_name="flashmla"):
|
|
return MLAConfig(
|
|
backend_name=backend_name,
|
|
num_attention_heads=16,
|
|
num_kv_heads=1,
|
|
head_dim=_LATENT_DIM,
|
|
attn_tp_size=1,
|
|
kv_lora_rank=_KV_LORA_RANK,
|
|
qk_nope_head_dim=128,
|
|
qk_rope_head_dim=_QK_ROPE_DIM,
|
|
v_head_dim=128,
|
|
scaling=192**-0.5,
|
|
kv_cache_dim=_LATENT_DIM,
|
|
)
|
|
|
|
|
|
def _make_flashmla_backend(
|
|
flashmla, pool, speculative_num_draft_tokens: int, is_draft: bool
|
|
):
|
|
spec = _mla_spec()
|
|
config = AttnConfig(
|
|
device=pool.arena.device,
|
|
dtype=torch.bfloat16,
|
|
kv_cache_dtype=torch.bfloat16,
|
|
kernel_page_size=_KERNEL_PAGE,
|
|
context_len=8 * pool.arena.prefix_granularity,
|
|
max_bs=8,
|
|
max_resident_requests=8,
|
|
kv_cache_quant_method="",
|
|
speculative_num_draft_tokens=speculative_num_draft_tokens,
|
|
is_draft=is_draft,
|
|
components=(spec,),
|
|
)
|
|
backend = flashmla.FlashMLABackend(config, spec, kernel_page_size=_KERNEL_PAGE)
|
|
backend.set_cache_pool(pool)
|
|
return backend
|
|
|
|
|
|
def _stacks_for(backend, pool, max_bs: int = 4) -> GroupTableStacks:
|
|
"""The router-side expansion stage: logical blocks -> this leaf's pages."""
|
|
return GroupTableStacks(
|
|
[
|
|
GroupTableSpec(
|
|
group_id=_FULL,
|
|
block_granularity=pool.arena.prefix_granularity,
|
|
kernel_page_size=backend.kernel_page_size,
|
|
max_num_pages=backend.max_num_pages,
|
|
atom_pages_per_block=(
|
|
pool.arena.prefix_granularity // backend.kernel_page_size
|
|
),
|
|
)
|
|
],
|
|
max_bs=max_bs,
|
|
max_tokens_per_req=backend.spec_num_tokens,
|
|
max_extend_tokens=0,
|
|
device=backend.device,
|
|
)
|
|
|
|
|
|
def _refresh_from_logical(backend, pool, logical_rows, seq_lens_cpu):
|
|
"""Expand the logical full-history table through the router's stacks and
|
|
refresh the leaf from the resulting kernel-page view (the unified path)."""
|
|
bs = len(logical_rows)
|
|
stacks = _stacks_for(backend, pool, max_bs=max(bs, 4))
|
|
raw = torch.tensor(logical_rows, dtype=torch.int32, device=backend.device)
|
|
stacks.fill(bs, bs, {_FULL: raw})
|
|
seq_lens = torch.tensor(seq_lens_cpu, device=backend.device, dtype=torch.int32)
|
|
backend.init_cuda_graph_state(max_bs=max(bs, 4))
|
|
backend.refresh_decode_metadata(bs, bs, seq_lens, stacks.table(_FULL, bs))
|
|
return stacks
|
|
|
|
|
|
def test_flashmla_grouped_decode_block_table_follows_the_stack_expansion(
|
|
flashmla, device
|
|
) -> None:
|
|
pool = _make_pool(device, usable_pages=6)
|
|
page_size = pool.arena.prefix_granularity # logical (scheduler) page size
|
|
ratio = page_size // _KERNEL_PAGE
|
|
|
|
# Two requests, each with two logical history pages.
|
|
logical_rows = [[3, 5], [1, 4]]
|
|
seq_lens_cpu = [page_size + 41, page_size + 7]
|
|
|
|
backend = _make_flashmla_backend(flashmla, pool, 1, False)
|
|
_refresh_from_logical(backend, pool, logical_rows, seq_lens_cpu)
|
|
|
|
meta = backend.forward_decode_metadata
|
|
# The leaf's table is the kernel-page expansion of the logical
|
|
# full-history table: each logical page -> `ratio` consecutive kernel pages.
|
|
expected_row0 = []
|
|
for lpage in logical_rows[0]:
|
|
expected_row0.extend(lpage * ratio + k for k in range(ratio))
|
|
got_row0 = meta.page_table[0, : len(expected_row0)].tolist()
|
|
assert got_row0 == expected_row0, (got_row0, expected_row0)
|
|
|
|
|
|
def test_flashmla_grouped_prefill_index_math(flashmla, device) -> None:
|
|
"""The per-token slots built from the expanded host kernel-page table
|
|
(flashinfer paged prefill, plan page_size=1).
|
|
|
|
Validates the metadata math directly through the module helper. The
|
|
flashinfer paged-prefill READ (wrapper.plan) needs a live serving wrapper
|
|
state and is validated end-to-end on a real model, not here.
|
|
"""
|
|
pool = _make_pool(device, usable_pages=6)
|
|
page_size = pool.arena.prefix_granularity
|
|
backend = _make_flashmla_backend(flashmla, pool, 1, False)
|
|
|
|
# The leaf consumes the host KERNEL-page table the router's stacks expand.
|
|
logical_table = torch.tensor([[3, 5]], dtype=torch.int32)
|
|
stacks = _stacks_for(backend, pool)
|
|
table_cpu = stacks.host_table(_FULL, logical_table, 1)
|
|
|
|
# Per-token slots: token t -> table[0, t // p] * p + t % p, which by
|
|
# the expansion invariant equals the logical-table slot. Position
|
|
# page_size+2 -> logical index 1 -> page 5, offset 2.
|
|
slots = flashmla._per_token_kv_indices(
|
|
table_cpu, torch.tensor([page_size + 3]), page_size=_KERNEL_PAGE
|
|
)
|
|
assert slots.tolist() == [3 * page_size + t for t in range(page_size)] + [
|
|
5 * page_size + t for t in range(3)
|
|
]
|
|
|
|
|
|
def test_flashmla_grouped_target_verify_uses_the_whole_window(flashmla, device) -> None:
|
|
"""Target verify (spec_num_tokens>1, non-draft decode) bakes the whole
|
|
window width into the decode views and clamps short rows to it."""
|
|
pool = _make_pool(device, usable_pages=6)
|
|
page_size = pool.arena.prefix_granularity
|
|
spec = 4
|
|
backend = _make_flashmla_backend(flashmla, pool, spec, False)
|
|
|
|
# Verify-window widths: target -> spec, draft -> 1 (the leaf property).
|
|
assert backend.verify_floor == spec
|
|
draft = _make_flashmla_backend(flashmla, pool, spec, True)
|
|
assert draft.verify_floor == 1
|
|
|
|
logical_rows = [[3, 5]]
|
|
seq_lens_cpu = [page_size + 11]
|
|
_refresh_from_logical(backend, pool, logical_rows, seq_lens_cpu)
|
|
|
|
meta = backend.forward_decode_metadata
|
|
assert meta.q_len_per_req == spec
|
|
# A row shorter than the window clamps up to it.
|
|
_refresh_from_logical(backend, pool, logical_rows, [1])
|
|
assert backend.forward_decode_metadata.seq_lens_k.tolist()[0] == spec
|
|
|
|
|
|
def test_flashmla_draft_consumes_staged_page_table(flashmla, device) -> None:
|
|
"""A draft leaf reads the batch-ordered draft page table (the staging
|
|
already expanded it into this leaf's kernel pages) as-is."""
|
|
pool = _make_pool(device, usable_pages=6)
|
|
page_size = pool.arena.prefix_granularity
|
|
ratio = page_size // _KERNEL_PAGE
|
|
backend = _make_flashmla_backend(flashmla, pool, 1, True)
|
|
|
|
# The staged table holds KERNEL page ids (already expanded at publish).
|
|
logical_rows = [[3, 5], [1, 4]]
|
|
staged_rows = [
|
|
[lpage * ratio + k for lpage in row for k in range(ratio)]
|
|
for row in logical_rows
|
|
]
|
|
staged = torch.tensor(staged_rows, device=device, dtype=torch.int32)
|
|
seq_lens = torch.tensor(
|
|
[page_size + 41, page_size + 7], device=device, dtype=torch.int32
|
|
)
|
|
backend.init_cuda_graph_state(max_bs=4)
|
|
backend.refresh_decode_metadata(2, 2, seq_lens, staged)
|
|
meta = backend.forward_decode_metadata
|
|
got_row0 = meta.page_table[0, : len(staged_rows[0])].tolist()
|
|
assert got_row0 == staged_rows[0], (got_row0, staged_rows[0])
|
|
|
|
|
|
def _read_limit_config(spec, degree):
|
|
return AttnConfig(
|
|
device="cuda",
|
|
dtype=torch.bfloat16,
|
|
kv_cache_dtype=torch.bfloat16,
|
|
kernel_page_size=_KERNEL_PAGE,
|
|
context_len=512,
|
|
max_bs=2,
|
|
max_resident_requests=2,
|
|
kv_cache_quant_method="",
|
|
kvp_size=degree,
|
|
kvp_group=tuple(range(degree)),
|
|
components=(spec,),
|
|
)
|
|
|
|
|
|
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA metadata required")
|
|
@pytest.mark.parametrize("degree", [1, 4])
|
|
def test_flashmla_prefill_read_range_checks_planned_virtual_slots(flashmla, degree):
|
|
from test.runtime.cache_pool_test_utils import make_mla_pool_at_read_limit
|
|
|
|
from tokenspeed.runtime.layers.attention.backends.paged.router import (
|
|
CacheGroupRouter,
|
|
)
|
|
|
|
spec = _mla_spec()
|
|
config = _read_limit_config(spec, degree)
|
|
router = CacheGroupRouter(
|
|
lambda gid, grain: flashmla.FlashMLABackend(
|
|
config, spec, kernel_page_size=_KERNEL_PAGE
|
|
),
|
|
is_draft=False,
|
|
spec_num_tokens=1,
|
|
device="cuda",
|
|
consumed_group_ids=("history",),
|
|
)
|
|
invalid = make_mla_pool_at_read_limit(degree, overflow=True)
|
|
with pytest.raises(ValueError, match="MLA prefill read slots"):
|
|
router.set_cache_pool(invalid)
|
|
assert router.cache_pool is None
|
|
assert router.leaves == {}
|
|
|
|
valid = make_mla_pool_at_read_limit(degree, overflow=False)
|
|
router.set_cache_pool(valid)
|
|
router.configure_runtime()
|
|
router.init_cuda_graph_state(max_bs=2)
|
|
geometry, leaves, stacks = router.geometry, router.leaves, router.stacks
|
|
leaf = leaves["history"]
|
|
pages, lengths = leaf.page_table_buf, leaf.seq_lens_buf
|
|
wrapper = leaf.prefill_wrapper_paged
|
|
pages.fill_(7)
|
|
lengths.fill_(11)
|
|
|
|
with pytest.raises(ValueError, match="MLA prefill read slots"):
|
|
router.set_cache_pool(invalid)
|
|
assert router.cache_pool is valid and leaf.cache_pool is valid
|
|
assert router.geometry is geometry and router.leaves is leaves
|
|
assert router.leaves["history"] is leaf and router.stacks is stacks
|
|
assert leaf.page_table_buf is pages and leaf.seq_lens_buf is lengths
|
|
assert leaf.prefill_wrapper_paged is wrapper
|
|
assert pages.eq(7).all() and lengths.eq(11).all()
|
|
|
|
# The final page representable by the int32 per-token read mapping.
|
|
table = torch.tensor([[(1 << 31) // 64 - 1]], dtype=torch.int32)
|
|
slots = flashmla._per_token_kv_indices(table, torch.tensor([64]), page_size=64)
|
|
assert slots[-1].item() == torch.iinfo(torch.int32).max
|
|
|
|
|
|
@pytest.mark.skipif(
|
|
not torch.cuda.is_available() or torch.version.hip is not None,
|
|
reason="NVIDIA MLA backends required",
|
|
)
|
|
@pytest.mark.parametrize("backend_name", ["mla", "trtllm_mla", "tokenspeed_mla"])
|
|
def test_chunked_mla_read_range_checks_planned_virtual_slots(backend_name, monkeypatch):
|
|
from test.runtime.cache_pool_test_utils import make_mla_pool_at_read_limit
|
|
|
|
from tokenspeed.runtime.configs.model_config import AttentionArch
|
|
from tokenspeed.runtime.layers.attention import registry
|
|
from tokenspeed.runtime.utils.env import global_server_args_dict
|
|
|
|
if backend_name == "tokenspeed_mla" and torch.cuda.get_device_capability()[0] != 10:
|
|
pytest.skip("CuTe MLA requires Blackwell")
|
|
monkeypatch.setitem(global_server_args_dict, "numerics", "auto")
|
|
degree = 1 if backend_name == "trtllm_mla" else 4
|
|
router = registry.create_paged_router(
|
|
_read_limit_config(_mla_spec(backend_name), degree), AttentionArch.MLA
|
|
)
|
|
valid = make_mla_pool_at_read_limit(degree, overflow=False)
|
|
router.set_cache_pool(valid)
|
|
with pytest.raises(ValueError, match="MLA prefill read slots"):
|
|
router.set_cache_pool(make_mla_pool_at_read_limit(degree, overflow=True))
|
|
assert router.cache_pool is valid
|