Enable batched CP shared-KV current reuse correctness

Batch-size > 1 cache-hit traffic must not lose the current/partial-current reuse fast path. This change extends the target MLA/index sync-correct path to validate batched current suffix rows, compose page-aligned prefix spans, and route batched index top-k through current-only or partial-current reuse without falling back to scalar guards.\n\nThe implementation keeps page as the minimum cache unit: prefix cache coverage is page-aligned, while current suffix rows are sliced by valid extend lengths so padded tail rows are not exposed to attention. The index top-k batch path now mirrors the single-request contract: current-only reuses current index KV directly, partial-current materializes once and shares the dense buffer across request segments.\n\nConstraint: CP shared-KV supports in-seq zigzag only; round-robin remains fail-fast for shared-KV.\nConstraint: No new collectives are introduced; this is a sync correctness path, not a new communication scheme.\nRejected: Keep bs>1 current_index_kv fail-fast | disables the cache-hit path that W4 is meant to restore.\nRejected: Pad requests to a common batch length | violates the page-granular contract and exposes padded tails to consumers.\nConfidence: medium\nScope-risk: moderate\nDirective: Do not reintroduce batch_size_not_one or batch_gt1 current-reuse guards without proving an equivalent batched fast path exists.\nTested: Local py_compile for touched runtime/test files.\nTested: Remote g0034 pytest test_nsa_cp_utils.py test_cp_shared_kv_runtime.py => 157 passed, 5 warnings, 2 subtests passed.\nTested: Remote g0034 pytest test_cp_shared_kv_layout.py => 27 passed, 3 warnings.\nNot-tested: Full ETE with live traffic; CUDA kernel-backed batched descriptors; L1 prefetch, HiCache load/backup, and draft/EAGLE bs>1 current reuse.
This commit is contained in:
laoyao0822
2026-06-03 07:06:21 +08:00
parent a7472c415f
commit 50d0008705
9 changed files with 1195 additions and 152 deletions
+379 -12
View File
@@ -19,11 +19,13 @@ from sglang.srt.layers.attention.nsa.utils import (
cp_collect_last_token_hidden,
cp_split_and_rebuild_1d,
cp_split_and_rebuild_data,
_torch_batch_in_seq_all_gather_rerange,
get_cp_shared_kv_batch_plan,
get_cp_shared_kv_local_out_cache_loc,
get_cp_shared_kv_local_physical_out_cache_loc,
get_cp_local_embedding_padded_token_count,
pad_cp_local_input_ids_for_embedding,
prepare_input_dp_with_cp_dsa,
split_tensor_by_cp_batch_plan,
split_in_seq_cp_local_pair,
)
@@ -543,6 +545,201 @@ class TestNSAInSeqCPUtils(unittest.TestCase):
torch.zeros((8, 1)), 2, forward_batch, stream=None
)
def test_cp_shared_kv_prepare_rejects_round_robin_mode(self):
class Mode:
def is_context_parallel_extend(self):
return True
forward_batch = SimpleNamespace(
uses_cp_shared_kv=True,
extend_seq_lens_cpu=[128],
extend_prefix_lens_cpu=[0],
token_to_kv_pool=SimpleNamespace(page_size=64),
forward_mode=Mode(),
)
with (
patch(
"sglang.srt.layers.attention.nsa.utils.is_nsa_prefill_cp_round_robin_split",
return_value=True,
),
self.assertRaisesRegex(
RuntimeError,
r"\[CP_SHARED_KV_FAIL_FAST\]\[round_robin_unsupported\]",
),
):
prepare_input_dp_with_cp_dsa(
128,
cp_rank=0,
cp_size=2,
seqs_len=[128],
forward_batch=forward_batch,
page_size=64,
)
def test_cp_shared_kv_all_gather_rejects_round_robin_mode(self):
import torch
forward_batch = SimpleNamespace(
uses_cp_shared_kv=True,
nsa_cp_metadata=NSAContextParallelMetadata(
split_list=[2, 2, 2, 2],
zigzag_index=[0, 3],
reverse_split_len=[2, 2, 2, 2],
cp_reverse_index=[0, 2, 3, 1],
total_seq_lens=torch.tensor(8),
),
)
with (
patch(
"sglang.srt.layers.attention.nsa.utils.is_nsa_prefill_cp_round_robin_split",
return_value=True,
),
self.assertRaisesRegex(
RuntimeError,
r"\[CP_SHARED_KV_FAIL_FAST\]\[round_robin_unsupported\]",
),
):
cp_all_gather_rerange_output(
torch.zeros((4, 1)), 2, forward_batch, stream=None
)
def test_batch_in_seq_all_gather_rerange_restores_request_order_bf16(self):
import torch
cp_size = 2
request_split_lists = [
[2, 1, 3, 0],
[1, 2, 0, 1],
]
input_tensor_all, expected = self._build_batch_rerange_case(
cp_size=cp_size,
request_split_lists=request_split_lists,
row_width=3,
dtype=torch.bfloat16,
)
forward_batch = SimpleNamespace(
nsa_cp_metadata=NSAContextParallelMetadata(
batch_size=2,
request_split_lists=request_split_lists,
max_rank_len=[6, 6],
)
)
actual = _torch_batch_in_seq_all_gather_rerange(
input_tensor_all,
forward_batch,
cp_size=cp_size,
)
self.assertEqual(actual.dtype, torch.bfloat16)
self.assertTrue(torch.equal(actual, expected))
def test_batch_in_seq_all_gather_rerange_treats_fp8_payload_as_opaque_rows(self):
import torch
cp_size = 2
request_split_lists = [
[1, 2, 1, 0],
[2, 0, 1, 1],
]
input_tensor_all, expected = self._build_batch_rerange_case(
cp_size=cp_size,
request_split_lists=request_split_lists,
row_width=5,
dtype=torch.uint8,
)
forward_batch = SimpleNamespace(
nsa_cp_metadata=NSAContextParallelMetadata(
batch_size=2,
request_split_lists=request_split_lists,
max_rank_len=[4, 4],
)
)
actual = _torch_batch_in_seq_all_gather_rerange(
input_tensor_all,
forward_batch,
cp_size=cp_size,
)
self.assertEqual(actual.dtype, torch.uint8)
self.assertTrue(torch.equal(actual, expected))
def _build_batch_rerange_case(
self,
*,
cp_size,
request_split_lists,
row_width,
dtype,
):
import torch
rank_tokens = []
for rank in range(cp_size):
mirror = cp_size * 2 - rank - 1
rank_tokens.append(
sum(split[rank] + split[mirror] for split in request_split_lists)
)
max_rank_token = max(rank_tokens)
total_tokens = sum(sum(split) for split in request_split_lists)
input_tensor_all = torch.zeros(
(max_rank_token * cp_size, row_width),
dtype=dtype,
)
expected = torch.empty((total_tokens, row_width), dtype=dtype)
next_value = 1
request_segments = []
for split in request_split_lists:
segments = []
for segment_len in split:
if dtype == torch.uint8:
rows = (
torch.arange(
next_value,
next_value + segment_len * row_width,
dtype=torch.int64,
)
.remainder(251)
.to(torch.uint8)
.view(segment_len, row_width)
)
else:
rows = (
torch.arange(
next_value,
next_value + segment_len * row_width,
dtype=torch.float32,
)
.view(segment_len, row_width)
.to(dtype)
)
next_value += segment_len * row_width
segments.append(rows)
request_segments.append(segments)
output_cursor = 0
for segments in request_segments:
for rows in segments:
expected[output_cursor : output_cursor + rows.shape[0]] = rows
output_cursor += rows.shape[0]
for rank in range(cp_size):
mirror = cp_size * 2 - rank - 1
rank_cursor = rank * max_rank_token
for segments in request_segments:
for segment_id in (rank, mirror):
rows = segments[segment_id]
input_tensor_all[
rank_cursor : rank_cursor + rows.shape[0]
] = rows
rank_cursor += rows.shape[0]
return input_tensor_all, expected
def test_local_pair_split_uses_metadata_lengths_not_half_split(self):
import torch
@@ -1209,12 +1406,69 @@ class TestNSAInSeqCPUtils(unittest.TestCase):
[[1, 1], [1, 1], [2, 2], [3, 3], [4, 4], [4, 4], [4, 4]],
)
def test_indexer_in_seq_cp_pair_batch_rejects_current_index_reuse(self):
def test_indexer_in_seq_cp_pair_batch_materializes_partial_current_index_reuse_once(self):
import torch
from sglang.srt.layers.attention.nsa.nsa_indexer import Indexer
indexer = object.__new__(Indexer)
indexer.index_topk = 2
current_index_kv = (torch.tensor([1]), torch.tensor([2]))
logical_pages = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.int32)
materialized_index = torch.tensor([11], dtype=torch.int32)
dense_pages = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.int32)
materialize_calls = []
topk_calls = []
class Metadata:
def get_page_table_64(self):
return logical_pages
def fake_materialize(
forward_batch,
layer_id,
logical_page_table,
current_index_kv=None,
):
materialize_calls.append(
{
"layer_id": layer_id,
"logical_page_table": logical_page_table,
"current_index_kv": current_index_kv,
}
)
return materialized_index, dense_pages
def fake_get_topk(
forward_batch,
layer_id,
q_fp8,
weights,
metadata,
kv_len,
actual_seq_q,
cp_index=None,
current_index_kv=None,
shared_index_buffer=None,
shared_block_tables=None,
actual_seq_q_tensor=None,
actual_seq_q_cu_tensor=None,
batch_idx=0,
):
topk_calls.append(
{
"batch_idx": batch_idx,
"current_index_kv": current_index_kv,
"shared_index_buffer": shared_index_buffer,
"shared_block_tables": shared_block_tables,
"actual_seq_q_cu_tensor": actual_seq_q_cu_tensor,
}
)
return torch.full((actual_seq_q, 2), len(topk_calls), dtype=torch.int32)
indexer._maybe_materialize_shared_index_buffer = fake_materialize
indexer._get_topk_ragged_with_cp = fake_get_topk
forward_batch = SimpleNamespace(
batch_size=2,
nsa_cp_metadata=NSAContextParallelMetadata(
@@ -1225,20 +1479,133 @@ class TestNSAInSeqCPUtils(unittest.TestCase):
request_actual_seq_q_next=[1, 3],
),
)
result = Indexer._get_topk_in_seq_cp_pair(
indexer,
forward_batch,
layer_id=7,
q_fp8=torch.empty(7, 1),
weights=torch.empty(7, 1),
metadata=Metadata(),
current_index_kv=current_index_kv,
)
with self.assertRaisesRegex(
RuntimeError,
"CP_SHARED_KV_FAIL_FAST.*batch_gt1_index_current_reuse_unsupported",
self.assertEqual(len(materialize_calls), 1)
self.assertIs(materialize_calls[0]["logical_page_table"], logical_pages)
self.assertIs(materialize_calls[0]["current_index_kv"], current_index_kv)
self.assertEqual(len(topk_calls), 4)
self.assertTrue(
all(call["current_index_kv"] is None for call in topk_calls)
)
self.assertTrue(
all(call["shared_index_buffer"] is materialized_index for call in topk_calls)
)
self.assertTrue(
all(call["shared_block_tables"] is dense_pages for call in topk_calls)
)
self.assertEqual([call["batch_idx"] for call in topk_calls], [0, 0, 1, 1])
self.assertEqual(
[call["actual_seq_q_cu_tensor"].tolist() for call in topk_calls],
[[0, 2], [0, 1], [0, 1], [0, 3]],
)
self.assertEqual(
result.tolist(),
[[1, 1], [1, 1], [2, 2], [3, 3], [4, 4], [4, 4], [4, 4]],
)
def test_indexer_in_seq_cp_pair_batch_reuses_current_index_without_materialize(self):
import torch
from sglang.srt.layers.attention.nsa.nsa_indexer import Indexer
indexer = object.__new__(Indexer)
indexer.index_topk = 2
current_index_kv = (torch.tensor([1]), torch.tensor([2]))
topk_calls = []
class Mode:
def is_extend_without_speculative(self):
return True
class Metadata:
def get_page_table_64(self):
raise AssertionError("current-only index reuse should not read page table")
def fake_materialize(*args, **kwargs):
raise AssertionError("current-only index reuse should not materialize")
def fake_get_topk(
forward_batch,
layer_id,
q_fp8,
weights,
metadata,
kv_len,
actual_seq_q,
cp_index=None,
current_index_kv=None,
shared_index_buffer=None,
shared_block_tables=None,
actual_seq_q_tensor=None,
actual_seq_q_cu_tensor=None,
batch_idx=0,
):
Indexer._get_topk_in_seq_cp_pair(
indexer,
forward_batch,
layer_id=7,
q_fp8=torch.empty(7, 1),
weights=torch.empty(7, 1),
metadata=SimpleNamespace(),
current_index_kv=(torch.empty(1), torch.empty(1)),
topk_calls.append(
{
"batch_idx": batch_idx,
"current_index_kv": current_index_kv,
"shared_index_buffer": shared_index_buffer,
"shared_block_tables": shared_block_tables,
"actual_seq_q_cu_tensor": actual_seq_q_cu_tensor,
}
)
return torch.full((actual_seq_q, 2), len(topk_calls), dtype=torch.int32)
indexer._maybe_materialize_shared_index_buffer = fake_materialize
indexer._get_topk_ragged_with_cp = fake_get_topk
forward_batch = SimpleNamespace(
batch_size=2,
forward_mode=Mode(),
extend_prefix_lens_cpu=[0, 0],
extend_seq_lens_cpu=[3, 4],
seq_lens_cpu=torch.tensor([3, 4], dtype=torch.int64),
nsa_cp_metadata=NSAContextParallelMetadata(
batch_size=2,
request_kv_len_prev=[3, 4],
request_kv_len_next=[3, 4],
request_actual_seq_q_prev=[2, 1],
request_actual_seq_q_next=[1, 3],
),
)
result = Indexer._get_topk_in_seq_cp_pair(
indexer,
forward_batch,
layer_id=7,
q_fp8=torch.empty(7, 1),
weights=torch.empty(7, 1),
metadata=Metadata(),
current_index_kv=current_index_kv,
)
self.assertEqual(len(topk_calls), 4)
self.assertTrue(
all(call["current_index_kv"] is current_index_kv for call in topk_calls)
)
self.assertTrue(
all(call["shared_index_buffer"] is None for call in topk_calls)
)
self.assertTrue(
all(call["shared_block_tables"] is None for call in topk_calls)
)
self.assertEqual([call["batch_idx"] for call in topk_calls], [0, 0, 1, 1])
self.assertEqual(
[call["actual_seq_q_cu_tensor"].tolist() for call in topk_calls],
[[0, 2], [0, 1], [0, 1], [0, 3]],
)
self.assertEqual(
result.tolist(),
[[1, 1], [1, 1], [2, 2], [3, 3], [4, 4], [4, 4], [4, 4]],
)
def test_indexer_in_seq_cp_pair_skips_materialize_when_current_index_reused(self):
import torch
@@ -565,6 +565,62 @@ class TestCpSharedKVRuntimeHelpers(unittest.TestCase):
forward_batch.out_cache_loc = torch.arange(64, dtype=torch.int64)
self.assertFalse(can_reuse_current_extend_kv(forward_batch))
def test_can_reuse_current_extend_kv_allows_batch_partial_cache_hits(self):
from sglang.srt.layers.attention.nsa.cp_shared_kv_runtime import (
can_reuse_current_extend_kv,
)
forward_batch = SimpleNamespace(
forward_mode=_FakeExtendForwardMode(),
batch_size=2,
extend_prefix_lens_cpu=[40384, 8192],
extend_seq_lens_cpu=[65, 128],
seq_lens_cpu=torch.tensor([40384 + 65, 8192 + 128], dtype=torch.int32),
out_cache_loc=torch.arange(256, dtype=torch.int64),
)
self.assertTrue(can_reuse_current_extend_kv(forward_batch))
forward_batch.out_cache_loc = torch.arange(192, dtype=torch.int64)
self.assertFalse(can_reuse_current_extend_kv(forward_batch))
forward_batch.out_cache_loc = torch.arange(256, dtype=torch.int64)
forward_batch.seq_lens_cpu = torch.tensor([40384 + 64, 8192 + 128], dtype=torch.int32)
self.assertFalse(can_reuse_current_extend_kv(forward_batch))
def test_current_extend_kv_rows_for_reuse_accepts_batch_bf16_and_fp8_payloads(self):
from sglang.srt.environ import envs
from sglang.srt.layers.attention.nsa import cp_shared_kv_runtime as runtime
forward_batch = SimpleNamespace(
forward_mode=_FakeExtendForwardMode(),
batch_size=2,
extend_prefix_lens_cpu=[0, 1024],
extend_seq_lens_cpu=[65, 128],
seq_lens_cpu=torch.tensor([65, 1024 + 128], dtype=torch.int32),
out_cache_loc=torch.arange(256, dtype=torch.int64),
)
bf16_k = torch.empty((193, 2, 4), dtype=torch.bfloat16)
fp8_like_k = torch.empty((193, 5), dtype=torch.uint8)
with envs.SGLANG_CP_SHARED_KV_CURRENT_REUSE.override(True):
self.assertEqual(
runtime.current_extend_kv_rows_for_reuse(
forward_batch,
bf16_k,
fp8_like_k,
),
193,
)
self.assertIsNone(
runtime.current_extend_kv_rows_for_reuse(
forward_batch,
bf16_k[:192],
fp8_like_k,
)
)
def test_should_reuse_current_extend_kv_enables_draft_partial_cache_hit_suffix(
self,
):
@@ -692,6 +748,21 @@ class TestCpSharedKVRuntimeHelpers(unittest.TestCase):
self.assertIn("prefix_pages=0", branch_source)
self.assertNotIn("kv_cache = current_kv_cache", branch_source)
def test_mla_partial_current_sync_uses_batch_prefix_slot_span(self):
from pathlib import Path
source = (
Path(__file__).resolve().parents[4]
/ "python/sglang/srt/layers/attention/nsa_backend.py"
).read_text()
branch_start = source.index("eagle_draft_mla_branch = \"partial_current_sync\"")
branch_end = source.index("forward_partial_current_sync_compose", branch_start)
branch_source = source[branch_start:branch_end]
self.assertIn("build_batch_prefix_slot_span", source)
self.assertIn("prefix_slot_span=", branch_source)
self.assertNotIn("or len(prefix_lens_cpu) != 1", branch_source)
def test_nsa_backend_topk_transform_uses_effective_forward_impl(self):
from sglang.srt.layers.attention.nsa_backend import (
NativeSparseAttnBackend,
@@ -942,7 +1013,7 @@ class TestCpSharedKVRuntimeHelpers(unittest.TestCase):
batch_size=2,
extend_prefix_lens_cpu=[64, 64],
extend_seq_lens_cpu=[64, 64],
seq_lens_cpu=torch.tensor([128, 128], dtype=torch.int32),
seq_lens_cpu=torch.tensor([129, 128], dtype=torch.int32),
out_cache_loc=torch.arange(128, dtype=torch.int64),
)
@@ -952,7 +1023,7 @@ class TestCpSharedKVRuntimeHelpers(unittest.TestCase):
joined = "\n".join(logs.output)
self.assertIn("[CP_SHARED_KV_FALLBACK][current_reuse]", joined)
self.assertIn("batch_size_not_one", joined)
self.assertIn("prefix_extend_seq_len_mismatch_req_0", joined)
def test_tai_index_mqa_prepare_fast_path_miss_logs_warning(self):
from sglang.srt.environ import envs
@@ -1210,6 +1281,188 @@ class TestCpSharedKVRuntimeHelpers(unittest.TestCase):
self.assertTrue(torch.equal(mixed_kv[12:14], current_kv))
self.assertEqual(mixed_locs.tolist(), [[4, 8, 12, 13, -1, -1]])
def test_batch_prefix_slot_span_covers_request_prefix_pages_only(self):
from sglang.srt.layers.attention.nsa import cp_shared_kv_runtime as runtime
logical_pages = torch.tensor(
[
[1, 2, 5],
[9, 11, 0],
],
dtype=torch.int64,
)
self.assertEqual(
runtime.build_batch_prefix_slot_span(
logical_pages=logical_pages,
prefix_lens_cpu=[8, 4],
page_size=4,
),
(0, 4),
)
self.assertEqual(
runtime.build_batch_prefix_slot_span(
logical_pages=logical_pages,
prefix_lens_cpu=[0, 4],
page_size=4,
),
(3, 4),
)
self.assertEqual(
runtime.build_batch_prefix_slot_span(
logical_pages=logical_pages,
prefix_lens_cpu=[0, 0],
page_size=4,
),
(0, 0),
)
def test_materialize_batch_prefix_span_and_reuse_current_kv_page_slots(self):
from sglang.srt.layers.attention.nsa import cp_shared_kv_runtime as runtime
from sglang.srt.mem_cache.cp_shared_kv_layout import CpSharedKVLayout
page_size = 4
layout = CpSharedKVLayout(page_size=page_size, cp_size=1, cp_rank=0)
kv_cache = torch.arange(0, 64, dtype=torch.float32).view(64, 1, 1)
logical_locs = torch.tensor(
[
[4, 8, 20, 21, -1, -1],
[36, 44, 45, -1, -1, -1],
],
dtype=torch.int64,
)
current_locs = torch.tensor([20, 21, 44, 45], dtype=torch.int64)
current_kv = torch.arange(100, 104, dtype=torch.float32).view(4, 1, 1)
remap_logical_pages = torch.tensor(
[
[1, 2, 5],
[9, 11, 0],
],
dtype=torch.int64,
)
slot_remap = runtime.build_shared_token_kv_slot_remap(
kv_cache=kv_cache,
logical_locs=logical_locs,
remap_logical_pages=remap_logical_pages,
layout=layout,
page_size=page_size,
)
prefix_slot_span = runtime.build_batch_prefix_slot_span(
logical_pages=remap_logical_pages,
prefix_lens_cpu=[8, 4],
page_size=page_size,
)
with patch.object(
runtime, "_all_reduce_materialized_buffer_range", _identity_all_reduce
):
mixed_kv, mixed_locs = (
runtime.materialize_prefix_and_reuse_current_kv_page_slots(
kv_cache=kv_cache,
logical_locs=logical_locs,
current_kv_cache=current_kv,
current_locs=current_locs,
slot_remap=slot_remap,
layout=layout,
page_size=page_size,
prefix_pages=0,
prefix_slot_span=prefix_slot_span,
)
)
self.assertEqual(mixed_locs.tolist(), [[4, 8, 12, 13, -1, -1], [16, 20, 21, -1, -1, -1]])
self.assertTrue(torch.equal(mixed_kv[4:8], kv_cache[4:8]))
self.assertTrue(torch.equal(mixed_kv[8:12], kv_cache[8:12]))
self.assertTrue(torch.equal(mixed_kv[16:20], kv_cache[36:40]))
self.assertTrue(torch.equal(mixed_kv[12:14], current_kv[:2]))
self.assertTrue(torch.equal(mixed_kv[20:22], current_kv[2:]))
def test_materialize_batch_prefix_span_and_reuse_current_index_page_slots(self):
from sglang.srt.layers.attention.nsa import cp_shared_kv_runtime as runtime
from sglang.srt.mem_cache.cp_shared_kv_layout import CpSharedKVLayout
page_size = 4
index_head_dim = 4
scale_bytes = 4
page_bytes = page_size * index_head_dim + page_size * scale_bytes
layout = CpSharedKVLayout(page_size=page_size, cp_size=1, cp_rank=0)
page_buffer = torch.zeros((16, page_bytes), dtype=torch.uint8)
page_buffer[1] = torch.arange(10, 10 + page_bytes, dtype=torch.uint8)
page_buffer[2] = torch.arange(40, 40 + page_bytes, dtype=torch.uint8)
page_buffer[9] = torch.arange(70, 70 + page_bytes, dtype=torch.uint8)
logical_pages = torch.tensor([[1, 2, 5], [9, 11, 0]], dtype=torch.int64)
slot_remap = runtime.build_shared_paged_buffer_slot_remap(
page_buffer,
logical_pages,
layout,
)
prefix_slot_span = runtime.build_batch_prefix_slot_span(
logical_pages=logical_pages,
prefix_lens_cpu=[8, 4],
page_size=page_size,
)
current_k = torch.tensor(
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]],
dtype=torch.uint8,
)
current_scale = torch.tensor([[1.25], [2.5], [3.5], [4.5]], dtype=torch.float32)
with patch.object(
runtime, "_all_reduce_materialized_buffer_range", _identity_all_reduce
):
dense_page_buffer, dense_pages = (
runtime.materialize_prefix_and_reuse_current_index_page_slots(
page_buffer=page_buffer,
current_index_k=current_k,
current_index_scale=current_scale,
current_locs=torch.tensor([20, 21, 44, 45], dtype=torch.int64),
slot_remap=slot_remap,
layout=layout,
page_size=page_size,
index_head_dim=index_head_dim,
prefix_pages=0,
prefix_slot_span=prefix_slot_span,
layer_id=2,
)
)
scale_offset = page_size * index_head_dim
self.assertEqual(dense_pages.tolist(), [[1, 2, 3], [4, 5, 0]])
self.assertTrue(torch.equal(dense_page_buffer[1], page_buffer[1]))
self.assertTrue(torch.equal(dense_page_buffer[2], page_buffer[2]))
self.assertTrue(torch.equal(dense_page_buffer[4], page_buffer[9]))
self.assertTrue(torch.equal(dense_page_buffer[3, 0:4], current_k[0]))
self.assertTrue(torch.equal(dense_page_buffer[3, 4:8], current_k[1]))
self.assertTrue(torch.equal(dense_page_buffer[5, 0:4], current_k[2]))
self.assertTrue(torch.equal(dense_page_buffer[5, 4:8], current_k[3]))
expected_scale_bytes = (
current_scale[:2].contiguous().view(torch.uint8).reshape(2, scale_bytes)
)
self.assertTrue(
torch.equal(
dense_page_buffer[
3,
scale_offset : scale_offset + page_size * scale_bytes,
].view(page_size, scale_bytes)[:2],
expected_scale_bytes,
)
)
def test_index_partial_current_sync_uses_batch_prefix_slot_span(self):
from pathlib import Path
source = (
Path(__file__).resolve().parents[4]
/ "python/sglang/srt/layers/attention/nsa/nsa_indexer.py"
).read_text()
branch_start = source.index(" if current_index_kv is not None:")
branch_end = source.index(" return materialized, dense_pages", branch_start)
branch_source = source[branch_start:branch_end]
self.assertIn("build_batch_prefix_slot_span", source)
self.assertIn("prefix_slot_span=", branch_source)
self.assertNotIn("or len(prefix_lens_cpu) != 1", branch_source)
def test_ipc_page_descriptor_builder_maps_slots_to_owner_physical_pages(self):
from sglang.srt.layers.attention.nsa import cp_shared_kv_runtime as runtime
from sglang.srt.mem_cache.cp_shared_kv_layout import CpSharedKVLayout