llama.cpp
介绍
部署
介绍
大模型的研究分为训练和推理两个部分:
- 训练的过程,实际上就是在寻找模型参数,使得模型的损失函数最小化;
- 推理结果最优化的过程;
训练完成之后,模型的参数就固定了,这时候就可以使用模型进行推理,对外提供服务。
llama.cpp 主要解决的是推理过程中的性能问题。主要有两点优化:
- llama.cpp 使用的是 C 语言写的机器学习张量库 ggml
- llama.cpp 提供了模型量化的工具
计算类 Python 库的优化手段之一就是使用 C 重新实现,这部分的性能提升非常明显。另外一个是量化,量化是通过牺牲模型参数的精度,来换取模型的推理速度。llama.cpp 提供了大模型量化的工具,可以将模型参数从 32 位浮点数转换为 16 位浮点数,甚至是 8、4 位整数。
除此之外,llama.cpp 还提供了服务化组件,可以直接对外提供模型的 API 。
使用量化模型
下载编译 llama.cpp
git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
make
在目录下会生成一系列可执行文件
- main:使用模型进行推理
- quantize:量化模型
- server:提供模型 API 服务
- …
准备 llama.cpp 支持的模型
llama.cpp 支持转换的模型格式有 PyTorch 的 .pth 、huggingface 的 .safetensors 、还有之前 llamma.cpp 采用的 ggmlv3。
在 huggingface 上找到合适格式的模型,下载至 llama.cpp 的 models 目录下。
git clone https://huggingface.co/4bit/Llama-2-7b-chat-hf ./models/Llama-2-7b-chat-hf
格式转化
- 依赖
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,需要显示指定。
量化模型
- 使用 quantize 量化模型
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
8 or Q5_0 : 4.33G, +0.0683 ppl @ LLaMA-v1-7B
9 or Q5_1 : 4.70G, +0.0349 ppl @ LLaMA-v1-7B
10 or Q2_K : 2.63G, +0.6717 ppl @ LLaMA-v1-7B
12 or Q3_K : alias for Q3_K_M
11 or Q3_K_S : 2