Gather a paged KV cache through a block table
Why it matters Paged attention kernels in production servers do exactly this lookup for every key they read, which lets memory be shared and allocated in small pieces.
With paged attention, a sequence's keys live in scattered fixed-size blocks of a shared pool. The attention kernel uses a block table to find token p: block block_table[p // block_size], slot p % block_size.
Write paged_gather(pool, block_tables, seq_lens). pool has shape (num_blocks, block_size, D). block_tables is a list of B lists of physical block ids, and seq_lens is a list of B token counts. Return a float array of shape (B, max(seq_lens), D) holding each sequence's tokens in logical order, with zeros after a sequence's own length. If a sequence's table has too few blocks for its length, raise ValueError. If seq_lens is empty, return an array of shape (0, 0, D).
def paged_gather(pool, block_tables, seq_lens)Example
pool with block_size 2 where block b slot s holds [10 * b + s], tables [[2, 0], [1]], lengths [3, 1] gives [[[20], [21], [0]], [[10], [0], [0]]].
Understand the idea
A block table works like the index at the back of a book. The sequence thinks its tokens are numbered 0, 1, 2, ... but physically they sit in whatever pages were free when it grew. To read token p you first ask which page (p // block_size), then which line on that page (p % block_size). Worked example: block size 2 and table [2, 0]. Token 0 is block 2 slot 0, token 1 is block 2 slot 1, token 2 is block 0 slot 0. Rule: physical = (table[p // bs], p % bs). Gathering into a dense padded buffer is what a reference implementation does to check a paged kernel; fast kernels skip the copy and read the blocks directly. This is the core idea that lets servers pack many requests into GPU memory without large contiguous reservations.
Shapes and data flow
pool (N, bs, D) table[b] list of ids out (B, Lmax, D) out[b, p] = pool[table[b][p // bs], p % bs]