llama.cpp 本地部署大模型指南
# llama.cpp 本地部署大模型指南
纯 C++ 实现的高效推理引擎,最极致的性能追求
什么是 llama.cpp?
- ⚡ 由 Georgi Gerganov 开发
- 🚀 纯 C++ 实现,无需 Python
- 📱 支持 CPU 和 GPU 推理
- 💾 量化支持,大幅降低显存需求
环境要求
CPU 版本
- 8GB+ RAM
- 支持 AVX2 指令集的 CPU
GPU 版本 (CUDA)
- NVIDIA 显卡 6GB+ 显存
- CUDA 12.1+
GPU 版本 (Metal)
- Apple Silicon (M1/M2/M3)
安装
macOS (Apple Silicon)
bash
brew install llama.cppLinux/macOS (从源码编译)
bash
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
makeWindows
下载预编译二进制:
https://github.com/ggerganov/llama.cpp/releases
GPU 加速版本
bash
# CUDA 版本
make LLAMA_CUDA=1
# Metal 版本 (macOS)
make LLAMA_METAL=1下载模型
从 Hugging Face 下载 GGUF 格式模型:
bash
# 安装 huggingface-cli
pip install huggingface-hub
# 下载 llama3-8b-instruct-q4_K_M.gguf
huggingface-cli download meta-llama/Meta-Llama-3-8B-Instruct-Q4_K_M.gguf --local-dir ./models常用模型:
- meta-llama/Meta-Llama-3-8B-Instruct-Q4_K_M.gguf
- TheBloke/Mistral-7B-Instruct-v0.2-GGUF
- TheBloke/CodeLlama-7B-Instruct-GGUF
运行模型
交互模式
bash
./main -m models/llama3-8b-instruct-q4_K_M.gguf -n 256 --temp 0.7 -p "你好,"参数说明
| 参数 | 说明 | 示例 |
|------|------|------|
| -m | 模型路径 | -m models/llama3.gguf |
| -n | 生成token数 | -n 256 |
| -c | Context长度 | -c 4096 |
| -temp | 温度 | -temp 0.7 |
| -t | 线程数 | -t 8 |
| -ngl | GPU层数 | -ngl 32 |
GPU 加速
bash
./main -m models/llama3-8b-instruct-q4_K_M.gguf -ngl 32 -t 8API 服务
使用 llama.cpp 的 HTTP 服务器:
bash
./server -m models/llama3-8b-instruct-q4_K_M.gguf -c 4096 -ngl 32默认端口:8080
OpenAI 兼容 API
bash
./server -m models/llama3-8b-instruct-q4_K_M.gguf --model ./models/llama3.gguf --slots --slot-save-path ./slots调用示例:
bash
curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "llama3",
"messages": [{"role": "user", "content": "你好"}]
}'与 OpenClaw 集成
env
AI_PROVIDER=ollama
OLLAMA_BASE_URL=http://localhost:8080/v1
OLLAMA_MODEL=llama3量化知识
模型精度与显存对照 (7B 模型):
| 量化 | 大小 | 显存需求 | 质量 |
|------|------|----------|------|
| Q4_0 | 3.5GB | 5GB | 较好 |
| Q4_K_M | 3.8GB | 6GB | 接近原始 |
| Q5_0 | 4.3GB | 6GB | 很好 |
| Q5_K_S | 4.5GB | 7GB | 接近原始 |
| Q8_0 | 6.7GB | 9GB | 几乎无损 |
性能优化
CPU 优化
bash
# 使用更多线程
./main -m model.gguf -t 16
# SIMD 优化
./main -m model.gguf -ngl 0GPU 优化
bash
# 调整 GPU 层数 (从 32 开始尝试)
./main -m model.gguf -ngl 40
# 如果显存不足,减少层数
./main -m model.gguf -ngl 20---
相关教程:
- [Ollama 本地部署](/post/ollama-local-llm)
- [LM Studio 本地部署](/post/lm-studio-local-llm)