ELLMEngineering Large
Language Models
Download PDF

Chapter 24

Quantization, Compression, and Adapter Serving

On this page

Compression changes capacity, bandwidth, arithmetic, layouts, calibration, and quality risk at once. Adapter serving adds another layer of dynamic state and batch compatibility. Neither is merely a smaller checkpoint.

The performance model exposed decode's byte traffic, and fleet placement made memory a replica-count problem. Compression changes both. In the running example, streaming 14 GB of weights accounts for a 4.7 ms lower bound, while logical KV grows by about 131 kB per token. The earlier estimate of roughly 200 conversations depends on their lengths and memory reserve; it is not a fixed concurrency limit.

Precision as a systems choice

Quantization maps values to a lower-precision representation plus scale and possibly zero-point metadata. The useful question is not "How many bits?" but:

  • which tensors are quantized;
  • which operations consume the format directly;
  • the scale granularity and metadata layout;
  • accumulation and output precision;
  • calibration or optimization data;
  • hardware and kernel support;
  • quality and performance at production shapes.

Common families include:

Family Main bandwidth/capacity effect Common challenge
Weight-only Smaller model reads and footprint Unpack/dequant overhead, small-row kernels
Weight-activation Smaller operands and low-precision matrix path Activation outliers and dynamic scaling
Floating low precision Wider dynamic range than integers at similar bits Scale policy and hardware availability
KV quantization More context or batch, fewer KV bytes Attention sensitivity and write/read conversion
Mixed precision Protect selected layers or channels More variants, conversions, and analysis

The format name alone does not determine speed. Group size, packing order, scale placement, padding, and fused epilogue support can decide whether the kernel reaches the intended hardware path.

Work one quantization group by hand

For signed symmetric b-bit integer quantization, choose Q=2^(b-1)-1 and scale s=max(abs(x))/Q for a nonzero group. Store q=round(x/s) clipped to [-Q,Q], and reconstruct x_hat=s*q. This symmetric convention leaves one signed integer code unused; asymmetric formats instead introduce a zero point and a different range. The stored format must specify which convention it uses.

With four bits and group maximum 7, the step size is one. Values [0.2,0.8,7] become [0,1,7]. The maximum rounding error inside the range is half a step, but the output error of a matrix multiply also depends on the activation values multiplying those errors. A rare large outlier can enlarge the scale enough to erase many small values. Smaller groups reduce that effect while adding scale traffic.

The payload is not the whole checkpoint. Four-bit values with one FP16 scale per 128 weights use 4+16/128=4.125 bits per weight before padding and other metadata. One byte of scale per 16 four-bit values gives 4.5 bits per value. On a nominal 7B weights, those idealized layouts require about 3.61 GB and 3.94 GB respectively, rather than exactly 3.5 GB. Embeddings or sensitive layers retained at higher precision add more.

The runnable symmetric_quantize reference demonstrates rounding, the zero-group convention, and outlier damage. It is not GPTQ, AWQ, or a hardware FP4 encoder. Its tests establish the stated scalar error bound, not model quality after quantization.

Why quantization algorithms look at activations

A layer's useful objective is often output reconstruction, such as minimizing norm(XW-XW_hat)² on calibration activations X, rather than minimizing unweighted weight error. An error in a weight multiplying a nearly inactive feature can matter less than the same error on a frequently large feature.

Method Core intervention What it does not establish
GPTQ Use approximate second-order reconstruction information while quantizing weights and compensating remaining error A universally optimal rounding or a fast runtime for every layout
AWQ Use activation statistics to choose channel scaling that protects salient weight directions Immunity to calibration or domain shift
SmoothQuant Redistribute scale between activation and weight channels to make activation quantization easier Elimination of quantization error in both operands
Rotation methods such as SpinQuant Change equivalent internal bases to distribute outliers before low-bit quantization Free rotations through arbitrary nonlinearities or guaranteed speedup

Primary references are GPTQ, AWQ, SmoothQuant, and SpinQuant. The methods target different constraints; do not infer that a newer publication dominates all older formats and kernels.

For the scale-redistribution idea, insert an invertible diagonal matrix D: XW=(XD^-1)(DW). The full-precision product is unchanged, while the operands' quantization ranges change. This identity does not say the quantized product is unchanged. Likewise, an orthogonal rotation can preserve a compatible linear computation while changing rounding error. Nonlinear activations and normalization require a valid placement or compensation; rotate every tensor arbitrarily and the original model is lost.

Calibrate on the target input distribution, then evaluate on a held-out distribution. Long reasoning, code, vision tokens, and rare languages can produce ranges missing from short generic prose. If the quantization method is tuned repeatedly on one calibration benchmark, retain an untouched quality set. Compare against a simple round-to-nearest baseline and report both quality and deployed kernel time.

Weight-only quantization

The packed weights and their scale metadata form one artifact contract. The serving kernel must consume that exact representation; reduced storage alone does not establish faster execution.
Open full diagram ↗

The packed weights and their scale metadata form one artifact contract. The serving kernel must consume that exact representation; reduced storage alone does not establish faster execution.

In small-batch decode, weight reads often dominate dense linear layers. Weight-only quantization stores packed low-bit weights, loads scales, reconstructs or directly consumes low-precision values, and multiplies by higher-precision activations.

Smaller weights can:

  • reduce step latency when bandwidth-bound;
  • make the model fit on fewer devices;
  • leave more memory for KV and batch;
  • reduce model load and replica startup time.

The path can lose if unpack and scale work is not overlapped, tensor-core instructions do not support the exact format, group metadata is large, layout conversion occurs at runtime, or the compressed model shifts the bottleneck to KV, communication, or launch overhead.

Calibration-aware methods protect important weights or choose scales using representative activations. The serving team still owns format validation because a high-quality checkpoint can be paired with a poor runtime layout.

On the running service, shrinking streamed weights from about 14 GB toward 4 GB reduces the weight-read contribution at 3 TB/s from about 4.7 ms to 1.3 ms. That is not a prediction of token-rate improvement. At the earlier eight-request, 4096-token context, the roughly 4.3 GB of FP16 KV reads remain: the combined ideal HBM floor moves from about 6.1 ms to 2.8 ms before unpacking, computation, collectives, or scheduling. Compression shifts the dominant term instead of accelerating every byte equally.

Weight-activation and floating formats

Quantizing activations can unlock lower-precision matrix instructions and reduce intermediate traffic. Activation distributions are input-dependent and often contain outliers. Strategies include per-token or per-row dynamic scales, offline transformations that move quantization difficulty between activations and weights, selective higher precision, and block-scaled floating formats.

Dynamic scaling adds reductions, metadata, and synchronization. Offline scaling depends on calibration coverage. Per-tensor scales are cheap but sensitive to outliers; per-channel, row, or block scales track range better but increase metadata and may complicate kernels.

Accumulate sensitive reductions in an appropriate wider type. Protect normalization, logits, embeddings, or selected layers when evidence shows they dominate error. "Everything at one dtype" is an implementation convenience, not a quality principle.

MXFP8 and NVFP4: scales are hardware operands

Blackwell-era low-precision paths use block scales to preserve useful local range. In the documented Transformer Engine FP8/FP4 recipes, MXFP8 groups 32 values with a power-of-two scale, while NVFP4 uses E2M1 four-bit values with finer blocks and additional scaling. Exact training recipes include operation-specific choices; consult the pinned runtime when selecting a layout rather than treating a format name as the complete recipe.

The NVFP4 recipe documentation describes block-scale layout requirements and safeguards such as transformations and rounding choices for training. A packed checkpoint, the matrix instruction's operand layout, and the training quantizer are separate artifacts. In particular, quantizing a matrix by rows and then transposing its codes does not generally produce the same result as transposing the original matrix and quantizing its new rows.

For a small original example, imagine one row containing values [1,1,1,100]. A shared row scale sacrifices resolution for the three small values. After transposition into a different block grouping, those values may share scales with different neighbors. Both orientations may be required by forward and backward GEMMs. The extra representation and conversion work belongs in the memory/time ledger.

Separate three experiments: post-training quantization of frozen weights, quantization-aware fine-tuning, and low-precision pretraining. Passing the first does not validate gradients in the third. Training must preserve convergence across many steps, not just one layer's output error. Keep sensitive statistics and state wider where required, test scale updates after outliers, and compare quality at equal compute as well as equal step count.

KV-cache quantization

KV state grows with live cached tokens, so lower precision can increase concurrency or context and reduce attention bandwidth. Keys affect attention scores; values affect the weighted sum, and their sensitivities may differ by layer, head, token position, and model.

Scale choices include per-tensor, per-head, per-channel, per-token, or grouped blocks. Finer scales improve range tracking but consume metadata and append-time work. Dynamic token scales may require a reduction when KV is written. The attention kernel must dequantize without destroying locality or occupancy.

Evaluate long-context retrieval, position-sensitive tasks, multi-turn conversations, rare tokens, tool-use formats, and output distributions, not only short perplexity. A format that doubles theoretical capacity but slows attention can reduce serving capacity under latency SLOs.

For the running service, halving KV payload bytes moves ideal capacity toward 900,000 cached tokens - about 400 median conversations per replica - before scale metadata and reserve. Four-bit KV could halve payload again. At a fixed live-token count, each halving reduces ideal KV traffic, but increased admission can spend that saving on more state. The 107,000-token traffic crossover assumes FP16 weights and KV; it must be recomputed whenever either format changes.

Compression shifts the optimum

Suppose uncompressed weights require a four-device tensor-parallel group. A weight format that fits the model plus reserve on two devices may create twice as many replicas, reduce collective degree, and change the best batch. This fleet-level gain can exceed its isolated kernel speedup.

The reverse can occur: a quantized format frees memory, the scheduler admits a larger batch, and longer iterations violate token-cadence SLOs. Re-tune group size, batch, KV budget, graph shapes, and autoscaling after changing precision.

Quantization validation ladder

Use a staged evaluation:

  1. tensor and layer numerical comparisons;
  2. teacher-forced token probability or perplexity by domain;
  3. generation quality, task, safety, and structured-output suites;
  4. long-context, multilingual, code, rare-slice, and adversarial tests;
  5. kernel benchmarks across batch, context, and alignment shapes;
  6. end-to-end replay with scheduling, KV pressure, and target hardware;
  7. canary with slice metrics, rollback, and version isolation.

Measure both mean quality and regressions concentrated in specific layers, languages, adapters, or long contexts. Use the same sampling seeds or distributional test appropriate to the reproducibility contract.

Multi-adapter serving

Low-rank adapters modify selected linear layers while sharing a base model. Serving many adapters on separate full replicas wastes base weights. A multi-adapter engine keeps the base resident, loads adapter matrices dynamically, and groups adapter work across requests.

For a linear layer with base output x W, a low-rank update has the form:

output = x W + scale times x A B

Requests in one batch may use different A and B. The engine can execute grouped low-rank operations, segment tokens by adapter, or fuse adapter work into a specialized path. Tiny ranks make launch and indexing overhead important; large or multiple adapters can create meaningful compute and memory pressure.

Adapter batching should not require every sequence to use the same adapter, but completely unstructured mixtures can reduce locality. Track adapter ID and rank as scheduling features and limit variant explosion.

Adapter lifecycle and isolation

An adapter has identity, base-model compatibility, rank and target modules, dtype, tokenizer/template expectations, authorization, and version. Loading should verify a manifest and content digest before publication. Keep reference counts while requests execute; evict only when no in-flight use remains.

An adapter cache trades load latency against device memory and batch capacity. Eviction value depends on request frequency, load cost, bytes, and whether the base worker can serve useful traffic while loading. Preload latency-critical adapters, but cap tenants so one customer cannot fill every worker.

Adapter and prefix identities interact: KV produced with one adapter cannot generally be reused under another. A rollout of an adapter version requires cache namespace separation just like a base-model rollout.

Capacity accounting with adapters

A worker memory budget includes:

base weights + resident adapters + active KV + reusable KV + workspaces + graph buffers + allocator reserve

Adapter count alone is misleading because ranks and targeted layers differ. Account bytes and measured per-token work. For sparse popularity, maintain a warm subset and route by adapter locality. For uniformly hot adapters, replicate them. For a long tail, consider host-resident staging, but include transfer time and queue hot spots.

Design Exercises

  1. Compare weight-only, weight-activation, and KV quantization as serving interventions.
  2. Why can a four-bit checkpoint be smaller but slower than a higher-precision one?
  3. Design a quality and performance evaluation for a new quantization recipe.
  4. How can quantization change the optimal parallelism and batching plan?
  5. Design multi-adapter batching and residency management.
  6. What isolation and versioning rules connect adapters, tokenizers, and prefix caches?

Worked Solutions

1. Quantization targets

Weight-only primarily reduces model footprint and decode weight bandwidth while leaving activation compute higher precision; it pays unpack and scale cost. Weight-activation can use lower-precision matrix paths and reduce operand traffic, but activation outliers, dynamic scales, and accumulation matter. KV quantization targets context capacity and attention bandwidth, adding append/read conversion and long-context quality risk. Choose the tensor whose bytes control the target phase and require a supported kernel and quality contract.

2. Smaller but slower

The runtime may unpack into a wider type, read many group scales, execute scalar conversions, use an unsupported or poorly tiled matrix path, or convert layouts at load or every step. The shape may be compute-bound already, or compression may expose KV, collective, sampling, or launch overhead. Measure achieved bandwidth/compute, instruction path, scale and conversion traffic, kernel time by layer and shape, group size, batch, and end-to-end goodput.

3. Evaluation design

Validate layers numerically, then probability/perplexity by representative domain, task and safety quality, generation behavior, long-context retrieval, code/multilingual/rare slices, and adapters. Benchmark exact deployed kernels across batch, context, alignment, and hardware. Replay production arrivals with KV pressure and measure first-token/cadence SLOs, memory, energy if relevant, and goodput. Canary by quantization version with rollback and cache isolation; do not infer production quality from one aggregate benchmark.

4. Re-planning after quantization

Smaller weights may let the model use fewer tensor-parallel devices, increasing replicas and reducing collectives. Freed memory permits more KV or adapters and a larger batch. Faster matrix work can make attention, communication, or host overhead dominant. Re-sweep group size, replica count, batch and iteration budget, KV allocation, graph variants, and autoscaling on the new artifact; the old optimum is no longer evidence.

5. Multi-adapter serving

Share one base model, tag tokens or sequences by adapter, and execute low-rank updates through grouped or segmented operations that support mixed adapters without padding every request to one rank. Cache adapters by expected saved load time per byte, preload latency-critical ones, route with bounded locality, and keep per-tenant quotas. Version manifests, validate base compatibility, reference-count in-flight use, and expose fallback or rejection when an adapter cannot load within SLO.

6. Isolation and versioning

Adapter identity includes content digest, base-model version, target modules, rank, scale, dtype, and any tokenizer/template requirements. Authenticate access before routing or loading. Prefix-cache keys include the exact adapter and tokenizer/template identity, so state never crosses incompatible versions or tenants. Rollout publishes a new namespace, drains references to the old one, and deletes adapter and cache artifacts under the same retention policy.