LLM | llama.cpp 安装使用(支持CPU、Metal及CUDA的单卡/多卡推理)

1. 详细步骤

1.1 安装 cuda 等 nvidia 依赖(非CUDA环境运行可跳过)

# 以 CUDA Toolkit 12.4: Ubuntu-22.04/24.04(x86_64) 为例,注意区分 WSL 和 Ubuntu,详见 https://developer.nvidia.com/cuda-12-4-1-download-archive?target_os=Linux&target_arch=x86_64&Distribution=Ubuntu&target_version=22.04&target_type=runfile_local
wget https://developer.download.nvidia.com/compute/cuda/12.4.1/local_installers/cuda_12.4.1_550.54.15_linux.run
sudo sh cuda_12.4.1_550.54.15_linux.run

注:通过 nvcc -V 来确定 cuda 等依赖是否安装到位,缺少的话根据提示再安装别的依赖,如 sudo apt install nvidia-cuda-toolkit 等

1.2 安装 llama.cpp (C/C++环境)

# 手动下载也可以
git clone https://github.com/ggerganov/llama.cpp

cd llama.cpp

# 没安装 make,通过 brew/apt 安装一下(cmake 也可以,但是没有 make 命令更简洁)
# Metal(MPS)/CPU
make
# CUDA
make GGML_CUDA=1

注:以前的版本好像一直编译挺快的,现在最新的版本CUDA上编译有点慢,多等一会

1.3 安装 llama-cpp (Python 环境)

# 也可以手动安装 torch 之后,再安装剩下的依赖
pip install -r requirements.txt

1.4 转换 HF 模型为 GGUF 文件

本步骤开始都以 Qwen2-7B-Instruct 为例

# 示例: 生成 FP-16 模型
python convert_hf_to_gguf.py /model_path/Qwen/Qwen-2.7B-Instruct/

1.5 GGUF 模型量化

# 示例: Q4_K_M 量化
./llama-quantize /model_path/Qwen/Qwen-2.7B-Instruct/ggml-model-f16.gguf /model_path/Qwen/Qwen-2.7B-Instruct/ggml-model-Q4_K_M.gguf Q4_K_M

1.6 GGUF 模型测试

# Metal(MPS)/CPU
./llama-cli -m /model_path/Qwen/Qwen-2.7B-Instruct/ggml-model-Q4_K_M.gguf -cnv -p "You are a helpful assistant"
# CUDA: 单卡推理
./llama-cli -m /model_path/Qwen/Qwen-2.7B-Instruct/ggml-model-Q4_K_M.gguf -cnv -p "You are a helpful assistant" -ngl 9999
# CUDA: 多卡推理(以双卡为例),-ts等参数含义详见 https://github.com/ggerganov/llama.cpp/blob/master/examples/server/README.md
./llama-cli -m /model_path/Qwen/Qwen-2.7B-Instruct/ggml-model-Q4_K_M.gguf -cnv -p "You are a helpful assistant" -ngl 9999 -ts 1,1

注: ngl可以灵活调整,取 9999 不是常规做法,比大模型实际的 100 以内的 ngl 大很多(不同模型的实际 ngl 也不一样)来确保所有的 ngl 都在 GPU 上运行(当然前提是显存足够)

2. 参考资料

2.1 llama.cpp

2.1.1 GitHub
官方页面

https://github.com/ggerganov/llama.cpp

build

https://github.com/ggerganov/llama.cpp/blob/master/docs/build.md

quantize

https://github.com/ggerganov/llama.cpp/blob/master/examples/quantize/README.md

http server

https://github.com/ggerganov/llama.cpp/blob/master/examples/server/README.md

2.2 NVIDIA DEVELOPER

CUDA Toolkit Archive

https://developer.nvidia.com/cuda-toolkit-archive

CUDA Toolkit 12.4: Ubuntu-22.04/24.04(x86_64)

https://developer.nvidia.com/cuda-12-4-1-download-archive?target_os=Linux&target_arch=x86_64&Distribution=Ubuntu&target_version=22.04&target_type=runfile_local

3. 资源

3.1 llama.cpp

3.1.1 GitHub
Python Bindings for llama.cpp

https://github.com/abetlen/llama-cpp-python

3.2 NVIDIA DEVELOPER

官方页面

https://developer.nvidia.com/

CUDA Toolkit

https://developer.nvidia.com/cuda-downloads

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值