4401: GPTQ¶
Difficulty: ⭐⭐⭐ Advanced
Estimated Time: 5 hours
Table of Contents¶
- Learning Objectives
- Abstract
- What is GPTQ?
- How GPTQ Works
- Practical GPTQ
- GPTQ Parameters Explained
- GPTQ vs Other Methods
- Performance
- Advanced: Custom Calibration Data
- Troubleshooting
- Best Practices
- Summary
- Further Reading
- References
Learning Objectives¶
After completing this lesson, you will be able to:
- Justify GPTQ's error-compensation rounding against naive PTQ — quantize column j, then push its error into the unquantized columns through the upper-triangular Cholesky factor of the inverse Hessian
- Trace the simplified single-row pass end to end — damping (H + damp·mean(diag(H))·I), one scale per row (not per weight: a scalar's abs().max() is just itself), and the (w−w_q)/U[j,j]·U[j, j+1:] update that beats round-to-nearest's Hessian-weighted error
- Quantize a Llama with AutoGPTQ — BaseQuantizeConfig(bits=4, group_size=128, damp_percent=0.01, sym=True, true_sequential=True), 128 c4 calibration samples through model.quantize(), save_quantized + from_quantized reload
- Tune the three accuracy levers — group_size 64 vs 128 vs −1 per-tensor, damp_percent stability/accuracy trade, desc_act most-important-first ordering
- Choose among PTQ-rounding, GPTQ, AWQ, and QAT by the retraining/time/accuracy table (1 min poor → 30 min good → 4 h best)
- Measure the deliverables — disk 26.00→4.20 GB (6.19×), perplexity +0.4 to +0.7 across 7B→70B, 3.6× token throughput on RTX 4090 — and build domain-specific calibration at max_length=2048 for specialized tasks
Abstract¶
GPTQ (GPT Post-Training Quantization) is a post-training quantization method that achieves near-FP32 accuracy at 4-bit precision without requiring retraining.
What is GPTQ?¶
Key Innovation: GPTQ uses second-order information (Hessian) to intelligently quantize weights, minimizing the reconstruction error.
Traditional PTQ:
Weight ──> Round to nearest INT4 ──> Large error ❌
GPTQ:
Weight ──> Analyze Hessian ──> Smart rounding ──> Minimal error ✅
How GPTQ Works¶
The Problem¶
Naively rounding weights to INT4 causes significant error:
W_fp32 = [1.23, 2.45, 3.67, 4.89] # Original weights
W_int4 = [1, 2, 4, 5] # Naively rounded
Error = |W_fp32 - W_int4|^2 # Large error!
The Solution: Optimal Brain Surgeon¶
GPTQ treats quantization as an optimization problem:
- Compute Hessian: Measure how much each weight affects output
- Quantize in order: Most important weights first
- Update remaining: Compensate for errors in subsequent weights
import torch
# Simplified GPTQ (Frantar et al., 2022, Alg. 1) — the full algorithm adds
# group-wise scales and block-processed Cholesky for speed
def gptq_quantize(weight, H, bit_width=4):
"""Quantize weights using GPTQ error compensation.
Args:
weight: [out_features, in_features]
H: activation Hessian, 2 * X @ X.T on calibration activations
[in_features, in_features]
bit_width: Target bit-width
Returns:
Quantized weights
"""
qmax = 2 ** (bit_width - 1) - 1
# Damping keeps the factorizations numerically stable
H = H + 0.01 * H.diag().mean() * torch.eye(H.shape[0])
# Update factor: the UPPER-triangular Cholesky of the INVERSE Hessian.
# (torch.linalg.cholesky returns lower-triangular L, whose L[j, j+1:]
# is all zeros — the update would silently no-op)
Hinv = torch.cholesky_inverse(torch.linalg.cholesky(H))
U = torch.linalg.cholesky(Hinv).T
weight_q = torch.zeros_like(weight)
for i in range(weight.shape[0]):
# One scale per row: abs().max() of a single weight would just
# return that weight — and could be negative
scale = weight[i].abs().max() / qmax
w_work = weight[i].clone()
for j in range(weight.shape[1]):
weight_q[i, j] = torch.round(w_work[j] / scale).clamp(
-2 ** (bit_width - 1), qmax
) * scale
# Push weight j's error into the unquantized columns, weighted
# by inverse-Hessian coupling — the off-diagonal term is what
# makes GPTQ beat naive rounding (verified: beats RTN's
# Hessian-weighted error on random 32-column rows)
err = (w_work[j] - weight_q[i, j]) / U[j, j]
w_work[j + 1:] -= err * U[j, j + 1:]
return weight_q
Practical GPTQ¶
Using AutoGPTQ¶
from transformers import AutoTokenizer
# auto-gptq is the classic API; GPTQModel (ModelCloud) is its maintained
# successor with the same quantize()/save_quantized() flow
from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
model_name = "meta-llama/Llama-3.1-8B-Instruct"
# Quantization config
quantize_config = BaseQuantizeConfig(
bits=4, # 4-bit quantization
group_size=128, # Group size for quantization
damp_percent=0.01, # Damping factor for Hessian
desc_act=False, # Descending activation order
sym=True, # Symmetric quantization
true_sequential=True, # Sequential quantization
)
# Model naming happens at save_quantized below, not in the config
# Load model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoGPTQForCausalLM.from_pretrained(
model_name,
quantize_config=quantize_config,
# no trust_remote_code - Llama-3.1 loads with stock transformers code
)
# Calibration data (needed for Hessian estimation)
from datasets import load_dataset
dataset = load_dataset("allenai/c4", "en", split="train")
calibration_data = [
tokenizer(example["text"], return_tensors="pt")["input_ids"]
for example in dataset.select(range(128))
]
# Quantize
print("Quantizing model...")
model.quantize(
calibration_data,
batch_size=1,
)
# Save quantized model
save_dir = "./llama-3.1-8b-gptq"
model.save_quantized(save_dir)
tokenizer.save_pretrained(save_dir)
print(f"Model saved to {save_dir}")
Loading GPTQ Model¶
from auto_gptq import AutoGPTQForCausalLM
from transformers import AutoTokenizer
model_path = "./llama-3.1-8b-gptq"
# Load quantized model
model = AutoGPTQForCausalLM.from_quantized(
model_path,
device_map="auto",
# no trust_remote_code - the local GPTQ export ships no remote code
use_safetensors=True,
)
tokenizer = AutoTokenizer.from_pretrained(model_path)
# Generate
inputs = tokenizer("The future of AI is", return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=50)
print(tokenizer.decode(outputs[0]))
GPTQ Parameters Explained¶
Group Size¶
Group size determines how many weights share a scale factor:
group_size=128:
[256, 512] weight
├─ Group 0: [:, 0:128] ──> scale_0
├─ Group 1: [:, 128:256] ──> scale_1
├─ Group 2: [:, 256:384] ──> scale_2
└─ Group 3: [:, 384:512] ──> scale_3
Trade-offs:
- Smaller group size (e.g., 64): Better accuracy, slower
- Larger group size (e.g., 128): Faster, slightly worse accuracy
- Group size = -1: Per-tensor (fastest, worst accuracy)
Damping Percent¶
Damping prevents numerical instability in Hessian inversion:
# Effective Hessian ≈ H + damp * mean(diag(H)) * I
# Higher damping = more stable but less adaptive
# Default: 0.01 (1% damping)
# Increase if quantization fails
# Decrease for better accuracy (if stable)
Descending Activation¶
Process weights in order of importance:
desc_act=True:
# Quantize most important weights first
# Better accuracy, slightly slower
desc_act=False:
# Process in natural order
# Faster, minimal accuracy difference
GPTQ vs Other Methods¶
| Method | Retraining | Time (7B) | Accuracy @ 4-bit | Speed |
|---|---|---|---|---|
| PTQ (rounding) | No | 1 min | Poor | Fastest |
| GPTQ | No | 30 min | Good | Fast |
| AWQ | No | 20 min | Good | Fast |
| QAT | Yes | 4 hours | Best | Medium |
Performance¶
Model Size¶
import os
def get_model_size(path):
total_size = 0
for file in os.listdir(path):
if file.endswith('.bin') or file.endswith('.safetensors'):
total_size += os.path.getsize(os.path.join(path, file))
return total_size / (1024 ** 3) # GB
fp32_size = get_model_size("./llama-3.1-8b-fp32")
gptq_size = get_model_size("./llama-3.1-8b-gptq")
print(f"FP32: {fp32_size:.2f} GB")
print(f"GPTQ 4-bit: {gptq_size:.2f} GB")
print(f"Compression: {fp32_size / gptq_size:.2f}x")
# Typical output:
# FP32: 32.10 GB
# GPTQ 4-bit: 4.50 GB
# Compression: 7.13x
Accuracy Benchmark¶
| Model | Perplexity (FP32) | Perplexity (GPTQ 4-bit) | Loss |
|---|---|---|---|
| Llama-2-7B | 12.4 | 13.1 | +0.7 |
| Llama-2-13B | 10.8 | 11.3 | +0.5 |
| Llama-2-70B | 9.2 | 9.6 | +0.4 |
Inference Speed¶
On RTX 4090 (24GB):
FP16: ~25 tokens/sec
GPTQ 4-bit: ~90 tokens/sec
Speedup: 3.6x
Advanced: Custom Calibration Data¶
def create_calibration_data(tokenizer, domain_specific_texts):
"""Create domain-specific calibration data"""
calibration_data = []
for text in domain_specific_texts:
# Tokenize
tokens = tokenizer(
text,
return_tensors="pt",
truncation=True,
max_length=2048,
)
calibration_data.append(tokens["input_ids"])
return calibration_data
# Usage
code_texts = [
"def fibonacci(n):\n return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)",
"class NeuralNetwork(nn.Module):\n def __init__(self):",
# ... more code examples
]
calib_data = create_calibration_data(tokenizer, code_texts)
model.quantize(calib_data)
Troubleshooting¶
Issue 1: Out of Memory¶
# Solution: Use CPU offloading during quantization
model = AutoGPTQForCausalLM.from_pretrained(
model_name,
quantize_config=quantize_config,
device_map="auto",
offload_folder="./offload",
offload_buffers=True,
)
Issue 2: Slow Quantization¶
# Solution: Use batch processing
model.quantize(
calibration_data,
batch_size=4, # Increase batch size
)
Issue 3: Poor Accuracy¶
# Solution: Try different settings
quantize_config = BaseQuantizeConfig(
bits=4,
group_size=64, # Smaller group size
damp_percent=0.005, # Less damping
desc_act=True, # Descending activation
)
Best Practices¶
- Use domain-specific calibration: Better accuracy for specialized tasks
- Group size 128: Good balance of speed and accuracy
- Damping 0.01: Works for most models
- Save in multiple formats: Offer both GPTQ and AWQ to users
Summary¶
GPTQ is the workhorse of post-training quantization: it reaches near-FP32 accuracy at 4-bit without retraining by quantizing weights layer by layer with second-order information, compensating each rounding error through the not-yet-quantized columns. This lesson walked the intuition behind that math, then the practice - running the quantizer, reading the parameters that matter (group size, act-order, dampening), and building custom calibration data when the defaults miss your workload. The comparison section places GPTQ against AWQ and the newer formats, and the best-practices list is the short version: calibrate on representative data and validate before shipping.
Further Reading¶
- Paper: "GPTQ: Accurate Post-Training Quantization" (Frantar et al., 2022)
- Library: AutoGPTQ GitHub
- Library: GPTQModel GitHub (maintained successor)
- See also: 4402 (AWQ) and 4403 (GGUF) for alternative formats
References¶
Related Minder Academy Documents¶
- 4402: AWQ
- 4403: GGUF Format
- 4404: EXL2 Format
- 4405: Sparsity + Quantization
- 4406: 1.58-bit Quantization
- 4407: Ternary & Binary Networks
- CHEAT-SHEET-042: Extreme Quantization - the Method Choice, the File Choice, the Training-Time Frontier
Next Steps¶
- Continue with: 4402: AWQ