Lecture 02 · NN Fundamentals

المحاضرة 02 · أساسيات الشبكات العصبية

Transformer block and attention by hand

كتلة Transformer والانتباه (attention) باليد

Slides 41–45 الشرائح 41–45 P1 MUST

One formula, four shapes and one reason for the square root. Then slide 43 computes a full attention column with integers, and slide 44 pushes the result through the feed-forward network. Finally, why N × N is the number that hurts on a microcontroller.

معادلة واحدة، وأربعة أشكال، وسبب واحد للجذر التربيعي. ثم تحسب الشريحة 43 عموداً كاملاً من الـ attention بأعداد صحيحة، وتمرّر الشريحة 44 النتيجة عبر شبكة feed-forward. وأخيراً، لماذا N × N هو الرقم المؤلم على المتحكم الدقيق.

The block on slide 41

الكتلة في الشريحة 41

Vaswani et al. (NeurIPS 2017) stack N identical layers. Each encoder layer has two sub-layers, each wrapped in a residual connection followed by LayerNorm:

يكدّس Vaswani وزملاؤه (NeurIPS 2017) عدداً N من الطبقات المتطابقة. كل طبقة encoder فيها طبقتان فرعيتان، وكل منهما محاطة بـ residual connection يتبعها LayerNorm:

  1. Multi-head attention: the only place tokens exchange information.

    Multi-head attention: المكان الوحيد الذي تتبادل فيه الـ tokens المعلومات.

  2. Add and Norm: output = LayerNorm(x + Sublayer(x)). The "Add" is the residual, the "Norm" is the layer norm from the previous pages.

    Add and Norm: المخرج = LayerNorm(x + Sublayer(x)). الـ Add هو الـ residual، والـ Norm هو layer norm من الصفحات السابقة.

  3. Position-wise feed-forward network: the same two-layer MLP with a ReLU, applied to every token separately.

    Position-wise feed-forward network: الشبكة نفسها ذات الطبقتين مع ReLU، تُطبَّق على كل token وحده.

  4. Add and Norm again.

    Add and Norm مرة أخرى.

The decoder adds a masked self-attention (a token cannot look at later tokens) and an encoder-decoder attention. The model has no recurrence and no convolution, so positional encodings are added to the input embeddings to tell it the token order.

يضيف الـ decoder طبقة masked self-attention (لا يستطيع الـ token أن ينظر إلى ما بعده) وطبقة encoder-decoder attention. والنموذج بلا تكرار وبلا التفاف، لذلك تُضاف positional encodings إلى الـ embeddings لتخبره بترتيب الـ tokens.

Base model hyperparameterالمعامل الفائق (hyperparameter) للنموذج الأساسيValueالقيمةMeaningالمعنى
N6layers in the encoder (and in the decoder)عدد الطبقات في الـ encoder (وفي الـ decoder)
dmodel512width of every token vectorعرض متجه كل token
h8attention headsعدد رؤوس الانتباه (attention heads)
dk = dv64per-head size, dmodel / h = 512 / 8حجم كل رأس، dmodel / h = 512 / 8
dff2048hidden width of the FFN, 4 × dmodelالعرض المخفي للـ FFN، 4 × dmodel

قيم النموذج الأساسي: N = 6 طبقات، وdmodel = 512 عرض متجه كل token، وh = 8 رؤوس، وdk = dv = 64 حجم كل رأس لأن 512 / 8 = 64، وdff = 2048 العرض الخفي لشبكة FFN، أي 4 × dmodel.

ENCODER BLOCK SCALED DOT-PRODUCT ATTENTION to next block N× = 6 Add & Norm Feed Forward 512 → 2048 → 512 Add & Norm Multi-Head Attention h = 8, d_k = 64 +x +x Input Embedding + Positional Encoding tokens, d_model = 512 Q N×d_k K N×d_k V N×d_v MatMul Q·Kᵀ N×N Scale ÷ √d_k Mask (opt.) Softmax per row N×N weights MatMul weights·V out N×d_v
Left: one encoder layer, repeated N = 6 times, with residual paths into each Add and Norm. Right: the inside of one attention head, with the shape of every matrix.
يساراً: طبقة encoder واحدة تتكرر N = 6 مرات، مع مسارات متبقية (residual) تدخل كل Add and Norm. يميناً: داخل رأس انتباه واحد (attention head)، مع شكل كل مصفوفة.

على اليسار: طبقة encoder واحدة تتكرر N = 6 مرات، مع مسارات residual (باللون الأحمر) تدخل في كل Add & Norm. وعلى اليمين: داخل رأس attention واحد. Q وK بشكل N×d_k يُضربان فيعطيان درجات بشكل N×N، ثم القسمة على √d_k، ثم قناع اختياري، ثم softmax على كل صف، ثم الضرب في V بشكل N×d_v لنحصل على مخرج بشكل N×d_v.

Attention: the formula and its shapes

الانتباه (attention): المعادلة وأشكالها

Attention(Q, K, V) = softmax( Q KT√dk ) V

Slide 42 reads it as a retrieval system, like YouTube search. The query is what you typed in the search bar, the keys are the titles and descriptions of the videos, and the values are the videos themselves. Score every key against the query, turn the scores into weights, and return a weighted mix of the values.

تقرأها الشريحة 42 كنظام استرجاع، مثل البحث في YouTube. الـ query هو ما كتبته في شريط البحث، والـ keys هي عناوين الفيديوهات وأوصافها، والـ values هي الفيديوهات نفسها. قارن كل key بالـ query، وحوّل الدرجات إلى أوزان، وأرجع خليطاً موزوناً من الـ values.

MatrixالمصفوفةShapeالشكلComes fromمصدرها
Q, KN × dkX WQ, X WK, one row per tokenX WQ, X WK، صف لكل token
VN × dvX WV
Q KT, and its softmaxQ KT، وsoftmax لهاN × Nevery query scored against every keyكل استعلام (query) يُقيَّم مقابل كل مفتاح (key)
OutputالمخرجN × dvweights × Vالأوزان × V

الأشكال: Q وK بشكل N × dk، وV بشكل N × dv، والدرجات Q KT ونتيجة الـ softmax بشكل N × N لأن كل query يُقارن بكل key، والمخرج بشكل N × dv.

Multi-head attention runs h = 8 such heads in parallel, each with its own WQ, WK, WV of size 512 × 64, concatenates the eight 64-wide outputs back to 512, and applies one more linear WO. The attention weights themselves are not learned: they are recomputed from Q and K for every input.

يشغّل multi-head attention عدد h = 8 من هذه الرؤوس على التوازي، لكل رأس WQ وWK وWV خاصة بحجم 512 × 64، ثم يضمّ المخرجات الثمانية بعرض 64 لتعود إلى 512، ويطبّق طبقة خطية أخيرة WO. أما أوزان الـ attention نفسها فهي ليست مُتعلَّمة: تُحسب من جديد من Q وK لكل مدخل.

Why divide by √dk

لماذا نقسم على √dk

Suppose the components of q and k are independent with mean 0 and variance 1. Then q · k = Σ qiki is a sum of dk terms each of variance 1, so its variance is dk and its standard deviation is √dk. With dk = 64 the scores typically land around ±8, and softmax of numbers that far apart is essentially one-hot: one weight near 1, the rest near 0, and gradients near 0. Dividing by √dk = 8 brings the variance back to 1.

افترض أن مكوّنات q وk مستقلة بمتوسط 0 وتباين 1. عندها q · k = Σ qiki مجموع dk حداً تباين كل منها 1، فيكون تباينه dk وانحرافه المعياري √dk. مع dk = 64 تقع الدرجات عادة حول ±8، وsoftmax لأرقام متباعدة هكذا يكون تقريباً one-hot: وزن واحد قريب من 1 والباقي قريب من 0، والـ gradients قريبة من 0. القسمة على √dk = 8 تُعيد التباين إلى 1.

Worked مثال محلول
three scores, unscaled, at d_k = 64:   (8, 0, -8)
  softmax  = (e^8, e^0, e^-8) / sum
           = (2981, 1, 0.0003) / 2982
           = (1.000, 0.000, 0.000)      saturated, no gradient

scaled by sqrt(64) = 8:                (1, 0, -1)
  softmax  = (2.718, 1, 0.368) / 4.086
           = (0.665, 0.245, 0.090)      alive, gradients flow

ثلاث درجات بلا قسمة عند d_k = 64: (8, 0, -8)، فيعطي الـ softmax تقريباً (1, 0, 0)، أي تشبّع بلا gradient. وبعد القسمة على 8 تصبح (1, 0, -1)، فيعطي (0.665, 0.245, 0.090)، والـ gradients تتدفق.

Attention by hand (slide 43)

الانتباه باليد (الشريحة 43)

Tom Yeh's sheet uses column vectors. Four tokens with six features each, and three 3 × 6 projection matrices, so dk = 3. Two shortcuts keep it integer: divide by 2 instead of √3 ≈ 1.73 (rounding toward zero), and use 3x instead of ex.

ورقة Tom Yeh تستخدم متجهات عمودية. أربعة tokens لكل منها ست خصائص، وثلاث مصفوفات إسقاط بحجم 3 × 6، إذن dk = 3. واختصاران يُبقيان الحساب بأعداد صحيحة: القسمة على 2 بدلاً من √3 ≈ 1.73 (مع التقريب نحو الصفر)، واستخدام 3x بدلاً من ex.

Worked مثال محلول
tokens (columns)
  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)

W_Q rows (1,1,0,0,0,0) (0,1,0,1,0,0) (0,0,1,0,1,1)
W_K rows (0,0,1,0,0,0) (0,1,0,0,0,0) (1,0,0,0,0,-1)
W_V rows (10,0,0,0,0,0) (0,0,0,10,0,0) (0,10,0,0,0,0)

step 1  project
  q1 = W_Q x1 = (2+0, 0+0, 0+2+1) = (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)

step 2  scores q1 . kj
  k1: 0 + 0 + 3     =  3
  k2: 4 + 0 + 0     =  4      best match
  k3: 2 + 0 - 3     = -1
  k4: 0 + 0 + 3     =  3

step 3  scale: divide by 2, round toward zero
  3, 4, -1, 3   ->   1, 2, 0, 1

step 4  softmax with base 3
  3^1, 3^2, 3^0, 3^1 = 3, 9, 1, 3       sum 16
  weights 3/16, 9/16, 1/16, 3/16 = 0.19, 0.56, 0.06, 0.19
  slide rounds to                  .2,   .6,   0,    .2

step 5  weighted sum of values
  z1 = .2 v1 + .6 v2 + 0 v3 + .2 v4
     = (4, 0, 0) + (0, 0, 6) + (4, 2, 0)
     = (8, 2, 6)

الخطوة 1: نُسقط فنحصل على q1 = (2, 0, 3) والـ keys والـ values. الخطوة 2: حاصل الضرب النقطي لـ q1 مع كل key يعطي 3, 4, -1, 3، والـ key الثاني هو الأفضل. الخطوة 3: القسمة على 2 مع التقريب نحو الصفر تعطي 1, 2, 0, 1. الخطوة 4: 3x يعطي 3, 9, 1, 3 ومجموعها 16، فالأوزان تقريباً .2, .6, 0, .2. الخطوة 5: المجموع الموزون للـ values يعطي z1 = (8, 2, 6).

The exact computation (divide by √3, real ex) gives weights 0.26, 0.46, 0.03, 0.26 and z1 = (10.3, 2.8, 4.6). The numbers drift, the ranking does not: key 2 still wins and keys 1 and 4 still tie.

الحساب الدقيق (القسمة على √3 وex الحقيقية) يعطي أوزاناً 0.26, 0.46, 0.03, 0.26 وz1 = (10.3, 2.8, 4.6). الأرقام تنحرف لكن الترتيب لا يتغيّر: الـ key الثاني ما زال الفائز، والأول والرابع ما زالا متعادلين.

Slide check تحقّق من الشريحة

The sheet draws q2 = (1, 1, 1), but the third row of WQ, (0, 0, 1, 0, 1, 1), dotted with x2 = (0, 1, 2, 0, 0, 0) is 2, so q2 = (1, 1, 2). Column 1 above is correct as drawn. The sheet also computes KTQ with columns summing to 1, the transpose of the paper's row-wise Q KT: same numbers, transposed.

ترسم الورقة q2 = (1, 1, 1)، لكن الصف الثالث من WQ وهو (0, 0, 1, 0, 1, 1) مضروباً نقطياً في x2 = (0, 1, 2, 0, 0, 0) يعطي 2، إذن q2 = (1, 1, 2). أما العمود الأول أعلاه فصحيح كما رُسم. والورقة تحسب KTQ بأعمدة مجموعها 1، وهو منقول صيغة الورقة البحثية Q KT بصفوف مجموعها 1: الأرقام نفسها، منقولة.

Then the FFN (slide 44)

ثم الـ FFN (الشريحة 44)

FFN(z) = W2 max(0, W1z + b1) + b2, with the same weights for every token. On the sheet, five tokens of three features each; the given attention matrix makes z1 = x1 + x2 = (5, 0, 1) + (6, 2, 0) = (11, 2, 1).

FFN(z) = W2 max(0, W1z + b1) + b2، بالأوزان نفسها لكل token. في الورقة خمسة tokens لكل منها ثلاث خصائص، ومصفوفة الـ attention المعطاة تجعل z1 = x1 + x2 = (5, 0, 1) + (6, 2, 0) = (11, 2, 1).

Worked مثال محلول
W1 rows (1,-1,0) (1,1,0) (0,1,1) (-1,1,1)    b1 = (1, 0, 1, 0)
W2 rows (1,0,0,-1) (0,1,1,0) (0,0,1,-1)       b2 = (0, 0, 1)

z1 = (11, 2, 1)
  layer 1   11 - 2 + 0 + 1 = 10
            11 + 2 + 0 + 0 = 13
             0 + 2 + 1 + 1 =  4
           -11 + 2 + 1 + 0 = -8      (the sheet draws -9; ReLU zeroes it anyway)
  ReLU      (10, 13, 4, 0)
  layer 2   10 + 0 + 0 - 0 = 10
             0 + 13 + 4 + 0 = 17
             0 + 0 + 4 - 0 + 1 = 5
  out1 = (10, 17, 5)                  matches the slide

الطبقة الأولى تحوّل z1 = (11, 2, 1) إلى (10, 13, 4, -8)، ثم ReLU يعطي (10, 13, 4, 0)، ثم الطبقة الثانية تعطي (10, 17, 5)، وهو ما في الشريحة. والورقة ترسم -9 بدلاً من -8، لكن ReLU يصفّرها في الحالتين. التوسيع من 3 إلى 4 ثم الرجوع إلى 3 هو الشكل نفسه لـ 512 → 2048 → 512 في النموذج الأساسي.

Why N × N is the embedded bottleneck

لماذا N × N هو عنق الزجاجة في الأنظمة المدمجة

Every query is scored against every key, so one head in one layer stores N2 scores. Memory and compute grow with the square of the sequence length.

كل query يُقارن بكل key، فرأس واحد في طبقة واحدة يخزّن N2 درجة. والذاكرة والحساب ينموان مع مربع طول التسلسل.

Tokens Nعدد الـ tokens NScores N2الدرجات N2fp32 bytes (× 4)بايتات fp32 (× 4)
644,09616 KB
25665,536256 KB
1,0241,048,5764 MB
4,09616,777,21664 MB

الجدول: عند N = 64 تكون الدرجات 4,096 أي 16 KB بصيغة fp32، وعند 256 تصبح 256 KB، وعند 1,024 تصبح 4 MB، وعند 4,096 تصبح 64 MB. مضاعفة N تضرب الذاكرة في 4.

A typical microcontroller has a few hundred KB of SRAM, so a single head at N = 1024 (4 MB) does not fit, even before the other 7 heads and the weights. Doubling N multiplies the memory by 4. The parameters, by contrast, do not depend on N: per base layer, attention holds 4 × 512 × 512 ≈ 1.05 M weights and the FFN 2 × 512 × 2048 ≈ 2.1 M.

المتحكم الدقيق النموذجي فيه بضع مئات من الـ KB من SRAM، فرأس واحد عند N = 1024 (4 MB) لا يتّسع، حتى قبل الرؤوس السبعة الأخرى والأوزان. ومضاعفة N تضرب الذاكرة في 4. أما عدد المعاملات فلا يعتمد على N: في كل طبقة أساسية يحمل الـ attention نحو 4 × 512 × 512 ≈ 1.05 M وزن، ويحمل الـ FFN نحو 2 × 512 × 2048 ≈ 2.1 M.

Memory hook خطّاف للذاكرة

"Score, scale, squash, sum." Q KT scores, ÷√dk scales, softmax squashes each row into weights, and multiplying by V sums the values.

"Score, scale, squash, sum." أي: Q KT يعطي الدرجات، و÷√dk يقيس، وsoftmax يضغط كل صف إلى أوزان، والضرب في V يجمع الـ values.

Trap فخ

Softmax is row-wise. Each query's row of N scores becomes N weights summing to 1. It is not a softmax over all N2 entries.

الـ softmax يُطبَّق على كل صف. صف الـ query الواحد من N درجة يصبح N وزناً مجموعها 1. وليس softmax على كل العناصر الـ N2 معاً.

Divide by √dk, not dk. The dot product has standard deviation √dk; dividing by dk = 64 would shrink scores by 64 and make the softmax nearly uniform.

اقسم على √dk لا على dk. الانحراف المعياري للضرب النقطي هو √dk، والقسمة على dk = 64 تُصغّر الدرجات 64 مرة فيصبح الـ softmax شبه متساوٍ.

Two different N's. On slide 41, "N×" counts stacked layers (6). On slide 42, N is the number of tokens. The N × N attention matrix uses the token N.

حرفا N مختلفان. في الشريحة 41 يعدّ N× الطبقات المكدّسة (6). وفي الشريحة 42 يمثّل N عدد الـ tokens. ومصفوفة الـ attention بشكل N × N تستخدم N الخاص بالـ tokens.

Everything on one card

كل شيء في بطاقة واحدة

Transformer cheat card

بطاقة مراجعة Transformer

Check yourself

اختبر نفسك

Single-head attention over N tokens with head size dk. What is the shape of the softmax output?

Attention برأس واحد على N من الـ tokens وحجم رأس dk. ما شكل مخرج الـ softmax؟

Q KT is (N × dk)(dk × N) = N × N, and softmax keeps the shape. Only after multiplying by V does it return to N × dv.

Q KT هو (N × dk)(dk × N) = N × N، والـ softmax يحافظ على الشكل. ولا يعود إلى N × dv إلا بعد الضرب في V.

Why does the transformer divide Q KT by √dk?

لماذا يقسم الـ transformer قيمة Q KT على √dk؟

Softmax already makes rows sum to 1 (A). The scaling targets the size of the scores: with dk = 64 they spread to about ±8 and softmax becomes one-hot with vanishing gradients.

الـ softmax يجعل مجموع الصفوف 1 أصلاً (A). والقسمة تستهدف حجم الدرجات: مع dk = 64 تنتشر حول ±8، فيصبح الـ softmax شبه one-hot وتختفي الـ gradients.

With q = (2, 0, 3) and keys k1 = (0, 0, 1), k2 = (2, 1, 0), k3 = (1, 0, −1), k4 = (0, 0, 1), what are the raw scores q · k?

مع q = (2, 0, 3) والـ keys k1 = (0, 0, 1) وk2 = (2, 1, 0) وk3 = (1, 0, −1) وk4 = (0, 0, 1)، ما الدرجات الخام q · k؟

k1: 0 + 0 + 3 = 3. k2: 4 + 0 + 0 = 4. k3: 2 + 0 − 3 = −1. k4: 3. Option B is the scaled (÷2, truncated) version, one step too far. Option D forgets the −1 in k3.

k1: 0 + 0 + 3 = 3. k2: 4 + 0 + 0 = 4. k3: 2 + 0 − 3 = −1. k4: 3. الخيار B هو النسخة بعد القسمة على 2، أي خطوة زائدة. والخيار D نسي الإشارة السالبة في k3.

One fp32 attention head processes N = 2048 tokens. How much memory do its scores take?

رأس attention واحد بصيغة fp32 يعالج N = 2048 من الـ tokens. كم ذاكرة تأخذ درجاته؟

20482 = 4,194,304 scores × 4 bytes = 16,777,216 bytes = 16 MB. Doubling N from 1024 (4 MB) multiplies memory by 4, not 2 (C). Option A is the linear 2048 × 4 bytes, forgetting that N appears twice.

20482 = 4,194,304 درجة × 4 بايت = 16,777,216 بايت = 16 MB. مضاعفة N من 1024 (4 MB) تضرب الذاكرة في 4 لا في 2 (C). والخيار A هو الحساب الخطي 2048 × 4 بايت، ونسي أن N يظهر مرتين.

In the slide 43 example, which numbers are learned parameters?

في مثال الشريحة 43، أي الأرقام هي معاملات مُتعلَّمة؟

Only the projections are trained. Q, K, V are computed from the input with them, and A is recomputed from Q and K for every new input, so it changes with the sentence (B, C).

وحدها مصفوفات الإسقاط تُدرَّب. أما Q وK وV فتُحسب من المدخل بواسطتها، وA تُحسب من جديد من Q وK لكل مدخل جديد، فهي تتغيّر مع الجملة (B وC).