Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Slot | Room in the KV cache for one token’s keys and values. |
allocate_slots | The one function the scheduler calls to get blocks for a request’s next tokens. |
| Lookahead | Extra slots reserved for tokens a speculative-decoding proposer will write this step (18.f). |
| KV connector | An add-on that loads KV from another engine, CPU or disk instead of computing it (19.b). |
| Coordinator | The layer that combines several groups of layers with different cache rules (17.i). |
| Watermark | Blocks kept free when admitting new requests (17.c). |
| Commit | The point where the function actually changes the pool, after every check has passed. |
1. What is it?#
Every time the scheduler wants to give a request some tokens, it makes one call:
kv_cache_manager.allocate_slots(request, num_new_tokens, …). The answer is either the new blocks
or None. Everything about memory admission is decided inside that call: whether a new request’s
whole prompt fits, whether the safety margin is respected, how many blocks a cache hit saved, when
blocks receive their hashes, and so when a “no” turns into a preemption. The scheduler never counts
free blocks itself.
This lesson follows one request through that function (vllm/v1/core/kv_cache_manager.py) from
its first call to its last.
Facts checked on 12 November 2026 against vLLM v0.32.0.
2. Why does it matter?#
If you can predict what allocate_slots will answer, you can predict when your server admits,
queues or preempts. Most surprising memory behaviour in vLLM (a request that waits although “there
is space”, usage that jumps on admission although nothing new is computed, a speculative decoder
that uses more cache) is explained by one line of this function.
3. Simple analogy#
A warehouse clerk who receives “I need shelf space for 100 more boxes”. The clerk first checks everything (does the whole order fit, is the safety margin kept, which shelves can the customer reuse from last time), and only then moves anything. If any check fails, the clerk says no and nothing has moved. Deciding which customer to throw out is not the clerk’s job; that is the manager’s (the scheduler’s).
4. Tiny example#
running request, 300 tokens computed, holds 19 blocks (304 slots), block size 16
step: 1 new token → needs ceil(301/16) = 19 blocks → 0 new blocks, returns []
...4 steps later: token 305 → needs 20 blocks → 1 new block from the free queueFifteen calls out of sixteen return an empty list after a little integer arithmetic.
5. Technical explanation#
Three layers#
| Class | File | Job |
|---|---|---|
KVCacheManager | kv_cache_manager.py | The scheduler’s interface: admission checks, watermark, statistics |
KVCacheCoordinator | kv_cache_coordinator.py | Combines one or more groups of layers (17.i) |
SingleTypeKVCacheManager | single_type_kv_cache_manager.py | One group’s block table per request, and how many blocks a number of tokens needs |
Below them sits the BlockPool (17.e). For an ordinary model there is one group, the coordinator
is the trivial UnitaryKVCacheCoordinator, and the three layers act as one.
The layout the function reasons about#
The docstring draws the token range:
----------------------------------------------------------------------
| < comp > | < new_comp > | < ext_comp > | < new > | < lookahead > |
----------------------------------------------------------------------
| < to be computed > |
----------------------------------------------------------------------
| < to be allocated > |
----------------------------------------------------------------------| Segment | Meaning |
|---|---|
comp | request.num_computed_tokens: already has blocks |
new_comp | A local prefix-cache hit found just now: blocks exist in the pool, not yet in this table |
ext_comp | Tokens whose KV a KV connector will load from outside this engine |
new | The tokens being scheduled this step, including unverified draft tokens |
lookahead | Extra slots a speculative proposer will write this step |
For a plain request with no hit, no connector and no speculative decoding, only comp and new
are non-zero, and the question is: are there enough blocks to hold comp + new tokens?
Stage 0: does the whole thing fit? (new requests only)#
if full_sequence_must_fit:
# First check and fail if the full request sequence won't fit.
full_num_tokens = min(request.num_tokens, self.max_model_len)
num_blocks_to_allocate = self.coordinator.get_num_blocks_to_allocate(
request_id=request.request_id, num_tokens=full_num_tokens, ...,
apply_admission_cap=True, ...
)
required_blocks = num_blocks_to_allocate + watermark_blocks
if required_blocks > self.block_pool.get_num_free_blocks():
return NoneThe scheduler passes full_sequence_must_fit=True only when admitting from the waiting queue
(17.a). The check is on request.num_tokens: the prompt, plus any output a preempted request has
already produced, with cache-hit blocks discounted. Nothing is reserved; it only refuses admission
when the answer is clearly no. For sliding-window layers the count is capped
(apply_admission_cap) because those layers recycle blocks as they go and never hold the whole
prompt at once.
The watermark is added only in a narrow case:
# The watermark is applied to waiting/preempted requests only, and only
# when there's at least one request already scheduled.
if has_scheduled_reqs and request.status in (RequestStatus.WAITING, RequestStatus.PREEMPTED):
watermark_blocks = self.watermark_blocksStage 1: give back what is no longer needed#
# Free the blocks that are skipped during the attention computation
# (e.g., tokens outside the sliding window).
# We can do this even if we cannot schedule this request due to
# insufficient free blocks.
# Should call this function before allocating new blocks to reduce
# the number of evicted blocks.
self.coordinator.remove_skipped_blocks(
request.request_id,
max(0, total_computed_tokens - request.num_in_flight_tokens),
...
)For full attention this does nothing: every past token is needed forever. For layers that look
only at a recent window it returns blocks that have fallen out of view, replacing them in the
table with the null block (17.i). It counts only processed tokens (- num_in_flight_tokens),
because steps still on the GPU may read those blocks (17.d). Doing it before allocating means the
request may cover its own need with memory it just released.
Stage 2: count#
num_tokens_main_model = total_computed_tokens + num_new_tokens
num_tokens_need_slot = min(num_tokens_main_model + num_lookahead_tokens, self.max_model_len)
num_blocks_to_allocate = self.coordinator.get_num_blocks_to_allocate(
request_id=request.request_id, num_tokens=num_tokens_need_slot, ...
)
# Keep `reserved_blocks` free for other in-flight sequences, and an
# additional watermark of headroom for waiting/preempted admissions.
available_blocks = self.block_pool.get_num_free_blocks() - reserved_blocks
required_blocks = num_blocks_to_allocate + watermark_blocks
if required_blocks > available_blocks:
# Cannot allocate new blocks
return Nonereserved_blocks is non-zero only when admitting a request whose KV a connector will load
asynchronously: such a request holds its blocks for the whole transfer without making progress, so
it may not take blocks that in-flight prefills are counting on.
For full attention the count is simple arithmetic
(SingleTypeKVCacheManager.get_num_blocks_to_allocate):
blocks needed = ceil(num_tokens_need_slot / 16)
− blocks already in the request's table
− cache-hit blocks about to be added
+ cache-hit blocks that are currently in the free queueThe last line is subtle, and the source says why: “If a computed block is an eviction candidate (in the free queue and ref_cnt == 0), it will be removed from the free queue when touched by the allocated request, so we must count it in the free-capacity check.” Hit blocks another request is already holding cost nothing. A partial-block hit (17.f) reserves one extra block for its copy-on-write.
A running request takes a fast path: it cannot have new cache hits, so the answer is just
max(blocks_required − blocks_held, 0).
Stage 3: commit#
Only now does anything change. Cache-hit blocks are touched and appended to the table; then new blocks are taken from the front of the free queue:
self.coordinator.allocate_new_computed_blocks(...) # the cache hit: touch()
new_blocks = self.coordinator.allocate_new_blocks(...) # block_pool.get_new_blocks()Check everything, then commit everything: a refused allocation leaves no trace, so there is nothing to roll back.
Stage 4: hashes#
# NOTE(woosuk): We want to commit (cache) up to num_local_computed_tokens
# + num_external_computed_tokens + num_new_tokens, but must exclude
# "non-committable" tokens (e.g., draft tokens that could be rejected).
# Therefore, we cap the number at `request.num_tokens`, ensuring only
# "finalized" tokens are cached.
num_tokens_to_cache = min(total_computed_tokens + num_new_tokens, request.num_tokens)
self.coordinator.cache_blocks(request, num_tokens_to_cache)Every block this step fills completely gets its hash now, at scheduling time. The cap at
request.num_tokens keeps speculative tokens out: a block holding a guessed token that may be
rejected must not be offered to other requests.
One exception: when a connector is loading this request’s KV asynchronously
(delay_cache_blocks=True), hashing waits until the data has actually arrived.
6. Under the hood#
The flow#
flowchart TB
C["<b>allocate_slots(request, num_new_tokens, ...)</b>"] --> F{"new request and<br/>full_sequence_must_fit?"}
F -- "yes" --> G{"blocks for the WHOLE prompt<br/>+ watermark ≤ free?"}
G -- "no" --> NO[":i-ban: return None"]
G -- "yes" --> RM
F -- "no" --> RM["free blocks no longer needed<br/><small>e.g. outside a sliding window</small>"]
RM --> N["blocks needed =<br/>ceil((computed + new + lookahead) / 16) − blocks held"]
N --> A{"needed + watermark ≤<br/>free − reserved?"}
A -- "no" --> NO
A -- "yes" --> T["touch cache-hit blocks<br/><small>ref_cnt + 1, leave the free queue</small>"]
T --> P["pop new blocks from the free queue<br/><small>evicting hashes as needed</small>"]
P --> H["give hashes to blocks that are now full<br/><small>up to request.num_tokens</small>"]
H --> OK[":i-check: return the new blocks"]
class C neutral
class F,G,A queue
class RM,N,T,P,H memory
class NO warn
class OK neutralWhat the worker does with the answer#
The new block IDs travel to the worker in the SchedulerOutput. Before the forward pass it may do
two jobs the scheduler requested:
- Zeroing.
new_block_ids_to_zerolists blocks freshly taken from the pool, whose old contents belong to a finished request. The comment explains: “preventing stale NaN/data from corrupting attention or SSM computation.” In v0.32.0 this is done only when the cache needs it: models with Mamba layers (whose state is read before it is fully written) and mixed-precision caches. Plain attention models skip it, because attention never reads slots that have not been written. - Copy-on-write copies.
kv_cache_block_copieslists(source, destination)pairs for partial-block cache hits (17.f).
None, and what follows#
| Caller | Reaction |
|---|---|
| Pass 1 (a running request) | Preempt a running request and call again (17.c) |
| Pass 2 (a waiting request) | Stop admitting for this step; the request stays at the head of the queue |
The function itself never evicts a request. It evicts cached blocks, implicitly, by popping them from the free queue.
allocate_slots in Go#
For a full-attention model, with the whole-prompt check, the watermark and a lookahead. The trace follows one request: admission with a cache hit, a chunked prefill, then decoding across a block boundary.
package main
import "fmt"
const blockSize = 16
type pool struct {
total, free int
watermark int // blocks kept free when admitting
}
type request struct {
numTokens int // prompt + output known so far
computed int
blocks int // length of the block table
waiting bool
}
func ceilDiv(a, b int) int { return (a + b - 1) / b }
// allocateSlots returns the number of new blocks, or -1 for "None".
// hitBlocksFree: cache-hit blocks that sit in the free queue and will be touched.
func (p *pool) allocateSlots(r *request, newTokens, hitTokens, hitBlocksFree, lookahead int, othersScheduled bool) int {
wm := 0
if r.waiting && othersScheduled {
wm = p.watermark
}
hitBlocks := hitTokens / blockSize
// Stage 0: a new request must fit in full.
if r.waiting {
full := ceilDiv(r.numTokens, blockSize) - hitBlocks + hitBlocksFree
if full+wm > p.free {
return -1
}
}
// Stage 2: blocks for this step.
needSlot := r.computed + hitTokens + newTokens + lookahead
need := ceilDiv(needSlot, blockSize) - r.blocks - hitBlocks + hitBlocksFree
if need < 0 {
need = 0
}
if need+wm > p.free {
return -1
}
// Stage 3: commit.
p.free -= need
r.blocks = ceilDiv(needSlot, blockSize)
r.computed += hitTokens // the hit is adopted; the scheduler advances the rest
r.waiting = false
return need - hitBlocksFree // truly new blocks, excluding touched cache blocks
}
func main() {
p := &pool{total: 100, free: 40, watermark: 5}
r := &request{numTokens: 300, waiting: true}
show := func(what string, got int) {
if got < 0 {
fmt.Printf("%-44s -> None free %2d\n", what, p.free)
return
}
fmt.Printf("%-44s -> %2d new block(s) free %2d table %2d blocks\n",
what, got, p.free, r.blocks)
}
// A 300-token prompt whose first 128 tokens hit the cache. Six of those eight
// blocks are idle in the free queue; two are held by another running request.
fmt.Println("admission: 300-token prompt, 128 tokens cached, budget allows 100 this step")
show(" allocate_slots(new=100, hit=128)", p.allocateSlots(r, 100, 128, 6, 0, true))
r.computed += 100
fmt.Println("\nprefill continues")
show(" allocate_slots(new=72)", p.allocateSlots(r, 72, 0, 0, 0, true))
r.computed += 72
fmt.Println("\ndecoding: one token per step")
for i := 0; i < 6; i++ {
r.numTokens++ // a token was sampled
show(fmt.Sprintf(" token %d: allocate_slots(new=1)", r.numTokens), p.allocateSlots(r, 1, 0, 0, 0, true))
r.computed++
}
fmt.Println("\nthe next step, with a speculative-decoding lookahead of 16 slots")
r.numTokens++
show(" allocate_slots(new=1, lookahead=16)", p.allocateSlots(r, 1, 0, 0, 16, true))
fmt.Println("\na second request arrives: 600 tokens, nothing cached")
r2 := &request{numTokens: 600, waiting: true}
got := p.allocateSlots(r2, 100, 0, 0, 0, true)
fmt.Printf(" needs %d blocks + %d watermark, %d free -> ", ceilDiv(600, blockSize), p.watermark, p.free)
if got < 0 {
fmt.Println("None: stays in the waiting queue")
} else {
fmt.Println("admitted")
}
}Output:
admission: 300-token prompt, 128 tokens cached, budget allows 100 this step
allocate_slots(new=100, hit=128) -> 7 new block(s) free 27 table 15 blocks
prefill continues
allocate_slots(new=72) -> 4 new block(s) free 23 table 19 blocks
decoding: one token per step
token 301: allocate_slots(new=1) -> 0 new block(s) free 23 table 19 blocks
token 302: allocate_slots(new=1) -> 0 new block(s) free 23 table 19 blocks
token 303: allocate_slots(new=1) -> 0 new block(s) free 23 table 19 blocks
token 304: allocate_slots(new=1) -> 0 new block(s) free 23 table 19 blocks
token 305: allocate_slots(new=1) -> 1 new block(s) free 22 table 20 blocks
token 306: allocate_slots(new=1) -> 0 new block(s) free 22 table 20 blocks
the next step, with a speculative-decoding lookahead of 16 slots
allocate_slots(new=1, lookahead=16) -> 1 new block(s) free 21 table 21 blocks
a second request arrives: 600 tokens, nothing cached
needs 38 blocks + 5 watermark, 21 free -> None: stays in the waiting queueHow to read it: the admission step takes 13 blocks from the free count (40 to 27) although only 7 are truly new: six cached blocks left the free queue by being touched. The second prefill chunk needs 4 more. Decoding allocates nothing for several tokens, then one block on crossing a boundary at token 305, and a lookahead makes the request take its next block well before its real tokens reach the boundary.
7. Performance implications#
- The common case is almost free: a decoding request’s call is a few integer operations and returns an empty list.
- A cache hit on idle blocks still consumes “free” capacity, though no new memory is used, so admission can fail on a heavily cached server even when usage looks moderate.
- Lookahead slots are a standing memory cost of speculative decoding with a proposer that writes its own KV (EAGLE, draft models).
- Check-then-commit means a failed call costs only the counting, not any undo work.
8. Production implications#
- Read
vllm:kv_cache_usage_percas “live requests’ share”. It is1 − free / (total − 1), and free includes cached blocks. Near 100% means preemption is close. - A waiting queue with free blocks usually means the head request’s whole prompt does not fit, or the watermark is in force.
- Disaggregated decode servers reserve blocks for in-progress async loads; expect admission to look slightly conservative there.
9. Common mistakes#
- Counting free blocks in your own monitoring and expecting it to predict admission; the whole-prompt check, watermark and reserved blocks all change the answer.
- Assuming a cache hit costs no capacity. Idle hit blocks leave the free queue.
- Expecting draft tokens to be cached. Hashing stops at
request.num_tokens. - Thinking
allocate_slotspreempts. The scheduler does. - Assuming new blocks are zeroed. Only for Mamba or mixed-precision caches.
10. Hands-on exercise#
- Set
watermarkto 0 and rerun. Is the second request admitted? What would happen at the first request’s next block boundary if it were? - Change
hitBlocksFreein the admission call from 6 to 0 (all eight hit blocks held by another running request). How many blocks does admission consume now? - Give the first request a lookahead of 16 on every decode step. How many more blocks does it hold on average?
11. Interview questions#
- Why is
remove_skipped_blockscalled before the allocation rather than after? - A cache hit lands on eight blocks, all idle in the free queue. By how much does the free count drop, and how much new memory is used?
- Why are blocks containing speculative draft tokens not given hashes?
- What does
Nonemean to pass 1, and to pass 2? - Why does a request with an asynchronous KV load reserve blocks for others?
12. Further reading#
Checked on 12 November 2026, against the v0.32.0 tag.
vllm/v1/core/kv_cache_manager.py:allocate_slotsand its docstringvllm/v1/core/kv_cache_coordinator.pyvllm/v1/core/single_type_kv_cache_manager.py:get_num_blocks_to_allocatevllm/v1/core/sched/output.py:new_block_ids_to_zero,kv_cache_block_copiesvllm/v1/kv_cache_interface.py:needs_kv_cache_zeroing