llama.cpp 快速上手教程
llama.cpp 快速上手建议按"编译 → 下载模型 → 运行对话"这条主线,15 分钟就能在本地跑通一个大模型。
1. 准备环境
需要:
- Git
- CMake 3.14+
- C/C++ 编译器:GCC/Clang(Linux/macOS)、MSVC/MinGW(Windows)
- GPU 驱动(可选):NVIDIA CUDA Toolkit、或 Apple Metal(M 系列芯片自带)
验证环境:
git --version
cmake --version2. 克隆并编译
git clone https://github.com/ggml-org/llama.cpp
cd llama.cpp
cmake -B build
cmake --build build --config Release -j$(nproc)编译完成后,可执行文件在 build/bin/ 目录下。
GPU 加速(可选):
# NVIDIA GPU
cmake -B build -DGGML_CUDA=ON
cmake --build build --config Release -j$(nproc)
# Apple Metal(M 系列芯片自动启用,无需额外参数)3. 下载模型
llama.cpp 使用 GGUF 格式的量化模型。推荐从 Hugging Face 下载:
# 示例:下载 Qwen2.5-7B-Instruct 的 Q4_K_M 量化版
# 在 Hugging Face 搜索 "Qwen2.5-7B-Instruct-GGUF"
# 下载 .gguf 文件到 models/ 目录
mkdir -p models
# 将下载的 .gguf 文件放入 models/ 目录常用模型推荐:
| 模型 | 大小 | 适用场景 |
|---|---|---|
| Qwen2.5-7B-Instruct Q4_K_M | ~4.5GB | 中文对话首选 |
| Llama-3.1-8B-Instruct Q4_K_M | ~4.9GB | 英文通用 |
| Phi-3.5-mini Q4_K_M | ~2.2GB | 轻量级,低配机器 |
| DeepSeek-R1-Distill-Qwen-7B Q4_K_M | ~4.5GB | 推理能力强 |
4. 命令行对话
./build/bin/llama-cli \
-m models/qwen2.5-7b-instruct-q4_k_m.gguf \
-p "用一句话介绍什么是大语言模型" \
-n 256 \
--color参数说明:
-m:模型文件路径-p:初始提示词-n:最大生成 token 数--color:彩色输出
5. 启动 HTTP 服务
llama.cpp 内置 OpenAI 兼容 API 服务器:
./build/bin/llama-server \
-m models/qwen2.5-7b-instruct-q4_k_m.gguf \
--host 0.0.0.0 \
--port 8080启动后自带 Web 聊天界面,浏览器打开 http://localhost:8080 即可对话。
也可用 API 调用:
curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "user", "content": "你好,请介绍一下自己"}
],
"temperature": 0.7
}'6. 性能调优
# 查看模型信息
./build/bin/llama-cli -m models/your-model.gguf --verbose-prompt
# GPU 层卸载(把更多层放到 GPU)
./build/bin/llama-server -m models/your-model.gguf -ngl 99
# 上下文长度(默认 512,可调大但占更多内存)
./build/bin/llama-server -m models/your-model.gguf -c 4096
# 多线程(CPU 推理时)
./build/bin/llama-cli -m models/your-model.gguf -t 8 -p "Hello"7. 常见问题
| 问题 | 解决方案 |
|---|---|
| 内存不足 | 换更小的量化版本(Q3_K_S)或更小的模型 |
| 生成速度慢 | 开启 GPU 加速(-ngl 99),减少上下文长度 |
| 中文乱码 | 确认模型支持中文,检查终端编码为 UTF-8 |
| 编译报错 | 确认 CMake ≥ 3.14,更新编译器版本 |
8. 下一步
- Python 绑定:
pip install llama-cpp-python,在 Python 中调用 - RAG 应用:结合向量数据库做本地知识库问答
- 微调模型:用
llama.cpp的finetune工具做 LoRA 微调 - 嵌入模型:用
llama-embedding生成文本向量