Inference Engineering Foundations
Learn how a language model turns a prompt into a streamed answer, and what each step costs in memory and time. Work through real numbers for Llama 3.1 8B, runnable NumPy code, and the measurements serving teams rely on.
How to work through this course
Before you begin: Comfortable with everyday Python. The lessons introduce the math and the NumPy you need as you go.
By the end: Follow a request through every stage, calculate its memory and compute needs, and find which part of the system is causing a delay.
- Understand the idea. Read each section in order and study its diagrams. When a pause-and-predict question appears, commit to an answer before you reveal it. Look up unfamiliar terms in the glossary below.
- Try it yourself. Run the code examples and compare your output with the lesson's. Use the browser labs where available; steps that need a GPU are optional and say so.
- Check your understanding. Answer the knowledge check at the end of each lesson and make sure you can say why the other options are wrong. Complete all units to unlock the final quiz; the passing score is 80%.
The optional project brings the lessons together. Keep notes on your choices, results, and any failures so you can explain what you learned.
Course orientation
What is inference engineering?
Inference engineering is the work of running trained models quickly, cheaply, and reliably for real users. It covers everything between a user pressing Enter and the last token arriving: turning text into tokens, scheduling work on the GPU, holding each request's state in memory, streaming results back, and recovering when something fails.
The problem it solves
Getting one answer from a model in a notebook is easy. Serving thousands of people at once is not: prompts vary from a few words to whole books, GPU memory runs out, users expect the first word within a second, and every idle GPU second costs money. This course connects the model's arithmetic to those practical limits, so you can predict and fix them.
Request path
- 01Request boundary
A chat template and a tokenizer turn the user's messages into token IDs, and the request's settings (length limits, sampling, stop rules) come along with them.
- 02Model execution
Prefill runs the whole prompt through the model in one parallel pass. Decode then produces one new token per step until the answer is complete.
- 03Memory and scheduling
A scheduler shares the GPU between many requests, and the KV cache keeps each request's attention state so earlier tokens are never recomputed.
- 04Service behavior
Sampling, stop rules, streaming, cancellation, metrics, and error handling turn a stream of token IDs into an API people can depend on.
What it covers
- Measuring and improving latency, throughput, memory use, and cost per token.
- Deciding how requests are batched, scheduled, admitted, and given cache memory.
- Streaming, cancellation, monitoring, and cleaning up after every request.
Outside its scope
- Training or fine-tuning model weights. The PyTorch and Transformers courses cover that.
- Prompt writing. Better prompts do not fix memory limits, queues, or slow decode steps.
- A bare HTTP wrapper around a model. A real service still needs admission control, scheduling, and cleanup.
Key terms in this course
- Token
- The unit a model reads and writes: a word, part of a word, or a symbol, stored as an integer ID.
- Tensor
- An array of numbers with a shape, a data type, and a device. Weights, activations, and the KV cache are all tensors.
- Prefill
- The phase that processes all prompt tokens in one parallel pass and fills the KV cache.
- Decode
- The phase that generates one new token per step, reusing the KV cache.
- KV cache
- The stored attention keys and values of every earlier token, kept so decode does not recompute them.
- Batch
- A group of requests the GPU processes together, so one read of the weights serves all of them.
- Quantization
- Storing weights or the cache with fewer bits per number, such as 8 or 4 instead of 16, to save memory and time.
- TTFT
- Time to first token: from the moment a request arrives until its first token reaches the user.
- ITL
- Inter-token latency: the time between two consecutive streamed tokens.
- Throughput
- How much useful work the system finishes per second, such as output tokens or completed requests.
Syllabus
- 01What is inference engineering?Up nextTrace one chat request through the template, tokenizer, prefill, decode loop, detokenizer, and stream, with real token counts.
- 02Tensors, shapes, and the forward passOpenRead a tensor's shape, dtype, and strides, and say what every axis means.
- 03From text to model inputsOpenExplain how byte-level BPE turns text into token IDs and back, and why the same tokenizer must do both.
- 04Attention and the transformer blockOpenCompute a row of causal attention by hand: scores, scaling, mask, softmax, and the weighted mix of values.
- 05Generation is a loop, not one passOpenTurn a model's logits into next-token probabilities with softmax, and pick the greedy token.
- 06The KV cache and its memory costOpenExplain which attention results a model can reuse between tokens, and what it still computes at every step.
- 07Batching and scheduling: one weight read, many requestsOpenCalculate how much batching raises decode throughput from a model's size and a GPU's memory bandwidth.
- 08Quantization: fewer bits, measured errorOpenCompare FP32, BF16, FP16, FP8, INT8, and INT4 by bytes per value, range, and precision.
- 09Serve, measure, and optimize the bottleneckOpenMeasure TTFT, inter-token latency, TPOT, end-to-end latency, and throughput from the client, with warm-up and percentiles.
- QFinal graded quizComplete all units to unlock
Full unit-by-unit learning objectives (42 outcomes)
01 · What is inference engineering?
- Trace one chat request through the template, tokenizer, prefill, decode loop, detokenizer, and stream, with real token counts.
- Explain which parts of inference stay fixed and which grow with each request.
- Estimate prefill and decode time for Llama 3.1 8B on an H100 from memory bandwidth and compute.
- Define time to first token, inter-token latency, end-to-end latency, and throughput, and predict how a change trades one against another.
02 · Tensors, shapes, and the forward pass
- Read a tensor's shape, dtype, and strides, and say what every axis means.
- Follow the shape of every matrix multiplication in one Llama 3.1 8B layer.
- Count a model's parameters from config.json and turn them into bytes of weights and FLOPs per token.
- Explain why a transpose makes a tensor non-contiguous, and catch a head split that has the right shape but the wrong contents.
03 · From text to model inputs
- Explain how byte-level BPE turns text into token IDs and back, and why the same tokenizer must do both.
- Predict when token counts run well above word counts: numbers, code, emoji, and many non-English languages.
- Render a chat template, count its special tokens, and avoid the doubled start token.
- Calculate the embedding table's memory for Llama 3.1 8B and explain why a token ID's size means nothing.
- Describe how rotary position embeddings and RMSNorm prepare token vectors for each layer.
04 · Attention and the transformer block
- Compute a row of causal attention by hand: scores, scaling, mask, softmax, and the weighted mix of values.
- Explain why the causal mask sets future scores to negative infinity, and what leaks when it does not.
- Follow the tensor shapes of multi-head and grouped-query attention in Llama 3.1 8B, from 4,096 features to 32 heads of 128.
- Trace a decoder block through its norms, attention, SwiGLU MLP, and two residual adds, and count where its 218 million parameters live.
- Estimate how attention work per token grows with context length, and explain why fast kernels never store the full score matrix.
05 · Generation is a loop, not one pass
- Turn a model's logits into next-token probabilities with softmax, and pick the greedy token.
- Predict, with numbers, how temperature, top-k, and top-p reshape the distribution, and explain why temperature 0 means greedy selection.
- Explain what a random seed guarantees and why a busy server can still answer the same request differently.
- Configure end tokens, stop strings, and token limits, and tell from the finish reason which one ended a response.
- Stream text without broken characters or leaked stop strings.
06 · The KV cache and its memory cost
- Explain which attention results a model can reuse between tokens, and what it still computes at every step.
- Calculate KV cache memory per token and per request from a model's config.json.
- Estimate how many requests fit on one GPU, and name the settings that change that number.
- Build a KV cache in NumPy and check that it gives the same output as recomputing everything.
07 · Batching and scheduling: one weight read, many requests
- Calculate how much batching raises decode throughput from a model's size and a GPU's memory bandwidth.
- Draw static and continuous batching schedules for the same requests and count the empty slots in each.
- Build a padded batch with an attention mask and read each request's next-token logits from the right position.
- Explain how a scheduler admits waiting requests under a KV cache budget, and what it does when the cache runs out.
- Pick a batch size that meets an inter-token latency target from the latency and throughput trade-off.
08 · Quantization: fewer bits, measured error
- Compare FP32, BF16, FP16, FP8, INT8, and INT4 by bytes per value, range, and precision.
- Quantize and restore values by hand with a scale and a zero point, and predict the largest rounding error.
- Choose per-tensor, per-channel, or per-group scales, and count what their metadata costs in bytes.
- Estimate a quantized model's weight memory and its decode speed limit from the bytes it moves.
- Plan an evaluation that checks quality, memory, and speed before a quantized model ships.
09 · Serve, measure, and optimize the bottleneck
- Measure TTFT, inter-token latency, TPOT, end-to-end latency, and throughput from the client, with warm-up and percentiles.
- Choose between closed-loop and open-loop load, and explain why a closed loop can hide queueing.
- Read a request trace to decide whether queueing, prefill, decode, or the network is the bottleneck.
- Calculate the expected tokens per target pass and the speedup of speculative decoding from its acceptance rate and draft cost.
- Plan, measure, and defend one optimization for a Llama 3.1 8B service, using every lesson in this course.
Optional field project
Plan and measure a chat service
- 01Trace one request through the model
- 02Explain tokens, attention, and sampling
- 03Size memory for the real workload
- 04Measure the service and recommend one change
View optional project brief
Sign in to read the project brief.
Free guides and tools
- FoundationsLLM inference explained: from prompt to generated tokens
- Memory & attentionKV cache quantization explained: FP8, INT8, and scaling
- Optimization & decodingStructured outputs and constrained decoding in LLM serving
- CalculatorEstimate model weights and KV-cache memory
- PracticePractice inference algorithms in Python and NumPy