Majid Al-RaimiFrom RNN limits to the transformer blockمن حدود RNN إلى كتلة المحوِّل (Transformer)

ICS 582Lecture 06المحاضرة 06Part 05الجزء 05

From RNN limits to the transformer blockمن حدود RNN إلى كتلة المحوِّل (Transformer)

Why RNNs struggle with coreference and a fixed-size context bottleneck, how self-attention and cross-attention fix that, and what a transformer block (attention, feedforward, residuals, layer norm) computes.لماذا تعاني RNN مع الإحالة المرجعية (coreference) وعنق الزجاجة لسياق ثابت الحجم، وكيف يعالج الانتباه الذاتي والانتباه المتقاطع ذلك، وما الذي تحسبه كتلة المحوِّل (الانتباه، والتغذية الأمامية، والوصلات المتبقية residuals، وتطبيع الطبقة layer norm).

Conceptsالمفاهيم
3
Slidesالشرائح
23-26
Readingمدة القراءة
18 min18 دقيقة
Understoodما فهمته
0/3 conceptsمفاهيم

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

You have spent this lecture building language models from RNNs and LSTMs. This part asks a blunt question: what is wrong with them? Two problems keep coming back, and the transformer was designed to remove both. Once you can name them, the shape of the transformer block stops looking arbitrary.

The part runs in three steps. First, self-attention as the fix for reaching a distant word inside one sentence. Second, cross-attention as the fix for the encoder bottleneck in translation. Third, the transformer block itself: attention, add, normalize, feedforward, add, normalize. Expect three exam questions from this material: name two RNN limitations that motivate transformers, write the block equations, and explain what the residual connections and layer norm are for. The mechanics of how attention weights are computed (queries, keys and values) come in the next part.

قضيت هذه المحاضرة في بناء نماذج لغوية من RNNs وLSTMs. هذا الجزء يطرح سؤالًا صريحًا: ما العيب فيها؟ هناك مشكلتان تتكرران، وقد صُمم الـ transformer لإزالتهما معًا. وحين تستطيع تسميتهما، يتوقف شكل كتلة الـ transformer عن أن يبدو اعتباطيًا.

يسير الجزء في ثلاث خطوات. أولًا، الـ self-attention بوصفه الحل للوصول إلى كلمة بعيدة داخل جملة واحدة. ثانيًا، الـ cross-attention بوصفه الحل لعنق الزجاجة في الـ encoder عند الترجمة. ثالثًا، كتلة الـ transformer نفسها: attention، ثم جمع، ثم تطبيع، ثم feedforward، ثم جمع، ثم تطبيع. توقّع ثلاثة أسئلة امتحان من هذه المادة: اذكر قيدين لشبكات RNN دفعا إلى الـ transformer، واكتب معادلات الكتلة، واشرح الغرض من الـ residual connections والـ layer norm. أما آلية حساب أوزان الانتباه (الـ queries والـ keys والـ values) فتأتي في الجزء التالي.

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

  1. State the two limitations of RNNs that motivate transformers: sequential (slow) computation, and weak long-range access through a single bottleneck state.أن تذكر قيدَي شبكات RNN اللذين دفعا إلى الـ transformer: الحساب التتابعي (البطيء)، وضعف الوصول إلى المعلومات البعيدة لأنها تمر عبر حالة واحدة تشكّل عنق زجاجة.
  2. Explain the chicken and road example: how self-attention lets it read chicken directly, in one step, at any distance.أن تشرح مثال chicken و road: كيف يسمح self-attention للكلمة it بقراءة chicken مباشرة، في خطوة واحدة، مهما كانت المسافة.
  3. Explain why the single final encoder state is a bottleneck in translation and how cross-attention removes it.أن تشرح لماذا تكون الحالة النهائية الوحيدة للـ encoder عنق زجاجة في الترجمة، وكيف يزيله cross-attention.
  4. Write the transformer block equations exactly as on slide 26, and say what each of the four pieces does.أن تكتب معادلات كتلة الـ transformer كما هي تمامًا في الشريحة 26، وأن تقول ما الذي تفعله كل قطعة من القطع الأربع.
  5. Explain the role of residual connections and layer normalization, and why input and output must both be N × d.أن تشرح دور الـ residual connections والـ layer normalization، ولماذا يجب أن يكون كل من الدخل والخرج بالشكل N × d.

Read this sentence: "The chicken didn’t cross the road because it was too tired." You know at once that it means the chicken. Roads do not get tired. To build a good vector for it, a model has to pull in information from chicken, which sits 6 tokens earlier.

اقرأ هذه الجملة: "The chicken didn’t cross the road because it was too tired." تعرف فورًا أن it تعني chicken (الدجاجة)، فالطرق لا تتعب. ولكي يبني النموذج متجهًا جيدًا للكلمة it، عليه أن يجلب معلومات من chicken التي تقع قبلها بـ 6 tokens.

How an RNN gets chicken to itكيف توصل شبكة RNN الكلمة chicken إلى it

A recurrent neural network (RNN) has exactly one way to move information forward: the hidden state. Whatever the network learned at chicken must be written into h₂, then survive being rewritten at didn’t, cross, the, road and because, before it reaches h₈ at it. Six updates, each one squeezing new words into the same fixed-size vector. Some of the chicken information is overwritten on the way, and during training the error signal has to travel the same 6 hops backward, shrinking as it goes. That is the vanishing gradient problem you met earlier. An LSTM softens it with gates and an additive cell state, but the path is still one step at a time.

لدى الشبكة العصبية التكرارية (RNN) طريقة واحدة فقط لنقل المعلومات إلى الأمام: الـ hidden state. كل ما تعلمته الشبكة عند chicken يجب أن يُكتب في h₂، ثم ينجو من إعادة الكتابة عند didn’t وcross وthe وroad وbecause، قبل أن يصل إلى h₈ عند it. ست عمليات تحديث، كل واحدة منها تحشر كلمات جديدة في المتجه نفسه ذي الحجم الثابت. يُمحى جزء من معلومات chicken في الطريق، وأثناء التدريب يجب على إشارة الخطأ أن تقطع القفزات الـ 6 نفسها إلى الخلف، وتتضاءل كلما تقدمت. هذه هي مشكلة الـ vanishing gradient التي قابلتها سابقًا. الـ LSTM يخففها بالبوابات (gates) وبحالة خلية تُحدَّث بالجمع، لكن المسار ما زال خطوة بعد خطوة.

The same chain causes a second, practical problem. To compute h₈ you must first have h₇, which needs h₆, and so on back to the start. A sentence of N tokens takes N steps that cannot be run at the same time, even during training when every word is known in advance. A GPU with thousands of cores sits mostly idle while the RNN walks the sentence.

السلسلة نفسها تسبب مشكلة ثانية عملية. لكي تحسب h₈ يجب أن تكون لديك h₇ أولًا، وهي تحتاج h₆، وهكذا رجوعًا حتى البداية. جملة من N من الـ tokens تستغرق N من الخطوات التي لا يمكن تشغيلها في الوقت نفسه، حتى أثناء التدريب حين تكون كل الكلمات معروفة مسبقًا. وهكذا يبقى GPU فيه آلاف الأنوية خاملًا في معظم الوقت بينما تمشي الـ RNN على الجملة كلمة كلمة.

Top: in an RNN, chicken reaches it only through 6 hidden-state hops, fading at each one. Bottom: with self-attention, it reads chicken (and a little of road) in one direct stepفي الأعلى: في شبكة RNN لا تصل chicken إلى it إلا عبر 6 قفزات في الـ hidden state، وتبهت عند كل قفزة. في الأسفل: مع self-attention تقرأ it الكلمة chicken (وقليلًا من road) في خطوة مباشرة واحدة

What self-attention does insteadما الذي يفعله self-attention بدلًا من ذلك

Slide 24 draws the alternative. The bottom row is layer k, one vector per token. The top row is layer k+1. To build the new vector for it, the model computes a weight for every token it is allowed to look at, and the weights form a probability distribution (they come out of a softmax, so they are non-negative and sum to 1). The darkest line on the slide goes to chicken, a lighter one to road, a faint one to The. The new vector for it is a weighted mix of those layer k vectors. That operation is self-attention: self, because the sequence attends to itself.

الشريحة 24 ترسم البديل. الصف السفلي هو الطبقة k، متجه واحد لكل token. والصف العلوي هو الطبقة k+1. لبناء المتجه الجديد للكلمة it، يحسب النموذج وزنًا لكل token مسموح له بالنظر إليه، وتشكّل هذه الأوزان توزيعًا احتماليًا (فهي تخرج من softmax، لذلك تكون غير سالبة ومجموعها 1). أغمق خط في الشريحة يذهب إلى chicken، وخط أفتح إلى road، وخط باهت إلى The. المتجه الجديد للكلمة it هو مزيج موزون من متجهات الطبقة k تلك. هذه العملية هي الـ self-attention: وكلمة self لأن التسلسل ينتبه إلى نفسه.

The distance between it and chicken no longer matters. Whether chicken is 6 tokens back or 600, it is one weighted lookup away. And because the vector for it does not depend on the new vector for because (only on the old layer k vectors), every position in layer k+1 can be computed at the same time.

المسافة بين it وchicken لم تعد مهمة. سواء كانت chicken قبلها بـ 6 tokens أو بـ 600، فهي على بعد عملية بحث موزونة واحدة. ولأن متجه it لا يعتمد على المتجه الجديد للكلمة because (بل على متجهات الطبقة k القديمة فقط)، يمكن حساب كل موضع في الطبقة k+1 في الوقت نفسه.

Worked exampleمثال محلول

Building the new vector for it as a weighted mixبناء المتجه الجديد للكلمة it كمزيج موزون

  1. Pick toy vectorsاختر متجهات بسيطة

    Use two-dimensional vectors so the arithmetic is visible: chicken = [1, 0], road = [0, 1], The = [0.5, 0.5]. Give every other token weight 0 for now.
    استخدم متجهات ثنائية الأبعاد حتى يكون الحساب واضحًا: chicken = [1, 0]، وroad = [0, 1]، وThe = [0.5, 0.5]. أعطِ كل token آخر الوزن 0 حاليًا.
  2. Pick attention weights that sum to 1اختر أوزان انتباه مجموعها 1

    Chicken 0.6, road 0.3, The 0.1. Check: 0.6 + 0.3 + 0.1 = 1.
    chicken بوزن 0.6، وroad بوزن 0.3، وThe بوزن 0.1. للتحقق: 0.6 + 0.3 + 0.1 = 1.
  3. Mixامزج

    0.6·[1, 0] + 0.3·[0, 1] + 0.1·[0.5, 0.5] = [0.65, 0.35].
    0.6·[1, 0] + 0.3·[0, 1] + 0.1·[0.5, 0.5] = [0.65, 0.35].
  4. Resultالنتيجة

    The new vector for it sits much closer to chicken than to road. In the real model the mixed vectors are learned projections called values, and the weights come from learned scores. That is the next part.
    المتجه الجديد للكلمة it أقرب بكثير إلى chicken منه إلى road. في النموذج الحقيقي تكون المتجهات التي تُمزج إسقاطات متعلَّمة تسمى values، وتأتي الأوزان من درجات (scores) متعلَّمة. وهذا موضوع الجزء التالي.

Try it in the simulator. The four sliders set raw scores; the softmax turns all eight scores into weights. With the slide preset, chicken gets about 0.63 and road about 0.14, which matches the picture: mostly chicken, some road.

جرّب ذلك في المحاكي. المنزلقات الأربعة تحدد الدرجات الخام (raw scores)، والـ softmax يحوّل الدرجات الثماني كلها إلى أوزان. مع الإعداد المسبق للشريحة، تحصل chicken على نحو 0.63 وroad على نحو 0.14، وهذا يطابق الصورة: معظم الانتباه لـ chicken، وبعضه لـ road.

SimulatorمحاكيWhere does it look?إلى أين ينظر؟
3.0
1.5
0.5
0.5
Strongest linkchicken 0.63Weights are softmax of the scores, so all eight sum to 1.الأوزان هي softmax للدرجات، لذا مجموع الثمانية كلها 1.
Unadjusted tokensscore 0The other four tokens keep score 0. Words after it are not visible yet in a left-to-right model.الرموز الأربعة الأخرى تبقى درجتها 0. والكلمات التي تليها غير مرئية بعد في نموذج يقرأ من اليسار إلى اليمين.
RNNRNNSelf-attentionSelf-attention
Steps to compute all N outputs of one layerعدد الخطوات لحساب كل المخرجات الـ N لطبقة واحدةN, one after anotherN، واحدة تلو الأخرى1 parallel stepخطوة متوازية واحدة
Hops from token i to token jعدد القفزات من الـ token رقم i إلى الـ token رقم j|i - j||i - j|11
Where long-range information livesأين تعيش المعلومات البعيدةSqueezed into one hidden state vectorمضغوطة في متجه hidden state واحدRead directly from the other tokenتُقرأ مباشرة من الـ token الآخر
Main costالكلفة الرئيسيةSlow, sequential training and fading memoryتدريب بطيء تتابعي وذاكرة تبهتN² token pairs per layerN² من أزواج الـ tokens في كل طبقة
RNN layer versus self-attention layerطبقة RNN مقابل طبقة self-attention

Recall

Name two limitations of RNNs that motivate the transformer, and say what fixes each.اذكر قيدين لشبكات RNN دفعا إلى الـ transformer، وقل ما الذي يصلح كلًا منهما.

One: sequential computation. Each hidden state needs the previous one, so N tokens take N non-parallel steps and training is slow. Removing recurrence fixes it. Two: long-range dependencies. Information must survive many hops through a single hidden state (and in seq2seq, through one final bottleneck vector). Attention fixes it by letting any token read any other token in one step.
الأول: الحساب التتابعي. كل hidden state تحتاج السابقة لها، لذلك تستغرق N من الـ tokens عدد N من الخطوات غير المتوازية ويكون التدريب بطيئًا. وإزالة التكرار (recurrence) تصلحه. الثاني: الاعتماديات البعيدة (long-range dependencies). على المعلومات أن تنجو من قفزات كثيرة عبر hidden state واحدة (وفي seq2seq عبر متجه نهائي واحد هو عنق الزجاجة). والانتباه يصلحه بأن يسمح لأي token بقراءة أي token آخر في خطوة واحدة.

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

Which property of an RNN stops it from computing all positions of a training sentence at once?أي خاصية في شبكة RNN تمنعها من حساب كل مواضع جملة التدريب دفعة واحدة؟

Now translate "I ate an apple" into German: "Ich habe einen Apfel gegessen". German puts the main verb at the end. Ate is the second English word, but its partner gegessen (eaten) is the fifth and last German word.

الآن ترجم "I ate an apple" إلى الألمانية: "Ich habe einen Apfel gegessen". الألمانية تضع الفعل الرئيسي في النهاية. ate هي الكلمة الإنجليزية الثانية، لكن نظيرتها gegessen (أُكِل، eaten) هي الكلمة الألمانية الخامسة والأخيرة.

One vector for the whole sentenceمتجه واحد للجملة كلها

Slide 25 shows the RNN encoder-decoder you built earlier in the lecture. The encoder reads I, ate, an, apple, <eos>. The red box is its final hidden state, and in the plain architecture that one vector is the entire context handed to the decoder. Every fact about the source, which verb, which object, what tense, has to fit inside it. The decoder then generates Ich, habe, einen, Apfel, gegessen with nothing else to look at.

الشريحة 25 تعرض نموذج الـ RNN encoder-decoder الذي بنيته في وقت سابق من المحاضرة. الـ encoder يقرأ I وate وan وapple و<eos>. المربع الأحمر هو الـ hidden state النهائية له، وفي البنية البسيطة يكون ذلك المتجه الواحد هو كامل الـ context الذي يُسلَّم إلى الـ decoder. كل حقيقة عن جملة المصدر، أي فعل، وأي مفعول به، وأي زمن، يجب أن تتسع داخله. ثم يولّد الـ decoder الكلمات Ich وhabe وeinen وApfel وgegessen دون أي شيء آخر ينظر إليه.

This is the bottleneck. For a four-word sentence it is survivable. For a forty-word sentence, the final state has to compress far more than it can hold, and the early words are the most faded because they went through the most updates. Bahdanau, Cho and Bengio put it this way in 2014: they conjectured that the fixed-length vector is a bottleneck for the basic encoder-decoder, and showed that letting the decoder search the source states helps most on long sentences.

هذا هو عنق الزجاجة (bottleneck). في جملة من أربع كلمات يمكن تحمّله. أما في جملة من أربعين كلمة، فعلى الحالة النهائية أن تضغط أكثر بكثير مما تستطيع حمله، وتكون الكلمات الأولى هي الأكثر بهتانًا لأنها مرت بأكبر عدد من التحديثات. وقد عبّر Bahdanau وCho وBengio عن ذلك عام 2014: افترضوا أن المتجه ثابت الطول عنق زجاجة للـ encoder-decoder الأساسي، وأظهروا أن السماح للـ decoder بالبحث في حالات المصدر يفيد أكثر ما يفيد في الجمل الطويلة.

The dashed lines: looking back at the sourceالخطوط المتقطعة: النظر إلى المصدر من جديد

The dashed arrows on the slide show what each decoder word actually needs. When the decoder produces Apfel, it wants the encoder state at apple. When it produces gegessen, it wants the state at ate, which is far back on the source side. Instead of hoping that information survived in the red box, let the decoder look at every encoder state and take a weighted mix, exactly as it did in the chicken example. Queries come from the decoder, and what gets mixed comes from the encoder. That is cross-attention.

الأسهم المتقطعة في الشريحة تبيّن ما تحتاجه فعلًا كل كلمة في الـ decoder. حين يُنتج الـ decoder الكلمة Apfel يريد حالة الـ encoder عند apple. وحين يُنتج gegessen يريد الحالة عند ate، وهي بعيدة إلى الخلف في جهة المصدر. فبدل أن نأمل أن تكون تلك المعلومة قد نجت داخل المربع الأحمر، نسمح للـ decoder بالنظر إلى كل حالات الـ encoder وأخذ مزيج موزون منها، تمامًا كما في مثال chicken. الـ queries تأتي من الـ decoder، وما يُمزج يأتي من الـ encoder. هذا هو الـ cross-attention.

At rest, every source word funnels through one final vector. Active: cross-attention links each German word straight to its English source, including gegessen back to ateفي حالة السكون، تمر كل كلمة من المصدر عبر متجه نهائي واحد. عند التفعيل: يربط cross-attention كل كلمة ألمانية مباشرة بمصدرها الإنجليزي، بما في ذلك gegessen رجوعًا إلى ate

Recall

On slide 25, what is the red box, and why is it a problem for long sentences?في الشريحة 25، ما هو المربع الأحمر، ولماذا يشكّل مشكلة في الجمل الطويلة؟

It is the final encoder hidden state, used as the only context passed to the decoder. All information about the source must be compressed into that one fixed-size vector, so for long inputs early words fade and details are lost. Cross-attention fixes it by letting each decoder step read every encoder state directly.
هو الـ hidden state النهائية للـ encoder، وتُستخدم بوصفها الـ context الوحيد الذي يُمرَّر إلى الـ decoder. يجب ضغط كل المعلومات عن المصدر في ذلك المتجه الواحد ثابت الحجم، لذلك في المدخلات الطويلة تبهت الكلمات الأولى وتضيع التفاصيل. والـ cross-attention يصلح ذلك بأن يسمح لكل خطوة في الـ decoder بقراءة كل حالات الـ encoder مباشرة.

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

In the plain RNN encoder-decoder on slide 25, what does the decoder receive about the source?في نموذج RNN encoder-decoder البسيط في الشريحة 25، ما الذي يتلقاه الـ decoder عن المصدر؟

Take the sentence from before, eight tokens, each an embedding of size d = 512. Stack them into a matrix x of shape 8 × 512. A transformer block takes that matrix in and hands back another 8 × 512 matrix, where every row has now been updated using the rest of the sentence.

خذ الجملة السابقة، ثمانية tokens، كل منها embedding بحجم d = 512. كدّسها في مصفوفة x شكلها 8 × 512. كتلة الـ transformer تأخذ هذه المصفوفة وتعيد مصفوفة أخرى بالشكل 8 × 512، حيث يكون كل صف قد حُدّث باستخدام بقية الجملة.

No recurrence, same shape in and outبلا تكرار، والشكل نفسه في الدخل والخرج

A transformer is a sequence model with no recurrent connections at all. It maps a sequence of N input vectors to a sequence of N output vectors of the same length and the same dimension d, and it is built by stacking identical transformer blocks. Matching shapes are not a coincidence. The block adds its input to its sublayer outputs, and you can only add two matrices of the same shape. Matching shapes also mean the output of block 1 can be the input of block 2, and so on for 12 or 96 layers.

الـ transformer نموذج تسلسلي بلا أي اتصالات تكرارية (recurrent connections) على الإطلاق. يحوّل تسلسلًا من N متجهات دخل إلى تسلسل من N متجهات خرج بالطول نفسه والبعد نفسه d، ويُبنى بتكديس transformer blocks متطابقة. تطابق الأشكال ليس صدفة. فالكتلة تجمع دخلها مع مخرجات طبقاتها الفرعية (sublayers)، ولا يمكنك جمع مصفوفتين إلا إذا كان لهما الشكل نفسه. وتطابق الأشكال يعني أيضًا أن خرج الكتلة 1 يمكن أن يكون دخل الكتلة 2، وهكذا لـ 12 أو 96 طبقة.

The block equations, exactly as on slide 26معادلات الكتلة، تمامًا كما في الشريحة 26

z=LayerNorm⁡(x+SelfAttn⁡(x))z = \operatorname{LayerNorm}\big(x + \operatorname{SelfAttn}(x)\big)
First sublayer: attention, add, normalizeالطبقة الفرعية الأولى: انتباه، ثم جمع، ثم تطبيع
y=LayerNorm⁡(z+FFN⁡(z))y = \operatorname{LayerNorm}\big(z + \operatorname{FFN}(z)\big)
Second sublayer: feedforward, add, normalizeالطبقة الفرعية الثانية: تغذية أمامية، ثم جمع، ثم تطبيع

Read them from the inside out, which is also bottom to top in the slide figure. Self-attention mixes information across positions. The result is added back to x through a residual connection. The sum goes through layer normalization to give z. Then the same pattern repeats with a feedforward network in place of attention: compute FFN(z), add z back, normalize, and the result is the block output y.

اقرأها من الداخل إلى الخارج، وهو أيضًا من الأسفل إلى الأعلى في شكل الشريحة. الـ self-attention يمزج المعلومات عبر المواضع. تُجمع النتيجة مع x عبر residual connection. ويمر المجموع عبر layer normalization ليعطي z. ثم يتكرر النمط نفسه مع شبكة feedforward بدل الانتباه: احسب FFN(z)، واجمع z معها، وطبّع، والنتيجة هي خرج الكتلة y.

One token vector travels through the block: SelfAttn, add the residual copy of x, LayerNorm, FFN, add the residual copy of z, LayerNorm. Input and output are both N × dمتجه token واحد يعبر الكتلة: SelfAttn، ثم جمع النسخة الـ residual من x، ثم LayerNorm، ثم FFN، ثم جمع النسخة الـ residual من z، ثم LayerNorm. الدخل والخرج كلاهما بالشكل N × d
PieceالقطعةWhat it computesما الذي تحسبهWhy it is thereلماذا هي موجودة
SelfAttnSelfAttnMixes information across positions: each token reads the othersيمزج المعلومات عبر المواضع: كل token يقرأ الـ tokens الأخرىThe only piece that looks at other tokensالقطعة الوحيدة التي تنظر إلى tokens أخرى
+ (residual)+ (residual)Adds the block input back to the sublayer outputيجمع دخل الكتلة مع خرج الطبقة الفرعيةKeeps the original signal and gives gradients a direct pathيحافظ على الإشارة الأصلية ويعطي الـ gradients مسارًا مباشرًا
LayerNormLayerNormRescales each token vector to zero mean and unit variance, then γ and βيعيد تحجيم كل متجه token ليصبح متوسطه صفرًا وتباينه واحدًا، ثم γ و βKeeps values in a range that trains wellيُبقي القيم في نطاق يتدرب جيدًا
FFNFFNTwo linear layers with a nonlinearity between themطبقتان خطيتان بينهما دالة غير خطيةProcesses each position on its own, with the same weights at every positionيعالج كل موضع على حدة، بالأوزان نفسها في كل موضع
The four pieces of the blockالقطع الأربع في الكتلة

The feedforward layerطبقة الـ feedforward

FFN is a small two-layer network: a linear map up to a wider hidden layer, a nonlinearity such as ReLU, and a linear map back down to d. It is applied to each position on its own, with the same weights at every position. Attention is the only part of the block where tokens talk to each other; the FFN then processes each token’s mixed vector privately. Beyond the slides: the hidden layer is usually 4d wide. The original transformer used d = 512 and d_ff = 2048.

الـ FFN شبكة صغيرة من طبقتين: تحويل خطي يصعد إلى طبقة مخفية أعرض، ثم دالة غير خطية مثل ReLU، ثم تحويل خطي ينزل مرة أخرى إلى d. تُطبَّق على كل موضع وحده، بالأوزان نفسها في كل موضع. الانتباه هو الجزء الوحيد في الكتلة الذي تتواصل فيه الـ tokens مع بعضها؛ ثم تعالج الـ FFN المتجه الممزوج لكل token على انفراد. وخارج نطاق الشرائح: تكون الطبقة المخفية عادة بعرض 4d. استخدم الـ transformer الأصلي d = 512 وd_ff = 2048.

FFN⁡(z)=max⁡(0, zW1+b1) W2+b2\operatorname{FFN}(z) = \max(0,\, zW_1 + b_1)\,W_2 + b_2
FFN with ReLU, as in Vaswani et al. (2017)FFN مع ReLU، كما في Vaswani et al. (2017)

Worked exampleمثال محلول

How big is one FFN?ما حجم FFN واحدة؟

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

    W₁ is 512 × 2048 = 1,048,576 weights, plus 2,048 biases.
    W₁ فيها 512 × 2048 = 1,048,576 وزنًا، إضافة إلى 2,048 من الـ biases.
  2. Second layerالطبقة الثانية

    W₂ is 2048 × 512 = 1,048,576 weights, plus 512 biases.
    W₂ فيها 2048 × 512 = 1,048,576 وزنًا، إضافة إلى 512 من الـ biases.
  3. Resultالنتيجة

    About 2.1 million parameters per block, roughly twice the 4 × 512² ≈ 1.05 million in the attention projections you will meet next. Most of a transformer’s parameters sit in its feedforward layers.
    نحو 2.1 million معامل (parameter) لكل كتلة، أي قرابة ضعف الـ 4 × 512² ≈ 1.05 million الموجودة في إسقاطات الانتباه التي ستقابلها لاحقًا. معظم معاملات الـ transformer موجودة في طبقات الـ feedforward.

Why residual connectionsلماذا الـ residual connections

A residual connection computes x + f(x) instead of f(x). The sublayer only has to learn a correction to its input, not rebuild the whole vector from scratch. If attention has nothing useful to add at some position, it can output something near zero and the token passes through unchanged. During training, the gradient of x + f(x) with respect to x contains a plain identity term, so the error signal has a direct path down through every block. This is what makes deep stacks trainable, the same lesson He and colleagues found for very deep image networks.

الـ residual connection تحسب x + f(x) بدل f(x). فلا تحتاج الطبقة الفرعية إلا إلى تعلّم تصحيح لدخلها، لا إلى إعادة بناء المتجه كله من الصفر. وإذا لم يكن لدى الانتباه ما يضيفه عند موضع ما، يمكنه أن يُخرج شيئًا قريبًا من الصفر فيمر الـ token دون تغيير. وأثناء التدريب، يحتوي الـ gradient لـ x + f(x) بالنسبة إلى x على حدّ هوية (identity) صريح، فيكون لإشارة الخطأ مسار مباشر نزولًا عبر كل كتلة. وهذا ما يجعل التكديسات العميقة قابلة للتدريب، وهو الدرس نفسه الذي وجده He وزملاؤه في شبكات الصور العميقة جدًا.

Why layer normalizationلماذا الـ layer normalization

After several additions, the numbers in a token vector can drift to large or lopsided values, which makes gradient descent unstable. Layer norm fixes each token vector on its own: subtract the mean of its d entries, divide by their standard deviation, then apply a learned gain γ and offset β. It normalizes across the dimensions of one token, never across different tokens or examples.

بعد عدة عمليات جمع، قد تنجرف الأرقام في متجه الـ token إلى قيم كبيرة أو غير متوازنة، وهذا يجعل الـ gradient descent غير مستقر. الـ layer norm يضبط كل متجه token وحده: اطرح متوسط عناصره الـ d، واقسم على انحرافها المعياري، ثم طبّق معامل تكبير متعلَّمًا γ وإزاحة متعلَّمة β. هو يطبّع عبر أبعاد token واحد، ولا يطبّع أبدًا عبر tokens مختلفة أو أمثلة مختلفة.

LayerNorm⁡(x)=γ x−μσ+β,μ=1d∑j=1dxj,σ=1d∑j=1d(xj−μ)2\operatorname{LayerNorm}(x) = \gamma\,\frac{x - \mu}{\sigma} + \beta,\quad \mu = \frac{1}{d}\sum_{j=1}^{d} x_j,\quad \sigma = \sqrt{\frac{1}{d}\sum_{j=1}^{d}(x_j - \mu)^2}
Layer norm on one token vector of size dlayer norm على متجه رمز واحد حجمه d

Worked exampleمثال محلول

One residual add and layer norm, with d = 4جمع residual واحد ثم layer norm، مع d = 4

  1. Residual addجمع الـ residual

    Let x = [1, 3, 2, 2] and suppose SelfAttn(x) = [1, 1, 4, 6] at this position. Then x + SelfAttn(x) = [2, 4, 6, 8].
    لتكن x = [1, 3, 2, 2] ولنفترض أن SelfAttn(x) = [1, 1, 4, 6] عند هذا الموضع. إذن x + SelfAttn(x) = [2, 4, 6, 8].
  2. Mean and standard deviationالمتوسط والانحراف المعياري

    μ = (2 + 4 + 6 + 8) / 4 = 5. Deviations are [-3, -1, 1, 3], squared [9, 1, 1, 9], mean 20 / 4 = 5, so σ = √5 ≈ 2.236.
    μ = (2 + 4 + 6 + 8) / 4 = 5. الانحرافات هي [-3, -1, 1, 3]، ومربعاتها [9, 1, 1, 9]، ومتوسطها 20 / 4 = 5، إذن σ = √5 ≈ 2.236.
  3. Normalizeطبّع

    (x - μ) / σ ≈ [-1.342, -0.447, 0.447, 1.342]. With γ = 1 and β = 0, that is z.
    (x - μ) / σ ≈ [-1.342, -0.447, 0.447, 1.342]. ومع γ = 1 وβ = 0 تكون هذه هي z.
  4. Resultالنتيجة

    The output has mean 0 and standard deviation 1, and still has 4 entries, so the next residual add z + FFN(z) works.
    الخرج متوسطه 0 وانحرافه المعياري 1، وما زال فيه 4 عناصر، لذلك ينجح جمع الـ residual التالي z + FFN(z).

Recall

Write the transformer block equations from slide 26, and say why input and output must have the same shape.اكتب معادلات كتلة الـ transformer من الشريحة 26، وقل لماذا يجب أن يكون للدخل والخرج الشكل نفسه.

z = LayerNorm(x + SelfAttn(x)); y = LayerNorm(z + FFN(z)). Both residual additions add a sublayer’s output to its input, which is only defined if they have the same shape N × d. Same shape in and out also lets blocks be stacked.
z = LayerNorm(x + SelfAttn(x)); y = LayerNorm(z + FFN(z)). عمليتا جمع الـ residual كلتاهما تجمعان خرج طبقة فرعية مع دخلها، وهذا لا يكون معرَّفًا إلا إذا كان لهما الشكل نفسه N × d. وتطابق الشكل في الدخل والخرج يسمح أيضًا بتكديس الكتل.

Recall

What do residual connections and layer norm each contribute?ما الذي تضيفه كل من الـ residual connections والـ layer norm؟

Residuals let each sublayer learn a correction on top of its input and give gradients a direct identity path through deep stacks. Layer norm rescales each token vector to zero mean and unit variance (then learned γ and β), keeping values in a range where training is stable.
الـ residuals تسمح لكل طبقة فرعية بتعلّم تصحيح فوق دخلها، وتعطي الـ gradients مسار هوية (identity) مباشرًا عبر التكديسات العميقة. والـ layer norm يعيد تحجيم كل متجه token ليصبح متوسطه صفرًا وتباينه واحدًا (ثم γ وβ متعلَّمان)، فيُبقي القيم في نطاق يكون فيه التدريب مستقرًا.

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

Which pair of equations matches the transformer block on slide 26?أي زوج من المعادلات يطابق كتلة الـ transformer في الشريحة 26؟

Recapالخلاصة

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

  • RNN limitation 1: computation is sequential. h_t needs h_{t-1}, so N tokens take N steps that cannot run in parallel.القيد الأول لشبكات RNN: الحساب تتابعي. الحالة h_t تحتاج h_{t-1}، لذلك تستغرق N من الـ tokens عدد N من الخطوات التي لا يمكن تشغيلها بالتوازي.
  • RNN limitation 2: long-range information must survive many hops through the hidden state, and in an encoder-decoder the whole source is squeezed into one final vector (the bottleneck).القيد الثاني لشبكات RNN: على المعلومات البعيدة أن تنجو من قفزات كثيرة عبر الـ hidden state، وفي نموذج encoder-decoder يُضغط المصدر كله في متجه نهائي واحد (عنق الزجاجة).
  • Self-attention: every token reads every allowed token directly, in one step, weighted by a softmax distribution. On slide 24, it attends mostly to chicken and somewhat to road.الـ self-attention: كل token يقرأ كل token مسموح له به مباشرة، في خطوة واحدة، بأوزان تأتي من توزيع softmax. في الشريحة 24 تنتبه it في الغالب إلى chicken وبقدر أقل إلى road.
  • Cross-attention: each decoder step looks back at all encoder states, so gegessen can read ate directly instead of hoping it survived in the final state.الـ cross-attention: كل خطوة في الـ decoder تنظر إلى جميع حالات الـ encoder، فتستطيع gegessen قراءة ate مباشرة بدل أن تأمل أن تكون معلومتها قد نجت في الحالة النهائية.
  • Slide 26 block (post-norm): z = LayerNorm(x + SelfAttn(x)), y = LayerNorm(z + FFN(z)).كتلة الشريحة 26 (post-norm): z = LayerNorm(x + SelfAttn(x))، و y = LayerNorm(z + FFN(z)).
  • Input and output are both N × d, which is what lets the residual additions work and lets blocks stack.الدخل والخرج كلاهما بالشكل N × d، وهذا ما يجعل عمليات الجمع في الـ residual ممكنة ويسمح بتكديس الكتل فوق بعضها.
  • FFN: two linear layers with a nonlinearity, applied to each position independently. Typical inner size is 4d (512 and 2048 in the original transformer).الـ FFN: طبقتان خطيتان بينهما دالة غير خطية، تُطبَّق على كل موضع بشكل مستقل. الحجم الداخلي المعتاد هو 4d (512 و 2048 في الـ transformer الأصلي).
  • Residuals carry the input and gradients straight through; layer norm rescales each token vector to zero mean and unit variance, then applies a learned γ and β.الـ residuals تمرر الدخل والـ gradients مباشرة عبر الكتلة؛ والـ layer norm يعيد تحجيم كل متجه token ليصبح متوسطه صفرًا وتباينه واحدًا، ثم يطبق γ و β متعلَّمين.
  • SLP3 (2026) uses pre-norm: h = x + SelfAttn(LayerNorm(x)), out = h + FFN(LayerNorm(h)). On the exam, write the slide's post-norm version.كتاب SLP3 (إصدار 2026) يستخدم pre-norm: h = x + SelfAttn(LayerNorm(x))، و out = h + FFN(LayerNorm(h)). في الامتحان اكتب نسخة الشريحة post-norm.

Sourcesالمصادر