Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 10 min read

Ollama Under the Hood: What Actually Happens Between ollama run and GPU Memory

You open a terminal, type ollama run deepseek-r1:8b, and seconds later tokens stream across your screen at sixty words a second. To most developers, Ollama feels like magic or a lightweight Python wrapper around llama.

You open a terminal, type ollama run deepseek-r1:8b, and seconds later tokens stream across your screen at sixty words a second.

To most developers, Ollama feels like magic or a lightweight Python wrapper around llama.cpp. When you look at the system monitor, however, there is no Python process running. Instead, you see a Go daemon consuming almost zero CPU, a child process named ollama runner holding onto gigabytes of VRAM, and a directory in ~/.ollama filled with SHA-256 hashes that look suspiciously like Docker container layers.

What is actually happening between the moment you hit Enter and the moment GPU tensor cores start multiplying weight matrices?

Here is what happens under the hood: how Ollama resolves OCI-compliant manifests, delegates inference to dynamic C++ runner subprocesses over localhost RPC, memory-maps 32-byte aligned GGUF tensors, and calculates the exact VRAM budget before your context window crashes your machine.

1. The OCI Blob Store: Models Stored Like Container Images

When you pull a model with Ollama, you are not downloading a simple monolithic .bin file from a random file host. Ollama implements the Open Container Initiative (OCI) image distribution specification.

If you inspect ~/.ollama/models, you will find two directories: manifests and blobs.

tree ~/.ollama/models
# ~/.ollama/models
# β”œβ”€β”€ blobs
# β”‚   β”œβ”€β”€ sha256-0ba8f0e314b4...
# β”‚   β”œβ”€β”€ sha256-43070e2d4e53...
# β”‚   └── sha256-6a0746a1ec1a...
# └── manifests
#     └── registry.ollama.ai
#         └── library
#             └── deepseek-r1
#                 └── 8b

The file in manifests/registry.ollama.ai/library/deepseek-r1/8b is pure JSON. It looks almost identical to a Docker image manifest:

{
  "schemaVersion": 2,
  "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
  "config": {
    "mediaType": "application/vnd.docker.container.image.v1+json",
    "digest": "sha256:0ba8f0e314b4...",
    "size": 486
  },
  "layers": [
    {
      "mediaType": "application/vnd.ollama.image.model",
      "digest": "sha256:6a0746a1ec1a...",
      "size": 4920752128
    },
    {
      "mediaType": "application/vnd.ollama.image.template",
      "digest": "sha256:e008d6c70172...",
      "size": 1785
    },
    {
      "mediaType": "application/vnd.ollama.image.params",
      "digest": "sha256:43070e2d4e53...",
      "size": 95
    }
  ]
}

Notice the separation of concerns:

  • Model layer: The raw GGUF file containing quantized weights and tensor definitions.
  • Template layer: The Go/Jinja template that converts user chat messages into raw token strings (such as <|User|>...<|Assistant|><think>...).
  • Params layer: Runtime defaults such as temperature, top_p, and stop tokens.

Because all layers are content-addressed by their SHA-256 hash in ~/.ollama/models/blobs, sharing models is instantaneous. If you create a custom Modelfile with a specialized system prompt based on deepseek-r1:8b, Ollama does not duplicate the 4.9 GB weight blob. It writes a tiny new manifest pointing to the exact same weight digest.

2. The Two-Process Architecture: Why Ollama Spawns Subprocesses

Once Ollama reads the manifest, it has to run inference. A naive design would import llama.cpp using Cgo directly inside the Go server.

Ollama deliberately does not do this. It uses a multi-process architecture. The main daemon is a process supervisor; the actual computation happens inside dynamically spawned C++ subprocesses.

+-----------------------------------------------------------+
|                   Ollama Daemon (Go)                      |
|  - HTTP REST API (port 11434)                             |
|  - Hardware Discovery (NVML, ROCm, Metal)                 |
|  - OCI Manifest & Blob Management                         |
|  - Memory Budgeting & Subprocess Lifecycle Supervision    |
+-----------------------------+-----------------------------+
                              |
                     Spawns & Supervises
                              |
                              v
+-----------------------------------------------------------+
|              ollama runner (C++ / llama.cpp)              |
|  - Binds to random ephemeral localhost port (e.g. 49152)  |
|  - Communicates with Go server via HTTP/JSON RPC          |
|  - mmap() GGUF Tensor Weight Tensors                      |
|  - Dispatches CUDA / ROCm / Metal Compute Kernels         |
+-----------------------------------------------------------+

There are three major architectural reasons for this separation:

1. Fault Isolation

Inference involves raw CUDA pointer math, vendor GPU drivers, and massive memory buffers. If an NVIDIA driver throws an out-of-memory error, or a tensor kernel faults, a C++ segfault in a monolithic process would take down your entire Ollama server and disconnect every active client. With subprocess isolation, if the runner crashes, the Go supervisor catches the exit code, logs the error, reclaims OS resources, and keeps running.

2. Dynamic GPU Library Selection

Your machine might have CUDA 12, CUDA 11, ROCm, or only AVX2 CPU instructions. Rather than building a single bloated binary or forcing users to compile from source, the Go daemon inspects your system at startup using NVML (NVIDIA Management Library) or sysfs. It then selects and launches the specific pre-compiled runner matching your hardware:

// Inside Ollama's llm/server.go
lib := gpus[0].RunnerName() // e.g. "cuda_v12", "rocm_v6", "cpu_avx2"
cmd := exec.Command(runnerPath, finalParams...)
cmd.Env = append(cmd.Env, fmt.Sprintf("LD_LIBRARY_PATH=%s", libPath))

3. Clean VRAM Eviction

Freeing VRAM in CUDA without terminating the host process is notoriously tricky due to CUDA context caching and memory pool fragmentation. By isolating the model in a subprocess, Ollama can free 100% of GPU VRAM simply by sending a SIGTERM to the runner.

3. The GGUF Memory Map (mmap) Trick

When the runner launches, how does it load a 5 GB model into memory in under a second?

If you used standard filesystem I/O (read()), the operating system would read bytes from your SSD into the kernel page cache, copy those bytes into the user-space process heap, and allocate another buffer before copying to the GPU. That double-buffering takes time and doubles your RAM consumption.

Instead, Ollama tells the runner to use mmap() on the GGUF file:

// Conceptual mmap inside the llama.cpp engine
int fd = open("blobs/sha256-6a0746a1ec...", O_RDONLY);
void* model_bytes = mmap(NULL, file_size, PROT_READ, MAP_SHARED, fd, 0);

The GGUF binary format is engineered specifically for this. All tensor data inside GGUF is aligned to 32-byte boundaries (matching hardware SIMD and cache lines).

When mmap() runs, the OS maps the file directly into the process's virtual address space. Not a single byte of weight data is actually read from disk yet. As the runner iterates over layers to offload them to the GPU, page faults load the exact chunks needed from disk directly into DMA buffers, where cudaMemcpyAsync streams them across the PCIe bus into GPU memory.

When Linux Overrules mmap

There is a catch that caught many Linux users off guard. If your system RAM is smaller than the model file, aggressive memory mapping causes the Linux kernel to thrash. Every time the model executes a forward pass, the kernel evicts earlier layers from the page cache to make room for later layers, forcing continuous reads from the SSD.

Ollama's llm/server.go includes a check for this exact edge case:

// If free system RAM is less than total model size, disable mmap
if (runtime.GOOS == "linux" && systemFreeMemory < estimate.TotalSize) || 
   (gpus[0].Library == "cpu") {
    params = append(params, "--no-mmap")
}

When --no-mmap is passed, the runner bypasses the virtual memory map and allocates explicit physical memory, avoiding disk thrashing during token generation.

4. The Secret VRAM Killer: KV Cache & Budget Math

Here is the most common mystery developers encounter: you have an 8 GB VRAM GPU and a Q4_K_M model that is 4.6 GB on disk. Yet when you run it, Ollama refuses to offload all layers to the GPU, or your system crashes with an out-of-memory error.

Why does a 4.6 GB model fail to fit inside 8 GB of VRAM?

Because weights are only one part of the memory equation. In llm/server.go, Ollama calls a function named EstimateGPULayers. It computes three distinct memory pools:

Total Required VRAM = Model Weights (Offloaded) + KV Cache + Compute Graph Overhead
+---------------------------------------------------------------+
|                      GPU VRAM (e.g. 8192 MB)                  |
+-------------------------------+---------------+---------------+
| Model Layer Weights           | KV Cache      | Compute Graph |
| (Offloaded to GPU)            | (Context Win) | Overhead      |
| ~4,700 MB                     | ~1,024 MB     | ~450 MB       |
+-------------------------------+---------------+---------------+
|<----------------------- Total Allocated --------------------->|

1. Compute Graph Overhead

During the forward pass, intermediate activation matrices, attention score buffers, and normalization workspaces must exist in GPU memory. For modern transformer architectures, this buffer takes between 200 MB and 600 MB depending on batch size.

2. The KV Cache Trap

The KV cache stores the Key and Value projection vectors for every token in your context window so the model does not have to recompute attention for past tokens on every step.

The memory required for the KV cache per token follows this exact formula:

$$\text{KV Bytes per Token} = 2 \times n_{\text{layers}} \times n_{\text{kv_heads}} \times d_{\text{head}} \times \text{bytes_per_element}$$

Let us calculate this for a standard 8B parameter model using Grouped-Query Attention (GQA):

  • Number of layers ($n_{\text{layers}}$): 32
  • Number of KV heads ($n_{\text{kv_heads}}$): 8
  • Head dimension ($d_{\text{head}}$): 128
  • Precision: 16-bit float (2 bytes)

$$\text{Bytes per Token} = 2 \times 32 \times 8 \times 128 \times 2 = 131,072 \text{ bytes} = 128 \text{ KB per token}$$

Now look at what happens when you adjust the context window (num_ctx):

  • At 2,048 tokens (2k): $128 \text{ KB} \times 2,048 = 256 \text{ MB}$
  • At 8,192 tokens (8k): $128 \text{ KB} \times 8,192 = 1,024 \text{ MB} = 1.0 \text{ GB}$
  • At 32,768 tokens (32k): $128 \text{ KB} \times 32,768 = 4,096 \text{ MB} = 4.0 \text{ GB}$

If you configure a 32k context window on an 8 GB card, the KV cache alone demands 4 GB of VRAM. Add 4.6 GB of weights and 400 MB of graph overhead, and you need 9 GB of VRAM.

Ollama's EstimateGPULayers calculates the KV cache size upfront based on your requested num_ctx. If the entire model plus KV cache cannot fit, Ollama calculates how many layers can fit:

// Ollama calculates exact GPU layer count that fits into remaining VRAM
layers, estimatedVRAM, estimatedTotal = EstimateGPULayers(gpus, ggml, projectors, opts)
opts.NumGPU = layers
params = append(params, "--n-gpu-layers", strconv.Itoa(opts.NumGPU))

5. Partial Offloading: The PCIe Bus Penalty

What happens when Ollama determines that only 24 out of 32 layers fit in your GPU?

It performs partial offloading: 24 layers are loaded into GPU VRAM, while the remaining 8 layers stay in system RAM and execute on the CPU.

While this allows you to run models that exceed your VRAM, it comes with a massive latency penalty. Here is what happens during every single generated token:

[Prompt Embeddings]
       |
       v
+-------------------------------------------------------+
| GPU VRAM (Tensor Cores)                               |
| Layers 0 to 23 executed at 800+ GB/s memory bandwidth |
+-------------------------------------------------------+
       |
       |  ACTIVATION TENSOR TRANSFER
       v  (Bottlenecked by PCIe bus: ~15 to 31 GB/s)
+-------------------------------------------------------+
| CPU System RAM (Host Cores)                           |
| Layers 24 to 31 executed at 50 to 80 GB/s bandwidth   |
+-------------------------------------------------------+
       |
       v
[Logits -> Sample Token]
  1. The token embedding is processed through Layers 0 to 23 on the GPU at high memory bandwidth (typically 500 to 1,000 GB/s on modern GDDR6/HBM).
  2. The intermediate activation tensor must now leave the GPU. It travels across the PCIe bus into system RAM.
  3. Your CPU processes Layers 24 to 31 using system RAM bandwidth (typically 50 to 80 GB/s on dual-channel DDR5).
  4. The final logits are computed, a token is sampled, and the process repeats for the next token.

Because this round-trip across the PCIe bus and CPU execution occurs for every single generated token, offloading even 4 or 5 layers to the CPU can cause generation speed to drop from 45 tokens per second to 5 tokens per second.

If you cannot fit all layers into VRAM, choosing a smaller quantization (such as Q4_K_M instead of Q8_0) that allows 100% layer offloading will almost always run significantly faster than running a higher-precision model split between GPU and CPU.

6. The Lifecycle & Idle Eviction Loop

Once the model is running and streaming tokens via Server-Sent Events (SSE) to your terminal or web UI, Ollama's background timer takes over.

In the Go daemon, each active model holds a reference count and an idle expiration timestamp governed by OLLAMA_KEEP_ALIVE (defaulting to 5 minutes):

// Inside Ollama model management
type loadedModel struct {
    runner   LlamaServer
    expires  time.Time
}

func (s *Server) pruneExpiredModels() {
    for model := range s.loaded {
        if time.Now().After(model.expires) {
            model.runner.Close() // Sends SIGTERM/Kill to subprocess
            delete(s.loaded, model)
        }
    }
}

If you do not send any prompts for 5 minutes, Ollama terminates the runner subprocess. The operating system kernel immediately reclaims all GPU VRAM and host RAM.

If you want the model to unload immediately after a script finishes, you can send an explicit keep-alive duration of zero:

curl http://localhost:11434/api/generate -d '{
  "model": "deepseek-r1:8b",
  "prompt": "Hello",
  "keep_alive": 0
}'

Conversely, if you are running an automated agent in production and want to prevent cold-start reload latency, set OLLAMA_KEEP_ALIVE=-1 in your environment to keep the model pinned in VRAM indefinitely.

7. Production Tuning Cheat Sheet

Knowing these internal mechanics gives you direct control over performance. Here are the configuration options that matter:

Setting / Variable Default What It Actually Does Internally
OLLAMA_NUM_PARALLEL 1 Multiplies KV cache allocation by N to support concurrent inference slots without queuing.
OLLAMA_FLASH_ATTENTION 0 Enables FlashAttention kernels in llama.cpp, cutting KV cache memory overhead in half on supported cards.
OLLAMA_MAX_LOADED_MODELS 1 Controls how many runner subprocesses can coexist in VRAM before LRU eviction triggers.
num_ctx (in API/Modelfile) 2048 Directly controls KV cache allocation. Setting this to 32k on limited VRAM will force layers to CPU.
num_gpu (in API request) Auto Overrides EstimateGPULayers to force a specific number of layers onto the GPU.

The Practical Takeaway

Ollama is not an AI model, and it is not a monolithic runtime. It is an orchestration bridge.

It packages models into content-addressed OCI container blobs, calculates strict memory budgets for weights and KV caches before touching hardware, and manages isolated C++ inference subprocesses over local RPC.

When your local models run slowly or trigger out-of-memory errors, the problem is rarely the model weights alone. Check your context window (num_ctx), verify whether partial offloading is bottlenecking your PCIe bus, and inspect your runner's layer estimation logs. The moment you understand the memory math, local model deployment stops being guesswork.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.