如何在 Ubuntu 上安装并使用 llama.cpp
- 安装依赖
sudo apt update && sudo apt upgrade -y && sudo apt install build-essential cmake git libopenblas-dev libcurl4-openssl-dev
- 获取 llama.cpp 的源文件
git clone https://github.com/ggerganov/llama.cpp
- 开始编译
# 进入目录
cd llama.cpp/
mkdir build
cd build
# 带 openblas 加速库进行编译
cmake .. -DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=OpenBLAS
cmake .. -DGGML_CUDA=ON
cmake --build . --config Release -j
- 模型格式转换
# 进入工作目录
cd llama.cpp/build/bin
# 将 huggingface 格式的模型转化为 gguf
python3 convert_hf_to_gguf.py /path/to/src_model --outtype f16 --outfile /path/to/target_model.gguf
注意此处 src_model 不是单个文件,包含模型结构配置、权重配置、分词器配置在内的完整模型目录。target_model.gguf 是单个文件。
量化 如果需要运行更小的模型文件,可以使用 llama.cpp 自带的量化工具。
# 进入工作目录
cd llama.cpp/build/bin
# 将原来的模型量化成 Q3_K_S
./llama-quantize src_model.gguf target_model_Q3_K_S.gguf Q3_K_S
# 可以查看其他可用的量化方案
./llama-quantize --help
如果上述工具运行报错,记得安装好依赖。
# 建议用 conda 做好环境隔离后再安装下列依赖,避免污染系统的基础环境
pip install transformers torch mistral_common sentencepiece -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host https://pypi.tuna.tsinghua.edu.cn
- 运行
直接使用 llama-server。
./llama-server -m model.gguf -c 4096 --host 0.0.0.0
在浏览器上打开下列链接,即可开始对话。
http://localhost:8080

