简介
llama.cpp 是一个专注于推理过程中性能优化的项目,主要解决大模型在本地运行时的效率问题。其核心优势在于无需 GPU 即可运行 LLaMA 模型,支持多种量化方案以加快推理速度并减少内存占用。
主要特点包括:
- 纯粹的 C/C++ 实现,无外部依赖
- 支持广泛的硬件:x86_64 CPU (AVX/AVX2/AVX512)、Apple Silicon (Metal/Accelerate)、NVIDIA GPU (CUDA)、AMD GPU (hipBLAS)、Intel GPU (SYCL) 等
- 多种量化方案(32 位浮点转 16 位、8 位、4 位整数)
- CPU+GPU 混合推理,加速超过总 VRAM 容量的模型
- 提供模型量化工具及服务化组件(API)
1. llama.cpp 环境安装
克隆仓库并进入目录:
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
构建 GPU 执行环境(需安装 CUDA 工具包):
如果 CUDA 设置正确,执行
nvidia-smi或nvcc --version无错误提示则表示配置成功。
mkdir build
sudo apt-get install make cmake gcc g++
locate cmake -B build -DGGML_CUDA=ON
cmake --build build --config Release -j4
cd build
make install
在当前版本中,指令已重命名为 llama-quantize、llama-cli、llama-server。可创建软链接以便调用:
ln -s your/path/to/llama.cpp/build/bin/llama-quantize llama-quantize
ln -s your/path/to/llama.cpp/build/bin/llama-server llama-server
ln -s your/path/to/llama.cpp/build/bin/llama-cli llama-cli
2. LLaMA 模型转换
2.1 PTH 原始模型处理
首先安装 Python 3.10 及相关依赖:
pip install protobuf==3.20.0
pip install transformers
pip install sentencepiece
pip install peft
2.1.1 下载模型权重
下载原版 LLaMA 模型的权重和 tokenizer.model 文件。可使用 IPFS 客户端或 BitTorrent 下载。
压缩包内文件目录示例(LLaMA-7B):
├── llama-7b
│ ├── consolidated.00.pth
│ ├── params.json
│ └── checklist.chk
└── tokenizer.model
2.1.2 使用 pyllama 下载
通过 pip 安装库:
pip3 install transformers pyllama -U
下载 Llama 7B 模型:
python3 -m llama.download --model_size 7B
若遇到架构兼容报错(如 Mac M2),需手动构建 itree 库:
brew install cmake
pip3 install https://github.com/juncongmoo/itree/archive/refs/tags/v0.0.18.tar.gz
卸载旧版 pyllama 并源码安装:
pip3 uninstall pyllama
git clone https://github.com/juncongmoo/pyllama
pip3 install -e pyllama
再次运行下载命令。
2.1.3 脚本下载
使用自动化脚本下载:
#!/bin/bash
function stop_script() {
echo "Stopping the script."
exit 0
}
trap stop_script SIGINT
while true; do
timeout 2000 python -m llama.download --model_size $1 --folder model
echo "restart download"
sleep 1
read -t 1 -n 1 -s key
if [[$key]]; then stop_script fi
done
运行脚本:
bash llama_download.sh 7B
2.2 格式转换
2.2.1 HF 格式转换
使用 HuggingFace 提供的脚本将原版 LLaMA 模型转换为 HuggingFace 格式:
git clone https://huggingface.co/luodian/llama-7b-hf ./models/Llama-7b-chat-hf
执行转换命令:
git clone https://github.com/huggingface/transformers.git
cd transformers
python src/transformers/models/llama/convert_llama_weights_to_hf.py \
--input_dir /workspace/pth_model/7B \
--model_size 7B \
--output_dir /workspace/hf_data
输出目录将包含 config.json、pytorch_model.bin 等 HF 格式文件。
2.2.2 合并 LoRA
使用 Chinese-LLaMA-Alpaca 脚本合并 LoRA 权重:
git clone https://github.com/ymcui/Chinese-LLaMA-Alpaca.git
合并脚本参数说明:
--base_model: HF 格式模型目录--lora_model: LoRA 解压后目录--output_type: 输出格式 (pth或huggingface)--output_dir: 保存全量模型权重的目录
python scripts/merge_llama_with_chinese_lora.py \
--base_model /workspace/hf_data \
--lora_model /workspace/chinese_llama_lora_7B \
--output_dir /workspace/lora_pth_data
2.3 HF 转 GGUF 模型
使用 convert_hf_to_gguf.py 将模型转化为 GGUF 格式并进行量化:
# HF 版本转换
python convert_hf_to_gguf.py ../hf_data --outfile /workspace/chinese_gguf/llama-7b.gguf --outtype q8_0
# PTH 版本转换
python3 examples/convert_legacy_llama.py /workspace/lora_pth_data/ --outfile /workspace/chinese_gguf/chinese.gguf
使用 llama-quantize 进行精度转换:
llama-quantize /workspace/chinese_gguf/chinese.gguf /workspace/chinese_gguf/chinese_q4_0.gguf Q4_0
支持的量化类型包括 Q4_0, Q4_K_M, Q5_K_M, Q8_0 等,数值越小体积越小但精度略降。
3. 使用 llama.cpp 运行 GGUF 模型
下载模型文件放在 llama.cpp 项目 models 目录下,例如从 HuggingFace 获取 GGUF 版本:
git clone https://huggingface.co/rozek/LLaMA-2-7B-32K-Instruct_GGUF ./models/LLaMA-2-7B-32K-Instruct_GGUF
3.1 交互模式
通过 llama-cli 运行模型:
llama-cli -m chinese_q4_0.gguf -p "you are a helpful assistant" -cnv -ngl 24
参数说明:
-m: 指定模型文件-cnv: 对话模式-ngl: GPU 层数卸载数量(编译支持 GPU 时有效)
3.2 模型 API 服务
使用 llama-server 启动 OpenAI API 兼容的服务:
./llama-server -m /mnt/workspace/my-llama-13b-q4_0.gguf -ngl 28
默认端口为 8080。可通过 curl 测试:
curl --request POST \
--url http://localhost:8080/completion \
--header "Content-Type: application/json" \
--data '{"prompt": "What color is the sun?", "n_predict": 512}'
也可使用 Python OpenAI SDK 访问:
import openai
client = openai.OpenAI(
base_url="http://127.0.0.1:8080/v1",
api_key="sk-no-key-required"
)
completion = client.chat.completions.create(
model="qwen",
messages=[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"tell me something about michael jordan"}]
)
print(completion.choices[0].message.content)
3.3 第三方 API 服务
使用 llama-cpp-python 提供 API 服务:
pip install llama-cpp-python
pip install sse_starlette starlette_context pydantic_settings
python -m llama_cpp.server --model models/Llama3-q8.gguf
4. 实现类似 ChatGPT 的聊天应用
借助开源项目打造本地聊天应用,推荐基于 Open WebUI 实现。Open WebUI 支持自托管、离线运行,兼容 Ollama 及 OpenAI 接口。
功能特性包括:直观界面、响应式设计、Markdown/LaTeX 支持、RAG 集成、多模态支持等。
使用 Docker 安装:
docker run -d -p 3000:8080 \
--add-host=host.docker.internal:host-gateway \
-v open-webui:/app/backend/data \
--name open-webui \
--restart always \
ghcr.io/open-webui/open-webui:main
浏览器访问 http://localhost:3000/ 注册账号后即可使用。


