Level 2 Agentic Coding · Building with AI
Running Models Locally
Run open language models on your own laptop or server with Ollama, llama.cpp or LM Studio. Learn what GGUF files and quantization levels like Q4_K_M mean, work out how much memory a model needs, and call the local model from code.
- Level
- ●●●●● Easy
- Reading
- 14 min
- To learn it well
- 1 hour to read, 20 minutes to get a model running
- Builds on
- 17 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 17 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Matrices and Matrix Multiplication
- Partial Derivatives and Gradients
- Supervised, Unsupervised and Reinforcement Learning
- Large Language Models, Explained Simply
- Tensors and Shapes
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Quantization
- Running Models Locally
Read them roughly in this order. See it on the concept map →
Why it matters
Most people meet language models through a cloud API. But many capable models are open-weight models: their trained weights are published, and anyone can download and run them. Llama, Qwen, Gemma, Mistral, DeepSeek and gpt-oss are examples. Running a local model on your own hardware gives you things an API can't:
- Privacy. Prompts and documents never leave your machine. This matters for medical, legal and company data.
- No per-token bill. Once you have the hardware, a million tokens costs only electricity.
- Offline use on a plane, in a lab, or in an air-gapped network.
- Control. The model never changes under you, and you can run your own fine-tuned versions.
- Learning. You can see exactly how memory, context length and quantization trade off.
The costs are real too. Local models small enough for a laptop are clearly weaker than the best hosted models at hard reasoning and coding. You also become responsible for hardware, updates and serving. For many tasks, though, such as summarising, extracting, classifying, drafting and chatting over your own notes with Retrieval-Augmented Generation, a well-chosen local model in the 4- to 30-billion-parameter range is good enough. And it is free to try.
The intuition
A model file is mostly one enormous table of numbers, the weights. To produce each token, the computer must read essentially every weight once. Two facts follow, and they explain almost everything about running models locally:
- The weights must fit in fast memory, ideally the GPU's memory (VRAM), or the unified memory of an Apple Silicon Mac. A model that doesn't fit either won't load, or spills onto the much slower CPU and system RAM.
- Speed is limited by how fast that memory can be read, its memory bandwidth, more than by raw computing power. Reading 5 GB of weights from memory that delivers 400 GB per second takes at least 1/80 of a second, so at best about 80 tokens per second.
Quantization helps with both. Storing each weight in about 4.9 bits instead of 16 makes the file about 3.3 times smaller, so a model that needed a 24 GB GPU now fits in 8 GB, and runs roughly 3 times faster because there are fewer bytes to read. The price is a small loss of accuracy, which grows quickly below about 4 bits per weight.
Key idea Memory decides whether a model runs. Memory bandwidth decides how fast. A good default is the largest model whose Q4_K_M file, plus a gigabyte or two for context, fits in your GPU or unified memory.
How it works
The three popular tools
- Ollama is the easiest start. You install one app, type
ollama run gemma3and you're chatting. It downloads models from its own library (one command each), manages them, and runs a local server with an API on port 11434. Under the hood it uses llama.cpp's engine. It runs on macOS, Windows and Linux. - llama.cpp is the engine underneath much of the local-AI world: fast inference in plain C/C++ for CPUs, NVIDIA and AMD GPUs and Apple Silicon. It is more hands-on: you choose a GGUF file and set the flags yourself. It ships
llama-clifor chat andllama-server, an OpenAI-compatible HTTP server with a small web UI. It also defined the GGUF format and its quantization types. - LM Studio is a desktop app with a graphical interface. You search Hugging Face for models, it shows which quantizations fit your hardware, and you chat or run an OpenAI-compatible local server. On Macs it can also use Apple's MLX engine.
All three expose a local API, an HTTP endpoint on localhost that looks like a cloud API. Code written for the OpenAI or Ollama API can therefore switch to a local model by changing the base URL.
GGUF files
GGUF is the file format llama.cpp uses for models. It is a single file holding the weights (usually quantized) plus everything needed to run them: the architecture, the tokenizer and the chat template. Hugging Face hosts thousands of GGUF conversions. A repository typically offers one file per quantization level, named like Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf.
Reading quantization names
A quantization level says how many bits store each weight and how. In llama.cpp's naming, Q plus a number gives the rough bits per weight. _K marks the "k-quant" schemes, which quantize weights in blocks with per-block scales and keep some sensitive tensors at higher precision. The _S, _M, _L suffix (small, medium, large) says how many tensors get that extra precision. IQ types use more elaborate encodings that hold up better at very low bit counts. Because of the mixed precision, the effective bits per weight are a bit higher than the name suggests. Here are the real files for Llama 3.1 8B Instruct (8.03 billion parameters):
| Level | File size | Effective bits/weight | Typical use |
|---|---|---|---|
| F16 | 16.1 GB | 16 | reference; rarely worth it locally |
| Q8_0 | 8.5 GB | 8.5 | practically indistinguishable from F16 |
| Q6_K | 6.6 GB | 6.6 | very close to F16 |
| Q5_K_M | 5.7 GB | 5.7 | high quality, a good choice if it fits |
| Q4_K_M | 4.9 GB | 4.9 | the common default: small, small quality loss |
| Q3_K_M | 4.0 GB | 4.0 | noticeable degradation |
| Q2_K | 3.2 GB | 3.2 | big degradation; a last resort |
Rule of thumb: a bigger model at Q4 usually beats a smaller model at Q8 of the same file size. Small models (under about 3 billion parameters) suffer more from aggressive quantization than big ones.
The memory arithmetic
Total memory is roughly three parts:
- is the number of parameters and the effective bits per weight, so is bytes.
- The KV cache stores a key and a value vector (the factor 2) for every layer , every key/value head of size , at bytes per number, for each of the tokens in the context.
- Overhead covers buffers and the runtime, roughly half a gigabyte to a gigabyte or two.
Worked example: Llama 3.1 8B at Q4_K_M with an 8,192-token context. Weights: GB. KV cache: bytes per token (128 KiB), times 8,192 tokens, is 1.07 GB. Total: about 6 GB plus overhead, so it fits comfortably on an 8 GB GPU. Raise the context to 32,768 tokens and the KV cache alone becomes 4.3 GB, for about 9.2 GB in total. Long contexts cost real memory, which is why local tools often default to a modest context length.
Weights alone for common sizes (GB):
| Parameters | F16 | Q8_0 | Q5_K_M | Q4_K_M | Fits (Q4_K_M + context) on |
|---|---|---|---|---|---|
| 3B | 6.0 | 3.2 | 2.1 | 1.8 | almost anything, including CPU-only laptops |
| 8B | 16.0 | 8.5 | 5.7 | 4.9 | 8 GB GPU; 16 GB Mac |
| 14B | 28.0 | 14.9 | 10.0 | 8.6 | 12 GB GPU; 16–24 GB Mac |
| 32B | 64.0 | 34.0 | 22.8 | 19.6 | 24 GB GPU; 32 GB+ Mac |
| 70B | 140 | 74.4 | 49.9 | 42.9 | two 24 GB GPUs or a 48 GB card; 64 GB+ Mac |
These figures use the effective bits per weight from the table above. Real files vary by a few per cent between architectures. On a Mac, the GPU can use most but not all of the unified memory, and your other apps need some too.
When it doesn't fit: offloading
llama.cpp can split a model: some layers on the GPU, the rest on the CPU in system RAM. This is GPU offloading, controlled by -ngl (number of GPU layers). It lets a model run that wouldn't fit otherwise, but every token must now pass through the slow part as well, so speed falls sharply. Ollama does this split automatically, and ollama ps shows the split (for example "40%/60% CPU/GPU"). If you see a CPU share, a smaller quantization or a smaller model will probably feel much faster.
How fast will it be?
Generating each token reads all the weights once, so an upper bound on generation speed is
For the 4.9 GB Q4_K_M file: an RTX 4090 (about 1,008 GB/s) allows at most about 205 tokens per second, an M2 Max laptop (400 GB/s) about 80, and a desktop CPU with dual-channel DDR5 (about 90 GB/s) about 18. Real speeds are lower, often around half to three-quarters of the bound. Reading your prompt (prefill) is different. It processes many tokens in parallel and is limited by computing power, so GPUs are far faster than CPUs at it. That's why long prompts feel slow on CPU-only machines.
In code
First, the memory and speed arithmetic as a small calculator. Runs as written.
BITS = {"F16": 16, "Q8_0": 8.5, "Q6_K": 6.6, "Q5_K_M": 5.7, "Q4_K_M": 4.9, "Q3_K_M": 4.0}
def weights_gb(params_billion, quant):
return params_billion * BITS[quant] / 8 # 1e9 params * bits / 8 = GB
def kv_cache_gb(layers, kv_heads, head_dim, context, bytes_per_value=2):
return 2 * layers * kv_heads * head_dim * bytes_per_value * context / 1e9 # K and V
# Llama 3.1 8B: 32 layers, 8 key/value heads of size 128 (grouped-query attention)
for quant in ["F16", "Q8_0", "Q4_K_M"]:
w = weights_gb(8.03, quant)
for ctx in (8_192, 32_768):
kv = kv_cache_gb(32, 8, 128, ctx)
print(f"{quant:7s} ctx {ctx:6d}: weights {w:5.1f} GB + KV {kv:4.1f} GB = {w + kv:5.1f} GB (+ ~1 GB overhead)")
for device, gb_per_s in [("RTX 4090 GPU", 1008), ("M2 Max laptop", 400), ("DDR5 desktop CPU", 90)]:
print(f"{device:16s}: at most ~{gb_per_s / weights_gb(8.03, 'Q4_K_M'):.0f} tokens/s for 8B Q4_K_M")
# F16 ctx 8192: weights 16.1 GB + KV 1.1 GB = 17.1 GB (+ ~1 GB overhead)
# F16 ctx 32768: weights 16.1 GB + KV 4.3 GB = 20.4 GB (+ ~1 GB overhead)
# Q8_0 ctx 8192: weights 8.5 GB + KV 1.1 GB = 9.6 GB (+ ~1 GB overhead)
# Q8_0 ctx 32768: weights 8.5 GB + KV 4.3 GB = 12.8 GB (+ ~1 GB overhead)
# Q4_K_M ctx 8192: weights 4.9 GB + KV 1.1 GB = 6.0 GB (+ ~1 GB overhead)
# Q4_K_M ctx 32768: weights 4.9 GB + KV 4.3 GB = 9.2 GB (+ ~1 GB overhead)
# RTX 4090 GPU : at most ~205 tokens/s for 8B Q4_K_M
# M2 Max laptop : at most ~81 tokens/s for 8B Q4_K_M
# DDR5 desktop CPU: at most ~18 tokens/s for 8B Q4_K_M
Next, getting a model running. In a terminal:
# Ollama: install from ollama.com, then
ollama pull gemma3 # download (the default tag is a Q4_K_M-style quantization)
ollama run gemma3 # chat in the terminal
ollama ps # loaded models, memory use, CPU/GPU split, context length
# llama.cpp: download a GGUF from Hugging Face and serve an OpenAI-compatible API on :8080
llama-server -hf bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M -c 8192 -ngl 99
Then call the local model from Python. With Ollama's official library (pip install ollama), with the Ollama server running:
from ollama import chat
response = chat(
model="gemma3",
messages=[{"role": "user", "content": "Summarise GGUF in one sentence."}],
options={"num_ctx": 8192, "temperature": 0}, # context length and sampling
)
print(response.message.content)
print(response.eval_count, "tokens in", response.eval_duration / 1e9, "s") # durations are in ns
Or with plain HTTP, which works from any language:
import requests
r = requests.post("http://localhost:11434/api/chat", json={
"model": "gemma3", "stream": False,
"messages": [{"role": "user", "content": "Name three uses of a local LLM."}],
})
print(r.json()["message"]["content"])
Ollama, llama.cpp's server and LM Studio also offer OpenAI-compatible endpoints (Ollama at http://localhost:11434/v1, llama-server at http://localhost:8080/v1, LM Studio at http://localhost:1234/v1 by default), so an existing app can often switch to a local model by changing only base_url and the model name. Many local models also support tool calling and JSON output through these APIs, though less reliably than the large hosted models. Test with your eval set.
Common pitfalls
- A silently short context. Local runtimes often default to a context of a few thousand tokens to save memory (as of 2026 Ollama picks a default based on your VRAM, 4,096 tokens below 24 GB). Long documents then get truncated without an error. Set
num_ctx(orOLLAMA_CONTEXT_LENGTH, or llama.cpp's-c) deliberately, and check withollama ps. - Accidental CPU offloading. A model slightly too big for the GPU runs many times slower. Check the CPU/GPU split, then pick a smaller quantization or model.
- Wrong chat template. A GGUF with a missing or wrong chat template produces rambling or role-confused output. Use well-maintained conversions, and the instruct variant, not the base model.
- Judging a model by its quantization. A Q2 version of a model is a different, worse model. Compare at Q4_K_M or better before deciding a model is weak.
- Benchmarks versus your task. Public leaderboards don't tell you how a local model does on your inputs. Run your own eval set.
- Licences. "Open weights" doesn't always mean open source. Some licences restrict commercial use or very large deployments. Read the model card.
Watch out A local server listening on all network interfaces can expose your model, and any tools it can call, to everyone on the network or the internet. Keep local APIs bound to
localhostunless you deliberately add authentication. Treat downloaded model files and community "model loaders" with the same caution as any downloaded software.
Where it leads
- Quantization: the theory behind the bit counts, and newer formats (GPTQ, AWQ, FP8, MXFP4).
- Serving LLMs at Scale: when one user becomes many, servers such as vLLM use batching and paged KV caches to serve far more requests per GPU than llama.cpp.
- Fine-Tuning an Open Model in Practice: train an adapter, merge it, convert to GGUF and run your own model here.
- Retrieval-Augmented Generation and Model Context Protocol: local models with local documents and tools make fully private assistants.
- Building AI Products: when a local or self-hosted model beats an API on cost, latency or privacy, and when it doesn't.
- AI Hardware: GPUs, TPUs and Accelerators: GPUs, unified memory and why bandwidth matters.
A bit of history
In February 2023 Meta released LLaMA to researchers, and its weights soon leaked publicly. Within weeks Georgi Gerganov released llama.cpp (March 2023), showing that a 4-bit-quantized LLaMA could run on a MacBook's CPU. An enthusiastic community followed, centred on Reddit's r/LocalLLaMA, along with a stream of fine-tuned variants. The project's GGML file format was replaced by GGUF in August 2023 to carry metadata and stay extensible. Ollama (2023) wrapped llama.cpp in a one-command experience, and LM Studio offered a friendly desktop app. Meanwhile open-weight models improved rapidly: Llama 2 and 3, Mistral and Mixtral, Qwen, Gemma, DeepSeek, and in 2025 OpenAI's gpt-oss. By 2025 models that fit on a single consumer GPU matched or beat the best hosted models of two years earlier on many benchmarks.
Try it
- Use
kv_cache_gbto find the largest context that fits next to an 8B Q4_K_M model on a 12 GB GPU, keeping 1 GB for overhead.- Install Ollama, run a small model, and ask the same question with
num_ctxset to 2048 and to 16384. Watchollama psto see how memory changes.- Point the OpenAI Python SDK at
http://localhost:11434/v1(any non-empty API key works locally) and rerun the Tool Use and Function Calling chapter's weather example with a local model. Does it call the tool correctly?Hint for 1: 12 − 4.9 − 1 = 6.1 GB for the cache, at 131,072 bytes per token, which is about 46,000 tokens.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Ollama
The easiest way to download and run open LLMs on your own computer.
llama.cpp
Fast LLM inference in plain C/C++ on CPUs and GPUs. It is the engine behind many local-AI apps.
LM Studio
A desktop app for finding, downloading and chatting with open models (GGUF, and MLX on Apple Silicon), with an OpenAI-compatible local server.
Ollama documentation
How to install Ollama, run and customise models, set the context length, and use its REST API and OpenAI-compatible endpoints.
GGUF on the Hugging Face Hub
What the GGUF format contains, the quantization types and their bits per weight, and how to find and inspect GGUF files on the Hub.
Ollama Python library
The official Python client for a local Ollama server: chat, generate, streaming, tool calling, structured outputs and embeddings.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/running-local-models.md