← Inference From First Principles

Quantization and Numerical Precision

Four different things are called quantisation quality: storage, reconstruction error, model behaviour and speed. Measured separately on GPT-2, they disagree.

I used the same 38.6-million-weight GPT-2 embedding table in two roles. With group-128, four-bit fake quantisation on the input lookup only, perplexity moved from 60.6 to 61.0 on a 12-window test. Quantising the output projection only instead raised it to 8,123. The first change is about 0.7 per cent; the second is roughly 134 times the baseline, just over two orders of magnitude. The reconstructed weights have a relative error of about 12.7 per cent in this experiment, yet the effects of that error depend dramatically on where the table is used. Those are measurements of a simulated quantiser on one GPT-2 checkpoint and one text sample, not universal properties of embeddings.

A claim such as “quantisation loses one per cent” needs at least three qualifiers: which scheme, which model and evaluation, and which metric. In this chapter we keep four questions separate: how many bits a proposed representation requires; how far reconstructed weights differ; how the language model’s predictions change; and whether a particular kernel on a particular device becomes faster. A result in one column cannot silently stand in for the other three.

The main findings are deliberately specific. Per-channel eight-bit weight-only fake quantisation of GPT-2’s 48 projection matrices changed perplexity by −0.13 per cent on this text, without establishing statistical equivalence. Per-tensor eight-bit rounding increased it by 11.2 per cent. Simple group-wise four-bit rounding raised perplexity by 8.5–13.3 per cent, with substantially lower next-token top-choice agreement. And unfused conversion of stored int8 or packed int4 weights back to fp16 inside every measured matrix product was up to about 26 times slower than an fp16 product. That is evidence against an inefficient execution path, not evidence that low-bit inference is intrinsically slower.

Where this sits

Matrix Multiplication and GPU Execution observed that fp16 roughly halved the time of a memory-limited GPT-2 output projection relative to fp32. Memory Bandwidth and Compute Bottlenecks explained the condition behind that result: time can improve when an execution path actually transfers fewer bytes. Quantisation tests both halves of the trade-off. The Transformer as a Computation also documented unusually large GPT-2 activations, while Tokens, Embeddings and Probability showed a large negative common offset in the logits. A common offset cancels under softmax; differences between vocabulary scores do not. We will test how coarse rounding interacts with those differences rather than assume weight error predicts output error.

The Inference Lab increment is a quantisation workbench: quantize_dequantize, integer packing helpers, activation fake quantisation, a storage estimator, a model evaluator, and separate speed probes. It does not yet export an independently loadable low-bit checkpoint, implement a fused weight-only kernel, or automatically attach a quantisation identity to every Building Our First Inference Engine engine manifest. Those are implementation obligations, not accomplishments to infer from an estimated file size. We will describe the proposed manifest fields and acceptance checks at the end.

For the Pi series, this is where “will the model fit locally?” becomes a quantitative design question. A storage estimate is the first filter; actual residency, activation memory, KV-cache growth, implementation support, accuracy and throughput still have to be measured. The serving chapters return to that complete decision.

Formats and what they can represent

Formats and what they can represent

Floating-point formats trade range (largely controlled by exponent bits) against precision (largely controlled by significand bits). The values below come from torch.finfo in the recorded PyTorch environment. “Epsilon” is the spacing immediately above 1, not a uniform relative error guarantee over the entire representable range. The fp8 rows describe formats, not an fp8 GPT-2 execution experiment.

Format Bits Largest value Smallest normal Relative step (epsilon)
fp32 32 \(3.4 \times 10^{38}\) \(1.2 \times 10^{-38}\) \(1.2 \times 10^{-7}\)
fp16 16 65,504 \(6.1 \times 10^{-5}\) \(9.8 \times 10^{-4}\)
bf16 16 \(3.4 \times 10^{38}\) \(1.2 \times 10^{-38}\) \(7.8 \times 10^{-3}\)
fp8 (e4m3) 8 448 0.0156 0.125
fp8 (e5m2) 8 57,344 \(6.1 \times 10^{-5}\) 0.25

The two 16-bit formats make different compromises. Bfloat16 keeps a range close to fp32 but offers seven explicit fraction bits, whereas fp16 has ten. In the recorded cast probe, 70,000 became inf in fp16 and 70,144 in bf16; 2,956 was exactly represented in fp16 and rounded to 2,960 in bf16. The same probe mapped \(10^{-9}\) to zero in fp16 but retained a nonzero bf16 approximation. Range, rounding and underflow can therefore affect different parts of a computation in different ways.

The The Transformer as a Computation residual coordinate of 2,956 falls within fp16’s finite range. That observation does not prove that every intermediate operation in this GPT-2 implementation is overflow-safe, nor does it establish fp16 as universally preferable: accumulation dtype, reductions, kernel implementation and the actual activation distribution matter. The measured GPT-2 evaluation below happens to preserve perplexity more closely in fp16 than bf16. That is an empirical result for this checkpoint and runtime; for other models, the larger exponent range of bf16 may be more valuable.

Integer quantisation represents a real number by a discrete code and metadata that maps that code back to a scale. In the simple symmetric, signed, round-to-nearest scheme used here, \(b\) bits provide up to \(2^b\) codes. For a nonzero finite tensor or quantisation group, the implementation uses a scale set by its largest absolute value:

\[ s = \frac{\max|x|}{2^{b-1}-1}, \qquad q = \operatorname{round}(x/s), \qquad \hat{x} = q\,s \]
Ignoring floating-point error in scale calculation, rounding within a representable group contributes at most half a quantisation step per value. That statement needs its conditions: it does not cover clipping from a separately calibrated range, invalid values, or the later effect of many errors after matrix multiplication. In this workbench the symmetric scale is selected from each observed group's maximum, and values are clamped to the chosen signed integer range. **Group outliers raise the scale and coarsen every other value.**

Granularity

For the GPT-2 Conv1D weights the stored matrix has shape [input, output]. The implementation shares a scale across the entire matrix (group=0), across all input coordinates of one output column (group=-1), or across blocks of \(g\) input coordinates inside each output column (group=g). Finer groups can reduce the effect of extreme weights, but add scale metadata and may impose alignment requirements on a real packing format. The estimator assumes a 16-bit scale for each complete group:

\[ \text{bits per weight} = b + \frac{16}{g} \]
A symmetric four-bit group-128 representation therefore has a **nominal** cost of \(4+16/128=4.125\) bits per weight, or 4.5 bits with groups of 32. The workbench's asymmetric option adds a zero point counted at \(b/g\) bits per weight. These are mathematical packing estimates: they do not include tensor headers, strides, block padding, alignment, kernel-specific layout or serialisation metadata. More importantly, `quantize_dequantize` **returns floating-point weights**; its estimated bit width is not the resident size of the evaluated PyTorch model.

What the weights look like

What the weights look like

GPT-2 small has 48 Conv1D projection modules (four per transformer layer), containing 84,934,656 stored weight elements, about 68 per cent of its 124.4-million-parameter checkpoint. The tied token-embedding/output-projection table accounts for most of the remainder. The following statistics are computed separately for those 48 projection matrices, not across the embedding table or all activations:

Statistic Median over 48 layers Worst
Largest weight over RMS 20.8 186 (layer 3, feed-forward output)
Excess kurtosis (0 for a Gaussian) 3.2 790 (same layer)

The largest peak-to-RMS ratios belong to the MLP output projections of layers 3, 2 and 1: approximately 186, 162 and 158. The reported excess kurtosis is also extreme for some of these layers. This shows that a per-tensor maximum can be a poor representative of typical weights. It does not mean every matrix has the same heavy tail, and the Gaussian comparison is only a heuristic; the measured distributions, rather than that analogy, justify looking at finer scales.

Consider the worst matrix, whose largest absolute entry is about 186 times its root-mean-square (RMS) weight. With signed symmetric int8 and a scale based on that maximum, the code’s grid spacing is approximately \(186/127\approx1.46\) times the RMS. Many ordinary-magnitude entries then collapse toward zero. The next table measures relative Frobenius error, \(\|\hat W-W\|_F/\|W\|_F\), for the reconstructed matrices. This is a matrix-level norm ratio, not the fraction of entries that change, the average error of an individual weight, or an accuracy metric.

Scheme Bits per weight Median error Worst layer
int8, per tensor 8.00 0.047 0.421
int8, per channel 8.01 0.0089 0.020
int8, group 128 8.13 0.0068 0.0097
int4, per channel 4.01 0.160 0.279
int4, group 128 4.13 0.124 0.148
int4, group 64 4.25 0.110 0.128
int4, group 32 4.50 0.099 0.109
int4, group 128, asymmetric 4.16 0.104 0.119
int3, group 128 3.13 0.287 0.324
int2, group 128 2.13 0.771 0.792

Per-tensor int8 has a median relative reconstruction error of 0.047 and a worst-layer value of 0.421. The latter does not mean that 42 per cent of weights were discarded: it means the Frobenius norm of the error is 42 per cent of that matrix’s original Frobenius norm. Per-output-channel scales reduce the median to 0.0089 and worst to 0.020; group-128 int8 reduces them further. At four bits, shrinking group size from 128 to 32 moves median error from 0.124 to 0.099 while raising the nominal cost from 4.125 to 4.5 bits per weight. This is a storage-versus-reconstruction trade-off, before we ask which errors matter to the network.

The reconstruction results are useful for checking the quantiser and understanding outliers. They cannot rank schemes by language-model quality on their own: different layers, inputs and tied uses give the same weight error very different downstream consequences.

What the model does

The evaluation tokenised the text of Chapters 6–11 into 57 non-overlapping windows of 512 tokens. That is 29,184 input tokens, of which 29,127 next-token positions were scored because the last token in each window has no within-window successor. The corpus contained 29,288 tokens before truncation. The fp32 GPT-2 reference obtained a perplexity of 62.69 on these positions. This is a reproducible local comparison on technical prose, not a standard language-model benchmark or a statistical claim about general text. Calibration for activation smoothing used a separate eight-window sample from Chapters 1–5.

  • Perplexity: \(\exp\) of the average negative log probability assigned to the true next token over the 29,127 scored positions; lower is better for this text.
  • Top-1 agreement: fraction of those same positions where the altered model and fp32 reference choose the same highest-logit token under teacher forcing; it does not measure agreement of free-running generated sequences.
  • KL divergence: mean \(D_{\mathrm{KL}}(p_{\mathrm{fp32}}\|p_{\mathrm{altered}})\) over the full vocabulary, in nats per position; it measures distributional drift from the reference rather than task accuracy.

Perplexity evaluates prediction of the observed corpus; top-1 agreement and KL measure fidelity to the fp32 reference. These questions can diverge. A tiny perplexity change does not prove identical greedy generations, and even high one-step agreement on fixed contexts cannot guarantee trajectory agreement after the model generates a different token and changes its own future context.

For the integer schemes below, the model’s projection weights were quantised and immediately dequantised to floating-point tensors. Its actual forward passes still used regular floating-point operations; no packed int8/int4 projection kernel was used to obtain the behaviour numbers. The fp16 and bf16 rows instead run the corresponding floating-point model dtypes, including activations. Thus the table combines observed model behaviour with a separate hypothetical compressed-storage estimate. Neither the bit count nor the quality test demonstrates an actual deployable checkpoint at that size, runtime speedup or matching hardware arithmetic.

Scheme Perplexity Change Top-1 agreement KL (nats) Bits per weight (linear) Whole model*
fp32 (reference) 62.69 – – – 32 475 MiB
fp16 62.70 0.00% 98.3% 0.0002 16 237 MiB
bf16 63.74 +1.67% 87.9% 0.0212 16 237 MiB
int8, per tensor 69.73 +11.2% 78.0% 0.136 8.00 156 MiB
int8, per channel 62.61 −0.13% 97.6% 0.0012 8.02 157 MiB
int8, group 128 62.70 +0.02% 98.5% 0.0005 8.13 158 MiB
int4, per channel 88.34 +40.9% 65.6% 0.343 4.02 116 MiB
int4, group 128 71.05 +13.3% 76.3% 0.145 4.13 117 MiB
int4, group 64 69.79 +11.3% 78.6% 0.115 4.25 118 MiB
int4, group 32 67.99 +8.5% 80.6% 0.090 4.50 121 MiB
int4, group 128, asymmetric 68.67 +9.5% 79.5% 0.105 4.16 117 MiB
int3, group 128 274.65 +338% 34.5% 1.59 3.13 107 MiB
int2, group 128 18,575 collapse 4.4% 6.05 2.13 97 MiB

* The “Whole model” values for the integer rows are estimated packed sizes, not torch.cuda.memory_allocated() or serialised artefact sizes. They assume the 48 projection matrices use the stated effective bits per weight, with the tied embedding/output projection, norms and biases at fp16; the actual simulated integer rows leave those non-projection tensors in fp32, while dequantised projection tensors also occupy floating-point storage. The table’s fp32 reference size is the full checkpoint at fp32. The 16-bit rows are nominal whole-model parameter sizes. No compressed model package was written or loaded in these experiments.

Read the table by metric and implementation, not by treating one number as a verdict.

fp16 preserves these metrics closely, but not identically. Relative to fp32, it changes the top-1 choice at about 1.7 per cent of scored positions (98.3 per cent agreement), while perplexity changes by only about 0.004 per cent before table rounding. Near-tied logits are one possible source of changes, but their margins were not analysed here. The 98.3 per cent figure is a measured comparator for this model, not an irreducible agreement floor or a universal upper bound on quantised models; a different scheme may even agree more often on a given corpus.

Perplexity and one-step fidelity can disagree. The bf16 row raises perplexity by 1.67 per cent yet changes the top-1 choice at about 12.1 per cent of fixed evaluation positions, with much larger KL divergence than fp16. That demonstrates distributional differences under the specified evaluation. It does not establish that 12 per cent of tokens in a freely generated response will change, or quantify whether readers would notice those changes. A reproducibility policy should compare generation traces separately.

Per-channel int8 weight-only fake quantisation is promising here, not proved equivalent. Its perplexity is 62.61 versus 62.69 for fp32 (−0.13 per cent), with 97.6 per cent top-1 agreement and mean KL 0.0012 nats. No resampling, confidence interval or second corpus was used, so “statistically indistinguishable” or “no measurable cost” would overstate the evidence. The nominal packed model is about 157 MiB versus 237 MiB for a full fp16 model, but the evaluation did not run a 157 MiB packed model. A single scale per tensor makes the same linear weights considerably less faithful on this test (+11.2 per cent perplexity).

Simple int4 rounding shows a strong granularity effect. In this corpus the group-128, group-64 and group-32 variants raised perplexity by 13.3, 11.3 and 8.5 per cent; per-channel int4 was worse at +40.9 per cent. Their top-1 disagreement rates are roughly 19–34 per cent across the four schemes, not uniformly one in five. The asymmetric group-128 row improves on the symmetric one at modest extra nominal metadata cost. These are plain maximum-scaled round-to-nearest experiments, not GPTQ or AWQ. The latter use calibration/information about model behaviour to prioritise rounding decisions or salient weights; their reported performance in other papers does not tell us what they would recover for this particular GPT-2 run.

There is a sharp deterioration in this setup below four bits. Group-128 int3 raises perplexity by 338 per cent and int2 reaches 18,575, with 4.4 per cent top-1 agreement at two bits. This establishes failure of these specific simple schemes on the selected model and text, not a general impossibility of three-bit or two-bit inference. Calibrated rounding, selective precision and different architectures may change the curve.

The matrix that is used twice

GPT-2 ties its token embeddings to its output projection: the same 38.6-million-element parameter table is read as vectors at input and multiplied by the final hidden state at output. To isolate the two roles, the experiment used separate input-lookup and output-projection paths with the same group-128 int4 reconstruction, deliberately breaking the usual tied-use coupling for analysis. Quantising both roles in the full 57-window experiment yielded perplexity 7,862; the smaller 12-window diagnostic used below has its own baseline and yielded 7,983. Those are different evaluations, not inconsistent repetitions of one measurement.

On a separate 12-window subset of the evaluation text (baseline perplexity 60.613), I measured where the distortion enters:

Where int4 (group 128) is applied Perplexity (baseline 60.6)
Input lookup only 61.0 (+0.7%)
Output projection only 8,123
Both (tied) 7,983
Both, int8 per channel 64.7 (+6.7%)
Both, int8 group 128 61.9 (+2.1%)

In these 12 windows, applying group-128 int4 only at lookup raised perplexity by about 0.7 per cent, while applying it to the final output projection raised perplexity to approximately 8,123. Quantising both reached 7,983. That is strong evidence that this tied output projection is unusually sensitive to this particular four-bit reconstruction. It does not show that input embedding quantisation is always safe or that every language model must retain its entire output projection at high precision. The next diagnostic helps explain the asymmetry.

Value
Spread of exact logits across the vocabulary (std) 3.43
Error std across the vocabulary, int8 group 128 0.24
Error std, int4 group 128 4.74
Error std, int4 per channel 5.25
Mean logit −123.9
Hidden-state norm / embedding-row norm 264 / 4.0

Using 64 final hidden states from one evaluation window, the experiment found that exact vocabulary logits have a standard deviation of 3.43 across tokens, while quantising the embedding table with group-128 int4 introduced logit-error standard deviation 4.74. The mean common error shift was only about 0.08; softmax is invariant to a constant shared by all logits, but not to token-dependent perturbations of that size. The hidden states also had norm about 264 versus embedding-row norm about 4, which suggests a mechanism for error amplification through the final dot product. The norm comparison alone does not prove causation: the alignment between errors and hidden states, not merely their norms, determines the actual logit errors. The measured error distribution and perplexity collapse are the evidence; the precise cause remains to be isolated.

A practical design hypothesis follows: protect highly sensitive uses of shared weights, especially output projections, until per-layer or per-role ablation demonstrates that a lower precision is acceptable. Here the main quality table holds the 38.6-million-entry tied embedding/output projection at an assumed fp16 for the storage calculation, and the simulated integer variants actually leave it at fp32. That is why the nominal int4 whole-model estimate remains near 117 MiB rather than shrinking to about 70 MiB. This protection costs storage, but the role-specific tests show why it deserves explicit consideration. A future implementation should test selective quantisation without accidentally breaking weight tying.

Quantising activations

Quantising activations: residual stream range

Weight-only quantisation can reduce weight-storage and weight-transfer requirements if a compatible kernel reads the compressed representation directly. W8A8 also quantises activations, potentially enabling an integer matrix-product path. This workbench instead simulates the numerical effect by rounding/dequantising activations before floating-point Conv1D operations. The scale is recalculated dynamically from either the whole activation tensor or each token row. No genuine integer W8A8 end-to-end execution path was benchmarked.

Scheme Perplexity Change Top-1 agreement KL
W8A8, activation scale per tensor 85.95 +37.1% 65.2% 0.383
W8A8, activation scale per token 63.00 +0.49% 94.2% 0.0073
W8A8, per tensor, with smoothing (α = 0.5) 79.69 +27.1% 68.1% 0.300

Activation granularity matters in this experiment. With per-tensor activation scales the simulated W8A8 variant increases perplexity by 37.1 per cent; per-token scaling reduces the increase to 0.49 per cent, but top-1 agreement is still only 94.2 per cent. Calling that “nearly free” is valid only for perplexity on this one corpus, not for exact model fidelity. Calibration over Chapters 1–5 found substantial differences between input-channel maxima, including a 28.9-to-1 max/median ratio at the input to the last MLP output projection. A tensor-wide scale can discard detail in smaller channels. Per-token scaling could instead help by isolating outlier-heavy rows, but the location and causal importance of those outliers were not tested.

The SmoothQuant paper proposes migrating activation-range difficulty into weights with an algebraically equivalent reparameterisation: for input channel \(j\), scale the activation by \(1/s_j\) and the corresponding weight row by \(s_j\), with \(s_j = (\max |X_j|)^\alpha/(\max |W_j|)^{1-\alpha}\). The unchanged real-valued product is a mathematical identity; rounding after the transform is not error-free. Here the implementation applies a SmoothQuant-inspired transform only to attention QKV and MLP-up projections (c_attn, c_fc), with \(\alpha=0.5\); it does not fold the divide into preceding layer-normalisation parameters or quantise every relevant projection. Perplexity improved from +37.1 to +27.1 per cent versus fp32, still substantially worse than the per-token variant. The hypothesis that the remaining damage comes from unsmoothed layers needs a layer-by-layer ablation and a calibration-only \(\alpha\) search before it can be treated as an explanation.

Does it run faster?

The quality experiments above do not establish a speed benefit. The following benchmark uses random inputs and an output-projection-shaped matrix, \(768\times50{,}257\), at a single query row on the recorded RTX 2060. It times CUDA execution of four distinct implementations, including two that unpack or dequantise weights afresh on every call. The table’s “stored size” is an estimated representation size, not the actual temporary fp16 matrix that these two implementations create; the comparison isolates the cost of those execution choices, not end-to-end model serving.

How the weights are used Time Stored size of the weights
fp32 weights 512 µs 147 MiB
fp16 weights 269 µs 74 MiB
int8 weights, converted to fp16 on each call 1,610 – 1,621 µs 37 MiB
packed int4 weights, unpacked and converted on each call 5,477 – 6,925 µs 19 MiB

The direct fp16 matrix product is fastest in this table. Per-call unfused dequantisation raises elapsed time roughly 6× for int8 storage and 20–26× for packed int4 storage relative to fp16. In the code, q8.half() * scale8.half() or unpack_int4(p4) followed by scaling materialises a large fp16 weight matrix before @ executes. That entails conversion kernels, allocation, intermediate memory traffic and a subsequent GEMM. The figures therefore do not measure the speed of an int8 or int4 matrix product on compressed weights, nor prove that the extra time follows a simple bandwidth formula. They measure how an unsuitable, unfused PyTorch pipeline can erase the storage advantage.

A purpose-built fused low-bit kernel could read packed weights, dequantise small tiles in registers or shared memory, and avoid materialising the full fp16 matrix. Whether it is faster also depends on instruction support, grouping layout, occupancy and output shape. This chapter did not benchmark a fused int4 weight-only kernel, so it cannot predict a realised speedup from the nominal fourfold compression. GPTQ and AWQ report results with their own kernels and hardware; those are research context, not measurements on this RTX 2060.

The benchmark includes a separate integer GEMM microbenchmark using PyTorch’s private torch._int_mm API. It consumes an int8 activation matrix and int8 weight matrix and returns an integer accumulation; it is not the same numerical operation as the fp16 reference. Its input activations are independently generated random int8 values, and the reported time excludes activation quantisation, scale handling, dequantisation/rescaling and model integration. The result can indicate potential kernel-level throughput, but not W8A8 model latency or accuracy.

Shape fp16 int8 × int8
Output projection (768 × 50,257) 1,150 – 1,178 µs 741 – 747 µs
Feed-forward up (768 × 3,072) 59 – 60 µs 60 – 61 µs
Square (4,096 × 4,096) 284 – 286 µs 289 – 291 µs

At \(M=256\), torch._int_mm took about 741–747 µs for the wide output-projection shape versus 1,150–1,178 µs for the fp16 GEMM: a kernel-only timing ratio of about 1.55×, not a measured end-to-end W8A8 speedup. The narrower MLP-up and square products did not improve. The integer path also padded the output-projection width from 50,257 to 50,264 columns, changing the executed shape slightly. Because activation data and output dtype differ between the paths, the numbers isolate a possible hardware/kernel advantage and cannot establish numerical equivalence or model quality. torch._int_mm is an internal API and requires its own compatibility checks.

The actionable conclusion is conditional: reducing stored bits improves throughput only if the deployed execution path actually reduces its bottleneck costs. For the tested RTX 2060, fp16 GEMM is a strong baseline, unfused low-bit conversion is a cautionary failure, and an isolated int8 GEMM suggests a possible speed opportunity. A deployment decision still needs a real packed model, fused-kernel parity, end-to-end latency and memory-residency measurements on the target device.

What the numbers do not show

  • One GPT-2 checkpoint and one local corpus. The 57-window evaluation is not a general quality benchmark; the 12-window embedding diagnostic uses a different baseline. Results for larger or differently trained models are not established.
  • No statistical generalisation. All schemes were evaluated on a single fixed corpus without confidence intervals, held-out domains or task metrics. Small perplexity differences should not be described as statistically insignificant or equivalent without a defined test.
  • Fake quantisation for integer quality tests. Weights and activations were reconstructed as floating-point values; the nominal 97–158 MiB model sizes are not measured resident or saved model sizes.
  • fp16 and bf16 are separate dtype runs. They quantise activations through the framework’s kernels as well as changing stored parameter dtype, so they are not a pure weight-only comparison.
  • Partial smoothing. The SmoothQuant-inspired experiment used \(\alpha=0.5\), calibrated on eight windows, and only smoothed c_attn and c_fc. It is not a full SmoothQuant reproduction.
  • No fused int4 execution. The very slow int8 and int4 rows dequantise afresh every call and do not measure production weight-only kernels.
  • Non-equivalent int8 GEMM comparison. torch._int_mm uses independently sampled integer inputs, different accumulation and padded columns; conversion and output scaling are excluded.
  • No KV-cache quantisation, task accuracy, energy, detailed error attribution or hardware-profiler counters. These require separate experiments.

Inference Lab increment

The Lab now has:

  • quantize_dequantize(w, bits, group, symmetric): simulate reconstruction and estimate effective packed bits per weight, including assumed scale and zero-point widths. It does not emit a deployable packed checkpoint.
  • fake_quant_activation, smoothing_scales, pack_int4 and unpack_int4: numerical experiments and an int4 packing round-trip. Packing assumes an even first dimension; a production serializer needs shape, alignment and metadata checks.
  • evaluate(model_q, model_ref, windows): report perplexity, teacher-forced top-1 agreement and forward KL on the same fixed token windows.
  • formats, weights, quality and speed: runnable experiments with different hardware requirements. The test suite checks the arithmetic helpers, not the GPU-wide quality and performance tables.

The required next-stage artefact contract extends From Training to Execution’s manifest concept; it is not yet automatically implemented by the Chapter 12 CLI. A saved quantised model should record its parent checkpoint and immutable digest; quantiser implementation/version; numeric format, signedness, scale dtype, zero-point convention, channel/group axis and size; exactly which parameters were converted or protected (including tied embeddings); packing layout; calibration corpus identity and method; runtime kernel and accumulation dtype; and measured quality thresholds. The packed weight bytes and metadata must be hashed together. Changing any of these can change outputs or invalidate cache identity from Key-Value Caching. The current workbench proves numerical concepts; it does not yet enforce that full manifest contract.

The evidence rule is unchanged: report storage, reconstruction error, model behaviour and performance separately. For reproducibility, label each result as a theoretical packing estimate, a floating-point simulation, an isolated kernel benchmark or an end-to-end deployment measurement. Confusing those stages is the commonest way to turn a promising experiment into an unjustified product claim.

What you should now be able to do

  • Read the range and precision of fp32, fp16, bf16 and the two fp8 variants without claiming that format availability guarantees kernel support.
  • Derive nominal bits per weight, including scale and zero-point metadata, and distinguish that estimate from actual file size and resident GPU memory.
  • Explain tensor-, channel- and group-wise quantisation for [input, output] weights and measure the reconstruction error of each.
  • Compute perplexity, teacher-forced top-1 agreement and KL divergence on the same scored positions, and explain what they do not tell us about open-loop text generation.
  • Show why equal weight-norm errors can have very different consequences when applied to a tied embedding’s input and output roles.
  • Explain why per-tensor activation scaling fails on these measurements, what per-token scaling changes, and which parts of SmoothQuant were not implemented.
  • Separate fused int8 GEMM throughput from an end-to-end W8A8 claim; identify when dequantisation destroys any apparent speed benefit.
  • Specify the metadata, quality gates and kernel-parity tests needed to turn fake quantisation into a real compressed inference artefact.

Key terms

  • Quantisation / fake quantisation: mapping real values to a discrete grid; in fake quantisation, reconstructing floating-point values before normal floating-point execution.
  • Scale / zero point: metadata mapping integer codes to real values; its precision and grouping affect reconstruction.
  • Granularity / group size: the tensor, output channel, or input-coordinate block that shares quantisation metadata.
  • Weight-only / W8A8: reducing weight precision alone, or representing both weights and activations in eight bits. The W8A8 result here is numerically simulated, not executed as an integer model.
  • Outlier / calibration: an unusually large value that affects a scale; using representative data to choose scales, smoothing or a quantisation policy.
  • Perplexity / top-1 agreement / KL: reference-text prediction quality; agreement of teacher-forced most likely next tokens; drift in full next-token distributions.
  • Fused dequantisation / packing: direct consumption of packed low-bit weights by an execution kernel, rather than reconstructing a whole floating-point matrix first.
  • Tied embedding: one parameter table serving both input lookup and output projection, whose two uses can have different sensitivity to quantisation.

Reader exercises

  1. Repeat the group-size sweep and graph perplexity and nominal packed bits per weight on the same axes or table. Is reconstruction error alone a reliable selection criterion?
  2. Repeat the 12-window tied-embedding ablation with output-side group-32 and group-64 int4; record top-1 agreement and logit-error standard deviation as well as perplexity.
  3. Change only one projection layer at a time and rank per-layer output sensitivity; compare that ranking with the layers’ Frobenius reconstruction errors.
  4. Expand the W8A8 smoothing experiment to all four projection types in simulation. Then run an \(\alpha\) search only on calibration text and evaluate the chosen value on held-out text once.
  5. Re-run fp16, bf16 and selected int8 schemes on a second corpus and report paired per-window perplexity changes and uncertainty; do not call a difference noise without testing it.
  6. Save and reload a genuinely packed int4 checkpoint with scales, zero points and layout. Verify its byte size, hash, round-trip weight reconstruction and tied-parameter behaviour.
  7. Implement or use a fused weight-only kernel; compare it with the unfused conversion path on the same inputs, separating packing, memory, execution and decoding time.
  8. Quantise the same fp16 activations for an int8 GEMM, rescale its int32 output, and check maximum logit error and end-to-end TTFT/TPOT versus fp16.
  9. Test a context-length and batch-size sweep, including KV-cache residency, before claiming the quantised model fits or runs faster in a serving workload.

References

Evidence in this chapter

Claim Evidence category and limit
Floating-point ranges/epsilon and the symmetric quantisation formula Format documentation and stated arithmetic assumptions; no fp8 execution result
48 projection matrices and their heavy-tailed weight statistics Recorded GPT-2 weight analysis; not the distribution of all parameters
Per-tensor versus per-channel/group weight reconstruction Recorded relative Frobenius errors; not task accuracy
fp32 perplexity 62.69 and all quantisation-quality rows One checkpoint, 57 windows, 29,127 scored positions; teacher-forced perplexity, agreement and KL
fp16 and bf16 model dtype effects Model dtype comparisons including activations, not weight-only fake quantisation
Integer-scheme memory numbers (approximately 97–158 MiB) Hypothetical packed parameter estimates; not measured saved/resident memory
Per-channel int8 perplexity difference of −0.13% Local observation; no significance or equivalence test
Int4 input-only vs output-only tied-embedding results Book experiment on 12 windows; 61.0 versus 8,123; not a general rule for every LM head
Hidden-state norm contributes to output sensitivity Hypothesis; logit-error variance observed, causal role not isolated
W8A8 per-tensor, per-token and partial smoothing quality Fake-quantised model results; no end-to-end integer W8A8 execution
Unfused int8/int4 conversion slows GEMM up to 6×/26× Book microbenchmark of unfused conversion on RTX 2060, not fused low-bit hardware throughput
_int_mm output-projection timing ~1.55× versus fp16 Isolated, non-equivalent-input integer GEMM with padded width; excludes conversion and rescaling
GPTQ, AWQ, full SmoothQuant, real packed checkpoint, KV quantisation, task quality, fused int4 speed Not evaluated or implemented in this chapter