Forward Deployed EngineeringAI EngineeringLLM Inference
Walk me through what actually happens when an LLM generates a response.
Question 11 of 13 · Updated
On this page
Interview-ready answer#
An LLM typically generates text autoregressively: it predicts the next token conditioned on the input and previously generated tokens, then repeats. In a decoder-only transformer, the request is first serialized into the model's chat format and tokenized into integer IDs. The model maps those IDs to embeddings, incorporates positional information, and runs them through transformer layers containing causal self-attention and feed-forward networks. The final hidden representation is projected into vocabulary-sized logits.
During prefill, the model processes the input prompt in parallel across token positions, subject to the causal attention mask, and computes the first next-token distribution while storing attention keys and values in a KV cache. A decoding strategy selects a token from the logits. During subsequent decoding steps, the model processes the newly selected token and uses the cached keys and values instead of recomputing the entire prefix. Generation continues until a stop condition is reached, and the output tokens are decoded into text and optionally streamed to the user.
From a production perspective, prefill heavily influences time to first token, while decoding, memory bandwidth, cache capacity, batching, and output length affect subsequent token latency and throughput. I would measure both phases separately before optimizing.
The inference pipeline#
Messages + instructions + optional retrieved context
-> Chat template -> Tokenizer -> Token IDs
-> Embeddings + positional information
-> Transformer blocks (causal attention + MLP)
-> Output projection -> Next-token logits
-> Token selection -> Append token -> Decode text
|
+-> Repeat using KV cache
until stop conditionThis describes conventional autoregressive decoder-only transformers; encoder-decoder, multimodal, and other model architectures can differ. The serving application may also perform tool calls, safety checks, retrieval, or additional model passes.
1. Tokenization and embeddings#
The tokenizer converts text into a sequence of vocabulary IDs, often using subword or byte-based units. A token is not necessarily a word: punctuation, spaces, and portions of words can be separate tokens. Chat templates add role markers and other special tokens. Token counts depend on the model's tokenizer and input language.
An embedding lookup converts each token ID into a dense vector of the model's hidden dimension. Positional information is incorporated using the architecture's chosen method, such as rotary position embeddings (RoPE) applied to attention queries and keys. Without position-sensitive processing, the model cannot distinguish sequence order in the intended way.
2. What happens inside the transformer#
Each transformer block commonly contains self-attention, a feed-forward network (MLP), normalization and residual connections. Attention allows a token representation to incorporate information from earlier tokens. Learned projections create query (Q), key (K) and value (V) vectors. For standard scaled dot-product attention:
Attention(Q, K, V) = softmax(QK^T / sqrt(d_k) + M) VHere is the key dimension and M is a causal mask that blocks attention to future positions. Query-key similarity determines attention weights, which combine value vectors. Multiple attention heads learn different interactions. The MLP transforms each token representation independently, while residual connections and normalization help information flow across layers. The exact normalization placement, attention head arrangement, and MLP design depend on the architecture.
After the final layer, the language-model head maps the final position's hidden state to one logit per vocabulary token. A logit is an unnormalized score, not a probability. Applying softmax to logits produces a categorical distribution; logits can first be modified by decoding controls.
3. Prefill versus decoding#
| Phase | What happens | Main serving considerations |
|---|---|---|
| Prefill | Process prompt tokens and populate layer-wise KV caches; compute first next-token logits | Prompt length, compute, attention cost, time to first token |
| Decode | Process each new token using prior cached keys and values; append newly computed K/V | Memory bandwidth, cache size, concurrency, inter-token latency |
For ordinary dense causal attention, prefill attention work grows quadratically with prompt length (holding model dimensions fixed). With KV caching, each subsequent token's attention work grows roughly linearly with the current sequence length; the model still computes new projections, attention and MLP operations for that token. Optimized attention kernels, sparse or sliding-window attention, batching and model architecture change practical costs.
Autoregressive token selection is sequential within a request because later tokens depend on earlier selected tokens. Across requests, the inference server can batch work; speculative decoding can also propose and verify multiple tokens to accelerate generation under suitable conditions.
4. Logits, sampling and stopping#
- Greedy decoding: Select the highest-logit token. It is usually repeatable under fixed conditions, but serving implementations need not guarantee bitwise determinism.
- Temperature: For T > 0, divide logits by T before softmax. Lower T sharpens the distribution; higher T flattens it. Greedy selection is the limiting behavior as T approaches zero.
- Top-k: Restrict sampling to the k highest-scoring candidates.
- Top-p (nucleus sampling): Restrict sampling to the smallest set of highest-probability tokens whose cumulative probability reaches p, then renormalize and sample.
The selected token is appended to the sequence. Generation stops on an end-of-sequence token, configured stop condition, output-token limit, or cancellation. Tool-call generation may instead return a structured request to the application, which executes an authorized tool and feeds the result back into a later model call. Inference does not normally update the model weights or automatically store new facts in its parameters.
5. Why the KV cache matters#
Without caching, naive generation repeatedly processes the entire growing prefix. The KV cache stores previously computed keys and values for every attention layer so subsequent steps can reuse them. It does not cache the final answer or eliminate all attention computation.
For a conventional transformer with uniform cache dimensions, approximate KV cache memory per sequence is:
2 × layers × cached_tokens × KV_heads × head_dim × bytes_per_elementThe factor 2 accounts for keys and values. For an illustrative model with 32 layers, 8 KV heads, head dimension 128, and 2-byte cache elements, the cache uses 128 KiB per token, or about 1 GiB for 8,192 cached tokens. This excludes model weights, activations, allocation overhead and other serving memory. Grouped-query attention reduces KV head count; quantized caches can reduce element size; paging reduces allocation waste. Sliding-window or nonstandard cache architectures can change the formula. Concurrent sequences consume additional cache capacity, subject to any safe prefix sharing.
6. Production inference trade-offs for an FDE#
Suppose a customer reports that its assistant takes several seconds to start answering after large documents are added to every prompt. I would measure queue time, tokenization and prompt size, prefill time, time to first token (TTFT), inter-token latency, output length, requests per second, GPU memory and cost per successful task.
If long prompts are the bottleneck, improve retrieval and context selection, remove redundant history, and consider safe prefix caching for repeated identical prefixes. If decode is slow, profile memory bandwidth, model size, cache pressure and batching. Continuous batching can improve aggregate throughput, but aggressive batching can hurt individual request latency. Weight quantization may improve memory use and speed, depending on hardware and kernels; verify quality on customer tasks. Streaming improves perceived responsiveness but does not necessarily reduce total generation time.
I would set customer-specific latency and quality objectives, benchmark representative prompt/output lengths at realistic concurrency, enforce token budgets, and isolate cached data across authorization boundaries. Higher sampling temperature does not improve factual accuracy by itself. Retrieval, validated tool results, and appropriate abstention are often needed for factual enterprise answers.
Likely interviewer follow-ups#
- Why is prefill parallel but decode sequential? The input tokens are already known, so their layer computations can be batched with a causal mask. New output tokens must first be selected before their successors can be computed.
- Does KV caching make generation constant-time? No. New queries still attend to cached keys and values; full-attention work per new token grows with context length.
- Why do two identical prompts produce different answers? Sampling randomness, configuration differences and numerical or serving variation can affect token selection.
- How would you reduce inference cost? Start with measured workload bottlenecks; evaluate shorter context, output limits, smaller suitable models, caching, quantization and batching against quality and latency requirements.
References
- 1.
- 2.
- 3.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models