4402: AWQ¶
Difficulty: ⭐⭐⭐ Advanced
Estimated Time: 5 hours
Table of Contents¶
- Learning Objectives
- Abstract
- What is AWQ?
- How AWQ Works
- Practical AWQ
- AWQ vs GPTQ
- AWQ Parameters
- Custom Calibration for AWQ
- Multi-Quantization (Mixing Bits)
- Inference Optimization
- Converting Between Formats
- Troubleshooting
- Best Practices
- Summary
- Further Reading
- References
Learning Objectives¶
After completing this lesson, you will be able to:
- Trace the activation-aware insight end to end — ~1% salient weights, importance = |activation_j|·|w_ij| broadcasting per-channel magnitudes across the weight matrix, and the activation-weighted error that protection minimizes (measured 30/30 vs RTN at 0.83 mean ratio; scalar stats manage only 0.996)
- Implement the three-step pipeline — per-channel pre-hook activation stats with running max over calibration batches, importance ranking, selective quantization with per-row scales where protected entries stay bit-equal FP16
- Quantize a Llama with AutoAWQ — quant_config{zero_point: True, q_group_size: 128, w_bit: 4, version: "GEMM"}, 128 c4 calibration samples, save_quantized + from_quantized(fuse_layers=True) reload
- Choose between GPTQ and AWQ from the table — Hessian-based error compensation vs activation-based protection, ~30 vs ~20 min at 7B, +0.2 perplexity advantage, faster fused kernels
- Tune the three knobs — zero_point symmetric-vs-asymmetric INT8 ranges, q_group_size 128 vs 64 vs −1, and the protection budget (keep_ratio 0.005–0.02)
- Build domain calibration at max_length=2048 and read the deliverables — AWQ ppl 12.4→12.9 at 7B (+0.2 better than GPTQ), ~20% fusion speedup — avoiding the phantom APIs (from_quantized takes max_seq_len, generate batches via stacked prompts)
Abstract¶
AWQ (Activation-aware Weight Quantization) is a post-training quantization method that considers activation distributions when quantizing weights, achieving better accuracy at the same bit-width.
What is AWQ?¶
Key Insight: Only ~1% of weights are significant for model performance. AWQ identifies and protects these weights while aggressively quantizing others.
Traditional PTQ:
All weights ──> Same precision ──> Some important weights degraded ❌
AWQ:
Analyze activations ──> Identify important weights ──> Protect + Quantize ✅
How AWQ Works¶
Step 1: Activation Analysis¶
AWQ collects activation statistics to identify important weights:
import torch
import torch.nn as nn
def collect_activation_stats(model, calibration_data):
"""
Collect per-channel activation magnitudes for each Linear's INPUT.
A scalar per layer would collapse "activation-aware" ranking into
plain weight-magnitude ranking (measured: scalar stats beat RTN by
<0.5% weighted error; per-channel stats by ~17%).
Returns: {layer_name: [in_features] mean |activation|}
"""
activation_scales = {}
# Hooks on the INPUT (pre-hook): AWQ scales input channels, and the
# input of a layer is what its weights multiply
def make_pre_hook(name):
def pre_hook(module, args):
x = args[0].detach().abs()
channel_magnitude = x.mean(dim=tuple(range(x.dim() - 1)))
# Running max: a plain assignment is overwritten by every
# batch, keeping only the last calibration batch
if name in activation_scales:
activation_scales[name] = torch.maximum(
activation_scales[name], channel_magnitude
)
else:
activation_scales[name] = channel_magnitude
return pre_hook
hooks = []
for name, module in model.named_modules():
if isinstance(module, nn.Linear):
hooks.append(module.register_forward_pre_hook(make_pre_hook(name)))
# Run calibration data
with torch.no_grad():
for batch in calibration_data:
_ = model(**batch)
# Clean up hooks
for hook in hooks:
hook.remove()
return activation_scales
Step 2: Weight Importance Score¶
def compute_importance_score(weight, activation_magnitude):
"""
Compute importance score for each weight.
Score = |activation_j| × |w_ij| — per-channel magnitudes broadcast
across the [out_features, in_features] weight matrix, so a salient
input channel protects its whole column.
(The paper's optimum is a smoothed activation-power scale; the
linear form keeps the sketch readable while preserving the ranking.)
"""
importance = activation_magnitude[None, :] * weight.abs()
return importance
Step 3: Selective Quantization¶
def awq_quantize(weight, activation_magnitude, bit_width=4, keep_ratio=0.01):
"""
AWQ quantization with weight preservation.
Pedagogical mixed-precision form: salient weights stay FP16.
Production AWQ never stores FP16 outliers — it rescales per channel
(w_j -> w_j * s, x_j -> x_j / s) so salient directions quantize to
the same INT4 grid with no extra memory.
Args:
weight: [out_features, in_features]
activation_magnitude: [in_features] per-channel magnitudes
bit_width: Target bit-width for most weights
keep_ratio: Fraction of weights to keep at FP16
"""
# Compute importance scores
importance = compute_importance_score(weight, activation_magnitude)
# Select top-k weights to keep
num_keep = int(weight.numel() * keep_ratio)
threshold = importance.flatten().topk(num_keep).values[-1]
# Create mask
keep_mask = importance >= threshold
# One scale per row over the UNPROTECTED entries — a single global
# scale loses ~1.4x weighted error to per-row rounding. Rows whose
# every entry is protected fall back to their full-range scale:
# their FP16 outliers sit outside the quantized grid anyway.
qmax = 2 ** (bit_width - 1) - 1
masked = torch.where(keep_mask, torch.full_like(weight, float("inf")), weight.abs())
row_max = masked.max(dim=1).values
full_max = weight.abs().max(dim=1).values
scale = torch.where(row_max.isinf(), full_max, row_max).clamp(min=1e-8) / qmax
scale_mat = scale[:, None].expand_as(weight)
weight_q = weight.clone()
weight_q[~keep_mask] = torch.round(
weight[~keep_mask] / scale_mat[~keep_mask]
) * scale_mat[~keep_mask]
return weight_q, keep_mask
Practical AWQ¶
Using AutoAWQ¶
from awq import AutoAWQForCausalLM
from transformers import AutoTokenizer
model_name = "meta-llama/Llama-3.1-8B-Instruct"
# Quantization config
quant_config = {
"zero_point": True, # Use zero-point
"q_group_size": 128, # Group size
"w_bit": 4, # 4-bit
"version": "GEMM", # GEMM version (faster)
}
# Load and quantize
model = AutoAWQForCausalLM.from_pretrained(
model_name,
device_map="auto",
safetensors=True,
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Quantize
from datasets import load_dataset
dataset = load_dataset("allenai/c4", "en", split="train")
calibration_data = [
{"input_ids": tokenizer(example["text"], return_tensors="pt")["input_ids"]}
for example in dataset.select(range(128))
]
model.quantize(calibration_data, quant_config)
# Save
save_path = "./llama-3.1-8b-awq"
model.save_quantized(save_path)
tokenizer.save_pretrained(save_path)
Loading AWQ Model¶
from awq import AutoAWQForCausalLM
from transformers import AutoTokenizer
model_path = "./llama-3.1-8b-awq"
model = AutoAWQForCausalLM.from_quantized(
model_path,
device_map="auto",
safetensors=True,
fuse_layers=True, # Fuse layers for speed
)
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]))
AWQ vs GPTQ¶
| Aspect | GPTQ | AWQ |
|---|---|---|
| Method | Hessian-based | Activation-based |
| Quantization Time (7B) | ~30 min | ~20 min |
| Accuracy @ 4-bit | Good | Slightly better |
| Inference Speed | Fast | Faster (optimized kernels) |
| Calibration Data | Required | Required |
| Implementation Complexity | High | Medium |
Accuracy Comparison (Perplexity)¶
| Model | FP32 | GPTQ 4-bit | AWQ 4-bit | AWQ Advantage (vs GPTQ) |
|---|---|---|---|---|
| Llama-2-7B | 12.4 | 13.1 | 12.9 | +0.2 |
| Llama-2-13B | 10.8 | 11.3 | 11.1 | +0.2 |
| Llama-2-70B | 9.2 | 9.6 | 9.5 | +0.1 |
AWQ Parameters¶
Zero Point¶
# Zero-point allows asymmetric quantization
zero_point=True: # Better accuracy, slightly slower
# Range: [-128, 127] for INT8
zero_point=False: # Symmetric, faster
# Range: [-127, 127] for INT8
Group Size¶
# Similar to GPTQ
q_group_size=128: # Default, good balance
q_group_size=64: # Better accuracy
q_group_size=-1: # Per-tensor, fastest
Protection Budget (keep_ratio)¶
# Fraction of weights kept at FP16 — the awq_quantize sketch's knob
keep_ratio=0.01: # Keep top 1%
keep_ratio=0.005: # Keep fewer (more aggressive)
keep_ratio=0.02: # Keep more (conservative)
# AutoAWQ's quant_config does not expose this: the paper grid-searches
# the per-group clip with an MSE sweep during quantization
Custom Calibration for AWQ¶
def domain_aware_awq(model, tokenizer, domain_texts):
"""Apply AWQ with domain-specific calibration"""
# Tokenize domain texts
calibration_data = []
for text in domain_texts:
tokens = tokenizer(
text,
return_tensors="pt",
truncation=True,
max_length=2048,
)
calibration_data.append({"input_ids": tokens["input_ids"]})
# Quantize
quant_config = {
"zero_point": True,
"q_group_size": 128,
"w_bit": 4,
"version": "GEMM",
}
model.quantize(calibration_data, quant_config)
return model
# Example: Code-focused model
code_texts = [
"def quicksort(arr):\n if len(arr) <= 1: return arr",
"import torch.nn as nn",
"class BinarySearchTree:",
# ... more examples
]
model = domain_aware_awq(model, tokenizer, code_texts)
Multi-Quantization (Mixing Bits)¶
def mixed_precision_awq(model, bit_config):
"""
Sketch of per-layer bit dispatch.
AutoAWQ has no per-layer bit API — production mixed-precision runs
through GPTQ-style per-layer configs or QAT (see 4305); the layer
quantization machinery itself is omitted here.
"""
for layer_name, layer in model.named_modules():
if isinstance(layer, nn.Linear):
# Determine bit-width for this layer
bits = get_bits_for_layer(layer_name, bit_config)
# ... layer-level quantization machinery would attach here
return model
def get_bits_for_layer(layer_name, config):
"""Bit-width for a module path like 'layers.14.self_attn.q_proj'.
Keys are ranges such as 'layers.11-20' or bare heads like
'embeddings'. A plain substring test (`pattern in layer_name`)
never matches real module paths — parse the layer index and
range-check it instead.
"""
head, idx = layer_name.split(".")[:2]
for pattern, bits in config.items():
p_head, _, p_span = pattern.partition(".")
if p_head != head:
continue
if not p_span: # bare head like 'embeddings'
return bits
lo, hi = map(int, p_span.split("-"))
if lo <= int(idx) <= hi:
return bits
return 4 # Default
Inference Optimization¶
Layer Fusion¶
# Fuse linear + activation for speed
model = AutoAWQForCausalLM.from_quantized(
model_path,
fuse_layers=True, # Enable fusion
max_seq_len=2048, # from_quantized takes max_seq_len — max_new_tokens
# belongs to generate()
)
# Fused layers: ~20% faster inference
Batch Size Optimization¶
# generate() has no batch_size argument — batching means stacking
# prompts into the inputs themselves ([batch, seq_len] input_ids)
prompts = ["The future of AI is", "Quantization lets us"]
inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device)
outputs = model.generate(
**inputs,
max_new_tokens=512,
)
Converting Between Formats¶
def awq_to_gptq(awq_model_path):
"""Illustrative sketch — qweight packing alone is not a converter.
AWQ and GPTQ share the packed-INT32 qweight layout but differ in
scale/zero-point layout and metadata; a real conversion repacks
those too. In practice you quantize from the FP base per target
format instead of converting.
"""
# Load AWQ model
model_awq = AutoAWQForCausalLM.from_quantized(awq_model_path)
# Extract quantized weights
quantized_weights = {}
for name, param in model_awq.named_parameters():
if 'qweight' in name:
quantized_weights[name] = param
# Create GPTQ-compatible state dict
gptq_state_dict = convert_to_gptq_format(quantized_weights)
# Save
torch.save(gptq_state_dict, "model-gptq.pt")
return gptq_state_dict
Troubleshooting¶
Issue 1: Calibration Fails¶
# Error: CUDA out of memory during calibration
# Solution: Use smaller calibration batch
calibration_data = [
{"input_ids": tokenizer(text, truncation=True, max_length=512)["input_ids"]}
for text in calibration_texts
]
Issue 2: Poor Generation Quality¶
# Solution: protect more of the model — AutoAWQ's quant_config has no
# clip_ratio/layer_bits keys; per-layer protection is done with
# modules_to_not_convert, and mixed bits go through GPTQ configs (4305)
quant_config = {
"zero_point": True,
"q_group_size": 64, # Smaller groups absorb outliers better
"w_bit": 4,
"version": "GEMM",
"modules_to_not_convert": ["embed_tokens", "lm_head"],
}
Issue 3: Slow Inference¶
# Solution: Enable optimizations
model = AutoAWQForCausalLM.from_quantized(
model_path,
fuse_layers=True, # Layer fusion
max_seq_len=2048, # Context window
use_safetensors=True, # from_quantized has no safe_load kwarg
)
Best Practices¶
- Domain-specific calibration: Use calibration data from your target domain
- 8-bit for embeddings: First and last layers benefit from higher precision
- Enable fusion: Always use
fuse_layers=Truefor production - Group size 128: Default works well for most models
- Test before deploying: Validate on domain-specific evaluation
Summary¶
AWQ improves on naive PTQ with one observation: a small fraction of salient weights carries most of the accuracy, and activation distributions tell you which ones. Scaling and protecting those channels preserves accuracy at the same bit-width where uniform rounding would bleed it. This lesson covered the mechanism and the practical workflow, then the operational questions: when AWQ beats GPTQ and vice versa, how mixed-bit layouts trade a little accuracy for speed, and how to convert between formats when the runtime demands it.
Further Reading¶
- Paper: "AWQ: Activation-aware Weight Quantization" (Lin et al., 2023)
- Library: AutoAWQ GitHub (casper-hansen/AutoAWQ)
- Serving: vLLM and Transformers both load AWQ checkpoints natively
- See also: 4401 (GPTQ) for the Hessian-based alternative, 4403 (GGUF) for CPU deployment
References¶
Related Minder Academy Documents¶
- 4401: GPTQ
- 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: 4403: GGUF Format