Implement paged KV cache access in C++ and optimize copies, page tables and prefetch
Company: NVIDIA
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
In a 25-minute coding segment you receive a C++ code skeleton and must implement the access path of a paged key-value (KV) cache, the structure transformer inference uses to keep the attention keys and values of every token a sequence has processed. The code has to be bug-free, and you must dry-run it by hand on a small example. You then explain the code and discuss optimizations, with many follow-up questions.
The interview's skeleton was not reported, so assume the standard paged layout below and confirm the details with the interviewer:
- Keys and values are each stored in a pool of fixed-size physical pages. A page holds `page_size` consecutive tokens of one sequence, and one token's key (or value) for the layer is `token_bytes` contiguous bytes.
- Each sequence has a page table mapping its logical page index to a physical page id, so its pages can sit anywhere in the pool.
- Pages come from a free list as a sequence grows and go back to it when the sequence ends.
A stand-in skeleton:
```cpp
#include <cstddef>
#include <cstdint>
#include <unordered_map>
#include <vector>
struct PagedKVCache {
int page_size; // tokens per page
size_t token_bytes; // bytes of one token's key, and of its value
std::vector<uint8_t> k_pool, v_pool; // num_pages * page_size * token_bytes bytes each
std::vector<int> free_pages; // physical page ids not in use
std::unordered_map<int, std::vector<int>> page_table; // sequence id -> physical page ids
std::unordered_map<int, int> seq_len; // sequence id -> tokens stored
// Store one token's key and value at the end of a sequence.
bool append(int seq_id, const uint8_t* k, const uint8_t* v);
// Copy the keys and values of tokens [begin, end) of a sequence into contiguous buffers.
bool gather(int seq_id, int begin, int end, uint8_t* k_out, uint8_t* v_out) const;
};
```
### Clarifying Questions
- Does "access" mean only reading a sequence's cached tokens, or also appending new ones?
- What should happen when the free list is empty or a requested range is out of bounds: a status code, an exception, or an assertion?
- Is this host-side C++ over ordinary memory, or a model of what a GPU kernel will do?
- Can more than one thread use the cache at the same time?
### Part 1 — Implement the access path
Implement `append` and `gather`, plus any helper you need. Then dry-run them by hand: with `page_size = 4` and a sequence that holds 10 tokens and has the page table `[7, 2, 5]`, trace `gather` for tokens `[3, 9)` and then one `append`, stating every page id and offset your code computes.
```hint Split the position
A token position has to become a page and a slot inside that page. Write that translation once and check it on the first and last token of a page.
```
```hint Decide the boundaries first
Before writing the loops, decide what `append` does when the last page is exactly full and when the free list is empty, and what `gather` does when the range starts or ends in the middle of a page.
```
#### What This Part Should Cover
- Correct translation from a token position to a physical page and byte offset, including page boundaries
- An append that takes a page only when needed and leaves the cache unchanged when no page is available
- A gather that handles ranges spanning several pages, with bounds checks
- A by-hand dry run whose numbers match the code
### Part 2 — Explain and optimize
Walk the interviewer through your code, then discuss how you would improve it: the API design, an efficient implementation of the copies (the `memcpy` calls), the page table design in the original code, whether prefetching can be improved, and whether the address translation can be overlapped further with the data movement.
```hint Count the work
For a long range, count how many copy calls and how many page-table lookups your gather makes, and what each one costs.
```
```hint What can be in flight
Translating the next page does not depend on the bytes of the current one. Think about what could be in progress at the same time.
```
#### What This Part Should Cover
- API changes that avoid unnecessary copies and batch work across tokens or sequences
- Copy granularity, alignment, and the memory layout of pages and of keys versus values
- The page table's data structure and the cost of each lookup
- Prefetching and pipelining translation with copies, including how this maps to a GPU
### What a Strong Answer Covers
- Bug-free code that matches the dry run, with off-by-one cases at page edges handled
- A clear explanation of the data layout and each function's contract
- Optimizations justified by where the time goes: lookups, number of copies, bandwidth, latency
- Awareness of how the same access path maps to GPU memory and attention kernels
### Follow-up Questions
- Two sequences share a common prompt prefix. How would you let them share pages, and what happens when one of them appends?
- How would you lay out keys and values (separate pools, interleaved, grouped by attention head) for a kernel that reads one head at a time?
- How do pages return to the free list when a sequence finishes or is evicted, and does the pool suffer from fragmentation?
- Instead of gathering into a contiguous buffer, how could the attention computation read the pages in place?
Overview: A C++ coding exercise to implement the access path of a paged KV cache for transformer inference, translating token positions through a page table to physical pages and copying key and value data, with a hand dry run. Follow-ups probe API design, efficient copies, page table layout, prefetching, and overlapping address translation with data movement.
Read the full NVIDIA Software Engineer interview experience this question came from