← govind p lal
AI and ML Bootcamp · Lecture 32 · lecture notes

Inference Engineering

In short — What is inference, and why is it harder for generative models than for classical ML? This lecture walks through a single request (prefill and decode), the metrics used to measure it, the GPU hardware underneath, the software stack, and one optimization, speculative decoding.

Training vs Inference

builds on Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026

AI development has two parts: training and inference. Training - weights are learned and saved. Happens once per model release. Inference - using the saved weights to answer new inputs. Happens on every request, forever.

Making this faster, cheaper, more efficient and more reliable -> Inference Engineering.

Why Generative AI Inference Is Hard

builds on Lecture 5: Week 4 - AI&ML | Transformers: Part 2 | 07/02/2026
Classical ML (XGBoost, scikit-learn)Generative AI
Model sizeMegabytesHundreds to thousands of GBs
Output sizeKnown shapeUnknown length
StateStatelessStateful (KV cache)
ScalingReplicate on another machineNeeds specialised hardware and optimisation

Unpredictable output length -> you cannot know compute, time or batch size in advance. Stateful -> the KV cache is read and appended on every token, so it must be maintained across the request. (Extra overhead) Unpredictability + statefulness make inference hard.

Prefill and Decode

builds on Lecture 5: Week 4 - AI&ML | Transformers: Part 2 | 07/02/2026, Lecture 2: Week 1 - AI and ML | Fast-tracking the course of AI | 18/01/2026

Every request is forward passes. Two phases:

Why: prefill speed depends on how fast you can process many tokens (compute). In decode the KV cache keeps growing and hits the memory limit (memory).

Input tokensPrefillcompute boundKV cache + 1st tokenDecode loopmemory boundStop / max tokens
Life of one request.

Three Layers and API vs Own GPUs

Before running your own models, evaluate if dedicated GPUs are viable versus a shared API.

Inference Metrics

Two views to measure:

Model Facts That Matter: Attention, KV Memory, MoE

builds on Lecture 5: Week 4 - AI&ML | Transformers: Part 2 | 07/02/2026, Lecture 7: Week 6 - AI&ML | What Changed Since 2017 — and Let's Build It | 21/02/2026

Transformer block: MLP holds most of the parameters. Attention is the most expensive operation in inference.

Example

A 13B model with 8000 tokens needs ~7 GB of KV cache per sequence. The weights are 26 GB. This is the memory problem.

Mixture of Experts (MoE) - the MLP is replaced by many small expert blocks chosen by a small router, trained during training.

!

At batch size 1, MoE is a big win (e.g. 8 of 128 experts active). At large batch (e.g. 100), different requests pick different experts, so nearly all are active and the benefit disappears.

Autoregressive models generate token by token. Image and video models are mostly diffusion models using iterative denoising.

GPU Hardware

builds on Lecture 6: Week 5 - AI&ML | Introduction to Tensors and PyTorch | 14/02/2026

CPU - complex computations, sequential. GPU - very simple operations, blazingly fast across thousands of data elements. Models are matrix multiplications, a uniform operation. Perfect fit. (Originally made for graphics)

A GPU has streaming multiprocessors (SMs) instead of CPU cores. H100 has 132 SMs. Inside each SM:

Memory hierarchy:

Sizing GPUs and the Compute-Memory Balance

A GPU has two resources: compute (FLOPs) and memory bandwidth. Operations-to-byte ratio - FLOPs the GPU must perform per byte fed to keep both busy.

Arithmetic intensity - FLOPs the workload actually performs per byte moved. Below the hardware ratio -> memory bound (decode). Above -> compute bound (prefill). Inference engineering tries to keep both resources busy.

Why Standard Attention Is Expensive

builds on Lecture 5: Week 4 - AI&ML | Transformers: Part 2 | 07/02/2026

Q, K, V are each N x d (e.g. 4096 x 128). S and P are scratchpad intermediates.

GPU Generations and Multi-GPU Communication

Letter = generation: H Hopper, B Blackwell, L Lovelace. Rubin comes next. Higher number = better (B300 > B200). Hopper added FP8 support; Blackwell added FP4. A kernel written for H100 may not use B200 well. That is why kernel work exists.

A node holds 8 GPUs connected by NVLink and NVSwitch. Between nodes, InfiniBand (NVIDIA), faster than Ethernet.

The Software Stack

builds on Lecture 6: Week 5 - AI&ML | Introduction to Tensors and PyTorch | 14/02/2026
GPU hardwareCUDA programmingmodelKernelsflash attention, cuBLASPyTorch frameworkInference enginevLLM, SGLangOrchestration
Inference software stack, bottom to top.

Kernel - just a function that runs on the GPU across many threads. Every model operation (matmul, activation, softmax) is a kernel.

Kernel fusion - combine several kernels into one.

Flash attention - fused kernel keeping intermediates in fast SRAM to make fewer round trips to VRAM. Makes compute cheaper. Paged attention - stores KV cache in small blocks instead of one contiguous space, like memory pages. Solves memory fragmentation (e.g. four 250 KB blocks instead of one 1 MB block). Started with vLLM.

!

Flash attention and paged attention solve different problems: compute round trips vs KV cache memory layout.

Inference engines (vLLM, SGLang, TensorRT) serve models with built-in optimisations and optimised kernels. They are opinionated, so switching is hard.

Speculative Decoding

builds on Lecture 2: Week 1 - AI and ML | Fast-tracking the course of AI | 18/01/2026

The Problem LLMs generate one token at a time. Decode is memory bound, so compute sits idle.

The Solution A small draft model guesses 3-4 next tokens. The target model verifies all of them in a single forward pass. Accepted tokens are a free speedup; rejected ones are discarded. Verification is cheaper than generation, like checking a Sudoku answer vs solving it.

One rejection kills everything after it.

MethodHow drafts are made
Draft-targetSeparate smaller model
MedusaExtra output heads on the target model
EagleExtra trained head on the final layer
N-gramNo model; dictionary from seen tokens, statistics only

Other techniques to study yourself: batching, quantization, KV cache reuse, prefix caching.

Glossary

Inference
Using trained, fixed weights to answer new requests.
Prefill
First forward pass that processes all input tokens and builds the KV cache. Compute bound.
Decode
Per-token generation loop reusing the KV cache. Memory bound.
TTFT
Time to first token.
SM
Streaming multiprocessor, the GPU's basic compute unit with CUDA, tensor and special function cores.
HBM
High bandwidth memory, the large DRAM that forms VRAM.
Kernel
A function that runs on the GPU across many threads.
Kernel fusion
Merging several kernels into one to cut memory round trips.
Paged attention
Storing the KV cache in small non-contiguous blocks.
Speculative decoding
A cheap draft proposes tokens that the target model verifies in one pass.