gguf-quantization について
ローカル LLM を展開する人向けに、llama.cpp での GGUF 変換、量子化、推論方法を解説するガイドです。量子化形式やハードウェア別の実行方法も扱います。
主な機能
- 01HuggingFace モデルを GGUF に変換
- 022~8ビットの量子化方式を選択
- 03imatrix で低ビット量子化の品質を改善
- 04CPU、Apple Silicon、GPU で推論
- 05CLI、Python、サーバーモードで実行
活用シーン
- 01コンシューマー向けハードウェアに合わせてモデルを圧縮
- 02低ビット量子化用の重要度行列を作成
- 03量子化モデルをローカルで実行
- 04OpenAI 互換の推論サーバーを展開
インストール
コマンドをコピーしてターミナルで実行します。
$
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 を使用する場面:
- コンシューマー向けハードウェア(ノートパソコン、デスクトップ)にデプロイする場合
- 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-quant)による 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-quant を使用する: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
参考資料
- 高度な使用方法 - バッチ処理、投機的デコーディング、カスタムビルド
- トラブルシューティング - よくある問題、デバッグ、ベンチマーク
リソース
- リポジトリ: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
エージェントの作業手順
- 環境を確認します。 GPU の種類、メモリ、ドライバー/CUDA のバージョン(
nvidia-smi)、フレームワークのバージョン、データセットの場所とサイズを確認します。 - 入力を確定します。 データまたはユーザーから、形式、識別子、パラメーターを確認します。結果を左右する値は推測せず、質問してください。
- まず小規模なバージョンを実行します。 スモークテストとして、小さなモデルまたはサブセットを使い、少ないステップ数で実行して、損失が減少し、チェックポイントが保存されることを確認します。
- 上記の手順と参考資料に従って、タスク全体を実行します。
- 結果を検証します。 ホールドアウトデータでメトリクスを追跡し、ベースラインと比較して、シード、設定、ハードウェアを記録します。
- 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、未確認の点を明記します。
| このような場合 | 次のように対応します |
|---|---|
| CUDA のメモリ不足 | バッチサイズを小さくする、勾配累積/チェックポイント保存または混合精度を有効にする、あるいはモデルをシャーディングします。 |
| 損失が NaN になる、または発散する | 学習率を下げ、データに無効な値がないか確認し、勾配クリッピングを有効にします。 |
| この手順に記載された関数、フラグ、エンドポイントがインストール済みのバージョンにない | インストール済みバージョンの公式ドキュメント(help()、--help、公式ドキュメント)を確認し、適宜対応してユーザーに伝えます。API を捏造してはいけません。 |
| 必須の入力、識別子、パラメーターが曖昧 | ユーザーに質問するか、実行前に仮定を明示します。 |
誠実性に関するルール
- 結果、パラメーター、識別子、引用、統計情報を決して捏造しないでください。実行または検証できないことは、明確に伝えます。
- ログがない状態で学習結果を主張してはいけません。大規模なジョブを開始する前に、計算コストを見積もります。
- ここに記載されたバージョン固有の情報は古い可能性があるものとして扱い、インストール済みバージョンの公式ドキュメントで確認します。
- 費用が発生する、共有 GPU またはクラウドクォータを消費する、個人データまたは患者データに触れる、あるいは取り消せない操作を行う場合は、事前に確認を取ります。
関連スキル
llama-cpp:NVIDIA ハードウェアなしで、CPU、Apple Silicon、一般向け GPU 上で LLM 推論を実行します。hqq-quantization:キャリブレーションデータを必要としない、LLM 向けの半二次量子化です。awq-quantization:速度を 3 倍にし、精度の低下を最小限に抑えながら LLM を圧縮する、アクティベーション対応の 4 ビット重み量子化です。
コメント
Markdown 対応