Skip to main content

llama.cpp: Efficient Local LLM Inference on CPU & GPU

llama.cpp is the engine powering most local AI tools — Ollama, KoboldCpp, LM Studio, GPT4All all run on it. Use it directly for maximum control over inference, custom quantization, embedding models, and integration into C/C++ or Python applications running on any hardware from a MacBook to a GPU cluster.

✓ Runs on CPU, CUDA, Metal, Vulkan, OpenCL ✓ GGUF model format (all quantization levels) ✓ OpenAI-compatible server mode ✓ Python bindings (llama-cpp-python)
Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →

Building llama.cpp

llama.cpp is a C++ project built with CMake. Choose the right build flags for your hardware:

# Clone the repository
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp

# CPU-only build (universal, works everywhere)
cmake -B build
cmake --build build --config Release -j$(nproc)

# NVIDIA GPU (CUDA) — requires CUDA toolkit
cmake -B build -DGGML_CUDA=ON
cmake --build build --config Release -j$(nproc)

# Apple Silicon (Metal) — best macOS performance
cmake -B build -DGGML_METAL=ON
cmake --build build --config Release

# AMD GPU (ROCm/HIP) — Linux only
cmake -B build -DGGML_HIPBLAS=ON
cmake --build build --config Release

# Vulkan — cross-platform GPU (Intel, AMD, NVIDIA)
cmake -B build -DGGML_VULKAN=ON
cmake --build build --config Release

# Binaries are in build/bin/
# Key binaries: llama-cli, llama-server, llama-embedding

GGUF Quantization: Choosing the Right Level

GGUF quantization compresses model weights to reduce file size and RAM usage. Here's a practical guide to choosing the right quantization for your hardware and quality requirements:

# Quantization comparison for Llama 3.2 7B:
# ──────────────────────────────────────────────────────────────
# Format     Size    RAM     Quality   Speed     Recommended
# Q2_K       2.7 GB  ~5 GB   ★★☆☆☆    Fastest   Low RAM only
# Q3_K_M     3.3 GB  ~6 GB   ★★★☆☆    Fast      Constrained RAM
# Q4_0       3.8 GB  ~6 GB   ★★★☆☆    Fast      Legacy, prefer Q4_K_M
# Q4_K_M     4.1 GB  ~7 GB   ★★★★☆    Fast      ← BEST BALANCE
# Q4_K_S     3.9 GB  ~7 GB   ★★★★☆    Fast      Slightly smaller than _M
# Q5_K_M     4.8 GB  ~8 GB   ★★★★☆    Moderate  High quality
# Q5_K_S     4.7 GB  ~8 GB   ★★★★☆    Moderate  Good for coding
# Q6_K       5.5 GB  ~8 GB   ★★★★★    Moderate  Near-lossless
# Q8_0       7.7 GB  ~10 GB  ★★★★★    Moderate  Near-lossless
# F16        14.1 GB ~16 GB  ★★★★★    Slowest   Reference quality

# Quantize your own model from HuggingFace:
# Step 1: Convert to GGUF
python convert_hf_to_gguf.py /path/to/hf/model --outtype f16

# Step 2: Quantize
./build/bin/llama-quantize model-f16.gguf model-Q4_K_M.gguf Q4_K_M

Server Mode (OpenAI-Compatible API)

The llama-server binary starts an HTTP server with an OpenAI-compatible API and a built-in chat UI:

# Start the server with GPU offloading
./build/bin/llama-server \
  --model models/llama-3.2-7b-instruct-q4_k_m.gguf \
  --port 8080 \
  --host 0.0.0.0 \
  --ctx-size 8192 \
  --n-gpu-layers 35 \    # Offload 35 layers to GPU (set 999 for all)
  --threads 8 \          # CPU threads for CPU layers
  --batch-size 512 \     # Prompt processing batch size
  --parallel 2           # Number of parallel request slots

# Chat UI: http://localhost:8080
# OpenAI API: http://localhost:8080/v1/chat/completions

# Use with Python openai SDK:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8080/v1", api_key="llamacpp")
resp = client.chat.completions.create(
    model="llama-3.2-7b",
    messages=[{"role": "user", "content": "Explain PagedAttention"}]
)
print(resp.choices[0].message.content)

Python Bindings: llama-cpp-python

llama-cpp-python wraps the C++ library for direct use in Python scripts. It also includes a built-in OpenAI-compatible server.

# Install (CPU)
pip install llama-cpp-python

# Install with CUDA support
CMAKE_ARGS="-DGGML_CUDA=on" pip install llama-cpp-python

# Install with Metal support (macOS)
CMAKE_ARGS="-DGGML_METAL=on" pip install llama-cpp-python

# Basic usage
from llama_cpp import Llama

llm = Llama(
    model_path="./models/llama-3.2-7b-q4_k_m.gguf",
    n_ctx=8192,          # Context window
    n_gpu_layers=35,     # GPU layers (0 = CPU only, -1 = all)
    n_threads=8,         # CPU threads
    verbose=False
)

# Chat completion
response = llm.create_chat_completion(
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Write a Python decorator for timing functions"}
    ],
    max_tokens=512,
    temperature=0.7
)
print(response["choices"][0]["message"]["content"])

# Start built-in OpenAI server
python -m llama_cpp.server --model model.gguf --port 8000

llama.cpp vs Ollama

Feature llama.cpp (direct) Ollama
Inference engineIS the engineBuilt on llama.cpp
Ease of useTechnical (build required)Very easy
Model quantization controlFull (quantize your own)Use pre-built GGUF
Embedding modelsllama-embedding binaryYes (ollama pull)
Python integrationllama-cpp-pythonVia openai SDK
Custom compile flagsFull controlFixed build
Best forResearch, custom builds, C++ appsDeveloper convenience

Frequently Asked Questions

What is llama.cpp?▼

llama.cpp is a C/C++ implementation of LLM inference that runs on virtually any hardware — from a Raspberry Pi to a data center GPU. Created by Georgi Gerganov, it introduced the GGUF model format and pioneered efficient CPU-based LLM inference. llama.cpp is the inference backbone used by Ollama, KoboldCpp, LM Studio, GPT4All, and dozens of other tools.

What is GGUF format?▼

GGUF (GGML Universal Format) is the standard quantized model format created for llama.cpp. It packs model weights, configuration, tokenizer, and metadata into a single file with a clean header format. GGUF replaced the older GGML format in 2023 and has become the dominant format for distributing quantized LLMs. Quantization levels like Q4_K_M, Q5_K_S, and Q8_0 compress model weights to 4–8 bits, reducing file size and RAM by 50–75% with minimal quality loss.

What do quantization levels like Q4_K_M mean?▼

Quantization levels have a naming convention: Q = quantization, the number = bits per weight (4 = 4-bit, 5 = 5-bit, 8 = 8-bit), K = k-quants (a smarter quantization method that quantizes different layers differently), and S/M/L = size of the quantization groups (Small/Medium/Large). Q4_K_M is 4-bit with medium-size k-quant groups — the most popular choice balancing file size (~4 GB for 7B) and quality. Q8_0 is near-lossless but twice as large.

How do I run llama.cpp as an OpenAI-compatible server?▼

Build llama.cpp and run the llama-server binary: ./llama-server -m model.gguf --port 8080 -c 8192 --host 0.0.0.0. This starts an OpenAI-compatible server at /v1/chat/completions. Use --n-gpu-layers N to offload N transformer layers to GPU. Set N to 999 to offload everything. The server also provides a built-in chat UI at http://localhost:8080.

What Python bindings are available for llama.cpp?▼

llama-cpp-python is the official Python binding for llama.cpp. Install with pip install llama-cpp-python. It wraps the C++ library and provides both a low-level ctypes API and a high-level API compatible with the OpenAI SDK. For GPU support: CMAKE_ARGS='-DGGML_CUDA=on' pip install llama-cpp-python (NVIDIA) or CMAKE_ARGS='-DGGML_METAL=on' pip install llama-cpp-python (Apple Silicon).

llama.cpp vs Ollama — what's the difference?▼

Ollama is built on top of llama.cpp — it uses llama.cpp as its inference engine but adds a model registry, CLI, automatic model management, and a cleaner API. Use llama.cpp directly when you need maximum control: custom compile flags, specific quantization experiments, embedding models, raw performance benchmarking, or embedding into a C/C++ application. Use Ollama when you want convenience and don't need llama.cpp-specific features.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

AI Hallucination Detector AI Safety Checklist Generator CrewAI Agent Config Generator AI Model Comparator AI Model Comparison Tool Jotai Atom Explorer LangChain PromptTemplate Builder LLM Cost Calculator CSS Container Query Builder LLM Context Window Calculator AI Prompt Cost Calculator LLM JSON Schema Builder AI Agent Run Cost Tracker AI Pipeline DAG Builder LLM Benchmark Calculator Prompt Injection Tester AI Token Cost Calculator MySQL Query Explainer PostgreSQL EXPLAIN Analyzer AI Model Benchmark Comparator Cron Expression Explainer Font Pairing Preview LLM Prompt Cost Calculator AI Model Context Window Visualizer OpenAI Prompt Tester AI Rate Limit Calculator LLM System Prompt Analyzer Vibe Coding Prompt Optimizer AI IDE Comparator Token Counter & Cost Estimator AI Model Comparison Table RAG Chunk Size Optimizer LLM Prompt Template Builder AI Commit Message Generator AI Doc Generator — Pro Tool AI Regex Explainer — Pro Tool AI System Guardian AI JSDoc Generator K8s Resource Limits Calculator Mermaid Diagram Generator Elasticsearch Query Tester mTLS Certificate Chain Builder Prompt Token Estimator JS Prototype Chain Visualizer OpenAI Token Counter System Prompt Builder AI Agent Memory Planner Token Context Calculator LLM Prompt Caching Calculator Multi-Agent Orchestration Planner AI Prompt Token Estimator OpenAI Function Calling Generator AI Context Window Visualizer Embedding Storage Calculator AI API Rate Limit Calculator HTTP Headers Analyzer AI Code Review — Pro Tool AI Error Explainer — Pro Tool AI SQL Builder — Pro Tool AI Unit Test Generator — Pro Tool Color Palette Generator Docker Compose Generator GitHub Actions Workflow Generator JWT Decoder Prompt Template Builder Regex Tester Pro Regex Tester RSA Key Pair Generator Dockerfile Generator SMTP Server Tester Biome Config Generator Terraform Variable Validator Kubernetes Resource Estimator Haproxy Config Validator SBOM Generator Kubernetes Resource Quota Calculator AI Variable Namer AI PR Description Generator Regex Flags Explainer LLM Token Counter Kubernetes Resource Calculator NATS Connection String Builder OAuth2 Flow Visualizer Playwright E2E Testing Guide Pulumi Modern IaC Guide Core Web Vitals Calculator RAG Chunking Calculator Solana Program ID Generator Multi-Chain Wallet Address Validator Pulumi Stack Config Generator Kubernetes Resource Calculator Kubernetes Resource Request Calculator LangGraph Workflow Visualizer RAG Chunking Calculator TypeScript Discriminated Union Builder Core Web Vitals Budget Calculator JWT Decoder & Validator Blockchain Transaction Fee Calculator Database Query Cost Analyzer

Related Articles

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →