Skip to main content
LearnMLAcademy
Intermediate10 min read

Efficient LLM Inference & Serving

Serve LLMs at scale with vLLM PagedAttention, KV cache reuse, and quantization, with token walkthroughs, prompt design tasks, and retrieval exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Why can generation feel slow and expensive?

An autoregressive LLM generates one token after another. Each new token depends on the existing sequence, so serving has to manage model memory, repeated attention work, batching, hardware utilization, and user latency.

KV cache — reuse attention states from earlier tokens

Without reuse, later generation steps would repeatedly recompute attention Keys and Values for the same earlier tokens. A KV cache stores those previous attention Key/Value states so the model can reuse them while generating later tokens.

KV caching reuses past attention state during token-by-token decoding

Request

tokenize prompt

Prefill

process all prompt tokens

KV cache

past K/V states

Decode token 1

reuse cache + append

Decode token 2 …

cache grows until stop

cache: promptcache: prompt + t₁cache: prompt + t₁ + t₂
The cache stores reusable attention states for the active sequence; it is runtime state, not persistent model memory.

Quantization — use fewer bits for weights

If a 1-billion-parameter model uses an idealized 8-bit representation, that is roughly one byte per parameter:

1,000,000,000 parameters × 1 byte ≈ 1 GB raw weight storage
This is a teaching estimate for raw weights only. Runtime memory also includes caches, activations/buffers, framework overhead, and other state.

Lower bit width can reduce memory, but 4-bit does not automatically mean faster. Actual latency depends on hardware support, kernels, runtime implementation, batch size, and workload.

Compare the raw-weight bars while keeping the additional runtime allocations in view. Reducing the weight representation does not remove the cache or the work needed to serve each request.

Lower bit width can reduce raw model storage—but runtime memory is larger

16-bit100%≈ 2 GB
8-bit50%≈ 1 GB
4-bit25%≈ 0.5 GB
+ KV cache+ buffers+ quantization metadata+ runtime overhead
Toy estimate for 1B parameters. Speedup still depends on kernels, hardware, runtime, and workload.

Two latency measures answer different questions

Interactive serving metrics

Interactive serving metrics
MetricQuestion it answers
Time to first token (TTFT)How long until the user sees the response begin?
Tokens per secondHow quickly does generation proceed after it starts?
End-to-end latencyHow long until the complete task finishes?

Batching trades individual waiting time for throughput

Serving several requests together can improve accelerator utilization and total throughput. But requests may wait in a queue while a batch forms or while long sequences occupy resources.

Typical trade-off

Typical trade-off
OptimizationCan improveCan worsen
Larger batchingHardware utilization, requests/tokens processed per secondQueueing delay and individual request latency
Aggressive long contextsInformation available to the modelMemory use and attention/serving cost
Lower precisionRaw model memoryQuality or speed if hardware/runtime support is weak

Why the next lesson matters

Serving optimization makes one model endpoint efficient. How do we version prompts, retrieval, models, observability, releases, retries, and rollback as one production LLM application?

LLMOps →

Summary / Key Takeaways

  • Autoregressive generation creates repeated inference work as tokens are produced sequentially.
  • KV cache stores prior attention Key/Value states so later tokens can reuse them.
  • A 1B-parameter 8-bit model is about 1 GB of raw weights in the simplified estimate, before runtime overhead.
  • Lower precision saves representation memory but does not guarantee faster latency on every hardware/runtime stack.
  • Time to first token measures initial responsiveness; generation rate and end-to-end latency answer different questions.
  • Batching can increase throughput while increasing queueing and per-request latency.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Efficient LLM Inference & Serving"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What does a KV cache primarily store during autoregressive inference?
Question 2 of 5numerical/formula
Ignoring runtime overhead, about how much raw weight memory does a 1B-parameter 8-bit representation require?
Question 3 of 5interpretation
Why can a 4-bit model fail to be faster than a higher-precision model on some hardware?
Question 4 of 5practical selection
Which metric is most directly about how quickly an interactive user sees the first generated token?
Question 5 of 5debugging/diagnostic
A team increases batch size and throughput rises, but individual requests wait much longer before processing. What trade-off is appearing?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What does a KV cache primarily store during autoregressive inference?▼

Correct Answer: Previous attention key/value states that can be reused

Cached past attention states reduce recomputation as the model generates later tokens.

2Ignoring runtime overhead, about how much raw weight memory does a 1B-parameter 8-bit representation require?▼

Correct Answer: 1 GB

One billion parameters at roughly one byte each is about one billion bytes, approximately 1 GB as a simple teaching estimate.

3Why can a 4-bit model fail to be faster than a higher-precision model on some hardware?▼

Correct Answer: Bit width alone does not determine speed; kernels, hardware support, runtime, and workload matter

Memory reduction is clear at the representation level, but actual latency depends on the execution stack.

4Which metric is most directly about how quickly an interactive user sees the first generated token?▼

Correct Answer: Time to first token

Time to first token captures initial interactive responsiveness; tokens/sec describes generation rate after that.

5A team increases batch size and throughput rises, but individual requests wait much longer before processing. What trade-off is appearing?▼

Correct Answer: Better throughput with worse queueing/latency

Batching can improve hardware utilization and throughput while adding waiting time for individual requests.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next