On this page
A 27-billion-parameter model needs 54 GB just to store its BF16 weights, far too large for a single 24 GB GPU. Pack those weights into 4-bit integer codes and the raw payload drops to 13.5 GB (13.922 GB with one FP16 scale per 128 weights, or 12.966 GiB), bringing a 24 GB card into play once you budget remaining VRAM for preserved FP16 tensors, KV cache, and workspace. You quantize the model, see perplexity barely move, and ship; two weeks later a tool integration starts breaking because fluent prose now hides malformed JSON arguments. (On real checkpoints such as Qwen3.6-27B, which also carries a vision encoder and hybrid recurrent/attention layers, always inspect the actual tensor inventory rather than multiplying the headline parameter count by 0.5 bytes.[1])
Three names dominate every quantization discussion, and engineers routinely mix their categories:
- GPTQ and AWQ are algorithms for choosing good low-bit codes (GPTQ via Hessian error compensation; AWQ via activation-aware channel scaling).
- GGUF is a binary container format (from
llama.cpp) that bundles metadata, tokenizer tables, and typed tensor blocks for local execution.
Quantizing static weights cuts storage and decode memory traffic, while leaving activations and the KV cache untouched unless you quantize them separately.
From floating-point values to four-bit codes
Suppose a weight is and each integer step represents . Dividing gives , rounding stores integer code , and multiplying back reconstructs with rounding error . A general affine quantizer formalizes this with a positive scale and integer zero-point :
Scale sets the spacing between representable marks, while maps real zero to an integer code. Stretching to cover an outlier coarsens every ordinary weight; shrinking clips extreme values. To actually save RAM, you also have to pack those 4-bit codes two nibbles per byte (here using a symmetric signed range):
import struct
def encode(weights):
scale = (max(abs(w) for w in weights) / 7) or 1.0
codes = [max(-7, min(7, round(w / scale))) for w in weights]
nibbles = [q & 15 for q in codes]
if len(nibbles) % 2:
nibbles.append(0)
payload = bytes(nibbles[i] | (nibbles[i + 1] << 4) for i in range(0, len(nibbles), 2))
return struct.pack("<Id", len(weights), scale) + payload
def decode(blob):
count, scale = struct.unpack("<Id", blob[:12])
codes = []
for byte in blob[12:]:
for n in (byte & 15, byte >> 4):
codes.append(n - 16 if n >= 8 else n)
codes = codes[:count]
return codes, [q * scale for q in codes]
weights = [0.15, -1.22, 2.40, -0.45, 0.73]
blob = encode(weights)
codes, restored = decode(blob)
mae = sum(abs(w - r) for w, r in zip(weights, restored)) / len(weights)
print("codes:", codes, "payload:", blob[12:].hex(), f"({len(blob) - 12}B codes, {len(blob)}B total)")
print("restored:", [round(w, 3) for w in restored], "MAE:", round(mae, 3))codes: [0, -4, 7, -1, 2] payload: c0f702 (3B codes, 15B total)
restored: [0.0, -1.371, 2.4, -0.343, 0.686] MAE: 0.091![A shared signed INT4 grid maps five weights to codes [0, −4, 7, −1, 2]. The codes pack low nibble first into bytes C0, F7, and 02, with a zero high-nibble pad in the last byte. Decoding uses scale 2.4/7 and gives mean absolute error 0.091; the count and FP64 scale add a 12-byte header.](https://assets.leetllm.com/v1/43ccdc15e7c7/fundamentals/model-quantization-gptq-awq-gguf/illustrations/_generated/quantization_pipeline_dark.png)
Symmetric, asymmetric, and per-group grids
- Symmetric (): with . No zero-point subtraction during dequantization.
- Asymmetric (): Covers an uneven interval containing zero with and . Useful for skewed weights and nonnegative ReLU outputs (note that SiLU takes negative values). Both GPTQ and AWQ commonly support asymmetric grids with zero-points.[2][3]
- Granularity (per-tensor vs. per-channel vs. per-group): Sharing one scale across a whole tensor lets one outlier crush precision everywhere. Per-group quantization assigns a fresh scale every weights (typically ), isolating outliers for just extra bits per weight ( total). Remember that group scales belong inside the dot-product sum: each group scales its own partial sum!
low, high = -1.0, 2.0
scale = (high - low) / 15
z_unsigned = round(-low / scale)
z_signed = -8 - round(low / scale)
values = [-2.0, -1.0, 0.0, 0.73, 2.0, 3.0]
u_codes = [max(0, min(15, round(w / scale) + z_unsigned)) for w in values]
restored = [round(scale * (q - z_unsigned), 2) for q in u_codes]
print(f"unsigned Z={z_unsigned}, signed Z={z_signed}")
print("codes:", u_codes, "-> restored:", restored)unsigned Z=5, signed Z=-3
codes: [0, 0, 5, 9, 15, 15] -> restored: [-1.0, -1.0, 0.0, 0.8, 2.0, 2.0]
Two checkpoints both claim INT4 precision, yet one is 10% larger on disk. What should you inspect first?
Answer
Check group size, zero-point storage, which layers were kept in FP16/BF16 (embeddings, LM head, norms), alignment padding, and container metadata.
Why 4-bit weights speed up decode (W4A16)
Why compress weights to 4 bits if activations stay in 16-bit floating point? During low-batch decode, linear layers run at : just 1 FLOP/byte in BF16, barely of an A100 80GB SXM's 312 dense FP16 TFLOPS compute peak (2,039 GB/s HBM, ridge point 153 FLOPs/byte).[4]
W4A16 cuts HBM weight traffic roughly by reading packed 4-bit codes and unpacking them inside a fused kernel right before the FP16 multiply-accumulate, avoiding writing an expanded FP16 matrix back to HBM.[5] Without fusion, a standalone dequantization pass gives away most of that bandwidth gain (on Ascend 910, where unpacking and multiplication communicate through global memory, W4A16 reached at most over FP16).[6] When prompts are long (prefill) or batches grow large, weight traffic stops dominating; accelerating compute then requires quantizing activations too, via integer W8A8 with SmoothQuant outlier migration[7] or native FP8.[8] Keep KV cache precision (such as FP8 KV cache in vLLM[9]) distinct from weight precision: quantizing weights does not shrink any user's KV cache, though shrinking 54 GB of BF16 weights to 13.92 GB on an 80 GB card (with an 8 GB reserve) expands the remaining KV pool from 18 GB to 58.08 GB (raising 5,120-token capacity from 53 to 173 users, or 36 to 119 including recurrent state).


GPTQ: Hessian-aware error compensation
Naive round-to-nearest treats every weight equally. In reality, weights multiply activations , so an error of on a high-energy channel damages layer outputs far more than on a quiet channel. GPTQ[2] directly minimizes layer output reconstruction error:
After rounding column to , GPTQ compensates the still-unquantized columns using the active Hessian inverse :
To avoid repeated inversions, GPTQ adds diagonal damping (, typically 1% of mean diagonal), computes a single upper Cholesky factor where , and batches deferred updates in 128-column blocks.[10] Sorting columns by descending diagonal energy (act-order / desc_act) quantizes high-energy channels first while the most free weights remain to absorb their error. (In Hugging Face Transformers, modern GPTQ tooling uses gptqmodel rather than legacy AutoGPTQ.[11])
Watch both the power and the risk of Hessian compensation on two weights: compensation cuts calibration error, yet can worsen error on an out-of-distribution input!
import numpy as np
w = np.array([1.2, 0.61])
X = np.array([[5.0, 4.0], [1.0, 1.0]])
H_inv = np.linalg.inv(2 * X @ X.T)
q0 = np.rint(w[0])
updated = w - (w[0] - q0) / H_inv[0, 0] * H_inv[:, 0]
naive = np.rint(w)
compensated = np.array([q0, np.rint(updated[1])])
err = lambda cand, inp: float(np.sum(((w - cand) @ inp) ** 2))
print("Compensated continuous w:", np.round(updated, 3).tolist(), "-> rounded:", compensated.tolist())
print(f"Calibration SSE: naive={err(naive, X):.3f}, compensated={err(compensated, X):.3f}")
print(f"Held-out I SSE: naive={err(naive, np.eye(2)):.3f}, compensated={err(compensated, np.eye(2)):.3f}")Compensated continuous w: [1.0, 1.51] -> rounded: [1.0, 2.0]
Calibration SSE: naive=0.540, compensated=0.500
Held-out I SSE: naive=0.192, compensated=1.972![In the weight plane, fixed calibration inputs make the SSE contours elongated along correlated weight changes. Rounding w₀ from 1.2 to 1 and compensating the still-free w₁ moves it from 0.61 to 1.51, then GPTQ rounds it to 2. Calibration outputs are [6.61, 5.41] before rounding, [6, 5] after independent rounding, and [7, 6] after compensation. Calibration SSE falls from 0.5402 to 0.5002; held-out identity SSE rises from 0.1921 to 1.9721.](https://assets.leetllm.com/v1/3deb998947fa/fundamentals/model-quantization-gptq-awq-gguf/illustrations/_generated/gptq_awq_mechanics_dark.png)
AWQ: activation-aware channel scaling
Instead of compensating after rounding, AWQ[12] protects salient channels before rounding by rescaling coordinates. It ranks input channels by average absolute activation magnitude and inserts an identity pair :
Multiplying a salient weight column by gives it finer effective step size , while fuses into the preceding LayerNorm or linear layer so serving stays uniform 4-bit.[13] Scaling too aggressively widens the group's dynamic range and hurts neighboring channels, so AWQ grid-searches over (typically 20 steps) to minimize layer output MSE, followed by clipping. (For modern AWQ export and serving, check maintained stacks such as vLLM's LLM Compressor rather than unmaintained legacy packages.[14][3])
import numpy as np
W = np.array([[0.3, 2.0]])
cal = np.array([[10.0, 8.0, -10.0, -8.0], [1.0, -1.0, 1.0, -1.0]])
held = np.array([[9.0, -9.0], [0.5, -0.5]])
def quantize_scaled(factor):
a = np.array([factor, 1.0])
scaled = W * a
step = float(np.max(np.abs(scaled))) / 7
return np.clip(np.rint(scaled / step), -7, 7) * step / a
mse = lambda cand, X: float(np.mean(((W - cand) @ X) ** 2))
for f in (1, 2, 4, 8):
cand = quantize_scaled(f)
print(f"scale={f}: cal MSE={mse(cand, cal):.6f}, held-out MSE={mse(cand, held):.6f}")scale=1: cal MSE=0.016735, held-out MSE=0.016531
scale=2: cal MSE=0.016735, held-out MSE=0.016531
scale=4: cal MSE=0.016735, held-out MSE=0.016531
scale=8: cal MSE=0.003265, held-out MSE=0.000816![For W = [0.3, 2], the selected AWQ channel transform uses D = diag(8, 1), so W times D is [2.4, 2] and the first activation row divides by 8. Each calibration column keeps the same product sum [5, 0.4, minus 1, minus 4.4] before rounding. Factors 1, 2, and 4 reconstruct the first weight as 2/7; factor 8 reconstructs it as 0.3 and moves the neighbor to 2.0571429. Calibration MSE falls to 0.003265 and held-out MSE is 0.000816 across the four-factor sweep.](https://assets.leetllm.com/v1/0b6968f3be8d/fundamentals/model-quantization-gptq-awq-gguf/illustrations/_generated/awq_channel_coordinate_transform_dark.png)
GGUF containers, k-quants, and CPU-GPU offloading
GGUF[15][16] is the self-describing binary format used by llama.cpp, packing architecture metadata, tokenizer tables, chat templates, and 32-byte-aligned tensor blocks into one memory-mappable file (plus a separate mmproj file for multimodal vision encoders[17]).
Its hierarchical k-quant blocks show why "4-bit" rarely means 4.0 bits per weight: a Q4_K super-block holds 256 weights in 8 sub-blocks of 32, taking 128 code bytes + 12 packed bytes of 6-bit local scales/mins + 4 bytes for two FP16 super-scales = 144 bytes (4.5 bits/weight), reconstructing weights as .[18] A preset like Q4_K_M uses Q4_K for most tensors while keeping sensitive value/down projections at Q6_K.[19]

When a GGUF exceeds GPU VRAM, llama.cpp's -ngl (--n-gpu-layers) offloads trailing blocks (including the output layer in standard builds) to GPU while keeping remaining early blocks on CPU.[20] For a 40-block model with -ngl 24, blocks 17 through 39 plus the output layer land on GPU.
blocks, requested = 40, 24
start = max(blocks + 1 - requested, 0) # output layer takes slot `blocks`
gpu_blocks = list(range(start, blocks))
print(f"40-block -ngl 24 -> GPU blocks {gpu_blocks[0]}..{gpu_blocks[-1]} + output layer")
# Capacity-bounded trailing placement with a 2,000 MB KV/workspace reserve:
layer_mb, device_mb, reserve_mb = [1000, 2000, 1500, 500], 6000, 2000
used, gpu_idx = 0, []
for idx in reversed(range(len(layer_mb))):
if used + layer_mb[idx] > device_mb - reserve_mb:
break
gpu_idx.append(idx)
used += layer_mb[idx]
cpu_idx = [i for i in range(len(layer_mb)) if i not in gpu_idx]
print(f"Budget fit: CPU={cpu_idx}, GPU={sorted(gpu_idx)} ({used} MB + {reserve_mb} MB reserve)")40-block -ngl 24 -> GPU blocks 17..39 + output layer
Budget fit: CPU=[0], GPU=[1, 2, 3] (4000 MB + 2000 MB reserve)
python convert_hf_to_gguf.py /path/to/checkpoint --outfile model-bf16.gguf --outtype bf16
./build/bin/llama-quantize model-bf16.gguf model-Q4_K_M.gguf Q4_K_MEvaluating quantized models beyond perplexity
As bit width drops from 8 bits to 4 bits to 2 bits, output MSE rises smoothly at first and then falls off a cliff (narrow symmetric 2-bit leaves only codes !):
import numpy as np
W = np.array([[0.3, -1.2, 2.0, 0.7]])
X = np.array([[2.0, -1.0, 3.0], [1.0, 2.0, -1.0], [-1.0, 0.5, 2.0], [0.2, -2.0, 1.0]])
for bits in (8, 4, 2):
qmax = 2 ** (bits - 1) - 1
scale = float(np.max(np.abs(W))) / qmax
restored = np.clip(np.rint(W / scale), -qmax, qmax) * scale
mse = float(np.mean(((W - restored) @ X) ** 2))
print(f"{bits}-bit: {(W.size * bits + 7) // 8} code bytes, held-out MSE={mse:.6f}")8-bit: 4 code bytes, held-out MSE=0.000204
4-bit: 2 code bytes, held-out MSE=0.067010
2-bit: 1 code bytes, held-out MSE=1.007200![Comparison of 8-bit, 4-bit, and 2-bit symmetric quantization on four weights [0.3, -1.2, 2.0, 0.7]. Left aligned number lines show original weights snapping to 8-bit [0.2992, -1.1969, 2, 0.6929], 4-bit [0.2857, -1.1429, 2, 0.5714], and 2-bit [0, -2, 2, 0] with ideal code payloads 4, 2, and 1 bytes. Right bar chart compares held-out output MSE across three activation columns: 0.000204 at 8-bit, 0.067010 at 4-bit, and 1.007200 at 2-bit (a 15x jump).](https://assets.leetllm.com/v1/a5c9bc733123/fundamentals/model-quantization-gptq-awq-gguf/illustrations/_generated/precision_comparison_dark.png)

| Symptom after quantization | Check first |
|---|---|
| JSON or code breaks while prose looks fluent | Reloaded artifact, tokenizer/template, decoding settings, and paired task evals before tuning calibration data |
| Decode stays slow despite 4-bit weights | Device placement, fused vs. standalone kernel dispatch, KV traffic, batch size, and queueing against BF16 |
| Prefill stays slow | Whether compute or queueing dominates (weight compression rarely fixes compute-bound prefill) |