関連する技術記事・ガイドを検索
量子化(Quantization)は、ニューラルネットワークの重みや活性化を、通常の32ビット浮動小数点から8ビットや4ビット整数などの低精度形式に変換することで、モデルサイズと計算量を大幅に削減する最適化技術です。
| 精度 | ビット数 | モデルサイズ | 精度低下 | |------|---------|-------------|---------| | FP32 | 32 | 100%(基準) | 0% | | FP16 | 16 | 50% | 0-1% | | INT8 | 8 | 25% | 1-3% | | INT4 | 4 | 12.5% | 3-10% | | 2bit | 2 | 6.25% | 10-20% |
動的量子化:
- 推論時に量子化
- 精度維持しやすい
- 速度向上は限定的
静的量子化:
- 事前に量子化
- 高速
- キャリブレーション必要
量子化認識訓練(QAT):
- 訓練時から量子化考慮
- 最高精度
- 時間がかかる
import torch
import torch.quantization as quantization
# 1. 動的量子化(最も簡単)
model_int8 = torch.quantization.quantize_dynamic(
model,
{torch.nn.Linear}, # 量子化する層
dtype=torch.qint8
)
# 2. 静的量子化
model.qconfig = torch.quantization.get_default_qconfig('fbgemm')
model_prepared = torch.quantization.prepare(model)
# キャリブレーション
for batch in calibration_data:
model_prepared(batch)
# 量子化実行
model_int8 = torch.quantization.convert(model_prepared)
from onnxruntime.quantization import quantize_dynamic
# モデルをONNXに変換後
quantize_dynamic(
model_input='model.onnx',
model_output='model_int8.onnx',
weight_type=QuantType.QInt8
)
# 4ビット量子化の例
from auto_gptq import AutoGPTQForCausalLM
model = AutoGPTQForCausalLM.from_quantized(
"TheBloke/Llama-2-7B-GPTQ",
device="cuda:0",
use_triton=True,
quantize_config={"bits": 4}
)
# メモリ使用量
# FP16: 14GB → INT4: 3.5GB
import bitsandbytes as bnb
# 8ビット量子化
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-2-7b-hf",
load_in_8bit=True,
device_map="auto"
)
# 4ビット量子化(QLoRA用)
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.float16
)
Llama 2 7Bモデル(RTX 4090):
FP16: 50 tokens/秒
INT8: 80 tokens/秒(1.6倍)
INT4: 120 tokens/秒(2.4倍)
メモリ帯域削減が主な要因
| モデル | タスク | FP32 | INT8 | INT4 | |--------|--------|------|------|------| | BERT | 分類 | 92.5% | 92.1% | 91.0% | | GPT-2 | 生成 | 30.2 PPL | 30.8 PPL | 32.5 PPL | | ResNet | 画像認識 | 94.0% | 93.8% | 92.5% |
# 層ごとに異なる精度
quantization_config = {
'attention': 8, # 重要な層は高精度
'feedforward': 4, # 大きい層は積極的に圧縮
'embeddings': 16 # 埋め込みは維持
}
通常: 全重みで1つのスケール
グループ: 128個ごとにスケール
利点:
- 精度向上
- 柔軟性
- ハードウェア対応良好
NVIDIA:
- Tensor Core INT8: Turing以降
- INT4: Ada Lovelace以降
AMD:
- Matrix Core INT8: RDNA 3
- 限定的なINT4対応
Intel:
- XMX INT8: Arc/Xe
- VNNI: CPU側も対応
スマートフォンでのLLM:
Original: 14GB(動作不可)
INT4量子化: 3.5GB(快適動作)
Raspberry Piでの画像認識:
FP32: 5 FPS
INT8: 20 FPS
推論サーバー比較(1000リクエスト/秒):
FP32: 8×A100必要($16/時間)
INT8: 2×A100で可能($4/時間)
コスト削減: 75%
| 用途 | 推奨精度 | 理由 | |------|---------|------| | 研究開発 | FP32/FP16 | 精度優先 | | 本番推論 | INT8 | バランス | | エッジ展開 | INT4 | サイズ優先 | | 実験的 | 2-3bit | 極限圧縮 |
# 量子化前後の比較
def evaluate_quantization(original_model, quantized_model, test_data):
original_outputs = []
quantized_outputs = []
for batch in test_data:
with torch.no_grad():
original_outputs.append(original_model(batch))
quantized_outputs.append(quantized_model(batch))
# 出力の差分を計算
mse = calculate_mse(original_outputs, quantized_outputs)
return mse
量子化は、AIモデルの実用的な展開において不可欠な技術となっています。適切に適用することで、精度をほぼ維持したまま、大幅なリソース削減を実現できます。