Mental model
Post-training quantization reduces the bytes moved and stored for a trained model by representing groups of weights with fewer bits, while calibration and error compensation limit quality loss. AWQ uses activation magnitudes to protect sensitive channels; GPTQ uses approximate curvature to compensate quantization error. A useful edge artifact includes packed weights, scales, format metadata, compatible kernels, and device-specific quality measurements.
Learning outcomes
- Calculate packed weight bytes from parameter count, bit width, group size, and scale storage, then name the memory terms that the estimate excludes.
- Compare AWQ and GPTQ by calibration inputs, quantization procedure, conversion cost, and the device kernel required at inference.
- Define a promotion gate with a measured task-quality floor, a memory cap, and decode latency on the target device class.
Theory
For a linear layer, inference multiplies an input vector by a weight matrix. Quantization maps each group of floating-point weights into integer codes and a scale. The runtime reconstructs approximate values while executing the matrix multiply. Four-bit codes use about half a byte per parameter instead of two bytes for FP16, but storage also includes scales, optional zero points, padding, and kernel workspace.
AWQ calibrates with representative layer inputs. It estimates which input channels carry unusually large activation magnitudes, rescales the corresponding weight channels before quantization, and compensates the adjacent computation with an inverse scale. The floating-point function remains approximately the same, while quantization error on high-impact channels falls. Calibration is therefore about the activation distribution of the target workload, not a generic collection of random tokens.
GPTQ treats quantization as a sequence of choices. It quantizes a column or group, estimates the resulting output error with approximate inverse-Hessian information from calibration activations, then adjusts remaining weights to offset some of that error. The curvature estimate makes conversion more expensive than simple round-to-nearest, but it can preserve layer outputs better at a fixed bit width. AWQ channel rescaling and GPTQ error compensation are different strategies; neither guarantees that every downstream task remains unchanged.
The model file is only one part of deployment. A browser or mobile runtime must support the packed format and relevant matrix shapes. If a kernel unpacks every value into FP16 before multiplication, the download shrinks but peak memory traffic and decode latency may erase much of the benefit. Benchmark prompt prefill and token-by-token decode separately because their matrix shapes and bottlenecks differ.
Estimate the artifact before loading it
A first-order storage estimate for a groupwise representation is:
Here, N is the number of scalar weights, b is bits per weight, G is weights per quantization group, s is bytes per stored scale, and M_meta covers alignment, zero points when used, and tensor headers. The ceiling rounds N/G up to the next complete group. The equation estimates serialized weight bytes; it excludes activations, temporary buffers, and optimizer or calibration state.
Consider a 7-billion-parameter model quantized to four bits with groups of 128 and one 2-byte scale per group. The packed codes require 3.50 billion bytes. The 54.69 million group scales add about 109 million bytes, for roughly 3.61 GB before metadata and alignment. The same parameter count at FP16 needs about 14.0 GB of weight bytes. The reduction is close to 3.9 times, not exactly four times, and it does not mean the model needs only 3.61 GB of device memory: prefill activations, dequantization tiles, embeddings, and runtime buffers add to the peak.
A quality gate should compare the quantized artifact with its baseline on the same prompt set and decode settings. Record task accuracy or loss, refusal and formatting behavior, first-token latency, steady-state tokens per second, peak resident memory, and energy on each target device class. Use the exact artifact hash and tokenizer revision so a benchmark cannot silently compare different model inputs.
Trade-offs
| Choice | Where it helps | Cost to measure |
|---|---|---|
| AWQ channel scaling | Calibration shows a small set of channels dominates activation magnitude | Calibration coverage and sensitivity to prompts outside that set |
| GPTQ error compensation | Weight memory is tight and offline conversion time is acceptable | Quantization time, group layout, and kernel support |
| Higher-bit fallback | Quality floor is missed or the target kernel lacks a low-bit path | Larger download, memory traffic, and cold-start time |
Group size couples metadata to reconstruction error. Smaller groups add more scales, but each scale fits a narrower weight range; larger groups reduce metadata while allowing outliers to consume more quantization levels. Choose it with the target kernel's supported layouts and a representative calibration set, then compare both quality and runtime measurements for each candidate.
Failure modes and misconceptions
A calibration set that omits code, multilingual prompts, or long contexts can hide quality regressions that appear only after deployment. An operator may have no low-bit kernel for a particular shape, causing conversion to float values or CPU fallback. That path can increase peak memory even though the artifact is smaller. An eight-bit or four-bit checkpoint may also pass average accuracy while degrading a rare but safety-critical class; stratify evaluation and fail the promotion gate on the protected class.
Treat the format, group size, calibration revision, and target runtime as one versioned artifact contract. A model that meets a memory limit on a laptop GPU may still exceed an integrated GPU's storage-buffer limit or drain a phone battery during a long decode.
Decision scenario
A four-bit conversion brings a 7B checkpoint under a mobile download budget, but the code-generation slice loses 8 percentage points and one attention shape falls back to FP16. Keep the canary paused. Compare the failing prompts against the FP16 baseline, identify whether calibration coverage or the unsupported shape causes the regression, and benchmark a supported low-bit shape or higher-bit fallback on the same device. Promote only when the code-task floor passes and peak memory and p95 decode latency stay within the mobile profile.
The following PyTorch routine demonstrates symmetric groupwise packing and reconstruction for a weight tensor. It is a baseline for measuring representation error, not an AWQ or GPTQ replacement: those methods need calibration-driven scaling or error feedback before packing.
Implementation: inspect a groupwise representation
pythonimport torchdef quantize_int4_groupwise(weight: torch.Tensor, group_size: int = 128):if group_size <= 0 or group_size % 2:raise ValueError("group_size must be a positive even number")original_shape = tuple(weight.shape)flat = weight.detach().float().reshape(-1)padding = (-flat.numel()) % group_sizeif padding:flat = torch.nn.functional.pad(flat, (0, padding))groups = flat.reshape(-1, group_size)scale_fp32 = groups.abs().amax(dim=1).clamp_min(1e-8) / 7codes = torch.round(groups / scale_fp32[:, None]).clamp(-7, 7).to(torch.int16)nibbles = torch.bitwise_and(codes, 15)packed = (nibbles[:, 0::2] | (nibbles[:, 1::2] << 4)).to(torch.uint8)return packed, scale_fp32.to(torch.float16), original_shapedef dequantize_int4_groupwise(packed, scales, original_shape):low = torch.bitwise_and(packed.to(torch.int16), 15)high = torch.bitwise_right_shift(packed.to(torch.int16), 4)unsigned = torch.stack((low, high), dim=-1).reshape(-1, packed.shape[1] * 2)signed = torch.where(unsigned >= 8, unsigned - 16, unsigned).float()restored = signed * scales.float()[:, None]count = int(torch.tensor(original_shape).prod().item())return restored.reshape(-1)[:count].reshape(original_shape)if __name__ == "__main__":torch.manual_seed(7)weight = torch.randn(64, 128)packed, scales, shape = quantize_int4_groupwise(weight)reconstructed = dequantize_int4_groupwise(packed, scales, shape)print({"packed_bytes": packed.numel(), "rmse": (weight - reconstructed).square().mean().sqrt().item()})