Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/features/kv_offloading_usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ vllm serve <model> \

Each entry in `secondary_tiers` is a dict with a required `type` field plus tier-specific fields.

The filesystem and object-store tiers can publish hash-only `BlockStored` KV events for blocks they successfully store, tagged with a stable per-tier `medium` (`FS` for the filesystem tier, `OBJ` for the object-store tier). Set `enable_secondary_tier_events: true` in the tier's entry to opt in; events are published only when KV cache events are also enabled globally via `--kv-events-config`.

### Filesystem (FS)

The filesystem tier (`type: "fs"`) writes blocks to a directory on local storage.
Expand All @@ -91,6 +93,7 @@ The filesystem tier (`type: "fs"`) writes blocks to a directory on local storage
| `root_dir` | yes | — | Base directory; vLLM creates subdirectories beneath it (see [On-Disk Layout](#on-disk-layout)). |
| `n_read_threads` | no | `16` | Read-priority I/O threads (load path). |
| `n_write_threads` | no | `16` | Write-priority I/O threads (store path). |
| `enable_secondary_tier_events` | no | `false` | Publish `BlockStored` KV events (medium `FS`) for successfully stored blocks. Requires globally enabled KV cache events. |

Each thread group prefers its own queue but pulls from the other when its primary queue is empty, so a write-heavy or read-heavy burst won't leave the off-priority queue waiting. Size the totals to your storage's effective concurrency.

Expand Down Expand Up @@ -120,6 +123,31 @@ To enable KV cache sharing between multiple vLLM instances using the same `root_
PYTHONHASHSEED=0 vllm serve ...
```

### Object Store (OBJ)

The object-store tier (`type: "obj"`) offloads blocks to an S3-compatible object store through the NIXL OBJ backend.

| Key | Required | Default | Notes |
| --- | --- | --- | --- |
| `type` | yes | — | Must be `obj`. |
| `store_config` | yes | — | Object store connection parameters (see below). |
| `prefix` | no | `""` | Key prefix prepended to all object keys. |
| `io_threads` | no | `4` | NIXL OBJ backend I/O threads. |
| `enable_secondary_tier_events` | no | `false` | Publish `BlockStored` KV events (medium `OBJ`) for successfully stored blocks. Requires globally enabled KV cache events. |

`store_config` fields:

| Key | Required | Default | Notes |
| --- | --- | --- | --- |
| `bucket` | yes | — | Bucket name. |
| `endpoint_override` | yes | — | Object store endpoint. |
| `scheme` | no | `http` | `http` or `https`. |
| `access_key`, `secret_key`, `session_token` | no | `""` | Explicit credentials. When left empty, the NIXL OBJ plugin falls back to the AWS SDK default credential provider chain (IAM roles, environment variables, credential files), which enables workload-identity auth on Kubernetes. |
| `region` | no | `""` | Bucket region, if the endpoint requires one. |
| `ca_bundle` | no | `""` | CA bundle path for TLS verification. |

Object keys follow the same run-configuration digest scheme as the filesystem tier (see [On-Disk Layout](#on-disk-layout)), stored under the optional `prefix`. The [Cross-Process Sharing](#cross-process-sharing) requirement (`PYTHONHASHSEED`) applies to shared buckets as well. At startup the tier probes object store connectivity and fails fast with a configuration error if the bucket is unreachable.

### P2P (Including P/D)

The P2P tier (`type: "p2p"`) shares completed KV blocks between vLLM instances over RDMA via NIXL. Each instance binds a control socket on `host:port` and exchanges blocks directly with peers — no shared filesystem required.
Expand Down
195 changes: 195 additions & 0 deletions tests/v1/kv_offload/tiering/test_fs_tier.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import pytest
import torch

from vllm.distributed.kv_events import MEDIUM_FS
from vllm.v1.kv_offload.base import (
LookupResult,
OffloadKey,
Expand Down Expand Up @@ -58,6 +59,16 @@
_MOCK_OFFLOADING_SPEC.block_size_factor = 1


def _make_offloading_spec(enable_kv_cache_events: bool) -> MagicMock:
"""Mock spec with an explicit global KV events flag."""
spec = MagicMock()
spec.vllm_config = _MOCK_VLLM_CONFIG
spec.kv_cache_config = _MOCK_KV_CACHE_CONFIG
spec.block_size_factor = 1
spec.kv_events_config.enable_kv_cache_events = enable_kv_cache_events
return spec


def key(n: int) -> OffloadKey:
return make_offload_key(n.to_bytes(8, "big"), 0)

Expand Down Expand Up @@ -164,6 +175,23 @@ def fs_tier(tmp_path):
tier.shutdown()


@pytest.fixture
def fs_tier_with_events(tmp_path):
tensor = _page_aligned_zero_tensor(4, _BLOCK_ELEMENTS)
mock_view = memoryview(tensor.numpy())
tier = FileSystemTierManager(
offloading_spec=_make_offloading_spec(enable_kv_cache_events=True),
primary_kv_view=mock_view,
tier_type="fs",
root_dir=str(tmp_path),
n_read_threads=4,
n_write_threads=4,
enable_secondary_tier_events=True,
)
yield tier
tier.shutdown()


# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -396,3 +424,170 @@ def test_batch_lookup_dispatch(fs_tier, monkeypatch, use_c_ext):

results = lookup_and_wait(tier, [key(1), key(2)])
assert results == [LookupResult.HIT, LookupResult.MISS]


# ---------------------------------------------------------------------------
# KV events
# ---------------------------------------------------------------------------


def test_successful_store_emits_stored_event(fs_tier_with_events):
"""A completed store job emits one stored event with the job's keys."""
tier = fs_tier_with_events
keys = [key(1), key(2)]
tier.submit_store(make_job(1, keys, [0, 1]))
assert all(r.success for r in drain(tier))

events = list(tier.take_events())
assert len(events) == 1
assert events[0].keys == keys
# Literal medium pins the wire contract, not just the constant choice.
assert events[0].medium == "FS"
assert not events[0].removed
# take_events drains the buffer.
assert list(tier.take_events()) == []


def test_load_job_emits_no_event(fs_tier_with_events):
tier = fs_tier_with_events
tier.submit_store(make_job(1, [key(1)], [0]))
results = drain(tier)
assert len(results) == 1
assert results[0].success
list(tier.take_events())

tier.submit_load(make_job(2, [key(1)], [1], is_promotion=True))
results = drain(tier)
assert len(results) == 1
assert results[0].success
assert list(tier.take_events()) == []


def test_mixed_job_results_emit_event_only_for_successful_job(
fs_tier_with_events, monkeypatch
):
"""With a failed and a successful store job in flight, exactly one event
is emitted and its keys belong to the successful job."""
import vllm.v1.kv_offload.tiering.fs.manager as mgr_mod

tier = fs_tier_with_events
failing_path = tier.file_mapper.get_file_name(key(1))
original_store_block = mgr_mod.store_block

def flaky_store_block(dest_path, *args, **kwargs):
if dest_path == failing_path:
raise OSError("injected store failure")
return original_store_block(dest_path, *args, **kwargs)

monkeypatch.setattr(mgr_mod, "store_block", flaky_store_block)

tier.submit_store(make_job(1, [key(1)], [0]))
tier.submit_store(make_job(2, [key(2)], [1]))
results = drain(tier)
assert len(results) == 2
by_id = {r.job_id: r for r in results}
assert not by_id[1].success
assert by_id[2].success

events = list(tier.take_events())
assert len(events) == 1
assert events[0].keys == [key(2)]


def test_partially_failed_store_emits_no_event(fs_tier_with_events, monkeypatch):
"""A store job with any failed block emits no event for the whole job."""
import vllm.v1.kv_offload.tiering.fs.manager as mgr_mod

tier = fs_tier_with_events
failing_path = tier.file_mapper.get_file_name(key(2))
original_store_block = mgr_mod.store_block

def flaky_store_block(dest_path, *args, **kwargs):
if dest_path == failing_path:
raise OSError("injected store failure")
return original_store_block(dest_path, *args, **kwargs)

monkeypatch.setattr(mgr_mod, "store_block", flaky_store_block)

tier.submit_store(make_job(1, [key(1), key(2)], [0, 1]))
results = drain(tier)
assert len(results) == 1
assert not results[0].success
assert list(tier.take_events()) == []
assert tier._store_job_keys == {}


def test_events_disabled_by_default(fs_tier):
tier, _ = fs_tier
tier.submit_store(make_job(1, [key(1)], [0]))
results = drain(tier)
assert len(results) == 1
assert results[0].success
assert tier.events is None
assert tier._store_job_keys == {}
assert list(tier.take_events()) == []


def test_events_require_global_kv_events_flag(tmp_path):
"""Tier-level opt-in alone is not enough; the global flag gates events."""
tensor = _page_aligned_zero_tensor(4, _BLOCK_ELEMENTS)
tier = FileSystemTierManager(
offloading_spec=_make_offloading_spec(enable_kv_cache_events=False),
primary_kv_view=memoryview(tensor.numpy()),
tier_type="fs",
root_dir=str(tmp_path),
enable_secondary_tier_events=True,
)
try:
assert tier.events is None
tier.submit_store(make_job(1, [key(1)], [0]))
results = drain(tier)
assert len(results) == 1
assert results[0].success
assert list(tier.take_events()) == []
assert tier._store_job_keys == {}
finally:
tier.shutdown()


def test_cascade_store_emits_fs_event_through_tiering_manager(tmp_path):
"""A GPU->CPU->fs cascade surfaces the tier-owned FS stored event via the
TieringOffloadingManager's aggregated take_events()."""
from vllm.v1.kv_offload.tiering.manager import (
CPUPrimaryTierOffloadingManager,
TieringOffloadingManager,
)

tensor = _page_aligned_zero_tensor(4, _BLOCK_ELEMENTS)
view = memoryview(tensor.numpy())
mock_region = MagicMock()
mock_region.create_kv_memoryview.return_value = view
primary = CPUPrimaryTierOffloadingManager(num_blocks=4, mmap_region=mock_region)
tier = FileSystemTierManager(
offloading_spec=_make_offloading_spec(enable_kv_cache_events=True),
primary_kv_view=primary.get_kv_memoryview(),
tier_type="fs",
root_dir=str(tmp_path),
enable_secondary_tier_events=True,
)
manager = TieringOffloadingManager(primary_tier=primary, secondary_tiers=[tier])
try:
keys = [key(1), key(2)]
manager.on_new_request(_CTX)
assert manager.prepare_store(keys, _CTX) is not None
manager.complete_store(keys, _CTX) # cascades to the fs tier

events = []
ctx = ScheduleEndContext(new_req_ids=[], preempted_req_ids=())
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline and not events:
manager.on_schedule_end(ctx)
events.extend(manager.take_events())
time.sleep(0.01)

fs_events = [e for e in events if e.medium == MEDIUM_FS]
assert len(fs_events) == 1
assert set(fs_events[0].keys) == set(keys)
assert not fs_events[0].removed
finally:
tier.shutdown()
Loading
Loading