19. Batching and slots
Why this layer exists
Chapter 17’s Engine serves one request at a time. It holds a lock from a request’s first token to its last, and that chapter’s exercise (e) measured the consequence: a second request sent alongside the first gets its first content delta only once the first has finished. An agent daemon does not send one request at a time. Subagents run side by side (chapter 45), tool results arrive together and each wants a model call, and several clients share one model behind chapter 22’s router. Serving them in turn wastes the machine as well as their time. Chapter 14 showed that a decoding step is bound by reading the weights, every weight for one token, and that one read can serve many sequences at once.
llama-server’s answer is slots (-np), each holding one sequence’s state, and continuous batching (-cb), which runs every busy slot’s next token through the model in one forward pass and lets requests join and leave between passes. This chapter builds both for tinygpt, with what they cost: memory per slot, fixed in advance; a queue for requests that find every slot taken; and a server that has to say “not now” in a way a client can act on. What llama-server does at each joint is stated as of llama.cpp da89bb3 (2026-09-29); captures from the fleet name the build that produced them.
Mechanism
Arithmetic per byte
Take one weight matrix of shape (d_in, d_out) and a batch of rows, shape (B, d_in). The product , shape (B, d_out), has entries, each a dot product of length , which chapter 3 counts as multiply-adds, FLOPs. So
With bytes per number, the product reads once, bytes, reads , bytes, and writes , bytes:
Their ratio is the arithmetic done per byte moved. Dividing the numerator and the denominator by ,
While is small beside both widths, the second factor is close to 1 and : each extra row adds FLOPs per byte, because it adds work without adding weight bytes. For the lab model’s (512, 2048) feed-forward matrix in float64, , a script gives , and , against the limit’s 0.25, 2 and 16; at 64 rows the activations begin to count.
A whole model with weights does the same at each step: FLOPs, and bytes of weights plus each sequence’s cache, bytes for sequence (the activations are small beside both):
If every sequence’s cache has the same size , this is , which grows like while is small beside and levels off at as grows. Batching amortises the weights, not the caches, since each sequence reads its own. Chapter 3 promised this ratio: “That ratio, arithmetic per byte of weight read, is what chapter 19’s batching improves.”
A machine that computes at most FLOP/s and moves at most bytes/s needs at least seconds for a step and at least seconds, and both have to happen. With caches small beside the weights,
The first term does not depend on and the second grows with it. They are equal where ; dividing both sides by and solving for ,
chapter 14’s crossover, which it reached from the throughput bound ; that bound is for this , so the two are one statement. Below a step costs the same whatever is, so throughput grows in proportion to ; above it the step is compute-bound and throughput stops growing. In terms of : the step is memory-bound while , the machine’s own FLOPs per byte, and reaches exactly at . That picture, with as the ridge between the two regimes, is Williams, Waterman and Patterson’s roofline model.
Now the measurement. Part 1 of the lab’s script (in the Lab section) builds a model with vocabulary 512, context 128, width 512, 8 heads, 4 layers and RoPE: 13,128,704 parameters, of which the 12,866,560 outside the embedding table are read at every step, 102.9 MB in float64. It decodes one token for each of slots that hold 8 positions each and times the step, the median of 12. Each figure below is the median of three runs of the script, on two machines: talos, an Intel i3-1315U laptop, and straylight, an AMD Ryzen AI Max+ 395 running the script at nice 19 beside its llama.cpp services, both with OPENBLAS_NUM_THREADS=1 (one core) and numpy 2.5.3.
| slots | talos ms/step | talos tokens/s | straylight ms/step | straylight tokens/s | FLOP per weight byte |
|---|---|---|---|---|---|
| 1 | 4.38 | 228 | 3.43 | 291 | 0.25 |
| 2 | 9.77 | 205 | 6.50 | 308 | 0.50 |
| 4 | 10.58 | 378 | 7.62 | 525 | 1.00 |
| 8 | 12.63 | 633 | 9.67 | 827 | 2.00 |
| 16 | 19.44 | 823 | 16.11 | 993 | 4.00 |
| 32 | 31.00 | 1,032 | 26.03 | 1,229 | 8.00 |
| 64 | 56.27 | 1,137 | 47.39 | 1,350 | 16.00 |
To place these against the roofline, exercise (a)’s script measures with a 2048 × 2048 float64 product and with a copy of 512 MiB, counting the bytes read and written: talos 62.50 GFLOP/s and 28.33 GB/s, straylight 118.29 GFLOP/s and 56.50 GB/s. So on talos and on straylight. The memory-bound ceiling, tokens/s per slot, is 275 on talos and 549 on straylight; the compute-bound ceiling is 2,429 and 4,597.
Three things in the table need explaining.
At one slot, talos reaches 228 tokens/s, 0.83 of its memory ceiling: reading 102.9 MB at 28.33 GB/s takes 3.63 ms of the 4.38. This is chapter 14’s memory-bound step. Straylight reaches 291, 0.53 of its ceiling; its memory is twice as fast, so the step’s fixed costs (Python, and the small operations between the products) are a larger share of a shorter step.
The step time rises from one slot to two: 4.38 to 9.77 ms on talos, 3.43 to 6.50 on straylight, so two slots produce fewer tokens per second than one on talos and barely more on straylight. The bare product (B, 512) @ (512, 2048) shows the cause (exercise (a)’s script times it): 140.4 µs at one row and 528.6 µs at two on talos, 77.2 and 229.2 µs on straylight, then nearly flat up to eight rows. With one row numpy calls the BLAS matrix-vector kernel, which streams through the matrix once. From two rows it calls the matrix-matrix kernel, which first copies blocks of the matrix into a packed layout for its inner loop, a cost that pays off only when enough rows reuse each packed block. (The one-row product reads its 8 MiB matrix at 59.75 GB/s on talos, faster than the copy’s , because a product repeated on one matrix finds it in the processor’s 10 MiB last-level cache. The model’s 102.9 MB never fits.)
From eight slots on, the curve bends near , which is between 8 and 9 on both machines, where the products approach the compute roof. The bend is where the roofline puts it, but the times are not the roofline’s: at 8 slots a step takes 12.63 ms on talos, 3.5 times its bound of ms, and 9.67 ms on straylight, 5.3 times ms. From 8 slots to 64, eight times the slots, throughput grows 1.8 times on talos and 1.6 times on straylight. But it stays well below the compute ceiling: at 64 slots talos reaches 0.47 of and straylight 0.29. Timing the step’s weight products alone (each layer’s query, key, value, projection, up and down matrices, and the head, on (B, 512) inputs) splits the step. In a separate run on talos at 64 slots, the products took 31.44 ms of a 51.43 ms step; at they would need 26.31 ms, so they ran at 84% of the machine’s peak, and the other 19.99 ms was attention, normalisation and Python. On straylight the products took 19.84 ms of 47.35 (70% of its peak) and the rest 27.51 ms. The rest grows by about 0.3 ms per slot on talos and 0.4 ms on straylight, because forward_batch runs attention in a Python loop over slots, for a reason the next sections give. So this toy is compute-bound in its matrix products at high , as the roofline says, and a growing share of each step is per-slot Python that a production engine runs as one attention kernel over every slot. (The split’s step times differ from the table’s by up to a tenth: separate runs, on laptops and a shared machine.)
Slots and their memory
A slot is one sequence’s state for the life of its request. For a transformer that state is its KV cache, chapter 12’s bytes for positions: keys and values (the 2), for each of layers, numbers per position (all heads together, ), bytes each. SlotCache allocates it once, for a capacity of positions per slot: k and v, each of shape (L, slots, H, C, d_head), so
chapter 12’s formula at for each slot. test_cache_is_allocated_once builds a cache with , 3 slots, , and in float64, bytes, three slots of , and checks that a forward pass leaves the array’s address and size unchanged. For the lab model (, , ) a slot is 4 MiB, and 16 slots are 64 MiB beside 102.9 MB of weights.
Why allocate once? Chapter 12’s KVCache.append concatenates, which copies the whole cache at every step: a sequence of positions copies on the order of numbers over its life, and each request grows one array per layer. A preallocated slot writes each position once, in place, and freeing it is setting its length to 0; nothing is copied or allocated while serving. It also makes memory a decision taken at startup. Slots times positions is known before the first request, so admission is a matter of counting free slots, and no generation can run out of memory halfway. The cost is waste: a request that ends at positions uses of its slot, and a slot sized for the longest request holds mostly zeros for a typical one.
llama-server offers both layouts. Without --kv-unified each slot gets -c divided by the number of slots, as chapter 12 described, which is SlotCache’s layout. With it, all slots draw positions from one buffer of -c, so a long request can use what short ones leave, and the slots together can never exceed it: each slot’s n_ctx_seq is the whole n_ctx when unified and n_ctx / n_seq_max otherwise (src/llama-context.cpp:291-295). --kv-unified is the default when the slot count is automatic, and automatic, -np -1, means 4 slots (tools/server/server.cpp:156-161). Kwon and colleagues’ PagedAttention (2023) attacks the waste differently: the cache is allocated in fixed-size blocks of positions, as an operating system allocates memory in pages, and each sequence keeps a table from its logical blocks to physical ones. A sequence then holds only the blocks it has filled, at most one of them partly empty, and sequences with a common prefix can share its blocks. It needs an attention kernel that reads keys and values through the table; this chapter describes it and does not build it.
Ragged batches
A step runs different amounts of work for different slots. A request just admitted needs its whole prompt run, many positions; one that is decoding needs one. forward_batch takes them together as one ragged batch of rows: row is token ids[j] of slot slots[j], a slot’s rows appear in order, and they go to that slot’s next positions, lengths[slot], lengths[slot] + 1, and so on. Positions are per slot and absolute, so a learned position table or RoPE treats each row by its own sequence’s position, not by its index in the batch.
Why does sharing a pass leave every row’s result unchanged? Follow a row through a layer. The embedding lookup reads one row of the table. Layer norm normalises each row over its own features. A matrix product acts row by row: row of is row of times , whatever the other rows hold. GELU acts element by element. A mixture-of-experts layer routes each row by its own router scores and sums that row’s experts’ outputs. So everywhere but attention, row ’s output is a function of row ’s input and the shared weights alone. Attention is where positions meet, and forward_batch restricts it: a row of slot at position attends over slot ’s keys and values at positions to (written by earlier steps, and for a prompt by earlier rows of this step) and over nothing of any other slot. That is what chapter 12’s forward_cached computes for the same sequence alone. By induction over the layers, every row’s logits are its sequence’s single-sequence logits. test_each_slot_matches_forward_cached checks it for learned positions, RoPE and MoE, with three sequences of different prompt lengths, one joining two steps late: each slot’s logits equal forward_cached on that sequence to within .
Why a tolerance and not equality? The functions are the same; the arithmetic is not. BLAS splits a product into blocks that depend on the number of rows, so a row’s dot products are summed in a different order in a batch of 7 rows than in a batch of 1, and floating-point addition is not associative. The two paths’ logits agree to about , not bit for bit. llama.cpp’s README says the same of its server: the logits “are not guaranteed to be bit-for-bit identical for different batch sizes” (tools/server/README.md, under cache_prompt).
The union of experts
For a mixture-of-experts layer, “every weight matrix multiplies all rows at once” needs care, because each row uses only its own top experts. moe_union computes each chosen expert once, over all the rows that chose it, so a step reads the union of its rows’ experts. Chapter 14 derived the expected size of that union when each of tokens picks of experts uniformly and independently: . Part 3 of the lab’s script counts the distinct experts forward_batch reports per layer (its stats argument) for a random model with and (the script prints as k, the model’s top_k), over 20 batches of random tokens per size and two layers each. On talos:
3. experts read per MoE layer by a batch of B tokens (E = 16, k = 2), against E(1 - (1 - k/E)^B)
B 1: measured 2.00, uniform routing 2.00
B 2: measured 3.77, uniform routing 3.75
B 4: measured 6.47, uniform routing 6.62
B 8: measured 10.68, uniform routing 10.50
B 16: measured 13.82, uniform routing 14.11
B 32: measured 15.68, uniform routing 15.78
The measured counts are within 0.3 of the formula at every size; the largest gap is at 16 tokens, 13.82 against 14.11. The router’s weights are random, so each token’s choice is fixed by the token but spread evenly over tokens, close to the uniform case the formula assumes. (Straylight’s three runs printed the same lines.) At 32 tokens a step reads 15.68 of the 16 experts, nearly all of them: chapter 14’s point that a large batch of decoding steps on a mixture-of-experts model reads nearly as many weight bytes as a dense model of its total size.
Continuous batching
Static batching takes requests, runs them together until the longest has finished, and only then takes the next . A request of tokens occupies its slot for of the steps the batch runs, so the fraction of slot-steps that produce a token is
For three requests of 5, 50 and 500 tokens, : the first two slots stand empty for 495 and 450 of the 500 steps, while requests may be waiting.
Iteration-level scheduling (Orca, Yu and colleagues, 2022) decides at every step instead: a request that finishes leaves at the end of its step, and a waiting request takes the slot at the next one. BatchEngine.step is that loop. Under the lock, it finishes requests whose clients have gone and admits waiting requests to free slots. Outside the lock, it runs one forward_batch over every active slot, a new request’s whole prompt and one token for each of the others. Under the lock again, it samples each slot’s next token, hands it to that request’s stream, and frees the slots of requests that are done. The figure shows the slot cache and eight such steps.
A long prompt admitted into a step makes that step long for every slot in it. llama-server bounds this: each pass first selects the generating slots (tools/server/server-context.cpp:2962-2975) and adds each one’s last sampled token to the batch (:3077-3080, through handle_last_sampled_token, :474-485), then fills the rest of the batch with pending prompt tokens up to n_batch (:3089-3096, :3505), so a long prompt is spread over several passes while the other slots keep decoding. forward_batch runs a whole prompt at once, which is simpler, and for a context of 128 positions costs little.
Each request samples from its own row’s logits with its own generator, mask and sampling settings, and gets its own stream, so batching changes nothing a request can observe except its timing: it receives the tokens and logprobs it would receive alone. test_continuous_batching_changes_nothing_a_request_sees sends four requests that arrive one per step and share two slots, and compares each with chapter 17’s stream_generate run on that request alone: the same tokens, and logprobs within . It decodes greedily because the two paths’ logits differ in the last bits: a sampled draw compares a uniform number with cumulative probabilities, so a last-bit difference could move a boundary across it, where an argmax changes only at an exact tie.
What BatchEngine gives up is chapter 17’s prompt cache. Engine kept the last request’s keys and values and reran only the new suffix; BatchEngine resets a slot when its request ends, so an agent resending its conversation pays for the whole prompt at every turn. llama-server keeps each slot’s cache after its request ends, sends a new request to the slot whose cached prompt matches it best (--slot-prompt-similarity, default 0.10), and can save idle slots’ caches to RAM for later (--cache-ram, --cache-idle-slots; all three in tools/server/README.md). Chapter 29 turns prefix stability into a budget the harness manages.
Recurrent and hybrid slots
A recurrent layer’s slot holds a fixed-size state instead of a growing cache: chapter 15’s SSM keeps a (D, N) array per layer per sequence whatever the length. SSMSlots holds state, one (slots, D, N) array per layer, and a step takes one token for each of some distinct slots: it gathers their rows of state, runs chapter 15’s step, and writes the new rows back. test_ssm_slots_match_single_sequences_and_do_not_grow runs sequences of 9, 4 and 12 tokens through three slots, compares each slot with chapter 15’s single-sequence step, and checks the size before and after, bytes for 2 layers, 3 slots, and in float64. A slot takes one token per step, since the recurrence consumes a sequence’s tokens one after another, and SSMSlots.step refuses a repeated slot. (Chapter 15’s scan could run a prompt’s tokens in one call; the lab steps through them.)
A hybrid model’s slot holds both. Ornith, chapter 14’s model, keeps a KV cache in its 10 full-attention layers, 20,480 bytes per position in f16, and about 62.8 MiB of recurrent state per sequence in its 30 Gated DeltaNet layers (chapter 15 derives both from llama.cpp’s sizes at da89bb3). Per slot, computed by a script:
| positions | KV cache | state | slot | state’s share |
|---|---|---|---|---|
| 4,096 | 80.0 MiB | 62.8 MiB | 142.8 MiB | 44% |
| 32,768 | 640.0 MiB | 62.8 MiB | 702.8 MiB | 9% |
At 4,096 positions the fixed state is almost half of a slot. At 32,768 the cache dominates again, but it has grown at a quarter of the rate of an all-attention model with the same heads, whose cache there would be 2,560 MiB.
What a state cannot do is roll back. Chapter 12’s KVCache.truncate(n) forgets the positions from on, and the cache is then exactly what it was after positions, because every position’s keys and values are stored separately. A recurrent state has folded every token into one array, and the state after positions is gone once the next token is consumed. Speculative decoding (chapter 14) discards rejected draft tokens and prompt-prefix reuse restarts from a shared prefix, so both need a copy of an earlier state: a snapshot. llama.cpp’s recurrent memory has one state cell per sequence, created with as many cells as n_seq_max, the slot count (src/llama-model.cpp:2614-2623). Each cell’s rows are allocated times over (n_rows = mem_size * (1 + n_rs_seq), src/llama-memory-recurrent.cpp:101), one extra row per token of rollback; seq_rm rolls back by at most n_rs_seq tokens and refuses more (:193-204), and n_rs_seq is set from the speculative-decoding settings (common/common.cpp:1635). A batch that names a sequence beyond the cells fails with “Try using a bigger --parallel value” (llama-memory-recurrent.cpp:536). For prefix reuse, llama-server saves whole states as context checkpoints, up to 32 per slot by default (--ctx-checkpoints, tools/server/README.md).
Queueing and backpressure
Slots bound how many requests run at once; something has to happen to the rest. Three averages over a long time describe any system that requests enter and leave: the arrival rate (requests per second), the mean time a request spends in the system , and the mean number in the system .
Little’s law, . Let be the number of requests in the system at time , and take an interval that starts and ends with the system empty, in which requests arrive, request at time , and leave, request at time . A request is counted exactly while it is present, so . Integrate both sides over . The integral of the indicator is the length of the interval where it is 1, , request ’s time in the system:
This is the area under counted two ways, by moments and by requests. Divide by and split the right side into a product:
The left side is the time-average number in the system, ; is the arrival rate ; the last factor is the mean time in the system, . Over an interval that does not start and end empty, the requests present at its ends add a boundary term; in a stable system it grows more slowly than , so it vanishes after dividing by , and the law holds for long-run averages (Little’s 1961 proof covers the general case). It assumes nothing about how arrivals or service times are distributed, which is why it can check the lab’s measurements below.
Apply it to the slots alone. Each admitted request occupies a slot for its service time, of mean , so the mean number of busy slots is , and with slots the fraction busy, the utilisation, is
A steady state needs . At , requests arrive at least as fast as busy slots can finish them.
How long is the queue below that? The simplest model that answers is one slot, , with requests arriving at random (a Poisson process of rate ) and exponential service times of mean , so that completions come at rate while the slot is busy: the M/M/1 queue. Let be the long-run fraction of time with requests in the system. The system goes from to by an arrival and back by a completion, one request at a time, so over a long run it crosses the boundary between and upward and downward equally often, give or take one. Upward crossings happen at rate during the fraction of time spent at , downward ones at rate during the fraction , so
with . The fractions sum to 1: for , so and . The mean number in the system is with . Subtracting from term by term leaves , so and
by Little’s law and . At a request spends in the system, at it spends , and at , . The wait is not proportional to the load; it is proportional to , and it explodes as the load nears capacity. More slots and other distributions change the constants in front of , and Kleinrock’s first volume works through them.
At there is no steady state: the number waiting grows at the rate , and the wait with it. An unbounded queue under overload means unbounded latency. Every client has a timeout, and once the queue’s wait passes it, clients give up on requests the server will still run: the server spends its capacity on answers nobody reads, and every client sees failure anyway. A bounded queue keeps the wait bounded (exercise (d)) and refuses the excess at once, while the client can still do something about it.
The refusal. HTTP has two candidate status codes. 429 Too Many Requests (RFC 6585 §4) “indicates that the user has sent too many requests in a given amount of time (“rate limiting”)”: it is about one client’s behaviour. 503 Service Unavailable (RFC 9110 §15.6.4) “indicates that the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay”, and a full queue is exactly that: the server’s capacity, whoever is asking. BatchEngine.stream raises a 503 with type unavailable_error and a Retry-After header, which RFC 9110 §10.2.3 defines as telling a client “how long the user agent ought to wait before making a follow-up request”, here as a whole number of seconds.
The estimate: a request refused with requests queued ahead of it (beyond those the free slots will take) would have been admitted at the th departure from the slots. busy slots finish requests at an average rate of , so departures take about seconds, and the header carries
at least 1. For exponential service times this is the exact expectation: an exponential time’s remainder is exponential with the same mean however long it has already run, so at every moment the time to the next of departures is exponential with mean , and such waits add. For other distributions, the requests in service at the moment of refusal are not typical ones: a long request holds its slot longer, so a moment chosen at random is more likely to fall inside a long request, and when request lengths are heavy-tailed, as an agent’s are (a one-line answer and a long file rewrite share a server), the time to the first departures exceeds and the estimate is too short. Exercise (e) computes by how much. The engine learns as a running mean of service times, from admission to finish, leaving out requests cancelled part-way, whose cut-short times would bias it low, with weight 0.1 per request and a starting value of 1 second; test_retry_after_learns_service_times_not_queueing checks on a fake clock that time spent queued is not counted, since the formula adds the queue itself.
llama-server does not refuse. A request that finds no free slot is deferred (tools/server/server-context.cpp:2385-2389) into a deque with no bound (tools/server/server-queue.cpp:76-82), and the server exports the count as the llamacpp:requests_deferred metric (tools/server/README.md). Nothing on the server bounds the wait. The handler waits for its first result in one-second waits on a condition variable that every waiting handler shares (server-queue.cpp:450-473, with HTTP_POLLING_SECONDS, server-context.cpp:39). It checks whether its client is still connected only when a full second passes with no result for any of them (:552-557). On a busy server, where every streamed token is a result, that never happens, so a deferred request waits for a slot whether or not its client is still there (chapter 23, exercise (e)). --timeout, 3,600 seconds by default and 7,200 in the dixie preset read in the Lab, sets the socket’s read and write timeouts (tools/server/server-http.cpp:215-217), which govern reading the request and writing the response. Its GET /slots?fail_on_no_slot=1 answers 503 when no slot is free, but that is a probe a client may choose to make, not admission control. In the course’s stack the refusal travels unchanged to the one who can act on it: chapter 23’s Go proxy passes the 503 and its Retry-After through to the client unchanged, and the retry belongs to chapter 24’s client. Chapter 45’s subagents meet the same backpressure from the other side: a fan-out wider than the slots is queued or refused.
Cancellation
A client that goes away must give its slot back. stream returns a _Stream, an iterator over the request’s queue of results; closing it, or dropping the last reference to it (which in CPython finalises it at once), marks the request cancelled, and the next step finishes it and resets its slot. Chapter 17’s Engine could rely on a generator’s finally, but that runs only in a generator that has started, and chapter 17’s chat_chunks sends its role chunk before it reads the engine’s stream: a client gone at that moment leaves the stream unstarted. test_a_client_that_leaves_after_the_first_chunk_frees_its_slot drives exactly that path, and test_an_abandoned_stream_frees_its_slot the mid-stream one. A request cancelled while still queued stops counting against the queue at once (test_a_cancelled_queued_request_does_not_hold_a_queue_place) and is skipped when it reaches the front; one cancelled in service does not count towards (test_a_cancelled_request_does_not_count_as_a_service_time). Carrying a cancel across a proxy to the upstream server is chapter 23’s lab.
The curve
Part 2 of the lab’s script is a closed loop: 16 client threads, each sending 3 requests one after another (an 8-token prompt and 48 new tokens at temperature 1, the next request only when the last has finished), against a BatchEngine with 1 to 16 slots. It reports generated tokens per second over the wall time ( tokens; the prompts are run but not counted, where part 1 counted only decoding steps), the median and 95th percentile of request latency, the median time to the first token, and the scheduler’s step count. Each cell is the median of three runs. The last column, from Little’s law, is explained below.
On talos:
| slots | tokens/s | latency p50 | latency p95 | first token p50 | steps | / tokens/s |
|---|---|---|---|---|---|---|
| 1 | 194 | 3.80 s | 4.19 s | 3.56 s | 2,304 | 3.96 s |
| 2 | 183 | 4.13 s | 4.29 s | 3.63 s | 1,153 | 4.20 s |
| 4 | 333 | 2.28 s | 2.37 s | 1.73 s | 577 | 2.31 s |
| 8 | 501 | 1.47 s | 1.64 s | 0.78 s | 289 | 1.53 s |
| 16 | 663 | 1.16 s | 1.18 s | 0.10 s | 145 | 1.16 s |
On straylight:
| slots | tokens/s | latency p50 | latency p95 | first token p50 | steps | / tokens/s |
|---|---|---|---|---|---|---|
| 1 | 265 | 2.89 s | 2.92 s | 2.72 s | 2,304 | 2.90 s |
| 2 | 279 | 2.75 s | 2.80 s | 2.42 s | 1,153 | 2.75 s |
| 4 | 476 | 1.59 s | 1.62 s | 1.21 s | 577 | 1.61 s |
| 8 | 687 | 1.11 s | 1.14 s | 0.59 s | 289 | 1.12 s |
| 16 | 832 | 0.94 s | 0.94 s | 0.08 s | 146 | 0.92 s |
Little’s law ties the columns together. In a closed loop of 16 clients each with one request outstanding, at all times, and requests arrive as fast as they complete, = tokens/s divided by 48. So divided by tokens/s, and that column agrees with the measured median latency to within 0.16 s on talos and 0.02 s on straylight (the law is about the mean, and the wall time includes the loop’s start and end). Throughput and latency here are one measurement, not two.
Throughput rises with slots, from 194 to 663 tokens/s on talos and from 265 to 832 on straylight, because each step serves more requests for a step time that grows more slowly than the slot count (part 1). With fixed at 16, latency falls as throughput rises. The time to first token falls fastest, from 3.56 s to 0.10 s on talos: with one slot a request waits behind everything queued before it, and with 16 slots every request is admitted at the next step and gets its first token from the step that runs its prompt. The step counts show the scheduling: with one slot, 2,304 steps of one token; with 16, 145 to 147 across runs, each client’s three requests of 48 tokens back to back, 144 steps, plus one to three where a client’s next request arrived just after a step began. Two slots are no faster than one on talos (183 against 194 tokens/s) and a little faster on straylight (279 against 265), the matrix-kernel switch of part 1. And the scheduler’s throughput stays below the bare step’s at every slot count, 663 against part 1’s 823 tokens/s at 16 on talos: its steps also run the prompts, and each step does per-request Python work (sampling, a softmax over the vocabulary per request, queue operations), with 16 client threads competing with the scheduler for the interpreter’s lock. The two machines give the same shape with different constants; neither table is a prediction for the other, and the numbers vary from run to run by up to a tenth.
Walkthrough
The module is py/tinygpt/batch.py, and the server gains --slots and --queue. The cache first.
class SlotCache:
"""Keys and values for n_slots sequences, allocated once: k and v are (L, slots, H, capacity,
d_head) and lengths[s] is how many positions slot s holds. Freeing a slot is setting its length
to 0; nothing is copied or reallocated while serving."""
def __init__(self, cfg, n_slots, capacity=None):
H, dh = cfg.n_heads, cfg.d_model // cfg.n_heads
self.capacity = capacity or cfg.context
self.k = np.zeros((cfg.n_layers, n_slots, H, self.capacity, dh))
self.v = np.zeros_like(self.k)
self.lengths = np.zeros(n_slots, dtype=np.int64)
def reset(self, slot):
self.lengths[slot] = 0
@property
def nbytes(self):
return self.k.nbytes + self.v.nbytes
capacity defaults to the model’s context, so a slot can hold any sequence the model can. lengths is the only state that changes when a request comes or goes: reset sets it to 0 and leaves the old keys and values in place, since attention never reads past a slot’s length.
def moe_union(moe, h):
"""Chapter 11's MoE over the (N, d) rows of a whole batch, computing each expert once for all the
rows that chose it: the step reads the union of the experts its tokens select (chapter 14).
Returns (out (N, d), number of distinct experts read)."""
z = h @ moe.router.weight.data # (N, E)
top = np.argsort(-z, axis=-1, kind="stable")[:, :moe.top_k] # (N, k)
zk = np.take_along_axis(z, top, axis=-1)
g = np.exp(zk - zk.max(axis=-1, keepdims=True))
g /= g.sum(axis=-1, keepdims=True) # (N, k) gates
out = np.zeros_like(h)
union = np.unique(top)
for e in union: # one read of expert e's weights
rows, slot = np.nonzero(top == e) # the rows that chose e, and where
u = gelu_np(h[rows] @ moe.up.data[e] + moe.up_bias.data[e])
out[rows] += g[rows, slot][:, None] * (u @ moe.down.data[e] + moe.down_bias.data[e])
return out, len(union)
The routing is chapter 12’s _moe line for line: router scores (N, E), the top by a stable sort, and a softmax over the chosen scores as gates (N, k). The difference is the loop. _moe loops over rows and runs each row’s experts; moe_union loops over np.unique(top), the experts chosen by any row. For each, np.nonzero(top == e) returns the rows that chose it and, for each such row, which of its choices it was, so g[rows, slot] picks the matching gate. One expert’s two matrices then multiply all of its rows at once: one read of that expert’s weights per step. test_moe_union_computes_each_chosen_expert_once compares the output with _moe and the count with the distinct experts of the same routing, and checks that a single token reads exactly .
def forward_batch(model, cache, slots, ids, stats=None):
"""Logits (N, V) for a ragged batch: token j is ids[j], the next token of slot slots[j]. A slot's
tokens appear in order (several for a prompt, one for a decoding step) and go to positions
lengths[slot], lengths[slot] + 1, ...; the cache is extended in place.
Every weight matrix multiplies all N rows at once, one read of the weights per step; attention
reads each slot's own keys and values. stats, a list, receives the distinct experts per MoE layer.
"""
cfg, H = model.cfg, model.cfg.n_heads
slots, ids = np.asarray(slots, dtype=np.int64), np.asarray(ids, dtype=np.int64)
N = len(ids)
if not all(blk.attn.causal for blk in model.blocks):
raise ValueError("forward_batch needs causal attention; a bidirectional model has no KV cache")
if len(slots) != N or N and (slots.min() < 0 or slots.max() >= len(cache.lengths)):
raise ValueError(f"each of the {N} ids needs a slot in [0, {len(cache.lengths)})")
groups = {s: np.flatnonzero(slots == s) for s in dict.fromkeys(slots.tolist())} # slot -> its rows
pos = np.empty(N, dtype=np.int64)
for s, rows in groups.items():
pos[rows] = cache.lengths[s] + np.arange(len(rows))
if N and (pos.max() >= min(cfg.context, cache.capacity) or ids.min() < 0 or ids.max() >= cfg.vocab_size):
raise ValueError("a slot would pass the context or capacity, or a token id is out of range")
x = model.tok.data[ids] # (N, d)
if model.pos is not None:
x = x + model.pos.data[pos]
for i, blk in enumerate(model.blocks):
a, h = blk.attn, layer_norm_np(x, blk.ln1)
q, k, v = (h @ lin.weight.data for lin in (a.query, a.key, a.value))
q, k, v = (t.reshape(N, H, -1).transpose(1, 0, 2) for t in (q, k, v)) # (H, N, d_head)
if a.rope:
q, k = _rope(q, pos), _rope(k, pos)
cache.k[i, slots, :, pos, :] = k.transpose(1, 0, 2) # (N, H, d_head) into each slot's rows
cache.v[i, slots, :, pos, :] = v.transpose(1, 0, 2)
y = np.empty((H, N, q.shape[-1]))
for s, rows in groups.items(): # attention: per slot, over its own cache
S = pos[rows[-1]] + 1
ks, vs = cache.k[i, s, :, :S], cache.v[i, s, :, :S] # (H, S, d_head)
scores = q[:, rows] @ ks.transpose(0, 2, 1) / np.sqrt(q.shape[-1])
scores = scores + np.where(np.arange(S)[None, :] > pos[rows][:, None], -np.inf, 0.0)
w = np.exp(scores - scores.max(axis=-1, keepdims=True))
y[:, rows] = (w / w.sum(axis=-1, keepdims=True)) @ vs
x = x + y.transpose(1, 0, 2).reshape(N, -1) @ a.proj.weight.data + a.proj.bias.data
h = layer_norm_np(x, blk.ln2)
if blk.moe is not None:
out, read = moe_union(blk.moe, h)
x = x + out
if stats is not None:
stats.append(read)
else:
x = x + gelu_np(h @ blk.up.weight.data + blk.up.bias.data) @ blk.down.weight.data + blk.down.bias.data
for s, rows in groups.items():
cache.lengths[s] += len(rows)
return layer_norm_np(x, model.ln_f) @ model.head.weight.data # (N, V)
Every check comes before the first write: attention must be causal, as chapter 12’s forward_cached requires; every row needs a slot inside the cache, because a negative index would silently wrap to the last slot in numpy; and every position must stay below both the context and the capacity, and every id inside the vocabulary. test_forward_batch_refuses_bad_slots_and_ids checks that a refused batch leaves every length at 0. groups maps each slot to its rows in order of first appearance, and pos gives each row its absolute position. The weight products (h @ lin.weight.data, the projection, the feed-forward or MoE layer, the head) each run once over all rows. The cache write cache.k[i, slots, :, pos, :] = … uses two index arrays separated by a slice; numpy then puts the indexed dimension first, so the target has shape (N, H, d_head) and the keys, (H, N, d_head), are transposed to match. Attention runs per slot: S is one past the slot’s last row’s position, ks and vs are its (H, S, d_head) keys and values, and the mask hides, for each row, the positions after its own; scores are (H, rows, S). Lengths advance only after every layer has run. test_a_freed_slot_starts_clean fills a slot, resets it, and checks that a new sequence there matches a fresh forward_cached, stale keys in the array notwithstanding.
class SSMSlots:
"""Chapter 15's SSM language model with n_slots sequences: each slot holds one (D, N) state per
layer, whatever its length. A step takes one token for each of some distinct slots."""
def __init__(self, model, n_slots):
self.model = model
self.state = [np.zeros((n_slots, model.cfg.d_model, model.cfg.d_state)) for _ in model.blocks]
self.lengths = np.zeros(n_slots, dtype=np.int64)
def reset(self, slot):
for h in self.state:
h[slot] = 0.0
self.lengths[slot] = 0
def step(self, slots, ids):
slots = np.asarray(slots, dtype=np.int64)
if len(set(slots.tolist())) != len(slots) or len(slots) and (slots.min() < 0 or
slots.max() >= len(self.lengths)):
raise ValueError(f"a recurrent step takes one token for each of some distinct slots in "
f"[0, {len(self.lengths)})")
logits, new = self.model.step(ids, [h[slots] for h in self.state])
for h, n in zip(self.state, new):
h[slots] = n
self.lengths[slots] += 1
return logits
@property
def nbytes(self):
return sum(h.nbytes for h in self.state)
h[slots] with an index array gathers a copy of the chosen rows, chapter 15’s step returns new arrays without touching its input, and h[slots] = n scatters them back. The check refuses a repeated slot, whose two new states would both be written to the same row, and a slot outside the arrays.
class _Job:
"""One request in the engine: its prompt, its sampling, and a queue its stream reads from."""
def __init__(self, ids, max_new, rng, stop_ids, mask, top_logprobs, sampling):
self.ids, self.max_new, self.rng, self.stop_ids = list(ids), max_new, rng, tuple(stop_ids)
self.mask, self.top_logprobs, self.sampling = mask, top_logprobs, sampling
self.out, self.slot, self.cancelled = [], None, False
self.results = queue.Queue()
self.start = None # when it takes a slot: its service starts
class _Stream:
"""The Steps of one job, read from its results queue. close(), or dropping the stream, marks the
job cancelled whether or not it was ever read, and the scheduler frees its slot at the next step."""
def __init__(self, job):
self.job, self.done = job, False
def __iter__(self):
return self
def __next__(self):
item = None if self.done else self.job.results.get()
if item is None or isinstance(item, Exception):
self.done = True
if item is not None:
raise item
raise StopIteration
return item
def close(self):
self.job.cancelled, self.done = True, True # a finished job is no longer scheduled: harmless
def __del__(self):
self.close()
class BatchEngine:
"""Continuous batching over n_slots slots, with chapter 17's stream() interface.
A scheduler thread runs steps. Each step admits waiting requests into free slots, runs one
forward_batch over every active slot (a new request's whole prompt, one token for the others),
samples each slot's next token and frees the slots whose requests finished. A request that finds
every slot taken waits in a queue of at most max_queue; past that, stream() raises 503 with a
Retry-After estimated from the mean service time.
"""
def __init__(self, model, tok, name="tinygpt", n_slots=4, max_queue=16, start=True):
if n_slots < 1 or max_queue < 0:
raise ValueError(f"an engine needs n_slots >= 1 and max_queue >= 0, not {n_slots} and {max_queue}")
self.model, self.tok, self.name, self.context = model, tok, name, model.cfg.context
self.n_slots, self.max_queue = n_slots, max_queue
self.cache = SlotCache(model.cfg, n_slots)
self.free, self.active, self.waiting = list(range(n_slots)), {}, collections.deque()
self.mean_seconds = 1.0 # running mean of service times, for Retry-After
self.steps = 0
self.cond = threading.Condition()
self.running = start
if start:
self.thread = threading.Thread(target=self._loop, daemon=True)
self.thread.start()
def stream(self, ids, max_new, rng, stop_ids=(), mask=None, top_logprobs=0, **sampling):
ids, V = [int(t) for t in ids], self.model.cfg.vocab_size
if not ids or min(ids) < 0 or max(ids) >= V:
raise ValueError(f"a prompt is one or more token ids in [0, {V})")
if max_new < 1 or len(ids) + max_new > self.context + 1:
raise ValueError(f"max_new must be at least 1 and prompt {len(ids)} + max_new {max_new} "
f"within context {self.context} + 1")
job = _Job(ids, max_new, rng, stop_ids, mask, top_logprobs, sampling)
with self.cond:
queued = sum(not j.cancelled for j in self.waiting)
ahead = queued - len(self.free) # queued requests that must wait for a departure
if ahead >= self.max_queue:
wait = math.ceil((ahead + 1) * self.mean_seconds / self.n_slots)
raise OpenAIError(503, f"all {self.n_slots} slots are taken and {ahead} requests are queued",
type="unavailable_error", headers={"Retry-After": max(1, wait)})
self.waiting.append(job)
self.cond.notify()
return _Stream(job)
def _finish(self, job, error=None):
if error is not None:
job.results.put(error)
job.results.put(None)
if job.slot is not None:
self.cache.reset(job.slot)
self.free.append(job.slot)
del self.active[job.slot]
if job.start is not None and not job.cancelled: # a whole service, queueing excluded
self.mean_seconds += 0.1 * (time.monotonic() - job.start - self.mean_seconds)
def step(self):
"""One scheduler iteration; returns the number of tokens it ran through the model."""
with self.cond:
for job in [j for j in self.active.values() if j.cancelled]:
self._finish(job)
while self.free and self.waiting:
job = self.waiting.popleft()
if job.cancelled:
continue
job.slot, job.start = self.free.pop(0), time.monotonic()
self.active[job.slot] = job
jobs = list(self.active.values())
if not jobs:
return 0
slots, ids, last = [], [], []
for job in jobs:
new = job.ids if not job.out else job.out[-1:] # the prompt once, then one token
slots += [job.slot] * len(new)
ids += new
last.append(len(ids) - 1) # the row that predicts its next token
try:
logits = forward_batch(self.model, self.cache, slots, ids)
except Exception as e: # fail this step's requests, keep serving
with self.cond:
for job in jobs:
self._finish(job, e)
return 0
self.steps += 1
with self.cond:
for job, row in zip(jobs, last):
try:
z = logits[row]
extra = job.mask(job.out) if job.mask is not None else None
tok = sample_token(z if extra is None else z + extra, job.rng, history=job.ids + job.out,
**job.sampling)
except Exception as e: # e.g. no token left: that request fails
self._finish(job, e)
continue
lp = log_softmax(z)
top = np.argsort(-lp, kind="stable")[:job.top_logprobs] if job.top_logprobs else ()
job.out.append(tok)
job.results.put(Step(tok, float(lp[tok]), tuple((int(t), float(lp[t])) for t in top)))
if tok in job.stop_ids or len(job.out) >= job.max_new or len(job.ids) + len(job.out) > self.context:
self._finish(job)
return len(ids)
def _loop(self):
while self.running:
with self.cond:
while self.running and not self.active and not self.waiting:
self.cond.wait()
if self.running:
self.step()
def close(self):
with self.cond:
self.running = False
self.cond.notify()
_Job is a request’s whole life: its prompt and sampling, the tokens generated so far, its slot, when its service began, and the queue its results go to. _Stream reads that queue; a result is a Step, an exception to raise, or None for the end. stream validates the prompt first, so that a bad request (an empty or out-of-range prompt, or a max_new below 1, which would let a prompt one position too long past the context check) fails alone, as chapter 17’s engine fails it, rather than failing every request that shares its step (test_a_bad_request_is_refused_before_it_joins_a_batch). Admission is one comparison: ahead counts the queued requests still wanted (a cancelled one no longer holds a place) that the free slots will not take, so a burst of requests that arrives before the scheduler wakes is counted against the queue too (test_a_burst_cannot_pass_the_queue), and the refusal carries the Mechanism’s estimate. step has the three phases described there. last records, for each request, the row whose logits predict its next token: its prompt’s last row, or its one row. An exception from forward_batch fails the requests of that step and the engine keeps serving; an exception while sampling fails that request alone (test_an_error_in_one_request_leaves_the_others_running gives one request a mask that leaves no token). The stopping rules are stream_generate’s: a stop id, max_new tokens, or the context. The scheduler thread and the HTTP handler threads meet only at cond: stream appends under it and notifies, and _loop sleeps on it when there is nothing to do.
In py/tinygpt/server.py, load_engine(run_dir, name, slots=0, max_queue=16) returns chapter 17’s Engine when slots is 0 and a BatchEngine otherwise, and main passes --slots and --queue to it. Nothing else in the server changes, because BatchEngine has Engine’s interface: chat_chunks calls stream and iterates, and the 503 arrives as an OpenAIError from the first chunk, before any header is sent, where the handler already turns such errors into responses with their headers.
Exercises
(a) Measure your machine’s (a large float64 matrix product) and (a large array copy), compute for the lab model, and compare it with where part 1’s curve bends.
Answer
A script that times the product and the copy, and the bare (B, 512) @ (512, 2048) product the Mechanism used, as its docstring says to run it:
"""Chapter 19: the bare matrix product behind a decoding step, and this machine's F and R. Run from py/:
OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python machine.py
"""
import time
import numpy as np
def median_seconds(f, n):
ts = []
for _ in range(n):
t = time.perf_counter()
f()
ts.append(time.perf_counter() - t)
return float(np.median(ts))
import pathlib
import socket
cpu = next((line.split(":", 1)[1].strip() for line in pathlib.Path("/proc/cpuinfo").read_text().splitlines()
if line.startswith("model name")), "?") if pathlib.Path("/proc/cpuinfo").exists() else "?"
print("host", socket.gethostname(), "cpu", cpu, "numpy", np.__version__)
rng = np.random.default_rng(0)
W = rng.normal(size=(512, 2048))
print("(B, 512) @ (512, 2048) in float64, median of 300")
for B in [1, 2, 3, 4, 8, 16, 32, 64]:
x = rng.normal(size=(B, 512))
s = median_seconds(lambda: x @ W, 300)
print(f"B {B:3d}: {1e6 * s:8.1f} us {2 * B * 512 * 2048 / s / 1e9:6.2f} GFLOP/s "
f"{W.nbytes / s / 1e9:6.2f} GB/s of weights")
n = 2048
A, C = rng.normal(size=(n, n)), rng.normal(size=(n, n))
F = 2 * n ** 3 / median_seconds(lambda: A @ C, 5)
a = np.ones(1 << 26) # 512 MiB of float64
out = np.empty_like(a)
R = 2 * a.nbytes / median_seconds(lambda: np.copyto(out, a), 5) # bytes read plus bytes written
print(f"F {F / 1e9:.2f} GFLOP/s (a {n} x {n} float64 product), R {R / 1e9:.2f} GB/s (a 512 MiB copy, read + write)")
print(f"B* = F b / (2 R) with b = 8: {F * 8 / (2 * R):.2f}")
On straylight:
host straylight cpu AMD RYZEN AI MAX+ 395 w/ Radeon 8060S numpy 2.5.3
(B, 512) @ (512, 2048) in float64, median of 300
B 1: 77.2 us 27.17 GFLOP/s 108.66 GB/s of weights
B 2: 229.2 us 18.30 GFLOP/s 36.60 GB/s of weights
B 3: 298.5 us 21.08 GFLOP/s 28.10 GB/s of weights
B 4: 260.7 us 32.17 GFLOP/s 32.17 GB/s of weights
B 8: 310.8 us 53.97 GFLOP/s 26.99 GB/s of weights
B 16: 461.0 us 72.79 GFLOP/s 18.20 GB/s of weights
B 32: 720.1 us 93.19 GFLOP/s 11.65 GB/s of weights
B 64: 1285.6 us 104.40 GFLOP/s 6.52 GB/s of weights
F 118.29 GFLOP/s (a 2048 x 2048 float64 product), R 56.50 GB/s (a 512 MiB copy, read + write)
B* = F b / (2 R) with b = 8: 8.37
On talos the same script gave = 62.50 GFLOP/s, = 28.33 GB/s and . Against part 1’s medians: tokens per second rise 2.8 times from 1 slot to 8 on talos (228 to 633) and 1.8 times from 8 to 64 (633 to 1,137); on straylight 2.8 and 1.6 times (291 to 827 to 1,350). The bend falls near , between 8 and 16 slots, on both machines, though the times there are several times the roofline’s bound. The curve is not the roofline’s straight line and flat ceiling, for the reasons the Mechanism gave: below the matrix-matrix kernel’s packing makes 2 slots cost more than 1, and above it the per-slot Python keeps throughput well under .
Two cautions about the measurement itself. A copy’s bandwidth is not the bandwidth of reading alone, and a product repeated on one matrix may be served from cache, as the one-row product is here (its 108.66 GB/s on straylight is well above ); the roofline’s is for data that does not fit in cache, which the model’s 102.9 MB of weights does not. And from a 2048 × 2048 product is what the BLAS reaches on large, square, cache-friendly blocks: it is the best case for the compute term.
(b) Six requests of 5, 50, 500, 5, 50 and 500 tokens arrive together at a server with three slots. How many steps does static batching take, in batches of three in arrival order, and how many does continuous batching take? What are the utilisations and the mean completion steps?
Answer
Static: the first batch, 5, 50 and 500, runs 500 steps; the second, the same lengths, another 500. 1,000 steps, and , the same as for one batch because the second batch is a copy of the first. The requests finish at steps 5, 50, 500, 505, 550 and 1,000, a mean of 435.
Continuous: each request takes the first slot to free. Slot 0 runs the first 5-token request to step 5, then the fourth to step 10, then the fifth, 50 tokens, to step 60. Slot 1 runs the second request to step 50, then the sixth, 500 tokens, to step 550. Slot 2 runs the third to step 500. All six are done at step 550, and . They finish at 5, 50, 500, 10, 60 and 550, a mean of 195.8. (A script checked both schedules.)
The 5-token request that arrived fourth finishes at step 10 instead of 505: continuous batching helps short requests most, because static batching makes every request in a batch wait for the batch’s longest. It does not help the last long request, which finishes at 550 in this arrival order; with the two long requests first, both would finish at 500 and the short ones would follow in the third slot, all done by 500. Scheduling order is a policy question the engine answers first come, first served.
(c) How much memory does one ornith slot need at 32,768 positions, and how many such slots fit beside its 18.8 GiB of Q4_0 weights on a machine with 32 GiB for the model?
Answer
From the Mechanism’s table, a slot at 32,768 positions is 640.0 MiB of cache and 62.8 MiB of state, 702.8 MiB. The room beside the weights is GiB, 13,516.8 MiB, and , so 19 slots, before counting anything else: llama.cpp also allocates compute buffers for the forward pass, and the operating system and other processes need memory too, so the practical number is lower.
A unified cache changes the question. Price a pool of 131,072 positions, the size of the dixie preset in the Lab (which serves a different model), for this model at that preset’s q8_0 cache type: chapter 12’s 34 bytes per 32 numbers make a position bytes, and the pool bytes, 1,360 MiB, shared by the slots whatever their requests’ lengths. The state is per slot in either layout, so 8 slots add MiB, 1,862.4 MiB in all, and every slot added costs 62.8 MiB before it holds a single position.
(d) Bound the queue: a single slot and at most requests in the system, so an arrival that finds is refused. Derive and the fraction refused, and evaluate the refused fraction and the mean time in the system of admitted requests for (one running, 16 queued) at and at . Why is this kinder than an unbounded queue?
Answer
The boundary argument of the Mechanism holds for every , since arrivals still move the system from to below , and at they are refused and move nothing. So for , now a finite sum: , and
which needs no condition on (for , every ). Poisson arrivals see the time averages, so the fraction of arrivals refused is . Admitted requests arrive at rate , and Little’s law over them gives with . A script, in units of :
rho 0.9: refused 0.0196, L 5.82, W 6.60 S
rho 1.5: refused 0.3336, L 15.01, W 15.02 S
At the bound refuses 2% of requests and holds the mean time in the system to , where the unbounded queue’s is with a tail that is longer still. At the unbounded queue has no steady state at all: its wait grows without limit and every client eventually times out. The bounded one refuses a third, which is close to the excess, , since the slot can serve only of what is offered, and serves the rest in a bounded . The refused third learn it at once and can go elsewhere or come back later; the served two thirds are answered, rather than everyone waiting until they give up.
(e) Suppose nine requests in ten take seconds and one in ten takes . With one slot and requests queued, what is the expected wait until the refused request would have been admitted, and how does Retry-After’s estimate compare?
Answer
The mean service time is , and the estimate is . The true wait is the remaining time of the request in service, then full services. The queued requests are ordinary draws, each on average. The one in service is not. At a random moment, the request in service is one of length with probability proportional to how often lengths of occur times how long each one lasts, ; normalising, the length found in service has density and mean , and a random moment falls on average halfway through it, so the expected remainder is
Here , so the remainder is , against for a typical request. The expected wait is . For the estimate says and the truth is , 51% more; for , 25% more; for , 10%; for , 3% (a script). The error is one term, the remainder’s excess, so it matters most when the queue is short. For exponential service, and the remainder is exactly , which is why the estimate is exact there; for constant service the remainder is and the estimate is too long. A client that retries exactly at Retry-After under heavy-tailed load will often be refused again.
(f) Run the server with --slots 2 --queue 1, send eight concurrent requests from threads, and count the 503s and their Retry-After values. Then make the clients honour Retry-After and count again.
Answer
With the server from the Lab running as PYTHONPATH=. uv run python -m tinygpt.server /tmp/tinygpt-chat --slots 2 --queue 1, this script sends eight requests through a barrier, so they leave together, first taking a 503 as final and then retrying after Retry-After, up to five attempts:
"""Eight requests at once against the chapter 19 server on 127.0.0.1:8017 (--slots 2 --queue 1):
first taking a 503 as final, then honouring Retry-After."""
import json
import threading
import time
import urllib.error
import urllib.request
URL = "http://127.0.0.1:8017/v1/chat/completions"
BODY = json.dumps({"messages": [{"role": "user", "content": "what is a queen ?"}], "temperature": 0}).encode()
def send():
"""(status, Retry-After or None, the reply's content or None)."""
req = urllib.request.Request(URL, BODY, {"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=20) as r:
return r.status, None, json.loads(r.read())["choices"][0]["message"]["content"]
except urllib.error.HTTPError as e:
return e.code, e.headers.get("Retry-After"), None
def burst(client, n=8):
results, gate = [None] * n, threading.Barrier(n)
def run(i):
gate.wait() # all eight send at the same moment
results[i] = client()
threads = [threading.Thread(target=run, args=(i,)) for i in range(n)]
for t in threads:
t.start()
for t in threads:
t.join()
return results
def patient():
"""Retry after the server's Retry-After, up to five times."""
tries = 0
while True:
status, after, content = send()
tries += 1
if status != 503 or tries == 5:
return status, tries, content
time.sleep(int(after))
t0 = time.perf_counter()
first = burst(send)
print("taking a 503 as final:", [s for s, _, _ in first], "Retry-After:", [a for _, a, _ in first if a])
time.sleep(2)
t0 = time.perf_counter()
second = burst(patient)
print("honouring Retry-After:", [s for s, _, _ in second], "attempts:", [n for _, n, _ in second],
f"{time.perf_counter() - t0:.2f}s")
print("a reply:", repr(next(c for _, _, c in second if c)))
Three runs on talos:
taking a 503 as final: [200, 200, 503, 503, 503, 503, 200, 503] Retry-After: ['1', '1', '1', '1', '1']
honouring Retry-After: [200, 200, 200, 200, 200, 200, 200, 200] attempts: [1, 2, 2, 3, 2, 3, 1, 1] 2.01s
a reply: 'i cannot look that up .'
taking a 503 as final: [503, 200, 503, 503, 200, 200, 503, 503] Retry-After: ['1', '1', '1', '1', '1']
honouring Retry-After: [200, 200, 200, 200, 200, 200, 200, 200] attempts: [3, 2, 3, 2, 1, 1, 2, 1] 2.01s
a reply: 'i cannot look that up .'
taking a 503 as final: [503, 200, 503, 200, 200, 503, 503, 503] Retry-After: ['1', '1', '1', '1', '1']
honouring Retry-After: [200, 200, 200, 200, 200, 200, 200, 200] attempts: [2, 2, 3, 1, 2, 3, 1, 1] 2.01s
a reply: 'i cannot look that up .'
On talos, three requests were admitted each time, two into the slots and one into the queue, and five refused, each with Retry-After: 1. On straylight and dixie (2026-10-01), one run in three admitted four or five. Which requests win, and on another machine how many, varies with thread scheduling; every refusal carried Retry-After: 1 and every retry succeeded. The value is 1 for two reasons in turn. At the first refusal after the server starts, few requests have finished and the engine’s is still near its starting value of 1 second, so the estimate is . As requests finish in milliseconds, the running mean decays towards their service time, the estimate falls below a second, and the header’s floor of one whole second applies. Honouring it, all eight succeed, in 2.01 s: three at once, three after one second, the last two after two. The retries come in waves because every refused client waited the same second and came back together, when again only three could be admitted. A client that adds a random delay to Retry-After spreads its retries out instead of arriving in waves; chapter 24’s client is where that policy lives.
Lab
Implement the stubs in py/labs/ch19/starter.py: SlotCache, moe_union, forward_batch, SSMSlots and BatchEngine.step. The engine’s plumbing is provided: _Job, _Stream, and BatchEngine’s constructor, stream with its admission control and 503, _finish, the scheduler thread and close. Run
make lab CH=19 IMPL=mine
until it passes; against the reference it takes about 1.2 seconds on talos. The acceptance tests are test_each_slot_matches_forward_cached[moe] and test_continuous_batching_changes_nothing_a_request_sees.
Then measure what batching buys. Save as /tmp/batch_lab.py:
"""Chapter 19 lab: what batching buys, measured. Run from py/:
OPENBLAS_NUM_THREADS=1 PYTHONPATH=. uv run python /tmp/batch_lab.py
"""
import threading
import time
import numpy as np
from tinygpt.batch import BatchEngine, SlotCache, forward_batch
from tinygpt.bpe import BPE
from tinygpt.chat import ChatTokenizer
from tinygpt.serve import SERVE_SPECIALS
from tinygpt.transformer import GPT, GPTConfig
cfg = GPTConfig(vocab_size=512, context=128, d_model=512, n_heads=8, n_layers=4, pos="rope")
model = GPT(cfg, np.random.default_rng(0))
params = sum(p.data.size for p in model.parameters())
weight_bytes = sum(p.data.nbytes for p in model.parameters()) - model.tok.data.nbytes
print(f"model: {params:,} parameters, {weight_bytes / 1e6:.1f} MB of weights read per step (float64)")
print("\n1. one decoding step for B slots (8 cached positions each)")
print(" B ms/step tokens/s FLOP/weight byte")
for B in [1, 2, 4, 8, 16, 32, 64]:
cache = SlotCache(cfg, B)
rng = np.random.default_rng(1)
forward_batch(model, cache, np.repeat(np.arange(B), 8), rng.integers(0, 512, 8 * B)) # prefill
times = []
for _ in range(12):
ids = rng.integers(0, 512, B)
t = time.perf_counter()
forward_batch(model, cache, np.arange(B), ids)
times.append(time.perf_counter() - t)
cache.lengths[:] = 8 # decode the same position again
ms = 1000 * np.median(times)
print(f"{B:4d} {ms:8.2f} {B / ms * 1000:9.0f} {2 * B * (params - model.tok.data.size) / weight_bytes:8.2f}")
print("\n2. continuous batching: 16 clients, 3 requests each, prompt 8, 48 new tokens")
tok = ChatTokenizer(BPE([]), SERVE_SPECIALS)
for n_slots in [1, 2, 4, 8, 16]:
engine = BatchEngine(model, tok, n_slots=n_slots, max_queue=64)
lat, ttft, lock = [], [], threading.Lock()
def client(i):
rng = np.random.default_rng(i)
for _ in range(3):
t = time.perf_counter()
first = None
for _step in engine.stream(list(rng.integers(0, 256, 8)), 48, rng, temperature=1.0):
first = first or time.perf_counter() - t
with lock:
lat.append(time.perf_counter() - t)
ttft.append(first)
start = time.perf_counter()
threads = [threading.Thread(target=client, args=(i,)) for i in range(16)]
for t in threads:
t.start()
for t in threads:
t.join()
wall = time.perf_counter() - start
engine.close()
print(f"slots {n_slots:2d}: {16 * 3 * 48 / wall:6.0f} tokens/s, latency p50 {np.median(lat):5.2f}s "
f"p95 {np.percentile(lat, 95):5.2f}s, first token p50 {np.median(ttft):5.2f}s, {engine.steps} steps")
print("\n3. experts read per MoE layer by a batch of B tokens (E = 16, k = 2), against E(1 - (1 - k/E)^B)")
moe_cfg = GPTConfig(vocab_size=512, context=128, d_model=64, n_heads=4, n_layers=2, pos="rope", n_experts=16, top_k=2)
moe_model = GPT(moe_cfg, np.random.default_rng(3))
for B in [1, 2, 4, 8, 16, 32]:
reads = []
for trial in range(20):
stats = []
ids = np.random.default_rng(trial).integers(0, 512, B)
forward_batch(moe_model, SlotCache(moe_cfg, B), np.arange(B), ids, stats)
reads += stats
expected = 16 * (1 - (1 - 2 / 16) ** B)
print(f"B {B:3d}: measured {np.mean(reads):5.2f}, uniform routing {expected:5.2f}")
and run it from py/ as its docstring says. It takes under a minute on talos. The Mechanism’s tables are the medians of three runs on talos and three on straylight; one of the talos runs, in full:
model: 13,128,704 parameters, 102.9 MB of weights read per step (float64)
1. one decoding step for B slots (8 cached positions each)
B ms/step tokens/s FLOP/weight byte
1 4.38 228 0.25
2 9.77 205 0.50
4 10.58 378 1.00
8 12.67 632 2.00
16 19.44 823 4.00
32 31.00 1032 8.00
64 56.62 1130 16.00
2. continuous batching: 16 clients, 3 requests each, prompt 8, 48 new tokens
slots 1: 194 tokens/s, latency p50 3.82s p95 4.25s, first token p50 3.60s, 2304 steps
slots 2: 182 tokens/s, latency p50 4.13s p95 4.48s, first token p50 3.63s, 1152 steps
slots 4: 333 tokens/s, latency p50 2.28s p95 2.37s, first token p50 1.74s, 576 steps
slots 8: 500 tokens/s, latency p50 1.48s p95 1.71s, first token p50 0.78s, 289 steps
slots 16: 669 tokens/s, latency p50 1.15s p95 1.16s, first token p50 0.10s, 146 steps
3. experts read per MoE layer by a batch of B tokens (E = 16, k = 2), against E(1 - (1 - k/E)^B)
B 1: measured 2.00, uniform routing 2.00
B 2: measured 3.77, uniform routing 3.75
B 4: measured 6.47, uniform routing 6.62
B 8: measured 10.68, uniform routing 10.50
B 16: measured 13.82, uniform routing 14.11
B 32: measured 15.68, uniform routing 15.78
The straylight runs went through tools/remote/straylight.sh, which copies the working tree to straylight and runs a command in the repository’s dev shell at nice 19, never touching the llama.cpp services there: with the script copied into the tree as py/.scratch-ch19/batch_lab.py (untracked, and deleted afterwards), AEC_REMOTE=straylight tools/remote/straylight.sh ch19-curve -- bash py/.scratch-ch19/run.sh, where run.sh changes into py and runs the script as above. Run it on a second machine you have; expect the same shape and different constants.
Then serve chapter 17’s model with slots. From py/, with the model from chapter 17’s lab in /tmp/tinygpt-chat:
PYTHONPATH=. uv run python -m tinygpt.server /tmp/tinygpt-chat --slots 4
It prints serving /tmp/tinygpt-chat at http://127.0.0.1:8017/v1, as before. Run chapter 17’s /tmp/openai_lab.py from two terminals at once: both conversations complete, and neither waits for the other’s whole generation, where chapter 17’s engine made the second wait on its lock. Exercise (f) pushes the same server past its queue.
Now the fleet, read-only. The routers autoload, so the script below reads GET /v1/models first, refuses unless the model’s status is loaded, and asks for /slots with autoload=false, so that the router answers 400 rather than load anything. Save as /tmp/slots_probe.py:
"""Read-only: the slots of a model a fleet router already has loaded, and the router's own limits.
python3 /tmp/slots_probe.py HOST MODEL e.g. dixie ornith-1.5-9b-uncensored
Never loads a model: it reads /v1/models first, refuses unless the model's status is "loaded", and
sends ?autoload=false so the router answers 400 rather than load anything."""
import json
import sys
import time
import urllib.request
host, model = sys.argv[1], sys.argv[2]
base = f"http://{host}:11434"
def get(path):
with urllib.request.urlopen(base + path, timeout=10) as r:
return json.loads(r.read())
props = get("/props")
print("date", time.strftime("%Y-%m-%d %H:%M %Z"), "host", host, "build", props["build_info"],
"max_instances", props["max_instances"], "autoload", props["models_autoload"])
status = {m["id"]: (m.get("status") or {}).get("value") for m in get("/v1/models")["data"]}
if status.get(model) != "loaded":
raise SystemExit(f"{model} is {status.get(model)!r} on {host}, not loaded; nothing sent")
slots = get(f"/slots?model={model}&autoload=false")
print(model, len(slots), "slots")
for s in slots:
print({k: s.get(k) for k in ("id", "n_ctx", "is_processing", "speculative")})
The model probed is ornith-1.5-9b-uncensored, the smaller ornith dixie serves, not the ornith-1.5-35b-a3b of chapters 14 and 15 whose sizes this chapter uses. python3 /tmp/slots_probe.py dixie ornith-1.5-9b-uncensored, from talos:
date 2026-09-30 01:47 PDT host dixie build b10964-b29c606 max_instances 2 autoload True
ornith-1.5-9b-uncensored 8 slots
{'id': 0, 'n_ctx': 131072, 'is_processing': False, 'speculative': False}
{'id': 1, 'n_ctx': 131072, 'is_processing': False, 'speculative': False}
{'id': 2, 'n_ctx': 131072, 'is_processing': False, 'speculative': False}
{'id': 3, 'n_ctx': 131072, 'is_processing': False, 'speculative': False}
{'id': 4, 'n_ctx': 131072, 'is_processing': False, 'speculative': False}
{'id': 5, 'n_ctx': 131072, 'is_processing': False, 'speculative': False}
{'id': 6, 'n_ctx': 131072, 'is_processing': False, 'speculative': False}
{'id': 7, 'n_ctx': 131072, 'is_processing': False, 'speculative': False}
The router runs build b10964-b29c606, from 2026-09-14, older than the da89bb3 whose source this chapter quotes, so where the two differ the capture shows the older behaviour. It has 8 slots for this model, all idle, none speculative, and each reports an n_ctx of 131,072. The capture alone cannot say whether that is each slot’s own context or one shared pool: under --kv-unified every slot’s n_ctx is the whole pool, and without it each slot’s share. The model’s preset answers it. GET /v1/models, which names no model and is safe without conditions, lists for each model of a router the arguments its llama-server was started with (status.args). Save as /tmp/preset_probe.py:
"""Read-only: the slot and cache options a fleet router starts a model with, from GET /v1/models.
python3 /tmp/preset_probe.py HOST MODEL e.g. dixie ornith-1.5-9b-uncensored
GET /v1/models names no model and loads nothing."""
import json
import sys
import time
import urllib.request
host, model = sys.argv[1], sys.argv[2]
with urllib.request.urlopen(f"http://{host}:11434/v1/models", timeout=10) as r:
entry = next(m for m in json.loads(r.read())["data"] if m["id"] == model)
args = entry["status"].get("args", [])
print("date", time.strftime("%Y-%m-%d %H:%M %Z"), "host", host, "model", model, "status", entry["status"]["value"])
for i, a in enumerate(args):
if a in ("--parallel", "--ctx-size", "--kv-unified", "--cache-type-k", "--cache-type-v", "--batch-size",
"--timeout", "--cont-batching", "--no-cont-batching"):
print(a, *([args[i + 1]] if i + 1 < len(args) and not args[i + 1].startswith("--") else []))
python3 /tmp/preset_probe.py dixie ornith-1.5-9b-uncensored, from talos:
date 2026-09-30 02:06 PDT host dixie model ornith-1.5-9b-uncensored status loaded
--batch-size 512
--ctx-size 131072
--cache-type-k q8_0
--cache-type-v q8_0
--kv-unified
--parallel 8
--timeout 7200
So the 8 slots share one pool of 131,072 positions, in an 8-bit cache: one request may use all of it, and all eight together no more than it. dixie’s preset asks for 8 slots explicitly rather than leaving -np automatic. Continuous batching is on by default (-cb, tools/server/README.md), and nothing in the preset turns it off. What the capture cannot show is how many requests are waiting: /slots lists slots, not the deferred queue, which only the llamacpp:requests_deferred metric reports.
Further reading
- Gyeong-In Yu, Joo Seong Jeong, Geon-Woo Kim, Soojeong Kim and Byung-Gon Chun, “Orca: A Distributed Serving System for Transformer-Based Generative Models” (OSDI, 2022). Iteration-level scheduling, the continuous batching of this chapter, and selective batching of the operations that cannot be batched across requests.
- Woosuk Kwon, Zhuohan Li, Siyuan Zhuang, Ying Sheng, Lianmin Zheng, Cody Hao Yu, Joseph Gonzalez, Hao Zhang and Ion Stoica, “Efficient Memory Management for Large Language Model Serving with PagedAttention” (SOSP, 2023). The KV cache in fixed-size blocks through a per-sequence table, the answer to preallocated slots’ waste.
- John D. C. Little, “A Proof for the Queuing Formula: L = λW”, Operations Research 9(3), 383–387 (1961). The law, proved without assumptions on the arrival or service distributions.
- Leonard Kleinrock, Queueing Systems, Volume 1: Theory (Wiley, 1975). The M/M/1 queue from its balance equations, and the queues with several servers and general service times whose constants this chapter leaves out.
- Samuel Williams, Andrew Waterman and David Patterson, “Roofline: An Insightful Visual Performance Model for Multicore Architectures”, Communications of the ACM 52(4), 65–76 (2009). Arithmetic intensity against a machine’s FLOPs per byte, the picture behind .
- Reiner Pope, Sholto Douglas, Aakanksha Chowdhery, Jacob Devlin, James Bradbury, Jonathan Heek, Kefan Xiao, Shivani Agrawal and Jeff Dean, “Efficiently Scaling Transformer Inference” (MLSys, 2023). Latency against throughput in batched decoding at scale, with the memory and compute costs this chapter derives for one core.
- M. Nottingham and R. Fielding, “Additional HTTP Status Codes”, RFC 6585 (2012). §4, 429 Too Many Requests: rate limiting of one client.
- R. Fielding, M. Nottingham and J. Reschke (editors), “HTTP Semantics”, RFC 9110 (2022). §15.6.4, 503 Service Unavailable, and §10.2.3,
Retry-After. - llama.cpp (commit
da89bb3):tools/server/README.mdfor-np,-cb,--kv-unified,--slot-prompt-similarity,--ctx-checkpoints,/slotsand the metrics;tools/server/server-context.cppfor deferral and how a pass is filled;src/llama-memory-recurrent.cppfor recurrent state cells and their rollback snapshots.