AI engineering · A guided lesson
LLM Inference Fundamentals
Follow one request from its first token to a shared service. Understand why inference needs memory, why batching changes speed, and how to decide whether an optimization actually helps.
- For
- Readers who know that an LLM has weights but are new to inference engines.
- Before reading
- Basic familiarity with vectors and model layers is helpful. No engine setup or prior knowledge of KV cache is required.
- Scope
- Standard autoregressive decoder inference and full-context K/V caching. Architecture-specific exceptions are identified where they matter.
Follow the work, not just the vocabulary
One request becomes an answer. Then we add caching, a memory budget, and other users. Each new problem introduces the next mechanism.
Read in order if inference is new. Use the figures to check your mental model, then explore the memory lab. All numerical scenarios are hypothetical, not benchmarks.
Chapter 1
From Prompt to Answer
A prompt arrives. What actually runs?
You send a prompt to a small assistant, and words appear. What looks like one operation actually involves three responsibilities.
The model contains an architecture and learned weights. The architecture defines the operations and connections. The weights are the numerical values used in those operations. Together, they determine how input is transformed into predictions.
The inference engine runs those operations on hardware. It loads weights, executes tensor operations, manages memory, and may schedule work from multiple requests. The serving layer exposes that execution to users through an API, accepts requests, and returns responses. A single product can implement both engine and serving functions, so these are responsibilities rather than necessarily separate programs.
The model sees tokens, not the sentence you see
Suppose the prompt is “Explain why the sky looks blue.” Before model execution, a tokenizer converts that text into token IDs. A token is not necessarily a word. Depending on the tokenizer and text, it can represent a whole word, a fragment, punctuation, or another text unit.
The model turns token IDs into numerical representations and transforms them through its layers. Its next-token output is not immediately a word. It is a set of scores, called logits, over possible next tokens.
A selection rule then chooses a token. Greedy decoding picks the highest-scoring candidate. Sampling chooses according to a probability distribution, potentially adjusted by settings such as temperature. We will not study those settings deeply here. The important distinction is that producing scores and choosing a token are separate steps.
Forward pass is the operation; prefill and decode are the stages
You may already know the term forward pass. It means running inputs through the model to obtain outputs. It does not update the weights. During training, weight updates require additional work, including backward computation and an optimizer step.
Prefill processes the prompt. If our prompt contains five tokens, those positions can be processed together in a forward pass. Causal attention restricts each position to itself and earlier positions, so parallel processing does not let a token look into the future. The final prompt position provides the logits used to select the first output token. Prefill also builds the prompt's KV cache, which we will explain in Part II.
After the first output token has been selected, the system must predict the next one. With a KV cache, a standard decode step processes the newly selected token and reuses context information from previous positions. Its logits are used to choose another token. The loop repeats until a stopping condition is met, such as an end-of-sequence token or an output limit.
There is a subtle distinction here: selecting a token and processing it are different events. The first output token is selected from prefill results. It becomes the input to the next decode pass. If generation stops immediately after selecting a final token, that final token may never need to be processed or added to the cache.

Why prompt length and answer length create different work
The assistant works. Now make either its prompt or its answer longer. These changes create different work.
A longer prompt gives prefill more input positions to process. A longer answer requires more decode steps. Within one ordinary autoregressive response, the next selected token depends on earlier selected tokens, so the engine cannot simply generate every future token independently in one batch.
At this point, a natural concern appears. If every new token needs the previous context, do we have to run the entire prompt again for every prediction? A naive implementation can repeat a great deal of work. The next part explains what can be saved instead.
A long prompt and a short answer: where is the main added work?
The long prompt adds prefill work. It also creates a larger context for the few decode steps that follow. A short answer limits the number of those steps, but does not erase the context cost.
Keep this distinction
Prompt length adds initial work. Answer length adds steps. Both affect the context used during decode.
Chapter 2
Understanding KV Cache
Attention: what is the new token looking for?
At each attention layer, token representations are projected into queries (Q), keys (K), and values (V).
The query is compared with visible keys to produce scores. Those scores are scaled and normalized with softmax into attention weights. The weights are then used to combine the corresponding values. This produces information used by the rest of the layer.
Read the formula as three steps: compare Q with K, normalize, then combine V. The causal mask blocks future positions.
Attention(Q, K, V) = softmax(QKT / sqrt(dhead) + causal mask) V
Why earlier K and V can be reused
Under causal attention, A could not see B, C, or D. B could not see C or D. C could not see D. Adding D does not change what those earlier positions were allowed to see. In standard causal inference, with the same model and positional interpretation, their earlier representations do not need to be recomputed just because a later token arrived.
That makes their per-layer keys and values reusable. Instead of regenerating K/V for A, B, and C, the engine stores them. When D is processed, it computes D's new K/V, combines them with the stored K/V, and performs attention for D.
This stored state is the KV cache. It is not a cache of complete answers, and it is not a store of text snippets. It holds numerical tensors derived from previously processed positions, separately at the relevant layers.
Why not keep old Q or attention scores?
Standard KV caching does not save the full history of attention scores. Old Q is unnecessary because we are not asking for a new output at the old positions. We only need the new position's query to compute the new position's attention output.
For D, its Q is compared with the keys for A, B, C, and D. These are new comparisons. D's query is different from C's query, so C's old scores cannot simply be used as D's scores. After normalization, D's weights combine the corresponding values.
This distinction explains why decode is not free after prefill. We removed repeated work on old representations, but we still have to read the cache and compute attention for every new position.
What changes when E arrives: all past K/V, or the query and attention calculation for E?
In the standard cached causal model, past K/V are reused. E has new Q/K/V, computes its own attention over the visible context, and contributes its K/V to the cache.
Chapter 3
Budgeting GPU Memory
One more architecture detail: query heads versus KV heads
In conventional multi-head attention (MHA), each query head has its own corresponding K/V head. A hypothetical model with 32 query heads could therefore have 32 KV heads.
In grouped-query attention (GQA), several query heads share one K/V set. With 32 query heads and eight KV heads, each group of four query heads uses the same keys and values. Their outputs can still differ because each query is different and produces different attention weights.
In multi-query attention (MQA), all query heads share one KV head. These designs change how much K/V needs to be stored and accessed. The number called “attention heads” in a model configuration often refers to query heads, so do not assume it is the cache-head count.
Weights fit. Why can memory still run out?
The missing piece is that weights are only one component. Inference also needs KV caches, intermediate activations, temporary buffers, and engine overhead. Some allocations depend on execution shape and engine features. A file's size on disk is not a complete estimate of resident inference memory.
Weights are normally shared by requests using the same model instance. Three active requests do not require three copies of those weights. But their contexts are separate, so each needs context state. Some engines can share identical cached prefixes, but we will assume no sharing for simple budgeting.
A request's cache grows as more positions are processed. That includes prompt positions and generated tokens fed back through decode. Therefore memory can grow while the answer is being produced, not only when the request arrives.
Inference memory ≈ resident weights + active KV caches + working memory and overhead
Which uses more cache: ten requests or two requests?
You cannot tell from request count alone. You also need their stored token counts and cache structure. Two very long contexts can use more cache than ten short ones.
Bits and bytes before the memory formula
A bit holds a binary value. A byte contains eight bits. Therefore a 16-bit value occupies two bytes, and a 32-bit value occupies four bytes. The lowercase b and uppercase B distinguish bits and bytes in unit names.
FP32 uses 32 bits per value. FP16 and BF16 each use 16 bits, although they represent numbers differently. INT8 uses eight bits. A raw four-bit payload is half a byte per value, so two such values can be packed into one byte.
The raw estimate is not the final allocation. Quantized formats need scales or other metadata, some tensors may retain higher precision, and runtime layouts can differ. Also, quantized weights do not automatically imply quantized KV cache. Weight precision and cache precision are separate facts to inspect.
Raw weight bytes ≈ parameter count × bits per parameter / 8
Build the KV formula one factor at a time
Let us derive the formula rather than start with it. For one token at one layer, we store K and V. That gives the factor two. Each has a vector for every KV head. Each vector contains a fixed number of elements, called the head dimension. Each element uses some number of bytes.
Use a hypothetical model with 32 layers, eight KV heads, head dimension 128, and FP16 cache. K and V give two; FP16 gives two bytes per element. The multiplication gives 131,072 bytes, or 128 KiB, per cached token.
At 4,096 tokens, that is 512 MiB. At 8,192 tokens, it is one GiB. Three requests each storing 8,192 tokens need three GiB of cache payload. The weights remain shared, while the cache allowance grows with the workload.
Cache bytes/token = 2 × layers × KV heads × head dimension × bytes/element
Explore the budget, then question its assumptions
Now test the mechanism. Move a slider and watch which part of the budget grows. The weights stay shared; each request adds its own token state.
The default model uses 128 KiB of cache per token. Each request budgets 8,192 tokens, or 1 GiB. The lab estimates memory, not speed or safe production capacity.
Memory lab / change one thing
Can three requests fit? Start with the example, then double the load or extend the context.
19.9 / 24 GiB budgeted
Change workload and watch cache grow independently of weights.
128 KiB/token; 1 GiB cache/request; 3 GiB cache total. Estimated headroom 4.1 GiB. Not a fit or performance guarantee.
Change hardware and model assumptions
Why not allocate all remaining memory to prompts immediately?
Generation adds context state, and runtime work needs headroom. A budget that ignores future output or temporary allocations can fail after requests have already started.
Chapter 4
Using the GPU Efficiently
A large memory is not a fast execution
The model fits, yet it is slow. Storing data and using it are different capabilities.
Capacity is how much memory is available. Memory bandwidth is how quickly data can be moved through a memory interface. Compute throughput is how much numerical work the hardware can perform per unit time. A system can have plenty of capacity while waiting on data movement or computation.
We call the first pattern compute-bound and the second memory-bandwidth-bound. Real workloads can move between them, and overhead can create other limits. The labels are hypotheses about execution, not properties permanently attached to a model.
Why prefill and small-batch decode often behave differently
During prefill, many input positions are available together. When the engine reads a tile of weights, it can use that data for calculations involving multiple token positions. This creates substantial computation relative to the data moved.
During decode for one request, only one new position is available in the ordinary generation step. The model still accesses the weights used by its layers, but there is less token work to perform from each weight read. It also reads context K/V for attention.
Long contexts can add significant attention work and cache traffic. Larger batches can increase reuse. Different models and hardware can change the balance. The useful habit is to ask how much computation is obtained from the data being moved, then verify the limiting resource when tuning.

Mechanism reference: source 3.
Why can processing several positions together be more efficient?
A piece of weight data can support calculations for multiple positions before it must be fetched again at the relevant memory level. More useful computation is obtained from data movement. This is an opportunity for efficiency, not a guarantee of lower latency.
Chapter 5
Handling Multiple Requests
Add two users: batching without mixing conversations
Now a second and third request arrive. Request A asks for an explanation, B asks for an email, and C asks for a summary. Their contexts are independent. Batching must not let A attend to B's private prompt.
What can be combined is execution work. At a decode step, the engine can process a new position from A, one from B, and one from C together. The same resident weights are used across the work, while each request accesses its own context state.
This gives the GPU more useful work per batch and can improve aggregate throughput. But A's next token still depends on A's previous selected token. Batching does not remove sequential dependence inside a response.
Requests do not finish together
In a simple static batch, membership is fixed for that batch. New requests wait for the batch to finish rather than replacing completed members immediately. This can leave useful execution opportunity unused while long requests continue.
Continuous batching updates active work at scheduling boundaries. A can leave when it finishes, and D can be admitted while B and C continue. The engine does not need all members to begin and end together.
Notice that D does not automatically accelerate B or C. It adds work and may improve overall hardware use. Whether existing users see better or worse token timing depends on the resulting execution and scheduling.

Keep this distinction
Continuous batching changes membership. Chunked prefill controls how new prompt work shares execution.
A long new prompt should not monopolize every turn
Imagine that B and C are streaming answers when D arrives with a very long prompt. If the engine spends a large uninterrupted interval processing D's entire prefill, B and C can experience a long gap before their next tokens.
Chunked prefill divides that prompt-processing work into smaller pieces. A scheduler can interleave pieces with decode work, allowing existing responses to keep advancing while the new prompt is processed.
The prompt is still one context. We are not treating its pieces as independent conversations or asking the model to forget earlier chunks. We are dividing execution work so it can be scheduled more flexibly.
Mechanism reference: source 3.
Does chunked prefill make a long prompt into several unrelated prompts?
No. The context remains connected. The engine schedules portions of the processing work while preserving the state needed to continue the same prompt.
Chapter 6
Measuring and Improving Performance
Give “fast” three different meanings
A user says the assistant is slow. That observation is useful, but incomplete. Did nothing appear for a long time? Did text start quickly and then crawl? Or did the service complete too little work for all users together?
Time to first token (TTFT) measures the wait before output begins. At the client, this can include transport, queueing, preprocessing, prefill, and delivery. Engine-only timing may use a narrower boundary, so state what you measured.
Output throughput measures total output tokens per unit time across the measured work. It describes system productivity, not the experience of one request.
Consider hypothetical steady generation. One request produces 40 tokens per second, around 25 milliseconds between tokens. With three requests, each produces 20 tokens per second, around 50 milliseconds between tokens. Total output is now 60 tokens per second. Throughput improved, but each user's generation slowed.
A fair benchmark changes one thing on purpose
Suppose engine A is tested with one active request, while engine B is tested with three. B produces more total tokens per second. Can we attribute the improvement to B? Not yet. Both the engine and concurrency changed.
Compare A and B at concurrency one, then compare them at concurrency three. Keep the hardware, model, precision, prompt set, output lengths, and cache conditions comparable. If the goal is instead to compare complete deployments with different formats, say so and evaluate quality as well. Different experiments answer different questions.
A fixed-concurrency test also does not fully describe a live service. Real requests arrive over time, sometimes in bursts. To understand queueing, test arrival patterns and measure waiting from the user's perspective, not only active engine execution.
Why does equal output length matter when comparing decode?
It controls the number of decode steps and helps keep the growth of context comparable. Otherwise one test may spend more time decoding at larger contexts than another.
A symptom is not yet a bottleneck diagnosis
We increase concurrency and observe that throughput barely changes, while ITL gets worse. This supports a practical conclusion: extra concurrency provides little benefit in this tested configuration. It does not prove that compute is fully utilized.
The next step is a targeted experiment or profile. Lower concurrency while keeping workload comparable. If throughput stays nearly the same and ITL improves, the lower setting may be preferable for interactive use. Then check queue time, because less active work can increase waiting outside the engine.
Likewise, a longer prompt that increases TTFT shows sensitivity to prompt work, but does not by itself identify a specific hardware bottleneck. A useful investigation separates what was observed, what is hypothesized, and what evidence would distinguish the hypotheses.
Chapter 7
Building a Predictable Service
A good average can hide unhappy users
We need a target for “acceptable.” A service-level objective, or SLO, turns that judgment into a measurable goal. For example: 95% of eligible requests should receive a first token within three seconds, including queue time, over a specified reporting window.
A mean TTFT of one second does not prove that target is met. The mean adds all waits and divides by request count. Very fast requests can offset slow ones without telling us how many users crossed the threshold.
This is why the best concurrency setting depends on the application. A batch job may value total throughput. An interactive assistant may prioritize first output and smooth continuation. The target makes the trade-off explicit.
Keep this distinction
Judge the whole wait: first output, continuation, queueing, and failures.
Three active slots do not control 100 arrivals
Our service permits three active requests. One user sends 100 at once. The active limit does not decide what happens to the other 97. Without additional policy, they can fill a queue and make everyone else wait.
Admission control decides whether new work is accepted, queued, or rejected. A queue limit bounds waiting work. A queue timeout bounds how long it remains useful to wait. Per-user active and queued limits prevent one person from occupying the whole service. Fair scheduling can take turns across users instead of draining one user's backlog first.
A hypothetical policy allows one active request and two queued requests per user, within global capacity. Of 100 simultaneous submissions from that user, one runs, two wait, and 97 are rejected if those admission slots are available. The numbers are illustrative. The lesson is that waiting should be bounded and explained.
If a user cancels, remove queued work or stop active generation and release resources no longer needed. A cancel button that only hides the answer leaves the GPU working on output nobody wants.
An occasional queue is not automatically a failure
Traffic is rarely perfectly steady. A short burst can create a queue even when the service has enough capacity for normal demand. After the burst ends, completions catch up and the queue empties.
That can be normal and useful. A queue absorbs temporary imbalance. The question is whether waiting stays within the service target and the backlog recovers, not whether the queue is always empty.
Persistent overload is different. If comparable work arrives faster than it can be completed over time, backlog grows until a limit is reached. Increasing queue size does not increase execution capacity. It only permits more waiting.
Streaming and readiness complete the user journey
Streaming lets the user read partial output before the full answer finishes. That makes waiting more useful, but does not automatically make model computation faster. If output arrives faster than the user reads, later text can be ready when needed; this depends on the user and content.
Before any of this works, the instance must be ready. A live API process is not necessarily a ready model. During startup, the server may exist while weights are still loading or the engine is warming up. If loading fails, inference traffic should not be routed there.
Readiness is different from capacity. An initialized engine with full active slots may still be healthy and ready in a technical sense; admission control handles the load. A deterministic out-of-memory load failure also will not be fixed by restarting the same configuration indefinitely.
Chapter 8
Putting It All Together
Return to the assistant: make a decision, not just a measurement
Consider the final hypothetical case. The model loads. One request runs smoothly. At concurrency three, throughput rises, ITL worsens, and memory remains sufficient. This is not a readiness failure or evidence of exhausted VRAM. It is a performance trade-off.
The decision depends on the service target. If first-output time, continuation latency, quality, and failure rates remain acceptable, the configuration may be worth keeping. If not, tune or change the deployment and measure again. Include queue time so an apparent engine improvement does not merely move waiting elsewhere.
This guide is a foundation rather than a deployment runbook. Sampling, quantization mechanisms and quality, GPU kernels, paged cache management, prefix caching, speculative decoding, and multi-GPU execution are useful next studies. Practical benchmarking connects the mental models here to a specific system.
Teach back the whole chain: why can a model fit but still fail or feel slow?
Weights are only part of memory; active caches and runtime work also need space. Execution can be limited by data movement, compute, or scheduling. Batching can improve aggregate work while worsening per-user latency. Queues and delivery add waiting beyond engine time. A useful service must satisfy targets across the whole path.
Serving policies and worked scenarios are engineering explanations and hypothetical examples, not prescribed settings. Validate engine behavior against the version you actually deploy.
Sources
- 1.Hugging Face: How caching works
Per-layer K/V reuse, causal attention, and incremental generation.
- 2.Ainslie et al.: GQA
Query/KV head sharing and the relationship between MHA, GQA, and MQA.
- 3.vLLM: Optimization and tuning
Chunked prefill, performance trade-offs, cache allocation, and preemption. Defaults are version-specific; this guide intentionally does not prescribe flags.