inference · Level 4
Inference engines explained
How a model actually runs on real hardware: memory, speed, batching, and how to serve it safely.

Your next step
Start this course online
Register your start, then work through the lessons and exercises at your own pace. You can download the PDF separately. Where a scored exam is available, you will find it after the lessons.
Register or resume your course
Start with the essentials
The short answer
An inference engine is the software that runs a trained model to produce output. It loads the weights into memory, turns your prompt into tokens, then generates the reply one token at a time. Whether a model runs, and how fast, is mostly a memory question: the weights plus the KV cache must fit, and quantisation shrinks them at some cost to quality.
What you will learn
- You will be able to explain the difference between training and inference, and what is inside a model download.
- You will be able to estimate the memory a model needs from its parameters, precision and context length.
- You will understand quantisation well enough to weigh precision, memory and quality for your own use.
- You will be able to explain prefill, decode, batching, paged attention and speculative decoding in plain terms.
- You will know the trade-offs between local and hosted inference, and between GPU, CPU and unified memory.
- You will be able to serve a model over a local HTTP API and lock it down sensibly.
Who it is for
Readers who already use AI tools or APIs and now want to know what happens when a model runs, so they can size hardware, choose an engine and serve models safely. There is some arithmetic, but nothing beyond multiplication.
Before you start
- Comfort with tokens and context windows (see What is AI?).
- The workbook GPU memory maths for LLMs and SLMs is the natural preparation: chapter 3 here recaps its memory sum only briefly.
- A terminal is helpful for the exercises but not essential.
Learn in your browser · Chapter 01 of 07
Training, inference and the model file
Training builds a model. Inference uses it. Almost everything a builder does with AI is inference, and it has an engineering craft of its own.
Training adjusts a model's numbers, called weights or parameters, until it predicts text well. It happens on large clusters, once or in stages. Inference runs the finished model to produce output. The weights do not change while you use it, and the model remembers nothing between requests unless the earlier text is sent again.
An inference engine is the software that does this work. It loads the weights into fast memory, turns your text into tokens, runs the calculations, picks the next token and repeats. Around that loop it manages memory, schedules many users and offers an interface such as an HTTP API.
A model download is a bundle: the weights (by far the biggest part), a tokeniser that converts text to token numbers, and a configuration file describing the architecture, such as the layer count and context length. Weights come in a few common formats.
Scroll sideways to see every column.
| Format | What it is | Worth knowing |
|---|---|---|
| safetensors | A simple tensor file format designed to be safe, unlike pickle, and fast to load. | Common for models shared on public model hubs. |
| GGUF | A single binary file holding weights and metadata for engines built on the GGML library, such as llama.cpp. | Often used for quantised models on personal machines. |
| Pickle-based checkpoints | Older Python checkpoint files built on pickle serialisation, which can run code when loaded. | Prefer other formats. Load pickle files only from sources you trust. |
Try it yourself · Activity 01
10 minRead a model's file list
Find out what is really inside a model download before you ever run it.
- Open any open-weight model's page on a public model hub and go to its Files tab.
- Note the weight file format, the number of weight files and their combined size.
- Find the licence and the parameter count on the model card.
- Divide the total size in bytes by the parameter count. That is roughly the bytes per parameter.
What precision does your bytes-per-parameter figure suggest? What else would you check before running the model?
Learn in your browser · Chapter 02 of 07
Precision and quantisation
Every weight is a stored number. How many bits you spend on each one is your biggest lever over memory.
A parameter is one learned number. At 16-bit precision it takes 2 bytes, at 8-bit 1 byte and at 4-bit half a byte. Quantisation means storing weights with fewer bits than the model was trained with, so the file and its memory footprint shrink.
Scroll sideways to see every column.
| Precision | Bytes per parameter | Weights for an 8-billion-parameter model |
|---|---|---|
| 16-bit | 2 | 16 GB |
| 8-bit | 1 | 8 GB |
| 4-bit | 0.5, and a little more in practice | 4 GB, and a little more |
The trade-off has three sides. Memory: smaller files fit on smaller devices. Speed: moving fewer bytes per token usually makes generation faster (chapter 4 explains why). Quality: rounding weights throws away some information. Lighter quantisation usually costs little and heavier costs more, but not equally for every task. The only reliable way to know is to test on your own work.
Real 4-bit formats also store small scaling values beside the weights, so the true size sits a little above the simple sum. Some engines can quantise the KV cache too (chapter 3). Some models are already published in a mixed low precision, so read the model card before you quantise anything twice.
Learn in your browser · Chapter 03 of 07
Memory in brief: weights plus KV cache
Whether a model runs comes down to one sum. Here it is in brief, from the engine's side.
Two things must fit in fast memory: the fixed weights, and the KV cache, which stores the keys and values attention has computed for every earlier token in each chat.
need = parameters x bytes_per_parameter (weights)
+ cache_per_token x tokens x chats (KV cache)
+ allowance (runtime overhead)The per-token figure comes from the model's configuration. The allowance has no published size: like the workbook named below, this recap assumes the larger of 1 GB or 10% of weights plus cache, and keeps 10% of the device free as a safety margin. Measure, then replace both.
Illustrative, imaginary model, decimal GB: 8 billion parameters at 4-bit,
131,072 bytes of 16-bit cache per token, one 8,192-token chat
weights 8 billion x 0.5 = 4.00 GB
cache 131,072 x 8,192 = 1.07 GB
allowance the 1 GB floor = 1.00 GB
need = 6.07 GB, within 0.9 x 8 = 7.20 GB on an 8 GB cardEach extra chat adds its own cache while the weights stay put, so an engine's spare memory is a budget of cached tokens shared by all active chats (chapter 5). If it runs short, shorten the context, serve fewer chats, lower the precision, quantise the KV cache where supported, or offload layers to the CPU (chapter 6). Count every expert of a mixture-of-experts model, not only the active ones.
Try it yourself · Activity 02
10 minHow many chats fit?
How many 8,192-token chats of this model fit at once on a 16 GB card (an example size)?
- Add chats until the need, allowance included, passes 0.9 x 16 GB.
- Repeat for 32,768-token chats.
What does a longer maximum context cost an engine?
Worked answer
Usable: 14.40 GB. Eight chats: 4.00 + 8.59 + 1.26 (10%) = 13.85 GB, which fits. Nine: 4.00 + 9.66 + 1.37 = 15.03 GB, too much. At 32,768 tokens, two fit (13.85 GB) and three need 18.57 GB: four times the context, a quarter of the chats.
For the full method, its limits, and the memory that training and adapters need, see the workbook GPU memory maths for LLMs and SLMs.
Learn in your browser · Chapter 04 of 07
Prefill, decode and the two speeds
When someone says a model is fast, ask: fast at what? Generation has two very different phases.
Prefill processes your whole prompt in one pass. All the prompt tokens can be handled in parallel, so it is dominated by raw arithmetic and takes longer as prompts grow. It ends when the first output token appears. That wait is the time to first token.
Decode then writes the reply one token at a time. Each token depends on the one before, so the steps cannot run in parallel. Every step must read all the active weights, and the growing KV cache, from memory. That makes decode usually limited by memory bandwidth, the rate at which data moves, rather than by arithmetic. It is why replies stream out word by word.
A rule of thumb, as an upper bound: if each decode step must read W gigabytes and your memory delivers B gigabytes per second, one chat cannot exceed roughly B divided by W tokens per second. Halve W by quantising and the ceiling roughly doubles. Real speed is lower, so measure your own setup.
Scroll sideways to see every column.
| Term | Meaning | What tends to improve it |
|---|---|---|
| Time to first token | The wait before the first word appears (prefill). | Shorter prompts, reusing work for a repeated prompt start, more compute. |
| Inter-token latency | The gap between words while streaming (decode). | More memory bandwidth, lower precision, speculative decoding. |
| Throughput | Total tokens per second across every user. | Batching, better memory management. |
| Latency | How long one user waits overall. | Fewer users per machine, a smaller model. |
Try it yourself · Activity 03
15 minMeasure the two speeds
See prefill and decode for yourself with any engine or streaming API you can use.
- Send a very short prompt and ask for a 200-word reply. Time the wait for the first word, then the time from first word to last.
- Paste in several pages of text, ask for the same reply and time both parts again.
- Compute words per second for the streaming part of each run.
Which number changed when the prompt grew, and which stayed about the same? What does that tell you about prefill and decode?
Learn in your browser · Chapter 05 of 07
Batching and three serving ideas
One user's request leaves most of a GPU idle. Serving engines exist to keep it busy without wasting memory.
Batching runs several requests through the model together. Because decode is limited by reading the weights, and one read can serve every sequence in the batch, adding sequences costs little extra time per step. That is how throughput rises.
Static batching waits for a batch to fill and runs it until the slowest request finishes, leaving finished slots idle. Continuous batching, also called iteration-level scheduling, re-forms the batch after every step: finished requests leave and waiting ones join at once. A 2022 systems paper described it, and it is a core feature of engines built for many users.
Paged attention attacks memory waste. Reserving one large contiguous block per request for its KV cache leaves gaps and duplicates. Paged attention splits the cache into small fixed-size blocks allocated as needed, borrowing the idea of virtual memory from operating systems. Less waste means more requests fit, which means bigger batches.
Speculative decoding speeds up decode. A small, fast draft (a separate small model, or a module built into the main one) guesses several tokens ahead. The large model checks them all in one parallel pass and accepts those it would have produced itself. Done correctly the output distribution is unchanged, so it alters speed, not answers. The gain depends on how often guesses are accepted.
Scroll sideways to see every column.
| Idea | Problem it attacks | Trade-off |
|---|---|---|
| Batching | Idle hardware | Each user may wait longer. |
| Continuous batching | Slots idling once a request finishes | More complex scheduling. |
| Paged attention | Wasted KV cache memory | The engine must manage blocks. |
| Speculative decoding | Slow token-by-token decode | Needs a draft, and the gain varies. |
Learn in your browser · Chapter 06 of 07
Hardware, engines, and local versus hosted
The right hardware follows from the memory sum, not the other way round.
GPU memory (VRAM) is fast and limited. If weights and cache fit, you get the best speed. CPU with system RAM can hold much larger models, but it generally moves data more slowly, so decode is slower. Unified memory lets the CPU and GPU share one pool, so more of the machine's memory is usable by the model. Its speed depends on that pool's bandwidth, so check the specification. Hybrid offload puts some layers on the GPU and the rest on the CPU, so a model bigger than your VRAM can still run, more slowly.
Three well-known open-source engines make useful examples. Each fact below was checked against the project's own documentation on 25 September 2026. Engines change quickly, so check current documentation before relying on any of it.
Scroll sideways to see every column.
| Engine | What it is | A natural first use |
|---|---|---|
| llama.cpp | A C/C++ engine for running models on a wide range of hardware, including CPU-only and mixed CPU and GPU. Uses the GGUF format and includes an HTTP server. | Personal machines and experiments. |
| vLLM | A library and server for high-throughput serving. Documents paged attention, continuous batching, speculative decoding and a chat-completions server. | Serving many users from GPU servers. |
| Ollama | A tool that downloads and runs open models on your own computer and exposes a REST API on your machine. | A quick way to try models locally. |
Scroll sideways to see every column.
| Question | Local, on your hardware | Hosted API |
|---|---|---|
| Does data leave your machine? | Not if you configure it to stay. | Yes, it goes to the provider. |
| Cost shape | Hardware up front, power, your time. | Pay per token, no hardware. |
| Scale and model size | Limited by your hardware. | The provider's capacity, often larger models. |
| Model choice | Open-weight models you can download. | The provider's catalogue. |
| Upkeep and security | Yours. | The provider's, plus their terms. |
Neither is better in general. Decide by data sensitivity, volume, and the model size you need.
Learn in your browser · Chapter 07 of 07
The local HTTP API, and running it safely
Most engines expose the model as a small web server. That is convenient, and it is also an attack surface.
The common pattern: the engine loads the model once and listens on an address and port. Your apps send JSON over HTTP and receive text back, often streamed. Many engines copy the chat-completions request format popularised by the big commercial chat APIs, so client code written for one can often be pointed at another by changing the base address.
# Illustrative request. The port and model name vary by engine.
curl 127.0.0.1:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "local-model", "messages": [{"role": "user", "content": "Say hello in five words."}]}'Bind to localhost. The address 127.0.0.1 means only programs on the same machine can connect. The address 0.0.0.0 means every network interface, which can expose your model to your whole network or the internet. The llama.cpp server documents a default of 127.0.0.1, and Ollama's FAQ says it binds 127.0.0.1 by default. Some container examples use 0.0.0.0 inside the container, so publish ports with care, and check the default of whatever you run.
- Keep the server bound to localhost unless you have a reason not to.
- If others need access, put an authenticating, encrypted reverse proxy in front. Do not simply open the port.
- Turn on the engine's API key option, and read what it covers. vLLM's documentation warns that its key protects only some routes.
- Do not enable experimental built-in tools, such as file access or shell commands, on a server others can reach. The llama.cpp server documentation warns against it in untrusted environments.
- Decide what is logged. Prompts and replies can hold personal or confidential data. Log metadata (time, model, token counts, errors) by default, keep content logs off unless needed, and protect and expire any you keep.
- Keep the engine and its libraries updated, and download weights only from the publisher's official page.
Try it yourself · Activity 04
10 minCheck what your server exposes
Prove to yourself who can reach your model.
- Start a local engine with its default settings.
- Use your operating system's network tool to find the address the server is listening on. Confirm it is 127.0.0.1 and not 0.0.0.0.
- From another device on the same network, try to reach the port. It should fail.
- Read the engine's log. Does it record your prompts?
What would you change before letting a colleague use this server?
Next, see how reasoning models spend extra computation, and how to judge a new model the day it lands.
Keep learning
The complete workbook
This workbook goes inside the engine that runs a model. You will learn what is in a model download, how to work out the memory a model needs, why generation has two different speeds, and how batching, paged attention and speculative decoding make serving efficient. It ends with the trade-offs between local and hosted inference and a safe way to serve a model over a local HTTP API.
- 01Training, inference and the model fileRead here · 1 exercise
Training builds a model. Inference uses it. Almost everything a builder does with AI is inference, and it has an engineering craft of its own.
- 02Precision and quantisationRead here · Reading
Every weight is a stored number. How many bits you spend on each one is your biggest lever over memory.
- 03Memory in brief: weights plus KV cacheRead here · 1 exercise
Whether a model runs comes down to one sum. Here it is in brief, from the engine's side.
- 04Prefill, decode and the two speedsRead here · 1 exercise
When someone says a model is fast, ask: fast at what? Generation has two very different phases.
- 05Batching and three serving ideasRead here · Reading
One user's request leaves most of a GPU idle. Serving engines exist to keep it busy without wasting memory.
- 06Hardware, engines, and local versus hostedRead here · Reading
The right hardware follows from the memory sum, not the other way round.
- 07The local HTTP API, and running it safelyRead here · 1 exercise
Most engines expose the model as a small web server. That is convenient, and it is also an attack surface.
Also inside: a 9-point checklist, a glossary of 12 terms and 10 questions and answers to test yourself. 4 hands-on exercises, each with a worked answer at the back where the workbook gives one.
The PDF is free. We ask for your name and email before downloading. Read the privacy notice at the download form. Free to download and use for personal learning, study groups and inside your own team. Please do not resell the workbooks or republish them as your own. Link people to trust-agent.ai instead.
Get your free PDF workbook
Enter your name and email, then download the complete workbook. This form also works without JavaScript.
Test yourself
Questions and answers
What is the difference between training and inference?
Training adjusts a model's weights so it predicts text well, and is done on large clusters. Inference runs the finished model to produce output. During inference the weights do not change, and the model remembers nothing between requests unless the earlier text is sent again.
What is quantisation, and does it ruin quality?
Quantisation stores weights with fewer bits, such as 8 or 4 instead of 16, so the model needs less memory. Lighter quantisation usually costs little quality and heavier costs more, unevenly across tasks. Test on your own work rather than trusting a rule.
Why does a serving engine claim most of the GPU's memory when it starts?
Some engines built for many users load the weights, then reserve much of the remaining memory as a KV cache pool before any request arrives, and hand out space from it as chats run. vLLM, for example, pre-allocates its cache using a configurable fraction of GPU memory. A nearly full card is therefore expected, not a leak. If other programs need room, lower that fraction, or the maximum context where the engine sizes its cache from it.
What happens when an engine runs out of KV cache memory?
It cannot keep every chat's cache in memory, so it must choose. Depending on the engine, new requests wait in a queue, or a running request is paused, its cache freed and later recomputed, which vLLM's documentation calls preemption. Some engines reject requests once their queue is full. So once the weights are loaded, the cache sets how many chats of a given length one machine can hold at once. Shorter contexts raise that number.
Why is generating a reply slower than reading the prompt?
Prompt tokens can be processed in parallel during prefill. Reply tokens are produced one at a time during decode, and each step must read the model's weights from memory. Decode is usually limited by memory bandwidth, not arithmetic.
What is continuous batching?
It is a scheduling method that re-forms the batch after every generation step. Finished requests leave immediately and waiting requests join, so the hardware stays busy. It raises total throughput compared with waiting for a whole batch to finish.
Does speculative decoding change the answers?
Not when implemented correctly. A fast draft proposes several tokens and the large model verifies them in one pass, accepting only those it would have produced. The output distribution is unchanged, so it affects speed rather than content.
Can I run a model without a GPU?
Yes, some engines run on the CPU alone, using system memory. It is slower, mainly because system memory moves data more slowly than graphics memory. Smaller or more heavily quantised models make CPU-only running more practical.
Is running a model locally more private?
It can be, because prompts need not leave your machine. But privacy then depends on your setup: who can reach the server, what it logs and where the weights came from. Local is not automatically safe.
Is it safe to expose a local model server to my network?
Not by default. Keep it bound to 127.0.0.1. If others need access, use an authenticating, encrypted reverse proxy, turn on the engine's API key, disable experimental tools, and decide deliberately what gets logged.
Write as you go
My notes
Use this scratchpad for your own notes, working or answers as you read. Notes are saved in this browser on this device. Downloading makes a local copy; it does not send your notes to Mickai.
Consolidate your learning
Review your work
Work through the exercises and questions, then compare your reasoning with the worked answers. A scored exam and verifiable certificate are not yet available for this course.
Review the questionsLearn the language
Key terms
- Inference
- Running a trained model to produce output. The weights are fixed while it runs.
- Weights (parameters)
- The learned numbers inside a model. Their count and precision decide most of its memory needs.
- Quantisation
- Storing weights with fewer bits than the model was trained with, to save memory at some cost in quality.
- KV cache
- The keys and values stored for every token already in each conversation, so attention does not recompute them. An engine needs room for one per active chat.
- Prefill
- The phase in which the engine processes the whole prompt in parallel before the first output token.
- Decode
- The phase in which the engine writes the reply one token at a time, usually limited by memory bandwidth.
6 of the workbook's 12 terms. The complete glossary is in the workbook.
Follow the evidence
Sources and checks
Facts last checked: .
These workbooks use AI assistance. See how the workbooks are made.
- llama.cpp: LLM inference in C/C++ (README)ggml-org, GitHub
- llama.cpp server documentationggml-org, GitHub
- GGUF file format specificationggml-org, GitHub
- vLLM (README)vLLM project, GitHub
- vLLM serve command documentationvLLM project
- vLLM documentation: Optimization and Tuning (preemption and cache pre-allocation)vLLM project
- Ollama (README)Ollama, GitHub
- Ollama FAQ: network exposure and concurrent requestsOllama, GitHub
- Ollama API documentation: compatibility with a common chat-completions APIOllama
- safetensors (README)Hugging Face, GitHub
- Pickle scanning and securityHugging Face Hub documentation
- Efficient Memory Management for Large Language Model Serving with PagedAttentionarXiv, 2309.06180
- Orca: A Distributed Serving System for Transformer-Based Generative ModelsUSENIX OSDI 2022
- Fast Inference from Transformers via Speculative DecodingarXiv, 2211.17192
- Accelerating Large Language Model Decoding with Speculative SamplingarXiv, 2302.01318
Created by Mickarle Wagstaff-Irons - Micky Irons with the Mickai team. Published by Mickai LTD. Last updated 25 September 2026.
NextKeep going
Where to go next
Recommended for you
Reasoning models and reasoning engines
What reasoning models are, when extra thinking pays off, how to control it, why a reasoning trace is not proof, and how classical reasoning engines differ.
Recommended for you
How to evaluate a new frontier model the day it lands
A ten-step method for judging a new model: primary sources, licence, architecture, hardware, benchmarks, your own tests, safety, jurisdiction and a decision record.
Recommended for you
Host a chatbot on your website, safely
Put a chatbot on your site without leaking keys or running up bills: server function, limits, CORS, privacy, accessibility, fallbacks, monitoring and a launch checklist.