Quantization, Part 2
Oct 22, 2026 · @Nora
1. Where we stopped
Last time we laid a ruler over the weights: evenly spaced marks, every weight snaps to the nearest one, and two numbers (scale and zero point) bring it back. That is linear quantization, and it is what lets a layer run on integers.
But the ruler left three questions open, and they decide whether the quantized model keeps its accuracy:
One ruler or many? A single ruler for a whole layer, or one per channel, or one per small group of weights?
Where do the ends go? Stretch the ruler to the largest weight, or clip it shorter and accept that a few extremes get cut?
Can the network be trained to cope? If snapping to the ruler costs accuracy, can training with the ruler in place win it back?
Answering the first two without touching the weights is called post-training quantization (PTQ). Answering the third is quantization-aware training (QAT). At the end, two extremes: weights that are only +1 or −1, and networks where every layer picks its own bit width.
في المقال السابق تعلمنا التكميم الخطي: نضع «مسطرة» ذات علامات متساوية فوق أوزان الطبقة، وكل وزن ينتقل إلى أقرب علامة ويُخزن كعدد صحيح. هذا يجعل الحساب رخيصًا، لكنه يترك ثلاثة قرارات تحدد هل تبقى الدقة أم تضيع:
القراران الأول والثاني يُتخذان على نموذج مدرَّب جاهز دون أي تدريب إضافي، ويسمى هذا التكميم بعد التدريب (PTQ). القرار الثالث يحتاج تدريبًا، ويسمى التدريب الواعي بالتكميم (QAT). وفي النهاية نلقي نظرة على حدّين متطرفين: أوزان من بت واحد فقط (+1 أو −1)، وشبكات تختار كل طبقة فيها عدد بتاتها بنفسها. |
2. One ruler or many?
Per-tensor: one ruler for the whole layer. Simplest and cheapest: one scale, one zero point. It works for big networks. It fails for small ones, because the output channels of a layer can have very different ranges, sometimes 100× apart. One ruler long enough for the widest channel leaves the narrow channels with only two or three marks in use.
Per-channel: one ruler per output channel. Each filter gets its own scale, fitted to its own largest weight. The cost is a handful of extra numbers per layer; the gain is that every channel uses its full set of marks. In the 4×4 example from last time, per-tensor 2-bit quantization turns the whole row −0.91 1.92 0 −1.03 into 0 2.12 0 0, while per-channel keeps 0 1.92 0 −1.92. Smaller error, same bits.
Per-group: one ruler per small block. Go finer still: a scale for every 16 or 32 weights along a row. Now even outliers inside a channel stop hurting their neighbours. To keep the overhead small, the group scales are themselves tiny integers, and only one float scale per channel sits above them. The effective cost of 4-bit weights with a 4-bit scale every 16 weights is 4 + 4/16 = 4.25 bits per weight. This is the scheme behind the 4-bit formats that run today's large language models, and new GPUs support it in hardware.

ثلاثة مستويات لعدد المساطر:
|
3. Where do the ends of the ruler go?
So far the ruler ran from the smallest weight to the largest. That is the obvious choice and often the wrong one. Most weights sit in a narrow band near zero; a few outliers sit far away. Stretch the ruler to reach them and the whole band in the middle, where almost all the weights live, gets only a few coarse marks.
Clipping. Make the ruler shorter on purpose. The few outliers beyond the ends are cut down to the end value (they get a large error), but all the weights in the middle get finer marks (they get a small error). As long as the outliers are rare, the trade is a win. The question is how short to make it, and there are three common answers, from rough to careful:
Average min/max. Run a few batches and take the mean of each batch's min and max instead of the extreme over all batches.
Minimum squared error. Pick the ends that make the total squared error between the real values and the snapped values as small as possible. If you assume a bell-shaped distribution, this can even be solved on paper.
Minimum lost information. Compare the histogram of the real values with the histogram after quantization and choose the ends where the two differ least (the KL-divergence rule, used by TensorRT). This is the usual choice for activations in INT8.
حتى الآن امتدت المسطرة من أصغر وزن إلى أكبره، وهذا الخيار البديهي غالبًا خاطئ: معظم الأوزان تتجمع في نطاق ضيق قرب الصفر، وقليل منها بعيد. إن مددنا المسطرة لتصل إلى البعيد، حصل النطاق المزدحم في الوسط على علامات قليلة خشنة. القصّ (clipping): نقصّر المسطرة عمدًا. القيم القليلة خارج الطرفين تُقطع عند الطرف (خطأ كبير لكنها نادرة)، والأوزان الكثيرة في الوسط تحصل على علامات أدق (خطأ صغير للجميع). السؤال: كم نقصّر؟ ثلاث إجابات من الأبسط إلى الأدق:
|
Activations need this most. Weights are fixed, so their range is known once and for all. Activations change with every input, so their range has to be measured: either tracked during training as a smoothed running min/max, or measured after training on a few hundred calibration samples, the same idea as Wanda's calibration pass. One large activation in one image should not set the ruler for all images, which is exactly why clipping matters more here than for weights.
المخرجات (activations) أحوج ما تكون لهذا. الأوزان ثابتة فمداها معروف مرة واحدة، أما المخرجات فتتغير مع كل مدخل، فلا بد من قياس مداها: إما بتتبعه أثناء التدريب كمتوسط متحرك، أو بقياسه بعد التدريب على بضع مئات من عينات المعايرة، كما فعلت Wanda . قيمة واحدة كبيرة في صورة واحدة يجب ألا تحدد المسطرة لكل الصور، ولهذا القصّ في المخرجات أهم منه للأوزان. |
4. Rounding: nearest is not always best
Every weight so far snapped to the nearest mark. That is the best choice for each weight on its own, but weights do not act on their own: the layer's output is a sum over many of them, and their rounding errors add up. Rounding one weight down when nearest says up can cancel another weight's error and leave the output closer to the original.
AdaRound does exactly this. For each weight it allows only two options, the mark just below or the mark just above, and learns which one to take so that the layer's output on a few calibration samples matches the unquantized output as closely as possible. It is a short optimization, no full training, and it is one of the reasons 4-bit weights are usable without retraining.

التقريب إلى أقرب علامة هو الأفضل لكل وزن وحده، لكن المخرج مجموع أوزان كثيرة وأخطاؤها تتراكم. أحيانًا تقريب وزن إلى الأسفل بدل الأقرب يلغي خطأ وزن آخر. AdaRound يتعلم لكل وزن هل يصعد أم ينزل بحيث يبقى خرج الطبقة أقرب ما يكون إلى الأصل، بضبط قصير بلا تدريب كامل. |
5. Quantization-aware training: teach the network to live with the ruler
Everything above was done after training, on frozen weights. For 8 bits that is usually enough. For 4 bits and below, or for small networks, accuracy still drops, and the fix is the same as with pruning: train a little more, but this time with the quantization inside the training loop.
The trick: two copies of the weights. The network keeps its full-precision weights as the master copy. In every forward pass, a copy is snapped to the ruler and the layer runs with the snapped values, so the network sees exactly the errors it will see on the phone. The loss is computed on that. Then the gradient updates the full-precision master copy, not the snapped one. Small nudges accumulate there without being lost to rounding, and after many steps they add up to a weight moving to a different mark. At the end, the master copy is snapped once and only the integers ship.
This is called fake quantization: during training the maths is still float, we are only pretending the values are coarse.

In the picture above, the float copy of the weight takes the values 0.84, 0.81, 0.78, 0.75, 0.72, 0.69, 0.66, 0.63 over the steps. At every step, before the layer runs, that value is snapped to the ruler: 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 0.5. The layer computes its output with the snapped weight, and the loss sees only that result; the float value never reaches the forward pass.
كل ما سبق جرى بعد التدريب على أوزان ثابتة، وهو كافٍ غالبًا لـ 8 بتات. أما مع 4 بتات فأقل، أو مع الشبكات الصغيرة، فالدقة تنزل، والعلاج كما في التشذيب: تدريب إضافي قليل، لكن هذه المرة والتكميم داخل حلقة التدريب. الحيلة: نسختان من الأوزان. تحتفظ الشبكة بأوزانها الكاملة الدقة كنسخة أصلية. في كل تمرير أمامي تُقرَّب نسخة منها إلى المسطرة وتعمل الطبقة بالقيم المقرَّبة، فترى الشبكة الخطأ نفسه الذي ستراه على الجهاز، وتُحسب الخسارة عليه. ثم يحدّث التدرج النسخة الأصلية الكاملة لا المقرَّبة، فتتراكم التحديثات الصغيرة فيها دون أن يبتلعها التقريب، وبعد خطوات كثيرة يكفي مجموعها لنقل الوزن إلى علامة أخرى. في النهاية تُقرَّب النسخة الأصلية مرة واحدة وتُشحن الأعداد الصحيحة فقط. يسمى هذا التكميم الوهمي (fake quantization): الحساب أثناء التدريب ما زال عائمًا، ونحن نتظاهر فقط أن القيم خشنة. |

The problem it has to solve. Snapping is a staircase: flat everywhere, with jumps. The slope of a flat step is zero, so the gradient through the snap is zero, and a zero gradient means the network learns nothing. The straight-through estimator fixes this with one bold assumption: pretend the staircase is a straight line and pass the gradient through unchanged. It is not mathematically right, and it works.
What it buys. A small network that loses most of its accuracy under post-training INT8 (because its ranges are lopsided across channels) gets almost all of it back with QAT, even with the simple per-tensor ruler.
المشكلة التي يجب حلها. التقريب جعل الأرقام كأنها في سُلَّم: لو رسمنا الوزن العائم على المحور الأفقي، والوزن بعد التقريب على المحور الرأسي. كل القيم من 0.5 إلى 1.5 تُقرَّب إلى 1، ومن 1.5 إلى 2.5 إلى 2، وهكذا. فالرسم لن يكون خطًا مائلًا بل درجات: مسطّح، ثم قفزة، ثم مسطّح. هذا هو الدرج. لماذا هذا مشكلة في التدريب؟ التدريب يعتمد على سؤال واحد: «لو حرّكت الوزن قليلًا، كم تتغير النتيجة؟» هذي هي أصلِا فكرة التدريب أغير شيء بسيط جدًا وأتوقع تحسن في الآداء ، لكن هنا لو غيرت قيمة من 0.80 إلى 0.83 لن يتغير شيء لأن تقريبهما 1 في الحالتين، فالميل صفر (التدريب معناه تغير في الميل). وإذا كان الميل صفرًا في كل مكان تقريبًا، فالتدرج الذي يصل إلى الوزن صفر، والوزن لا يتحرك أبدًا، والشبكة لا تتعلم. الحل: نتظاهر. في التمرير الأمامي نستخدم الدرج فعلًا (الشبكة ترى القيم المقرَّبة). أما في التمرير الخلفي، عندما نحسب الميل، فنتجاهل الدرج ونعامله كأنه الخط المستقيم المنقّط في الصورة: الميل 1، أي «حرّك الوزن العائم بقدر ما يقول التدرج». هذا هو المقدّر المباشر (straight-through): التدرج «يمرّ مباشرة» عبر صندوق التقريب كأنه غير موجود. ليس صحيحًا رياضيًا، لكن عمليًا يعطي الوزن العائم دفعة في الاتجاه الصحيح، وبعد عدة دفعات يعبر الوزن إلى درجة أخرى، كما رأينا في الـصورة المتحركة أعلاه Figure: one weight through seven QAT steps. عند 0.75. |

The circle is the weight (float copy 0.71), the square is the input 0.26 from the previous layer. Each cycle both are snapped to a 0.1 ruler, multiplied in layer N, the output is snapped again and compared with a target of 0.4. The gradient passes straight back through the snap boxes and updates the float weight, never the snapped one. Notice cycle 2: the weight moved from 0.71 to 0.82, but 0.21 and 0.24 both snap to 0.2, so the loss did not change; that is the staircase at work. The table below lists every number.

الشكل: وزن واحد ومدخل واحد عبر ثلاث دورات. الدائرة هي الوزن (نسخته العائمة 0.71)، والمربع هو المدخل 0.26 القادم من الطبقة السابقة. في كل دورة يُقرَّب كلاهما إلى مسطرة خطوتها 0.1، ويُضربان في الطبقة N، ويُقرَّب الناتج مرة أخرى ويُقارن بهدف 0.4. التدرج يرجع مباشرة عبر صناديق التقريب (المربعات الوردية) ويحدّث الوزن العائم لا المقرَّب. لاحظ/ـي الدورة الثانية: الوزن تحرك من 0.71 إلى 0.82، لكن 0.21 و0.24 يُقرَّبان معًا إلى 0.2، فلم تتغير الخسارة؛ هذا هو الدرج في العمل.
6. All the way down: binary and ternary weights
Look back at where we are. K-means solved storage but not computation: the weights are small indexes, yet every multiply still happens in float after a lookup. Linear quantization solved both: integer weights and integer arithmetic. The natural next question is whether we can make the arithmetic simpler still, and the answer is to go to the smallest ruler possible.
الـK-means حلّت التخزين لا الحساب، والخطية حلّت الاثنين. ممتاز ،، لكن هل فيه مجال نبسط الموضوع أكثر ؟ الخطية تستخدم التقريب إلى أعداد صحيحة أو أعداد قصيرة المدى (عدد البت معقول ) ، لكن ماذا لو استخدمنا أصغر مسطرة ممكنة : وزن من بت واحد

Binary weights. A binary weight is only +1 or −1, its sign. Storage drops 32×, and the multiply disappears: weight × input becomes “add the input or subtract it”. The arithmetic is about 2× cheaper.
Binary weights and inputs. If the activations coming into the layer are also only +1 or −1, every term is ±1 × ±1, which is just “same sign or not”. A whole dot product becomes two bit operations, XNOR then count the ones, tens of times cheaper than multiplying, and the activations shrink 32× as well.

The raw version loses a lot of accuracy, and binarizing the inputs loses much more than binarizing the weights. Two small fixes recover most of it on the weight side:
One scale per layer. Store the signs, plus one float that says how big a typical weight is (the average absolute value). The weights become ±α instead of ±1, which costs almost nothing and keeps a weight-only binary network within a fraction of a point of the original.
Allow a zero: ternary. Weights become −α, 0, +α. Small weights go to zero (a threshold, typically 0.7 of the mean), the rest keep their sign. That is 2 bits, and it closes most of the remaining gap. Letting the positive and negative scales be learned separately helps a little more.

Binary and ternary networks are a niche today, since 4-bit with group scales gives most of the saving with far less pain, but they show how far the idea stretches
أقل ما يمكن بت واحد: الوزن إما +1 أو −1، أي إشارته فقط، فيصبح الضرب جمعًا أو طرحًا. الدقة تنهار إن فعلنا ذلك بسذاجة، لكن مقياسًا واحدًا لكل طبقة (±α بدل ±1) يستعيد معظمها، والسماح بالصفر (ثلاثي: −α، 0، +α ببتّين) يسد معظم الباقي. طريقة نادرة الاستخدام اليوم، لكنها تبيّن إلى أين تمتد الفكرة. |
7. Mixed precision: a different bit width per layer
The same lesson as pruning ratios: layers are not equal, so why give them all 8 bits? A robust layer might be fine at 4; a sensitive one might need 7. Letting each layer choose its own bit width, for weights and for activations separately, is mixed precision.
The catch is the size of the choice. With 8 options for weights and 8 for activations, each layer has 64 settings, and a 50-layer network has 64⁵⁰ combinations. No person searches that. The answer is the same agent we met for pruning ratios: it walks the layers, picks a bit width for each, gets a score from the quantized network's accuracy and from the real latency or energy on the target chip, and learns. Given a latency budget, it finds settings that beat uniform 8-bit at the same speed, and it adapts them to the hardware: what is cheap on one chip is not cheap on another.
كما في نسب التشذيب، الطبقات ليست متساوية: بعضها يكفيه 4 بتات وبعضها يحتاج 7. لكن عدد التركيبات هائل، فنترك لوكيل يتعلم اختيار عدد البتات لكل طبقة بحسب الدقة وزمن التشغيل الفعلي على الشريحة المستهدفة. |
8. Closing
A recipe, in the order you would actually use it:
Start with post-training INT8: per-channel rulers for weights, a clipped range for activations measured on a few hundred samples. For most networks this is enough and costs no training.
If accuracy drops, or you want 4 bits: add group scales, use a smarter rounding, and if that is still not enough, fine-tune with fake quantization (QAT) and the straight-through estimator.
If every bit matters, let an agent pick a different width per layer, scored on the real chip.
Pruning and quantization are the two halves of model compression: fewer weights, then fewer bits per weight. Together they take a model dozens of times smaller with the same accuracy, which is what makes running it on a phone possible at all.
الوصفة بالترتيب الذي تستخدمه فعلًا:
الـ pruning والـ quantization نصفا ضغط النماذج (model compression): أوزان أقل، ثم بتات أقل لكل وزن. معًا يصغّران النموذج عشرات المرات بالدقة نفسها، وهذا ما يجعل تشغيله على الجوال ممكنًا أصلًا. |
Sources
MIT 6.5940 Lecture 6: Quantization, Part II
Jacob et al., Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference, CVPR 2018 (per-channel, QAT, EMA ranges)
Krishnamoorthi, Quantizing Deep Convolutional Networks for Efficient Inference: A Whitepaper, 2018 (PTQ vs QAT results)
Migacz, 8-bit Inference with TensorRT, 2017 (KL-divergence calibration)
Nagel et al., Up or Down? Adaptive Rounding for Post-Training Quantization, 2020 (AdaRound)
Bengio, Estimating or Propagating Gradients Through Stochastic Neurons, 2013 (straight-through estimator)
Rastegari et al., XNOR-Net, ECCV 2016; Li et al., Ternary Weight Networks, 2016; Zhu et al., Trained Ternary Quantization, ICLR 2017
Dai et al., VS-Quant, 2021 (per-vector scaling)
Wang et al., HAQ: Hardware-Aware Automated Quantization with Mixed Precision, CVPR 2019




Comments