Pidoku

Building the Batch

Module 18 Lesson 18.b 50 min Difficulty 4/5

Prerequisites 18.a, 12.k, 12.l


Before you start: words you need#

WordPlain meaning
Flat batchAll the tokens of all requests in one step laid end to end in a single row, with no padding between requests.
PositionWhere a token sits in its own sequence (0 for the first token). The model’s positional encoding needs it.
Block tableFor each request, the list of physical KV-cache blocks that hold its context, in order (12.l).
SlotOne token’s place in the KV cache: block_id × block_size + offset.
LogitsThe model’s raw score for every vocabulary token at one position.
VectorisedDone as one operation over a whole array instead of a Python loop over items.
Triton kernelA small GPU program written in Python-like Triton (6.e).

1. What is it?#

A textbook batch is a rectangle: batch × sequence_length, with short rows padded. vLLM’s batch is not a rectangle. One step may hold a request computing a single token, another computing 5,000 tokens of its prompt (chunked prefill, 12.k), and a third computing three. Padding them to a common length would waste almost all the work.

Instead the model runner flattens everything into one long row of tokens and builds a few small index tensors. They say which request each token belongs to, what position it has, where in the KV cache its result must be written, and where its context must be read from. The dense layers never notice; only attention needs the indices. Seven tensors describe the whole step.

The code cited is vLLM v0.32.0, where Model Runner V2 builds these tensors on the GPU. Facts checked on 12 November 2026.


2. Why does it exist?#

Most of a transformer treats each token position independently. Embedding lookup, the feed-forward network, normalisation and the final projection are applied row by row. For those layers only the total number of tokens matters; which request a token belongs to is irrelevant.

Attention is the one place where tokens interact, and it interacts only within a request. So the batch can be one flat list, provided attention is told where each request’s rows start and stop. A step with one 5,000-token chunk and 200 single-token decodes is then exactly 5,200 rows of work, with no padding. This is what makes continuous batching (12.j) and chunked prefill cheap at the tensor level.


3. Simple analogy#

A print shop gets jobs of 1 page, 5 pages and 3 pages. It does not pad every job to 5 pages. It prints all 9 pages in one run and keeps a slip saying “pages 1 belong to A, 2–6 to B, 7–9 to C”. The printer (the dense layers) never reads the slip. Only the person binding the booklets (attention) does.


4. Tiny example#

Three requests, block size 4 (vLLM’s usual size is 16, but small numbers are easier to read):

A decoding        1 token at position 10       block table [7 2 12]
B mid-prompt      5 tokens at positions 4..8   block table [3 9 5]
C new             3 tokens at positions 0..2   block table [6]

flat batch        9 tokens: A | B B B B B | C C C
query_start_loc   [0 1 6 9]   request i owns rows [loc[i], loc[i+1])
logits_indices    [0 5 8]     the last row of each request

Request B’s token at position 8 is in its third block (8 / 4 = 2), physical block 5, offset 8 % 4 = 0: slot 5 × 4 + 0 = 20.


5. Technical explanation#

The seven tensors#

For a step with N requests and T scheduled tokens in total:

TensorShapeMeaning
input_ids[T]The token IDs to process, all requests concatenated
positions[T]Each token’s position within its own sequence
query_start_loc[N+1]Request i owns rows query_start_loc[i] to query_start_loc[i+1]
seq_lens[N]Total context length of each request after this step
block_table[N, max_blocks]Each request’s physical block IDs: where to read its context
slot_mapping[T]For each new token, the slot where its key and value are written
logits_indices[N] (longer with speculative decoding)Which rows become next-token distributions

How the older runner computes them, step by step#

The older runner’s _prepare_inputs (vllm/v1/worker/gpu_model_runner.py) explains itself with a worked example in its comments, for num_scheduled_tokens = [2, 5, 3]:

Python
# OPTIMIZATION: Start copying the block table first.
# This way, we can overlap the copy with the following CPU operations.
self.input_batch.block_table.commit_block_table(num_reqs)

# Get request indices.
# E.g., [2, 5, 3] -> [0, 0, 1, 1, 1, 1, 1, 2, 2, 2]
req_indices = np.repeat(self.arange_np[:num_reqs], num_scheduled_tokens)

# cu_num_tokens: [2, 5, 3] -> [2, 7, 10]
# self.query_pos.np[:10]: [0, 1, 0, 1, 2, 3, 4, 0, 1, 2]
cu_num_tokens = self._get_cumsum_and_arange(
    num_scheduled_tokens, self.query_pos.np
)

# Get positions.
positions_np = (
    self.input_batch.num_computed_tokens_cpu[req_indices]
    + self.query_pos.np[: cu_num_tokens[-1]]
)

A token’s position is its request’s num_computed_tokens plus its offset in this step’s chunk. That is all chunked prefill means at the tensor level: the second chunk of a prompt starts at a position other than zero.

Token IDs are gathered from the persistent batch, which stores every request’s tokens as one row of a max_num_reqs × max_model_len array:

Python
# E.g., [0, 1, 0, 1, 2, 3, 4, 0, 1, 2]
# -> [0, 1, M, M + 1, M + 2, M + 3, M + 4, 2 * M, 2 * M + 1, 2 * M + 2]
# where M is the max_model_len.
token_indices = (
    positions_np + req_indices * self.input_batch.token_ids_cpu.shape[1]
)
# NOTE(woosuk): We use torch.index_select instead of np.take here
# because torch.index_select is much faster than np.take for large
# tensors.
torch.index_select(
    self.input_batch.token_ids_cpu_tensor.flatten(), 0, token_indices_tensor,
    out=self.input_ids.cpu[:total_num_scheduled_tokens],
)

One vectorised gather, no Python loop over requests. And the boundaries:

Python
self.query_start_loc.np[0] = 0
self.query_start_loc.np[1 : num_reqs + 1] = cu_num_tokens
# Note: pad query_start_loc to be non-decreasing, as kernels
# like FlashAttention requires that
self.query_start_loc.np[num_reqs + 1 :].fill(cu_num_tokens[-1])

The buffer is sized for the maximum number of requests; the unused tail is filled with the total, so every padding “request” has zero length.

The first line matters too. The block table is the largest tensor of the step, so its copy to the GPU starts first, asynchronously, and runs while the CPU computes the rest.

The same job in Model Runner V2#

MRV2 (GPUModelRunner.prepare_inputs in vllm/v1/worker/gpu/model_runner.py) computes only query_start_loc on the CPU, with one np.cumsum, and copies it asynchronously. Everything else comes from Triton kernels in vllm/v1/worker/gpu/input_batch.py:

Kernel wrapperProduces
prepare_prefill_inputsPrompt token IDs for prefilling requests, read straight from CPU memory through unified virtual addressing (UVA)
prepare_pos_seq_lenspositions and seq_lens
combine_sampled_and_draft_tokensDecode inputs from last step’s sampled and draft tokens, plus logits_indices

The design document gives two reasons:

  1. Better async behavior: GPU can derive values (for example with speculative decoding) that CPU may not know yet.
  2. Lower CPU overhead: input prep is very cheap on GPU and avoids Python bottlenecks.

The first ties to async scheduling (17.d). A decoding request’s input token is the previous step’s sample, which exists only on the GPU when the CPU prepares the next step. Assembling input_ids on the GPU means that value never makes a round trip.

Reading and writing the KV cache#

The KV cache is one large tensor per layer, cut into blocks; a request’s tokens live in blocks anywhere in it (12.l).

Writing. Each token processed this step produces a key and a value in every layer, stored at:

slot = block_table[request][position // block_size] * block_size + position % block_size

slot_mapping holds that number for all T tokens. It is computed by a GPU kernel from positions, query_start_loc and the block table: _COMPUTE_SLOT_MAPPING_KERNEL in vllm/v1/worker/block_table.py for the older runner, _compute_slot_mappings_kernel in vllm/v1/worker/gpu/block_table.py for MRV2. The mapping is never built in Python.

Reading. To attend, the kernel needs the keys and values of all earlier tokens of the same request. It gets the request’s row of block_table and its seq_len, and follows the block IDs (18.c).

The worker’s block table is updated by appending: when the scheduler grants a new block, only that one ID crosses to the worker (17.g).

Only one row per request reaches the vocabulary#

The final projection from hidden state to vocabulary scores is the largest matrix multiply per row: hidden size times 100,000 or more. A next-token distribution is only needed at the last position of each request:

Python
logits_indices = query_start_loc[1:] - 1

Hidden states are indexed with logits_indices before the projection. A step with 5,200 tokens from 201 requests projects 201 rows, not 5,200.

A request whose chunk did not reach the end of its prompt still gets a row, because a fixed shape is cheaper than a branch. The older runner says so: “We will ignore the sampled tokens from the partial requests.” MRV2’s sampler marks such requests as producing no output token. With speculative decoding, each request needs one row per draft token plus one, and logits_indices is longer (18.f).


6. Under the hood#

Multimodal inputs take a different door#

For an image, the prompt holds a run of placeholder tokens and the real input is a tensor of embeddings from a vision encoder. When a chunk overlaps an image’s placeholders, the runner runs the encoder (once; the result stays in an encoder cache), does the ordinary embedding lookup, and then overwrites the embeddings at the placeholder positions. From there the flat batch is processed as usual (18.h).

Padding, after all that#

One kind of padding survives: to the nearest CUDA graph size. A recorded graph works for one exact token count, so a batch of 37 tokens runs as 40 (18.d). Padding rows belong to no request (their query_start_loc range is empty) and their outputs are dropped.

Build all seven tensors#

Go
package main

import "fmt"

const blockSize = 4 // small, so the numbers are readable (vLLM's default is 16)

type request struct {
	name       string
	tokenIDs   []int // prompt + output so far
	computed   int   // num_computed_tokens before this step
	scheduled  int   // tokens the scheduler granted this step
	blockTable []int // physical block IDs, in order
}

func main() {
	// Three requests in one step: num_scheduled_tokens = [1, 5, 3].
	reqs := []request{
		// A is decoding: one token, the one it sampled last step, at position 10.
		{"A", seq(100, 11), 10, 1, []int{7, 2, 12}},
		// B is in the middle of its prompt: 5 tokens at positions 4..8.
		{"B", seq(200, 20), 4, 5, []int{3, 9, 5}},
		// C is new: its first 3 tokens.
		{"C", seq(300, 3), 0, 3, []int{6}},
	}

	var reqIndices, positions, inputIDs, slotMapping, seqLens []int
	queryStartLoc := []int{0}

	for i, r := range reqs {
		for q := 0; q < r.scheduled; q++ {
			pos := r.computed + q
			reqIndices = append(reqIndices, i)
			positions = append(positions, pos)
			inputIDs = append(inputIDs, r.tokenIDs[pos])
			// The token at logical position pos lives in physical slot:
			//   block_table[pos / block_size] * block_size + pos % block_size
			slot := r.blockTable[pos/blockSize]*blockSize + pos%blockSize
			slotMapping = append(slotMapping, slot)
		}
		queryStartLoc = append(queryStartLoc, len(positions))
		seqLens = append(seqLens, r.computed+r.scheduled)
	}

	// One row of logits is needed per request: its LAST scheduled token.
	var logitsIndices []int
	for i := range reqs {
		logitsIndices = append(logitsIndices, queryStartLoc[i+1]-1)
	}

	fmt.Println("flat batch of", len(inputIDs), "tokens from", len(reqs), "requests")
	fmt.Println()
	fmt.Println("req_indices     ", reqIndices)
	fmt.Println("positions       ", positions)
	fmt.Println("input_ids       ", inputIDs)
	fmt.Println("slot_mapping    ", slotMapping, "  <- where each new K/V is WRITTEN")
	fmt.Println()
	fmt.Println("query_start_loc ", queryStartLoc, "  <- request i owns rows [loc[i], loc[i+1])")
	fmt.Println("seq_lens        ", seqLens, "  <- how much context each request attends over")
	fmt.Println("logits_indices  ", logitsIndices, "  <- rows that get a next-token distribution")
	fmt.Println()
	fmt.Println("block_table (one row per request; where its context is READ from):")
	for _, r := range reqs {
		fmt.Printf("  %s %v\n", r.name, r.blockTable)
	}

	fmt.Println()
	for i, r := range reqs {
		kind := "prefill chunk: sampled token is discarded"
		if r.computed+r.scheduled == len(r.tokenIDs) {
			kind = "caught up: a token is sampled from row " + fmt.Sprint(logitsIndices[i])
		}
		fmt.Printf("  %s computed %d + scheduled %d of %d known tokens -> %s\n",
			r.name, r.computed, r.scheduled, len(r.tokenIDs), kind)
	}
}

func seq(base, n int) []int {
	out := make([]int, n)
	for i := range out {
		out[i] = base + i
	}
	return out
}

Output:

flat batch of 9 tokens from 3 requests

req_indices      [0 1 1 1 1 1 2 2 2]
positions        [10 4 5 6 7 8 0 1 2]
input_ids        [110 204 205 206 207 208 300 301 302]
slot_mapping     [50 36 37 38 39 20 24 25 26]   <- where each new K/V is WRITTEN

query_start_loc  [0 1 6 9]   <- request i owns rows [loc[i], loc[i+1])
seq_lens         [11 9 3]   <- how much context each request attends over
logits_indices   [0 5 8]   <- rows that get a next-token distribution

block_table (one row per request; where its context is READ from):
  A [7 2 12]
  B [3 9 5]
  C [6]

  A computed 10 + scheduled 1 of 11 known tokens -> caught up: a token is sampled from row 0
  B computed 4 + scheduled 5 of 20 known tokens -> prefill chunk: sampled token is discarded
  C computed 0 + scheduled 3 of 3 known tokens -> caught up: a token is sampled from row 8

B’s tokens at positions 4 to 7 sit in block 9 (slots 36 to 39) and position 8 in block 5 (slot 20). Two adjacent tokens of the same request are nineteen slots apart, and nothing in the model cares.


7. Performance implications#

  • No padding between requests means the dense layers do exactly T rows of work. GPU time per step follows total scheduled tokens, which is why the token budget (17.b) is the main scheduling knob.
  • The vocabulary projection is applied to N rows, not T. For long prefill chunks this saves most of the cost of the largest matrix multiply.
  • Input preparation on the GPU (MRV2) turns Python work proportional to T into a few kernel launches. On the older runner it is NumPy work on the CPU, partly hidden by async scheduling.
  • CUDA graph padding adds a few rows to small batches; above a few dozen tokens it is a few percent at most (18.d).

8. Production implications#

  • max_num_batched_tokens sizes these buffers. All seven tensors are pre-allocated for the maximum, and the value is part of the compilation cache key (18.d). Changing it means a new compile.
  • prompt_logprobs defeats the last-row trick. It needs a distribution at every prompt position, so the projection runs over far more rows (18.e).
  • Long prompts are cheap to batch with decodes. Thanks to flattening, mixing a large prefill chunk with hundreds of decodes costs no padding; the trade-off is decode latency during that step (12.k).
  • Debugging wrong output. If only long or chunked prompts go wrong, suspect positions or slot mapping in a custom model or backend: they are the two indices most often computed wrongly.

9. Common mistakes#

  1. Assuming position equals row index. A token’s position is num_computed_tokens + offset in chunk; row 0 of the flat batch can be position 10,000.
  2. Confusing slot_mapping with block_table. One says where new K/V are written, the other where old K/V are read.
  3. Projecting every row to the vocabulary in a custom model, instead of selecting logits_indices first.
  4. Treating the partial request’s sampled token as output. It is discarded until the prompt is finished.
  5. Expecting query_start_loc to have N+1 meaningful entries in the buffer. The tail is padded with the total so kernels see non-decreasing values.

10. Hands-on exercise#

  1. Add a fourth request that is new, with a 9-token prompt and block table [1, 4, 8]. Predict its slot_mapping before running.
  2. Change blockSize to 16 and give request B the block table [3]. Which of the seven tensors change, and which do not?
  3. In the v0.32.0 source, find where the older runner computes logits_indices for speculative decoding (spec_decode_metadata.logits_indices). How long is it for 3 requests with 2 drafts each?
  4. Read prepare_pos_seq_lens in vllm/v1/worker/gpu/input_batch.py. What does each Triton program instance compute?

11. Interview questions#

  1. Why does flattening the batch not confuse the feed-forward layers?
  2. A token is at position 37 of a request whose block table is [12, 4, 30] with block size 16. Which slot holds its key and value?
  3. Why is the vocabulary projection applied to only one row per request, and when is that not true?
  4. Why does Model Runner V2 build input_ids on the GPU rather than the CPU?
  5. What is the only padding a vLLM batch still has, and why?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in