LLMModule 16 · Hands-on labs

Hands-On LLM Serving and Optimization: the book's code as a lab track

Chi Wang and Peiheng Hu's O'Reilly book comes with a repository of notebooks and services, from a serving system built from scratch to a full Qwen3-14B optimisation case study. This module turns that repo into a lab sequence and pairs each lab with the course pages that explain it.

Source: orca3/llm-model-inference on GitHub (companion code for Hands-On LLM Serving and Optimization: Hosting LLMs at Scale, O'Reilly), read 4 Nov 2026 · book website · O'Reilly page. The repo has no licence file and asks readers to refer to the book, so it's summarised and linked here, not copied. READMEs saved in sources/16-*.

Start here (no maths needed)

A book that shows you how to build the "kitchen" that serves AI answers, with real code you can run yourself.

Think of it like this

Think of a pizza shop. Orders come in (requests). Someone at the counter takes them (the web server). A manager groups orders so the oven is always full (batching). The oven bakes them (the AI model on a GPU), and slices go out as soon as each one is ready (streaming). This book builds a small version of that shop in code, then shows how the big shops make it fast and cheap.

How it works

  1. Start with tiny examples that run on a normal computer, to see how a model produces words one by one.
  2. Build your own small "shop": a server that takes requests, groups them and streams answers.
  3. Swap in professional engines (vLLM, SGLang, TensorRT-LLM, llama.cpp).
  4. Try speed tricks: smaller numbers (quantisation), guessing ahead (speculative decoding), reusing work (caching).
  5. Finish with a real case study that tunes a large model step by step.

Why robots care

The book's first chapter includes "edge" serving, running a model on a device itself, and its last chapter covers edge AI. A robot is an edge device. It can't always wait for a server far away.

Try it

In the demo below, raise Max wait. Watch the batches get bigger and the oven work more efficiently, but each customer waits longer. That's the trade-off every server must choose.

Words to know

Serving
Running a model so people (or programs) can send it requests.
Batching
Grouping several requests to run together on the GPU.
Streaming
Sending the answer word by word as it's made.
Notebook
A document mixing code you can run with explanations.
Edge
Running AI on the device itself, not in a data centre.

Going deeper: the book map, the lab track, the from-scratch server's design, and practical gotchas.

Track: LLM. It connects to robotics through the book's edge-serving material (chapters 1 and 10) and llama.cpp (chapter 8), which is how models run on small, local hardware.

In this module
  1. Summary
  2. The book, chapter by chapter
  3. The lab track
  4. Inside the from-scratch server
  5. Dynamic batching (interactive)
  6. The Chapter 9 case study as a method
  7. Two inference books: which to read when
  8. Practical gotchas
  9. Why it matters for robotics
  10. Self-check

1. Summary

TL;DR

The repo holds code for chapters 2–4 and 6–9 of a 10-chapter O'Reilly book (chapters 1 and 5 are conceptual). Highlights:

Most labs need an NVIDIA GPU, and the authors suggest Google Colab if you don't have one.

2. The book, chapter by chapter

Chapter topics are from the repo README. The right-hand column is where this course already explains each topic.

ChapterTopics (per the README)In this course
1 Introduction to model servingModel anatomy and lifecycle, why optimise, serving paradigms (edge, single-model, multi-model), platforms09 hub, 13 · book map
2 LLM servingTransformer internals, autoregressive generation, attention, KV cache, prefill/decode, running vLLM09 · lifecycle, 09 · KV cache, 06 · Day 13
3 Serving system designSingle- and multi-model services from scratch, batching, streaming, Triton, cost vs latency designsSection 4 below, 09 · batching
4 Best practicesServing for agents (RAG, CAG), enterprise architecture, open-source vs cloud vendor, build or buy, performance measurement10 · agent harnesses, 09 · observability
5 ChallengesAccelerators and GPU specs, model-loading bottlenecks, KV sizing, arithmetic intensity of prefill vs decode09 · GPUs, 09 · roofline
6 Essential optimisationsDynamic/continuous batching, chunked prefill, scalable attention and fusion, quantisation, distillation, pruning, prefix caching and RadixAttention09 · 03, 09 · 04, 04 · distillation, 12 · serving video
7 Advanced optimisationsSpeculative decoding, multi-GPU and multi-node (data/tensor/pipeline/expert), prefill–decode disaggregation, advanced KV caching09 · 05, 12 · 5D parallelism, 12 · video 04
8 Serving frameworksvLLM internals, TensorRT-LLM, SGLang, llama.cpp, choosing a framework09 · Problem 18, 15 · benchmark caveats
9 Optimisation in practiceQwen3-14B with vLLM: hardware inspection, benchmarking, quantisation, distributed serving, trade-offsSection 6 below, 09 · Problem 24
10 AdvancementsSemantic caching, profiling, multimodal, edge AI, multi-LoRA serving, serving inside RL12 · LoRA, 08 · multimodal, 07 (RL needs fast rollouts)

3. The lab track

A suggested order, from the repo folders. Hardware notes are mine. Check each folder's README and requirements.txt before running.

#Lab (repo folder)What you doLikely hardwarePair with
1ch02/ notebooksStep through transformer execution, the KV cache, streaming and batching basics, then run Qwen on vLLMCPU for the internals; GPU for vLLM09 · KV sizer
2ch03/single_model_llm_servingRun and read a FastAPI server with a workload manager, batching, streaming and a vLLM endpoint (uses facebook/opt-125m)Small model, so likely CPU-friendly for the non-vLLM pathsSection 4, 09 · Problem 2 (SSE)
3ch03/multi_model_servingServe several models behind one service, including a Triton DenseNet exampleGPU helpful09 · Problem 21 (multi-tenant)
4ch04/KnowledgeAgent, AWS foldersA RAG + planning agent; Bedrock, JumpStart and Deep Learning Container deploymentsAPI keys / AWS account (costs money)10 · harnesses
5ch06/ quantisation notebookCompare precisions against throughputGPU09 · Problem 11
6ch07/ SpecDecode, LMCacheHands-on speculative decoding and advanced KV cachingGPU09 · Problem 10, 12 · video 04
7ch08/ SGLang, TensorRT-LLM, llama.cppRun the same model on three enginesGPU (llama.cpp can run on CPU)09 · Problem 18
8ch09/ optimisation planBenchmark Qwen3-14B with vLLM, then quantise, distribute and analyse the trade-offsNVIDIA GPU with at least 24 GB (46 GB+ recommended), 32 GB+ RAM, 100 GB+ disk (per the README)Section 6

4. Inside the from-scratch server

The chapter 3 single-model service is a good first serving codebase to read, because its parts mirror the ones in production engines. From its README:

HTTP request
  └─ main.py           API layer: FastAPI endpoints, validation, streaming responses
      └─ LLMEngine      orchestration: runs the processing loop, picks the backend
          ├─ WorkloadManager   queues requests (stream vs batch), forms batches, tracks sequences
          └─ ModelExecutor     manages a separate worker process and its queues
              └─ ModelWorker   runs inference (transformers) in that process: CPU/GPU, token generation
                  └─ ModelManager  loads and caches models and tokenizers

5. Dynamic batching

Before continuous batching, the classic server policy is dynamic batching: hold requests until either the batch is full or the oldest has waited T ms, then run them together. Bigger batches use the GPU better, but every request pays the wait.

Interactive: max-wait vs latency and throughput

A simulated stream of requests with random arrivals. A batch takes base + per-request × size ms. The batch launches when it's full or when the oldest request has waited Max wait. All timings are illustrative assumptions.

Mean batch size
–
Mean latency
–
p95 latency
–
GPU busy
–

The chart sweeps Max wait from 0 to 200 ms at the current rate and batch size: mean latency (line) and mean batch size (bars). The marker shows your setting. With base 30 ms + 4 ms per request, one request at a time (batch size 1) tops out near 29 requests/s. Raise the rate past that with batch size 1, then let batching rescue it.

Continuous batching (Module 09 page 03) removes most of this trade-off for LLMs. It admits new requests at every decode step instead of waiting to form a batch. That's why modern engines use it.

6. The Chapter 9 case study as a method

The ch09 guide describes an end-to-end workflow for Qwen3-14B on vLLM. The parts worth copying into your own work:

  1. Inspect the hardware (GPU, VRAM) before choosing settings.
  2. Inspect the workload. The repo's inspect_dataset.py prints prompt and output length distributions for ShareGPT, random and "prefix repetition" datasets. Its example output shows a heavily skewed distribution, with many very short prompts and a long tail. That shape drives batching and caching choices.
  3. Benchmark a baseline on realistic data (ShareGPT conversations, plus a prefix-repetition set to test caching).
  4. Change one thing at a time (quantisation, distributed serving, caching) and re-measure.
  5. Write up the trade-offs, not just the best number. That's the same discipline as Module 04's honest results and Module 08 Stage 11.

7. Two inference books: which to read when

Inference Engineering (Kiely, Baseten)Hands-On LLM Serving and Optimization (Wang & Hu, O'Reilly)
Shape8 chapters, stack-wide: prerequisites → models → hardware → software → techniques → modalities → production10 chapters, code-backed: from-scratch serving systems → optimisations → frameworks → a case study
CompanionInteractive site with calculators and quizzes (Module 15)This repo: notebooks and services
Best forThe mental model and production decisionsBuilding and running things
In this courseModule 13 100-day planThis module's lab track

Suggestion: follow Module 13's plan with Kiely for reading, and slot in labs from section 3 as the "build" for each block. For example, run lab 2 during Kiely's chapter 4 (software), and labs 5–6 during chapter 5 (techniques).

8. Practical gotchas

9. Why it matters for robotics

10. Self-check

Why does the chapter 3 server run the model in a separate process?

To isolate heavy GPU work from the API layer. The server stays responsive, and an inference crash doesn't kill the web front end.

In dynamic batching, what does raising the max wait do?

Batches get bigger, so GPU efficiency and throughput go up. But each request waits longer, so latency rises, especially at low traffic.

Why does continuous batching beat dynamic batching for LLMs?

LLM requests generate many tokens of varying length. Continuous batching admits and retires requests at every decode step, so nobody waits for a batch to form and slots don't sit idle while long requests finish.

What should you check before trusting the chapter 9 benchmark setup today?

The vLLM version (the guide suggests v0.6.0), the dataset file actually downloaded, and that Git LFS artefacts are present.

Which two book chapters matter most for on-robot inference?

Chapter 1 (the edge serving paradigm) and chapter 10 (edge AI, multi-LoRA). Chapter 8's llama.cpp section is the practical tool.