Repository navigation
[KV Connector] Canonical CPU layout for parallelism-agnostic KV offload #48414
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
orozery
merged 12 commits into
vllm-project:main
from
Etelis:kv-offload-fragment-layout
Aug 10, 2026
Merged
Changes from 8 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
86941a3
Add per-layer KV head region schema for TP-agnostic offload
EtelisIBM b693ab4
Merge branch 'main' into kv-offload-region-schema
Etelis 5d96fe5
Replace KV head regions with canonical page mappings
EtelisIBM f5966e8
Add canonical CPU layout for KV offload
EtelisIBM a3d8541
Merge branch 'main' into kv-offload-fragment-layout
EtelisIBM f004328
Merge branch 'main' into kv-offload-fragment-layout
EtelisIBM da4c745
Address review: extract canonical-path helpers, rename for clarity
EtelisIBM 670df66
Add GPU roundtrip test for canonical layout cross-topology contract
EtelisIBM bc564c6
Address review round 2: config threading, verified fill optimizations…
EtelisIBM 6f5bf4a
Merge branch 'main' into kv-offload-fragment-layout
EtelisIBM 1af655d
Drop model-runner version from canonical portability gate
EtelisIBM 73d2619
Pin the shared region in the cross-topology test
EtelisIBM File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,171 @@ | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # SPDX-FileCopyrightText: Copyright contributors to the vLLM project | ||
| import time | ||
|
|
||
| import numpy as np | ||
| import pytest | ||
| import torch | ||
|
|
||
| from vllm.v1.kv_offload.base import ( | ||
| CanonicalKVCacheRef, | ||
| CanonicalPageMapping, | ||
| CopyRun, | ||
| GPULoadStoreSpec, | ||
| ) | ||
| from vllm.v1.kv_offload.cpu.common import CPULoadStoreSpec | ||
| from vllm.v1.kv_offload.cpu.gpu_worker import ( | ||
| SingleDirectionOffloadingHandler, | ||
| _build_copy_plan, | ||
| _canonical_block_sizes, | ||
| _canonical_page_ids, | ||
| ) | ||
|
|
||
|
|
||
| def _ref(mapping: CanonicalPageMapping, tensor_idx: int = 0) -> CanonicalKVCacheRef: | ||
| return CanonicalKVCacheRef( | ||
| tensor_idx=tensor_idx, | ||
| page_size_bytes=mapping.local_page_size_bytes, | ||
| mapping=mapping, | ||
| ) | ||
|
|
||
|
|
||
| def _nhd_mapping() -> CanonicalPageMapping: | ||
| # 4-token NHD page at tp=4, rank 2: K and V runs of 4x128B fragments | ||
| runs = ( | ||
| CopyRun(0, 256, 128, 4, 128, 512), | ||
| CopyRun(512, 2304, 128, 4, 128, 512), | ||
| ) | ||
| return CanonicalPageMapping(4096, 1024, runs, 1, 0, True) | ||
|
|
||
|
|
||
| def test_copy_plan_unrolls_runs(): | ||
| plan = _build_copy_plan(_ref(_nhd_mapping()), gpu_to_cpu=True) | ||
| k_dst = [256, 768, 1280, 1792] | ||
| assert plan.frag_offsets_src.tolist() == [0, 128, 256, 384, 512, 640, 768, 896] | ||
| assert plan.frag_offsets_dst.tolist() == k_dst + [2048 + o for o in k_dst] | ||
| assert plan.frag_sizes.tolist() == [128] * 8 | ||
| assert plan.num_frags == 8 | ||
|
|
||
|
|
||
| def test_load_direction_swaps_offsets(): | ||
| store = _build_copy_plan(_ref(_nhd_mapping()), gpu_to_cpu=True) | ||
| load = _build_copy_plan(_ref(_nhd_mapping()), gpu_to_cpu=False) | ||
| assert np.array_equal(store.frag_offsets_src, load.frag_offsets_dst) | ||
| assert np.array_equal(store.frag_offsets_dst, load.frag_offsets_src) | ||
| assert np.array_equal(store.frag_sizes, load.frag_sizes) | ||
|
|
||
|
|
||
| def test_writer_rotation_matches_is_writer(): | ||
| # Replicas take turns writing shared canonical pages, keyed by the | ||
| # CPU-side canonical page id; the enumeration must agree with is_writer | ||
| identity = CopyRun(0, 0, 256, 1, 256, 256) | ||
| mapping = CanonicalPageMapping(256, 256, (identity,), 2, 1, True) | ||
| ids = _canonical_page_ids( | ||
| np.array([3, 7, 9]), blocks_per_chunk=4, count=10, skip_count=2 | ||
| ) | ||
| assert ids.tolist() == [14, 15, 28, 29, 30, 31, 36, 37, 38, 39] | ||
| mask = ids % mapping.num_writers == mapping.writer_index | ||
| assert mask.tolist() == [mapping.is_writer(int(b)) for b in ids] | ||
|
|
||
|
|
||
| def test_canonical_block_sizes_take_max_per_tensor(): | ||
| identity = CopyRun(0, 0, 512, 1, 512, 512) | ||
| small = CanonicalPageMapping(2048, 512, (identity,), 1, 0, False) | ||
| refs = [[_ref(_nhd_mapping(), 0), _ref(small, 0)], [_ref(small, 1)]] | ||
| assert _canonical_block_sizes(refs, 2) == [4096, 2048] | ||
|
|
||
|
|
||
| def _tp2_rank_mapping(rank: int) -> CanonicalPageMapping: | ||
| # 4-token NHD page, 4 total heads of 64B, tp=2: rank holds 2 heads, | ||
| # so K and V each scatter as 4 per-token 128B fragments | ||
| runs = ( | ||
| CopyRun(0, rank * 128, 128, 4, 128, 256), | ||
| CopyRun(512, 1024 + rank * 128, 128, 4, 128, 256), | ||
| ) | ||
| return CanonicalPageMapping(2048, 1024, runs, 1, 0, True) | ||
|
|
||
|
|
||
| def _whole_page_mapping() -> CanonicalPageMapping: | ||
| identity = CopyRun(0, 0, 2048, 1, 2048, 2048) | ||
| return CanonicalPageMapping(2048, 2048, (identity,), 1, 0, True) | ||
|
|
||
|
|
||
| def _transfer(handler, num_blocks: int, gpu_to_cpu: bool) -> None: | ||
| block_ids = list(range(num_blocks)) | ||
| gpu_spec = GPULoadStoreSpec( | ||
| block_ids, group_sizes=(num_blocks,), block_indices=(0,) | ||
| ) | ||
| cpu_spec = CPULoadStoreSpec(block_ids) | ||
| src, dst = (gpu_spec, cpu_spec) if gpu_to_cpu else (cpu_spec, gpu_spec) | ||
| assert handler.transfer_async(0, src, dst) | ||
| deadline = time.time() + 30 | ||
| while time.time() < deadline: | ||
| if handler.get_finished(): | ||
| return | ||
| time.sleep(0.001) | ||
| raise TimeoutError("transfer did not complete") | ||
|
|
||
|
|
||
| def _canonical_handler(gpu_tensor, cpu_tensor, mapping, gpu_to_cpu): | ||
| page = mapping.local_page_size_bytes | ||
| refs = [[CanonicalKVCacheRef(tensor_idx=0, page_size_bytes=page, mapping=mapping)]] | ||
| return SingleDirectionOffloadingHandler( | ||
| gpu_tensors=[gpu_tensor], | ||
| cpu_tensors=[cpu_tensor], | ||
| blocks_per_chunk=1, | ||
| layer_refs_per_group=refs, | ||
| gpu_to_cpu=gpu_to_cpu, | ||
| canonical_layout=True, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") | ||
| def test_gpu_roundtrip_assembles_canonical_page_across_ranks(): | ||
| """Two TP2-style rank handlers must scatter into one shared canonical | ||
| CPU page such that each rank reloads bit-exact and a whole-page (TP1) | ||
| reader sees both shards — the cross-topology contract.""" | ||
| torch.manual_seed(0) | ||
| num_blocks = 4 | ||
| gpu_rank = [ | ||
| torch.randint(-128, 128, (num_blocks, 1024), dtype=torch.int8, device="cuda") | ||
| for _ in range(2) | ||
| ] | ||
| cpu_canonical = torch.zeros(num_blocks, 2048, dtype=torch.int8, pin_memory=True) | ||
|
|
||
| for rank in (0, 1): | ||
| store = _canonical_handler( | ||
| gpu_rank[rank], cpu_canonical, _tp2_rank_mapping(rank), gpu_to_cpu=True | ||
| ) | ||
| _transfer(store, num_blocks, gpu_to_cpu=True) | ||
| torch.accelerator.synchronize() | ||
|
|
||
| # independent oracle: replay each rank's runs in numpy | ||
| expected = np.zeros((num_blocks, 2048), dtype=np.int8) | ||
| for rank in (0, 1): | ||
| local = gpu_rank[rank].cpu().numpy() | ||
| for run in _tp2_rank_mapping(rank).runs: | ||
| for i in range(run.num_fragments): | ||
| lo = run.local_offset + i * run.local_stride | ||
| co = run.canonical_offset + i * run.canonical_stride | ||
| expected[:, co : co + run.fragment_size] = local[ | ||
| :, lo : lo + run.fragment_size | ||
| ] | ||
| assert np.array_equal(cpu_canonical.numpy(), expected) | ||
|
|
||
| # each rank reloads its shard bit-exact | ||
| gpu_back = torch.zeros(num_blocks, 1024, dtype=torch.int8, device="cuda") | ||
| load = _canonical_handler( | ||
| gpu_back, cpu_canonical, _tp2_rank_mapping(0), gpu_to_cpu=False | ||
| ) | ||
| _transfer(load, num_blocks, gpu_to_cpu=False) | ||
| torch.accelerator.synchronize() | ||
| assert torch.equal(gpu_back, gpu_rank[0]) | ||
|
|
||
| # a whole-page reader (TP1 topology) sees the assembled page | ||
| gpu_full = torch.zeros(num_blocks, 2048, dtype=torch.int8, device="cuda") | ||
| load_full = _canonical_handler( | ||
| gpu_full, cpu_canonical, _whole_page_mapping(), gpu_to_cpu=False | ||
| ) | ||
| _transfer(load_full, num_blocks, gpu_to_cpu=False) | ||
| torch.accelerator.synchronize() | ||
| assert torch.equal(gpu_full.cpu(), cpu_canonical) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Claude:
Missing test: cross-topology roundtrip for canonical layout
The canonical layout's core value proposition — KV written with one parallelism config can be read with a different one — has no integration test.
The existing tests in
test_canonical_layout.pyverify the building blocks (_build_copy_plan,_canonical_page_ids,_canonical_block_sizes) and a single-topology GPU roundtrip, but nobody tests that aTP=2writer's data is actually usable by aTP=4reader.Suggested test (in
test_canonical_layout.py):SharedOffloadRegion(simulates the canonical mmap file)tp_size=writer_tp), each scatters its KV fragment into canonical positions (GPU→CPU)tp_size=reader_tp), each gathers its fragment from the same canonical region (CPU→GPU)Parametrize over
(writer_tp, reader_tp)pairs like(2, 4), (4, 2), (2, 1).This is the one test that proves the feature works end-to-end, not just that the pieces are individually correct.