Pidoku

Quantization for the Edge

Module 29 Lesson 29.f 1h 15m Difficulty 4/5

Prerequisites 10.l, 13.b, 13.c, 13.f, 13.g, 13.h, 29.b


Before you start: words you need#

WordPlain meaning
Weight-only quantization (W4A16)Weights stored in 4 bits, activations kept in 16-bit floats. The usual choice for CPUs and GPUs.
W8A8, W4A8Weights and activations in integers. Integer-only accelerators (many NPUs) need this.
Mixed precisionDifferent tensors at different bit widths, chosen by how much each one hurts quality when squeezed.
QATQuantization-aware training: training or fine-tuning the model with quantization simulated, so it learns to cope with it.
Calibration dataA few hundred sample inputs run through the model to measure activations before quantizing it.
Palettization / codebookStoring each weight as an index into a small table of values (a “palette”), instead of as a scaled integer.
KL divergence (KLD)A measure of how far the quantized model’s next-token probabilities are from the original’s. Lower is better; 0 means identical.
Tied embeddingsThe same matrix used for the input embedding and the output head, to save parameters.

1. What is it?#

Module 13 and 10.l teach quantization in general: number formats, GPTQ and AWQ, FP8 and FP4, KV-cache quantization. This lesson is about what changes on devices, where quantization stops being an optimisation and becomes the condition for running at all:

  • Lower bits. Data-centre serving lives at 8 and 4 bits. On phones 4 bits is the norm, 2–3 bits is common for system models, and some shipped models use 2-bit weights.
  • Hardware-shaped formats. The format must match what the target’s kernels or NPU compiler accept: GGUF block types (29.b), MLX group quantization (29.c), symmetric INT4 with INT8 or INT16 activations for NPUs (29.e), palettes for Apple’s Neural Engine.
  • Whole-model budgets. Embeddings, the output head and the KV cache, which servers often leave in 16 bits, are a large share of a small model and must be squeezed too.
  • Training, not just conversion. The best on-device models are trained or fine-tuned for their quantization (QAT, distillation, adapters), not just converted.

Facts checked on 13 November 2026.


2. Why does it matter?#

  • Bytes decide everything on a device (29.a): whether the model fits the memory budget, how fast it decodes, how long it takes to download, and how much battery each token costs.
  • Quality falls off a cliff below about 3.5 bits with simple post-training methods. On a device you often need to be below that line, so you need the methods that work there.
  • The OS vendors show what is possible. Apple’s 2025 on-device model used 2-bit weights with QAT, 4-bit embeddings and an 8-bit KV cache, and recovered lost quality with low-rank adapters. Google publishes QAT checkpoints for Gemma, and says LiteRT’s 2- and 4-bit weights plus memory-mapped per-layer embeddings run Gemma 4 E2B in under 1.5 GB on some devices.
  • Mistakes are invisible until users find them. A quantized model usually produces fluent text; the damage shows up as wrong facts, broken JSON or a worse language you did not test.

3. Simple analogy#

Packing for a weekend with a cabin bag only. A data-centre model travels with a suitcase and packs everything. On a device you have the cabin bag, so you roll the clothes tightly (fewer bits), leave behind what you will not use (pruning, smaller vocabulary), keep the fragile items well wrapped (sensitive layers at more bits), and practise living out of the bag before the trip (QAT), so nothing you need is missing when you arrive.


4. Tiny example: one model, three recipes#

A 3.5B model with a 256,000-token vocabulary and tied embeddings, on a phone with 77 GB/s:

BF16 everything                      7.5 GB   ≤ 10 tok/s   does not fit a 6 GB app budget
4-bit weights, 16-bit KV (8k)        2.5 GB   ≤ 31 tok/s   fits
2-bit QAT layers, 4-bit embeddings,
  8-bit KV                           1.5 GB   ≤ 51 tok/s   fits, with room for a second model

The third recipe is roughly what Apple described for its 2025 on-device model. It is only usable because the model was trained for it; converting a 16-bit model straight to 2 bits would wreck it.


5. Technical explanation#

Where the bytes are in a small model#

In a 70B model the embeddings are a rounding error. In a 1–4B model with a modern vocabulary (150,000–260,000 tokens) they are 15–25% of the parameters, and with tied embeddings the output head reads the whole matrix for every generated token. So:

  • Quantize embeddings and the output head, usually to 4–6 bits, not 16. Apple used 4-bit embeddings; llama.cpp recipes put the output head at Q6_K; llama-quantize has --token-embedding-type and --output-tensor-type.
  • Keep rarely read weights out of DRAM. The input embedding is read one row per token, so it can be memory-mapped from flash (Gemma 4’s per-layer embeddings, 29.a); the output head cannot.
  • The KV cache at long context can match the weights (29.a). 8-bit KV is nearly free in quality for most models; 4-bit KV needs checking (13.h).

Choosing bits per tensor#

Not all tensors suffer equally. Rules of thumb that recur across llama.cpp’s recipes, MLX’s mixed predicates and published studies:

  • More bits for attn_v, ffn_down (the down projection), the first and last few layers, the output head and, in MoE models, the shared expert and router.
  • Fewer bits for ffn_gate/ffn_up and the bulk of routed experts.
  • Measure, do not guess. Run a sensitivity sweep: quantize one tensor group at a time to low bits and record KL divergence. MLX’s mlx_lm.dynamic_quant automates this; llama.cpp’s --tensor-type lets you apply the result.

Post-training methods that work at low bits#

MethodWhat it doesWhere you find it
Round-to-nearest with small groupsper-group scale (16–64 weights); simple, fastQ4_0, MLX affine, ORT builder int4 with a block size
Importance-weighted roundingweights error by measured activation sizellama.cpp imatrix (29.b), AWQ (13.c)
Second-order roundingcorrects remaining weights as each column is quantizedGPTQ (13.c), mlx_lm.gptq
Non-uniform grids and codebooksweights snap to a learned or lattice set of valuesllama.cpp I-quants; Core ML palettization; AQLM-style codebooks
Rotationsmultiply by an orthogonal (Hadamard) matrix to spread outliers before quantizingQuaRot-style methods (24.d); llama.cpp now applies Hadamard rotations to the KV cache
Distillation of scalesfine-tunes only scales and biases to match the full model’s outputsMLX DWQ

Below about 3.5 bits, plain rounding loses badly (in llama.cpp’s own table, Q2_K adds 3.5 perplexity points on Llama-3-8B against 0.18 for Q4_K_M, 29.b). Importance weighting, non-uniform grids and distillation are what keep 2–3-bit models usable.

Training for the device#

The strongest on-device models are trained knowing they will be quantized:

  • Quantization-aware training. The forward pass uses quantized weights (with a straight-through gradient), so the model learns weights that survive rounding. Apple trained its 2025 on-device model this way at 2 bits, with learnable weight clipping. Google’s Gemma QAT checkpoints (from Gemma 3) do the same at 4 bits and ship as Q4_0 GGUFs and LiteRT files.
  • Adapters to recover quality. Apple trains low-rank adapters on top of the compressed model to win back what compression lost; feature-specific adapters can be swapped at runtime on one base model.
  • Distillation. A small model trained to imitate a large teacher (13.p) tolerates quantization better than one trained from scratch on raw text, and the teacher is the natural reference for measuring damage.
  • Native low-bit models. Ternary and 1-bit models (BitNet b1.58 2B4T, 2025) are trained with {−1, 0, +1} weights from the start; ggml has TQ1_0, TQ2_0 and Q1_0 types for them. They are a research direction more than a mainstream choice in 2026 (24.d).
  • Architecture choices count as compression: grouped-query attention, sliding-window layers, KV sharing between layers (Apple’s 37.5% saving), smaller vocabularies, per-layer embeddings, and sparse models routed per prompt (29.c).

Formats per target#

TargetPractical format
llama.cpp on CPU/Metal/VulkanQ4_K_M, IQ4_XS; IQ3_*/IQ2_* with an imatrix when memory is tight; Q4_0 where a backend only accelerates legacy types
MLX on Apple GPUsaffine 4-bit group 64, mixed_3_6 or DWQ for 3-bit; mxfp4/nvfp4 to reuse data-centre checkpoints
Apple Neural Engine (Core AI / Core ML)palettized (lookup-table) or linear INT8/INT4 weights with FP16 activations
Qualcomm Hexagon, Intel and AMD NPUssymmetric INT4 or INT8 weights, per-channel or per-block scales; INT8/INT16 activations; follow the vendor’s recipe (AI Hub, OpenVINO NNCF, Ryzen AI tools)
LiteRT GPU/NPUAI Edge Quantizer recipes: INT8/INT4 and 2-bit weights, often mixed per tensor
ONNX Runtime GenAImodel builder int4 (block size, accuracy level) for CPU, CUDA, DirectML and WebGPU; QNN and OpenVINO need their providers’ formats

Apple’s server model used 3.56 bits per weight with ASTC, a GPU texture-compression format, so the GPU’s texture hardware decompresses weights for free. Reusing hardware built for something else is a recurring edge trick.

Measuring damage#

  • KL divergence against the full model on a few thousand tokens of your own traffic: the best single number (llama-perplexity --kl-divergence, 29.b; 28.e).
  • Top-token agreement: how often the quantized model’s most likely token matches the original’s.
  • Task evaluations that exercise what quantization breaks first: arithmetic, code, structured output, long-context recall, less common languages.
  • Per backend. The same quantized weights can behave differently on CPU, GPU and NPU kernels. Evaluate on each path you ship (28.b).

6. Under the hood: a byte budget for a small model#

This program splits a typical 3.5B layout (256,000-token vocabulary, tied embeddings, 30 layers, grouped-query attention with 4 KV heads) into embeddings, sensitive tensors (attn_v, ffn_down) and the rest, then prices six recipes. Bit widths include block scales (4.5 for a 4-bit format, 6.5 for a 6-bit one). The model is illustrative, not a specific product.

Go
// budget.go — where the bytes go in a small on-device model, under different recipes.
// The model is a made-up but typical 3.5B layout with a large vocabulary and tied embeddings.
package main

import "fmt"

func main() {
	const (
		vocab, hidden, layers, ffn = 256000, 2560, 30, 10240
		kvHeads, headDim           = 4, 128
		ctx                        = 8192
		bwGBs                      = 77.0 // phone bandwidth (A19 Pro class)
	)
	embed := float64(vocab * hidden) // tied: also the output head
	attnV := float64(hidden * kvHeads * headDim)
	attnOther := float64(2*hidden*hidden + hidden*kvHeads*headDim) // q, o, k
	ffnDown := float64(ffn * hidden)
	ffnOther := float64(2 * ffn * hidden) // gate, up
	perLayer := attnV + attnOther + ffnDown + ffnOther
	fmt.Printf("params: embeddings %.2fB (%.0f%%), layers %.2fB, total %.2fB\n\n",
		embed/1e9, 100*embed/(embed+perLayer*layers), perLayer*layers/1e9, (embed+perLayer*layers)/1e9)

	type recipe struct {
		name                        string
		embBits, sensBits, restBits float64 // sens = attn_v and ffn_down
		kvBits                      float64
	}
	recipes := []recipe{
		{"BF16 everything", 16, 16, 16, 16},
		{"8-bit weights (Q8_0-like)", 8.5, 8.5, 8.5, 16},
		{"4-bit uniform", 4.5, 4.5, 4.5, 16},
		{"4-bit, 6-bit sensitive + embed", 6.5, 6.5, 4.5, 16},
		{"same + 8-bit KV", 6.5, 6.5, 4.5, 8.5},
		{"2-bit QAT layers, 4-bit embed, 8-bit KV", 4.5, 2.5, 2.5, 8.5},
	}
	fmt.Println("recipe                                    weights   KV(8k)   total   read/token  ceiling")
	for _, r := range recipes {
		embGB := embed * r.embBits / 8 / 1e9
		layGB := layers * (attnV*r.sensBits + ffnDown*r.sensBits + (attnOther+ffnOther)*r.restBits) / 8 / 1e9
		kvGB := 2 * layers * kvHeads * headDim * ctx * r.kvBits / 8 / 1e9
		read := layGB + embGB + kvGB // tied output head reads the whole embedding matrix every token
		fmt.Printf("%-40s %6.2f GB %6.2f GB %6.2f GB %8.2f GB %6.0f tok/s\n",
			r.name, embGB+layGB, kvGB, embGB+layGB+kvGB, read, bwGBs/read)
	}
}

Output:

params: embeddings 0.66B (19%), layers 2.83B, total 3.49B

recipe                                    weights   KV(8k)   total   read/token  ceiling
BF16 everything                            6.97 GB   0.50 GB   7.48 GB     7.48 GB     10 tok/s
8-bit weights (Q8_0-like)                  3.70 GB   0.50 GB   4.21 GB     4.21 GB     18 tok/s
4-bit uniform                              1.96 GB   0.50 GB   2.46 GB     2.46 GB     31 tok/s
4-bit, 6-bit sensitive + embed             2.33 GB   0.50 GB   2.83 GB     2.83 GB     27 tok/s
same + 8-bit KV                            2.33 GB   0.27 GB   2.60 GB     2.60 GB     30 tok/s
2-bit QAT layers, 4-bit embed, 8-bit KV    1.25 GB   0.27 GB   1.52 GB     1.52 GB     51 tok/s

How to read it:

  • Embeddings are a fifth of this model, and in the 2-bit recipe they are 30% of the weight bytes (0.37 of 1.25 GB). On small models, the vocabulary is a quantization target.
  • Protecting sensitive tensors costs about 15% more bytes (2.33 vs 1.96 GB) and 4 tokens per second of ceiling. That is usually the best quality-per-byte trade available.
  • 8-bit KV buys back most of that cost at an 8k context, at almost no quality cost.
  • The 2-bit recipe nearly doubles the decode ceiling of the 4-bit one. Whether it is usable depends entirely on how the model was trained.

7. Performance implications#

  • Fewer bits, faster decode, but not proportionally. Unpacking low-bit or codebook formats costs instructions; I-quants and palettes can be compute-bound on weak CPUs. Measure tokens per second per format on the target.
  • Prefill gains little from weight quantization unless activations are quantized too and the hardware has fast integer or FP8/FP4 matrix units (NPUs, M5 Neural Accelerators).
  • W8A8 on NPUs makes prefill much faster than W4A16 on a CPU, but activation quantization is where outlier problems bite (13.d); rotations and per-token scales help.
  • Smaller files load faster and leave more memory for other apps, which lowers the chance the OS kills yours in the background.

8. Production implications#

  • Decide the target device class first, then the format, then the method. A format your target’s fast kernels do not support is slow however small it is.
  • Prefer QAT or vendor-published quantized checkpoints (Gemma QAT, vendor model zoos) over converting yourself at 2–3 bits.
  • Keep the unquantized reference and an evaluation set that represents your users. Every new quantization, runtime or backend version is re-evaluated against it (28.d).
  • Ship more than one quantization when the device range is wide: a 4-bit build for capable devices, a 2–3-bit build or a smaller model for the rest, and the cloud for the bottom tier (29.g).
  • Record the recipe (method, calibration data, per-tensor bits, tool version) with the model file. You will need it when quality complaints arrive.

9. Common mistakes#

  1. Leaving embeddings and the output head at 16 bits on a small model with a large vocabulary.
  2. Using perplexity alone. It averages away failures in code, maths and structured output; use KLD and task evaluations.
  3. Calibrating on the wrong data: English prose for a multilingual or code assistant.
  4. Converting to 2 bits after training and expecting the quality of a QAT model.
  5. Quantizing activations for an NPU without handling outliers, then blaming the NPU.
  6. Evaluating on one backend and shipping on another.

10. Hands-on exercise#

  1. Run budget.go. Untie the embeddings (add a separate output head at the same bits) and see how much the 2-bit recipe grows.
  2. Change the vocabulary to 32,000. How does the share of embeddings change, and which recipe now wins on quality per byte?
  3. With llama.cpp, quantize a 1–4B model to Q4_K_M, then again with --token-embedding-type q8_0 and --output-tensor-type q8_0, then with both at q4_k. Compare size and KL divergence.
  4. Run mlx_lm.dynamic_quant on a small model and read which layers it keeps at higher precision. Do they match the rules of thumb in section 5?
  5. Take a Gemma QAT Q4_0 GGUF and a Q4_0 you make yourself from the BF16 weights. Compare their KL divergence against BF16 on the same text.

11. Interview questions#

  1. Why do embeddings and the output head matter more for quantizing a 2B model than a 70B model?
  2. Which tensors do quantization recipes protect, and how would you check that on a new architecture?
  3. Why are QAT and distillation more important on devices than in the data centre?
  4. An NPU needs W8A8. What goes wrong when you quantize activations, and how do you mitigate it?
  5. Design the quantization plan for an assistant that must run on phones with 8 GB and 16 GB of RAM.

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in