Lesson 34 of 40Building LLM systems
Open-Weight Models and Local Inference
Run open-weight models on a laptop or your own GPUs: licences, memory maths, quantisation, Ollama, llama.cpp, vLLM, and when self-hosting actually pays.
Your company signs a contract with a hospital group. Their lawyers add one line: patient notes must never leave infrastructure you control. The support assistant you built on a hosted API is now off the table for that customer. Someone suggests "just run Llama on our own servers", and the room turns to you with three questions. Will it fit on the GPUs we have? Will it be good enough? Will it cost more or less than the API? This lesson gives you the vocabulary and the arithmetic to answer all three with numbers instead of hope.
Open weights are not open source
When a lab publishes a model's weights (the trained numbers) so you can download and run them, the model is open-weight. People often say "open-source model", but that is usually wrong. Open source means you get the source and the right to use, change and share it under an approved licence. For a model, the real "source" is the training data and training code, and almost nobody releases those. What you get is the finished weights plus a licence, and the licences differ a lot.
| Licence family | Examples (check each model card) | What it means for you |
|---|---|---|
| Apache 2.0 or MIT | OpenAI's gpt-oss models, many Qwen and Mistral models | Commercial use, modification and fine-tuning allowed, with attribution |
| Custom community licence | Meta's Llama models | Commercial use allowed with conditions: naming rules, an acceptable use policy, and a clause for very large companies |
| Research or non-commercial | Some releases from labs and universities | You may experiment; you may not ship it in a product |
The licence is attached to each model, not to the lab. One company can release an Apache 2.0 small model and a restricted large one in the same month. Before anything reaches production, read the licence for the exact model and version you will deploy, and send anything unusual to legal. Fine-tuned derivatives on Hugging Face usually inherit the base model's licence, whatever the uploader wrote in the README.
Why teams self-host, and why most do not
There are four good reasons to run a model yourself:
- Data control. Prompts never leave your network. For some contracts and regulated data this is the deciding factor.
- Cost at steady, high volume. A GPU you keep busy around the clock can produce tokens more cheaply than an API. A GPU that sits idle half the day cannot.
- Freedom to customise. You can fine-tune, merge adapters, and pin a version forever. A hosted model can be retired on the provider's schedule.
- Offline and edge. Factory floors, ships, laptops on planes, phones.
And three reasons most teams stay on APIs:
- Quality gap on hard tasks. The strongest open models are very good, but on long agent runs and hard reasoning the frontier hosted models usually still lead. Measure on your own tasks before you assume either way.
- Operations. Someone has to own GPU capacity, drivers, upgrades, autoscaling, monitoring and on-call. That is a real team cost that never shows up in a per-token comparison.
- Idle hardware. Traffic is spiky. You pay for the GPU whether it serves one request or a thousand.
There is a middle road worth knowing: managed open models. Amazon Bedrock, Google Vertex AI and specialist inference providers (Together AI, Fireworks AI, Groq and others) host open-weight models behind an API. You get open-weight licensing and portability without running GPUs. You do not get "data never leaves our network", so it does not solve the hospital problem, but it often solves the cost one.
Memory maths: will it fit?
The first question about any model is whether it fits in GPU memory (VRAM). The weights alone need roughly:
parameters x bytes per parameter
| Precision | Bytes per parameter | 8B model | 70B model |
|---|---|---|---|
| FP16 / BF16 | 2 | about 15 GiB | about 131 GiB |
| FP8 or INT8 | 1 | about 7.5 GiB | about 66 GiB |
| 4-bit | 0.5 | about 3.7 GiB | about 33 GiB |
Real 4-bit files are a little bigger than this, because quantisation stores scale factors alongside the weights. Treat the table as a floor, then add headroom.
Weights are only part of the bill. Every token in every active conversation also needs a KV cache entry: the attention keys and values the model computed for that token, kept so it does not recompute them for every new token. Its size per token is:
2 x layers x KV heads x head dimension x bytes
For a Llama 3.1 8B-shaped model (32 layers, 8 KV heads, head dimension 128, FP16) that is 128 KiB per token. It sounds tiny until you multiply by context length and by the number of users served at once. Run the calculator:
Press Run (⌘ Enter) to see what happens.Look at the last line for the 70B model: sixteen users with long contexts need more memory for the KV cache than the 4-bit weights themselves. This is why a model that "fits" in a quick test falls over under real load. The KV cache grows with context length x concurrent requests, and it is the number most capacity plans forget.
Weights load once and never grow. Quantisation shrinks them: 4-bit is about a quarter of FP16.
Two more details that come up in design reviews:
- Mixture-of-experts (MoE) models have a large total parameter count but only a fraction of active parameters per token, because a router sends each token through a few expert sub-networks. All experts still have to sit in memory, so memory follows the total. Speed per token follows the active count. An MoE model can be much faster than a dense model of the same size, but it does not need less VRAM.
- Grouped-query attention (fewer KV heads than query heads) is why modern models have small KV caches compared with older ones. Always read
num_key_value_headsfrom the model'sconfig.jsoninstead of assuming.
What does this print?
params = 70e9 bytes_per_param = 0.5 # 4-bit print(params * bytes_per_param / 1e9)
Quantisation formats
Quantisation stores weights in fewer bits than they were trained in. Quality drops a little, memory and bandwidth drop a lot, and since generating each token is mostly limited by how fast the GPU can read the weights, smaller weights often mean faster tokens too. The formats you will see:
| Format | Where it runs | Notes |
|---|---|---|
GGUF (Q4_K_M, Q5_K_M, Q8_0 ...) | llama.cpp, Ollama, LM Studio | One file with weights and metadata. Runs on CPU, Apple Silicon and GPUs. Q4_K_M is a common default; Q8_0 is near-lossless. |
| AWQ, GPTQ | vLLM, SGLang, TGI on GPUs | 4-bit weight-only formats for GPU servers. |
| FP8 | Recent data-centre GPUs with vLLM or SGLang | 8-bit floating point. Small quality loss, good speed on hardware that supports it. |
The trade-off is not uniform. Quantisation tends to hurt small models more than large ones, and it can hurt specific skills (maths, long-context recall, a rare language) more than general chat. A 4-bit large model often beats an FP16 small model that uses the same memory, but "often" is not "always": run your own evals on the exact quantised file you will deploy, not on the original.
Match each situation to a sensible format or tool.
Running a model on your laptop
For prototyping, three tools cover nearly everyone:
- Ollama: a background server plus a model library.
ollama rundownloads and chats; the server listens on port 11434. - llama.cpp: the C++ engine many other tools build on.
llama-serverserves a GGUF file over HTTP. - LM Studio: a desktop app with a model browser and a local server, good for people who prefer a GUI.
ollama pull qwen3:8bollama run qwen3:8b "Summarise this in one line: the export button does nothing."Model tags change often; browse the Ollama library for current names. To change defaults such as the context window (local runtimes often default to a small one, which silently truncates long prompts), write a Modelfile:
FROM qwen3:8b
PARAMETER num_ctx 16384
PARAMETER temperature 0.2
SYSTEM You turn customer emails into short ticket titles.ollama create ticket-titler -f Modelfileollama run ticket-titlerWith llama.cpp you point the server at a GGUF file (or a Hugging Face repo with -hf) and choose the context size, GPU offload and port:
llama-server -m models/qwen3-8b-q4_k_m.gguf -c 16384 -ngl 99 --port 8080The useful trick is that all three expose an OpenAI-compatible HTTP API. Your application code does not care whether the model runs on a laptop, in your data centre or at a provider. Only the base URL changes:
from openai import OpenAI
# Ollama's OpenAI-compatible endpoint. The key is required by the client but ignored locally.
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
reply = client.chat.completions.create(
model="ticket-titler",
messages=[{"role": "user", "content": "The export button does nothing on Safari."}],
)
print(reply.choices[0].message.content)Compatible is not identical. Tool calling, structured output and streaming details vary by runtime and by model, so test the features you depend on.
Serving in production: vLLM and SGLang
A laptop runtime serves one person well. A production server has to serve hundreds of requests at once without wasting the GPU. vLLM and SGLang are the common open-source engines for this (Hugging Face's TGI is another you may meet in older stacks). Three ideas make them fast:
- Continuous batching. Instead of waiting for a whole batch to finish, the server adds new requests to the running batch at every generation step and removes finished ones. The GPU stays busy and short requests do not wait behind long ones.
- PagedAttention. vLLM stores the KV cache in small fixed-size blocks, like pages in an operating system, instead of one big reserved slab per request. Far less memory is wasted, so more requests fit at once.
- Prefix caching. Requests that share a beginning (the same system prompt and tools) reuse the cached KV blocks for that prefix. This is the self-hosted version of the prompt caching you saw in AI Features in Production.
vllm serve Qwen/Qwen3-8B --max-model-len 16384 --gpu-memory-utilization 0.90 --api-key "$VLLM_API_KEY"That starts an OpenAI-compatible server (port 8000 by default). For models too big for one GPU, --tensor-parallel-size splits each layer across several GPUs in one machine. Check the vLLM CLI reference for current flags; they change between releases.
Two numbers describe a serving setup, and they pull against each other:
- Per-user speed: tokens per second one user sees, plus time to first token.
- Total throughput: tokens per second across all users.
Bigger batches raise total throughput (cheaper per token) and lower per-user speed (slower for each person). A chat product needs a floor on per-user speed. An overnight batch job only cares about throughput. Load test with your real prompt lengths and concurrency, because a benchmark with 100-token prompts tells you nothing about 8,000-token RAG prompts.
Self-hosted versus API: doing the sum honestly
An API charges per token. A GPU charges per hour, busy or not. So the honest comparison depends on utilisation: how much of each hour the GPU is actually serving traffic. The numbers below are made up to show the shape of the calculation; plug in your own GPU quote, your API price and the throughput from your own load test.
Press Run (⌘ Enter) to see what happens.The same hardware swings from cheaper to many times dearer depending on how busy it is. And this sum still leaves out engineering time, redundancy (you need at least two replicas for availability, which halves utilisation at low traffic) and the cost of a quality gap if the open model gets more answers wrong.
Switching models without guessing
Moving a feature from an API model to an open-weight one is a model migration like any other, so it follows the evidence-first method from Choosing a Model, with a few open-model specifics:
Put the steps for moving a feature to a self-hosted open model in a sensible order.
- Tap the steps below in the right order.
- open-weight model
- A model whose trained weights are published for download under a licence. Not the same as open source: training data and code are usually not released.
- KV cache
- Stored attention keys and values for every token in active requests. Grows with context length times concurrent users.
- quantisation
- Storing weights (or the KV cache) in fewer bits, such as 8 or 4, to save memory and speed up inference at a small quality cost.
- GGUF
- The single-file model format used by llama.cpp, Ollama and LM Studio, with quantisation levels like Q4_K_M and Q8_0.
- mixture of experts
- A model that routes each token through a few expert sub-networks. Memory follows total parameters; speed follows active parameters.
- continuous batching
- Adding and removing requests from the running batch at every generation step, so the GPU stays busy and short requests are not blocked.
- PagedAttention
- vLLM's technique for storing the KV cache in small fixed-size blocks, cutting wasted memory so more requests fit at once.