gguf-quantization について
gguf-quantizationは、llama.cppで推論するためのモデル変換とGGUF量子化を扱うスキルガイドです。量子化方式、重要度行列、CPU・Apple Silicon・GPUでの実行方法を説明します。
主な機能
- 01HuggingFaceモデルからGGUFへの変換
- 022~8ビットの量子化方式
- 03重要度行列によるキャリブレーション
- 04CPU・GPU推論の手引き
- 05CLI・Python・サーバーの手順
活用シーン
- 01ローカル推論向けのモデル圧縮
- 02メモリ制約に応じた量子化方式の選択
- 03llama.cppによるGGUFモデルの提供
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ orchestra-research/ ai-research-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 を使用する場合:
- コンシューマー向けハードウェア(ノートパソコン、デスクトップ)にデプロイする場合
- Metal アクセラレーションを使用して Apple Silicon(M1/M2/M3)上で実行する場合
- GPU を必要とせず CPU で推論する必要がある場合
- 柔軟な量子化(Q2_K から Q8_0)を利用したい場合
- ローカル AI ツール(LM Studio、Ollama、text-generation-webui)を使用する場合
主な利点:
- 汎用的なハードウェア対応: CPU、Apple Silicon、NVIDIA、AMD をサポート
- Python ランタイム不要: 純粋な C/C++ による推論
- 柔軟な量子化: 各種手法(K-quants)による 2〜8 ビット
- エコシステムのサポート: 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_K | 2.5 | ~2.8 GB | 低 | 極端な圧縮 |
| Q3_K_S | 3.0 | ~3.0 GB | 低〜中 | メモリ制約がある場合 |
| Q3_K_M | 3.3 | ~3.3 GB | 中 | バランス型 |
| Q4_K_S | 4.0 | ~3.8 GB | 中〜高 | 良好なバランス |
| Q4_K_M | 4.5 | ~4.1 GB | 高 | 推奨デフォルト |
| Q5_K_S | 5.0 | ~4.6 GB | 高 | 品質重視 |
| Q5_K_M | 5.5 | ~4.8 GB | 非常に高い | 高品質 |
| Q6_K | 6.0 | ~5.5 GB | 優秀 | 原本に近い品質 |
| Q8_0 | 8.0 | ~7.2 GB | 最高 | 最大品質 |
レガシー手法
| タイプ | 説明 |
|---|---|
| Q4_0 | 4 ビット、基本 |
| Q4_1 | デルタ付き 4 ビット |
| Q5_0 | 5 ビット、基本 |
| Q5_1 | デルタ付き 5 ビット |
推奨事項: 最良の品質とサイズの比率を得るには、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
- GGUF ファイルを
~/.cache/lm-studio/models/に配置します - LM Studio を開き、モデルを選択します
- コンテキスト長と GPU オフロードを設定します
- 推論を開始します
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
ベストプラクティス
- K-quants を使用する: Q4_K_M が最良の品質とサイズのバランスを提供します
- imatrix を使用する: Q4 以下では常に重要度行列を使用してください
- GPU オフロード: VRAM が許す限り多くのレイヤーをオフロードしてください
- コンテキスト長: 4096 から始め、必要に応じて増やしてください
- スレッド数: 論理コア数ではなく、物理 CPU コア数に合わせてください
- バッチサイズ: プロンプト処理を高速化するために 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
参考資料
- Advanced Usage - バッチ処理、投機的デコーディング、カスタムビルド
- Troubleshooting - よくある問題、デバッグ、ベンチマーク
リソース
- リポジトリ: https://github.com/ggml-org/llama.cpp
- Python バインディング: https://github.com/abetlen/llama-cpp-python
- 量子化済みモデル: https://huggingface.co/TheBloke
- GGUF 変換ツール: https://huggingface.co/spaces/ggml-org/gguf-my-repo
- ライセンス: MIT
コメント
Markdown 対応