Majid Al-RaimiActivation functions and the transformerدوال التنشيط والمحوّل (Transformer)

COE 592Lecture 02المحاضرة 02Part 06الجزء 06

Activation functions and the transformerدوال التنشيط والمحوّل (Transformer)

The non-linearities used in embedded networks, then the transformer block: scaled dot-product attention worked by hand and the position-wise feed-forward network.اللاخطيات المستخدمة في الشبكات المضمّنة، ثم كتلة المحوّل: انتباه الضرب النقطي المقيّس (scaled dot-product attention) محلولًا يدويًا، وشبكة التغذية الأمامية الموضعية (position-wise feed-forward).

Conceptsالمفاهيم
6
Slidesالشرائح
39-45
Readingمدة القراءة
36 min36 دقيقة
Understoodما فهمته
0/6 conceptsمفاهيم

Why this part mattersلماذا يهمّ هذا الجزء

Every model you will compress, quantize or deploy on a microcontroller in this course has an activation function between its layers, and that one choice decides whether int8 inference is exact and cheap or approximate and slow. MobileNetV2 and V3 picked ReLU6 and hard swish for exactly this reason.

The second half of the part opens the transformer, now the model family you are most likely to be asked to shrink for the edge. Its attention block has a cost that grows with the square of the sequence length, which is the first number an embedded designer must reason about. The exam asks for the attention formula with shapes, the sqrt(d_k) argument, and a small attention computed by hand, so the part ends with two worked slides checked line by line, including two arithmetic slips on the slides themselves.

كل نموذج ستضغطه أو تكمّمه (quantize) أو تنشره على متحكم دقيق (microcontroller) في هذا المقرر توجد بين طبقاته دالة تفعيل، وهذا الاختيار الواحد يحدد هل سيكون الاستدلال بـ int8 دقيقًا ورخيصًا أم تقريبيًا وبطيئًا. ولهذا السبب تحديدًا اختارت MobileNetV2 وV3 الدالتين ReLU6 وhard swish.

النصف الثاني من هذا الجزء يفتح الـ transformer، وهو الآن عائلة النماذج التي يُرجَّح أن يُطلب منك تصغيرها للأجهزة الطرفية (edge). كتلة الانتباه فيه لها كلفة تنمو مع مربع طول التسلسل، وهذا أول رقم يجب أن يفكّر فيه مصمم الأنظمة المضمّنة. والاختبار يطلب صيغة الانتباه مع الأشكال، وحجة القسمة على sqrt(d_k)، وحساب انتباه صغير يدويًا، لذلك ينتهي الجزء بشريحتين محلولتين مُراجعتين سطرًا بسطر، بما في ذلك خطآن حسابيان في الشرائح نفسها.

By the end you canفي نهاية هذا الجزء ستستطيع

  1. Explain why activations must be non-linear, and write sigmoid, ReLU, ReLU6, leaky ReLU, swish and hard swish with their ranges and derivatives.تشرح لماذا يجب أن تكون دوال التفعيل غير خطية، وتكتب sigmoid وReLU وReLU6 وleaky ReLU وswish وhard swish مع مداها ومشتقاتها.
  2. Argue which activations suit quantized embedded models and why: a bounded range and no exponential.تحتج لأي دوال التفعيل تناسب النماذج المضمّنة المكمّمة (quantized) ولماذا: مدى محدود وعدم وجود دالة أُسّية.
  3. Draw the transformer block and place multi-head attention, Add and Norm, the feed-forward network and positional encoding.ترسم كتلة الـ transformer وتحدد موضع multi-head attention وAdd and Norm والشبكة الأمامية (feed-forward network) والترميز الموضعي (positional encoding).
  4. State Attention(Q, K, V) with every matrix shape, explain the query, key and value roles, and justify the sqrt(d_k) scaling.تكتب Attention(Q, K, V) مع شكل كل مصفوفة، وتشرح أدوار الاستعلام (query) والمفتاح (key) والقيمة (value)، وتبرّر القسمة على sqrt(d_k).
  5. Compute a small self-attention and a position-wise FFN by hand, and explain why the N x N attention matrix is the embedded bottleneck.تحسب self-attention صغيرًا وشبكة FFN تعمل على كل موضع (position-wise) يدويًا، وتشرح لماذا مصفوفة الانتباه N x N هي عنق الزجاجة في الأنظمة المضمّنة.

Start with the Neuron from the beginning of the lecture: three inputs, three weights, a Bias, and then y = f(w0 x0 + w1 x1 + w2 x2 + b). Now ask what happens if f is the identity and you stack two such layers. The second layer computes W2 (W1 x + b1) + b2, which multiplies out to (W2 W1) x + (W2 b1 + b2): one matrix, one bias, one linear layer. Ten layers would collapse the same way. Depth buys nothing.

ابدأ بـ neuron (العصبون) من بداية المحاضرة: ثلاثة مدخلات، وثلاثة weights (أوزان)، وbias (انحياز)، ثم y = f(w0 x0 + w1 x1 + w2 x2 + b). الآن اسأل: ماذا يحدث لو كانت f هي الدالة المحايدة (identity) وكدّست طبقتين من هذا النوع؟ الطبقة الثانية تحسب W2 (W1 x + b1) + b2، وبفك الأقواس تصبح (W2 W1) x + (W2 b1 + b2): مصفوفة واحدة، وانحياز واحد، أي طبقة خطية واحدة. وعشر طبقات ستنهار بالطريقة نفسها. العمق لا يضيف شيئًا.

Worked exampleمثال محلول

Two linear layers collapse into oneطبقتان خطيتان تنهاران إلى طبقة واحدة

  1. Write the second layer in terms of the firstاكتب الطبقة الثانية بدلالة الأولى

    y = W2 h + b2 with h = W1 x + b1, so y = W2 W1 x + W2 b1 + b2.
    y = W2 h + b2 حيث h = W1 x + b1، إذن y = W2 W1 x + W2 b1 + b2.
  2. Name the productsسمِّ حواصل الضرب

    Set W = W2 W1 and b = W2 b1 + b2. Both are constants once training stops.
    ضع W = W2 W1 وb = W2 b1 + b2. كلاهما ثابت بمجرد انتهاء التدريب.
  3. A single fully connected layerطبقة واحدة متصلة بالكامل

    y = W x + b. The stacked network can only draw straight decision boundaries, exactly like the one layer it collapsed into. Goodfellow, Bengio and Courville open their chapter on feedforward networks with XOR for this reason: no single line separates its four points, but a hidden layer of rectified units does.
    y = W x + b. الشبكة المكدّسة لا تستطيع رسم إلا حدود قرار مستقيمة، تمامًا مثل الطبقة الواحدة التي انهارت إليها. ولهذا السبب يفتتح Goodfellow وBengio وCourville فصلهم عن الشبكات الأمامية (feedforward) بمسألة XOR: لا يوجد خط واحد يفصل نقاطها الأربع، لكن طبقة مخفية من الوحدات المقوِّمة (rectified units) تفعل ذلك.

That is why the slide says activation functions are typically non-linear. The Activation function is the bend that stops the collapse, and it sits after every weighted sum in every Hidden layer. Slide 39 places it on the CNN component map beside convolution, pooling, fully connected layers and the normalization block of the previous part: the only component with no parameters and no shape arithmetic, just a pointwise bend applied to every value. Which bend to use is a real design decision, and on embedded hardware it is decided by two questions the slide leaves implicit: does the function need an exponential, and is its output bounded?

لهذا تقول الشريحة إن دوال التفعيل تكون عادةً غير خطية. فـ activation function (دالة التفعيل) هي الانحناء الذي يمنع الانهيار، وتأتي بعد كل مجموع موزون في كل hidden layer (طبقة مخفية). تضعها الشريحة 39 على خريطة مكونات الـ CNN بجانب الالتفاف (convolution) والتجميع (pooling) والطبقات المتصلة بالكامل وكتلة التطبيع (normalization) من الجزء السابق: إنها المكوّن الوحيد الذي لا يملك معاملات ولا حسابات أشكال، بل مجرد انحناء نقطي يُطبَّق على كل قيمة. واختيار الانحناء قرار تصميمي حقيقي، وفي العتاد المضمّن يحسمه سؤالان تتركهما الشريحة ضمنيين: هل تحتاج الدالة إلى دالة أُسّية، وهل مخرجها محدود؟

The six on the slide, and what each costs a microcontrollerالدوال الست في الشريحة، وكلفة كل منها على المتحكم الدقيق

Sigmoid, 1 / (1 + e^-x), squashes any input into (0, 1). Its derivative is s(1 - s), at most 0.25 at zero and already 0.0066 at x = 5. A sigmoid unit therefore saturates across most of its domain, which is why Goodfellow and colleagues say its use as a hidden unit is now discouraged. It also needs an exponential per element. ReLU, max(0, x), has derivative 0 or 1, needs a single comparison, and is the same textbook's recommended default; AlexNet is the network that made it standard.

Sigmoid، أي 1 / (1 + e^-x)، تضغط أي مدخل إلى المجال (0, 1). مشتقتها s(1 - s)، وأقصاها 0.25 عند الصفر، وتصبح 0.0066 فقط عند x = 5. لذلك تتشبّع وحدة sigmoid على معظم مجالها، وهذا سبب قول Goodfellow وزملائه إن استخدامها كوحدة مخفية لم يعد مُستحسَنًا. وهي تحتاج أيضًا إلى دالة أُسّية لكل عنصر. أما ReLU، أي max(0, x)، فمشتقتها 0 أو 1، وتحتاج مقارنة واحدة فقط، وهي الخيار الافتراضي الذي يوصي به الكتاب نفسه؛ وAlexNet هي الشبكة التي جعلتها معيارًا.

ReLU6, min(max(0, x), 6), is ReLU with a ceiling. Krizhevsky introduced the cap in 2010 to encourage sparse features; MobileNetV2 kept it for a different reason, robustness when used with low-precision computation. Leaky ReLU, max(alpha x, x), replaces the flat negative side with a small slope so a unit that is off still passes a gradient; Maas, Hannun and Ng used alpha = 0.01, which is still PyTorch's default. Swish, x / (1 + e^-x), is x times its own sigmoid (the general form is x sigmoid(beta x), PyTorch calls it SiLU). It dips to -0.278 at x = -1.28 before rising, and Ramachandran, Zoph and Le found it beats ReLU on deeper models. It costs an exponential, which is the whole problem on a Cortex-M.

ReLU6، أي min(max(0, x), 6)، هي ReLU مع سقف. قدّم Krizhevsky هذا السقف عام 2010 لتشجيع الميزات المتناثرة (sparse features)؛ واحتفظت به MobileNetV2 لسبب مختلف، وهو المتانة عند استخدامها مع حسابات منخفضة الدقة. Leaky ReLU، أي max(alpha x, x)، تستبدل الجانب السالب المسطّح بميل صغير بحيث تظل الوحدة المطفأة تمرّر تدرّجًا؛ استخدم Maas وHannun وNg القيمة alpha = 0.01، وما زالت القيمة الافتراضية في PyTorch. أما Swish، أي x / (1 + e^-x)، فهي x مضروبة في الـ sigmoid الخاصة بها (الصيغة العامة x sigmoid(beta x)، وتسميها PyTorch باسم SiLU). تنخفض إلى -0.278 عند x = -1.28 قبل أن ترتفع، ووجد Ramachandran وZoph وLe أنها تتفوق على ReLU في النماذج الأعمق. لكنها تكلّف دالة أُسّية، وهذه هي المشكلة كلها على معالج Cortex-M.

Hard swish is MobileNetV3's answer: x ReLU6(x + 3) / 6. Expand it and you get the slide's three cases, 0 for x <= -3, x for x >= 3, and x(x + 3) / 6 between. Howard and colleagues give three reasons: optimized ReLU6 kernels exist on virtually every framework and chip, the piecewise form removes the precision loss that different approximate sigmoids introduce in quantized mode, and it can run with fewer memory accesses. They saw no discernible accuracy difference against real swish, and an optimized h-swish added about 1 ms over ReLU on a Pixel 1.

Hard swish هي إجابة MobileNetV3: x ReLU6(x + 3) / 6. بفكّها تحصل على الحالات الثلاث في الشريحة: 0 عندما x <= -3، وx عندما x >= 3، وx(x + 3) / 6 بينهما. يذكر Howard وزملاؤه ثلاثة أسباب: أنوية (kernels) ReLU6 المحسّنة موجودة تقريبًا على كل إطار عمل وكل شريحة، والصيغة المجزّأة تزيل فقدان الدقة الذي تسببه تقريبات sigmoid المختلفة في الوضع المكمَّم، ويمكن تشغيلها بعدد أقل من الوصول إلى الذاكرة. ولم يلاحظوا أي فرق ملموس في الدقة مقارنة بـ swish الحقيقية، وأضافت h-swish المحسّنة حوالي 1 ms فقط فوق ReLU على هاتف Pixel 1.

h-swish(x)=x⋅ReLU6⁡(x+3)6={0x≤−3xx≥3x(x+3)6otherwise\text{h-swish}(x) = x \cdot \frac{\operatorname{ReLU6}(x + 3)}{6} = \begin{cases} 0 & x \le -3 \\ x & x \ge 3 \\ \dfrac{x(x + 3)}{6} & \text{otherwise} \end{cases}
One clamp, one add, one multiply, no exponentialقصّ واحد وجمع واحد وضرب واحد، بلا دالة أسية
Swish (faint) and hard swish drawn over it: flat until -3, a parabola to 3, then the identity lineSwish (باهتة) وhard swish مرسومة فوقها: مسطّحة حتى -3، ثم قطع مكافئ حتى 3، ثم خط الدالة المحايدة
xxswishswishhard swishhard swishgapالفجوة
-3-3-0.142-0.142000.1420.142
-1-1-0.269-0.269-0.333-0.3330.0640.064
00000000
110.7310.7310.6670.6670.0640.064
332.8582.858330.1420.142
443.9283.928440.0720.072
Swish against hard swish at a few inputsSwish مقابل hard swish عند بعض المدخلات

The largest gap on [-6, 6] is 0.142, at the two knots x = -3 and x = 3. The derivative also lines up: swish has slope 0.5 at zero and hard swish has (2x + 3) / 6 = 0.5 there too.

أكبر فجوة على المجال [-6, 6] هي 0.142، عند العقدتين x = -3 وx = 3. والمشتقة تتطابق أيضًا: ميل swish عند الصفر 0.5، وميل hard swish هناك (2x + 3) / 6 = 0.5 كذلك.

FunctionالدالةFormulaالصيغةRangeالمدىDerivativeالمشتقةNeedsتحتاجEmbedded noteملاحظة للأنظمة المضمّنة
SigmoidSigmoid1 / (1 + e^-x)1 / (1 + e^-x)(0, 1)(0, 1)s(1 - s), at most 0.25s(1 - s)، و0.25 على الأكثرexpexpSaturates both sides; output gates and probabilities onlyتتشبّع من الجانبين؛ لبوابات المخرج والاحتمالات فقط
ReLUReLUmax(0, x)max(0, x)[0, inf)[0, inf)0 or 10 أو 1max onlymax فقطDefault hidden unit; unbounded, so the int8 range must be calibratedالوحدة المخفية الافتراضية؛ غير محدودة، لذا يجب معايرة مدى int8
ReLU6ReLU6min(max(0, x), 6)min(max(0, x), 6)[0, 6][0, 6]1 on (0, 6), else 01 على (0, 6)، و0 فيما عدا ذلكmax and minmax وminBounded: fixed quantization grid; MobileNetV2's choiceمحدودة: شبكة تكميم ثابتة؛ اختيار MobileNetV2
Leaky ReLULeaky ReLUmax(alpha x, x)max(alpha x, x)(-inf, inf)(-inf, inf)alpha or 1alpha أو 1max onlymax فقطKeeps a small gradient for negative inputs, alpha = 0.01 by defaultتُبقي تدرّجًا صغيرًا للمدخلات السالبة، والقيمة الافتراضية alpha = 0.01
SwishSwishx / (1 + e^-x)x / (1 + e^-x)[-0.278, inf)[-0.278, inf)s + x s(1 - s)s + x s(1 - s)expexpSmooth and non-monotonic; better than ReLU on deep models, costly on MCUsناعمة وغير رتيبة (non-monotonic)؛ أفضل من ReLU في النماذج العميقة، ومكلفة على المتحكمات الدقيقة (MCUs)
Hard swishHard swishx ReLU6(x + 3) / 6x ReLU6(x + 3) / 6[-0.375, inf)[-0.375, inf)0, (2x + 3)/6, or 10 أو (2x + 3)/6 أو 1multiply and clampضرب وقصّ (clamp)Swish traced with a ruler; MobileNetV3's replacement for swishSwish مرسومة بالمسطرة؛ البديل الذي اعتمدته MobileNetV3 عن swish
tanhtanh2 s(2x) - 12 s(2x) - 1(-1, 1)(-1, 1)1 - tanh^21 - tanh^2expexpZero-centred sigmoid; still saturatessigmoid متمركزة حول الصفر؛ وما زالت تتشبّع
GELUGELUx Phi(x)x Phi(x)[-0.17, inf)[-0.17, inf)Phi(x) + x phi(x)Phi(x) + x phi(x)erf or tanherf أو tanhDefault in BERT and GPT style transformersالافتراضية في نماذج الـ transformer من نمط BERT وGPT
ELUELUx if x > 0 else e^x - 1x if x > 0 else e^x - 1(-1, inf)(-1, inf)1 or e^x1 أو e^xexpexpNegative saturation at -1 pushes the mean toward zeroالتشبّع السالب عند -1 يدفع المتوسط نحو الصفر
MishMishx tanh(softplus(x))x tanh(softplus(x))[-0.31, inf)[-0.31, inf)numeric in practiceتُحسب عدديًا في التطبيقexp, log, tanhexp وlog وtanhSmooth like swish, even more expensiveناعمة مثل swish، وأغلى منها كلفة
Activation functions: formula, range, derivative and MCU costدوال التفعيل: الصيغة والمدى والمشتقة والكلفة على المتحكم الدقيق (MCU)

Why bounded is what int8 wantsلماذا المحدودية هي ما يريده int8

Quantizing an Activation tensor to 8 bits means choosing a range and dividing it into 255 steps. With ReLU6 the range is known before you see a single input: [0, 6], so each step is 6 / 255 = 0.0235 and every layer shares the same grid. With plain ReLU the range depends on the data. If one activation channel happens to reach 60, the step becomes 60 / 255 = 0.235, ten times coarser, for every value in that tensor, including the many small ones. MobileNetV2's sentence about low-precision robustness is the citation; the arithmetic is the reason.

تكميم موتّر activation (تفعيلات) إلى 8 بتات يعني اختيار مدى وتقسيمه إلى 255 خطوة. مع ReLU6 يكون المدى معروفًا قبل أن ترى أي مدخل: [0, 6]، فكل خطوة 6 / 255 = 0.0235 وتتشارك كل الطبقات الشبكة نفسها. أما مع ReLU العادية فالمدى يعتمد على البيانات. فإذا وصلت قناة تفعيل واحدة إلى 60، تصبح الخطوة 60 / 255 = 0.235، أي أخشن بعشر مرات، لكل قيمة في ذلك الموتّر، بما فيها القيم الصغيرة الكثيرة. جملة MobileNetV2 عن المتانة مع الدقة المنخفضة هي المرجع؛ والحساب هو السبب.

ReLU rises out of the picture; a ceiling at 6 bends it flat and hands the quantizer a fixed grid of 255 stepsReLU ترتفع خارج الصورة؛ وسقف عند 6 يجعلها مسطّحة ويعطي المكمِّم (quantizer) شبكة ثابتة من 255 خطوة

Worked exampleمثال محلول

uint8 grid for ReLU6 versus an unbounded ReLUشبكة uint8 لـ ReLU6 مقابل ReLU غير محدودة

  1. Boundedمحدودة

    Range [0, 6], 255 steps, step size 6 / 255 = 0.0235. Fixed at design time.
    المدى [0, 6]، و255 خطوة، وحجم الخطوة 6 / 255 = 0.0235. ثابت منذ وقت التصميم.
  2. Unbounded, calibrated on dataغير محدودة، ومعايَرة على البيانات

    Observed range [0, 60], step size 60 / 255 = 0.235. One outlier channel sets the grid for everyone.
    المدى الملاحَظ [0, 60]، وحجم الخطوة 60 / 255 = 0.235. قناة شاذة واحدة تحدد الشبكة للجميع.
  3. Resultالنتيجة

    Same 8 bits, ten times the rounding error per value. A bounded activation removes the calibration risk entirely.
    نفس الـ 8 بتات، لكن خطأ التقريب لكل قيمة عشرة أضعاف. التفعيل المحدود يزيل خطر المعايرة (calibration) تمامًا.
SimulatorمحاكيActivation plotter with derivative and MCU costراسم دوال التنشيط مع المشتقة وكلفة MCU
-20246-6-4-20246
Swish: y = x / (1 + e^-x)Hard swish: y = x ReLU6(x + 3) / 6
1.0
f(1.0)0.731
derivativeالمشتقة0.928slope the gradient seesالميل الذي يراه التدرج
gap to Hard swishالفرق عن Hard swish0.064largest gap on the plot 0.142أكبر فرق على الرسم 0.142
cost on an MCUالكلفة على MCU
needs an exponentialتحتاج دالة أُسّية
boundedمحدودة
no, range [-0.278, inf)لا، المدى [-0.278, inf)

Quick checkاختبار سريع

Which activation removes the exponential so a quantized microcontroller can run it cheaply?أي دالة تفعيل تُلغي الدالة الأُسّية بحيث يستطيع متحكم دقيق مكمَّم تشغيلها بكلفة رخيصة؟

Recall

Which activation would you pick for an int8 MCU model and why, and what would you use instead of swish?أي دالة تفعيل ستختار لنموذج int8 على MCU ولماذا، وماذا ستستخدم بدل swish؟

ReLU6, because its output is bounded in [0, 6] so the quantizer has a fixed grid (MobileNetV2 chose it for low-precision robustness). Instead of swish, hard swish, because it replaces the sigmoid with ReLU6(x + 3) / 6: no exponential, piecewise polynomial.
ReLU6، لأن مخرجها محدود في [0, 6] فيكون للمكمِّم شبكة ثابتة (اختارتها MobileNetV2 للمتانة مع الدقة المنخفضة). وبدل swish نستخدم hard swish، لأنها تستبدل الـ sigmoid بـ ReLU6(x + 3) / 6: بلا دالة أُسّية، وكثيرة حدود مجزّأة.

Feed a four-word sentence into the model of Vaswani and colleagues. Each word becomes an embedding of d_model = 512 numbers, a positional encoding of the same size is added to it, and the four vectors enter the first encoder layer. That layer does exactly two things: a Multi-head attention step that lets each word read the others, then a position-wise feed-forward network that processes each word on its own. Around each of the two sits an Add and Norm. Repeat the layer N = 6 times and you have the encoder of the original Transformer.

أدخل جملة من أربع كلمات إلى نموذج Vaswani وزملائه. تصبح كل كلمة تضمينًا (embedding) من d_model = 512 رقمًا، ويُضاف إليه positional encoding (ترميز موضعي) بالحجم نفسه، ثم تدخل المتجهات الأربعة إلى طبقة المُرمِّز (encoder) الأولى. هذه الطبقة تفعل شيئين فقط: خطوة multi-head attention تسمح لكل كلمة بقراءة الكلمات الأخرى، ثم position-wise feed-forward network (شبكة أمامية تعمل على كل موضع) تعالج كل كلمة وحدها. وحول كل واحدة من الاثنتين توجد خطوة Add and Norm. كرّر الطبقة N = 6 مرات وستحصل على مُرمِّز الـ transformer الأصلي.

Embedding + PE
d_model = 512

Token vector plus a sinusoidal position vector.

متجه الرمز مضافًا إليه متجه موضع جيبي.

Multi-head attention
h = 8 headsh = 8 رؤوس

Every token reads every other token.

كل رمز يقرأ كل رمز آخر.

Add and Norm
residual + LayerNorm

LayerNorm(x + Sublayer(x)).

Feed-forward
512 to 2048 to 512

Same two-layer MLP on each position.

شبكة MLP نفسها ذات الطبقتين على كل موضع.

Add and Norm, then x NAdd and Norm، ثم x N
N = 6

Output feeds the next identical layer.

يغذّي الإخراجُ الطبقةَ المطابقة التالية.

One encoder layer: two sub-layers, each wrapped in a residual add and a LayerNorm, stacked N timesطبقة مُرمِّز واحدة: طبقتان فرعيتان، كل منهما ملفوفة باتصال متبقٍّ (residual add) وLayerNorm، ومكدّسة N مرة

The Add and Norm box is the link back to the normalization part. Each sub-layer's output is added to its own input (a residual connection, the ResNet idea) and the sum goes through Layer normalization: LayerNorm(x + Sublayer(x)). LayerNorm rather than BatchNorm because it normalizes each token's 512 features on their own, so it behaves identically at training and inference and needs no batch statistics, which is what you want for variable-length sequences. Jurafsky and Martin describe the whole stack as a residual stream that each component reads from and adds back to.

صندوق Add and Norm هو الرابط مع جزء التطبيع (normalization). مخرج كل طبقة فرعية يُضاف إلى مدخلها نفسه (residual connection، أي الاتصال المتبقي، وهي فكرة ResNet) ثم يمر المجموع عبر layer normalization: LayerNorm(x + Sublayer(x)). نستخدم LayerNorm بدل BatchNorm لأنها تطبّع ميزات كل token البالغة 512 وحدها، فتتصرف بالطريقة نفسها في التدريب والاستدلال ولا تحتاج إحصاءات الدفعة (batch statistics)، وهذا ما تريده للتسلسلات متغيرة الطول. ويصف Jurafsky وMartin المكدّس كله بأنه تيار متبقٍّ (residual stream) يقرأ منه كل مكوّن ثم يضيف إليه.

A residual stream runs left to right; attention and the FFN branch off, compute, and add their result back before a LayerNormتيار متبقٍّ يجري من اليسار إلى اليمين؛ يتفرّع عنه الانتباه والـ FFN، فيحسبان ثم يضيفان نتيجتهما إليه قبل LayerNorm

Base model hyperparameters (Vaswani et al. 2017)المعاملات الفائقة للنموذج الأساسي (Vaswani وزملاؤه 2017)

Layers per stack Nعدد الطبقات في كل مكدّس N
66
Model width d_modelعرض النموذج d_model
512512
Heads hعدد الرؤوس h
88
Head size d_k = d_vحجم الرأس d_k = d_v
512 / 8 = 64512 / 8 = 64
FFN hidden width d_ffالعرض المخفي للـ FFN d_ff
20482048

Inside the two sub-layersداخل الطبقتين الفرعيتين

Multi-head attention runs h = 8 copies of Scaled dot-product attention in parallel. Each head first projects the queries, keys and values with its own small linear layers down to d_k = 64, computes attention, and the eight 64-wide results are concatenated back to 512 and passed through one more linear layer. Because each head works at one eighth of the width, the total cost is about that of a single head at full width, and each head is free to attend to a different relationship.

يشغّل multi-head attention عدد h = 8 نسخ من scaled dot-product attention على التوازي. كل رأس (head) يُسقط أولًا الاستعلامات والمفاتيح والقيم بطبقاته الخطية الصغيرة الخاصة إلى d_k = 64، ثم يحسب الانتباه، ثم تُضمّ (concatenate) النتائج الثماني ذات العرض 64 لتعود إلى 512 وتمر عبر طبقة خطية إضافية واحدة. ولأن كل رأس يعمل بثُمن العرض، فالكلفة الكلية تقارب كلفة رأس واحد بالعرض الكامل، وكل رأس حرّ في الانتباه إلى علاقة مختلفة.

MultiHead(Q,K,V)=Concat(head1,…,headh) WO,headi=Attention(QWiQ,KWiK,VWiV)\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\, W^O, \qquad \text{head}_i = \text{Attention}(Q W_i^Q, K W_i^K, V W_i^V)
h parallel attentions on projected inputs, concatenated, then one linear layerh من آليات الانتباه المتوازية على مدخلات مُسقَطة، تُضم معًا ثم تمر بطبقة خطية واحدة

The feed-forward sub-layer is a two-layer MLP with a ReLU between, widening from 512 to 2048 and back. It is applied to each position separately and identically, which the paper notes is the same as two convolutions with kernel size 1. This is where the block's non-linearity lives: once the attention weights are fixed, attention itself is a linear mix of the values.

الطبقة الفرعية الأمامية هي MLP من طبقتين بينهما ReLU، تتسع من 512 إلى 2048 ثم تعود. تُطبَّق على كل موضع بشكل منفصل ومتطابق، وتلاحظ الورقة أن هذا يعادل التفافين (convolutions) بحجم نواة 1. هنا يسكن اللاخطّية في الكتلة: فبمجرد تثبيت أوزان الانتباه، يكون الانتباه نفسه مزيجًا خطيًا من القيم.

FFN(x)=max⁡(0,  xW1+b1) W2+b2\text{FFN}(x) = \max(0,\; x W_1 + b_1)\, W_2 + b_2
Linear, ReLU, linear, the same weights at every positionخطية ثم ReLU ثم خطية، بالأوزان نفسها في كل موضع

Position, the decoder, and the outputالموضع، والمُفكِّك (decoder)، والمخرج

Attention has no notion of order: swap two tokens and the same weights come out swapped. So before the first layer, a positional encoding is added to each embedding. The paper uses sinusoids of different wavelengths, PE(pos, 2i) = sin(pos / 10000^(2i / d_model)) and cosine for odd indices, so that every position gets a distinct 512-vector and relative offsets are easy to express.

الانتباه لا يعرف مفهوم الترتيب: بدّل موضعي token وستخرج الأوزان نفسها مبدّلة. لذلك يُضاف ترميز موضعي إلى كل تضمين قبل الطبقة الأولى. تستخدم الورقة موجات جيبية بأطوال موجية مختلفة، PE(pos, 2i) = sin(pos / 10000^(2i / d_model)) وجيب التمام (cosine) للمؤشرات الفردية، بحيث يحصل كل موضع على متجه مميّز من 512 بعدًا ويسهل التعبير عن الإزاحات النسبية.

The decoder stack (right side of the slide) repeats the same layer with two changes. Its self-attention is masked so that position i cannot see positions after i, which together with the outputs being shifted right by one keeps training honest about what is known when. And a third sub-layer, encoder-decoder attention, takes queries from the decoder and keys and values from the encoder output. A final linear layer and softmax turn the last vector into next-token probabilities.

مكدّس المُفكِّك (decoder، الجانب الأيمن من الشريحة) يكرر الطبقة نفسها مع تغييرين. الأول أن self-attention فيه مُقنَّع (masked) بحيث لا يرى الموضع i المواضع التي بعد i، وهذا مع إزاحة المخرجات إلى اليمين بمقدار واحد يُبقي التدريب صادقًا بشأن ما هو معروف في كل لحظة. والثاني طبقة فرعية ثالثة، هي انتباه المُرمِّز والمُفكِّك (encoder-decoder attention)، تأخذ الاستعلامات من المُفكِّك والمفاتيح والقيم من مخرج المُرمِّز. وفي النهاية تحوّل طبقة خطية ثم softmax المتجه الأخير إلى احتمالات الـ token التالي.

Recall

What does the position-wise FFN do that attention does not, and vice versa?ما الذي تفعله الـ FFN التي تعمل على كل موضع ولا يفعله الانتباه، والعكس؟

The FFN applies the same two-layer MLP with ReLU to each token independently and never mixes positions. Attention is the only sub-layer that moves information between positions, and once its weights are fixed it is a linear mix of the values.
الـ FFN تطبّق الـ MLP نفسها ذات الطبقتين مع ReLU على كل token بشكل مستقل ولا تمزج المواضع أبدًا. والانتباه هو الطبقة الفرعية الوحيدة التي تنقل المعلومات بين المواضع، وبمجرد تثبيت أوزانه يكون مزيجًا خطيًا من القيم.

Type a phrase into YouTube's search bar. The phrase is your query. Every video carries a title and description, which is its key. The video itself is the value. Search scores your query against every key, ranks the matches, and hands you back videos. Attention does the same three things with vectors, with one twist: instead of returning the single best video it returns a blend of all the values, weighted by how well each key matched. That is the Query, key, value design of the slide.

اكتب عبارة في شريط البحث في YouTube. العبارة هي استعلامك (query). كل فيديو يحمل عنوانًا ووصفًا، وهذا هو مفتاحه (key). والفيديو نفسه هو القيمة (value). يقارن البحث استعلامك بكل مفتاح، ويرتّب المطابقات، ويعيد لك الفيديوهات. والانتباه يفعل الأشياء الثلاثة نفسها بالمتجهات، مع اختلاف واحد: بدل أن يعيد أفضل فيديو واحد، يعيد مزيجًا من كل القيم، موزونًا بمدى تطابق كل مفتاح. هذا هو تصميم query-key-value في الشريحة.

In self-attention all three come from the same input matrix X of N tokens, each through its own learned projection: Q = X W_Q, K = X W_K, V = X W_V. Jurafsky and Martin give the roles precisely: the query is the current element being compared, a key is a preceding input being compared to it to produce a similarity weight, and a value is what gets weighted and summed. The comparison is a dot product, so the whole score table is one matrix multiply, and the paper names the result Scaled dot-product attention.

في self-attention تأتي الثلاثة كلها من مصفوفة المدخل نفسها X المكوّنة من N token، كل منها عبر إسقاط متعلَّم خاص به: Q = X W_Q، K = X W_K، V = X W_V. ويحدد Jurafsky وMartin الأدوار بدقة: الاستعلام هو العنصر الحالي الذي تجري مقارنته، والمفتاح مدخل سابق يُقارَن به لإنتاج وزن تشابه، والقيمة هي ما يُوزَن ويُجمع. المقارنة حاصل ضرب نقطي (dot product)، فجدول الدرجات كله عملية ضرب مصفوفات واحدة، وتسمّي الورقة الناتج scaled dot-product attention.

Attention(Q,K,V)=softmax ⁣(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{Q K^{T}}{\sqrt{d_k}}\right) V
Scaled dot-product attentionانتباه الضرب النقطي المُحجَّم (scaled dot-product attention)

Shapes for N tokens with head size d_k and value size d_vالأشكال لعدد N من الـ tokens بحجم رأس d_k وحجم قيمة d_v

Q, K
N x d_kN x d_k
V
N x d_vN x d_v
Q K^T (scores) and softmax outputQ K^T (الدرجات) ومخرج softmax
N x NN x N
Outputالمخرج
N x d_vN x d_v

Read the slide's diagram bottom to top with those shapes: Q and K of shape N x d multiply into an N x N table of scores, the optional mask sets forbidden entries to minus infinity, softmax turns each row into a probability distribution, and multiplying by V (N x d) gives one output row per token. The masked version is what the decoder uses so that a token cannot attend to what comes after it.

اقرأ مخطط الشريحة من الأسفل إلى الأعلى بهذه الأشكال: Q وK بشكل N x d يُضربان لينتجا جدول درجات بشكل N x N، ويضع القناع الاختياري (mask) الخانات الممنوعة عند سالب ما لا نهاية، وتحوّل softmax كل صف إلى توزيع احتمالي، والضرب في V (N x d) يعطي صف مخرج واحدًا لكل token. والنسخة المقنّعة هي ما يستخدمه المُفكِّك حتى لا يستطيع token أن ينتبه إلى ما يأتي بعده.

Why divide by the square root of d_kلماذا نقسم على الجذر التربيعي لـ d_k

If the components of a query and a key have mean zero and variance one, their dot product has variance d_k: it is a sum of d_k products. So raw scores grow with the head size, and Vaswani and colleagues observe that large dot products push the softmax into regions where it has extremely small gradients. Goodfellow and colleagues say the same about softmax in general: its outputs saturate when the differences between inputs become extreme. Dividing by sqrt(d_k) brings the variance back to one, whatever the head size.

إذا كان متوسط مكونات الاستعلام والمفتاح صفرًا وتباينها واحدًا، فإن تباين حاصل ضربهما النقطي يساوي d_k: لأنه مجموع d_k حاصل ضرب. إذن تكبر الدرجات الخام مع حجم الرأس، ويلاحظ Vaswani وزملاؤه أن حواصل الضرب النقطي الكبيرة تدفع softmax إلى مناطق تكون فيها تدرّجاتها صغيرة جدًا. ويقول Goodfellow وزملاؤه الشيء نفسه عن softmax عمومًا: تتشبّع مخرجاتها عندما تصبح الفروق بين المدخلات متطرفة. والقسمة على sqrt(d_k) تعيد التباين إلى واحد، مهما كان حجم الرأس.

d_kd_kUnscaled scoresالدرجات دون قسمةsoftmax unscaledsoftmax دون قسمةsoftmax after / sqrt(d_k)softmax بعد القسمة على sqrt(d_k)
44(2, 0, -2)(2, 0, -2)(0.867, 0.117, 0.016)(0.867, 0.117, 0.016)(0.665, 0.245, 0.090)(0.665, 0.245, 0.090)
6464(8, 0, -8)(8, 0, -8)(1.000, 0.000, 0.000)(1.000, 0.000, 0.000)(0.665, 0.245, 0.090)(0.665, 0.245, 0.090)
512512(22.6, 0, -22.6)(22.6, 0, -22.6)(1.000, 0.000, 0.000)(1.000, 0.000, 0.000)(0.665, 0.245, 0.090)(0.665, 0.245, 0.090)
Three scores that are one standard deviation apart, before and after scalingثلاث درجات يفصل بين كل منها انحراف معياري واحد، قبل القسمة وبعدها

Without the division, a head of size 64 already turns a modest spread into a one-hot answer of (1.000, 0.000, 0.000), and the gradient through those zeros is essentially zero. With it, every head size sees the same healthy distribution. Softmax is also shift-invariant, softmax(z) = softmax(z + c), so only differences between scores matter, which is what implementations exploit for numerical stability.

بدون القسمة، رأس بحجم 64 يحوّل انتشارًا متواضعًا إلى إجابة أحادية (one-hot) هي (1.000, 0.000, 0.000)، والتدرّج عبر تلك الأصفار يكاد يكون صفرًا. ومع القسمة، يرى كل حجم رأس التوزيع الصحي نفسه. كذلك softmax لا تتأثر بالإزاحة، softmax(z) = softmax(z + c)، فالفروق بين الدرجات وحدها هي المهمة، وهذا ما تستغله التطبيقات البرمجية لتحقيق الاستقرار العددي.

The N x N matrix is the embedded constraintمصفوفة N x N هي القيد في الأنظمة المضمّنة

Every query is scored against every key, so one head at one layer produces N^2 scores, whatever the feature size. Jurafsky and Martin state it plainly: attention is quadratic in the length of the input. Vaswani's complexity table writes the per-layer cost as O(n^2 d). Double the sequence and you quadruple the score matrix; multiply by heads and layers and it is the dominant activation memory of the model.

كل استعلام يُقارَن بكل مفتاح، فرأس واحد في طبقة واحدة ينتج N^2 درجة، مهما كان حجم الميزات. ويقولها Jurafsky وMartin بوضوح: الانتباه تربيعي في طول المدخل. وجدول التعقيد عند Vaswani يكتب كلفة الطبقة على أنها O(n^2 d). ضاعف التسلسل وستضاعف مصفوفة الدرجات أربع مرات؛ واضربها في عدد الرؤوس والطبقات وستجدها أكبر ذاكرة تفعيلات في النموذج.

A 4 x 4 score grid grows to 8 x 8 and 16 x 16: four times the tokens, sixteen times the scoresشبكة درجات 4 x 4 تكبر إلى 8 x 8 ثم 16 x 16: أربعة أضعاف الـ tokens تعني ستة عشر ضعف الدرجات
Tokens Nعدد الـ tokens NEntries N^2عدد الخانات N^2Memoryالذاكرة
16162562561 KB1 KB
64644,0964,09616 KB16 KB
25625665,53665,536256 KB256 KB
1,0241,0241,048,5761,048,5764 MB4 MB
4,0964,09616,777,21616,777,21664 MB64 MB
Scores per head per layer in fp32الدرجات لكل رأس في كل طبقة بدقة fp32

Quick checkاختبار سريع

What is the shape of the softmax output in single-head attention over N tokens with head size d_k?ما شكل مخرج softmax في انتباه برأس واحد على N من الـ tokens بحجم رأس d_k؟

Quick checkاختبار سريع

Why does Vaswani et al. divide Q K^T by the square root of d_k?لماذا يقسم Vaswani وزملاؤه Q K^T على الجذر التربيعي لـ d_k؟

Recall

Write the attention formula and give the shape of every matrix for N tokens and head size d_k.اكتب صيغة الانتباه وأعطِ شكل كل مصفوفة لعدد N من الـ tokens وحجم رأس d_k.

Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V. Q and K are N x d_k, V is N x d_v, Q K^T and its softmax are N x N, and the output is N x d_v.
Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V. المصفوفتان Q وK بشكل N x d_k، وV بشكل N x d_v، وQ K^T وناتج softmax عليها بشكل N x N، والمخرج بشكل N x d_v.

Recall

Where does the N^2 come from and why does it matter on embedded hardware?من أين يأتي N^2 ولماذا يهم على العتاد المضمّن؟

Every query is scored against every key, so N tokens give N x N scores per head per layer. Memory and compute grow quadratically with sequence length (Vaswani Table 1: O(n^2 d)), so on a small SRAM the score matrix caps the usable sequence length.
كل استعلام يُقارَن بكل مفتاح، فـ N من الـ tokens تعطي N x N درجة لكل رأس في كل طبقة. الذاكرة والحساب ينموان تربيعيًا مع طول التسلسل (جدول 1 عند Vaswani: O(n^2 d))، لذلك على ذاكرة SRAM صغيرة تحدّ مصفوفة الدرجات طول التسلسل القابل للاستخدام.

Tom Yeh's drawing makes Scaled dot-product attention concrete with numbers you can check at a desk. Four tokens, each with six features, are the columns x1 = (2, 0, 0, 0, 2, 1), x2 = (0, 1, 2, 0, 0, 0), x3 = (0, 0, 1, 1, 0, 1) and x4 = (2, 0, 0, 1, 0, 1). Three 3 x 6 matrices W_Q, W_K and W_V project them to the queries, keys and values of head size d_k = 3. Those 54 numbers are the only learned parameters; everything else is computed from the input.

رسم Tom Yeh يجعل scaled dot-product attention ملموسًا بأرقام يمكنك التحقق منها على مكتبك. أربعة tokens، لكل منها ست ميزات، هي الأعمدة x1 = (2, 0, 0, 0, 2, 1) وx2 = (0, 1, 2, 0, 0, 0) وx3 = (0, 0, 1, 1, 0, 1) وx4 = (2, 0, 0, 1, 0, 1). ثلاث مصفوفات بشكل 3 x 6 هي W_Q وW_K وW_V تُسقطها إلى queries, keys and values (الاستعلامات والمفاتيح والقيم) بحجم رأس d_k = 3. هذه الأرقام الـ 54 هي المعاملات المتعلَّمة الوحيدة؛ وكل ما عداها يُحسب من المدخل.

Two shortcuts keep the arithmetic in your head. Dividing by sqrt(3) = 1.732 is replaced by dividing by 2 and dropping the fraction (rounding toward zero, so -1 / 2 becomes 0), and e^x is replaced by 3^x, which has the same shape and integer values for non-negative exponents. The shortcuts preserve the ranking for three of the four queries; the comparison table below shows the one query where halving squashes the gap away.

اختصاران يُبقيان الحساب في رأسك. القسمة على sqrt(3) = 1.732 تُستبدل بالقسمة على 2 وحذف الكسر (التقريب نحو الصفر، فتصبح -1 / 2 صفرًا 0)، وe^x تُستبدل بـ 3^x، التي لها الشكل نفسه وقيم صحيحة للأسس غير السالبة. يحافظ الاختصاران على الترتيب في ثلاثة من الاستعلامات الأربعة؛ وجدول المقارنة أدناه يُظهر الاستعلام الوحيد الذي يسحق فيه التنصيف الفرق.

Worked exampleمثال محلول

Column 1: what token 1 attends toالعمود 1: إلى ماذا ينتبه الـ token رقم 1

  1. Projectالإسقاط

    q1 = W_Q x1 = (2, 0, 3). The keys are k1 = (0, 0, 1), k2 = (2, 1, 0), k3 = (1, 0, -1), k4 = (0, 0, 1), and the values v1 = (20, 0, 0), v2 = (0, 0, 10), v3 = (0, 10, 0), v4 = (20, 10, 0).
    q1 = W_Q x1 = (2, 0, 3). المفاتيح هي k1 = (0, 0, 1)، k2 = (2, 1, 0)، k3 = (1, 0, -1)، k4 = (0, 0, 1)، والقيم v1 = (20, 0, 0)، v2 = (0, 0, 10)، v3 = (0, 10, 0)، v4 = (20, 10, 0).
  2. Scoreالدرجات

    Dot products of q1 with each key: 3, 4, -1, 3. Key 2 is the best match.
    حواصل الضرب النقطي لـ q1 مع كل مفتاح: 3, 4, -1, 3. المفتاح 2 هو أفضل تطابق.
  3. Scaleالقسمة (التحجيم)

    Divide by 2 and truncate: 1, 2, 0, 1. (Exact: divide by 1.732, giving 1.73, 2.31, -0.58, 1.73.)
    اقسم على 2 واحذف الكسر: 1, 2, 0, 1. (القيمة الدقيقة: القسمة على 1.732 تعطي 1.73, 2.31, -0.58, 1.73.)
  4. Softmax with powers of threeSoftmax بقوى العدد ثلاثة

    3^1, 3^2, 3^0, 3^1 = 3, 9, 1, 3, sum 16, weights 0.19, 0.56, 0.06, 0.19, drawn as .2, .6, 0, .2.
    3^1, 3^2, 3^0, 3^1 = 3, 9, 1, 3، والمجموع 16، والأوزان 0.19, 0.56, 0.06, 0.19، وتُرسم .2, .6, 0, .2.
  5. Weighted sum of valuesالمجموع الموزون للقيم

    z1 = 0.2 v1 + 0.6 v2 + 0 v3 + 0.2 v4 = (4, 0, 0) + (0, 0, 6) + (4, 2, 0).
    z1 = 0.2 v1 + 0.6 v2 + 0 v3 + 0.2 v4 = (4, 0, 0) + (0, 0, 6) + (4, 2, 0).
  6. z1 = (8, 2, 6)z1 = (8, 2, 6)

    Token 1's new representation is mostly value 2 (weight 0.6), with a fifth each of values 1 and 4. The exact computation gives (10.3, 2.8, 4.6) with the same ranking.
    التمثيل الجديد للـ token رقم 1 هو في معظمه القيمة 2 (بوزن 0.6)، مع خُمس من كل من القيمتين 1 و4. والحساب الدقيق يعطي (10.3, 2.8, 4.6) بالترتيب نفسه.
wij=3trunc⁡(sij/2)∑j′3trunc⁡(sij′/2)  ≈  esij/3∑j′esij′/3w_{ij} = \frac{3^{\operatorname{trunc}(s_{ij} / 2)}}{\sum_{j'} 3^{\operatorname{trunc}(s_{ij'} / 2)}} \;\approx\; \frac{e^{s_{ij} / \sqrt{3}}}{\sum_{j'} e^{s_{ij'} / \sqrt{3}}}
The by-hand softmax: base 3 instead of e, halving and rounding toward zero instead of dividing by sqrt(3)softmax اليدوية: الأساس 3 بدلًا من e، والتنصيف مع التقريب نحو الصفر بدلًا من القسمة على sqrt(3)
SimulatorمحاكيScaled dot-product attention on four tokens, one step at a timeانتباه الضرب النقطي المُحجَّم على أربعة رموز، خطوة في كل مرة
Q (rows q1 to q4)
d1d2d3
q1
q2
q3
q4
K (rows k1 to k4)
d1d2d3
k1
k2
k3
k4
V (rows v1 to v4)
d1d2d3
v1
v2
v3
v4
paper view: Q K^T, rows are queriesعرض الورقة: Q K^T، الصفوف هي الاستعلامات
k1k2k3k4
q10.200.600.100.20
q20.300.300.100.30
q30.400.100.000.40
q40.100.800.100.10
query q1 against every keyالاستعلام q1 مقابل كل مفتاح
q . ktrunc(s / 2)3^sweight
k1313.000.200
k2429.000.600
k3-101.000.100
k4313.000.200

Sum of the exponentials 16.00. Each weight is its power divided by this sum, rounded to one decimal as on the slide.مجموع الأُسّيات 16.00. كل وزن هو قوّته مقسومة على هذا المجموع، مقرّبة إلى منزلة عشرية واحدة كما في الشريحة.

z1 = sum of weight times valuez1 = مجموع حاصل ضرب كل وزن في قيمته

0.20 (20, 0, 0) + 0.60 (0, 0, 10) + 0.10 (0, 10, 0) + 0.20 (20, 10, 0)

(8.0, 3.0, 6.0)

Head size d_k = 3, N = 4 tokens, so the score matrix has 16 entries whatever the feature size. The highlighted row is the selected query; the teal entries are the keys that win (all of them when tied). Switch between the two arithmetics: the weights move and the winner rarely does. Try q2 to see the one default row where halving erases the gap.حجم الرأس d_k = 3، وعدد الرموز N = 4، لذلك تحتوي مصفوفة الدرجات على 16 مدخلًا مهما كان حجم الخصائص. الصف المظلل هو الاستعلام المختار، والمدخلات الفيروزية هي المفاتيح الفائزة (كلها عند التعادل). بدّل بين طريقتي الحساب: تتغير الأوزان ونادرًا ما يتغير الفائز. جرّب q2 لترى الصف الافتراضي الوحيد الذي تمحو فيه القسمة على اثنين الفارق.

4
scores per head16= N^2
fp32 memory64 Bone head, one layer, scores onlyرأس واحد، وطبقة واحدة، والدرجات فقط
QueryالاستعلامScores q . kالدرجات q . kSlide weightsأوزان الشريحةExact weightsالأوزان الدقيقةSlide zz في الشريحةExact zz الدقيقة
q1 = (2, 0, 3)q1 = (2, 0, 3)3, 4, -1, 33, 4, -1, 3.2, .6, 0, .2.2, .6, 0, .2.258, .459, .026, .258.258, .459, .026, .258(8, 2, 6)(8, 2, 6)(10.3, 2.8, 4.6)(10.3, 2.8, 4.6)
q2 = (1, 1, 2)q2 = (1, 1, 2)2, 3, -1, 22, 3, -1, 2.3, .3, .1, .3.3, .3, .1, .3.253, .450, .045, .253.253, .450, .045, .253(12, 4, 3)(12, 4, 3)(10.1, 3.0, 4.5)(10.1, 3.0, 4.5)
q3 = (0, 1, 2)q3 = (0, 1, 2)2, 1, -2, 22, 1, -2, 2.4, .2, 0, .4.4, .2, 0, .4.376, .211, .037, .376.376, .211, .037, .376(16, 4, 2)(16, 4, 2)(15.0, 4.1, 2.1)(15.0, 4.1, 2.1)
q4 = (2, 1, 1)q4 = (2, 1, 1)1, 5, 1, 11, 5, 1, 1.1, .7, .1, .1.1, .7, .1, .1.077, .770, .077, .077.077, .770, .077, .077(4, 2, 7)(4, 2, 7)(3.1, 1.5, 7.7)(3.1, 1.5, 7.7)
Slide arithmetic versus exact, all four queries (keys in order k1 to k4, q2 corrected)حساب الشريحة مقابل الحساب الدقيق للاستعلامات الأربعة كلها (المفاتيح بالترتيب من k1 إلى k4، مع تصحيح q2)

For q1, q3 and q4 the same key wins under both arithmetics, and the second-best key is the same too: softmax cares about differences between scores, and a monotone squashing of those differences preserves the order as long as the differences survive. The numbers drift (a weight of 0.6 becomes 0.46), the decision does not. The corrected q2 is the exception that shows how coarse the shortcut is: its scores 2, 3, -1, 2 halve to 1, 1, 0, 1, so the by-hand softmax hands keys 1, 2 and 4 the same 0.3 while the exact softmax still separates key 2 at 0.45. Integer halving erased a difference of one, which is exactly the kind of information a real quantizer must be careful not to lose.

بالنسبة لـ q1 وq3 وq4 يفوز المفتاح نفسه في الحسابين، والمفتاح الثاني هو نفسه أيضًا: softmax تهتم بالفروق بين الدرجات، وأي ضغط رتيب (monotone) لتلك الفروق يحافظ على الترتيب ما دامت الفروق باقية. الأرقام تنحرف (وزن 0.6 يصبح 0.46)، لكن القرار لا يتغير. والـ q2 المصحّحة هي الاستثناء الذي يُظهر مدى خشونة الاختصار: درجاتها 2, 3, -1, 2 تتنصّف إلى 1, 1, 0, 1، فتعطي softmax اليدوية المفاتيح 1 و2 و4 الوزن نفسه 0.3، بينما ما زالت softmax الدقيقة تميّز المفتاح 2 عند 0.45. التنصيف الصحيح محا فرقًا مقداره واحد، وهذا بالضبط نوع المعلومات الذي يجب أن يحرص المكمِّم الحقيقي على عدم فقدانه.

Quick checkاختبار سريع

On slide 43 with query q1 = (2, 0, 3), which key receives the largest attention weight?في الشريحة 43 مع الاستعلام q1 = (2, 0, 3)، أي مفتاح يحصل على أكبر وزن انتباه؟

Recall

With q = (2, 0, 3) and keys (0, 0, 1), (2, 1, 0), (1, 0, -1), (0, 0, 1), which key wins and what are the raw scores?مع q = (2, 0, 3) والمفاتيح (0, 0, 1) و(2, 1, 0) و(1, 0, -1) و(0, 0, 1)، أي مفتاح يفوز وما الدرجات الخام؟

Scores 3, 4, -1, 3. Key 2 wins; keys 1 and 4 tie for second, key 3 is the only negative match.
الدرجات 3, 4, -1, 3. يفوز المفتاح 2؛ ويتعادل المفتاحان 1 و4 في المركز الثاني، والمفتاح 3 هو التطابق السالب الوحيد.

The second by-hand slide picks up where the first stopped. Five tokens with three features arrive from the previous block, x1 = (5, 0, 1), x2 = (6, 2, 0), x3 = (0, 4, 1), x4 = (7, 0, 1), x5 = (0, 3, 0). The attention weight matrix A is given rather than computed, and it is deliberately simple: each column has exactly two ones, so each token attends equally to itself and to one other token (the next neighbour for tokens 1 to 4, and token 1 for token 5). The attention-weighted feature of token 1 is then a plain sum, z1 = x1 + x2 = (11, 2, 1), and likewise z2 = x2 + x3, z3 = x3 + x4, z4 = x4 + x5 and z5 = x1 + x5.

الشريحة اليدوية الثانية تكمل من حيث توقفت الأولى. خمسة tokens بثلاث ميزات تصل من الكتلة السابقة: x1 = (5, 0, 1)، x2 = (6, 2, 0)، x3 = (0, 4, 1)، x4 = (7, 0, 1)، x5 = (0, 3, 0). مصفوفة أوزان الانتباه A معطاة وليست محسوبة، وهي بسيطة عمدًا: في كل عمود واحدان بالضبط، فكل token ينتبه بالتساوي إلى نفسه وإلى token واحد آخر (الجار التالي للـ tokens من 1 إلى 4، والـ token رقم 1 للـ token رقم 5). عندها تكون الميزة الموزونة بالانتباه للـ token رقم 1 مجموعًا بسيطًا، z1 = x1 + x2 = (11, 2, 1)، وبالمثل z2 = x2 + x3، وz3 = x3 + x4، وz4 = x4 + x5، وz5 = x1 + x5.

Now the position-wise feed-forward network takes each z_j on its own. The first Fully connected layer has weights W1 of shape 4 x 3 with rows (1, -1, 0), (1, 1, 0), (0, 1, 1), (-1, 1, 1) and biases (1, 0, 1, 0). A ReLU follows. The second layer has W2 of shape 3 x 4 with rows (1, 0, 0, -1), (0, 1, 1, 0), (0, 0, 1, -1) and biases (0, 0, 1). Widen from three to four, bend, narrow back to three: the same expand-and-contract shape as the paper's 512 to 2048 to 512.

الآن تأخذ position-wise feed-forward network كل z_j وحده. الطبقة الأولى fully connected layer (متصلة بالكامل) أوزانها W1 بشكل 4 x 3 وصفوفها (1, -1, 0)، (1, 1, 0)، (0, 1, 1)، (-1, 1, 1) وانحيازاتها (1, 0, 1, 0). تليها ReLU. والطبقة الثانية لها W2 بشكل 3 x 4 وصفوفها (1, 0, 0, -1)، (0, 1, 1, 0)، (0, 0, 1, -1) وانحيازاتها (0, 0, 1). توسيع من ثلاثة إلى أربعة، ثم انحناء، ثم تضييق إلى ثلاثة: شكل التوسيع والتضييق نفسه في الورقة من 512 إلى 2048 إلى 512.

Worked exampleمثال محلول

Token 1 through the FFNالـ token رقم 1 عبر الـ FFN

  1. First layerالطبقة الأولى

    W1 z1 + b1 with z1 = (11, 2, 1): row 1 gives 11 - 2 + 0 + 1 = 10, row 2 11 + 2 + 0 = 13, row 3 0 + 2 + 1 + 1 = 4, row 4 -11 + 2 + 1 + 0 = -8. Hidden vector (10, 13, 4, -8).
    W1 z1 + b1 مع z1 = (11, 2, 1): الصف 1 يعطي 11 - 2 + 0 + 1 = 10، والصف 2 11 + 2 + 0 = 13، والصف 3 0 + 2 + 1 + 1 = 4، والصف 4 -11 + 2 + 1 + 0 = -8. المتجه المخفي (10, 13, 4, -8).
  2. ReLUReLU

    max(0, h) = (10, 13, 4, 0). The fourth unit is off for this token.
    max(0, h) = (10, 13, 4, 0). الوحدة الرابعة مطفأة لهذا الـ token.
  3. Second layerالطبقة الثانية

    W2 h + b2: row 1 10 - 0 + 0 = 10, row 2 13 + 4 + 0 = 17, row 3 4 - 0 + 1 = 5.
    W2 h + b2: الصف 1 10 - 0 + 0 = 10، والصف 2 13 + 4 + 0 = 17، والصف 3 4 - 0 + 1 = 5.
  4. out1 = (10, 17, 5)out1 = (10, 17, 5)

    This vector goes to the next block. Run the same three steps with the same W1, b1, W2, b2 on the other four tokens and you get the slide's five outputs.
    هذا المتجه يذهب إلى الكتلة التالية. نفّذ الخطوات الثلاث نفسها بنفس W1, b1, W2, b2 على الـ tokens الأربعة الأخرى وستحصل على المخرجات الخمسة في الشريحة.
Tokenالـ tokenzzW1 z + b1W1 z + b1after ReLUبعد ReLUW2 h + b2W2 h + b2
z1 = x1 + x2z1 = x1 + x2(11, 2, 1)(11, 2, 1)(10, 13, 4, -8)(10, 13, 4, -8)(10, 13, 4, 0)(10, 13, 4, 0)(10, 17, 5)(10, 17, 5)
z2 = x2 + x3z2 = x2 + x3(6, 6, 1)(6, 6, 1)(1, 12, 8, 1)(1, 12, 8, 1)(1, 12, 8, 1)(1, 12, 8, 1)(0, 20, 8)(0, 20, 8)
z3 = x3 + x4z3 = x3 + x4(7, 4, 2)(7, 4, 2)(4, 11, 7, -1)(4, 11, 7, -1)(4, 11, 7, 0)(4, 11, 7, 0)(4, 18, 8)(4, 18, 8)
z4 = x4 + x5z4 = x4 + x5(7, 3, 1)(7, 3, 1)(5, 10, 5, -3)(5, 10, 5, -3)(5, 10, 5, 0)(5, 10, 5, 0)(5, 15, 6)(5, 15, 6)
z5 = x1 + x5z5 = x1 + x5(5, 3, 1)(5, 3, 1)(3, 8, 5, -1)(3, 8, 5, -1)(3, 8, 5, 0)(3, 8, 5, 0)(3, 13, 6)(3, 13, 6)
All five tokens through the same FFNالـ tokens الخمسة كلها عبر الـ FFN نفسها
FFN(zj)=W2 max⁡(0,  W1zj+b1)+b2for each j independently\text{FFN}(z_j) = W_2\, \max(0,\; W_1 z_j + b_1) + b_2 \quad \text{for each } j \text{ independently}
Same weights, every position (column convention of the slide)الأوزان نفسها في كل موضع (اصطلاح الأعمدة في الشريحة)

Where the parameters sitأين توجد المعاملات

The FFN is small on the slide and large in the real model. Derive it from the base hyperparameters: the four attention projections W_Q, W_K, W_V, W_O are each 512 x 512, about 1.05 M weights per layer. The FFN's two matrices are 512 x 2048 and 2048 x 512, about 2.1 M. Two thirds of a layer's weights live in the FFN, so pruning and quantization work in later lectures will spend most of its effort there, while the N^2 activation cost of the previous concept lives in attention.

الـ FFN صغيرة في الشريحة وكبيرة في النموذج الحقيقي. استنتج ذلك من معاملات النموذج الأساسي: إسقاطات الانتباه الأربعة W_Q, W_K, W_V, W_O كل منها 512 x 512، أي حوالي 1.05 M وزن لكل طبقة. ومصفوفتا الـ FFN هما 512 x 2048 و2048 x 512، أي حوالي 2.1 M. ثلثا أوزان الطبقة تعيش في الـ FFN، لذلك سيصرف عمل التقليم (pruning) والتكميم في المحاضرات اللاحقة معظم جهده هناك، بينما تعيش كلفة التفعيلات N^2 من المفهوم السابق في الانتباه.

Weights in one base encoder layer, derived from d_model = 512 and d_ff = 2048 (biases omitted)الأوزان في طبقة مُرمِّز أساسية واحدة، مشتقة من d_model = 512 وd_ff = 2048 (دون الانحيازات)

Attention projections (4 x 512 x 512)إسقاطات الانتباه (4 x 512 x 512)
1,048,5761,048,576
FFN (2 x 512 x 2048)الـ FFN (2 x 512 x 2048)
2,097,1522,097,152
FFN share of the layerحصة الـ FFN من الطبقة
about 67%حوالي 67%

Quick checkاختبار سريع

In the position-wise feed-forward network, which statement is true?في الشبكة الأمامية التي تعمل على كل موضع (position-wise FFN)، أي عبارة صحيحة؟

Recall

Slide 44: compute the FFN output for token 4, whose attention-weighted feature is z4 = (7, 3, 1).الشريحة 44: احسب مخرج الـ FFN للـ token رقم 4، الذي ميزته الموزونة بالانتباه z4 = (7, 3, 1).

First layer: (7 - 3 + 1, 7 + 3, 3 + 1 + 1, -7 + 3 + 1) = (5, 10, 5, -3). ReLU: (5, 10, 5, 0). Second layer: (5 - 0, 10 + 5, 5 - 0 + 1) = (5, 15, 6). The slide writes the hidden entry as -4, but ReLU makes that difference vanish.
الطبقة الأولى: (7 - 3 + 1, 7 + 3, 3 + 1 + 1, -7 + 3 + 1) = (5, 10, 5, -3). ReLU: (5, 10, 5, 0). الطبقة الثانية: (5 - 0, 10 + 5, 5 - 0 + 1) = (5, 15, 6). تكتب الشريحة القيمة المخفية -4، لكن ReLU تُخفي هذا الفرق.

The closing slide lists the ten works the lecturer built this lecture from. Read them as a map of where each part came from: the convolution arithmetic animations and CS231n behind parts 2 to 4, the two normalization papers behind part 5, the four architecture papers whose design choices (ReLU in AlexNet, depth in VGG, residuals in ResNet, ReLU6 in MobileNetV2) run through this part, and the survey and course that frame the whole thing for embedded deployment.

الشريحة الختامية تسرد الأعمال العشرة التي بنى منها المحاضر هذه المحاضرة. اقرأها كخريطة لمصدر كل جزء: رسوم حساب الالتفاف المتحركة وCS231n وراء الأجزاء من 2 إلى 4، وورقتا التطبيع وراء الجزء 5، وأوراق المعماريات الأربع التي تسري خيارات تصميمها في هذا الجزء (ReLU في AlexNet، والعمق في VGG، والاتصالات المتبقية في ResNet، وReLU6 في MobileNetV2)، والمسح (survey) والمقرر اللذان يؤطّران الموضوع كله للنشر على الأنظمة المضمّنة.

Sourcesالمصادر

Recapالخلاصة

If you remember nothing elseإن لم تتذكر شيئاً آخر فتذكّر هذا

  • Without a non-linearity, stacked linear layers collapse into one linear layer, so depth buys nothing.بدون دالة غير خطية تنهار الطبقات الخطية المكدّسة إلى طبقة خطية واحدة، فلا يضيف العمق شيئًا.
  • Sigmoid saturates on both sides with a derivative of at most 0.25. ReLU, max(0, x), is the default hidden unit.دالة sigmoid تتشبّع من الجانبين ومشتقتها 0.25 على الأكثر. ودالة ReLU، أي max(0, x)، هي الوحدة المخفية الافتراضية.
  • ReLU6 = min(max(0, x), 6) is bounded, which hands int8 a fixed grid of 6/255 per step. MobileNetV2 chose it for low-precision robustness.ReLU6 = min(max(0, x), 6) محدودة، فتعطي الـ int8 شبكة ثابتة خطوتها 6/255. اختارتها MobileNetV2 لمتانتها مع الدقة المنخفضة (low precision).
  • Hard swish = x ReLU6(x + 3)/6 stays within 0.15 of swish everywhere and needs no exponential.Hard swish = x ReLU6(x + 3)/6 تبقى ضمن 0.15 من swish في كل مكان ولا تحتاج دالة أُسّية.
  • A transformer block is multi-head attention, Add and Norm (residual plus LayerNorm), position-wise FFN, Add and Norm. Base model: N = 6, d_model = 512, h = 8, d_k = 64, d_ff = 2048.كتلة الـ transformer هي multi-head attention، ثم Add and Norm (اتصال متبقٍّ residual مع LayerNorm)، ثم FFN تعمل على كل موضع، ثم Add and Norm. النموذج الأساسي: N = 6، d_model = 512، h = 8، d_k = 64، d_ff = 2048.
  • Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V. Q and K are N x d_k, the weights are N x N, the output is N x d_v.Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V. المصفوفتان Q وK بشكل N x d_k، والأوزان بشكل N x N، والمخرج بشكل N x d_v.
  • Dividing by sqrt(d_k) keeps the dot-product variance at 1 so softmax does not saturate and its gradients stay alive.القسمة على sqrt(d_k) تُبقي تباين حاصل الضرب النقطي عند 1 فلا تتشبّع softmax وتبقى تدرّجاتها حيّة.
  • Attention memory and compute grow with N^2. At N = 1024 one fp32 head already holds 4 MB of scores.ذاكرة الانتباه وحسابه ينموان مع N^2. عند N = 1024 يحمل رأس واحد بدقة fp32 وحده 4 MB من الدرجات (scores).
  • Slide 43 by hand: q1 = (2, 0, 3) scores 3, 4, -1, 3 against the keys, weights about 0.2, 0.6, 0, 0.2, z1 = (8, 2, 6). The slide's q2 should be (1, 1, 2).الشريحة 43 يدويًا: q1 = (2, 0, 3) تعطي الدرجات 3 و4 و-1 و3 مقابل المفاتيح، والأوزان تقريبًا 0.2 و0.6 و0 و0.2، وz1 = (8, 2, 6). والصحيح أن تكون q2 في الشريحة (1, 1, 2).
  • The FFN applies the same linear, ReLU, linear to every token independently. Slide 44's two wrong hidden entries (-9 and -4 instead of -8 and -3) are zeroed by ReLU anyway.الـ FFN تطبّق نفس العمليات (خطية، ثم ReLU، ثم خطية) على كل token بشكل مستقل. والقيمتان المخفيتان الخاطئتان في الشريحة 44 (-9 و-4 بدل -8 و-3) تصفّرهما ReLU على أي حال.

Sourcesالمصادر