01 · The jobTwo phases, and only one of them is fast
Generating text has two phases that look similar and behave nothing alike. reads the whole prompt in one forward pass. then produces one token at a time, and each token needs its own pass through the entire model.
Chart scrolls sideways →
The number that bounds everything
Llama-3.2-1B in is 2.48 GB of weights. An A40 moves 696 GB/s. If a decode step does nothing but stream the weights once:
No arithmetic trick beats that floor for a single sequence — it is a , not a FLOPs problem. Which points at the escape route the whole field uses: if you must read all the weights anyway, use them for more than one sequence at a time. Sections 05 and 06 are that idea, cashed in.
The bandwidth budget
Every decode step reads the same 2.48 GB, whether it serves one sequence or sixty-four. Drag the width: the read is fixed, the tokens it pays for are not.
Where 2.48 GB comes from, and why the GPU is bored
Llama-3.2-1B holds about 1.24 billion parameters. At two bytes each in bfloat16 that is 2.48 GB, and every one of them is touched on every forward pass, because a transformer has no branch a token can skip.
Now count the arithmetic. A matrix-vector product does roughly two floating-point operations per weight, so one decode token costs about 2.5 GFLOP. An A40 does about 150 TFLOP/s in bfloat16. The maths takes 0.017 ms; the reading takes 3.56 ms. The GPU spends over 99% of a decode step waiting for memory.
That ratio — FLOPs per byte moved — is called arithmetic intensity, and it is the reason batching works at all. Adding a sequence adds arithmetic, which is free here, and adds no weight traffic, which is not. Prefill is the opposite regime: 128 tokens of work against the same read, which is why a prompt is cheap per token and a reply is not.
02 · Step oneDon't recompute what you already computed
Attention at position t needs the keys and values of every earlier token. The naive engine gets them by re-running the model over the whole sequence each step. Step 200 redoes the work of steps 1–199.
The fix is the : keep each layer's keys and values after computing them once, then feed only the new token and read the rest from memory.
Chart scrolls sideways →
Before the number: how much faster does the KV cache make this engine?
Workload: 128-token prompt, 256 generated tokens, one sequence at a time.
Textbooks imply the KV cache is a bigger win than 21%. It is — at longer sequences. At 128 in / 256 out on a 1B model, a decode step is so dominated by fixed overhead that re-reading a few hundred tokens barely registers, and the cache adds its own cost by growing a tensor every step. The size of a speedup is a property of the workload, not of the idea. That is the first lesson of measuring rather than assuming — and the figure below is the same lesson with the dial in your hand.
Work saved vs. time saved
Set how many tokens the reply is. The left column counts arithmetic; the right column is what the stopwatch said. They are not the same shape, and the gap between them is the whole point.
Token-passes through the model over the whole reply — a 128-token prompt, one sequence.
32 KB per token, and why it isn't 128 KB
Per token, per layer, the cache stores one key and one value vector for each KV head:
8 heads × 64 dims × 2 tensors × 2 bytes = 2 KB.
Times 16 layers, that is 32 KB per token, or 128 MB for a
full 4,096-token sequence — per sequence, and 32 of those is 4 GB of GPU
memory doing nothing but remembering.
Eight KV heads, but the model has 32 query heads. That is : four queries share each key/value head, so the cache is a quarter of the size it would be with one KV head per query head. It is the single largest reason a 1B model can hold dozens of concurrent sequences on one card — and, as section 07 shows, it also costs 10% of GPU time, because something has to expand those 8 heads back to 32 before the multiply.
The measured sweep, from docs/benchmarks.md, taken on the last commit where
the no-cache path still existed:
| Tokens out | no cache | KV cache | cache is worth |
|---|---|---|---|
| 256 | 60.7 | 69.5 | 1.15× |
| 512 | 44.6 | 71.9 | 1.61× |
| 1024 | 24.1 | 69.6 | 2.88× |
Read the columns, not the ratio: cached throughput barely moves with length, while the recompute path collapses. The cache is not getting better; the alternative is getting worse.
03 · Step twoA measured zero, reported as a zero
The first cache wrapped a HuggingFace DynamicCache. The second stored keys and
values as plain tensors instead — fewer layers of indirection, no dependency on a
library's internals, and full control of the memory layout.
A cleaner rewrite of the same data structure. What does the stopwatch say?
Same workload, same kernels, same arithmetic — only the container changed.
Nothing. Three independent measurements, all within run-to-run variance. The rewrite was still worth doing — it removed a coupling and became the foundation the paged cache was built on — but it did not make anything faster, and the documentation says so.
This is worth pausing on, because it is the part of engineering that gets quietly edited out of write-ups. A change can be correct, necessary, and not an optimisation. An engine whose docs claim a win for every merge is an engine whose numbers you cannot trust.
What "inside noise" means here, precisely
Re-running the same configuration alone versus inside a parallel sweep moved throughput by 2.0% and inter-token latency by 3.8%, in opposite directions. So the harness treats ±4% as the resolution floor: below roughly 1.1×, a difference is a measurement, not a result. Every speedup claimed on this page clears that floor, except the two explicitly reported as zeroes.
A rewrite that buys nothing today can still be the precondition for something that buys a lot — here, owning the memory layout is what made a paged cache writable at all. The honest way to record that is a zero in the results table and a sentence about why the code stayed.
04 · Step threePages instead of arrays — a deliberate local loss
A contiguous per-sequence cache wastes memory in three distinguishable ways, and they are worth naming separately because the fix kills them at different rates. Reserved space is held for tokens the sequence will eventually generate: it does get used, just not yet, and until then nobody else can have it. is the gap between what you reserved and what the reply actually needed — reserve 4,096 tokens for an answer that stops at 30 and 99% of that allocation is never touched at all. is the unusable holes left between differently-sized contiguous allocations. Multiply by the number of concurrent slots and the GPU runs out of room long before it runs out of compute.
Operating systems solved this with paging, and inference engines borrow it wholesale. Cut memory into fixed-size blocks. Give each sequence a mapping its logical blocks 0, 1, 2… to whatever physical blocks the pool had free. The sequence addresses its cache as if it were one contiguous run; the table quietly does the translation. Sequences grow a block at a time, blocks come from one shared pool, and nothing needs to be adjacent to anything.
Diagram scrolls sideways →
block_size consecutive slots — so an address collapses to
a single integer, which is what lets the cache move a whole batch in one tensor operation.
Paging fixes the memory waste. What does it do to throughput?
Same model, same batch of one, blocks of 16 tokens instead of one contiguous array.
Resolve a token to its physical slot
Pick any logical position. Watch it become one integer. Then append tokens and watch a block boundary get crossed. block_size is 4 here so the slots fit on screen; the engine runs 16.
Logical view — what seq A believes it has: one contiguous run
Block table — logical block → physical block
The arithmetic
Physical pool — 10 blocks of 4 slots, one shared array
Pool scrolls sideways →
block_size, not by how long the reply might have been.
Paging made this engine slower. Blocks are scattered, so before attention runs, the keys and values have to be gathered back into a contiguous tensor — every layer, every step. Production engines avoid that by teaching the attention kernel to walk the block table itself, so the blocks are never materialised as one tensor at all; liteinfer has not written that kernel yet, so it pays the gather on every single layer of every single step.
What it does buy is memory. Reserved space and external fragmentation go to zero: a block is allocated only when the previous one fills, and every block is the same size, so there are no awkward holes. Internal fragmentation survives — but it shrinks from the difference between the reply you got and the longest one you might have got to at most block_size − 1 unused slots in the last block. That is the whole trade, and it is why the block size is a knob rather than a constant.
It was still the right move, and this is the subtle part: an optimisation can lose locally and win globally. Paging is what makes it possible to admit and evict sequences independently — and that unlocks section 06, which is worth 5×. Judging paging on its own 8% loss would have meant never getting there.
The whole address translation, in one tensor op
Because a block is block_size consecutive slots in one flat array, a token's
address is a single integer and the translation for an entire batch is arithmetic on a
tensor — no Python loop over sequences, no loop over blocks. This is
slot_table, the only place in the engine that knows how blocks are addressed:
# cache/block_pool.py — every read and write goes through this
logical = torch.arange(max_total, device=device) - (max_total - count).unsqueeze(1)
is_real = logical >= 0
logical = logical.clamp(min=0)
slots = blocks.gather(1, logical // block_size) * block_size + logical % block_size
return torch.where(is_real, slots, 0) # 0 = the null block
Three details earn their place. The rows are right-aligned, so the newest token is always the last column — which is what the left-padded attention mask expects. Positions that do not exist yet are pointed at slot 0, the null block, so padded batch positions can be written and read without anyone masking them. And the pool is allocated with one extra block behind the scenes, so that null block costs no usable capacity.
An earlier version of the same lookup walked the block tables in Python, once per layer, once per step. Vectorising it is what made continuous batching 7× faster — see section 12.
05 · Step fourMake one weight read serve many sequences
Back to the floor from section 01. A decode step streams 2.48 GB of weights to produce one token. Run four sequences through the same pass and the same read produces four. The weights are the expensive part and they are shared.
One sequence at a time — output tokens/second
Near-linear in the batch size, which tells you the GPU was never the constraint — it was idling on memory. This is : gather a group of requests, run them together, return them together.
And that last word is the flaw. A batch finishes when its slowest member finishes. A request that wanted 20 tokens sits occupying a slot until the one that wanted 500 is done. The GPU is busy; much of what it computes is padding. The next section lets you step through exactly that, one iteration at a time.
Why 4× the sequences is 3.84× the tokens, and not 4×
The missing 4% is everything that does not get shared: the KV cache reads grow with the batch, the sampler now picks four tokens instead of one, the mask is bigger, and the batch runs at the length of its longest member so some positions are padding. vLLM measures 3.84× on the identical transition, which is a useful sanity check — when your scaling matches the reference implementation's scaling, the residual is physics rather than a bug in your loop.
The interesting question is where the near-linearity stops. It stops when the weight read is no longer the dominant cost — at large enough batch or long enough context, the KV cache traffic overtakes the weights, and throughput flattens. On a 1B model with 128-token prompts that point is far away, which is why section 06 can go to 32 slots and keep gaining.
06 · Step fiveNever leave a slot idle
removes the batch boundary. The scheduler holds a set of slots; on every step it evicts whichever sequences finished and admits waiting ones into the freed slots. Requests join and leave mid-flight.
The name to hold on to is the mechanism, not the effect: batch membership is re-decided once per iteration, which is why the same idea travels under iteration-level scheduling and in-flight batching as well. Nothing about the forward pass changes. The only change is who is in it.
Step the scheduler: static vs continuous
Seven requests, four slots, identical work in both grids. Press play, or step through with the arrow keys. An illustrative schedule, not a measurement — the measured numbers are below.
Timelines scroll sideways →
Each pair reads static → continuous, counted up to the current step.
This is also where paging pays for itself. Admitting and evicting sequences independently requires per-sequence memory that can be handed back in pieces — exactly what block tables provide, and exactly what a contiguous per-sequence array cannot do.
Adding concurrency — output tokens/second
The scheduler, in full — it really is this small
There is no queueing theory in here. Every step: fill any empty slot from the waiting list, then split whoever is running into the ones that need a prefill pass and the ones that need a decode pass.
# engine/continuous_scheduler.py
def schedule(self) -> ContinuousSchedulerOutput:
available = self.config.max_num_seqs - len(self.running)
if available > 0 and self.waiting:
n = min(available, len(self.waiting))
admitted, self.waiting = self.waiting[:n], self.waiting[n:]
for seq in admitted:
seq.status = SequenceStatus.RUNNING
self.running.extend(admitted)
prefill_seqs = [s for s in self.running if not s.is_finished and not s.output_token_ids]
decode_seqs = [s for s in self.running if not s.is_finished and s.output_token_ids]
return ContinuousSchedulerOutput(prefill_seqs, decode_seqs)
The companion is remove_finished, which evicts sequences individually
instead of waiting for the batch — three lines, and the entire difference between
this section and the last one.
Splitting prefill from decode is also the one place liteinfer scales slightly below vLLM: when both kinds of work are pending it issues two forward passes in a step where vLLM would issue one mixed pass. That is worth 5.01× against vLLM's 6.17× on the same 4 → 32 transition, and the fix has a name — chunked prefill.
07 · Reality checkWhere the time actually goes
Intuition says a forward pass is matrix multiplication. A profiler disagrees. Here is GPU time during decode, by operation:
Share of GPU time during decode
Two findings hide in there. Sampling costs 7% — picking the
highest-scoring token out of a 128,256-wide vocabulary is not free. And
a tenth of the time is clone, almost all of it one line:
this model has 32 query heads sharing 8 key/value heads, and attention materialises a
4× copy of K and V so the shapes line up. Section 08 removes the larger of the two
memory costs in attention; this copy is the smaller one, and it is still there —
a fused kernel can broadcast those heads internally instead, which is the next change
queued on this file.
Suppose you made it free
Tick the parts of the profile you would optimise away entirely — the best case, not a realistic one. The ceiling is : 1 ÷ (1 − the fraction you removed).
torch.compile and fused
kernels do their work. That is the difference between reading a profile and reading it
arithmetically.
The lesson generalises past this codebase: profile before you optimise. Nobody guesses "the sampler" or "a shape-fixing copy" when asked where the time goes.
The clone that costs 10%, and why it exists
Grouped-query attention stores 8 KV heads for 32 query heads. Before the multiply, the two sides have to agree on head count, so the engine expands the KV heads back to 32:
# models/attention.py — _repeat_kv
return (
hidden_states[:, :, None, :, :]
.expand(batch, num_kv_heads, n_rep, slen, head_dim)
.reshape(batch, num_kv_heads * n_rep, slen, head_dim)
)
expand is free — it is a view with a zero stride. reshape
is not: the tensor is no longer contiguous, so PyTorch materialises a real 4× copy
of every key and value in the batch, on every layer, on every step. That copy is the
clone in the profile.
A kernel that broadcasts the heads internally never makes the copy — which is exactly what a purpose-built paged-attention kernel does, and one of the two remaining items on this file's roadmap.
08 · Step sixAttention that never writes the matrix down
Every design so far attacked how often the model runs. This one attacks what a single attention call keeps in memory — and unlike the others, it is not a speedup. It is the difference between running and not running.
Written out plainly, attention builds a score for every (query, key) pair: one
[batch, heads, queries, keys] tensor, and the
upcasts it to fp32 to stay
numerically safe. That tensor is the largest thing in the forward pass, and it
grows with the square of sequence length. At 32 sequences × 32 heads
× 1024², it is 4.00 GiB in a single allocation — and
liteinfer died there, out of memory, on a prompt length vLLM handled without noticing.
The fix is the idea behind , and it is worth stating carefully because the name suggests a faster multiply, which it is not. The scores are computed in tiles that fit in the GPU's on-chip . Each tile is scored, softmaxed and folded into a running output right there; then it is discarded. The softmax is kept correct across tiles by carrying a running maximum and a running sum, and rescaling the accumulated output when a later tile raises the maximum — the online softmax trick. The full matrix is never assembled anywhere, so peak memory stops depending on sequence length at all.
Diagram scrolls sideways →
Size the score matrix yourself
The eager kernel's peak is dominated by one term: batch × 32 heads × length², at 4 bytes once the softmax upcasts. Push either dial and watch a quadratic do what quadratics do.
Peak GPU memory for a single attention call, against the A40's 46 GB — of which the weights and the KV pool have already taken their share.
In liteinfer this is one call: torch.nn.functional.scaled_dot_product_attention,
which dispatches to a fused CUDA backend. One detail is worth knowing because it surprises
people reading a profile. Prompts of different lengths are left-padded, so liteinfer passes
an explicit additive mask — and FlashAttention proper accepts no such mask, only a
causal flag. PyTorch therefore falls to its memory-efficient backend, which does
take a mask and tiles the same way. Different kernel, same property: no matrix.
A fused attention kernel replaces plain matmuls. Faster?
Same 32 slots, same prompts, same output length — shapes the eager kernel could already serve.
Which is the honest headline, and the second measured zero on this page. Every shape the engine could already serve, it serves at the same rate. Tiling does not make the arithmetic cheaper; it changes where the intermediate lives.
Output tokens/second by prompt length — 32 slots
One caution, because it is the kind of credit that gets misassigned. The ISL 1024 rows here run under both kernels — what unlocked those was a separate fix to how the block pool is sized, which had been claiming 32 GB it could never address. ISL 2048 is the first length only the fused kernel reaches. Two memory bugs, stacked; fixing one made the other visible.
Both kernels, side by side — and the backend PyTorch actually picks
The two implementations sit in the same file and differ by one call. Eager is kept deliberately: it is what the arithmetic looks like, and it is the parity reference the fused path is checked against.
# models/attention.py — eager: every step visible, and the memory ceiling
scores = torch.matmul(query, key.transpose(2, 3)) * scaling
scores = scores + attention_mask[:, :, :, : key.shape[-2]]
weights = nn.functional.softmax(scores, dim=-1, dtype=torch.float32).to(query.dtype)
return torch.matmul(weights, value)
# models/attention.py — sdpa: the same function, tiled, no score matrix
return nn.functional.scaled_dot_product_attention(
query, key, value, attn_mask=mask, scale=scaling)
Which backend serves that second call is not the obvious one. Left-padded batches need an
explicit additive mask, and FlashAttention takes only is_causal, so PyTorch
falls to its memory-efficient backend. Probed on these exact tensors: flash unavailable,
mem-efficient available, and forcing the math fallback instead costs
+4,872 MiB against mem-efficient's +32 MiB.
The two kernels disagree in exactly one place, and the file says so: on fully masked query
rows — the left padding — sdpa returns zeros while eager returns the average
of every value vector, because the mask is finfo.min rather than
-inf and a softmax over equal scores is uniform. A row that attends to
nothing has no defined answer; the engine reads logits from the last column, which is
never padding, so neither answer reaches the output. Knowing why two kernels
differ is what lets you call one of them a reference.
09 · The other profileOnce the model is fast, the loop around it isn't
Every section so far changed what the model computes or how often it runs. But an engine is not only a model. On every iteration it also decides who is in the batch, turns a row of scores into a token, turns tokens into text, and hands that text to whoever asked for it. Those stages launch few kernels and read like plumbing, so they are the last place anyone looks — which is exactly why they are where the surprises are.
Section 07 profiled GPU operations, and that profile answers one question: which
kernel. It cannot answer what fraction of an iteration is inside a kernel at all,
because work that never touches the device does not appear in it. The complementary
measurement is to charge every stage of the loop to a bucket — schedule, forward,
sample, deliver — and to print whatever is left over as unattributed.
When the buckets account for nearly all of the wall clock, “where does the time
go” stops being a script somebody has to write and becomes a number the engine
reports about itself.
Diagram scrolls sideways →
Outside the model, which stage of a serving loop costs the most?
A continuous-batching loop with a few dozen slots, generating a long reply.
The parts that look like overhead usually aren't
A scheduler that admits and evicts a handful of sequences per iteration is a few list operations weighed against a forward pass that streams gigabytes. An async queue hand-off is a pointer. Measured, they stay in the noise — and knowing that is worth as much as finding a hotspot, because it is a week you now know not to spend. The reason to suspect them is that they are “the code that isn't the model”, which is a category, not a measurement.
The accidental quadratic
Here is the shape to learn, because it recurs far outside inference: any per-step operation that re-derives its answer from the entire history is quadratic in the length of the run, even when the line that does it looks constant-time. Turning generated ids back into text is the classic instance. Decoding all tokens so far on every step is one innocent function call; over a reply, the total work it does grows with the square of the reply length.
That is also why it hides. At a short reply it is a rounding error — a few percent of the loop, comfortably inside the noise floor, indistinguishable from nothing. It only becomes the largest non-model cost when replies get long. The same lesson as section 02, arriving from the other side: a workload shape you never benchmark is a bug you never find.
The fix is to keep incremental state and decode only what the newest token added — and the subtlety here is worth more than the speedup, because it is where the obvious version of this optimisation is silently wrong. You cannot simply decode the new token on its own. A UTF-8 character can span two tokens, and a byte-level BPE piece renders differently depending on what precedes it. The robust trick is a sliding window: decode a short window ending at the new token, decode the same window one token shorter, and keep the difference. When the window ends mid-character the decoder emits a replacement character — which is the signal that this is not text yet, so you hold it back and let the next token complete it. An optimisation is only worth having if it produces the same bytes.
Where an iteration's time goes as replies get longer
Four stages, one loop. Drag the reply length; switch how the text hand-off is written. An illustrative model, not a measurement — what matters is which curve is flat and which is not.
Share of one iteration, averaged over the whole reply.
A loop over the batch is a loop of round trips
The host and the device are two machines with a bus between them, and a is the CPU standing still until everything it has queued on the GPU has drained. That makes two ordinary-looking Python patterns expensive out of all proportion to the arithmetic in them.
- Reading results back one row at a time. A loop over the batch that pulls each row's answer out as a number forces one synchronisation per row. The arithmetic is trivial; the waiting is not. Take the whole batch in one operation and bring it back in one transfer.
- Building inputs one row at a time. Constructing a small tensor per sequence is one per sequence, and an ordinary copy blocks the caller while it runs. Pad on the host, move the batch once.
- Asking the device for something the host already knows. Reading a maximum or a count off a tensor to size a buffer, when plain Python integers were already in hand, buys a full pipeline stall for nothing.
The tell is easy to check and hard to argue with: count transfers, or kernel launches, per step, and see whether the count tracks the batch width. A per-step cost proportional to the number of sequences is a Python loop wearing a tensor costume.
Measure the component to find the target; measure the engine to size it
One habit is worth carrying away from all of this. Timing an operation in isolation is the right way to find a candidate — and a systematically bad way to predict what it will be worth. Isolated numbers read high, for two reasons that compound: the isolated version pays synchronisation costs that in the real loop overlap with other work, and, far more often, the ratio is being taken against the wrong denominator. A 30× win on something worth 3% of the loop is 1.03×. That is again, this time applied to your estimate rather than your result — and it is the cheapest way to stop a change from being ranked above the one that actually matters.
None of the changes in this section touched a kernel; some are pure Python. That is the point worth generalising. Once the obvious algorithmic wins have landed, the next tranche of speed usually lives in the machinery around the model — and the only reliable way to find it is to make the machinery report on itself.
What “the loop accounts for 99% of its own time” actually buys
Self-instrumentation is a feature, not a debugging session. Three details separate a breakdown you can trust from a comforting pie chart.
Keep a residual bucket. A breakdown whose slices sum to 100% by construction cannot tell you it has missed a stage. Charging stages explicitly and printing the leftover as unattributed means the accounting has to earn its own credibility: if the named stages cover 99% of wall time, the picture is complete; if they cover 70%, the interesting thing is the 30%.
Do not charge a stage for the previous stage's queue. GPU work is asynchronous, so a naive timer around a stage that issues no device work will happily bill it for whatever the last stage left running. Stages that launch nothing should skip the device synchronisation entirely, or every number after the forward pass is fiction.
Then check the instrument. It is common to find that a timer measured something other than its name — a counter labelled “forward pass” that quietly includes the sampler and the stop check, say. Splitting them is not a cosmetic fix: it is what makes the sampler visible as its own line instead of inflating the model's. Instrumentation is code, and it is wrong in the same ways other code is wrong.
The prize is that ranking becomes arithmetic rather than argument. Every item on a performance backlog is implicitly a claim about a share of the total; once the shares are measured, the claims can be checked before the work starts.
The sliding window, and why the obvious version corrupts text
The naive incremental version — decode the new token, append its text — is wrong in two distinct ways, both of which produce output that is almost right, which is the worst kind of wrong. A multi-byte character split across two tokens decodes to a replacement character when either half is decoded alone; and byte-level BPE pieces carry no fixed rendering, so the same id contributes different text depending on its neighbour.
Decoding a window twice sidesteps both, because the difference between the two decodings is by construction exactly what the new token added in context:
# the text the newest token contributed, in context
prefix = decode(ids[start : cut]) # window, one token shorter
whole = decode(ids[start : ]) # window, up to the new token
if whole.endswith(REPLACEMENT_CHAR):
return "" # mid-character: hold, let the window grow
return whole[len(prefix):] # the difference, and only the difference
Two consumers usually want that text — the stop-condition check and whatever streams output to the caller — and in a first implementation they each tend to rebuild it independently. Advancing it once per step and letting both read the result removes a duplicate decode nobody had counted, which is a reminder that the same computation appearing twice is easier to find in a stage breakdown than in the source.
10 · The ceilingHow far is this from production?
vLLM is the reference implementation of everything on this page, plus the kernel engineering liteinfer hasn't done. Compared at matched batch width — comparing a 1-slot engine to a 32-slot one measures the slot count, not the engine:
liteinfer as a fraction of vLLM, at the same batch width
Full width of each track = parity with vLLM.
A gap that widened with batch size would mean something scaling with batch × sequence length — an algorithmic problem. A flat ~3× means a constant per-step cost: no , no fused paged-attention kernel. In bandwidth terms, vLLM sustains about 68% of what the A40 can move; liteinfer manages roughly 26%.
Which is a satisfying place for a teaching engine to land. Every idea on this page is the same idea production engines use. The remaining 3× is kernel engineering, and it is the least conceptual, most laborious part of the work.
Turning milliseconds into a bandwidth percentage
The floor from section 01 is 3.56 ms per decode step: 2.48 GB of weights at 696 GB/s. vLLM's measured inter-token latency is 5.2 ms, so it is running at 3.56 / 5.2 = 68% of the card's bandwidth. liteinfer's is 13.7 ms → 26%. Same hardware, same model, same arithmetic; the difference is entirely in how much of each step is spent not streaming weights.
Where does liteinfer's extra 8.5 ms go? Section 07 answers most of it: 42% of GPU time on data movement, plus gaps where the GPU sits idle waiting for Python to issue the next kernel. CUDA graphs attack the second one by replaying a recorded launch sequence instead of re-issuing it; that is why they are the top item on the roadmap.
One number in the other direction, and it needs reading narrowly: liteinfer's time-to-first-token is better than vLLM's, 15.7 ms against 22.7 ms. At a 128-token prompt both are dominated by fixed per-call overhead — vLLM pays IPC to a separate engine process — so this measures offline round-trip latency, not prefill speed. Reporting it as a win would be exactly the kind of benchmark theatre section 11 is about.
11 · How we knowNumbers that survive contact
Every figure here comes from one harness, and a few rules keep them honest. They are worth stealing whole:
- Force the output length. If one engine stops at an end-of-text token and another runs on, you are comparing sentence lengths, not engines.
- Measure the mode that matches the change. Throughput answers "how much fits at once"; latency answers "what does one step cost". Reporting a latency measured under saturation mostly records queue position.
- Compare at matched batch width, and against the design each change actually improves on — not against whatever number is handy.
- Know your noise floor. Run-to-run variance here is about ±4%, so anything under ~1.1× is not a result.
- Report the metric that got worse. Continuous batching won throughput 5.0× and gave up about 9% of single-request latency against the fastest single-sequence design. Both belong in the write-up.
One consequence is unusual enough to state plainly: when a design clearly and generally beats another, the loser is deleted. Its measurements stay in the results so the progression is still readable, but the code goes, and whatever abstraction existed only to support the choice collapses with it. Every design in sections 02–05 has been removed from the engine on those grounds.
The exception matters as much as the rule: an improvement that only applies under some precondition — a mixture-of-experts kernel, a quantised path — replaces nothing, however large its win, because outside its domain it does not apply. Two paths chosen by a precondition are not debt; they are the feature.
The rules that made these numbers comparable
Identical inputs. One canonical prompt set per (model, prompt length, reply length), reused by every engine, drawn from the same ShareGPT corpus vLLM's own benchmarks use. Every result stores the SHA-256 of its prompt set and the report flags any group whose members disagree.
Forced output length. min_tokens = max_tokens = OSL with
ignore_eos, verified after every run: a run that violates it fails instead
of reporting.
Warmup and isolation. Each run exercises the exact path it is about to measure, twice, before the clock starts — so kernel autotuning and CUDA graph capture land outside the timed region. Each (config, mode) pair runs in a fresh process, so no allocator fragmentation carries over.
vLLM at its strongest. Its own scheduler, CUDA graphs on,
gpu_memory_utilization=0.90, bfloat16. And the harness is checked against
vLLM's own tooling at the identical shape: vllm bench throughput reports
4,421.7 tok/s where this harness reports 4,465.9 — 1.0% apart, with both emitting
exactly 51,200 tokens.
One measurement was thrown out. In the first parallel sweep vLLM's TTFT read 28.1 ms; re-run sequentially it dropped to 21.3 ms while every other number stayed put. Its offline TTFT is mostly IPC overhead and therefore CPU-scheduling sensitive. The latency tables are all from the sequential re-run, and the harness now warns when latency mode is combined with parallel GPUs.
12 · Read it yourselfWhere to start in 2,272 lines
The engine is deliberately small enough to read end to end. One execution path, no alternatives to hold in your head. A reasonable order — every file links to the branch this page describes:
async_llm.py
Start here. The public API — submit prompts, await results, or stream tokens as they arrive.
engine/async_llm_engine.py
The loop. Evict finished sequences, admit waiting ones, run a pass, deliver events.
engine/continuous_scheduler.py
Section 06 in code: which sequences prefill and which decode on this step. Smaller than you expect.
cache/block_pool.py
Section 04 in code: the slot arithmetic, the null block, and slot_table.
cache/continuous_kv_cache.py
Per-sequence block tables; register on admit, free on evict.
models/llama.py
The transformer itself, written out plainly — RoPE, MLP, norms, projections.
models/attention.py
Section 08 in code: the two kernels, and the one line that picks between them.
engine/metrics.py
Section 09 in code: the stage accounting, and the residual bucket that keeps it honest.
tokenizer.py
The incremental detokenizer — the sliding window, and the replacement-character rule.
sampling/sampler.py
Greedy rows taken together in one kernel; stochastic rows, which each need their own stream, stay a loop.
benchmarks/
Sections 10–11 in code: the matrix, the harness, the report, and the stored results.
The one line worth memorising
# A whole batch's cached keys, read in a single indexing operation.
# self._slots is [batch, max_tokens] of physical slot numbers.
gathered_k = keys[self._slots].permute(0, 2, 1, 3)
An earlier version of that gather looped over sequences and blocks in Python, once per layer, once per step — roughly 8,000 tensor operations per decode step at 32 slots. Replacing it with the line above made continuous batching 7× faster. Address arithmetic that collapses to one integer is the reason it fits on one line.
Two claims on this page were false before that fix: that paging beats no cache at all, and that continuous batching beats static batching. Both were true of the designs and untrue of the implementation. It is worth knowing how easily a Python loop can libel an algorithm.
13 · ReferenceThe vocabulary, in one place
Every dotted term on this page, collected. Nothing here is liteinfer-specific — it is the shared vocabulary of inference serving.