Skip to main content

llama.cpp Architecture

llama.cpp is designed as a minimal, efficient C/C++ implementation for large language model inference. The architecture prioritizes simplicity, portability, and performance.

Design Philosophy

Minimal Dependencies

Pure C/C++ with no external dependencies for core functionality

Hardware Agnostic

Runs efficiently on CPU, GPU, and specialized accelerators

Memory Efficient

Optimized memory management with support for memory mapping and quantization

Production Ready

Battle-tested codebase used by millions through tools like Ollama, LM Studio, and GPT4All

High-Level Architecture

Core Components

1. GGML Tensor Library

Purpose: Low-level tensor operations and compute graph execution. Key Features:
  • Automatic differentiation
  • Computation graph building and execution
  • Multi-dimensional tensor operations
  • Backend abstraction layer
  • Memory-efficient tensor storage
Key Files:
  • ggml/include/ggml.h - Core tensor library API
  • ggml/include/ggml-backend.h - Backend abstraction
  • ggml/src/ggml.c - Tensor operations implementation
GGML (Georgi Gerganov Machine Learning) is a general-purpose tensor library. llama.cpp serves as the main playground for developing GGML features.
Example: Building a Computation Graph

2. GGUF File Format

Purpose: Binary format for storing models with metadata and quantized weights. Key Features:
  • Self-describing format with embedded metadata
  • Multiple quantization formats (1.5-bit to 16-bit)
  • Extensible key-value metadata system
  • Memory-mappable for efficient loading
  • Single-file model distribution
Key Files:
  • ggml/include/gguf.h - GGUF format API
  • ggml/src/gguf.c - GGUF implementation
See GGUF Format Documentation for details.

3. llama Library

Purpose: High-level LLM inference API built on top of GGML. Key Components:
Handles model loading, weight storage, and metadata.
Responsibilities:
  • Load GGUF files from disk
  • Initialize model weights and architecture
  • Manage memory allocation across backends
  • Provide model introspection (layer count, dimensions, etc.)
Manages inference state including KV cache and processing batches.
Responsibilities:
  • Maintain conversation context (KV cache)
  • Process input tokens in batches
  • Execute inference through backend scheduler
  • Manage context window and memory
Handles token sampling strategies for generation.
Responsibilities:
  • Apply temperature scaling
  • Filter tokens (top-k, top-p, min-p)
  • Apply repetition penalties
  • Sample next token from distribution
Manages tokenization and vocabulary.Supported Tokenizer Types:
  • SPM (SentencePiece) - LLaMA, Mistral
  • BPE (Byte-Pair Encoding) - GPT-2, GPT-3
  • WPM (WordPiece) - BERT
  • UGM (Unigram) - T5
  • RWKV - Greedy tokenization
Responsibilities:
  • Encode text to token IDs
  • Decode token IDs to text
  • Handle special tokens (BOS, EOS, etc.)
Key Files:
  • include/llama.h - Public C API
  • src/llama.cpp - Main implementation
  • src/llama-vocab.cpp - Tokenization
  • src/llama-context.cpp - Context management
  • src/llama-model.cpp - Model loading

Inference Pipeline

The complete flow from input text to generated output:

Model Loading Process

KV Cache Management

The Key-Value cache is critical for efficient autoregressive generation:
Cache Operations:
The KV cache stores attention keys and values for previously processed tokens, avoiding recomputation during generation.

Memory Management

llama.cpp employs several strategies for efficient memory usage:

Memory Mapping (mmap)

Benefits:
  • Zero-copy model loading
  • OS handles paging
  • Shared memory across processes
  • Faster startup

Memory Locking (mlock)

Benefits:
  • Prevents model from being swapped to disk
  • Consistent inference latency
  • Requires sufficient RAM

Quantization

See Quantization Documentation for details on reducing memory footprint.

Backend Abstraction

The backend scheduler dynamically routes operations to appropriate compute devices:
Split Execution:
  • CPU handles some operations (layer norms, embeddings)
  • GPU handles matrix multiplications
  • Automatic data transfer between devices
See Backends Documentation for supported hardware.

Thread Pool

llama.cpp uses a thread pool for CPU parallelism:
Optimal thread count is typically the number of physical CPU cores, not logical cores.

Optimization Techniques

Batch Processing

Process multiple tokens/prompts simultaneously:

Flash Attention

Memory-efficient attention computation:

Speculative Decoding

Use a small draft model to speed up generation:

Simple Example

Minimal inference example:

Further Reading