| name | quantization-optimization |
| description | Guide complet de la quantification et optimisation de modèles — GPTQ, AWQ, GGUF, bitsandbytes, QAT, SmoothQuant, FP8, distillation, pruning. En français. |
Quantification & Optimisation de Modèles — Guide Complet
Réduire la mémoire, accélérer l'inférence, déployer sur plus de matériel.
1. Pourquoi Quantifier ?
Trade-off Quantification
Précision (FP32) ───────────────────────────────────────────── Efficacité
┌────────┬────────┬────────┬────────┬────────┐
FP32 FP16 INT8 INT4 INT2 NF4
Haute Basse
précision latence
Lente Rapide
Beaucoup Peu
VRAM VRAM
2. Types de Quantification
Symétrique vs Asymétrique
Per-Tensor vs Per-Channel vs Per-Group
3. GPTQ (Frantar et al., 2023)
def gptq_quantize(W, H, bits=4, group_size=128):
"""
W: matrice de poids (in_feat, out_feat)
H: matrice Hessian (in_feat, in_feat) — info de Fisher
Quantifie W en bits bits avec compensation d'erreur.
"""
W_quant = W.clone().float()
H_diag = torch.diag(H)
importance = torch.argsort(H_diag, descending=True)
for idx in importance:
w = W_quant[idx, :]
q = quantize_weight(w, bits)
err = w - dequantize_weight(q, bits)
if len(remaining) > 0:
W_quant[remaining, :] -= err * H[idx, remaining] / H[idx, idx]
return W_quant
from auto_gptq import AutoGPTQForCausalLM
model = AutoGPTQForCausalLM.from_quantized(
"TheBloke/Llama-2-7B-GPTQ",
model_basename="gptq_model-4bit-128g",
use_triton=True,
device_map="auto",
)
4. AWQ (Lin et al., 2024)
class AWQ:
"""Activation-Aware Weight Quantization.
Étapes :
1. Analyser les activations sur un petit dataset
2. Identifier les channels saillants
3. Appliquer un scaling protecteur aux poids importants
4. Quantifier en INT4 (standard)
"""
@staticmethod
def compute_scales(model, calibration_data, alpha=0.5):
"""Calcule les scales de protection AWQ."""
pass
@staticmethod
def apply_scale(model, scales):
"""Applique le scaling aux poids."""
pass
from awq import AutoAWQForCausalLM
model = AutoAWQForCausalLM.from_pretrained(
"meta-llama/Llama-2-7B-hf",
)
model.quantize(
tokenizer,
quant_config={"zero_point": True, "q_group_size": 128,
"w_bit": 4, "version": "GEMM"},
)
5. BitsAndBytes (4-bit QLoRA)
from transformers import BitsAndBytesConfig
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3-8B",
quantization_config=bnb_config,
device_map="auto",
)
NF4 — NormalFloat4
6. GGUF / llama.cpp
K-Quant (llama.cpp)
7. SmoothQuant (Xiao et al., 2023)
def smooth_quant(model, calibration_data, alpha=0.5):
"""SmoothQuant : quantification INT8 des activations.
Principe mathématique :
Y = X · W = (X / s) · (s · W)
où s_j = max(|X_j|)^alpha / max(|W_j|)^(1-alpha)
s transfère la variance de X vers W.
X/s est plus lisse → quantifiable en INT8
s·W est plus rugueux → mais poids en FP16
"""
pass
8. FP8 Training (H100 native)
import transformer_engine.pytorch as te
linear = te.Linear(4096, 4096, dtype=torch.float8)
9. QAT — Quantization-Aware Training
class QATLinear(nn.Module):
"""Linear avec quantification simulée (Fake Quant)."""
def __init__(self, in_features, out_features, n_bits=8):
super().__init__()
self.weight = nn.Parameter(torch.randn(out_features, in_features))
self.n_bits = n_bits
def fake_quantize(self, x):
"""Simule la quantification pendant l'entraînement.
Pendant forward : quantise et déquantise (arrondi)
Pendant backward : arrondi ignoré (STE — Straight-Through Estimator)
"""
scale = x.abs().max() / (2**(self.n_bits - 1) - 1)
x_q = torch.round(x / scale)
x_deq = x_q * scale
return x + (x_deq - x).detach()
def forward(self, x):
w_q = self.fake_quantize(self.weight)
return F.linear(x, w_q)
10. Pruning (Élagage)
class SparseGPT:
"""SparseGPT : pruning structuré sans fine-tuning.
Principe : un peu comme GPTQ mais met à zéro les poids
au lieu de les quantifier.
- 50% sparse : aucune perte de perplexité
- 60% sparse : légère perte
- 2:4 sparsity : support hardware natif (NVIDIA Ampere+)
"""
pass
11. Distillation comme Optimisation
12. Tableau Récapitulatif
| Méthode | Bits | VRAM (7B) | VRAM (70B) | Qualité | Calibration |
|---|
| FP16 | 16 | 14 Go | 140 Go | ★★★★★ | - |
| INT8 (bitsandbytes) | 8 | 7 Go | 70 Go | ★★★★☆ | - |
| INT8 (SmoothQuant) | 8 | 7 Go | 70 Go | ★★★★★ | 100 samples |
| GPTQ 4-bit | 4 | 4 Go | 35 Go | ★★★★☆ | 128 samples |
| AWQ 4-bit | 4 | 4 Go | 35 Go | ★★★★★ | 128 samples |
| NF4 (QLoRA) | 4 | 5.5 Go | 55 Go | ★★★★☆ | - |
| GGUF Q4_K_M | 4 | 4.5 Go | 45 Go | ★★★★☆ | - |
| GGUF Q2_K | 2 | 2.5 Go | 25 Go | ★★★☆☆ | - |
| Sparse 50% | 16 | 7 Go | 70 Go | ★★★★★ | 128 samples |
13. Guide Pratique
Références