Files
tokenspeed/test/runtime/test_cache_loc_kernel.py
Fan Yang baa2b46ba6 perf(dsv41,kernel): eliminate serving-time Triton JIT specializations and warmup gaps (#3917)
## Summary
Fixes several serving-time Triton JIT specializations and startup warmup
gaps observed on DeepSeek V4.1-Flash workloads under
`TOKENSPEED_JIT_COMPILE_CHECK=error`:

1. **`fused_decode_input_prep_kernel`
(`python/tokenspeed/runtime/execution/cache_loc_kernel.py`):** Replace
the copy-pasted `do_not_specialize=["max_pages"]` with
`do_not_specialize=["uniform_input_length"]`. Also add
`uniform_input_length` to `compute_out_cache_loc_kernel` and use
`max_draft_prefix` for `dflash_prepare_decode_kernel`, allowing
compilation reuse as decode and verify step widths or draft-prefix
lengths change.
2. **`_normalize_candidate_blocks`
(`tokenspeed-kernel/python/tokenspeed_kernel/ops/attention/dsv41/_deep_gemm/indexer.py`):**
Launch through `kernel_launcher` and register warmup variants for the
power-of-two `BLOCK` buckets from 1 through 2048, matching
`next_power_of_2(blocks)`.
3. **`_global_rope_scatter`
(`tokenspeed-kernel/python/tokenspeed_kernel/ops/attention/dsv41/_triton/rope.py`):**
Move the runtime stride scalars `X0`, `POS0`, `CS0`, `C0`, `C1`, and
`S0` from `tl.constexpr` to `do_not_specialize`. Use an overflow-safe
slot bounds check, handle contiguous and noncontiguous cache rows
through `CONTIGUOUS_ROW`, launch through `kernel_launcher`, and register
warmup for `num_warps=(1, 4)` and both `CONTIGUOUS_ROW` values.
4. **`_dspark_rows_kernel`
(`tokenspeed-kernel/python/tokenspeed_kernel/ops/attention/dsv41/triton.py`):**
Add `X0`, `POS0`, `CS0`, `S0`, `W0`, `W1`, `O0`, and `PAGES` to
`do_not_specialize` to prevent stride and pool-size specializations, and
make the window-slot bounds check overflow-safe.
5. **Host row gathers
(`tokenspeed-kernel/python/tokenspeed_kernel/ops/embedding/triton_host_gather.py`):**
Keep MXFP8 batch dimensions, index strides, and table strides out of the
specialization key; do the same for uint8 row counts, widths, and table
and output strides while using 64-bit row indexing. Disable alignment
specialization for sliced index, code, and scale views. During
`kernel_warmup(enabled=True)`, precompile the sorted-threshold and
unsorted MXFP8 gather paths as well as `_copy_duplicate_rows_kernel`.

## Verification
- Verified `python3 -m py_compile`, `ruff check --select F821,F401,E9`,
and `pre-commit run --all-files` locally.
- Added `assert_no_triton_compile` behavioral GPU tests across
`test_cache_loc_kernel.py`, `test_attention_dsv41_rope.py`,
`test_attention_dsv41.py`, and `test_embedding_host_gather.py` (GPU run
pending on Blackwell runner).

---------

Signed-off-by: Fan Yang <250624800+fanyang-real@users.noreply.github.com>
2026-12-02 15:26:28 -08:00

224 lines
8.1 KiB
Python

"""Write-location kernel: hole routing, overflow, and the page-table width.
The first tests pin the safety behaviors of the slot math: null/hole pages
and past-the-table positions must route to the dummy slot 0, never to a real
request's bytes, and the staged table's address recorded at capture must see
in-place updates on replay.
The last test pins the table's width as a runtime argument: ``tl.constexpr``
there recompiles the kernel once per distinct width.
"""
from __future__ import annotations
import importlib.util
import inspect
import os
import sys
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 ci_system.ci_register import register_cuda_ci
register_cuda_ci(est_time=10, suite="runtime-1gpu")
from test.runtime.conftest import requires_cuda
from tokenspeed.runtime.execution.cache_loc_kernel import (
compute_out_cache_loc_kernel,
compute_out_cache_loc_uniform,
dflash_prepare_decode,
fused_decode_input_prep,
fused_decode_input_prep_kernel,
)
_P = 16 # kernel page size for the tests
def _uniform(table, cache_start, num_tokens):
bs = table.shape[0]
out = torch.zeros(bs * num_tokens, dtype=torch.int64, device=table.device)
compute_out_cache_loc_uniform(
out_cache_loc_ptr=out,
uniform_input_length=num_tokens,
cache_start=cache_start,
page_table=table,
page_size=_P,
)
return out.view(bs, num_tokens)
@requires_cuda
def test_mapping_matches_reference() -> None:
table = torch.tensor(
[[11, 12, 13, 14], [21, 22, 23, 24]], device="cuda", dtype=torch.int32
)
# Request 0 writes at 5 (inside page 0); request 1 at 35 (its page 2).
cache_start = torch.tensor([5, 35], device="cuda", dtype=torch.int32)
locs = _uniform(table, cache_start, num_tokens=3)
for req in range(2):
for k in range(3):
position = int(cache_start[req]) + k
page = int(table[req, position // _P])
assert int(locs[req, k]) == page * _P + position % _P, (req, k)
@requires_cuda
def test_null_hole_routes_to_dummy_slot() -> None:
"""A write that lands on a null (id 0) column must route to slot 0,
never to page 0's real bytes."""
table = torch.tensor([[0, 12, 13, 14]], device="cuda", dtype=torch.int32)
cache_start = torch.tensor([2], device="cuda", dtype=torch.int32) # column 0
locs = _uniform(table, cache_start, num_tokens=1)
assert int(locs[0, 0]) == 0
@requires_cuda
def test_overflow_routes_to_dummy_slot() -> None:
"""A position past the table's last column clamps and routes to slot 0
instead of reading out of bounds."""
table = torch.tensor([[91, 12, 13, 14]], device="cuda", dtype=torch.int32)
cache_start = torch.tensor([64], device="cuda", dtype=torch.int32) # column 4
locs = _uniform(table, cache_start, num_tokens=1)
assert int(locs[0, 0]) == 0
@requires_cuda
def test_capture_replay_address_stability() -> None:
"""The staged table's address is recorded at capture; replays must see
in-place updates. Mirrors how the drafter's multi-step loop uses it."""
table = torch.tensor([[11, 12, 13, 14]], device="cuda", dtype=torch.int32)
cache_start = torch.tensor([0], device="cuda", dtype=torch.int32)
out = torch.zeros(1, dtype=torch.int64, device="cuda")
# Warmup (Triton JIT) outside capture.
compute_out_cache_loc_uniform(
out_cache_loc_ptr=out,
uniform_input_length=1,
cache_start=cache_start,
page_table=table,
page_size=_P,
)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
compute_out_cache_loc_uniform(
out_cache_loc_ptr=out,
uniform_input_length=1,
cache_start=cache_start,
page_table=table,
page_size=_P,
)
page = (1 << 31) // _P + 1
table[0, 0] = page # in-place update, same address
graph.replay()
torch.cuda.synchronize()
assert int(out[0]) == page * _P
@requires_cuda
def test_dflash_prepare_writes_the_block_end_lengths() -> None:
"""The block end is the clamped prefix plus the query width.
It is written beside the prefix, the anchor token, and the positions."""
width, verify = 4, 3
output_tokens = torch.arange(12, dtype=torch.int32, device="cuda").view(4, 3) + 100
accept_lengths = torch.tensor([1, 3, 0, 2], dtype=torch.int32, device="cuda")
slots = torch.tensor([2, 0, 1, 3], dtype=torch.int64, device="cuda")
valid = torch.tensor([10, 20, 30, 95], dtype=torch.int32, device="cuda")
prefix = torch.empty(4, dtype=torch.int32, device="cuda")
block_end = torch.empty(4, dtype=torch.int32, device="cuda")
block_ids = torch.zeros(4, width, dtype=torch.int32, device="cuda")
positions = torch.empty(4, width, dtype=torch.int64, device="cuda")
dflash_prepare_decode(
output_tokens.view(-1),
accept_lengths,
slots,
valid,
prefix,
block_end,
block_ids,
positions,
verify_width=verify,
draft_query_width=width,
max_draft_prefix=96,
)
expected = torch.minimum(valid[slots] + accept_lengths, torch.tensor(96).cuda())
assert torch.equal(prefix, expected.int())
assert torch.equal(block_end, expected.int() + width)
anchor = accept_lengths.clamp(1, verify).long() - 1
assert torch.equal(
block_ids[:, 0], output_tokens[torch.arange(4, device="cuda"), anchor]
)
assert torch.equal(
positions, expected.long()[:, None] + torch.arange(width, device="cuda")
)
# --------------------------------------------------------------------------
# Page-table width stays a runtime argument
# --------------------------------------------------------------------------
@pytest.mark.parametrize(
"kernel",
[compute_out_cache_loc_kernel],
ids=["out_cache_loc"],
)
def test_max_pages_is_not_constexpr(kernel) -> None:
"""Re-annotating it ``tl.constexpr`` is the regression to catch.
Only the uniform slot-resolve kernel still reads a page table; the
decode-prep and DFLASH-prep kernels stopped producing write locations
(the router owns all slot math)."""
parameter = inspect.signature(kernel.fn).parameters["max_pages"]
assert parameter.annotation is inspect.Parameter.empty
@requires_cuda
def test_fused_decode_input_prep_reuses_compilation_across_step_widths() -> None:
"""Varying uniform_input_length across step widths must not recompile."""
kernel_test_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"..",
"tokenspeed-kernel",
"test",
)
helper_spec = importlib.util.spec_from_file_location(
"cache_loc_kernel_test_utils", os.path.join(kernel_test_dir, "utils.py")
)
helper = importlib.util.module_from_spec(helper_spec)
helper_spec.loader.exec_module(helper)
req_pool = torch.tensor([3, 1, 5, 2], dtype=torch.int64, device="cuda")
valid_cache = torch.tensor(
[0, 10, 25, 40, 55, 70], dtype=torch.int32, device="cuda"
)
positions = torch.empty(4 * 8, dtype=torch.int64, device="cuda")
seq_lens = torch.empty(4, dtype=torch.int32, device="cuda")
fused_decode_input_prep(positions[:4], seq_lens, req_pool, valid_cache, 1)
with helper.assert_no_triton_compile(fused_decode_input_prep_kernel):
for bs in (2, 4):
for width in (1, 2, 4, 8):
pool_slice = req_pool[:bs]
pos_slice = positions[: bs * width]
seq_slice = seq_lens[:bs]
fused_decode_input_prep(
pos_slice, seq_slice, pool_slice, valid_cache, width
)
expected_start = valid_cache[pool_slice].long()
expected_pos = expected_start[:, None] + torch.arange(
width, dtype=torch.int64, device="cuda"
)
assert torch.equal(pos_slice.view(bs, width), expected_pos)
assert torch.equal(seq_slice, expected_start.int() + width)
if __name__ == "__main__":
raise SystemExit(pytest.main([__file__, "-v"]))