[ PROMPT_NODE_22814 ]
gguf-quantization
[ SKILL_DOCUMENTATION ]
# GGUF - llama.cpp 的量化格式
GGUF (GPT-Generated Unified Format) 是 llama.cpp 的标准文件格式,支持在 CPU、Apple Silicon 和 GPU 上进行高效推理,并提供灵活的量化选项。
## 何时使用 GGUF
**在以下情况使用 GGUF:**
- 在消费级硬件(笔记本、台式机)上部署
- 在 Apple Silicon (M1/M2/M3) 上使用 Metal 加速运行
- 需要 CPU 推理且没有 GPU 要求
- 需要灵活的量化(Q2_K 到 Q8_0)
- 使用本地 AI 工具(LM Studio, Ollama, text-generation-webui)
**主要优势:**
- **通用硬件支持**:支持 CPU、Apple Silicon、NVIDIA、AMD
- **无需 Python 运行时**:纯 C/C++ 推理
- **灵活的量化**:2-8 bit,包含多种方法(K-quants)
- **生态支持**:LM Studio, Ollama, koboldcpp 等
- **imatrix**:重要性矩阵(Importance matrix),提升低比特下的质量
**建议使用替代方案:**
- **AWQ/GPTQ**:在 NVIDIA GPU 上通过校准获得最高精度
- **HQQ**:针对 HuggingFace 的快速免校准量化
- **bitsandbytes**:与 transformers 库的简单集成
- **TensorRT-LLM**:生产环境 NVIDIA 部署,追求极致速度
## 快速开始
### 安装
bash
# 克隆 llama.cpp
git clone https://github.com/ggml-org/llama.cpp
cd llama.cpp
# 构建 (CPU)
make
# 使用 CUDA 构建 (NVIDIA)
make GGML_CUDA=1
# 使用 Metal 构建 (Apple Silicon)
make GGML_METAL=1
# 安装 Python 绑定 (可选)
pip install llama-cpp-python
### 将模型转换为 GGUF
bash
# 安装依赖
pip install -r requirements.txt
# 将 HuggingFace 模型转换为 GGUF (FP16)
python convert_hf_to_gguf.py ./path/to/model --outfile model-f16.gguf
# 或指定输出类型
python convert_hf_to_gguf.py ./path/to/model
--outfile model-f16.gguf
--outtype f16
### 量化模型
bash
# 基础量化至 Q4_K_M
./llama-quantize model-f16.gguf model-q4_k_m.gguf Q4_K_M
# 使用重要性矩阵进行量化 (质量更好)
./llama-imatrix -m model-f16.gguf -f calibration.txt -o model.imatrix
./llama-quantize --imatrix model.imatrix model-f16.gguf model-q4_k_m.gguf Q4_K_M
### 运行推理
bash
# CLI 推理
./llama-cli -m model-q4_k_m.gguf -p "Hello, how are you?"
# 交互模式
./llama-cli -m model-q4_k_m.gguf --interactive
# 使用 GPU 卸载
./llama-cli -m model-q4_k_m.gguf -ngl 35 -p "Hello!"
## 量化类型
### K-quant 方法 (推荐)
| 类型 | 位数 | 大小 (7B) | 质量 | 使用场景 |
|------|------|----------