AI State of the Art
SOTA/Inference & Optimization/29 min
Section 131

Ollama: Local Inference in Practice

Listen as a podcast →

The Dream: A Model on Your Own Machine

For a long time, running a large language model (LLM) on your own machine was an ordeal: compiling C++ libraries, untangling graphics-driver dependencies, converting weight formats by hand. In 2023 only the most stubborn got there.

Today it is one command. Local inference means keeping the model on your disk and running it offline, on your processor or your graphics card. No paid programming interface, no data leaving the machine, no dependence on the network.

What local inference changes, and what it does not

Privacy: no data goes to a third party. That is the first argument in a professional setting, and it is a legal argument as much as a technical one. Zero marginal cost: once the hardware is bought, no more per-token bill. Availability: it works on a plane.

Two things, however, do not change. The hardware remains the constraint: the question is never "does this work" but "does this fit in my memory". And the quality remains that of the model you can fit, which is smaller than the ones served online.

Ollama: What It Actually Is

Ollama is what democratised local inference, and it is worth understanding precisely what it does, because it is not what people assume.

Ollama is not an inference engine. It is a model manager plus a server: it downloads, stores and versions models, then delegates the computation to an underlying engine of the llama.cpp family (see GGUF and llama.cpp). Hence the Docker analogy: the visible part is package management, the real work happens underneath.

Four-tier vertical diagram titled Local LLM workflow with Ollama. At the top, a User interface box listing CLI, API and Web-UI. An arrow goes down to a large dark Ollama Server box subtitled Go backend, containing two sub-boxes: Model management with pull, run and list, and Inference engine with llama.cpp. A final arrow goes down to a blue Local hardware box with CPU, GPU and RAM.
The whole stack in one image, and the answer to the question of what Ollama is. The two sub-boxes in the middle tier say it all: on the left Model management, pull, run, list, which is Ollama's own job; on the right Inference engine, occupied by llama.cpp, which does the computing and talks to the hardware in the bottom tier.Source : EmiTechLogic (Emmimal Alexander)
# Installation
curl -fsSL https://ollama.com/install.sh | sh

# Download and run a model
ollama run mistral

# The local programming interface, served automatically
curl http://localhost:11434/api/generate -d '{
  "model": "mistral",
  "prompt": "Explain transformers"
}'

Port 11434 belongs to the local server, and it is listening as soon as Ollama is running. Note that Ollama does not quantize anything itself: it downloads an already quantized variant, published in the GGUF format (llama.cpp's file format, which packs the compressed weights and everything needed to interpret them into a single file).

Sequence diagram with five actors: Ollama CLI, Ollama HTTP Server in Go, llama.cpp in C++, Local Storage and Ollama Remote Registry. A first red phase, prepare or model warmup, shows the command ollama run gemma3:1b, a POST /api/show, a read of the local manifest returning 404 Not Found, then a POST /api/pull to the remote registry downloading the manifest, the blobs, the GGUF and the Modelfile, and finally local storage. A second blue phase, interactive or chat, shows POST /api/generate then POST /api/chat, the server querying llama.cpp on a local port via GET /health then POST /completion, and the response travelling back to the CLI.
What a single command really does. Red phase: the server looks for the model locally, does not find it (hence the 404 Not Found) fetches the file from the remote registry, then stores it on disk. It is a docker pull, literally. Blue phase: subsequent requests go straight to the engine already loaded in memory, which is why the first launch is slow and the following ones instant.Source : The AI Merge, The Complete Guide to Ollama

The One Calculation You Need: Will It Fit?

This is the question that decides everything, and the answer is a multiplication. We will not redo the arithmetic of quantization here, it is laid out in Quantization: the concepts, so go there if the relation between bits and bytes is not yet a reflex. We will use it.

The useful rule for Ollama fits in one sentence: the default quantization costs about 0.6 bytes per parameter. That number deserves its explanation, because "4 bits" would suggest 0.5 bytes. The quantization lesson shows where the surcharge comes from: weights are quantized in small groups, and each group additionally has to store its own scaling factor at full precision. That surcharge takes you from 0.5 to roughly 0.6.

So, for any given model: parameter count × 0.6 = gigabytes of weights.

ModelParametersCalculationWeights
Phi-3 Mini3.8 billion3.8 × 0.6≈ 2.3 GB
Mistral7 billion7 × 0.6≈ 4.3 GB
LLaMA 38 billion8 × 0.6≈ 4.8 GB
Gemma 29 billion9 × 0.6≈ 5.5 GB
Mixtral 8x7B46.7 billion46.7 × 0.6≈ 26 GB
LLaMA 370 billion70 × 0.6≈ 42 GB

Two remarks about that table, and they are the two classic traps.

Mixtral 8x7B does not have 56 billion parameters, despite the name: the attention layers are shared across the experts, which brings the total down to roughly 46.7 billion (see MoE in practice). And all the experts have to be loaded into memory even though each token activates only two: the routing decides at the last moment, so all of them must be available.

It follows that Mixtral 8x7B in 4 bits does not fit on a 24 GB graphics card. 26 GB against 24 GB of video memory, and you still need room for the attention cache. The opposite claim is often written; it comes from doing the multiplication on 56 billion, or from confusing total parameters with active parameters.

And that is the weights alone

The table above gives the memory needed to load the model, before the attention cache. That cache sits on top and grows with the length of the text in flight; the calculation is done in the KV cache.

This is not a marginal detail. Over a long context the cache can become comparable to the weights themselves. What matters most is that its size does not depend on the total parameter count but on the number of layers and key-value heads, two models of the same size can have very different caches.

Table titled Model file sizes in GB after quantization, with one quantization-format column and three size columns for an 8B, 14B and 70B model. FP16: 12.38 then 29.51 then 141.06. GPTQ 4-bit: 6.98 then 9.98 then 39.81. MLX 4-bit: 4.35 then 9.09 then 39.66. GGUF Q4_K_M: 5.03 then 9.00 then 42.50. GGUF Q4_K_XL: 5.14 then 9.16 then 42.70. EXL2 4.25-bit: 5.43 then 9.19 then 39.27. EXL2 3.5-bit: 4.78 then 7.95 then 32.89. EXL2 2.2-bit: 3.69 then 5.89 then 21.91. A header note specifies that this is the base memory to load the model, before the KV cache.
A table of real file sizes, useful for checking the calculation above, the GGUF Q4_K_M row is the format Ollama uses by default, and its 5.03 GB for an 8-billion-parameter model matches our 8 × 0.6 nicely. But read it with method rather than trust: its FP16 cell for that same model says 12.38 GB, where the arithmetic gives 8 × 2 = 16 GB. Either the 8B column means a 6-billion-parameter model, or the figure is wrong. When a table and a multiplication disagree, believe the multiplication.Source : Hardware Corner, Quantization for local LLMs

The Second Calculation: How Fast?

There is a speed ceiling you can compute before buying anything, and it follows directly from the fact established in Quantization: the concepts: producing a token requires streaming all the model's weights out of memory. Speed is therefore bounded by the memory's throughput.

tokens per second (ceiling)=memory bandwidth, in GB/smodel size, in GB\text{tokens per second (ceiling)} = \frac{\text{memory bandwidth, in GB/s}}{\text{model size, in GB}}

A worked example. On an entry-level M1 MacBook, Apple's specification is about 68 GB/s. An 8-billion-parameter model in 4 bits weighs 4.8 GB. Ceiling: 68/4.8≈1468 / 4.8 \approx 14 tokens per second.

On an RTX 4090 graphics card, NVIDIA quotes about 1,000 GB/s. For the same model: 1000/4.8≈2081000 / 4.8 \approx 208 tokens per second. The ratio between the two machines is almost exactly the ratio of their bandwidths, and that is no coincidence.

A ceiling, not a forecast

These numbers are upper bounds, and it is worth knowing by how much you will miss them. Two reasons.

First, no chip reaches its datasheet bandwidth: in practice you get something like 60 to 80% of the quoted figure. Second, streaming weights is not all that happens: attention, normalisations and cache reads take time too.

So expect to measure well below the ceiling. Its real usefulness is elsewhere: it tells you which quantity to look at when choosing hardware. Between two machines, memory bandwidth is what decides generation speed, not raw compute, and not the amount of memory either, which only decides what fits.

Two practical consequences of the formula, which often surprise people:

A bigger model is mechanically slower, in direct proportion to its size. Doubling the parameter count roughly halves the token throughput on the same machine. Any claim in which a bigger model produces more tokens per second than its smaller sibling, on the same hardware, contains an error.

Quantizing further speeds things up, even though the number of operations is unchanged. It is the same mechanism seen from the other side: fewer bytes to stream, less waiting.

Finally, the cliff to know about: if the model does not fit in memory, the system moves part of the computation to the central processor or, worse, starts writing to disk. Throughput does not drop 20% then, it collapses by an order of magnitude, because the pipe you have just started using is far narrower. Hence the rule: a smaller model that fits beats a bigger model that overflows.

Customising a Model: The Modelfile

Ollama lets you create variants of a model with no fine-tuning at all, using a file that looks a lot like a Dockerfile:

FROM mistral

PARAMETER temperature 0.7
PARAMETER num_ctx 8192

SYSTEM """
You are a senior Python expert.
Always answer with commented code.
Favour clarity over brevity.
"""
ollama create python-expert -f Modelfile
ollama run python-expert "how do I filter a list with a comprehension?"

Three instructions are enough to grasp the mechanism. FROM names the starting model. PARAMETER sets a default, here temperature, which controls how adventurous the word sampling is, and num_ctx, the context length in tokens. SYSTEM sets the system message, the standing instructions given to the model ahead of any conversation.

This is not fine-tuning: not one byte of the weights changes. You are building a named, reusable, shareable preset.

The Ecosystem

Ollama exposes an interface compatible with OpenAI's, at /v1/chat/completions. The concrete consequence: code written against OpenAI's interface works against Ollama by changing the base address alone. That is why nearly every client tool supports it with no special work.

The commonest integrations are LangChain for building retrieval-augmented chains and agents, Continue.dev for code completion in the editor, Open WebUI for a web chat interface, and LM Studio or Jan as complete competing solutions, with a graphical interface where Ollama favours the command line and the programming interface.

On comparisons between these tools

They age within months, and categorical statements of the form "that one is processor-only" or "that one is faster" are stale almost as soon as they are written. What does not go stale: they all rest, more or less, on the same underlying engine and the same file format. So the choice comes down to which interface you prefer, not to performance, which comes from the hardware and the model size, as the formula above shows.

The Settings That Actually Matter

Four points, in order of importance.

1. Pick the right quantization. Q4_K_M is the sensible default. The name reads as: Q4 for 4 bits, _K for the family that quantizes in groups with scaling factors, _M for the medium variant of the internal trade-off. If memory allows, Q5_K_M buys a little quality for a little space. Going below 4 bits degrades far faster than people expect: see Extreme quantization.

2. Set the context length to match available memory. Every context token consumes attention cache. Reducing num_ctx (in the Modelfile, or globally via the OLLAMA_CONTEXT_LENGTH environment variable) is the most direct lever when memory is tight. Careful if you serve several requests in parallel: the memory needed is multiplied by the number of concurrent requests, each holding its own cache.

3. Check that everything really is on the graphics card. This is the highest-return setting, and it is not something to guess at: it is something to read. The ollama ps command shows, for each loaded model, the split between processor and graphics card.

ollama ps
# NAME      ID      SIZE     PROCESSOR    CONTEXT
# mistral   ...     4.4 GB   100% GPU     8192

If that column says anything other than 100% GPU, some of the layers are being computed on the central processor, and that is where your speed is going. The remedy is to reduce the context length, or move to a more aggressive quantization, until the whole thing fits. Ollama decides this split itself based on the memory it can see; there is no command-line option to pin a layer count.

4. Watch the disk. As soon as the operating system starts paging memory out to disk, performance collapses for the reason explained above. This is a binary signal: it does not happen a little.

Apple unified memory: what you actually have

On a Mac with unified memory, the same memory serves the system, the applications and the model. Your advertised 16 GB are not 16 GB available: the operating system takes a share, your browser another. Count what is left, not what is on the box.

The honest calculation: an 8-billion-parameter model in 4 bits (4.8 GB of weights, plus its cache) fits comfortably on a 16 GB machine. A 13-billion one (7.8 GB) gets tight. A 32-billion one is not happening.

What You Can Build On Top

The point of local inference is not to run a model for its own sake, it is to run a complete chain with no data leaving the building. A model served by Ollama, an orchestration library, a vector store kept on your disk: you have a retrieval-augmented generation system over your own documents, entirely offline.

For a doctor, a researcher, or anyone working on confidential material, that is the difference between a usable tool and one forbidden by internal policy, regardless of how good the online model is.

One last point of honesty. You read that local inference is "accessible to anyone with a recent computer". That is true for a 7- or 8-billion-parameter model on a machine with 16 GB or more. It is not true below that, and it is not true of the models making the news, whose sizes run into hundreds of billions of parameters. The two calculations above tell you exactly where you stand.

Check your understanding0 / 5

1. What exactly is Ollama?

2. Does Mixtral 8x7B quantized to 4 bits fit on a 24 GB graphics card?

3. Between two machines, which quantity decides the generation speed of the same local model?

4. A Modelfile with SYSTEM and PARAMETER builds a python-expert out of Mistral. Is that fine-tuning?

5. A model exceeds your card's memory by a gigabyte or two. What will happen?