mcpField
G
gguf-quantization

gguf-quantization

github.com/kalarislabs开发9657 次安装3 天前更新
代码仓库

关于 gguf-quantization

面向本地 LLM 部署与推理的 GGUF 量化格式指南,介绍 llama.cpp 的模型转换、量化和运行流程,以及不同位宽和硬件选项。

主要功能

  1. 01HuggingFace 模型转换为 GGUF
  2. 02支持 2–8 位量化选项
  3. 03使用 imatrix 改善低位量化质量
  4. 04在 CPU、Apple Silicon 和 GPU 上推理
  5. 05通过命令行、Python 或服务器模式运行

适用场景

  1. 01将模型压缩以适配消费级硬件
  2. 02为低位量化生成重要性矩阵
  3. 03在本地运行量化模型
  4. 04部署兼容 OpenAI 的推理服务器

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill gguf-quantization

安装后在 Claude Code 中输入/gguf-quantization确认已加载。

附带文件references/advanced-usage.mdreferences/troubleshooting.md

详细介绍

GGUF - llama.cpp 的量化格式

GGUF(GPT-Generated Unified Format)是 llama.cpp 的标准文件格式,可通过灵活的量化选项,在 CPU、Apple Silicon 和 GPU 上高效推理。

何时使用 GGUF

适合使用 GGUF 的场景:

  • 在消费级硬件(笔记本电脑、台式机)上部署
  • 在 Apple Silicon(M1/M2/M3)上使用 Metal 加速运行
  • 需要无需 GPU 的 CPU 推理
  • 需要灵活的量化(Q2_K 至 Q8_0)
  • 使用本地 AI 工具(LM Studio、Ollama、text-generation-webui)

主要优势:

  • 通用硬件支持:支持 CPU、Apple Silicon、NVIDIA 和 AMD
  • 无需 Python 运行时:纯 C/C++ 推理
  • 灵活量化:2-8 位,支持多种方法(K-quants)
  • 生态支持:LM Studio、Ollama、koboldcpp 等
  • imatrix:通过重要性矩阵提升低位量化的质量

可改用以下替代方案:

  • AWQ/GPTQ:在 NVIDIA GPU 上通过校准实现最高精度
  • HQQ:适用于 HuggingFace 的快速免校准量化
  • bitsandbytes:与 transformers 库简单集成
  • TensorRT-LLM:面向生产环境的 NVIDIA 部署,速度最高

快速入门

安装
# Clone llama.cpp
git clone https://github.com/ggml-org/llama.cpp
cd llama.cpp

# Build (CPU)
make

# Build with CUDA (NVIDIA)
make GGML_CUDA=1

# Build with Metal (Apple Silicon)
make GGML_METAL=1

# Install Python bindings (optional)
pip install llama-cpp-python
将模型转换为 GGUF
# Install requirements
pip install -r requirements.txt

# Convert HuggingFace model to GGUF (FP16)
python convert_hf_to_gguf.py ./path/to/model --outfile model-f16.gguf

# Or specify output type
python convert_hf_to_gguf.py ./path/to/model \
    --outfile model-f16.gguf \
    --outtype f16
量化模型
# Basic quantization to Q4_K_M
./llama-quantize model-f16.gguf model-q4_k_m.gguf Q4_K_M

# Quantize with importance matrix (better quality)
./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
运行推理
# CLI inference
./llama-cli -m model-q4_k_m.gguf -p "Hello, how are you?"

# Interactive mode
./llama-cli -m model-q4_k_m.gguf --interactive

# With GPU offload
./llama-cli -m model-q4_k_m.gguf -ngl 35 -p "Hello!"

量化类型

K-quant 方法(推荐)
类型位数大小(7B)质量使用场景
Q2_K2.5~2.8 GB低极限压缩
Q3_K_S3.0~3.0 GB低-中内存受限
Q3_K_M3.3~3.3 GB中平衡
Q4_K_S4.0~3.8 GB中-高良好平衡
Q4_K_M4.5~4.1 GB高推荐默认选项
Q5_K_S5.0~4.6 GB高注重质量
Q5_K_M5.5~4.8 GB很高高质量
Q6_K6.0~5.5 GB极佳接近原始质量
Q8_08.0~7.2 GB最佳最高质量
传统方法
类型描述
Q4_04 位,基础
Q4_14 位,带增量
Q5_05 位,基础
Q5_15 位,带增量

建议:使用 K-quant 方法(Q4_K_M、Q5_K_M),以获得最佳质量/大小比。

转换工作流

工作流 1:HuggingFace 转 GGUF
# 1. Download model
huggingface-cli download meta-llama/Llama-3.1-8B --local-dir ./llama-3.1-8b

# 2. Convert to GGUF (FP16)
python convert_hf_to_gguf.py ./llama-3.1-8b \
    --outfile llama-3.1-8b-f16.gguf \
    --outtype f16

# 3. Quantize
./llama-quantize llama-3.1-8b-f16.gguf llama-3.1-8b-q4_k_m.gguf Q4_K_M

# 4. Test
./llama-cli -m llama-3.1-8b-q4_k_m.gguf -p "Hello!" -n 50
工作流 2:使用重要性矩阵(质量更好)
# 1. Convert to GGUF
python convert_hf_to_gguf.py ./model --outfile model-f16.gguf

# 2. Create calibration text (diverse samples)
cat > calibration.txt << 'EOF'
The quick brown fox jumps over the lazy dog.
Machine learning is a subset of artificial intelligence.
Python is a popular programming language.
# Add more diverse text samples...
EOF

# 3. Generate importance matrix
./llama-imatrix -m model-f16.gguf \
    -f calibration.txt \
    --chunk 512 \
    -o model.imatrix \
    -ngl 35  # GPU layers if available

# 4. Quantize with imatrix
./llama-quantize --imatrix model.imatrix \
    model-f16.gguf \
    model-q4_k_m.gguf \
    Q4_K_M
工作流 3:多种量化
#!/bin/bash
MODEL="llama-3.1-8b-f16.gguf"
IMATRIX="llama-3.1-8b.imatrix"

# Generate imatrix once
./llama-imatrix -m $MODEL -f wiki.txt -o $IMATRIX -ngl 35

# Create multiple quantizations
for QUANT in Q4_K_M Q5_K_M Q6_K Q8_0; do
    OUTPUT="llama-3.1-8b-${QUANT,,}.gguf"
    ./llama-quantize --imatrix $IMATRIX $MODEL $OUTPUT $QUANT
    echo "Created: $OUTPUT ($(du -h $OUTPUT | cut -f1))"
done

Python 用法

llama-cpp-python
from llama_cpp import Llama

# Load model
llm = Llama(
    model_path="./model-q4_k_m.gguf",
    n_ctx=4096,          # Context window
    n_gpu_layers=35,     # GPU offload (0 for CPU only)
    n_threads=8          # CPU threads
)

# Generate
output = llm(
    "What is machine learning?",
    max_tokens=256,
    temperature=0.7,
    stop=["</s>", "\n\n"]
)
print(output["choices"][0]["text"])
聊天补全
from llama_cpp import Llama

llm = Llama(
    model_path="./model-q4_k_m.gguf",
    n_ctx=4096,
    n_gpu_layers=35,
    chat_format="llama-3"  # Or "chatml", "mistral", etc.
)

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is Python?"}
]

response = llm.create_chat_completion(
    messages=messages,
    max_tokens=256,
    temperature=0.7
)
print(response["choices"][0]["message"]["content"])
流式传输
from llama_cpp import Llama

llm = Llama(model_path="./model-q4_k_m.gguf", n_gpu_layers=35)

# Stream tokens
for chunk in llm(
    "Explain quantum computing:",
    max_tokens=256,
    stream=True
):
    print(chunk["choices"][0]["text"], end="", flush=True)

服务端模式

启动 OpenAI 兼容服务
# Start server
./llama-server -m model-q4_k_m.gguf \
    --host 0.0.0.0 \
    --port 8080 \
    -ngl 35 \
    -c 4096

# Or with Python bindings
python -m llama_cpp.server \
    --model model-q4_k_m.gguf \
    --n_gpu_layers 35 \
    --host 0.0.0.0 \
    --port 8080
与 OpenAI 客户端搭配使用
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="not-needed"
)

response = client.chat.completions.create(
    model="local-model",
    messages=[{"role": "user", "content": "Hello!"}],
    max_tokens=256
)
print(response.choices[0].message.content)

硬件优化

Apple Silicon(Metal)
# Build with Metal
make clean && make GGML_METAL=1

# Run with Metal acceleration
./llama-cli -m model.gguf -ngl 99 -p "Hello"

# Python with Metal
llm = Llama(
    model_path="model.gguf",
    n_gpu_layers=99,     # Offload all layers
    n_threads=1          # Metal handles parallelism
)
NVIDIA CUDA
# Build with CUDA
make clean && make GGML_CUDA=1

# Run with CUDA
./llama-cli -m model.gguf -ngl 35 -p "Hello"

# Specify GPU
CUDA_VISIBLE_DEVICES=0 ./llama-cli -m model.gguf -ngl 35
CPU 优化
# Build with AVX2/AVX512
make clean && make

# Run with optimal threads
./llama-cli -m model.gguf -t 8 -p "Hello"

# Python CPU config
llm = Llama(
    model_path="model.gguf",
    n_gpu_layers=0,      # CPU only
    n_threads=8,         # Match physical cores
    n_batch=512          # Batch size for prompt processing
)

与工具集成

Ollama
# Create Modelfile
cat > Modelfile << 'EOF'
FROM ./model-q4_k_m.gguf
TEMPLATE """{{ .System }}
{{ .Prompt }}"""
PARAMETER temperature 0.7
PARAMETER num_ctx 4096
EOF

# Create Ollama model
ollama create mymodel -f Modelfile

# Run
ollama run mymodel "Hello!"
LM Studio
  1. 将 GGUF 文件放入 ~/.cache/lm-studio/models/
  2. 打开 LM Studio 并选择模型
  3. 配置上下文长度和 GPU 卸载
  4. 开始推理
text-generation-webui
# Place in models folder
cp model-q4_k_m.gguf text-generation-webui/models/

# Start with llama.cpp loader
python server.py --model model-q4_k_m.gguf --loader llama.cpp --n-gpu-layers 35

最佳实践

  1. 使用 K-quants:Q4_K_M 在质量和大小之间达到最佳平衡
  2. 使用 imatrix:对于 Q4 及更低位量化,始终使用重要性矩阵
  3. GPU 卸载:尽可能卸载更多层,直到达到 VRAM 容量上限
  4. 上下文长度:从 4096 开始,按需增加
  5. 线程数:与 CPU 物理核心数相同,而非逻辑核心数
  6. 批次大小:增大 n_batch,以加快提示词处理速度

常见问题

模型加载缓慢:

# Use mmap for faster loading
./llama-cli -m model.gguf --mmap

内存不足:

# Reduce GPU layers
./llama-cli -m model.gguf -ngl 20  # Reduce from 35

# Or use smaller quantization
./llama-quantize model-f16.gguf model-q3_k_m.gguf Q3_K_M

低位量化时质量不佳:

# Always use imatrix for Q4 and below
./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

参考资料

资源

Agent 操作流程

  1. 检查环境。 检查 GPU 类型、内存、驱动/CUDA 版本(nvidia-smi)、框架版本,以及数据集的位置和大小。
  2. 明确输入。 根据数据或用户确认格式、标识符和参数。任何会影响结果的值都应询问确认,而非猜测。
  3. 先运行小规模版本。 进行冒烟测试:使用小型模型或子集、少量步骤,并确认损失下降且检查点成功保存。
  4. 按照上述说明和参考资料执行完整任务。
  5. 验证结果。 在留出数据上跟踪指标,与基线比较,并记录随机种子、配置和硬件。
  6. 报告结果。 说明运行了什么(版本、命令、参数)、检查了什么,以及还有哪些不确定之处。
如果出现这种情况请执行以下操作
CUDA 显存不足减小批次大小,启用梯度累积、梯度检查点或混合精度,或者对模型进行分片。
损失为 NaN 或发散降低学习率,检查数据中是否存在无效值,并启用梯度裁剪。
已安装版本中缺少这些说明提到的函数、标志或端点查看已安装版本自身的文档(help()、--help、官方文档),调整操作,并告知用户。切勿编造 API。
所需输入、标识符或参数含义不明确询问用户,或在运行前明确说明所采用的假设。

诚信准则

  • 切勿捏造结果、参数、标识符、引用或统计数据。如果无法运行或验证某项内容,请如实说明。
  • 没有日志时,切勿声称取得了训练结果;启动大型作业前,应先估算计算成本。
  • 请将此处与特定版本相关的细节视为可能已过时,并根据已安装版本的官方文档进行确认。
  • 对于需要付费、占用共享 GPU 或云配额、涉及个人或患者数据,或无法撤销的操作,执行前必须征得同意。

相关技能

  • llama-cpp:无需 NVIDIA 硬件,即可在 CPU、Apple Silicon 和消费级 GPU 上运行 LLM 推理。
  • hqq-quantization:无需校准数据的 LLM 半二次量化。
  • awq-quantization:用于 4 位 LLM 压缩的激活感知权重量化,可提速 3 倍且精度损失极小。

评论

支持 Markdown