Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@
/tensorrt_llm/_torch/attention/backends/sparse/*/cache_manager.py @NVIDIA/trt-llm-kv-cache-manager-devs
/tensorrt_llm/_torch/modules/fla @NVIDIA/trt-llm-torch-attention-devs
/tests/microbenchmarks/cute_dsl_kernels/paged_mqa_logits @NVIDIA/trt-llm-torch-attention-devs
/scripts/trtllm_gen_fmha_stage_kv @NVIDIA/trt-llm-torch-attention-devs
/tests/unittest/_torch/attention @NVIDIA/trt-llm-torch-attention-devs
# The kernel-ownership question this test was waiting on is settled: the top-k
# kernel has two production consumers (Attention and KV-cache compression), so it
Expand Down Expand Up @@ -355,6 +356,8 @@
/cpp/tensorrt_llm/nanobind/runtime/moe* @NVIDIA/trt-llm-moe-devs
/cpp/tensorrt_llm/runtime/moeLoadBalancer @NVIDIA/trt-llm-moe-devs
/tensorrt_llm/_torch/moe @NVIDIA/trt-llm-moe-devs
/tensorrt_llm/_torch/kernels/blackwell/moe_* @NVIDIA/trt-llm-kernels-devs @NVIDIA/trt-llm-moe-devs
/tensorrt_llm/_torch/modules/expert_l2_prefetch.py @NVIDIA/trt-llm-models-devs @NVIDIA/trt-llm-moe-devs
/tensorrt_llm/deep_ep @NVIDIA/trt-llm-moe-devs
/tests/microbenchmarks/bench_moe @NVIDIA/trt-llm-moe-devs
/tests/microbenchmarks/bench_moe_comm.py @NVIDIA/trt-llm-moe-devs
Expand Down
2 changes: 1 addition & 1 deletion cpp/tensorrt_llm/batch_manager/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ target_link_libraries(
tllm_kv_cache
PUBLIC tllm::kv_cache_host_memory tllm::common_cuda tllm::executor_types
CUDA::cuda_driver
PRIVATE tllm::common_environment)
PRIVATE tllm::common_environment tllm::executor_transfer_agent)

add_library(
tllm_kv_cache_legacy STATIC
Expand Down
49 changes: 45 additions & 4 deletions cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ SPDX-License-Identifier: Apache-2.0
# KVCacheManagerV2 C++ Guide

This directory contains the C++ implementation of KVCacheManagerV2: allocation,
prefix reuse, eviction, GPU/host/disk movement, page locking, and KV-cache event
prefix reuse, eviction, GPU/host/disk/remote movement, page locking, and KV-cache event
generation. Python accesses it through the nanobind bindings in
`cpp/tensorrt_llm/nanobind/batch_manager/kvCacheManagerV2.cpp`.

Expand Down Expand Up @@ -64,7 +64,9 @@ them before changing `batch.*`, `sparseCache.*` or the index conversion.
-- act on which class they caught; throw those directly:
`OutOfMemoryError` and its `Host`/`Disk`/`Cu` forms, `LogicError`,
`AssertionError`, `CuError`, `CorruptedError`, `ResourceBusyError`,
`OutOfPagesError`.
`OutOfPagesError`, and `RemoteMemError` (a failed remote cache level: the
Comment thread
dc3671 marked this conversation as resolved.
Resolved
V2 scheduler and the prefetch path catch it by class to re-match, recompute
or fail only the affected requests).
Validation at the binding boundary that throws `std::invalid_argument` or
`std::out_of_range` is legacy and should migrate to `TLLM_CHECK*` as it is
touched, so that KVCM2 ends up on the same footing as the rest of the repo.
Expand Down Expand Up @@ -148,7 +150,7 @@ sizes match, which is what lets a sparse pool be backed by host memory while a
dense pool of the same group and level is device memory; the group reports
GPU_MEM either way. Compatible sparse buffers still coalesce. Sparse buffers place no requirement on the cold tiers.

`StorageManager` coordinates GPU, host, and disk cache levels. It allocates
`StorageManager` coordinates GPU, host, disk, and remote cache levels. It allocates
slots, schedules pages for eviction, migrates pages between levels, and resizes
pools. `CopyEngine` performs the actual batched transfers; C++ code calls it
directly and must not round-trip through Python bindings.
Expand Down Expand Up @@ -428,6 +430,33 @@ physically duplicate the whole prompt; ownership splits at the prompt tail:
when that is unavailable or fails. Pieces are served reads first, then
required writes, then background writes, with aging so no queue starves.

### Remote cache levels

A remote level (`RemoteCacheTierConfig`, `CacheTier::REMOTE`) keeps its slots in
host memory other processes donate (`tensorrt_llm/_torch/pyexecutor/kv_cache/remote_donor.py`).

- `storage/remoteMem.*`: `RemoteMemClient`, one per rendezvous directory and
`StorageManager`: the donor table, the chunks claimed with O_EXCL claim files,
and the transfer backend. It opens and checks the directory once
(`openRendezvousDirectory`) and reads every donor file through that descriptor.
`RemoteRange` maps a pool's slots onto claimed chunks.
- `storage/remoteTransfer.h`: the backend interface; `remoteTransferAgent.*`
(NIXL, one-sided RDMA concluded on the host) and `remoteTransferFabric.*`
(fabric memory mapped into this process, copied on the caller's stream).
- Pages move through the pinned page staging ring. A host-concluded transfer
that misses its deadline fails the level, and its staging lease stays out of
use (`mUnquiescedRemoteTransfers`) until `quiesced()`; `destroy()` gives it one
more timeout, then leaks the lease, the claims and the backend
(`RemoteMemClient::abandon`).
- A failed client fails its levels for good: they take no pages and give none
back. `dropPagesOfFailedRemoteLevels()` drops their evictable pages,
`KvCacheManager::_unlinkPagesOfFailedRemoteLevels()` unlinks the held ones from
the radix tree (from `createKvCache` with tokens, `prefetchReuse` and the
probes), and `prepareFreeSlots()` retries an eviction past a level whose WRITE
failed. Callers tell this failure apart by `RemoteMemError`.
- A remote level cannot sit next to a file-backed disk level (rejected at
construction).

## Testing a change here

The Python suite (`tests/unittest/kv_cache_manager_v2_tests/`) does **not** build this
Expand Down Expand Up @@ -471,6 +500,15 @@ from it: the radix tree, the storage manager, and the living-`KvCache` set.
Mutating APIs take it exclusively; read-only queries take it shared, so several
`probeReuse()` lookups run concurrently while a writer is excluded.

Remote levels add two exceptions. Each `RemoteMemClient` has its own `mMutex`
for its donor table, claims and backend; it is taken inside the manager lock
(the storage manager calls the client), never the other way round, and the
client never calls back into the manager. Its failure flag `mFailed` is an
atomic, read without any lock by `StorageManager::anyRemoteLevelFailed()` /
`numFailedRemoteClients()`: the `any_remote_level_failed` binding and the
probes' check for newly failed levels, which then take the lock exclusively to
unlink their pages before matching.

**What the lock does and does not cover.** It protects state *shared between*
`KvCache`s, not the fields of an individual one, and it is a guarantee about the
bound (Python-visible) API only -- see "Where the guarantee applies" below.
Expand Down Expand Up @@ -525,7 +563,10 @@ Two exposed accessors look like they might leak shared state and do not:
`get_life_cycle_pool_group_indices`,
`get_page_stride`, `get_page_index_scale`, `get_page_index_converter`,
`get_mem_pool_base_address`, `supports_index_mode`, `init_config`, and the
config flags. `get_page_index_upper_bound` resembles that group but reads a
config flags. `any_remote_level_failed` is lock-free too but reads runtime
state: each remote client's atomic `failed()` flag, walking `mRemoteClients`,
which `destroy()` clears; it is safe while no `shutdown()` runs concurrently.
`get_page_index_upper_bound` resembles that group but reads a
pool's current `numSlots`, which `_adjustLevel()` changes, so it takes the
shared lock. Anything added here that reads resize-mutable state must too.
- `get_base_page_indices` returns a zero-copy numpy view, but into
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ set(KV_CACHE_MANAGER_V2_SRCS
kv_cache_manager_v2/utils/optionalGilRelease.cpp
kv_cache_manager_v2/storage/config.cpp
kv_cache_manager_v2/storage/core.cpp
kv_cache_manager_v2/storage/remoteMem.cpp
kv_cache_manager_v2/storage/remoteTransfer.cpp
kv_cache_manager_v2/storage/remoteTransferAgent.cpp
kv_cache_manager_v2/storage/remoteTransferFabric.cpp
kv_cache_manager_v2/evictionController.cpp
kv_cache_manager_v2/stagingBuffer.cpp
kv_cache_manager_v2/copyEngine.cpp
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ enum class CacheTier : int
GPU_MEM = 0,
HOST_MEM = 1,
DISK = 2,
REMOTE = 3,
};

// PageIndexMode — how converted page indices relate to layers within a layer group.
Expand Down
44 changes: 44 additions & 0 deletions cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include <algorithm>
#include <filesystem>
#include <map>
#include <optional>
#include <set>
#include <stdexcept>
#include <string>
Expand Down Expand Up @@ -165,6 +166,24 @@ void DiskCacheTierConfig::validate() const
}
}

void RemoteCacheTierConfig::validate() const
{
TLLM_CHECK_WITH_INFO(quota > 0, "RemoteCacheTierConfig: quota must be > 0");
TLLM_CHECK_WITH_INFO(std::filesystem::is_directory(path),
"RemoteCacheTierConfig: rendezvous directory '%s' is not a directory", path.c_str());
TLLM_CHECK_WITH_INFO(0 < waitTimeoutMs && waitTimeoutMs <= kMaxRemoteTimeoutMs,
"RemoteCacheTierConfig: wait_timeout_ms (donor_wait_timeout_s) must be in (0, %lld], got %lld",
static_cast<long long>(kMaxRemoteTimeoutMs), static_cast<long long>(waitTimeoutMs));
// The fabric transport's copies are stream-ordered and never timed.
TLLM_CHECK_WITH_INFO(transfer.transport != RemoteTransport::kNixl
|| (0 < transfer.timeoutMs && transfer.timeoutMs <= kMaxRemoteTimeoutMs),
"RemoteCacheTierConfig: the NIXL transfer timeout_ms (transfer_timeout_s) must be in (0, %lld], got %lld",
static_cast<long long>(kMaxRemoteTimeoutMs), static_cast<long long>(transfer.timeoutMs));
TLLM_CHECK_WITH_INFO(std::all_of(poolRatio.begin(), poolRatio.end(),
[](double weight) { return std::isfinite(weight) && weight > 0.0; }),
"RemoteCacheTierConfig: pool ratio entries must be positive and finite");
}

namespace
{

Expand Down Expand Up @@ -319,6 +338,31 @@ void KVCacheManagerConfig::validate() const
std::visit([](auto const& cfg) { cfg.validate(); }, tier);
}

// Remote levels move pages through the page staging buffer, which cannot reach a file-backed disk level, and share
// one transport, so that their copies are either all stream-ordered or all host-synchronous.
std::optional<RemoteTransport> remoteTransport;
bool hasFileDisk = false;
for (auto const& tier : cacheTiers)
{
if (std::holds_alternative<DiskCacheTierConfig>(tier))
{
hasFileDisk = true;
}
else if (auto const* remote = std::get_if<RemoteCacheTierConfig>(&tier))
{
if (remoteTransport.value_or(remote->transfer.transport) != remote->transfer.transport)
{
throw AssertionError("KVCacheManagerConfig: remote cache levels must share one transport");
}
remoteTransport = remote->transfer.transport;
}
}
if (remoteTransport.has_value() && hasFileDisk)
{
throw AssertionError(
"KVCacheManagerConfig: a remote cache level cannot be combined with a file-backed disk level");
}

// Zero asks for host-backed pools with no room for a single slot. It is not a way to turn
// them off: whether a pool is host-backed is a property of the buffer, not of this quota.
if (hostSparsePoolQuota.has_value() && *hostSparsePoolQuota == 0)
Expand Down
56 changes: 54 additions & 2 deletions cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/config.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "tensorrt_llm/common/assert.h"
#include <cmath>
#include <cstdint>
#include <map>
#include <optional>
#include <stdexcept>
#include <string>
Expand Down Expand Up @@ -119,8 +120,59 @@ struct DiskCacheTierConfig
void validate() const;
};

// Variant holding any tier config.
using CacheTierConfig = std::variant<GpuCacheTierConfig, HostCacheTierConfig, DiskCacheTierConfig>;
//! How a remote tier moves pages (storage/remoteTransfer.h). Donors must use the same one.
enum class RemoteTransport : int
{
//! A NIXL transfer agent (executor::kv_cache::BaseTransferAgent): one-sided RDMA, concluded on the host.
kNixl = 0,
//! NVLink fabric memory mapped into this process, copied on the caller's stream.
kFabric = 1,
};

//! Upper bound of the remote tier's timeouts: 1e6 s, as RemoteCacheConfig allows.
inline constexpr int64_t kMaxRemoteTimeoutMs = 1'000'000'000;

//! How a remote tier's pages move, apart from what memory it declares (RemoteCacheTierConfig).
struct RemoteTransferConfig
{
RemoteTransport transport = RemoteTransport::kNixl;
//! NIXL: how long one batch of transfers may take before the level fails (transfer_timeout_s), in (0,
//! kMaxRemoteTimeoutMs]. Unused by FABRIC, whose copies run on the stream.
int64_t timeoutMs = 30'000;
//! NIXL only: the agent's backend parameters, passed as they are (e.g. UCX's {"device_list": "mlx5_0, mlx5_1"});
//! empty uses the process's UCX environment.
std::map<std::string, std::string> backendParams;

bool operator==(RemoteTransferConfig const&) const = default;
};

//! Slots in host memory other processes donate (storage/remoteMem.h). Shares nothing with the disk tier.
struct RemoteCacheTierConfig
{
size_t quota = 0; // bytes
std::string path; // the rendezvous directory the donors publish into
//! How long creating the level waits for donor capacity (RemoteCacheConfig.donor_wait_timeout_s), in (0,
//! kMaxRemoteTimeoutMs].
int64_t waitTimeoutMs = 900'000;
//! Donors the job starts; once all have reported, a claim stops waiting. 0 if unknown.
uint32_t expectedDonors = 0;
//! Positive weights, one per layer group, that split the quota across layer groups instead of the hot level's
//! ratio; normalized by the storage manager. Empty follows the hot level.
std::vector<double> poolRatio;
//! How the pages move.
RemoteTransferConfig transfer;

[[nodiscard]] CacheTier tier() const noexcept
{
return CacheTier::REMOTE;
}

void validate() const;
};

// Variant holding any tier config; an alternative's index is its CacheTier.
using CacheTierConfig
= std::variant<GpuCacheTierConfig, HostCacheTierConfig, DiskCacheTierConfig, RemoteCacheTierConfig>;

// Helper to extract tier from a variant.
inline CacheTier cacheTierOf(CacheTierConfig const& cfg)
Expand Down
12 changes: 12 additions & 0 deletions cpp/tensorrt_llm/batch_manager/kv_cache_manager_v2/exceptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,18 @@ class OutOfPagesError : public std::runtime_error
}
};

// A remote cache level could not reach its donors, or a transfer to or from one failed or timed out
// (storage/remoteMem.h). Not an out-of-pages error: the level's contents can no longer be trusted, which no retry
// fixes.
class RemoteMemError : public std::runtime_error
{
public:
explicit RemoteMemError(std::string const& msg)
: std::runtime_error(msg)
{
}
};

// ---------------------------------------------------------------------------
// Helper: unwrap a weak_ptr, throw LogicError on dangling reference.
// Mirrors Python's unwrap_rawref(_utils.py:163).
Expand Down
Loading
Loading