Elamur Research

Understanding and Overcoming the Challenges of Efficient Transformer Quantization

Paper · 2021 · Yelysei Bondarenko, Markus Nagel and Tijmen Blankevoort

Summary

Reducing the number of bits used in a neural network can make it much smaller, but the simplest way to do it can badly damage its predictions. This paper investigates why that happens in BERT, an encoder built from repeated Transformer and attention layers. The authors find that the main difficulty lies in activations, the intermediate values computed for each input. In particular, a few feature dimensions repeatedly contain unusually large values around the residual addition after the feed-forward network. Giving the whole tensor a range wide enough to include these values leaves a coarse grid for ordinary values. Choosing a finer grid over a narrower range clips the extremes. The large values also appear to serve a purpose: in the attention head the authors examine, a few dimensions make a strong contribution to directing attention toward the special separator token.

The authors try three ways to preserve the information carried by these activations. Mixed-precision post-training quantization gives selected values 16-bit precision while keeping weights and most activations at 8 bits. Per-embedding-group quantization keeps activations at 8 bits and gives different groups of feature dimensions their own numerical ranges. The groups are formed by sorting dimensions according to their observed ranges, so that the ones with extreme values can share a scale. Both approaches start from an already trained checkpoint. The third approach, quantization-aware training, simulates rounding and clipping during task-specific training so that the weights and numerical ranges can adapt together.

On the development sets of GLUE, excluding WNLI, the full-precision BERT-base baseline scores 83.06. Standard 8-bit post-training quantization of weights and activations scores 71.03. Mixed precision brings the aggregate to 82.43, grouping brings it to 82.45, and 8-bit quantization-aware training reaches 83.26. The similar aggregate scores for the two post-training methods leave a practical choice. Mixed precision needs support for higher-bit operations at selected points. Grouping keeps a common bit-width and introduces extra work where the groups meet.

The authors also examine how far they can compress the stored weights and token embeddings. With quantization-aware training, 4-bit weights, 8-bit activations, and 2-bit token embeddings give a GLUE development score of 82.29 and a reported ×8.85 reduction in memory relative to the full-precision checkpoint. The result concerns the size of the stored network and its scores on the benchmark. The paper leaves actual device latency and energy savings unmeasured.

Deep dive: Understanding and Overcoming the Challenges of Efficient Transformer Quantization

Why a few unusually large activations make BERT hard to quantize, and how mixed precision, feature grouping, and training recover performance. · about 33 minutes to read

The problem and its context

Why shrinking the numbers can change the predictions

A Transformer encoder uses its weights repeatedly to turn a sequence of input tokens into representations suitable for a downstream task. The weights are stored with the network. Activations are produced as the network processes a particular sequence, and each stage passes some of those values to the next. Low-bit weights reduce the space needed to store the network. Low-bit activations make it possible for operations involving those activations to use lower-precision arithmetic as well. A deployment can benefit from one change without getting the benefits associated with the other.

Quantization is the conversion that makes this possible. A set of representable levels stands in for the more finely spaced values available in floating point. Each value is rounded to a nearby level. Values beyond the available interval are clipped to an endpoint. The error can be small enough that predictions barely change, or it can interfere with calculations the network relies on. A bit-width gives the number of levels the quantizer can use. The range determines where it puts those levels, and the granularity determines how many values have to share them.

These decisions interact. When a tensor contains largely small values and a few much larger ones, a wide interval accommodates the extremes and puts more distance between neighboring levels. Two ordinary values with meaningfully different magnitudes may then round to the same place. A narrow interval can preserve those distinctions and still distort the large values. Treating the large values as expendable would make sense only if the network can tolerate the distortion. One question the authors pursue is whether the most conspicuous values are also the ones that the network needs to preserve.

This matters because the paper's account of deployment treats memory, latency, and energy as practical barriers to running pretrained encoders. Fewer bits reduce the storage required for a tensor, and fixed-point matrix multiplication offers a route to lower arithmetic cost. The device has to support the representation and operations for these advantages to translate into faster inference. Giving every tensor its own elaborate representation could preserve predictions and make the calculation harder to execute efficiently. The paper is therefore concerned with representations simple enough to use as well as accurate enough to trust.

What efficiency research had already addressed

The paper places quantization alongside other efforts to make Transformers cheaper. Much of the work it discusses changes self-attention, where each token's representation is updated using information from other positions. A dense attention calculation becomes expensive on long sequences. Some approaches restrict which positions may interact, using fixed or learned sparsity. Others approximate dense attention using low-rank or kernel methods. The paper cites the original Transformer and discusses Longformer as an example of work on efficient attention for long inputs. Attention Is All You Need

Other work reduces the cost of the network more broadly. The strategies the authors describe include reusing weights across layers, reusing parameters across tasks, removing parameters through pruning, and designing compact architectures. Distillation trains a smaller student to reproduce behavior from a larger teacher. Those approaches can change which computations are performed or how many parameters they require. Quantization changes the numerical representation of a computation, so a researcher can investigate it on an existing checkpoint. The paper's examples of compact or distilled systems include MobileBERT and DistilBERT.

Earlier work had established the use of integer arithmetic in quantized neural networks, particularly for computer vision. The paper also discusses 8-bit post-training quantization for machine translation. In the work it cites, one translation system combined distillation with quantization, while another showed how specialized hardware could accelerate quantized inference. The authors draw on the established method of simulating quantization and its reconstruction in floating point while assessing the effect of the grid. Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference

For BERT-like encoders, the paper describes a different balance in the preceding work. Q8BERT used an 8-bit scheme with training, and Q-BERT assigned precision according to layer sensitivity estimated using Hessian information, which concerns the curvature of the training objective. I-BERT concentrated on fully integer inference, using polynomial approximations for operations such as GELU, softmax, and layer normalization. These papers addressed questions about compression, precision, or arithmetic. As the authors characterize the literature, BERT-focused studies usually relied on some form of quantization-aware training and gave post-training conversion a smaller role.

Why start with a trained checkpoint

Post-training quantization, or PTQ, starts from a network whose weights have already been learned. It establishes numerical ranges and converts the stored values and intermediate computations to the desired precision. A static activation range can be set with a small calibration sample and then reused for subsequent inputs. This makes PTQ attractive when the training process would be expensive to repeat or the labeled task data would be inconvenient to obtain. It also makes the experiment diagnostic: the authors can change how a trained computation is represented while holding its weights fixed.

Quantization-aware training, or QAT, lets the computation adapt to simulated low precision. An improvement under QAT can come from better numerical ranges, from updated weights, or from their interaction. PTQ offers a more direct starting point for asking which part of the original computation was poorly represented. Once the authors identify a sensitive operation, they can ask whether it needs more bits, whether its values should use different scales, and whether training can compensate when the representational scheme stays simple.

An encoder is particularly informative for this investigation because a residual connection brings two streams of values back together. The feed-forward branch transforms its input, then the residual addition combines that transformation with the branch's input. The sum becomes part of the representation used later in the encoder. A large spread in the transformed values can therefore affect the precision available to values carried through the shortcut as well. A quantization scheme that looks reasonable for either stream in isolation can behave quite differently at the point where they meet.

The method, step by step

From a floating-point value to an integer code

The paper uses uniform affine quantization. “Uniform” means neighboring levels are evenly spaced. “Affine” means there is both a scale that sets the spacing and a zero point that locates real zero on the integer grid. The quantizer first divides by the spacing, rounds to a grid position, shifts by the zero point, and clips to the allowed set of codes.

x⁽ℤ⁾ = clip(round(x / s) + z, 0, 2ᵇ − 1)

Here x is a real-valued input tensor, and x⁽ℤ⁾ is the tensor of integer codes. The superscript ℤ indicates an integer representation. The positive scale s is the spacing between consecutive reconstructed values. The integer z is the zero point. b is the bit-width, round chooses the nearest integer, and clip bounds each value by the endpoints supplied as its last arguments. The lower code is 0, and the upper code is 2ᵇ − 1, where 2 is the base of the binary representation and 1 is subtracted to obtain the last code on a grid that starts at zero. Division, rounding, shifting, and clipping apply element by element.

The paper assesses the effect of that discrete grid by reconstructing approximations to the original real-valued entries. The reconstruction subtracts the zero point and multiplies by the spacing. This is called dequantization.

x̂ = q(x, s, z, b) = s · (x⁽ℤ⁾ − z) ≈ x

The hat in x̂ marks the reconstruction. The function q denotes quantization followed by dequantization, given input x, scale s, zero point z, and bit-width b. The tensor x⁽ℤ⁾ holds the integer codes from the preceding step. The dot denotes multiplication, and ≈ indicates an approximation. Rounding changes values between representable levels, and clipping changes values outside the range.

The authors ordinarily use symmetric quantization for weights and asymmetric quantization for activations. A symmetric grid represents a range centered at real zero. With asymmetric quantization, the represented interval can extend farther on one side of zero than on the other. That freedom matters when the data occupy an uneven interval. In either case, at a fixed bit-width, widening the interval spreads the same available codes farther apart.

The implementation simulates these operations in floating point to measure their numerical effect. Thus an experiment can ask how predictions change when values are confined to a particular fixed-point grid. The subsequent arithmetic argument about grouping explains what scales can be applied outside an integer accumulation and what operations would be needed to realize the scheme on suitable hardware.

Setting ranges before inference

The authors use static activation ranges. They pass calibration data through the network, estimate the required intervals, and hold those ranges fixed for inference. A range estimated this way can be applied without analyzing the minimum and maximum of every new input. Weight ranges can be estimated from the stored tensors themselves. For activation ranges, the estimator sees examples because the tensors depend on the input sequence.

The paper considers several estimators. Current min-max uses the observed minimum and maximum. Running min-max smooths the extrema over multiple batches with an exponential moving average. For the running estimator, the paper uses a momentum coefficient of 0.9. The mean squared error estimator, abbreviated MSE, chooses a range that minimizes the squared reconstruction error averaged over the entries. It can favor a narrower interval if giving up some accuracy at the extremes improves the reconstruction across the tensor.

The initial 8-bit PTQ investigation searches over estimators for weights and activations, and over calibration batch settings for activations. Current min-max uses a single batch. Running min-max can use several batches, and its estimate depends on the sequence of extrema seen during calibration. The best setting is chosen separately for each task by its development score. In the subsequent comparisons of the proposed methods, the weight range for 8-bit quantization comes from the earlier search, while the ordinary activation ranges use min-max from a single input sequence. Grouped activation ranges require a further calibration operation to determine which dimensions share a quantizer.

The initial investigation gives the authors a way to locate the sensitive values. They first quantize weights and activations together, then separately. Within activation quantization, they leave selected tensors in floating point and check which exemption restores the most performance. The problematic tensor is the residual sum after the feed-forward network, abbreviated FFN. Its numerical difficulty is visible in the distribution of the FFN's inputs and outputs. A broad output range can force a large spacing when the branch values have to be represented together at the addition. A scheme that instead follows the narrower input range can clip the output.

Giving sensitive activations more bits

The mixed-precision post-training method, called MP-PTQ, starts from 8-bit activations and gives selected tensors a 16-bit grid. The wider grid has enough levels to cover a broad interval with finer spacing. This lets the method preserve smaller differences in the presence of large values. The weights in the main mixed-precision comparison remain at 8 bits.

The paper tests an ordered set of changes. It first gives the FFN residual sum the higher precision. It next adds the FFN input and output, keeping more of the computation on either side of the addition at higher precision. For the similarity regression task, it also evaluates a higher-precision final output, using MSE to estimate that range. This final output is a separate location from the FFN residual sums inside the encoder. The design lets the authors check whether the residual computation accounts for the score loss and whether the last stage introduces an additional precision bottleneck.

Mixed precision retains a single grid for each quantized tensor. It changes how many bits are available at the sensitive sites. As a consequence, its implementation depends on whether the hardware can execute the chosen mix of precisions and how much the more expensive operations contribute to the total work. The paper evaluates the number of activation quantizers receiving higher precision and the resulting task scores.

Giving feature groups separate scales

The grouped method begins with a different observation. The unusually large values are repeatedly found in a small set of feature dimensions. A hidden activation records features for every token in every sequence in a batch. The same feature index occurs at every token position. If that index regularly has a large range, giving it a separate quantizer can keep its values from dictating the spacing for a feature whose values occupy a much narrower interval.

shape(x) = (B, T, d)

The function shape gives the dimensions of the hidden activation tensor x. The first axis, B, is the batch size. The second, T, is the sequence length. The last, d, is the number of features, called embedding dimensions in the paper. For BERT-base, d is 768. These coordinates belong to the intermediate representation at a layer. Grouped activation quantization acts on this feature axis, while later experiments on token embedding compression reduce the precision of the stored lookup values for input tokens.

A separate quantizer for every dimension would allow each feature to use its own range. The scale and zero point would each have one entry per feature, and an entry would be shared across the batch and token axes. The paper describes the elementwise quantization and reconstruction formulas as broadcasting along the feature axis. Broadcasting here means that the same feature's quantization settings are reused wherever that feature appears in the tensor.

That fine granularity changes the arithmetic of a linear layer. To show what changes, the authors take a matrix-vector product and assume zero points of zero. With a single weight scale and a single activation scale, the product of those scales is common to every term in the accumulation.

(Ŵx̂)ᵢ = sʷ · sˣ · ∑ⱼ₌₁ᵈ Wᵢⱼ⁽ℤ⁾ · xⱼ⁽ℤ⁾

Here Ŵ is the reconstructed weight matrix, x̂ is the reconstructed activation vector, and i identifies an output coordinate of their product. sʷ is the weight scale, and sˣ is the activation scale. ∑ⱼ₌₁ᵈ adds over input coordinates indexed by j, starting at 1 and ending at the feature count d. Wᵢⱼ⁽ℤ⁾ is the integer weight code at row i and column j, and xⱼ⁽ℤ⁾ is the integer activation code at coordinate j. A dot indicates multiplication. The integer products are accumulated before the shared scale is applied.

Now keep the same weight quantizer and assign a separate activation scale to each feature. The corresponding scale travels into the sum.

(Ŵx̂)ᵢ = sʷ · ∑ⱼ₌₁ᵈ sⱼˣ · Wᵢⱼ⁽ℤ⁾ · xⱼ⁽ℤ⁾

Ŵ, x̂, and i again identify the reconstructed matrix, the reconstructed vector, and the output coordinate. sʷ is still shared by the weights. sⱼˣ is the activation scale for input coordinate j. The sum runs from 1 to d over the indexed integer weight and activation codes, Wᵢⱼ⁽ℤ⁾ and xⱼ⁽ℤ⁾. The dots denote multiplication. A different factor for each term prevents a single activation scale from being applied to the full integer sum afterwards.

The proposed compromise is per-embedding-group quantization, abbreviated PEG. The authors split the feature axis into equally sized groups. Every feature in a group uses that group's scale and zero point. For the zero-point assumption used in the matrix-vector example, the reconstructed vector is assembled as follows.

x̂ = [s₁ˣ · [x₁⁽ℤ⁾, …, x_d⁄K⁽ℤ⁾], …, sₖˣ · [x_(d−d⁄K+1)⁽ℤ⁾, …, x_d⁽ℤ⁾]]

In this expression x̂ is the reconstructed vector. The outer brackets mean concatenation, or joining the displayed subvectors along the feature axis. The inner brackets collect consecutive integer codes x⁽ℤ⁾ in the current feature order. K is the number of equal groups, d is the feature count, and d⁄K is the number of features per group. The first subvector starts at coordinate 1 and ends at d⁄K. The last starts immediately after coordinate d−d⁄K and ends at d. The scales s₁ˣ and sₖˣ belong to the first and last groups, respectively, with the subscript ₖ denoting the final group indexed by K. A dot means multiplying each entry of a subvector by its group scale. The ellipses stand for the intervening entries or groups. In the affine implementation, dequantization also subtracts each group's zero point.

Within a group, the activation scale can be taken outside the sum of integer products. Distinct groups still have to be brought onto compatible scales when their contributions are added. The number of scale applications on that side of the calculation goes from one per feature in the finest scheme to one per group. The choice of which features share each scale becomes important precisely because the authors want to keep the number of groups small.

Sorting the dimensions before calibration

The authors first pass calibration data through the unquantized network. For each feature they record the span of the activation values observed over the batch and token axes.

rⱼ = max(x[:, :, j]) − min(x[:, :, j])

rⱼ is the observed range for feature index j in activation tensor x. Each colon inside the brackets selects all available positions on its axis. The first colon covers the batch and the second covers the token positions. The last index selects a single feature. max and min return the largest and smallest values in that selection, and the minus sign gives the width of the interval between them.

The authors sort the feature indices by these range estimates and form equal groups in the resulting order. Features with the largest observed ranges then sit near one another. A subsequent range-estimation pass establishes separate quantization settings for the groups. Group membership is determined once before deployment, so the ordering remains fixed as new inputs are processed. The input can produce different activations at inference time without triggering another sort.

The main experiments use this procedure only for the FFN input, output, and residual sum. The authors use one permutation for those tensors, expecting the extreme output values to govern the ordering. Sharing the permutation also aligns the feature indices on both sides of the residual addition. A feature moved to a new position on one branch has to occupy the corresponding position on the other branch for the addition to represent the original computation.

Calibrating and applying per-embedding-group quantization

The steps in order.

Calibrating and applying per-embedding-group quantizationStep 1: Run calibration inputs through the unquantized network1. Run calibration inputs through the unquantized networkStep 2: Record the observed range of each feature2. Record the observed range of each featureStep 3: Sort feature indices by range3. Sort feature indices by rangeStep 4: Divide the sorted indices into equal groups4. Divide the sorted indices into equal groupsStep 5: Calibrate a quantizer for each group5. Calibrate a quantizer for each groupStep 6: Quantize the feed-forward input, output, and residual sum6. Quantize the feed-forward input, output, and residual sumStep 7: Restore feature order before the next layer normalization7. Restore feature order before the next layer normalization

The authors also explain how to express the grouped computation using ordinary per-tensor quantization operations. They start by permuting and splitting the output of the first layer normalization along the feature axis. Layer normalization transforms the features using statistics computed across that axis. Reordering the features preserves those statistics, and its feature-specific parameters can be placed in the corresponding order. The linear-layer weights can likewise be rearranged ahead of inference so that the reordered input meets the matching weight columns.

The first linear layer is split by input columns. Each smaller operation sees one activation group and produces a partial contribution to the same output. Summing these contributions element by element reconstructs the first layer's full linear output. The second linear layer is split by output rows. Its smaller operations produce separate slices of the output features. Those slices are concatenated in the chosen order before the residual addition, and the inverse permutation restores the ordinary feature order before the next layer normalization.

The equivalence concerns how the underlying operations are rewritten. In the quantized computation, summing group contributions can require rescaling and requantization. The paper counts the additional parameters used to record the permutation and each group's quantization settings as follows.

d + 2 · 3 · K

Here d counts the feature indices stored for the permutation. The factor 2 counts a scale and a zero point for every group. The factor 3 counts the FFN input, output, and residual sum, and K is the number of groups. Addition combines the two types of extra storage, and the dots indicate multiplication. The expression is a count per attention layer. The authors report that the overhead is less than 0.04% of BERT-base's total size. The arithmetic overhead comes from a different source, namely splitting the computation and combining values represented on different grids.

Letting training adapt to the grid

In the quantization-aware approach, the forward computation includes simulated rounding, clipping, and reconstruction. The task loss is therefore evaluated using activations and weights that have experienced the quantization error. The authors initialize the quantizer parameters from their PTQ setup and let the ranges of both weights and activations be learned during fine-tuning. The network can compensate for a change in representation by changing its weights as well as by changing the ranges.

Rounding presents a problem for gradient-based training. Small movements inside a rounding interval leave the code constant, and crossing a boundary changes it abruptly. The paper describes the straight-through estimator for this situation. It substitutes an approximate gradient through the quantization operation so that the effects of the task loss can still be communicated to the underlying trainable values. The forward operation continues to expose the training procedure to the discrete grid.

The starting checkpoint is uncased BERT-base from Hugging Face, with 109M parameters. Input sequences are tokenized and truncated at a maximum length of 128. Sequences that are shorter are padded with [PAD]. For the full-precision baseline, the authors train for 3 epochs and decay the learning rate linearly from its initial maximum to zero. They select the task-specific batch size and maximum learning rate by development performance. Quantization starts from the median checkpoint for the corresponding task. The optimizer used in full-precision fine-tuning and QAT is Adam.

For QAT, the learning rate first rises linearly during the initial 10% of training steps and then falls linearly to zero. For every task in the 8-bit experiments, the authors explore different settings for self-attention dropout, epoch count, batch size, and the maximum learning rate. Dropout controls how much of the attention computation is randomly suppressed during training. The paper gives a separate hyper-parameter search for lower-bit weights. The PTQ experiments report medians across five random seeds. The main QAT comparison selects the best setting by the median across three seeds for the task.

The weight and embedding experiments extend the same setup to smaller bit-widths. Below 8 bits, the paper uses MSE to estimate weight and token embedding ranges. One post-training comparison adds AdaRound, which optimizes the rounding choices for weights. The authors use 1024 random sequences for that optimization. The paper accompanies the experiments with the authors' transformer-quantization code.

Experiments and results

What the benchmark comparisons measure

The authors evaluate task-fine-tuned BERT-base on the development sets of GLUE. The benchmark tests several kinds of language understanding, so its component scores represent different decisions or predictions. MNLI, QNLI, and RTE are treated as classification tasks in the paper's discussion of the sensitive cases. STS-B is a regression task, where the prediction is a numerical similarity score. The tables use the GLUE task metrics, all with higher scores preferred, and summarize the included tasks with an aggregate GLUE score.

The main results cover eight tasks. WNLI is omitted from the score tables because the authors consider its development behavior unstable and point to issues in the dataset's construction. Some of the diagnostic activation plots include WNLI inputs. Those plots show ranges and can be read independently of which datasets contribute to the aggregate score.

Precision labels identify which values have been quantized. In W8A8, the weights and activations use 8 bits. W32A8 retains full-precision weights while quantizing activations, and W8A32 does the reverse. In W8A{8,16}, the weights are at 8 bits and the activations use a mix of 8 and 16 bits. The initial standard PTQ baseline quantizes the weights and the input and output activations of the layers. The authors select the best calibration configuration for that baseline separately by task.

The cost of ordinary post-training quantization

With full precision, the aggregate development score is 83.06. Standard joint 8-bit PTQ scores 71.03, and activation-only quantization scores 70.25. Weight-only quantization scores 83.23. Those settings isolate the main difficulty at this precision. The drop occurs when the activations are confined to their integer grids, including when the weights retain their original precision.

The per-task values make the variation visible. On the MNLI development set, the full-precision score is 84.91, joint PTQ scores 50.31, and weight-only PTQ scores 84.58. On QNLI, the respective development scores are 91.58, 52.32, and 91.43. Under the same joint PTQ setup, SST-2 scores 92.55 against the full-precision result of 93.12. MRPC scores 88.53 against 88.36. The magnitude of the activation problem therefore depends on the task being evaluated. Results on a task that happens to tolerate the change would give a misleading picture of how broadly the setting can be used.

The weight-only aggregate is slightly above the full-precision aggregate for these checkpoints and tasks. Individual task values move in both directions. The result supports the authors' decision to concentrate their initial diagnosis on activations and to return separately to the question of how low weight precision can go.

Comparing the proposed methods

BERT-base quantization settings on the GLUE development aggregate

Both post-training methods recover most of the lost performance, and quantization-aware training gives the highest score.

BERT-base quantization settings on the GLUE development aggregateFull precision: 83.06Full precision83.06Standard W8A8 PTQ: 71.03Standard W8A8 PTQ71.03Mixed-precision PTQ: 82.43Mixed-precision PTQ82.43Per-embedding-group PTQ: 82.45Per-embedding-group PTQ82.45W8A8 quantization-aware training (this paper): 83.26W8A8 quantization-aware training (thispaper)83.26
The numbers
System or settingGLUE score
Full precision83.06
Standard W8A8 PTQ71.03
Mixed-precision PTQ82.43
Per-embedding-group PTQ82.45
W8A8 quantization-aware training (this paper)83.26

The mixed-precision result uses the higher-precision settings chosen through the preceding comparisons. The grouped result uses K = 6 groups and range-based sorting for the FFN input, output, and residual sum. Other activation tensors retain per-tensor quantization. Both methods bring difficult tasks back near their full-precision scores, although their recovered scores vary by task.

On STS-B, mixed precision scores 88.00 and grouping scores 87.92, with a full-precision development score of 89.09. On MNLI, mixed precision reaches 82.67 and grouping reaches 81.25. Grouping does better on QNLI, with 91.07 against 90.41 for mixed precision. On RTE it scores 69.31 against 68.95. Each method gives the sensitive region of the computation more usable resolution. The way it supplies that resolution changes where the remaining score losses fall.

The 8-bit QAT result uses per-tensor quantization. Its STS-B development score is 88.95, its MNLI score is 83.74, and its RTE score is 70.40, the same as the full-precision baseline on that task. On QNLI it scores 90.48, while grouped PTQ scores 91.07. The aggregate for QAT leads the comparison. Its QNLI result illustrates why that overall ranking cannot be transferred to each task individually. The aggregate also combines the effects of training and the choice of per-task training settings.

Comparisons with prior quantization results

The comparison table gives Q8BERT aggregates of 80.13 for PTQ and 82.38 for QAT. Both are macro-averages without MNLI, so they have different coverage from the new aggregates. Q8BERT also reports F1 for MRPC and QQP and Pearson correlation for STS-B, while the new experiments use the corresponding combined metrics. Its PTQ setup uses dynamic activation quantization, and both its listed configurations leave softmax, GELU, and layer normalization in full precision. The comparison includes these differences in arithmetic and reporting.

The table also includes Q-BERT, which uses grouped per-channel weight quantization with 128 groups and retains its final fully connected layer in full precision. It reports only a subset of the task scores in the main comparison. On SST-2, for example, Q-BERT reports 92.88, compared with 93.00 for the authors' 8-bit QAT setup. Each study begins with its own full-precision baseline. The authors present their overall results as advancing post-training quantization and per-tensor QAT for BERT on GLUE. The common tasks, the granularity, and the operations retained in floating point are the relevant conditions for reading those comparisons.

Compressing weights and token embeddings further

The lower-bit experiments ask whether BERT's apparent tolerance of quantized weights extends below 8 bits. With full-precision activations, 6-bit weight PTQ scores 81.41 and has a reported memory reduction of ×5.33. Standard 4-bit weight PTQ scores 72.31 at ×8.00. Adding AdaRound at the same bit-width and with full-precision activations brings the score to 81.46. The memory reduction remains ×8.00. This comparison isolates the importance of the rounding choices in a setting where each weight has much less numerical resolution.

Low-bit weight and embedding settings on the BERT-base GLUE development aggregate

Training recovers most of the score lost at low weight precision and supports further compression of token embeddings.

Low-bit weight and embedding settings on the BERT-base GLUE development aggregateFull precision: 83.06Full precision83.06W6A32 PTQ: 81.41W6A32 PTQ81.41W4A32 PTQ: 72.31W4A32 PTQ72.31W4A32 PTQ with AdaRound: 81.46W4A32 PTQ with AdaRound81.46W4A32 QAT (this paper): 82.95W4A32 QAT (this paper)82.95W4A8 QAT: 82.64W4A8 QAT82.64W4A8 QAT with 2-bit token embeddings: 82.29W4A8 QAT with 2-bit token embeddings82.29
The numbers
System or settingGLUE score
Full precision83.06
W6A32 PTQ81.41
W4A32 PTQ72.31
W4A32 PTQ with AdaRound81.46
W4A32 QAT (this paper)82.95
W4A8 QAT82.64
W4A8 QAT with 2-bit token embeddings82.29

With QAT, 4-bit weights paired with full-precision activations score 82.95. Using 8-bit activations with those weights gives 82.64. The paper reports ×8.00 memory reduction for both. Reducing the token embeddings to 2 bits brings the reported reduction to ×8.85 and produces a GLUE development score of 82.29. The authors describe that score as a drop of less than 0.8% relative to the original full-precision checkpoint.

A separate embedding comparison keeps other weights at 8 bits and activations in full precision. On the GLUE development aggregate, it gives 82.88 with 6-bit token embeddings, 82.73 with 4-bit embeddings, and 82.40 with 2-bit embeddings. This comparison narrows the intervention to the stored lookup table. The combined result with low-bit weights and 8-bit activations then tests how much of that tolerance survives while other parts of the calculation are also quantized. Taken together, these measurements describe the storage and score tradeoff under the tested settings.

What the ablations show

Locating the sensitive operation

The authors' leave-one-out experiment starts from a network with activation quantizers throughout and removes them from one category of tensors at a time. The weights stay in full precision. The activation quantizers use current min-max with batch size 1, a controlled setting for comparing exemptions. The paper looks at difficult development tasks including STS-B, MNLI, QNLI, and RTE. It reports medians over 5 runs.

Under this setup, quantizing all activations gives MNLI a development score of 42.67. Exempting the input to softmax gives 42.54. Exempting its output gives 50.35. The other tested exemptions include the sum of embeddings and the output of self-attention. Leaving the residual additions after the FFNs in full precision gives 82.56, near the full-precision development score of 84.91. Exempting only those sums in layers 10 and 11 gives 81.24. The contrast between softmax and the FFN sum identifies where the choice of representation does the most damage under this calibration setting.

QNLI shows the same pattern. With all activations quantized, the development score is 50.74, compared with 91.58 in full precision. Exempting the FFN residual sums yields 89.73. Restricting the exemption to layers 10 and 11 gives 88.03. On RTE, the all-activation setting scores 48.74, the exemption across all FFNs scores 67.15, and the deeper-layer exemption scores 63.90. The strongest effect concentrates in the deep residual sums, with some additional recovery from exempting the sums throughout the encoder.

This experiment answers a question different from whether a high-precision FFN sum can improve the final deployment setup. It holds the activation quantization procedure fixed and identifies the exemption that brings back the most score. The later mixed-precision experiments then ask how much of that recovery can be retained when the exemption becomes a finite increase in precision.

Where the large values occur

To understand the numerical mechanism, the authors inspect the input and output of the FFN in BERT-base's 11th layer in full precision. One view compares the ranges for individual tokens in the first MNLI development sequence. The output ranges are much wider than the input ranges. A second view shows which embedding dimensions contain extreme values across the first ten development sequences. Values more than six standard deviations from the tensor mean are marked. The same dimensions recur across examples.

The visualizations give two reasons to treat the problem at the feature level. The first is that the FFN output can dominate the range at the addition. An interval set for that output can lead to coarse rounding of the smaller input values. The second is that the extreme values are concentrated along the feature axis. A group of features with a relatively ordinary spread can therefore use a finer grid even when a few other dimensions require a much wider one.

The appendix shows recurring feature positions across layers of BERT-base and visualizes examples from MNLI, STS-B, and MRPC. It also compares full-precision FFN input and output ranges in pretrained BERT-large, DistilRoBERTa, MobileBERT, and RoBERTa. The plotted ranges support the idea that the mismatch can recur across architectures and training objectives. The authors infer from the regularity across examples that learned weights and embeddings help determine which dimensions become extreme.

How those values relate to attention

The attention visualization follows the analysis into the next attention calculation. A query describes what a token can match, and a key describes what another position presents for matching. Their dot product is a sum of feature-by-feature products. Attention depends on that sum, so a few especially large positive products can strongly favor a position even when many other features contribute little.

exp((qᵢ · kⱼ) / √d)

Here qᵢ is the query vector for token position i, and kⱼ is the key vector for position j. The dot between the vectors is their dot product. In this expression d is the dimension used to scale the query-key product, and √d is its square root. exp is the exponential function. The expression gives the unnormalized quantity in the attention visualization. Softmax normalizes such quantities across the candidate keys to obtain attention probabilities for a query.

The figure looks at the 6th head in the 11th layer of BERT-base, using the first development sequence from MNLI. In the view showing attention between tokens, many queries concentrate on [SEP]. The companion view breaks the query-key match down into products by feature. A few coordinates produce conspicuously large contributions that recur in matches involving the separator. This connects the repeated feature outliers to a recognizable pattern of attention, through the way queries and keys are formed and compared.

The paper relates this pattern to earlier attention analysis by Clark and colleagues. Their interpretation was that a head can attend to the separator when a passage lacks the pattern the head would otherwise act on. Bondarenko and colleagues suggest that the large residual values help implement this behavior and that it can be useful to prediction. They also hypothesize that architectural choices, long pretraining, and the absence of explicit activation regularization may allow the outliers to develop. The attention figure provides a view of a possible mechanism inside a trained encoder. The hypotheses about why training produces it remain open.

How much of the intervention is needed

The mixed-precision comparison progressively expands where it uses 16-bit activations. Its per-tensor PTQ starting point on QNLI is 51.73. Raising the precision of the FFN residual sums brings it to 88.38, and also raising the precision of the FFN inputs and outputs brings it to 90.41. Giving the final output higher precision leaves that result at 90.41. MNLI similarly gets most of its improvement from the higher-precision sum, with a development score of 82.20 in that setting compared with the per-tensor PTQ starting score of 45.60.

STS-B responds differently. In that comparison, the per-tensor 8-bit baseline is 79.78. The higher-precision residual sums give 85.41, and including the FFN inputs and outputs gives 85.27. The addition of a 16-bit final output raises the score to 88.00. Thus the first intervention restores much of the performance, and the last one matters for the regression score in a way it does not for the selected classification results. The authors count 36 out of 161 activation quantizers at 16 bits in the configuration they discuss, described as 22% of the activation quantizers.

The grouped comparisons vary both the scope of finer quantization and the number of groups. On the STS-B development set, using 768 separate feature quantizers throughout gives 87.87. Limiting that granularity to the FFN input, output, and residual sum gives 87.92. On QNLI, the corresponding results are 90.66 and 90.68. The selected FFN sites therefore capture much of the benefit of the finer grid, consistent with the leave-one-out experiment.

The authors then test small group counts, first with features in their original order and then after sorting by range. With K = 3 and no permutation, the development scores are 85.96 on STS-B and 80.74 on QNLI. With range-based permutation at the same group count, those scores are 87.92 and 91.07. In this comparison, changing the membership of the groups recovers much of the benefit without increasing their number. With permutation, the K = 6 setting also gives 87.92 on STS-B and 91.07 on QNLI, and it gives 81.25 on MNLI against 80.64 for K = 3. The authors use the six-group configuration in the main comparison.

The progression clarifies what makes the grouped scheme work. The important decision is which features share the same grid. With the features in their original order, a small number of groups can still leave ordinary features sharing a wide interval with extreme ones. Sorting makes the groups reflect the structure observed in calibration. The resulting quantizers concentrate the wide interval where the tensors need it and can allocate finer spacing elsewhere.

Limitations

Limits the authors state

The authors explicitly leave actual on-device performance unmeasured. Their evidence concerns task scores, low-bit representations, and the arithmetic and storage implications of those representations. Latency and energy depend on the target device. A platform may support 8-bit operations efficiently and offer less favorable execution for the higher-precision part of mixed precision. The grouped method can be expressed using per-tensor operations, but extra summation and requantization can add work. Its small parameter overhead describes stored settings and indices, which is a separate question from execution time.

The authors also describe QAT as more demanding to apply. It runs task training with simulated quantization, needs labeled data, and requires choosing training settings. The post-training methods use calibration and avoid another task-training run. The study's PTQ comparisons still include estimator selection, and the settings used in the comparison are specific enough to matter when reproducing the scores. WNLI is excluded from the main benchmark results because of the dataset and stability concerns the authors identify.

The proposed origin of the outliers is framed as a hypothesis. The authors point to architectural choices and pretraining as possible causes. Their explanation for the attention pattern also draws on an interpretation of separator attention from earlier work. These claims concern what the observed pattern could be doing and how it could arise.

Limits of the experimental setup

The main score comparisons are on GLUE development sets with task-fine-tuned BERT-base. The range visualizations across other pretrained encoders broaden the evidence that similar activation patterns occur. They leave open how much performance the proposed interventions recover in each of those encoders. The score comparisons therefore support conclusions about the tested BERT-base setup, while the cross-architecture plots support a narrower conclusion about the recurrence of the numerical problem.

The settings were selected using development performance, including the calibration search for standard PTQ and the hyper-parameter search for QAT. The reported medians help summarize variation across seeds within those experiments. A development medians comparison does not supply a separate evaluation of tuning on unseen benchmark splits. The near-equal aggregate scores for mixed precision and grouping are also consistent with visible per-task differences. They give two viable settings in the comparison without establishing a stable ranking across other task mixes.

Some displayed baselines come from different experiments. The standard W8A8 baseline in the main comparison scores 50.31 on MNLI and 52.32 on QNLI. The per-tensor PTQ starting point in the mixed-precision and grouping comparisons is 45.60 on MNLI and 51.73 on QNLI. The paper describes an estimator search for the initial investigation and a single-sequence activation calibration in the proposed-method experiments. Gains from the targeted ablations are clearest when read against the baseline in the same comparison. Results cited from earlier work introduce further differences in starting checkpoints, reported metrics, and operations retained in full precision.

The attention evidence is localized. A plot from a particular head and development sequence can show that strong query-key products align with attention to the separator. It leaves open how many heads use the same mechanism and whether every extreme feature is needed for prediction. The leave-one-out experiment changes quantization at whole tensor sites. It does not isolate individual features and track the causal effect of each on a downstream prediction. The stronger conclusion is that these activations contain repeatable structure and that preserving adequate resolution around the FFN greatly improves the tested quantized networks.

Finally, a static range and a fixed feature ordering depend on what calibration observes. They work well in the reported setting. The experiments leave open how the grouping and intervals would transfer to inputs whose activation distributions differ from those used in calibration. That question follows directly from the design: each group keeps its assigned grid even as the values produced by later inputs change.

What came after

Precision at larger scales

The citing work LLM.int8() takes 8-bit matrix multiplication as its subject and puts the emphasis on Transformers at scale. That continues a question raised by the grouped method's arithmetic: a representation must preserve the values needed by the network and still give the matrix multiplication a practical way to combine them. In this paper, that question appears in the placement of scale factors inside or outside the accumulation. In the later work, the stated focus is the matrix multiplication itself at larger scale.

ZeroQuant takes up efficient and affordable post-training quantization for large-scale Transformers. It shares the original paper's concern with what can be done once a checkpoint has already been trained. The change in scope matters because the attraction of post-training conversion lies in the cost of bringing an existing network to lower precision. Here the authors demonstrate that changing how activations are represented can recover performance with calibration. ZeroQuant places post-training conversion for larger Transformers at the center of the research problem.

The case for 4-bit precision looks at low-bit inference through scaling laws. Bondarenko and colleagues explore several bit-width choices for one encoder and benchmark, separating changes to activations, weights, and token embeddings. The later paper's stated question concerns how inference behaves as precision and scale vary. Its connection is to the decision about bit-width itself, alongside the decision about which tensors have to use that width.

Which values need special treatment

Massive Activations in Large Language Models puts unusually large activations at the center of the investigation. In the BERT study, the authors first encounter the values as an obstacle to quantization and then inspect what they contribute to an attention calculation. The later work's focus makes the activation phenomenon itself the subject. This follows the original paper's observation that an extreme value can be informative about the learned computation as well as troublesome for a low-bit grid.

SqueezeLLM approaches quantization through a dense-and-sparse representation. The connection is the choice to give values with different representational needs different treatment. PEG groups the feature dimensions of an activation tensor and gives each group a uniform grid. SqueezeLLM's stated approach uses a dense and a sparse component. These are distinct choices about where to introduce finer control over how numerical information is stored.

KVQuant applies quantization to the key-value cache for long-context inference. The cache stores attention keys and values for reuse, which makes it a different target from the FFN activations calibrated here. Both studies put the representation of intermediate numerical state at the center of the memory question. The BERT work investigates the values passed through an encoder layer, while KVQuant focuses on state retained as the context grows.

Optimization and training

QuantEase frames quantization as an optimization problem. The BERT study already distinguishes several places where optimization can enter. MSE chooses a range according to reconstruction error, AdaRound changes the rounding choices, and QAT updates parameters in response to a downstream task loss. QuantEase continues the line of work in which the quantization decision is itself the object of optimization, with a broader stated focus on language systems.

pQuant pursues low-bit precision through decoupled linear quantization-aware training. This connects to the route in which simulated quantization is part of training and the learned computation can adapt to its numerical constraints. The BERT paper's comparisons show why that route can matter when weight and token embedding precision are pushed lower. The later work keeps training central and identifies decoupled linear quantization as its particular approach.

Cite

Cite as Yelysei Bondarenko, Markus Nagel and Tijmen Blankevoort. 2021. Understanding and Overcoming the Challenges of Efficient Transformer Quantization. Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.18653/v1/2021.emnlp-main.627

@inproceedings{bondarenko2021understanding,
  title = {{Understanding and Overcoming the Challenges of Efficient Transformer Quantization}},
  author = {Yelysei Bondarenko, Markus Nagel and Tijmen Blankevoort},
  booktitle = {Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing},
  year = {2021},
  doi = {10.18653/v1/2021.emnlp-main.627},
  url = {https://doi.org/10.18653/v1/2021.emnlp-main.627}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/bondarenko-2021-understanding-overcoming-challenges-efficient-transformer/