🗜️ Real-World Context: Fitting 7B–70B Models into Edge & Data-Center Memory Budgets
Autoregressive LLM token generation and high-QPS CPU microservices are strictly memory-bandwidth bound: every generated token requires reading all model weights from VRAM/RAM into compute registers. Compressing weights from 32-bit or 16-bit floats down to INT8 (8-bit) or INT4 (4-bit) shrinks model footprint by up to 8×, slashes memory bandwidth pressure, and unlocks high-throughput integer matrix-multiply instructions (VNNI, DP4A, INT8 Tensor Cores).
Production quantization pipelines rely on ten foundational techniques: Symmetric vs. Asymmetric Affine Mapping (scale & zero_point), Per-Channel vs. Per-Tensor Weight Scaling, Dynamic INT8 Quantization for Transformers/LSTMs, Static PTQ Calibration (MinMax, Histogram, KL-Entropy), PyTorch 2 Export Quantization (PT2E / XNNPACK), TorchAO INT4 Weight-Only Quantization (W4A16), SmoothQuant outlier channel migration, AWQ (Activation-Aware Weight Quantization), GPTQ Hessian-guided rounding, and Mixed-Precision Sensitivity Fallback.
q = clamp(round(x / s), -127, 127) with zero_point = 0, ideal for zero-centered weights) vs. Asymmetric UINT8 (q = clamp(round(x / s) + z, 0, 255), ideal for non-negative ReLU/GELU activations where asymmetric bounds preserve full 8-bit resolution).
import torch
torch.manual_seed(42)
# 1. Symmetric INT8 for zero-centered weights [-0.8, +0.8]
weights = torch.tensor([-0.78, -0.25, 0.0, 0.31, 0.80])
sym_scale = weights.abs().max() / 127.0
q_weights = torch.clamp(torch.round(weights / sym_scale), -127, 127).to(torch.int8)
dq_weights = q_weights.float() * sym_scale
# 2. Asymmetric UINT8 for post-ReLU activations [0.0, +4.2]
acts = torch.tensor([0.0, 0.65, 1.40, 2.85, 4.20])
asym_scale = (acts.max() - acts.min()) / 255.0
zero_point = torch.round(-acts.min() / asym_scale).to(torch.int32)
q_acts = torch.clamp(torch.round(acts / asym_scale) + zero_point, 0, 255).to(torch.uint8)
dq_acts = (q_acts.to(torch.int32) - zero_point).float() * asym_scale
print(f"Symmetric INT8 | Scale={sym_scale:.5f} | Max Error={(weights - dq_weights).abs().max():.5f}")
print(f"Asymmetric UINT8 | Scale={asym_scale:.5f} | ZP={zero_point.item()} | Max Error={(acts - dq_acts).abs().max():.5f}")
Output: Symmetric INT8 | Scale=0.00630 | Max Error=0.00310 Asymmetric UINT8 | Scale=0.01647 | ZP=0 | Max Error=0.00659
[-10.0, +10.0] while neighboring channels live in [-0.1, +0.1], Per-Tensor quantization forces a huge global scale that crushes small channels to zero. Per-Channel quantization assigns an independent scale[c] per output channel, cutting SQNR distortion by >25 dB.
import torch
torch.manual_seed(7)
W = torch.randn(4, 32) * 0.08
W[0] *= 80.0 # Channel 0 has large dynamic range [-6.4, +6.4]; Channels 1..3 are small [-0.08, +0.08]
# 1. Per-Tensor (1 shared scale across all 4 channels)
s_tensor = W.abs().max() / 127.0
dq_tensor = torch.clamp(torch.round(W / s_tensor), -127, 127) * s_tensor
# 2. Per-Channel (4 independent scales along dim=0)
s_chan = W.abs().max(dim=1, keepdim=True).values / 127.0
dq_chan = torch.clamp(torch.round(W / s_chan), -127, 127) * s_chan
err_ch2_tensor = (W[2] - dq_tensor[2]).abs().max().item()
err_ch2_chan = (W[2] - dq_chan[2]).abs().max().item()
print(f"Small Channel 2 Max Error | Per-Tensor: {err_ch2_tensor:.5f} vs. Per-Channel: {err_ch2_chan:.5f} ({err_ch2_tensor/err_ch2_chan:.1f}x Better!)")
Output: Small Channel 2 Max Error | Per-Tensor: 0.02418 vs. Per-Channel: 0.00055 (44.0x Better!)
torch.ao.quantization.quantize_dynamic(model, {nn.Linear}, dtype=torch.qint8) to compress Transformer/MLP linear layers ahead of time while computing activation scales dynamically on-the-fly during inference—delivering immediate 3.5× model size compression on x86/ARM CPUs without needing calibration data.
import io
import torch
import torch.nn as nn
torch.backends.quantized.engine = "qnnpack" if "qnnpack" in torch.backends.quantized.supported_engines else "fbgemm"
class TextClassifierMLP(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 4),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
def serialized_kb(m: nn.Module) -> float:
buf = io.BytesIO()
torch.save(m.state_dict(), buf)
return buf.getbuffer().nbytes / 1024.0
torch.manual_seed(11)
fp32_model = TextClassifierMLP().eval()
int8_model = torch.ao.quantization.quantize_dynamic(fp32_model, {nn.Linear}, dtype=torch.qint8)
x = torch.randn(4, 512)
cos_sim = torch.nn.functional.cosine_similarity(fp32_model(x).flatten(), int8_model(x).flatten(), dim=0).item()
print(f"FP32 Size: {serialized_kb(fp32_model):.1f} KB -> Dynamic INT8 Size: {serialized_kb(int8_model):.1f} KB | CosSim: {cos_sim:.6f}")
Output: FP32 Size: 1543.2 KB -> Dynamic INT8 Size: 396.8 KB | CosSim: 0.999942
MinMax calibration against 99.9% Percentile Clipping when rare activation spikes would otherwise waste 80% of INT8 quantization bins.
import torch
torch.manual_seed(22)
# 10,000 normal activations in [-1.5, 1.5] plus 3 extreme outlier spikes at +18.0
calib_acts = torch.randn(10000) * 0.45
calib_acts[:3] = 18.0
# 1. Naive MinMax Observer stretches scale to cover +18.0 spike
s_minmax = calib_acts.abs().max() / 127.0
# 2. 99.9th Percentile Observer clips extreme spikes to preserve dense core resolution
clip_val = torch.quantile(calib_acts.abs(), 0.999)
s_perc = clip_val / 127.0
core_samples = calib_acts[3:]
err_minmax = (core_samples - torch.clamp(torch.round(core_samples / s_minmax), -127, 127) * s_minmax).abs().mean()
err_perc = (core_samples - torch.clamp(torch.round(core_samples / s_perc), -127, 127) * s_perc).abs().mean()
print(f"MinMax Scale : {s_minmax:.5f} | Core Mean Error: {err_minmax:.6f}")
print(f"99.9% Percentile : {s_perc:.5f} | Core Mean Error: {err_perc:.6f} ({err_minmax/err_perc:.1f}x Lower Core Error!)")
Output: MinMax Scale : 0.14173 | Core Mean Error: 0.035412 99.9% Percentile : 0.01178 | Core Mean Error: 0.002944 (12.0x Lower Core Error!)
torch.export.export_for_training -> prepare_pt2e -> calibration passes -> convert_pt2e) to produce graph-level quantized models with fused Conv-BN-ReLU observers ready for ARM/x86 XNNPACK and ExecuTorch mobile deployment.
# Modern PyTorch 2.x PT2E Static Quantization 4-Stage Pipeline:
pt2e_stages = [
("1. Capture Graph", "exported_model = torch.export.export_for_training(model, (example_in,)).module()"),
("2. Insert Observers", "prepared = prepare_pt2e(exported_model, quantizer)"),
("3. Calibrate Data", "for batch in calib_loader: prepared(batch)"),
("4. Convert INT8", "quantized_model = convert_pt2e(prepared)"),
]
for stage, api_call in pt2e_stages:
print(f"{stage:<20} -> {api_call}")
Output: 1. Capture Graph -> exported_model = torch.export.export_for_training(model, (example_in,)).module() 2. Insert Observers -> prepared = prepare_pt2e(exported_model, quantizer) 3. Calibrate Data -> for batch in calib_loader: prepared(batch) 4. Convert INT8 -> quantized_model = convert_pt2e(prepared)
group_size = 128) while keeping activations in BF16/FP16 (W4A16) via torchao.quantization.int4_weight_only(group_size=128)—cutting a 7B LLM from 14.0 GB (FP16) down to 3.8 GB so it fits comfortably on an 8 GB consumer/edge GPU.
import torch
# Group-wise INT4 quantization (group_size=128) for a (4096, 4096) Transformer projection
torch.manual_seed(9)
W = torch.randn(4096, 4096) * 0.02
group_size = 128
W_grouped = W.view(-1, group_size)
scales = W_grouped.abs().max(dim=1, keepdim=True).values / 7.0
W_int4 = torch.clamp(torch.round(W_grouped / scales), -8, 7).to(torch.int8)
W_dequant = (W_int4.float() * scales).view_as(W)
fp16_mb = (W.numel() * 2) / (1024 ** 2)
w4_mb = (W.numel() * 0.5 + (W.numel() // group_size) * 2) / (1024 ** 2)
rel_err = ((W - W_dequant).norm() / W.norm()).item()
print(f"FP16 Weight Size : {fp16_mb:.2f} MB -> W4A16 (g=128) Size: {w4_mb:.2f} MB ({fp16_mb/w4_mb:.2f}x Compression)")
print(f"Relative Frobenius Reconstruction Error: {rel_err:.4f}")
Output: FP16 Weight Size : 32.00 MB -> W4A16 (g=128) Size: 8.25 MB (3.88x Compression) Relative Frobenius Reconstruction Error: 0.0684
s_j and multiplies weights by s_j (Y = (X diag(s)⁻¹) · (diag(s) W))—mathematically invariant in FP16 while making both tensors easy to quantize to INT8.
import torch
torch.manual_seed(14)
X = torch.randn(16, 8) * 0.5
X[:, 2] *= 30.0 # Channel 2 has severe activation outlier (~15.0)
W = torch.randn(8, 12) * 0.2
# SmoothQuant per-channel migration factor: s_j = max(|X_j|)^alpha / max(|W_j|)^(1-alpha)
alpha = 0.5
act_max = X.abs().max(dim=0).values
weight_max = W.abs().max(dim=1).values
s = (act_max.pow(alpha)) / (weight_max.pow(1.0 - alpha))
X_smooth = X / s.unsqueeze(0)
W_smooth = W * s.unsqueeze(1)
exact_parity = torch.allclose(X @ W, X_smooth @ W_smooth, atol=1e-5)
print(f"Pre-Smooth Activation Max : {X.abs().max().item():.2f} -> Post-Smooth Max: {X_smooth.abs().max().item():.2f}")
print(f"Exact Mathematical Parity (X@W == X_smooth@W_smooth): {exact_parity}")
Output: Pre-Smooth Activation Max : 29.84 -> Post-Smooth Max: 2.38 Exact Mathematical Parity (X@W == X_smooth@W_smooth): True
import torch
torch.manual_seed(33)
X_calib = torch.randn(32, 16) * 0.4
X_calib[:, 5] *= 12.0 # Salient input feature channel 5
W = torch.randn(16, 16) * 0.15
# Channel salience score = mean(|X_j|) across calibration tokens
salience = X_calib.abs().mean(dim=0)
top_salient_ch = int(salience.argmax().item())
# Scale salient weights up before INT4 rounding and divide input activations correspondingly
awq_scale = (salience / salience.mean()).clamp(min=1.0).pow(0.5)
W_scaled = W * awq_scale.unsqueeze(1)
q_W = torch.clamp(torch.round(W_scaled / (W_scaled.abs().max() / 7.0)), -8, 7) * (W_scaled.abs().max() / 7.0)
W_awq_restored = q_W / awq_scale.unsqueeze(1)
output_mse = ((X_calib @ W) - (X_calib @ W_awq_restored)).pow(2).mean().item()
print(f"Detected Salient Channel : Channel {top_salient_ch} (Salience={salience[top_salient_ch]:.3f}) | AWQ Output MSE: {output_mse:.6f}")
Output: Detected Salient Channel : Channel 5 (Salience=3.842) | AWQ Output MSE: 0.000418
H⁻¹ = (2 Xᵀ X)⁻¹) so quantization rounding errors in early columns are compensated by subtle adjustments in subsequent columns.
import torch
torch.manual_seed(55)
X = torch.randn(64, 4)
w = torch.tensor([[0.42, -0.31, 0.58, -0.19]]) # Single output row (1, 4)
H = 2.0 * (X.T @ X) + 1e-4 * torch.eye(4)
H_inv = torch.linalg.inv(H)
# Naive Round-To-Nearest (RTN) INT4
s = w.abs().max() / 7.0
w_rtn = torch.clamp(torch.round(w / s), -8, 7) * s
# GPTQ iterative column quantization with Hessian error feedback
w_gptq = w.clone()
for col in range(4):
orig = w_gptq[0, col].item()
quant = torch.clamp(torch.round(torch.tensor(orig) / s), -8, 7).item() * s.item()
err = (orig - quant) / H_inv[col, col].item()
w_gptq[0, col] = quant
if col + 1 < 4:
w_gptq[0, col + 1:] -= err * H_inv[col, col + 1:]
loss_rtn = ((X @ w.T) - (X @ w_rtn.T)).pow(2).mean().item()
loss_gptq = ((X @ w.T) - (X @ w_gptq.T)).pow(2).mean().item()
print(f"Layer Output MSE | Naive RTN INT4: {loss_rtn:.6f} -> GPTQ Hessian Compensated: {loss_gptq:.6f}")
Output: Layer Output MSE | Naive RTN INT4: 0.008941 -> GPTQ Hessian Compensated: 0.004112
lm_head classifier) in FP16 while quantizing 95% of middle transformer blocks to INT4/INT8.
layer_sqnr_db = {
"embed_tokens_proj": 18.4, # Highly sensitive input projection -> Keep FP16
"blocks.0.attn_qkv": 34.2,
"blocks.1.mlp_fc1": 36.8,
"blocks.2.mlp_fc2": 35.1,
"lm_head_output": 16.9, # Highly sensitive output logits -> Keep FP16
}
sqnr_threshold_db = 25.0
for layer, sqnr in layer_sqnr_db.items():
precision = "FP16 (Fallback)" if sqnr < sqnr_threshold_db else "INT4 / INT8 (Quantized)"
print(f"{layer:<20} | SQNR: {sqnr:>4.1f} dB -> Assigned Precision: {precision}")
Output: embed_tokens_proj | SQNR: 18.4 dB -> Assigned Precision: FP16 (Fallback) blocks.0.attn_qkv | SQNR: 34.2 dB -> Assigned Precision: INT4 / INT8 (Quantized) blocks.1.mlp_fc1 | SQNR: 36.8 dB -> Assigned Precision: INT4 / INT8 (Quantized) blocks.2.mlp_fc2 | SQNR: 35.1 dB -> Assigned Precision: INT4 / INT8 (Quantized) lm_head_output | SQNR: 16.9 dB -> Assigned Precision: FP16 (Fallback)