Skip to content
Visual explainer 3h to learn 4 steps

Running open-weight models locally

Run an open model locally and swap it in behind the same interface.

By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.

Topic 30 of 33

In short

Tools like Ollama and llama.cpp run open-weight models on your own machine. Putting model calls behind one interface lets you swap a local model in for testing, privacy or cost, then compare quality and speed.

Explained simply

Open-weight models are models whose trained weights you can download and run yourself, on a laptop, a workstation or your own server. Popular families include Llama, Mistral, Qwen and Gemma. You pay for hardware and electricity instead of per token, and your data never leaves your machine.

Tools make this easy. Ollama downloads a model with one command and serves it on your computer. llama.cpp is the fast engine underneath many tools, and you can run it directly for more control.

The big limit is memory. A model must fit in your RAM, or ideally your GPU's memory, to run at a useful speed. Quantisation shrinks models by storing each weight with fewer bits, so a model that needs 16 GB can run in about 5 GB with a small loss in quality.

Smart apps keep model calls behind one interface. Then you can switch between a hosted API and a local model with a config change, and compare both on your own eval set before deciding.

Press Play on a diagram to walk through it one step at a time.

CompareHosted API vs local model
Hosted API
  • Top quality models
  • No hardware needed
  • Per-token cost
  • Data sent to provider
Local open model
  • Runs on your machine
  • Data stays local
  • Limited by RAM and GPU
  • Often lower quality for size
FlowSwapping in a local model, step by step
  1. 1
    Install a runtime

    Ollama or llama.cpp

  2. 2
    Pull a quantised model

    Small enough for your memory

  3. 3
    Write an adapter

    Same interface as the hosted one

  4. 4
    Run the eval set

    Both models, same prompts

  5. 5
    Compare

    Quality, speed, memory, cost

  6. 6
    Choose per use case

    Local for some tasks, hosted for others

In depth

How much memory a model needs

The rough rule is parameters times bytes per weight. At 16-bit precision each weight takes 2 bytes, so an 8-billion-parameter (8B) model needs about 16 GB just for weights. At 8-bit it is about 8 GB, and at 4-bit about 4 to 5 GB, because some layers stay at higher precision and there is metadata.

On top of the weights comes the KV cache, the memory that holds the attention state for the tokens in the context. It grows with context length and with the number of requests served at once, so a long 32,000-token context can need several extra gigabytes.

For good speed the whole model should fit in GPU memory (VRAM). If it does not fit, tools can keep some layers on the CPU, but generation slows down a lot. Apple Silicon Macs share one pool of memory between CPU and GPU, which is why they run fairly large models well.

  • 16-bit: about 2 GB per billion parameters
  • 8-bit: about 1 GB per billion parameters
  • 4-bit: about 0.5 to 0.6 GB per billion parameters
  • Add room for the KV cache: more context, more memory

Quantisation: picking a size

Quantisation stores weights with fewer bits. llama.cpp's GGUF files use names that describe the method. Q8_0 is 8-bit and nearly indistinguishable from the original for most tasks. Q6_K and Q5_K_M are a little smaller with very small losses. Q4_K_M is a popular balance of size and quality. Below 4 bits, quality usually drops noticeably, and small models suffer more than large ones.

A useful rule of thumb: a bigger model at 4-bit often beats a smaller model at 8-bit for the same memory. But rules of thumb are not data. Your task might need precise numbers, strict JSON or a language the model rarely saw, and quantisation can hurt exactly those.

In Ollama, model tags pick the size and often the quantisation, and the model page lists the available tags. Run your eval set on two or three options and pick the smallest one that meets your quality bar.

Ollama, llama.cpp and vLLM in practice

Ollama is the easiest start. ollama pull downloads a model, ollama run chats with it, ollama list shows downloaded models, and ollama ps shows what is loaded and how much runs on GPU or CPU. It serves an HTTP API on port 11434, with its own endpoints like /api/chat and an OpenAI-compatible endpoint under /v1. Set OLLAMA_HOST to listen on another address. A Modelfile sets a system prompt and parameters such as num_ctx, the context length; Ollama's default context is often much smaller than the model's maximum, so set it for RAG.

llama.cpp gives finer control. Its llama-server program loads a GGUF file and serves an OpenAI-compatible API, with flags for context size (-c) and how many layers go to the GPU (-ngl).

For production GPU serving to many users, vLLM is common. It batches requests continuously and manages KV cache memory efficiently, giving much higher throughput than a single-user tool.

MapLocal and self-hosted runtimes
Run an open model
  • Ollama
    • One-command install and pull
    • API on port 11434
    • Great for laptops and dev
  • llama.cpp
    • GGUF files, CPU and GPU
    • llama-server, OpenAI-compatible
    • Fine control with flags
  • vLLM
    • GPU servers
    • Continuous batching
    • High throughput for many users

One interface, many backends

Wrap model access in a small interface, for example a Protocol with an async chat(messages) method that returns text. Write one adapter per backend: your hosted provider's SDK, Ollama, llama-server. The rest of the app only knows the interface, and a setting chooses the adapter.

Many local servers speak an OpenAI-compatible API, so one client pointed at a different base URL often works for several backends. Do not assume features match, though. Tool calling, structured output and long contexts depend on the model and the server; a small local model may ignore tool schemas a large hosted one follows perfectly.

Keep prompts per model if needed. A prompt tuned for one model family may need changes for another, so version prompts by model and let the eval set decide.

LayersSwappable model backends
  1. 1
    App code

    RAG, tools, API endpoints

  2. 2
    ChatModel interface

    async chat(messages) returns text

  3. 3
    Adapters

    Hosted SDK, Ollama, llama-server

  4. 4
    Backends

    Provider API or local process

Comparing quality, speed, cost and licence

Compare like for like. Run the same eval set through each model with the same prompt version and record quality scores, time to first token, tokens per second and peak memory. ollama run --verbose prints timing statistics, including the generation rate, after each reply.

Cost comparisons need honest numbers. A local model has no per-token bill, but hardware, power and your time are real costs, and a GPU server sitting idle at night still costs money. Hosted APIs are often cheaper at low volume; self-hosting can win at steady high volume or when data must stay in-house.

Check the licence before shipping. Some open-weight models use permissive licences such as Apache 2.0, while others use custom licences with conditions on use or scale. Read the licence of the exact model you deploy.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Install Ollama or llama.cpp~45m
  2. 2
    Run an open-weight model locally~45m
  3. 3
    Swap it in behind the same interface~45m
  4. 4
    Compare quality and speed~45m

Key points

  • Quantised models use less memory at a small cost in quality.
  • Model size must fit in your RAM or GPU memory to run well.
  • Hide providers behind one interface so swapping needs no app changes.
  • Run the same eval set to compare local and hosted models fairly.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
# Download and chat with a small open model
ollama pull llama3.2
ollama run llama3.2 "Explain RAG in one sentence"

# Ollama also serves a local HTTP API on port 11434
curl http://localhost:11434/api/generate \
  -d '{"model": "llama3.2", "prompt": "Hello", "stream": false}'

Run a local model from the terminal and over HTTP.

An Ollama adapter behind a shared interface

Your app already calls a hosted model through a ChatModel interface. Step 1: define the interface with typing.Protocol, so any class with a matching chat method fits. Step 2: write OllamaChat, which posts the messages to Ollama's /api/chat endpoint with stream set to false. Step 3: the reply's message.content field holds the text. Step 4: choose the adapter from config, for example MODEL_BACKEND=ollama, and the rest of the app does not change. In a real service, reuse one AsyncClient instead of opening one per call.

python
from typing import Protocol
import httpx

class ChatModel(Protocol):
    async def chat(self, messages: list[dict]) -> str: ...

class OllamaChat:
    def __init__(self, model: str = "llama3.2", url: str = "http://localhost:11434"):
        self.model, self.url = model, url

    async def chat(self, messages: list[dict]) -> str:
        async with httpx.AsyncClient(timeout=120) as client:
            r = await client.post(f"{self.url}/api/chat", json={"model": self.model, "messages": messages, "stream": False})
            r.raise_for_status()
            return r.json()["message"]["content"]

A custom model with a bigger context, and a speed check

Your RAG prompts are about 6,000 tokens, but answers seem to ignore the first chunks. The cause: the context length was too small, so the start of the prompt was cut off. Step 1: write a Modelfile that starts from the base model and sets num_ctx to 8192 and a low temperature. Step 2: create a named model from it. Step 3: run it with --verbose to see timing, including the eval rate in tokens per second. Step 4: ollama ps shows how much memory the model uses and whether it runs fully on the GPU. A larger context uses more memory, so check that it still fits.

bash
cat > Modelfile <<'EOF'
FROM llama3.2
PARAMETER num_ctx 8192
PARAMETER temperature 0.2
SYSTEM """You answer questions about our internal docs. Be concise."""
EOF
ollama create docs-bot -f Modelfile
ollama run docs-bot --verbose "Explain RAG in one sentence"
ollama ps    # memory used and the GPU/CPU split

Quick reference

  • Memory for weights is about parameters x bytes per weight: 8B at 4-bit is roughly 5 GB
  • Q4_K_M is a popular size and quality balance; Q8_0 is close to the original
  • ollama pull, run, list, ps; the API listens on localhost:11434
  • Ollama has an OpenAI-compatible endpoint under /v1 as well as /api/chat
  • Set num_ctx in a Modelfile when prompts are long; defaults are often small
  • llama-server -m model.gguf -c 8192 -ngl 99 serves an OpenAI-compatible API
  • Use vLLM for high-throughput GPU serving to many users
  • Compare models on your own eval set and read each model's licence before shipping

Common mistakes

  • Assuming a local model matches a large hosted model without testing.
  • Picking a model too big for your memory, making it extremely slow.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Roughly how much memory do the weights of an 8B model need at 16-bit precision?

Question 2

2A local model seems to ignore the first part of a long RAG prompt. What is a likely cause?

Question 3

3Which tool is designed for high-throughput GPU serving to many concurrent users?

Question 4

4Why keep model calls behind one interface such as ChatModel?

Question 5

5Your 4-bit local model passes 70% of evals while the hosted model passes 88%. What is the most sensible next step?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Install Ollama, pull a small model, ask it one question from the terminal and once over HTTP with curl, and note the generation speed with --verbose.

  2. Exercise 2medium

    Write estimate_gb(params_billion, bits) that estimates weight memory in GB with a 10% overhead, and print estimates for 8B and 70B at 16, 8 and 4 bits.

  3. Exercise 3hard

    Write a benchmark that runs the same list of prompts through two ChatModel adapters and reports, for each, the average latency and how many answers pass a checker function.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can I run an LLM on my laptop without a GPU?
Yes, small quantised models run on a CPU with tools like Ollama or llama.cpp, just more slowly. A few billion parameters at 4-bit is a comfortable start on a laptop.
Are open-weight models as good as hosted frontier models?
The best open models are strong, but the largest hosted models usually still lead on hard tasks. For narrow tasks a smaller open model can be good enough; measure on your eval set.
What is the difference between Ollama and llama.cpp?
llama.cpp is an efficient inference engine and set of tools for GGUF models. Ollama is a friendlier wrapper that handles downloading, model management and a local API.
Is open-weight the same as open source?
Not always. Open-weight means you can download the weights; the licence may still restrict use, and the training data and code are often not released.

Go deeper

ShareXLinkedInWhatsApp