Table of Contents


Ollama runs GGUF models locally with a single command — a server on localhost:11434, a CLI, and a Python library. This lab installs it, works offline, inspects token throughput, dissects model names and quantizations, tunes sampling parameters, and benchmarks models.

Objectives

By the end of this session you should be able to:

  1. Install Ollama on Linux and Windows.
  2. Pull models and verify they work fully offline.
  3. Measure tokens/sec with verbose mode and know what to expect.
  4. Decode model names — MoE, reasoning, coder, instruct, distill, size.
  5. Explain quantization — FP16, Q8, Q4 — and its size/quality trade-off.
  6. Change parameters (temperature, top_p, num_ctx, num_thread) per session or per model.
  7. Save custom models with a Modelfile.
  8. Benchmark and compare models objectively.
  9. Use Ollama from Python.

Setup and install

Linux

curl -fsSL https://ollama.com/install.sh | sh

The script installs the binary, a systemd service (ollama serve, listening on http://localhost:11434), and adds the user to the ollama group.

Windows

Download the installer from https://ollama.com/download/windows and run it. Ollama runs in the background as a tray app; the CLI is available in any terminal.

Verify

ollama --version
ollama serve        # only needed if not already running
ollama list

GPU

Ollama auto-detects CUDA (NVIDIA) and ROCm (AMD) and offloads layers to GPU. Check with ollama ps — a fully loaded model shows 100% GPU. Without a GPU it runs on CPU, and num_thread matters (see Changing parameters).

Pull models for offline usage

ollama pull qwen2.5-coder:7b
ollama pull llama3.2:3b          # small, fast
ollama pull qwen3:4b             # reasoning-capable
ollama list                      # shows name, id, size, modified

Once pulled, the model lives in the local store (~/.ollama/models on Linux, %USERPROFILE%\.ollama\models on Windows) and works with no internet:

# fully offline: block the network and test
ollama run llama3.2:3b "What is the capital of Portugal?"

Housekeeping:

ollama rm llama3.2:3b          # delete a model
ollama cp a b                  # copy a model
ollama show qwen2.5-coder:7b   # architecture, context, quantization, capabilities

Verbose mode — tokens/sec

Run with --verbose to see the timings after each answer:

ollama run qwen2.5-coder:7b --verbose
>>> Summarize the TCP three-way handshake.

The output includes:

total duration:       12.4s
load duration:        120ms
prompt eval count:    18 tokens
prompt eval rate:     95.0 tokens/s
eval count:           210 tokens
eval rate:            38.4 tokens/s   <-- generation speed
  • prompt eval rate — how fast the prompt is processed (prefill).
  • eval rate — how fast new tokens are generated (decode). This is the number people mean by tokens/sec.

The three regimes

ollama ps shows where the model is loaded: 100% GPU (fast, e.g. 40–100+ tok/s), partial CPU/GPU offload (much slower), or 100% CPU (a few tok/s for 7B). A model that fits entirely in VRAM is an order of magnitude faster than one that spills to RAM.

Programmatic alternative:

curl -s http://localhost:11434/api/generate -d '{
  "model": "qwen2.5-coder:7b",
  "prompt": "Explain DNS in one sentence.",
  "stream": false
}' | grep -o '"eval_rate":[^,}]*'

Types of models

Model names encode the model family and its purpose:

TypeName hintsWhat it does
Instructinstruct, itFollows instructions; the default for chat/assistant use.
Base (pretrained)noneRaw next-token prediction; not for chat.
Codercoder, codeTrained on code; good for codegen, completion, refactors (e.g. qwen2.5-coder).
Reasoningr1, thinkProduces a thinking trace before the answer; better at math/logic, slower (e.g. deepseek-r1, qwen3).
MoEmixture of expertsMany small expert networks; per token only a few experts fire — large capability, fast decode (e.g. mixtral, qwen3:30b-a3b).
Visionvl, visionAccepts images (e.g. llama3.2-vision).
Embeddingnomic-embed-text, bgeOutputs vectors, not text.

MoE naming

MoE models often show the active parameters after the size, e.g. qwen3:30b-a3b = 30B total, 3B active per token. This is why they decode faster than a dense 30B model.

Distilled size

Distillation trains a smaller model to imitate a larger one (often on its outputs). A model like deepseek-r1-distill-qwen-7b is a 7B Qwen fine-tuned to reproduce DeepSeek-R1’s reasoning behavior.

  • You get part of the big model’s reasoning at a fraction of the cost.
  • It is not equivalent: a 7B distill of a 671B model is noticeably weaker on hard problems.
  • Rule of thumb: pick the largest model that fits your hardware with headroom.

Quantization

Quantization stores weights with fewer bits — smaller file, faster inference, slight quality loss.

FormatBits/weight~7B model sizeQuality
FP1616~13–14 GBReference (best)
Q88~7–8 GBNearly indistinguishable
Q44~4–5 GBSlight degradation; the standard choice
Q33~3–4 GBNoticeable degradation
Q22~2–3 GBOnly for very tight hardware

Variants like Q4_K_M are K-quant mixes — mixed precision per layer, keeping quality close to Q4 while improving it. Ollama’s default tags are quantized (typically Q4); quantization only matters for local models, not cloud ones.

Choosing a variant

Start with Q4_K_M. If it doesn’t fit in VRAM, drop to a smaller size or a more aggressive quant. Prefer a smaller model at Q4 that fits fully in GPU over a bigger model that spills to RAM.

Changing parameters

Sampling parameters mirror LM22-model-parameters — temperature, top_p, top_k, plus Ollama’s runtime knobs:

ParameterDefaultEffect
temperature0.8Higher = more creative/random; lower = deterministic.
top_p0.9Nucleus sampling — cut the tail of the distribution.
top_k40Keep only the k most likely tokens.
num_ctxsmall (Ollama default)Context window size. Critical for agents; 64k+ recommended for coding agents.
num_threadautoCPU threads; physical cores are usually best.
num_predict-1Max tokens to generate.

Per session — /set inside the REPL

ollama run qwen2.5-coder:7b
>>> /set parameter temperature 0.2
>>> /set parameter num_ctx 16384
>>> /set parameter num_thread 8
>>> /show info        # confirm the active settings

Per model — ollama run with a Modelfile (see Saving)

One-shot — from the API

curl -s http://localhost:11434/api/generate -d '{
  "model": "qwen2.5-coder:7b",
  "prompt": "The sky color is?",
  "options": {
    "temperature": 0.0,
    "top_p": 0.9,
    "num_ctx": 8192,
    "num_thread": 8
  },
  "stream": false
}'

num_ctx costs memory

Each context token needs KV cache. Doubling num_ctx roughly doubles the KV cache size and can push the model out of VRAM. Set it explicitly, not “as high as possible”.

Saving

Persist your tuned parameters as a custom model with a Modelfile:

# Modelfile
FROM qwen2.5-coder:7b
PARAMETER temperature 0.2
PARAMETER top_p 0.9
PARAMETER num_ctx 16384
PARAMETER num_thread 8
SYSTEM "You are a precise Python code assistant. Answer concisely."
ollama create codeassist -f Modelfile
ollama run codeassist

codeassist now behaves as a standalone model with your parameters baked in. It appears in ollama list and can be served to other tools (e.g. LM23-tui-agents agents) via the OpenAI-compatible endpoint http://localhost:11434/v1.

Benchmark and comparing models

A simple, repeatable benchmark: same prompt, fixed parameters, measure eval rate and quality.

Throughput benchmark

#!/bin/sh
# bench.sh — compare models on the same prompt
MODEL=${1:-qwen2.5-coder:7b}
curl -s http://localhost:11434/api/generate -d '{
  "model": "'$MODEL'",
  "prompt": "Write a Python function that computes the median of a list without sorting.",
  "options": {"temperature": 0.0, "num_predict": 256},
  "stream": false
}' | python3 -c "
import json, sys
r = json.load(sys.stdin)
print(f\"{r['model']}: {r['eval_rate']:.1f} tok/s, {r['eval_count']} tokens, {r['total_duration']/1e9:.1f}s\")
"
sh bench.sh llama3.2:3b
sh bench.sh qwen2.5-coder:7b
sh bench.sh qwen3:4b

Quality comparison

For a fixed set of tasks, compare on:

  1. Correctness — does the code run? Does the reasoning reach the right answer?
  2. Tool use — does the model emit valid tool calls (needed for agents, see LM23-tui-agents)?
  3. Instruction following — does it respect format/length constraints at low temperature?
  4. Latency — time to first token and total time.

A practical approach: a small table of 5–10 prompts (code, reasoning, extraction), run each model at temperature 0.0, and score pass/fail. Record eval rate alongside — the best model is the one that passes your tasks and fits your hardware budget.

Python library usage

The official Python client (ollama) talks to the same server:

pip install ollama

Chat

from ollama import chat
 
response = chat(
    model="qwen2.5-coder:7b",
    messages=[
        {"role": "system", "content": "You are a concise Python assistant."},
        {"role": "user", "content": "What is the difference between a tuple and a list?"},
    ],
    options={"temperature": 0.2, "num_ctx": 8192},
)
print(response.message.content)

Streaming

from ollama import chat
 
stream = chat(
    model="qwen2.5-coder:7b",
    messages=[{"role": "user", "content": "Explain the GIL in 3 sentences."}],
    stream=True,
)
for chunk in stream:
    print(chunk.message.content, end="", flush=True)

Measuring tokens/sec from Python

 
def get_prompt_details(response):
    """ Print details of response message """
    print(f"Model: {response.model}")
    print('-'*33)
    print(f"Total duration:    {response.total_duration / 1e9:6.2f} seconds")
    print(f"  Load duration:   {response.load_duration / 1e9:6.2f} seconds")
    print(f"  Prompt duration: {response.prompt_eval_duration / 1e9:6.2f} seconds")
    print(f"  Eval duration:   {response.eval_duration / 1e9:6.2f} seconds")
    print('-'*33)
    print(f"Prompt: {response.prompt_eval_count:17d} tokens")
    print(f"Eval:   {response.eval_count:17d} tokens")
    print('-'*36)
    print(f"Prompt speed:  {response.prompt_eval_count / (response.prompt_eval_duration / 1e9):9.2f} tokens/sec")
    print(f"Eval speed:    {response.eval_count / (response.eval_duration / 1e9):9.2f} tokens/sec")
    
 
resp = chat(
    model="bonsai-2:9b",
    messages=[{"role": "user", "content": "Write a haiku about VRAM."}],
    think=False,
    options={"temperature": 0.0},
)
 
get_prompt_details(resp)

Generate and embeddings

from ollama import embed
 
# embeddings (for local vector search, not RAG-heavy setups)
e = embed(model="nomic-embed-text", input="llama.cpp serves GGUF models")
print(e["embeddings"][0][:5])

The options dict accepts the same parameters as the CLI (temperature, top_p, top_k, num_ctx, num_thread, num_predict), so all tuning from this lab applies directly in Python.

Run — quick checklist

# 1. Install
curl -fsSL https://ollama.com/install.sh | sh        # or the Windows installer
 
# 2. Pull a model for offline use
ollama pull qwen2.5-coder:7b
 
# 3. Inspect and benchmark
ollama run qwen2.5-coder:7b --verbose
ollama ps
 
# 4. Tune and save
ollama create codeassist -f Modelfile
 
# 5. Use from Python
pip install ollama