Danila (Dayfing)
Back to writing
2,064 words10 min

GGUF quantization guide: Q4_K_M vs Q5_K_M vs Q8_0 and IQ4_XS

Start with Q4_K_M when you need a model to fit comfortably inside consumer VRAM, step up to Q5_K_M or Q6_K for coding, tool calling, and non-English text, and reserve Q8_0 as the near-lossless baseline when memory is abundant. When a larger model barely misses your memory ceiling, IQ4_XS calibrated with an importance matrix (llama-imatrix) saves roughly 9% of weight memory over Q4_K_M while preserving comparable perplexity, whereas dropping to 3-bit IQ3_M is only worth it when a larger parameter count beats a cleaner 4-bit smaller model. Weight compression is only half the budget, so plan the remaining VRAM for context and quantized KV caches using the local LLM hardware guide.

How K-quants compress weights: Q4_K_M, Q5_K_M, Q6_K, and Q8_0

GGUF quantization stores floating-point weight matrices as small integer groups paired with scaling factors. Legacy Q8_0 divides each tensor into blocks of 32 weights and attaches one 16-bit floating-point scale (fp16) per block, landing at 8.50 bits per weight (bpw). Because every weight keeps 8 bits of integer resolution, Q8_0 tracks the F16 or BF16 original within noise floor across almost all tasks, at roughly half the footprint.

K-quants (Q4_K, Q5_K, Q6_K) reduce metadata overhead by grouping 256 weights into a super-block divided into 8 sub-blocks of 32 weights (or 16 sub-blocks of 16 in certain layouts). Instead of storing uncompressed fp16 scales and minimums for every sub-block, a K-quant quantizes the sub-block scales and minimums themselves to 4 or 6 bits and stores only two fp16 super-block factors (d and dmin). That nested scaling keeps effective bit width tight without losing local dynamic range when a single weight row contains an outlier.

The _S, _M, and _L suffixes tell llama-quantize how aggressively to mix higher-precision tensors into sensitive layers rather than applying a single format everywhere. Unless you pass --pure, the llama.cpp quantize documentation explains that llama-quantize assigns elevated precision to attention value projections (attn_v), feed-forward down projections (ffn_down), token embeddings, and the output head:

  • Q4_K_S (4.67 bpw on Llama-3.1-8B): Uses Q4_K across most tensors and promotes fewer sensitive layers, prioritizing smaller file size over margin.
  • Q4_K_M (4.89 bpw on Llama-3.1-8B): Uses Q4_K as the base and promotes half of attn_v and ffn_down tensors plus output.weight to Q6_K, making it the standard 4-bit default.
  • Q5_K_M (5.70 bpw on Llama-3.1-8B): Uses Q5_K across most matrices and promotes half of attn_v and ffn_down to Q6_K, trimming nearly all noticeable 4-bit reasoning drift.
  • Q6_K (6.56 bpw on Llama-3.1-8B): Quantizes weights to 6 bits with 8-bit quantized sub-block scales, sitting close to Q8_0 quality while saving roughly 23% of weight memory compared with Q8_0.

How I-quants and llama-imatrix change the trade-off

While K-quants place weights onto uniform scalar grids within each sub-block, I-quants (IQ4_XS, IQ4_NL, IQ3_M, IQ2_M) borrow concepts from vector quantization and non-linear lookup tables. IQ4_NL maps 4-bit indices onto a non-linear codebook shaped around typical neural weight distributions instead of evenly spaced integers. IQ4_XS builds on that non-linear grid with super-block scaling to compress Llama-3.1-8B down to 4.46 bpw (4.17 GiB), roughly 410 MiB smaller than Q4_K_M on an 8B model and several gigabytes smaller on 70B weights.

Below 4 bits, uniform grids break down quickly because 8 or 4 discrete levels per block cannot track multi-dimensional weight correlations. IQ3_M (3.76 bpw) and IQ2_M encode groups of weights as indices into precomputed vector codebooks coupled with sign bits and sub-block scales. That vector packing squeezes more expressive power into 2-bit and 3-bit budgets, though unpacking lookup tables can trade away decode throughput on CPU-only hosts or older GPUs compared with straightforward integer kernels.

An importance matrix (imatrix) shifts quantization precision toward the weights that actually fire during inference. Running llama-imatrix passes a calibration corpus through the unquantized F16 or BF16 model and accumulates squared activation magnitudes per weight channel. When llama-quantize --imatrix searches for optimal scales or codebook matches, channels with large activation scores receive higher optimization weight. Both I-quants and K-quants benefit from an imatrix, and for IQ3_M or smaller formats an imatrix is essential to avoid collapsing rare output paths.

Quant type Bits/weight Llama-3.1-8B size Prompt eval (t/s @ 512) Generation (t/s @ 128) Typical role
IQ3_M 3.76 3.52 GiB 768.7 70.2 Tight VRAM fallback with imatrix
IQ4_XS 4.46 4.17 GiB 771.8 77.5 Compact 4-bit alternative to Q4_K_M
Q4_K_S 4.67 4.36 GiB 818.6 76.7 Minimalist 4-bit K-quant
Q4_K_M 4.89 4.58 GiB 821.8 71.9 Default general-purpose 4-bit quant
Q5_K_M 5.70 5.33 GiB 758.7 67.2 Coding, tool calling, multilingual work
Q6_K 6.56 6.14 GiB 812.0 58.7 High-accuracy production on mid VRAM
Q8_0 8.50 7.95 GiB 865.1 50.9 Reference quality and calibration baseline
F16 16.00 14.96 GiB 923.5 29.2 Unquantized conversion source

Figures in the table come from the Llama-3.1-8B benchmark published in the llama.cpp quantize README. Notice how decode generation speed peaks around 4-bit formats (70–78 t/s) and drops toward F16 (29.2 t/s) because autoregressive token generation is bound by memory bandwidth rather than compute.

Why coding, tool calling, and multilingual output degrade faster below 4 bits

Casual English conversation stays legible even under aggressive 3-bit compression because everyday prose has high redundancy and wide logit margins between plausible next words. When quantization nudges a probability from 0.62 to 0.54, the sampler still picks a coherent phrasing and readers barely notice.

Structured and multilingual tasks have razor-thin logit margins where a single flipped token ruins the entire output. Code completion requires exact punctuation, indentation depth, variable spelling, and closing delimiters across hundreds of tokens. Tool calling demands strict JSON keys, escaped strings, enum values, and numeric types that match a schema without hallucinated fields. Non-English languages, especially Cyrillic, Arabic, and CJK scripts, rely on longer subword sequences and lower-frequency token embeddings whose rows sit further down the activation distribution.

Three habits protect those fragile capabilities when memory is tight:

  • Keep token embeddings and the output head high precision: Use --output-tensor-type q6_k (or --leave-output-tensor) and --token-embedding-type q5_k in llama-quantize so final logit projections do not inject rounding noise across the whole vocabulary.
  • Calibrate imatrix on representative workloads: Building an imatrix solely on English Wikipedia under-represents code syntax, JSON tool traces, and target-language grammar; mix code snippets, tool-call transcripts, and multilingual samples into the calibration file.
  • Test with task evals instead of vibes: Run deterministic coding, JSON-schema, and multilingual benchmarks against each candidate quant before shipping, following the workflow in the AI agent evals guide.

Memory footprint math across 8B, 32B, and 70B models

Before choosing a quant, add up weights, KV cache, and runtime buffers (typically 0.5–1.5 GiB for CUDA/Metal compute graphs). Approximate weight footprint scales directly from bits per weight:

Weight size (GiB) ≈ (Parameters × bpw) / (8 × 1024^3) + 0.1–0.4 GiB metadata

8B  @ Q4_K_M (4.89 bpw):  ~4.58 GiB
8B  @ Q5_K_M (5.70 bpw):  ~5.33 GiB
32B @ IQ4_XS (4.46 bpw): ~16.8 GiB
32B @ Q4_K_M (4.89 bpw): ~18.5 GiB
32B @ Q5_K_M (5.70 bpw): ~21.5 GiB
70B @ IQ3_M  (3.76 bpw): ~31.0 GiB
70B @ Q4_K_M (4.89 bpw): ~40.1 GiB (43.1 GB decimal)
70B @ Q6_K   (6.56 bpw): ~53.8 GiB

On a 24 GB GPU such as an RTX 3090 or RTX 4090, an 8B model fits at Q8_0 (~8 GiB) with 14+ GiB left for long contexts and concurrent requests. A 32B dense model tells a sharper story: Q5_K_M (~21.5 GiB) fills nearly the entire 24 GB card before any KV cache is allocated, forcing partial layer offload to system RAM. Stepping down to Q4_K_M (~18.5 GiB) or IQ4_XS (~16.8 GiB) frees 4.5–6.0 GiB on the GPU, keeping 100% of layers in VRAM alongside a healthy context window.

For 70B models, Q4_K_M (~40.1 GiB) fits cleanly across dual 24 GB GPUs (48 GB total) or a 64 GB Apple Silicon machine, whereas Q6_K (~53.8 GiB) pushes onto 96–128 GB unified memory or multi-GPU servers. When a model spills onto system RAM through partial -ngl offloading, decode speed falls straight to host memory bandwidth, which is why tuning dual-channel or multi-channel RAM matters as explained in the DDR5 memory guide.

Quantizing the KV cache: q8_0 vs f16

Every active context token stores Key and Value tensors across all attention layers. For a 32B-class GQA model with 64 layers, 8 KV heads, and head dimension 128, a single f16 KV token takes:

2 × 64 × 8 × 128 × 2 bytes = 262,144 bytes (256 KiB/token)
32,768 tokens @ f16        = 8.00 GiB per sequence
32,768 tokens @ q8_0       ≈ 4.25 GiB per sequence (~53% of f16)

In llama.cpp, KV cache quantization requires Flash Attention (-fa on). Enabling -ctk q8_0 -ctv q8_0 (--cache-type-k q8_0 --cache-type-v q8_0) cuts KV memory nearly in half with negligible perplexity change across most models. Keep -ctk and -ctv identical rather than setting keys to q4_0: attention dot products are far more sensitive to key quantization error, and mixed types can bypass optimized GPU kernels on some backends. Reserve q4_0 KV cache only for emergency memory crunches on retrieval tasks where you have verified zero context-recall regression.

End-to-end llama-imatrix, llama-quantize, and llama-perplexity workflow

Always quantize from an unquantized BF16 or F16 GGUF rather than requantizing an existing 4-bit file (--allow-requantize compounds rounding error). Start by converting the Hugging Face checkpoint, building an importance matrix, and generating your target quants:

# 1. Convert source weights to BF16 GGUF
python convert_hf_to_gguf.py /models/Qwen3-32B \
  --outfile qwen3-32b-bf16.gguf --outtype bf16

# 2. Generate calibration importance matrix (mix prose, code, JSON, target languages)
./build/bin/llama-imatrix \
  -m qwen3-32b-bf16.gguf \
  -f calibration-mixed.txt \
  -o qwen3-32b.imatrix.gguf \
  --chunk 512 -ngl 99

# 3. Quantize to IQ4_XS and Q5_K_M using the imatrix
./build/bin/llama-quantize --imatrix qwen3-32b.imatrix.gguf \
  qwen3-32b-bf16.gguf qwen3-32b-IQ4_XS.gguf IQ4_XS

./build/bin/llama-quantize --imatrix qwen3-32b.imatrix.gguf \
  --output-tensor-type q6_k \
  qwen3-32b-bf16.gguf qwen3-32b-Q5_K_M.gguf Q5_K_M

Next, measure both perplexity (PPL) and Kullback-Leibler divergence (KLD) with llama-perplexity. Raw perplexity can occasionally dip by chance on a quantized model even while output distributions drift, whereas KL divergence compares the quantized model's full token probability distribution directly against the BF16 baseline (0.0 means zero drift):

# Step A: Save baseline logits from the BF16 model (warning: .kld files are 10-40+ GB)
./build/bin/llama-perplexity \
  -m qwen3-32b-bf16.gguf \
  -f wikitext-2-raw/wiki.test.raw \
  -c 2048 -ngl 99 \
  --kl-divergence-base baseline_logits.kld

# Step B: Measure KLD and PPL shift on each quantized artifact
./build/bin/llama-perplexity \
  -m qwen3-32b-IQ4_XS.gguf \
  --kl-divergence-base baseline_logits.kld \
  --kl-divergence -c 2048 -ngl 99

Watch both mean KLD and the 99.9th-percentile spike: tight mean KLD with sharp tail spikes often points to specific sensitive tokens or tool-call syntax breaking under aggressive compression. Once a quant clears your KLD threshold and task evals, serve it with q8_0 KV caching enabled, as detailed in our local LLM inference servers guide:

llama-server -m qwen3-32b-IQ4_XS.gguf \
  --host 127.0.0.1 --port 8080 \
  -c 32768 -np 2 -ngl all \
  -fa on -ctk q8_0 -ctv q8_0

Which GGUF quant to choose: practical decision checklist

  • Choose Q8_0 (8.50 bpw) when the model easily fits in VRAM with room for full context, or when you need a local reference baseline without running BF16.
  • Choose Q6_K (6.56 bpw) when you want near-Q8_0 fidelity on strict JSON schemas, complex codebases, or multilingual agents while saving ~23% VRAM.
  • Choose Q5_K_M (5.70 bpw) as the primary daily workhorse for coding assistants and tool-calling agents whenever Q4_K_M leaves spare VRAM.
  • Choose Q4_K_M (4.89 bpw) as the balanced default when fitting the next size class up (for example, 32B instead of 14B) on 24 GB GPUs.
  • Choose IQ4_XS with imatrix (4.46 bpw) when Q4_K_M overflows your VRAM by 1–3 GiB and you want 4-bit quality without spilling layers onto system RAM.
  • Choose IQ3_M with imatrix (3.76 bpw) only when stepping up in parameter count clearly outperforms a Q5_K_M or Q6_K smaller model on your own evaluation suite, and always validate JSON schemas and tool outputs after quantizing.

More