Skip to content

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.

21 min read0/5 questions

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 familyExamples (check each model card)What it means for you
Apache 2.0 or MITOpenAI's gpt-oss models, many Qwen and Mistral modelsCommercial use, modification and fine-tuning allowed, with attribution
Custom community licenceMeta's Llama modelsCommercial use allowed with conditions: naming rules, an acceptable use policy, and a clause for very large companies
Research or non-commercialSome releases from labs and universitiesYou 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.

Quick check
A teammate wants to ship a product feature on a model they found on Hugging Face, described as 'open source'. What should you check first?
Need a nudge? A hint rules out a wrong answer.

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

PrecisionBytes per parameter8B model70B model
FP16 / BF162about 15 GiBabout 131 GiB
FP8 or INT81about 7.5 GiBabout 66 GiB
4-bit0.5about 3.7 GiBabout 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:

Python
GIB = 1024 ** 3 BYTES_PER_PARAM = {"FP16": 2.0, "FP8": 1.0, "INT8": 1.0, "4-bit": 0.5} # Published architecture numbers (check the model's config.json).MODELS = { "8B dense": {"params": 8.0e9, "layers": 32, "kv_heads": 8, "head_dim": 128}, "70B dense": {"params": 70.6e9, "layers": 80, "kv_heads": 8, "head_dim": 128},} def weights_gib(params, fmt): return params * BYTES_PER_PARAM[fmt] / GIB def kv_cache_gib(m, tokens, kv_bytes=2): # 2 = one K and one V tensor per layer per_token = 2 * m["layers"] * m["kv_heads"] * m["head_dim"] * kv_bytes return per_token * tokens / GIB for name, m in MODELS.items(): print(name) for fmt in ["FP16", "INT8", "4-bit"]: print(f" weights {fmt:5}: {weights_gib(m['params'], fmt):6.1f} GiB") for users, ctx in [(1, 8_192), (16, 8_192), (16, 32_768)]: kv = kv_cache_gib(m, users * ctx) print(f" KV cache, {users:2} users x {ctx:6,} tokens: {kv:6.1f} GiB")
Output
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.

What fills a GPU serving one model
  1. Model weightsfixed: parameters x bytes
  2. KV cachegrows with context x concurrent users
  3. Activations and buffersworking memory per batch
  4. Runtime overheadCUDA context, graphs, fragmentation

Weights load once and never grow. Quantisation shrinks them: 4-bit is about a quarter of FP16.

1/4

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_heads from the model's config.json instead of assuming.
Predict the outputPython

What does this print?

params = 70e9
bytes_per_param = 0.5   # 4-bit
print(params * bytes_per_param / 1e9)
Need a nudge? Hints walk you through it.

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:

FormatWhere it runsNotes
GGUF (Q4_K_M, Q5_K_M, Q8_0 ...)llama.cpp, Ollama, LM StudioOne 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, GPTQvLLM, SGLang, TGI on GPUs4-bit weight-only formats for GPU servers.
FP8Recent data-centre GPUs with vLLM or SGLang8-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 the pairs0/4 matched

Match each situation to a sensible format or tool.

Choose an item, then its match on the other side.

Running a model on your laptop

For prototyping, three tools cover nearly everyone:

  • Ollama: a background server plus a model library. ollama run downloads and chats; the server listens on port 11434.
  • llama.cpp: the C++ engine many other tools build on. llama-server serves 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:

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-titler

With 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 8080

The 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:

local_client.py
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.

Quick check
Your vLLM server handles 4 users smoothly, but at 40 concurrent users with long RAG prompts, requests queue and time to first token climbs. GPU utilisation looks fine. What is the most likely limit?
Need a nudge? A hint rules out a wrong answer.

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.

Python
# Illustrative inputs only. These are NOT real prices: plug in your own quotes.GPU_COST_PER_HOUR = 4.00 # one rented GPU server, in your currencyAPI_COST_PER_MILLION = 1.00 # blended input+output price of the API model you compare againstMEASURED_TOKENS_PER_SECOND = 2500 # total throughput from YOUR load test, all users combined def self_hosted_cost_per_million(utilisation): # utilisation: fraction of the hour the GPU is actually busy serving tokens_per_hour = MEASURED_TOKENS_PER_SECOND * 3600 * utilisation return GPU_COST_PER_HOUR / tokens_per_hour * 1_000_000 print(f"API: {API_COST_PER_MILLION:.2f} per million tokens, at any volume")for utilisation in [1.0, 0.5, 0.2, 0.05]: cost = self_hosted_cost_per_million(utilisation) verdict = "cheaper" if cost < API_COST_PER_MILLION else "dearer" print(f"self-hosted at {utilisation:4.0%} busy: {cost:6.2f} per million ({verdict})") # Break-even: how busy must the GPU be to match the API?full = self_hosted_cost_per_million(1.0)print(f"break-even utilisation: {full / API_COST_PER_MILLION:.0%}")
Output
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 it in order6 steps

Put the steps for moving a feature to a self-hosted open model in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.