97 LLM Inference Interview Questions and Answers (2026)

Blog / 97 LLM Inference Interview Questions and Answers (2026)
LLM Inference interview questions and answers

Every token a model generates costs GPU time, and teams shipping LLM products are judged on latency, throughput, and cost per request. That's why interviewers no longer settle for "I've called an API." They want you to explain why decode is memory-bound, how a KV cache eats HBM, and what continuous batching actually buys you. Walk in shaky on the fundamentals and a single roofline question can sink the whole loop.

This guide gives you 97 questions with concise, interview-ready answers, plus code and back-of-the-envelope math where it helps. It's organized Junior → Mid → Senior, so you start with prefill vs. decode and FLOPs per token and build up to paged attention, quantization, speculative decoding, and disaggregated serving. Work through it in order and you'll answer from understanding, not memorization.

Q1.How many FLOPs per parameter are required to process a single token in a forward pass?

Junior

Roughly 2 FLOPs per parameter per token: each weight takes part in one multiply and one add (a multiply-accumulate) in the matrix multiplications. A 7B model therefore needs about 14 GFLOPs per token in a forward pass.

  • Where the 2 comes from:

    • A linear layer computes y = Wx. For a d_in × d_out weight matrix, one token costs d_in·d_out multiplies plus about as many adds, so 2 FLOPs per weight.

    • Nearly all parameters sit in these matmuls (QKV/output projections, MLP), so the rule is FLOPs ≈ 2N per token.

  • The attention term sits on top of the parameter count:

    • QKᵀ and attention·V add about 2·n_layers·n_ctx·d_model FLOPs per token (Kaplan et al.).

    • This is small next to 2N at short contexts. It becomes significant at very long contexts.

  • Related rules of thumb:

    • Training costs about 6N per token: forward 2N, plus backward 4N (gradients with respect to activations and to weights).

    • For MoE models, N means active parameters per token, not total parameters.

  • Why interviewers ask: Combined with bytes per parameter, this gives the arithmetic intensity of decode: about 2 FLOPs per 2 bytes in FP16, or roughly 1 FLOP/byte at batch 1. That number is why decode is memory-bound.

Q2.What is the difference between the prefill phase and the decode phase in LLM inference?

Junior

Prefill processes the entire prompt in one parallel forward pass and builds the KV cache. Decode then generates output tokens one at a time, each step reusing that cache. Prefill is compute-bound and determines time-to-first-token (TTFT). Decode is memory-bandwidth-bound and determines time-per-output-token (TPOT).

  • Prefill:

    • All N prompt tokens go through the model at once as large matrix-matrix multiplies (GEMMs).

    • It writes K and V for every prompt token into the KV cache and produces the first output token.

    • Weights are reused across N tokens, giving high arithmetic intensity. The GPU's tensor cores are well utilized, and latency scales with prompt length.

  • Decode:

    • It is autoregressive: each step feeds one new token per sequence, so the work is matrix-vector multiplies (GEMVs).

    • Every step must read all weights plus that sequence's KV cache from HBM, yet does very little math with them.

    • It is memory-bound. Batching many sequences raises throughput because the weight reads are shared across them.

  • Metrics and scheduling consequences:

    • TTFT is dominated by prefill. Inter-token latency (TPOT) is dominated by decode.

    • A long prefill can stall in-flight decodes. Chunked prefill splits the prompt and mixes chunks with decode steps.

    • Prefill/decode disaggregation runs the two phases on separate GPU pools so each can be tuned independently (e.g. DistServe, Splitwise).

Q3.What does arithmetic intensity represent in LLM inference?

Junior

Arithmetic intensity is the number of FLOPs performed per byte moved from memory (FLOPs/byte). Comparing it to the hardware's ratio of peak compute to memory bandwidth tells you whether an operation is limited by compute or by memory bandwidth. That comparison is the core diagnostic for LLM inference performance.

  • Definition: AI = FLOPs / bytes accessed

  • Hardware ridge point: peak FLOPs / memory bandwidth:

    • H100 SXM: about 989 TFLOPs (dense BF16) / 3.35 TB/s ≈ 295 FLOPs/byte.

    • If AI is below the ridge point, the operation is memory-bound. If it is above, the operation is compute-bound.

  • Applied to LLM phases:

    • Decode at batch 1: each FP16 weight (2 bytes) does 2 FLOPs, so AI ≈ 1. That is far below the ridge, so the GPU mostly waits on memory.

    • Batch B in decode: weights are read once and used B times, so AI ≈ B for the weight matmuls.

    • Prefill with N prompt tokens: AI ≈ N, which is often in the hundreds or thousands, so it is compute-bound.

    • Attention over the KV cache in decode: each cached byte is used about once per sequence, so AI stays low no matter the batch size.

  • Why it matters: It tells you which optimization will help. To raise AI, use batching, speculative decoding, or kernel fusion. To cut bytes, use quantization or GQA. To raise FLOPs, use better kernels, but only when you are already compute-bound.

Q4.What is the difference between time to first token and time per output token?

Junior

Time to first token (TTFT) is the wait from sending a request until the first output token arrives. It is dominated by queueing plus prefill. Time per output token (TPOT) is the average time to generate each subsequent token, which is set by the decode loop. TTFT is the user's "is it responding?" delay; TPOT is the streaming speed.

  • TTFT:

    • Includes network, tokenization, scheduler queueing, and the prefill forward pass over the whole prompt.

    • Grows with prompt length and load. Prefill is compute-bound.

  • TPOT:

    • Defined as (E2E latency − TTFT) / (output tokens − 1), an average per request.

    • Driven by decode steps, which are memory-bandwidth-bound and sensitive to batch size and KV cache size.

  • How they combine: E2E ≈ TTFT + TPOT × (N − 1), so short answers are TTFT-dominated and long answers are TPOT-dominated.

  • Different optimizations target each:

    • TTFT: prefix caching, chunked prefill, and more compute or tensor parallelism.

    • TPOT: quantization, speculative decoding, and smaller batches.

Q5.What is the difference between per-user tokens per second and per-GPU throughput?

Junior

Per-user tokens per second is the streaming speed one request experiences (≈ 1/TPOT). Per-GPU throughput is the total tokens per second a GPU produces across all concurrent requests. Batching raises the second while usually lowering the first, so one measures user experience and the other measures cost.

  • Per-user TPS:

    • Determined by how long one decode step takes. It is highest at batch size 1.

    • Needs to beat reading speed (~5–10 tok/s) for chat, and much more for agents and code tools.

  • Per-GPU throughput:

    • Roughly per-user TPS × concurrent sequences ÷ GPUs in the replica.

    • Determines $/token. Larger batches amortize the weight reads, so throughput climbs until compute or KV memory saturates.

  • Why they diverge:

    • Going from batch 1 to 64 can raise GPU throughput by tens of times while each step gets somewhat slower, so each user sees fewer tok/s.

    • Tensor parallelism across more GPUs raises per-user speed but often lowers per-GPU throughput because of communication overhead.

  • In practice, plot the Pareto curve (per-user tok/s vs per-GPU tok/s) and pick the point that meets the latency SLO at the lowest cost.

Q6.How do you calculate the memory footprint of the KV cache for a single sequence?

Junior

Multiply the per-token cost by the sequence length. Each layer stores one key vector and one value vector per KV head for every token. So bytes = 2 × layers × KV heads × head dim × sequence length × bytes per element.

python
def kv_cache_bytes(n_layers, n_kv_heads, head_dim, seq_len, bytes_per_elem=2, batch=1): # 2 = one K and one V tensor return 2 * n_layers * n_kv_heads * head_dim * seq_len * bytes_per_elem * batch # Llama-2-7B (MHA): 32 layers, 32 KV heads, head_dim 128, fp16 kv_cache_bytes(32, 32, 128, 4096) # ~2.1 GB (0.5 MB per token) # Llama-3-8B (GQA): 32 layers, 8 KV heads kv_cache_bytes(32, 8, 128, 4096) # ~0.5 GB (128 KB per token)

Q7.How does a KV cache reduce the per-token compute cost of autoregressive generation?

Junior

The KV cache stores the keys and values of all previous tokens. Each decode step then pushes only the one new token through the model, instead of re-running the whole prefix. It trades memory for compute.

  • Without a cache, step t recomputes everything:

    • All t tokens go through every layer again: the QKV projections, the MLP, and attention.

    • Cost per step is roughly O(t·d² + t²·d).

    • Summed over a generation of length n, that is about cubic in n.

  • With a cache, only the new token is processed:

    • The model computes q, k and v for the new token only, then appends its k and v to the cache.

    • Its query attends over all cached keys and values.

    • Cost per step is O(d²) for the projections and MLP plus O(t·d) for attention.

  • Why reuse is valid:

    • The causal mask means past tokens never see future ones.

    • So their keys and values never change once computed.

  • Consequences:

    • Memory grows linearly with sequence length and batch size.

    • Decode becomes memory-bandwidth bound: each step reads all weights plus the whole cache to do very little math.

    • Prefill still processes the full prompt in parallel to build the cache.

Q8.Why do we only cache keys and values instead of query vectors?

Junior

Under causal attention, a past token's query is used exactly once: to compute that token's own output. Past keys and values, by contrast, are read by every future query. Only K and V are ever reused, so only they are worth caching.

  • How each decode step works:

    • The output at step t is softmax(q_t · K_{≤t}ᵀ / √d) · V_{≤t}.

    • It needs the current query plus every past key and value.

  • Past outputs are already final:

    • Thanks to the causal mask, a new token cannot change earlier tokens' attention outputs.

    • So there is never a reason to recompute old queries.

  • Caching Q would be pure waste: It would add memory and bandwidth cost for data that is never read again.

  • Caveat:

    • This relies on causality.

    • In bidirectional encoders, every token's representation depends on all other tokens, so incremental KV caching does not apply the same way.

Q9.Why does static pre-allocation of KV cache buffers waste GPU memory?

Junior

Static allocation reserves a contiguous buffer sized for the maximum sequence length for every request, because output length is unknown in advance. Most of that reserved memory never holds real tokens, and it blocks other requests from running.

  • Internal fragmentation: A request that stops at 200 tokens inside a 4096-token slot wastes the remainder for its whole lifetime.

  • Reservation waste: Slots for future tokens sit idle until those tokens are generated, if they ever are.

  • External fragmentation:

    • Variable-size contiguous chunks leave gaps.

    • Free memory can exist yet be too scattered to fit a new buffer.

  • Impact:

    • The vLLM paper found only about 20–38% of KV memory held actual token states in prior systems.

    • Wasted memory means smaller batches, and decode throughput depends heavily on batch size.

    • Contiguous per-request buffers also prevent sharing KV across requests, for example common prefixes or parallel samples.

  • The fix: Allocate on demand in small fixed-size blocks (PagedAttention).

Q10.What is the difference between static batching and continuous (in-flight) batching?

Junior

Static batching groups requests and runs the whole batch until every sequence finishes. Continuous (in-flight) batching schedules at the level of each decode iteration: finished sequences leave the batch and new ones join immediately, so GPU slots stay full.

  • Static batching (request-level):

    • The batch is fixed at launch. Short sequences finish early, but their slots sit idle (or padded) until the longest sequence completes.

    • New arrivals wait for the entire batch to drain, which inflates queueing latency and time to first token (TTFT).

    • Works acceptably when output lengths are uniform, for example offline jobs with fixed max tokens.

  • Continuous batching (iteration-level, from the Orca paper):

    • After every forward step, the scheduler evicts sequences that emitted EOS or hit their max length, then admits waiting requests (running their prefill).

    • There is no padding to the longest output, and utilization stays high under variable lengths.

    • This gives much higher throughput and lower queueing delay. It is the default in vLLM, TGI, TensorRT-LLM and SGLang.

  • What continuous batching requires:

    • Dynamic KV-cache memory management (e.g. PagedAttention), because sequences join and leave constantly.

    • Kernels that handle ragged batches mixing prefill and decode tokens.

    • A policy for preemption when memory runs out.

Q11.What is the difference between post-training quantization and quantization-aware training for deployment?

Junior

Post-training quantization (PTQ) quantizes an already-trained model using a small calibration set, with no retraining. Quantization-aware training (QAT) simulates quantization during training or fine-tuning so the weights learn to tolerate it. PTQ is cheap and fast. QAT costs training compute but recovers accuracy at aggressive bit-widths.

  • PTQ:

    • Calibrate scales and zero-points from a few hundred samples. Smarter variants (GPTQ, AWQ, SmoothQuant) reduce the error.

    • Takes minutes to hours and needs no training pipeline. This is the default for LLMs.

    • Works well at INT8/FP8 and W4 weight-only. Quality degrades at 3-bit or below, or with full low-bit activations.

  • QAT:

    • Inserts fake-quant (quantize then dequantize) ops in the forward pass.

    • Gradients pass through the rounding step via the straight-through estimator.

    • The model adapts to rounding noise, giving better accuracy at INT4/INT2.

    • Costs: training data, compute, and engineering effort. Expensive at LLM scale, though partial QAT and LoRA-based variants exist.

  • How to choose:

    • Start with PTQ and evaluate it.

    • Move to QAT only if PTQ's accuracy loss is unacceptable at the bit-width your hardware or memory budget requires.

Q12.What is operator fusion?

Junior

Operator fusion combines several consecutive operations into a single GPU kernel so intermediate results stay in registers or shared memory instead of being written to and re-read from HBM, and so fewer kernels are launched.

  • Without fusion: Each op (e.g. matmul → bias add → GELU) is a separate kernel that reads inputs from HBM and writes outputs back.

  • With fusion: One kernel loads data once, applies all ops on-chip, writes the final result once.

  • Common LLM examples:

    • Residual add + RMSNorm; SwiGLU activation; QKV projection as one GEMM; RoPE into attention; GEMM epilogues (bias, activation, dequant).

    • FlashAttention is fusion of QKᵀ, softmax, and ·V into one tiled kernel.

  • How it's done: Hand-written CUDA/Triton kernels, or compilers like torch.compile (Inductor), TensorRT, XLA.

  • Tradeoff: fused kernels are less flexible and harder to maintain; fusing ops with incompatible parallelization can hurt occupancy.

Q13.What are CUDA Graphs?

Junior

CUDA Graphs let you record a sequence of GPU operations (kernels, memcpys) once and replay the whole sequence with a single launch, removing per-kernel CPU launch overhead and driver work.

  • Capture: Run the workload under stream capture; CUDA records kernels and dependencies into a graph instead of executing them.

  • Instantiate and replay: The graph is compiled into an executable graph; each cudaGraphLaunch replays it with near-zero CPU cost.

  • Constraints:

    • Static shapes and fixed memory addresses: inputs must be copied into the same buffers before replay.

    • No data-dependent control flow or CPU sync inside the captured region.

  • In LLM serving:

    • vLLM, SGLang, TensorRT-LLM capture decode graphs for a set of batch sizes and pad to the nearest one; prefill (variable length) usually runs eagerly.

    • Cost: capture time at startup and extra memory per captured graph.

python
g = torch.cuda.CUDAGraph() with torch.cuda.graph(g): static_out = model(static_in) # captured, not run eagerly static_in.copy_(new_in) # write new data into the same buffer g.replay() # one launch for all kernels

Q14.What are the main components of GPU memory usage when serving an LLM?

Junior

GPU memory holds model weights, the KV cache, transient activations and workspace buffers, and runtime overhead. Weights are fixed. The KV cache gets whatever is left, and it is what limits concurrency and context length.

  • Model weights:

    • Size is params × bytes per param: about 2 bytes in FP16/BF16, 1 in FP8/INT8, about 0.5 in INT4. A 70B model in FP16 is about 140 GB.

    • Divided across GPUs by TP, PP, or EP.

  • KV cache:

    • Per token: 2 × layers × kv_heads × head_dim × bytes. For Llama-3-70B (GQA, 8 KV heads) that is about 320 KB/token in FP16.

    • Grows linearly with batch size × sequence length. It is usually the largest dynamic consumer.

    • Paged allocation (PagedAttention) reduces fragmentation, and FP8 KV halves the per-token size.

  • Activations and workspace:

    • Intermediate tensors from the forward pass, which peak during large prefill batches.

    • Logits buffer (batch × vocab, which is large for 128K+ vocabularies), plus GEMM and attention kernel workspaces and sampling buffers.

  • Runtime overhead:

    • CUDA context, cuBLAS/cuDNN handles, NCCL communication buffers, and CUDA graph memory pools, typically a few GB per GPU.

    • Allocator fragmentation and caching.

  • Optional extras: LoRA adapters, a speculative-decoding draft model, and multimodal encoders.

  • How engines budget it: vLLM loads weights, profiles peak activation memory with a dummy batch, then gives the rest (up to gpu_memory_utilization) to KV cache blocks.

Q15.How do you estimate the minimum number of GPUs needed to serve a 70B parameter model in FP16?

Junior

Add up weights + KV cache budget + overhead, divide by usable memory per GPU, then round up to a valid parallelism degree. A 70B model in FP16 needs about 140 GB for weights alone. On 80 GB GPUs that technically fits on 2, but practically you need 4 to leave room for the KV cache.

  1. Weights: 70B × 2 bytes ≈ 140 GB.

  2. KV cache (set by your workload target):

    • Llama-3-70B: 2 × 80 layers × 8 KV heads × 128 head_dim × 2 bytes ≈ 320 KB/token.

    • Example: 32 concurrent requests × 4K tokens = 128K tokens, about 42 GB.

  3. Overhead: Activations, CUDA context, NCCL buffers, and CUDA graphs: plan for about 2–5 GB per GPU, or roughly 10% headroom.

  4. Divide and round:

    • Total is about 140 + 42 + 10 ≈ 192 GB. At about 72 GB usable per 80 GB GPU, that is roughly 2.7, so 3 GPUs.

    • TP degree must divide the attention and KV head counts (64 and 8), so round up to TP=4.

  • Interview nuances:

    • 2× 80 GB is the absolute minimum to hold the weights, but it leaves only a few GB for KV: very low concurrency and short contexts.

    • Memory per GPU changes the answer: 2× H200 (141 GB) or 2× MI300X (192 GB) is comfortable.

    • Quantization shifts it too: FP8 gives about 70 GB of weights, which barely fits on 1× 80 GB but comfortably on 2. INT4 is about 35–40 GB.

    • Memory sets the minimum. Throughput and latency targets may require more replicas.

Q16.Why is the prefill phase compute-bound while the decode phase is memory-bandwidth bound?

Mid

The difference is data reuse. Prefill loads each weight once and applies it to every prompt token, so it does a lot of math per byte. Decode loads every weight (and the KV cache) to process just one token per sequence, so its arithmetic intensity falls far below the GPU's ridge point.

  • Prefill means many tokens per weight load:

    • An input of shape [N, d] times a weight of shape [d, d] is a GEMM with about 2·N·d² FLOPs over about 2·d² bytes of weights, so AI ≈ N.

    • With a prompt of a few hundred tokens or more, AI exceeds the ridge point (about 300 FLOPs/byte on an H100), so tensor cores become the bottleneck.

  • Decode means one token per weight load:

    • The work is a GEMV: about 2·d² FLOPs over 2·d² bytes, so AI ≈ 1 FLOP/byte at batch 1.

    • Step time ≈ bytes read / HBM bandwidth. The compute units sit mostly idle.

  • Why batching only partly fixes decode:

    • Batching B sequences shares the weight reads, giving AI ≈ B. It pushes the weight matmuls toward compute-bound once B reaches the hundreds.

    • KV-cache reads are per-sequence and are never shared, so decode attention stays memory-bound and grows with context length.

    • KV memory also caps the maximum batch size, which in practice keeps decode memory-bound.

Q17.How does HBM bandwidth dictate the theoretical maximum decoding speed?

Mid

Every decode step must stream all model weights (plus the KV cache) from HBM to the compute units. Single-stream speed is therefore capped at about tokens/s ≈ HBM bandwidth / bytes read per token, regardless of how many FLOPS the GPU has.

  • The bound:

    • Bytes per token ≈ params × bytes_per_param + KV cache bytes.

    • Minimum step time ≈ bytes / bandwidth. Its inverse is the ceiling on tokens/s.

  • Worked examples (H100, 3.35 TB/s):

    • 7B in FP16 is about 14 GB, giving roughly 240 tok/s as a ceiling.

    • 70B in FP16 is about 140 GB (and needs at least 2 GPUs). Per-GPU it works out to roughly 24 tok/s; with tensor parallelism across 2 GPUs, aggregate bandwidth doubles to about 48 tok/s.

    • Real systems reach roughly 60–85% of peak bandwidth because of kernel overheads, communication, and launch latency.

  • Levers that follow from the bound:

    • Fewer bytes: weight quantization (INT8/INT4 roughly 2–4× fewer bytes), KV-cache quantization, and GQA/MQA.

    • More bandwidth: tensor parallelism sums bandwidth across GPUs, and newer HBM helps (H200 4.8 TB/s, B200 about 8 TB/s).

    • More tokens per weight read: speculative decoding verifies k draft tokens in one pass.

    • Batching raises aggregate throughput, not single-stream speed. Each stream still waits for a full weight sweep per step.

Q18.What is the difference between compute-bound and memory-bound operations under the roofline model?

Mid

The roofline model caps attainable performance at min(peak FLOPs, arithmetic intensity × memory bandwidth). An operation is memory-bound when its arithmetic intensity is below the hardware ridge point. It is compute-bound when its intensity is above it.

  • Shape of the roofline:

    • The x-axis is arithmetic intensity (FLOPs/byte) and the y-axis is attainable FLOPs/s.

    • The slanted part is bandwidth × AI, where memory is the limit. The flat part is peak compute.

    • The ridge point, peak FLOPs / bandwidth, is where they meet. It is about 295 FLOPs/byte for an H100 in BF16.

  • Memory-bound operations:

    • Runtime ≈ bytes / bandwidth, and the ALUs sit idle waiting for data.

    • LLM examples: decode GEMVs at small batch, decode attention over the KV cache, and elementwise ops such as LayerNorm, activations, and residual adds.

    • Fixes: move fewer bytes (quantization, kernel fusion, FlashAttention-style tiling) or raise reuse (batching).

  • Compute-bound operations:

    • Runtime ≈ FLOPs / peak FLOPs, and memory keeps up.

    • LLM examples: prefill GEMMs, large-batch decode matmuls, and training.

    • Fixes: lower-precision tensor cores (FP8/FP4), better kernels, sparsity, or simply fewer FLOPs.

  • Key insight: applying the wrong optimization does nothing. Adding FLOPS to a memory-bound kernel leaves its runtime unchanged.

Q19.Why does a GPU with higher compute FLOPS but identical memory bandwidth fail to accelerate single-stream token generation?

Mid

Single-stream decode is memory-bandwidth-bound. Each step's time is set by how fast weights and the KV cache can be read from HBM, not by how fast they can be multiplied. Raising peak FLOPS lifts the flat roof of the roofline, but decode sits far down on the slanted, bandwidth-limited part.

  • The math:

    • At batch 1, AI ≈ 1 FLOP/byte (FP16), versus a ridge point of about 300 on modern GPUs.

    • Step time ≈ max(FLOPs/peak_FLOPs, bytes/bandwidth). The bandwidth term is already about 100× larger.

    • Doubling FLOPS halves a term that was already negligible, so latency stays essentially the same.

  • It actually lowers utilization: The ridge point moves right (more FLOPs per byte are needed to saturate the chip), so decode uses an even smaller fraction of the compute.

  • Real-world illustration: H100 to H200 keeps roughly the same compute but raises bandwidth from 3.35 to 4.8 TB/s, and decode gets meaningfully faster.

  • What does help single-stream decode:

    • More bandwidth: newer HBM, or tensor parallelism to aggregate it across GPUs.

    • Fewer bytes per token: weight and KV quantization, GQA/MQA.

    • Converting idle compute into tokens: speculative decoding (or Medusa/EAGLE) verifies several tokens per weight read.

    • Extra FLOPS do pay off for prefill and for large-batch serving throughput, where AI is high.

Q20.Why does per-token decode latency increase as the context length grows, even at a fixed batch size?

Mid

Each new token must attend over every previous token, so each decode step reads that sequence's entire KV cache from HBM. The cache grows linearly with context length, and so does the bytes-per-step cost of a memory-bound operation. Latency therefore rises even though batch size and weights are unchanged.

  • KV cache size per sequence:

    • Size = 2 (K,V) × n_layers × n_kv_heads × head_dim × bytes × seq_len.

    • Llama-2-7B (MHA, FP16) needs about 0.5 MB per token, so 32k tokens comes to about 16 GB. That exceeds the roughly 13.5 GB of weights and makes each step about twice as slow as at short context.

  • Why batching or extra compute doesn't hide it:

    • Weight reads are shared across a batch. KV reads are per-sequence and used about once, so attention's arithmetic intensity stays near 1 FLOP/byte.

    • Attention FLOPs also grow linearly with context, but bandwidth is the binding limit.

  • Secondary effects:

    • With a single query token, naive attention kernels parallelize poorly over long sequences and underuse the GPU. FlashDecoding splits the KV sequence across thread blocks to fix this.

    • Longer contexts consume KV memory, which shrinks the feasible batch size and so reduces throughput as well.

  • Mitigations:

    • Shrink the KV cache: GQA/MQA, MLA (DeepSeek), KV quantization (FP8/INT4).

    • Bound it: sliding-window or local attention, or KV eviction (e.g. StreamingLLM, H2O).

    • Note: PagedAttention reduces memory fragmentation, not the bytes read per step.

Q21.How does inter-token latency differ from time per output token?

Mid

Inter-token latency (ITL) is the gap between each pair of consecutive tokens, so it is a distribution over individual tokens. TPOT is a single per-request average of those gaps. They share a mean in spirit, but ITL exposes stalls and jitter that TPOT averages away. Some tools use the two terms interchangeably, so always check the definition.

  • Definitions:

    • TPOT = (E2E − TTFT) / (N − 1): one number per request.

    • ITL = ti − ti−1 for every token, which gives N − 1 samples per request.

  • Aggregation differs:

    • Mean TPOT across requests weights each request equally. Mean ITL across tokens weights long responses more.

    • The p99 of ITL captures individual spikes. The p99 of TPOT only flags requests that were slow on average.

  • What ITL reveals that TPOT hides: A 500 ms pause caused by another request's prefill, a preemption, or a KV swap barely moves TPOT over 500 tokens, but it shows up clearly in ITL.

  • Measurement quirks:

    • Speculative decoding and chunked streaming deliver several tokens at once. That produces near-zero ITL samples followed by a larger gap, while TPOT stays smooth.

    • Client-side ITL also includes network and SSE buffering effects.

Q22.What is the trade-off between maximizing throughput per GPU and minimizing per-user latency?

Mid

Batching more requests per GPU amortizes the cost of streaming the weights, which lowers cost per token. But every request then shares slower steps, more queueing, and more prefill interference, so per-user latency rises. Serving is about choosing a point on this Pareto curve that meets the latency SLOs at the lowest cost.

  • Why larger batches help throughput: Decode is memory-bound, so adding sequences is nearly free until you approach the compute ridge point or exhaust KV memory.

  • Why they hurt latency:

    • Step time grows as KV reads and compute increase, which raises TPOT.

    • New requests wait for slots and their prefills stall ongoing decodes, which raises TTFT and causes ITL spikes.

    • High KV occupancy leads to preemption and recomputation, which inflates tail latency.

  • Levers that move along or reshape the curve:

    • Scheduler limits such as max concurrent sequences (vLLM's max_num_seqs) and the token budget per step.

    • Parallelism: higher tensor-parallel degree lowers latency but costs throughput per GPU.

    • Speculative decoding helps at low batch sizes, where spare compute exists, and helps less or even hurts at high batch sizes.

    • Chunked prefill and prefill/decode disaggregation reduce interference, which improves both latency and throughput.

  • Choosing by workload:

    • Interactive chat: cap the batch to meet TTFT/ITL SLOs.

    • Offline or batch jobs: maximize batch size for throughput.

    • Optimize goodput rather than raw tokens per second.

Q23.Why is p99 inter-token latency a critical SLO for conversational applications?

Mid

In streaming chat, users watch tokens arrive one by one, so a single long pause feels like the system froze, even if the average speed is fine. A long response contains hundreds of gaps, so nearly every response will hit the tail at least once. That makes p99 ITL, not the mean, the metric that tracks perceived smoothness.

  • The math of tails:

    • A 500-token reply has ~500 gaps. P(at least one exceeds p99) = 1 − 0.99^500 ≈ 99%.

    • So the per-token p99 is effectively what a typical user experiences at least once per response.

  • Averages hide stalls: Mean TPOT can look healthy while sporadic 300–1000 ms freezes occur.

  • Some pipelines are especially sensitive:

    • Voice and TTS pipelines need a steady token feed, or the audio gaps or stutters.

    • Real-time agents and UIs that render progressively are also affected.

  • Common causes of ITL spikes:

    • Long prefills of newly admitted requests that block a decode step.

    • KV cache preemption or swapping, recompute, and GC or network hiccups.

  • Mitigations:

    • Chunked prefill with a per-step token budget.

    • Prefill/decode disaggregation.

    • Admission control, priority scheduling, and leaving KV memory headroom.

Q24.Why is goodput preferred over raw tokens per second as a serving metric?

Mid

Goodput counts only the requests (or tokens) completed within their latency SLOs, such as TTFT ≤ X and TPOT ≤ Y. Raw tokens per second can be inflated by overloading the server: tokens still flow, but users get unacceptable latency. Goodput therefore measures the useful work a deployment actually delivers.

  • Raw throughput is misleading:

    • Pushing batch size and request rate up keeps increasing tokens per second while TTFT and TPOT blow past acceptable levels.

    • Tokens from requests that time out or get abandoned are wasted compute, yet they still count in tokens per second.

  • Goodput aligns metrics with value:

    • Typically defined as the maximum request rate at which a target fraction of requests (e.g. 90%) meets every SLO.

    • Cost per SLO-compliant request is then the true unit cost of serving.

  • It changes design decisions:

    • Popularized for LLM serving by DistServe, where prefill/decode disaggregation raised goodput even when raw throughput looked similar.

    • It forces you to evaluate both TTFT and TPOT, because optimizing one metric alone is no longer enough.

  • Caveat: goodput depends on the SLO thresholds and the workload mix, so always report it alongside those settings.

Q25.What factors govern time to first token versus time per output token?

Mid

TTFT is governed by queueing plus prefill. Prefill is a compute-bound pass over the whole prompt, so prompt length and FLOPs dominate. TPOT is governed by decode, where each step streams the weights and KV cache from HBM. That makes memory bandwidth, model bytes, KV size, and batch size the main factors.

  • TTFT factors:

    • Prompt length: linear cost in the MLP layers plus quadratic attention for long contexts.

    • Model size and available compute: GPU FLOPs, precision, and tensor-parallel degree.

    • Queueing and the scheduler: load, admission policy, and waiting for KV memory to free up.

    • Prefix cache hits, which skip prefill for shared system prompts or history.

    • Chunked prefill: lowers interference but can lengthen a single long prompt's TTFT.

    • Overheads such as network, tokenization, and LoRA or model loading.

  • TPOT factors:

    • Memory bandwidth vs bytes read per step: TPOT ≈ (weight bytes + KV bytes) / HBM bandwidth.

    • Weight quantization and KV-reducing attention variants (GQA/MQA, FP8 KV) shrink those bytes.

    • Batch size and context length: more KV to read, and eventually compute limits.

    • Prefill interference from other requests sharing the same step.

    • Speculative decoding: produces several tokens per weight pass.

    • Tensor-parallel all-reduce cost and kernel launch overhead (reduced by CUDA graphs).

  • Key contrast: adding FLOPs helps TTFT, while adding bandwidth or cutting bytes helps TPOT. This asymmetry motivates prefill/decode disaggregation onto different hardware.

Q26.How does PagedAttention use virtual memory concepts to solve KV cache fragmentation?

Mid

PagedAttention treats the KV cache like OS virtual memory. Each sequence's cache is split into fixed-size blocks (pages) that can live anywhere in GPU memory. A per-sequence block table maps logical blocks to physical ones, and blocks are allocated only as tokens are generated.

  • The OS analogy:

    • Blocks are pages, each holding the KV of a fixed number of tokens (for example 16).

    • Sequences are processes.

    • The block table is the page table.

  • How fragmentation is solved:

    • No external fragmentation: all blocks are the same size, so any free block fits any sequence.

    • Minimal internal fragmentation: waste is limited to the last, partially filled block. The vLLM paper reports under 4% waste.

    • No reservation: a new block is allocated only when the current one fills.

  • Extra OS-style features:

    • Sharing with reference counts and copy-on-write. This covers parallel sampling, beam search and shared prompt prefixes.

    • Preemption: blocks can be swapped to CPU memory or recomputed when GPU memory runs out.

  • Cost:

    • The attention kernel must gather K and V through the block table, since memory is non-contiguous.

    • That adds a small kernel overhead.

    • It is far outweighed by larger batches: vLLM reported roughly 2–4× throughput gains over prior systems.

Q27.What is the tradeoff between small and large block sizes in PagedAttention?

Mid

Block size trades memory efficiency and sharing granularity against kernel efficiency and bookkeeping overhead. Small blocks waste less memory and share prefixes at finer granularity. Large blocks give attention kernels bigger contiguous chunks and smaller block tables. vLLM defaults to 16 tokens per block as a balance.

  • Small blocks (e.g. 1 to 8 tokens):

    • Less internal fragmentation: only the last, partially filled block of each sequence wastes slots (at most block_size - 1 tokens).

    • Finer prefix caching: only full blocks are hashed and reused, so more of a shared prefix gets a cache hit.

    • Cheaper copy-on-write, because forking copies a smaller partial block.

    • Cost: longer block tables, more indirection per token, and smaller memory reads. This hurts coalescing and per-block parallelism in the attention kernel.

  • Large blocks (e.g. 64 to 256 tokens):

    • Better kernel throughput: larger contiguous K/V tiles, fewer table lookups, and less metadata.

    • Cost: more waste per sequence, which hurts most with many short sequences. That waste means fewer concurrent sequences fit, so batch size and throughput drop.

    • Coarser prefix reuse: a prefix that doesn't fill a whole block isn't cached.

  • How to choose:

    • The vLLM paper found that very small blocks degrade kernel performance, while very large ones raise fragmentation and reduce sharing. A middle value (16) works well for most workloads.

    • Hardware and kernel backends may require specific sizes (e.g. some attention backends require multiples of 16 or larger pages).

    • Workloads with long sequences and little sharing tolerate larger blocks. Workloads with short requests or heavy prefix reuse favor smaller ones.

Q28.How does a block table map logical token positions to physical blocks in PagedAttention?

Mid

Each sequence has a block table: an array whose i-th entry is the physical block ID holding that sequence's i-th logical block. A token's position is split into a logical block index and an in-block offset. The table converts that pair into a physical slot, so KV memory can be non-contiguous, much like a page table in virtual memory.

  • Address translation:

    1. logical_block = pos // block_size and offset = pos % block_size.

    2. physical_block = block_table[logical_block].

    3. The physical slot in the KV pool is physical_block * block_size + offset.

  • Allocation is on demand:

    • A new physical block is taken from the free pool only when the sequence's last block fills. Waste is therefore bounded to one partial block per sequence.

    • Physical blocks can be anywhere in the pool. Only the table preserves the logical order.

  • How the kernels use it:

    • Writes: the scheduler precomputes a slot_mapping for new tokens, so the cache-write kernel stores K/V straight into their physical slots.

    • Reads: the paged attention kernel receives the batched block tables. It walks the logical blocks in order and gathers K/V from the physical blocks they point to.

  • Sharing falls out naturally: two tables can point to the same physical block (prefix caching, parallel sampling), with reference counts tracking how many tables do.

python
def physical_slot(pos, block_table, block_size=16): logical_block, offset = divmod(pos, block_size) return block_table[logical_block] * block_size + offset # seq tokens 0..15 in phys block 7, 16..31 in phys block 2 physical_slot(20, [7, 2]) # -> 2*16 + 4 = 36

Q29.Explain how prefix caching reuses the KV cache across requests.

Mid

Prefix caching keeps the KV blocks of finished or running requests indexed by their token content. A new request whose prompt begins with the same tokens can point its block table at those existing blocks. It then skips prefill for that prefix and computes only the new suffix.

  • Indexing (vLLM-style, block hashing):

    • Each full block gets a hash of (parent block hash, its token IDs, extra keys such as LoRA ID or multimodal input hashes).

    • Chaining in the parent hash makes a block's identity depend on the entire prefix. This is required because a token's K/V depends on every token before it.

    • SGLang instead uses a radix tree over token sequences, which serves the same purpose.

  • On a new request:

    1. Hash the prompt's full blocks in order and look up the longest run of consecutive hits.

    2. Reuse the matched physical blocks: add them to the block table and increment their ref counts.

    3. Prefill only the uncached suffix. At least the last token is recomputed so the model produces logits.

  • Lifetime: When a request finishes, its blocks are not erased. Their ref count drops to 0 and they stay cached until LRU eviction reclaims them.

  • Wins: Large TTFT and compute savings for shared system prompts, few-shot examples, multi-turn chat (each turn's history), RAG over common documents, and agent loops.

  • Limits:

    • The match must be an exact token prefix. A change near the start (e.g. a timestamp in the system prompt) invalidates everything after it.

    • Only full blocks are reused, and reuse is local to one replica's memory unless routing or offloading tiers extend it.

Q30.How do serving engines batch requests that use different LoRA adapters on a single shared base model?

Mid

The engine runs the shared base-model matmuls once for the whole mixed batch. It then adds each request's low-rank delta (x·A_i·B_i) using custom gather kernels that apply a different adapter per token. Requests for different adapters can therefore share one batch instead of being split per adapter.

  • Why this works:

    • LoRA output is W·x + B·A·x. The dense W·x is identical for all requests, so it is computed as one large batched GEMM.

    • The adapter term is small (rank r is around 8 to 64) and is computed per request.

    • Weights are not merged into the base model, because merging would force one adapter per batch.

  • Heterogeneous adapter kernels:

    • Punica's SGMV and BGMV kernels, and S-LoRA's MBGMM and MBGMV, take a per-token adapter index. They gather the right A/B matrices and compute all deltas in one launch.

    • This avoids looping over adapters or padding every adapter to one rank.

  • Adapter memory management (S-LoRA):

    • All adapters live in host memory. Only those used by active requests are paged onto the GPU, and the rest are evicted with an LRU policy.

    • A unified paged pool holds both KV cache and adapter weights, which limits fragmentation.

    • Adapter loads can be prefetched so they overlap with compute.

  • Practical knobs and trade-offs:

    • vLLM exposes these as --enable-lora, --max-loras (adapters per batch) and --max-lora-rank.

    • The scheduler may delay requests whose adapter isn't resident, or cap how many distinct adapters share a batch.

    • The overhead is a modest per-token cost compared with base-only serving, in exchange for serving thousands of fine-tunes on one GPU.

Q31.What problem does chunked prefill solve when combining long prompts and active decodes?

Mid

A long prompt's prefill is a large compute-bound step. If it runs as one unit, every active decode in the same iteration waits for it, which causes inter-token latency spikes ("generation stalls"). Chunked prefill splits the prompt into fixed-size chunks and processes one chunk per iteration alongside the ongoing decodes, so decodes keep progressing smoothly.

  • The underlying problem:

    • In continuous batching, one iteration's latency is set by its heaviest work. A 32k-token prefill can take hundreds of milliseconds.

    • Every decoding user sees that delay as a stutter, so p99 time per output token (TPOT) explodes.

    • The alternative of pausing prefills to protect decodes instead starves new requests and hurts TTFT.

  • How chunked prefill works:

    1. Each step has a token budget (vLLM: max_num_batched_tokens).

    2. Decode tokens (one per running sequence) are scheduled first.

    3. The remaining budget is filled with a slice of a pending prefill. Its KV cache is written, and the next slice continues from it in the following step.

  • Benefits:

    • Iteration times become bounded and predictable, giving stable TPOT (the "stall-free" scheduling of Sarathi-Serve).

    • Better GPU utilization: memory-bound decodes piggyback on compute-bound prefill chunks.

  • Trade-offs:

    • TTFT for the long prompt rises slightly, because it spans several steps.

    • Each later chunk re-reads the earlier chunks' KV, adding a little overhead.

    • Chunk size is a dial: smaller chunks give smoother TPOT, while larger chunks give better prefill efficiency and TTFT.

Q32.Why does head-of-line blocking occur in unified prefill-decode engines?

Mid

In a unified engine, prefill and decode share the same GPU and the same iteration loop. A step cannot finish until all its work finishes, so one expensive prefill (or a long prompt at the front of the queue) delays everything behind it or batched with it.

  • Within an iteration:

    • Prefill is compute-bound and scales with prompt length. Decode is memory-bound and cheap per token.

    • When they are batched together, the step time is roughly the prefill time, so every decoding sequence stalls. This shows up as a TPOT spike.

  • In the queue:

    • Under FCFS, a huge prompt at the head of the queue may not fit the token budget or the free KV blocks. Smaller requests behind it wait even if they would fit, which inflates TTFT.

    • Long-running decodes that hold KV memory can also block admission of new prefills.

  • Root cause: two phases with different resource profiles are coupled in one scheduler.: Optimizing for TTFT (prioritize prefill) and optimizing for TPOT (prioritize decode) conflict with each other.

  • Mitigations:

    • Chunked prefill, which bounds per-step prefill work.

    • Smarter admission: skip-ahead, shortest-job-first, priority queues.

    • Prefill-decode disaggregation (DistServe, Splitwise), with separate GPU pools and KV transfer between them.

Q33.When would a continuous-batching scheduler choose to preempt an active sequence?

Mid

Mainly when the KV cache runs out of free blocks. Running sequences grow by one token per step, and eventually the engine cannot allocate the next block for everyone. It then evicts some sequences to let the rest continue. Priority or SLO policies can also trigger preemption deliberately.

  • Memory pressure (the common case):

    • The scheduler admits requests optimistically, because output length is unknown at admission time.

    • When a decode step needs new blocks and none are free, the scheduler picks victims instead of failing the step.

  • Priority or fairness:

    • A high-priority or SLO-critical request arrives and there is no capacity for it.

    • A low-priority, long-running sequence is evicted to make room (vLLM's priority scheduling policy).

  • Victim selection: Usually the most recently admitted or lowest-priority sequence (reverse FCFS), which preserves progress on older requests and avoids starvation.

  • How the evicted state is handled:

    1. Recompute: drop the KV and re-prefill prompt plus generated tokens later. This is cheap on memory and often faster on modern GPUs; it is vLLM's default.

    2. Swap: copy KV blocks to CPU memory and restore them later. This saves compute but is bound by PCIe bandwidth.

  • Signals to watch: Frequent preemptions mean the engine is oversubscribed. Lower max_num_seqs, raise gpu_memory_utilization, use quantized KV, or add capacity.

Q34.Why does continuous batching provide higher throughput than dynamic batching for requests of variable length?

Mid

Dynamic batching collects requests within a time window or up to a size limit, but then runs that batch as a unit until it completes. Continuous batching re-forms the batch every decode step. With variable output lengths, dynamic batching wastes slots on finished sequences and makes new arrivals wait, while continuous batching refills those slots immediately.

  • Where dynamic batching loses throughput:

    • Batch duration equals the longest generation. A 20-token reply batched with a 2,000-token reply idles for about 99% of the batch's life.

    • There is padding or masking for ragged lengths, which is wasted compute and memory.

    • Arrivals can't join a running batch, so the GPU runs under-full while the queue grows.

    • Dynamic batching was designed for single-pass models (e.g. classifiers), not autoregressive loops.

  • Why continuous batching wins:

    • Iteration-level scheduling: completed sequences exit and queued ones are admitted at every step.

    • Decode is memory-bandwidth-bound, so a fuller batch amortizes each weight read over more tokens. Throughput scales with the average occupancy.

    • The gain grows with length variance, and reported speedups over naive batching reach an order of magnitude.

  • Enablers and caveats:

    • Paged KV cache memory removes fragmentation, which allows larger effective batches.

    • Mixing prefills into running batches needs care: use chunked prefill to protect TPOT.

Q35.What is the difference between weight-only quantization and weight-and-activation quantization?

Mid

Weight-only quantization (e.g. W4A16) stores weights in low precision but dequantizes them and computes in FP16/BF16. It mainly saves memory and bandwidth. Weight-and-activation quantization (e.g. W8A8 INT8/FP8) quantizes both operands, so the matmul itself runs on low-precision tensor cores, which also saves compute.

  • Weight-only:

    • Weights are static, so they can be quantized offline accurately, even at 4-bit (GPTQ, AWQ).

    • Speeds up memory-bound decode. Gives little gain in compute-bound prefill, since the math is still FP16.

  • Weight + activation:

    • Uses INT8/FP8 GEMMs, roughly 2× FP16 tensor-core throughput. This helps prefill and large-batch serving.

    • Harder to do well: activations are dynamic and have outlier channels, which blow up the quantization range.

    • Common remedies: SmoothQuant (shift scale from activations into weights), per-token or dynamic scaling, and FP8 (wider dynamic range).

    • Usually stays at 8 bits. W4A4 is still lossy without tricks such as rotations (QuaRot, SpinQuant).

  • Rule of thumb: for latency-sensitive small-batch serving, use weight-only. For throughput-bound large batches on hardware with INT8/FP8 support, use W8A8.

Q36.How do you measure the accuracy degradation caused by quantization before deploying a model?

Mid

Compare the quantized model against the full-precision baseline on the same inputs. Use cheap intrinsic metrics first, then task benchmarks, then your own production-like evals, and gate deployment on predefined regression thresholds.

  • Intrinsic metrics:

    • Perplexity on held-out text (e.g. WikiText, C4, or in-domain data). It's fast, but it can hide task-specific breakage.

    • KL divergence between baseline and quantized next-token distributions. It's more sensitive than perplexity.

    • Top-1 token agreement rate with the baseline.

  • Standard benchmarks:

    • Examples: MMLU, GSM8K, HumanEval, long-context retrieval, run through harnesses like lm-evaluation-harness.

    • Math, code, and long-context tasks usually degrade first.

  • Application-specific evals:

    • Use real prompts with graded outputs: exact match, an LLM-as-judge pairwise comparison against the baseline, or JSON/tool-call validity.

    • Cover multilingual input and edge cases you care about.

  • Methodology:

    • Use identical decoding settings (greedy for determinism) and the same prompt template.

    • Use enough samples to separate real regressions from noise, and report confidence intervals.

    • Make sure the calibration set differs from the eval set.

    • Before full rollout, run shadow or canary traffic with online quality metrics.

Q37.Why does weight-only quantization speed up the decode phase but offer little speedup in prefill?

Mid

Decode is memory-bandwidth bound: each step reads all the weights to produce one token per sequence, so shrinking the weights 4× cuts the dominant cost. Prefill is compute bound: many tokens reuse each weight read. Because weight-only kernels still do the math in FP16, the FLOPs don't change and prefill gains little.

  • Arithmetic intensity:

    • Decode does a GEMV (or a skinny GEMM at small batch), at about 1–2 FLOPs per weight byte. That is far below the GPU's roofline ridge point, so it is bandwidth bound.

    • Prefill multiplies by thousands of tokens at once, giving high intensity, so it is compute bound.

  • What weight-only changes:

    • Fewer bytes are moved from HBM, which brings a near-proportional decode speedup (e.g. W4 can give about 2–3× in practice).

    • Weights are dequantized to FP16 in registers, and FP16 tensor cores still do every multiply.

  • Prefill can even slow down:

    • Dequantization adds ALU work in a regime where compute is the bottleneck.

    • The same effect appears at large decode batches, which also become compute bound.

  • To speed up prefill you need fewer or cheaper FLOPs: W8A8 INT8/FP8 GEMMs.

Q38.What is the core conceptual difference between AWQ and GPTQ?

Mid

Both are post-training, mostly 4-bit weight-only methods. They differ in how they reduce error. GPTQ quantizes weights one at a time and uses second-order (Hessian) information to update the remaining weights, compensating for each rounding error. AWQ uses activation statistics to find the small set of salient weight channels and protects them by rescaling before quantizing, with no error-compensation updates.

  • GPTQ: error compensation:

    • Works layer by layer and minimizes ||WX − ŴX||² on calibration inputs.

    • Quantizes columns sequentially, then adjusts the not-yet-quantized weights using the inverse Hessian (H = XXᵀ), building on Optimal Brain Quantization.

    • Very accurate, but it can overfit the calibration data.

  • AWQ: salience protection:

    • Observes that about 1% of weight channels matter most. These are the channels that see large activation magnitudes.

    • Scales those channels up (and the activations down by the same factor), which reduces their relative rounding error. The per-channel scales come from a simple grid search.

    • No backprop and no weight reconstruction, so it is less sensitive to the calibration set and generalizes well across domains.

  • In practice:

    • Similar quality at 4-bit, and both are supported by vLLM and TensorRT-LLM kernels (e.g. Marlin).

    • AWQ is typically faster to quantize and more robust. GPTQ is sometimes slightly better in-distribution.

Q39.What is the difference between symmetric and asymmetric uniform quantization?

Mid

Both map floats to integers as q = round(x/s) + z. Symmetric quantization fixes the zero-point z = 0 and centers the range on zero. Asymmetric quantization adds a zero-point offset so the integer range covers [min, max] exactly. Symmetric is simpler and faster. Asymmetric wastes fewer levels on skewed data.

  • Symmetric:

    • s = max|x| / (2^(b−1) − 1), e.g. /127 for INT8, and z = 0.

    • Zero maps exactly to 0, and matmuls need no zero-point correction terms, which makes for cheaper kernels.

    • Wastes half the range when data is one-sided, e.g. post-ReLU activations.

  • Asymmetric (affine):

    • s = (max − min) / (2^b − 1), and z = round(−min/s).

    • Uses every level for skewed ranges, which gives better precision at low bit-widths.

    • Costs extra compute (cross terms involving z) and requires storing a zero-point.

  • Typical LLM usage:

    • Weights are roughly zero-centered, so INT8 weights are usually symmetric.

    • 4-bit group-wise weights (GPTQ/AWQ) often use asymmetric quantization with per-group zero-points.

    • Activations are commonly quantized symmetrically for speed.

python
# symmetric INT8 s = x.abs().max() / 127 q = (x / s).round().clamp(-127, 127) # asymmetric UINT8 s = (x.max() - x.min()) / 255 z = (-x.min() / s).round() q = (x / s + z).round().clamp(0, 255) x_hat = (q - z) * s

Q40.What are the trade-offs of quantizing the KV cache to FP8 or INT8?

Mid

Quantizing the KV cache to 8 bits halves its memory and bandwidth compared with FP16/BF16. That buys larger batches, longer contexts, and faster long-context decode. The costs are a small and sometimes task-dependent accuracy loss, plus scale-management and kernel-support complexity.

  • Benefits:

    • About 2× more tokens fit in the KV pool. That means more concurrent sequences, higher throughput, and fewer preemptions.

    • Decode attention is bandwidth bound on reading the KV cache, so long contexts get faster per step.

    • It is independent of weight quantization, so the two stack.

  • Costs and risks:

    • Errors accumulate across many cached tokens and every later step. Long-context retrieval and reasoning are the most sensitive.

    • Keys have outlier channels, so they are often harder to quantize than values. Finer granularity helps (per-head or per-channel scales).

    • You need scales: static ones (calibrated, cheaper) or dynamic ones (per-token, more accurate but with overhead).

    • Dequantization or conversion inside attention kernels adds compute. Gains depend on fused kernel support.

  • FP8 vs INT8:

    • FP8 (E4M3) has wider dynamic range and handles outliers better, often with just a per-tensor scale. It is native on Hopper and Ada (e.g. vLLM kv_cache_dtype="fp8").

    • INT8 works on older GPUs but usually needs finer-grained scales to match FP8 accuracy.

  • Validate with long-context evals (needle-in-a-haystack, long QA), not just short-prompt perplexity.

Q41.What are the dynamic range and precision differences between FP8 E4M3, FP8 E5M2 and INT8 for inference?

Mid

All three use 8 bits but spend them differently. E4M3 trades range for precision, E5M2 trades precision for range, and INT8 gives uniform spacing over a range that is set entirely by an external scale. That makes E4M3 the usual inference choice and E5M2 mainly a gradient format.

  • FP8 E4M3 (4 exponent bits, 3 mantissa bits):

    • Max magnitude is about 448 in the OCP/NVIDIA variant, which has no infinity and only one NaN pattern.

    • Smallest subnormal is 2^-9, so it covers roughly 18 binades.

    • 8 steps per power of two, giving about 12.5% relative spacing.

    • Preferred for inference weights and activations.

  • FP8 E5M2 (5 exponent bits, 2 mantissa bits):

    • Max is about 57344 and the smallest subnormal is 2^-16, covering roughly 32 binades.

    • Follows IEEE-like rules, with infinity and NaN.

    • Only 4 steps per power of two, giving about 25% relative spacing. That is too coarse for most inference tensors.

    • Used mostly for gradients in FP8 training, where range matters more than precision.

  • INT8 (uniform integer grid):

    • 256 evenly spaced levels (-128..127) multiplied by a scale, so dynamic range is only about 127:1 per scale group.

    • Absolute error is constant across the range. Relative precision is excellent near the max but poor for small values.

    • A single outlier stretches the scale and crushes small values toward zero. This is why INT8 needs careful calibration and finer scale granularity.

  • Practical implications:

    • FP8 still uses a per-tensor or per-channel scale, but its log-spaced grid tolerates outliers and bell-shaped distributions much better than INT8.

    • FP8 tensor cores require newer hardware (Hopper, Ada, Blackwell, MI300). INT8 runs on far more hardware, including Ampere and CPUs.

Q42.Why are activations in LLMs harder to quantize than weights?

Mid

Weights are static, roughly Gaussian and known ahead of time, so they can be quantized offline with expensive, fine-grained methods. Activations change with every input and contain huge, systematic outlier channels. They must also be quantized at runtime using scales that fit efficient GEMM kernels.

  • Massive outlier features:

    • A few hidden dimensions carry values up to about 100x larger than the rest.

    • These outliers appear consistently across tokens and layers, and become pronounced in models around 6.7B parameters and larger.

    • A per-tensor scale sized for the outliers leaves only a few quantization levels for the normal values.

  • Outliers sit in the wrong axis for scaling:

    • Activation outliers live in specific input channels, which is the GEMM reduction dimension K.

    • A per-channel scale along K can't be factored out of the dot product, so kernels are restricted to per-tensor or per-token scales. Those don't isolate the outliers.

  • Dynamic and input-dependent:

    • Ranges vary per prompt and per token.

    • You either calibrate static scales, which risks clipping unseen ranges, or compute scales dynamically, which adds runtime overhead.

  • No offline optimization budget:

    • Weights can use GPTQ, AWQ or group size 128 once, offline.

    • Activations are quantized on every forward pass, so the method must be cheap.

  • Result:

    • Weight-only 4-bit quantization (W4A16) is easy.

    • Quantizing activations to 8 bits (W8A8) needs tricks such as LLM.int8() decomposition, SmoothQuant or rotations (QuaRot, SpinQuant), or the use of FP8.

Q43.Why is GGUF favored for CPU and edge inference?

Mid

GGUF is llama.cpp's self-contained, memory-mappable model format. It pairs many block-wise quantization types with hand-optimized CPU and Apple Silicon kernels, so a model ships as one small file and runs with no Python or CUDA stack.

  • Single self-describing file:

    • Bundles tensors with metadata: architecture, hyperparameters, tokenizer and chat template.

    • No separate config or tokenizer files, and no PyTorch dependency.

  • mmap-friendly layout:

    • Aligned tensors can be memory-mapped directly, giving fast load and lazy paging.

    • Several processes can share the OS page cache, which suits RAM-limited devices.

  • Rich low-bit quant types:

    • Available types include Q8_0, Q4_K_M, Q5_K_S and the IQ* family.

    • They use small blocks with per-block scales, and k-quants use super-blocks.

    • This gives fine-grained size/quality choices from about 2 to 8 bits per weight, which matters because CPU inference is memory-bandwidth bound.

  • Kernels built for commodity hardware:

    • Block formats are designed for SIMD dequantize-and-dot loops on AVX2, AVX-512 and ARM NEON, plus Metal and Vulkan.

    • Partial GPU offload (-ngl) splits layers between CPU and GPU when VRAM is small.

  • Ecosystem: Used by Ollama, LM Studio and llama-cpp-python, with ready-made GGUF quants for most open models.

  • Trade-off:

    • Optimized for single-user, low-batch local use.

    • High-throughput GPU serving usually prefers AWQ, GPTQ or FP8 checkpoints in vLLM or TensorRT-LLM.

Q44.What is the trade-off between per-tensor scaling and per-channel or per-group scaling in quantization?

Mid

Finer granularity (one scale per channel or per group of about 64–128 values) gives better accuracy because outliers only distort their own group. You pay with more scale metadata, more dequantization work and more complex kernels. Per-tensor is the cheapest and simplest option but the most fragile.

  • Per-tensor:

    • One scale for the whole matrix, so overhead is negligible and kernels are simplest.

    • A single outlier sets the range for everything, so small values lose resolution. This is acceptable for INT8 or FP8 on well-behaved tensors.

  • Per-channel (one scale per output channel / row of W):

    • Handles channels with very different magnitudes.

    • The scale is constant along the reduction dimension K, so it can be applied once in the GEMM epilogue at almost no cost.

    • This is the standard choice for INT8 weights. Per-token is the analogous choice for activations.

  • Per-group (scales every G elements along K):

    • Essential for 3–4-bit weights, where per-channel loses too much accuracy.

    • Adds storage overhead: an FP16 scale per 128 weights adds about 0.125 bits per weight, more if zero-points are included.

    • Scales vary along K, so dequantization must happen inside the inner loop. That costs ALU work and registers and makes kernels harder to tune.

  • Rule of thumb:

    • The fewer bits you have, the finer granularity you need.

    • Activations can't easily use per-channel scaling along K, which is why outlier handling (SmoothQuant, rotations) exists.

Q45.How does LLM.int8() use mixed-precision decomposition to handle outlier features?

Mid

LLM.int8() splits each matmul in two. The few hidden dimensions containing outliers are computed in FP16, and everything else (more than 99.9% of values) uses vector-wise INT8. The two results are summed, which preserves full accuracy even at 175B scale.

  • The problem:

    • Beyond about 6.7B parameters, a handful of feature dimensions show values up to about 100x larger than typical activations.

    • Plain INT8 absmax quantization zeroes out the normal values, and accuracy collapses.

  • How the decomposition works:

    1. Detect outlier columns: any input feature dimension in X where some value has |x| ≥ 6.0 (the threshold).

    2. FP16 part: those columns of X times the matching rows of W.

    3. INT8 part: the remaining columns use vector-wise quantization, with per-row (token) absmax scales for X and per-column (output channel) scales for W.

    4. Dequantize the INT32 result with the outer product of the two scale vectors, then add the FP16 part.

  • Why it works:

    • Outliers are few (roughly 0.1% of dimensions) and consistent across tokens.

    • Isolating them lets the INT8 scales fit the well-behaved bulk of the values.

  • Costs:

    • Gathering outlier columns and running two GEMMs adds overhead.

    • It is often slower than FP16. Its main benefit is roughly halving weight memory, not speed.

    • Exposed as load_in_8bit=True via bitsandbytes.

Q46.When is prompt-lookup decoding preferable to serving a dedicated draft model?

Mid

Prompt-lookup decoding proposes draft tokens by matching the last few generated tokens (an n-gram) against the prompt and copying the tokens that followed. It needs no extra model. It wins when outputs heavily copy from the input, or when running a second model is impractical.

  • How it works:

    • Take the last n tokens and search for them in the prompt (and in prior output).

    • On a match, propose the next k tokens from that location.

    • The target model verifies them in one forward pass, exactly as in standard speculative decoding.

    • Exposed in HF generate(prompt_lookup_num_tokens=...) and in vLLM's ngram speculative method.

  • Prefer it when the workload is input-grounded:

    • Good fits: RAG answers that quote context, summarization, extraction, document QA.

    • Also: code editing or refactoring, where most of the file is repeated, and rewriting or translation with shared entities.

    • Here long verbatim spans give high acceptance and multi-token jumps.

  • Prefer it when a draft model is costly or unavailable:

    • There is no small model with the same tokenizer and a well-matched distribution.

    • GPU memory is tight: no draft weights and no draft KV cache.

    • Draft cost is near zero (a CPU-side string match), so a failed lookup just falls back to normal decoding.

    • Ops are simpler: nothing to train, version or keep aligned with the target.

  • A dedicated draft model (or EAGLE/Medusa) is better when output is novel: Examples: open-ended chat, creative writing, reasoning, where the prompt rarely contains the continuation.

  • Caveat:

    • At high batch, the GPU is already compute bound, so verifying rejected tokens wastes compute.

    • Any speculation, including prompt lookup, helps less in that regime.

Q47.Why can the target model verify multiple draft tokens in a single forward pass?

Mid

A transformer with a causal mask computes output distributions for every input position in parallel, just like during prefill. Feeding the accepted prefix plus k draft tokens therefore yields k+1 next-token distributions in one pass. Because decoding is memory-bandwidth bound, that pass costs about the same as generating a single token.

  • Parallelism comes from the causal mask:

    • The output at position i depends only on tokens ≤ i.

    • So the distribution at draft position i is identical to what sequential decoding would have produced, if the earlier drafts were the tokens actually chosen.

    • Training already uses this property (teacher forcing). Verification is a short prefill over the draft tokens, reusing the existing KV cache.

  • Verification logic:

    1. Compare each draft token against the target distribution at its position (exact match for greedy, rejection sampling for sampling).

    2. Accept the longest valid prefix.

    3. Take one bonus token from the target's distribution at the first rejected position, or after the last draft if all were accepted.

  • Why it's nearly free:

    • At small batch, each decode step's cost is dominated by loading all weights from HBM.

    • Processing k+1 tokens reuses those same weight loads, so arithmetic intensity rises with little extra latency.

  • KV cache handling:

    • K/V entries are written for all draft positions.

    • Entries for rejected tokens are discarded or overwritten by rolling back the sequence length.

  • Limit: At large batch the GPU becomes compute bound, so the extra positions are no longer free.

Q48.Explain the concept of early exit decoding in multi-layer transformers.

Mid

Early exit decoding lets a token stop at an intermediate layer once the model is already confident, skipping the remaining layers. Easy tokens use less compute; hard tokens still use the full depth.

  • Mechanism:

    • Attach an LM head (often the shared final head plus final norm) to selected intermediate layers.

    • After each such layer, compute a confidence signal: max softmax probability, entropy, hidden-state change between layers, or a small learned classifier.

    • If confidence exceeds a threshold, emit the token. The threshold sets the speed/quality trade-off.

  • Training requirements:

    • Vanilla models have poor intermediate predictions.

    • Early-exit losses at intermediate layers, and layer dropout (as in LayerSkip), make shallow layers produce usable logits.

    • CALM calibrates thresholds to bound quality loss relative to the full model.

  • The KV cache problem:

    • If token t exits at layer 8, layers 9 to N have no K/V for t, yet later tokens attending at those layers need it.

    • Fix 1: copy the exited hidden state upward and compute the missing K/V (CALM-style state propagation).

    • Fix 2: compute the missing K/V lazily, batched with the next token.

  • Serving challenges:

    • In a batch, different sequences exit at different layers. The GPU must still run deep layers for the slowest member, so batched savings shrink.

    • Data-dependent control flow complicates CUDA graphs and kernel fusion.

  • Modern variant: self-speculative decoding (LayerSkip):

    • Early-exit layers act as the draft model.

    • The remaining layers verify the drafts, reusing the shared early-layer computation.

    • This recovers exact target outputs instead of trusting the early exit.

Q49.What is the architectural difference between draft-model speculative decoding and Medusa multi-head prediction?

Mid

Draft-model speculative decoding uses a separate, smaller model that autoregressively generates k candidate tokens. Medusa instead adds several lightweight prediction heads on the target model's own final hidden state. Each head guesses a token further ahead, so candidates come from the same forward pass, and a tree of candidates is verified at once.

  • Draft-model approach:

    • Two full models: the draft runs k sequential steps with its own weights and KV cache.

    • The draft must share the target's tokenizer and roughly match its distribution.

    • Each draft token is conditioned on the previous draft tokens, so the chain is coherent.

    • Verification uses rejection sampling, so it is lossless.

    • Costs: extra memory, extra latency for k draft steps, and orchestrating two models.

  • Medusa approach:

    • Head i (a small residual MLP plus LM head) predicts token t+i+1 from the hidden state at position t.

    • No separate model, no draft KV cache, and no sequential draft steps.

    • Training options: Medusa-1 trains only the heads on a frozen backbone; Medusa-2 fine-tunes jointly for better acceptance.

    • Top-k guesses per head are combined into a candidate tree.

    • Tree attention (a custom mask) verifies all branches in one forward pass, and the longest accepted path is kept.

  • Key trade-offs:

    • Medusa heads predict independently and are not conditioned on earlier speculated tokens. Accuracy drops quickly for further positions, which is why it relies on trees.

    • EAGLE addresses this with an autoregressive feature-level head.

    • Medusa's "typical acceptance" speeds up sampling but is not exactly lossless. Greedy verification is exact.

    • Medusa ties the heads to one specific target model. A draft model can be swapped or reused across fine-tunes that share a tokenizer.

Q50.Why is beam search more expensive than sampling in KV cache memory and throughput at serving time?

Mid

Beam search with width B keeps B live hypotheses per request, each needing its own KV cache tail and its own decode slot. Every step also needs cross-beam synchronization and cache forking. One request therefore consumes roughly the resources of B sampled requests, while still producing one answer.

  • KV cache memory:

    • Beams share the prompt prefix. Paged attention can share those blocks via reference counts and copy-on-write.

    • Generated tokens diverge, so cache grows about B× in the decode phase.

    • This reduces how many requests fit in the batch, so throughput per GPU drops.

    • When a beam is replaced by a fork of another, partially filled blocks must be copied or reference counts juggled.

  • Compute and scheduling:

    • Each step processes B tokens per request.

    • It then runs a top-B over B × vocab log-probs, which forces a global sync across beams before the next step.

    • Beams can't be scheduled, preempted or finished independently. The request ends only when the beam set completes, and length normalization keeps finished hypotheses around.

    • This fights continuous batching's per-sequence model, so many engines (e.g. vLLM) moved beam search off the fast path.

  • Latency and UX:

    • You can't stream tokens, because the winning beam is unknown until the end.

    • Time-to-final-answer gets worse.

  • Contrast with sampling:

    • One sequence, one cache, an independent per-token decision, and streamable output.

    • It is compatible with speculative decoding and prefix caching without extra machinery.

Q51.Why can grammar-constrained decoding add latency in a serving engine?

Mid

Grammar-constrained decoding must compute a mask of allowed tokens from the grammar state at every step, for every constrained request, before sampling can happen. That work is mostly on the CPU, scales with vocabulary size, and sits on the critical path between the GPU forward pass and the next step.

  • Per-token mask cost:

    • The engine checks which of ~100k+ vocabulary tokens (multi-character strings) keep the grammar valid from the current state.

    • Regex and JSON-schema constraints compile to an FSM, so masks can be precomputed per state (the Outlines approach).

    • General CFGs need a pushdown automaton whose stack makes masks context-dependent and harder to cache.

  • It breaks CPU/GPU overlap:

    • Engines hide CPU scheduling behind GPU compute.

    • Here sampling must wait for the mask, and the mask depends on the previously sampled token, which serializes the step.

    • In a large batch, the slowest request's mask stalls everyone.

  • Compilation cost:

    • Building the automaton and token index for a new schema can take milliseconds to seconds.

    • This inflates time-to-first-token unless compiled grammars are cached.

  • Interaction with other optimizations:

    • Speculative decoding needs masks for every draft position, plus grammar-state rollback on rejection.

    • The bitmask must be copied to the GPU and applied to the logits.

    • Python-level grammar code can bottleneck the GIL.

  • Mitigations:

    • XGrammar splits tokens into context-independent ones (precomputed) and context-dependent ones (checked at runtime), and uses an adaptive mask cache.

    • Compute the next mask on CPU while the GPU runs the forward pass.

    • Jump-forward decoding emits forced tokens (fixed JSON keys, punctuation) without a model step, which can make constrained output faster overall.

Q52.Why does operator fusion yield significant speedups during memory-bound decode?

Mid

In decode, each step processes one token per sequence, so most ops have very low arithmetic intensity: runtime is dominated by moving bytes through HBM and by kernel launch overhead, not FLOPs. Fusion cuts both, so it directly attacks the bottleneck.

  • Decode is memory-bound:

    • With small batch, matmuls are near matrix-vector products: ~1–2 FLOPs per byte, far below the GPU's ridge point (hundreds of FLOPs/byte).

    • Elementwise ops (norms, activations, residual adds, RoPE) do almost no math per byte loaded.

  • Fusion removes HBM round trips:

    • Unfused, every intermediate is written to and re-read from HBM; fused, it stays in registers/shared memory.

    • Since time ≈ bytes moved / bandwidth, removing intermediate traffic gives near-proportional speedup for those ops.

  • Fusion removes launch overhead: Decode kernels are tiny (microseconds), so a ~5 µs launch can be comparable to the work itself; hundreds of kernels per token add up.

  • Contrast with prefill: Prefill is compute-bound in large GEMMs, so fusing small elementwise ops matters relatively less there.

  • High-value decode fusions: dequantization inside the GEMM (weight-only INT4/FP8), residual + RMSNorm, fused SwiGLU, fused attention over the KV cache.

Q53.How do CUDA Graphs eliminate CPU launch overhead during token-by-token decoding?

Mid

A decode step launches hundreds of small kernels, and at small batch the CPU can't issue them as fast as the GPU finishes them, leaving the GPU idle. CUDA Graphs capture the whole decode forward pass once and replay it with one launch per step, so the GPU runs back-to-back kernels without waiting on Python, the framework, or the driver.

  • The problem:

    • Each kernel launch costs several µs of CPU work (Python dispatch, PyTorch op overhead, driver).

    • Decode kernels often run only a few µs each, so the step becomes CPU-launch-bound.

  • How graphs fix it:

    1. At startup, capture the decode pass for each bucketed batch size into static input/output buffers.

    2. Each step: copy token IDs, positions, and block tables into those buffers.

    3. Call replay(): the driver submits the pre-built kernel sequence in one shot with dependencies already resolved.

  • Making it work with dynamic serving:

    • Pad the live batch to the nearest captured size.

    • Attention kernels read sequence lengths and paged-KV block tables from device buffers, so varying lengths need no recapture.

    • Sampling or other dynamic logic may stay outside the graph.

  • Impact and limits:

    • Large gains at small batch / small models where launch overhead dominates; diminishing at large batch where kernels are long.

    • Costs: capture time and extra memory per batch-size bucket; prefill is usually run eagerly.

Q54.Why are FlashAttention and PagedAttention complementary rather than mutually exclusive?

Mid

They solve different problems at different layers: FlashAttention is a compute kernel that avoids materializing the attention matrix in HBM, while PagedAttention is a memory-management scheme for how the KV cache is stored across requests. A kernel can do both: compute attention in fused, tiled fashion while reading K/V from non-contiguous pages.

  • FlashAttention: how attention is computed:

    • Tiles Q, K, V into SRAM, uses online softmax, never writes the N×N score matrix to HBM.

    • Biggest win in prefill/training (long sequences, compute and IO heavy).

  • PagedAttention: where the KV cache lives:

    • Splits each sequence's KV cache into fixed-size blocks mapped by a block table, like OS virtual memory.

    • Eliminates fragmentation and over-reservation, enabling larger batches and prefix sharing (copy-on-write).

    • Biggest win in serving throughput during decode.

  • How they combine:

    • Tiling naturally maps to pages: each tile of K/V is loaded from whichever block the table points to.

    • FlashAttention-2/3 and FlashInfer support paged KV inputs; vLLM uses FlashAttention/FlashInfer backends with paged caches.

  • Interview framing: one optimizes HBM traffic within a single attention call; the other optimizes memory capacity across many concurrent requests, so using both compounds the gains.

Q55.What does torch.compile do to speed up LLM inference?

Mid

torch.compile JIT-captures the model's Python code into a graph and generates fused, optimized GPU kernels. This cuts the two main costs of eager decode: many tiny kernel launches and redundant memory round-trips between ops.

  • The compiler pipeline:

    1. TorchDynamo traces Python bytecode into an FX graph and inserts guards (shape, dtype, device) that trigger recompilation if they change.

    2. AOTAutograd lowers it to primitive ATen ops.

    3. TorchInductor emits Triton kernels (GPU) or C++ (CPU).

  • Kernel fusion:

    • Chains of elementwise and reduction ops become one kernel that reads and writes HBM once, so intermediates are never materialized. Typical examples are RMSNorm, RoPE, SiLU·gate, residual adds and dequantization.

    • Matmuls usually stay on cuBLAS. max-autotune can benchmark Triton GEMM templates and pick the fastest.

  • CUDA Graphs via mode="reduce-overhead":

    • At small batch, decode is launch/CPU-overhead bound: hundreds of kernels per token, each doing very little work.

    • Replaying a captured graph removes Python dispatch and per-kernel launch cost, which is often the biggest single win (e.g. gpt-fast).

    • It needs static shapes and addresses, so you need a preallocated static KV cache.

  • Caveats:

    • Compile time and warmup add to startup.

    • Graph breaks (unsupported Python, data-dependent control flow) split the graph and lose fusion.

    • Changing sequence or batch shapes cause recompiles. Mitigate with dynamic=True, mark_dynamic, or padding to buckets.

python
model = torch.compile(model, mode="reduce-overhead", fullgraph=True) # first calls compile + capture CUDA graphs; later decode steps replay them

Q56.Why is tensor parallelism preferred within a node while pipeline parallelism is used across nodes for serving?

Mid

Tensor parallelism needs bandwidth-heavy all-reduces inside every layer for every token, so it needs NVLink-class interconnect. Pipeline parallelism only sends activations point-to-point at stage boundaries, so it tolerates the much slower inter-node network.

  • TP communication pattern:

    • Two all-reduces per transformer layer per forward pass sit on the critical path of every decode step.

    • NVLink (~900 GB/s per H100) keeps them cheap, while InfiniBand (~50 GB/s per 400 Gb NIC) would make communication dominate latency.

  • PP communication pattern: There is one send/recv of the hidden state (tokens × hidden) per stage boundary, which is small, infrequent and easy to overlap.

  • Latency vs throughput:

    • TP splits each layer's work, so per-token latency drops. It also shards weights and KV cache.

    • PP runs stages sequentially, so a single request gets no faster. It adds capacity and needs many in-flight micro-batches to avoid pipeline bubbles.

  • Typical layout: TP = GPUs per node (e.g. 8) and PP = number of nodes, such as TP8×PP2 for a model that doesn't fit on one node.

  • Caveats:

    • Very high TP degrees shrink the matmuls and hurt efficiency.

    • Large NVLink domains (GB200 NVL72) allow TP or expert parallelism across trays.

    • MoE models often use expert parallelism across nodes instead of PP.

Q57.What causes long cold-start times when spinning up new LLM replicas?

Mid

Cold start is dominated by moving and initializing huge artifacts: provisioning a GPU node, pulling a multi-GB container image, and downloading and loading hundreds of GB of weights into GPU memory. Engine initialization (CUDA/NCCL setup, compilation, CUDA graph capture, memory profiling) adds more. Together these can stretch to many minutes.

  • Infrastructure:

    • The autoscaler has to acquire a GPU node (cloud capacity, VM boot, driver and device-plugin setup).

    • Container images with CUDA, PyTorch, and the engine are often 10–20 GB to pull.

  • Weight loading (usually the biggest cost):

    • Download from object storage or a model hub: 140 GB at about 1 GB/s is over 2 minutes.

    • Disk to CPU to GPU copies, deserialization (pickle-based checkpoints are slow; safetensors with mmap is faster), and sharding or reshaping for TP.

  • Engine initialization:

    • CUDA context creation and NCCL communicator setup across TP ranks.

    • torch.compile, Triton, or TensorRT engine builds when caches are cold.

    • CUDA graph capture across many batch sizes, memory profiling, and KV cache allocation.

    • Warmup requests, then readiness probes and registration with the load balancer.

  • Mitigations:

    • Pre-pulled or lazily loaded images, and weights cached on local NVMe or a shared high-throughput filesystem.

    • Streaming, parallel loaders (e.g. Run:ai Model Streamer, fastsafetensors) and GPUDirect Storage.

    • Pre-sharded checkpoints, persisted compile and engine caches, and fewer captured CUDA graph sizes.

    • Process or GPU snapshot-restore (CUDA checkpointing), and warm standby pools instead of scaling to zero.

    • Scale predictively ahead of load so cold starts don't sit on the request path.

Q58.How does decoding concurrency affect the memory consumed by activation buffers?

Mid

Activation memory scales with the number of tokens processed in one forward pass, not with the number of sequences held in memory. In pure decode, each running sequence adds only one token per step, so activation buffers grow roughly linearly with decode batch size but stay small compared with the KV cache. The real peak usually comes from prefill tokens mixed into the same step.

  • Why decode activations are small:

    • Per step, hidden states are batch × 1 × hidden_size and MLP intermediates are batch × intermediate_size.

    • Buffers are transient and reused layer by layer, so you pay for roughly one layer's worth at a time, not all layers.

    • Example: 256 sequences × 14,336 (Llama-3-8B MLP width) × 2 bytes is about 7 MB per intermediate tensor, which is tiny.

  • Buffers that do grow noticeably with concurrency:

    • Logits: batch × vocab_size, often upcast to fp32 for sampling. For example, 256 × 128k × 4 B is about 128 MB, plus softmax and top-k/top-p scratch.

    • Attention workspace: split-KV / flash-decoding scratch scales with batch × heads × number of splits.

    • CUDA graphs: engines capture one graph per batch-size bucket, and each capture pins its own static input and output buffers.

    • MoE: token routing and permutation buffers scale with batch × top-k experts.

  • The peak is set by the token budget, not by decode:

    • With continuous batching and chunked prefill, one step can hold up to max_num_batched_tokens tokens: decode tokens plus prefill chunks.

    • Engines such as vLLM profile a dummy forward pass at this maximum at startup. That reserves the worst-case activation peak, and the rest goes to the KV cache.

  • Practical takeaway:

    • Raising decode concurrency mostly costs KV cache. Raising the per-step token budget or max batch size costs activation memory.

    • So the activation reservation trades directly against KV capacity, and therefore against how many requests can stay resident.

Q59.How do you partition GPU memory across model weights, the KV cache pool and activations?

Mid

Weights are a fixed cost, and activations plus runtime overhead are a measured worst-case reserve. Everything left under a utilization cap becomes the KV cache pool, because KV capacity is what determines concurrency.

  1. Weights (fixed):

    • Size is params × bytes per param ÷ tensor-parallel degree. For example, 70B in FP16 is 140 GB, about 35 GB per GPU at TP=4.

    • Quantization (FP8, INT4) is the main lever for freeing space for KV cache.

  2. Activation and runtime reserve (measured):

    • Peak activations at the maximum per-step token budget (max_num_batched_tokens), found with a profiling forward pass.

    • Plus CUDA graph buffers, NCCL communication buffers, the CUDA context, allocator fragmentation, and sampling scratch.

  3. Safety headroom:

    • Leave a margin with a utilization cap: vLLM gpu_memory_utilization (default 0.9) or TensorRT-LLM kv_cache_free_gpu_mem_fraction.

    • This guards against OOM from memory spikes and other processes on the GPU.

  4. KV cache pool (the remainder):

    • Preallocated as fixed-size blocks (PagedAttention).

    • Tokens that fit = pool bytes ÷ (2 × layers × kv_heads × head_dim × bytes ÷ TP).

  5. Tuning trade-offs:

    • A larger token budget lowers TTFT for long prompts but enlarges the activation reserve and shrinks KV capacity.

    • An FP8 KV cache roughly doubles concurrency. More tensor parallelism splits both weights and KV, freeing per-GPU space.

    • Validate with the engine's startup log (it reports KV blocks and maximum concurrency) and with load tests.

python
total = 80e9 * 0.90 # gpu_memory_utilization weights = 16e9 # 8B params, FP16 reserve = 4e9 # profiled activations + graphs + NCCL kv_pool = total - weights - reserve # ~52 GB for KV blocks

Q60.Why is GPU memory utilization from nvidia-smi a poor indicator of serving capacity in engines using PagedAttention?

Mid

PagedAttention engines preallocate almost all GPU memory for the KV block pool at startup. nvidia-smi therefore shows around 90% used whether the server is idle or saturated. Real capacity is how many of those KV blocks are actually occupied, which only the engine knows.

  • Memory is reserved, not consumed:

    • vLLM claims gpu_memory_utilization × total memory at launch and carves it into blocks. The driver sees one large allocation.

    • Block allocation and freeing happens inside the engine's own block manager, which is invisible to nvidia-smi.

  • "GPU-Util" also misleads:

    • It measures the fraction of time any kernel is running, not how much of the compute or bandwidth is used.

    • A small decode batch can show 100% while the GPU is far from saturated.

  • What to watch instead:

    • KV cache usage percentage (vLLM vllm:gpu_cache_usage_perc, renamed kv_cache_usage_perc in newer versions).

    • Running vs. waiting requests (num_requests_running, num_requests_waiting).

    • Preemption count: sequences evicted or recomputed when blocks run out.

    • TTFT and inter-token latency against your SLO.

    • For real hardware saturation, DCGM SM activity and DRAM bandwidth.

  • Capacity also depends on the workload:

    • The same pool holds many short requests or few long ones.

    • Prefix caching can make cached blocks look "used" when they are actually reclaimable.

Q61.How do you calculate the maximum number of concurrent requests a GPU can serve before running out of memory?

Mid

Take the memory left after weights and the activation reserve, divide by the KV cache bytes per token to get total token capacity, then divide by the average tokens each request holds (prompt plus generated). That gives sustainable concurrency.

  1. KV bytes per token:

    • 2 (K and V) × layers × kv_heads × head_dim × bytes per element, divided by the TP degree per GPU.

    • GQA reduces kv_heads, and an FP8 KV cache halves the bytes per element.

  2. Available KV memory: Total × utilization cap − weights − (peak activations + CUDA graphs + NCCL + overhead).

  3. Token capacity: Available ÷ bytes per token.

  4. Concurrency:

    • Token capacity ÷ average (input + output) tokens per request.

    • With static allocation, divide by max_model_len instead. That gap is why PagedAttention raises concurrency.

  5. Caveats:

    • Use a tail-length mix rather than just the mean. Requests grow as they decode, so peak occupancy exceeds the average and triggers preemption.

    • Prefix sharing raises effective capacity, and block granularity wastes a little.

    • Memory is only the ceiling. Latency SLOs (TPOT degrades as batch grows) often cap concurrency lower.

python
# Llama-3-8B on one 80 GB H100, FP16 KV kv_per_tok = 2 * 32 * 8 * 128 * 2 # 131,072 B = 128 KiB avail = 80e9 * 0.9 - 16e9 - 4e9 # ~52 GB tokens = avail / kv_per_tok # ~397k tokens concurrency = tokens / 4096 # ~97 requests at 4k tokens each

Q62.When would you choose vLLM over TensorRT-LLM for a serving deployment?

Mid

Choose vLLM when flexibility and iteration speed matter more than the last 10–30% of performance. That means new or varied models, non-NVIDIA hardware, frequent upgrades, and minimal build tooling. Choose TensorRT-LLM when you are NVIDIA-only, the model is stable, and squeezing maximum throughput or latency out of each GPU justifies the engineering cost.

  • Favor vLLM when:

    • Model coverage and day-zero support matter: it loads Hugging Face checkpoints directly, and new architectures land quickly.

    • Hardware is heterogeneous: it supports AMD ROCm, TPU, Intel Gaudi and CPU as well as NVIDIA.

    • You want simple operations: pip install, an OpenAI-compatible server, and no per-GPU engine build step.

    • You need built-in features out of the box: multi-LoRA, prefix caching, structured output, and speculative decoding.

    • The team is Python-centric and wants to read, patch and debug the scheduler.

  • Favor TensorRT-LLM when:

    • It is a fixed, high-volume model on Hopper or Blackwell, where fused kernels and FP8/FP4 paths give the best tokens per dollar.

    • You already run NVIDIA's stack (Triton, NIM, Dynamo) and want vendor support.

    • Strict latency SLOs justify per-model tuning and engine builds.

  • Nuances to mention:

    • The performance gap has narrowed. vLLM uses FlashInfer and CUDA graphs, and newer TensorRT-LLM offers a PyTorch-based workflow that reduces build friction.

    • Always benchmark both on your own model, input/output length mix, and SLO. Results vary a lot by workload.

Q63.What constraints shape LLM inference on phones and laptops compared with datacenter GPUs?

Mid

On-device inference is limited by small shared memory, low memory bandwidth, and power and thermal budgets, and it runs at batch size 1. You therefore need small, heavily quantized models, and decode speed is set almost entirely by how fast the weights can be streamed from memory.

  • Memory capacity:

    • Phones have 8–16 GB, and laptops 16–128 GB of unified memory, shared with the OS and other apps. That compares with 80–192 GB of dedicated HBM per datacenter GPU.

    • Mobile OSes kill memory-hungry apps. This caps model size (usually 1–8B parameters at 4-bit) and context length, since the KV cache competes for the same memory.

  • Memory bandwidth dominates decode:

    • Tokens/s ≈ bandwidth ÷ model bytes.

    • Phones have roughly 50–100 GB/s and Apple M-series laptops 100–800 GB/s, against about 3.35 TB/s on an H100.

    • Example: a 4 GB model at 60 GB/s tops out around 15 tokens/s.

  • No batching amortization: A single user means each weight read serves one token. Datacenters batch many users to become compute-efficient.

  • Power and thermals:

    • Sustained load throttles clocks and drains the battery, so peak benchmarks overstate real throughput.

    • Prefill, which is compute-bound, is often offloaded to the NPU for efficiency.

  • Fragmented hardware and software:

    • Work is split across CPU, GPU and NPU, each with limited operator and datatype support.

    • Runtimes include llama.cpp, MLX, Core ML, ExecuTorch and Qualcomm QNN, rather than a single CUDA stack.

  • Other constraints: App download size, model load and cold-start time, and storage limits.

  • Upside: Privacy, offline use, no network latency, and zero marginal serving cost. These motivate hybrid designs that route hard queries to the cloud.

Q64.At what point does increasing batch size transition the decoding phase from memory-bound to compute-bound?

Senior

Decode crosses from memory-bound to compute-bound when its arithmetic intensity (FLOPs per byte loaded) passes the GPU's ridge point (peak FLOPs ÷ memory bandwidth). For dense FP16/BF16 weights, intensity is roughly equal to the batch size, so the crossover sits around a batch of ~150–300 tokens on A100/H100-class GPUs. That holds only for the weight GEMMs: attention over the KV cache stays memory-bound at any batch size.

  • Why intensity ≈ batch size:

    • Each decode step reads every weight once (2 bytes/param in FP16) and does 2 FLOPs per param per token, so FLOPs/byte ≈ 2B / 2 = B.

    • Batching amortizes one weight read across B tokens, which is why throughput scales almost linearly with batch at first.

  • Ridge point examples (dense BF16):

    • A100: ~312 TFLOPS / ~2 TB/s ≈ 156 FLOPs/byte.

    • H100 SXM: ~989 TFLOPS / ~3.35 TB/s ≈ 295 FLOPs/byte.

    • In practice kernels hit their limits earlier, so throughput gains flatten somewhat before the theoretical point.

  • Why real decode often never gets there:

    • KV cache reads scale with batch × context and are not shared across sequences. Attention has intensity ~1 regardless of batch, so with long contexts KV traffic dominates and the step stays bandwidth-bound.

    • KV memory capacity usually caps the batch before you reach the ridge point.

  • Things that shift the crossover:

    • Weight-only quantization (INT4/INT8) reduces bytes per param, which raises intensity per token and moves the crossover to a smaller batch. FP8 compute also raises peak FLOPs, which pushes it back up.

    • MoE routes tokens across experts, so each expert sees only part of the batch and needs a much larger global batch to become compute-bound.

    • Mixed batches with chunked prefill add compute-heavy prefill tokens, which effectively raises intensity.

Q65.What are the trade-offs of KV cache eviction policies such as StreamingLLM or H2O?

Senior

Eviction policies cap KV memory by discarding tokens, which makes the cache lossy. Once a token is evicted, the model can never attend to it again.

  • StreamingLLM: keep a few attention-sink tokens plus a recent sliding window:

    • Pros:

    • Constant memory, so it supports effectively unbounded streaming.

    • Trivially simple, needs no attention scores, and works with FlashAttention and paged kernels.

    • Cons:

    • Anything in the middle is forgotten, so retrieval over the full context fails.

    • It provides stable generation, not a longer effective context.

  • H2O (Heavy-Hitter Oracle): keep recent tokens plus the tokens with the highest accumulated attention:

    • Pros:

    • Retains important older tokens.

    • Keeps good quality at small budgets (around 20% of the cache in the paper).

    • Cons:

    • Needs attention scores, which fused kernels like FlashAttention do not materialize.

    • Eviction is greedy and irreversible: past importance does not guarantee future importance.

    • Per-head and per-layer bookkeeping plus irregular retained sets complicate batching and paging.

  • Shared trade-offs:

    • They trade memory and throughput for accuracy.

    • They hurt most on needle-in-a-haystack, multi-hop QA and long-document tasks.

    • Lossless or near-lossless alternatives: KV quantization, CPU offloading, GQA or MLA.

Q66.Why do attention sinks prevent a model from collapsing when older tokens are evicted from the KV cache?

Senior

Models learn to dump excess attention onto the first few tokens. These sinks act as a "no-op" target that softmax needs. Evicting them forces that probability mass onto other tokens, which corrupts attention outputs and makes perplexity explode. Keeping their KV entries preserves the distribution the model was trained with.

  • Why sinks form:

    • Softmax must sum to 1, even when a head has nothing relevant to attend to.

    • Initial tokens are visible to every position under the causal mask.

    • So they become the learned dumping ground, typically with small value vectors that contribute little to the output.

  • What eviction breaks:

    • With a pure sliding window, the sink tokens disappear.

    • Their large share of attention gets renormalized onto content tokens.

    • This shifts hidden states away from the training distribution, and the error compounds across layers.

  • The fix (StreamingLLM):

    • Always keep the KV of about 4 initial tokens alongside the recent window.

    • Assign positions relative to the cache rather than the original text.

    • What matters is the sink's position and role, not its semantic content.

  • Design alternatives:

    • Train with a dedicated learnable sink token.

    • Or add a learnable sink logit (softmax off-by-one style) so heads can attend to "nothing" without needing real tokens.

Q67.How does Multi-Head Latent Attention (MLA) compress the KV cache footprint?

Senior

MLA (introduced in DeepSeek-V2) caches one small shared latent vector per token instead of full per-head keys and values. K and V are reconstructed from it by up-projections. Those up-projections can be folded into the query and output matrices, so the full K and V never need to be materialized during decode.

  • Low-rank joint compression:

    • Compute c_KV = W_DKV · h, a latent vector of dimension d_c (512 in DeepSeek-V2).

    • Keys and values are recovered as k = W_UK · c_KV and v = W_UV · c_KV.

  • Matrix absorption:

    • Attention is linear in K and V, so W_UK can be absorbed into the query projection.

    • Likewise, W_UV can be absorbed into the output projection.

    • Queries then attend directly over the cached latents.

  • Decoupled RoPE:

    • RoPE is position-dependent, so it breaks absorption.

    • MLA therefore adds a small separate key of 64 dimensions that carries RoPE.

    • That key is shared across heads and cached alongside the latent.

  • Footprint:

    • About 576 elements per token per layer, versus 2 × n_heads × head_dim for MHA.

    • DeepSeek-V2 reports a 93.3% KV cache reduction versus DeepSeek 67B.

  • Trade-offs:

    • Reported quality matches or beats MHA, unlike MQA or GQA, which share heads.

    • It costs more FLOPs per byte loaded. That suits bandwidth-bound decode well.

    • Kernels are more complex.

Q68.How does prefix-aware routing across replicas maximize KV cache hit rates?

Senior

KV caches are local to each replica. Round-robin or least-loaded routing scatters requests that share a prefix, so with N replicas the hit rate falls toward 1/N. Prefix-aware routing sends each request to the replica most likely to already hold its prefix, while still guarding against overloading that replica.

  • Tracking which replica has which prefix:

    • Approximate: the router keeps a radix tree (or a set of block hashes) for each replica, built from the prompts it has routed there. This is SGLang router's cache-aware mode.

    • Exact: replicas publish KV events (block stored or evicted) to the router, as in the NVIDIA Dynamo KV router and llm-d. The router's view then reflects real evictions.

    • Simple: consistent hashing on a session ID or on the first k prompt blocks, so a given conversation or system prompt always lands on the same replica.

  • Making the decision:

    • Score each replica by (expected cached-prefix length) against (load: queue depth, running batch, free KV blocks).

    • Pick the best match unless that replica's load exceeds a threshold relative to the others. In that case, fall back to the least-loaded replica.

  • Pitfalls:

    • Hotspots: one popular system prompt can pin all traffic to one replica. Mitigate by replicating hot prefixes to several replicas or by load-aware fallback.

    • A stale approximate view routes to a replica that has already evicted the prefix. The cost is a miss, not an error.

    • Autoscaling or replica failure reshuffles the mapping. Consistent hashing limits how many keys move.

  • Payoff: higher hit rates mean less redundant prefill, lower TTFT, and more GPU capacity for decode. This matters most for multi-turn chat and agent workloads.

Q69.How does a serving engine decide between swapping KV cache blocks to host memory and recomputing a preempted request under memory pressure?

Senior

When the KV pool runs out of blocks, the scheduler preempts some sequences (typically the most recently arrived or lowest priority) and frees their blocks. It can either swap the blocks to CPU memory and copy them back later, or discard them and recompute the KV by re-running prefill over the prompt plus already-generated tokens. The choice compares PCIe transfer cost against prefill compute cost, plus engine constraints.

  • Swapping:

    • Cost: KV bytes / PCIe bandwidth, paid twice (out and back in). It also needs reserved CPU swap space.

    • Swap traffic competes with other host-device transfers.

    • Better for long contexts, where re-prefill attention cost grows faster than KV size.

    • Required when blocks are shared within a sequence group (beam search, parallel sampling). Recomputing would break the sharing, so vLLM V0 only swaps multi-sequence groups.

  • Recomputation:

    • Cost: one prefill over prompt plus generated tokens. This is cheaper than the original decode because those tokens are processed in parallel as a compute-efficient prefill.

    • Needs no host memory and no PCIe traffic, which favors fast GPUs with slow interconnect and short to medium sequences.

    • Gets even cheaper with prefix caching, because surviving cached blocks need not be recomputed.

  • What engines actually do:

    • vLLM V0 exposed preemption_mode and defaulted to recompute for single-sequence groups. The vLLM paper found both comparable at medium block sizes, with swapping hurt by small blocks because many small transfers are inefficient.

    • vLLM V1 uses recompute only. It is simpler, and prefix caching makes it cheap.

    • Eviction is all-or-nothing per sequence, since a partial KV is useless. Preempted requests are re-admitted with priority once memory frees up.

  • Tuning signal: frequent preemption means the KV pool is undersized. Raise gpu_memory_utilization, lower max_num_seqs, or add GPUs rather than relying on either mechanism.

Q70.How does copy-on-write allow parallel generation branches to share KV cache blocks?

Senior

Parallel branches (parallel sampling, beam search) start from the same prompt. Their block tables can point to the same physical KV blocks, tracked by reference counts. A block is copied only when one branch must write into a block that others still share, which in practice is only the last, partially filled block.

  • Mechanism:

    1. Fork: the child copies the parent's block table (not the KV data), and each referenced block's ref count is incremented.

    2. Write: when a branch appends a token, the engine checks the target block's ref count.

    3. If ref count > 1: allocate a new block, copy the existing tokens' K/V into it, repoint this branch's table entry, and decrement the old block's count. Then write the new token.

    4. If ref count == 1: the block is private, so write in place.

  • Why it's cheap:

    • Full blocks are immutable because tokens are only appended. They stay shared for the branch's lifetime.

    • At most one partial block per branch is ever copied, so the copy cost is bounded by block_size tokens.

  • Beam search benefits most:

    • Beams constantly fork and get pruned. Ref counting frees blocks automatically when no surviving beam references them.

    • This avoids the frequent full-KV copies that naive implementations need. The vLLM paper reports much larger memory savings for beam search than for parallel sampling.

  • The same ref-count machinery underlies prefix caching across requests. Copy-on-write just adds the copy step for blocks that are still mutable.

Q71.How does SGLang's RadixAttention optimize multi-call generation workflows?

Senior

RadixAttention keeps the KV cache of all requests in a radix tree keyed by token sequences, instead of freeing it when a request ends. Any later call that shares a prefix automatically reuses that KV. This fits multi-call LLM programs (few-shot, multi-turn, fork/branch, agent loops), where calls overlap heavily.

  • Radix tree cache:

    • Edges hold token sequences and nodes map to KV pages. Insertion splits nodes at divergence points.

    • Matching finds the longest cached prefix at token granularity (page size 1 by default), not only at full-block boundaries.

    • Reuse is automatic: no manual prompt-cache API is needed.

  • Eviction:

    • LRU eviction removes leaves first, so shared ancestors (system prompts) survive longest.

    • Nodes used by running requests are ref-counted and cannot be evicted.

  • Cache-aware scheduling:

    • Waiting requests are ordered by longest shared prefix, which approximates a depth-first traversal of the tree.

    • Requests that share a subtree run close together, before it can be evicted, which raises the hit rate versus FCFS.

  • Frontend co-design for multi-call programs:

    • SGLang primitives like fork, gen, and select make branches explicit.

    • Forked branches share the parent's KV, and the frontend can send the shared prefix first so branches hit the cache.

    • Typical wins: tree-of-thought, self-consistency sampling, multi-turn chat, few-shot evaluation, and agents re-sending growing histories. The SGLang paper reports up to several times higher throughput on such workloads.

Q72.What conditions cause an inference engine to evict shared prefix blocks from GPU memory?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q73.What causes prefill starvation in a unified continuous batching scheduler?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q74.Under load, p99 time to first token spikes while time per output token stays stable. How would you diagnose and fix this?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q75.Throughput on your serving cluster drops sharply after users start sending much longer prompts. What is happening and what would you change?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q76.How does SmoothQuant mitigate activation outliers?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q77.How does GPTQ use second-order Hessian information to minimize quantization error?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q78.Why can INT4 weight-only quantization run slower than FP16 at very large batch sizes?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q79.You need to serve a 70B model on a single 80GB GPU. Which quantization approach would you choose and what trade-offs would you weigh?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q80.Why does speculative decoding preserve the exact output distribution of the target model?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q81.Under what conditions does speculative decoding cause a slowdown rather than a speedup?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q82.How does EAGLE use the target model's hidden features to improve draft acceptance rates?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q83.How does tree-based speculative decoding verify multiple candidate branches in parallel?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q84.How does FlashDecoding parallelize attention across the sequence dimension during decode?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q85.Why does standard FlashAttention provide limited speedup during the decode phase compared to prefill?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q86.How do inference runtimes like vLLM use CUDA Graphs despite variable batch sizes?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q87.What are the trade-offs of ahead-of-time engine compilation in TensorRT-LLM compared to PyTorch eager or JIT execution?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q88.What collective communication operations does tensor parallelism require per transformer layer?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q89.What network bottleneck is introduced by transferring KV caches in disaggregated serving?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q90.How does expert parallelism in MoE serving introduce all-to-all communication overhead?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q91.What causes GPU load imbalance when serving MoE models with expert parallelism?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q92.How does context parallelism enable serving very long context sequences?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q93.How do pipeline bubbles affect latency and utilization in distributed decoding?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q94.When would you choose prefill-decode disaggregation over running both phases on the same GPU cluster?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q95.What GPU signals or metrics should trigger autoscaling in an LLM serving cluster?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q96.How would you estimate the cost per million output tokens for a self-hosted model deployment?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q97.How would you choose GPU hardware for serving a given model under a latency SLO and a cost budget?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.