大模型基于llama.cpp量化详解

概述

llama.cpp 是一个高性能的 LLM 推理库,支持在各种硬件(包括 CPU 和 GPU)上运行量化后的大语言模型。本文档详细介绍如何使用 llama.cpp 将 HuggingFace 格式的模型转换为 GGUF 格式,并进行不同程度的量化。

GGUF 格式:GGUF(Georgi Gerganov Universal Format)是 llama.cpp 专门设计的模型文件格式,针对快速加载和保存模型进行了优化,支持单文件部署,包含加载模型所需的所有信息,无需依赖外部文件。

1.安装cmake

CMake 是跨平台的构建工具,用于编译 llama.cpp 项目。

下载地址https://cmake.org/download/

安装建议

  • Windows 用户建议下载 cmake-3.x.x-windows-x86_64.msi 安装包
  • 安装时选择 "Add CMake to the system PATH",以便在命令行中直接使用

验证安装

bash 复制代码
cmake --version



2.安装llama.cpp

```bash
git clone https://github.com/ggerganov/llama.cpp

convert_hf_to_gguf.py:HuggingFace 格式转 GGUF 的脚本

llama-quantize(或 quantize.exe):量化工具

main(或 main.exe):推理主程序

examples/:各种示例程序

3.编译

bash 复制代码
cd llama.cpp

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple

pip install -r requirements/requirements-convert_hf_to_gguf.txt

cmake -G "MinGW Makefiles" -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -B build

cmake --build build --config Release

4.模型转换

将safetensors转换为gguf

bash 复制代码
convert-hf-to-gguf.py D:\\Project\\2026\\llama3-lora-merge --outtype f16 --outfile D:\\Project\\2026\\my_llama3.gguf

参数说明:

D:\Project\2026\llama3-lora-merge:输入模型路径(包含 config.json 和权重文件的目录)

--outtype f16:输出类型,f16 表示半精度浮点数(16-bit),可选 f32(全精度)或 bf16

--outfile:输出 GGUF 文件路径

类型 精度 说明
f32 32-bit 全精度,文件最大,精度最高
f16 16-bit 半精度,平衡选择
bf16 16-bit Brain Float,动态范围更大
q8_0 8-bit 直接量化为 8 位

6.进一步量化

bash 复制代码
D:\Project\2026\test_llama3.cpp\llama.cpp\build\bin\Release
quantize.exe D:\\Project\\2026\\my_llama3.gguf D:\\Project\\2026\\quantized_model.gguf q4_0

llama-quantize可执行文件来对模型进行进一步量化处理。量化可以帮助我们减少模型的大小,但是代价是损失了模型精度,也就是模型回答的能力可能有所下降。权衡以后我们可以选择合适的量化参数,保证模型的最大效益。

量化使用 q 表示存储权重的位数。位数越低,模型越小,速度越快,但精度损失越大。

量化类型 位宽 精度损失 适用场景 典型压缩率
q2_k 2-bit 极低资源环境,实验用途 ~75%
q3_k_s / q3_k_m / q3_k_l 3-bit 中高 资源受限,可接受一定质量损失 ~60%
q4_0 / q4_1 4-bit 最常用,平衡大小与质量 ~50%
q4_k_s / q4_k_m 4-bit 改进的 4-bit,质量更好 ~50%
q5_0 / q5_1 5-bit 较高质量要求 ~40%
q5_k_s / q5_k_m 5-bit 改进的 5-bit ~40%
q6_k 6-bit 很低 接近原始质量 ~35%
q8_0 8-bit 极低 几乎无损,文件较大 ~25%
f16 16-bit 原始转换,未量化 0%

K-quant 说明:

后缀带 _k 的(如 q4_k_m)使用改进的量化算法

混合量化策略:对 attention 层使用更高精度,其他层使用较低精度

_s(small)、_m(medium)、_l(large)表示混合程度

相关推荐
WiSirius1 天前
LLM:基于 AgentScope + Streamlit 的 AI Agent脑暴室
人工智能·深度学习·自然语言处理·大模型·llama
掘金安东尼1 天前
llama.cpp、Ollama、LM Studio:背后是谁在做?为什么会出现?要什么机器才能跑?
llama
海天一色y1 天前
LLaMA-Factory PPO 训练实战:从 SFT 到 RLHF 完整指南
llama
接着奏乐接着舞。1 天前
5分钟本地跑起大模型
人工智能·llama
liuze4082 天前
Ollama安装
llama
小超同学你好2 天前
Transformer 14. DeepSeekMoE 架构解析:与 LLaMA 以及 Transformer 架构对比
语言模型·架构·transformer·llama
小超同学你好2 天前
Transformer 15: DeepSeek-V2 架构解析:MLA + DeepSeekMoE 与主流架构对比
语言模型·架构·transformer·llama
品克缤3 天前
Trading-Analysis:基于“规则+LLM”的行情分析终端(兼谈 Vibe Coding 实战感)
前端·后端·node.js·vue·express·ai编程·llama
seaside20033 天前
llama.cpp 部署qwen3.5 2B 高通芯片安卓实战
llama·qwen3.5·高通soc
JAdroid3 天前
LLM大模型操作比特币
llama