Files
tokenspeed/test/runtime/cache_pool_test_utils.py
WangBo d41c0b3927 refactor(cache): use int64 token write slots across backends (#3986)
## Summary

Use int64 for token write locations throughout the runtime. In a sharded
or strided cache, expanding an int32 page ID into a token slot can
exceed `INT32_MAX` even when the page table and the owner-local
allocation both fit. Widening before multiplication lets the runtime
address the full planned pool.

- The group router, DFlash, QSA (including the gfx950 decode monokernel)
and sparse KV offload produce and retain int64 write locations through
metadata refresh, graph replay and cache writes. The offload planner
accounts for the wider metadata.
- Scheduler page IDs and page tables remain int32. Backends that pass
flattened int32 read indices to attention kernels check their own read
ranges when binding a pool. A failed rebind preserves the previous pool.
- The group specification and the cache-transfer protocol keep their
existing layout. Model integrations inherit the slot width from the
host.

## Verification

- Added boundary coverage for sharded and strided tables, sparse reads,
graph replay, and offload metadata sizing and writeback.
- Ran the runtime and kernel suites on NVIDIA B300. They covered group
routing and pool rebinding, DFlash, QSA, FlashMLA, DSA, MSA,
cache-transfer serialization, and KV offload. Result: 1,157 passed and
19 skipped.
- On gfx950, the Muse Spark target launcher accepts the router’s int64
slot vector; its sequence lengths stay int32.
- The gfx950 verify-versus-decode test stages a recent slot above 2³¹
and checks the staged keys, positions and output against single-token
decode steps.
- A 260 GiB cache allocation resolved virtual slots 2,181,020,817 and
2,181,020,818 to different owner-local rows. BF16 keys read back
byte-for-byte after replaying graph-captured metadata refresh.
- `pre-commit run --all-files` passed. Ascend device execution remains
unverified.

---------

Signed-off-by: wangbo981016 <wangbo981016@gmail.com>
2026-11-30 21:33:12 +08:00

552 lines
18 KiB
Python

from __future__ import annotations
import inspect
import math
from collections.abc import Iterator
import torch
from tokenspeed.runtime.layers.attention.kv_cache.arena import CacheArena
from tokenspeed.runtime.layers.attention.kv_cache.base import CachePool
from tokenspeed.runtime.layers.attention.kv_cache.mha import MHATokenToKVPool
from tokenspeed.runtime.layers.attention.kv_cache.mla import MLATokenToKVPool
from tokenspeed.runtime.layers.attention.kv_cache.qwen4_exp import (
QWEN4_EXP_QSA_CACHE_GROUP,
QWEN4_EXP_QSA_RECENT_CACHE_GROUP,
qsa_compressed_field,
qsa_raw_key_field,
qsa_rope_position_field,
)
from tokenspeed.runtime.layers.attention.kv_cache.recipes import spec
from tokenspeed.runtime.layers.attention.kv_cache.recipes.plan import (
FLAT_KV_PLANE,
CacheFieldSpec,
cache_dtype_name,
mxfp8_kv_scale_fields,
pack,
scatter_stored_dtype_name,
)
def specs_for_layers(
*,
layer_types,
group_ids,
prefix_granularity,
sliding_window_tokens=None,
pd_disaggregation_enabled=False,
):
"""The group specs a layer vocabulary produces.
A group must declare fields, so this supplies a one-byte placeholder per
layer: the subject here is the scheduler semantics (kind, window, block
span), not the bytes.
"""
return tuple(
group_spec
for group_spec, _ in spec.group(
layer_types=layer_types,
group_ids=group_ids,
sliding_window_tokens=sliding_window_tokens,
prefix_granularity=prefix_granularity,
pd_disaggregation_enabled=pd_disaggregation_enabled,
fields_for_layer=lambda layer_id, group_id, occurrence: (
CacheFieldSpec(
f"layer.{layer_id}.probe", f"unit.{occurrence}", (1,), "uint8"
),
),
)
)
def one_group(group_id: str, *fields, **spec_kwargs):
"""One ``(spec, fields)`` pair for a plan under test.
A whole-group declaration, the way a recipe declares a group that is not
per-layer: the id is spelled once, in its spec, and its fields hang off
it. Row geometry defaults so a byte-layout test need not restate
scheduler semantics. ``group`` (the pipeline stage) is the other way in.
"""
spec_kwargs.setdefault("attn_kind", "full_history")
if spec_kwargs["attn_kind"] != "state":
spec_kwargs.setdefault("rows_per_page", spec_kwargs.pop("page_size", 1))
spec_kwargs.setdefault("entry_stride_tokens", 1)
return spec.CacheGroupSpec(
group_id=group_id, **spec_kwargs, replayable=False
), tuple(fields)
def plan_group_specs(plan) -> tuple[spec.CacheGroupSpec, ...]:
"""Row-geometry specs for every group the plan names.
The arena publishes a contract unconditionally, so a test that only
exercises field geometry still needs specs. Derive them from the plan
rather than restating numbers: a group's CacheBlock spans
``prefix_granularity / cache_blocks_per_lcm_block`` tokens, declared here
as one row per token. Tests whose subject *is* the geometry or the
kind/transfer policy pass their own specs instead.
"""
return tuple(
spec.CacheGroupSpec(
group_id=group.group_id,
attn_kind="full_history",
rows_per_page=plan.prefix_granularity // group.cache_blocks_per_lcm_block,
entry_stride_tokens=1,
replayable=False,
)
for group in plan.groups
)
class MinimalCacheView(CachePool):
"""The smallest constructible cache view.
``CachePool`` is abstract in exactly the four accessors a view owes its
kernels, so this stub doubles as the list of what a real pool must add.
Use it to exercise view-layer behaviour the base class owns (arena
ownership, dtype, layer window, the scheduler bridge) without dragging in
a family's kernel buffers.
"""
layer_num = 0
def get_key_buffer(self, layer_id: int) -> torch.Tensor:
raise AssertionError("not exercised")
def get_value_buffer(self, layer_id: int) -> torch.Tensor:
raise AssertionError("not exercised")
def get_kv_buffer(self, layer_id: int):
raise AssertionError("not exercised")
def set_kv_buffer(self, layer, loc, cache_k, cache_v) -> None:
raise AssertionError("not exercised")
def make_arena(plan, device: str = "cuda", **kwargs) -> CacheArena:
"""Allocate the arena the pool(s) under test are compute views onto."""
if "cache_group_specs" not in kwargs:
kwargs["cache_group_specs"] = plan_group_specs(plan)
return CacheArena(plan, device, **kwargs)
def make_pool(pool_cls, plan, *, device="cpu", arena=None, **kwargs):
"""Build one pool as a compute view over ``plan``'s arena.
Tests name a plan and the view's compute parameters; the arena is
created here (or shared, when several views of one arena are under
test) so no test has to restate the allocation contract.
"""
arena_kwargs = {
key: kwargs.pop(key)
for key in ("cache_group_specs", "token_capacity")
if key in kwargs
}
if arena is None:
arena = make_arena(plan, device, **arena_kwargs)
elif arena_kwargs:
raise TypeError("arena parameters cannot be passed alongside a shared arena")
return arena, pool_cls(arena=arena, **kwargs)
def make_mha_pool_for_groups(
cache_group_specs: tuple[spec.CacheGroupSpec, ...], *, device: str
) -> MHATokenToKVPool:
"""Build a small real MHA pool publishing the supplied group contracts.
Each history group gets one layer's K/V fields; state groups get a state
field. Thirty-two parents cover the page IDs used by metadata tests.
"""
grain = math.lcm(
*(
group.block_granularity
for group in cache_group_specs
if group.attn_kind != "state"
)
)
groups = []
for layer, group in enumerate(cache_group_specs):
if group.attn_kind == "state":
fields = (
CacheFieldSpec(
f"layer.{layer}.state", f"state.{layer}", (1,), "float16"
),
)
else:
fields = tuple(
CacheFieldSpec(
f"layer.{layer}.{name}",
f"unit.{layer}.{name}",
(group.rows_per_page, 1, 1),
"float16",
)
for name in ("k", "v")
)
groups.append((group, fields))
layout = pack(
groups,
prefix_granularity=grain,
cache_blocks_per_lcm_block={
group.group_id: (
1 if group.attn_kind == "state" else grain // group.block_granularity
)
for group in cache_group_specs
},
alignment=1,
max_padding_fraction=float("inf"),
)
arena = CacheArena(layout.bind(32), device, cache_group_specs=cache_group_specs)
return MHATokenToKVPool(arena, torch.float16, 1, 1, len(cache_group_specs), 0)
def make_qsa_pool_for_layers(
*,
device: str,
layer_ids: tuple[int, ...],
field_layer_offset: int,
num_layers: int,
num_lcm_blocks: int,
kv_head_dim: int,
enable_memory_saver: bool,
) -> MHATokenToKVPool:
"""Build a real pool with tiny QSA fields for the specified global layers.
The pool's layer window can exclude an adjacent draft layer's fields.
QSA keys have eight columns, four recent rows and 64 compressed rows;
K/V geometry is independent and uses ``kv_head_dim`` columns.
"""
specs = (
spec.CacheGroupSpec("full_attention", "full_history", 256, 1, replayable=False),
spec.CacheGroupSpec(
QWEN4_EXP_QSA_CACHE_GROUP, "full_history", 64, 4, replayable=False
),
spec.CacheGroupSpec(
QWEN4_EXP_QSA_RECENT_CACHE_GROUP, "full_history", 64, 1, replayable=False
),
)
kv_fields = tuple(
CacheFieldSpec(
f"layer.{layer}.{name}",
f"layer.{layer}.{name}",
(256, 1, kv_head_dim),
"bfloat16",
)
for layer in range(field_layer_offset, field_layer_offset + num_layers)
for name in ("k", "v")
)
compressed = tuple(
CacheFieldSpec(
qsa_compressed_field(layer),
qsa_compressed_field(layer),
(64, 1, 8),
"bfloat16",
)
for layer in layer_ids
)
recent = tuple(
CacheFieldSpec(field_id, field_id, shape, dtype)
for layer in layer_ids
for field_id, shape, dtype in (
(qsa_raw_key_field(layer), (4, 1, 8), "bfloat16"),
(qsa_rope_position_field(layer), (3,), "int64"),
)
)
layout = pack(
tuple(zip(specs, (kv_fields, compressed, recent))),
prefix_granularity=256,
cache_blocks_per_lcm_block={group.group_id: 1 for group in specs},
alignment=1,
max_padding_fraction=float("inf"),
)
arena = CacheArena(
layout.bind(num_lcm_blocks),
device,
cache_group_specs=specs,
enable_memory_saver=enable_memory_saver,
)
return MHATokenToKVPool(
arena,
torch.bfloat16,
1,
kv_head_dim,
num_layers,
0,
field_layer_offset=field_layer_offset,
)
def plan_fields(
fields,
*,
prefix_granularity,
budget_bytes=None,
num_lcm_blocks=None,
**kwargs,
):
"""Solve a layout and bind capacity the way the recipes do.
``fields`` is the ``{group_id: fields}`` map a recipe field builder
returns; declarations are formed here, the same join the recipes do.
"""
layout = pack(
tuple(
one_group(group_id, *declared, rows_per_page=prefix_granularity)
for group_id, declared in fields.items()
),
prefix_granularity=prefix_granularity,
**kwargs,
)
if budget_bytes is not None:
# Parent 0 backs logical null page 0 and is never schedulable.
num_lcm_blocks = budget_bytes // layout.lcm_block_bytes - 1
return layout.bind(num_lcm_blocks)
def make_layer_group_ids(
*,
layer_num: int,
layer_types: tuple[str, ...] = (),
sliding_window_tokens: int | tuple[int | None, ...] | None = None,
) -> tuple[str, ...]:
"""Derive per-layer cache group ids the way the recipes do."""
if not layer_types:
return ("full_attention",) * layer_num
return tuple(
spec.layer_group_ids(
layer_types=layer_types,
sliding_window_tokens=sliding_window_tokens,
)
)
def make_mha_memory_plan(
*,
size: int,
prefix_granularity: int,
layer_num: int,
kv_heads: int,
head_dim: int,
dtype: torch.dtype,
layer_types: tuple[str, ...] = (),
sliding_window_tokens: int | tuple[int | None, ...] | None = None,
mxfp8: bool = False,
):
"""An MHA plan the way the recipe builds one: group, pack, bind."""
if size % prefix_granularity:
raise ValueError("test pool size must be divisible by prefix_granularity")
# Resolve the labels the way a recipe does: one per layer, full-history
# when the caller declares none.
if not layer_types:
layer_types = ("full_attention",) * layer_num
group_ids = make_layer_group_ids(
layer_num=layer_num,
layer_types=layer_types,
sliding_window_tokens=sliding_window_tokens,
)
kv_dtype = (
cache_dtype_name(torch.float8_e4m3fn)
if mxfp8
else scatter_stored_dtype_name(dtype)
)
shape = (prefix_granularity, kv_heads, head_dim)
def fields_for_layer(layer_id, group_id, occurrence):
fields = (
CacheFieldSpec(
f"layer.{layer_id}.k", f"unit.{occurrence}.k", shape, kv_dtype
),
CacheFieldSpec(
f"layer.{layer_id}.v", f"unit.{occurrence}.v", shape, kv_dtype
),
)
if not mxfp8:
return fields
# The production builder, so a test plan cannot declare a scale shape
# the recipes would never emit.
return fields + mxfp8_kv_scale_fields(
layer_id=layer_id,
occurrence=occurrence,
kv_heads=kv_heads,
head_dim=head_dim,
prefix_granularity=prefix_granularity,
)
groups = spec.group(
layer_types=layer_types,
group_ids=group_ids,
sliding_window_tokens=sliding_window_tokens,
prefix_granularity=prefix_granularity,
fields_for_layer=fields_for_layer,
)
layout = pack(
groups,
prefix_granularity=prefix_granularity,
cache_blocks_per_lcm_block={gid: 1 for gid in set(group_ids)},
alignment=1,
max_padding_fraction=1.0,
)
return layout.bind(size // prefix_granularity)
def make_mla_pool_at_read_limit(degree: int, *, overflow: bool) -> MLATokenToKVPool:
"""A meta pool with 128-token blocks, 64-token subpages and 2x physical stride."""
grain, width = 128, 576
group = spec.CacheGroupSpec(
"history", "full_history", grain, 1, shard_count=degree, replayable=False
)
state = spec.CacheGroupSpec("state", "state", None, None, replayable=False)
kv = CacheFieldSpec(
"layer.0.latent_kv",
FLAT_KV_PLANE,
(grain, 1, width),
"bfloat16",
exact_page_stride=False,
)
padding = CacheFieldSpec(
"layer.1.ssm", FLAT_KV_PLANE, (2 * grain, width), "bfloat16"
)
layout = pack(
((group, (kv,)), (state, (padding,))),
prefix_granularity=grain,
cache_blocks_per_lcm_block={"history": 1, "state": 1},
alignment=1,
max_padding_fraction=float("inf"),
)
# The last token of a real block is at block_id * 2 * grain + grain - 1.
parents = ((1 << 31) - grain) // (2 * grain * degree) + int(overflow)
arena = CacheArena(layout.bind(parents), "meta", cache_group_specs=(group, state))
return MLATokenToKVPool(
arena, torch.bfloat16, torch.bfloat16, "none", 512, 64, 1, 0
)
def make_mla_memory_plan(
*,
size: int,
prefix_granularity: int,
layer_num: int,
latent_width: int,
dtype: torch.dtype,
):
"""An MLA plan: one full-attention group, one latent field per layer."""
if size % prefix_granularity:
raise ValueError("test pool size must be divisible by prefix_granularity")
latent_dtype = scatter_stored_dtype_name(dtype)
groups = spec.group(
layer_types=("full_attention",) * layer_num,
group_ids=("full_attention",) * layer_num,
sliding_window_tokens=None,
prefix_granularity=prefix_granularity,
fields_for_layer=lambda layer_id, group_id, occurrence: (
CacheFieldSpec(
f"layer.{layer_id}.latent_kv",
f"slot.{occurrence}",
(prefix_granularity, 1, latent_width),
latent_dtype,
),
),
)
layout = pack(
groups,
prefix_granularity=prefix_granularity,
cache_blocks_per_lcm_block={"full_attention": 1},
alignment=1,
max_padding_fraction=1.0,
)
return layout.bind(size // prefix_granularity)
def binding_state(node: object) -> dict[str, object]:
"""Every attribute of ``node``, reduced to what a fresh-vs-rebound comparison sees."""
return {name: _reduced(value, set()) for name, value in vars(node).items()}
def _reduced(value: object, seen: set[int]) -> object:
if isinstance(value, torch.Tensor):
return (
"tensor",
tuple(value.shape),
value.stride(),
value.dtype,
str(value.device),
)
if isinstance(value, dict):
return (
"dict",
tuple(
(str(key), _reduced(item, seen))
for key, item in sorted(value.items(), key=lambda kv: str(kv[0]))
),
)
if isinstance(value, (list, tuple)):
return (type(value).__name__, tuple(_reduced(item, seen) for item in value))
if isinstance(value, (set, frozenset)):
return (type(value).__name__, sorted(map(str, value)))
if isinstance(value, (bool, int, float, str, type(None))):
return value
if isinstance(value, (torch.dtype, torch.device)):
return str(value)
if (
hasattr(value, "__dict__")
and not isinstance(value, type)
and not callable(value)
):
if id(value) in seen:
return type(value).__name__
seen.add(id(value))
return (
type(value).__name__,
tuple(
(name, _reduced(item, seen))
for name, item in sorted(vars(value).items())
),
)
return type(value).__name__
def storages_of(*tensors: torch.Tensor) -> set[int]:
"""The untyped storages behind ``tensors``, so views at any offset are
recognised; an empty tensor has no storage to alias."""
return {tensor.untyped_storage().data_ptr() for tensor in tensors if tensor.numel()}
def reachable_tensors(node: object) -> list[torch.Tensor]:
"""Every tensor reachable from ``node``'s attributes, for an alias set taken before a rebind."""
return [
tensor for value in vars(node).values() for tensor in _tensors(value, set())
]
def assert_no_alias(node: object, storages: set[int]) -> None:
"""Fail if any tensor reachable from ``node``'s attributes lives in ``storages``."""
for name, value in vars(node).items():
for tensor in _tensors(value, set()):
assert (
not tensor.numel()
or tensor.untyped_storage().data_ptr() not in storages
), f"{name} still aliases the old pool"
def _tensors(value: object, seen: set[int]) -> Iterator[torch.Tensor]:
if isinstance(value, torch.Tensor):
yield value
elif isinstance(value, dict):
for item in value.values():
yield from _tensors(item, seen)
elif isinstance(value, (list, tuple, set, frozenset)):
for item in value:
yield from _tensors(item, seen)
elif inspect.isfunction(value) and value.__closure__:
for cell in value.__closure__:
yield from _tensors(cell.cell_contents, seen)
elif isinstance(value, torch.nn.Module) or (
hasattr(value, "__dict__")
and not isinstance(value, type)
and not callable(value)
):
if id(value) in seen:
return
seen.add(id(value))
for item in vars(value).values():
yield from _tensors(item, seen)