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.
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
JSON Formatter & Validator
Format, beautify, and validate JSON online. Paste your JSON to instantly pretty-print it with 2-space, 4-space, or tab indentation. Minify JSON too. Free, runs in your browser.
Open free tool →
Regex Tester
Free regex tester. Test regular expressions against multiple strings with expected match/no-match assertions — see instant pass/fail results. Built-in presets for email, URL, IPv4, and phone. Pro: unl
Open free tool →
Base64 Encoder & Decoder
Free Base64 Encoder & Decoder. Convert text, images, and any file to Base64 and back. Supports URL-safe Base64, image data URIs, and file download from Base64. Runs 100% in your browser — no data sent
Open free tool →
More Free Tools
Related Articles
curl 深度使用手冊:API 測試從入門到進階
curl 是每位開發者必備的 CLI 工具。本文涵蓋 GET/POST/PUT/DELETE 請求、認證、header 設定、檔案上傳、除錯技巧,以及 REST API 測試的完整實戰範例。
Best AI Code Review Tools 2026: CodeRabbit, Sourcery, DeepCode & Bito Compared
Compare top AI code review tools for 2026: CodeRabbit, Sourcery, DeepCode, and Bito. Features, pricing, GitHub/GitLab integration, and choosing the right tool for your team.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
AI Coding Tools Comparison 2026: GitHub Copilot vs Cursor vs Windsurf vs Cline
Comprehensive comparison of the best AI coding tools in 2026: GitHub Copilot, Cursor, Windsurf, and Cline. Pricing, features, model support, and real-world benchmarks.
AI Pair Programming in 2026: GitHub Copilot vs Cursor vs Claude Code
Master AI pair programming in 2026. Compare GitHub Copilot, Cursor, and Claude Code for autocomplete, chat, and agentic workflows. Includes setup guides and productivity tips.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$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.
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 engine | IS the engine | Built on llama.cpp |
| Ease of use | Technical (build required) | Very easy |
| Model quantization control | Full (quantize your own) | Use pre-built GGUF |
| Embedding models | llama-embedding binary | Yes (ollama pull) |
| Python integration | llama-cpp-python | Via openai SDK |
| Custom compile flags | Full control | Fixed build |
| Best for | Research, custom builds, C++ apps | Developer 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.
Related Products
on GumroadAI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →AI Developer Prompts Pack
55 battle-tested prompt templates for the workflows developers actually use: code review, debugging, architecture, documentation, and testing. Stop writing prompts from scratch.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →You Might Also Need
AI Hallucination Detector
Scan LLM-generated text for hallucination risk signals: fabricated citations, overconfident claims, suspect statistics, and verification gaps. Risk score 0-100 with highlighted problem spans.
Open free tool →
AI Safety Checklist Generator
Generate a customized AI safety evaluation checklist for your deployment. Covers technical safety, content moderation, security, bias, privacy, and regulatory compliance. Export to Markdown.
Open free tool →
CrewAI Agent Config Generator
Build CrewAI agent configurations visually. Define roles, goals, backstories, and tools. Generate YAML or Python code for multi-agent crews.
Open free tool →
More Free Tools
Related Articles
DSPy: Building Self-Optimizing LLM Pipelines in 2026
DSPy 2026: build self-optimizing LLM pipelines with signatures, modules, and teleprompters. Real-world examples vs manual prompting for developers.
Building a Production RAG Pipeline: Complete Implementation Guide 2026
A comprehensive guide to building production-ready RAG pipelines in 2026. Covers chunking strategies, embedding models, vector store selection, retrieval techniques, reranking, evaluation with RAGAS/TruLens, and LangChain vs LlamaIndex vs custom implementations.
LangChain vs LlamaIndex: Which AI Framework Should You Use in 2026?
A head-to-head comparison of LangChain vs LlamaIndex in 2026 — covering architecture philosophy, RAG pipelines, agent support, ecosystem, and a decision framework for your next AI project.
LiteLLM vs OpenRouter vs AI Suite: LLM Gateway & Model Routing in 2026
A comprehensive comparison of LiteLLM, OpenRouter, and AI Suite for LLM gateway and model routing in 2026 — unified API, model fallback, cost routing, rate limiting, caching, and deployment options with Python code examples.
Model Context Protocol (MCP) Complete Guide 2026
The definitive guide to MCP (Model Context Protocol) by Anthropic. Learn what MCP is, how its architecture works, how to build MCP servers, real-world integrations, and how it compares to function calling and plugins.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$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.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →