Large Language ModelsInference & Performance Optimization
How do you design hierarchical KV-cache offloading for sparse-attention LLM decoding across GPU HBM, host DRAM, and scale-up memory pools?
Question 299 of 309 · Updated
On this page
- 1. The memory problem does not disappear when attention becomes sparse
- 2. A numerical example: full history, small GPU working set
- 3. Why ordinary CPU offload is not enough
- 4. Sparse attention creates two different cache access patterns
- 5. Hierarchical KV residency: the main components
- 5.1 Authoritative backing tier
- 5.2 Bounded HBM hot buffer
- 5.3 Selector and indexer
- 5.4 Transfer engine
- 5.5 Attention integration
- 5.6 Scheduler and memory-fabric controller
- 6. HiSparse: exact hierarchical KV residency
- 7. OasisKV and DualDecoder: predictive prefetch with sparse working sets
- 8. XM-Sparse: offloading both KV and indexer state to scale-up memory
- 9. Compare the design families without conflating correctness
- 10. A numerical example for hit rate and bandwidth
- 11. Cache replacement and working-set sizing
- 12. Coalescing, tiling, and transfer overlap
- 13. Exactness, approximation, and quality validation
- 14. Failure modes in production
- 15. How to benchmark a hierarchical sparse-KV system
- 16. A practical implementation and rollout sequence
- 17. Interview-ready summary
1. The memory problem does not disappear when attention becomes sparse#
Long-context LLM decoding is often limited by the key-value (KV) cache. Every generated token attends to selected parts of the request's history, and the serving system must preserve enough historical state to satisfy the model's attention mechanism.
Sparse attention reduces the amount of history read by an attention operation. A top-k selector, for example, may choose a few thousand positions from a much longer sequence. But sparse computation alone does not guarantee low memory use. If every historical KV entry must remain in GPU high-bandwidth memory (HBM) so that it can be selected later, the cache's storage footprint still grows with the full context.
This creates two different resource questions:
- How much history must remain available? The full KV history may be needed because future attention selections can point to any earlier token.
- How much history must be resident in HBM right now? Only a subset may be read by the current decode step.
A hierarchical KV-cache design separates these questions. It keeps the authoritative KV history in a larger, slower memory tier and maintains a bounded working set in HBM. The challenge is to fetch selected entries quickly enough that attention does not stall.
This lesson focuses on sparse-attention serving and hierarchical residency across HBM, host DRAM, and higher-bandwidth scale-up memory pools. It is distinct from:
- Question 242, which introduces general disaggregated KV storage and remote prefix reuse;
- Question 246, which focuses on reducing KV bytes through quantization and compression;
- Question 291, which focuses on saving or recomputing state when requests are preempted;
- Question 297, which distributes context/attention across GPUs;
- Question 298, which separates model-weight placement from request attention ownership.
Here the central issue is how to retain a complete selectable history while keeping only a small, actively used portion in scarce GPU memory.
2. A numerical example: full history, small GPU working set#
Imagine one request with a 256,000-token context. Assume its full KV history occupies 32 GiB. This is an illustrative number; real cache size depends on model layers, KV heads, head dimension, dtype, attention architecture, and implementation.
Suppose the sparse-attention selector chooses 2,048 historical token positions for the next decode step.
A dense-resident design may keep all 32 GiB in HBM even though this attention operation reads only the selected positions. A hierarchical design could instead:
- retain the complete 32 GiB in host or pooled memory;
- keep a small hot KV buffer in HBM;
- fetch selected entries that are not already resident;
- use the fetched entries for attention;
- retain or evict blocks according to future reuse and memory budget.
If the selected 2,048 tokens occupy 256 MiB in this hypothetical model, the active attention working set is much smaller than the full history. But the system must still handle selection metadata, block alignment, layer-specific layouts, hot-buffer space, temporary tensors, and cache misses.
The key distinction is:
Full KV history: authoritative and selectable
|
v
Selection/indexing: identifies needed token positions
|
v
Bounded HBM working set: hot and fetched KV blocks
|
v
Attention kernel: consumes the selected KV entriesThe goal is not to pretend the full history no longer exists. The goal is to avoid paying the HBM capacity cost for every historical entry at every decode step.
3. Why ordinary CPU offload is not enough#
A basic offload system moves KV blocks from GPU memory to host DRAM and fetches them back when required. This increases the amount of state that can be retained, but it introduces a data-movement path.
A simplified transfer lower bound is:
transfer time >= bytes transferred / effective bandwidthFor example, transferring 256 MiB over an effective 32 GiB/s link has a payload lower bound of roughly 7.8 ms, before queueing, launch overhead, synchronization, and memory-layout conversion. If a decode step needs many such transfers on its critical path, inter-token latency can rise sharply.
Three limitations matter:
- Bandwidth: PCIe-class host-device links can be much slower than HBM. Fetching selected KV entries on demand can stall attention.
- Capacity: host DRAM is larger than GPU HBM, but it is not unlimited. Very high concurrency can exhaust host memory too.
- Transfer granularity: sparse selectors may request small or scattered token blocks. Many tiny copies can waste bandwidth and create substantial launch and bookkeeping overhead.
The right comparison is not “HBM is fast, host RAM is slow.” It is whether the system can overlap the movement of the required KV blocks with useful computation, and whether the resulting working set fits within the memory and bandwidth budgets.
4. Sparse attention creates two different cache access patterns#
A sparse-attention serving stack may maintain more than one kind of state.
KV data contains the keys and values used by attention. Which KV positions are needed can depend on the current query and selector output. These accesses may be dynamic and irregular.
Indexer or selection metadata helps decide which historical positions matter. In models such as DeepSeek sparse-attention variants, compact indexer keys (often called K-index state) are used to score or select historical tokens. The access pattern for this metadata can be more predictable than the eventual selected KV reads.
This distinction matters because one transfer policy is unlikely to be optimal for both:
- dynamic KV misses may be fetched on demand and overlapped with attention;
- predictable index pages can be prefetched before they are needed.
XM-Sparse makes this distinction central. Its paper argues that offloading KV alone does not remove the HBM ceiling if hot KV buffers and a fully resident indexer-key cache still occupy substantial GPU memory. It therefore offloads both kinds of state and uses different I/O paths for them.
Do not assume every sparse-attention architecture has a separate K-index cache. The details depend on the model's selector and attention design. A generic system should expose the selector's metadata requirements rather than hard-code one model's state layout.
5. Hierarchical KV residency: the main components#
A practical design can be understood as six cooperating components.
5.1 Authoritative backing tier#
This tier retains the complete KV history required by the model's selection semantics. Depending on the deployment, it may be:
- host DRAM attached to the decode server;
- a shared or remote memory pool;
- a scale-up memory fabric with direct GPU access;
- a combination of local and remote tiers.
The backing tier must preserve request identity, layer identity, token positions, KV layout, dtype, and ownership metadata. A cache block cannot be treated as an interchangeable byte range.
5.2 Bounded HBM hot buffer#
The GPU retains a fixed or dynamically controlled set of recently used or predicted-to-be-used KV blocks. This reduces HBM usage from full-history residency to a working-set budget.
The hot buffer needs:
- block-level identity and location metadata;
- a replacement policy;
- free-list or allocator management;
- pinning for blocks currently used by kernels;
- synchronization for concurrent reads and evictions;
- accounting for temporary staging buffers.
A simple LRU policy is a useful baseline, but sparse attention can have access patterns where pure recency is not ideal. A token selected repeatedly may be valuable even if its most recent use was several steps ago. More advanced policies can combine recency, frequency, selection probability, and transfer cost.
5.3 Selector and indexer#
The selector determines which historical token positions are needed. Its output must be mapped to physical KV blocks.
The selector may use:
- query-dependent top-k scores;
- indexer keys;
- attention-specific sparse patterns;
- recent-token windows plus selected long-range positions;
- lookahead information from speculative decoding.
The selector is part of correctness. If it changes which tokens the model attends to, the output distribution may change. If the goal is exact output preservation, the hierarchy should change placement and retrieval only, not selection semantics.
5.4 Transfer engine#
The transfer engine moves blocks from the backing tier to HBM. It should support:
- coalescing adjacent token or page requests;
- asynchronous copies;
- pinned host buffers where required;
- DMA or hardware-assisted transfer mechanisms supported by the platform;
- bounded in-flight requests;
- cancellation when a request finishes or a selection becomes obsolete;
- prioritization for latency-critical decode work.
5.5 Attention integration#
A naive design performs selection, copies all misses, waits for completion, and only then launches attention. This serializes transfer and compute.
A better design overlaps data movement with useful attention work:
- Identify which selected blocks are already in HBM.
- Compute attention for resident tiles.
- Fetch missing tiles while resident tiles are being processed.
- Consume fetched tiles as they arrive.
- Update the hot buffer and metadata safely.
This is where fused kernels and tile-level pipelines can matter. The kernel can resolve hits, request missing data, and perform attention in a coordinated schedule rather than forcing a separate global swap-in stage.
5.6 Scheduler and memory-fabric controller#
The scheduler coordinates cache traffic with other GPU and fabric activity. Prefetching should not overwhelm:
- attention-critical reads;
- expert-parallel collectives;
- tensor-parallel communication;
- model activation transfers;
- other latency-sensitive kernels.
A good policy limits outstanding requests, batches small transfers, observes fabric utilization, and backs off when decode latency rises.
6. HiSparse: exact hierarchical KV residency#
HiSparse is an example of a hierarchical cache designed for sparse-attention serving. Its key idea is to retain the full KV history in host memory while bounding the GPU decode footprint with a small fixed-size cache.
The paper describes a fused CUDA kernel that resolves per-layer selections, checks whether selected KV blocks are already resident, performs LRU replacement, and fetches missing blocks from host memory within the decode CUDA graph. For models where selection information is shared across layers, it also describes exact layer-wise prefetching to hide part of the remaining miss overhead.
The important correctness property is that HiSparse changes KV placement rather than the attention selection or model computation. The authors report that model outputs are unchanged. That makes it conceptually different from approximate sparse-selection techniques that intentionally reduce the attended token set.
The paper reports evaluation across DeepSeek Sparse Attention (DSA), Native Sparse Attention (NSA), and Quest on H200, B200, and GH200 platforms. It reports peak generation-throughput improvements of up to 4.7× on long-context workloads while preserving comparable per-token latency. These are paper-specific maxima, not a guarantee for every request distribution or hardware setup.
Engineering lessons:
- keep full history available if exact selection must remain possible;
- bound the GPU-resident working set;
- resolve cache hits and misses close to the attention kernel;
- avoid a separate synchronization point for every fetched block;
- exploit layer-wise selection reuse only when the model semantics permit it;
- measure host-device I/O as the remaining cost after compute and metadata overhead are controlled.
7. OasisKV and DualDecoder: predictive prefetch with sparse working sets#
Other systems exploit the fact that decode-time attention can be sparse and that future KV demand may be predicted.
OasisKV uses lookahead tokens drafted by speculative decoding to predict important future KV blocks. A background pipeline identifies and prefetches selected blocks from host or remote memory into HBM before the next decode step needs them. It also considers tiering across prefill, decode, and remote-memory nodes.
The OasisKV paper reports that, with a 2,048-token KV budget, its evaluated configuration stayed within about 0.61 points of full-attention accuracy on the reported benchmarks. It reports up to 1.86× throughput over vLLM on AIME24 and up to 2.2× in multi-GPU long-context serving in its evaluated configurations. Those results involve a sparse selection path and therefore must be interpreted with the quality metric and workload, not just throughput.
DualDecoder also uses predictive prefetching. Its key observation is that the preceding speculated token can help predict which KV entries will be needed in the next decode step. It combines a dual-token decoding pipeline with layer-aware transfer scheduling and a layer-scoped memory manager. The paper reports up to 2.62× decoding throughput over its evaluated state-of-the-art systems while preserving its reported latency and model-quality targets.
These designs share the principle of moving data before the foreground attention operation needs it. But prediction introduces questions that an exact cache-placement design does not:
- What happens when a predicted block is wrong?
- Is the missing block fetched on demand, or does the request stall?
- Does the predictor consume meaningful HBM or compute?
- Does speculative-token acceptance rate affect prefetch usefulness?
- Can prediction be disabled when it harms latency or bandwidth?
A production system needs a mandatory miss-recovery path. Prediction should optimize the common case; it must not become the only way to retrieve correct KV state.
8. XM-Sparse: offloading both KV and indexer state to scale-up memory#
XM-Sparse extends sparse-attention offloading to scale-up memory pools. Its motivation is that moving KV history out of HBM may still leave two important HBM consumers: hot KV buffers and the indexer-key cache used to select tokens.
The paper distinguishes their access patterns and uses different mechanisms.
Dynamic KV entries: XM-Sparse fuses TMA-based retrieval with attention in a tile-level pipeline. It processes available tiles and fetches missing ones while computation proceeds, reducing the need for a separate swap-in stage.
Predictable K-index pages: XM-Sparse uses GPU-initiated DMA to prefetch pages. The paper describes coordinating this prefetching with latency-critical operations so index traffic does not interfere with decode-critical KV retrieval or other shared-fabric operations.
The design point is important: a larger, faster external memory tier does not automatically solve HBM pressure. If index metadata and hot KV buffers remain resident, they can still limit the batch size. XM-Sparse therefore treats both as candidates for offloading, with different I/O policies.
The paper reports an implementation atop SGLang and evaluation on DeepSeek-V3.2 and GLM-5.3 using an emulated scale-up memory pool. It reports up to 4.98× and 4.52× higher decode throughput than PCIe-based ECHO and HiSparse, respectively, and up to 1.34× over a naive integration on the same emulated pool, across 16K–1M contexts.
Important limitation: the reported scale-up memory pool is emulated. These results are promising system evidence, but they do not establish identical performance, contention, power, or tail-latency behavior on every real memory-fabric deployment. Validate on the target hardware before using the reported ratios for capacity planning.
9. Compare the design families without conflating correctness#
The systems above share the broad objective of reducing HBM residency, but their correctness contracts differ.
- HiSparse: changes where selected KV blocks reside. Its stated objective is exact, indexer-agnostic sparse-attention serving with full history retained in host memory.
- OasisKV: uses speculative lookahead to predict important future tokens and selectively stage KV blocks. Its evaluation reports small measured quality differences under its sparse working-set budget.
- DualDecoder: predicts future KV demand using a preceding speculated token and overlaps transfer with decode. Its gains depend on prediction and transfer scheduling.
- XM-Sparse: targets scale-up memory pools and offloads both dynamic KV entries and predictable indexer-key pages using different transfer mechanisms.
Do not label every method “lossless KV compression.” These methods primarily change residency, selection, prefetch, and data movement. Whether the model output is unchanged depends on whether the exact attention selection and values are preserved. A bounded sparse working set can be exact if every selected block is fetched correctly; an approximate selector or restricted token budget can change the attended set and therefore model behavior.
10. A numerical example for hit rate and bandwidth#
Assume a decode step selects 2,000 KV blocks. Each block is 128 KiB, so the selected payload is approximately 250 MiB.
Suppose:
- 80% of selected blocks are already resident in HBM;
- 20% are misses;
- the missing payload is therefore about 50 MiB;
- effective backing-tier bandwidth is 100 GiB/s.
The ideal payload transfer time for the misses is about 0.49 ms. Real latency will be higher because of lookup, queueing, synchronization, transfer granularity, and kernel scheduling.
Now compare two situations:
Low hit rate: If only 20% of blocks hit, about 200 MiB must be fetched. The ideal payload time rises to about 1.95 ms at the same effective bandwidth.
Higher bandwidth: If the backing tier can sustain 400 GiB/s for this traffic pattern, the 50 MiB miss payload has an ideal transfer time near 0.12 ms.
These calculations illustrate why hit rate and bandwidth interact. But a high hit rate is not sufficient if the hot buffer consumes too much HBM, and high external bandwidth is not sufficient if the indexer metadata remains resident and caps concurrency.
A useful system objective is to maximize SLO-compliant throughput subject to:
- HBM budget;
- host or pooled-memory capacity;
- effective transfer bandwidth;
- maximum outstanding I/O;
- acceptable miss latency;
- accuracy or exactness requirements.
11. Cache replacement and working-set sizing#
A small HBM cache must choose which blocks remain resident.
LRU evicts the least recently used block. It is simple and often useful, but can perform poorly when a large one-time scan displaces frequently reused blocks.
Frequency-aware policies retain blocks that are repeatedly selected. They may require counters or approximate frequency sketches, which themselves consume memory and update bandwidth.
Selection-aware policies use recent selector outputs or known sparse-attention patterns to estimate reuse. They can improve hit rate but must not confuse predicted future relevance with guaranteed demand.
Cost-aware policies account for the time and bandwidth required to reload a block. A remote-memory miss may be more expensive than a local host-memory miss, so equal recency does not imply equal eviction cost.
The cache budget should be measured in bytes, not merely number of blocks, if layers or cache formats have different block sizes. It should also reserve space for in-flight fetches; otherwise the system can deadlock or thrash while trying to load blocks into an already full buffer.
A robust implementation should distinguish:
- resident and unpinned blocks;
- resident and currently pinned blocks;
- fetches in flight;
- blocks selected but not yet requested;
- blocks no longer needed by any active attention operation.
Eviction must not free memory while an asynchronous attention kernel still reads it.
12. Coalescing, tiling, and transfer overlap#
Sparse selection can produce scattered token indices. Issuing one copy for every small fragment can be inefficient.
A transfer planner can:
- map selected token positions to cache pages or blocks;
- sort or group requests by physical location;
- merge adjacent ranges where possible;
- prioritize blocks needed earliest;
- issue bounded asynchronous transfers;
- expose completion events to the attention pipeline.
Tile-level fusion can avoid a global wait. For example, while attention computes on resident tiles, a TMA-backed path may fetch a missing tile into shared memory for a later attention iteration. The exact mechanism depends on GPU architecture, memory fabric, and supported transfer APIs.
Prefetching also needs backpressure. If the system queues more reads than the memory fabric can serve, it can increase tail latency for all requests. A useful controller monitors:
- outstanding bytes and request count;
- queue depth and completion latency;
- HBM hit rate;
- transfer bandwidth by memory tier;
- time spent waiting for data;
- impact on decode ITL/TPOT.
The controller should reduce speculative or low-priority prefetch traffic when the fabric is saturated.
13. Exactness, approximation, and quality validation#
There are two broad ways to use sparse KV residency.
Exact selection with hierarchical placement: The model's selector chooses the same positions it would have chosen if all KV data were in HBM. The system fetches any selected entries that are not resident. If every selected value is retrieved correctly and in time, the attention computation can remain unchanged.
Approximate selection or bounded attention: The system intentionally limits which tokens can be selected or uses a predictor that may omit relevant entries. This can reduce transfers and memory use further, but it changes the effective attention input and may affect output quality.
Do not compare these systems using throughput alone. Track:
- exact output parity where exactness is claimed;
- task-level quality for approximate variants;
- long-context retrieval and needle-in-a-haystack tests;
- reasoning benchmarks and adversarial prompts;
- output divergence across context lengths;
- selection recall and precision where a reference set exists;
- performance under low and high KV miss rates.
A quality tolerance should be explicit and workload-specific. A 0.5-point aggregate score change may be acceptable for one use case and unacceptable for another.
14. Failure modes in production#
Cold-cache storms. Many requests begin with empty HBM working sets and issue large numbers of reads at once. Stagger admission, reserve I/O capacity, and warm predictable state only when justified.
Hot-buffer thrashing. A buffer that is too small can repeatedly evict blocks that are needed again shortly. Measure reuse distance and miss rate, and test cache budgets under realistic mixed contexts.
Indexer cache becomes the new bottleneck. Offloading KV but retaining all selector metadata in HBM can leave the system capacity-bound. Treat metadata residency as a first-class budget.
Transfer queue saturation. Too many prefetch requests can compete with demand reads. Apply priority, rate limits, and backpressure.
Stale or incorrect mappings. A selector index may point to an evicted or relocated block. Use versioned block mappings and synchronize relocation with in-flight readers.
Request completion races. A request can finish while its KV fetch is in flight. Cancel or safely retire the transfer without recycling memory still referenced by a kernel.
Host-memory exhaustion. Offloading moves the capacity problem; it does not eliminate it. Apply per-tenant quotas, admission control, eviction, and explicit failure behavior.
NUMA and topology mistakes. Host memory attached to the wrong CPU socket or GPU root complex can reduce effective bandwidth. Benchmark the actual topology and pin memory and workers deliberately.
Fabric contention. Scale-up memory, collectives, and other I/O may share resources. Prioritize decode-critical reads and measure interference rather than assuming peak link bandwidth is available to every workload.
Approximation hidden as a cache optimization. If the selector or token set changes, this is a quality-affecting algorithmic change, not merely a transparent storage optimization. Version and evaluate it accordingly.
15. How to benchmark a hierarchical sparse-KV system#
Use a representative matrix of workloads:
- short and long contexts;
- low and high concurrency;
- sparse-attention models with different selector behavior;
- warm and cold working sets;
- low and high cache miss rates;
- local host DRAM and scale-up memory where available;
- steady-state and bursty arrivals.
Compare at least:
- full KV residency in HBM;
- conventional host offload;
- bounded HBM cache with on-demand fetch;
- prefetch-enabled design;
- scale-up memory design;
- a no-I/O or all-HBM oracle to isolate kernel and selection overhead.
Track:
- decode throughput and completed requests per second;
- p50/p95/p99 inter-token latency or TPOT;
- time to first token;
- HBM bytes used by KV, hot buffers, indexer state, and runtime;
- host and pooled-memory capacity;
- hit/miss rate by cache type;
- bytes transferred per generated token;
- effective bandwidth and transfer queue depth;
- kernel time spent waiting for missing blocks;
- selector and indexer overhead;
- quality metrics and exactness checks;
- cost per million generated tokens.
Run both fixed-concurrency and fixed-SLO comparisons. A system that increases peak throughput while violating p99 inter-token latency is not a win for an interactive endpoint.
For a scale-up memory pool, test real hardware where possible. If only an emulated pool is available, document the emulation, link latency, bandwidth model, contention assumptions, and capacity mapping. Do not treat an emulated result as a production guarantee.
16. A practical implementation and rollout sequence#
- Confirm sparse-attention semantics. Identify the selector, token-selection granularity, KV format, and whether exact output preservation is required.
- Measure the full-resident baseline. Establish HBM usage, throughput, ITL, quality, and concurrency with all KV state resident.
- Separate memory accounting. Measure full KV history, hot KV buffers, indexer state, selection metadata, and temporary workspaces independently.
- Choose the backing tier. Start with local host DRAM if it meets capacity and bandwidth needs; consider scale-up or remote memory only when the topology justifies it.
- Implement a bounded HBM cache. Add block identity, pinning, safe eviction, and miss recovery before introducing prediction.
- Integrate retrieval with attention. Overlap transfers with resident-tile computation and avoid a global wait where the kernel design permits.
- Add prefetch conservatively. Use observed selection patterns or supported lookahead signals, and retain an on-demand miss path.
- Offload metadata when justified. If indexer state consumes significant HBM, design a separate policy for its more predictable access pattern.
- Stress the memory fabric. Test cold starts, bursts, high miss rates, large contexts, and simultaneous collectives.
- Validate correctness and quality. Verify exact parity for placement-only changes and task quality for approximate selection.
- Canary production traffic. Compare latency, throughput, memory, error rates, and cost under a representative slice.
- Keep a fallback. Retain full-HBM or conventional offload mode until the new system proves stable.
17. Interview-ready summary#
Sparse attention can reduce the KV data read by each decode step, but it does not automatically reduce the amount of history that must remain available. A hierarchical KV system keeps the complete history in host or pooled memory and maintains a bounded HBM working set for selected tokens. It needs a selector-to-block mapping, safe replacement, asynchronous retrieval, and overlap between data movement and attention. HiSparse emphasizes exact hierarchical residency; OasisKV and DualDecoder use lookahead-based predictive prefetch; XM-Sparse extends offloading to scale-up memory and treats both dynamic KV entries and predictable indexer-key pages as separate I/O problems. The production choice depends on the model's selection semantics, memory topology, miss rate, quality contract, and measured tail latency—not just peak throughput.
References
- 1.
- 2.
- 3.
- 4.
- 5.Stanford MAST — HiSparsemast.stanford.edu
- 6.vLLM — KV Cache Offloadingdocs.vllm.ai
Related questions
- How does Decode Token Parallelism (TKNP) decouple attention ownership from model-weight placement to scale high-concurrency, long-context LLM decoding across nodes?
- How do context parallelism and decode context parallelism scale long-context LLM inference across GPUs while balancing KV-cache capacity, attention compute, and communication?
- What is Direct Paged Attention?
Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents