COE 592Lecture 5.3المحاضرة 5.3Full guideالشرح الكامل
Quantization (III): PTQ granularity, range clipping, rounding, QAT, binary/ternary and mixed precisionالتكميم (Quantization) الجزء الثالث: دقة PTQ، وقص المدى، والتقريب، وQAT، والثنائي والثلاثي، والدقة المختلطة
The whole lecture on one page, taught concept by concept. Work through the parts in order, mark each concept once you understand it, and open the slide chips when you want the original slides.المحاضرة كاملة في صفحة واحدة، مشروحة مفهومًا مفهومًا. امشِ على الأجزاء بالترتيب، وعلّم كل مفهوم بعد أن تفهمه، وافتح أزرار الشرائح عندما تريد الرجوع إلى الشرائح الأصلية.
- Partsالأجزاء
- 9
- Conceptsالمفاهيم
- 41
- Slidesالشرائح
- 76
- Readingمدة القراءة
- 246 min246 دقيقة
Part 01: Quantization granularity: per-tensor vs per-channel scalesدقة التكميم (Granularity): مقاييس لكل موتر مقابل لكل قناة
Post-training quantization asks how to choose S and Z. The first knob is granularity: one scale for the whole weight tensor fails when output channels have wildly different ranges, so per-channel quantization gives each output channel its own scale and cuts reconstruction error, shown on a full 2-bit worked example.التكميم بعد التدريب (PTQ) يسأل كيف نختار S وZ. أول خيار هو الدقة (granularity): مقياس واحد لموتر الأوزان كله يفشل عندما تكون لقنوات المخرج مديات مختلفة جدًا، لذا يعطي التكميم لكل قناة (per-channel) كل قناة مخرج مقياسها الخاص ويقلل خطأ إعادة البناء، كما يظهر في مثال محلول كامل بـ2 بت.
5 concepts5 مفاهيم, ، slides 1-13الشرائح 1-13
Why this part mattersلماذا يهمّ هذا الجزء
The last two lectures gave you the machinery of linear quantization: a real number is stored as an integer with . What they did not settle is how to choose and for a real network that has already been trained. This part starts that story with the first and most exam-visible decision: how many weights should share one scale.
The ideas come in a chain. First, the framing: post-training quantization and its three questions. Second, the menu of granularities. Third, why the simplest choice, one scale per tensor, breaks on small models. Fourth and fifth, the lecture’s 2-bit example computed by hand under both schemes, ending with the reason per-channel scales live on output channels. Expect the midterm to hand you a small matrix and ask for , and the error under both schemes, so the worked examples are written to be copied step by step.
أعطتك المحاضرتان السابقتان أدوات التكميم الخطي: يُخزَّن العدد الحقيقي كعدد صحيح بحيث . لكنهما لم تحسما كيف نختار و لشبكة حقيقية دُرِّبت بالفعل. يبدأ هذا الجزء تلك القصة بالقرار الأول والأكثر ظهورًا في الامتحان: كم وزنًا يجب أن يتشارك scale واحدًا؟
تأتي الأفكار في سلسلة. أولًا الإطار العام: التكميم بعد التدريب (post-training quantization) وأسئلته الثلاثة. ثانيًا قائمة مستويات الدقة (granularity). ثالثًا لماذا ينهار أبسط خيار، أي scale واحد لكل tensor، في النماذج الصغيرة. رابعًا وخامسًا مثال المحاضرة ذو 2 bit محسوبًا باليد بالطريقتين، وننتهي بسبب وضع مقاييس per-channel على قنوات الخرج (output channels). توقّع أن يعطيك الامتحان النصفي مصفوفة صغيرة ويطلب و والخطأ بالطريقتين، لذلك كُتبت الأمثلة المحلولة بحيث تنسخها خطوة بخطوة.
By the end you canفي نهاية هذا الجزء ستستطيع
- State what post-training quantization does and name the three questions it answers about S and Z.أن تذكر ما يفعله التكميم بعد التدريب (PTQ) وتسمّي الأسئلة الثلاثة التي يجيب عنها بشأن S وZ.
- Distinguish per-tensor, per-channel and group granularity by how many weights share one scale.أن تميّز بين granularity من نوع per-tensor وper-channel وgroup بحسب عدد الأوزان التي تتشارك scale واحدًا.
- Compute S, q and the reconstruction error for a small weight matrix under symmetric per-tensor and per-channel quantization.أن تحسب S وq وخطأ إعادة البناء لمصفوفة أوزان صغيرة في التكميم المتماثل per-tensor وper-channel.
- Explain why one outlier output channel ruins per-tensor quantization, citing the MobileNetV2 evidence.أن تشرح لماذا تُفسد قناة خرج شاذة واحدة تكميم per-tensor، مستشهدًا بدليل MobileNetV2.
- Explain why per-channel scales are taken over output channels and not input channels.أن تشرح لماذا تؤخذ مقاييس per-channel على قنوات الخرج (output channels) وليس على قنوات الدخل.
Suppose a colleague hands you a ResNet trained in FP32 and says: make it run in INT8 on our microcontroller by Friday, and no, you cannot retrain it. You have the weights, perhaps a few hundred unlabeled images, and that is all.
لنفترض أن زميلًا أعطاك شبكة ResNet مدرّبة بدقة FP32 وقال: اجعلها تعمل بـ INT8 على المتحكم الدقيق (microcontroller) لدينا قبل يوم الجمعة، ولا، لا يمكنك إعادة تدريبها. لديك الأوزان، وربما بضع مئات من الصور غير الموسومة، وهذا كل شيء.
That job is Post-training quantization (PTQ). The network’s weights are frozen; the only things you get to choose are the quantization parameters, the scale and the zero point , for every tensor you quantize. Its opposite, which the lecture covers later, is Quantization-aware training (QAT), where quantization is simulated during training so the weights can adapt to it. PTQ is cheap and needs no labels; QAT costs a training run but recovers more accuracy at low bit widths.
هذه المهمة هي post-training quantization (التكميم بعد التدريب). أوزان الشبكة مجمّدة، والشيء الوحيد الذي تختاره هو معاملات التكميم: الـ scale ونقطة الصفر (zero point) ، لكل tensor تكمّمه. ونقيضه، الذي تغطيه المحاضرة لاحقًا، هو quantization-aware training (التدريب الواعي بالتكميم)، حيث يُحاكى التكميم أثناء التدريب كي تتكيّف الأوزان معه. الـ PTQ رخيص ولا يحتاج إلى تسميات (labels)، أما QAT فيكلّف عملية تدريب كاملة لكنه يستعيد دقة أكبر عند عدد بتات منخفض.
The lecture breaks the PTQ question “what are the best ?” into three independent sub-questions, and the rest of the lecture’s first half answers them in order.
تقسّم المحاضرة سؤال الـ PTQ «ما أفضل ؟» إلى ثلاثة أسئلة فرعية مستقلة، ويجيب باقي النصف الأول من المحاضرة عنها بالترتيب.
How many weights share one S? The whole tensor, one channel, or a small group.
كم وزنًا يتشارك S واحدًا؟ الـ tensor بأكمله، أو قناة واحدة، أو مجموعة صغيرة.
Which |r|_max to map onto q_max? The observed max, or a smaller clipped value.
أي قيمة |r|_max نربطها بـ q_max؟ القيمة العظمى المرصودة، أو قيمة أصغر بعد القص.
Round each value to the nearest level, or choose up or down to cut layer error.
قرّب كل قيمة إلى أقرب مستوى، أو اختر التقريب للأعلى أو للأسفل لتقليل خطأ الطبقة.
Keep the three apart in your head. Granularity decides who shares a scale. Dynamic range clipping decides how large that scale is, given the values that share it. Rounding decides which level each value lands on once the grid is fixed; the default, Rounding to nearest, turns out not to be optimal. Every one of the three changes the same final number, the error between the original and the dequantized weights, so they interact, but each can be studied with the other two held fixed.
أبقِ الثلاثة منفصلة في ذهنك. الـ granularity تحدد من يتشارك الـ scale. وdynamic range clipping (قصّ المدى الديناميكي) يحدد كم يكون كبيرًا هذا الـ scale، بالنظر إلى القيم التي تتشاركه. والتقريب (rounding) يحدد أي مستوى تقع عليه كل قيمة بعد تثبيت الشبكة؛ والخيار الافتراضي، rounding to nearest (التقريب إلى الأقرب)، يتبيّن أنه ليس الأمثل. كل واحد من الثلاثة يغيّر الرقم النهائي نفسه، أي الخطأ بين الأوزان الأصلية والأوزان بعد إزالة التكميم (dequantized)، لذا فهي تتفاعل فيما بينها، لكن يمكن دراسة كل واحد منها مع تثبيت الاثنين الآخرين.
Recall
Name the three PTQ sub-questions and say in one phrase what each one decides.سمِّ الأسئلة الفرعية الثلاثة في PTQ وقل بعبارة واحدة ماذا يحدد كل منها.
Granularity: which weights share one scale. Dynamic range clipping: what range is mapped onto the integer grid, which sets the size of S. Rounding: which grid level each value is assigned to once S is fixed.
الـ granularity: أي الأوزان تتشارك scale واحدًا. الـ dynamic range clipping: أي مدى يُسقَط على الشبكة الصحيحة، وهذا يحدد حجم S. الـ rounding: أي مستوى في الشبكة تُسنَد إليه كل قيمة بعد تثبيت S.
Take two filters in the same layer. One has weights in [-128, 128], the other in (-0.5, 0.5). Quantize both to INT8 with one shared scale: S = 128 / 127 ≈ 1.01. Every weight of the second filter divided by 1.01 is below 0.5 in magnitude, so all of them round to 0. That filter is erased, even with 8 bits.
خذ مرشحين في الطبقة نفسها. أحدهما أوزانه في [-128, 128]، والآخر في (-0.5, 0.5). كمّم الاثنين إلى INT8 بـ scale مشترك واحد: S = 128 / 127 ≈ 1.01. كل وزن من المرشح الثاني بعد قسمته على 1.01 تكون قيمته المطلقة أقل من 0.5، فتُقرَّب كلها إلى 0. هذا المرشح يُمحى تمامًا، حتى مع 8 bits.
This is the example Nagel et al. (ICCV 2019) use, and it is the whole reason this part exists. Before going further, fix the recipe the lecture uses for weights. Weights are roughly centred on zero, so the lecture uses Symmetric quantization: the zero point is and the range is set by the largest magnitude.
هذا هو المثال الذي يستخدمه Nagel et al. (ICCV 2019)، وهو السبب الذي يوجد هذا الجزء من أجله أصلًا. قبل المتابعة، ثبّت الوصفة التي تستخدمها المحاضرة للأوزان. الأوزان متمركزة تقريبًا حول الصفر، لذا تستخدم المحاضرة symmetric quantization (التكميم المتماثل): نقطة الصفر والمدى تحدده أكبر قيمة مطلقة.
Notice what does to the integer range. An N-bit two’s complement integer can hold -2^(N-1) up to 2^(N-1) - 1, but a symmetric grid uses only -q_max to +q_max, so the most negative code is never produced. For N = 8 that is [-127, 127], exactly the range the TensorFlow Lite (LiteRT) specification mandates for weights. For N = 2 it is dramatic: q_max = 2^1 - 1 = 1, so only the three codes -1, 0, 1 are used, and the fourth code, -2, is wasted.
لاحظ ما تفعله بمدى الأعداد الصحيحة. العدد الصحيح ذو N bit بتمثيل المتمم الثنائي (two’s complement) يمكن أن يحمل القيم من -2^(N-1) حتى 2^(N-1) - 1، لكن الشبكة المتماثلة لا تستخدم إلا من -q_max إلى +q_max، فلا يُنتَج الرمز الأكثر سالبية أبدًا. عند N = 8 يكون ذلك [-127, 127]، وهو بالضبط المدى الذي تفرضه مواصفة TensorFlow Lite (LiteRT) للأوزان. وعند N = 2 يكون الأثر كبيرًا: q_max = 2^1 - 1 = 1، فلا تُستخدم إلا الرموز الثلاثة -1, 0, 1، ويضيع الرمز الرابع -2.
One scale, many channels: the outlier problemscale واحد وقنوات كثيرة: مشكلة القيم الشاذة (outliers)
With one scale per tensor, is the largest weight in the entire layer. If one output channel holds that outlier, its range dictates the step size for every channel. Channels whose weights are much smaller collapse onto a handful of levels, often just zero.
مع scale واحد لكل tensor، تكون أكبر وزن في الطبقة كلها. إذا كانت قناة خرج واحدة تحمل هذه القيمة الشاذة، فإن مداها يفرض حجم الخطوة على كل القنوات. القنوات ذات الأوزان الأصغر بكثير تنهار إلى عدد قليل من المستويات، وغالبًا إلى الصفر وحده.
The lecture’s evidence is the box plot from Nagel et al.: the per-output-channel weight ranges of the first depthwise-separable layer in MobileNetV2. Most of the 32 channels sit within a few units of zero, while a few stretch to around ±50 to ±100. The lecture’s summary:
دليل المحاضرة هو مخطط الصندوق (box plot) من Nagel et al.: مديات الأوزان لكل قناة خرج في أول طبقة depthwise-separable في MobileNetV2. معظم القنوات الـ 32 تقع في حدود وحدات قليلة حول الصفر، بينما يمتد بعضها إلى نحو ±50 حتى ±100. خلاصة المحاضرة:
- Per-tensor quantization works well for large models but accuracy drops for small models.تكميم per-tensor يعمل جيدًا للنماذج الكبيرة لكن الدقة تنخفض في النماذج الصغيرة.
- The common failure is a large difference, more than 100×, in weight ranges across output channels, caused by outlier weights.الفشل الشائع هو فرق كبير، أكثر من 100×، في مديات الأوزان بين قنوات الخرج، تسببه الأوزان الشاذة.
- The solution is per-channel quantization.الحل هو تكميم per-channel.
The numbers in the paper are stark. MobileNetV2 reaches 71.72% top-1 on ImageNet in FP32. With plain per-tensor INT8 it drops to 0.12%, essentially random guessing; with per-channel INT8 it keeps 70.65%. Depthwise layers are the worst offenders because each output channel has only a few weights (3 × 3 = 9), so one channel can drift far from the others, and folding batch normalization into the weights amplifies the imbalance (Nagel et al., 2021). Large models like ResNets have many weights per channel and smoother ranges, which is why per-tensor survives there.
الأرقام في الورقة صارخة. يصل MobileNetV2 إلى دقة top-1 قدرها 71.72% على ImageNet بدقة FP32. ومع تكميم INT8 عادي من نوع per-tensor تهبط إلى 0.12%، أي ما يعادل التخمين العشوائي؛ ومع INT8 من نوع per-channel تحافظ على 70.65%. طبقات الـ depthwise هي أسوأ المتسببين لأن كل قناة خرج فيها لا تملك إلا أوزانًا قليلة (3 × 3 = 9)، فيمكن لقناة واحدة أن تبتعد كثيرًا عن الأخرى، كما أن دمج الـ batch normalization في الأوزان يضخّم هذا التفاوت (Nagel et al., 2021). أما النماذج الكبيرة مثل ResNets فلديها أوزان كثيرة في كل قناة ومديات أكثر انتظامًا، ولهذا ينجو الـ per-tensor هناك.
Quick checkاختبار سريع
In the lecture's 2-bit symmetric scheme, which integer codes can a quantized weight take?في طريقة المحاضرة المتماثلة بـ 2 bit، ما الرموز الصحيحة التي يمكن أن يأخذها وزن مكمَّم؟
Now the lecture’s example, done by hand. Rows are output channels (oc), columns are input channels (ic), and we quantize to N = 2 bits with one scale.
الآن مثال المحاضرة، محلولًا باليد. الصفوف هي قنوات الخرج (oc)، والأعمدة هي قنوات الدخل (ic)، ونكمّم إلى N = 2 bits بـ scale واحد.
Worked exampleمثال محلول
Per-tensor, 2-bit symmetricPer-tensor، تكميم متماثل بـ 2 bit
Find the rangeأوجد المدى
The largest magnitude anywhere in W is 2.12 (row oc1, last column), so |r|_max = 2.12.أكبر قيمة مطلقة في أي مكان من W هي 2.12 (الصف oc1، العمود الأخير)، إذن |r|_max = 2.12.Compute the scaleاحسب الـ scale
Divide and roundاقسم وقرّب
Divide every weight by 2.12 and round to the nearest integer in [-1, 1]. Anything with |W| < 1.06 (half a step) becomes 0. So 2.09 / 2.12 = 0.986 → 1, 1.48 / 2.12 = 0.698 → 1, -0.98 / 2.12 = -0.462 → 0, -1.08 / 2.12 = -0.509 → -1 (just past half a step), and -1.03 / 2.12 = -0.486 → 0 (just short of it).اقسم كل وزن على 2.12 وقرّبه إلى أقرب عدد صحيح في [-1, 1]. أي وزن فيه |W| < 1.06 (نصف خطوة) يصبح 0. لذلك 2.09 / 2.12 = 0.986 → 1، و1.48 / 2.12 = 0.698 → 1، و-0.98 / 2.12 = -0.462 → 0، و-1.08 / 2.12 = -0.509 → -1 (تجاوز نصف الخطوة بقليل)، و-1.03 / 2.12 = -0.486 → 0 (قصُر عنها بقليل).Reconstructأعد البناء
Multiply back by S: every nonzero code becomes ±2.12.اضرب مرة أخرى في S: كل رمز غير صفري يصبح ±2.12.Measure the errorقِس الخطأ
Sum the squared differences over all 16 entries, then take the square root (the Frobenius norm). The biggest contributors are the weights zeroed out (-0.98, -0.91, -1.03) and the small positives pushed up to 2.12 (1.48, 1.53, 1.49).اجمع مربعات الفروق على المدخلات الـ 16 كلها، ثم خذ الجذر التربيعي (معيار فروبينيوس، Frobenius norm). أكبر المساهمين هم الأوزان التي صُفّرت (-0.98 و-0.91 و-1.03) والقيم الموجبة الصغيرة التي دُفعت إلى 2.12 (1.48 و1.53 و1.49).Resultالنتيجة
S = 2.12, codes only in {-1, 0, 1}, error ‖W - Sq‖_F = 2.28.S = 2.12، والرموز فقط في {-1, 0, 1}، والخطأ ‖W - Sq‖_F = 2.28.
Recall
Without looking back: what is S for this matrix under 2-bit per-tensor quantization, and why is it equal to |r|_max?دون النظر إلى ما سبق: ما قيمة S لهذه المصفوفة في تكميم per-tensor بـ 2 bit، ولماذا تساوي |r|_max؟
S = 2.12. Because q_max = 2^(2-1) - 1 = 1, dividing |r|_max by 1 leaves it unchanged. At 8 bits the same matrix would give S = 2.12 / 127 ≈ 0.0167.
S = 2.12. لأن q_max = 2^(2-1) - 1 = 1، فقسمة |r|_max على 1 تتركها كما هي. وعند 8 bits تعطي المصفوفة نفسها S = 2.12 / 127 ≈ 0.0167.
Quick checkاختبار سريع
Under 2-bit per-tensor quantization with S = 2.12, which code does the weight -1.03 receive?في تكميم per-tensor بـ 2 bit مع S = 2.12، ما الرمز الذي يأخذه الوزن -1.03؟
Same matrix, same 2 bits, but now each output channel (each row) gets its own scale. With q_max = 1, each scale is simply that row’s largest magnitude.
المصفوفة نفسها، و2 bits نفسها، لكن الآن تحصل كل قناة خرج (كل صف) على scale خاص بها. ومع q_max = 1، يكون كل scale ببساطة أكبر قيمة مطلقة في ذلك الصف.
Worked exampleمثال محلول
Per-channel, 2-bit symmetricPer-channel، تكميم متماثل بـ 2 bit
One range per rowمدى واحد لكل صف
oc0: |r|_max = 2.09, so S_0 = 2.09. oc1: 2.12, so S_1 = 2.12. oc2: 1.92, so S_2 = 1.92. oc3: 1.87, so S_3 = 1.87. Only oc1 keeps the per-tensor scale, because it is the row that holds the global maximum.oc0: |r|_max = 2.09، إذن S_0 = 2.09. oc1: 2.12، إذن S_1 = 2.12. oc2: 1.92، إذن S_2 = 1.92. oc3: 1.87، إذن S_3 = 1.87. وحده oc1 يحتفظ بالـ scale نفسه الذي في per-tensor، لأنه الصف الذي يحمل القيمة العظمى الكلية.Divide each row by its own scaleاقسم كل صف على الـ scale الخاص به
Most codes do not change. The one that does is in oc2: -1.03 / 1.92 = -0.536 → -1, where per-tensor gave -1.03 / 2.12 = -0.486 → 0. Shrinking the step from 2.12 to 1.92 pushed it just past half a step.معظم الرموز لا تتغير. الرمز الذي يتغير موجود في oc2: -1.03 / 1.92 = -0.536 → -1، بينما أعطى per-tensor القيمة -1.03 / 2.12 = -0.486 → 0. تصغير الخطوة من 2.12 إلى 1.92 دفعه إلى ما بعد نصف الخطوة بقليل.Reconstruct row by rowأعد البناء صفًا صفًا
Each row is multiplied by its own scale, written .يُضرب كل صف في الـ scale الخاص به، ونكتب ذلك .Measure the errorقِس الخطأ
Resultالنتيجة
Per-channel error 2.08 is below per-tensor 2.28, with one code changed.خطأ per-channel البالغ 2.08 أقل من خطأ per-tensor البالغ 2.28، مع تغيّر رمز واحد فقط.
Where did the improvement come from? Not only from the one flipped code. Break the squared error down by row:
من أين جاء التحسّن؟ ليس فقط من الرمز الواحد الذي انقلب. فكّك الخطأ المربّع حسب الصف:
| Channelالقناة | Per-tensor SS في per-tensor | Per-tensor squared errorالخطأ المربّع في per-tensor | Per-channel S_iS_i في per-channel | Per-channel squared errorالخطأ المربّع في per-channel |
|---|---|---|---|---|
| oc0oc0 | 2.122.12 | 1.3791.379 | 2.092.09 | 1.3411.341 |
| oc1oc1 | 2.122.12 | 1.1041.104 | 2.122.12 | 1.1041.104 |
| oc2oc2 | 2.122.12 | 1.9291.929 | 1.921.92 | 1.6201.620 |
| oc3oc3 | 2.122.12 | 0.8080.808 | 1.871.87 | 0.2600.260 |
| Totalالمجموع | 5.219 → √ = 2.285.219 → √ = 2.28 | 4.32 → √ = 2.084.32 → √ = 2.08 |
oc3 gains the most, and none of its codes changed: its nonzero weights 1.87, 1.53, 1.49 are now reconstructed as 1.87 instead of 2.12, much closer. oc2 gains from the flipped code (error on that entry falls from 1.03 to |-1.03 + 1.92| = 0.89) and from 1.92 now being exact. oc1 is unchanged because its scale is unchanged. The lesson: a smaller, better-fitted scale helps both by moving values onto nonzero codes and by placing the levels closer to the values.
oc3 يستفيد أكثر من غيره، ولم يتغير أي من رموزه: أوزانه غير الصفرية 1.87, 1.53, 1.49 يُعاد بناؤها الآن كـ 1.87 بدل 2.12، وهذا أقرب بكثير. ويستفيد oc2 من الرمز المنقلب (ينخفض الخطأ في ذلك المدخل من 1.03 إلى |-1.03 + 1.92| = 0.89) ومن أن 1.92 أصبحت الآن دقيقة تمامًا. أما oc1 فلا يتغير لأن الـ scale الخاص به لم يتغير. الدرس: الـ scale الأصغر والأكثر ملاءمة يساعد بطريقتين: بنقل القيم إلى رموز غير صفرية، وبوضع المستويات أقرب إلى القيم.
Recall
Compute -0.91 / 1.92 and round it. Does the first weight of oc2 change code under per-channel quantization?احسب -0.91 / 1.92 وقرّبه. هل يتغير رمز الوزن الأول في oc2 في تكميم per-channel؟
-0.91 / 1.92 = -0.474, which rounds to 0, the same as per-tensor (-0.91 / 2.12 = -0.429 → 0). A near miss: it would need |W| ≥ 0.96 to reach code -1. So in oc2 only -1.03 flips.
-0.91 / 1.92 = -0.474، ويُقرَّب إلى 0، تمامًا كما في per-tensor (-0.91 / 2.12 = -0.429 → 0). كاد أن يتغير: كان سيحتاج إلى |W| ≥ 0.96 ليصل إلى الرمز -1. لذلك في oc2 لا ينقلب إلا -1.03.
Try it live. Switch between the two schemes and watch the highlighted cell; then change the bit width. At 3 and 4 bits per-channel is actually a hair worse on this particular matrix (0.710 versus 0.699 at 3 bits), because its row ranges are almost equal (1.87 to 2.12) and which side of a rounding boundary each value lands on is partly luck. Per-channel wins reliably when ranges differ a lot, which is exactly the MobileNetV2 situation.
جرّبه مباشرة. بدّل بين الطريقتين وراقب الخلية المظلَّلة، ثم غيّر عدد البتات. عند 3 و4 bits يكون per-channel في الواقع أسوأ بفارق ضئيل على هذه المصفوفة بالذات (0.710 مقابل 0.699 عند 3 bits)، لأن مديات صفوفها متساوية تقريبًا (من 1.87 إلى 2.12)، وفي أي جانب من حد التقريب تقع كل قيمة هو جزئيًا مسألة حظ. يفوز per-channel بشكل موثوق عندما تختلف المديات كثيرًا، وهذا بالضبط وضع MobileNetV2.
Why output channels, not input channelsلماذا قنوات الخرج وليس قنوات الدخل
The slides draw the scale arrows along rows, the output channels, and the convolution picture boxes the filter dimension c_o. That is not arbitrary; it is what keeps integer arithmetic possible. Output i of a layer is a dot product over the inputs j. Write the weights as S_i q_ij and the activations as s_x x_j with integer x_j:
ترسم الشرائح أسهم الـ scale على طول الصفوف، أي قنوات الخرج، وصورة الالتفاف تؤطّر بُعد المرشح c_o. هذا ليس اعتباطيًا؛ بل هو ما يُبقي الحساب بالأعداد الصحيحة ممكنًا. الخرج i لطبقة ما هو جداء نقطي (dot product) على المدخلات j. اكتب الأوزان على شكل S_i q_ij والتنشيطات (activations) على شكل s_x x_j حيث x_j عدد صحيح:
Because S_i is the same for every term of the sum, the hardware accumulates Σ_j q_ij x_j in an integer register and applies one multiplication by S_i s_x at the end, a step it already performs per output anyway. If the scale instead varied with the input index j, it would sit inside the sum, and every product would need its own rescale before being added, destroying the point of integer accumulation. The same argument is why per-channel scales on activations are hard: an activation scale per input channel cannot be pulled out of the summation (Nagel et al., 2021). This is also why TensorFlow Lite quantizes convolution weights per axis along the output channel dimension.
لأن S_i هو نفسه في كل حد من حدود المجموع، يراكم العتاد Σ_j q_ij x_j في مسجّل (register) للأعداد الصحيحة ثم يطبّق عملية ضرب واحدة في S_i s_x في النهاية، وهي خطوة يؤديها أصلًا لكل خرج على أي حال. لو كان الـ scale يتغيّر بدلًا من ذلك مع فهرس الدخل j، لبقي داخل المجموع، ولاحتاج كل حاصل ضرب إلى إعادة قياس خاصة به قبل جمعه، مما يُفقد المراكمة بالأعداد الصحيحة فائدتها. والحجة نفسها هي سبب صعوبة مقاييس per-channel على التنشيطات: لا يمكن إخراج scale تنشيط خاص بكل قناة دخل من المجموع (Nagel et al., 2021). ولهذا أيضًا يكمّم TensorFlow Lite أوزان الالتفاف لكل محور (per axis) على طول بُعد قناة الخرج.
Quick checkاختبار سريع
Why are per-channel weight scales taken over output channels rather than input channels?لماذا تؤخذ مقاييس الأوزان per-channel على قنوات الخرج وليس على قنوات الدخل؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- PTQ takes a trained floating-point model and picks (S, Z) without retraining. The lecture splits the choice into granularity, dynamic range clipping and rounding.يأخذ PTQ نموذجًا مدرّبًا بالفاصلة العائمة ويختار (S, Z) دون إعادة تدريب. تقسّم المحاضرة هذا الاختيار إلى granularity وdynamic range clipping وrounding.
- Symmetric weight quantization: Z = 0, |r|_max = |W|_max, S = |r|_max / q_max with q_max = 2^(N-1) - 1, and q = clip(round(W / S)).تكميم الأوزان المتماثل: Z = 0، و|r|_max = |W|_max، وS = |r|_max / q_max حيث q_max = 2^(N-1) - 1، وq = clip(round(W / S)).
- For N = 2, q_max = 1, so only the codes -1, 0, 1 appear. The code -2 exists in two's complement but the restricted symmetric grid never uses it.عند N = 2 تكون q_max = 1، فلا تظهر إلا الرموز -1 و0 و1. الرمز -2 موجود في تمثيل two's complement لكن الشبكة المتماثلة المقيّدة لا تستخدمه أبدًا.
- Per-tensor uses one S for the whole tensor. It works for large models but fails on small ones whose output channel ranges differ by more than 100x (the lecture's figure; MobileNetV2 evidence from Nagel et al. 2019).يستخدم per-tensor قيمة S واحدة للـ tensor كله. ينجح مع النماذج الكبيرة لكنه يفشل مع الصغيرة التي تختلف مديات قنوات الخرج فيها بأكثر من 100x (شكل المحاضرة، ودليل MobileNetV2 من Nagel et al. 2019).
- Per-channel gives output channel i its own S_i = max_j |W_ij| / q_max, so an outlier channel no longer inflates the step size of every other channel.يعطي per-channel قناة الخرج i قيمة خاصة بها S_i = max_j |W_ij| / q_max، فلا تعود القناة الشاذة تضخّم حجم الخطوة لكل قناة أخرى.
- Worked example: per-tensor S = 2.12, error ||W - S q||_F = 2.28. Per-channel S = (2.09, 2.12, 1.92, 1.87), one code changes (-1.03 goes from 0 to -1), error 2.08.المثال المحلول: في per-tensor تكون S = 2.12 والخطأ ||W - S q||_F = 2.28. وفي per-channel تكون S = (2.09, 2.12, 1.92, 1.87)، ويتغيّر رمز واحد (-1.03 ينتقل من 0 إلى -1)، والخطأ 2.08.
- Scales must sit on output channels because y_i = S_i s_x Σ_j q_ij x_j: the scale factors out of the integer dot product, so accumulation stays in integers.يجب أن تكون المقاييس على قنوات الخرج لأن y_i = S_i s_x Σ_j q_ij x_j: الـ scale يخرج كعامل مشترك من الجداء النقطي الصحيح، فتبقى المراكمة بالأعداد الصحيحة.
Sourcesالمصادر
- Data-Free Quantization Through Weight Equalization and Bias CorrectionPaperNagel, van Baalen, Blankevoort, Welling, ICCV 2019Source of the MobileNetV2 per-channel weight range box plot, the [-128, 128] versus (-0.5, 0.5) example, and the 71.72% / 0.12% / 70.65% results.مصدر مخطط الصندوق لمديات أوزان MobileNetV2 لكل قناة، ومثال [-128, 128] مقابل (-0.5, 0.5)، والنتائج 71.72% / 0.12% / 70.65%.(opens in a new tab)(يفتح في تبويب جديد)
- A White Paper on Neural Network QuantizationPaperNagel et al., Qualcomm AI Research, 2021Sections 2.2.3 and 2.4.2: granularity, why per-channel weight scales need no rescaling, and why per-channel activations are hard.القسمان 2.2.3 و2.4.2: مستويات الدقة (granularity)، ولماذا لا تحتاج مقاييس الأوزان per-channel إلى إعادة قياس، ولماذا يصعب تطبيق per-channel على التنشيطات.(opens in a new tab)(يفتح في تبويب جديد)
- Quantizing deep convolutional networks for efficient inference: A whitepaperPaperKrishnamoorthi, Google, 2018Per-channel weights with per-layer activations at 8 bits stay within 2% of floating point post-training.الأوزان per-channel مع تنشيطات per-layer عند 8 bits تبقى ضمن 2% من دقة الفاصلة العائمة بعد التدريب.(opens in a new tab)(يفتح في تبويب جديد)
- Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only InferencePaperJacob et al., CVPR 2018The integer-only inference scheme behind r = S(q - Z), cited on slide 7.طريقة الاستدلال بالأعداد الصحيحة فقط التي تقوم عليها r = S(q - Z)، والمذكورة في الشريحة 7.(opens in a new tab)(يفتح في تبويب جديد)
- LiteRT 8-bit quantization specificationDocsGoogle AI EdgeWeights are symmetric int8 in [-127, 127] with zero point 0, quantized per axis along the output channel.الأوزان int8 متماثلة في [-127, 127] ونقطة الصفر 0، وتُكمَّم لكل محور (per axis) على طول قناة الخرج.(opens in a new tab)(يفتح في تبويب جديد)
- TinyML and Efficient Deep Learning Computing (6.5940), Quantization Part IIDocsMIT Han LabThe course these slides are adapted from.المقرر الذي اقتُبست منه هذه الشرائح.(opens in a new tab)(يفتح في تبويب جديد)
Part 02: Group quantization: VS-Quant and shared micro-exponent formatsالتكميم بالمجموعات: VS-Quant وصيغ الأس الدقيق المشترك (MX)
Going finer than a channel: give small groups of elements their own scale. VS-Quant uses a cheap integer per-vector scale under a floating-point per-tensor or per-channel scale, and the MX formats share tiny exponents across 2 and 16 elements; the cost is counted as effective bit width.الذهاب إلى ما هو أدق من القناة: إعطاء مجموعات صغيرة من العناصر مقياسها الخاص. يستخدم VS-Quant مقياسًا صحيحًا رخيصًا لكل متجه تحت مقياس عائم لكل موتر أو لكل قناة، وتشارك صيغ MX أسسًا صغيرة عبر 2 و16 عنصرًا؛ وتُحسب الكلفة بوصفها عرض بت فعّالًا.
4 concepts4 مفاهيم, ، slides 14-21الشرائح 14-21
Why this part mattersلماذا يهمّ هذا الجزء
Part 1 ended with per-channel scales beating a single per-tensor scale. That is the whole story at 8 bits. At 4 bits it is not, and 4 bits is exactly where modern edge accelerators and data-center GPUs are heading. This part shows the next step down the granularity ladder: give small groups of weights their own scale, then pay for those extra scales cleverly with a second, coarser level. The one number to carry into the exam is the Effective bit width, and you will be able to compute it for any scheme in seconds.
انتهى الجزء 1 بتفوّق مقاييس كل قناة (per-channel) على مقياس واحد للموتر كله (per-tensor). هذه هي القصة كاملة عند 8 بت. أما عند 4 بت فليست كذلك، و4 بت هو بالضبط الاتجاه الذي تسير إليه مسرّعات الحافة (edge) الحديثة ووحدات GPU في مراكز البيانات. يعرض هذا الجزء الدرجة التالية نزولًا في سلّم الدقة الحبيبية (granularity): نعطي مجموعات صغيرة من الأوزان مقياسًا خاصًا بكل منها، ثم ندفع ثمن هذه المقاييس الإضافية بذكاء عبر مستوى ثانٍ أخشن. الرقم الوحيد الذي يجب أن تحمله معك إلى الاختبار هو effective bit width (عرض البت الفعلي)، وستتمكن من حسابه لأي مخطط في ثوانٍ.
By the end you canفي نهاية هذا الجزء ستستطيع
- Explain why per-channel scales stop being enough at 4 bits and what a group scale buys.تشرح لماذا لا تعود مقاييس كل قناة (per-channel) كافية عند 4 بت، وما الذي يكسبه مقياس المجموعة (group scale).
- Write the VS-Quant two-level form r = gamma * S_q (q - Z) and say which scale is integer and which is floating point, and why.تكتب الصيغة ثنائية المستوى في VS-Quant وهي r = gamma * S_q (q - Z)، وتحدد أي المقياسين عدد صحيح وأيهما فاصلة عائمة (floating point)، ولماذا.
- Generalize to r = (q - z) * s_l0 * s_l1 * ... and compute the effective bit width of any scheme.تعمّم إلى الصيغة r = (q - z) * s_l0 * s_l1 * ... وتحسب عرض البت الفعلي (effective bit width) لأي مخطط.
- Reproduce the slide 21 table: per-channel 4, VSQ 4.25, MX4 4, MX6 6, MX9 9.تعيد بناء جدول الشريحة 21: per-channel يساوي 4، وVSQ يساوي 4.25، وMX4 يساوي 4، وMX6 يساوي 6، وMX9 يساوي 9.
- Tell the paper's MX4/MX6/MX9 apart from the OCP MXFP4 and NVIDIA NVFP4 formats that Blackwell runs.تميّز صيغ MX4 وMX6 وMX9 الواردة في الورقة البحثية عن صيغتي MXFP4 من OCP وNVFP4 من NVIDIA اللتين تشغّلهما معالجات Blackwell.
Start with one output channel of eight weights, quantized to symmetric INT4. Symmetric INT4 gives you integers from -7 to 7, so . Split the channel into two groups of four: group A is [0.13, -0.21, 0.17, 0.06] and group B is [3.15, -0.3, 0.4, 0.1]. The 3.15 is an outlier, the kind every trained layer has a few of.
ابدأ بقناة إخراج واحدة فيها ثمانية أوزان، مكمّمة إلى INT4 متماثل. يعطيك INT4 المتماثل أعدادًا صحيحة من -7 إلى 7، أي أن . قسّم القناة إلى مجموعتين من أربعة أوزان: المجموعة A هي [0.13, -0.21, 0.17, 0.06] والمجموعة B هي [3.15, -0.3, 0.4, 0.1]. القيمة 3.15 قيمة شاذة (outlier)، من النوع الذي يوجد منه القليل في كل طبقة مدرَّبة.
Worked exampleمثال محلول
One outlier, two choices of scaleقيمة شاذة واحدة وخياران للمقياس
Per-channel scaleمقياس لكل قناة
Per-channel quantization uses one scale for all eight weights: . Group A divided by 0.45 gives 0.29, -0.47, 0.38, 0.13, and every one rounds to 0. Group A is erased.يستخدم per-channel quantization مقياسًا واحدًا للأوزان الثمانية كلها: . قسمة المجموعة A على 0.45 تعطي 0.29, -0.47, 0.38, 0.13، وكل واحدة منها تُقرَّب إلى 0. المجموعة A تُمحى تمامًا.Per-group scalesمقياس لكل مجموعة
Give each group of four its own scale. Group A: , so q = [4, -7, 6, 2] and the reconstruction is [0.12, -0.21, 0.18, 0.06]. Group B keeps because it holds the outlier.أعطِ كل مجموعة من أربعة أوزان مقياسها الخاص. المجموعة A: ، إذن q = [4, -7, 6, 2] وإعادة البناء تساوي [0.12, -0.21, 0.18, 0.06]. أما المجموعة B فتحتفظ بـ لأنها تحتوي القيمة الشاذة.Compare the errorsقارن الأخطاء
Group B is identical in both schemes (squared error 0.035). Group A costs 0.0935 under the channel scale and 0.0002 under its own scale. Total: 0.1285 versus 0.0352.المجموعة B متطابقة في المخططين (الخطأ التربيعي 0.035). أما المجموعة A فتكلّف 0.0935 تحت مقياس القناة و0.0002 تحت مقياسها الخاص. المجموع: 0.1285 مقابل 0.0352.Resultالنتيجة
The group scale cuts the squared error by more than 3.5x, and it does so by keeping the outlier's damage inside its own group.مقياس المجموعة يخفّض الخطأ التربيعي بأكثر من 3.5x، ويفعل ذلك بحصر ضرر القيمة الشاذة داخل مجموعتها.
That is Group quantization. Slides 14 and 15 place it on the Quantization granularity ladder: Per-tensor quantization shares one scale across the whole tensor, per-channel shares one across each output channel, and group quantization shares one across a small group of elements, typically 16 to 64, inside a channel. The slides name two concrete families: per-vector quantization (VS-Quant) and the shared micro-exponent (MX) data types.
هذا هو group quantization (التكميم بالمجموعات). تضعه الشريحتان 14 و15 على سلّم quantization granularity: per-tensor quantization يشارك مقياسًا واحدًا عبر الموتر كله، وper-channel يشارك مقياسًا واحدًا عبر كل قناة إخراج، والتكميم بالمجموعات يشارك مقياسًا واحدًا عبر مجموعة صغيرة من العناصر داخل القناة، عادة من 16 إلى 64 عنصرًا. تسمّي الشرائح عائلتين محددتين: التكميم لكل متجه (VS-Quant) وأنواع بيانات الأسس الدقيقة المشتركة (MX).
The general rule: the fewer quantization levels you have, the more each scale has to be fitted to its local neighbourhood. At 8 bits you have 255 levels and a channel scale wastes a few of them. At 4 bits you have 15, and wasting most of them on one outlier leaves the bulk of the weights with one or two levels, or none.
القاعدة العامة: كلما قلّ عدد مستويات التكميم، وجب أن يُضبط كل مقياس أكثر على جواره المحلي. عند 8 بت لديك 255 مستوى، ومقياس القناة يهدر بضعة منها فقط. عند 4 بت لديك 15 مستوى فقط، وإهدار معظمها على قيمة شاذة واحدة يترك أغلب الأوزان بمستوى أو مستويين، أو بلا مستوى إطلاقًا.
Why the hardware vendors careلماذا يهتم صانعو العتاد
Slide 16 frames the goal as a balance between quantization accuracy and hardware efficiency, and uses NVIDIA Blackwell as the evidence. Blackwell tensor cores support "micro-tensor scaling" to keep FP4 accurate, and the FP4 path has twice the theoretical throughput of the FP8/FP6/INT8 path: an HGX B200 board (eight GPUs) is rated at 144 PFLOPS FP4 versus 72 PFLOPS FP8/FP6 and 72 POPS INT8. Halving the bits doubles the math per cycle, but only if accuracy survives, and at 4 bits accuracy survives only with fine-grained scales. So the vendor built the group scaling into the tensor core itself: the hardware reads a block of FP4 values together with its scale and applies the scale during the dot product.
تصوغ الشريحة 16 الهدف على أنه توازن بين دقة التكميم وكفاءة العتاد، وتستخدم NVIDIA Blackwell دليلًا على ذلك. تدعم أنوية الموترات (tensor cores) في Blackwell ما يسمى "micro-tensor scaling" للحفاظ على دقة FP4، ومسار FP4 له ضعف الإنتاجية النظرية لمسار FP8/FP6/INT8: لوحة HGX B200 (ثماني وحدات GPU) مصنّفة بـ 144 PFLOPS في FP4 مقابل 72 PFLOPS في FP8/FP6 و72 POPS في INT8. تقليل عدد البتات إلى النصف يضاعف الحساب في كل دورة، لكن فقط إذا صمدت الدقة، وعند 4 بت لا تصمد الدقة إلا بمقاييس دقيقة الحبيبات. لذلك بنى الصانع التحجيم بالمجموعات داخل نواة الموترات نفسها: يقرأ العتاد كتلة من قيم FP4 مع مقياسها، ويطبّق المقياس أثناء حساب الضرب النقطي (dot product).
Recall
Why is a per-channel scale usually fine at INT8 but often not at INT4?لماذا يكون مقياس القناة الواحدة (per-channel) كافيًا عادةً في INT8 لكنه كثيرًا ما لا يكفي في INT4؟
INT8 has 255 levels, so even when an outlier stretches the range, small weights still get many levels. INT4 has only 15 symmetric levels, so an outlier in a long channel makes the scale so large that most small weights round to 0 or ±1. Smaller groups restore a scale that fits their own values.
يملك INT8 عدد 255 مستوى، فحتى عندما تمدّ قيمة شاذة المدى، تبقى للأوزان الصغيرة مستويات كثيرة. أما INT4 فلا يملك إلا 15 مستوى متماثلًا، فالقيمة الشاذة في قناة طويلة تجعل المقياس كبيرًا إلى حد أن معظم الأوزان الصغيرة تُقرَّب إلى 0 أو ±1. المجموعات الأصغر تعيد مقياسًا يناسب قيمها الخاصة.
Quick checkاختبار سريع
Why does group quantization beat per-channel quantization at 4 bits?لماذا يتفوق التكميم بالمجموعات على التكميم لكل قناة عند 4 بت؟
Back to the example. Group A wanted and group B wanted . Stored as FP16 numbers, these scales would cost 16 bits per group, which for groups of 16 INT4 weights adds a full 1 bit per weight. Worse, the hardware would need a floating-point multiplier next to every small vector unit. VS-Quant (Dai et al., NVIDIA) avoids both by noticing that the per-vector scales inside one channel differ from each other by modest factors. Factor each one as a shared floating-point number times a small integer:
نعود إلى المثال. المجموعة A أرادت والمجموعة B أرادت . لو خُزّنت هذه المقاييس أعدادًا من نوع FP16 لكلّفت 16 بت لكل مجموعة، وهذا يضيف 1 بت كاملًا لكل وزن عندما تكون المجموعات من 16 وزنًا INT4. والأسوأ أن العتاد سيحتاج إلى وحدة ضرب فاصلة عائمة بجانب كل وحدة متجهات صغيرة. يتجنب VS-Quant (Dai et al. من NVIDIA) المشكلتين بملاحظة أن مقاييس المتجهات داخل القناة الواحدة تختلف عن بعضها بعوامل معتدلة. لذلك نحلّل كل واحد منها إلى عدد فاصلة عائمة مشترك مضروبًا في عدد صحيح صغير:
- is a floating-point, coarse-grained scale, one per channel or per tensor. مقياس فاصلة عائمة خشن الحبيبات، واحد لكل قناة أو لكل موتر.
- is an integer scale, one per vector of elements (for example 16), stored with only a few bits such as UINT4. مقياس عدد صحيح، واحد لكل متجه من العناصر (مثلًا 16 عنصرًا)، ويُخزَّن ببتات قليلة فقط مثل UINT4.
In the example, pick so the largest per-vector scale fits in UINT4. Then and : two 4-bit integers and one FP16 number replace two FP16 scales. In a real layer one covers thousands of vectors, so its cost all but vanishes. (Real scales rarely divide this neatly; rounding the scale itself adds a small error, which VS-Quant's calibration algorithm accounts for.)
في المثال، اختر حتى يتسع أكبر مقياس متجه في UINT4. عندها و: عددان صحيحان من 4 بت وعدد FP16 واحد يحلّون محل مقياسين من FP16. في طبقة حقيقية يغطي واحد آلاف المتجهات، فتكاد كلفته تختفي. (نادرًا ما تنقسم المقاييس الحقيقية بهذه السهولة، وتقريب المقياس نفسه يضيف خطأً صغيرًا، وتأخذه خوارزمية المعايرة (calibration) في VS-Quant في الحسبان.)
Why the fine scale is the integer oneلماذا يكون المقياس الناعم هو العدد الصحيح
The design rule on slide 17 is: less expensive integer scales at finer granularity, more expensive floating-point scales at coarser granularity. Count how often each scale is stored and used. There is one per vector, so there are many of them, and each one must be both small in memory and cheap to multiply. An integer scale lets the vector MAC unit finish the whole per-vector dot product, scaling included, in integer arithmetic. There is only one per channel, so it can afford to be a precise floating-point number, applied once to the accumulated result. Put the expensive thing where it is rare.
قاعدة التصميم في الشريحة 17 هي: مقاييس أعداد صحيحة أرخص عند الحبيبات الناعمة، ومقاييس فاصلة عائمة أغلى عند الحبيبات الخشنة. احسب كم مرة يُخزَّن كل مقياس ويُستخدم. هناك واحد لكل متجه، أي أن عددها كبير، ويجب أن يكون كل واحد منها صغيرًا في الذاكرة ورخيصًا في الضرب. المقياس الصحيح يسمح لوحدة MAC المتجهية بإنهاء الضرب النقطي لكل متجه كاملًا، بما في ذلك التحجيم، بحساب الأعداد الصحيحة. وهناك واحد فقط لكل قناة، فيمكنه أن يكون عدد فاصلة عائمة دقيقًا يُطبَّق مرة واحدة على النتيجة المتراكمة. ضع الشيء المكلف حيث يكون نادرًا.
The memory billفاتورة الذاكرة
Slide 17 gives the overhead: 4-bit elements with a 4-bit per-vector scale for every 16 elements cost bits per element, a storage overhead of 6.25% over plain INT4. The paper writes this as for -bit elements, -bit scales and vectors of elements.
تعطي الشريحة 17 الكلفة الإضافية: عناصر من 4 بت مع مقياس متجه من 4 بت لكل 16 عنصرًا تكلّف بت لكل عنصر، أي كلفة تخزين إضافية قدرها 6.25% فوق INT4 العادي. تكتب الورقة ذلك على الصورة لعناصر من بت، ومقاييس من بت، ومتجهات من عنصرًا.
Recall
Write the VS-Quant reconstruction formula and say which factor is integer, which is floating point, and the granularity of each.اكتب صيغة إعادة البناء في VS-Quant، وحدد أي العاملين عدد صحيح وأيهما فاصلة عائمة، ودرجة الحبيبات لكل منهما.
. is an integer scale, one per vector (fine granularity). is a floating-point scale, one per channel or tensor (coarse granularity).
. مقياس عدد صحيح، واحد لكل متجه (حبيبات ناعمة). مقياس فاصلة عائمة، واحد لكل قناة أو موتر (حبيبات خشنة).
Quick checkاختبار سريع
Why is the fine-level scale in VS-Quant an integer rather than floating point?لماذا يكون مقياس المستوى الناعم في VS-Quant عددًا صحيحًا لا فاصلة عائمة؟
VS-Quant has two scale levels. Nothing stops you from having more, so slides 18 to 20 write the general Multi-level scaling form. Take one weight, say . It belongs to a small group (level 0), which belongs to a larger group (level 1), and so on. Its real value is its integer times the product of every scale above it:
لدى VS-Quant مستويان من المقاييس. لا شيء يمنعك من أكثر من ذلك، لذلك تكتب الشرائح من 18 إلى 20 الصيغة العامة لـ multi-level scaling (التحجيم متعدد المستويات). خذ وزنًا واحدًا، مثلًا . إنه ينتمي إلى مجموعة صغيرة (المستوى 0)، وهذه تنتمي إلى مجموعة أكبر (المستوى 1)، وهكذا. قيمته الحقيقية هي عدده الصحيح مضروبًا في حاصل ضرب كل المقاييس التي فوقه:
VS-Quant is the case , , and plain per-channel quantization is the one-level case. With the scheme is Symmetric quantization, which is what every row of the slide table uses.
VS-Quant هو الحالة و، والتكميم العادي لكل قناة هو حالة المستوى الواحد. ومع يكون المخطط symmetric quantization (تكميمًا متماثلًا)، وهو ما تستخدمه كل صفوف جدول الشريحة.
The effective bit widthعرض البت الفعلي (effective bit width)
Every scale is shared by its group, so its bits are spread over the group's elements. Add the element bits to each level's share:
كل مقياس تشترك فيه مجموعته، فتتوزع بتاته على عناصر المجموعة. أضف إلى بتات العنصر حصة كل مستوى:
Worked exampleمثال محلول
The two rows on slide 20الصفان في الشريحة 20
Per-channel INT4, FP16 scale per channelINT4 لكل قناة، مع مقياس FP16 لكل قناة
One level, (the channel length). For K = 4096: . The slide writes 4.مستوى واحد، و (طول القناة). عندما K = 4096: . تكتب الشريحة 4.VSQ INT4VSQ بصيغة INT4
L0: UINT4 per 16 elements. L1: FP16 per channel. . The slide writes .L0: UINT4 لكل 16 عنصرًا. L1: FP16 لكل قناة. . تكتب الشريحة .Resultالنتيجة
Both slide numbers drop the per-channel FP16 term. That is a fair approximation because one scale per thousands of weights is a few thousandths of a bit, but say so explicitly if an exam asks for exact numbers.رقما الشريحة كلاهما يُسقطان حد FP16 الخاص بكل قناة. هذا تقريب مقبول لأن مقياسًا واحدًا لكل آلاف الأوزان لا يتجاوز بضعة أجزاء من الألف من البت، لكن صرّح بذلك إذا طلب الاختبار أرقامًا دقيقة.
Use the calculator to rebuild every row of the slide table and to try the exam case. Notice how the L1 share collapses toward 0 as its group grows, and how the L0 share dominates.
استخدم الحاسبة لإعادة بناء كل صف في جدول الشريحة ولتجربة حالة الاختبار. لاحظ كيف تنهار حصة L1 نحو 0 كلما كبرت مجموعتها، وكيف تهيمن حصة L0.
4 + 4/16 + 16/4096 = 4.2539
UINT4 scale per 16 weights, FP16 scale per 4096-weight channel. The slide keeps only 4/16. Effective bits = b + s0/g0 + s1/g1.معامل scale بصيغة UINT4 لكل 16 وزنًا، ومعامل scale بصيغة FP16 لكل قناة من 4096 وزنًا. الشريحة تحتفظ بالحد 4/16 فقط. عدد البتات الفعلي (effective bits) يساوي b + s0/g0 + s1/g1.
Recall
A scheme stores INT4 elements, a UINT8 scale per 64 elements, and an FP32 scale per 4096 elements. What is its effective bit width?مخطط يخزّن عناصر INT4، ومقياس UINT8 لكل 64 عنصرًا، ومقياس FP32 لكل 4096 عنصرًا. ما عرض البت الفعلي له؟
bits per element. Dropping the coarse term gives 4.125.
بت لكل عنصر. وإسقاط الحد الخشن يعطي 4.125.
Quick checkاختبار سريع
INT4 weights use one 8-bit scale per 32 elements. What is the effective bit width?أوزان INT4 تستخدم مقياسًا واحدًا من 8 بت لكل 32 عنصرًا. ما عرض البت الفعلي؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- Group quantization gives each small group of elements (16 to 64) its own scale, so an outlier only spoils its own group.التكميم بالمجموعات (group quantization) يعطي كل مجموعة صغيرة من العناصر (من 16 إلى 64) مقياسًا خاصًا بها، فلا تُفسد القيمة الشاذة (outlier) إلا مجموعتها.
- At 4 bits a symmetric INT4 has only 15 levels, so one big weight in a long channel pushes most small weights to 0. That is why 4-bit schemes go finer than per-channel.عند 4 بت لا يملك INT4 المتماثل إلا 15 مستوى، لذلك يكفي وزن كبير واحد في قناة طويلة لدفع معظم الأوزان الصغيرة إلى 0. ولهذا تنزل مخططات 4 بت إلى دقة أنعم من مستوى القناة.
- Blackwell's FP4 tensor cores give 2x the throughput of FP8/FP6/INT8 (HGX B200: 144 vs 72 PFLOPS, both sparse), and micro-tensor scaling is what keeps FP4 accurate.أنوية الموترات FP4 في Blackwell تعطي ضعف إنتاجية FP8/FP6/INT8 (في HGX B200: 144 مقابل 72 PFLOPS، وكلاهما بالتناثر sparse)، والتحجيم الدقيق للموترات (micro-tensor scaling) هو ما يحافظ على دقة FP4.
- VS-Quant: r = gamma * S_q (q - Z). Cheap integer S_q per vector at fine granularity, expensive floating-point gamma per channel or tensor at coarse granularity.VS-Quant: r = gamma * S_q (q - Z). مقياس صحيح رخيص S_q لكل متجه بدقة حبيبية ناعمة، ومقياس فاصلة عائمة مكلف gamma لكل قناة أو موتر بدقة حبيبية خشنة.
- General form: r = (q - z) * s_l0 * s_l1 * ..., z = 0 means symmetric.الصيغة العامة: r = (q - z) * s_l0 * s_l1 * ...، وz = 0 تعني تكميمًا متماثلًا (symmetric).
- Effective bit width = element bits + sum over levels of (scale bits / group size). INT4 with an 8-bit scale per 32 gives 4.25.عرض البت الفعلي = بتات العنصر + مجموع (بتات المقياس / حجم المجموعة) على كل المستويات. INT4 مع مقياس 8 بت لكل 32 عنصرًا يعطي 4.25.
- Slide table: per-channel 4, VSQ 4 + 4/16 = 4.25, MX4 3 + 1/2 + 8/16 = 4, MX6 6, MX9 9. The per-channel FP16 terms are ignored because they are spread over thousands of weights.جدول الشريحة: per-channel يساوي 4، وVSQ يساوي 4 + 4/16 = 4.25، وMX4 يساوي 3 + 1/2 + 8/16 = 4، وMX6 يساوي 6، وMX9 يساوي 9. تُهمل حدود FP16 الخاصة بكل قناة لأنها موزعة على آلاف الأوزان.
- MX scales are powers of two (E1M0, E8M0), so applying them is a shift, not a multiply.مقاييس MX قوى للعدد 2 (E1M0 وE8M0)، لذلك يكون تطبيقها إزاحة بتات (shift) لا عملية ضرب.
Sourcesالمصادر
- VS-Quant: Per-vector Scaled Quantization for Accurate Low-Precision Neural Network InferencePaperDai, Venkatesan, Ren, Zimmer, Dally and Khailany (NVIDIA), arXiv 2021Section 4.4: the per-vector scale factored into an integer s_q and a floating-point coarse gamma; with N = M = 4 and V = 16 the overhead is 6.25%, an effective 4.25 bits.القسم 4.4: مقياس المتجه محلَّل إلى عدد صحيح s_q ومقياس فاصلة عائمة خشن gamma؛ ومع N = M = 4 وV = 16 تكون الكلفة الإضافية 6.25%، أي عرض فعلي قدره 4.25 بت.(opens in a new tab)(يفتح في تبويب جديد)
- With Shared Microexponents, A Little Shifting Goes a Long WayPaperRouhani et al. (Microsoft and Meta), arXiv 2023Bits per element (m + 1) + d1/k1 + d2/k2; Table II defines MX9, MX6, MX4 with k1 = 16, k2 = 2, d1 = 8, d2 = 1 and m = 7, 4, 2.البتات لكل عنصر (m + 1) + d1/k1 + d2/k2؛ والجدول II يعرّف MX9 وMX6 وMX4 مع k1 = 16 وk2 = 2 وd1 = 8 وd2 = 1 وm = 7 و4 و2.(opens in a new tab)(يفتح في تبويب جديد)
- OCP Microscaling Formats (MX) Specification v1.0DocsOpen Compute ProjectTable 1: MXFP8, MXFP6, MXFP4 (E2M1) and MXINT8, all with block size 32 and an E8M0 shared scale.الجدول 1: MXFP8 وMXFP6 وMXFP4 (E2M1) وMXINT8، كلها بحجم كتلة 32 ومقياس مشترك E8M0.(opens in a new tab)(يفتح في تبويب جديد)
- Introducing NVFP4 for Efficient and Accurate Low-Precision InferenceArticleNVIDIA Technical BlogNVFP4: E2M1 values, an FP8 E4M3 scale per 16 values and an FP32 per-tensor scale, about 4.5 bits per value; MXFP4 uses E8M0 per 32.NVFP4: قيم E2M1، ومقياس FP8 E4M3 لكل 16 قيمة، ومقياس FP32 لكل موتر، أي نحو 4.5 بت لكل قيمة؛ أما MXFP4 فيستخدم E8M0 لكل 32.(opens in a new tab)(يفتح في تبويب جديد)
- NVIDIA HGX PlatformDocsNVIDIAHGX B200: FP4 144 | 72 PFLOPS (sparse | dense), FP8/FP6 72 PFLOPS and INT8 72 POPS sparse.HGX B200: FP4 بقيمة 144 | 72 PFLOPS (sparse | dense)، وFP8/FP6 بقيمة 72 PFLOPS، وINT8 بقيمة 72 POPS، وكلها بالتناثر (sparse).(opens in a new tab)(يفتح في تبويب جديد)
- MIT 6.5940 EfficientML.ai, Lecture 6: Quantization (Part II)DocsMIT HAN LabThe course from which this lecture's slides are adapted.المقرر الذي اقتُبست منه شرائح هذه المحاضرة.(opens in a new tab)(يفتح في تبويب جديد)
Part 03: Dynamic range clipping for activations: EMA, calibration, MSE and KLقص المدى الديناميكي للتنشيطات: EMA والمعايرة وMSE وKL
Activations change with every input, so their range must be estimated before deployment, either with an exponential moving average during training or by running calibration batches. Clipping outliers trades clipping error for finer resolution, and the clip point is chosen by minimizing MSE (analytically for Laplace, or with OCTAV's Newton-Raphson) or KL divergence.تتغير التنشيطات مع كل مدخل، لذا يجب تقدير مداها قبل النشر، إما بمتوسط متحرك أسي (EMA) أثناء التدريب أو بتشغيل دفعات معايرة (calibration). قص القيم الشاذة يقايض خطأ القص بدقة تمثيل أنعم، وتُختار نقطة القص بتقليل MSE (تحليليًا لتوزيع Laplace، أو بطريقة Newton-Raphson في OCTAV) أو تباعد KL.
6 concepts6 مفاهيم, ، slides 22-31الشرائح 22-31
Why this part mattersلماذا يهمّ هذا الجزء
Linear quantization needs a range before it can do anything. Parts one and two chose how many scales a tensor gets. This part asks a different question: for one scale, which range should it cover? For weights the answer is easy because they sit still. Activations do not, so you have to measure them, and then decide how much of what you measured to throw away.
The thread runs in one direction. First, why activations need data at all. Second and third, the two ways to collect that data: a moving average during training, or calibration batches after it. Then the central trade: cutting off rare outliers costs a little clipping error but buys finer steps for everything else. The last three concepts are three ways to choose the cut: a closed-form MSE table for Laplace data, KL divergence as TensorRT does it, and OCTAV's Newton-Raphson search. For the midterm, expect an EMA update by hand, the Laplace table, and a "why does clipping help" explanation.
يحتاج التكميم الخطي إلى مدى قبل أن يفعل أي شيء. اختار الجزءان الأول والثاني عدد المقاييس (scales) التي يحصل عليها الموتر. أما هذا الجزء فيطرح سؤالًا مختلفًا: لمقياس واحد، ما المدى الذي يجب أن يغطيه؟ في الأوزان الجواب سهل لأنها ثابتة لا تتحرك. التنشيطات ليست كذلك، لذلك عليك أن تقيسها، ثم تقرر كم مما قسته ستتخلص منه.
يسير الخيط في اتجاه واحد. أولًا: لماذا تحتاج التنشيطات إلى بيانات أصلًا. ثانيًا وثالثًا: الطريقتان لجمع تلك البيانات، إما متوسط متحرك أثناء التدريب، أو دفعات معايرة (calibration batches) بعده. ثم المقايضة المحورية: قص القيم الشاذة النادرة يكلّف قليلًا من خطأ القص (clipping error) لكنه يشتري خطوات أدق لكل القيم الأخرى. المفاهيم الثلاثة الأخيرة هي ثلاث طرق لاختيار حد القص: جدول MSE بصيغة مغلقة لبيانات لابلاس، وتباعد KL كما يفعله TensorRT، وبحث نيوتن-رافسون في OCTAV. في اختبار منتصف الفصل توقّع تحديث EMA يدويًا، وجدول لابلاس، وشرحًا لسؤال «لماذا يفيد القص».
By the end you canفي نهاية هذا الجزء ستستطيع
- Explain why weight ranges can be read offline but activation ranges must be estimated from data before deployment.أن تشرح لماذا يمكن قراءة مدى الأوزان دون اتصال (offline)، بينما يجب تقدير مدى التنشيطات من البيانات قبل النشر.
- Update an exponential moving average of r_max and r_min by hand, and state which way the slide's α points.أن تحدّث متوسطًا متحركًا أُسّيًا (EMA) لـ r_max وr_min يدويًا، وأن تحدد على أي حدّ تقع α في صيغة الشريحة: على القيمة الجديدة أم على التقدير القديم.
- Explain why clipping outliers can lower the total quantization error, in terms of clipping error and rounding error.أن تشرح لماذا قد يقلل قص القيم الشاذة الخطأ الكلي للتكميم، من خلال خطأ القص وخطأ التقريب.
- Read the Laplace table (2.83b, 3.89b, 5.03b) and turn a measured b into a clip value.أن تقرأ جدول لابلاس (2.83b و3.89b و5.03b) وتحوّل قيمة b المقيسة إلى قيمة قص.
- Contrast the MSE and KL calibration objectives, and describe how TensorRT's entropy method picks a threshold.أن تقارن بين هدفي المعايرة MSE وKL، وتصف كيف تختار طريقة الإنتروبيا في TensorRT حد العتبة.
- Describe what OCTAV computes with Newton-Raphson and what its int4 results show.أن تصف ما يحسبه OCTAV باستخدام نيوتن-رافسون وما تُظهره نتائجه عند int4.
Take a trained image classifier and look at the output of its third convolution layer. Feed it a dark night photo and the largest activation might be 3.1. Feed it a bright beach photo and the largest might be 11.4. The weights of that layer were identical both times. Only the input changed.
خذ مصنّف صور مدرَّبًا وانظر إلى مخرج طبقة الالتفاف الثالثة فيه. أدخل صورة ليلية مظلمة فقد يكون أكبر تنشيط 3.1. أدخل صورة شاطئ مشرقة فقد يكون الأكبر 11.4. أوزان تلك الطبقة كانت متطابقة في المرتين، والذي تغيّر هو المدخل فقط.
The range is the scaleالمدى هو المقياس
This matters because the range is not a side detail of linear quantization. It is the scale itself. With , the scale is fixed by the range you choose to cover:
هذا مهم لأن المدى ليس تفصيلًا جانبيًا في التكميم الخطي، بل هو المقياس نفسه. مع ، يتحدد المقياس بالمدى الذي تختار أن تغطيه:
So the question on slide 22, how to get the optimal (S, Z) in Post-training quantization (PTQ), is the same question as how to pick the range. The lecture splits it into three topics: granularity (how many scales, the previous two parts), Dynamic range clipping (this part), and rounding (the next part).
إذن سؤال الشريحة 22، أي كيف نحصل على (S, Z) الأمثل في post-training quantization، هو نفسه سؤال كيف نختار المدى. تقسّمه المحاضرة إلى ثلاثة موضوعات: الدقة الحُبيبية (granularity)، أي عدد المقاييس، وهو موضوع الجزأين السابقين، وdynamic range clipping (هذا الجزء)، والتقريب (rounding) في الجزء التالي.
| Weightsالأوزان | Activationsالتنشيطات | |
|---|---|---|
| When the values existمتى توجد القيم | After training, frozenبعد التدريب، وتكون مجمّدة | Only when an input flows through the networkفقط عندما يمر مدخل عبر الشبكة |
| Does the range changeهل يتغير المدى | Neverأبدًا | With every input image, sentence or sensor frameمع كل صورة أو جملة أو إطار حسّاس يدخل |
| How the range is foundكيف يُحدَّد المدى | Read min and max (or a clip) directly from the tensorيُقرأ الحد الأدنى والأعلى (أو حد قص) مباشرة من الموتر | Estimated from data: an EMA during training or calibration batchesيُقدَّر من البيانات: EMA أثناء التدريب أو دفعات معايرة |
| Where the work happensأين يتم العمل | Offline, onceدون اتصال (offline)، مرة واحدة | Offline, before deployment, so the device can use fixed scalesدون اتصال، قبل النشر، حتى يستخدم الجهاز مقاييس ثابتة |
Jacob et al. state the rule plainly: for weights, set the range to the tensor's own min and max. For activations, the range depends on the inputs, so it has to be estimated. Why not just measure each activation's range live, on the device, for every input? You can, and some runtimes do, but it costs an extra pass over every tensor at inference time, and it stops the integer pipeline from folding the scales into fixed constants ahead of time. Edge deployment usually wants fixed scales, so the statistics are gathered before deployment, which is exactly what slide 23 stresses.
يذكر Jacob et al. القاعدة بوضوح: في الأوزان، اجعل المدى هو الحد الأدنى والأعلى للموتر نفسه. أما في التنشيطات فالمدى يعتمد على المدخلات، لذلك يجب تقديره. لماذا لا نقيس مدى كل تنشيط مباشرة على الجهاز لكل مدخل؟ يمكنك ذلك، وبعض بيئات التشغيل تفعله، لكنه يكلّف مرورًا إضافيًا على كل موتر وقت الاستدلال، ويمنع خط المعالجة بالأعداد الصحيحة من دمج المقاييس في ثوابت محددة مسبقًا. النشر على الأجهزة الطرفية يريد عادة مقاييس ثابتة، لذلك تُجمع الإحصاءات قبل النشر، وهذا بالضبط ما تؤكده الشريحة 23.
Recall
Why can a weight tensor be quantized with no data at all, while an activation tensor cannot?لماذا يمكن تكميم موتر الأوزان دون أي بيانات، بينما لا يمكن ذلك لموتر التنشيطات؟
Suppose you are already training with quantization in the loop. Every training step already computes the activations, so you see their min and max for free. One batch says the max is 6.0, the next says 8.0, the next 5.0. Which one do you believe?
افترض أنك تدرّب النموذج والتكميم داخل الحلقة أصلًا. كل خطوة تدريب تحسب التنشيطات بالفعل، فترى حدها الأدنى والأعلى مجانًا. دفعة تقول إن الحد الأعلى 6.0، والتالية تقول 8.0، والتي بعدها 5.0. أيها تصدّق؟
Smooth the range instead of trusting one batchنعّم المدى بدل أن تثق بدفعة واحدة
None of them alone. Type 1 on slide 24, from Jacob et al., keeps an Exponential moving average (EMA) of the observed extremes. Each step blends the newest observation with the running estimate:
لا واحدة منها وحدها. النوع الأول في الشريحة 24، من Jacob et al.، يحتفظ بـ exponential moving average للقيم القصوى المرصودة. كل خطوة تمزج أحدث رصد مع التقدير الجاري:
Unroll it and the weight on an observation from k steps ago is . Old batches never vanish, they fade geometrically. That is why the paper says the ranges are smoothed across thousands of training steps: one freak batch moves the estimate by only a fraction α of its surprise.
افرد الصيغة فيصبح وزن رصدٍ جاء قبل k خطوة هو . الدفعات القديمة لا تختفي أبدًا، بل يتلاشى أثرها هندسيًا. لهذا تقول الورقة إن المديات تُنعَّم عبر آلاف خطوات التدريب: دفعة شاذة واحدة تحرّك التقدير بجزء α فقط من مقدار مفاجأتها.
Worked exampleمثال محلول
Two EMA steps by hand, α = 0.1خطوتا EMA يدويًا، α = 0.1
Initialize from the first batchابدأ من الدفعة الأولى
The first batch gives r_min = -2.0 and r_max = 6.0 (a tensor before its ReLU, so it has negative values). Start the estimate there: r̂_min = -2.0, r̂_max = 6.0.تعطي الدفعة الأولى r_min = -2.0 وr_max = 6.0 (موتر قبل دالة ReLU الخاصة به، لذلك فيه قيم سالبة). ابدأ التقدير من هناك: r̂_min = -2.0 وr̂_max = 6.0.Step 1: observe -3.0 and 8.0الخطوة 1: نرصد -3.0 و8.0
r̂_max = 0.1 × 8.0 + 0.9 × 6.0 = 0.8 + 5.4 = 6.2. r̂_min = 0.1 × (-3.0) + 0.9 × (-2.0) = -0.3 - 1.8 = -2.1.r̂_max = 0.1 × 8.0 + 0.9 × 6.0 = 0.8 + 5.4 = 6.2. r̂_min = 0.1 × (-3.0) + 0.9 × (-2.0) = -0.3 - 1.8 = -2.1.Step 2: observe -1.0 and 5.0الخطوة 2: نرصد -1.0 و5.0
r̂_max = 0.1 × 5.0 + 0.9 × 6.2 = 0.5 + 5.58 = 6.08. r̂_min = 0.1 × (-1.0) + 0.9 × (-2.1) = -0.1 - 1.89 = -1.99.r̂_max = 0.1 × 5.0 + 0.9 × 6.2 = 0.5 + 5.58 = 6.08. r̂_min = 0.1 × (-1.0) + 0.9 × (-2.1) = -0.1 - 1.89 = -1.99.Turn the range into an 8-bit scaleحوّل المدى إلى مقياس 8 بت
S = (6.08 - (-1.99)) / 255 = 8.07 / 255 ≈ 0.0316.S = (6.08 - (-1.99)) / 255 = 8.07 / 255 ≈ 0.0316.Resultالنتيجة
The observed max jumped to 8.0 and then fell to 5.0, but the estimate only moved 6.0 → 6.2 → 6.08. That damping is the point of the EMA.قفز الحد الأعلى المرصود إلى 8.0 ثم هبط إلى 5.0، لكن التقدير تحرّك فقط 6.0 → 6.2 → 6.08. هذا التخميد هو الغاية من EMA.
| Step tالخطوة t | Sourceالمصدر | Observed r_min / r_maxالمرصود r_min / r_max | EMA r̂_min / r̂_maxتقدير EMA r̂_min / r̂_max |
|---|---|---|---|
| 00 | first batchالدفعة الأولى | -2.0 / 6.0-2.0 / 6.0 | -2.00 / 6.00-2.00 / 6.00 |
| 11 | next batchالدفعة التالية | -3.0 / 8.0-3.0 / 8.0 | -2.10 / 6.20-2.10 / 6.20 |
| 22 | next batchالدفعة التالية | -1.0 / 5.0-1.0 / 5.0 | -1.99 / 6.08-1.99 / 6.08 |
Quick checkاختبار سريع
Using the slide's formula with α = 0.1, the running r̂_max is 6.0 and the next batch shows 8.0. What is the new r̂_max?باستخدام صيغة الشريحة مع α = 0.1، التقدير الجاري r̂_max يساوي 6.0 والدفعة التالية تُظهر 8.0. ما قيمة r̂_max الجديدة؟
Now suppose the model is already trained in FP32 and you will not train again. You still need ranges. Type 2 on slide 25 runs a few Calibration batches of ordinary samples through the trained model and records the activations. No labels, no gradients, just forward passes.
افترض الآن أن النموذج مدرَّب مسبقًا بدقة FP32 ولن تدرّبه من جديد. ما زلت تحتاج إلى المديات. النوع الثاني في الشريحة 25 يمرّر بضع calibration batches من العينات العادية عبر النموذج المدرَّب ويسجّل التنشيطات. لا تسميات، ولا تدرجات، مجرد تمريرات أمامية.
One outlier can waste most of the gridقيمة شاذة واحدة قد تهدر معظم الشبكة
The naive choice is the global min and max seen during calibration. Picture four calibration images whose maximum activations in one layer are 5.8, 6.1, 6.0 and 25.0. The last one is a glare spot. With unsigned 8-bit codes and the global max, the step is 25.0 / 255 ≈ 0.098. Nearly all real values live below 6.1, so they get only about 62 of the 255 steps. Three quarters of the codes are reserved for values that almost never occur.
الخيار الساذج هو الحد الأدنى والأعلى الكليّان المرصودان أثناء المعايرة. تخيّل أربع صور معايرة أكبر تنشيطاتها في طبقة ما هي 5.8 و6.1 و6.0 و25.0. الأخيرة بقعة وهج. مع رموز 8 بت بلا إشارة والحد الأعلى الكلي، تكون الخطوة 25.0 / 255 ≈ 0.098. تقريبًا كل القيم الحقيقية تقع تحت 6.1، فلا تحصل إلا على نحو 62 من الخطوات الـ255. ثلاثة أرباع الرموز محجوزة لقيم لا تكاد تظهر أبدًا.
The slide's first fix is to average the per-sample extremes instead of taking the global one: (5.8 + 6.1 + 6.0 + 25.0) / 4 = 10.725. The step becomes 10.725 / 255 ≈ 0.042, more than twice as fine. The glare value now lands beyond the range and is clipped to 10.725. The mean softens the outlier, though it does not remove its pull, which is why the slide also points to analytical methods.
الحل الأول في الشريحة هو أخذ متوسط القيم القصوى لكل عينة بدل القيمة القصوى الكلية: (5.8 + 6.1 + 6.0 + 25.0) / 4 = 10.725. تصبح الخطوة 10.725 / 255 ≈ 0.042، أي أدق بأكثر من الضعف. قيمة الوهج تقع الآن خارج المدى وتُقص إلى 10.725. المتوسط يخفف أثر القيمة الشاذة لكنه لا يزيل جذبها، ولهذا تشير الشريحة أيضًا إلى الطرق التحليلية.
Two errors, one dialخطآن ومقبض واحد
Every clipping decision trades two kinds of error. Values inside the range suffer rounding error, at most half a step and on average in squared terms. Values outside suffer clipping error: they are forced to the edge, and the error grows with how far out they were. Widen the range and the clipping error falls but every step grows. Narrow it and the steps shrink but more values are cut. The total has a minimum somewhere in between, and that is what the next three concepts hunt for.
كل قرار قص يقايض بين نوعين من الخطأ. القيم داخل المدى تعاني خطأ التقريب (rounding error)، وهو نصف خطوة على الأكثر، ومتوسطه بالقيم المربعة. أما القيم خارج المدى فتعاني خطأ القص (clipping error): تُجبر على الحافة، ويكبر الخطأ كلما كانت أبعد. وسّع المدى فينخفض خطأ القص لكن كل خطوة تكبر. ضيّقه فتصغر الخطوات لكن تُقص قيم أكثر. للمجموع قيمة دنيا في مكان ما بينهما، وهذا ما تبحث عنه المفاهيم الثلاثة التالية.
Recall
Name the two error sources in a clipped quantizer and say which way each moves when you widen the range.سمِّ مصدري الخطأ في مكمِّم مقصوص، وقل في أي اتجاه يتحرك كل منهما عندما توسّع المدى.
A calibration run tells you that one layer's activations look like a sharp peak at zero with long, thin tails, and that the mean absolute value is 0.2. You will quantize to 4 bits. Where do you clip?
تخبرك جولة معايرة أن تنشيطات إحدى الطبقات تبدو كقمة حادة عند الصفر مع ذيول طويلة رفيعة، وأن متوسط القيمة المطلقة 0.2. ستكمّم إلى 4 بت. أين تقص؟
Write the error down and minimize itاكتب الخطأ صراحة ثم قلّله
Slide 26 answers with the most direct objective: pick the clip that minimizes the mean squared error between the input X and its reconstruction Q(X).
تجيب الشريحة 26 بالهدف الأكثر مباشرة: اختر حد القص الذي يقلل متوسط مربع الخطأ (MSE) بين المدخل X وإعادة بنائه Q(X).
To solve it you need the distribution of X. Banner et al. observe that activations are often close to Gaussian or Laplace. For a Laplace(0, b) input quantized with M bits over [-α, α] (their notation, α is the clip), the two error terms have a closed form:
لحلها تحتاج إلى توزيع X. يلاحظ Banner et al. أن التنشيطات كثيرًا ما تكون قريبة من التوزيع الغاوسي أو توزيع لابلاس. لمدخل Laplace(0, b) مكمَّم بـM بت على [-α, α] (برموزهم، α هي حد القص)، يكون لحدّي الخطأ صيغة مغلقة:
Set the derivative to zero, , and solve numerically. Because α only ever appears as α/b, the answer is a pure multiple of b. That multiple is the Laplace optimal clipping table:
اجعل المشتقة صفرًا، ، وحلّ عدديًا. وبما أن α لا تظهر إلا في الصورة α/b، فالجواب مضاعف خالص لـb. هذا المضاعف هو جدول Laplace clipping:
The scale parameter is estimated from the calibration data as the mean absolute deviation, . For our layer that is the 0.2 we measured.
يُقدَّر معامل المقياس من بيانات المعايرة بوصفه متوسط الانحراف المطلق، . في طبقتنا هذا هو الـ0.2 الذي قسناه.
Worked exampleمثال محلول
Laplace clip for b = 0.2حد قص لابلاس عند b = 0.2
4 bits4 بت
|r|max = 5.03 × 0.2 = 1.006. Step Δ = 2 × 1.006 / 16 ≈ 0.126.|r|max = 5.03 × 0.2 = 1.006. الخطوة Δ = 2 × 1.006 / 16 ≈ 0.126.Price the two errors at that clipاحسب كلفة الخطأين عند حد القص هذا
Clipping: 2 × 0.04 × e^(-5.03) ≈ 0.08 × 0.00654 ≈ 0.00052. Rounding: 1.006² / 768 ≈ 0.00132. Total ≈ 0.00184.القص: 2 × 0.04 × e^(-5.03) ≈ 0.08 × 0.00654 ≈ 0.00052. التقريب: 1.006² / 768 ≈ 0.00132. المجموع ≈ 0.00184.Compare with a wide range of 2.0 (10b)قارن بمدى واسع قدره 2.0 (10b)
Clipping: 0.08 × e^(-10) ≈ 0.0000036. Rounding: 4 / 768 ≈ 0.00521. Total ≈ 0.00521, about 2.8× worse, even though almost nothing was clipped.القص: 0.08 × e^(-10) ≈ 0.0000036. التقريب: 4 / 768 ≈ 0.00521. المجموع ≈ 0.00521، أي أسوأ بنحو 2.8×، مع أنه لم يُقص شيء تقريبًا.2 bits2 بت
|r|max = 2.83 × 0.2 = 0.566, so Δ = 2 × 0.566 / 4 ≈ 0.283.|r|max = 2.83 × 0.2 = 0.566، إذن Δ = 2 × 0.566 / 4 ≈ 0.283.Resultالنتيجة
At 4 bits clip at 1.006; at 2 bits clip at 0.566. Fewer bits, tighter clip.عند 4 بت قص عند 1.006؛ وعند 2 بت قص عند 0.566. بتات أقل، قص أضيق.
| Bits Mعدد البتات M | Optimal clipحد القص الأمثل | Clip at b = 0.2حد القص عند b = 0.2 | Step Δالخطوة Δ | Fraction of values clippedنسبة القيم المقصوصة |
|---|---|---|---|---|
| 22 | 2.83b2.83b | 0.5660.566 | 0.2830.283 | 5.9%5.9% |
| 33 | 3.89b3.89b | 0.7780.778 | 0.1940.194 | 2.0%2.0% |
| 44 | 5.03b5.03b | 1.0061.006 | 0.1260.126 | 0.65%0.65% |
Uses the Banner et al. model: MSE ≈ clipping + |r|max² / (3 · 4^M), with the clipping term 2b² e^(-|r|max / b) for Laplace and a numerical integral for Gaussian. Values are in units of the scale parameter, so multiply the best clip by your measured b or σ. The rounding model assumes the density is flat inside each bin, so it is rough at 2 bits.نستخدم نموذج Banner et al.: MSE ≈ clipping + |r|max² / (3 · 4^M)، حيث حد القص يساوي 2b² e^(-|r|max / b) لتوزيع Laplace، وتكاملًا عدديًا لتوزيعGaussian. القيم معطاة بوحدات معامل المقياس للتوزيع، لذا اضرب أفضل قيمة قص في قيمة b أو σ التي قستها. يفترض نموذج التقريب أن الكثافة ثابتة داخل كل خانة، لذلك يكون تقريبيًا عند 2 bits.
Quick checkاختبار سريع
A layer's calibration data gives b = 0.3. What clip does the Laplace table give at 3 bits?تعطي بيانات المعايرة لإحدى الطبقات b = 0.3. ما حد القص الذي يعطيه جدول لابلاس عند 3 بت؟
Quick checkاختبار سريع
Clipping a Laplace tensor at 5.03b instead of 10b at 4 bits lowers the total MSE. Why?قص موتر لابلاسي عند 5.03b بدل 10b عند 4 بت يخفض MSE الكلي. لماذا؟
Recall
For b = 0.5, give the 2-bit and 4-bit clips and the fraction of values clipped in each case.عند b = 0.5، أعطِ حد القص عند 2 بت و4 بت ونسبة القيم المقصوصة في كل حالة.
Look at slide 27's histogram for VGG-19 conv3_4. The counts fall over seven orders of magnitude between 0 and about 25,000. No neat Laplace formula is going to describe that tail, so a clip read from an assumed shape is on shaky ground. NVIDIA's TensorRT took a different route in 2017: compare distributions instead of values.
انظر إلى المدرّج التكراري في الشريحة 27 لطبقة VGG-19 conv3_4. تنخفض الأعداد عبر سبع مراتب عشرية بين 0 ونحو 25,000. لن تصف أي صيغة لابلاس أنيقة ذلك الذيل، لذلك فحد القص المقروء من شكل مفترض يقف على أرض هشة. سلكت TensorRT من NVIDIA طريقًا مختلفًا في 2017: قارن بين التوزيعات بدل القيم.
KL divergence: how much information the quantized histogram losesتباعد KL: كم من المعلومات يفقد المدرّج التكراري المكمَّم
The idea on slide 27 is that the INT8 model should encode the same information as the FP32 model. Information loss between two distributions is measured by KL divergence:
الفكرة في الشريحة 27 أن نموذج INT8 يجب أن يرمّز المعلومات نفسها التي يرمّزها نموذج FP32. فقدان المعلومات بين توزيعين يُقاس بـKL divergence:
Worked exampleمثال محلول
KL on three binsتباعد KL على ثلاث خانات
Set upالإعداد
Let P = [0.5, 0.3, 0.2] and Q = [0.4, 0.4, 0.2], using the natural log.لتكن P = [0.5, 0.3, 0.2] وQ = [0.4, 0.4, 0.2]، مع استخدام اللوغاريتم الطبيعي.Sum the termsاجمع الحدود
0.5 ln(0.5/0.4) + 0.3 ln(0.3/0.4) + 0.2 ln(1) = 0.5 × 0.2231 + 0.3 × (-0.2877) + 0 = 0.1116 - 0.0863.0.5 ln(0.5/0.4) + 0.3 ln(0.3/0.4) + 0.2 ln(1) = 0.5 × 0.2231 + 0.3 × (-0.2877) + 0 = 0.1116 - 0.0863.Resultالنتيجة
D_KL(P || Q) ≈ 0.0253 nats. Swapping the arguments gives ≈ 0.0258: KL is not symmetric, so the order matters. TensorRT uses the FP32 histogram as P.D_KL(P || Q) ≈ 0.0253 نات (nats). تبديل الوسيطين يعطي ≈ 0.0258: تباعد KL ليس متماثلًا، لذلك الترتيب مهم. تستخدم TensorRT المدرّج التكراري لـFP32 بوصفه P.
How the threshold is chosenكيف تُختار العتبة
- Run the calibration batches and build a fine histogram of each layer's activation values.شغّل دفعات المعايرة وابنِ مدرّجًا تكراريًا دقيقًا لقيم التنشيط في كل طبقة.
- Try many candidate thresholds. For each, form the reference P: the histogram up to the threshold, with every value beyond it counted at the threshold, because that is where clipping will put it. This is the single detached point in the right panel of slide 28.جرّب عتبات مرشحة كثيرة. لكل واحدة كوّن المرجع P: المدرّج التكراري حتى العتبة، مع احتساب كل قيمة تتجاوزها عند العتبة نفسها، لأن القص سيضعها هناك. هذه هي النقطة المنفصلة الوحيدة في اللوحة اليمنى من الشريحة 28.
- Quantize that histogram into the 8-bit levels to get Q, and compute D_KL(P || Q).كمّم ذلك المدرّج التكراري إلى مستويات 8 بت لتحصل على Q، واحسب D_KL(P || Q).
- Keep the threshold with the smallest divergence. Repeat for every layer.احتفظ بالعتبة ذات أصغر تباعد. كرّر ذلك لكل طبقة.
Slide 28 shows the trade on ResNet-152 res4b30. The entropy method sets the threshold near 45 although values reach about 470. The slide's question, what happens with a higher r_max, has the answer it gives: a larger dynamic range means larger steps, so a larger quantization (rounding) loss on the dense part of the histogram, where almost all values live.
تُظهر الشريحة 28 المقايضة على طبقة ResNet-152 res4b30. تضع طريقة الإنتروبيا العتبة قرب 45 مع أن القيم تصل إلى نحو 470. وسؤال الشريحة، ماذا يحدث مع r_max أعلى، جوابه كما تعطيه: مدى ديناميكي أكبر يعني خطوات أكبر، أي خسارة تكميم (تقريب) أكبر في الجزء الكثيف من المدرّج التكراري، حيث تعيش تقريبًا كل القيم.
Every layer gets its own answerلكل طبقة جوابها الخاص
Slide 29 is the best evidence that no fixed rule (say, clip at the 99th percentile) would work. The thresholds read from its four panels:
الشريحة 29 هي أفضل دليل على أنه لا توجد قاعدة ثابتة (مثل القص عند المئين 99) تنجح. العتبات المقروءة من لوحاتها الأربع:
| Layerالطبقة | Largest valueأكبر قيمة | KL thresholdعتبة KL | How much is clippedمقدار ما يُقص |
|---|---|---|---|
| AlexNet pool2AlexNet pool2 | about 140نحو 140 | about 140نحو 140 | None: a spike of real values sits at the top of the rangeلا شيء: قمة من القيم الحقيقية تقع عند أعلى المدى |
| GoogLeNet inception_3a/poolGoogLeNet inception_3a/pool | about 140نحو 140 | about 140نحو 140 | None, for the same reasonلا شيء، للسبب نفسه |
| GoogLeNet inception_5a/5x5GoogLeNet inception_5a/5x5 | about 175نحو 175 | about 137نحو 137 | Mild: only the sparse far tail is cutخفيف: لا يُقص إلا الذيل البعيد المتناثر |
| ResNet-152 res4b8_branch2aResNet-152 res4b8_branch2a | about 210نحو 210 | about 15نحو 15 | Heavy: almost all mass sits near zeroشديد: تقريبًا كل الكتلة الاحتمالية تقع قرب الصفر |
The two pooling layers keep their full range because their histograms rise into a spike at the top: many real values sit there, so cutting them would distort the distribution badly. ResNet's branch layer is the opposite: a tall peak near zero and a tail of rare values, so the method clips about 93% of the range away and loses almost no probability mass.
طبقتا التجميع (pooling) تحتفظان بمداهما الكامل لأن مدرّجهما التكراري يرتفع إلى قمة عند الطرف الأعلى: قيم حقيقية كثيرة تقع هناك، فقصها سيشوّه التوزيع بشدة. طبقة الفرع في ResNet هي العكس: قمة عالية قرب الصفر وذيل من القيم النادرة، لذلك تقص الطريقة نحو 93% من المدى ولا تكاد تفقد شيئًا من الكتلة الاحتمالية.
| Methodالطريقة | What it minimizes or computesما الذي تقلله أو تحسبه | Characterطبيعتها |
|---|---|---|
| Mean of per-sample min/maxمتوسط الحد الأدنى والأعلى لكل عينة | Average the extremes of each calibration sampleنأخذ متوسط القيم القصوى لكل عينة معايرة | Cheap, softens one-off outliers, ignores the shape of the bulkرخيصة، تخفف أثر القيم الشاذة العارضة، وتتجاهل شكل الكتلة الكثيفة |
| Minimize MSEتقليل MSE | E[(X - Q(X))²]E[(X - Q(X))²] | Penalizes large value errors; analytical model for Laplace and Gaussian, or OCTAV for any dataتعاقب أخطاء القيم الكبيرة؛ نموذج تحليلي لتوزيعي لابلاس والغاوسي، أو OCTAV لأي بيانات |
| Minimize KL divergenceتقليل تباعد KL | D_KL(P || Q)D_KL(P || Q) | Compares histogram shapes; TensorRT's default entropy calibration for INT8تقارن أشكال المدرّجات التكرارية؛ وهي معايرة الإنتروبيا الافتراضية في TensorRT لـINT8 |
Quick checkاختبار سريع
Which statement best separates the MSE and KL calibration objectives?أي العبارات تفرّق بين هدفي المعايرة MSE وKL على أفضل وجه؟
Recall
Why do AlexNet pool2 and GoogLeNet inception_3a/pool get no clipping from the entropy method?لماذا لا تقص طريقة الإنتروبيا شيئًا من AlexNet pool2 وGoogLeNet inception_3a/pool؟
Slide 30 puts two int4 grids over the same tensor. On the left, 16 levels are spread from -0.8 to 0.8, about 0.1 apart. The tensor's density is a narrow peak within roughly ±0.15, so only about three levels touch it: large quantization noise exactly where the data is, and most levels spent on low-density regions. On the right, the grid is clipped to about ±0.2. The same 16 levels are now about 0.025 apart and almost all of them cover the peak.
تضع الشريحة 30 شبكتي int4 فوق الموتر نفسه. على اليسار، 16 مستوى موزعة من -0.8 إلى 0.8، المسافة بينها نحو 0.1. كثافة الموتر قمة ضيقة ضمن نحو ±0.15، فلا يلامسها إلا نحو ثلاثة مستويات: ضجيج تكميم كبير تمامًا حيث توجد البيانات، ومعظم المستويات مهدورة على مناطق منخفضة الكثافة. على اليمين، الشبكة مقصوصة إلى نحو ±0.2. المستويات الـ16 نفسها صارت المسافة بينها نحو 0.025، وتقريبًا كلها تغطي القمة.
Find the MSE minimum without assuming a shapeأوجد أصغر MSE دون افتراض شكل للتوزيع
The Laplace table needs the data to be Laplace. OCTAV (Sakr et al., NVIDIA, ICML 2022) drops that assumption. It writes the clipped quantization MSE as a function of the clip scalar s, using the data itself:
يحتاج جدول لابلاس إلى أن تكون البيانات لابلاسية. أما OCTAV (Sakr et al.، NVIDIA، ICML 2022) فيتخلى عن هذا الافتراض. يكتب MSE التكميم المقصوص دالةً في قيمة القص s، مستخدمًا البيانات نفسها:
Newton-Raphson finds a minimum by repeating . Working out the derivatives turns that into one compact update that needs only a few sums over the tensor:
تجد طريقة نيوتن-رافسون القيمة الدنيا بتكرار . وبحساب المشتقات يتحول ذلك إلى تحديث واحد مختصر لا يحتاج إلا إلى بضعة مجاميع على الموتر:
Worked exampleمثال محلول
OCTAV on Laplace data, 4 bitsOCTAV على بيانات لابلاس، 4 بت
Plug in the Laplace expectationsعوّض توقعات لابلاس
For Laplace(0, 1): E[|X| 1(|X| > s)] = (s + 1)e^(-s) and P(|X| > s) = e^(-s). With B = 4, 4^(-4)/3 = 1/768.لتوزيع Laplace(0, 1): E[|X| 1(|X| > s)] = (s + 1)e^(-s) وP(|X| > s) = e^(-s). ومع B = 4 يكون 4^(-4)/3 = 1/768.Iterate from a poor guess, s = 1كرّر بدءًا من تخمين سيئ، s = 1
s₂ = 2 × 0.368 / (0.632/768 + 0.368) ≈ 2.00, then the values below.s₂ = 2 × 0.368 / (0.632/768 + 0.368) ≈ 2.00، ثم القيم في الجدول أدناه.Resultالنتيجة
It settles at s ≈ 5.03 in about six steps: the same 5.03b as Banner's table, reached without solving anything by hand.يستقر عند s ≈ 5.03 في نحو ست خطوات: القيمة 5.03b نفسها في جدول Banner، دون حل أي شيء يدويًا.
| Iteration nالتكرار n | Clip s_nحد القص s_n |
|---|---|
| 11 | 1.001.00 |
| 22 | 2.002.00 |
| 33 | 2.972.97 |
| 44 | 3.883.88 |
| 55 | 4.594.59 |
| 66 | 4.964.96 |
| 77 | 5.035.03 |
Because each step is a handful of reductions over the tensor, OCTAV is cheap enough to rerun every training iteration: it "finds optimal scalars on the fly", as slide 31 puts it. The paper uses only 10 iterations everywhere and reports that the starting guess does not matter.
لأن كل خطوة ليست سوى بضع عمليات اختزال على الموتر، فإن OCTAV رخيص بما يكفي لإعادة تشغيله في كل تكرار تدريب: إنه «يجد القيم المثلى أثناء التشغيل»، كما تقول الشريحة 31. تستخدم الورقة 10 تكرارات فقط في كل مكان، وتذكر أن التخمين الابتدائي لا يهم.
| Networkالشبكة | FP32FP32 | OCTAV int4OCTAV int4 | Changeالتغيّر |
|---|---|---|---|
| ResNet-50ResNet-50 | 76.0776.07 | 75.8475.84 | -0.23-0.23 |
| MobileNet-V2MobileNet-V2 | 71.7171.71 | 70.8870.88 | -0.83-0.83 |
| BERT-LargeBERT-Large | 91.0091.00 | 87.0987.09 | -3.91-3.91 |
The CNNs lose under one point at 4 bits. BERT-Large loses almost four, a reminder that transformers have harder activation outliers, the same networks Wu et al. found hardest for max calibration.
تخسر شبكات CNN أقل من نقطة واحدة عند 4 بت. أما BERT-Large فيخسر نحو أربع نقاط، وهذا تذكير بأن المحوّلات (transformers) فيها قيم شاذة أصعب في التنشيطات، وهي الشبكات نفسها التي وجدها Wu et al. الأصعب مع معايرة max.
Recall
On slide 30, why does max-scaled int4 quantization give large noise even though no value is clipped?في الشريحة 30، لماذا يعطي تكميم int4 المضبوط على القيمة القصوى ضجيجًا كبيرًا مع أنه لا تُقص أي قيمة؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- Weights are fixed after training, so their range is read directly. Activations change with every input, so their range is estimated from data before deployment.الأوزان ثابتة بعد التدريب، لذلك يُقرأ مداها مباشرة. أما التنشيطات فتتغير مع كل مدخل، لذلك يُقدَّر مداها من البيانات قبل النشر.
- Choosing r_max and r_min is choosing the scale S, and the scale sets the step size of every quantized value in that tensor.اختيار r_max وr_min هو نفسه اختيار المقياس S، والمقياس يحدد حجم الخطوة لكل قيمة مكمّمة في ذلك الموتر.
- Type 1 (Jacob et al.): during training, smooth the observed min and max with an EMA, r̂(t) = α r(t) + (1 - α) r̂(t-1). With α on the new value, α must be small (PyTorch uses 0.01).النوع الأول (Jacob et al.): أثناء التدريب نُنعّم الحد الأدنى والأعلى المرصودين بمتوسط متحرك أُسّي EMA، أي r̂(t) = α r(t) + (1 - α) r̂(t-1). وبما أن α تضرب القيمة الجديدة، يجب أن تكون α صغيرة (PyTorch تستخدم 0.01).
- Type 2: run a few calibration batches through the trained FP32 model. Options: mean of per-sample min/max, minimize MSE, minimize KL divergence.النوع الثاني: نمرّر بضع دفعات معايرة عبر نموذج FP32 المدرَّب. الخيارات: متوسط الحد الأدنى والأعلى لكل عينة، أو تقليل MSE، أو تقليل تباعد KL.
- Total error = clipping error (values beyond the clip) + rounding error (Δ²/12 with Δ = 2|r|max / 2^M). Widening the range lowers the first and raises the second.الخطأ الكلي = خطأ القص (للقيم التي تتجاوز حد القص) + خطأ التقريب (Δ²/12 حيث Δ = 2|r|max / 2^M). توسيع المدى يقلل الأول ويزيد الثاني.
- For Laplace(0, b) inputs the MSE-optimal clip is 2.83b, 3.89b, 5.03b at 2, 3, 4 bits. Example: b = 0.2 at 4 bits gives 1.006.لمدخلات Laplace(0, b) يكون حد القص الأمثل وفق MSE هو 2.83b و3.89b و5.03b عند 2 و3 و4 بت. مثال: b = 0.2 عند 4 بت يعطي 1.006.
- KL calibration (TensorRT entropy method) picks the threshold whose quantized histogram loses the least information, D_KL(P || Q) = Σ P log(P/Q). It chooses a different clip for every layer.معايرة KL (طريقة الإنتروبيا في TensorRT) تختار العتبة التي يفقد عندها المدرّج التكراري المكمَّم أقل قدر من المعلومات، D_KL(P || Q) = Σ P log(P/Q). وهي تختار حد قص مختلفًا لكل طبقة.
- OCTAV solves the MSE problem with Newton-Raphson in a few iterations, on the fly. Int4 results: ResNet-50 76.07 to 75.84, MobileNet-V2 71.71 to 70.88, BERT-Large 91.00 to 87.09.يحل OCTAV مسألة MSE بطريقة نيوتن-رافسون في بضع تكرارات وأثناء التشغيل. نتائج int4: ResNet-50 من 76.07 إلى 75.84، وMobileNet-V2 من 71.71 إلى 70.88، وBERT-Large من 91.00 إلى 87.09.
Sourcesالمصادر
- Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference (Jacob et al.)PaperCVPR 2018, arXiv:1712.05877Weights use their own min and max; activation ranges are aggregated with an EMA whose smoothing parameter is close to 1, and activation quantization is disabled for the first 50 thousand to 2 million steps.تستخدم الأوزان حدها الأدنى والأعلى الخاصين بها؛ وتُجمع مديات التنشيطات بمتوسط EMA معامل تنعيمه قريب من 1، ويُعطَّل تكميم التنشيطات في أول 50 ألف إلى 2 مليون خطوة.(opens in a new tab)(يفتح في تبويب جديد)
- Post training 4-bit quantization of convolutional networks for rapid-deployment (Banner, Nahshan, Soudry)PaperNeurIPS 2019Eq. 5 and 6: the Laplace MSE model, optimal clips 2.83b, 3.89b, 5.03b for 2, 3, 4 bits, and b estimated as E|X - E(X)|.المعادلتان 5 و6: نموذج MSE لتوزيع لابلاس، وحدود القص المثلى 2.83b و3.89b و5.03b عند 2 و3 و4 بت، وتقدير b بالصيغة E|X - E(X)|.(opens in a new tab)(يفتح في تبويب جديد)
- Optimal Clipping and Magnitude-aware Differentiation for Improved Quantization-aware Training (Sakr et al.)PaperICML 2022, arXiv:2206.06501OCTAV: Theorem 3.1 gives the Newton-Raphson recursion for the MSE-optimal clip; Section 3 discusses convexity and 10-iteration convergence; the experiments note rare non-convex layers.OCTAV: تعطي المبرهنة 3.1 علاقة نيوتن-رافسون التكرارية لحد القص الأمثل وفق MSE؛ ويناقش القسم 3 التحدّب والتقارب في 10 تكرارات؛ وتشير التجارب إلى طبقات نادرة غير محدّبة.(opens in a new tab)(يفتح في تبويب جديد)
- Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation (Wu et al.)PaperNVIDIA, arXiv:2004.09602Table 5 and the calibration section: max, entropy (KL, TensorRT's default) and percentile calibration compared; max suffers on networks with outliers, 99.9% clips too aggressively.الجدول 5 وقسم المعايرة: مقارنة بين معايرة max والإنتروبيا (KL، الافتراضية في TensorRT) والمئين؛ معايرة max تتعثر في الشبكات ذات القيم الشاذة، والمئين 99.9% يقص بشدة زائدة.(opens in a new tab)(يفتح في تبويب جديد)
- MovingAverageMinMaxObserverDocsPyTorch documentationEMA of min and max with the constant on the new observation, averaging_constant = 0.01 by default.متوسط EMA للحد الأدنى والأعلى يضع الثابت على الرصد الجديد، مع averaging_constant = 0.01 افتراضيًا.(opens in a new tab)(يفتح في تبويب جديد)
- TensorRT Python API: Int8 CalibratorDocsNVIDIA TensorRT documentationLists the ENTROPY_CALIBRATION, ENTROPY_CALIBRATION_2 and MINMAX_CALIBRATION algorithms; the implicit calibration API is deprecated since TensorRT 10.1 in favor of explicit quantization.تسرد خوارزميات ENTROPY_CALIBRATION وENTROPY_CALIBRATION_2 وMINMAX_CALIBRATION؛ وواجهة المعايرة الضمنية مُهملة (deprecated) منذ TensorRT 10.1 لصالح التكميم الصريح.(opens in a new tab)(يفتح في تبويب جديد)
Part 04: AdaRound and what post-training INT8 achievesAdaRound وما يحققه INT8 بعد التدريب
Rounding each weight to nearest is not optimal for the layer output, so AdaRound learns whether each weight rounds up or down to reconstruct activations. The section closes the PTQ story with the summary of zero point, granularity, range and rounding choices and real INT8 PTQ results, where small models like MobileNet lose too much.تقريب كل وزن إلى الأقرب ليس الأمثل لمخرج الطبقة، لذا يتعلم AdaRound ما إذا كان كل وزن يُقرَّب للأعلى أو للأسفل لإعادة بناء التنشيطات. ويختتم القسم قصة PTQ بملخص خيارات نقطة الصفر والدقة (granularity) والمدى والتقريب، ونتائج INT8 PTQ حقيقية، حيث تفقد النماذج الصغيرة مثل MobileNet الكثير من الدقة.
4 concepts4 مفاهيم, ، slides 32-38الشرائح 32-38
Why this part mattersلماذا يهمّ هذا الجزء
The last two parts chose the grid: how fine the scales are and where the range is clipped. One decision is left before a weight becomes an integer. It sits between two grid points, and something has to decide which one it lands on. Everyone rounds to nearest without thinking. This part shows why that habit is not optimal, how AdaRound learns a better choice, and then closes the post-training story with real INT8 numbers.
For the COE 592 midterm, expect three kinds of questions: explain why nearest rounding can be beaten, write and label the AdaRound objective, and read the INT8 results table to say which models suffer and what to do next. For edge deployment, this is the part that tells you when a push-button INT8 conversion is enough and when it is not.
اختار الجزءان السابقان الشبكة (grid): مدى دقة المقاييس، وأين يُقصّ المدى. بقي قرار واحد قبل أن يصبح الوزن عددًا صحيحًا. فالوزن يقع بين نقطتين من الشبكة، ولا بد من شيء يقرر على أيهما يستقر. الجميع يقرّب إلى الأقرب دون تفكير. يبيّن هذا الجزء لماذا لا تكون هذه العادة هي الأمثل، وكيف يتعلم AdaRound اختيارًا أفضل، ثم يختم قصة التكميم بعد التدريب بأرقام INT8 حقيقية.
في اختبار منتصف الفصل لمقرر COE 592، توقّع ثلاثة أنواع من الأسئلة: اشرح لماذا يمكن التفوق على التقريب إلى الأقرب، واكتب هدف AdaRound وسمِّ حدوده، واقرأ جدول نتائج INT8 لتقول أي النماذج تتضرر وما الخطوة التالية. أما في النشر على الأجهزة الطرفية (edge)، فهذا هو الجزء الذي يخبرك متى يكفي تحويل INT8 بضغطة زر ومتى لا يكفي.
By the end you canفي نهاية هذا الجزء ستستطيع
- Explain why rounding every weight to its nearest grid value is not the best rounding for the layer output.اشرح لماذا لا يكون تقريب كل وزن إلى أقرب قيمة في الشبكة هو أفضل تقريب لمخرج الطبقة.
- Write the AdaRound objective from memory and name every term: W, x, W̃, V, h(), λ and f_reg.اكتب هدف AdaRound من الذاكرة وسمِّ كل حد فيه: W وx وW̃ وV وh() وλ وf_reg.
- Show on a two-weight example how choosing floor or ceil per weight lowers the output error.بيّن على مثال بوزنين كيف يقلل اختيار الأرضية (floor) أو السقف (ceil) لكل وزن خطأ المخرج.
- Say what the rectified sigmoid and the regularizer f_reg do, and why the result is still post-training quantization.اذكر ما تفعله دالة rectified sigmoid والمنظِّم f_reg، ولماذا تظل النتيجة تكميمًا بعد التدريب.
- Fill the storage and computation table for FP, K-means and linear quantization, and list the four PTQ knobs.املأ جدول التخزين والحساب لكل من FP وK-means والتكميم الخطي، واذكر مفاتيح PTQ الأربعة.
- Read the INT8 PTQ table, name the models that lose most, explain why, and say what fixes it.اقرأ جدول نتائج INT8 PTQ، وسمِّ النماذج التي تخسر أكثر، واشرح السبب، واذكر ما يعالج ذلك.
Why rounding each weight to nearest is not optimalلماذا لا يكون تقريب كل وزن إلى أقرب قيمة هو الأمثل
Take a neuron with two weights, both exactly 0.5, on a grid whose only levels are 0 and 1. Feed it the input x = [1, 1]. The true output is 0.5 + 0.5 = 1. Round each weight on its own and both go the same way, up to 1, so the quantized output is 2. Each weight made the smallest possible mistake, yet the output is off by a full unit. Round one up and one down and the output is exactly 1 again.
خذ عصبونًا له وزنان، كل منهما يساوي 0.5 تمامًا، على شبكة ليس فيها إلا المستويان 0 و1. أدخل إليه x = [1, 1]. المخرج الحقيقي هو 0.5 + 0.5 = 1. قرّب كل وزن بمفرده فيذهب الاثنان في الاتجاه نفسه، إلى أعلى نحو 1، فيصبح المخرج المكمَّم 2. ارتكب كل وزن أصغر خطأ ممكن، ومع ذلك ينحرف المخرج بوحدة كاملة. قرّب أحدهما إلى أعلى والآخر إلى أسفل فيعود المخرج 1 تمامًا.
The third PTQ question: which way to roundسؤال PTQ الثالث: في أي اتجاه نقرّب
Post-training quantization (PTQ) asks how to get the best (S, Z) for a trained model, and the lecture splits that into three topics: granularity, dynamic range clipping, and rounding. Once S and Z are fixed, every weight w (measured in grid steps) lies between its floor ⌊w⌋ and its ceil ⌈w⌉. Rounding to nearest picks whichever is closer. That is the right choice if you only care about each weight on its own: it gives the smallest error per weight, at most half a step.
يسأل post-training quantization كيف نحصل على أفضل (S, Z) لنموذج مدرَّب، وتقسم المحاضرة ذلك إلى ثلاثة مواضيع: الدقة الحبيبية (granularity)، وقص المدى الديناميكي (dynamic range clipping)، والتقريب (rounding). بعد تثبيت S وZ، يقع كل وزن w (مقيسًا بعدد خطوات الشبكة) بين أرضيته ⌊w⌋ وسقفه ⌈w⌉. يختار rounding to nearest أيهما أقرب. وهذا هو الاختيار الصحيح إذا كان كل ما يهمك هو كل وزن بمفرده: فهو يعطي أصغر خطأ لكل وزن، نصف خطوة على الأكثر.
But the network never uses a weight on its own. A layer computes Wx, and every output is a sum of many weights times many inputs. The errors Δw = w̃ − w of the weights in one row add together inside that sum. If they all lean the same way, they pile up. If some lean up and others down, they cancel. Nearest rounding decides each weight blind to its neighbours, so it cannot arrange the cancellation. The slide states it in one line: weights are correlated with each other, so the best rounding for each weight is not the best rounding for the whole tensor.
لكن الشبكة لا تستخدم وزنًا بمفرده أبدًا. الطبقة تحسب Wx، وكل مخرج هو مجموع لأوزان كثيرة مضروبة في مُدخلات كثيرة. أخطاء الأوزان Δw = w̃ − w في صف واحد تُجمع معًا داخل هذا المجموع. إذا مالت كلها في الاتجاه نفسه تراكمت، وإذا مال بعضها إلى أعلى وبعضها إلى أسفل ألغى بعضها بعضًا. التقريب إلى الأقرب يقرر كل وزن دون أن يرى جيرانه، لذلك لا يستطيع ترتيب هذا الإلغاء. والشريحة تقولها في سطر واحد: الأوزان مترابطة فيما بينها، لذلك فإن أفضل تقريب لكل وزن ليس أفضل تقريب للموتر كله.
Why the loss sees pairs of weightsلماذا ترى دالة الخسارة الأوزان أزواجًا
Nagel et al. make this precise with a second-order Taylor expansion of the task loss around the trained weights. For a small weight perturbation Δw:
يجعل Nagel et al. هذا دقيقًا باستخدام مفكوك تايلور (Taylor expansion) من الدرجة الثانية لخسارة المهمة حول الأوزان المدرَّبة. لاضطراب صغير في الأوزان Δw:
A trained network sits near a minimum, so g ≈ 0 and the Hessian term dominates. If H were diagonal, the cost would be a sum of independent terms H_ii Δw_i², and making each |Δw_i| as small as possible (nearest rounding) would be optimal. The off-diagonal entries H_ij Δw_i Δw_j are exactly the interactions between weights, and nearest rounding ignores them. The paper then shows that, layer by layer and under mild assumptions, minimizing this cost becomes minimizing the mean squared error of the layer's pre-activations, E[(ΔW x)²]. That is why the slide says the optimal rounding is the one that reconstructs the original activation best.
الشبكة المدرَّبة تقع قرب نقطة صغرى، لذلك g ≈ 0 ويهيمن حد مصفوفة هيسه (Hessian). لو كانت H قطرية، لكانت الكلفة مجموع حدود مستقلة H_ii Δw_i²، ولكان جعل كل |Δw_i| أصغر ما يمكن (أي التقريب إلى الأقرب) هو الأمثل. أما العناصر خارج القطر H_ij Δw_i Δw_j فهي بالضبط التفاعلات بين الأوزان، والتقريب إلى الأقرب يتجاهلها. ثم تبيّن الورقة أنه، طبقة بعد طبقة وتحت افتراضات معتدلة، يصبح تقليل هذه الكلفة هو تقليل متوسط مربع الخطأ لقيم ما قبل التنشيط (pre-activations) في الطبقة، أي E[(ΔW x)²]. لهذا تقول الشريحة إن التقريب الأمثل هو الذي يعيد بناء التنشيط الأصلي بأفضل شكل.
Back to the slide's tensorعودة إلى موتر الشريحة
Slide 33 rounds [0.3, 0.5, 0.7, 0.2] to nearest and gets [0, 1, 1, 0]. AdaRound might instead return [0, 0, 1, 0]: the 0.5 goes down. Whether that is better depends on the inputs the layer actually sees, which is the whole point. In the explorer below the layer sees two inputs, x1 = [1, 0, 1, 1] and x2 = [−1, 1, 1, −1]. Both roundings have the same weight error (0.47), but nearest gives an output error of 1.73 and the AdaRound result gives 0.13, the best of all 16 possible roundings.
تقرّب الشريحة 33 المتجه [0.3, 0.5, 0.7, 0.2] إلى الأقرب فتحصل على [0, 1, 1, 0]. أما AdaRound فقد يعيد بدلًا من ذلك [0, 0, 1, 0]: القيمة 0.5 تنزل إلى أسفل. وكون ذلك أفضل أم لا يعتمد على المُدخلات التي تراها الطبقة فعلًا، وهذا هو بيت القصيد. في المستكشف أدناه ترى الطبقة مُدخلين، x1 = [1, 0, 1, 1] وx2 = [−1, 1, 1, −1]. للتقريبين خطأ الأوزان نفسه (0.47)، لكن التقريب إلى الأقرب يعطي خطأ مخرج قدره 1.73 بينما تعطي نتيجة AdaRound القيمة 0.13، وهي الأفضل بين كل التقريبات الممكنة وعددها 16.
Recall
Two weights are both 0.4 on an integer grid and the input is x = [1, 1]. Compare nearest rounding with the best rounding.وزنان قيمة كل منهما 0.4 على شبكة أعداد صحيحة والمُدخل x = [1, 1]. قارن التقريب إلى الأقرب بأفضل تقريب.
Quick checkاختبار سريع
Why can rounding every weight to its nearest grid value be suboptimal?لماذا قد لا يكون تقريب كل وزن إلى أقرب قيمة في الشبكة هو الأمثل؟
Rounding is a yes or no question per weight: up or down. With millions of weights there are 2^n answers, far too many to try. AdaRound turns that discrete search into a smooth optimization that gradient descent can solve in minutes.
التقريب سؤال إجابته نعم أو لا لكل وزن: إلى أعلى أم إلى أسفل. ومع ملايين الأوزان توجد 2^n إجابة، وهذا أكثر بكثير مما يمكن تجربته. يحوّل AdaRound هذا البحث المتقطع إلى تحسين سلس يستطيع الانحدار التدريجي (gradient descent) حله في دقائق.
Step 1: restrict the choice to floor or ceilالخطوة 1: حصر الاختيار في الأرضية أو السقف
Instead of ⌊w⌉ (round to nearest), AdaRound chooses from {⌊w⌋, ⌈w⌉}, the two grid points around the weight. It writes the choice with an offset δ:
بدلًا من ⌊w⌉ (التقريب إلى الأقرب)، يختار AdaRound من {⌊w⌋, ⌈w⌉}، أي نقطتي الشبكة المحيطتين بالوزن. ويكتب هذا الاختيار بإزاحة δ:
Take w = 2.3. The floor is 2. With δ = 0.2, ⌊2.2⌉ = 2; with δ = 0.9, ⌊2.9⌉ = 3. So δ is a dial that selects floor or ceil, and it never moves the weight more than one step. Nearest rounding is the special case δ = w − ⌊w⌋, the weight's own fractional part (here 0.3, giving ⌊2.3⌉ = 2); AdaRound is free to pick any δ instead.
خذ w = 2.3. الأرضية هي 2. مع δ = 0.2 نحصل على ⌊2.2⌉ = 2، ومع δ = 0.9 نحصل على ⌊2.9⌉ = 3. إذن δ مقبض يختار الأرضية أو السقف، ولا يحرّك الوزن أبدًا أكثر من خطوة واحدة. التقريب إلى الأقرب هو الحالة الخاصة δ = w − ⌊w⌋، أي الجزء الكسري من الوزن نفسه (هنا 0.3، مما يعطي ⌊2.3⌉ = 2)، أما AdaRound فحرّ في اختيار أي δ بدلًا من ذلك.
Step 2: pick the δ values that reconstruct the outputالخطوة 2: اختيار قيم δ التي تعيد بناء المخرج
The dials are learned. The loss is the reconstruction error of the layer output, plus a regularizer:
هذه المقابض تُتعلَّم. دالة الخسارة هي خطأ إعادة بناء مخرج الطبقة، مضافًا إليه منظِّم (regularizer):
Every term of the AdaRound objectiveكل حد في هدف AdaRound
- Wx
- The original layer output (pre-activation) with full-precision weights. This is the target.مخرج الطبقة الأصلي (قبل التنشيط، pre-activation) بأوزان كاملة الدقة. وهذا هو الهدف المطلوب.
- W̃x
- The same layer with quantized weights. Each entry of W̃ is either the floor or the ceil of the matching weight.الطبقة نفسها بأوزان مكمَّمة. كل عنصر في W̃ إما أرضية الوزن المقابل له أو سقفه.
- x
- The input to this layer, collected by running a few unlabeled calibration samples through the network.مُدخل هذه الطبقة، ويُجمع بتمرير عدد قليل من عينات المعايرة غير المعنونة عبر الشبكة.
- V
- A continuous, learnable tensor with the same shape as W. One entry per weight decides that weight's direction.موتر مستمر قابل للتعلّم له شكل W نفسه. لكل وزن عنصر واحد يقرر اتجاه تقريب ذلك الوزن.
- h(V)
- Maps each V entry into [0, 1] (a rectified sigmoid). It replaces the hard δ so gradients can flow.تنقل كل عنصر من V إلى [0, 1] (دالة rectified sigmoid). وتحل محل الإزاحة الحادة δ حتى تستطيع التدرجات أن تمر.
- ||·||²_F
- Squared Frobenius norm: the sum of squared output errors over every output unit and every calibration sample.مربع معيار فروبينيوس (Frobenius): مجموع مربعات أخطاء المخرج على كل وحدة مخرج وكل عينة معايرة.
- λ f_reg(V)
- The regularizer, weighted by λ. It is zero only when each h(V) is exactly 0 or 1, so it forces a real floor or ceil decision.المنظِّم (regularizer) مضروبًا في الوزن λ. قيمته صفر فقط عندما تكون كل h(V) مساوية 0 أو 1 تمامًا، لذلك يفرض قرارًا حقيقيًا بالأرضية أو السقف.
Step 3: make the offset smooth, then force it binaryالخطوة 3: اجعل الإزاحة سلسة، ثم أجبرها على أن تكون ثنائية
The hard round inside W̃ has zero gradient almost everywhere, so AdaRound replaces δ by h(V), a smooth function of a free variable V. The paper uses the Rectified sigmoid h(V) from Louizos et al.:
التقريب الحاد داخل W̃ تدرّجه صفر في كل مكان تقريبًا، لذلك يستبدل AdaRound الإزاحة δ بالدالة h(V)، وهي دالة سلسة لمتغير حر V. تستخدم الورقة دالة rectified sigmoid من Louizos et al.:
Stretching then clipping matters. A plain sigmoid only approaches 0 and 1, and its gradient vanishes on the way. The rectified version hits 0 and 1 exactly with a gradient that is still healthy just before it gets there. During training, though, nothing stops h(V) from settling at 0.5, a half-step weight that no integer grid can store. The regularizer fixes that:
المد ثم القص أمر مهم. دالة sigmoid العادية تقترب فقط من 0 و1، ويتلاشى تدرّجها في الطريق. أما النسخة المقوَّمة (rectified) فتبلغ 0 و1 تمامًا بتدرّج لا يزال سليمًا قبل وصولها مباشرة. لكن أثناء التدريب لا شيء يمنع h(V) من الاستقرار عند 0.5، أي وزن عند نصف خطوة لا تستطيع أي شبكة أعداد صحيحة تخزينه. والمنظِّم يعالج ذلك:
Worked exampleمثال محلول
How f_reg scores one weightكيف يقيّم f_reg وزنًا واحدًا
Undecided weightوزن غير محسوم
With h = 0.5, |2(0.5) − 1| = 0, so the penalty is 1 − 0 = 1, the maximum, whatever β is.مع h = 0.5 يكون |2(0.5) − 1| = 0، لذلك تكون العقوبة 1 − 0 = 1، وهي القيمة القصوى، أيًّا كانت β.Nearly decided, early in trainingشبه محسوم، في بداية التدريب
With h = 0.9 and β = 20: |0.8|^20 ≈ 0.012, penalty ≈ 0.99. Almost the same as undecided, so the regularizer barely acts and the reconstruction term steers.مع h = 0.9 وβ = 20: |0.8|^20 ≈ 0.012، والعقوبة ≈ 0.99. أي تقريبًا مثل الوزن غير المحسوم، لذلك لا يكاد المنظِّم يعمل، ويتولى حد إعادة البناء التوجيه.Nearly decided, late in trainingشبه محسوم، في نهاية التدريب
With h = 0.9 and β = 2: 0.8² = 0.64, penalty 0.36. Now there is a clear slope toward h = 1.مع h = 0.9 وβ = 2: 0.8² = 0.64، والعقوبة 0.36. الآن يوجد ميل واضح نحو h = 1.Resultالنتيجة
At h = 1 or h = 0 the penalty is 0. Annealing β lets the weights explore first and then commits each one to exactly floor or ceil, after which the outer round has nothing left to do.عند h = 1 أو h = 0 تكون العقوبة 0. تخفيض β تدريجيًا (annealing) يسمح للأوزان بالاستكشاف أولًا، ثم يُلزم كل وزن بالأرضية أو السقف تمامًا، وبعدها لا يبقى للتقريب الخارجي ما يفعله.
The two-weight exercise, solved the AdaRound wayتمرين الوزنين، محلولًا بطريقة AdaRound
Worked exampleمثال محلول
Weights [0.5, 0.5], input x = [1, 1], grid {0, 1}الأوزان [0.5, 0.5]، والمُدخل x = [1, 1]، والشبكة {0, 1}
Targetالهدف
Wx = 0.5 + 0.5 = 1.Wx = 0.5 + 0.5 = 1.Nearest roundingالتقريب إلى الأقرب
Rounding half up, as slide 33 does with 0.5, gives [1, 1], so W̃x = 2 and the squared error is (1 − 2)² = 1. Rounding half to even would give [0, 0] and the same error, 1.التقريب بجعل النصف إلى أعلى، كما تفعل الشريحة 33 مع 0.5، يعطي [1, 1]، لذلك W̃x = 2 ومربع الخطأ (1 − 2)² = 1. أما التقريب بجعل النصف إلى العدد الزوجي فيعطي [0, 0] والخطأ نفسه، 1.All four candidatesالمرشحون الأربعة كلهم
The floor of each weight is 0, so W̃ = h(V) once h is binary. The options are [0, 0], [1, 0], [0, 1], [1, 1] with outputs 0, 1, 1, 2 and squared errors 1, 0, 0, 1.أرضية كل وزن هي 0، لذلك W̃ = h(V) بمجرد أن تصبح h ثنائية. الخيارات هي [0, 0] و[1, 0] و[0, 1] و[1, 1]، ومخرجاتها 0, 1, 1, 2، ومربعات أخطائها 1, 0, 0, 1.What AdaRound learnsما يتعلمه AdaRound
Gradient descent on the reconstruction term pulls h(V1) + h(V2) toward 1, and f_reg then pushes the two values apart to 1 and 0.الانحدار التدريجي على حد إعادة البناء يسحب h(V1) + h(V2) نحو 1، ثم يدفع f_reg القيمتين بعيدًا عن بعضهما إلى 1 و0.Resultالنتيجة
AdaRound picks [1, 0] (or [0, 1]), output 1, error 0, against error 1 for nearest.يختار AdaRound المتجه [1, 0] (أو [0, 1])، فيكون المخرج 1 والخطأ 0، مقابل خطأ 1 للتقريب إلى الأقرب.
Why it still counts as post-trainingلماذا يظل يُعدّ تكميمًا بعد التدريب
- Weights only. Activations are quantized with the usual range methods; AdaRound only decides the rounding of weights, and it does not change the scale S, which is fixed beforehand.الأوزان فقط. تُكمَّم التنشيطات بطرق المدى المعتادة، وAdaRound يقرر فقط تقريب الأوزان، ولا يغيّر المقياس S الذي يُثبَّت مسبقًا.
- Layer by layer. Each layer is optimized on its own local reconstruction loss, so there is no end-to-end training and no task loss.طبقة بعد طبقة. كل طبقة تُحسَّن على خسارة إعادة البناء المحلية الخاصة بها، لذلك لا يوجد تدريب من الطرف إلى الطرف (end-to-end) ولا خسارة مهمة.
- Little data, no labels. The paper uses 1024 unlabeled ImageNet images and 10k Adam iterations per layer; ResNet-18 takes about 10 minutes. That is the slide's "short-term tuning, (almost) post-training quantization".بيانات قليلة بلا تسميات. تستخدم الورقة 1024 صورة غير معنونة من ImageNet و10k تكرار من Adam لكل طبقة، ويستغرق ResNet-18 نحو 10 دقائق. وهذا ما تسميه الشريحة "short-term tuning, (almost) post-training quantization"، أي ضبط قصير المدى، وتكميم بعد التدريب (تقريبًا).
- It pays off at low bit widths. With 4-bit weights, ResNet-18 goes from 23.99% with nearest rounding to 68.71% with AdaRound (FP32 69.68%), and ResNet-50 from 35.60% to 75.23% (FP32 76.07%).يؤتي ثماره عند عروض البتات المنخفضة. مع أوزان 4 بت، يرتفع ResNet-18 من 23.99% بالتقريب إلى الأقرب إلى 68.71% مع AdaRound (ودقة FP32 هي 69.68%)، ويرتفع ResNet-50 من 35.60% إلى 75.23% (ودقة FP32 هي 76.07%).
Recall
Name every term in argmin_V ||Wx − ⌊⌊W⌋ + h(V)⌉x||²_F + λ f_reg(V).سمِّ كل حد في argmin_V ||Wx − ⌊⌊W⌋ + h(V)⌉x||²_F + λ f_reg(V).
Recall
Why does AdaRound need f_reg at all, if the reconstruction loss already prefers good roundings?لماذا يحتاج AdaRound إلى f_reg أصلًا، إذا كانت خسارة إعادة البناء تفضّل التقريبات الجيدة بالفعل؟
Quick checkاختبار سريع
What does the regularizer f_reg(V) do in AdaRound?ما الذي يفعله المنظِّم f_reg(V) في AdaRound؟
Take the running 4×4 matrix from Lecture 5.1, with entries such as 2.09, −0.98 and 1.48. K-means quantization stores 2.09 as index 3 and looks up 2.00 in a floating-point codebook. Linear quantization stores it as the integer q = 1 and recovers (1 − (−1)) × 1.07 = 2.14. Both store small integers. Only one of them can also compute with them.
خذ المصفوفة 4×4 المرافقة من المحاضرة 5.1، بعناصر مثل 2.09 و−0.98 و1.48. تكميم K-means يخزّن 2.09 على أنه الفهرس 3 ويبحث عن 2.00 في دفتر رموز (codebook) بالفاصلة العائمة. أما التكميم الخطي فيخزّنه كعدد صحيح q = 1 ويستعيد (1 − (−1)) × 1.07 = 2.14. كلاهما يخزّن أعدادًا صحيحة صغيرة، لكن واحدًا منهما فقط يستطيع أيضًا أن يحسب بها.
| Approachالطريقة | Storageالتخزين | Computationالحساب | What it savesما الذي توفره |
|---|---|---|---|
| Floating-point baselineخط الأساس بالفاصلة العائمة | Floating-point weightsأوزان بالفاصلة العائمة | Floating-point arithmeticحساب بالفاصلة العائمة | Nothing savedلا توفير |
| K-means-basedK-means | Integer indexes plus a floating-point codebookفهارس صحيحة مع دفتر رموز (codebook) بالفاصلة العائمة | Floating-point arithmeticحساب بالفاصلة العائمة | Storage onlyالتخزين فقط |
| Linearخطي | Integer weights (plus S and Z)أوزان صحيحة (مع S وZ) | Integer arithmeticحساب بالأعداد الصحيحة | Storage and computeالتخزين والحساب |
K-means indexes are only pointers. Before any multiply-accumulate the hardware must look up the real floating-point value, so the arithmetic stays floating point and the saving is memory and bandwidth. Linear quantization has an affine map r = S(q − Z), which lets a whole matrix product run on integers with the scale applied once at the end. That is why the rest of this lecture tunes linear quantization.
فهارس K-means مجرد مؤشرات. قبل أي عملية ضرب وتجميع (multiply-accumulate) يجب على العتاد أن يبحث عن القيمة الحقيقية بالفاصلة العائمة، لذلك يبقى الحساب بالفاصلة العائمة، ويكون التوفير في الذاكرة وعرض النطاق (bandwidth). أما التكميم الخطي فله تحويل أفيني (affine) r = S(q − Z)، يسمح بإجراء ضرب مصفوفة كامل بالأعداد الصحيحة مع تطبيق المقياس مرة واحدة في النهاية. ولهذا تضبط بقية هذه المحاضرة التكميم الخطي.
Every post-training choice in one listكل اختيارات ما بعد التدريب في قائمة واحدة
With this part, all four knobs of linear post-training quantization are on the table. Each answers a different question about the same map r = S(q − Z):
مع هذا الجزء، أصبحت مفاتيح التكميم الخطي بعد التدريب الأربعة كلها مطروحة. كل منها يجيب عن سؤال مختلف حول التحويل نفسه r = S(q − Z):
| Knobالمفتاح | Optionsالخيارات | Question it answersالسؤال الذي يجيب عنه | Covered inموضع الشرح |
|---|---|---|---|
| Zero pointنقطة الصفر | Asymmetric, symmetricغير متماثل، متماثل | Where real 0 sits on the integer gridأين يقع الصفر الحقيقي على شبكة الأعداد الصحيحة | Lecture 5.2المحاضرة 5.2 |
| Scaling granularityالدقة الحبيبية للمقياس (granularity) | Per-tensor, per-channel, groupلكل موتر، لكل قناة، لكل مجموعة | How many values share one scale Sكم قيمة تتشارك مقياسًا واحدًا S | Parts 1 and 2الجزءان 1 و2 |
| Range clippingقص المدى | EMA, minimize KL, minimize MSEEMA، تقليل KL، تقليل MSE | Which r_min and r_max set Sأي r_min وr_max يحددان S | Part 3الجزء 3 |
| Roundingالتقريب | Nearest, AdaRoundإلى الأقرب، AdaRound | Which grid point each weight lands onأي نقطة في الشبكة يستقر عليها كل وزن | This partهذا الجزء |
The first three shape the grid: Symmetric quantization or asymmetric for Z, Quantization granularity for how many values share S, and Dynamic range clipping for what range S must cover. Rounding is the last step: it places each weight on the grid the first three built.
المفاتيح الثلاثة الأولى تشكّل الشبكة: symmetric quantization أو غير المتماثل لاختيار Z، وquantization granularity لعدد القيم التي تتشارك S، وdynamic range clipping للمدى الذي يجب أن يغطيه S. والتقريب هو الخطوة الأخيرة: فهو يضع كل وزن على الشبكة التي بنتها المفاتيح الثلاثة الأولى.
Recall
Fill the table: storage and computation for FP, K-means and linear quantization.املأ الجدول: التخزين والحساب لكل من FP وK-means والتكميم الخطي.
Convert ResNet-50 to INT8 with no retraining, symmetric per-channel weights and EMA-calibrated activations, and it loses 0.6% of top-1 accuracy. Apply the exact same recipe to MobileNetV1 and it loses 11.8%. Same bit width, same recipe, wildly different results. This concept is about why.
حوّل ResNet-50 إلى INT8 دون إعادة تدريب، بأوزان متماثلة لكل قناة وتنشيطات معايرة بـEMA، فيخسر 0.6% من دقة top-1. طبّق الوصفة نفسها تمامًا على MobileNetV1 فيخسر 11.8%. عرض البتات نفسه، والوصفة نفسها، ونتائج مختلفة اختلافًا هائلًا. هذا المفهوم يدور حول السبب.
Reading the tableقراءة الجدول
Slide 37 compares two post-training INT8 recipes. In the first, activations are symmetric per-tensor with the range chosen by minimizing KL divergence (the TensorRT entropy calibration from part 3), and weights are symmetric Per-tensor quantization. In the second, activations are asymmetric per-tensor with the range tracked by an Exponential moving average (EMA), and weights are symmetric Per-channel quantization. The numbers are the change in top-1 accuracy against the floating-point model.
تقارن الشريحة 37 بين وصفتين لتكميم INT8 بعد التدريب. في الأولى، التنشيطات متماثلة لكل موتر (per-tensor) مع اختيار المدى بتقليل KL divergence (معايرة الإنتروبيا في TensorRT من الجزء 3)، والأوزان متماثلة بأسلوب per-tensor quantization. في الثانية، التنشيطات غير متماثلة لكل موتر مع تتبع المدى بـexponential moving average، والأوزان متماثلة بأسلوب per-channel quantization. الأرقام هي التغير في دقة top-1 مقارنة بنموذج الفاصلة العائمة.
| Networkالشبكة | Act: sym per-tensor, KL. W: sym per-tensorالتنشيطات: متماثلة لكل موتر، KL. الأوزان: متماثلة لكل موتر | Act: asym per-tensor, EMA. W: sym per-channelالتنشيطات: غير متماثلة لكل موتر، EMA. الأوزان: متماثلة لكل قناة |
|---|---|---|
| GoogleNetGoogleNet | −0.45%−0.45% | 0%0% |
| ResNet-50ResNet-50 | −0.13%−0.13% | −0.6%−0.6% |
| ResNet-152ResNet-152 | −0.08%−0.08% | −1.8%−1.8% |
| MobileNetV1MobileNetV1 | not reportedلم يُذكر | −11.8%−11.8% |
| MobileNetV2MobileNetV2 | not reportedلم يُذكر | −2.1%−2.1% |
The boxed rows on slide 37 are the good news: for GoogleNet and the ResNets, INT8 post-training quantization costs at most 1.8% and often almost nothing. Krishnamoorthi's whitepaper reports the same overall picture: per-channel weights with per-layer activations stay within about 2% of floating point across many networks. For these models, PTQ is a push-button win: 4× smaller weights and integer arithmetic for almost free.
الصفوف المؤطَّرة في الشريحة 37 هي الخبر السار: بالنسبة لـGoogleNet ونماذج ResNet، يكلّف تكميم INT8 بعد التدريب 1.8% على الأكثر، وكثيرًا ما يكلّف شبه لا شيء. وتورد الورقة البيضاء (whitepaper) لـKrishnamoorthi الصورة العامة نفسها: الأوزان لكل قناة مع التنشيطات لكل طبقة تبقى في حدود نحو 2% من الفاصلة العائمة عبر شبكات كثيرة. بالنسبة لهذه النماذج، PTQ مكسب بضغطة زر: أوزان أصغر بمقدار 4× وحساب بالأعداد الصحيحة مقابل شبه لا شيء.
Why small models breakلماذا تنهار النماذج الصغيرة
Slide 38 boxes MobileNetV1 at −11.8% and MobileNetV2 at −2.1%, and gives the explanation: smaller models seem to not respond as well to post-training quantization, presumably due to their smaller representational capacity. A big ResNet has many redundant weights, so the small random errors that rounding adds average out and other weights carry the same information. A compact model like MobileNet has been squeezed to use nearly every parameter, so there is little slack to absorb the noise. Its depthwise separable convolutions make it worse: each depthwise filter has only 9 weights, so per-filter ranges vary a lot. Per-channel weight scales absorb that for the weights, but the activations in this recipe still share one scale per tensor, which wastes most of the grid on the narrow channels.
تؤطّر الشريحة 38 نموذج MobileNetV1 عند −11.8% وMobileNetV2 عند −2.1%، وتعطي التفسير: يبدو أن النماذج الأصغر لا تستجيب جيدًا للتكميم بعد التدريب، ويُفترض أن ذلك بسبب سعتها التمثيلية الأصغر. نموذج ResNet الكبير فيه أوزان زائدة كثيرة، لذلك تتلاشى بالمتوسط الأخطاء العشوائية الصغيرة التي يضيفها التقريب، وتحمل أوزان أخرى المعلومات نفسها. أما النموذج المضغوط مثل MobileNet فقد عُصر ليستخدم كل معامل تقريبًا، لذلك لا يبقى هامش يُذكر لامتصاص الضوضاء. والالتفافات القابلة للفصل عمقيًا (depthwise separable convolutions) تزيد الأمر سوءًا: كل مرشح عمقي فيه 9 أوزان فقط، لذلك تختلف المديات كثيرًا من مرشح لآخر. المقاييس لكل قناة تمتص ذلك في الأوزان، لكن التنشيطات في هذه الوصفة لا تزال تتشارك مقياسًا واحدًا لكل موتر، مما يهدر معظم الشبكة على القنوات الضيقة.
How to get the accuracy backكيف نستعيد الدقة
- Better PTQ. Per-channel scales, cross-layer equalization and bias correction (Nagel et al., ICCV 2019) bring MobileNetV2 at 8/8 bits to 71.2% against 71.72% in floating point, with no data at all. AdaRound pushes PTQ down to 4-bit weights.PTQ أفضل. المقاييس لكل قناة، والمعادلة عبر الطبقات (cross-layer equalization)، وتصحيح الانحياز (bias correction) من Nagel et al., ICCV 2019 ترفع MobileNetV2 عند 8/8 بت إلى 71.2% مقابل 71.72% بالفاصلة العائمة، دون أي بيانات على الإطلاق. ويدفع AdaRound تكميم PTQ نزولًا إلى أوزان 4 بت.
- Quantization-aware training (QAT). When PTQ is still not enough, let the network learn with quantization in the loop. In the whitepaper, QAT lifts MobileNetV1 from 59.1% to 70.7%, against 70.9% in floating point. That is the answer to the slide's question "How should we improve performance of quantized models?" and the subject of the next part.quantization-aware training. عندما لا يكفي PTQ، دع الشبكة تتعلم والتكميم داخل الحلقة. في الورقة البيضاء، يرفع QAT نموذج MobileNetV1 من 59.1% إلى 70.7%، مقابل 70.9% بالفاصلة العائمة. هذه هي الإجابة عن سؤال الشريحة "How should we improve performance of quantized models?" (كيف نحسّن أداء النماذج المكمَّمة؟)، وهي موضوع الجزء التالي.
Recall
Why does a large model like ResNet-152 tolerate post-training INT8 better than MobileNetV1?لماذا يتحمل نموذج كبير مثل ResNet-152 تكميم INT8 بعد التدريب أفضل من MobileNetV1؟
Quick checkاختبار سريع
In the slide 37 table, which network loses the most top-1 accuracy under post-training INT8, and why?في جدول الشريحة 37، أي شبكة تخسر أكبر قدر من دقة top-1 تحت تكميم INT8 بعد التدريب، ولماذا؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- Rounding to nearest minimizes each weight's own error, but weights are correlated in the output Wx, so their errors can add up instead of cancel.التقريب إلى الأقرب يقلل خطأ كل وزن بمفرده، لكن الأوزان مترابطة في المخرج Wx، لذلك قد تتراكم أخطاؤها بدل أن يلغي بعضها بعضًا.
- Slide 33: [0.3, 0.5, 0.7, 0.2] rounds to [0, 1, 1, 0] by nearest; AdaRound may return [0, 0, 1, 0].الشريحة 33: المتجه [0.3, 0.5, 0.7, 0.2] يُقرَّب إلى [0, 1, 1, 0] بالتقريب إلى الأقرب، بينما قد يعيد AdaRound المتجه [0, 0, 1, 0].
- Optimal rounding is the one that best reconstructs the layer output (the activation), not the weights.التقريب الأمثل هو الذي يعيد بناء مخرج الطبقة (التنشيط) بأفضل شكل، وليس الأوزان.
- AdaRound picks floor or ceil per weight: w̃ = ⌊⌊w⌋ + δ⌉, δ ∈ [0, 1].يختار AdaRound الأرضية أو السقف لكل وزن: w̃ = ⌊⌊w⌋ + δ⌉، حيث δ ∈ [0, 1].
- Objective: argmin_V ||Wx − ⌊⌊W⌋ + h(V)⌉x||²_F + λ f_reg(V). x is the layer input, V a learnable tensor shaped like W, h a rectified sigmoid into [0, 1], f_reg pushes h(V) to 0 or 1.الهدف: argmin_V ||Wx − ⌊⌊W⌋ + h(V)⌉x||²_F + λ f_reg(V). هنا x مُدخل الطبقة، وV موتر قابل للتعلّم بشكل W نفسه، وh دالة rectified sigmoid تنقل القيم إلى [0, 1]، وf_reg يدفع h(V) إلى 0 أو 1.
- AdaRound is weight-only, layer by layer, with a short optimization on a little unlabeled data: almost post-training. 4-bit ResNet-18 goes from 23.99% (nearest) to 68.71% (FP 69.68%).AdaRound يعمل على الأوزان فقط، طبقة بعد طبقة، مع تحسين قصير على قليل من البيانات غير المعنونة: إنه تكميم بعد التدريب تقريبًا. ResNet-18 بأوزان 4 بت ترتفع من 23.99% (بالتقريب إلى الأقرب) إلى 68.71% (ودقة FP هي 69.68%).
- PTQ knobs: zero point (asymmetric, symmetric), granularity (per-tensor, per-channel, group), range clipping (EMA, KL, MSE), rounding (nearest, AdaRound).مفاتيح PTQ: نقطة الصفر (غير متماثل، متماثل)، والدقة الحبيبية granularity (لكل موتر، لكل قناة، لكل مجموعة)، وقص المدى (EMA، KL، MSE)، والتقريب (إلى الأقرب، AdaRound).
- K-means stores integer indexes plus an FP codebook and computes in FP; linear stores integers and computes in integers.K-means يخزّن فهارس صحيحة مع دفتر رموز codebook بالفاصلة العائمة ويحسب بالفاصلة العائمة، أما التكميم الخطي فيخزّن أعدادًا صحيحة ويحسب بالأعداد الصحيحة.
- INT8 PTQ costs large models under 2%, but MobileNetV1 loses 11.8% with symmetric per-channel weights. Small models have less spare capacity, which motivates QAT.تكميم INT8 بعد التدريب يكلّف النماذج الكبيرة أقل من 2%، لكن MobileNetV1 يخسر 11.8% مع أوزان متماثلة لكل قناة. النماذج الصغيرة لديها سعة احتياطية أقل، وهذا ما يدفع إلى QAT.
Sourcesالمصادر
- Up or Down? Adaptive Rounding for Post-Training QuantizationPaperNagel, Amjad, van Baalen, Louizos, Blankevoort. ICML 2020, PMLR 119The AdaRound paper behind slides 33 to 35.ورقة AdaRound التي تستند إليها الشرائح من 33 إلى 35.(opens in a new tab)(يفتح في تبويب جديد)
- Up or Down? Adaptive Rounding for Post-Training Quantization (arXiv full text)PaperarXiv 2004.10568Taylor expansion argument, the ResNet-18 rounding experiment, rectified sigmoid, f_reg with annealed β, and 4-bit results.حجة مفكوك تايلور، وتجربة التقريب على ResNet-18، ودالة rectified sigmoid، والمنظِّم f_reg مع تخفيض β تدريجيًا، ونتائج 4 بت.(opens in a new tab)(يفتح في تبويب جديد)
- Quantizing Deep Convolutional Networks for Efficient Inference: A WhitepaperPaperRaghuraman Krishnamoorthi, arXiv 2018Source of the per-channel column on slides 37 and 38, and the QAT recovery numbers for MobileNet.مصدر عمود لكل قناة في الشريحتين 37 و38، وأرقام استعادة الدقة بـQAT لنماذج MobileNet.(opens in a new tab)(يفتح في تبويب جديد)
- Data-Free Quantization Through Weight Equalization and Bias CorrectionPaperNagel, van Baalen, Blankevoort, Welling. ICCV 2019Cross-layer equalization and bias correction for MobileNet-style models.المعادلة عبر الطبقات (cross-layer equalization) وتصحيح الانحياز (bias correction) للنماذج من نمط MobileNet.(opens in a new tab)(يفتح في تبويب جديد)
- A White Paper on Neural Network QuantizationPaperNagel et al., arXiv 2021Readable overview of the whole PTQ pipeline, including AdaRound, and when to switch to QAT.عرض عام سهل القراءة لمسار PTQ كله، بما في ذلك AdaRound، ومتى يجب الانتقال إلى QAT.(opens in a new tab)(يفتح في تبويب جديد)
Part 05: Quantization-aware training: fake quantization and the straight-through estimatorالتدريب الواعي بالتكميم (QAT): التكميم الزائف والمقدّر المباشر (STE)
QAT fine-tunes the network with quantization simulated in the forward pass while a full-precision weight copy accumulates small gradient updates. Because rounding has zero gradient almost everywhere, the straight-through estimator passes gradients through as if quantization were the identity, and QAT recovers most of the INT8 accuracy that PTQ loses on MobileNets.يضبط QAT الشبكة ضبطًا دقيقًا مع محاكاة التكميم في التمرير الأمامي، بينما تراكم نسخة كاملة الدقة من الأوزان تحديثات تدرج صغيرة. ولأن للتقريب تدرجًا صفريًا في كل مكان تقريبًا، يمرر المقدّر المباشر (straight-through estimator) التدرجات كأن التكميم دالة هوية، ويستعيد QAT معظم دقة INT8 التي يفقدها PTQ على نماذج MobileNet.
4 concepts4 مفاهيم, ، slides 39-48الشرائح 39-48
Why this part mattersلماذا يهمّ هذا الجزء
The last part ended on a bad number: INT8 post-training quantization drops MobileNetV1 to 0.1% top-1 with per-tensor scales. Clever choices of scale, clipping and rounding only go so far. The next lever is to let the network itself adapt to quantization by training with it in the loop.
The part follows one argument. First, why training helps and what it looks like for K-means quantization, where only the centroids move. Second, how linear quantization is put into the training graph as fake quantization while a full-precision weight copy absorbs the updates. Third, the obstacle: rounding has zero gradient, and the straight-through estimator that gets around it. Fourth, the payoff in measured accuracy. For the midterm, expect to compute a centroid update, explain the role of the FP copy, derive the zero gradient and write the STE rule, and read the PTQ versus QAT table.
انتهى الجزء السابق برقم سيئ: الـ INT8 post-training quantization يُسقط دقة MobileNetV1 إلى 0.1% في top-1 عند استخدام scale واحد لكل tensor (per-tensor). الاختيارات الذكية للـ scale والـ clipping والتقريب (rounding) لها حدود. الرافعة التالية هي أن نترك الشبكة نفسها تتكيّف مع الـ quantization بأن ندرّبها وهو داخل الحلقة.
يتبع هذا الجزء حجة واحدة. أولاً، لماذا يفيد التدريب، وكيف يبدو في حالة K-means quantization حيث تتحرك الـ centroids فقط. ثانياً، كيف يُدخَل الـ linear quantization في رسم التدريب (training graph) على شكل fake quantization، بينما تمتص نسخة الأوزان بالدقة الكاملة التحديثات. ثالثاً، العقبة: التقريب له gradient يساوي صفراً، والـ straight-through estimator هو ما يلتف عليها. رابعاً، المكسب في الدقة المقاسة. في الاختبار النصفي توقّع أن تحسب تحديث centroid، وأن تشرح دور نسخة الـ FP، وأن تشتق الـ gradient الصفري وتكتب قاعدة الـ STE، وأن تقرأ جدول المقارنة بين PTQ وQAT.
By the end you canفي نهاية هذا الجزء ستستطيع
- Explain why aggressive quantization (4 bits and below) needs training with quantization in the loop, and why fine-tuning a pretrained FP model beats training from scratch.أن تشرح لماذا يحتاج الـ quantization الحاد (4 بتات فأقل) إلى تدريب يكون فيه الـ quantization داخل الحلقة، ولماذا يتفوق الـ fine-tuning لنموذج FP مدرَّب مسبقاً على التدريب من الصفر.
- Carry out one K-means QAT step: group gradients by cluster index, sum, scale by the learning rate and subtract from the centroids.أن تنفّذ خطوة واحدة من K-means QAT: تجميع الـ gradients حسب رقم الـ cluster، ثم جمعها، ثم ضربها في معدل التعلم وطرحها من الـ centroids.
- Describe fake (simulated) quantization: which tensors are quantized, which operations still run in full precision, and why a full-precision weight copy is kept.أن تصف الـ fake (simulated) quantization: أي الـ tensors تُكمَّم، وأي العمليات تبقى بالدقة الكاملة، ولماذا نحتفظ بنسخة من الأوزان بالدقة الكاملة.
- Show with the chain rule why the true gradient through a quantizer is zero, and write the straight-through estimator for weights and activations.أن تبيّن بقاعدة السلسلة (chain rule) لماذا يساوي الـ gradient الحقيقي عبر الـ quantizer صفراً، وأن تكتب الـ straight-through estimator للأوزان وللـ activations.
- Read the INT8 PTQ versus QAT table and explain why MobileNets gain the most.أن تقرأ جدول INT8 الذي يقارن PTQ مع QAT وتشرح لماذا تستفيد شبكات MobileNet أكثر من غيرها.
Take the 4×4 weight matrix you have quantized many times already and cluster it with K-means into four values: 2.00, 1.50, 0.00, -1.00. Every weight is now stored as a 2-bit cluster index, and the network only ever sees those four numbers. Its accuracy has dropped. Can a few more training steps win some of it back, even though the weights are no longer free to take any value?
خذ مصفوفة الأوزان 4×4 التي كمّمتها مرات عديدة من قبل، وجمّعها بالـ K-means في أربع قيم: 2.00, 1.50, 0.00, -1.00. أصبح كل وزن الآن مخزَّناً كرقم cluster من 2 بت، والشبكة لا ترى إلا هذه الأرقام الأربعة. لقد انخفضت دقتها. هل يمكن لبضع خطوات تدريب إضافية أن تستعيد جزءاً منها، رغم أن الأوزان لم تعد حرة في أخذ أي قيمة؟
Train with the quantizer, not after itدرّب مع الـ quantizer، لا بعده
Yes, and that is the whole idea of Quantization-aware training (QAT). In Post-training quantization (PTQ), the network was trained without ever seeing rounding, and we rounded it afterwards. The error that rounding adds is a surprise to every later layer. If the network is trained or fine-tuned while its weights and activations are already quantized, gradient descent can steer the remaining free parameters toward a solution that works well on the quantization grid. This matters most for aggressive settings, 4 bits and below, where the grid is so coarse that no choice of scale or rounding alone keeps accuracy.
نعم، وهذه هي فكرة Quantization-aware training (QAT) كلها. في Post-training quantization (PTQ) دُرّبت الشبكة دون أن ترى التقريب أبداً، ثم قرّبناها بعد ذلك. الخطأ الذي يضيفه التقريب يكون مفاجأة لكل طبقة لاحقة. أما إذا دُرّبت الشبكة أو أُجري لها fine-tuning وأوزانها وactivations مكمَّمة أصلاً، فإن الـ gradient descent يستطيع توجيه المعاملات الحرة المتبقية نحو حل يعمل جيداً على شبكة الـ quantization. هذا مهم أكثر ما يكون في الإعدادات الحادة، 4 بتات فأقل، حيث تكون الشبكة خشنة لدرجة أنه لا يوجد اختيار للـ scale أو للتقريب وحده يحافظ على الدقة.
The slides add a practical rule: fine-tune a pretrained floating-point model rather than training a quantized model from scratch. Krishnamoorthi reports the same finding in his INT8 study. The FP model has already found a good region of the loss surface with full freedom. QAT then only has to make small corrections so that the quantized version of that solution works, which is a much easier problem than searching the whole space through a coarse grid.
تضيف الشرائح قاعدة عملية: اعمل fine-tuning لنموذج floating-point مدرَّب مسبقاً بدلاً من تدريب نموذج مكمَّم من الصفر. ويذكر Krishnamoorthi النتيجة نفسها في دراسته عن INT8. نموذج الـ FP وجد أصلاً منطقة جيدة من سطح الخسارة (loss surface) وهو يتمتع بحرية كاملة. وبعدها لا يحتاج الـ QAT إلا إلى تصحيحات صغيرة كي تعمل النسخة المكمَّمة من ذلك الحل، وهذه مسألة أسهل بكثير من البحث في الفضاء كله عبر شبكة خشنة.
QAT for K-means quantization: only the centroids learnQAT في K-means quantization: الـ centroids وحدها تتعلم
With K-means quantization the cluster assignment is frozen. What can still change is the codebook, the four centroid values. Every weight in cluster equals the centroid , so by the chain rule the gradient of the loss with respect to is the sum of the gradients of all weights that point to it. That gives a four-step recipe from Deep Compression (Han et al., ICLR 2016): compute the usual weight gradients, group them by cluster index, reduce each group by summing, then multiply by the learning rate and subtract from the centroid.
في K-means quantization يكون توزيع الأوزان على الـ clusters مجمَّداً. ما يمكن أن يتغير هو الـ codebook، أي قيم الـ centroids الأربع. كل وزن في الـ cluster رقم يساوي الـ centroid ، لذلك بقاعدة السلسلة يكون gradient الخسارة بالنسبة إلى هو مجموع gradients كل الأوزان التي تشير إليه. هذا يعطينا وصفة من أربع خطوات من Deep Compression (Han et al., ICLR 2016): احسب gradients الأوزان المعتادة، وجمّعها حسب رقم الـ cluster، واختزل كل مجموعة بالجمع، ثم اضرب في معدل التعلم واطرح من الـ centroid.
Worked exampleمثال محلول
One centroid update from slide 40 (lr = 1)تحديث centroid واحد من الشريحة 40 (lr = 1)
Group by indexالتجميع حسب الرقم
The cluster index matrix puts five weights in cluster 1. Their gradients are 0.02, -0.01, 0.01, 0.04, -0.02.مصفوفة أرقام الـ clusters تضع خمسة أوزان في الـ cluster رقم 1. وgradients هذه الأوزان هي 0.02, -0.01, 0.01, 0.04, -0.02.Reduceالاختزال
Sum them: 0.02 - 0.01 + 0.01 + 0.04 - 0.02 = 0.04.اجمعها: 0.02 - 0.01 + 0.01 + 0.04 - 0.02 = 0.04.Scale and subtractالضرب ثم الطرح
With lr = 1, the centroid moves from 0.00 to 0.00 - 0.04 = -0.04.مع lr = 1 ينتقل الـ centroid من 0.00 إلى 0.00 - 0.04 = -0.04.Resultالنتيجة
Doing the same for every cluster turns [2.00, 1.50, 0.00, -1.00] into [1.96, 1.48, -0.04, -0.97]. Note the sign: cluster 0 has a negative sum -0.03, so its centroid rises.تطبيق الشيء نفسه على كل cluster يحوّل [2.00, 1.50, 0.00, -1.00] إلى [1.96, 1.48, -0.04, -0.97]. انتبه للإشارة: الـ cluster رقم 0 مجموعه سالب -0.03، لذلك يرتفع الـ centroid الخاص به.
| Indexالرقم | Grouped gradientsالـ gradients المجمَّعة | Sumالمجموع | Centroid beforeالـ centroid قبل | Centroid afterالـ centroid بعد |
|---|---|---|---|---|
| 33 | -0.03, 0.12, 0.02, -0.07-0.03, 0.12, 0.02, -0.07 | 0.040.04 | 2.002.00 | 1.961.96 |
| 22 | 0.03, 0.01, -0.020.03, 0.01, -0.02 | 0.020.02 | 1.501.50 | 1.481.48 |
| 11 | 0.02, -0.01, 0.01, 0.04, -0.020.02, -0.01, 0.01, 0.04, -0.02 | 0.040.04 | 0.000.00 | -0.04-0.04 |
| 00 | -0.01, -0.02, -0.01, 0.01-0.01, -0.02, -0.01, 0.01 | -0.03-0.03 | -1.00-1.00 | -0.97-0.97 |
Recall
Why should QAT start from a pretrained FP model, and what changes during K-means QAT?لماذا يجب أن يبدأ الـ QAT من نموذج FP مدرَّب مسبقاً، وما الذي يتغير أثناء K-means QAT؟
The FP model already sits in a good region of the loss surface, so QAT only makes small corrections; training through the coarse grid from scratch reaches lower accuracy. In K-means QAT the cluster indices stay fixed and only the centroids change, each by lr times the sum of its members' gradients.
نموذج الـ FP موجود أصلاً في منطقة جيدة من سطح الخسارة، لذلك لا يجري الـ QAT إلا تصحيحات صغيرة؛ أما التدريب عبر الشبكة الخشنة من الصفر فيصل إلى دقة أقل. في K-means QAT تبقى أرقام الـ clusters ثابتة ولا تتغير إلا الـ centroids، كل منها بمقدار lr مضروباً في مجموع gradients أعضائه.
Quick checkاختبار سريع
Cluster 0 has centroid -1.00 and grouped gradients -0.01, -0.02, -0.01 and 0.01. With lr = 1, what is the new centroid?الـ cluster رقم 0 قيمة الـ centroid فيه -1.00، والـ gradients المجمَّعة فيه هي -0.01 و-0.02 و-0.01 و0.01. مع lr = 1، ما قيمة الـ centroid الجديدة؟
Now switch to linear quantization. Suppose one weight is w = 1.48 on the 2-bit grid of slide 43, whose step is S = 1.07. It rounds to the level 1.07. A typical SGD update is tiny, say 0.005. If we stored only the quantized weight and applied the update to it, we would get 1.075, which rounds straight back to 1.07. Every update is erased, forever.
لننتقل الآن إلى الـ linear quantization. افترض أن وزناً واحداً قيمته w = 1.48 على شبكة الـ 2 بت في الشريحة 43، وخطوتها S = 1.07. هذا الوزن يُقرَّب إلى المستوى 1.07. تحديث SGD المعتاد صغير جداً، وليكن 0.005. لو خزّنّا الوزن المكمَّم فقط وطبقنا التحديث عليه لحصلنا على 1.075، وهذه تُقرَّب مباشرة إلى 1.07 من جديد. كل تحديث يُمحى، وإلى الأبد.
Keep a full-precision copy and quantize on the flyاحتفظ بنسخة بالدقة الكاملة وكمّم أثناء التشغيل
The fix is to keep a Full-precision weight copy of the weights throughout training. The optimizer updates this copy, so small steps accumulate without being rounded away. Every forward pass then quantizes the current copy into and uses that. In the example, w = 1.48 must reach the rounding boundary halfway between 1.07 and 2.14, at 1.5 × 1.07 = 1.605. That is 0.125 away, so after about 25 steps of 0.005 the quantized weight jumps to 2.14. The many small steps were not lost, they were stored up. Once training ends the copy is thrown away and only the quantized weights are used for inference.
الحل هو الاحتفاظ بـ Full-precision weight copy للأوزان طوال التدريب. الـ optimizer يحدّث هذه النسخة، فتتراكم الخطوات الصغيرة دون أن يمحوها التقريب. ثم في كل forward pass نكمّم النسخة الحالية إلى ونستخدمها. في المثال، يجب أن يصل w = 1.48 إلى حد التقريب الواقع في منتصف المسافة بين 1.07 و2.14، أي عند 1.5 × 1.07 = 1.605. المسافة 0.125، لذلك بعد نحو 25 خطوة كل منها 0.005 يقفز الوزن المكمَّم إلى 2.14. الخطوات الصغيرة الكثيرة لم تضِع، بل كانت تُدَّخر. وعند انتهاء التدريب تُرمى النسخة ولا تُستخدم في الـ inference إلا الأوزان المكمَّمة.
Fake quantization: discrete values, floating-point arithmeticالـ fake quantization: قيم متقطعة وحساب بالـ floating point
How is computed? It is linear quantization followed immediately by dequantization, all in floating point: . The result is still an FP tensor, but every entry lies exactly on the quantization grid. This is called Simulated (fake) quantization, or simulated quantization, because no integer hardware is involved. Slide 43 shows the arithmetic with the zero point included.
كيف تُحسب ؟ هي linear quantization يتبعه مباشرة dequantization، وكل ذلك بالـ floating point: . الناتج ما زال tensor من نوع FP، لكن كل عنصر فيه يقع تماماً على شبكة الـ quantization. يسمى هذا Simulated (fake) quantization، أي quantization محاكى، لأنه لا يستخدم أي عتاد للأعداد الصحيحة. الشريحة 43 تعرض الحساب مع إدخال الـ zero point.
Worked exampleمثال محلول
Slide 43: the 2-bit Q(W) for the 4×4 matrixالشريحة 43: قيم Q(W) بـ 2 بت للمصفوفة 4×4
Scale and zero pointالـ scale والـ zero point
The weights span [-1.08, 2.12] and 2-bit signed codes span [-2, 1], so S = 3.20 / 3 ≈ 1.07 and Z = round(-2 + 1.08/1.07) = round(-0.99) = -1.تمتد الأوزان على [-1.08, 2.12]، وتمتد الرموز الموقّعة (signed codes) بـ 2 بت على [-2, 1]، لذلك S = 3.20 / 3 ≈ 1.07 وZ = round(-2 + 1.08/1.07) = round(-0.99) = -1.Codesالرموز
The first row [2.09, -0.98, 1.48, 0.09] gives q_W = [1, -2, 0, -1]. For example 1.48 / 1.07 ≈ 1.38, which rounds to 1, and adding Z = -1 gives 0.الصف الأول [2.09, -0.98, 1.48, 0.09] يعطي q_W = [1, -2, 0, -1]. مثلاً 1.48 / 1.07 ≈ 1.38، وهذه تُقرَّب إلى 1، وبإضافة Z = -1 نحصل على 0.Dequantizeالـ dequantization
(q_W - Z) × S = [2, -1, 1, 0] × 1.07 = [2.14, -1.07, 1.07, 0].(q_W - Z) × S = [2, -1, 1, 0] × 1.07 = [2.14, -1.07, 1.07, 0].Resultالنتيجة
The full has rows [2.14, -1.07, 1.07, 0], [0, 0, -1.07, 2.14], [-1.07, 2.14, 0, -1.07] and [2.14, 0, 1.07, 1.07]. Only four values occur: -1.07, 0, 1.07, 2.14. This is what the layer computes with during QAT.صفوف الكاملة هي [2.14, -1.07, 1.07, 0] و[0, 0, -1.07, 2.14] و[-1.07, 2.14, 0, -1.07] و[2.14, 0, 1.07, 1.07]. لا تظهر إلا أربع قيم: -1.07, 0, 1.07, 2.14. وهذا ما تحسب به الطبقة أثناء الـ QAT.
Activations get the same treatment. The output of a layer is fake-quantized as before it is passed on, so the next layer receives as its input. The scale of the activations is not known from the weights; it is tracked during training, typically with an Exponential moving average (EMA) of the observed range.
الـ activations تُعامَل بالطريقة نفسها. مخرج الطبقة يمر بـ fake quantization على الشكل قبل أن يُمرَّر، فتستقبل الطبقة التالية كمدخل لها. الـ scale الخاص بالـ activations لا يُعرف من الأوزان؛ بل يُتتبَّع أثناء التدريب، عادةً باستخدام Exponential moving average (EMA) للمدى المرصود.
Arrives already fake-quantized as Q(X).
يصل وقد خضع مسبقًا للتكميم الزائف (fake quantization) بصورة Q(X).
Conv, batch norm and ReLU run in FP, using Q(W) from the FP weight copy W.
تعمل Conv وbatch norm وReLU بالفاصلة العائمة (FP)، باستخدام Q(W) المأخوذة من نسخة الأوزان W بصيغة FP.
Y becomes S_Y (q_Y - Z_Y) = Q(Y).
تصبح Y هي S_Y (q_Y - Z_Y) = Q(Y).
Discrete values, exactly as integer inference will produce them.
قيم متقطعة، تمامًا كما سينتجها الاستدلال بالأعداد الصحيحة (integer inference).
| Tensor or operationالـ tensor أو العملية | What happensما يحدث | Value usedالقيمة المستخدمة |
|---|---|---|
| Weights Wالأوزان W | Full precision copy, updated by the optimizerنسخة بالدقة الكاملة يحدّثها الـ optimizer | Q(W) = S_W q_WQ(W) = S_W q_W |
| Layer input Xمدخل الطبقة X | Already quantized by the previous layerمكمَّم أصلاً بواسطة الطبقة السابقة | Q(X)Q(X) |
| Conv, batch norm, ReLUconv و batch norm و ReLU | Run in full precision on the fake-quantized valuesتعمل بالدقة الكاملة على القيم المكمَّمة بالـ fake quantization | Not quantized inside the blockلا تُكمَّم داخل الكتلة |
| Layer output Yمخرج الطبقة Y | Full precision result of the blockنتيجة الكتلة بالدقة الكاملة | Q(Y) = S_Y (q_Y - Z_Y)Q(Y) = S_Y (q_Y - Z_Y) |
Recall
Why must QAT keep a full-precision copy of the weights?لماذا يجب أن يحتفظ الـ QAT بنسخة من الأوزان بالدقة الكاملة؟
Gradient updates are usually much smaller than half a quantization step. Applied to a quantized weight, each one rounds straight back to the same level and is lost. The FP copy accumulates them until the weight crosses a rounding boundary, and only then does Q(W) change.
تحديثات الـ gradient عادةً أصغر بكثير من نصف خطوة quantization. إذا طُبّق كل منها على وزن مكمَّم فإنه يُقرَّب مباشرة إلى المستوى نفسه ويضيع. نسخة الـ FP تراكمها حتى يعبر الوزن حدّ تقريب، وعندها فقط تتغير Q(W).
Recall
During fake quantization, which tensors are quantized and which operations stay in full precision?أثناء الـ fake quantization، أي الـ tensors تُكمَّم وأي العمليات تبقى بالدقة الكاملة؟
The weights (Q(W) = S_W q_W) and the layer outputs (Q(Y) = S_Y (q_Y - Z_Y)) are quantized, so inputs to the next layer are Q(X). Conv, batch norm and ReLU inside the layer still run in full precision.
تُكمَّم الأوزان (Q(W) = S_W q_W) ومخرجات الطبقات (Q(Y) = S_Y (q_Y - Z_Y))، فتكون مدخلات الطبقة التالية Q(X). أما conv وbatch norm وReLU داخل الطبقة فتبقى تعمل بالدقة الكاملة.
Quick checkاختبار سريع
During quantization-aware training, which values are stored in full precision and updated by the optimizer?أثناء الـ quantization-aware training، ما القيم المخزَّنة بالدقة الكاملة والتي يحدّثها الـ optimizer؟
Plot for w from 0 to 5. You get a staircase. Pick any point, say w = 2.3, and nudge it slightly: Q stays at 2. The slope there is exactly zero. The same is true at every point except the jumps at 0.5, 1.5, 2.5, …, where the function is not differentiable at all.
ارسم لقيم w من 0 إلى 5. ستحصل على درَج. اختر أي نقطة، ولتكن w = 2.3، وحرّكها قليلاً: تبقى Q عند 2. الميل هناك يساوي صفراً تماماً. والأمر نفسه صحيح عند كل نقطة ما عدا القفزات عند 0.5, 1.5, 2.5, …، حيث الدالة غير قابلة للاشتقاق أصلاً.
The true gradient kills learningالـ gradient الحقيقي يقتل التعلم
Backpropagation reaches the weights through the quantizer, so the chain rule multiplies by that slope.
الـ backpropagation يصل إلى الأوزان عبر الـ quantizer، لذلك تضرب قاعدة السلسلة في ذلك الميل.
The layer above still produces a useful signal : it knows whether the effective weight should be larger or smaller. But the zero factor wipes it out. The FP copy would receive a zero gradient on every step and never move. Slide 44 posed exactly this question: how should gradients back-propagate through the simulated quantization?
الطبقة التي فوقها ما زالت تنتج إشارة مفيدة : فهي تعرف هل يجب أن يكون الوزن الفعلي أكبر أم أصغر. لكن العامل الصفري يمحوها. ستستقبل نسخة الـ FP gradient صفرياً في كل خطوة ولن تتحرك أبداً. الشريحة 44 طرحت هذا السؤال بالضبط: كيف يجب أن تنتشر الـ gradients للخلف عبر الـ quantization المحاكى؟
Pretend the quantizer is the identity on the way backتظاهَر بأن الـ quantizer هو دالة الهوية في طريق العودة
The Straight-through estimator (STE) answers it with a deliberate approximation. In the forward pass, quantize as usual. In the backward pass, treat the quantizer as if it were the identity function, the dashed diagonal through the staircase, whose slope is 1. The gradient arriving at is passed straight through to . The idea goes back to Hinton's 2012 Coursera lectures and was analysed by Bengio, Léonard and Courville in 2013.
يجيب Straight-through estimator (STE) عن هذا السؤال بتقريب متعمَّد. في الـ forward pass نكمّم كالمعتاد. وفي الـ backward pass نعامل الـ quantizer كأنه دالة الهوية (identity)، أي القطر المتقطع المار عبر الدرَج، وميله 1. الـ gradient الواصل إلى يُمرَّر مباشرة إلى . تعود الفكرة إلى محاضرات Hinton على Coursera عام 2012، وحلّلها Bengio وLéonard وCourville عام 2013.
Why is this a reasonable lie? Over a range of many steps the staircase follows the identity line closely: raising by one step raises by one step on average. The STE uses that average slope instead of the local one. Combined with the FP copy, it gives exactly the behaviour you want: the copy drifts in the direction the loss prefers, and jumps to the next level once the drift is large enough.
لماذا هذه كذبة معقولة؟ على مدى خطوات كثيرة يتبع الدرَج خط الهوية عن قرب: رفع بمقدار خطوة واحدة يرفع بخطوة واحدة في المتوسط. الـ STE يستخدم ذلك الميل المتوسط بدلاً من الميل المحلي. ومع نسخة الـ FP يعطي بالضبط السلوك المطلوب: تنجرف النسخة في الاتجاه الذي تفضّله الخسارة، وتقفز إلى المستوى التالي عندما يكبر الانجراف بما يكفي.
Watch it work on a single weight. Loss L = ½ (Q(w) - 2.3)² wants the effective weight to be 2.3, but the grid only offers integers. Switch between the true gradient and the STE, and step the training loop.
شاهدها تعمل على وزن واحد. الخسارة L = ½ (Q(w) - 2.3)² تريد أن يكون الوزن الفعلي 2.3، لكن الشبكة لا تقدم إلا أعداداً صحيحة. بدّل بين الـ gradient الحقيقي والـ STE، وتقدّم في حلقة التدريب خطوة خطوة.
Loss L = ½ (Q(w) - 2.3)², so dL/dQ(w) = Q(w) - 2.3. Update w ← w - 0.15 g_w starting from w = 0.3. With the true gradient the weight never moves. With STE it climbs, Q(w) jumps from level to level, and w ends up hovering at the rounding boundary 2.5 because neither level 2 nor 3 equals the target.الخسارة L = ½ (Q(w) - 2.3)²، لذلك dL/dQ(w) = Q(w) - 2.3. التحديث هو w ← w - 0.15 g_w بدءًا من w = 0.3. مع التدرج الحقيقي لا يتحرك الوزن أبدًا. أما مع STE فإنه يصعد، وتقفز Q(w) من مستوى إلى آخر، وينتهي الأمر بـ w وهو يحوم عند حد التقريب 2.5 لأن أيًّا من المستويين 2 و3 لا يساوي الهدف.
With the true gradient nothing ever happens. With the STE the FP copy climbs, jumps from 0 to 1 to 2, and then the copy settles at the boundary 2.5, flipping between levels 2 and 3. Krishnamoorthi observed the same effect in real networks: during QAT the FP weights converge to the quantization decision boundaries.
مع الـ gradient الحقيقي لا يحدث شيء أبداً. ومع الـ STE تصعد نسخة الـ FP، وتقفز من 0 إلى 1 إلى 2، ثم تستقر النسخة عند الحد 2.5 وتتأرجح بين المستويين 2 و3. لاحظ Krishnamoorthi الأثر نفسه في الشبكات الحقيقية: أثناء الـ QAT تتقارب أوزان الـ FP نحو حدود قرار الـ quantization.
Recall
Derive why the true gradient through a quantizer is zero, then write the STE.اشتق لماذا يساوي الـ gradient الحقيقي عبر الـ quantizer صفراً، ثم اكتب الـ STE.
g_W = ∂L/∂W = ∂L/∂Q(W) · ∂Q(W)/∂W. Rounding is flat between jumps, so ∂Q(W)/∂W = 0 almost everywhere, hence g_W = 0 and nothing learns. The STE treats Q as the identity in the backward pass: g_W = ∂L/∂Q(W), and for activations g_Y ← ∂L/∂Q(Y).
g_W = ∂L/∂W = ∂L/∂Q(W) · ∂Q(W)/∂W. التقريب مسطّح بين القفزات، لذلك ∂Q(W)/∂W = 0 تقريباً في كل مكان، ومن ثم g_W = 0 ولا يتعلم شيء. الـ STE يعامل Q كدالة الهوية في الـ backward pass: g_W = ∂L/∂Q(W)، وللـ activations g_Y ← ∂L/∂Q(Y).
Quick checkاختبار سريع
Under the straight-through estimator, what is g_W for a weight inside the clipping range when dL/dQ(W) = 0.3?مع الـ straight-through estimator، ما قيمة g_W لوزن داخل مدى الـ clipping عندما تكون dL/dQ(W) = 0.3؟
Return to the worst number in this lecture. MobileNetV1 has 70.9% top-1 accuracy in floating point. INT8 PTQ with asymmetric Per-tensor quantization collapses it to 0.1%, which is chance level on ImageNet. Fine-tune the same model with QAT and the same per-tensor scheme reaches 70.0%.
لنعد إلى أسوأ رقم في هذه المحاضرة. دقة MobileNetV1 في top-1 هي 70.9% بالـ floating point. الـ INT8 PTQ مع Per-tensor quantization غير المتماثل (asymmetric) يهوي بها إلى 0.1%، وهو مستوى التخمين العشوائي على ImageNet. أجرِ fine-tuning للنموذج نفسه بالـ QAT فيصل المخطط نفسه (per-tensor) إلى 70.0%.
| Networkالشبكة | FPFP | PTQ asym per-tensorPTQ asym per-tensor | PTQ sym per-channelPTQ sym per-channel | QAT asym per-tensorQAT asym per-tensor | QAT sym per-channelQAT sym per-channel |
|---|---|---|---|---|---|
| MobileNetV1MobileNetV1 | 70.970.9 | 0.10.1 | 59.159.1 | 70.070.0 | 70.770.7 |
| MobileNetV2MobileNetV2 | 71.971.9 | 0.10.1 | 69.869.8 | 70.970.9 | 71.171.1 |
| NASNet-MobileNASNet-Mobile | 74.9 (paper: 74.0)74.9 (في الورقة: 74.0) | 72.272.2 | 72.172.1 | 73.073.0 | 73.073.0 |
Reading the tableقراءة الجدول
- QAT recovers most of the loss. With Symmetric quantization and Per-channel quantization, MobileNetV1 goes from 59.1% to 70.7%, a gain of 11.6 points, ending only 0.2 below FP. MobileNetV2 goes from 69.8% to 71.1%.الـ QAT يستعيد معظم الخسارة. مع Symmetric quantization وPer-channel quantization ينتقل MobileNetV1 من 59.1% إلى 70.7%، أي مكسب قدره 11.6 نقطة، لينتهي أقل من الـ FP بـ 0.2 فقط. وينتقل MobileNetV2 من 69.8% إلى 71.1%.
- Training makes simple schemes viable. Per-tensor asymmetric quantization is unusable after training (0.1%) but within 1 point of FP with QAT. The network learns to live with one shared scale.التدريب يجعل المخططات البسيطة صالحة للاستخدام. الـ quantization غير المتماثل لكل tensor غير قابل للاستخدام بعد التدريب (0.1%)، لكنه يصبح ضمن 1 نقطة من الـ FP مع الـ QAT. الشبكة تتعلم أن تتعايش مع scale واحد مشترك.
- The models PTQ hurts most gain the most. NASNet-Mobile was already fine after PTQ (72.2%), so QAT adds less than 1 point.النماذج التي يضرّها الـ PTQ أكثر هي التي تكسب أكثر. كان NASNet-Mobile جيداً أصلاً بعد الـ PTQ (72.2%)، لذلك يضيف الـ QAT أقل من 1 نقطة.
- Why MobileNets suffer, and so gain the most. Krishnamoorthi traces almost all of the loss to weight quantization. Batch norm is folded into the conv weights for inference, and its per-channel scaling makes the weight ranges of different kernels in one layer vary enormously. A single per-tensor scale is then sized for the widest kernel, so narrow kernels get only a handful of the 256 levels, or round to zero. Compact networks with few parameters, like MobileNets with their depthwise convolutions, have little redundancy to absorb that error, while larger networks such as ResNets are more robust. Per-channel scales sidestep the range problem, and QAT lets the weights adapt to whatever grid remains.لماذا تعاني شبكات MobileNet، ولذلك تكسب أكثر. يُرجع Krishnamoorthi معظم الخسارة تقريباً إلى quantization الأوزان. الـ batch norm يُدمج (folded) في أوزان الـ conv من أجل الـ inference، والتحجيم الخاص بكل قناة فيه يجعل مدى أوزان الـ kernels المختلفة في الطبقة الواحدة يتفاوت تفاوتاً هائلاً. عندها يُحدَّد الـ scale الواحد لكل tensor على مقاس أعرض kernel، فلا تحصل الـ kernels الضيقة إلا على عدد قليل من المستويات الـ 256، أو تُقرَّب إلى صفر. الشبكات المدمجة ذات المعاملات القليلة، مثل MobileNet بطبقات الـ depthwise convolutions، فيها تكرار (redundancy) قليل يمتص ذلك الخطأ، بينما الشبكات الأكبر مثل ResNet أكثر متانة. الـ scales لكل قناة (per-channel) تتجاوز مشكلة المدى، والـ QAT يسمح للأوزان بالتكيف مع أي شبكة متبقية.
- Two variables change between columns. Each pair of columns changes both symmetry and granularity, so the table compares recipes, not single factors.متغيران يتغيران بين الأعمدة. كل زوج من الأعمدة يغيّر التماثل (symmetry) والدقة الحبيبية (granularity) معاً، لذلك يقارن الجدول وصفات كاملة، لا عوامل منفردة.
Where this leaves usأين يتركنا هذا
Slide 48 repeats the summary table of the two quantization families and points an arrow at a question mark. K-means quantization stores integer indices but still computes in floating point after a codebook lookup. Linear quantization stores integers and computes with integers. QAT works for both, with a different update rule for each. The question mark asks how far the bit width can go. The next part pushes it to the limit, a single bit, with Binarization, where the same STE idea is what makes training possible.
تكرر الشريحة 48 جدول الملخص لعائلتي الـ quantization وتوجّه سهماً نحو علامة استفهام. الـ K-means quantization يخزّن أرقاماً صحيحة (indices) لكنه ما زال يحسب بالـ floating point بعد البحث في الـ codebook. الـ linear quantization يخزّن أعداداً صحيحة ويحسب بأعداد صحيحة. والـ QAT يعمل مع كليهما، بقاعدة تحديث مختلفة لكل منهما. علامة الاستفهام تسأل: إلى أي حد يمكن أن ينخفض عدد البتات؟ الجزء التالي يدفعه إلى أقصى حد، بت واحد، مع binarization، حيث فكرة الـ STE نفسها هي ما يجعل التدريب ممكناً.
| Floating pointFloating point | K-means quantizationK-means quantization | Linear quantizationLinear quantization | |
|---|---|---|---|
| Storageالتخزين | FP weightsأوزان FP | Integer indices plus an FP codebookأرقام صحيحة (indices) مع codebook بالـ FP | Integer weightsأوزان صحيحة |
| Computationالحساب | FP arithmeticحساب بالـ FP | FP arithmetic (look up, then multiply)حساب بالـ FP (بحث في الـ codebook ثم ضرب) | Integer arithmeticحساب بالأعداد الصحيحة |
| How QAT trains itكيف يدرّبه الـ QAT | Not applicableلا ينطبق | Sum gradients per cluster, update centroidsجمع الـ gradients لكل cluster ثم تحديث الـ centroids | Fake quantization plus STE on an FP copyfake quantization مع STE على نسخة FP |
Recall
Compare PTQ and QAT for MobileNetV1 at INT8 in both schemes on the slide.قارن بين PTQ و QAT لـ MobileNetV1 عند INT8 في المخططين الموجودين على الشريحة.
FP is 70.9%. Asymmetric per-tensor: PTQ 0.1%, QAT 70.0%. Symmetric per-channel: PTQ 59.1%, QAT 70.7%. QAT closes the gap to within 0.2 to 0.9 points and even makes per-tensor quantization usable.
الـ FP هو 70.9%. في asymmetric per-tensor: PTQ 0.1% وQAT 70.0%. في symmetric per-channel: PTQ 59.1% وQAT 70.7%. الـ QAT يضيّق الفجوة إلى ما بين 0.2 و0.9 نقطة، بل ويجعل الـ per-tensor quantization قابلاً للاستخدام.
Quick checkاختبار سريع
For MobileNetV1 with symmetric per-channel INT8, how many top-1 points does QAT gain over PTQ?لـ MobileNetV1 مع INT8 بمخطط symmetric per-channel، كم نقطة في top-1 يكسبها الـ QAT مقارنة بالـ PTQ؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- PTQ is fine at 8 bits for big models, but small models and 4 bits or fewer need quantization-aware training. Start from a pretrained FP model, not from scratch.الـ PTQ مناسب عند 8 بتات للنماذج الكبيرة، لكن النماذج الصغيرة و4 بتات فأقل تحتاج إلى quantization-aware training. ابدأ من نموذج FP مدرَّب مسبقاً، لا من الصفر.
- K-means QAT: group the weight gradients by cluster index, sum each group, multiply by lr and subtract from the centroid. With lr = 1, [2.00, 1.50, 0.00, -1.00] becomes [1.96, 1.48, -0.04, -0.97].في K-means QAT: نجمّع gradients الأوزان حسب رقم الـ cluster، ونجمع كل مجموعة، ثم نضرب في lr ونطرح من الـ centroid. مع lr = 1 تصبح [2.00, 1.50, 0.00, -1.00] هي [1.96, 1.48, -0.04, -0.97].
- Linear QAT keeps a full-precision W. The forward pass uses Q(W) = S_W q_W and Q(Y) = S_Y (q_Y - Z_Y), so values crossing layer boundaries are discrete, while conv, batch norm and ReLU still run in FP.الـ linear QAT يحتفظ بنسخة W بالدقة الكاملة. الـ forward pass يستخدم Q(W) = S_W q_W و Q(Y) = S_Y (q_Y - Z_Y)، فتكون القيم التي تعبر حدود الطبقات متقطعة، بينما تبقى عمليات conv و batch norm و ReLU تعمل بالـ FP.
- The FP copy lets updates much smaller than one quantization step accumulate until a weight crosses a rounding boundary. After training only the quantized weights ship.نسخة الـ FP تسمح للتحديثات الأصغر بكثير من خطوة quantization واحدة بأن تتراكم حتى يعبر الوزن حدّ تقريب. بعد التدريب تُشحن الأوزان المكمَّمة فقط.
- dQ(W)/dW = 0 almost everywhere, so g_W = dL/dQ(W) · dQ(W)/dW = 0 and nothing learns. STE treats Q as the identity in the backward pass: g_W = dL/dQ(W), and likewise g_Y = dL/dQ(Y).dQ(W)/dW = 0 تقريباً في كل مكان، لذلك g_W = dL/dQ(W) · dQ(W)/dW = 0 ولا يتعلم شيء. الـ STE يعامل Q كدالة الهوية (identity) في الـ backward pass: g_W = dL/dQ(W)، وبالمثل g_Y = dL/dQ(Y).
- INT8 on MobileNetV1: PTQ 0.1% (asymmetric per-tensor) and 59.1% (symmetric per-channel) become 70.0% and 70.7% with QAT, against 70.9% in FP.عند INT8 على MobileNetV1: نتائج PTQ وهي 0.1% (asymmetric per-tensor) و59.1% (symmetric per-channel) تصبح 70.0% و70.7% مع QAT، مقابل 70.9% بالـ FP.
Sourcesالمصادر
- Quantizing deep convolutional networks for efficient inference: A whitepaper (R. Krishnamoorthi)PaperarXiv 2018Table 4 (PTQ vs QAT at INT8); simulated quantization with an FP weight copy; clipped STE (equations 14 and 15); fine-tuning an FP checkpoint beats training from scratch; FP weights converge to decision boundaries.الجدول 4 (PTQ مقابل QAT عند INT8)؛ الـ simulated quantization مع نسخة أوزان FP؛ الـ STE المقصوص (المعادلتان 14 و15)؛ الـ fine-tuning لـ checkpoint بالـ FP يتفوق على التدريب من الصفر؛ أوزان الـ FP تتقارب نحو حدود القرار.(opens in a new tab)(يفتح في تبويب جديد)
- Deep Compression: Compressing Deep Neural Networks with Pruning, Trained Quantization and Huffman Coding (Han, Mao, Dally)PaperICLR 2016Retraining fine-tunes the shared centroids after weight sharing.إعادة التدريب تجري fine-tuning للـ centroids المشتركة بعد مشاركة الأوزان (weight sharing).(opens in a new tab)(يفتح في تبويب جديد)
- Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation (Bengio, Léonard, Courville)PaperarXiv 2013Describes the straight-through estimator as copying the gradient of the output directly as the gradient of the input.يصف الـ straight-through estimator بأنه نسخ الـ gradient الخاص بالمخرج مباشرة ليكون الـ gradient الخاص بالمدخل.(opens in a new tab)(يفتح في تبويب جديد)
- Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference (Jacob et al.)PaperarXiv 2017Co-designed training procedure that simulates quantization to preserve accuracy after integer deployment.إجراء تدريب مصمَّم بالتوازي مع النشر يحاكي الـ quantization للحفاظ على الدقة بعد النشر بالأعداد الصحيحة.(opens in a new tab)(يفتح في تبويب جديد)
- BinaryConnect: Training Deep Neural Networks with binary weights during propagations (Courbariaux, Bengio, David)PaperNIPS 2015Quantized weights in both passes while gradients accumulate in full-precision stored weights.أوزان مكمَّمة في المسارين (forward و backward) بينما تتراكم الـ gradients في أوزان مخزَّنة بالدقة الكاملة.(opens in a new tab)(يفتح في تبويب جديد)
Part 06: Binary weights: sign, stochastic binarization and the BWN scaleالأوزان الثنائية: sign والتثنيث العشوائي ومقياس BWN
Pushing to 1 bit: if weights are only +1 or -1, a dot product needs only additions and subtractions, storage drops about 32x. Weights can be binarized deterministically with sign or stochastically with a hard sigmoid, and a single per-tensor scale alpha = mean |W| shrinks the error and nearly closes the accuracy gap.الوصول إلى بت واحد: إذا كانت الأوزان +1 أو -1 فقط، فإن الضرب النقطي يحتاج فقط إلى جمع وطرح، وينخفض التخزين نحو 32x. يمكن تثنيث الأوزان حتميًا بدالة sign أو عشوائيًا بدالة hard sigmoid، ومقياس واحد لكل موتر alpha = mean |W| يقلل الخطأ ويكاد يسد فجوة الدقة.
4 concepts4 مفاهيم, ، slides 49-54الشرائح 49-54
Why this part mattersلماذا يهمّ هذا الجزء
Parts 01 to 05 squeezed weights to 8, 4 and even 2 bits while keeping a multiply in every multiply-accumulate. This part asks the extreme question: what if each weight is a single bit? You will see that the multiply disappears, memory drops about 32×, and a single well-chosen scale factor rescues almost all of the accuracy.
The thread runs in four steps: where 1-bit weights sit in the quantization family, what they do to a dot product, the two ways to turn a real weight into a bit, and the Binary Weight Network scale that makes it work on ImageNet. For the COE 592 midterm expect a calculation (alpha, the sign matrix, a Frobenius error or a hard-sigmoid probability), a short derivation, and a compare question on deterministic versus stochastic binarization. For edge deployment, this is the bridge to part 07, where binarizing the activations too turns the remaining additions into XNOR and popcount.
ضغطت الأجزاء من 01 إلى 05 الأوزان إلى 8 و4 بل وحتى 2 بت، مع الإبقاء على عملية ضرب داخل كل عملية ضرب وتجميع (multiply-accumulate). هذا الجزء يطرح السؤال الأقصى: ماذا لو كان كل وزن بتًا واحدًا فقط؟ سترى أن الضرب يختفي، وأن الذاكرة تنخفض بنحو 32×، وأن معامل مقياس واحدًا مختارًا بعناية يستعيد كل الدقة تقريبًا.
يسير الخيط في أربع خطوات: أين تقع الأوزان ذات البت الواحد في عائلة التكميم، وماذا تفعل بحاصل الضرب النقطي، والطريقتان لتحويل وزن حقيقي إلى بت، ثم مقياس شبكة Binary Weight Network الذي يجعلها تعمل على ImageNet. في اختبار منتصف الفصل لمقرر COE 592 توقّع سؤالًا حسابيًا (قيمة alpha، أو مصفوفة الإشارات، أو خطأ Frobenius، أو احتمال hard sigmoid)، واشتقاقًا قصيرًا، وسؤال مقارنة بين التثنئة الحتمية والعشوائية. وبالنسبة للنشر على الأجهزة الطرفية (edge)، فهذا الجزء هو الجسر إلى الجزء 07، حيث تؤدي تثنئة التنشيطات أيضًا إلى تحويل عمليات الجمع المتبقية إلى XNOR وpopcount.
By the end you canفي نهاية هذا الجزء ستستطيع
- Place binary and ternary quantization in the storage and computation table next to K-means and linear quantization.تضع التكميم الثنائي والثلاثي في جدول التخزين والحساب بجانب تكميم K-means والتكميم الخطي.
- Evaluate a dot product with real and with binarized weights, and explain why multiplications disappear.تحسب حاصل الضرب النقطي بأوزان حقيقية ثم بأوزان مثنّاة، وتشرح لماذا تختفي عمليات الضرب.
- Justify the about 32x memory and about 2x computation savings of real-input, binary-weight layers.تبرّر توفير الذاكرة بنحو 32x وتوفير الحساب بنحو 2x في الطبقات ذات المدخلات الحقيقية والأوزان الثنائية.
- Apply deterministic sign binarization and stochastic hard-sigmoid binarization, including the r = 0 case.تطبّق التثنئة الحتمية بالإشارة sign والتثنئة العشوائية بالـ hard sigmoid، بما في ذلك حالة r = 0.
- Compute alpha = (1/n) ||W||_1, the binarized matrix and both squared Frobenius errors for the slide's 4 x 4 matrix.تحسب alpha = (1/n) ||W||_1 والمصفوفة المثنّاة وخطأي Frobenius المربّعين لمصفوفة الشريحة 4 x 4.
- Derive why alpha = mean |W| is the error-minimizing scale.تشتق لماذا يكون alpha = mean |W| هو المقياس الذي يجعل الخطأ أصغر ما يمكن.
Take the running 4 × 4 weight matrix of this course, the one that starts with 2.09, −0.98, 1.48, 0.09. Lecture 05-1 stored it four ways. As plain FP32 it costs 16 × 32 = 512 bits. K-means replaced each value with a 2-bit index into a four-entry floating-point codebook. Linear quantization stored 2-bit integers and rebuilt values as (q − Z) × S with Z = −1, S = 1.07. The fourth column of the recap slide keeps one bit per weight.
خذ مصفوفة الأوزان 4 × 4 المتكررة في هذا المقرر، تلك التي تبدأ بـ 2.09، −0.98، 1.48، 0.09. خزّنتها المحاضرة 05-1 بأربع طرق. بصيغة FP32 العادية تكلّف 16 × 32 = 512 بت. استبدل تكميم K-means كل قيمة بفهرس من 2 بت يشير إلى دفتر رموز (codebook) من أربع قيم عائمة. وخزّن التكميم الخطي أعدادًا صحيحة من 2 بت وأعاد بناء القيم بالعلاقة (q − Z) × S حيث Z = −1 وS = 1.07. أما العمود الرابع في شريحة المراجعة فيحتفظ ببت واحد لكل وزن.
| Schemeالطريقة | Storageالتخزين | Computationالحساب | Bits per weightالبتات لكل وزن |
|---|---|---|---|
| Full precisionالدقة الكاملة | Floating-point weightsأوزان بالفاصلة العائمة | Floating-point arithmeticحساب بالفاصلة العائمة | 32 bits32 بت |
| K-meansK-means | Integer indices plus a floating-point codebookفهارس صحيحة مع دفتر رموز بالفاصلة العائمة | Floating-point arithmeticحساب بالفاصلة العائمة | 2 bits plus codebook2 بت مع دفتر الرموز |
| Linearخطي | Integer weights (with S and Z)أوزان صحيحة (مع S وZ) | Integer arithmeticحساب بالأعداد الصحيحة | 2 to 8 bitsمن 2 إلى 8 بت |
| Binary or ternaryثنائي أو ثلاثي | Binary or ternary weightsأوزان ثنائية أو ثلاثية | Bit operations (add, subtract, XNOR)عمليات على البتات (جمع، طرح، XNOR) | 1 or 2 bits1 أو 2 بت |
Reading the table as a ladderقراءة الجدول كسُلّم
Read the table along two axes. The storage row shrinks from left to right, and so does the price of the arithmetic. K-means saves memory but still multiplies floats, because the codebook entries are floats. Linear quantization moves the multiply into cheap integer hardware. Binarization goes one step further: if every weight is +1 or −1, there is nothing left to multiply by, and the computation row becomes bit operations. That is why the slide labels the last column Bit Operations rather than integer arithmetic.
اقرأ الجدول على محورين. صف التخزين يصغر من اليسار إلى اليمين، وكذلك تكلفة العمليات الحسابية. تكميم K-means يوفّر الذاكرة لكنه ما زال يضرب أعدادًا عائمة، لأن مدخلات دفتر الرموز أعداد عائمة. والتكميم الخطي ينقل الضرب إلى عتاد الأعداد الصحيحة الرخيص. أما binarization (التثنئة) فتذهب خطوة أبعد: إذا كان كل وزن +1 أو −1 فلا يبقى شيء نضرب به، ويصبح صف الحساب عمليات على البتات. لهذا تسمّي الشريحة العمود الأخير Bit Operations (عمليات البتات) وليس حسابًا بالأعداد الصحيحة.
Look closely at the binary matrix on the recap slide: it shows 0 and 1, not −1 and +1. That is the stored bit pattern. The bit 1 encodes +1 and the bit 0 encodes −1. Row one, 1 0 1 1, is exactly the sign pattern +1 −1 +1 +1 of 2.09, −0.98, 1.48, 0.09, and the same holds for every row of the BWN matrix you will build in the last concept. Keep this encoding in mind, since part 07 uses it to turn dot products into XNOR and popcount.
انظر جيدًا إلى المصفوفة الثنائية في شريحة المراجعة: إنها تُظهر 0 و1، لا −1 و+1. هذا هو نمط البتات المخزّن. البت 1 يمثّل +1 والبت 0 يمثّل −1. الصف الأول 1 0 1 1 هو بالضبط نمط الإشارات +1 −1 +1 +1 للقيم 2.09, −0.98, 1.48, 0.09، والأمر نفسه ينطبق على كل صف في مصفوفة BWN التي ستبنيها في المفهوم الأخير. احفظ هذا الترميز في ذهنك، لأن الجزء 07 يستخدمه لتحويل حاصل الضرب النقطي إلى XNOR وpopcount.
Recall
Without looking, fill in the storage and computation rows for K-means, linear and binary quantization.دون النظر، املأ صفّي التخزين والحساب لتكميم K-means والتكميم الخطي والتكميم الثنائي.
K-means: integer indices and a floating-point codebook, floating-point arithmetic. Linear: integer weights, integer arithmetic. Binary or ternary: binary or ternary weights, bit operations. Only the last two change the arithmetic; K-means only saves memory.
K-means: فهارس صحيحة ودفتر رموز عائم، وحساب بالأعداد العائمة. الخطي: أوزان صحيحة وحساب بالأعداد الصحيحة. الثنائي أو الثلاثي: أوزان ثنائية أو ثلاثية وعمليات على البتات. الأخيران فقط يغيّران طريقة الحساب، أما K-means فيوفّر الذاكرة فقط.
Quick checkاختبار سريع
Which scheme stores integer codes yet still computes with floating-point arithmetic?أي طريقة تخزّن رموزًا صحيحة لكنها ما زالت تحسب بالفاصلة العائمة؟
Every fully connected or convolution layer reduces to dot products. Take one output neuron with weights [8, −3, 5, −1] and inputs [5, 2, 0, 1].
كل طبقة كاملة الاتصال (fully connected) أو طبقة التفاف (convolution) تُختزل إلى حواصل ضرب نقطية. خذ عصبون إخراج واحدًا أوزانه [8, −3, 5, −1] ومدخلاته [5, 2, 0, 1].
Now replace each weight by its sign: [+1, −1, +1, −1]. Multiplying by +1 is just keeping the input, and multiplying by −1 is just negating it. The product terms collapse to the inputs themselves, added or subtracted.
الآن استبدل كل وزن بإشارته: [+1, −1, +1, −1]. الضرب في +1 يعني ببساطة إبقاء المدخل كما هو، والضرب في −1 يعني ببساطة عكس إشارته. فتنهار حدود الضرب إلى المدخلات نفسها، مجموعة أو مطروحة.
Notice that the answer changed from 33 to 2. Signs alone throw away magnitudes, so the raw binary output is not an approximation of the real one in scale. The last concept of this part fixes this with a scale factor: α = (8 + 3 + 5 + 1)/4 = 4.25 would give 4.25 × 2 = 8.5, and the multiply by α happens once per output, not once per weight.
لاحظ أن الناتج تغيّر من 33 إلى 2. الإشارات وحدها تتخلص من المقادير، لذلك فإن الناتج الثنائي الخام ليس تقريبًا للناتج الحقيقي من حيث الحجم. يعالج المفهوم الأخير في هذا الجزء ذلك بمعامل مقياس: القيمة α = (8 + 3 + 5 + 1)/4 = 4.25 تعطي 4.25 × 2 = 8.5، والضرب في α يحدث مرة واحدة لكل مخرج، لا مرة لكل وزن.
Where the 32x and 2x come fromمن أين يأتي الرقمان 32x و2x
| Inputالمدخل | Weightالوزن | Operationsالعمليات | Memoryالذاكرة | Computationالحساب |
|---|---|---|---|---|
| ℝℝ | ℝℝ | + and ×+ و× | 1×1× | 1×1× |
| ℝℝ | 𝔹𝔹 | + and −+ و− | ≈32× lessأقل بنحو 32× | ≈2× lessأقل بنحو 2× |
- Memory, about 32×. An FP32 weight is 32 bits and a binary weight is 1 bit. It is "about" because a few full-precision numbers remain, such as a scale per layer or filter. For a layer of 1,000,000 weights plus one FP32 scale, the ratio is 32,000,000 / 1,000,032 ≈ 31.999.الذاكرة، نحو 32×. الوزن بصيغة FP32 يشغل 32 بت والوزن الثنائي يشغل 1 بت. نقول "نحو" لأن بعض الأعداد بالدقة الكاملة تبقى، مثل مقياس لكل طبقة أو لكل مرشّح (filter). لطبقة فيها 1,000,000 وزن ومقياس واحد بصيغة FP32، تكون النسبة 32,000,000 / 1,000,032 ≈ 31.999.
- Computation, about 2×. A dot product of length n costs n multiplications and about n additions. Binary weights delete the multiplications and keep the additions and subtractions, so the operation count roughly halves. The real saving in energy and chip area is larger, because a multiplier costs far more than an adder; BinaryConnect makes exactly this point.الحساب، نحو 2×. حاصل الضرب النقطي بطول n يكلّف n عملية ضرب ونحو n عملية جمع. الأوزان الثنائية تحذف عمليات الضرب وتُبقي الجمع والطرح، لذلك ينخفض عدد العمليات إلى النصف تقريبًا. أما التوفير الحقيقي في الطاقة ومساحة الشريحة فأكبر من ذلك، لأن الضارب (multiplier) يكلّف أكثر بكثير من الجامع (adder)، وهذه بالضبط النقطة التي تؤكدها ورقة BinaryConnect.
- Why not more than 2×? The inputs are still real numbers, so the additions are still full precision. Only when activations are binarized as well (the third row of the table, filled in part 07) do the additions become XNOR and popcount.لماذا لا يزيد عن 2×؟ المدخلات ما زالت أعدادًا حقيقية، لذلك تبقى عمليات الجمع بالدقة الكاملة. فقط عندما تُثنّى التنشيطات أيضًا (الصف الثالث في الجدول، الذي يُملأ في الجزء 07) تتحول عمليات الجمع إلى XNOR وpopcount.
Worked exampleمثال محلول
Memory of the slide's 4 x 4 matrixذاكرة مصفوفة الشريحة 4 x 4
FP32FP32
16 × 32 = 512 bits.16 × 32 = 512 بت.Binary weights onlyأوزان ثنائية فقط
16 × 1 = 16 bits, exactly 32× less.16 × 1 = 16 بت، أي أقل بمقدار 32× بالضبط.Binary weights plus one FP32 scaleأوزان ثنائية مع مقياس واحد بصيغة FP32
16 + 32 = 48 bits, so 512 / 48 ≈ 10.7×. The scale dominates in a tiny matrix but is negligible in a real layer.16 + 32 = 48 بت، إذن 512 / 48 ≈ 10.7×. المقياس يطغى في مصفوفة صغيرة جدًا، لكنه مهمل في طبقة حقيقية.Resultالنتيجة
The "about 32×" holds for real layer sizes, where one scale is spread over many weights.عبارة "نحو 32×" صحيحة لأحجام الطبقات الحقيقية، حيث يتوزع مقياس واحد على عدد كبير من الأوزان.
Recall
Why is the computation saving only about 2x while the memory saving is about 32x?لماذا يكون توفير الحساب نحو 2x فقط بينما توفير الذاكرة نحو 32x؟
Memory depends only on the weight bit width, which falls from 32 to 1. Computation counts operations: the n multiplications vanish but the n additions of real inputs remain, so the count roughly halves.
الذاكرة تعتمد فقط على عرض بتات الوزن، الذي ينخفض من 32 إلى 1. أما الحساب فيعدّ العمليات: عمليات الضرب الـ n تختفي، لكن عمليات الجمع الـ n على المدخلات الحقيقية تبقى، لذلك ينخفض العدد إلى النصف تقريبًا.
Quick checkاختبار سريع
A layer has real inputs and binary weights. Which pair of savings matches the lecture?طبقة مدخلاتها حقيقية وأوزانها ثنائية. أي زوج من التوفير يطابق المحاضرة؟
Suppose a weight has the real value r = 0.4. One option says: it is positive, so it becomes +1, every time. Another option says: it is positive but not by much, so make it +1 seven times out of ten and −1 three times out of ten. These are the two binarization rules on slide 53.
افترض أن وزنًا قيمته الحقيقية r = 0.4. خيار أول يقول: إنه موجب، إذن يصبح +1 في كل مرة. وخيار ثانٍ يقول: إنه موجب لكن ليس بفارق كبير، إذن اجعله +1 سبع مرات من عشر و−1 ثلاث مرات من عشر. هاتان هما قاعدتا التثنئة في الشريحة 53.
Deterministic binarization: a threshold at zeroالتثنئة الحتمية: عتبة عند الصفر
Deterministic binarization compares the value with a threshold, almost always 0, and outputs the sign.
Deterministic binarization (التثنئة الحتمية) تقارن القيمة بعتبة، وهي 0 في الغالب تقريبًا، وتُخرج الإشارة.
The ≥ matters. Mathematically sign(0) = 0, but a binary weight has no zero level, so this convention sends r = 0 to +1. In the slide matrix the two zeros, at row 3 column 3 and row 4 column 2, both become +1. In hardware the rule is free: for a floating-point or two's complement number the sign bit already is the answer.
العلامة ≥ مهمة. رياضيًا sign(0) = 0، لكن الوزن الثنائي ليس له مستوى صفري، لذلك يرسل هذا الاصطلاح r = 0 إلى +1. في مصفوفة الشريحة يتحول الصفران، في الصف 3 العمود 3 وفي الصف 4 العمود 2، كلاهما إلى +1. وفي العتاد هذه القاعدة مجانية: في العدد العائم أو العدد بصيغة المتمم الثنائي (two's complement) يكون بت الإشارة هو الجواب نفسه.
Stochastic binarization: a coin weighted by the valueالتثنئة العشوائية: عملة مرجّحة بالقيمة
Stochastic binarization draws the bit at random, with a probability set by the value. In BinaryConnect (Courbariaux, Bengio and David, NeurIPS 2015) the probability is the hard sigmoid.
Stochastic binarization (التثنئة العشوائية) تسحب البت عشوائيًا باحتمال تحدده القيمة. في BinaryConnect (Courbariaux و Bengio و David، مؤتمر NeurIPS 2015) يكون هذا الاحتمال هو دالة hard sigmoid.
The hard sigmoid is a straight ramp clipped to [0, 1]: 0 for r ≤ −1, 1 for r ≥ 1, and the line (r + 1)/2 in between. BinaryConnect picked it over the smooth sigmoid because it is far cheaper to compute, in software and in hardware.
دالة hard sigmoid منحدر مستقيم مقصوص إلى المجال [0, 1]: قيمتها 0 عندما r ≤ −1، و1 عندما r ≥ 1، والخط (r + 1)/2 بينهما. اختارتها BinaryConnect بدل دالة sigmoid الناعمة لأنها أرخص بكثير في الحساب، برمجيًا وفي العتاد.
Worked exampleمثال محلول
Stochastic binarization of four weightsالتثنئة العشوائية لأربعة أوزان
r = 0.4r = 0.4
σ = (0.4 + 1)/2 = 0.7. So q = +1 with probability 0.7, −1 with 0.3.σ = (0.4 + 1)/2 = 0.7. إذن q = +1 باحتمال 0.7، و−1 باحتمال 0.3.r = −0.4r = −0.4
σ = 0.6/2 = 0.3. Mostly −1, but +1 three times in ten.σ = 0.6/2 = 0.3. غالبًا −1، لكن +1 ثلاث مرات من عشر.r = 0r = 0
σ = 0.5: a fair coin. Compare with the deterministic rule, which always gives +1.σ = 0.5: عملة عادلة. قارن ذلك بالقاعدة الحتمية التي تعطي دائمًا +1.r = 1.5 and r = −2r = 1.5 و r = −2
Clipped: σ(1.5) = 1 and σ(−2) = 0, so both are certain and agree with sign(r).مقصوصتان: σ(1.5) = 1 وσ(−2) = 0، إذن كلتاهما مؤكدة وتتفق مع sign(r).Resultالنتيجة
Inside [−1, 1] the expected bit is E[q] = p − (1 − p) = 2p − 1 = r. For r = 0.4, E[q] = 0.7 − 0.3 = 0.4.داخل المجال [−1, 1] تكون القيمة المتوقعة للبت E[q] = p − (1 − p) = 2p − 1 = r. عند r = 0.4: E[q] = 0.7 − 0.3 = 0.4.
That last line is the whole reason for the randomness. On average the stochastic bit equals the real weight, so rounding errors on different weights and different mini-batches cancel instead of piling up, in the same spirit as DropConnect noise. BinaryConnect also clips the stored real weights to [−1, 1] after each update, which is exactly the range where E[q] = r holds.
هذا السطر الأخير هو السبب الكامل للعشوائية. في المتوسط يساوي البت العشوائي الوزن الحقيقي، لذلك تُلغي أخطاء التقريب في الأوزان المختلفة والدفعات الصغيرة (mini-batches) المختلفة بعضها بعضًا بدل أن تتراكم، بروح ضجيج DropConnect نفسها. كما تقصّ BinaryConnect الأوزان الحقيقية المخزّنة إلى المجال [−1, 1] بعد كل تحديث، وهو بالضبط المجال الذي تتحقق فيه E[q] = r.
Drag r below and watch p, 1 − p and the expected value move, while the deterministic answer only flips at zero.
اسحب r في الأسفل وراقب كيف تتحرك p و1 − p والقيمة المتوقعة، بينما لا يتغير الجواب الحتمي إلا عند الصفر.
| Deterministicالحتمية | Stochastic (BinaryConnect)العشوائية (BinaryConnect) | |
|---|---|---|
| Ruleالقاعدة | q = sign(r)q = sign(r) | q = +1 with p = σ(r), else −1q = +1 باحتمال p = σ(r)، وإلا −1 |
| Same input twiceالمدخل نفسه مرتين | Same output every timeالمخرج نفسه في كل مرة | Can give different outputsقد يعطي مخرجات مختلفة |
| Value at r = 0القيمة عند r = 0 | +1+1 | +1 or −1, each with p = 0.5+1 أو −1، لكل منهما p = 0.5 |
| Expected valueالقيمة المتوقعة | sign(r)sign(r) | 2p − 1 = r for |r| ≤ 12p − 1 = r عندما |r| ≤ 1 |
| Hardware costتكلفة العتاد | One comparator (read the sign bit)مقارن واحد (قراءة بت الإشارة) | Needs a random number per weightيحتاج رقمًا عشوائيًا لكل وزن |
| Typical useالاستخدام المعتاد | Inference and most trainingالاستدلال ومعظم التدريب | Training as a regularizer (BinaryConnect)التدريب كمنظِّم (BinaryConnect) |
Why the deterministic rule wins in practiceلماذا تفوز القاعدة الحتمية عمليًا
The BinaryNet paper (Courbariaux et al., 2016) states the trade-off plainly: stochastic binarization is more appealing in theory, but harder to implement because the hardware must generate random bits every time it quantizes. A random number generator per weight is area, energy and latency that a tiny edge accelerator would rather not spend. So inference uses sign, and the stochastic form, if used at all, lives in training, where it acts as a regularizer.
ورقة BinaryNet (Courbariaux وزملاؤه، 2016) تذكر المفاضلة بوضوح: التثنئة العشوائية أكثر جاذبية نظريًا، لكنها أصعب في التنفيذ لأن العتاد يجب أن يولّد بتات عشوائية في كل مرة يكمّم فيها. مولّد أرقام عشوائية لكل وزن يعني مساحة وطاقة وزمن تأخير يفضّل مسرّع طرفي صغير ألا يدفعها. لذلك يستخدم الاستدلال (inference) دالة sign، أما الصيغة العشوائية، إن استُخدمت أصلًا، فمكانها التدريب حيث تعمل كمنظِّم (regularizer).
Recall
What is P(q = +1) for r = -0.6, r = 0 and r = 3 under stochastic binarization?ما قيمة P(q = +1) عند r = -0.6 و r = 0 و r = 3 في التثنئة العشوائية؟
σ(−0.6) = 0.4/2 = 0.2, σ(0) = 0.5, and σ(3) = min(2, 1) = 1. Deterministic binarization would give −1, +1 and +1.
σ(−0.6) = 0.4/2 = 0.2، وσ(0) = 0.5، وσ(3) = min(2, 1) = 1. أما التثنئة الحتمية فستعطي −1 و+1 و+1.
Quick checkاختبار سريع
Why does the lecture call stochastic binarization harder to implement than deterministic binarization?لماذا تصف المحاضرة التثنئة العشوائية بأنها أصعب في التنفيذ من التثنئة الحتمية؟
Binarize four small, realistic weights: [0.02, −0.05, 0.03, −0.01]. The signs are [+1, −1, +1, −1], and the squared error is 0.98² + 0.95² + 0.97² + 0.99² ≈ 3.78. The weights themselves only have energy 0.0039, so setting them all to zero would be about a thousand times closer. The signs are right; the size is absurd. A single scale fixes it: α = (0.02 + 0.05 + 0.03 + 0.01)/4 = 0.0275 gives ±0.0275 and an error of only 0.000875.
ثنِّ أربعة أوزان صغيرة واقعية: [0.02, −0.05, 0.03, −0.01]. الإشارات هي [+1, −1, +1, −1]، والخطأ المربّع 0.98² + 0.95² + 0.97² + 0.99² ≈ 3.78. أما طاقة الأوزان نفسها فلا تتجاوز 0.0039، لذلك فإن جعلها كلها أصفارًا سيكون أقرب بنحو ألف مرة. الإشارات صحيحة، لكن الحجم سخيف. مقياس واحد يصلح ذلك: α = (0.02 + 0.05 + 0.03 + 0.01)/4 = 0.0275 يعطي ±0.0275 وخطأً قدره 0.000875 فقط.
The Binary Weight Network ruleقاعدة Binary Weight Network
The Binary Weight Network (BWN) of XNOR-Net (Rastegari et al., ECCV 2016) approximates the real tensor as a scale times a sign tensor. The sign is kept from deterministic binarization, and the scale is the mean absolute value.
شبكة Binary Weight Network في ورقة XNOR-Net (Rastegari وزملاؤه، مؤتمر ECCV 2016) تقرّب الموتر الحقيقي بمقياس مضروب في موتر إشارات. الإشارة مأخوذة من التثنئة الحتمية، والمقياس هو متوسط القيم المطلقة.
The scale is stored as one FP32 number and applied once to the output of the dot product, so it costs one multiply per output, not per weight. The XNOR-Net paper later reuses the same idea for activations.
يُخزَّن المقياس كعدد واحد بصيغة FP32 ويُطبَّق مرة واحدة على ناتج حاصل الضرب النقطي، لذلك يكلّف عملية ضرب واحدة لكل مخرج، لا لكل وزن. وتعيد ورقة XNOR-Net لاحقًا استخدام الفكرة نفسها مع التنشيطات.
Worked exampleمثال محلول
BWN on the slide's 4 x 4 matrixBWN على مصفوفة الشريحة 4 x 4
Write down Wاكتب W
[[2.09, −0.98, 1.48, 0.09], [0.05, −0.14, −1.08, 2.12], [−0.91, 1.92, 0, −1.03], [1.87, 0, 1.53, 1.49]][[2.09, −0.98, 1.48, 0.09], [0.05, −0.14, −1.08, 2.12], [−0.91, 1.92, 0, −1.03], [1.87, 0, 1.53, 1.49]]Binarize with signثنِّ باستخدام sign
W^B = [[1, −1, 1, 1], [1, −1, −1, 1], [−1, 1, 1, −1], [1, 1, 1, 1]]. The zeros at (3, 3) and (4, 2) become +1.W^B = [[1, −1, 1, 1], [1, −1, −1, 1], [−1, 1, 1, −1], [1, 1, 1, 1]]. الصفران في الموضعين (3, 3) و(4, 2) يصبحان +1.L1 normنُظيم L1
Row sums of absolute values: 4.64 + 3.39 + 3.86 + 4.89 = 16.78.مجاميع القيم المطلقة لكل صف: 4.64 + 3.39 + 3.86 + 4.89 = 16.78.Scaleالمقياس
α = 16.78 / 16 = 1.04875 ≈ 1.05.α = 16.78 / 16 = 1.04875 ≈ 1.05.Error without the scaleالخطأ دون المقياس
‖W − W^B‖²_F = 9.28 (exactly 9.2832).‖W − W^B‖²_F = 9.28 (بالضبط 9.2832).Error with the scaleالخطأ مع المقياس
‖W − αW^B‖²_F = 9.245 (exactly 9.2452).‖W − αW^B‖²_F = 9.245 (بالضبط 9.2452).Resultالنتيجة
The scale always helps or ties. Here the gain is small because the mean magnitude 1.05 is already close to 1; for real weights, which are typically far smaller than 1, the gain is huge, as the opening example showed.المقياس دائمًا يحسّن الخطأ أو يساويه. هنا المكسب صغير لأن متوسط المقدار 1.05 قريب أصلًا من 1، أما في الأوزان الحقيقية، التي تكون عادة أصغر بكثير من 1، فالمكسب هائل، كما أظهر المثال الافتتاحي.
| Approximationالتقريب | Scaleالمقياس | Squared errorالخطأ المربّع | Whyالسبب |
|---|---|---|---|
| sign(W)sign(W) | 11 | 9.289.28 | Every cell is ±1, far from 2.09 or 0.05كل خلية ±1، بعيدة عن 2.09 أو 0.05 |
| α · sign(W)α · sign(W) | 1.048751.04875 | 9.2459.245 | Cells are ±1.05, the best a single scale can doالخلايا ±1.05، أفضل ما يستطيعه مقياس واحد |
Why alpha is the mean of |W|لماذا تكون alpha متوسط |W|
This is the derivation from XNOR-Net and a natural exam question. Write the error for a fixed sign vector B ∈ {+1, −1}ⁿ and expand.
هذا هو الاشتقاق من ورقة XNOR-Net، وهو سؤال امتحان طبيعي. اكتب الخطأ لمتجه إشارات ثابت B ∈ {+1, −1}ⁿ ثم افكّه.
- For any positive α, the error is smallest when WᵀB is largest. Each term w_i b_i is largest when b_i has the sign of w_i, so B* = sign(W) and WᵀB* = Σ|w_i| = ‖W‖₁.لأي α موجبة، يكون الخطأ أصغر ما يمكن عندما يكون WᵀB أكبر ما يمكن. كل حد w_i b_i يكون أكبر ما يمكن عندما تحمل b_i إشارة w_i، إذن B* = sign(W) وWᵀB* = Σ|w_i| = ‖W‖₁.
- Differentiate in α: dJ/dα = 2αn − 2‖W‖₁. Setting it to zero gives α* = ‖W‖₁ / n, the mean absolute weight. The second derivative 2n is positive, so this is a minimum.اشتق بالنسبة إلى α: dJ/dα = 2αn − 2‖W‖₁. مساواتها بالصفر تعطي α* = ‖W‖₁ / n، أي متوسط القيمة المطلقة للأوزان. والمشتقة الثانية 2n موجبة، إذن هذه قيمة صغرى.
- Substituting back gives the minimum error J* = WᵀW − ‖W‖₁² / n. On the slide matrix: 26.8432 − 16.78² / 16 = 26.8432 − 17.5980 = 9.2452, matching the worked example.بالتعويض نحصل على أصغر خطأ J* = WᵀW − ‖W‖₁² / n. على مصفوفة الشريحة: 26.8432 − 16.78² / 16 = 26.8432 − 17.5980 = 9.2452، وهو مطابق للمثال المحلول.
What the scale buys on ImageNetماذا يكسب المقياس على ImageNet
XNOR-Net trained AlexNet three ways on ImageNet. Full precision reached 56.6% top-1. BinaryConnect, signs with no scale, reached 35.4%, a drop of 21.2 points. BWN, the same signs plus α, reached 56.8%, 0.2 points above full precision. The paper also tried learning the scale as a separate layer instead of computing it with the formula and got only 46.2%, so the closed-form α is not a detail.
درّبت ورقة XNOR-Net شبكة AlexNet بثلاث طرق على ImageNet. الدقة الكاملة وصلت إلى 56.6% في top-1. وBinaryConnect، أي إشارات بلا مقياس، وصلت إلى 35.4%، بانخفاض 21.2 نقطة. وBWN، أي الإشارات نفسها مع α، وصلت إلى 56.8%، أي أعلى من الدقة الكاملة بـ 0.2 نقطة. وجرّبت الورقة أيضًا تعلّم المقياس كطبقة مستقلة بدل حسابه بالصيغة، فلم تحصل إلا على 46.2%، لذلك فإن α بالصيغة المغلقة ليست تفصيلًا ثانويًا.
Recall
Compute alpha and the sign vector for W = [0.6, -0.2, 0, -1.0].احسب alpha ومتجه الإشارات للمتجه W = [0.6, -0.2, 0, -1.0].
sign(W) = [+1, −1, +1, −1] (the zero becomes +1). α = (0.6 + 0.2 + 0 + 1.0)/4 = 0.45, so αW^B = [0.45, −0.45, 0.45, −0.45].
sign(W) = [+1, −1, +1, −1] (الصفر يصبح +1). α = (0.6 + 0.2 + 0 + 1.0)/4 = 0.45، إذن αW^B = [0.45, −0.45, 0.45, −0.45].
Recall
Why does BWN almost match full precision on AlexNet while BinaryConnect loses 21.2 points?لماذا تكاد BWN تطابق الدقة الكاملة على AlexNet بينما تخسر BinaryConnect نحو 21.2 نقطة؟
Both use the same signs, but BinaryConnect has no scale, so every weight is forced to magnitude 1. BWN multiplies by α = mean |W|, the error-minimizing scale, which restores the right magnitude per filter and closes the gap.
كلتاهما تستخدم الإشارات نفسها، لكن BinaryConnect بلا مقياس، فيُجبَر كل وزن على المقدار 1. أما BWN فتضرب في α = mean |W|، المقياس الذي يجعل الخطأ أصغر ما يمكن، فتستعيد المقدار الصحيح لكل مرشّح وتسدّ الفجوة.
Quick checkاختبار سريع
For W = [2, -1, 0, -1], what are alpha and the binarized weights alpha times sign(W)?للمتجه W = [2, -1, 0, -1]، ما قيمة alpha وما الأوزان المثنّاة alpha مضروبة في sign(W)؟
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- Binary and ternary quantization store 1 or 2 bit weights and compute with bit operations, the far end of the table that starts at FP32 and passes through K-means and linear quantization.التكميم الثنائي والثلاثي يخزّن أوزانًا من 1 أو 2 بت ويحسب بعمليات البتات، وهو الطرف الأقصى من الجدول الذي يبدأ بـ FP32 ويمر بتكميم K-means والتكميم الخطي.
- Real dot product: 8x5 + (-3)x2 + 5x0 + (-1)x1 = 33. With weights [1, -1, 1, -1] it becomes 5 - 2 + 0 - 1 = 2, using only additions and subtractions.حاصل الضرب النقطي الحقيقي: 8x5 + (-3)x2 + 5x0 + (-1)x1 = 33. ومع الأوزان [1, -1, 1, -1] يصبح 5 - 2 + 0 - 1 = 2، باستخدام الجمع والطرح فقط.
- Real input, binary weight: about 32x less weight memory (32 bits to 1) and about 2x less computation (the n multiplications vanish, the n additions stay).مدخلات حقيقية وأوزان ثنائية: ذاكرة أوزان أقل بنحو 32x (من 32 بت إلى 1) وحساب أقل بنحو 2x (تختفي عمليات الضرب الـ n وتبقى عمليات الجمع الـ n).
- Deterministic: q = sign(r), +1 for r >= 0 and -1 for r < 0, so zero maps to +1.الحتمية: q = sign(r)، أي +1 عندما r >= 0 و -1 عندما r < 0، لذلك يتحول الصفر إلى +1.
- Stochastic (BinaryConnect): q = +1 with probability sigma(r) = min(max((r + 1)/2, 0), 1). At r = 0.4, p = 0.7. E[q] = r inside [-1, 1]. Needs random bits, so it is harder in hardware.العشوائية (BinaryConnect): q = +1 باحتمال sigma(r) = min(max((r + 1)/2, 0), 1). عند r = 0.4 يكون p = 0.7. وE[q] = r داخل [-1, 1]. تحتاج بتات عشوائية، لذلك هي أصعب في العتاد.
- BWN: W^B = sign(W), alpha = (1/n)||W||_1. On the slide matrix sum |W| = 16.78, alpha = 1.04875 (about 1.05), error 9.28 for sign only and 9.245 with alpha.BWN: W^B = sign(W) و alpha = (1/n)||W||_1. في مصفوفة الشريحة sum |W| = 16.78 و alpha = 1.04875 (تقريبًا 1.05)، والخطأ 9.28 بالإشارة وحدها و 9.245 مع alpha.
- alpha = mean |W| comes from setting d/d alpha of ||W - alpha sign(W)||^2 = 2 alpha n - 2 ||W||_1 to zero.تأتي alpha = mean |W| من مساواة مشتقة ||W - alpha sign(W)||^2 بالنسبة إلى alpha، وهي 2 alpha n - 2 ||W||_1، بالصفر.
- AlexNet on ImageNet, top-1 versus full precision: BinaryConnect -21.2 points, BWN +0.2 points.شبكة AlexNet على ImageNet، دقة top-1 مقارنة بالدقة الكاملة: BinaryConnect تخسر 21.2 نقطة، و BWN تكسب 0.2 نقطة.
Sourcesالمصادر
- BinaryConnect: Training Deep Neural Networks with binary weights during propagationsPaperCourbariaux, Bengio and David, NeurIPS 2015Deterministic sign with w >= 0 to +1, stochastic binarization with the hard sigmoid clip((x+1)/2, 0, 1), multiply-accumulate replaced by additions and subtractions, weight clipping to [-1, 1]الإشارة الحتمية مع تحويل w >= 0 إلى +1، والتثنئة العشوائية بدالة hard sigmoid أي clip((x+1)/2, 0, 1)، واستبدال الضرب والتجميع بعمليات جمع وطرح، وقصّ الأوزان إلى [-1, 1](opens in a new tab)(يفتح في تبويب جديد)
- Binarized Neural Networks: Training Deep Neural Networks with Weights and Activations Constrained to +1 or -1PaperCourbariaux, Hubara, Soudry, El-Yaniv and Bengio, 2016Stochastic binarization is harder to implement because hardware must generate random bits, so the deterministic sign is usedالتثنئة العشوائية أصعب في التنفيذ لأن العتاد يجب أن يولّد بتات عشوائية، لذلك تُستخدم الإشارة الحتمية(opens in a new tab)(يفتح في تبويب جديد)
- XNOR-Net: ImageNet Classification Using Binary Convolutional Neural NetworksPaperRastegari, Ordonez, Redmon and Farhadi, ECCV 2016BWN derivation B* = sign(W), alpha* = ||W||_1 / n, about 32x memory saving, AlexNet top-1: BWN 56.8, BC 35.4, full precision 56.6, separate-layer alpha 46.2اشتقاق BWN: B* = sign(W) و alpha* = ||W||_1 / n، وتوفير في الذاكرة بنحو 32x، ودقة top-1 لشبكة AlexNet: BWN 56.8 و BC 35.4 والدقة الكاملة 56.6 و alpha كطبقة مستقلة 46.2(opens in a new tab)(يفتح في تبويب جديد)
- A Survey of Quantization Methods for Efficient Neural Network InferencePaperGholami, Kim, Dong, Yao, Mahoney and Keutzer, 2021Section on extreme quantization: binarization and ternarization, BinaryConnect, BWN and XNOR-Net in contextقسم التكميم المتطرف: التثنئة والتثليث، و BinaryConnect و BWN و XNOR-Net في سياقها(opens in a new tab)(يفتح في تبويب جديد)
Part 07: Binary weights and activations: XNOR and popcountالأوزان والتنشيطات الثنائية: XNOR وpopcount
When activations are binarized too, each multiply of +1/-1 values becomes an XNOR on bits, and the sum becomes a popcount. The identity y = -n + 2 * popcount(W xnor x) turns a dot product into two cheap bit operations, giving about 32x less memory and about 58x less computation.عندما تُثنَّث التنشيطات أيضًا، يصبح كل ضرب لقيم +1/-1 عملية XNOR على البتات، ويصبح المجموع popcount. المتطابقة y = -n + 2 * popcount(W xnor x) تحوّل الضرب النقطي إلى عمليتي بت رخيصتين، مما يعطي ذاكرة أقل بنحو 32x وحسابًا أقل بنحو 58x.
4 concepts4 مفاهيم, ، slides 55-60الشرائح 55-60
Why this part mattersلماذا يهمّ هذا الجزء
Part 6 binarized the weights and kept the activations real, which turned every multiply into an add or a subtract. This part goes all the way: weights and activations are both +1 or -1. Then a dot product stops being arithmetic at all. It becomes two bit operations on packed words, XNOR and popcount, plus one shift and one add.
The whole part runs on one example from the slides: W = [1, -1, 1, -1] and x = [1, 1, -1, 1], with n = 4 and true answer -2. You will watch a naive bit trick get the wrong answer (1), repair it with a one-line derivation, and then price the result in memory and compute. For the midterm, expect to derive the formula, evaluate it on given vectors, justify the XNOR truth table, and quote the cost numbers with their caveats. For embedded work, this is the reason a binarized network can run on a microcontroller with no floating-point unit.
في الجزء 6 حوّلنا الأوزان إلى قيم ثنائية (binarized) وأبقينا الـ activations حقيقية، فتحوّل كل ضرب إلى عملية جمع أو طرح. هذا الجزء يذهب إلى النهاية: الأوزان والـ activations كلاهما إما +1 أو -1. عندها يتوقف الـ dot product عن كونه عملية حسابية أصلًا، ويصبح عمليتين على البتات فوق كلمات مضغوطة (packed words)، هما XNOR وpopcount، إضافة إلى إزاحة (shift) واحدة وعملية جمع واحدة.
الجزء كله يدور حول مثال واحد من الشرائح: W = [1, -1, 1, -1] وx = [1, 1, -1, 1]، مع n = 4 والإجابة الصحيحة -2. ستشاهد حيلة بتات ساذجة تعطي إجابة خاطئة (1)، ثم تصلحها باشتقاق من سطر واحد، ثم تقدّر تكلفة النتيجة من حيث الذاكرة والحساب. في الاختبار النصفي توقّع أن يُطلب منك اشتقاق الصيغة، وحسابها على متجهات معطاة، وتبرير جدول حقيقة XNOR، وذكر أرقام التكلفة مع شروطها. وفي العمل على الأنظمة المدمجة (embedded)، هذا هو السبب الذي يجعل شبكة ثنائية تعمل على microcontroller لا يحتوي على وحدة فاصلة عائمة (floating-point unit).
By the end you canفي نهاية هذا الجزء ستستطيع
- Compute a dot product between two ±1 vectors by hand, and say why it needs no multiplier.تحسب يدويًا الـ dot product بين متجهين قيمهما ±1، وتشرح لماذا لا يحتاج إلى أي multiplier.
- Explain, with the two truth tables, why XNOR on the bit encoding reproduces the product of signs.تشرح باستخدام جدولَي الحقيقة لماذا تعيد عملية XNOR على الترميز الثنائي (bits) إنتاج حاصل ضرب الإشارات.
- Derive y = -n + 2 · popcount(W xnor x) from first principles, and explain why summing XNOR bits alone is wrong.تشتق y = -n + 2 · popcount(W xnor x) من المبادئ الأساسية، وتشرح لماذا يكون جمع بتات XNOR وحدها خاطئًا.
- Evaluate the hardware form -n + (popcount << 1) on packed bit words, with the shift applied to the popcount only.تحسب الصيغة العتادية -n + (popcount << 1) على كلمات بتات مضغوطة (packed words)، مع تطبيق الإزاحة (shift) على الـ popcount وحده.
- Quote and qualify the cost table: about 32x less memory, about 2x less compute for binary weights, about 58x for binary weights and inputs.تذكر جدول التكلفة مع شروطه: ذاكرة أقل بنحو 32x، وحساب أقل بنحو 2x للأوزان الثنائية، ونحو 58x للأوزان والمدخلات الثنائية معًا.
Take one row of a weight matrix, [8, -3, 5, -1], and an input column, [5, 2, 0, 1]. In full precision the output is 8·5 - 3·2 + 5·0 - 1·1 = 33: four multiplies and three adds on 32-bit floats. Now apply Binarization to both sides. The weight row becomes [1, -1, 1, -1] and the slide turns the input into [1, 1, -1, 1].
خذ صفًا واحدًا من مصفوفة أوزان، [8, -3, 5, -1]، وعمود مدخلات، [5, 2, 0, 1]. بالدقة الكاملة يكون الناتج 8·5 - 3·2 + 5·0 - 1·1 = 33: أربع عمليات ضرب وثلاث عمليات جمع على أعداد عائمة بطول 32-bit. الآن طبّق الـ Binarization على الطرفين. يصبح صف الأوزان [1, -1, 1, -1]، وتحوّل الشريحة المدخلات إلى [1, 1, -1, 1].
Look at what each product can be. Two signs multiplied give a sign: +1 when they agree and -1 when they differ. No product is ever 0, 2 or 0.7. So the result is fully determined by one number: how many positions agree. That observation is the whole part. Everything after it is a way of counting agreements cheaply.
انظر إلى القيم الممكنة لكل حاصل ضرب. ضرب إشارتين يعطي إشارة: +1 عندما تتفقان و-1 عندما تختلفان. لا يكون أي حاصل ضرب 0 أو 2 أو 0.7 أبدًا. لذلك تتحدد النتيجة بالكامل برقم واحد: عدد المواضع التي تتفق فيها الإشارتان. هذه الملاحظة هي الجزء كله، وكل ما يأتي بعدها مجرد طريقة رخيصة لعدّ التطابقات.
This is the setting of XNOR-Net (Rastegari et al., ECCV 2016) and of the Binarized Neural Network (BNN) of Courbariaux, Hubara and colleagues, which appeared the same year. Compared with the Binary Weight Network (BWN) of part 6, the difference is the input side: the activations are binarized too, usually with the same Deterministic binarization, so both operands of every multiply-accumulate are one bit.
هذا هو إطار XNOR-Net (Rastegari et al., ECCV 2016) وإطار الـ Binarized Neural Network (BNN) لـ Courbariaux وHubara وزملائهما، التي ظهرت في السنة نفسها. مقارنةً بالـ Binary Weight Network (BWN) في الجزء 6، الفرق في جانب المدخلات: الـ activations تصبح ثنائية أيضًا، عادةً بنفس الـ Deterministic binarization، فيكون كلا معاملَي كل عملية multiply-accumulate بتًا واحدًا.
Recall
Why does a dot product of two ±1 vectors depend only on how many positions agree?لماذا يعتمد الـ dot product لمتجهين قيمهما ±1 فقط على عدد المواضع التي تتفق فيها الإشارتان؟
Each product is +1 if the two signs agree and -1 if they differ, so the sum is (agreements) minus (disagreements). With n fixed, the number of agreements alone determines it.
A processor does not store -1 in one bit. It stores 0 or 1. So pick an encoding: +1 becomes bit 1 and -1 becomes bit 0. The weight row [1, -1, 1, -1] packs into 1010 and the input [1, 1, -1, 1] into 1101. The question is which logic gate, applied to the bits, behaves like multiplication applied to the signs.
المعالج لا يخزّن -1 في بت واحد، بل يخزّن 0 أو 1. لذلك نختار ترميزًا: +1 يصبح البت 1، و-1 يصبح البت 0. يُضغط صف الأوزان [1, -1, 1, -1] إلى 1010، والمدخلات [1, 1, -1, 1] إلى 1101. والسؤال: أي بوابة منطقية (logic gate)، إذا طُبّقت على البتات، تتصرف مثل الضرب المطبّق على الإشارات؟
Line the two truth tables upضع جدولَي الحقيقة جنبًا إلى جنب
| WW | xx | W × xW × x | b_wb_w | b_xb_x | XNOR(b_w, b_x)XNOR(b_w, b_x) |
|---|---|---|---|---|---|
| +1+1 | +1+1 | +1+1 | 11 | 11 | 11 |
| +1+1 | -1-1 | -1-1 | 11 | 00 | 00 |
| -1-1 | -1-1 | +1+1 | 00 | 00 | 11 |
| -1-1 | +1+1 | -1-1 | 00 | 11 | 00 |
Read across each row. The product is +1 in rows one and three, where the signs agree. XNOR, the negation of exclusive OR, outputs 1 exactly when its two inputs are equal, which is again rows one and three. So under this encoding the product column and the XNOR column are the same column, with -1 written as 0. That is the precise sense in which XNOR replaces multiplication: it is an equality test, and the product of two signs is also an equality test.
اقرأ كل صف أفقيًا. حاصل الضرب يساوي +1 في الصفين الأول والثالث، حيث تتفق الإشارتان. والـ XNOR، وهي نفي الـ exclusive OR، تُخرج 1 بالضبط عندما يتساوى مدخلاها، أي في الصفين الأول والثالث مرة أخرى. إذن تحت هذا الترميز يكون عمود حاصل الضرب وعمود الـ XNOR العمود نفسه، مع كتابة -1 على شكل 0. هذا هو المعنى الدقيق لقولنا إن XNOR تحل محل الضرب: إنها اختبار تساوٍ، وحاصل ضرب إشارتين هو أيضًا اختبار تساوٍ.
The tempting shortcut that failsالاختصار المغري الذي يفشل
If XNOR is the product, surely the dot product is just the sum of the XNOR bits. Try it on the running example, pairing 1010 with 1101 position by position.
إذا كانت XNOR هي حاصل الضرب، فلا بد أن الـ dot product هو مجرد مجموع بتات الـ XNOR. جرّب ذلك على المثال الجاري، بمقابلة 1010 مع 1101 موضعًا بموضع.
The mapping is right element by element but wrong in aggregate, because the encoding is not a linear map that preserves sums. A disagreement should contribute -1, but its bit contributes 0. The sum of XNOR bits therefore counts the agreements and silently drops every disagreement. Here there is one agreement and three disagreements, so the true answer is 1 - 3 = -2 while the bit sum reports only the 1.
التحويل صحيح عنصرًا بعنصر لكنه خاطئ في المجموع، لأن الترميز ليس تحويلًا خطيًا يحافظ على المجاميع. عدم التطابق يجب أن يساهم بـ -1، لكن البت الخاص به يساهم بـ 0. لذلك فمجموع بتات الـ XNOR يعدّ التطابقات ويُسقط بصمت كل عدم تطابق. هنا يوجد تطابق واحد وثلاثة عدم تطابقات، فالإجابة الصحيحة 1 - 3 = -2، بينما مجموع البتات لا يُظهر إلا الـ 1.
Quick checkاختبار سريع
Under the encoding +1 → 1 and -1 → 0, which gate reproduces the product of two signs?تحت الترميز +1 → 1 و-1 → 0، أي بوابة تعيد إنتاج حاصل ضرب إشارتين؟
Recall
Sum the XNOR bits for W bits 1010 and x bits 1101. Why is the result not the dot product?اجمع بتات XNOR لبتات W وهي 1010 وبتات x وهي 1101. لماذا لا تكون النتيجة هي الـ dot product؟
1010 xnor 1101 = 1000, which sums to 1. It counts only the agreements; each of the three disagreements should subtract 1 but contributes 0, so the true value is 1 - 3 = -2.
Start from the worst case. Suppose every one of the n = 4 products were -1. The sum would be -4, which is -n. Now each position where the XNOR is 1 is a position whose product is really +1, not -1. Changing one term from -1 to +1 raises the sum by 2. The example has one such position, so the answer is -4 + 2 = -2. That is the blue line on slide 58.
ابدأ من أسوأ حالة. افترض أن كل واحد من حواصل الضرب الـ n = 4 يساوي -1. سيكون المجموع -4، أي -n. الآن، كل موضع تكون فيه الـ XNOR مساوية 1 هو موضع حاصل ضربه في الحقيقة +1 وليس -1. وتغيير حد واحد من -1 إلى +1 يرفع المجموع بمقدار 2. في المثال يوجد موضع واحد من هذا النوع، فتكون الإجابة -4 + 2 = -2. هذا هو الخط الأزرق في الشريحة 58.
The general ruleالقاعدة العامة
Write m for the number of matches, the positions where the signs agree. The other n - m positions are mismatches. Matches contribute +1 each and mismatches -1 each, so y = m - (n - m) = 2m - n. And m is exactly the number of 1 bits in the XNOR of the two packed words, which is what Popcount returns.
ليكن m عدد التطابقات، أي المواضع التي تتفق فيها الإشارتان. المواضع الأخرى وعددها n - m هي عدم تطابقات. كل تطابق يساهم بـ +1 وكل عدم تطابق بـ -1، لذلك y = m - (n - m) = 2m - n. وm هو بالضبط عدد البتات التي تساوي 1 في ناتج XNOR للكلمتين المضغوطتين، وهو ما تُرجعه عملية الـ Popcount.
The same identity drops out of the encoding algebraically. With s = 2b - 1 for each sign and bit, the product of two signs is 2 · XNOR(b_w, b_x) - 1 (check it: 2·1 - 1 = +1, 2·0 - 1 = -1). Summing over n positions gives 2 · Σ XNOR - n, the formula above. Either route is acceptable in an exam; the counting route is quicker to write and easier to defend.
المتطابقة نفسها تخرج جبريًا من الترميز. مع s = 2b - 1 لكل إشارة وبتها، يكون حاصل ضرب إشارتين 2 · XNOR(b_w, b_x) - 1 (تحقّق: 2·1 - 1 = +1، و2·0 - 1 = -1). والجمع على n موضعًا يعطي 2 · Σ XNOR - n، وهي الصيغة أعلاه. الطريقتان مقبولتان في الاختبار؛ وطريقة العدّ أسرع كتابةً وأسهل في الدفاع عنها.
Worked exampleمثال محلول
The slide example, n = 4مثال الشرائح، n = 4
Encodeالترميز
W = [1, -1, 1, -1] → 1010 and x = [1, 1, -1, 1] → 1101.
W = [1, -1, 1, -1] → 1010 وx = [1, 1, -1, 1] → 1101.XNORالـ XNOR
Position by position: 1,1 → 1, 0,1 → 0, 1,0 → 0, 0,1 → 0, so 1010 xnor 1101 = 1000.
موضعًا بموضع: 1,1 → 1، 0,1 → 0، 1,0 → 0، 0,1 → 0، إذن 1010 xnor 1101 = 1000.Popcountالـ Popcount
popcount(1000) = 1: one match.
popcount(1000) = 1: تطابق واحد.Correct for the mismatchesالتصحيح لعدم التطابقات
y = -4 + 2 × 1 = -2.
y = -4 + 2 × 1 = -2.Resultالنتيجة
-2, identical to 1 - 1 - 1 - 1 computed with real multiplies.-2، وهي مطابقة لـ 1 - 1 - 1 - 1 المحسوبة بعمليات ضرب حقيقية.
Worked exampleمثال محلول
Your turn first, then check: n = 8حاول بنفسك أولًا ثم تحقّق: n = 8
The vectorsالمتجهات
W = [1, 1, -1, 1, -1, -1, 1, 1] and x = [-1, 1, -1, 1, 1, -1, -1, 1].
W = [1, 1, -1, 1, -1, -1, 1, 1] وx = [-1, 1, -1, 1, 1, -1, -1, 1].Encodeالترميز
W → 11010011 and x → 01011001.
W → 11010011 وx → 01011001.XNORالـ XNOR
Matches at positions 2, 3, 4, 6, 8, so 11010011 xnor 01011001 = 01110101.
التطابقات في المواضع 2, 3, 4, 6, 8، إذن 11010011 xnor 01011001 = 01110101.Popcount and correctالـ Popcount ثم التصحيح
popcount = 5, so y = -8 + 2 × 5 = 2.
popcount = 5، إذن y = -8 + 2 × 5 = 2.Resultالنتيجة
Check with signs: products -1, 1, 1, 1, -1, 1, -1, 1 sum to 5 - 3 = 2.تحقّق بالإشارات: حواصل الضرب -1, 1, 1, 1, -1, 1, -1, 1 مجموعها 5 - 3 = 2.
Quick checkاختبار سريع
With W = [-1, 1, 1, -1], x = [1, 1, -1, -1] and n = 4, what does -n + 2 · popcount(W xnor x) give?مع W = [-1, 1, 1, -1] و x = [1, 1, -1, -1] و n = 4، ماذا يعطي -n + 2 · popcount(W xnor x)؟
Recall
Derive y = -n + 2 · popcount(W xnor x) without looking.اشتق y = -n + 2 · popcount(W xnor x) دون النظر.
Let m be the number of positions where the signs agree. Those products are +1, the other n - m are -1, so y = m - (n - m) = 2m - n. Under +1 → 1, -1 → 0, XNOR is 1 exactly where the signs agree, so m = popcount(W xnor x).
On real hardware the bits of W_i and x sit packed in machine words, 32 or 64 to a register. One XNOR instruction compares all of them at once, one popcount instruction counts the matches, and multiplying by 2 is a left shift by one bit. The slide writes the result as follows.
في العتاد الحقيقي تكون بتات W_i وx مضغوطة في كلمات الآلة (machine words)، 32 أو 64 بتًا في كل register. تعليمة XNOR واحدة تقارن جميعها دفعة واحدة، وتعليمة popcount واحدة تعدّ التطابقات، والضرب في 2 هو إزاحة لليسار (left shift) ببت واحد. وتكتب الشريحة النتيجة كما يلي.
On the slide example: popcount(1010 xnor 1101) = popcount(1000) = 1, then 1 << 1 = 2, then -4 + 2 = -2. In C, up to 64 elements take a handful of integer instructions: ~(w ^ x) for the XNOR (an XOR and a NOT on most CPUs), __builtin_popcountll for the count, a shift and an add. The BNN paper describes the GPU version as 32 connections evaluated with three instructions (accumulate, popcount, XNOR) taking about 6 clock cycles, a theoretical speedup of 32/6 ≈ 5.3 on that GPU.
على مثال الشرائح: popcount(1010 xnor 1101) = popcount(1000) = 1، ثم 1 << 1 = 2، ثم -4 + 2 = -2. في لغة C، ما يصل إلى 64 عنصرًا يحتاج بضع تعليمات صحيحة فقط: ~(w ^ x) للـ XNOR (أي XOR ثم NOT في معظم المعالجات)، و__builtin_popcountll للعدّ، ثم إزاحة وجمع. وتصف ورقة الـ BNN نسخة الـ GPU بأنها تقيّم 32 اتصالًا بثلاث تعليمات (accumulate وpopcount وXNOR) تستغرق نحو 6 دورات ساعة، أي تسريع نظري قدره 32/6 ≈ 5.3 على ذلك الـ GPU.
What it savesما الذي توفّره
| Inputالمدخلات | Weightالأوزان | Operationsالعمليات | Memoryالذاكرة | Computationالحساب | Where the number comes fromمصدر الرقم |
|---|---|---|---|---|---|
| Realحقيقية | Realحقيقية | multiply and addضرب وجمع | 1x1x | 1x1x | Full-precision baselineخط الأساس بالدقة الكاملة |
| Realحقيقية | Binaryثنائية | add and subtractجمع وطرح | ≈32x less≈32x أقل | ≈2x less≈2x أقل | Binary Weight Network: each weight only picks the sign of an inputالـ Binary Weight Network: كل وزن يختار فقط إشارة أحد المدخلات |
| Binaryثنائية | Binaryثنائية | XNOR and popcountXNOR وpopcount | ≈32x less≈32x أقل | ≈58x less≈58x أقل | XNOR-Net: 64 bit operations per CPU clock, one convolution measuredالـ XNOR-Net: 64 عملية بت لكل دورة ساعة في الـ CPU، مقيسة على convolution واحدة |
The memory column is simple arithmetic: a 32-bit float weight becomes one bit, so weight storage shrinks 32x (ignoring the small per-filter scale factors). The computation column needs more care. For binary weights with real inputs, the paper says convolutions need only addition and subtraction, giving about a 2x speedup, and adds that on CPUs which fuse multiply and add into one cycle, binary weights alone give no speedup at all.
عمود الذاكرة حساب بسيط: الوزن العائم بطول 32-bit يصبح بتًا واحدًا، فيصغر تخزين الأوزان 32x (مع تجاهل معاملات المقياس الصغيرة لكل filter). أما عمود الحساب فيحتاج عناية أكبر. للأوزان الثنائية مع مدخلات حقيقية، تقول الورقة إن الـ convolutions لا تحتاج إلا الجمع والطرح، ما يعطي تسريعًا بنحو 2x، وتضيف أنه على المعالجات التي تدمج الضرب والجمع في دورة واحدة لا تعطي الأوزان الثنائية وحدها أي تسريع على الإطلاق.
The 58x comes from a specific count. A standard convolution needs c · N_W · N_I operations (channels, filter size, input size). The binary version needs the same number of binary operations, done 64 per clock, plus N_I non-binary ones for scaling.
الـ 58x تأتي من عدّ محدد. الـ convolution العادية تحتاج c · N_W · N_I عملية (عدد القنوات، وحجم الـ filter، وحجم المدخلات). والنسخة الثنائية تحتاج العدد نفسه من العمليات الثنائية، تُنفَّذ 64 منها في كل دورة ساعة، إضافة إلى N_I عملية غير ثنائية للتحجيم (scaling).
Worked exampleمثال محلول
Where 62.27x and 58x come fromمن أين تأتي 62.27x و58x
Plug in the paper's typical layerعوّض بالطبقة النموذجية في الورقة
c = 256 channels, a 3 × 3 filter so N_W = 9, and c · N_W = 2304.
c = 256 قناة، وfilter بحجم 3 × 3 أي N_W = 9، وc · N_W = 2304.Theoretical speedupالتسريع النظري
S = 64 × 2304 / (2304 + 64) = 147456 / 2368 ≈ 62.27.
S = 64 × 2304 / (2304 + 64) = 147456 / 2368 ≈ 62.27.Resultالنتيجة
The authors measured 58x for one convolution in their CPU implementation, excluding memory allocation and memory access. With c = 3 and a 1 × 1 filter the formula gives only about 2.9x, which is why the first and last layers are usually kept in full precision.قاس المؤلفون 58x لـ convolution واحدة في تطبيقهم على الـ CPU، باستثناء حجز الذاكرة والوصول إليها. ومع c = 3 وfilter بحجم 1 × 1 تعطي الصيغة نحو 2.9x فقط، ولهذا تُترك الطبقتان الأولى والأخيرة عادةً بالدقة الكاملة.
Click any weight or input to flip its sign. Every row below updates at once.انقر على أي وزن أو مُدخل لعكس إشارته. تتحدث كل الصفوف أدناه في الوقت نفسه.
Start from the all-mismatch total -n and add the shifted count.ابدأ من المجموع -n الذي يقابل عدم التطابق في كل المواضع، ثم أضف العدد بعد الإزاحة.
Quick checkاختبار سريع
Why do binary weights with real inputs save only about 2x compute, not 58x?لماذا توفّر الأوزان الثنائية مع مدخلات حقيقية نحو 2x فقط من الحساب، لا 58x؟
Quick checkاختبار سريع
How do C and C++ group the expression -n + p << 1?كيف تجمّع لغتا C و C++ التعبير -n + p << 1؟
Recall
Give the three numbers of the cost table and one condition attached to each.اذكر أرقام جدول التكلفة الثلاثة وشرطًا واحدًا مرتبطًا بكل منها.
Memory about 32x less in both binary rows: 1 bit per weight instead of 32. About 2x less computation for binary weights: only additions and subtractions, and no gain on CPUs with fused multiply-add. About 58x for binary weights and inputs: measured on one convolution with c = 256 and 3 × 3 filters, 62.27x in theory.
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- With both operands in {-1, +1}, every product is ±1: +1 when the signs agree, -1 when they differ.عندما يكون المعاملان كلاهما في {-1, +1} يكون كل حاصل ضرب ±1: يكون +1 عندما تتفق الإشارتان، و-1 عندما تختلفان.
- Encode +1 as bit 1 and -1 as bit 0. Then XNOR(b_w, b_x) is 1 exactly where W × x = +1, so XNOR is the product in disguise.رمّز +1 بالبت 1 و-1 بالبت 0. عندها تكون XNOR(b_w, b_x) مساوية 1 بالضبط حيث W × x = +1، أي أن XNOR هي حاصل الضرب متنكرًا.
- Summing XNOR bits counts matches only. It ignores that each mismatch contributes -1, so it gives 1 instead of -2 on the slide example.جمع بتات XNOR يعدّ التطابقات فقط، ويتجاهل أن كل عدم تطابق يساهم بـ -1، لذلك يعطي 1 بدل -2 في مثال الشرائح.
- Matches m and mismatches n - m give y = m - (n - m) = 2m - n. With m = popcount(W xnor x): y = -n + 2 · popcount.التطابقات m وعدم التطابقات n - m تعطي y = m - (n - m) = 2m - n. ومع m = popcount(W xnor x) نحصل على y = -n + 2 · popcount.
- Hardware form: y = -n + (popcount(W xnor x) << 1). The shift binds to the popcount; written without brackets in C it would apply to the whole sum.الصيغة العتادية: y = -n + (popcount(W xnor x) << 1). الإزاحة (shift) ترتبط بالـ popcount وحده؛ ولو كُتبت بلا أقواس في لغة C لطُبّقت على المجموع كله.
- Slide example: 1010 xnor 1101 = 1000, popcount 1, shifted 2, y = -4 + 2 = -2. Exercise with n = 8: popcount 5, y = -8 + 10 = 2.مثال الشرائح: 1010 xnor 1101 = 1000، والـ popcount يساوي 1، وبعد الإزاحة يصبح 2، فيكون y = -4 + 2 = -2. وفي التمرين مع n = 8: الـ popcount يساوي 5، و y = -8 + 10 = 2.
- XNOR-Net reports about 32x memory saving and about 58x faster convolutions (62.27x theoretical, c = 256, 3 × 3 filters, 64 bit operations per clock). Binary weights alone give about 2x.تذكر ورقة XNOR-Net توفيرًا في الذاكرة بنحو 32x وتسريعًا للـ convolutions بنحو 58x (و62.27x نظريًا، مع c = 256 ومرشحات 3 × 3 و64 عملية بت لكل دورة ساعة). أما الأوزان الثنائية وحدها فتعطي نحو 2x.
Sourcesالمصادر
- XNOR-Net: ImageNet Classification Using Binary Convolutional Neural Networks (Rastegari, Ordonez, Redmon, Farhadi)PaperECCV 2016, arXiv:1603.05279Section 4.1 efficiency analysis: S = 64cN_W / (cN_W + 64), 62.27x theoretical and 58x measured; about 32x memory and about 2x speedup for binary weights.القسم 4.1 تحليل الكفاءة: S = 64cN_W / (cN_W + 64)، و62.27x نظريًا و58x مقيسة؛ ونحو 32x في الذاكرة ونحو 2x تسريعًا للأوزان الثنائية.(opens in a new tab)(يفتح في تبويب جديد)
- Binarized Neural Networks: Training Deep Neural Networks with Weights and Activations Constrained to +1 or -1 (Courbariaux, Hubara, Soudry, El-Yaniv, Bengio)PaperarXiv:1602.02830, 2016Section 3.2 XNOR-count and section 4: packing 32 binary values per register, popcount(xnor(...)) in three instructions.القسم 3.2 عن XNOR-count والقسم 4: ضغط 32 قيمة ثنائية في كل register، وحساب popcount(xnor(...)) بثلاث تعليمات.(opens in a new tab)(يفتح في تبويب جديد)
- Bit Operation Builtins: __builtin_popcountDocsGCC documentationReturns the number of 1 bits in its argument.تُرجع عدد البتات التي تساوي 1 في وسيطها.(opens in a new tab)(يفتح في تبويب جديد)
- C++ built-in operators, precedence, and associativityDocsMicrosoft LearnAddition and subtraction (group 6) bind more tightly than left and right shift (group 7).الجمع والطرح (المجموعة 6) يرتبطان أقوى من الإزاحة لليسار ولليمين (المجموعة 7).(opens in a new tab)(يفتح في تبويب جديد)
- MIT 6.5940 TinyML and Efficient Deep Learning Computing, Lecture 6: Quantization (Part II)DocsMIT Han LabCourse page with the Quantization (Part II) lecture slides, the companion deck to this lecture's XNOR figures.صفحة المقرر مع شرائح محاضرة Quantization (Part II)، وهي العرض المرافق لأشكال XNOR في هذه المحاضرة.(opens in a new tab)(يفتح في تبويب جديد)
Part 08: Accuracy cost of binarization and ternary quantizationكلفة التثنيث على الدقة والتكميم الثلاثي
Binarizing activations as well as weights costs a lot of accuracy, though scale factors help. Adding a zero level gives ternary weights: TWN thresholds at 0.7 times the mean magnitude with one fixed scale, and TTQ learns separate positive and negative scales, closing more of the gap to full precision.تثنيث التنشيطات مع الأوزان يكلّف كثيرًا من الدقة، وإن كانت معاملات القياس تساعد. إضافة مستوى صفري تعطي أوزانًا ثلاثية: يضع TWN العتبة عند 0.7 من متوسط المقدار مع مقياس ثابت واحد، ويتعلم TTQ مقياسين منفصلين للموجب والسالب، فيسد جزءًا أكبر من الفجوة مع الدقة الكاملة.
4 concepts4 مفاهيم, ، slides 61-64الشرائح 61-64
Why this part mattersلماذا يهمّ هذا الجزء
Going from 8 bits to 1 bit promises a 32× smaller model and multiplications replaced by bit tricks, which is exactly what a microcontroller or a tiny accelerator wants. This part puts a price on that promise. It reads the accuracy table for binary networks, then shows how adding a single zero state, the ternary idea, buys back most of what binarization loses.
The argument runs in four steps. First, the cost of binarization and the two things that drive it. Second, Ternary Weight Networks, with a full calculation on the same 4×4 matrix the lecture has used since K-means quantization. Third, Trained Ternary Quantization, which learns its scales. Fourth, a map of every quantization family by what it stores and what arithmetic it runs. For the midterm, expect to compute Δ, r_t and a ternary matrix by hand, to rank the binary variants, and to state the difference between TWN and TTQ in one sentence.
الانتقال من 8 بت إلى 1 بت يعد بنموذج أصغر بـ 32×، وبعمليات ضرب تُستبدل بحيل على مستوى البت، وهذا بالضبط ما يريده المتحكم الدقيق (microcontroller) أو المسرّع الصغير. هذا الجزء يضع ثمنًا لهذا الوعد. يقرأ جدول الدقة للشبكات الثنائية، ثم يبيّن كيف أن إضافة حالة صفر واحدة، وهي فكرة التكميم الثلاثي (ternary)، تستعيد معظم ما يضيع بسبب التحويل الثنائي.
يسير الشرح في أربع خطوات. أولًا، كلفة التحويل الثنائي والعاملان اللذان يحددانها. ثانيًا، شبكات الأوزان الثلاثية Ternary Weight Networks، مع حساب كامل على مصفوفة 4×4 نفسها التي تستخدمها المحاضرة منذ تكميم K-means. ثالثًا، التكميم الثلاثي المدرَّب Trained Ternary Quantizationالذي يتعلّم مقاييسه. رابعًا، خريطة لكل عائلات التكميم بحسب ما تخزّنه وما تنفّذه من عمليات حسابية. في الاختبار النصفي، توقّع أن تحسب Δ وr_t والمصفوفة الثلاثية يدويًا، وأن ترتّب المتغيرات الثنائية، وأن تذكر الفرق بين TWN وTTQ في جملة واحدة.
By the end you canفي نهاية هذا الجزء ستستطيع
- Rank BWN, BNN and XNOR-Net by AlexNet accuracy and explain the ranking with two causes: scale factors and binarized activations.رتّب BWN وBNN وXNOR-Net حسب دقة AlexNet، وفسّر الترتيب بسببين: معاملات المقياس (scale factors) وتحويل التنشيطات إلى قيم ثنائية.
- Compute the TWN threshold Δ, the shared scale r_t and the ternary matrix for a given weight tensor.احسب عتبة TWN أي Δ، والمقياس المشترك r_t، والمصفوفة الثلاثية لمصفوفة أوزان معطاة.
- Explain why a zero state makes ternary weights far more accurate than binary ones for only one extra bit.اشرح لماذا تجعل حالة الصفر الأوزانَ الثلاثية أدق بكثير من الثنائية مقابل بت إضافي واحد فقط.
- State exactly what TTQ changes relative to TWN, and why learned asymmetric scales help.اذكر بدقة ما الذي يغيّره TTQ مقارنة بـ TWN، ولماذا تفيد المقاييس غير المتماثلة المتعلَّمة.
- Place K-means, linear and binary or ternary quantization on the storage and arithmetic axes.ضع تكميم K-means والتكميم الخطي والتكميم الثنائي أو الثلاثي على محوري التخزين والعمليات الحسابية.
Take AlexNet on ImageNet and binarize it three different ways. Binarize only the weights and keep a scale factor: top-1 accuracy goes up by 0.2 points. Binarize weights and activations with scale factors on both: it drops 12.4 points. Binarize both without any scale factors: it drops 28.7 points. Same network, same bit width for the weights, and a spread of almost 29 points.
خذ AlexNet على ImageNet وحوّلها إلى ثنائية بثلاث طرق مختلفة. حوّل الأوزان فقط مع الإبقاء على معامل مقياس: ترتفع دقة top-1 بمقدار 0.2 نقطة. حوّل الأوزان والتنشيطات مع معاملات مقياس على كليهما: تنخفض 12.4 نقطة. حوّل الاثنين دون أي معاملات مقياس: تنخفض 28.7 نقطة. الشبكة نفسها، وعرض البت نفسه للأوزان، ومع ذلك يبلغ الفارق قرابة 29 نقطة.
| Methodالطريقة | W bitsبتات الأوزان W | A bitsبتات التنشيطات A | Scale factors onمعاملات المقياس على | Top-1 deltaفرق top-1 |
|---|---|---|---|---|
| BWNBWN | 11 | 3232 | Weights onlyالأوزان فقط | +0.2%+0.2% |
| XNOR-NetXNOR-Net | 11 | 11 | Weights and activationsالأوزان والتنشيطات | -12.4%-12.4% |
| BNNBNN | 11 | 11 | Noneلا شيء | -28.7%-28.7% |
Two causes, read off the tableسببان نقرؤهما من الجدول
The three rows differ in exactly two switches, so you can isolate each one. Compare XNOR-Net with Binarized Neural Network (BNN): both have 1 bit weights and 1 bit activations, and the only difference is the scale factors. That switch alone is worth about 16.3 points (-12.4 against -28.7). Now compare the Binary Weight Network (BWN) with XNOR-Net: both are scaled, and the only difference is whether activations are binarized. That switch costs 12.6 points (+0.2 against -12.4).
تختلف الصفوف الثلاثة في مفتاحين فقط، لذا يمكنك عزل أثر كل منهما. قارن XNOR-Net مع BNN: كلاهما بأوزان 1 بت وتنشيطات 1 بت، والفرق الوحيد هو معاملات المقياس. هذا المفتاح وحده يساوي نحو 16.3 نقطة (-12.4 مقابل -28.7). الآن قارن BWN مع XNOR-Net: كلاهما يستخدم المقياس، والفرق الوحيد هو هل التنشيطات ثنائية أم لا. هذا المفتاح يكلّف 12.6 نقطة (+0.2 مقابل -12.4).
- Scale factors matter. A sign function throws away magnitude. The scale puts the average magnitude back, so the binarized layer outputs numbers of the right size. Without it, every layer sees signals of the wrong scale, and the errors compound through depth.معاملات المقياس مهمة. دالة الإشارة (sign) تتخلص من المقدار. والمقياس يعيد متوسط المقدار، فتُخرج الطبقة الثنائية أرقامًا بالحجم الصحيح. ومن دونه ترى كل طبقة إشارات بمقياس خاطئ، وتتراكم الأخطاء مع العمق.
- Binarizing activations is the expensive part. Weights are learned, so training can adapt them to a two-level grid. Activations are fresh data at every input. Forcing each one to ±1 discards most of what the previous layer computed, and no amount of training can recover information that never reaches the next layer.تحويل التنشيطات إلى ثنائية هو الجزء المكلف. الأوزان تُتعلَّم، لذا يستطيع التدريب أن يكيّفها مع شبكة من مستويين. أما التنشيطات فهي بيانات جديدة مع كل مدخل. إجبار كل واحدة منها على ±1 يُهدر معظم ما حسبته الطبقة السابقة، ولا يستطيع أي قدر من التدريب أن يستعيد معلومات لم تصل أصلًا إلى الطبقة التالية.
The reward for paying the activation cost is speed. With both operands in ±1, a dot product becomes XNOR and popcount, which is why XNOR-Net reports 58× faster convolutions and 32× less memory. BWN keeps real-valued activations, so it saves memory but still needs additions for every weight. That is the trade the table prices: accuracy against arithmetic.
المكافأة على دفع كلفة التنشيطات هي السرعة. عندما يكون المعاملان كلاهما في ±1، يتحول الضرب النقطي إلى XNOR وpopcount، ولهذا يذكر XNOR-Net التفافات أسرع بـ 58× وذاكرة أقل بـ 32×. أما BWN فيُبقي التنشيطات بقيم حقيقية، فيوفر الذاكرة لكنه يظل يحتاج عمليات جمع لكل وزن. هذه هي المقايضة التي يسعّرها الجدول: الدقة مقابل كلفة العمليات الحسابية.
Quick checkاختبار سريع
Rank the AlexNet variants by ImageNet top-1 accuracy, best first.رتّب متغيرات AlexNet حسب دقة top-1 على ImageNet، من الأفضل إلى الأسوأ.
Recall
Which single change costs more on AlexNet: removing scale factors, or binarizing activations? Give the numbers.أي تغيير منفرد يكلّف أكثر على AlexNet: إزالة معاملات المقياس، أم تحويل التنشيطات إلى ثنائية؟ اذكر الأرقام.
Removing scale factors costs more: XNOR-Net to BNN is -12.4 to -28.7, about 16.3 points. Binarizing activations (BWN to XNOR-Net) costs 12.6 points. Both are large; neither is free.
إزالة معاملات المقياس تكلّف أكثر: من XNOR-Net إلى BNN ننتقل من -12.4 إلى -28.7، أي نحو 16.3 نقطة. وتحويل التنشيطات إلى ثنائية (من BWN إلى XNOR-Net) يكلّف 12.6 نقطة. كلاهما كبير، ولا أحد منهما مجاني.
Look at the running matrix again. Most weights sit near ±1 to ±2, but 0.09, 0.05, -0.14 and the two zeros are tiny. Binarization has no choice but to push them all the way to ±α, about ±1.05. A weight of 0.05 becomes 1.05, an error twenty times its own size. What these weights need is a third option: zero.
انظر مجددًا إلى المصفوفة المرجعية. معظم الأوزان تقع قرب ±1 إلى ±2، لكن 0.09 و0.05 و-0.14 والصفرين صغيرة جدًا. التحويل الثنائي لا يملك خيارًا سوى دفعها كلها إلى ±α، أي نحو ±1.05. فالوزن 0.05 يصبح 1.05، بخطأ يساوي عشرين ضعف حجمه. ما تحتاجه هذه الأوزان هو خيار ثالث: الصفر.
The ternary ruleالقاعدة الثلاثية
Ternary Weight Networks (TWN) (Li, Zhang and Liu, 2016) give every weight three choices. A dead zone of half-width around zero maps small weights to 0. Everything outside it keeps its sign and takes one shared magnitude .
تعطي Ternary Weight Networks (TWN) (Li, Zhang and Liu, 2016) كل وزن ثلاثة خيارات. منطقة ميتة (dead zone) نصف عرضها حول الصفر تحوّل الأوزان الصغيرة إلى 0. وكل ما يقع خارجها يحتفظ بإشارته ويأخذ مقدارًا واحدًا مشتركًا .
Both quantities come from minimizing the squared distance between the real and the ternary weights. For a fixed , the best scale is simply the mean magnitude of the weights that survive, the same logic as the binary but averaged only over the nonzero positions. The best has no closed form, so the paper assumes a weight distribution. Uniform weights give ; Gaussian weights give . The rule of thumb 0.7 sits between the two.
الكميتان كلتاهما تأتيان من تقليل المسافة التربيعية بين الأوزان الحقيقية والأوزان الثلاثية. عند تثبيت ، يكون أفضل مقياس ببساطة هو متوسط مقدار الأوزان الناجية، وهو المنطق نفسه لـ في الحالة الثنائية لكن المتوسط يؤخذ فقط على المواقع غير الصفرية. أما أفضل فليس له صيغة مغلقة، لذا تفترض الورقة توزيعًا للأوزان. الأوزان المنتظمة (uniform) تعطي ، والأوزان الغاوسية تعطي . والقاعدة التقريبية 0.7 تقع بين الحالتين.
Worked exampleمثال محلول
Ternarize the running 4×4 matrixحوّل المصفوفة المرجعية 4×4 إلى ثلاثية
Sum the magnitudesاجمع المقادير
Row sums of |W|: 4.64, 3.39, 3.86, 4.89. So ‖W‖₁ = 16.78 and E(|W|) = 16.78 / 16 = 1.049.
مجاميع صفوف |W|: 4.64 و3.39 و3.86 و4.89. إذن ‖W‖₁ = 16.78 وE(|W|) = 16.78 / 16 = 1.049.
Thresholdالعتبة
Δ = 0.7 × 1.049 = 0.734 ≈ 0.73.
Δ = 0.7 × 1.049 = 0.734 ≈ 0.73.
Find the survivorsحدّد الأوزان الناجية
Five weights have |r| ≤ 0.73: 0.09, 0.05, -0.14 and the two zeros. The other eleven survive, the smallest being -0.91.
خمسة أوزان تحقق |r| ≤ 0.73: 0.09 و0.05 و-0.14 والصفران. الأحد عشر الباقية تنجو، وأصغرها -0.91.
Shared scaleالمقياس المشترك
Their magnitudes sum to 16.78 - 0.09 - 0.05 - 0.14 = 16.50, so r_t = 16.50 / 11 = 1.5.
مجموع مقاديرها 16.78 - 0.09 - 0.05 - 0.14 = 16.50، إذن r_t = 16.50 / 11 = 1.5.
Write the ternary matrixاكتب المصفوفة الثلاثية
Rows: [1, -1, 1, 0], [0, 0, -1, 1], [-1, 1, 0, -1], [1, 0, 1, 1]. The deployed weight is this matrix times 1.5.
الصفوف: [1, -1, 1, 0] و[0, 0, -1, 1] و[-1, 1, 0, -1] و[1, 0, 1, 1]. والوزن المستخدم فعليًا عند النشر هو هذه المصفوفة مضروبة في 1.5.
Resultالنتيجة
Δ = 0.73, r_t = 1.5, eleven nonzeros, five zeros. Stored in 2 bits per weight plus one FP scale.Δ = 0.73، وr_t = 1.5، وأحد عشر عنصرًا غير صفري، وخمسة أصفار. تُخزَّن بـ 2 بت لكل وزن مع مقياس واحد بالفاصلة العائمة FP.
What the zero buysماذا يشتري الصفر
Measure squared error on the same matrix. Binary with α = 1.049 gives Σ(r - q)² ≈ 9.25. Ternary with Δ = 0.73 and r_t = 1.5 gives about 2.09, more than four times smaller. Two things happen at once. The tiny weights stop paying a 1.05 penalty, and because they no longer drag the average down, the scale moves up to 1.5, much closer to the large weights that actually carry the signal.
قِس الخطأ التربيعي على المصفوفة نفسها. التحويل الثنائي مع α = 1.049 يعطي Σ(r - q)² ≈ 9.25. والتحويل الثلاثي مع Δ = 0.73 وr_t = 1.5 يعطي نحو 2.09، أي أصغر بأكثر من أربع مرات. يحدث أمران في الوقت نفسه. الأوزان الصغيرة جدًا تتوقف عن دفع عقوبة 1.05، ولأنها لم تعد تسحب المتوسط إلى الأسفل، يرتفع المقياس إلى 1.5، وهو أقرب بكثير إلى الأوزان الكبيرة التي تحمل الإشارة فعلًا.
The price is one extra bit: three states need 2 bits, so the model is 16× smaller than FP32 instead of 32×. The arithmetic stays cheap. A zero weight is skipped, and the others are adds or subtracts followed by one multiply by per output. On the slide’s ResNet-18 numbers the trade is clearly worth it: 65.3 top-1 for TWN against 60.8 for BWN, with full precision at 69.6 (see the erratum below for which backbone the 65.3 really comes from).
الثمن بت إضافي واحد: ثلاث حالات تحتاج 2 بت، فيكون النموذج أصغر بـ 16× من FP32 بدلًا من 32×. وتبقى العمليات الحسابية رخيصة. الوزن الصفري يُتخطّى، والبقية عمليات جمع أو طرح يليها ضرب واحد في لكل مخرج. وبحسب أرقام ResNet-18 في الشريحة، فالمقايضة تستحق بوضوح: 65.3 في top-1 لـ TWN مقابل 60.8 لـ BWN، والدقة الكاملة عند 69.6 (انظر التصحيح أدناه لمعرفة الشبكة الأساسية التي يأتي منها الرقم 65.3 فعلًا).
Quick checkاختبار سريع
A layer has mean absolute weight 0.40. What threshold does the TWN rule of thumb give?طبقة متوسط القيمة المطلقة لأوزانها 0.40. ما العتبة التي تعطيها القاعدة التقريبية في TWN؟
Recall
Weights are [1.2, -0.1, 0.4, -0.9]. Compute Δ, r_t and the ternary vector.الأوزان هي [1.2, -0.1, 0.4, -0.9]. احسب Δ و r_t والمتجه الثلاثي.
E(|r|) = 2.6 / 4 = 0.65, so Δ = 0.455. Survivors are 1.2 and -0.9, so r_t = 2.1 / 2 = 1.05. Ternary vector [1, 0, 0, -1], deployed as [1.05, 0, 0, -1.05].
E(|r|) = 2.6 / 4 = 0.65، إذن Δ = 0.455. الناجيان هما 1.2 و-0.9، إذن r_t = 2.1 / 2 = 1.05. المتجه الثلاثي [1, 0, 0, -1]، ويُستخدم عند النشر بالشكل [1.05, 0, 0, -1.05].
Split the eleven TWN survivors by sign. The seven positives have mean magnitude 12.50 / 7 ≈ 1.79. The four negatives have mean magnitude 4.00 / 4 = 1.00. TWN forces both sides to share r_t = 1.5, which is too small for the positives and too large for the negatives. If each side had its own scale, the squared error on this matrix would fall from about 2.09 to about 0.52.
قسّم الأوزان الأحد عشر الناجية في TWN حسب الإشارة. الأوزان الموجبة السبعة متوسط مقدارها 12.50 / 7 ≈ 1.79. والسالبة الأربعة متوسط مقدارها 4.00 / 4 = 1.00. يجبر TWN الجانبين على مشاركة r_t = 1.5، وهو صغير جدًا على الموجبة وكبير جدًا على السالبة. لو كان لكل جانب مقياسه الخاص، لانخفض الخطأ التربيعي على هذه المصفوفة من نحو 2.09 إلى نحو 0.52.
Trained Ternary Quantization (TTQ) (Zhu, Han, Mao and Dally, ICLR 2017) takes that idea further: it gives each layer two scales, for positive weights and for negative ones, and it does not compute them from the weights at all. They are parameters, trained by gradient descent along with everything else.
يأخذ Trained Ternary Quantization (TTQ) (Zhu, Han, Mao and Dally, ICLR 2017) هذه الفكرة أبعد: يعطي كل طبقة مقياسين، للأوزان الموجبة و للسالبة، ولا يحسبهما من الأوزان إطلاقًا. إنهما معاملات تُدرَّب بالانحدار التدريجي (gradient descent) مع كل شيء آخر.
The pipelineخط المعالجة
- Normalize. Divide each layer’s full-precision weights by their largest magnitude so they lie in [-1, 1].التطبيع. اقسم الأوزان كاملة الدقة في كل طبقة على أكبر مقدار فيها حتى تقع في المجال [-1, 1].
- Quantize. Threshold at ±t to get intermediate weights in {-1, 0, +1}. The paper uses Δ = t × max(|w|) with t = 0.05 for every layer.التكميم. طبّق العتبة عند ±t للحصول على أوزان وسيطة في {-1, 0, +1}. تستخدم الورقة Δ = t × max(|w|) مع t = 0.05 لكل الطبقات.
- Scale. Multiply the +1 entries by and the -1 entries by .التدريج بالمقياس. اضرب العناصر +1 في والعناصر -1 في .
- Train. Backpropagate two gradients: one into and (which learns the ternary values), and one into the Full-precision weight copy of the weights (which learns which weights land in which state).التدريب. مرّر تدرّجين عكسيًا: أحدهما إلى و (وهو الذي يتعلّم القيم الثلاثية)، والآخر إلى النسخة كاملة الدقة full-precision copy من الأوزان (وهو الذي يتعلّم أي وزن يقع في أي حالة).
The latent weights get a Straight-through estimator (STE) style gradient, scaled by or outside the dead zone and passed through unchanged inside it. At inference the full-precision copy is thrown away. Only the 2-bit codes and two FP numbers per layer remain, so storage is still about 16× below FP32.
تحصل الأوزان الكامنة (latent) على تدرّج من نمط straight-through estimator (STE)، مضروب في أو خارج المنطقة الميتة، ويمر كما هو دون تغيير داخلها. عند الاستدلال (inference) تُرمى النسخة كاملة الدقة. ولا يبقى إلا رموز 2 بت ورقمان بالفاصلة العائمة لكل طبقة، فيظل التخزين أقل بنحو 16× من FP32.
Learning the scales from the loss, rather than fitting them to the weights, is the important part. Minimizing weight error is only a proxy; what matters is the network’s output. On ResNet-18 ImageNet, TTQ reaches 66.6 top-1 against 65.3 for TWN, closing the gap to full precision to three points with the same 2 bits per weight. On AlexNet the paper reports TTQ slightly above full precision.
تعلّم المقاييس من دالة الخسارة، بدلًا من ملاءمتها للأوزان، هو الجزء المهم. تقليل خطأ الأوزان ليس إلا بديلًا تقريبيًا؛ ما يهم فعلًا هو مخرج الشبكة. على ResNet-18 مع ImageNet يصل TTQ إلى 66.6 في top-1 مقابل 65.3 لـ TWN، فيقلّص الفجوة مع الدقة الكاملة إلى ثلاث نقاط بالعدد نفسه من البتات، 2 بت لكل وزن. وعلى AlexNet تذكر الورقة أن TTQ أعلى قليلًا من الدقة الكاملة.
| TWNTWN | TTQTTQ | |
|---|---|---|
| Valuesالقيم | {-r_t, 0, +r_t}{-r_t, 0, +r_t} | {-w_n, 0, +w_p}{-w_n, 0, +w_p} |
| Scaleالمقياس | One, computed from the weightsمقياس واحد، يُحسب من الأوزان | Two, trained by gradient descentمقياسان، يُدرَّبان بالانحدار التدريجي (gradient descent) |
| Symmetric?متماثل؟ | Yes, same magnitude both sidesنعم، المقدار نفسه على الجانبين | No, sides can differلا، يمكن أن يختلف الجانبان |
| Thresholdالعتبة | Δ = 0.7 · E(|r|)Δ = 0.7 · E(|r|) | Δ = t · max(|r|), t = 0.05Δ = t · max(|r|), t = 0.05 |
| Storageالتخزين | 2 bits per weight + 1 FP scale2 بت لكل وزن + مقياس واحد بالفاصلة العائمة FP | 2 bits per weight + 2 FP scales2 بت لكل وزن + مقياسان بالفاصلة العائمة FP |
| ResNet-18 top-1دقة top-1 لـ ResNet-18 | 65.365.3 | 66.666.6 |
Quick checkاختبار سريع
What is the essential change TTQ makes compared with TWN?ما التغيير الجوهري الذي يجريه TTQ مقارنة بـ TWN؟
Recall
Why can asymmetric scales help, and how are they found in TTQ?لماذا قد تفيد المقاييس غير المتماثلة، وكيف تُحدَّد في TTQ؟
Positive and negative weights in a layer need not have the same typical magnitude, so one shared scale misfits both sides. TTQ treats w_p and w_n as parameters and updates them by gradient descent on the training loss, summing the gradients of the weights assigned to each side.
لا يلزم أن يكون للأوزان الموجبة والسالبة في الطبقة المقدار المعتاد نفسه، لذا فإن مقياسًا واحدًا مشتركًا لا يناسب أيًّا من الجانبين. يعامل TTQ كلًّا من w_p وw_n كمعاملات ويحدّثهما بالانحدار التدريجي على خسارة التدريب، بجمع تدرّجات الأوزان المسندة إلى كل جانب.
The same 4×4 matrix has now been quantized three ways in this course. K-means turned it into 2-bit indices into a codebook of four FP centroids (2.00, 1.50, 0.00, -1.00). Linear quantization turned it into 2-bit signed integers with zero point -1 and scale 1.07, so . Binary or ternary quantization turned it into signs, optionally with zeros. What differs is not only the bit width but what the hardware has to do with the result.
المصفوفة 4×4 نفسها كُمّمت الآن بثلاث طرق في هذا المقرر. حوّلها K-means إلى فهارس من 2 بت تشير إلى دفتر رموز (codebook) من أربعة مراكز بالفاصلة العائمة (2.00، 1.50، 0.00، -1.00). وحوّلها التكميم الخطي إلى أعداد صحيحة بإشارة من 2 بت مع نقطة صفر -1 ومقياس 1.07، أي . وحوّلها التكميم الثنائي أو الثلاثي إلى إشارات، مع أصفار اختياريًا. والاختلاف ليس في عرض البت فقط، بل في ما يجب على العتاد أن يفعله بالنتيجة.
| Familyالعائلة | Storedما يُخزَّن | Arithmetic at inferenceالعمليات الحسابية عند الاستدلال | Bits per weightعدد البتات لكل وزن |
|---|---|---|---|
| Full precisionالدقة الكاملة | FP32 weightsأوزان FP32 | Floating-point arithmeticعمليات بالفاصلة العائمة | 3232 |
| K-meansK-means | Integer indices plus an FP codebookفهارس صحيحة مع دفتر رموز (codebook) بالفاصلة العائمة | Floating-point arithmeticعمليات بالفاصلة العائمة | 2 (plus codebook)2 (إضافة إلى دفتر الرموز) |
| Linearالخطي | Integer weights plus scale and zero pointأوزان صحيحة مع مقياس (scale) ونقطة صفر (zero point) | Integer arithmeticعمليات بالأعداد الصحيحة | 2 to 8من 2 إلى 8 |
| Binary or ternaryالثنائي أو الثلاثي | 1 or 2 bit weights plus a scaleأوزان 1 أو 2 بت مع مقياس | Bit operations (XNOR, popcount, add and subtract)عمليات على مستوى البت (XNOR وpopcount والجمع والطرح) | 1 or 21 أو 2 |
K-means saves memory only. Before every multiply the index is looked up in the codebook and the arithmetic runs in floating point, so it helps a memory-bound model but not a compute-bound one. Linear quantization saves memory and also lets the multiply-accumulate run in integers, which is why it dominates deployed edge inference. Binary and ternary quantization go furthest: multiplications collapse into sign flips, additions, skips for zeros, or Popcount when activations are binary too. The accuracy table from the first concept is the price of that last step.
K-means يوفر الذاكرة فقط. قبل كل عملية ضرب يُبحث عن الفهرس في دفتر الرموز وتُنفَّذ العمليات بالفاصلة العائمة، لذا يفيد النموذج المقيَّد بالذاكرة (memory-bound) لا المقيَّد بالحساب (compute-bound). والتكميم الخطي يوفر الذاكرة ويسمح أيضًا بتنفيذ الضرب والتجميع (multiply-accumulate) بالأعداد الصحيحة، ولهذا يهيمن على الاستدلال المنشور على أجهزة الحافة (edge). أما التكميم الثنائي والثلاثي فيذهبان أبعد: تنهار عمليات الضرب إلى قلب إشارات، وعمليات جمع، وتخطٍّ للأصفار، أو popcount عندما تكون التنشيطات ثنائية أيضًا. وجدول الدقة في المفهوم الأول هو ثمن هذه الخطوة الأخيرة.
Recall
For K-means, linear and ternary quantization, what is stored and what arithmetic runs?في تكميم K-means والخطي والثلاثي، ما الذي يُخزَّن وما العمليات الحسابية التي تُنفَّذ؟
K-means: integer indices plus an FP codebook, FP arithmetic. Linear: integer weights (with scale and zero point), integer arithmetic. Ternary: 2-bit weights plus a scale, bit operations (add, subtract, skip) with one scale multiply per output.
K-means: فهارس صحيحة مع دفتر رموز بالفاصلة العائمة، وعمليات بالفاصلة العائمة. الخطي: أوزان صحيحة (مع مقياس ونقطة صفر)، وعمليات بالأعداد الصحيحة. الثلاثي: أوزان من 2 بت مع مقياس، وعمليات على مستوى البت (جمع، طرح، تخطٍّ) مع ضرب واحد في المقياس لكل مخرج.
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- AlexNet top-1 change: BWN (W 1 bit, A 32 bit, scaled) +0.2%, XNOR-Net (W and A 1 bit, scaled) -12.4%, BNN (W and A 1 bit, no scale) -28.7%.التغير في دقة top-1 لـ AlexNet: BWN (أوزان 1 بت، تنشيطات 32 بت، مع مقياس) +0.2%، وXNOR-Net (أوزان وتنشيطات 1 بت، مع مقياس) -12.4%، وBNN (أوزان وتنشيطات 1 بت، بلا مقياس) -28.7%.
- Scale factors recover about 16 points between BNN and XNOR-Net. Binarizing activations is the expensive step: BWN to XNOR-Net loses 12.6 points.معاملات المقياس تستعيد نحو 16 نقطة بين BNN وXNOR-Net. وتحويل التنشيطات إلى ثنائية هو الخطوة المكلفة: الانتقال من BWN إلى XNOR-Net يخسر 12.6 نقطة.
- TWN: q = r_t if r > Δ, 0 if |r| ≤ Δ, -r_t if r < -Δ, with Δ = 0.7 · E(|r|) and r_t = mean of |r| over the weights above Δ.قاعدة TWN: q = r_t إذا كان r > Δ، و0 إذا كان |r| ≤ Δ، و-r_t إذا كان r < -Δ، حيث Δ = 0.7 · E(|r|) و r_t هو متوسط |r| على الأوزان التي تتجاوز Δ.
- Running matrix: Δ = 0.7 × 16.78 / 16 = 0.73, eleven weights survive, r_t = 16.50 / 11 = 1.5, and five small weights become 0.المصفوفة المرجعية: Δ = 0.7 × 16.78 / 16 = 0.73، ينجو أحد عشر وزنًا، و r_t = 16.50 / 11 = 1.5، وتصبح خمسة أوزان صغيرة 0.
- Ternary needs 2 bits per weight (16× smaller than FP32). On the running matrix its squared error is 2.09 against 9.25 for binary.التكميم الثلاثي يحتاج 2 بت لكل وزن (أصغر بـ 16× من FP32). وعلى المصفوفة المرجعية يبلغ خطؤه التربيعي 2.09 مقابل 9.25 للثنائي.
- TTQ normalizes weights to [-1, 1], thresholds at t, then scales by two trained parameters: w_p for positives and w_n for negatives.يطبّع TTQ الأوزان إلى المجال [-1, 1]، ثم يطبّق العتبة عند t، ثم يضرب في معاملين مدرَّبين: w_p للموجبة و w_n للسالبة.
- ResNet-18 ImageNet top-1: FP 69.6, BWN 60.8, TWN 65.3, TTQ 66.6.دقة top-1 لـ ResNet-18 على ImageNet: الدقة الكاملة FP 69.6، وBWN 60.8، وTWN 65.3، وTTQ 66.6.
- K-means: integer indices plus FP codebook, FP arithmetic. Linear: integer weights, integer arithmetic. Binary or ternary: 1 or 2 bit weights, bit operations.K-means: فهارس صحيحة مع دفتر رموز (codebook) بالفاصلة العائمة، وعمليات بالفاصلة العائمة. الخطي: أوزان صحيحة وعمليات صحيحة. الثنائي أو الثلاثي: أوزان 1 أو 2 بت، وعمليات على مستوى البت.
Sourcesالمصادر
- XNOR-Net: ImageNet Classification Using Binary Convolutional Neural Networks (Rastegari, Ordonez, Redmon, Farhadi)PaperECCV 2016Table 1: AlexNet top-1 full precision 56.6, BWN 56.8, XNOR-Net 44.2, BNN 27.9. 32× memory saving, 58× faster convolutions.الجدول 1: دقة top-1 لـ AlexNet بالدقة الكاملة 56.6، وBWN 56.8، وXNOR-Net 44.2، وBNN 27.9. توفير في الذاكرة بمقدار 32×، والتفافات أسرع بـ 58×.(opens in a new tab)(يفتح في تبويب جديد)
- Binarized Neural Networks: Training Deep Neural Networks with Weights and Activations Constrained to +1 or -1 (Courbariaux et al.)PaperarXiv 2016BNN: binary weights and activations without scale factors.BNN: أوزان وتنشيطات ثنائية دون معاملات مقياس.(opens in a new tab)(يفتح في تبويب جديد)
- Ternary Weight Networks (Li, Zhang, Liu), original 2016 versionPaperarXiv 2016Section 3.2.3: Δ* = 0.7 · E(|W|) as a rule of thumb between the uniform (2/3) and Gaussian (0.75) cases; scale = mean of survivors.القسم 3.2.3: Δ* = 0.7 · E(|W|) كقاعدة تقريبية بين الحالة المنتظمة (2/3) والحالة الغاوسية (0.75)، والمقياس = متوسط الأوزان الناجية.(opens in a new tab)(يفتح في تبويب جديد)
- Ternary Weight Networks, revised versionPaperarXivTable 2: ResNet-18 top-1 61.8 (ResNet-18B 65.3); revised rule of thumb 0.75 · E(|W|).الجدول 2: دقة top-1 لـ ResNet-18 هي 61.8 (و ResNet-18B هي 65.3)، والقاعدة التقريبية المعدّلة 0.75 · E(|W|).(opens in a new tab)(يفتح في تبويب جديد)
- Trained Ternary Quantization (Zhu, Han, Mao, Dally)PaperICLR 2017Normalize to [-1, 1], threshold Δ = t × max(|w|) with t = 0.05, trained w_p and w_n. Table 3: ResNet-18 error 30.4 / 39.2 / 34.7 / 33.4 for FP, BWN, TWN, TTQ.التطبيع إلى [-1, 1]، والعتبة Δ = t × max(|w|) مع t = 0.05، ومعاملان مدرَّبان w_p و w_n. الجدول 3: خطأ ResNet-18 هو 30.4 / 39.2 / 34.7 / 33.4 لكل من FP وBWN وTWN وTTQ.(opens in a new tab)(يفتح في تبويب جديد)
- MIT 6.5940 TinyML and Efficient Deep Learning Computing, Lecture 6: Quantization (Part II)DocsMIT HAN LabThe course these slides are adapted from.المقرر الذي اقتُبست منه هذه الشرائح.(opens in a new tab)(يفتح في تبويب جديد)
Part 09: Mixed-precision quantization and HAQالتكميم بدقة مختلطة وHAQ
Different layers tolerate different bit widths, but choosing weight and activation bits per layer gives a design space of 64^n. HAQ automates the choice with an actor-critic reinforcement-learning agent that gets latency and energy feedback directly from the target hardware, beating uniform quantization and producing different policies for edge and cloud.تتحمل الطبقات المختلفة عروض بت مختلفة، لكن اختيار بتات الأوزان والتنشيطات لكل طبقة يعطي فضاء تصميم حجمه 64^n. يؤتمت HAQ هذا الاختيار بوكيل تعلم معزز من نوع actor-critic يتلقى تغذية راجعة عن زمن الاستجابة والطاقة مباشرة من العتاد المستهدف، فيتفوق على التكميم المنتظم وينتج سياسات مختلفة للحافة (edge) والسحابة.
6 concepts6 مفاهيم, ، slides 65-76الشرائح 65-76
Why this part mattersلماذا يهمّ هذا الجزء
Every technique so far in this lecture asked how to quantize a layer well. This last part asks a different question: should every layer get the same number of bits at all? The answer is no, and once you allow layers to differ, the number of possible configurations explodes beyond any manual search. HAQ solves this with a reinforcement learning agent that tries bit widths on the real accelerator and learns from what it measures.
For the midterm on Wed 28 Oct 2026, expect four kinds of question: why mixed precision helps, computing the design space (64^n and its power of two), why HAQ uses hardware feedback instead of FLOPs, and explaining the edge versus cloud policy with memory bound versus compute bound layers. For your research and for real embedded deployments, the deeper lesson is that the best compression policy depends on the hardware it will run on.
كل تقنية رأيناها حتى الآن في هذه المحاضرة كانت تسأل كيف نكمّم طبقة واحدة جيدًا. هذا الجزء الأخير يطرح سؤالًا مختلفًا: هل يجب أن تحصل كل الطبقات على عدد البتات نفسه أصلًا؟ الجواب لا، وبمجرد أن نسمح للطبقات بأن تختلف، ينفجر عدد التكوينات الممكنة إلى حد يتجاوز أي بحث يدوي. تحل HAQ هذه المشكلة بوكيل تعلّم معزّز (reinforcement learning agent) يجرّب عروض البتات على المسرّع الحقيقي ويتعلم مما يقيسه.
في اختبار منتصف الفصل يوم Wed 28 Oct 2026، توقّع أربعة أنواع من الأسئلة: لماذا تفيد الدقة المختلطة، وحساب حجم فضاء التصميم (64^n وكتابته كقوة للعدد 2)، ولماذا تستخدم HAQ القياس المباشر من العتاد (hardware feedback) بدلًا من FLOPs، وشرح سياسة الحافة (edge) مقابل السحابة (cloud) باستخدام الطبقات المحدودة بالذاكرة (memory bound) مقابل المحدودة بالحساب (compute bound). أما لبحثك وللتطبيقات المدمجة الحقيقية، فالدرس الأعمق هو أن أفضل سياسة ضغط تعتمد على العتاد الذي ستعمل عليه.
By the end you canفي نهاية هذا الجزء ستستطيع
- Explain why one bit width for every layer wastes bits, and what mixed precision changes.تشرح لماذا يهدر استخدام عرض بتات واحد لكل الطبقات بعض البتات، وما الذي تغيّره الدقة المختلطة (mixed precision).
- Compute the size of the mixed-precision design space for any number of layers and bit choices, in powers of two.تحسب حجم فضاء التصميم للدقة المختلطة لأي عدد من الطبقات وخيارات البتات، مكتوبًا كقوة للعدد 2.
- Describe HAQ as a reinforcement learning loop: state, action, reward, and where the accelerator sits.تصف HAQ كحلقة تعلّم معزّز (reinforcement learning): الحالة (state) والفعل (action) والمكافأة (reward)، وأين يقع المسرّع (accelerator).
- Argue why measured latency and energy beat proxies such as FLOPs or model size.تبرهن لماذا يتفوق زمن الاستجابة (latency) والطاقة المقيسان فعليًا على المؤشرات التقريبية مثل FLOPs أو حجم النموذج.
- Explain the edge and cloud policies for MobileNet using memory bound depthwise and compute bound pointwise layers.تشرح سياستي الحافة (edge) والسحابة (cloud) لشبكة MobileNet باستخدام طبقات depthwise المحدودة بالذاكرة (memory bound) وطبقات pointwise المحدودة بالحساب (compute bound).
- Place every technique in this lecture (PTQ, QAT, binary, ternary, mixed precision) on one map.تضع كل تقنية في هذه المحاضرة (PTQ و QAT والثنائية binary والثلاثية ternary والدقة المختلطة) على خريطة واحدة.
Take a three-layer network quantized the usual way: layer 1 gets 8-bit weights and 8-bit activations, and so do layers 2 and 3. Every value in the model now costs one byte. That is uniform quantization, and it is what you get from a default integer pipeline such as the one by Jacob et al.
خذ شبكة من ثلاث طبقات مكمّمة بالطريقة المعتادة: الطبقة 1 تحصل على أوزان من 8 بت وتنشيطات من 8 بت، وكذلك الطبقتان 2 و3. كل قيمة في النموذج تكلّف الآن بايتًا واحدًا. هذا هو التكميم الموحّد (uniform quantization)، وهو ما تحصل عليه من خط معالجة افتراضي بالأعداد الصحيحة (integer pipeline) مثل الذي قدّمه Jacob et al.
Now suppose you measured each layer and found that layer 1 still works with 4-bit weights and 5-bit activations, layer 2 needs 6 / 7, and layer 3 is happy with 5 / 4. That assignment is Mixed-precision quantization. The weight and activation of the same layer get their own widths, and neighbouring layers can differ freely. Count the bits per weight-activation pair: uniform spends 16 + 16 + 16 = 48, the mixed policy spends 9 + 13 + 9 = 31, about 35% fewer bits for the same three layers.
افترض الآن أنك قست كل طبقة ووجدت أن الطبقة 1 ما زالت تعمل بأوزان من 4 بت وتنشيطات من 5 بت، وأن الطبقة 2 تحتاج 6 / 7، وأن الطبقة 3 تكفيها 5 / 4. هذا التوزيع هو mixed-precision quantization (التكميم بدقة مختلطة). وزن الطبقة الواحدة وتنشيطها يحصل كل منهما على عرضه الخاص، ويمكن للطبقات المتجاورة أن تختلف بحرية. احسب البتات لكل زوج وزن وتنشيط: التكميم الموحّد ينفق 16 + 16 + 16 = 48، والسياسة المختلطة تنفق 9 + 13 + 9 = 31، أي بتات أقل بحوالي 35% للطبقات الثلاث نفسها.
Why layers deserve different widthsلماذا تستحق الطبقات عروضًا مختلفة
Layers are not equal in two separate ways. First, they differ in sensitivity: some layers, often the first and last, lose a lot of accuracy when squeezed, while many middle layers barely notice. Second, they differ in cost: a layer with huge feature maps or huge weight tensors dominates memory traffic or arithmetic, so each bit removed there saves far more time and energy than a bit removed from a tiny layer. Uniform precision ignores both facts. It pays full price in cheap, robust layers and gives no extra protection to fragile ones.
الطبقات ليست متساوية من ناحيتين منفصلتين. أولًا، تختلف في الحساسية (sensitivity): بعض الطبقات، وغالبًا الأولى والأخيرة، تفقد قدرًا كبيرًا من الدقة عند ضغطها، بينما كثير من الطبقات الوسطى بالكاد تتأثر. ثانيًا، تختلف في التكلفة: الطبقة ذات خرائط السمات (feature maps) الضخمة أو موترات الأوزان الضخمة تهيمن على حركة الذاكرة أو على العمليات الحسابية، لذا فكل بت يُزال منها يوفّر وقتًا وطاقة أكثر بكثير من بت يُزال من طبقة صغيرة. الدقة الموحّدة تتجاهل الحقيقتين معًا. فهي تدفع السعر كاملًا في الطبقات الرخيصة المتينة، ولا تعطي أي حماية إضافية للطبقات الهشّة.
| Uniformالموحّدة | Mixed precisionالدقة المختلطة | |
|---|---|---|
| Bit width decisionقرار عرض البتات | One global choice, for example 8 / 8اختيار عام واحد، مثلًا 8 / 8 | One choice per layer, separately for weights and activationsاختيار لكل طبقة، منفصل للأوزان وللتنشيطات |
| Who choosesمن يختار | The engineer, onceالمهندس، مرة واحدة | A search procedure, or an expert with rules of thumbإجراء بحث، أو خبير يتبع قواعد تقريبية |
| Sensitive layersالطبقات الحساسة | Get the same bits as robust layersتحصل على البتات نفسها التي تحصل عليها الطبقات المتينة | Can keep more bitsيمكنها الاحتفاظ ببتات أكثر |
| Robust or expensive layersالطبقات المتينة أو المكلفة | Pay for bits they do not needتدفع ثمن بتات لا تحتاجها | Can drop to 4 bits or fewerيمكن خفضها إلى 4 بت أو أقل |
| Hardware neededالعتاد المطلوب | Any integer engineأي محرّك للأعداد الصحيحة (integer engine) | An engine that runs several bit widths efficiently (BISMO, BitFusion)محرّك يشغّل عدة عروض بتات بكفاءة (BISMO وBitFusion) |
Recall
Give two different reasons why one layer should get more bits than another.اذكر سببين مختلفين يجعلان طبقة ما تستحق بتات أكثر من طبقة أخرى.
Suppose each weight tensor may use any width from 1 to 8 bits, and so may each activation. One layer then has 8 × 8 = 64 possible pairs. Two layers have 64 × 64 = 4,096 combined policies, because every choice in layer 1 can pair with every choice in layer 2. Three layers have 64^3 = 262,144.
افترض أن كل موتر أوزان يمكنه استخدام أي عرض من 1 إلى 8 بت، وكذلك كل تنشيط. عندها يكون للطبقة الواحدة 8 × 8 = 64 زوجًا ممكنًا. وللطبقتين 64 × 64 = 4,096 سياسة مجمّعة، لأن كل خيار في الطبقة 1 يمكن أن يقترن بكل خيار في الطبقة 2. وللطبقات الثلاث 64^3 = 262,144.
The general rule is the multiplication principle. With B_w weight choices, B_a activation choices and n layers, the Mixed-precision design space has
القاعدة العامة هي مبدأ الضرب (multiplication principle). مع B_w خيارًا للأوزان وB_a خيارًا للتنشيطات وn طبقة، يكون حجم design space (فضاء التصميم)
Writing it as a power of two is the exam trick: each layer adds log2(64) = 6 bits of "choice", so the exponent is just 6n. To turn it into a decimal number, multiply the exponent by log10(2) ≈ 0.301.
كتابته كقوة للعدد 2 هي حيلة الامتحان: كل طبقة تضيف log2(64) = 6 بتات من «الاختيار»، فيصبح الأس ببساطة 6n. ولتحويله إلى عدد عشري، اضرب الأس في log10(2) ≈ 0.301.
Worked exampleمثال محلول
How big is the space for MobileNetV1?ما حجم الفضاء لشبكة MobileNetV1؟
Count the layersعُدّ الطبقات
Counting depthwise and pointwise convolutions as separate layers, MobileNetV1 has 28 layers (Howard et al.).إذا عددنا التفافات depthwise وpointwise كطبقات منفصلة، فإن MobileNetV1 فيها 28 طبقة (Howard et al.).Apply the formulaطبّق الصيغة
64^28 = 2^(6 × 28) = 2^168.64^28 = 2^(6 × 28) = 2^168.Convert to decimalحوّل إلى النظام العشري
168 × 0.301 ≈ 50.6, so 2^168 ≈ 10^50.6 ≈ 3.7 × 10^50.168 × 0.301 ≈ 50.6، إذن 2^168 ≈ 10^50.6 ≈ 3.7 × 10^50.Sanity check with a smaller networkتحقّق منطقي بشبكة أصغر
Even 10 layers give 2^60 ≈ 1.15 × 10^18. Evaluating one policy per second would take about 3.7 × 10^10 years, more than twice the age of the universe. And evaluating a policy really means quantizing and fine-tuning, which takes far longer than a second.حتى 10 طبقات تعطي 2^60 ≈ 1.15 × 10^18. لو قيّمنا سياسة واحدة كل ثانية لاستغرق الأمر حوالي 3.7 × 10^10 سنة، أي أكثر من ضعف عمر الكون. وتقييم السياسة فعليًا يعني تكميم النموذج وضبطه الدقيق (fine-tuning)، وهذا يستغرق أطول بكثير من ثانية.Resultالنتيجة
The space grows exponentially in depth. Brute force is impossible for any real network, and hand-written rules ("keep the first and last layers at 8 bits") explore only a sliver of it.الفضاء ينمو أسيًا مع العمق. البحث الشامل (brute force) مستحيل لأي شبكة حقيقية، والقواعد المكتوبة يدويًا («أبقِ الطبقتين الأولى والأخيرة على 8 بت») لا تستكشف إلا شريحة صغيرة منه.
Quick checkاختبار سريع
With 8 weight and 8 activation bit choices per layer, how many mixed-precision policies does a 10-layer network have?مع 8 خيارات لبتات الأوزان و8 خيارات لبتات التنشيطات في كل طبقة، كم سياسة دقة مختلطة توجد لشبكة من 10 طبقات؟
Picture the search as a game played one layer at a time. The player looks at layer k: how many input and output channels it has, its kernel size, stride, feature map size, number of parameters, whether it is depthwise, and what it chose for the previous step. It then announces a bit width. After it has chosen for every layer, the whole quantized network is run on the accelerator and scored. Over many games, the player learns which choices pay off. That is HAQ (Hardware-Aware Automated Quantization).
تخيّل البحث كلعبة تُلعب طبقة بعد طبقة. ينظر اللاعب إلى الطبقة k: كم قناة دخل وقناة خرج فيها، وحجم النواة (kernel)، والخطوة (stride)، وحجم خريطة السمات، وعدد المعاملات، وهل هي depthwise، وماذا اختار في الخطوة السابقة. ثم يعلن عرض بتات. بعد أن يختار لكل الطبقات، تُشغَّل الشبكة المكمّمة كاملة على المسرّع وتُقيَّم. ومع تكرار اللعب مرات كثيرة، يتعلم اللاعب أي الاختيارات تؤتي ثمارها. هذه هي HAQ.
The reinforcement learning formulationصياغة المسألة كتعلّم معزّز (reinforcement learning)
- Agent. DDPG, an off-policy actor-critic algorithm for continuous actions (Lillicrap et al.). The actor proposes the action; the critic estimates how good that action is in that state, and the actor is trained to raise the critic's estimate.الوكيل (Agent). خوارزمية DDPG، وهي خوارزمية actor-critic خارج السياسة (off-policy) للأفعال المتصلة (Lillicrap et al.). الممثّل (actor) يقترح الفعل، والناقد (critic) يقدّر مدى جودة هذا الفعل في هذه الحالة، ويُدرَّب الممثّل على رفع تقدير الناقد.
- State. A ten-feature vector per layer, normalised to [0, 1]: (k, c_in, c_out, s_kernel, s_stride, s_feat, n_params, i_dw, i_w/a, a_(k-1)). Each layer takes two steps, one for weights and one for activations, flagged by i_w/a.الحالة (State). متجه من عشر خصائص لكل طبقة، مُطبَّع إلى [0, 1]: (k, c_in, c_out, s_kernel, s_stride, s_feat, n_params, i_dw, i_w/a, a_(k-1)). كل طبقة تأخذ خطوتين، واحدة للأوزان وواحدة للتنشيطات، ويميّز بينهما i_w/a.
- Action. A continuous value a_k ∈ [0, 1], rounded to a bit width. A continuous action keeps the order of widths (2 bits is more aggressive than 4, which is more aggressive than 8), which a set of unordered discrete labels would lose.الفعل (Action). قيمة متصلة a_k ∈ [0, 1] تُقرَّب إلى عرض بتات. الفعل المتصل يحافظ على ترتيب العروض (2 بت أشد ضغطًا من 4، و4 أشد ضغطًا من 8)، وهو ترتيب تفقده مجموعة من التسميات المنفصلة غير المرتّبة.
- Reward. Accuracy only, after one epoch of fine-tuning: R = 0.1 × (acc_quant − acc_origin). Resource limits are not in the reward; they are enforced separately, as below.المكافأة (Reward). الدقة فقط، بعد حقبة (epoch) واحدة من الضبط الدقيق: R = 0.1 × (acc_quant − acc_origin). حدود الموارد ليست جزءًا من المكافأة، بل تُفرض بشكل منفصل كما يلي.
Each layer is then quantized linearly, with the clipping range chosen to minimise the KL divergence between the original and quantized weight distributions, the same idea you met for activation clipping earlier in this lecture.
بعد ذلك تُكمَّم كل طبقة خطيًا، ويُختار مدى القص (clipping range) بحيث يقلّل KL divergence بين توزيع الأوزان الأصلي وتوزيعها المكمّم، وهي الفكرة نفسها التي رأيتها في قص التنشيطات سابقًا في هذه المحاضرة.
Hardware in the loopالعتاد داخل الحلقة (hardware in the loop)
The decisive step is how the budget is checked. After the agent proposes a full policy, HAQ maps the quantized model onto a real mixed-precision accelerator, or a cycle-accurate simulator of it, and reads back the latency and energy. If the policy exceeds the budget, HAQ lowers the bit widths layer by layer until it fits, and only then fine-tunes and computes the reward. This is Direct hardware feedback. Three targets were used: the BISMO bit-serial FPGA overlay as an edge design (Zynq-7020) and a cloud design (VU9P), and the BitFusion spatial ASIC, whose processing elements fuse to match each layer's width.
الخطوة الحاسمة هي طريقة التحقق من الميزانية. بعد أن يقترح الوكيل سياسة كاملة، تضع HAQ النموذج المكمّم على مسرّع حقيقي يدعم الدقة المختلطة، أو على محاكٍ دقيق على مستوى الدورة (cycle-accurate simulator) له، وتقرأ زمن الاستجابة والطاقة. إذا تجاوزت السياسة الميزانية، تخفّض HAQ عروض البتات طبقة بعد طبقة حتى تتسع لها، وبعدها فقط تجري الضبط الدقيق وتحسب المكافأة. هذا هو hardware feedback (التغذية الراجعة من العتاد). استُخدمت ثلاثة أهداف: طبقة BISMO التسلسلية على مستوى البت فوق FPGA (bit-serial FPGA overlay) بتصميم للحافة (Zynq-7020) وتصميم للسحابة (VU9P)، ومسرّع BitFusion المكاني (spatial ASIC) الذي تندمج عناصر المعالجة فيه لتطابق عرض كل طبقة.
Why not simply count FLOPs or model size? Because they are proxies, and the proxy can be wrong in exactly the places that matter. Two layers with equal FLOPs can have very different latency: an ordinary convolution reuses each loaded value many times, while a depthwise convolution reuses little and spends its time waiting on memory. Cache locality, kernel launch counts and memory bandwidth all shift the real number. The HAQ paper also shows that a policy tuned for one accelerator is not the best on another, so no single proxy can serve every target.
لماذا لا نكتفي بعدّ FLOPs أو حجم النموذج؟ لأنها مؤشرات تقريبية (proxies)، والمؤشر التقريبي قد يخطئ في المواضع المهمة بالضبط. طبقتان لهما FLOPs متساوية قد يختلف زمن استجابتهما كثيرًا: الالتفاف العادي يعيد استخدام كل قيمة محمَّلة مرات كثيرة، بينما التفاف depthwise يعيد الاستخدام قليلًا ويقضي وقته في انتظار الذاكرة. محلية الذاكرة المخبئية (cache locality) وعدد مرات إطلاق النوى (kernel launches) وعرض نطاق الذاكرة (memory bandwidth) كلها تغيّر الرقم الحقيقي. وتُظهر ورقة HAQ أيضًا أن السياسة المضبوطة لمسرّع واحد ليست الأفضل على مسرّع آخر، فلا يمكن لمؤشر تقريبي واحد أن يخدم كل الأهداف.
Recall
What are HAQ's state, action and reward, and where do latency and energy enter?ما الحالة والفعل والمكافأة في HAQ، وأين يدخل زمن الاستجابة والطاقة؟
Quick checkاختبار سريع
Why does HAQ query the accelerator instead of minimising FLOPs?لماذا تستعلم HAQ من المسرّع بدلًا من تقليل عدد FLOPs؟
Fix a latency budget on the BISMO edge accelerator and ask which MobileNetV1 is most accurate within it. At about 45.5 ms, uniform 4-bit quantization (trained with PACT) reaches 62.44% top-1 on ImageNet. HAQ's mixed policy, at the same 45.5 ms, reaches 67.40%. Same speed, almost five points more accuracy.
ثبّت ميزانية زمن استجابة على مسرّع BISMO للحافة، واسأل: أي نسخة من MobileNetV1 هي الأدق ضمنها؟ عند حوالي 45.5 ms، يصل التكميم الموحّد بـ 4 بت (المدرَّب بطريقة PACT) إلى دقة top-1 قدرها 62.44% على ImageNet. أما السياسة المختلطة من HAQ، عند 45.5 ms نفسها، فتصل إلى 67.40%. السرعة نفسها، وحوالي خمس نقاط دقة إضافية.
| Latency budgetميزانية زمن الاستجابة | Uniform (PACT)الموحّد (PACT) | HAQHAQ | Gain (points)المكسب (نقاط) |
|---|---|---|---|
| ≈45.5 ms≈45.5 ms | 62.44%62.44% | 67.40%67.40% | +4.96+4.96 |
| ≈57.7 ms≈57.7 ms | 67.00%67.00% | 70.58%70.58% | +3.58+3.58 |
| ≈70 ms≈70 ms | 70.46%70.46% | 71.20%71.20% | +0.74+0.74 |
| 96.20 ms96.20 ms | 70.82% (8 / 8)70.82% (8 / 8) | referenceالمرجع | dashed lineالخط المتقطع |
Three patterns in slide 71 are worth stating in an exam. First, HAQ is above uniform at every budget. Second, the gap is largest when the budget is tightest, because that is where choosing which layers to squeeze matters most. Third, at about 70 ms HAQ (71.20%) slightly beats even the full 8-bit model (70.82%, the grey dashed line), which needs 96.20 ms. That is roughly a 1.4× speed-up with no accuracy loss. Across settings, the paper reports 1.4× to 1.95× lower latency and 1.9× lower energy than fixed 8-bit quantization with negligible accuracy loss.
ثلاثة أنماط في الشريحة 71 تستحق الذكر في الامتحان. أولًا، HAQ أعلى من التكميم الموحّد عند كل ميزانية. ثانيًا، الفجوة تكون أكبر عندما تكون الميزانية أضيق، لأن هناك بالضبط يصبح اختيار الطبقات التي نضغطها أهم ما يكون. ثالثًا، عند حوالي 70 ms تتفوق HAQ (71.20%) قليلًا حتى على النموذج الكامل بـ 8 بت (70.82%، الخط الرمادي المتقطع)، الذي يحتاج 96.20 ms. أي تسريع بحوالي 1.4× دون خسارة في الدقة. وعبر الإعدادات المختلفة، تذكر الورقة زمن استجابة أقل بمقدار 1.4× إلى 1.95× وطاقة أقل بمقدار 1.9× مقارنة بالتكميم الثابت بـ 8 بت، مع خسارة دقة لا تُذكر.
One method, three budgetsطريقة واحدة، وثلاث ميزانيات
Because the budget is just whatever the hardware or the size counter reports, the same agent can optimise different objectives. Slide 72 shows MobileNetV1 under a model size budget, a latency budget and an energy budget. The shape repeats: HAQ dominates, with the biggest margin at the tightest budget. Under the size budget around 1.1 MB the gap is about 20 points (about 57% versus 37%); under the energy budget around 8 mJ it is about 5 points (about 67.5% versus 62.5%).
لأن الميزانية ببساطة هي أي رقم يعطيه العتاد أو عدّاد الحجم، يستطيع الوكيل نفسه أن يحسّن أهدافًا مختلفة. تعرض الشريحة 72 شبكة MobileNetV1 تحت ميزانية لحجم النموذج، وميزانية لزمن الاستجابة، وميزانية للطاقة. والشكل يتكرر: HAQ تتفوق، وأكبر هامش عند أضيق ميزانية. تحت ميزانية حجم حول 1.1 MB تكون الفجوة حوالي 20 نقطة (حوالي 57% مقابل 37%)، وتحت ميزانية طاقة حول 8 mJ تكون حوالي 5 نقاط (حوالي 67.5% مقابل 62.5%).
Recall
Why is HAQ's advantage over uniform quantization largest at the tightest budget?لماذا تكون أفضلية HAQ على التكميم الموحّد أكبر ما تكون عند أضيق ميزانية؟
Take one block of MobileNetV1 on a 14 × 14 feature map with 512 channels. It has a 3 × 3 depthwise convolution followed by a 1 × 1 pointwise convolution from 512 to 512 channels. Count what each one does and what it moves.
خذ كتلة واحدة من MobileNetV1 على خريطة سمات 14 × 14 بعدد 512 قناة. فيها التفاف depthwise بحجم 3 × 3 يليه التفاف pointwise بحجم 1 × 1 من 512 إلى 512 قناة. احسب ما يفعله كل منهما وما ينقله.
Worked exampleمثال محلول
Operational intensity of a depthwise and a pointwise layerالكثافة التشغيلية (operational intensity) لطبقة depthwise وطبقة pointwise
Arithmeticالعمليات الحسابية
Depthwise: 14 × 14 × 512 × 9 = 903,168 MACs. Pointwise: 14 × 14 × 512 × 512 = 51,380,224 MACs, about 57× more.Depthwise: 14 × 14 × 512 × 9 = 903,168 عملية MAC. Pointwise: 14 × 14 × 512 × 512 = 51,380,224 عملية MAC، أي أكثر بحوالي 57×.Memory at 8 bitsالذاكرة عند 8 بت
Both read a 100,352-value input and write a 100,352-value output. Depthwise has only 512 × 9 = 4,608 weights; pointwise has 512 × 512 = 262,144. Bytes moved: 205,312 versus 462,848.كلاهما يقرأ دخلًا من 100,352 قيمة ويكتب خرجًا من 100,352 قيمة. طبقة depthwise فيها 512 × 9 = 4,608 وزنًا فقط، وطبقة pointwise فيها 512 × 512 = 262,144. البايتات المنقولة: 205,312 مقابل 462,848.Operations per byteالعمليات لكل بايت
Counting a MAC as two operations, depthwise does 1,806,336 / 205,312 ≈ 8.8 ops/byte and pointwise does 102,760,448 / 462,848 ≈ 222 ops/byte, about 25× higher.إذا عددنا كل MAC كعمليتين، فإن depthwise تنفّذ 1,806,336 / 205,312 ≈ 8.8 عملية لكل بايت (ops/byte)، وpointwise تنفّذ 102,760,448 / 462,848 ≈ 222 عملية لكل بايت، أي أعلى بحوالي 25×.Resultالنتيجة
Depthwise is memory bound: it does little work per byte, so it waits on memory, and 97.8% of its bytes are feature maps. Pointwise is compute bound: it holds 98.3% of the block's MACs and almost all of its weights.طبقة depthwise memory bound (محدودة بالذاكرة): تنجز عملًا قليلًا لكل بايت، فتنتظر الذاكرة، و97.8% من بايتاتها خرائط سمات. أما pointwise فهي محدودة بالحساب (compute bound): تحمل 98.3% من عمليات MAC في الكتلة وكل أوزانها تقريبًا.
| Quantityالكمية | Depthwise 3 × 3Depthwise 3 × 3 | Pointwise 1 × 1Pointwise 1 × 1 |
|---|---|---|
| MACsعمليات MAC | 903,168903,168 | 51,380,22451,380,224 |
| Weightsالأوزان | 4,6084,608 | 262,144262,144 |
| Feature maps in + outخرائط السمات دخلًا وخرجًا | 200,704200,704 | 200,704200,704 |
| Bytes moved at 8 bitsالبايتات المنقولة عند 8 بت | 205,312205,312 | 462,848462,848 |
| Operational intensityالكثافة التشغيلية (operational intensity) | ≈8.8 ops/byte≈8.8 ops/byte | ≈222 ops/byte≈222 ops/byte |
| Share of bytes that are feature mapsنسبة البايتات التي هي خرائط سمات | ≈97.8%≈97.8% | ≈43.4%≈43.4% |
This is the roofline view (Williams, Waterman and Patterson): a layer whose operational intensity sits below the machine's ratio of peak compute to memory bandwidth is limited by memory; above it, by arithmetic. The same layer can land on different sides on different machines, which is exactly why HAQ finds different policies for edge and cloud.
هذه هي نظرة نموذج السقف (roofline) من Williams, Waterman and Patterson: الطبقة التي تقع كثافتها التشغيلية تحت نسبة ذروة الحساب إلى عرض نطاق الذاكرة في الجهاز تكون محدودة بالذاكرة، وإذا كانت فوقها فهي محدودة بالحساب. والطبقة نفسها قد تقع على جانبين مختلفين في أجهزة مختلفة، وهذا بالضبط سبب أن HAQ تجد سياسات مختلفة للحافة والسحابة.
Edge: batch 1, small bandwidthالحافة (edge): دفعة بحجم 1، وعرض نطاق صغير
On the edge accelerator with batch size 1, MobileNetV1's latency is dominated by the depthwise layers. Their time is spent moving feature maps, so the fastest way to speed them up is to shrink those activations. Dropping depthwise activations from 8 to 4 bits cuts this layer's traffic from 205,312 to about 104,960 bytes, nearly halving a memory bound layer's time. So HAQ gives depthwise activations fewer bits and spends the saved budget on pointwise layers.
على مسرّع الحافة بحجم دفعة 1، تهيمن طبقات depthwise على زمن استجابة MobileNetV1. وقتها يُصرف في نقل خرائط السمات، لذا فأسرع طريقة لتسريعها هي تقليص تلك التنشيطات. خفض تنشيطات depthwise من 8 إلى 4 بت يقلّل حركة البيانات في هذه الطبقة من 205,312 إلى حوالي 104,960 بايت، فيكاد يخفض زمن طبقة محدودة بالذاكرة إلى النصف. لذلك تعطي HAQ تنشيطات depthwise بتات أقل، وتنفق الميزانية الموفَّرة على طبقات pointwise.
Cloud: batch 16, large bandwidth and parallelismالسحابة (cloud): دفعة بحجم 16، وعرض نطاق كبير، وتوازٍ عالٍ
On the cloud accelerator, a batch of 16 images reuses every loaded weight 16 times, and the device has much more bandwidth and a bigger processing array. The network now behaves as compute bound, and compute lives in the pointwise layers (the MobileNet paper reports 95% of computation time and 75% of parameters in 1 × 1 convolutions). On a bit-serial engine such as BISMO, the work of a multiply grows with the number of weight bits times activation bits, so cutting pointwise widths saves the most time. Meanwhile HAQ raises depthwise widths to protect accuracy, which costs almost nothing because depthwise layers hold a tiny share of the weights (1.7% in the block above).
على مسرّع السحابة، تعيد دفعة من 16 صورة استخدام كل وزن محمَّل 16 مرة، والجهاز لديه عرض نطاق أكبر بكثير ومصفوفة معالجة أكبر. الشبكة الآن تتصرف كمحدودة بالحساب، والحساب يتركز في طبقات pointwise (تذكر ورقة MobileNet أن 95% من زمن الحساب و75% من المعاملات في التفافات 1 × 1). وفي محرّك تسلسلي على مستوى البت (bit-serial) مثل BISMO، يزداد عمل عملية الضرب مع حاصل ضرب عدد بتات الوزن في عدد بتات التنشيط، لذا فخفض عروض pointwise يوفّر أكبر قدر من الوقت. وفي الوقت نفسه ترفع HAQ عروض depthwise لحماية الدقة، وهذا لا يكلّف شيئًا تقريبًا لأن طبقات depthwise تحمل حصة ضئيلة من الأوزان (1.7% في الكتلة أعلاه).
| Edge (BISMO)الحافة (BISMO) | Cloud (BISMO)السحابة (BISMO) | |
|---|---|---|
| Batch sizeحجم الدفعة (batch size) | 11 | 1616 |
| Platform in HAQالمنصة في HAQ | Xilinx Zynq-7020, 8×8 PE arrayXilinx Zynq-7020، مع مصفوفة عناصر معالجة 8×8 | Xilinx VU9P, 16×16 PE arrayXilinx VU9P، مع مصفوفة عناصر معالجة 16×16 |
| What limits latencyما يحدّ زمن الاستجابة | Memory traffic of depthwise layersحركة الذاكرة في طبقات depthwise | Arithmetic of pointwise layersالعمليات الحسابية في طبقات pointwise |
| Depthwise layersطبقات depthwise | Fewer activation bitsبتات تنشيط أقل | More bits (cheap, few weights)بتات أكثر (رخيصة، أوزانها قليلة) |
| Pointwise layersطبقات pointwise | More bitsبتات أكثر | Fewer bitsبتات أقل |
The figure's annotations add a finer pattern on the cloud: depthwise layers get fewer bits in the first few layers and more in the last few. A reasonable reading, though the paper does not spell it out, is that early layers have large feature maps, so their depthwise traffic still costs time, while late layers have small feature maps, so extra precision there is cheap.
تضيف تعليقات الشكل نمطًا أدق على السحابة: طبقات depthwise تحصل على بتات أقل في الطبقات القليلة الأولى وعلى بتات أكثر في الطبقات القليلة الأخيرة. التفسير المعقول، مع أن الورقة لا تصرّح به، هو أن الطبقات المبكرة لها خرائط سمات كبيرة، فتظل حركة بيانات depthwise فيها مكلفة زمنيًا، بينما الطبقات المتأخرة لها خرائط سمات صغيرة، فتكون الدقة الإضافية فيها رخيصة.
Recall
Explain in four sentences why HAQ gives depthwise layers fewer bits on the edge and more on the cloud.اشرح في أربع جمل لماذا تعطي HAQ طبقات depthwise بتات أقل على الحافة وبتات أكثر على السحابة.
Quick checkاختبار سريع
On the cloud accelerator with batch 16, why can HAQ give depthwise layers more bits cheaply?على مسرّع السحابة بدفعة 16، لماذا تستطيع HAQ إعطاء طبقات depthwise بتات أكثر بتكلفة زهيدة؟
Quick checkاختبار سريع
On the edge BISMO accelerator with batch 1, which bits does HAQ cut most for MobileNetV1?على مسرّع BISMO للحافة بدفعة 1، أي البتات تخفضها HAQ أكثر من غيرها في MobileNetV1؟
Picture a trained floating-point MobileNet you must ship to a microcontroller next week. This lecture gave you a sequence of decisions, from the cheapest to the most involved, and slide 75 lists them.
تخيّل شبكة MobileNet مدرَّبة بالفاصلة العائمة (floating point) يجب أن تشحنها إلى متحكم دقيق (microcontroller) الأسبوع القادم. أعطتك هذه المحاضرة سلسلة من القرارات، من الأرخص إلى الأكثر تعقيدًا، والشريحة 75 تسردها.
- Quantize without retraining. Post-training quantization (PTQ) maps each real range onto the integer grid with a scale and zero point. Decide the granularity (per-tensor, per-channel or group) and the range, using min/max, an Exponential moving average (EMA), KL divergence or other clipping.كمّم دون إعادة تدريب. post-training quantization (التكميم بعد التدريب) يربط كل مدى حقيقي بشبكة الأعداد الصحيحة باستخدام scale وzero point. حدّد مستوى الحبيبية (granularity): per-tensor أو per-channel أو group، وحدّد المدى باستخدام min/max أو exponential moving average أو KL divergence أو أنواع أخرى من clipping (القص).
- Retrain if accuracy drops. Quantization-aware training (QAT) inserts Simulated (fake) quantization in the forward pass and uses the Straight-through estimator (STE) so gradients pass through the rounding.أعد التدريب إذا انخفضت الدقة. quantization-aware training (التدريب المراعي للتكميم) يُدخل fake quantization في التمرير الأمامي (forward pass) ويستخدم straight-through estimator حتى تمر التدرجات عبر عملية التقريب.
- Go to the extreme if the hardware wants it. Binarization and ternary weights turn multiplies into sign flips or XNOR and popcount.اذهب إلى الحد الأقصى إذا كان العتاد يريد ذلك. binarization (التحويل الثنائي) وternary weights (الأوزان الثلاثية) تحوّلان عمليات الضرب إلى قلب للإشارة أو إلى XNOR وpopcount.
- Let the bits differ per layer. Mixed precision, searched automatically with the target hardware in the loop, as HAQ does.اجعل البتات تختلف من طبقة لأخرى. الدقة المختلطة (mixed precision)، يُبحث عنها آليًا مع وجود العتاد المستهدف داخل الحلقة، كما تفعل HAQ.
| Stageالمرحلة | Techniquesالتقنيات | Question it answersالسؤال الذي تجيب عنه |
|---|---|---|
| PTQ: granularityPTQ: الحبيبية | Per-tensor, per-channel, group (VS-Quant, MX)per-tensor وper-channel وgroup (VS-Quant وMX) | How many scale factors, and over which valuesكم معامل scale نستخدم، وعلى أي قيم |
| PTQ: rangePTQ: المدى | Min/max, EMA, KL, clippingmin/max وEMA وKL والقص (clipping) | Which real range maps onto the integer gridأي مدى حقيقي يُربط بشبكة الأعداد الصحيحة |
| PTQ: roundingPTQ: التقريب | AdaRoundAdaRound | Round up or down per weight to minimise layer output errorالتقريب للأعلى أو للأسفل لكل وزن لتقليل خطأ خرج الطبقة |
| QATQAT | Fake quantization + STEالتكميم الزائف (fake quantization) مع STE | Train with the rounding in the loop so weights adaptالتدريب مع وجود التقريب داخل الحلقة لكي تتكيف الأوزان |
| Extreme low bitالبتات المنخفضة جدًا | Binary (BNN, XNOR-Net), ternary (TWN, TTQ)الثنائي (BNN وXNOR-Net)، والثلاثي (TWN وTTQ) | 1 or 2 bits, multiplies become sign flips, XNOR and popcount1 أو 2 بت، فتصبح عمليات الضرب قلبًا للإشارة وXNOR وpopcount |
| Mixed precisionالدقة المختلطة (mixed precision) | HAQHAQ | Different bits per layer, chosen with hardware in the loopبتات مختلفة لكل طبقة، تُختار مع وجود العتاد داخل الحلقة |
Slide 76 lists the 16 references the lecture draws on, taken from the MIT EfficientML.ai course. The ones worth opening first for this part are HAQ (Wang et al., CVPR 2019), Jacob et al. (CVPR 2018) for integer-only inference, and Krishnamoorthi's 2018 whitepaper for a practical PTQ and QAT guide. The rest map onto this lecture as follows: Deep Compression (Han et al.) and Intel's Distiller docs for the basics; data-free quantization (Nagel et al., listed as "Markus et al."), Banner et al. and NVIDIA's TensorRT talk for PTQ ranges; Hinton's lecture and Bengio et al. for the straight-through estimator; BNN, DoReFa-Net, PACT, WRPN, ABC-Net and INQ for low-bit training.
تسرد الشريحة 76 المراجع الـ 16 التي تعتمد عليها المحاضرة، وهي مأخوذة من مقرر MIT EfficientML.ai. أولى المراجع بالفتح لهذا الجزء هي HAQ (Wang et al., CVPR 2019)، وJacob et al. (CVPR 2018) للاستدلال بالأعداد الصحيحة فقط (integer-only inference)، والورقة البيضاء (whitepaper) لـ Krishnamoorthi عام 2018 كدليل عملي لـ PTQ وQAT. وبقية المراجع ترتبط بالمحاضرة كما يلي: Deep Compression (Han et al.) ووثائق Distiller من Intel للأساسيات؛ والتكميم دون بيانات (data-free quantization) لـ Nagel et al. (المدرج باسم «Markus et al.»)، وBanner et al.، ومحاضرة TensorRT من NVIDIA لمديات PTQ؛ ومحاضرة Hinton وBengio et al. لمقدّر straight-through؛ وBNN وDoReFa-Net وPACT وWRPN وABC-Net وINQ للتدريب منخفض البتات.
Recall
From memory, list the four families of techniques in this lecture and one key idea of each.من الذاكرة، اذكر العائلات الأربع من التقنيات في هذه المحاضرة وفكرة أساسية واحدة لكل منها.
Recapالخلاصة
If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا
- Uniform quantization gives every layer the same weight and activation width (for example 8 / 8). Mixed precision lets each layer choose, for example 4 / 5, 6 / 7, 5 / 4.التكميم الموحّد (uniform quantization) يعطي كل الطبقات عرض البتات نفسه للأوزان والتنشيطات (مثلًا 8 / 8). أما الدقة المختلطة (mixed precision) فتسمح لكل طبقة بأن تختار، مثلًا 4 / 5 و 6 / 7 و 5 / 4.
- With B_w weight choices and B_a activation choices, one layer has B_w × B_a options and n layers have (B_w × B_a)^n. With 8 × 8 = 64, that is 64^n = 2^(6n).مع B_w خيارًا للأوزان و B_a خيارًا للتنشيطات، يكون للطبقة الواحدة B_w × B_a خيارًا، ولعدد n من الطبقات (B_w × B_a)^n. ومع 8 × 8 = 64 يصبح العدد 64^n = 2^(6n).
- MobileNetV1 has 28 layers, so 64^28 = 2^168 (about 3.7e50). Even 10 layers give 2^60 (about 1.15e18). Brute force is impossible.شبكة MobileNetV1 فيها 28 طبقة، إذن 64^28 = 2^168 (حوالي 3.7e50). وحتى 10 طبقات تعطي 2^60 (حوالي 1.15e18). البحث الشامل (brute force) مستحيل.
- HAQ (Wang et al., CVPR 2019) uses a DDPG actor-critic agent. State: a 10-feature description of the layer. Action: a continuous value rounded to a bit width in [2, 8]. Reward: 0.1 × (quantized accuracy minus original accuracy).تستخدم HAQ (Wang et al., CVPR 2019) وكيل actor-critic من نوع DDPG. الحالة (state): وصف للطبقة من 10 خصائص. الفعل (action): قيمة متصلة تُقرَّب إلى عرض بتات في [2, 8]. المكافأة (reward): 0.1 × (دقة النموذج المكمّم ناقص الدقة الأصلية).
- Resource limits are enforced by measuring the policy on the accelerator (BISMO edge, BISMO cloud, BitFusion) and lowering bits until the budget is met. That is direct hardware feedback, not FLOPs.تُفرض حدود الموارد بقياس السياسة على المسرّع نفسه (BISMO edge و BISMO cloud و BitFusion)، ثم تخفيض البتات حتى تتحقق الميزانية. هذه تغذية راجعة مباشرة من العتاد (hardware feedback)، وليست FLOPs.
- On MobileNetV1 at about 45 ms on the edge, HAQ reaches 67.40% top-1 versus 62.44% for uniform 4-bit. HAQ wins under latency, energy and model size budgets alike.على MobileNetV1 عند حوالي 45 ms على الحافة (edge)، تصل HAQ إلى دقة top-1 قدرها 67.40% مقابل 62.44% للتكميم الموحّد بـ 4 بت. وتفوز HAQ تحت ميزانيات زمن الاستجابة والطاقة وحجم النموذج على حد سواء.
- Depthwise convolution is memory bound and pointwise is compute bound. Edge, batch 1: depthwise activations get fewer bits. Cloud, batch 16: depthwise gets more bits (cheap, few weights) and pointwise gets fewer.الالتفاف depthwise محدود بالذاكرة (memory bound)، والالتفاف pointwise محدود بالحساب (compute bound). على الحافة بدفعة 1 (batch 1): تحصل تنشيطات depthwise على بتات أقل. على السحابة بدفعة 16: تحصل depthwise على بتات أكثر (رخيصة، أوزانها قليلة) وتحصل pointwise على بتات أقل.
Sourcesالمصادر
- HAQ: Hardware-Aware Automated Quantization with Mixed PrecisionPaperWang, Liu, Lin, Lin, Han. CVPR 2019 (arXiv)State, action, reward, DDPG agent, BISMO and BitFusion setups, Table 3 latency results, Figures 3 and 4 policiesالحالة والفعل والمكافأة، ووكيل DDPG، وإعدادات BISMO و BitFusion، ونتائج زمن الاستجابة في الجدول 3، والسياسات في الشكلين 3 و 4(opens in a new tab)(يفتح في تبويب جديد)
- MobileNets: Efficient Convolutional Neural Networks for Mobile Vision ApplicationsPaperHoward et al. (arXiv 2017)28 layers; 95% of computation time and 75% of parameters in 1 × 1 convolutions28 طبقة، و95% من زمن الحساب و75% من المعاملات في التفافات 1 × 1(opens in a new tab)(يفتح في تبويب جديد)
- BISMO: A Scalable Bit-Serial Matrix Multiplication Overlay for Reconfigurable ComputingPaperUmuroglu, Rasnayake, Själander. FPL 2018 (arXiv)The bit-serial accelerator whose performance scales with the required precisionالمسرّع التسلسلي على مستوى البت (bit-serial) الذي يتناسب أداؤه مع الدقة المطلوبة(opens in a new tab)(يفتح في تبويب جديد)
- Bit Fusion: Bit-Level Dynamically Composable Architecture for Accelerating Deep Neural NetworksPaperSharma et al. ISCA 2018 (arXiv)The spatial accelerator that fuses bit-level elements to match each layer's widthالمسرّع المكاني الذي يدمج عناصر على مستوى البت لتطابق عرض كل طبقة(opens in a new tab)(يفتح في تبويب جديد)
- Continuous control with deep reinforcement learningPaperLillicrap et al. ICLR 2016 (arXiv)DDPG, the actor-critic algorithm HAQ uses for continuous actionsDDPG، خوارزمية actor-critic التي تستخدمها HAQ للأفعال المتصلة(opens in a new tab)(يفتح في تبويب جديد)
- Roofline: An Insightful Visual Performance Model for Floating-Point Programs and Multicore ArchitecturesPaperWilliams, Waterman, Patterson. UC Berkeley EECS-2008-134Memory bound versus compute bound by operational intensityالمحدود بالذاكرة (memory bound) مقابل المحدود بالحساب (compute bound) حسب الكثافة التشغيلية(opens in a new tab)(يفتح في تبويب جديد)
- MIT 6.5940 TinyML and Efficient Deep Learning Computing, Lecture 6: Quantization (Part II)DocsMIT HAN LabThe EfficientML.ai course the slides and the reference list come fromمقرر EfficientML.ai الذي أُخذت منه الشرائح وقائمة المراجع(opens in a new tab)(يفتح في تبويب جديد)