main
py 688 lines 25.3 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 """Worker-side unit tests for SimpleCPUOffloadConnector.
4
5 Covers the GPU->CPU store cross-stream synchronization: the store copy must be
6 ordered after the compute stream that writes the KV blocks, otherwise it can
7 read partially written / stale blocks and silently corrupt the CPU cache.
8 """
9
10 from __future__ import annotations
11
12 import time
13 from contextlib import nullcontext
14 from unittest.mock import MagicMock
15
16 import pytest
17 import torch
18
19 from vllm.platforms import current_platform
20
21 if not current_platform.is_cuda_alike():
22 pytest.skip("Requires CUDA or ROCm", allow_module_level=True)
23
24 from tests.v1.attention.utils import dense_kv_cache_tensor, dense_kv_cache_views
25 from tests.v1.kv_connector.unit.test_kv_connector_lifecycle import (
26 _make_empty_scheduler_output,
27 )
28 from vllm.config import CacheConfig
29 from vllm.distributed.kv_transfer.kv_connector.v1.simple_cpu_offload_connector import (
30 SimpleCPUOffloadConnector,
31 )
32 from vllm.v1.core.kv_cache_utils import (
33 get_kv_cache_config_from_groups,
34 is_kv_cache_spec_uniform,
35 resolve_kv_cache_block_sizes,
36 )
37 from vllm.v1.kv_cache_interface import (
38 FullAttentionSpec,
39 KVCacheConfig,
40 KVCacheGroupSpec,
41 KVCacheLayout,
42 KVCacheSpec,
43 KVCacheTensor,
44 MLAAttentionSpec,
45 UniformTypeKVCacheSpecs,
46 )
47 from vllm.v1.simple_kv_offload.copy_backend import DmaCopyBackend
48 from vllm.v1.simple_kv_offload.cuda_mem_ops import (
49 CU_MEMCPY_SRC_ACCESS_ORDER_ANY,
50 CU_MEMCPY_SRC_ACCESS_ORDER_STREAM,
51 build_params,
52 )
53 from vllm.v1.simple_kv_offload.disk_backend import DiskBackend
54 from vllm.v1.simple_kv_offload.metadata import (
55 SimpleCPUOffloadMetadata,
56 SimpleCPUOffloadWorkerMetadata,
57 )
58 from vllm.v1.simple_kv_offload.worker import SimpleCPUOffloadWorker
59 from vllm.v1.worker.gpu.kv_connector import ActiveKVConnector
60 from vllm.v1.worker.kv_connector_model_runner_mixin import KVConnectorModelRunnerMixin
61 from vllm.v1.worker.utils import allocate_kv_cache
62
63 NUM_BLOCKS = 64
64 BLOCK_BYTES = 4096
65 ITERS = 30
66 # Keep the compute stream busy so the KV write lands late; this makes the
67 # store-vs-compute race deterministic instead of timing-dependent.
68 SLEEP_CYCLES = 50_000_000
69
70
71 def _make_worker(
72 kv_cache_config: KVCacheConfig | None, cpu_capacity_bytes: int
73 ) -> SimpleCPUOffloadWorker:
74 return SimpleCPUOffloadWorker(None, kv_cache_config, cpu_capacity_bytes)
75
76
77 def _make_backend() -> tuple[DmaCopyBackend, torch.Tensor, torch.Tensor]:
78 gpu = {"k": torch.zeros((NUM_BLOCKS, BLOCK_BYTES), dtype=torch.int8, device="cuda")}
79 cpu = {
80 "k": torch.zeros(
81 (NUM_BLOCKS, BLOCK_BYTES), dtype=torch.int8, device="cpu", pin_memory=True
82 )
83 }
84 low_pri, _ = torch.cuda.Stream.priority_range()
85 backend = DmaCopyBackend()
86 backend.init(
87 gpu,
88 cpu,
89 gpu["k"].device,
90 torch.cuda.Stream(priority=low_pri),
91 torch.cuda.Stream(priority=low_pri),
92 )
93 return backend, gpu["k"], cpu["k"]
94
95
96 @pytest.mark.parametrize("use_v2", [False, True])
97 def test_no_forward_step_completes_cpu_store(monkeypatch, use_v2):
98 """A finished request's final store must drain without another model step."""
99 backend, gpu, cpu = _make_backend()
100 worker = _make_worker(None, 0)
101 worker._backend = backend
102 connector = SimpleCPUOffloadConnector.__new__(SimpleCPUOffloadConnector)
103 connector.worker_handler = worker
104 output = _make_empty_scheduler_output()
105 output.kv_connector_metadata = SimpleCPUOffloadMetadata(
106 store_event=0, store_gpu_blocks=[0], store_cpu_blocks=[0]
107 )
108 module = "vllm.v1.worker.kv_connector_model_runner_mixin"
109 monkeypatch.setattr(f"{module}.get_kv_transfer_group", lambda: connector)
110 monkeypatch.setattr(f"{module}.set_forward_context", lambda *a: nullcontext())
111 monkeypatch.setattr(f"{module}.get_forward_context", lambda: None)
112 try:
113 gpu.fill_(91)
114 if use_v2:
115 active = ActiveKVConnector.__new__(ActiveKVConnector)
116 active.kv_connector = connector
117 active._disabled = False
118 active._pending_load_kwargs = None
119 module = "vllm.v1.worker.gpu.kv_connector"
120 monkeypatch.setattr(f"{module}.is_forward_context_available", lambda: True)
121 monkeypatch.setattr(f"{module}.get_forward_context", lambda: None)
122 result = active.no_forward(output)
123 else:
124 result = KVConnectorModelRunnerMixin.kv_connector_no_forward(output, None)
125 completion = (
126 result.kv_connector_output.kv_connector_worker_meta
127 if result.kv_connector_output is not None
128 else None
129 )
130 deadline = time.monotonic() + 5
131 while completion is None and time.monotonic() < deadline:
132 connector.get_finished(set())
133 completion = connector.build_connector_worker_meta()
134 time.sleep(0.001)
135 assert completion is not None, "CPU store never completed on the empty step"
136 assert isinstance(completion, SimpleCPUOffloadWorkerMetadata)
137 assert completion.completed_store_events == {0: 1}
138 assert torch.equal(cpu[0], gpu[0].cpu())
139 finally:
140 backend.shutdown()
141
142
143 def test_deferred_store_waits_for_draft_forward(monkeypatch):
144 """Target completion must not submit the store before draft finalization."""
145 backend, gpu, cpu = _make_backend()
146 worker = _make_worker(None, 0)
147 worker._backend = backend
148 connector = SimpleCPUOffloadConnector.__new__(SimpleCPUOffloadConnector)
149 connector.worker_handler = worker
150 output = _make_empty_scheduler_output()
151 output.kv_connector_metadata = SimpleCPUOffloadMetadata(
152 store_event=0, store_gpu_blocks=[0], store_cpu_blocks=[0]
153 )
154 module = "vllm.v1.worker.kv_connector_model_runner_mixin"
155 monkeypatch.setattr(f"{module}.get_kv_transfer_group", lambda: connector)
156 monkeypatch.setattr(f"{module}.has_kv_transfer_group", lambda: True)
157 monkeypatch.setattr(f"{module}.get_forward_context", lambda: None)
158 launch = MagicMock(wraps=backend.launch_copy)
159 monkeypatch.setattr(backend, "launch_copy", launch)
160 try:
161 with KVConnectorModelRunnerMixin._get_kv_connector_output(
162 output, defer_finalize=True
163 ):
164 gpu.fill_(17)
165 launch.assert_not_called()
166 gpu.fill_(91)
167 KVConnectorModelRunnerMixin.finalize_kv_connector()
168 assert launch.call_count == 1
169 completion = None
170 deadline = time.monotonic() + 5
171 while completion is None and time.monotonic() < deadline:
172 connector.get_finished(set())
173 completion = connector.build_connector_worker_meta()
174 time.sleep(0.001)
175 assert completion is not None
176 assert completion.completed_store_events == {0: 1}
177 assert torch.equal(cpu[0], gpu[0].cpu())
178 assert launch.call_count == 1
179 finally:
180 backend.shutdown()
181
182
183 def _drive_store(
184 backend: DmaCopyBackend,
185 gpu: torch.Tensor,
186 cpu: torch.Tensor,
187 *,
188 with_barrier: bool,
189 ) -> int:
190 """Run ITERS store cycles; return how many landed corrupted in the CPU pool.
191
192 Each cycle writes a unique value on a compute stream (after a deliberate
193 delay) and then issues the GPU->CPU store. The store is issued *after* the
194 write in host program order, mirroring the connector's deferred-store
195 assumption. Only the compute-done event creates a real device-side
196 happens-before edge.
197 """
198 block_ids = list(range(gpu.shape[0]))
199 compute_stream = torch.cuda.Stream()
200 corrupt = 0
201 for it in range(ITERS):
202 val = (it % 126) + 1 # 1..126; distinct from the zero-initialized pool
203 with torch.cuda.stream(compute_stream):
204 torch.cuda._sleep(SLEEP_CYCLES)
205 gpu.fill_(val)
206
207 wait_event = None
208 if with_barrier:
209 wait_event = torch.Event()
210 wait_event.record(compute_stream)
211
212 store_events: list[tuple[int, torch.Event]] = []
213 backend.launch_copy(
214 block_ids,
215 block_ids,
216 is_store=True,
217 event_idx=it,
218 events_list=store_events,
219 wait_event=wait_event,
220 )
221
222 deadline = time.time() + 10.0
223 while not store_events and time.time() < deadline:
224 time.sleep(0.0005)
225 assert store_events, "background copy was never enqueued"
226 store_events[0][1].synchronize()
227
228 if int((cpu[:, 0].to(torch.int32) != val).sum().item()):
229 corrupt += 1
230
231 # Drain the compute stream before returning: in the no-barrier control
232 # phase the store never waits on compute, so the host loop runs far ahead
233 # and leaves a backlog of sleep+fill kernels in flight. Without this, the
234 # leftover control-phase fills race the barrier phase's fill->copy window
235 # on the shared gpu tensor and flakily corrupt one iteration.
236 compute_stream.synchronize()
237 return corrupt
238
239
240 def test_store_orders_after_compute_write():
241 """The store must wait for the compute event; without it, it races.
242
243 Asserts both directions so the test is self-validating: the no-barrier
244 control must actually corrupt (proving the race window is exercised), and
245 the fixed path with the compute-done event must be clean.
246 """
247 backend, gpu, cpu = _make_backend()
248 try:
249 control = _drive_store(backend, gpu, cpu, with_barrier=False)
250 fixed = _drive_store(backend, gpu, cpu, with_barrier=True)
251 finally:
252 backend.shutdown()
253
254 assert control > 0, (
255 "no-barrier store did not race the compute write; the test no longer "
256 "exercises the hazard it is meant to guard"
257 )
258 assert fixed == 0, f"store raced compute even with the barrier: {fixed} corrupt"
259
260
261 class _RecordingBackend:
262 """Captures launch_copy calls without touching the GPU."""
263
264 def __init__(self) -> None:
265 self.calls: list[dict] = []
266
267 def launch_copy(
268 self,
269 src_blocks,
270 dst_blocks,
271 is_store,
272 event_idx,
273 events_list,
274 wait_event=None,
275 ) -> None:
276 self.calls.append({"is_store": is_store, "wait_event": wait_event})
277
278
279 def test_transfer_hooks_pass_wait_event_for_store_only():
280 """wait_for_save gates stores on a compute-done event; start_load_kv does not."""
281 worker = _make_worker(
282 kv_cache_config=None,
283 cpu_capacity_bytes=0,
284 )
285 recording = _RecordingBackend()
286 worker._backend = recording
287 worker._connector_metadata = SimpleCPUOffloadMetadata(
288 load_event=0,
289 load_gpu_blocks=[0],
290 load_cpu_blocks=[0],
291 store_event=1,
292 store_gpu_blocks=[1],
293 store_cpu_blocks=[1],
294 )
295
296 worker.start_load_kv()
297 worker.wait_for_save()
298
299 store_calls = [c for c in recording.calls if c["is_store"]]
300 load_calls = [c for c in recording.calls if not c["is_store"]]
301 assert len(store_calls) == 1
302 assert len(load_calls) == 1
303 assert isinstance(store_calls[0]["wait_event"], torch.Event)
304 assert load_calls[0]["wait_event"] is None
305
306
307 def test_build_params_src_access_order():
308 """build_params defaults to ANY and honors an explicit STREAM override."""
309 gpu = {"k": torch.zeros((4, 64), dtype=torch.int8, device="cuda")}
310 cpu = {"k": torch.zeros((4, 64), dtype=torch.int8, device="cpu")}
311 stream = torch.cuda.Stream()
312
313 default = build_params(gpu, cpu, stream)
314 assert default.attrs.srcAccessOrder == CU_MEMCPY_SRC_ACCESS_ORDER_ANY
315
316 ordered = build_params(
317 gpu, cpu, stream, src_access_order=CU_MEMCPY_SRC_ACCESS_ORDER_STREAM
318 )
319 assert ordered.attrs.srcAccessOrder == CU_MEMCPY_SRC_ACCESS_ORDER_STREAM
320
321
322 @pytest.mark.parametrize("layout", list(KVCacheLayout))
323 def test_register_shared_kv_cache_storage(monkeypatch, layout: KVCacheLayout):
324 num_blocks = 4
325 num_layers = 2
326 spec = FullAttentionSpec(
327 block_size=2,
328 num_kv_heads=2,
329 head_size=2,
330 dtype=torch.float16,
331 )
332 raw = torch.zeros(
333 num_blocks * num_layers * spec.page_size_bytes,
334 dtype=torch.int8,
335 device="cuda",
336 )
337 caches = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
338 layer_names = [f"layer.{i}" for i in range(num_layers)]
339 cache_config = MagicMock(
340 num_blocks=num_blocks,
341 kv_cache_tensors=[
342 dense_kv_cache_tensor(
343 raw, spec, num_blocks, num_layers, layout, layer_names
344 )
345 ],
346 )
347 worker = _make_worker(
348 kv_cache_config=cache_config,
349 cpu_capacity_bytes=raw.nbytes,
350 )
351 worker._backend = MagicMock()
352 monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
353
354 worker.register_kv_caches(
355 {f"layer.{layer_idx}": cache for layer_idx, cache in enumerate(caches)}
356 )
357
358 assert worker.gpu_kv_caches is not None
359 if layout.is_layer_compact and not layout.is_block_compact:
360 expected_regions = num_layers * spec.num_heads
361 expected_block_bytes = spec.page_size_bytes // spec.num_heads
362 elif layout.is_layer_compact:
363 expected_regions = num_layers
364 expected_block_bytes = spec.page_size_bytes
365 else:
366 expected_regions = 1
367 expected_block_bytes = spec.page_size_bytes * num_layers
368 assert len(worker.gpu_kv_caches) == expected_regions
369 assert {cache.shape for cache in worker.gpu_kv_caches.values()} == {
370 (num_blocks, expected_block_bytes)
371 }
372
373
374 def test_register_kv_cache_storage_with_trailing_padding(monkeypatch):
375 num_blocks = 4
376 block_bytes = 32
377 cache_bytes = num_blocks * block_bytes
378 raw = torch.zeros(4096, dtype=torch.int8, device="cuda")
379 cache = raw[:cache_bytes].view(num_blocks, block_bytes)
380 worker = _make_worker(
381 kv_cache_config=MagicMock(
382 num_blocks=num_blocks,
383 kv_cache_tensors=[
384 KVCacheTensor(
385 size=cache_bytes,
386 layers=["layer.0"],
387 layer_stride=cache_bytes,
388 block_stride=block_bytes,
389 )
390 ],
391 ),
392 cpu_capacity_bytes=cache_bytes,
393 )
394 worker._backend = MagicMock()
395 monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
396
397 worker.register_kv_caches({"layer.0": cache})
398
399 assert worker.gpu_kv_caches is not None
400 assert list(worker.gpu_kv_caches) == ["layer.0"]
401 assert worker.gpu_kv_caches["layer.0"].shape == (num_blocks, block_bytes)
402
403
404 def test_register_separate_kv_head_groups(monkeypatch):
405 # LHBNC hoists the K/V head groups outside the block dim, so each layer's
406 # blocks are registered as one region per group (K, V).
407 layout = KVCacheLayout.LHBNC
408 num_blocks = 4
409 num_layers = 2
410 spec = FullAttentionSpec(
411 block_size=2,
412 num_kv_heads=2,
413 head_size=2,
414 dtype=torch.float16,
415 num_head_slots=2,
416 state_content_bytes=2 * 2 * 2,
417 )
418 raw = torch.zeros(
419 num_blocks * num_layers * spec.page_size_bytes,
420 dtype=torch.int8,
421 device="cuda",
422 )
423 caches = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
424 layer_names = [f"layer.{i}" for i in range(num_layers)]
425 worker = _make_worker(
426 kv_cache_config=MagicMock(
427 num_blocks=num_blocks,
428 kv_cache_tensors=[
429 dense_kv_cache_tensor(
430 raw, spec, num_blocks, num_layers, layout, layer_names
431 )
432 ],
433 ),
434 cpu_capacity_bytes=raw.nbytes,
435 )
436 worker._backend = MagicMock()
437 monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
438
439 worker.register_kv_caches(
440 {f"layer.{layer_idx}": cache for layer_idx, cache in enumerate(caches)}
441 )
442
443 assert worker.gpu_kv_caches is not None
444 assert len(worker.gpu_kv_caches) == num_layers * spec.num_heads
445 per_group_block_bytes = (
446 spec.num_kv_heads * spec.block_size * spec.head_size * spec.dtype.itemsize
447 )
448 assert {cache.shape for cache in worker.gpu_kv_caches.values()} == {
449 (num_blocks, per_group_block_bytes)
450 }
451
452
453 def _dsa_specs(num_layers: int, block_size: int) -> dict[str, KVCacheSpec]:
454 """A DSA model's per-layer specs (DeepSeek-V3.2, GLM-5.2).
455
456 Each decoder layer contributes an MLA latent cache and the indexer's key
457 cache, whose pages differ in size (``MLAAttentionSpec`` off ``head_size``:
458 512 + 64 for the latent, 128 fp8 keys + one fp32 scale per 128 elements for
459 the indexer). Both are ``MLAAttentionSpec`` with the same block size, so the
460 hybrid allocator puts them in one ``UniformTypeKVCacheSpecs`` cache group.
461 See ``DeepseekV32IndexerCache.get_kv_cache_spec`` and
462 ``MLAAttention.get_kv_cache_spec``.
463 """
464 specs: dict[str, KVCacheSpec] = {}
465 for i in range(num_layers):
466 specs[f"model.layers.{i}.self_attn.attn"] = MLAAttentionSpec(
467 block_size=block_size,
468 num_kv_heads=1,
469 head_size=512 + 64,
470 dtype=torch.uint8,
471 cache_dtype_str="fp8",
472 )
473 specs[f"model.layers.{i}.self_attn.indexer.k_cache"] = MLAAttentionSpec(
474 block_size=block_size,
475 num_kv_heads=1,
476 head_size=128 + 128 // 128 * 4,
477 dtype=torch.uint8,
478 )
479 return specs
480
481
482 def test_register_mixed_page_sizes_in_one_cache_group(monkeypatch):
483 """Sparse-MLA models mix page sizes inside one cache group.
484
485 The MLA latent and indexer key caches of a layer have different page sizes,
486 so the allocation has no single per-layer block size to reinterpret it with:
487 ``num_layers * (mla_page + indexer_page)`` is not a multiple of either page.
488 Registration must derive each region from the placement metadata instead.
489 """
490 num_layers = 4
491 block_size = 64
492 specs = _dsa_specs(num_layers, block_size)
493 # Differing head sizes make the specs non-identical but same-type, which is
494 # what lands both caches of a layer in one group.
495 assert not is_kv_cache_spec_uniform(specs)
496 assert UniformTypeKVCacheSpecs.is_uniform_type(specs)
497 group = KVCacheGroupSpec(
498 list(specs),
499 UniformTypeKVCacheSpecs(block_size=block_size, kv_cache_specs=specs),
500 )
501
502 # DEEPSEEK_V32_INDEXER declares no supported layouts, so resolution lands on
503 # the default preference: layer-outermost, one region per layer.
504 layout = KVCacheLayout.LBNHC
505 vllm_config = MagicMock()
506 vllm_config.cache_config = CacheConfig()
507 vllm_config.cache_config.kv_cache_layout = layout.name
508 vllm_config.cache_config.num_gpu_blocks_override = None
509 vllm_config.attention_config.hisparse_config = None
510 vllm_config.kv_transfer_config = None
511
512 pages = [spec.page_size_bytes for spec in specs.values()]
513 num_blocks = 4
514 kv_cache_config = get_kv_cache_config_from_groups(
515 vllm_config, [group], sum(pages) * num_blocks
516 )
517 assert kv_cache_config.num_blocks == num_blocks
518 assert len(set(pages)) > 1, "the mixed page sizes are what this test covers"
519
520 kv_caches = allocate_kv_cache(kv_cache_config, torch.device("cuda"), layout)
521 worker = _make_worker(
522 kv_cache_config=kv_cache_config,
523 cpu_capacity_bytes=sum(pages) * num_blocks,
524 )
525 worker._backend = MagicMock()
526 monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
527
528 worker.register_kv_caches(kv_caches)
529
530 assert worker.gpu_kv_caches is not None
531 # One region per layer, each with that layer's own page as its block stride.
532 assert sorted(worker.gpu_kv_caches) == sorted(specs)
533 assert {name: cache.shape[1] for name, cache in worker.gpu_kv_caches.items()} == {
534 name: spec.page_size_bytes for name, spec in specs.items()
535 }
536 assert all(cache.shape[0] == num_blocks for cache in worker.gpu_kv_caches.values())
537
538 # Every registered region must alias the bytes the model writes through, or
539 # offloaded blocks would be copied from the wrong place.
540 for name, cache in kv_caches.items():
541 region = worker.gpu_kv_caches[name]
542 assert region.data_ptr() == cache.data_ptr()
543 assert region.stride(0) == specs[name].page_size_bytes
544
545
546 @pytest.mark.parametrize("rank_blocks", [1, 5])
547 def test_register_mixed_page_sizes_odd_block_counts(monkeypatch, rank_blocks):
548 """Registration holds at block counts that are not powers of two.
549
550 ``num_blocks`` comes out of ``available_memory // bytes_per_block``, so
551 any integer is reachable. Registration derives regions from the config's
552 own block count and strides, and the CPU pool rounds down from the same
553 per-block byte total; none of it assumes anything about how the count
554 was reached.
555 """
556 num_layers = 4
557 block_size = 64
558 specs = _dsa_specs(num_layers, block_size)
559 group = KVCacheGroupSpec(
560 list(specs),
561 UniformTypeKVCacheSpecs(block_size=block_size, kv_cache_specs=specs),
562 )
563 layout = KVCacheLayout.LBNHC
564 vllm_config = MagicMock()
565 vllm_config.cache_config = CacheConfig()
566 vllm_config.cache_config.kv_cache_layout = layout.name
567 vllm_config.cache_config.num_gpu_blocks_override = None
568 vllm_config.attention_config.hisparse_config = None
569 vllm_config.kv_transfer_config = None
570
571 pages = [spec.page_size_bytes for spec in specs.values()]
572 kv_cache_config = get_kv_cache_config_from_groups(
573 vllm_config, [group], sum(pages) * rank_blocks
574 )
575 assert kv_cache_config.num_blocks == rank_blocks
576
577 kv_caches = allocate_kv_cache(kv_cache_config, torch.device("cuda"), layout)
578 worker = _make_worker(
579 kv_cache_config=kv_cache_config,
580 cpu_capacity_bytes=sum(pages) * rank_blocks,
581 )
582 worker._backend = MagicMock()
583 monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
584
585 worker.register_kv_caches(kv_caches)
586
587 assert worker.gpu_kv_caches is not None
588 assert {n: c.shape for n, c in worker.gpu_kv_caches.items()} == {
589 name: (rank_blocks, spec.page_size_bytes) for name, spec in specs.items()
590 }
591 assert worker.num_cpu_blocks == rank_blocks
592
593
594 def test_mixed_page_byte_placement_is_dcp_invariant():
595 """DCP scales a block's token span, not its byte placement.
596
597 ``get_kv_cache_config_from_groups`` never reads
598 ``decode_context_parallel_size``, so every placement field registration
599 derives regions from is identical at dcp=1 and dcp=2. What DCP scales is
600 the block's token span, reported by ``resolve_kv_cache_block_sizes``;
601 checking that it doubles proves DCP was actually in effect, or the
602 identity above would be trivially true.
603 """
604 specs = _dsa_specs(4, block_size=128)
605
606 placements = []
607 for dcp_size in (1, 2):
608 group = KVCacheGroupSpec(
609 list(specs),
610 UniformTypeKVCacheSpecs(block_size=128, kv_cache_specs=specs),
611 )
612 vllm_config = MagicMock()
613 vllm_config.cache_config = CacheConfig()
614 vllm_config.cache_config.block_size = 128
615 vllm_config.cache_config.kv_cache_layout = KVCacheLayout.LBNHC.name
616 vllm_config.cache_config.num_gpu_blocks_override = None
617 vllm_config.parallel_config.decode_context_parallel_size = dcp_size
618 vllm_config.attention_config.hisparse_config = None
619 vllm_config.kv_transfer_config = None
620
621 page_bytes = sum(spec.page_size_bytes for spec in specs.values())
622 config = get_kv_cache_config_from_groups(vllm_config, [group], page_bytes * 4)
623 scheduler_block_size, _ = resolve_kv_cache_block_sizes(config, vllm_config)
624 assert scheduler_block_size == 128 * dcp_size
625 placements.append(
626 [
627 (t.size, tuple(t.layers), t.layer_stride, t.block_stride, t.offset)
628 for t in config.kv_cache_tensors
629 ]
630 )
631
632 assert placements[0] == placements[1]
633
634
635 @pytest.mark.parametrize(
636 ("block_bytes", "use_page_cache", "expect_ok"),
637 [
638 (4096, True, True), # aligned control
639 (3 * 512, True, True), # 512-aligned only: fine for buffered I/O
640 (3 * 512, False, False), # O_DIRECT keeps enforcing 4096 alignment
641 ],
642 )
643 def test_disk_backend_alignment_only_required_for_direct_io(
644 tmp_path, monkeypatch, block_bytes: int, use_page_cache: bool, expect_ok: bool
645 ):
646 """The 4096 stride assert belongs to O_DIRECT; page-cache I/O must not hit it.
647
648 Hybrid models (e.g. 101 per-rank cache tensors) sum to a block stride that
649 is 512- but not 4096-aligned, which previously made disk offload unbootable
650 even with use_page_cache=True.
651 """
652 # Host pinning is a separate lifecycle concern with its own tests; the
653 # alignment gate must not depend on registration state, so stub both ends.
654 monkeypatch.setattr(
655 "vllm.v1.simple_kv_offload.disk_backend.pin_tensor", lambda t: None
656 )
657 monkeypatch.setattr(
658 "vllm.v1.simple_kv_offload.disk_backend.unpin_tensor",
659 lambda t: None,
660 raising=False, # harmless on branches without teardown-side unpins
661 )
662 num_blocks = 4
663 gpu = {"k": torch.zeros((num_blocks, block_bytes), dtype=torch.int8, device="cuda")}
664 backend = DiskBackend()
665 disk_path = tmp_path / "kv-offload.bin"
666
667 def _init() -> None:
668 backend.init(
669 gpu,
670 gpu["k"].device,
671 torch.cuda.Stream(),
672 torch.cuda.Stream(),
673 str(disk_path),
674 num_blocks,
675 block_bytes,
676 use_page_cache=use_page_cache,
677 )
678
679 if not expect_ok:
680 with pytest.raises(AssertionError, match="not aligned"):
681 _init()
682 return
683
684 _init()
685 try:
686 assert disk_path.stat().st_size == num_blocks * block_bytes
687 finally:
688 backend.shutdown()