◆ AI All-in-One

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
↗ Plan a path here

Read first

QuantizationLarge Language Models, Explained Simply

This leads to

—
The full path from zero — 17 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Matrices and Matrix Multiplication
  7. Partial Derivatives and Gradients
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Large Language Models, Explained Simply
  10. Tensors and Shapes
  11. Gradient Descent
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Quantization
  18. 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:

  1. 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.
  2. 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.

0 4 8 12 16 20 17.2 F16 16.1 GB 9.6 Q8_0 8.5 GB 7.7 Q6_K 6.6 GB 6.8 Q5_K_M 5.7 GB 6.0 Q4_K_M 4.9 GB 5.1 Q3_K_M 4.0 GB 4.2 Q2_K 3.2 GB 8 GB GPU 12 GB GPU 16 GB GPU weights (GGUF file) KV cache, 8,192 tokens GB of memory fewer bits per weight: smaller and faster, but quality drops, sharply below ~4 bits
Fig. 1 Memory needed for an 8-billion-parameter model at different quantization levels, using real GGUF file sizes, plus the key-value cache for an 8,192-token context. Horizontal lines mark common GPU memory sizes.

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

  • Ollama is the easiest start. You install one app, type ollama run gemma3 and 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-cli for chat and llama-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.
Your Python app ollama or openai SDK Chat UI or IDE Open WebUI, editors Agent / RAG app tools via MCP Local HTTP API on localhost Ollama :11434 (/api/chat, /v1) · llama-server :8080/v1 · LM Studio :1234/v1 (OpenAI-compatible) Ollama one-command models llama.cpp llama-cli, llama-server LM Studio desktop app (+ MLX on Mac) Inference engine (mostly llama.cpp underneath) loads a GGUF file: quantized weights + tokenizer + chat template GGUF on disk e.g. 8B Q4_K_M = 4.9 GB GPU VRAM or unified memory weights + KV cache; bandwidth sets speed CPU + RAM overflow layers: slow
Fig. 2 The local stack. Applications talk to a local HTTP API; Ollama, llama.cpp's server and LM Studio provide it, mostly on top of the llama.cpp engine, which loads a GGUF file into GPU or unified memory and spills layers to the CPU only if it must.

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:

memory≈N×b8⏟weights  +  2×L×hkv×dh×B×T⏟KV cache  +  overhead\text{memory} \approx \underbrace{N \times \frac{b}{8}}_{\text{weights}} \;+\; \underbrace{2 \times L \times h_{kv} \times d_h \times B \times T}_{\text{KV cache}} \;+\; \text{overhead}
  • NN is the number of parameters and bb the effective bits per weight, so N×b/8N \times b/8 is bytes.
  • The KV cache stores a key and a value vector (the factor 2) for every layer LL, every key/value head hkvh_{kv} of size dhd_h, at BB bytes per number, for each of the TT 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: 8.03×109×4.9/8≈4.98.03 \times 10^9 \times 4.9 / 8 \approx 4.9 GB. KV cache: 2×32×8×128×2=131,0722 \times 32 \times 8 \times 128 \times 2 = 131{,}072 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

tokens per second≲memory bandwidth (GB/s)model size (GB)\text{tokens per second} \lesssim \frac{\text{memory bandwidth (GB/s)}}{\text{model size (GB)}}

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 (or OLLAMA_CONTEXT_LENGTH, or llama.cpp's -c) deliberately, and check with ollama 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 localhost unless you deliberately add authentication. Treat downloaded model files and community "model loaders" with the same caution as any downloaded software.

Where it leads

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

  1. Use kv_cache_gb to find the largest context that fits next to an 8B Q4_K_M model on a 12 GB GPU, keeping 1 GB for overhead.
  2. Install Ollama, run a small model, and ask the same question with num_ctx set to 2048 and to 16384. Watch ollama ps to see how memory changes.
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Your laptop's memory delivers about 400 GB/s and the model file is 4.9 GB. Roughly what is the best-case generation speed?

  2. ollama ps shows a model running at '40%/60% CPU/GPU' and it feels very slow. What is the most likely cause and fix?

  3. You have about 9 GB of file space for weights. Which choice does the chapter's rule of thumb favour?

  4. You raise an 8B Q4_K_M model's context from 8,192 to 32,768 tokens and it no longer fits in GPU memory. Why?

  5. You feed a long document to a local model and it seems to ignore the beginning, with no error. What is a likely cause?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Tool

Ollama

Ollama · Beginner · Free

The easiest way to download and run open LLMs on your own computer.

Tool

llama.cpp

ggml-org · Intermediate · Free

Fast LLM inference in plain C/C++ on CPUs and GPUs. It is the engine behind many local-AI apps.

Tool

LM Studio

Element Labs · Beginner · Free

A desktop app for finding, downloading and chatting with open models (GGUF, and MLX on Apple Silicon), with an OpenAI-compatible local server.

Docs

Ollama documentation

Ollama · Beginner · Free

How to install Ollama, run and customise models, set the context length, and use its REST API and OpenAI-compatible endpoints.

Docs

GGUF on the Hugging Face Hub

Hugging Face · Intermediate · Free

What the GGUF format contains, the quantization types and their bits per weight, and how to find and inspect GGUF files on the Hub.

Tool

Ollama Python library

Ollama · Beginner · Free

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