Overview

3 Choosing What to Quantize and at What Granularity

This chapter explains that quantization should be chosen by tensor type, because weights, activations, and transformer KV caches behave very differently. Weights are frozen, usually centered near zero, and are relatively forgiving, so they are the easiest target and often yield large memory savings with little accuracy loss. Activations are harder because their ranges change with each input and they often contain outliers, while the KV cache is a special transformer memory that grows with sequence length and can become a major bottleneck in long-context inference.

For weights, the chapter shows that per-channel quantization is usually better than per-tensor quantization because a single global scale wastes precision when different channels have different ranges. The same logic extends to low-bit settings where group-wise quantization becomes important: smaller groups can dramatically reduce error at modest metadata cost, especially for INT4. The chapter also emphasizes that memory layout matters, since grouping should follow the contiguous axis to keep kernels efficient, and that sub-byte packing introduces additional implementation constraints. In practice, the best choice depends on the model architecture, bit-width, and hardware support.

For activations, the key issue is calibration under dynamic, input-dependent distributions, which makes static ranges fragile when data shifts. Dynamic and per-token quantization can recover much better accuracy by adapting to each input or each token position, especially in transformers where token importance varies within a sequence. For KV caches, the chapter argues for an asymmetric strategy: keys behave like channel-structured data and benefit from per-channel quantization, while values vary more by token and benefit from per-token quantization. The chapter closes with a practical decision framework: quantize weights almost always, add activation quantization when speed matters, treat KV cache quantization as essential for long contexts, and choose granularity based on the structure of the data, the model, and the runtime.

ResNet-18 first conv layer weight distribution
ResNet-18 first conv layer weight distribution
Most channels in ResNet-18's conv1 have maximum weights well below the global max of 1.016 (left), using only 20–50% of the integer range under per-tensor quantization (right)—the inefficiency that per-channel quantization eliminates.
Most channels in ResNet-18's conv1 have maximum weights well below the global max of 1.016 (left), using only 20–50% of the integer range under per-tensor quantization (right)—the inefficiency that per-channel quantization eliminates.
Per-channel quantization reduces MSE by up to 56,000× for underutilized channels (left). The largest gains (right) align with the near-zero channels from Figure 3.2 that collapsed to a single integer under per-tensor quantization.
Per-channel quantization reduces MSE by up to 56,000× for underutilized channels (left). The largest gains (right) align with the near-zero channels from Figure 3.2 that collapsed to a single integer under per-tensor quantization.
BERT's query projection weights cluster around 0.15 while the global max reaches 0.525, leaving 93% of channels below 50% integer utilization (top). The error distributions (bottom) tell the story: per-tensor produces flat, uniform error across ±0.002; per-channel concentrates errors near zero, reducing MSE by 9×.
BERT's query projection weights cluster around 0.15 while the global max reaches 0.525, leaving 93% of channels below 50% integer utilization (top). The error distributions (bottom) tell the story: per-tensor produces flat, uniform error across ±0.002; per-channel concentrates errors near zero, reducing MSE by 9×.
The outlier dilemma quantified. Protecting the max (25.8) preserves outliers perfectly but leaves only 9 integer levels for typical values. Clipping to the 99th percentile (4.8) gives typical values 51 levels—6× better resolution—but introduces catastrophic error (21!) for the clipped outliers.
The outlier dilemma quantified. Protecting the max (25.8) preserves outliers perfectly but leaves only 9 integer levels for typical values. Clipping to the 99th percentile (4.8) gives typical values 51 levels—6× better resolution—but introduces catastrophic error (21!) for the clipped outliers.
Left panel: Heatmap or bar chart showing "Hottest Channel Ratio" (max/median) per layer, highlighting layer 10's extreme 36.1x ratio Right panel: Bar chart showing "Number of Outlier Channels (>5x median)" per layer, showing the concentration in layers 3-5
Left panel: Heatmap or bar chart showing "Hottest Channel Ratio" (max/median) per layer, highlighting layer 10's extreme 36.1x ratio Right panel: Bar chart showing "Number of Outlier Channels (>5x median)" per layer, showing the concentration in layers 3-5
Attention dataflow with KV cache highlighted. Read left-to-right: (1) each token's hidden state projects into Q, K, V vectors; (2) QK^T dot products produce raw relevance scores; (3) softmax normalizes scores into attention weights; (4) weights scale V vectors, and the weighted sum becomes the output. The dashed box marks the KV cache—keys and values from all prior tokens, stored to avoid recomputation. For quantization, the critical observation is that K and V sit on different sides of the softmax, leading to different statistical structures.
Attention dataflow with KV cache highlighted. Read left-to-right: (1) each token's hidden state projects into Q, K, V vectors; (2) QK^T dot products produce raw relevance scores; (3) softmax normalizes scores into attention weights; (4) weights scale V vectors, and the weighted sum becomes the output. The dashed box marks the KV cache—keys and values from all prior tokens, stored to avoid recomputation. For quantization, the critical observation is that K and V sit on different sides of the softmax, leading to different statistical structures.
Row-major layout means input features are consecutive in memory (left, arrow shows memory order). Grouping along this dimension (right, each color = one scale factor) enables coalesced loads: read G weights, load one scale, accumulate. Grouping along output features would scatter access across memory.
Row-major layout means input features are consecutive in memory (left, arrow shows memory order). Grouping along this dimension (right, each color = one scale factor) enables coalesced loads: read G weights, load one scale, accumulate. Grouping along output features would scatter access across memory.
INT4 packing stores two values per byte. The first value occupies the high nibble (bits 4–7), the second the low nibble (bits 0–3). Unpacking requires bit shifts and masks before arithmetic—a cost that must be offset by memory bandwidth savings.
INT4 packing stores two values per byte. The first value occupies the high nibble (bits 4–7), the second the low nibble (bits 0–3). Unpacking requires bit shifts and masks before arithmetic—a cost that must be offset by memory bandwidth savings.
Smaller groups reduce MSE (left) but add scale overhead that erodes compression (right). Group-128 sits at the sweet spot: ~3% overhead for 2× lower error than group-256. Below g=64, overhead climbs steeply with diminishing accuracy returns.
Smaller groups reduce MSE (left) but add scale overhead that erodes compression (right). Group-128 sits at the sweet spot: ~3% overhead for 2× lower error than group-256. Below g=64, overhead climbs steeply with diminishing accuracy returns.
Granularity decision tree. INT8 is simple: per-channel is the standard. INT4 requires choosing your priority—group-128 balances accuracy and compression, smaller groups maximize accuracy at higher overhead, larger groups maximize compression at some accuracy cost.
Granularity decision tree. INT8 is simple: per-channel is the standard. INT4 requires choosing your priority—group-128 balances accuracy and compression, smaller groups maximize accuracy at higher overhead, larger groups maximize compression at some accuracy cost.
End-to-end quantization decision tree, read top-to-bottom. Phase 1 (top): select which tensors to quantize—weights are always included, activations add compute speedup, KV cache is context-length dependent. Phase 2 (middle): for each target, select granularity using bit-width as the primary fork—INT8 paths favor per-channel/per-token, INT4 paths favor group-128. Phase 3 (bottom): architecture-specific overrides (e.g., first/last layers in FP16). All paths converge on the hardware compatibility gate (right)—if your runtime doesn't support the chosen scheme, fall back to the next coarser granularity.
End-to-end quantization decision tree, read top-to-bottom. Phase 1 (top): select which tensors to quantize—weights are always included, activations add compute speedup, KV cache is context-length dependent. Phase 2 (middle): for each target, select granularity using bit-width as the primary fork—INT8 paths favor per-channel/per-token, INT4 paths favor group-128. Phase 3 (bottom): architecture-specific overrides (e.g., first/last layers in FP16). All paths converge on the hardware compatibility gate (right)—if your runtime doesn't support the chosen scheme, fall back to the next coarser granularity.

Summary

  • Weights are the safest target—static, zero-centered, tolerant of perturbation. Even INT4 often preserves quality with appropriate granularity.
  • Activations unlock compute speedup but require calibration. Static works for CNNs; dynamic per-token is essential for transformers.
  • The KV cache dominates long-context LLM memory, exceeding model weights at 128K context with batch size 4 or more. Keys need per-channel quantization; values need per-token.
  • Per-channel is the INT8 standard (3–9× better MSE than per-tensor). Group-128 is the INT4 standard (~2× better than per-channel, ~3% overhead).
  • Memory layout must align with granularity—group along the contiguous axis for coalesced loads.
  • The decision framework: select targets, choose granularity by bit-width, apply architecture-specific adjustments, verify hardware compatibility.

FAQ

What is the main difference between weights, activations, and the KV cache for quantization?Weights are frozen parameters learned during training, activations are intermediate values that change with every input, and the KV cache stores past keys and values during transformer generation. Because they have different statistics and access patterns, they should not be quantized the same way.
Why are weights usually the easiest target for quantization?Weights are static at inference time, so their distribution can be analyzed offline and does not shift across inputs. They are often bell-shaped around zero and tolerate small rounding errors well, which makes them well suited to symmetric quantization.
Why is activation quantization harder than weight quantization?Activations are input-dependent, so their ranges vary from one example to another. They also often contain heavy-tailed outliers, especially in transformers, which makes it hard to choose a single scale without either clipping useful values or wasting precision.
What is calibration in activation quantization?Calibration is the process of running representative data through the model to estimate activation ranges before deployment. Those observed min/max values are then used to compute scale and zero-point parameters for static quantization.
When should you use per-tensor versus per-channel weight quantization?Per-tensor quantization is simpler and uses one scale for the whole tensor, but it can waste precision when channels have different ranges. Per-channel quantization uses one scale per output channel and is usually the default because it greatly reduces error with negligible metadata overhead.
Why does per-channel quantization help so much for transformer weights?Transformer layers often have strong channel-wise outliers, so a single global scale underuses most of the integer range. Per-channel quantization gives each channel its own scale, reducing the penalty caused by outlier channels and improving accuracy significantly.
Why is the KV cache treated differently from normal activations?The KV cache is written once per token but read many times during generation, so it behaves like a long-lived memory structure rather than a transient activation. This makes memory savings especially valuable, and because keys and values have different statistical patterns, they benefit from different granularity choices.
What granularity is recommended for KV cache keys and values?Keys generally work best with per-channel quantization because they exhibit consistent channel-wise outliers. Values generally work best with per-token quantization because their variation is more token-dependent than channel-dependent.
Why are group-wise quantization schemes useful at low bit widths like INT4?At INT4, only 16 integer levels are available, so per-channel scales can be too coarse for large tensors. Group-wise quantization uses smaller local groups with separate scales, which improves accuracy while keeping metadata overhead relatively small.
How should memory layout influence the choice of quantization granularity?Granularity should match the tensor layout to preserve efficient memory access. For row-major linear layers, grouping along the input dimension keeps values contiguous in memory, enabling coalesced loads and better kernel performance.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Quantization and Fast Inference Quantization and Fast Inference ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Quantization and Fast Inference Quantization and Fast Inference ebook for free