1. 大模型部署工具 llama.cpp
大模型的研究分为训练和推理两个部分。训练的过程,实际上就是在寻找模型参数,使得模型的损失函数最小化,推理结果最优化的过程。训练完成之后,模型的参数就固定了,这时候就可以使用模型进行推理,对外提供服务。
llama.cpp(https://github.com/ggerganov/llama.cpp)主要解决的是推理过程中的性能问题。主要有两点优化:
- llama.cpp 使用的是 C 语言写的机器学习张量库 ggml。
- llama.cpp 提供了模型量化的工具。
计算类 Python 库的优化手段之一就是使用 C 重新实现,这部分的性能提升非常明显。另外一个是量化,量化是通过牺牲模型参数的精度,来换取模型的推理速度。llama.cpp 提供了大模型量化的工具,可以将模型参数从 32 位浮点数转换为 16 位浮点数,甚至是 8、4 位整数。
除此之外,llama.cpp 还提供了服务化组件,可以直接对外提供模型的 API。
2. 使用 llama.cpp 量化模型
2.1 下载编译 llama.cpp
克隆代码,编译 llama.cpp:
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
make
在目录下会生成一系列可执行文件:
main:使用模型进行推理quantize:量化模型server:提供模型 API 服务
2.2 准备 llama.cpp 支持的模型
llama.cpp 支持转换的模型格式有 PyTorch 的 .pth、HuggingFace 的 .safetensors,以及之前 llama.cpp 采用的 ggmlv3。
在 HuggingFace 上找到合适格式的模型,下载至 llama.cpp 的 models 目录下:
git clone https://huggingface.co/4bit/Llama-2-7b-chat-hf ./models/Llama-2-7b-chat-hf
2.3 转换为 GGUF 格式
- 安装依赖
llama.cpp 项目下带有 requirements.txt 文件,直接安装依赖即可:
pip install -r requirements.txt
- 转换模型
python convert.py ./models/Llama-2-7b-chat-hf --vocabtype spm
输出示例:
params = Params(n_vocab=32000, n_embd=4096, n_mult=5504, n_layer=32, n_ctx=2048, n_ff=11008, n_head=32, n_head_kv=32, f_norm_eps=1e-05, f_rope_freq_base=None, f_rope_scale=None, ftype=None, path_model=PosixPath('models/Llama-2-7b-chat-hf'))
Loading vocab file 'models/Llama-2-7b-chat-hf/tokenizer.model', type 'spm'
...
Wrote models/Llama-2-7b-chat-hf/ggml-model-f16.gguf
vocabtype 指定分词算法,默认值是 spm,如果是 bpe,需要显式指定。
2.4 开始量化模型
quantize 提供各种精度的量化。用法如下:
./quantize
usage: ./quantize [--help] [--allow-requantize] [--leave-output-tensor] model-f32.gguf [model-quant.gguf] type [nthreads]
--allow-requantize: Allows requantizing tensors that have already been quantized. Warning: This can severely reduce quality compared to quantizing from 16bit or 32bit
--leave-output-tensor: Will leave output.weight un(re)quantized. Increases model size but may also increase quality, especially when requantizing
Allowed quantization types:
2 or Q4_0 : 3.56G, +0.2166 ppl @ LLaMA-v1-7B
3 or Q4_1 : 3.90G, +0.1585 ppl @ LLaMA-v1-7B
...
7 or Q8_0 : 6.70G, +0.0004 ppl @ LLaMA-v1-7B
1 or F16 : 13.00G @ 7B
0 or F32 : 26.00G @ 7B
执行量化命令:
./quantize ./models/Llama-2-7b-chat-hf/ggml-model-f16.gguf ./models/Llama-2-7b-chat-hf/ggml-model-q4_0.gguf Q4_0
输出日志:
llama_model_quantize_internal: model size = 12853.02 MB
llama_model_quantize_internal: quant size = 3647.87 MB
llama_model_quantize_internal: hist: 0.036 0.015 0.025 0.039 0.056 0.076 0.096 0.112 0.118 0.112 0.096 0.077 0.056 0.039 0.025 0.021
量化之后,模型的大小从 13G 降低到 3.6G,但模型精度从 16 位浮点数降低到 4 位整数。
3. 模型推理与服务
完成量化后,可以使用生成的 GGUF 模型进行推理或启动服务。
3.1 本地推理
使用 main 程序加载模型进行对话:
./main -m ./models/Llama-2-7b-chat-hf/ggml-model-q4_0.gguf -p "Hello, how are you?" -n 128
3.2 启动 API 服务
llama.cpp 内置了 HTTP 服务器,可以方便地集成到其他应用中:
./server -m ./models/Llama-2-7b-chat-hf/ggml-model-q4_0.gguf -c 2048 --port 8080
服务启动后,可通过 POST 请求向 /completion 接口发送文本以获取推理结果。


