Majid Al-RaimiFull guideالشرح الكامل

ICS 582Lecture 06المحاضرة 06Full guideالشرح الكامل

Neural Language Modelsنماذج اللغة العصبية

The whole lecture on one page, taught concept by concept. Work through the parts in order, mark each concept once you understand it, and open the slide chips when you want the original slides.المحاضرة كاملة في صفحة واحدة، مشروحة مفهومًا مفهومًا. امشِ على الأجزاء بالترتيب، وعلّم كل مفهوم بعد أن تفهمه، وافتح أزرار الشرائح عندما تريد الرجوع إلى الشرائح الأصلية.

Partsالأجزاء
8
Conceptsالمفاهيم
32
Slidesالشرائح
43
Readingمدة القراءة
192 min192 دقيقة
Understoodما فهمته
0/32 conceptsمفاهيم

Part 01: Sequence task shapes and the recurrent cellأشكال مهام التسلسل والخلية المتكررة

Why different tasks need different input/output shapes, and how a simple RNN carries a hidden state through time with one tanh layer.لماذا تحتاج المهام المختلفة أشكالا مختلفة للمدخلات والمخرجات، وكيف تحمل شبكة RNN البسيطة حالة مخفية عبر الزمن بطبقة tanh واحدة.

3 concepts3 مفاهيم, ، slides 1-5الشرائح 1-5

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

Up to now every language model in this course counted things. This lecture replaces counting with learned functions, and it starts with the most basic question a neural model of text must answer: how do you feed a sequence of unknown length into a network and get the right kind of answer out?

This part builds the vocabulary the rest of the lecture uses. First, the map of the lecture so you know where each later idea plugs in. Second, the five input/output shapes a sequence model can take, each tied to a real NLP task. Third, the recurrent cell itself: one small equation, reused at every word, whose weakness (it forgets) drives everything that comes after, from the LSTM to attention. Expect exam questions of two kinds: "which shape fits task X" and "write and explain the RNN recurrence".

حتى الآن، كان كل نموذج لغة في هذا المقرر يعتمد على العدّ. هذه المحاضرة تستبدل العدّ بدوال متعلَّمة، وتبدأ بأبسط سؤال يجب أن يجيب عنه أي نموذج عصبي للنص: كيف تُدخل تسلسلًا مجهول الطول إلى شبكة، وتحصل منها على النوع الصحيح من الإجابة؟

يبني هذا الجزء المفردات التي تستخدمها بقية المحاضرة. أولًا، خريطة المحاضرة حتى تعرف أين تندرج كل فكرة لاحقة. ثانيًا، أشكال الإدخال والإخراج الخمسة التي يمكن أن يتخذها نموذج التسلسل، وكل شكل مربوط بمهمة NLP حقيقية. ثالثًا، الخلية التكرارية نفسها: معادلة صغيرة واحدة يُعاد استخدامها عند كل كلمة، ونقطة ضعفها (أنها تنسى) هي ما يقود كل ما يأتي بعدها، من الـ LSTM إلى الانتباه (attention). توقّع أسئلة اختبار من نوعين: "أي شكل يناسب المهمة X" و"اكتب معادلة التكرار في الـ RNN واشرحها".

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

  1. Name the four arcs of this lecture and say what problem each one solves for the next.سمِّ المحاور الأربعة لهذه المحاضرة، وبيّن المشكلة التي يحلّها كل محور للمحور الذي يليه.
  2. Draw the five input/output shapes of a sequence model and match a concrete task to each.ارسم أشكال الإدخال والإخراج الخمسة لنموذج التسلسل، وطابق كل شكل مع مهمة محددة.
  3. Explain why machine translation needs the delayed many-to-many shape and tagging needs the synchronized one.اشرح لماذا تحتاج الترجمة الآلية إلى شكل many-to-many المؤجَّل (delayed)، بينما يحتاج الوسم (tagging) إلى الشكل المتزامن (synchronized).
  4. Write the simple RNN recurrence and output equation from memory and name every symbol.اكتب معادلة التكرار ومعادلة الإخراج للـ RNN البسيطة من الذاكرة، وسمِّ كل رمز فيهما.
  5. Explain parameter sharing across time steps and why it makes model size independent of sentence length.اشرح مشاركة المعاملات (parameter sharing) عبر الخطوات الزمنية، ولماذا تجعل حجم النموذج مستقلًا عن طول الجملة.
  6. Run a scalar RNN by hand for three steps and use the numbers to explain why simple RNNs forget.شغّل RNN عددية (scalar) يدويًا لثلاث خطوات، واستخدم الأرقام لتشرح لماذا تنسى الـ RNN البسيطة.

Take the sentence "The students who sat the midterm on Monday ___". A trigram model sees only "on Monday" and has no idea the blank belongs to a plural subject six words back. Every idea in this lecture is a better answer to that one problem: how to let the prediction depend on the whole history, not a fixed window of counts.

خذ الجملة "The students who sat the midterm on Monday ___". نموذج الـ trigram لا يرى إلا "on Monday"، وليست لديه أي فكرة أن الفراغ يعود إلى فاعل جمع يقع قبل ست كلمات. كل فكرة في هذه المحاضرة هي إجابة أفضل عن هذه المشكلة الواحدة: كيف نجعل التنبؤ يعتمد على التاريخ كله، لا على نافذة ثابتة من الأعداد.

The lecture is organized in four arcs, and each one fixes a limit of the one before it.

تنتظم المحاضرة في أربعة محاور، وكل محور يعالج قيدًا في المحور الذي قبله.

  1. Deep learning architectures: The Recurrent neural network (RNN) reads a sequence one token at a time and carries a memory forward. The Long short-term memory (LSTM) adds gates so that memory survives longer, and the Encoder-decoder (seq2seq) joins two RNNs so input and output sequences can have different lengths.معماريات التعلم العميق: تقرأ recurrent neural network التسلسل token تلو الآخر وتحمل معها ذاكرة إلى الأمام. ويضيف الـ LSTM بوابات (gates) حتى تصمد تلك الذاكرة مدة أطول، ويربط الـ encoder-decoder شبكتي RNN معًا حتى يمكن أن يختلف طول تسلسل الإدخال عن طول تسلسل الإخراج.
  2. Neural language models: A Neural language model uses an RNN to predict the next word, replacing the sparse counts of a Count-based (n-gram) language model with learned vectors, and is trained with cross-entropy and teacher forcing.نماذج اللغة العصبية: يستخدم neural language model شبكة RNN للتنبؤ بالكلمة التالية، فيستبدل الأعداد المتناثرة (sparse counts) في count-based LM بمتجهات متعلَّمة، ويُدرَّب باستخدام cross-entropy وteacher forcing.
  3. Transformers: The Transformer drops recurrence entirely and lets every position look at every other position directly through Self-attention.المحوّلات: يتخلى الـ transformer عن التكرار تمامًا، ويسمح لكل موضع بأن ينظر إلى كل موضع آخر مباشرة عبر self-attention.
  4. Transformer language models: Stacks of transformer blocks become decoder-only models such as GPT and encoder-only models such as BERT, with a language modeling head on top.نماذج اللغة المبنية على المحوّل: تتحول طبقات متراصّة من كتل المحوّل إلى نماذج من نوع decoder-only مثل GPT، ونماذج من نوع encoder-only مثل BERT، وفوقها رأس لنمذجة اللغة (language modeling head).
The four arcs of the lecture. This part sits at the start of the first arc, the recurrent architectures.المحاور الأربعة للمحاضرة. يقع هذا الجزء في بداية المحور الأول، أي المعماريات التكرارية.

Keep the thread in mind as you read: RNNs process tokens in order, so they are natural for sequences but slow to train and forgetful over long distances. Transformers answer both complaints. You cannot appreciate why attention matters until you have seen exactly where recurrence breaks, and that is what the rest of this part sets up.

أبقِ هذا الخيط في ذهنك وأنت تقرأ: تعالج الـ RNN الـ tokens بالترتيب، لذلك هي طبيعية للتسلسلات، لكنها بطيئة في التدريب وتنسى عبر المسافات الطويلة. المحوّلات تجيب عن الشكويين معًا. ولن تقدّر أهمية الانتباه (attention) حتى ترى بالضبط أين ينهار التكرار، وهذا ما تمهّد له بقية هذا الجزء.

Recall

Name the four arcs of the lecture in order, and say in one phrase what each adds to the previous one.سمِّ المحاور الأربعة للمحاضرة بالترتيب، وقل في عبارة واحدة ما يضيفه كل محور إلى ما قبله.

Architectures (RNN, LSTM, encoder-decoder: a memory that runs along the sequence), neural language models (use that memory to predict the next word instead of counting n-grams), transformers (replace recurrence with attention so every position sees every other), transformer language models (stack transformer blocks into GPT and BERT style models with a language modeling head).
المعماريات (RNN وLSTM وencoder-decoder: ذاكرة تسري على طول التسلسل)، ثم نماذج اللغة العصبية (تستخدم تلك الذاكرة للتنبؤ بالكلمة التالية بدل عدّ الـ n-grams)، ثم المحوّلات (تستبدل التكرار بالانتباه حتى يرى كل موضع كل موضع آخر)، ثم نماذج اللغة المبنية على المحوّل (ترصّ كتل المحوّل في نماذج على طراز GPT وBERT مع رأس لنمذجة اللغة).

Consider three jobs. Decide whether a movie review is positive. Tag every word of a sentence with its part of speech. Translate an English sentence into Arabic. All three take a sentence as input, yet they need very different networks, because what comes out differs: one label, one label per word, or a whole new sentence.

تأمّل ثلاث مهام. قرّر هل مراجعة فيلم إيجابية. ضع لكل كلمة في جملة وسمَ قسمها الكلامي (part of speech). ترجم جملة إنجليزية إلى العربية. المهام الثلاث كلها تأخذ جملة مدخلًا، ومع ذلك تحتاج إلى شبكات مختلفة جدًا، لأن ما يخرج مختلف: تسمية واحدة، أو تسمية لكل كلمة، أو جملة جديدة كاملة.

These input/output configurations are the sequence task shapes. Slide 3 reproduces Andrej Karpathy's well-known figure of five of them. Red boxes are inputs, green boxes are the hidden state, blue boxes are outputs, and the horizontal green arrows are the recurrence that carries state from one step to the next. The slide gives no example task, so here is the mapping you should be able to reproduce in an exam.

هذه التشكيلات من الإدخال والإخراج هي sequence task shapes (أشكال مهام التسلسل). تعيد الشريحة 3 رسم الشكل المشهور لـ Andrej Karpathy الذي يعرض خمسة منها. المربعات الحمراء هي المدخلات، والخضراء هي الحالة المخفية (hidden state)، والزرقاء هي المخرجات، والأسهم الخضراء الأفقية هي التكرار الذي ينقل الحالة من خطوة إلى التالية. لا تعطي الشريحة أي مهمة مثالًا، لذلك إليك الربط الذي يجب أن تستطيع إعادة كتابته في الاختبار.

ShapeالشكلInput and outputالإدخال والإخراجExample tasksأمثلة على المهامWhat to rememberما يجب تذكّره
One to oneOne to one1 input, 1 output, no recurrenceإدخال واحد، وإخراج واحد، بلا تكرارImage classificationتصنيف الصورThere is no sequence at all; this is the feedforward baseline the others extend.لا يوجد تسلسل أصلًا؛ هذا هو خط الأساس الأمامي (feedforward) الذي توسّعه الأشكال الأخرى.
One to manyOne to many1 input, a sequence outإدخال واحد، ويخرج تسلسلImage captioning; generating text from a single prompt vectorوصف الصور (image captioning)؛ توليد نص من متجه موجِّه (prompt) واحدThe input seeds the hidden state; each output step feeds the next.الإدخال يهيّئ الحالة المخفية؛ وكل خطوة إخراج تغذّي الخطوة التالية.
Many to oneMany to oneA sequence in, 1 outputيدخل تسلسل، ويخرج مخرج واحدSentiment classification; spam detectionتصنيف المشاعر (sentiment)؛ كشف الرسائل المزعجة (spam)Only the final hidden state is read, so it must summarize the whole input.لا تُقرأ إلا الحالة المخفية الأخيرة، لذلك يجب أن تلخّص الإدخال كله.
Many to many, delayedMany to many، مؤجَّل (delayed)Read all input, then emit a sequenceاقرأ الإدخال كله، ثم أخرج تسلسلًاMachine translation; summarizationالترجمة الآلية؛ التلخيصOutput length and order are free to differ from the input. This is the encoder-decoder.طول الإخراج وترتيبه يمكن أن يختلفا بحرية عن الإدخال. هذا هو الـ encoder-decoder.
Many to many, synchronizedMany to many، متزامن (synchronized)One output per input tokenمخرج واحد لكل token في الإدخالPart-of-speech tagging; named entity recognitionوسم أقسام الكلام (part-of-speech tagging)؛ التعرف على الكيانات المسماة (NER)Same length, same order; each label is emitted as its token is read.نفس الطول ونفس الترتيب؛ كل تسمية تُخرَج عند قراءة الـ token الخاص بها.
The five shapes, with concrete tasksالأشكال الخمسة مع مهام محددة

Pick a shape below and try to name a task for it before revealing the examples. The diagram redraws with the same color code as the slide: grey for inputs, the accent color for hidden states, teal for outputs.

اختر شكلًا أدناه وحاول أن تسمّي مهمة له قبل أن تكشف الأمثلة. يُعاد رسم المخطط بنفس ترميز الألوان في الشريحة: الرمادي للمدخلات، ولون التمييز (accent) للحالات المخفية، والأزرق المخضرّ (teal) للمخرجات.

InteractiveتفاعليFive sequence task shapesخمسة أشكال لمهام التسلسل

1 to 1: one fixed input, one output, no recurrence. Inputs drawn: 1, outputs drawn: 1. Nothing is a sequence, so a plain feedforward network is enough.من 1 إلى 1: مدخل ثابت واحد ومخرج واحد، دون تكرار (recurrence). المدخلات المرسومة: 1، والمخرجات المرسومة: 1. لا شيء هنا تسلسل، لذا تكفي شبكة أمامية التغذية (feedforward) عادية.

Read the figure by asking two questionsاقرأ الشكل بطرح سؤالين

You do not need to memorize five pictures. Ask two questions of any task. First, is the input a sequence, and is the output a sequence? That separates one to one, one to many, many to one and many to many. Second, if both are sequences, does each output line up with one input, at the same moment it is read? If yes, the shape is synchronized. If the output can only start once the whole input has been seen, it is delayed.

لا تحتاج إلى حفظ خمس صور. اطرح سؤالين على أي مهمة. الأول: هل الإدخال تسلسل، وهل الإخراج تسلسل؟ هذا يفصل بين one to one وone to many وmany to one وmany to many. الثاني: إذا كان كلاهما تسلسلًا، فهل يقابل كل مخرج مدخلًا واحدًا، في نفس اللحظة التي يُقرأ فيها؟ إذا كانت الإجابة نعم، فالشكل متزامن (synchronized). وإذا كان الإخراج لا يمكن أن يبدأ إلا بعد رؤية الإدخال كاملًا، فهو مؤجَّل (delayed).

Sentiment is many to one: the review is a sequence, the verdict is one label, and the network reads every word before deciding from its final hidden state. Spam detection is the same shape. Part-of-speech tagging and named entity recognition are synchronized many to many: the word "book" gets its tag when it is read, and the output has exactly as many labels as the input has tokens. Image captioning is one to many: one image vector in, a sentence out.

تحليل المشاعر (sentiment) هو many to one: المراجعة تسلسل، والحكم تسمية واحدة، والشبكة تقرأ كل كلمة قبل أن تقرر من حالتها المخفية الأخيرة. كشف الرسائل المزعجة (spam detection) له نفس الشكل. أما وسم أقسام الكلام (part-of-speech tagging) والتعرف على الكيانات المسماة (named entity recognition) فهما many to many متزامن: الكلمة "book" تأخذ وسمها عند قراءتها، وعدد التسميات في الإخراج يساوي تمامًا عدد الـ tokens في الإدخال. ووصف الصور (image captioning) هو one to many: متجه صورة واحد يدخل، وجملة تخرج.

Why translation needs the delayed shapeلماذا تحتاج الترجمة إلى الشكل المؤجَّل

Slide 9 later in this lecture gives the example that makes the point. English "Zaid went to his house" is five tokens. The Arabic ذهب زيد إلى بيته is four words, glossed "went Zaid to his-house". Two things break a synchronized model here. The lengths differ (five against four, because "his house" becomes one word), and the order differs (Arabic puts the verb first, verb-subject-object, while English puts the subject first). A synchronized network must emit the Arabic verb at the moment it reads "Zaid", before it has even seen "went". The only safe plan is to read the whole source first and then generate: the delayed shape, which is exactly the Encoder-decoder (seq2seq) of the next part.

تعطي الشريحة 9 لاحقًا في هذه المحاضرة المثال الذي يوضح الفكرة. الجملة الإنجليزية "Zaid went to his house" فيها خمسة tokens. والعربية ذهب زيد إلى بيته أربع كلمات، ومقابلها الحرفي "went Zaid to his-house". هناك أمران يكسران النموذج المتزامن هنا. الأطوال مختلفة (خمسة مقابل أربعة، لأن "his house" تصبح كلمة واحدة)، والترتيب مختلف (العربية تقدّم الفعل، فعل ثم فاعل ثم مفعول، بينما تقدّم الإنجليزية الفاعل). على الشبكة المتزامنة أن تُخرج الفعل العربي في اللحظة التي تقرأ فيها "Zaid"، قبل أن ترى حتى "went". الخطة الآمنة الوحيدة هي قراءة المصدر كاملًا أولًا ثم التوليد: أي الشكل المؤجَّل، وهو بالضبط الـ encoder-decoder في الجزء التالي.

Alignment between the English tokens and the Arabic gloss: the teal lines cross because the verb moves to the front, and two English tokens merge into one Arabic word.المحاذاة بين الكلمات الإنجليزية ومقابلها العربي: تتقاطع الخطوط الزرقاء المخضرّة لأن الفعل ينتقل إلى البداية، وتندمج كلمتان إنجليزيتان في كلمة عربية واحدة.

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

Which shape fits named entity recognition, where every token receives a tag such as PERSON or O?أي شكل يناسب التعرف على الكيانات المسماة (NER)، حيث يأخذ كل token وسمًا مثل PERSON أو O؟

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

Why does English to Arabic translation need the delayed many-to-many shape rather than the synchronized one?لماذا تحتاج الترجمة من الإنجليزية إلى العربية إلى شكل many-to-many المؤجَّل بدل المتزامن؟

Recall

Spam detection uses which shape, and which hidden state does the classifier read?أي شكل يستخدمه كشف الرسائل المزعجة، وأي حالة مخفية يقرؤها المصنِّف؟

Many to one. The network reads every token of the email and the classifier reads only the final hidden state, which therefore has to summarize the whole message.
Many to one. تقرأ الشبكة كل token في البريد، ولا يقرأ المصنِّف إلا الحالة المخفية الأخيرة، لذلك يجب أن تلخّص تلك الحالة الرسالة كلها.

Read the sentence "the movie was not good" one word at a time and keep a single running note in your head. After "not" the note says "something negative may be coming"; after "good" it says "negative overall". You never reread the sentence. You only update the note with the new word. That running note is the Hidden state, and the rule that updates it is the recurrent cell.

اقرأ الجملة "the movie was not good" كلمة كلمة، واحتفظ في ذهنك بملاحظة جارية واحدة. بعد "not" تقول الملاحظة "قد يأتي شيء سلبي"؛ وبعد "good" تقول "سلبية في المجمل". أنت لا تعيد قراءة الجملة أبدًا، بل تحدّث الملاحظة بالكلمة الجديدة فقط. تلك الملاحظة الجارية هي hidden state (الحالة المخفية)، والقاعدة التي تحدّثها هي الخلية التكرارية.

Slide 4 opens the architectures arc with its two families, RNNs and transformers. This part covers the first. Slide 5 draws the simplest Recurrent neural network (RNN) cell, taken from Christopher Olah's diagram: the previous hidden state h_(t-1) enters from the left, the current input x_t from below, both are combined and passed through one tanh layer, and the result leaves to the right as the new state h_t and upward as the output o_t.

تفتتح الشريحة 4 محور المعماريات بعائلتيه: RNNs والمحوّلات. يغطي هذا الجزء الأولى. وترسم الشريحة 5 أبسط خلية recurrent neural network، مأخوذة من مخطط Christopher Olah: تدخل الحالة المخفية السابقة h_(t-1) من اليسار، ويدخل الإدخال الحالي x_t من الأسفل، ويُدمجان ويمرّان عبر طبقة tanh واحدة، وتخرج النتيجة إلى اليمين بوصفها الحالة الجديدة h_t وإلى الأعلى بوصفها المخرج o_t.

The recurrence, written outمعادلة التكرار مكتوبة بالتفصيل

ht=tanh⁡(Whh ht−1+Wxh xt+b)h_t = \tanh\left(W_{hh}\,h_{t-1} + W_{xh}\,x_t + b\right)
Hidden state update of a simple (Elman) RNNتحديث الحالة المخفية في RNN بسيطة (Elman)
ot=Why ht,y^t=softmax⁡(ot)o_t = W_{hy}\,h_t,\qquad \hat{y}_t = \operatorname{softmax}(o_t)
Output at step tالمخرج عند الخطوة t
  • x_t is the input at step t, for text usually a word embedding of size d_x.x_t هو الإدخال عند الخطوة t، وهو في النصوص عادة word embedding بحجم d_x.
  • h_t is the hidden state of size d_h; h_0 is usually a zero vector.h_t هي الحالة المخفية بحجم d_h؛ وh_0 عادة متجه أصفار.
  • W_xh (d_h × d_x) maps the input into the hidden space, W_hh (d_h × d_h) maps the old state into the new one, b is a bias.W_xh (d_h × d_x) تنقل الإدخال إلى الفضاء المخفي، وW_hh (d_h × d_h) تنقل الحالة القديمة إلى الحالة الجديدة، وb هو الانحياز (bias).
  • W_hy maps the state to output scores, and a Softmax turns them into a probability distribution when the task needs one.W_hy تنقل الحالة إلى درجات الإخراج، ثم تحوّلها softmax إلى توزيع احتمالي عندما تحتاج المهمة إلى ذلك.

Jurafsky and Martin write the same equations as h_t = g(U h_(t-1) + W x_t) and y_t = f(V h_t), so in the textbook U is the recurrent matrix, W the input matrix and V the output matrix. The letters change between sources; the roles do not. The tanh keeps every component of h_t between -1 and 1, so the state cannot grow without bound as the sequence gets longer.

يكتب Jurafsky وMartin نفس المعادلات على الصورة h_t = g(U h_(t-1) + W x_t) وy_t = f(V h_t)، فتكون U في الكتاب هي المصفوفة التكرارية، وW مصفوفة الإدخال، وV مصفوفة الإخراج. الحروف تتغير بين المصادر، أما الأدوار فلا. وتُبقي tanh كل مكوّن من h_t بين -1 و1، فلا تستطيع الحالة أن تنمو بلا حد كلما طال التسلسل.

One set of weights, reused at every stepمجموعة أوزان واحدة يُعاد استخدامها في كل خطوة

The single most important property of the cell is that W_hh, W_xh, b and W_hy are the same at every time step. When you unroll the network over a four-word sentence you draw four boxes, but they are four copies of one cell, not four networks. The textbook says it directly: the weights are shared across all time steps, while new values of h and y are computed at each step.

أهم خاصية على الإطلاق في الخلية أن W_hh وW_xh وb وW_hy هي نفسها في كل خطوة زمنية. عندما تفرد (unroll) الشبكة على جملة من أربع كلمات ترسم أربعة صناديق، لكنها أربع نسخ من خلية واحدة، لا أربع شبكات. ويقولها الكتاب صراحة: الأوزان مشتركة عبر كل الخطوات الزمنية، بينما تُحسب قيم جديدة لـ h وy في كل خطوة.

Unrolled over four steps: one bank of weights feeds every copy of the cell, while the hidden state flows left to right.الشبكة مفرودة على أربع خطوات: مخزن أوزان واحد يغذّي كل نسخة من الخلية، بينما تسري الحالة المخفية من اليسار إلى اليمين.

Parameter sharing buys three things. The model handles sentences of any length with the same network. The number of parameters is fixed: with d_x = 100 and d_h = 128, the recurrent layer has 128 × 128 + 128 × 100 + 128 = 29,312 parameters whether the sentence has five words or five hundred. And whatever the cell learns about a pattern such as "not" followed by an adjective applies at every position, not only at the position where it was seen in training.

تمنحنا مشاركة المعاملات (parameter sharing) ثلاثة أشياء. يتعامل النموذج مع جمل بأي طول بنفس الشبكة. وعدد المعاملات ثابت: مع d_x = 100 وd_h = 128 تحتوي الطبقة التكرارية على 128 × 128 + 128 × 100 + 128 = 29,312 معاملًا سواء كانت الجملة خمس كلمات أو خمسمئة. وكل ما تتعلمه الخلية عن نمط ما، مثل "not" متبوعة بصفة، ينطبق في كل موضع، لا في الموضع الذي رأته فيه أثناء التدريب فقط.

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

An RNN reads a 10-token sentence and later a 200-token sentence. How many recurrent matrices W_hh does it use?تقرأ RNN جملة من 10 tokens ثم لاحقًا جملة من 200 token. كم مصفوفة تكرارية W_hh تستخدم؟

Recall

Write the simple RNN equations from memory and say which quantities change with t and which do not.اكتب معادلات الـ RNN البسيطة من الذاكرة، وقل أي الكميات تتغير مع t وأيها لا تتغير.

h_t = tanh(W_hh h_(t-1) + W_xh x_t + b) and o_t = W_hy h_t (then softmax). The inputs x_t, the states h_t and the outputs o_t change with t. The weights W_hh, W_xh, W_hy and the bias b are shared and never change with t.
h_t = tanh(W_hh h_(t-1) + W_xh x_t + b) وo_t = W_hy h_t (ثم softmax). المدخلات x_t والحالات h_t والمخرجات o_t تتغير مع t. أما الأوزان W_hh وW_xh وW_hy والانحياز b فهي مشتركة ولا تتغير مع t أبدًا.

Running the cell by handتشغيل الخلية يدويًا

The vectors hide what the recurrence does, so shrink everything to scalars. Use w_hh = 0.5, w_xh = 1, b = 0, start from h_0 = 0, and feed a single pulse followed by silence: x = [1, 0, 0, 0].

المتجهات تخفي ما يفعله التكرار، لذلك صغّر كل شيء إلى قيم عددية (scalars). استخدم w_hh = 0.5 وw_xh = 1 وb = 0، وابدأ من h_0 = 0، وأدخل نبضة واحدة يتبعها صمت: x = [1, 0, 0, 0].

Worked exampleمثال محلول

A scalar RNN with one input pulseRNN عددية مع نبضة إدخال واحدة

  1. t = 1t = 1

    h_1 = tanh(0.5 × 0 + 1 × 1) = tanh(1) ≈ 0.762. The pulse enters the state.
    h_1 = tanh(0.5 × 0 + 1 × 1) = tanh(1) ≈ 0.762. تدخل النبضة إلى الحالة.
  2. t = 2t = 2

    h_2 = tanh(0.5 × 0.762 + 0) = tanh(0.381) ≈ 0.363. No new input, so the state is only the old state, halved and squashed.
    h_2 = tanh(0.5 × 0.762 + 0) = tanh(0.381) ≈ 0.363. لا يوجد إدخال جديد، لذلك الحالة هي الحالة القديمة فقط، بعد تنصيفها وضغطها.
  3. t = 3t = 3

    h_3 = tanh(0.5 × 0.363) = tanh(0.182) ≈ 0.180. One more step gives h_4 ≈ 0.090.
    h_3 = tanh(0.5 × 0.363) = tanh(0.182) ≈ 0.180. وخطوة أخرى تعطي h_4 ≈ 0.090.
  4. Resultالنتيجة

    The trace of the input roughly halves every step: 0.762, 0.363, 0.180, 0.090. After a dozen words it is effectively gone.
    أثر الإدخال ينخفض إلى النصف تقريبًا في كل خطوة: 0.762, 0.363, 0.180, 0.090. وبعد دزينة من الكلمات يكون قد اختفى فعليًا.
With w_hh = 0.5 the single input at t = 1 leaves a trace that roughly halves at every step.مع w_hh = 0.5 يترك الإدخال الوحيد عند t = 1 أثرًا ينخفض إلى النصف تقريبًا في كل خطوة.

Step through the same network below, and try the other recurrent weights. With w_hh = 1 the trace decays more slowly (0.762, 0.642, 0.566, 0.513); with w_hh = 2 the state saturates near 0.95 and holds itself there with no input at all, while the flat tanh makes every local factor small.

تنقّل خطوة بخطوة في نفس الشبكة أدناه، وجرّب الأوزان التكرارية الأخرى. مع w_hh = 1 يتلاشى الأثر ببطء أكبر (0.762, 0.642, 0.566, 0.513)؛ ومع w_hh = 2 تتشبّع الحالة قرب 0.95 وتثبّت نفسها هناك دون أي إدخال، بينما يجعل الجزء المسطّح من tanh كل عامل محلي صغيرًا.

InteractiveتفاعليUnrolled scalar RNN, one step at a timeRNN عددية مفرودة، خطوة في كل مرة
w_xh = 1, b = 0, x = [1, 0, 0, 0], h_0 = 0
  1. t = 1h = ?x = 1
  2. t = 2h = ?x = 0
  3. t = 3h = ?x = 0
  4. t = 4h = ?x = 0
Pre-activation-a_tpress Nextاضغط التالي
Hidden state-h_t = tanh(a_t)
Local factor-w_hh(1 - h_t²)
Gradient to h_1-∂h_t / ∂h_1

Before the first step, h is 0قبل الخطوة الأولى، قيمة h تساوي 0

stepالخطوة 0 / 4

The same three numbers, w_hh, w_xh and b, are used at every step. Only the input pulse at t = 1 is non-zero, so everything the later cells hold is an echo of it. The last readout multiplies the local factors together: it is how strongly a change in h_1 still moves h_t, which is the quantity backpropagation through time has to carry backwards.الأعداد الثلاثة نفسها، w_hh وw_xh وb، تُستخدم في كل خطوة. النبضة المدخلة عند t = 1 هي وحدها غير الصفرية، لذا فكل ما تحمله الخلايا اللاحقة هو صدى لها. القراءة الأخيرة تضرب العوامل المحلية بعضها في بعض: فهي تقيس إلى أي حد ما زال تغيّرٌ في h_1 يحرّك h_t، وهي الكمية التي يجب أن يحملها الانتشار العكسي عبر الزمن (backpropagation through time) إلى الخلف.

What the slides imply but never say: vanishing gradientsما تلمّح إليه الشرائح ولا تقوله أبدًا: تلاشي التدرّج (vanishing gradients)

Fading in the forward pass has a twin in training. To learn that a word at step 1 matters for a prediction at step 4, backpropagation must send the error back through every intermediate state. Each step multiplies it by the local derivative

للتلاشي في التمرير الأمامي (forward pass) توأم في التدريب. لكي تتعلم الشبكة أن كلمة عند الخطوة 1 مهمة لتنبؤ عند الخطوة 4، يجب أن يرسل الانتشار العكسي (backpropagation) الخطأ عائدًا عبر كل حالة وسيطة. وكل خطوة تضربه في المشتقة المحلية

∂ht∂ht−1=whh (1−ht2)\frac{\partial h_t}{\partial h_{t-1}} = w_{hh}\,\bigl(1 - h_t^{2}\bigr)
Local factor of a scalar tanh RNNالعامل المحلي في RNN عددية بدالة tanh

In our example these factors are 0.434, 0.484 and 0.496, so ∂h_4 / ∂h_1 ≈ 0.434 × 0.484 × 0.496 ≈ 0.104. Because the derivative of tanh is at most 1, any |w_hh| < 1 makes every factor smaller than 1, and the product shrinks geometrically with distance. Large weights do not rescue it either: they push tanh into saturation, where 1 - h² is tiny. This is the Vanishing gradient problem. Jurafsky and Martin describe it as gradients being driven to zero by the repeated multiplications of backpropagation through time, and Pascanu, Mikolov and Bengio show that the opposite case, factors above 1, causes exploding gradients, which are usually handled by clipping.

في مثالنا هذه العوامل هي 0.434 و0.484 و0.496، لذلك ∂h_4 / ∂h_1 ≈ 0.434 × 0.484 × 0.496 ≈ 0.104. ولأن مشتقة tanh لا تتجاوز 1، فإن أي |w_hh| < 1 تجعل كل عامل أصغر من 1، فيتقلص حاصل الضرب هندسيًا مع المسافة. والأوزان الكبيرة لا تنقذ الموقف أيضًا: فهي تدفع tanh إلى التشبّع، حيث تكون 1 - h² صغيرة جدًا. هذه هي مشكلة vanishing gradient. يصفها Jurafsky وMartin بأنها تدرّجات تُدفع نحو الصفر بسبب الضرب المتكرر في الانتشار العكسي عبر الزمن (backpropagation through time)، ويبيّن Pascanu وMikolov وBengio أن الحالة المعاكسة، أي عوامل أكبر من 1، تسبب انفجار التدرّج (exploding gradients)، الذي يُعالج عادة بالقصّ (clipping).

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

A scalar RNN has w_hh = 0.5, w_xh = 1, b = 0, h_0 = 0 and inputs x = [1, 0, 0]. What is h_3?لدى RNN عددية w_hh = 0.5 وw_xh = 1 وb = 0 وh_0 = 0، والمدخلات x = [1, 0, 0]. ما قيمة h_3؟

Recall

Why does a simple RNN struggle to connect a word to a prediction twenty steps later?لماذا تجد الـ RNN البسيطة صعوبة في ربط كلمة بتنبؤ يأتي بعد عشرين خطوة؟

The gradient from the prediction back to that word is a product of twenty local factors w_hh(1 - h_t²). With tanh their size is usually below 1, so the product shrinks geometrically toward zero (vanishing gradients) and the weights receive almost no signal about the long-range dependency. The forward trace of the word fades the same way.
التدرّج من التنبؤ عائدًا إلى تلك الكلمة هو حاصل ضرب عشرين عاملًا محليًا w_hh(1 - h_t²). ومع tanh يكون حجمها عادة أقل من 1، فيتقلص حاصل الضرب هندسيًا نحو الصفر (تلاشي التدرّج) ولا تصل إلى الأوزان تقريبًا أي إشارة عن الاعتماد بعيد المدى. وأثر الكلمة في التمرير الأمامي يتلاشى بنفس الطريقة.

Recapالخلاصة

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

  • The lecture has four arcs: deep learning architectures (RNN, LSTM, encoder-decoder), neural language models, the transformer, and transformer language models.للمحاضرة أربعة محاور: معماريات التعلم العميق (RNN وLSTM وencoder-decoder)، ونماذج اللغة العصبية، والمحوّل (transformer)، ونماذج اللغة المبنية على المحوّل.
  • One to one: fixed input, fixed output, no sequence (image classification). One to many: one input, a sequence out (image captioning).One to one: إدخال ثابت وإخراج ثابت، بلا تسلسل (تصنيف الصور). One to many: إدخال واحد يخرج منه تسلسل (وصف الصور، image captioning).
  • Many to one: read the whole sequence, classify from the final hidden state (sentiment, spam detection).Many to one: اقرأ التسلسل كاملًا، ثم صنّف من الحالة المخفية الأخيرة (تحليل المشاعر، كشف الرسائل المزعجة).
  • Many to many delayed: read everything, then emit an output of a different length and order (machine translation, the encoder-decoder case).Many to many المؤجَّل: اقرأ كل شيء، ثم أخرج تسلسلًا بطول وترتيب مختلفين (الترجمة الآلية، وهي حالة encoder-decoder).
  • Many to many synchronized: one label per token, same length, same order (POS tagging, NER).Many to many المتزامن: تسمية واحدة لكل token، بنفس الطول ونفس الترتيب (وسم أقسام الكلام POS tagging، والتعرف على الكيانات المسماة NER).
  • Simple RNN: h_t = tanh(W_hh h_{t-1} + W_xh x_t + b), o_t = W_hy h_t, usually followed by softmax.الـ RNN البسيطة: h_t = tanh(W_hh h_{t-1} + W_xh x_t + b)، وo_t = W_hy h_t، ويتبعها عادة softmax.
  • The same W_hh, W_xh, b and W_hy are reused at every time step, so the parameter count does not depend on sequence length.تُستخدم نفس W_hh وW_xh وb وW_hy في كل خطوة زمنية، لذلك لا يعتمد عدد المعاملات على طول التسلسل.
  • With w_hh = 0.5 and one input pulse, h runs 0.762, 0.363, 0.180, 0.090: the input's influence fades, and the gradient back to h_1 falls to about 0.104 after three steps. This is the vanishing gradient problem that motivates the LSTM.مع w_hh = 0.5 ونبضة إدخال واحدة، تتوالى قيم h هكذا: 0.762، 0.363، 0.180، 0.090. يتلاشى أثر الإدخال، ويهبط التدرّج الراجع إلى h_1 إلى نحو 0.104 بعد ثلاث خطوات. هذه هي مشكلة تلاشي التدرّج (vanishing gradient) التي تدفع إلى الـ LSTM.

Sourcesالمصادر

Part 02: LSTM gates, RNN variants and encoder-decoder RNNsبوابات LSTM ومتغيرات RNN وشبكات Encoder-decoder

How the LSTM's forget, input and output gates control a cell state, what GRUs, bidirectional and stacked RNNs add, and how an encoder compresses a source sentence into a context that a decoder unrolls into a target sentence.كيف تتحكم بوابات النسيان والإدخال والإخراج في LSTM بحالة الخلية، وما تضيفه GRU وشبكات RNN ثنائية الاتجاه والمكدسة، وكيف يضغط المشفر (encoder) الجملة المصدر في سياق يفرده المفكك (decoder) إلى جملة الهدف.

4 concepts4 مفاهيم, ، slides 6-11الشرائح 6-11

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

Part 01 ended with the weakness of the simple RNN: the same hidden state has to carry long-range memory and make the current prediction, and the gradient that should teach it shrinks every time it is multiplied back through a step. This part is the fix and what it unlocked.

First, the LSTM: a separate memory line with three gates that decide what to erase, what to write and what to show. Second, three variants the slides name in one line each: the GRU, bidirectional RNNs and stacked RNNs. Third, the encoder-decoder idea, which turns a sentence in one language into a sentence in another. Fourth, the concrete RNN version of it from the textbook figure on slide 11, and the single-vector bottleneck that motivates attention in part 05. For the exam, the six LSTM equations and the role of each gate are the core: expect to write them and reason about extreme gate values.

انتهى الجزء 01 بنقطة ضعف RNN البسيطة: الحالة المخفية نفسها مطلوب منها أن تحمل الذاكرة بعيدة المدى وأن تصنع التنبؤ الحالي في الوقت ذاته، والتدرج الذي يفترض أن يعلّمها ذلك يصغر في كل مرة يُضرب فيها راجعًا عبر خطوة. هذا الجزء هو الحل، وما أتاحه هذا الحل.

أولًا، LSTM: خط ذاكرة منفصل له ثلاث بوابات تقرر ماذا تمحو، وماذا تكتب، وماذا تُظهر. ثانيًا، ثلاثة أشكال مشتقة تذكرها الشرائح في سطر واحد لكل منها: GRU وشبكات RNN ثنائية الاتجاه وشبكات RNN المكدسة. ثالثًا، فكرة encoder-decoder التي تحوّل جملة في لغة إلى جملة في لغة أخرى. رابعًا، نسختها العملية المبنية على RNN من شكل الكتاب في الشريحة 11، وعنق الزجاجة الناتج عن المتجه الواحد الذي يمهّد للانتباه (attention) في الجزء 05. للامتحان، معادلات LSTM الست ودور كل بوابة هي الأساس: توقع أن تكتبها وأن تستدل على ما يحدث عند القيم القصوى للبوابات.

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

  1. Write the six LSTM equations from slide 7 from memory and say what each gate decides.تكتب معادلات LSTM الست من الشريحة 7 من الذاكرة، وتشرح ما تقرره كل بوابة.
  2. Compute one LSTM step by hand and predict what happens when the forget gate is near 0 or near 1.تحسب خطوة LSTM واحدة يدويًا، وتتوقع ما يحدث عندما تكون بوابة النسيان (forget gate) قريبة من 0 أو من 1.
  3. Explain why the additive cell update lets information and gradients survive many time steps.تشرح لماذا يسمح التحديث الجمعي (additive) لحالة الخلية بأن تبقى المعلومات والتدرجات (gradients) عبر خطوات زمنية كثيرة.
  4. Contrast the GRU, bidirectional RNNs and stacked RNNs, and say which of them can generate text left to right.تقارن بين GRU وشبكات RNN ثنائية الاتجاه (bidirectional) وشبكات RNN المكدسة (stacked)، وتحدد أيها يستطيع توليد النص من اليسار إلى اليمين.
  5. Describe the RNN encoder-decoder: what the context is, how <s> and </s> are used, and why one vector is a bottleneck.تصف نموذج RNN encoder-decoder: ما هو السياق (context)، وكيف يُستخدم <s> و</s>، ولماذا يمثل المتجه الواحد عنق زجاجة (bottleneck).

Read this sentence word by word: “The keys that I left on the kitchen table yesterday aregone.” To choose are rather than is, a model must remember that the subject, keys, was plural, and hold that fact across eight intervening words while ignoring table, which is singular. A simple RNN rewrites its whole Hidden state at every step, so the fact “plural subject” has to survive eight full rewrites. In practice it fades, and during training the signal that should teach it to survive fades too: this is the Vanishing gradient problem.

اقرأ هذه الجملة كلمة كلمة: “The keys that I left on the kitchen table yesterday are gone.” (المفاتيح التي تركتها على طاولة المطبخ أمس اختفت). لكي يختار النموذج are بدلًا من is، يجب أن يتذكر أن الفاعل keys جمع، وأن يحتفظ بهذه المعلومة عبر ثماني كلمات فاصلة متجاهلًا كلمة table وهي مفردة. شبكة RNN البسيطة تعيد كتابة hidden state (الحالة المخفية) بالكامل في كل خطوة، لذلك يجب أن تنجو معلومة “الفاعل جمع” من ثماني عمليات إعادة كتابة كاملة. عمليًا تتلاشى هذه المعلومة، وأثناء التدريب تتلاشى أيضًا الإشارة التي يفترض أن تعلّمها البقاء: هذه هي مشكلة vanishing gradient (تلاشي التدرج).

The Long short-term memory (LSTM) changes the design rather than the training. It adds a second vector that runs beside the hidden state, the Cell state C(t), and it only lets three small learned switches touch it. One switch decides what to erase, one decides what to write, and one decides how much of the memory to reveal. When nothing needs to change, the switches can leave the memory almost untouched for many steps. The diagram on slide 6 is Christopher Olah’s drawing: the horizontal line across the top of each block is the cell state, the yellow boxes are learned layers, and the pink circles are elementwise operations.

تغيّر LSTM التصميم نفسه لا طريقة التدريب. فهي تضيف متجهًا ثانيًا يسير بجانب الحالة المخفية، وهو cell state (حالة الخلية) C(t)، ولا تسمح بلمسه إلا لثلاثة مفاتيح صغيرة متعلَّمة. مفتاح يقرر ماذا يُمحى، ومفتاح يقرر ماذا يُكتب، ومفتاح يقرر كم يُكشف من الذاكرة. عندما لا يلزم تغيير شيء، تستطيع المفاتيح أن تترك الذاكرة شبه سليمة لخطوات كثيرة. المخطط في الشريحة 6 من رسم Christopher Olah: الخط الأفقي أعلى كل كتلة هو حالة الخلية، والمربعات الصفراء طبقات متعلَّمة، والدوائر الوردية عمليات تُجرى عنصرًا بعنصر.

The cell state runs straight through the unit and is touched only by one multiplication (the forget gate) and one addition (the gated candidate). The output branch reads it through tanh and the output gate to produce h(t).تمر حالة الخلية مباشرة عبر الوحدة، ولا يلمسها إلا عملية ضرب واحدة (بوابة النسيان) وعملية جمع واحدة (المرشح بعد مروره ببوابته). فرع الإخراج يقرؤها عبر tanh وبوابة الإخراج لينتج h(t).

Every gate is the same recipeكل البوابات تتبع الوصفة نفسها

All three gates on slide 7 share one form. Take the previous hidden state and the current input, glue them into one longer vector [h(t-1), x(t)] (this bracket is concatenation, not a list of two things fed separately), multiply by the gate’s own weight matrix, add its bias, and squash with the sigmoid σ. The sigmoid output lies between 0 and 1. That is all the arrow in “(0 → 1)” on the slide means: the range of the gate value, not a transition from 0 to 1 over time.

البوابات الثلاث في الشريحة 7 لها الشكل نفسه. خذ الحالة المخفية السابقة والمدخل الحالي، وألصقهما في متجه واحد أطول [h(t-1), x(t)] (هذا القوس يعني الضمّ concatenation، وليس قائمة من شيئين يُمرَّر كل منهما وحده)، ثم اضربه في مصفوفة الأوزان الخاصة بالبوابة، وأضف الانحياز (bias)، ثم اضغطه بدالة sigmoid σ. ناتج sigmoid يقع بين 0 و1. وهذا كل ما يعنيه السهم في “(0 → 1)” على الشريحة: إنه مدى قيمة البوابة، وليس انتقالًا من 0 إلى 1 مع مرور الزمن.

ft=σ(Wf[ht−1,xt]+bf)f_t = \sigma\left(W_f[h_{t-1}, x_t] + b_f\right)
Forget gate: what to throw away from the cell stateبوابة النسيان: ما الذي يُحذف من حالة الخلية
it=σ(Wi[ht−1,xt]+bi)i_t = \sigma\left(W_i[h_{t-1}, x_t] + b_i\right)
Input gate: how much new information to let inبوابة الإدخال: كم يُسمح بدخول معلومات جديدة
ot=σ(Wo[ht−1,xt]+bo)o_t = \sigma\left(W_o[h_{t-1}, x_t] + b_o\right)
Output gate: how much of the cell to exposeبوابة الإخراج: كم يُكشف من الخلية

A fourth layer has the same shape but uses tanh instead of σ. It proposes the new content, the candidate C̃(t), with values between -1 and 1 so it can push memory up or down:

طبقة رابعة لها الشكل نفسه لكنها تستخدم tanh بدلًا من σ. هي تقترح المحتوى الجديد، أي المرشح C̃(t)، بقيم بين -1 و1 حتى تستطيع رفع الذاكرة أو خفضها:

C~t=tanh⁡(WC[ht−1,xt]+bC)\tilde{C}_t = \tanh\left(W_C[h_{t-1}, x_t] + b_C\right)
Candidate: what new information could be storedالمرشح: ما المعلومات الجديدة التي يمكن تخزينها

Then the two update lines, which are the heart of the LSTM:

ثم يأتي سطرا التحديث، وهما قلب LSTM:

Ct=ft⊙Ct−1+it⊙C~tC_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t
New cell state: keep part of the old, add part of the newحالة الخلية الجديدة: احتفظ بجزء من القديم وأضف جزءًا من الجديد
ht=ot⊙tanh⁡(Ct)h_t = o_t \odot \tanh(C_t)
New hidden state: a gated, squashed view of the cellالحالة المخفية الجديدة: رؤية مضغوطة ومبوَّبة للخلية

The slide writes the products with a dot, f(t) · C(t-1). Here the dot means the elementwise (Hadamard) product, written ⊙ above: component k of the result is component k of f(t) times component k of C(t-1). It is not a dot product, which would collapse two vectors into one number. Because each component has its own gate value, the LSTM can keep dimension 3 (say, “subject is plural”) while erasing dimension 7 in the same step.

تكتب الشريحة حواصل الضرب بنقطة، f(t) · C(t-1). النقطة هنا تعني الضرب عنصرًا بعنصر (elementwise أو Hadamard product)، المكتوب ⊙ في المعادلات أعلاه: المكوّن k من الناتج يساوي المكوّن k من f(t) مضروبًا في المكوّن k من C(t-1). إنه ليس الضرب النقطي (dot product) الذي يختزل متجهين في رقم واحد. ولأن لكل مكوّن قيمة بوابة خاصة به، تستطيع LSTM أن تحتفظ بالبُعد 3 (مثلًا “الفاعل جمع”) وتمحو البُعد 7 في الخطوة نفسها.

What each gate does at its extremesماذا تفعل كل بوابة عند قيمها القصوى

  • Forget gate near 1: the old memory passes through almost unchanged. Near 0: it is wiped. A language model might drop the subject’s number once the verb has been produced.forget gate (بوابة النسيان) قريبة من 1: تمر الذاكرة القديمة شبه دون تغيير. قريبة من 0: تُمسح. قد يتخلص نموذج لغة من معلومة عدد الفاعل بعد أن يكون قد أنتج الفعل.
  • Input gate near 0: nothing new is written, whatever the candidate says. Near 1: the full candidate is added.input gate (بوابة الإدخال) قريبة من 0: لا يُكتب شيء جديد مهما كان المرشح. قريبة من 1: يُضاف المرشح كاملًا.
  • Output gate near 0: the memory is kept privately and h(t) is close to 0, so this step’s prediction ignores it. Near 1: the whole squashed memory tanh(C(t)) is shown.output gate (بوابة الإخراج) قريبة من 0: تُحفظ الذاكرة سرًّا وتكون h(t) قريبة من 0، فيتجاهلها تنبؤ هذه الخطوة. قريبة من 1: تظهر الذاكرة المضغوطة كاملة tanh(C(t)).

Note the separation: the output gate changes only h(t), never C(t). The LSTM can hide a fact for ten words and still have it intact when it becomes useful.

لاحظ هذا الفصل: بوابة الإخراج تغيّر h(t) فقط، ولا تغيّر C(t) أبدًا. تستطيع LSTM أن تخفي معلومة لعشر كلمات وتبقى سليمة لديها عندما تصبح مفيدة.

Worked exampleمثال محلول

One LSTM step with scalar valuesخطوة LSTM واحدة بقيم عددية مفردة

  1. The settingالمعطيات

    Use one-dimensional vectors so every product is ordinary multiplication. Old memory C(t-1) = 2. Suppose the gate layers produced f = 0.9, i = 0.5, o = 0.6 and the candidate is C̃ = 0.8.
    نستخدم متجهات أحادية البعد حتى يكون كل ضرب ضربًا عاديًا. الذاكرة القديمة C(t-1) = 2. لنفترض أن طبقات البوابات أنتجت f = 0.9 وi = 0.5 وo = 0.6، وأن المرشح C̃ = 0.8.
  2. Keep part of the old memoryاحتفظ بجزء من الذاكرة القديمة

    f · C(t-1) = 0.9 × 2 = 1.8.
    f · C(t-1) = 0.9 × 2 = 1.8.
  3. Write part of the candidateاكتب جزءًا من المرشح

    i · C̃ = 0.5 × 0.8 = 0.4.
    i · C̃ = 0.5 × 0.8 = 0.4.
  4. Add themاجمعهما

    C(t) = 1.8 + 0.4 = 2.2.
    C(t) = 1.8 + 0.4 = 2.2.
  5. Expose a gated viewاكشف نسخة مرّت عبر البوابة

    tanh(2.2) ≈ 0.976, so h(t) = 0.6 × 0.976 ≈ 0.585.
    tanh(2.2) ≈ 0.976، إذن h(t) = 0.6 × 0.976 ≈ 0.585.
  6. Now set the forget gate to 0الآن اجعل بوابة النسيان 0

    C(t) = 0 × 2 + 0.4 = 0.4. Everything stored before is gone, and only the new write remains. Then h(t) = 0.6 × tanh(0.4) ≈ 0.6 × 0.380 ≈ 0.228.
    C(t) = 0 × 2 + 0.4 = 0.4. كل ما خُزّن سابقًا اختفى، ولم يبقَ إلا ما كُتب للتو. ثم h(t) = 0.6 × tanh(0.4) ≈ 0.6 × 0.380 ≈ 0.228.
  7. Resultالنتيجة

    With f = 0.9 the cell grows to 2.2 and h(t) ≈ 0.585. With f = 0 the past is erased and C(t) = 0.4. With f = 1 and i = 0, C(t) = C(t-1) = 2 exactly: a perfect copy.
    مع f = 0.9 تكبر الخلية إلى 2.2 وh(t) ≈ 0.585. مع f = 0 يُمحى الماضي وC(t) = 0.4. مع f = 1 وi = 0 تكون C(t) = C(t-1) = 2 تمامًا: نسخة مطابقة.
SimulatorمحاكيLSTM gate lab: one scalar cell, one time stepمختبر بوابات LSTM: خلية عددية واحدة، وخطوة زمنية واحدة
0.90
0.50
0.60
2.00
0.80
f · C(t-1)1.800what survives from the pastما يبقى من الماضي
i · C̃(t)0.400what is written nowما يُكتب الآن
C(t)2.200sum of the twoمجموع الاثنين
h(t)0.585o · tanh(C(t)) = o · 0.976

Real gate values come out of a sigmoid, so they approach 0 and 1 but never reach them exactly. The presets use the limits to make the behavior obvious. Try holding f at 1 and i at 0, then move the output gate: h(t) changes, C(t) does not.

قيم البوابات الحقيقية تخرج من sigmoid، لذلك تقترب من 0 و1 لكنها لا تصل إليهما تمامًا. الإعدادات الجاهزة تستخدم الحدود لتجعل السلوك واضحًا. جرّب تثبيت f عند 1 وi عند 0، ثم حرّك بوابة الإخراج: تتغير h(t) ولا تتغير C(t).

Why the additive update helpsلماذا يساعد التحديث الجمعي

In a simple RNN, h(t) = g(U h(t-1) + W x(t)): the old state goes through a weight matrix and a squashing function at every step, and backpropagation multiplies by those factors again and again on the way back, so the gradient tends to shrink toward zero. In the LSTM, the direct path from C(t-1) to C(t) is just “multiply by f(t), then add something.” There is no weight matrix and no squashing on that path, so its local derivative is simply f(t). When the forget gate stays near 1, information flows forward and gradient flows backward along the cell line with little loss. This is often called a gradient highway. It eases the vanishing gradient problem; it does not abolish it, because a forget gate below 1 still shrinks the signal over very long spans.

في RNN البسيطة، h(t) = g(U h(t-1) + W x(t)): تمر الحالة القديمة عبر مصفوفة أوزان ودالة ضاغطة في كل خطوة، والانتشار العكسي (backpropagation) يضرب في هذه العوامل مرة بعد مرة في طريق العودة، فيميل التدرج إلى الانكماش نحو الصفر. أما في LSTM فالمسار المباشر من C(t-1) إلى C(t) هو ببساطة “اضرب في f(t) ثم أضف شيئًا”. لا توجد على هذا المسار مصفوفة أوزان ولا دالة ضاغطة، لذلك مشتقته المحلية هي f(t) فقط. عندما تبقى بوابة النسيان قريبة من 1، تتدفق المعلومات إلى الأمام والتدرج إلى الخلف على خط الخلية بخسارة قليلة. يُسمى هذا غالبًا الطريق السريع للتدرج (gradient highway). إنه يخفف مشكلة تلاشي التدرج ولا يلغيها، لأن بوابة نسيان أقل من 1 ما زالت تقلّص الإشارة عبر مسافات طويلة جدًا.

Recall

Why does information survive many steps on the LSTM cell line but fade in a simple RNN’s hidden state?لماذا تبقى المعلومات خطوات كثيرة على خط الخلية في LSTM بينما تتلاشى في الحالة المخفية لـ RNN البسيطة؟

A simple RNN pushes its state through a weight matrix and a squashing function at every step, so the gradient is multiplied by those factors again and again and shrinks. On the cell line the old state is only scaled elementwise by f(t) and then added to, so the local derivative is f(t); with the forget gate near 1 both the memory and its gradient pass through almost unchanged.
RNN البسيطة تمرر حالتها عبر مصفوفة أوزان ودالة ضاغطة في كل خطوة، فيُضرب التدرج في هذه العوامل مرة بعد مرة وينكمش. على خط الخلية لا تُضرب الحالة القديمة إلا عنصرًا بعنصر في f(t) ثم يُضاف إليها، لذلك المشتقة المحلية هي f(t)؛ ومع بوابة نسيان قريبة من 1 تمر الذاكرة وتدرجها شبه دون تغيير.

Recall

Without looking, write the six LSTM equations and name the activation used in each.دون النظر، اكتب معادلات LSTM الست وسمِّ دالة التنشيط المستخدمة في كل منها.

f(t) = σ(W_f[h(t-1), x(t)] + b_f), i(t) = σ(W_i[h(t-1), x(t)] + b_i), o(t) = σ(W_o[h(t-1), x(t)] + b_o), C̃(t) = tanh(W_C[h(t-1), x(t)] + b_C), C(t) = f(t) ⊙ C(t-1) + i(t) ⊙ C̃(t), h(t) = o(t) ⊙ tanh(C(t)). Three gates use σ; the candidate and the output squashing use tanh.
f(t) = σ(W_f[h(t-1), x(t)] + b_f)، i(t) = σ(W_i[h(t-1), x(t)] + b_i)، o(t) = σ(W_o[h(t-1), x(t)] + b_o)، C̃(t) = tanh(W_C[h(t-1), x(t)] + b_C)، C(t) = f(t) ⊙ C(t-1) + i(t) ⊙ C̃(t)، h(t) = o(t) ⊙ tanh(C(t)). البوابات الثلاث تستخدم σ، والمرشح والضغط عند الإخراج يستخدمان tanh.

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

An LSTM step has forget gate near 1 and input gate near 0. What happens to the cell state?في خطوة LSTM، بوابة النسيان قريبة من 1 وبوابة الإدخال قريبة من 0. ماذا يحدث لحالة الخلية؟

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

On slide 7, what does the dot in f(t) · C(t-1) denote?في الشريحة 7، علامَ تدل النقطة في f(t) · C(t-1)؟

Slide 8 names three ideas with one bullet each. They answer three different questions: can the gating be simpler, can a position see words to its right, and can the network be deeper?

تذكر الشريحة 8 ثلاث أفكار بنقطة واحدة لكل منها. وهي تجيب عن ثلاثة أسئلة مختلفة: هل يمكن أن تكون البوابات أبسط؟ هل يمكن لموضع ما أن يرى الكلمات التي على يمينه؟ وهل يمكن أن تكون الشبكة أعمق؟

The GRU: two gates, no separate cellGRU: بوابتان ولا خلية منفصلة

The Gated recurrent unit (GRU) merges the LSTM’s cell state and hidden state into one vector h(t) and uses two gates instead of three. The reset gate r(t) decides how much of the past to use when proposing new content. The update gate z(t) decides how to blend old and new, playing the role of the LSTM’s forget and input gates together:

تدمج GRU حالة الخلية والحالة المخفية في LSTM في متجه واحد h(t)، وتستخدم بوابتين بدلًا من ثلاث. بوابة إعادة الضبط (reset gate) r(t) تقرر كم يُستخدم من الماضي عند اقتراح المحتوى الجديد. بوابة التحديث (update gate) z(t) تقرر كيف يُمزج القديم بالجديد، فتؤدي دور بوابتي النسيان والإدخال في LSTM معًا:

zt=σ(Wz[ht−1,xt]),rt=σ(Wr[ht−1,xt])z_t = \sigma(W_z[h_{t-1}, x_t]), \quad r_t = \sigma(W_r[h_{t-1}, x_t])
Update and reset gatesبوابتا التحديث وإعادة الضبط
h~t=tanh⁡(W[rt⊙ht−1,xt])\tilde{h}_t = \tanh\left(W[r_t \odot h_{t-1}, x_t]\right)
Candidate hidden state, built from a reset view of the pastالحالة المخفية المرشحة، مبنية من رؤية معاد ضبطها للماضي
ht=(1−zt)⊙ht−1+zt⊙h~th_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t
New state: an interpolation between old and newالحالة الجديدة: استيفاء بين القديم والجديد

With z(t) near 0 the old state is copied, the same carry-forward behavior as an LSTM with its forget gate open and input gate closed. With fewer parameters per unit, a GRU is a little cheaper and often performs about as well; neither one wins on every task.

عندما تكون z(t) قريبة من 0 تُنسخ الحالة القديمة، وهو سلوك الحمل إلى الأمام نفسه في LSTM عندما تكون بوابة النسيان مفتوحة وبوابة الإدخال مغلقة. ولأن عدد معاملات كل وحدة أقل، فإن GRU أرخص قليلًا وكثيرًا ما تؤدي بمستوى مقارب؛ ولا تتفوق أي منهما في كل المهام.

Bidirectional RNNs: read both waysشبكات RNN ثنائية الاتجاه: القراءة في الاتجاهين

Consider tagging bank in “I sat by the bank of the river.” A left-to-right RNN at bank has seen only “I sat by the,” but the deciding word, river, comes later. A Bidirectional RNN runs two independent RNNs over the sentence: a forward one from the first word to the last and a backward one from the last word to the first. At each position it concatenates the two states, so the representation of bank carries information from both sides. The top figure on slide 8 shows exactly that: RNN 1 forward, RNN 2 backward, outputs concatenated.

فكّر في وسم كلمة bank في “I sat by the bank of the river.” (جلست عند ضفة النهر). شبكة RNN تقرأ من اليسار إلى اليمين لم ترَ عند bank إلا “I sat by the”، لكن الكلمة الحاسمة، river، تأتي لاحقًا. شبكة bidirectional RNN (ثنائية الاتجاه) تشغّل شبكتي RNN مستقلتين على الجملة: أمامية من الكلمة الأولى إلى الأخيرة، وخلفية من الكلمة الأخيرة إلى الأولى. وعند كل موضع تضم الحالتين، فيحمل تمثيل bank معلومات من الجانبين. الشكل العلوي في الشريحة 8 يبيّن ذلك تمامًا: RNN 1 أمامية، وRNN 2 خلفية، والمخرجات مضمومة.

A forward RNN reads left to right, a backward RNN reads right to left, and each position’s output is the concatenation of the two states.شبكة RNN أمامية تقرأ من اليسار إلى اليمين، وشبكة RNN خلفية تقرأ من اليمين إلى اليسار، ومخرج كل موضع هو ضمّ الحالتين.

The price is that the backward RNN cannot start until the last word exists. That is fine for tagging, classification and encoding a sentence that is already complete. It is impossible for generating text left to right, where the future words are exactly what you are trying to produce.

الثمن أن الشبكة الخلفية لا تستطيع البدء حتى توجد الكلمة الأخيرة. هذا مقبول في الوسم والتصنيف وترميز جملة مكتملة أصلًا. لكنه مستحيل عند توليد النص من اليسار إلى اليمين، حيث الكلمات المستقبلية هي بالضبط ما تحاول إنتاجه.

Stacked RNNs: depth over timeشبكات RNN المكدسة: عمق فوق الزمن

A Stacked (multi-layer) RNN places RNN layers on top of each other. Layer 1 reads the word embeddings x(1) … x(n) and produces a sequence of hidden states; that entire output sequence becomes the input sequence of layer 2, and so on. The final output is taken from the top layer. As in deep feedforward networks, lower layers tend to capture local, surface patterns and higher layers more abstract ones. The bottom figure on slide 8 shows three stacked layers. More layers cost more computation and are harder to train, so the right depth is found by experiment.

شبكة stacked RNN (المكدسة) تضع طبقات RNN بعضها فوق بعض. الطبقة 1 تقرأ تضمينات الكلمات (word embeddings) x(1) … x(n) وتنتج تسلسلًا من الحالات المخفية؛ ويصبح تسلسل المخرجات هذا بأكمله تسلسل مدخلات الطبقة 2، وهكذا. ويؤخذ المخرج النهائي من الطبقة العليا. وكما في الشبكات الأمامية العميقة، تميل الطبقات السفلى إلى التقاط أنماط محلية سطحية، والطبقات العليا إلى أنماط أكثر تجريدًا. الشكل السفلي في الشريحة 8 يبيّن ثلاث طبقات مكدسة. الطبقات الإضافية تكلّف حسابًا أكثر وتجعل التدريب أصعب، لذلك يُحدَّد العمق المناسب بالتجربة.

VariantالشكلWhat changesما الذي يتغيرWhat it buysما الذي يكسبهCan generate left to right?هل يستطيع التوليد من اليسار إلى اليمين؟
GRUGRUTwo gates (update z, reset r), no separate cell stateبوابتان (التحديث z وإعادة الضبط r)، ولا توجد حالة خلية منفصلةCheaper drop-in replacement for an LSTM unitبديل أرخص يحل مباشرة محل وحدة LSTMYesنعم
Bidirectionalثنائية الاتجاهA forward RNN and a backward RNN; outputs concatenated per positionشبكة RNN أمامية وشبكة RNN خلفية، وتُضم مخرجاتهما عند كل موضعEvery position sees left and right contextكل موضع يرى السياق من اليسار ومن اليمينNo, the backward pass needs future wordsلا، فالمرور الخلفي يحتاج الكلمات المستقبلية
StackedمكدسةLayer k’s output sequence is layer k + 1’s input sequenceتسلسل مخرجات الطبقة k هو تسلسل مدخلات الطبقة k + 1Higher layers build more abstract representationsالطبقات العليا تبني تمثيلات أكثر تجريدًاYes, if every layer is left to rightنعم، إذا كانت كل طبقة من اليسار إلى اليمين
The three variants on slide 8الأشكال الثلاثة في الشريحة 8

These ideas combine. LSTM or GRU units can be placed into any of these layouts, which is why slide 11 can speak of a stacked bidirectional LSTM, a “stacked BLSTM.”

هذه الأفكار تتجمع معًا. يمكن وضع وحدات LSTM أو GRU في أي من هذه التركيبات، ولهذا تتحدث الشريحة 11 عن LSTM مكدسة ثنائية الاتجاه، أي “stacked BLSTM”.

Recall

What is the difference between a bidirectional RNN and a two-layer stacked RNN? Both have two RNNs.ما الفرق بين RNN ثنائية الاتجاه وRNN مكدسة من طبقتين؟ كلتاهما فيها شبكتا RNN.

In a bidirectional RNN the two RNNs sit side by side and read the same input in opposite directions; their states are concatenated per position. In a stacked RNN the two layers read in the same direction, one on top of the other, and the second layer’s input is the first layer’s output sequence.
في RNN ثنائية الاتجاه تقف الشبكتان جنبًا إلى جنب وتقرآن المدخل نفسه في اتجاهين متعاكسين، وتُضم حالتاهما عند كل موضع. في RNN المكدسة تقرأ الطبقتان في الاتجاه نفسه، إحداهما فوق الأخرى، ومدخل الطبقة الثانية هو تسلسل مخرجات الطبقة الأولى.

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

Why can a bidirectional RNN not serve as a left-to-right generator?لماذا لا تصلح RNN ثنائية الاتجاه لتكون مولّدًا من اليسار إلى اليمين؟

Slide 9 translates “Zaid went to his house” into Arabic: ذهب زيد إلى بيته (dhahab zayd ’iilaa baytihi), glossed word by word as “went Zaid to his-house.” The verb moves to the front, because Arabic often uses verb, subject, object order. The two words his house become one word, بيته, so five English words come out as four Arabic words.

تترجم الشريحة 9 الجملة “Zaid went to his house” إلى العربية: ذهب زيد إلى بيته (dhahab zayd ’iilaa baytihi)، ومقابلها كلمة بكلمة بالإنجليزية “went Zaid to his-house.” ينتقل الفعل إلى البداية، لأن العربية تستخدم كثيرًا ترتيب الفعل ثم الفاعل ثم المفعول. والكلمتان his house تصبحان كلمة واحدة، بيته، فتخرج خمس كلمات إنجليزية على شكل أربع كلمات عربية.

Try to do this with a tagger that emits one output per input as it reads. At the first English word, Zaid, the tagger would have to emit the first Arabic word, went, which it has not seen yet. The output at each position depends on the whole input, not on the word at the same position, and the output length need not match the input length. That is what slide 9 means by “the output sequence is a complex function of the entire input sequence.”

حاول أن تفعل ذلك بأداة وسم (tagger) تُخرج مخرجًا واحدًا لكل مدخل أثناء القراءة. عند أول كلمة إنجليزية، Zaid، سيتعين على الأداة إخراج أول كلمة عربية، “ذهب” (went)، وهي لم ترها بعد. المخرج عند كل موضع يعتمد على المدخل كله، لا على الكلمة في الموضع نفسه، ولا يلزم أن يساوي طول المخرج طول المدخل. هذا ما تقصده الشريحة 9 بقولها “تسلسل المخرجات دالة معقدة لتسلسل المدخلات بأكمله”.

Two networks with one job eachشبكتان، لكل منهما مهمة واحدة

The Encoder-decoder (seq2seq) architecture, also called sequence to sequence, splits the work. An encoder reads the entire input x(1) … x(n) and builds a contextualized representation of it, which the slide calls the context. A decoder receives that context and generates the output y(1) … y(m) one token at a time, with m free to differ from n. Slide 10’s figure is that idea and nothing more: encoder, context, decoder. It does not yet say what the encoder and decoder are made of; LSTMs, CNNs and transformers can all fill those boxes.

معمارية encoder-decoder، وتسمى أيضًا sequence to sequence، تقسم العمل. المُرمِّز (encoder) يقرأ المدخل كاملًا x(1) … x(n) ويبني له تمثيلًا سياقيًا، تسميه الشريحة context (السياق). والمُفكِّك (decoder) يستقبل هذا السياق ويولّد المخرج y(1) … y(m) رمزًا (token) بعد رمز، مع حرية أن يختلف m عن n. شكل الشريحة 10 هو هذه الفكرة لا أكثر: مُرمِّز، سياق، مُفكِّك. ولا يحدد بعد مما يُصنع المُرمِّز والمُفكِّك؛ فـLSTM وCNN وtransformers كلها يمكن أن تملأ هذين الصندوقين.

Recall

Give two reasons, using slide 9’s example, why a one-output-per-input tagger cannot translate English to Arabic.باستخدام مثال الشريحة 9، اذكر سببين يجعلان أداة وسم تُخرج مخرجًا واحدًا لكل مدخل عاجزة عن الترجمة من الإنجليزية إلى العربية.

Word order changes (the verb went must come first but appears second in English), and lengths need not match (his house becomes the single word بيته). Both mean each output depends on the whole input, not the word at the same position.
ترتيب الكلمات يتغير (الفعل “ذهب” went يجب أن يأتي أولًا لكنه يظهر ثانيًا في الإنجليزية)، والأطوال لا يلزم أن تتطابق (his house تصبح كلمة واحدة بيته). وكلاهما يعني أن كل مخرج يعتمد على المدخل كله، لا على الكلمة في الموضع نفسه.

Slide 11 is figure 14.17 from the textbook. It translates the English “the green witch arrived” into the Spanish “llegó la bruja verde,” glossed “arrived the witch green”: the verb moves to the front and the adjective moves after the noun, the same kind of reordering as the Arabic example.

الشريحة 11 هي الشكل 14.17 من الكتاب. يترجم الجملة الإنجليزية “the green witch arrived” (وصلت الساحرة الخضراء) إلى الإسبانية “llegó la bruja verde,” ومقابلها كلمة بكلمة “arrived the witch green”: ينتقل الفعل إلى البداية وتنتقل الصفة إلى ما بعد الاسم، وهو النوع نفسه من إعادة الترتيب في المثال العربي.

The encoder reads the four source words and its outputs are ignored. Its final hidden state h(n) becomes the context c. The decoder starts from c at <s>, emits llegó, feeds it back, and continues until it produces </s>.يقرأ المُرمِّز كلمات المصدر الأربع، وتُتجاهل مخرجاته. حالته المخفية الأخيرة h(n) تصبح السياق c. يبدأ المُفكِّك من c عند <s>، ويُخرج llegó، ثم يعيدها مدخلًا، ويستمر حتى يُنتج </s>.

Walking through the figureالمرور على الشكل خطوة خطوة

  1. Encode. The source words the, green, witch, arrived are embedded and fed through the RNN one by one. The figure notes that the output of the source is ignored: no softmax prediction is used while reading the English.الترميز. كلمات المصدر the, green, witch, arrived تُحوَّل إلى تضمينات وتُمرَّر عبر RNN واحدة تلو الأخرى. يوضح الشكل أن مخرجات المصدر تُتجاهل: لا يُستخدم أي تنبؤ softmax أثناء قراءة الإنجليزية.
  2. Hand over the context. The final hidden state, h(n) (the green box), becomes the context c, and it initializes the decoder: h(0) of the decoder = c. In the textbook’s fuller version, c is also fed to every decoder step so its influence does not fade.تسليم السياق. الحالة المخفية الأخيرة h(n) (الصندوق الأخضر) تصبح السياق c، وتُستخدم لتهيئة المُفكِّك: h(0) of the decoder = c. وفي النسخة الأكمل في الكتاب، تُمرَّر c أيضًا إلى كل خطوة من خطوات المُفكِّك حتى لا يتلاشى أثرها.
  3. Start decoding. The separator <s> is the first decoder input. The decoder computes a softmax over the Spanish vocabulary and produces llegó.بدء فك الترميز. الفاصل <s> هو أول مدخل للمُفكِّك. يحسب المُفكِّك softmax على مفردات الإسبانية ويُنتج llegó.
  4. Feed back. At inference time, each generated word is the next input, which is Autoregressive generation: llegó produces la, la produces bruja, and so on. During training, the correct previous word is fed instead, which is Teacher forcing.التغذية الراجعة. وقت الاستدلال (inference) تكون كل كلمة مولَّدة هي المدخل التالي، وهذا هو autoregressive generation (التوليد الانحداري الذاتي): llegó تُنتج la، وla تُنتج bruja، وهكذا. أما أثناء التدريب فتُمرَّر الكلمة السابقة الصحيحة بدلًا من ذلك، وهذا هو teacher forcing.
  5. Stop. Decoding ends when the model emits </s>.التوقف. ينتهي فك الترميز عندما يُخرج النموذج </s>.
p(y∣x)=∏t=1mp(yt∣y1,…,yt−1,x)p(y \mid x) = \prod_{t=1}^{m} p(y_t \mid y_1, \ldots, y_{t-1}, x)
The decoder is a language model conditioned on the sourceالمفكِّك (decoder) نموذج لغة مشروط بالمصدر

Each target word is predicted from the target words already produced and the source, which reaches the decoder only through c. In other words, the decoder is the RNN language model of part 03 with its starting state replaced by a summary of the source sentence.

كل كلمة هدف يُتنبأ بها من كلمات الهدف التي أُنتجت سابقًا ومن المصدر، والمصدر لا يصل إلى المُفكِّك إلا عبر c. بعبارة أخرى، المُفكِّك هو نموذج اللغة المبني على RNN من الجزء 03، مع استبدال حالته الابتدائية بملخص لجملة المصدر.

What real encoders look likeكيف تبدو المُرمِّزات الحقيقية

The slide’s two bullets describe practice, not the drawing. Stacked architectures are the norm, and the states of the top layer are taken as the encoder’s output. A widely used encoder is a stacked bidirectional LSTM, and at each position the forward and backward top-layer states are concatenated. This is the same combination of the three slide-8 ideas: LSTM units, bidirectional reading (allowed here, because the source sentence is complete before encoding starts), and stacking. The decoder, which generates, stays left to right.

النقطتان في الشريحة تصفان الممارسة الفعلية، لا الرسم. المعماريات المكدسة هي القاعدة، وتؤخذ حالات الطبقة العليا على أنها مخرج المُرمِّز. ومن المُرمِّزات الواسعة الاستخدام LSTM مكدسة ثنائية الاتجاه، وعند كل موضع تُضم الحالتان الأمامية والخلفية للطبقة العليا. هذا هو الجمع نفسه بين أفكار الشريحة 8 الثلاث: وحدات LSTM، والقراءة ثنائية الاتجاه (مسموحة هنا لأن جملة المصدر مكتملة قبل بدء الترميز)، والتكديس. أما المُفكِّك، الذي يولّد، فيبقى من اليسار إلى اليمين.

The bottleneckعنق الزجاجة

Everything the decoder knows about the source sentence must pass through one fixed-size vector, c = h(n). For four words that is manageable. For a forty-word sentence, the same vector must hold every name, number and clause, and the first words have been through the most updates before the encoder finishes, so they tend to be represented least well. Making the vector larger helps only a little. This is the bottleneck problem, and its solution, letting the decoder look at all encoder states with weights that change at every output step, is attention, which part 05 introduces.

كل ما يعرفه المُفكِّك عن جملة المصدر يجب أن يمر عبر متجه واحد ثابت الحجم، c = h(n). مع أربع كلمات يمكن التعامل مع ذلك. أما مع جملة من أربعين كلمة، فيجب أن يحمل المتجه نفسه كل اسم ورقم وعبارة، والكلمات الأولى تكون قد مرت بأكبر عدد من التحديثات قبل أن ينتهي المُرمِّز، لذلك تميل إلى أن تكون الأسوأ تمثيلًا. وتكبير المتجه لا يساعد إلا قليلًا. هذه هي مشكلة عنق الزجاجة (bottleneck)، وحلها هو السماح للمُفكِّك بالنظر إلى كل حالات المُرمِّز بأوزان تتغير عند كل خطوة إخراج، وهذا هو الانتباه (attention) الذي يقدمه الجزء 05.

Recall

In slide 11, which encoder outputs does the decoder use, and what happens at <s> and </s>?في الشريحة 11، أي مخرجات المُرمِّز يستخدمها المُفكِّك، وماذا يحدث عند <s> و</s>؟

It uses none of the per-word encoder outputs; they are ignored. It uses only the final hidden state h(n) as the context that initializes the decoder. <s> is the first decoder input that starts generation, and producing </s> ends it.
لا يستخدم أيًّا من مخرجات المُرمِّز لكل كلمة؛ فهي تُتجاهل. يستخدم فقط الحالة المخفية الأخيرة h(n) بوصفها السياق الذي يهيّئ المُفكِّك. <s> هو أول مدخل للمُفكِّك ويبدأ التوليد، وإنتاج </s> يُنهيه.

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

In the basic RNN encoder-decoder on slide 11, what does the decoder receive from the source?في نموذج RNN encoder-decoder الأساسي في الشريحة 11، ماذا يستقبل المُفكِّك من المصدر؟

Recapالخلاصة

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

  • Every LSTM gate is σ(W[h(t-1), x(t)] + b): a learned layer on the concatenated previous hidden state and current input, squashed into the range 0 to 1.كل بوابة في LSTM هي σ(W[h(t-1), x(t)] + b): طبقة متعلَّمة تعمل على ضمّ (concatenation) الحالة المخفية السابقة مع المدخل الحالي، ثم تُضغط قيمتها إلى المدى من 0 إلى 1.
  • C(t) = f(t) · C(t-1) + i(t) · C̃(t) and h(t) = o(t) · tanh(C(t)), where · is the elementwise (Hadamard) product.C(t) = f(t) · C(t-1) + i(t) · C̃(t) و h(t) = o(t) · tanh(C(t))، حيث · هو الضرب عنصرًا بعنصر (elementwise أو Hadamard).
  • Forget gate near 1 keeps the old memory, near 0 erases it. Input gate controls how much of the candidate is written. Output gate controls how much of the memory is exposed as h(t).بوابة النسيان القريبة من 1 تحتفظ بالذاكرة القديمة، والقريبة من 0 تمحوها. بوابة الإدخال تتحكم في مقدار ما يُكتب من المرشح (candidate). بوابة الإخراج تتحكم في مقدار ما يُكشف من الذاكرة على شكل h(t).
  • The cell update is additive, so the direct path from C(t-1) to C(t) is scaled only by f(t). That path is the gradient highway that eases vanishing gradients.تحديث الخلية جمعي، لذلك فإن المسار المباشر من C(t-1) إلى C(t) لا يُضرب إلا في f(t). هذا المسار هو الطريق السريع للتدرج (gradient highway) الذي يخفف مشكلة تلاشي التدرج.
  • GRU (beyond the slides): two gates, update z and reset r, and no separate cell state.GRU (خارج الشرائح): بوابتان، بوابة التحديث z وبوابة إعادة الضبط r، ولا توجد حالة خلية منفصلة.
  • Bidirectional RNN: forward and backward RNNs, outputs concatenated at each position. It needs the whole sentence, so it cannot generate left to right.RNN ثنائية الاتجاه: شبكة أمامية وشبكة خلفية، وتُضم مخرجاتهما عند كل موضع. تحتاج الجملة كاملة، لذلك لا تستطيع التوليد من اليسار إلى اليمين.
  • Stacked RNN: the output sequence of layer k is the input sequence of layer k + 1.RNN المكدسة: تسلسل مخرجات الطبقة k هو تسلسل مدخلات الطبقة k + 1.
  • Encoder-decoder: the encoder reads the source, its final hidden state h(n) is the context c, the decoder starts from c, begins at <s> and stops at </s>. One fixed vector for the whole source is the bottleneck that attention removes.Encoder-decoder: المُرمِّز (encoder) يقرأ المصدر، وحالته المخفية الأخيرة h(n) هي السياق c، والمُفكِّك (decoder) ينطلق من c، ويبدأ عند <s> ويتوقف عند </s>. المتجه الثابت الواحد لكامل المصدر هو عنق الزجاجة الذي يزيله الانتباه (attention).

Sourcesالمصادر

Part 03: RNN language models and autoregressive generationنماذج اللغة RNN والتوليد الانحداري الذاتي

Why neural LMs beat counted n-grams on sparsity, how an RNN LM computes a next-word distribution at every step, how it generates text by sampling, and what multi-layer RNN LMs look like.لماذا تتفوق نماذج اللغة العصبية على الـ n-grams المعدودة في مشكلة التفرق، وكيف يحسب نموذج RNN توزيع الكلمة التالية في كل خطوة، وكيف يولد النص بالعينات، وكيف تبدو نماذج RNN متعددة الطبقات.

6 concepts6 مفاهيم, ، slides 12-18الشرائح 12-18

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

In lecture 03 you built language models by counting. A bigram model looked at one previous word, a trigram model at two, and every word was an index into a table. This part replaces the table with a network. An RNN language model reads a sentence one word at a time, keeps a running summary of everything it has read, and turns that summary into a probability for every word in the vocabulary.

The concepts build on each other. First, why moving from counts to vectors fixes sparsity. Second, the four equations of the RNN LM with every matrix shape. Third, how the same model writes text by feeding its own words back in. Fourth, the second notation on slide 16, which reuses the letter U for a different matrix. Fifth, what recurrence buys and what it costs, and last, how layers stack. For the exam, expect to write the forward equations with shapes, list advantages and problems, and explain why the model size does not grow with input length.

في المحاضرة 03 بنيت نماذج لغة بالعدّ. نموذج bigram كان ينظر إلى كلمة سابقة واحدة، ونموذج trigram إلى كلمتين، وكانت كل كلمة مجرد رقم فهرس في جدول. هذا الجزء يستبدل الجدول بشبكة عصبية. نموذج اللغة RNN يقرأ الجملة كلمة كلمة، ويحتفظ بملخص متجدد لكل ما قرأه حتى الآن، ثم يحوّل هذا الملخص إلى احتمال لكل كلمة في المفردات (vocabulary).

المفاهيم مبنية بعضها على بعض. أولًا، لماذا ينحل مشكل التناثر (sparsity) عند الانتقال من العدّ إلى المتجهات. ثانيًا، المعادلات الأربع لنموذج RNN LM مع أبعاد كل مصفوفة. ثالثًا، كيف يكتب النموذج نفسه نصًا بأن يعيد إدخال كلماته هو. رابعًا، الترميز الثاني في الشريحة 16، الذي يستخدم الحرف U لمصفوفة مختلفة. خامسًا، ماذا يكسب التكرار (recurrence) وماذا يكلّف، وأخيرًا كيف تُكدَّس الطبقات. في الامتحان توقّع أن يُطلب منك كتابة معادلات التمرير الأمامي مع الأبعاد، وذكر المزايا والمشكلات، وشرح لماذا لا يزداد حجم النموذج بزيادة طول المدخل.

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

  1. Contrast a count-based n-gram LM with a neural LM: the Markov assumption and counting versus learned word vectors that share statistical strength.تقارن بين نموذج لغة n-gram قائم على العدّ ونموذج لغة عصبي: افتراض ماركوف والعدّ في مقابل متجهات كلمات متعلَّمة تتشارك القوة الإحصائية بين الكلمات المتشابهة.
  2. Write the four RNN LM equations (embedding, recurrence, softmax output, cross-entropy loss) and give the shape of every vector and matrix.تكتب معادلات RNN LM الأربع (التضمين embedding، والتكرار recurrence، ومخرج softmax، وخسارة cross-entropy) وتعطي أبعاد كل متجه وكل مصفوفة.
  3. Count the parameters of an RNN LM and explain why the count does not grow with input length.تحسب عدد معاملات RNN LM وتشرح لماذا لا يزداد هذا العدد بزيادة طول المدخل.
  4. Describe autoregressive generation from <s> to </s>, and contrast greedy decoding, sampling and temperature.تصف التوليد الانحداري الذاتي (autoregressive generation) من <s> إلى </s>، وتقارن بين فك الترميز الجشع (greedy decoding) والاختيار العشوائي (sampling) ودرجة الحرارة (temperature).
  5. Translate between the SLP3 notation (E, W, U, V) and the CS224n notation (E, W_e, W_h, U) used on the slides.تترجم بين ترميز SLP3 (أي E وW وU وV) وترميز CS224n (أي E وW_e وW_h وU) المستخدمَين في الشرائح.
  6. List two advantages and two remaining problems of RNN LMs, and sketch a two-layer RNN LM.تذكر ميزتين ومشكلتين باقيتين في نماذج RNN LM، وترسم مخططًا لنموذج RNN LM من طبقتين.

Suppose your training corpus contains "the cat sat on the mat" many times but never "the dog sat on the rug". A trigram model asked for P(rug∣on the)P(\text{rug} \mid \text{on the}) after a dog sentence has nothing to say about dogs or rugs specifically. To the count table, cat and dog are just two unrelated column numbers. Every fact it knows about cats is useless for dogs.

افترض أن مدوّنة التدريب (corpus) تحتوي الجملة "the cat sat on the mat" مرات كثيرة، لكنها لا تحتوي أبدًا "the dog sat on the rug". نموذج trigram يُسأل عن P(rug∣on the)P(\text{rug} \mid \text{on the}) بعد جملة عن الكلب لا يملك ما يقوله عن الكلاب أو السجاد تحديدًا. بالنسبة لجدول العدّ، cat وdog مجرد رقمي عمودين لا علاقة بينهما. وكل معلومة يعرفها عن القطط عديمة الفائدة للكلاب.

Count-based models: Markov assumption plus countingالنماذج القائمة على العدّ: افتراض ماركوف مع العدّ

A Count-based (n-gram) language model makes two moves. It assumes the next word depends only on the previous n-1 words (an n-th order Markov assumption in the slide's phrasing), and it estimates each conditional probability as a ratio of counts, then smooths so that unseen events do not get probability zero. Both moves are where the trouble lives. The window throws away anything older than n-1 words, and the counts treat each word as an atomic symbol, so the model cannot generalize from one word to a similar one. Making n larger to see more context makes the problem worse, because the number of possible n-grams grows as |V|^n: with |V| = 10,000, there are already 10^12 possible trigrams, almost all unseen.

يقوم count-based LM بخطوتين. يفترض أن الكلمة التالية تعتمد فقط على آخر n-1 كلمة (افتراض ماركوف من الرتبة n بحسب صياغة الشريحة)، ويقدّر كل احتمال شرطي بوصفه نسبة بين عددين، ثم يطبّق التنعيم (smoothing) كي لا تحصل الأحداث غير المرئية على احتمال صفر. والمشكلة تكمن في هاتين الخطوتين بالذات. النافذة تتخلص من كل ما هو أقدم من n-1 كلمة، والعدّ يعامل كل كلمة رمزًا ذريًا مستقلًا، فلا يستطيع النموذج التعميم من كلمة إلى كلمة مشابهة لها. وتكبير n لرؤية سياق أوسع يزيد المشكلة سوءًا، لأن عدد الـ n-grams الممكنة ينمو بمقدار |V|^n: فمع |V| = 10,000 يوجد بالفعل 10^12 trigram ممكن، وكلها تقريبًا لم تُرَ قط.

Neural models: words as vectors, parameters learnedالنماذج العصبية: الكلمات متجهات، والمعاملات متعلَّمة

A Neural language model attacks sparsity by representing each word as a dense vector. Training pushes words that appear in similar contexts toward similar vectors, so cat and dog end up close, and mat and rug end up close. Now the evidence from "the cat sat on the mat" also raises the probability of "the dog sat on the rug", because the network's computation is smooth in its inputs: nearby input vectors give nearby outputs. Bengio and colleagues (2003) put it this way: a new sentence can receive high probability if its words are close in representation space to words in sentences already seen. The second bullet of slide 13 matters too: nothing is counted. The vectors and all other weights are parameters learned by gradient descent as part of training.

يعالج neural language model مشكلة التناثر بتمثيل كل كلمة متجهًا كثيفًا (dense vector). التدريب يدفع الكلمات التي تظهر في سياقات متشابهة نحو متجهات متشابهة، فينتهي الأمر بـ cat وdog متقاربتين، وبـ mat وrug متقاربتين. والآن فإن الدليل الآتي من "the cat sat on the mat" يرفع أيضًا احتمال "the dog sat on the rug"، لأن حسابات الشبكة سلسة بالنسبة لمدخلاتها: المتجهات المتقاربة في المدخل تعطي مخرجات متقاربة. وقد عبّر عن ذلك Bengio وزملاؤه (2003) هكذا: الجملة الجديدة يمكن أن تنال احتمالًا عاليًا إذا كانت كلماتها قريبة في فضاء التمثيل من كلمات في جمل سبق رؤيتها. والنقطة الثانية في الشريحة 13 مهمة كذلك: لا شيء يُعدّ هنا. المتجهات وكل الأوزان الأخرى معاملات تُتعلَّم بالانحدار التدرجي (gradient descent) جزءًا من التدريب.

Left: a count table treats each word as a separate cell, so most cells stay empty. Right: in a learned vector space, cat and dog share a neighborhood, so evidence flows between them.يسارًا: جدول العدّ يعامل كل كلمة خلية منفصلة، فتبقى معظم الخلايا فارغة. يمينًا: في فضاء متجهات متعلَّم تتشارك cat وdog الجوار نفسه، فينتقل الدليل بينهما.
Count-based (statistical)القائمة على العدّ (الإحصائية)Neuralالعصبية
What is assumedما الذي يُفترضAn (n-1)-th order Markov assumption: only the last n-1 words matterافتراض ماركوف من الرتبة (n-1): آخر n-1 كلمة فقط هي المهمةNo fixed window; an RNN summarizes the whole prefix in a hidden stateلا نافذة ثابتة؛ تلخّص RNN البادئة كاملة في حالة مخفية
How probabilities are obtainedكيف نحصل على الاحتمالاتCounting n-grams in a corpus, then smoothingبعدّ الـ n-grams في مدوّنة ثم التنعيم (smoothing)Computed by a network whose parameters are learned by trainingتحسبها شبكة تُتعلَّم معاملاتها بالتدريب
How a word is representedكيف تُمثَّل الكلمةAn atomic symbol, a row or column index in a count tableرمز ذري، أي رقم صف أو عمود في جدول العدّA dense learned vector, so similar words sit close togetherمتجه كثيف متعلَّم، فتقع الكلمات المتشابهة قريبة بعضها من بعض
What happens to an unseen n-gramماذا يحدث لـ n-gram لم يُرَZero count; it only gets mass that smoothing steals from seen eventsعدده صفر؛ لا ينال إلا الكتلة الاحتمالية التي يقتطعها التنعيم من الأحداث المرئيةGets a sensible probability if its words resemble words seen in trainingينال احتمالًا معقولًا إذا كانت كلماته تشبه كلمات رُئيت في التدريب
Size as context growsالحجم مع اتساع السياقPossible n-grams grow as |V|^nعدد الـ n-grams الممكنة ينمو بمقدار |V|^nFixed: the same matrices are reused at every stepثابت: المصفوفات نفسها يُعاد استخدامها في كل خطوة
Slide 13 expanded: count-based versus neural language modelsتوسعة الشريحة 13: نماذج اللغة القائمة على العدّ في مقابل النماذج العصبية

Lecture 04 learned embeddings with a separate method such as word2vec. Here the embedding matrix is part of the language model itself and is learned together with everything else. And because an RNN carries a hidden state forward, it also drops the fixed window: it conditions on the whole prefix, not just the last n-1 words.

في المحاضرة 04 تعلّمنا التضمينات (embeddings) بطريقة منفصلة مثل word2vec. أما هنا فمصفوفة التضمين جزء من نموذج اللغة نفسه وتُتعلَّم مع كل شيء آخر. ولأن RNN تحمل حالة مخفية إلى الأمام، فإنها تتخلص أيضًا من النافذة الثابتة: تشترط على البادئة كاملة (prefix)، لا على آخر n-1 كلمة فقط.

Recall

Name the two things a count-based LM does, and the two things slide 13 says a neural LM does instead.اذكر الأمرين اللذين يقوم بهما نموذج اللغة القائم على العدّ، والأمرين اللذين تقول الشريحة 13 إن النموذج العصبي يقوم بهما بدلًا منهما.

Count-based: it makes an n-th order Markov assumption and estimates n-gram probabilities by counting and smoothing. Neural: it solves data sparsity by representing words as vectors, and its parameters are learned as part of training.

القائم على العدّ: يفترض افتراض ماركوف من الرتبة n، ويقدّر احتمالات n-gram بالعدّ والتنعيم. العصبي: يحل مشكلة تناثر البيانات بتمثيل الكلمات متجهات، ومعاملاته تُتعلَّم جزءًا من التدريب.

Take the prefix "So long and" from the slide's figure. The model must output a probability for every vocabulary word as the next word, and it should put a lot of mass on "thanks". Here is the exact path a word takes from input to that distribution, in the notation of Jurafsky and Martin (SLP3), which slide 14 uses.

خذ البادئة "So long and" من رسم الشريحة. يجب أن يُخرج النموذج احتمالًا لكل كلمة في المفردات بوصفها الكلمة التالية، وينبغي أن يضع كتلة احتمالية كبيرة على "thanks". وهذا هو المسار الدقيق الذي تسلكه الكلمة من المدخل إلى ذلك التوزيع، بترميز Jurafsky وMartin (SLP3) الذي تستخدمه الشريحة 14.

The four equationsالمعادلات الأربع

et=E xtht=g(U ht−1+W et)y^t=softmax⁡(V ht)LCE(y^t,yt)=−log⁡y^t[wt+1]\begin{aligned} e_t &= E\,x_t \\ h_t &= g\left(U\,h_{t-1} + W\,e_t\right) \\ \hat{y}_t &= \operatorname{softmax}\left(V\,h_t\right) \\ L_{CE}(\hat{y}_t, y_t) &= -\log \hat{y}_t\left[w_{t+1}\right] \end{aligned}
RNN LM forward pass and per-step loss (SLP3 notation, slide 14 with the hat restored)المرور الأمامي في نموذج لغة RNN والخسارة لكل خطوة (ترميز SLP3، الشريحة 14 مع إعادة علامة القبعة)
  1. Embed. The current word arrives as a one-hot vector xtx_t. Multiplying by the Embedding matrix E just selects one column of EE, the word's vector ete_t.التضمين. تصل الكلمة الحالية متجهًا أحادي الساخن (one-hot) xtx_t. والضرب في embedding matrix يختار ببساطة عمودًا واحدًا من EE، وهو متجه الكلمة ete_t.
  2. Recur. The new Hidden state mixes the old state, weighted by UU, with the new word, weighted by WW, and passes the sum through a nonlinearity gg such as tanh. This is the Recurrent neural network (RNN) cell of part 1; nothing new except that the input is a word embedding.التكرار. الـ hidden state الجديدة تمزج الحالة القديمة، موزونة بـ UU، مع الكلمة الجديدة، موزونة بـ WW، ثم تمرّر المجموع عبر دالة غير خطية gg مثل tanh. هذه هي خلية RNN من الجزء 1؛ لا جديد فيها سوى أن المدخل تضمين كلمة.
  3. Score and normalize. VhtV h_t gives one score per vocabulary word, and Softmax turns the scores into a probability distribution y^t\hat{y}_t. Its entry y^t[k]\hat{y}_t[k] is P(wt+1=k∣w1,…,wt)P(w_{t+1} = k \mid w_1, \ldots, w_t).حساب الدرجات والتطبيع. يعطي VhtV h_t درجة (score) واحدة لكل كلمة في المفردات، وتحوّل softmax هذه الدرجات إلى توزيع احتمالي y^t\hat{y}_t. والمدخل y^t[k]\hat{y}_t[k] منه يساوي P(wt+1=k∣w1,…,wt)P(w_{t+1} = k \mid w_1, \ldots, w_t).
  4. Pay for the mistake. In training, the Cross-entropy loss at step t looks up the probability the model gave to the true next word and takes minus its log. Part 4 derives why the full cross-entropy collapses to this one term.دفع ثمن الخطأ. أثناء التدريب، تبحث cross-entropy loss عند الخطوة t عن الاحتمال الذي أعطاه النموذج للكلمة التالية الصحيحة وتأخذ سالب لوغاريتمه. الجزء 4 يشتق لماذا تنهار الـ cross-entropy الكاملة إلى هذا الحد الوحيد.
Unrolled RNN LM on <s> the cat sat: each input is embedded, U carries the state right, and V plus softmax predict the next word above.نموذج RNN LM مفرود زمنيًا على <s> the cat sat: كل مدخل يُضمَّن، وU تحمل الحالة إلى اليمين، وV مع softmax تتنبأ بالكلمة التالية في الأعلى.

Every shape, and where the parameters liveكل الأبعاد، وأين تقع المعاملات

Shapes are the fastest way to check you remember the equations correctly, because a wrong matrix cannot be multiplied. Write |V| for the vocabulary size, d_e for the embedding size and d_h for the hidden size. SLP3 sets d_e = d_h = d for simplicity, which makes WW and UU both d × d.

الأبعاد أسرع طريقة للتأكد من أنك تتذكر المعادلات بشكل صحيح، لأن المصفوفة الخاطئة لا يمكن ضربها. اكتب |V| لحجم المفردات، وd_e لحجم التضمين، وd_h لحجم الحالة المخفية. يضع SLP3 القيمة d_e = d_h = d للتبسيط، مما يجعل WW وUU كلتيهما بحجم d × d.

Shapes in the RNN LM (column vectors)الأبعاد في RNN LM (متجهات عمودية)

x_t (one-hot input word)x_t (كلمة الإدخال بصيغة one-hot)
|V| × 1|V| × 1
E (embedding matrix)E (مصفوفة التضمين)
d_e × |V|d_e × |V|
e_t = E x_t
d_e × 1d_e × 1
W (input to hidden)W (من الإدخال إلى المخفية)
d_h × d_ed_h × d_e
U (hidden to hidden)U (من المخفية إلى المخفية)
d_h × d_hd_h × d_h
h_t (hidden state)h_t (الحالة المخفية)
d_h × 1d_h × 1
V (hidden to output)V (من المخفية إلى الإخراج)
|V| × d_h|V| × d_h
V h_t and ŷ_tV h_t وŷ_t
|V| × 1|V| × 1

Worked exampleمثال محلول

Parameter count for |V| = 10,000 and d_e = d_h = 512عدد المعاملات عندما |V| = 10,000 وd_e = d_h = 512

  1. Embedding matrix Eمصفوفة التضمين E

    512 × 10,000 = 5,120,000 weights.
    512 × 10,000 = 5,120,000 وزن.
  2. Input matrix W and recurrent matrix Uمصفوفة الإدخال W والمصفوفة التكرارية U

    Each is 512 × 512 = 262,144, so 524,288 together.
    كل منهما بحجم 512 × 512 = 262,144، فمجموعهما 524,288.
  3. Output matrix Vمصفوفة الإخراج V

    10,000 × 512 = 5,120,000 weights. This one matrix is as large as the whole embedding table.
    10,000 × 512 = 5,120,000 وزن. هذه المصفوفة وحدها بحجم جدول التضمين كله.
  4. Resultالنتيجة

    About 10.76 M weights in total (10,764,288, ignoring biases), and over 95% of them sit in E and V, the two matrices that touch the vocabulary. With Weight tying, SLP3 reuses E⊤E^\top in place of VV, which removes 5.12 M weights.
    نحو 10.76 M وزن إجمالًا (10,764,288، مع إهمال الانحيازات biases)، وأكثر من 95% منها يقع في E وV، المصفوفتين اللتين تتعاملان مع المفردات. ومع weight tying يعيد SLP3 استخدام E⊤E^\top مكان VV، مما يحذف 5.12 M وزن.

Worked exampleمثال محلول

One softmax step and its lossخطوة softmax واحدة وخسارتها

  1. Scoresالدرجات

    Shrink the vocabulary to three words, thanks, for and all, and suppose V h_t = [2.0, 1.0, 0.1] gives them scores 2.0, 1.0 and 0.1.
    صغّر المفردات إلى ثلاث كلمات: thanks وfor وall، وافترض أن V h_t = [2.0, 1.0, 0.1] يعطيها الدرجات 2.0 و1.0 و0.1.
  2. Exponentiate and normalizeالرفع الأسي ثم التطبيع

    e^2.0 = 7.389, e^1.0 = 2.718, e^0.1 = 1.105, sum 11.212. So ŷ_t = [0.659, 0.242, 0.099].
    e^2.0 = 7.389 وe^1.0 = 2.718 وe^0.1 = 1.105، والمجموع 11.212. إذن ŷ_t = [0.659, 0.242, 0.099].
  3. Lossالخسارة

    The true next word is thanks, so L_CE = -ln 0.659 = 0.417. Had the true word been all, the loss would be -ln 0.099 = 2.31: confident mistakes cost more.
    الكلمة التالية الصحيحة هي thanks، إذن L_CE = -ln 0.659 = 0.417. ولو كانت الكلمة الصحيحة all لكانت الخسارة -ln 0.099 = 2.31: الأخطاء الواثقة تكلّف أكثر.
  4. Resultالنتيجة

    Training lowers the loss by raising the true word's probability at every position.
    التدريب يخفّض الخسارة برفع احتمال الكلمة الصحيحة عند كل موضع.

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

With |V| = 10,000 and d_h = 512, what is the shape of the output matrix V in SLP3 notation?عندما |V| = 10,000 وd_h = 512، ما أبعاد مصفوفة الإخراج V بترميز SLP3؟

Recall

Write the four RNN LM equations from memory and say what ŷ_t[k] means.اكتب معادلات RNN LM الأربع من الذاكرة، ووضّح ماذا يعني ŷ_t[k].

e_t = E x_t; h_t = g(U h_{t-1} + W e_t); ŷ_t = softmax(V h_t); L_CE = -log ŷ_t[w_{t+1}]. The entry ŷ_t[k] is the probability that the next word is vocabulary item k given all words up to t.

e_t = E x_t؛ h_t = g(U h_{t-1} + W e_t)؛ ŷ_t = softmax(V h_t)؛ L_CE = -log ŷ_t[w_{t+1}]. والمدخل ŷ_t[k] هو احتمال أن تكون الكلمة التالية هي عنصر المفردات k بمعلومية كل الكلمات حتى t.

A trained RNN LM can write. Give it only the start marker <s>. It outputs a distribution over the first word; you pick "So". Now "So" becomes the next input, the model updates its hidden state and outputs a distribution for the second word; you pick "long", and so on. The model is reading its own writing.

نموذج RNN LM المدرَّب يستطيع الكتابة. أعطه علامة البداية <s> فقط. سيُخرج توزيعًا على الكلمة الأولى، فتختار "So". الآن تصبح "So" المدخل التالي، فيحدّث النموذج حالته المخفية ويُخرج توزيعًا للكلمة الثانية، فتختار "long"، وهكذا. النموذج يقرأ ما يكتبه بنفسه.

The procedureالإجراء

  1. Feed <s> as the first input and compute y^1\hat{y}_1.أدخل <s> مدخلًا أول واحسب y^1\hat{y}_1.
  2. Choose a word from that softmax distribution.اختر كلمة من توزيع softmax هذا.
  3. Look up the chosen word's embedding and use it as the input at the next step, carrying the hidden state forward.ابحث عن تضمين الكلمة المختارة واستخدمه مدخلًا في الخطوة التالية، مع حمل الحالة المخفية إلى الأمام.
  4. Repeat until the model produces </s> or a maximum length is reached.كرّر حتى يُنتج النموذج </s> أو يُبلَغ الحد الأقصى للطول.

This is Autoregressive generation: each output is conditioned on outputs the model itself chose earlier. SLP3 notes the name is used loosely, since a true autoregressive model in statistics is linear, while an LM is not. The procedure is exactly the Shannon-style sampling of lecture 03, with one change that matters: an n-gram sampler forgets everything older than n-1 words, while the RNN carries the whole prefix in hth_t.

هذا هو autoregressive generation: كل مخرج مشروط بمخرجات اختارها النموذج نفسه سابقًا. يلاحظ SLP3 أن الاسم مستخدم بتساهل، لأن النموذج الانحداري الذاتي الحقيقي في الإحصاء خطي، بينما نموذج اللغة ليس كذلك. والإجراء هو بالضبط الاختيار العشوائي على طريقة Shannon من المحاضرة 03، مع تغيير واحد مهم: مولّد n-gram ينسى كل ما هو أقدم من n-1 كلمة، بينما تحمل RNN البادئة كاملة في hth_t.

Generation: each sampled word (top) loops back as the next input (bottom), so the model conditions on its own earlier choices.التوليد: كل كلمة مختارة (في الأعلى) تعود في حلقة لتصبح المدخل التالي (في الأسفل)، فيشترط النموذج على اختياراته السابقة نفسها.

How to choose the word: greedy, sampling and temperatureكيف نختار الكلمة: الجشع، والاختيار العشوائي، ودرجة الحرارة

Step 2 hides a design choice. Greedy decoding always takes the most probable word. It is deterministic, so the same prefix always produces the same text, and SLP3 notes it tends to be generic and repetitive. Random sampling draws a word in proportion to its probability, which gives variety but sometimes picks a strange low-probability word. Temperature sampling sits between the two: divide the scores by τ\tau before the softmax.

الخطوة 2 تخفي قرار تصميم. فك الترميز الجشع (greedy decoding) يأخذ دائمًا الكلمة الأعلى احتمالًا. وهو حتمي، فالبادئة نفسها تنتج دائمًا النص نفسه، ويلاحظ SLP3 أنه يميل إلى نص عام ومكرر. أما الاختيار العشوائي (random sampling) فيسحب كلمة بنسبة احتمالها، وهذا يعطي تنوعًا لكنه يختار أحيانًا كلمة غريبة منخفضة الاحتمال. والاختيار بدرجة الحرارة (temperature sampling) يقع بين الاثنين: اقسم الدرجات على τ\tau قبل softmax.

y^t=softmax⁡ ⁣(Vhtτ)\hat{y}_t = \operatorname{softmax}\!\left(\frac{V h_t}{\tau}\right)
Temperature sampling: τ < 1 sharpens toward greedy, τ = 1 is the plain softmax, τ > 1 flattensالمعاينة بدرجة الحرارة: τ < 1 تحدّ التوزيع نحو الاختيار الجشع، وτ = 1 هي softmax العادية، وτ > 1 تسطّحه

Worked exampleمثال محلول

The same scores at two temperaturesالدرجات نفسها عند درجتي حرارة

  1. At τ = 1عند τ = 1

    Scores 2.0, 1.0, 0.1 give 0.659, 0.242, 0.099, as in the previous concept.
    الدرجات 2.0, 1.0, 0.1 تعطي 0.659, 0.242, 0.099، كما في المفهوم السابق.
  2. At τ = 0.5عند τ = 0.5

    Scores become 4.0, 2.0, 0.2. Exponentials 54.60, 7.39, 1.22, sum 63.21, so the probabilities are 0.864, 0.117, 0.019.
    تصبح الدرجات 4.0, 2.0, 0.2. الأسس 54.60, 7.39, 1.22، والمجموع 63.21، إذن الاحتمالات 0.864, 0.117, 0.019.
  3. Resultالنتيجة

    Halving the temperature moved the top word from 66% to 86%. As τ→0\tau \to 0, sampling becomes greedy decoding.
    تنصيف درجة الحرارة نقل الكلمة الأولى من 66% إلى 86%. وعندما τ→0\tau \to 0 يصبح الاختيار العشوائي فك ترميز جشعًا.

Try it below. The toy model starts at <s> with about 0.62 on "the". Run greedy twice and you get the same sentence. Switch to sampling and pick "dog" when it comes up: after "on the", rug becomes likely instead of mat, because the hidden state still remembers the subject from four steps back, something a trigram model could not do.

جرّبه بالأسفل. النموذج المصغّر يبدأ من <s> باحتمال نحو 0.62 على "the". شغّل الوضع الجشع مرتين فتحصل على الجملة نفسها. انتقل إلى الاختيار العشوائي واختر "dog" عندما تظهر: بعد "on the" تصبح rug مرجّحة بدلًا من mat، لأن الحالة المخفية لا تزال تتذكر الفاعل من أربع خطوات سابقة، وهذا ما لا يستطيعه نموذج trigram.

SimulatorمحاكيRNN LM generation stepper: greedy versus samplingمتتبع التوليد في نموذج لغة RNN: الجشع مقابل المعاينة
Next: draw from ŷالتالي: سحب عينة من ŷ
Sequence so far (each word becomes the next input)التسلسل حتى الآن (كل كلمة تصبح المدخل التالي)<s>
Step t0words
P(last word)none
log P(sequence)0.00nats
h_t remembersnonesubjectdecides mat or rug laterيحدد لاحقاً mat أم rug
ŷ for step 1 at τ = 1ŷ للخطوة 1 عند τ = 1
  • the0.62
  • a0.28
  • cat0.04
  • dog0.04
  • sat0.00
  • slept0.00
  • on0.00
  • mat0.00
  • rug0.00
  • </s>0.00

The scores behind ŷ are a fixed toy table standing in for V h_t. They depend on the whole prefix, not only the last word: after "on the", the subject chosen several steps earlier decides whether mat or rug is likely. Greedy always takes the tallest bar, so it produces the same sentence every time.الدرجات التي يقوم عليها ŷ جدول تجريبي ثابت يحل محل V h_t. وهي تعتمد على البادئة كلها، لا على الكلمة الأخيرة فقط: بعد «on the» يحدد الفاعل الذي اختير قبل عدة خطوات أيّ الكلمتين أرجح، mat أم rug. الفك الجشع يأخذ دائماً أطول عمود، لذا ينتج الجملة نفسها في كل مرة.

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

With greedy decoding, you generate twice from <s> using the same trained RNN LM. What do you get?باستخدام فك الترميز الجشع (greedy decoding)، تولّد مرتين بدءًا من <s> بنموذج RNN LM المدرَّب نفسه. ماذا تحصل؟

Recall

List the generation loop in four steps, including both stopping conditions.اذكر حلقة التوليد في أربع خطوات، مع شرطَي التوقف كليهما.

Feed <s>; choose a word from the softmax; feed that word's embedding as the next input; repeat until </s> is produced or the maximum length is reached.

أدخل <s>؛ اختر كلمة من softmax؛ أدخل تضمين تلك الكلمة مدخلًا تاليًا؛ كرّر حتى يُنتَج </s> أو يُبلَغ الحد الأقصى للطول.

Slide 16 shows the same model again, but its equations come from Stanford CS224n, not SLP3. Read it with slide 14 in mind and you hit a trap at once: the output distribution is softmax⁡(Uh(t)+b2)\operatorname{softmax}(U h^{(t)} + b_2), yet on slide 14 the matrix UU was the recurrent one. Same letter, different matrix.

الشريحة 16 تعرض النموذج نفسه مرة أخرى، لكن معادلاتها مأخوذة من Stanford CS224n لا من SLP3. اقرأها وفي ذهنك الشريحة 14 وستقع في فخ فورًا: توزيع الإخراج هو softmax⁡(Uh(t)+b2)\operatorname{softmax}(U h^{(t)} + b_2)، مع أن المصفوفة UU في الشريحة 14 كانت المصفوفة التكرارية. الحرف نفسه، والمصفوفة مختلفة.

h(t)=σ ⁣(Whh h(t−1)+We e(t)+b1),y^(t)=softmax⁡ ⁣(U h(t)+b2)∈R∣V∣h^{(t)} = \sigma\!\left(W_{hh}\,h^{(t-1)} + W_e\,e^{(t)} + b_1\right), \qquad \hat{y}^{(t)} = \operatorname{softmax}\!\left(U\,h^{(t)} + b_2\right) \in \mathbb{R}^{|V|}
Slide 16 in consistent CS224n form, with the time index fixedالشريحة 16 بصيغة CS224n متسقة، مع تصحيح فهرس الزمن
RoleالدورSlide 14 (SLP3)الشريحة 14 (SLP3)Slide 16 (CS224n)الشريحة 16 (CS224n)
Embedding lookupالبحث عن التضمينEEEE
Input embedding to hiddenمن تضمين الإدخال إلى المخفيةWWW_eW_e
Hidden to hidden (recurrent)من المخفية إلى المخفية (التكرارية)UUW_hh (or W_h)W_hh (or W_h)
Hidden to output scoresمن المخفية إلى درجات الإخراجVVUU
Biasesالانحيازات (biases)Omittedمحذوفةb_1, b_2b_1, b_2
Nonlinearityالدالة غير الخطيةg (often tanh)g (غالبًا tanh)σ (any nonlinearity)σ (أي دالة غير خطية)
Time indexفهرس الزمنsubscript: h_tرمز سفلي: h_tsuperscript: h^(t)رمز علوي: h^(t)
Translating between the two notations on the slidesالترجمة بين الترميزين المستخدمَين في الشرائح

Beyond the letters, slide 16 adds two real details. It includes bias vectors b_1 and b_2, which SLP3 drops to keep the equations short. And it states the output space explicitly, y^(t)∈R∣V∣\hat{y}^{(t)} \in \mathbb{R}^{|V|}, which is the shape check from the previous concept. Its figure also shows an initial hidden state h^(0), usually a vector of zeros, and the softmax histogram over the vocabulary at the last step, with mat and floor as likely continuations of "The cat slept quietly on the".

بعيدًا عن الحروف، تضيف الشريحة 16 تفصيلين حقيقيين. فهي تتضمن متجهي الانحياز b_1 وb_2، اللذين يحذفهما SLP3 لإبقاء المعادلات قصيرة. وتنص صراحة على فضاء الإخراج y^(t)∈R∣V∣\hat{y}^{(t)} \in \mathbb{R}^{|V|}، وهو فحص الأبعاد نفسه من المفهوم السابق. ويُظهر رسمها أيضًا حالة مخفية ابتدائية h^(0)، وهي عادة متجه من الأصفار، ومدرّج softmax على المفردات في الخطوة الأخيرة، حيث mat وfloor تكملتان مرجّحتان لـ "The cat slept quietly on the".

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

On slide 16 (CS224n notation), which matrix plays the role that V plays on slide 14?في الشريحة 16 (ترميز CS224n)، أي مصفوفة تؤدي الدور الذي تؤديه V في الشريحة 14؟

Recall

Translate h^(t) = σ(W_hh h^(t-1) + W_e e^(t) + b_1) into SLP3 letters.ترجم h^(t) = σ(W_hh h^(t-1) + W_e e^(t) + b_1) إلى حروف SLP3.

h_t = g(U h_{t-1} + W e_t), dropping the bias. W_hh becomes U, W_e becomes W, and the output matrix CS224n calls U becomes V.

h_t = g(U h_{t-1} + W e_t)، مع حذف الانحياز. W_hh تصبح U، وW_e تصبح W، ومصفوفة الإخراج التي يسميها CS224n باسم U تصبح V.

Feed the RNN LM a five-word sentence and then a five-hundred-word article. The second run takes a hundred times as many steps, but it uses exactly the same E, W, U and V. Nothing in the parameter count mentions the sentence length. That one fact explains most of slide 17.

أدخل إلى RNN LM جملة من خمس كلمات ثم مقالًا من خمسمئة كلمة. التشغيل الثاني يستغرق خطوات أكثر بمئة مرة، لكنه يستخدم بالضبط E وW وU وV نفسها. لا شيء في عدد المعاملات يتعلق بطول الجملة. وهذه الحقيقة الواحدة تفسّر معظم الشريحة 17.

Why the model size does not grow with input lengthلماذا لا يزداد حجم النموذج بزيادة طول المدخل

The parameter count from the forward-pass worked example, d_e|V| + d_h d_e + d_h^2 + |V| d_h, contains no term for the sequence length T. Length only changes how many times the cell is applied. Compare the two alternatives. A count-based model that wants more context needs a larger n, and its table can grow as |V|^n. A fixed-window neural LM, as in Bengio and colleagues, concatenates the window's embeddings, so its first weight matrix grows with the window size, and CS224n notes that each window position gets its own separate weights. The RNN applies one rule at every step instead, which is weight sharing across time.

عدد المعاملات من المثال المحلول في التمرير الأمامي، d_e|V| + d_h d_e + d_h^2 + |V| d_h، لا يحتوي أي حد لطول التسلسل T. الطول يغيّر فقط عدد مرات تطبيق الخلية. قارن بالبديلين. النموذج القائم على العدّ الذي يريد سياقًا أوسع يحتاج n أكبر، وجدوله قد ينمو بمقدار |V|^n. ونموذج اللغة العصبي ذو النافذة الثابتة، كما عند Bengio وزملائه، يضم تضمينات النافذة متتالية، فتكبر مصفوفة أوزانه الأولى مع حجم النافذة، ويلاحظ CS224n أن لكل موضع في النافذة أوزانه المنفصلة. أما RNN فتطبّق قاعدة واحدة في كل خطوة، وهذا هو تشارك الأوزان عبر الزمن (weight sharing across time).

AdvantageالميزةWhyالسببRemaining problemالمشكلة الباقيةWhyالسبب
Any length inputمدخل بأي طولThe same cell is applied once per word, so 5 or 500 words both workالخلية نفسها تُطبَّق مرة لكل كلمة، فتصلح 5 كلمات أو 500 كلمةRecurrent computation is slowالحساب التكراري بطيءh_t needs h_{t-1}, so the steps of one sequence cannot run in parallelh_t تحتاج h_{t-1}، فلا يمكن تشغيل خطوات التسلسل الواحد على التوازي
Model size does not growحجم النموذج لا يزدادE, W, U, V are the same matrices at every stepE وW وU وV هي المصفوفات نفسها في كل خطوةLong-range information is hard in practiceالمعلومات البعيدة صعبة عمليًاGradients shrink through many steps, so distant words are poorly usedالتدرّجات تتقلص عبر خطوات كثيرة، فلا يُستفاد جيدًا من الكلمات البعيدة
Long history in theoryتاريخ طويل نظريًاh_t can carry information from the very first wordيمكن لـ h_t أن تحمل معلومات من الكلمة الأولى نفسها
Shared weights across timeأوزان مشتركة عبر الزمنEvery position is processed by the same rule, so what is learned at one position transfersكل موضع يُعالَج بالقاعدة نفسها، فما يُتعلَّم في موضع ينتقل إلى غيره
Slide 17: RNN LM advantages and remaining problemsالشريحة 17: مزايا RNN LM والمشكلات الباقية

The two remaining problemsالمشكلتان الباقيتان

Recurrent computation is slow. To compute hth_t you need ht−1h_{t-1}, which needs ht−2h_{t-2}, and so on. A sequence of T words therefore takes T steps one after another, even during training when every word is already known. A GPU cannot spread one sequence's time steps across its cores. Transformers remove this dependency and train all positions at once; that is the Parallel training of the transformer parts later in this lecture.

الحساب التكراري بطيء. لحساب hth_t تحتاج ht−1h_{t-1}، التي تحتاج ht−2h_{t-2}، وهكذا. لذلك يستغرق تسلسل من T كلمة عدد T من الخطوات واحدة بعد الأخرى، حتى أثناء التدريب حين تكون كل الكلمات معروفة مسبقًا. لا تستطيع GPU توزيع الخطوات الزمنية لتسلسل واحد على أنويتها. المحوّلات (Transformers) تزيل هذا الاعتماد وتدرّب كل المواضع دفعة واحدة؛ وهذا هو parallel training في أجزاء المحوّلات لاحقًا في هذه المحاضرة.

Long-range information is hard in practice. In theory, hth_t can carry the first word of the document. In practice, the gradient that tells early steps how to help a late prediction is multiplied by one factor per step on the way back, and over many steps it shrinks toward zero. That is the Vanishing gradient problem, and it is why gated cells such as the LSTM of part 2 exist. Even an LSTM squeezes the whole past into a fixed-size vector, the bottleneck that attention removes in part 5.

المعلومات البعيدة صعبة الاستخدام عمليًا. نظريًا، يمكن لـ hth_t أن تحمل الكلمة الأولى من المستند. عمليًا، التدرّج (gradient) الذي يخبر الخطوات المبكرة كيف تساعد تنبؤًا متأخرًا يُضرب في معامل واحد لكل خطوة في طريق العودة، وعبر خطوات كثيرة يتقلص نحو الصفر. هذه هي مشكلة vanishing gradient، ولهذا وُجدت الخلايا ذات البوابات مثل LSTM في الجزء 2. وحتى LSTM تضغط الماضي كله في متجه ثابت الحجم، وهو عنق الزجاجة (bottleneck) الذي يزيله الانتباه (attention) في الجزء 5.

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

Why does an RNN LM's parameter count stay fixed as the input sentence grows longer?لماذا يبقى عدد معاملات RNN LM ثابتًا كلما طالت جملة الإدخال؟

Recall

Why can an RNN LM not be parallelized across time within one sequence, even in training?لماذا لا يمكن توزيع حساب RNN LM على التوازي عبر الزمن داخل تسلسل واحد، حتى أثناء التدريب؟

Each hidden state depends on the previous one through h_t = g(U h_{t-1} + W e_t), so step t cannot start until step t-1 is finished. The T steps form a chain.

كل حالة مخفية تعتمد على سابقتها عبر h_t = g(U h_{t-1} + W e_t)، فالخطوة t لا يمكن أن تبدأ قبل انتهاء الخطوة t-1. الخطوات الـ T تشكّل سلسلة.

In the slide's example, the input is "I saw a cat". A first RNN reads the words and produces hidden states h_1^(1) to h_4^(1). A second RNN treats that sequence of states as its input sequence and produces h_1^(2) to h_4^(2). Only the second layer's states feed the softmax that predicts "saw a cat on".

في مثال الشريحة، المدخل هو "I saw a cat". تقرأ RNN أولى الكلمات وتنتج الحالات المخفية من h_1^(1) إلى h_4^(1). ثم تعامل RNN ثانية هذا التسلسل من الحالات بوصفه تسلسل مدخلاتها وتنتج من h_1^(2) إلى h_4^(2). وحالات الطبقة الثانية وحدها تغذّي softmax التي تتنبأ بـ "saw a cat on".

ht(1)=g(U(1)ht−1(1)+W(1)et)ht(2)=g(U(2)ht−1(2)+W(2)ht(1))y^t=softmax⁡(Vht(2))\begin{aligned} h_t^{(1)} &= g\left(U^{(1)} h_{t-1}^{(1)} + W^{(1)} e_t\right) \\ h_t^{(2)} &= g\left(U^{(2)} h_{t-1}^{(2)} + W^{(2)} h_t^{(1)}\right) \\ \hat{y}_t &= \operatorname{softmax}\left(V h_t^{(2)}\right) \end{aligned}
A two-layer RNN LM in SLP3 letters; the superscript is now the layerنموذج لغة RNN بطبقتين برموز SLP3؛ والرمز العلوي الآن هو الطبقة
Two-layer RNN LM: layer 1 reads the words, layer 2 reads layer 1's states, and only layer 2 predicts the next word.نموذج RNN LM من طبقتين: الطبقة 1 تقرأ الكلمات، والطبقة 2 تقرأ حالات الطبقة 1، والطبقة 2 وحدها تتنبأ بالكلمة التالية.

This is a Stacked (multi-layer) RNN. Each layer has its own recurrent matrix and its own input matrix, and each carries its own hidden state through time, starting from its own h_0. The second layer's input matrix is d_h × d_h, because its input is a hidden state rather than an embedding. SLP3 reports that stacked RNNs generally outperform single-layer ones, likely because layers learn representations at different levels of abstraction, much as early visual areas detect edges that later areas assemble into shapes. The cost is more training time, and the best number of layers depends on the task and data.

هذه stacked RNN. لكل طبقة مصفوفتها التكرارية الخاصة ومصفوفة إدخالها الخاصة، وكل منها تحمل حالتها المخفية الخاصة عبر الزمن، بدءًا من h_0 الخاصة بها. مصفوفة إدخال الطبقة الثانية بحجم d_h × d_h، لأن مدخلها حالة مخفية لا تضمين. ويذكر SLP3 أن شبكات RNN المكدّسة تتفوق عمومًا على ذات الطبقة الواحدة، على الأرجح لأن الطبقات تتعلم تمثيلات على مستويات مختلفة من التجريد، كما تكتشف المناطق البصرية المبكرة الحواف التي تجمّعها المناطق اللاحقة في أشكال. والثمن هو وقت تدريب أطول، والعدد الأمثل للطبقات يعتمد على المهمة والبيانات.

Recall

In a two-layer RNN LM, what is the input of the second layer at step t, and which layer feeds the softmax?في نموذج RNN LM من طبقتين، ما مدخل الطبقة الثانية عند الخطوة t، وأي طبقة تغذّي softmax؟

The second layer's input at step t is the first layer's hidden state h_t^(1), in place of a word embedding. Only the top layer's state h_t^(2) feeds the output matrix and softmax.

مدخل الطبقة الثانية عند الخطوة t هو الحالة المخفية للطبقة الأولى h_t^(1)، بدلًا من تضمين كلمة. وحالة الطبقة العليا وحدها h_t^(2) تغذّي مصفوفة الإخراج وsoftmax.

Recapالخلاصة

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

  • n-gram LMs make an (n-1)-word Markov assumption and estimate probabilities by counting and smoothing; unseen n-grams get no evidence of their own.نماذج n-gram تفترض افتراض ماركوف بطول (n-1) كلمة، وتقدّر الاحتمالات بالعدّ ثم التنعيم (smoothing)؛ والـ n-gram التي لم تُرَ لا تملك أي دليل خاص بها.
  • Neural LMs map words to learned vectors, so evidence about one word also helps similar words, and all parameters are learned by training.النماذج العصبية تحوّل الكلمات إلى متجهات متعلَّمة، فالدليل عن كلمة ما يفيد الكلمات المشابهة لها أيضًا، وكل المعاملات تُتعلَّم أثناء التدريب.
  • RNN LM forward pass (SLP3): e_t = E x_t, h_t = g(U h_{t-1} + W e_t), ŷ_t = softmax(V h_t). The prediction is ŷ_t, not y_t.التمرير الأمامي في RNN LM (ترميز SLP3): e_t = E x_t ثم h_t = g(U h_{t-1} + W e_t) ثم ŷ_t = softmax(V h_t). التنبؤ هو ŷ_t وليس y_t.
  • Shapes: x_t is |V|×1, E is d_e×|V|, W is d_h×d_e, U is d_h×d_h, V is |V|×d_h. With |V| = 10,000 and d_h = 512, V alone holds 5.12 M weights.الأبعاد: x_t بحجم |V|×1، وE بحجم d_e×|V|، وW بحجم d_h×d_e، وU بحجم d_h×d_h، وV بحجم |V|×d_h. عندما |V| = 10,000 وd_h = 512 تحمل V وحدها 5.12 M وزن.
  • Loss at step t: L_CE = -log ŷ_t[w_{t+1}], the negative log probability of the true next word.الخسارة عند الخطوة t هي L_CE = -log ŷ_t[w_{t+1}]، أي سالب لوغاريتم الاحتمال الذي أعطاه النموذج للكلمة التالية الصحيحة.
  • Generation is autoregressive: start at <s>, pick a word from ŷ, feed its embedding back, stop at </s> or a length limit. Greedy is deterministic; temperature reshapes the softmax.التوليد انحداري ذاتي (autoregressive): ابدأ من <s>، اختر كلمة من ŷ، أعد تضمينها مدخلًا، وتوقّف عند </s> أو عند حد أقصى للطول. الاختيار الجشع (greedy) حتمي، ودرجة الحرارة (temperature) تعيد تشكيل softmax.
  • Slide 16 uses CS224n names: W_e is input, W_hh is recurrent, U is OUTPUT. On slide 14, U is recurrent and V is output.الشريحة 16 تستخدم أسماء CS224n: W_e مصفوفة الإدخال، وW_hh المصفوفة التكرارية، وU هي مصفوفة الإخراج. أما في الشريحة 14 فـ U هي التكرارية وV هي الإخراج.
  • Advantages: any input length, fixed model size, long history in theory, shared weights. Problems: slow sequential computation, long-range information hard in practice.المزايا: أي طول للمدخل، وحجم نموذج ثابت، وتاريخ طويل نظريًا، وأوزان مشتركة. المشكلات: حساب تتابعي بطيء، وصعوبة الاستفادة من المعلومات البعيدة عمليًا.
  • A two-layer RNN LM feeds h_t^(1) into the second layer as its input; only the top layer feeds the softmax.نموذج RNN LM من طبقتين يُدخل h_t^(1) إلى الطبقة الثانية بوصفه مدخلها، والطبقة العليا وحدها تغذّي softmax.

Sourcesالمصادر

Part 04: Self-supervised training: cross-entropy and teacher forcingالتدريب الذاتي الإشراف: الإنتروبيا المتقاطعة والتغذية القسرية

How a language model learns from raw text by predicting the next word, why the cross-entropy loss collapses to minus log of the true word's probability, and why training feeds the gold word instead of the model's guess.كيف يتعلم نموذج اللغة من النص الخام بالتنبؤ بالكلمة التالية، ولماذا تختزل خسارة الإنتروبيا المتقاطعة إلى سالب لوغاريتم احتمال الكلمة الصحيحة، ولماذا يغذي التدريب الكلمة الصحيحة (gold) بدلا من تخمين النموذج (teacher forcing).

3 concepts3 مفاهيم, ، slides 19-22الشرائح 19-22

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

Part 3 built an RNN language model that turns a history into a probability distribution over the next word. Untrained, its weights are random and its predictions are noise. This part answers the question the rest of the lecture depends on: where does the training signal come from, and how exactly is the model punished for a bad guess?

The answer has three pieces that fit together. The data labels itself, because the next word of real text is the target. The punishment is the cross-entropy loss, which for a one-hot target is just minus the log probability given to the true word. And during training the model is always fed the true history, a scheme called teacher forcing. The same three ideas train every transformer later in this lecture, so expect them on the exam as a derivation, a calculation and a definition.

بنى الجزء 3 نموذج لغة من نوع RNN يحوّل التاريخ (السياق السابق) إلى توزيع احتمالي على الكلمة التالية. قبل التدريب تكون أوزانه عشوائية وتنبؤاته مجرد ضجيج. هذا الجزء يجيب عن السؤال الذي يعتمد عليه بقية المحاضرة: من أين تأتي إشارة التدريب، وكيف بالضبط يُعاقَب النموذج على التخمين السيئ؟

للإجابة ثلاث قطع تتكامل معًا. البيانات تسمّي نفسها بنفسها، لأن الكلمة التالية في النص الحقيقي هي الهدف. والعقاب هو خسارة الإنتروبيا المتقاطعة (cross-entropy loss)، وهي مع هدف one-hot مجرد سالب لوغاريتم الاحتمال المعطى للكلمة الصحيحة. وأثناء التدريب يُغذّى النموذج دائمًا بالتاريخ الصحيح، وهي طريقة تسمى teacher forcing. هذه الأفكار الثلاث نفسها تدرّب كل transformer لاحقًا في هذه المحاضرة، فتوقّعها في الاختبار على شكل استنتاج، وعملية حسابية، وتعريف.

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

  1. Explain why next-word prediction on raw text counts as self-supervised training, with no human labels.اشرح لماذا يُعدّ التنبؤ بالكلمة التالية على نص خام تدريبًا ذاتي الإشراف (self-supervised) لا يحتاج إلى أي تسميات بشرية.
  2. Derive why the cross-entropy loss with a one-hot target collapses to minus the log probability of the true next word.استنتج لماذا تختزل خسارة الإنتروبيا المتقاطعة (cross-entropy) مع هدف one-hot إلى سالب لوغاريتم احتمال الكلمة التالية الصحيحة.
  3. Compute the loss for a given predicted distribution, and the average loss and perplexity for a short sequence.احسب الخسارة لتوزيع متنبأ به معطى، واحسب متوسط الخسارة والـ perplexity لتسلسل قصير.
  4. Define teacher forcing, say why it is used, and name its known downside, exposure bias.عرّف teacher forcing، واذكر سبب استخدامه، وسمِّ عيبه المعروف: exposure bias.

Take the sentence “so long and thanks for all the fish”. Without asking any annotator, you can already write down one training example for every word after the first: after so the answer is long, after so long it is and, after so long and it is thanks, and so on. The sentence is both the question and the answer key.

خذ الجملة «so long and thanks for all the fish». من دون أن تسأل أي مُعلِّق بشري، تستطيع أن تكتب مثال تدريب واحدًا لكل كلمة بعد الأولى: بعد so الإجابة هي long، وبعد so long هي and، وبعد so long and هي thanks، وهكذا. الجملة هي السؤال ومفتاح الإجابة في الوقت نفسه.

Shift the text one position: each input word points at its own target, the next wordأزِح النص موضعًا واحدًا: كل كلمة مُدخلة تشير إلى هدفها الخاص، وهو الكلمة التالية

The training algorithm in two linesخوارزمية التدريب في سطرين

This is why a Neural language model is trained by Self-supervised training. The algorithm on the slide is short because the idea is short:

لهذا السبب يُدرَّب neural language model بطريقة self-supervised training. الخوارزمية في الشريحة قصيرة لأن الفكرة نفسها قصيرة:

  1. Take a corpus of raw text.خذ corpus من النص الخام.
  2. At each time step t, ask the model for a distribution over the next word, compare it with the word that actually comes next, and use gradient descent to reduce the prediction error.عند كل خطوة زمنية t، اطلب من النموذج توزيعًا على الكلمة التالية، وقارنه بالكلمة التي تأتي فعلًا بعدها، واستخدم gradient descent لتقليل خطأ التنبؤ.

Nothing in this loop needs a human. In supervised sentiment classification someone must tag each review as positive or negative. Here the “label” at position t is the token at position t+1, so every sentence ever written is free training data. That is the economic reason language models can be trained on billions of words.

لا شيء في هذه الحلقة يحتاج إلى إنسان. في تصنيف المشاعر الخاضع للإشراف (supervised) يجب أن يوسم شخصٌ ما كل مراجعة بأنها إيجابية أو سلبية. أما هنا فإن «التسمية» عند الموضع t هي الـ token عند الموضع t+1، لذلك كل جملة كُتبت في التاريخ هي بيانات تدريب مجانية. وهذا هو السبب الاقتصادي الذي يجعل تدريب نماذج اللغة على مليارات الكلمات ممكنًا.

Compare this with the Count-based (n-gram) language model of lecture 3. An n-gram model is “trained” by counting and normalizing, which has a closed-form answer. A neural model has millions of weights inside a Recurrent neural network (RNN) and a Softmax, and no formula gives the best weights directly. So we need a single number that says how wrong the model is, and then we follow its gradient downhill. That number is the loss in the next concept.

قارن هذا بـ count-based (n-gram) language model في المحاضرة 3. نموذج الـ n-gram «يُدرَّب» بالعدّ ثم التطبيع (normalizing)، ولذلك له حل بصيغة مغلقة (closed-form). أما النموذج العصبي فلديه ملايين الأوزان داخل RNN وsoftmax، ولا توجد معادلة تعطي أفضل الأوزان مباشرة. لذلك نحتاج إلى رقم واحد يقول مدى خطأ النموذج، ثم نتبع تدرّجه (gradient) نزولًا. هذا الرقم هو الخسارة في المفهوم التالي.

Recall

Why is next-word prediction called self-supervised, and what is the target at position t?لماذا يسمى التنبؤ بالكلمة التالية ذاتي الإشراف (self-supervised)، وما الهدف عند الموضع t؟

The targets come from the text itself, so no human labels are needed. At position t the target is the next token of the same sequence, w_(t+1).
الأهداف تأتي من النص نفسه، لذلك لا حاجة إلى تسميات بشرية. عند الموضع t يكون الهدف هو الـ token التالي من التسلسل نفسه، w_(t+1).

Shrink the vocabulary to four words, {so, long, and, thanks}. The model has just read so and outputs ŷ = [0.1, 0.6, 0.2, 0.1]. The true next word is long. How bad was this guess, as a single number?

صغّر المفردات إلى أربع كلمات، {so, long, and, thanks}. النموذج قرأ للتو so وأخرج ŷ = [0.1, 0.6, 0.2, 0.1]. الكلمة التالية الصحيحة هي long. ما مدى سوء هذا التخمين، معبَّرًا عنه برقم واحد؟

What a good loss must doما الذي يجب أن تفعله الخسارة الجيدة

Slide 20 lists the requirements in plain words. We want the model to put high probability on the true word w. The loss should therefore be small when that probability is high and large when it is low, and training should move the weights to raise the probability of the true word. The loss that does this is the same one you met for logistic regression and skip-gram in lecture 4: the Cross-entropy loss.

الشريحة 20 تسرد المتطلبات بكلمات بسيطة. نريد من النموذج أن يضع احتمالًا عاليًا على الكلمة الصحيحة w. لذلك يجب أن تكون الخسارة صغيرة عندما يكون ذلك الاحتمال عاليًا وكبيرة عندما يكون منخفضًا، ويجب أن يحرّك التدريب الأوزان لرفع احتمال الكلمة الصحيحة. الخسارة التي تحقق ذلك هي نفسها التي رأيتها مع logistic regression وskip-gram في المحاضرة 4: cross-entropy loss.

From the full sum to one termمن المجموع الكامل إلى حد واحد

Cross-entropy measures the gap between two distributions: the correct one y_t and the predicted one ŷ_t that the softmax produced. Written out over the whole vocabulary V:

تقيس الإنتروبيا المتقاطعة الفجوة بين توزيعين: التوزيع الصحيح y_t والتوزيع المتنبأ به ŷ_t الذي أنتجه الـ softmax. وعند كتابتها على كامل المفردات V:

LCE(y^t,yt)=−∑w∈Vyt[w] log⁡y^t[w]L_{CE}(\hat{y}_t, y_t) = -\sum_{w \in V} y_t[w]\,\log \hat{y}_t[w]
Cross-entropy at step tالإنتروبيا المتقاطعة عند الخطوة t

The correct distribution is one-hot. It puts 1 on the word that really comes next and 0 on every other word. Multiply anything by 0 and it disappears, so every term in the sum vanishes except the one for the true word, where the factor is 1:

التوزيع الصحيح من نوع one-hot. فهو يضع 1 على الكلمة التي تأتي فعلًا بعدها ويضع 0 على كل كلمة أخرى. أي شيء يُضرب في 0 يختفي، لذلك تتلاشى كل حدود المجموع ما عدا حد الكلمة الصحيحة، حيث يكون المعامل 1:

LCE=−(0⋅log⁡0.1+1⋅log⁡0.6+0⋅log⁡0.2+0⋅log⁡0.1)=−log⁡y^t[wt+1]L_{CE} = -\big(0\cdot\log 0.1 + 1\cdot\log 0.6 + 0\cdot\log 0.2 + 0\cdot\log 0.1\big) = -\log \hat{y}_t[w_{t+1}]
The one-hot target kills every term except the true wordالهدف one-hot يلغي كل الحدود عدا حد الكلمة الصحيحة
Multiply ŷ by the one-hot y: three terms become zero, only the true word's -log 0.6 = 0.511 survivesاضرب ŷ في y من نوع one-hot: ثلاثة حدود تصبح صفرًا، ولا يبقى إلا حد الكلمة الصحيحة -log 0.6 = 0.511

Worked exampleمثال محلول

Loss for one predictionالخسارة لتنبؤ واحد

  1. Read off the true word's probabilityاقرأ احتمال الكلمة الصحيحة

    The true next word is long, and ŷ[long] = 0.6.
    الكلمة التالية الصحيحة هي long، وŷ[long] = 0.6.
  2. Take minus the natural logخذ سالب اللوغاريتم الطبيعي

    L = -ln 0.6 = 0.511 nats.
    L = -ln 0.6 = 0.511 nats.
  3. Compare with a bad modelقارن بنموذج سيئ

    If the model had given long only 0.05, then L = -ln 0.05 = 3.00 nats, almost six times larger.
    لو أعطى النموذج long احتمال 0.05 فقط، لكانت L = -ln 0.05 = 3.00 nats، أي أكبر بنحو ستة أضعاف تقريبًا.
  4. Compare with a perfect modelقارن بنموذج مثالي

    If ŷ[long] = 1, then L = -ln 1 = 0. Zero is the floor; the loss can never be negative.
    إذا كانت ŷ[long] = 1، فإن L = -ln 1 = 0. الصفر هو الحد الأدنى، ولا يمكن أن تكون الخسارة سالبة أبدًا.
  5. Resultالنتيجة

    0.6 → 0.511, 0.05 → 3.00, 1 → 0. The loss rises gently at first and then sharply as the true word's probability falls toward 0.
    0.6 → 0.511، 0.05 → 3.00، 1 → 0. ترتفع الخسارة ببطء في البداية ثم بحدة كلما اقترب احتمال الكلمة الصحيحة من 0.
SimulatorمحاكيDrag the probability of the true next wordاسحب احتمال الكلمة التالية الصحيحة
p(long)
0.60
so0.100
long0.600
and0.200
thanks0.100
Loss -ln p0.511nats
Loss -log2 p0.737bits
exp(loss)1.67perplexity if every word scored like thisالحيرة (perplexity) لو حصلت كل كلمة على هذه الدرجة

Drag the slider and watch the shape of -ln p. Between 0.6 and 1 the curve is almost flat, so a model that is already right gains little from becoming more confident. Below about 0.1 the curve climbs steeply, so a confident miss is punished hard. That asymmetry is exactly what pushes the model to never give the true word a near-zero probability.

اسحب المؤشر وراقب شكل -ln p. بين 0.6 و1 يكون المنحنى شبه مسطح، لذلك فإن النموذج المصيب أصلًا لا يكسب الكثير من زيادة ثقته. وتحت 0.1 تقريبًا يصعد المنحنى بحدة، لذلك يُعاقَب الخطأ الواثق بشدة. هذا اللاتماثل هو بالضبط ما يدفع النموذج إلى ألا يعطي الكلمة الصحيحة احتمالًا قريبًا من الصفر أبدًا.

From one word to a whole sequenceمن كلمة واحدة إلى تسلسل كامل

A training sentence gives one loss per position. The figure on slide 14 (and again on slide 42 for transformers) sums the per-step losses and divides by the length T, so the sequence loss is the average:

جملة التدريب الواحدة تعطي خسارة واحدة لكل موضع. الشكل في الشريحة 14 (ومرة أخرى في الشريحة 42 مع الـ transformers) يجمع خسائر الخطوات ويقسمها على الطول T، لذلك تكون خسارة التسلسل هي المتوسط:

L=1T∑t=1TLCE,t=−1T∑t=1Tlog⁡y^t[wt+1]L = \frac{1}{T}\sum_{t=1}^{T} L_{CE,t} = -\frac{1}{T}\sum_{t=1}^{T}\log \hat{y}_t[w_{t+1}]
Average cross-entropy over a sequence of length Tمتوسط الإنتروبيا المتقاطعة على تسلسل طوله T
Input w_tالمُدخل w_tTarget w_(t+1)الهدف w_(t+1)ŷ_t[target]ŷ_t[الهدف]-ln ŷ (nats)-ln ŷ (nats)
sosolonglong0.60.60.5110.511
longlongandand0.50.50.6930.693
andandthanksthanks0.20.21.6091.609
thanksthanksforfor0.40.40.9160.916
forforallall0.80.80.2230.223
Per-step losses for the input so long and thanks for (illustrative probabilities)خسائر كل خطوة للمُدخل so long and thanks for (احتمالات توضيحية)

Worked exampleمثال محلول

Average loss and perplexityمتوسط الخسارة والـ perplexity

  1. Sum the per-step lossesاجمع خسائر الخطوات

    0.511 + 0.693 + 1.609 + 0.916 + 0.223 = 3.953
    0.511 + 0.693 + 1.609 + 0.916 + 0.223 = 3.953
  2. Divide by T = 5اقسم على T = 5

    L = 3.953 / 5 = 0.791 nats per word.
    L = 3.953 / 5 = 0.791 nats لكل كلمة.
  3. Exponentiate to get perplexityطبّق الدالة الأسية لتحصل على الـ perplexity

    PP = e^0.791 ≈ 2.20. A single step with loss 0.511 alone would give e^0.511 ≈ 1.67, which is just 1 / 0.6.
    PP = e^0.791 ≈ 2.20. أما خطوة واحدة بخسارة 0.511 وحدها فكانت ستعطي e^0.511 ≈ 1.67، وهو ببساطة 1 / 0.6.
  4. Resultالنتيجة

    Minimizing average cross-entropy is the same as minimizing perplexity, the metric from lecture 3, because PP = exp(average CE) is increasing in the loss.
    تقليل متوسط الإنتروبيا المتقاطعة هو نفسه تقليل الـ perplexity، المقياس من المحاضرة 3، لأن PP = exp(average CE) دالة متزايدة في الخسارة.

Recall

Starting from the full cross-entropy sum, why does the next-word loss reduce to -log ŷ_t[w_(t+1)]?انطلاقًا من مجموع الإنتروبيا المتقاطعة الكامل، لماذا تختزل خسارة الكلمة التالية إلى -log ŷ_t[w_(t+1)]؟

The gold distribution y_t is one-hot: 1 for the true next word and 0 for every other word. Each term y_t[w] log ŷ_t[w] with y_t[w] = 0 is zero, leaving only -1 · log ŷ_t[w_(t+1)].
التوزيع الصحيح (gold) y_t من نوع one-hot: 1 للكلمة التالية الصحيحة و0 لكل كلمة أخرى. كل حد y_t[w] log ŷ_t[w] فيه y_t[w] = 0 يساوي صفرًا، فلا يبقى إلا -1 · log ŷ_t[w_(t+1)].

Recall

A model gives the true word probability 0.1. What is the loss in nats, and what would it be for 0.9?نموذج يعطي الكلمة الصحيحة احتمال 0.1. كم تساوي الخسارة بوحدة nats، وكم ستكون لو كان الاحتمال 0.9؟

-ln 0.1 = 2.303 nats, and -ln 0.9 = 0.105 nats.
-ln 0.1 = 2.303 nats، و-ln 0.9 = 0.105 nats.

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

A model assigns probability 0.25 to the correct next word. What is its cross-entropy loss in nats?نموذج يعطي الكلمة التالية الصحيحة احتمال 0.25. كم تساوي خسارة الإنتروبيا المتقاطعة (cross-entropy) بوحدة nats؟

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

Why does the cross-entropy sum over the whole vocabulary reduce to a single term?لماذا يختزل مجموع الإنتروبيا المتقاطعة على كامل المفردات إلى حد واحد؟

Back to “so long and thanks”. At step 2 the model has read so long and predicts the instead of and. It pays its loss, -log ŷ[and]. Now, what should it read at step 3: its own mistaken the, or the real word and?

لنعد إلى «so long and thanks». عند الخطوة 2 قرأ النموذج so long وتنبأ بـ the بدلًا من and. يدفع خسارته، -log ŷ[and]. والآن، ماذا يجب أن يقرأ عند الخطوة 3: كلمته الخاطئة the، أم الكلمة الحقيقية and؟

The ruleالقاعدة

Teacher forcing answers: always the real word. At each position t the model sees the correct tokens w_(1:t), computes the loss -log ŷ_t[w_(t+1)] for the next token, and then, at position t+1, its own prediction is ignored. The gold word w_(t+1) is added to the context and training moves on. In an RNN this means the input at each step is the true word, combined with the Hidden state that summarizes the true history so far.

يجيب teacher forcing: دائمًا الكلمة الحقيقية. عند كل موضع t يرى النموذج الـ tokens الصحيحة w_(1:t)، ويحسب الخسارة -log ŷ_t[w_(t+1)] للـ token التالي، ثم عند الموضع t+1 يُتجاهَل تنبؤه هو. تُضاف الكلمة الصحيحة (gold) w_(t+1) إلى السياق ويمضي التدريب. في الـ RNN يعني هذا أن المُدخل عند كل خطوة هو الكلمة الحقيقية، مع hidden state الذي يلخّص التاريخ الحقيقي حتى تلك اللحظة.

Top: one wrong guess, but the next input is still the gold word. Bottom: the wrong guess is fed back and the sentence driftsفي الأعلى: تخمين خاطئ واحد، لكن المُدخل التالي يبقى الكلمة الصحيحة (gold). في الأسفل: يُعاد التخمين الخاطئ كمُدخل فتنحرف الجملة
Teacher forcingTeacher forcingFree runningالتشغيل الحر (free running)
Input at step t+1المُدخل عند الخطوة t+1The gold word w_(t+1) from the training textالكلمة الصحيحة (gold) w_(t+1) من نص التدريبThe model's own sampled or argmax wordالكلمة التي اختارها النموذج نفسه بأخذ عيّنة (sampled) أو بالـ argmax
When it is usedمتى يُستخدمTrainingأثناء التدريبInference (generation), or training variants such as scheduled samplingوقت الاستدلال (التوليد)، أو في صيغ تدريب معدّلة مثل scheduled sampling
Effect of one mistakeأثر خطأ واحدContained: the next step still sees the true historyمحصور: الخطوة التالية ما زالت ترى التاريخ الحقيقيCompounds: later steps condition on the wrong wordيتراكم: الخطوات اللاحقة تعتمد على الكلمة الخاطئة
Targets known in advanceهل الأهداف معروفة مسبقًاYes, every input and target is fixed by the textنعم، كل مُدخل وكل هدف يحدده النصNo, each input depends on the previous outputلا، كل مُدخل يعتمد على المُخرج السابق
Teacher forcing during training versus free running during generationTeacher forcing أثناء التدريب مقابل التشغيل الحر (free running) أثناء التوليد

Why train this wayلماذا نتدرب بهذه الطريقة

  • Stable targets. Every step is graded against a sensible history. Early in training the model's own guesses are nearly random, so feeding them back would turn later steps into nonsense and their losses would teach nothing useful.أهداف مستقرة. كل خطوة تُقيَّم مقابل تاريخ منطقي. في بداية التدريب تكون تخمينات النموذج شبه عشوائية، فلو أعدناها إليه كمُدخلات لتحولت الخطوات اللاحقة إلى هراء، ولما علّمت خسائرها شيئًا مفيدًا.
  • Faster convergence. One early mistake cannot derail the rest of the sentence, so each gradient carries a clean signal. Jurafsky and Martin note that teacher forcing speeds up training.تقارب أسرع. خطأ مبكر واحد لا يمكنه أن يُخرج بقية الجملة عن مسارها، لذلك يحمل كل gradient إشارة نظيفة. ويذكر Jurafsky وMartin أن teacher forcing يسرّع التدريب.
  • Inputs known in advance. Because no input depends on a sampled output, the whole input and target sequence is fixed before the forward pass. An RNN still computes hidden states in order, but nothing has to be sampled between steps. A transformer goes further: with the Causal (masked) self-attention, it computes all positions' losses in one pass, which is the Parallel training you will see in part 8.المدخلات معروفة مسبقًا. لأنه لا يوجد مُدخل يعتمد على مُخرج تم أخذه بالعيّنة (sampled)، فإن تسلسل المدخلات والأهداف كله محدد قبل الـ forward pass. الـ RNN ما زال يحسب الـ hidden states بالترتيب، لكن لا حاجة إلى أخذ أي عيّنة بين الخطوات. والـ transformer يذهب أبعد من ذلك: مع causal mask، يحسب خسائر كل المواضع في تمريرة واحدة، وهذا هو parallel training الذي ستراه في الجزء 8.

The price: exposure biasالثمن: exposure bias

Recall

At position t+1 of training with teacher forcing, what is the input, and what happens to the model's prediction from step t?عند الموضع t+1 في التدريب باستخدام teacher forcing، ما المُدخل، وماذا يحدث لتنبؤ النموذج من الخطوة t؟

The input is the gold word w_(t+1) from the text. The model's prediction from step t is used only to compute the loss -log ŷ_t[w_(t+1)] and is then discarded.
المُدخل هو الكلمة الصحيحة (gold) w_(t+1) من النص. تنبؤ النموذج من الخطوة t يُستخدم فقط لحساب الخسارة -log ŷ_t[w_(t+1)] ثم يُهمَل.

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

During training with teacher forcing, what is fed as the input at position t+1?أثناء التدريب باستخدام teacher forcing، ما الذي يُدخل كمُدخل عند الموضع t+1؟

Recapالخلاصة

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

  • Self-supervised: the target at step t is simply word t+1 of the same text. The corpus labels itself.التدريب ذاتي الإشراف (self-supervised): الهدف عند الخطوة t هو ببساطة الكلمة t+1 من النص نفسه. الـ corpus يسمّي نفسه بنفسه.
  • Training loop: at every position, predict the next word, measure the error, and nudge the weights by gradient descent.حلقة التدريب: عند كل موضع، تنبأ بالكلمة التالية، وقِس الخطأ، وحرّك الأوزان قليلًا باستخدام gradient descent.
  • L_CE = -Σ_w y_t[w] log ŷ_t[w]. Because y_t is one-hot, every term but the true word is zero, so L_CE = -log ŷ_t[w_(t+1)].L_CE = -Σ_w y_t[w] log ŷ_t[w]. ولأن y_t من نوع one-hot، فكل حد يساوي صفرًا ما عدا حد الكلمة الصحيحة، لذلك L_CE = -log ŷ_t[w_(t+1)].
  • Worked numbers: ŷ[long] = 0.6 gives 0.511 nats; 0.05 gives 3.00 nats; 1.0 gives 0. The loss explodes as p falls toward 0.أرقام محلولة: ŷ[long] = 0.6 تعطي 0.511 nats، و0.05 تعطي 3.00 nats، و1.0 تعطي 0. الخسارة تنفجر كلما اقتربت p من 0.
  • Sequence loss is the average over positions, L = (1/T) Σ L_CE,t, and exp of that average is the perplexity.خسارة التسلسل هي المتوسط على المواضع، L = (1/T) Σ L_CE,t، والدالة الأسية (exp) لهذا المتوسط هي الـ perplexity.
  • Teacher forcing: at step t+1, ignore what the model predicted and feed the gold word w_(t+1) instead.Teacher forcing: عند الخطوة t+1، تجاهل ما تنبأ به النموذج وأدخل بدلًا منه الكلمة الصحيحة (gold) w_(t+1).
  • It is used because targets and inputs are fixed in advance: stable training, faster convergence, parallel losses.يُستخدم لأن الأهداف والمدخلات محددة مسبقًا: تدريب مستقر، وتقارب أسرع، وحساب الخسائر بالتوازي.
  • Downside (beyond the slides): exposure bias. Training sees only gold histories, generation sees the model's own outputs.العيب (من خارج الشرائح): exposure bias. التدريب يرى فقط تواريخ صحيحة (gold)، بينما التوليد يرى مخرجات النموذج نفسه.

Sourcesالمصادر

Part 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).

3 concepts3 مفاهيم, ، slides 23-26الشرائح 23-26

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المصادر

Part 06: Self-attention, multi-head, positional, cross and causal attentionالانتباه الذاتي والرؤوس المتعددة والموضعي والمتقاطع والسببي

The query, key, value computation in full, scaled dot-product attention in matrix form, why we use several heads, how positional encodings inject word order, how decoders cross-attend to the encoder, and how the causal mask hides the future.حساب الاستعلام والمفتاح والقيمة (query وkey وvalue) كاملا، والانتباه بالضرب النقطي المُقيَّس (scaled dot-product) بصيغة المصفوفات، ولماذا نستخدم عدة رؤوس، وكيف يُدخل الترميز الموضعي ترتيب الكلمات، وكيف ينتبه المفكك بشكل متقاطع إلى المشفر، وكيف يخفي القناع السببي (causal mask) المستقبل.

5 concepts5 مفاهيم, ، slides 27-31الشرائح 27-31

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

The previous part argued that a transformer replaces recurrence with attention. This part opens the box. You will compute attention by hand, see why the formula divides by √d_k, split it into heads, give it a sense of word order, connect a decoder to an encoder, and stop a language model from reading the future.

Every later idea in the lecture, from GPT-style decoders to BERT and the language modeling head, is built from these five pieces. For the exam, expect a small numeric attention computation, the matrix formula with each term explained, the shapes of Q, K, V and QKᵀ, the source of the queries and keys in cross-attention, and a causal mask drawn for a short sequence.

رأينا في الجزء السابق أن الـ transformer يستبدل التكرار (recurrence) بالـ attention. في هذا الجزء نفتح الصندوق. ستحسب الـ attention يدويًا، وترى لماذا تقسم الصيغة على √d_k، ثم تقسمه إلى رؤوس (heads)، وتمنحه إحساسًا بترتيب الكلمات، وتربط decoder بـ encoder، وتمنع نموذج اللغة من قراءة المستقبل.

كل فكرة لاحقة في المحاضرة، من الـ decoders على طراز GPT إلى BERT ورأس نمذجة اللغة (language modeling head)، مبنية من هذه القطع الخمس. في الامتحان توقّع: حسابًا عدديًا صغيرًا للـ attention، وصيغة المصفوفات مع شرح كل حد فيها، وأبعاد Q وK وV وQKᵀ، ومصدر الـ queries والـ keys في الـ cross-attention، ورسم causal mask لتسلسل قصير.

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

  1. Compute queries, keys and values, the scaled scores, the softmax weights and the output vector for a small example by hand.أن تحسب يدويًا الـ queries والـ keys والـ values، والدرجات المقيَّسة (scaled scores)، وأوزان الـ softmax، ومتجه المخرج لمثال صغير.
  2. Write softmax(QKᵀ/√d_k)V, name the shape of every term, and explain why the scores are divided by √d_k.أن تكتب softmax(QKᵀ/√d_k)V، وتسمّي أبعاد كل حد فيها، وتشرح لماذا تُقسَم الدرجات على √d_k.
  3. Explain what multiple heads buy, and track the shapes from d = 512 through 8 heads of 64 and back through Wᴼ.أن تشرح ما الذي تضيفه الرؤوس المتعددة (multiple heads)، وتتتبع الأبعاد من d = 512 عبر 8 رؤوس بحجم 64 ثم العودة عبر Wᴼ.
  4. Explain why attention needs positional encodings, and evaluate the sinusoidal formula for a given position.أن تشرح لماذا يحتاج الـ attention إلى positional encodings، وتحسب الصيغة الجيبية (sinusoidal) لموضع معطى.
  5. State where Q, K and V come from in cross-attention, and draw the causal mask for N = 4.أن تذكر مصدر Q وK وV في الـ cross-attention، وترسم الـ causal mask عندما N = 4.

Take the sentence “the cat sat because it was tired”. To build a better vector for “it”, the model wants to pull in information from “cat” and mostly ignore “because”. It needs three things for every word: a way to ask what it is looking for, a way to advertise what it contains, and the content it would hand over if chosen.

خذ الجملة “the cat sat because it was tired”. لكي يبني النموذج متجهًا أفضل للكلمة “it”، يريد أن يسحب معلومات من “cat” وأن يتجاهل “because” في الغالب. يحتاج لكل كلمة إلى ثلاثة أشياء: طريقة ليسأل عمّا يبحث عنه، وطريقة ليعلن عمّا يحتويه، والمحتوى الذي سيسلّمه إن وقع عليه الاختيار.

Three roles for every tokenثلاثة أدوار لكل token

Self-attention gives each input vector x_i those three roles through three learned matrices. These are the query, key and value projections:

يمنح الـ Self-attention كل متجه دخل x_i هذه الأدوار الثلاثة عبر ثلاث مصفوفات مُتعلَّمة. هذه هي إسقاطات الـ query, key and value:

qi=WQxi,ki=WKxi,vi=WVxiq_i = W^{Q} x_i, \qquad k_i = W^{K} x_i, \qquad v_i = W^{V} x_i
Slide 27, column-vector formالشريحة 27، بصيغة متجه العمود
  • The query q_i is what position i is looking for.الـ query q_i هو ما يبحث عنه الموضع i.
  • The key k_j is what position j offers to be matched against.الـ key k_j هو ما يعرضه الموضع j لتتم المطابقة معه.
  • The value v_j is what position j actually contributes once chosen.الـ value v_j هو ما يساهم به الموضع j فعليًا بعد أن يقع عليه الاختيار.

The same token plays all three roles, but with different matrices, so “what I look for” and “what I offer” can differ. That separation is the whole point: “it” may look for an animate noun while advertising itself as a pronoun.

الـ token نفسه يؤدي الأدوار الثلاثة، لكن بمصفوفات مختلفة، فيمكن أن يختلف «ما أبحث عنه» عن «ما أعرضه». وهذا الفصل هو بيت القصيد: قد تبحث “it” عن اسم لكائن حي بينما تعلن عن نفسها بوصفها ضميرًا.

Score, normalize, mixاحسب الدرجة، طبّع، امزج

Attention for one query is three steps. Score every key by a dot product with the query. Turn the scores into weights with a Softmax, so they are positive and sum to one. Use the weights to average the values.

الـ attention لـ query واحد ثلاث خطوات. أعطِ كل key درجة بحاصل الضرب النقطي (dot product) مع الـ query. حوّل الدرجات إلى أوزان بـ softmax، فتصبح موجبة ومجموعها واحد. استخدم الأوزان لحساب متوسط الـ values.

scoreij=qi⋅kjdk,αij=exp⁡(scoreij)∑kexp⁡(scoreik),yi=∑jαijvj\text{score}_{ij} = \frac{q_i \cdot k_j}{\sqrt{d_k}}, \qquad \alpha_{ij} = \frac{\exp(\text{score}_{ij})}{\sum_{k}\exp(\text{score}_{ik})}, \qquad y_i = \sum_{j} \alpha_{ij} v_j
One output vector, with the scaling includedمتجه مخرج واحد، مع تضمين التحجيم

Stack every query as a row of Q, every key as a row of K and every value as a row of V, and all N outputs come out of one matrix expression. That is Scaled dot-product attention, and it is why a transformer can process a whole sequence in parallel instead of step by step.

رصّ كل query كصف في Q، وكل key كصف في K، وكل value كصف في V، فتخرج المخرجات الـ N كلها من تعبير مصفوفي واحد. هذا هو الـ scaled dot-product attention، ولهذا يستطيع الـ transformer معالجة التسلسل كله بالتوازي بدلًا من خطوة بخطوة.

SelfAttention(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\text{SelfAttention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right) V
Slide 27, matrix formالشريحة 27، بصيغة المصفوفات

Shapes for N tokens in row form (SLP3 convention)الأبعاد لـ N من الـ tokens بصيغة الصفوف (اصطلاح SLP3)

X (input rows)X (صفوف الدخل)
N × dN × d
W^Q, W^K
d × d_kd × d_k
W^V
d × d_vd × d_v
Q, K
N × d_kN × d_k
V
N × d_vN × d_v
QKᵀ and the weight matrixQKᵀ ومصفوفة الأوزان
N × NN × N
softmax(QKᵀ/√d_k) V
N × d_vN × d_v

Read the formula term by term. QKᵀ is an N × N table: row i, column j holds q_i · k_j, how well position i’s question matches position j’s label. Dividing by √d_k rescales it. The softmax is applied to each row separately, so row i becomes a probability distribution over the positions i attends to. Multiplying by V replaces each row of weights with the matching weighted average of value vectors.

اقرأ الصيغة حدًّا حدًّا. QKᵀ جدول بحجم N × N: الصف i والعمود j يحملان q_i · k_j، أي مدى تطابق سؤال الموضع i مع وسم (label) الموضع j. القسمة على √d_k تعيد تقييسه. يُطبَّق الـ softmax على كل صف منفصلًا، فيصبح الصف i توزيعًا احتماليًا على المواضع التي ينتبه إليها i. والضرب في V يستبدل كل صف من الأوزان بالمتوسط الموزون المقابل له من متجهات الـ values.

Worked exampleمثال محلول

Attention for one query over three tokens (d_k = 2)الـ attention لـ query واحد على ثلاثة tokens (d_k = 2)

  1. Set upالإعداد

    Query q = [1, 0]. Keys k_1 = [1, 0], k_2 = [0, 1], k_3 = [1, 1]. Values v_1 = [1, 0], v_2 = [0, 1], v_3 = [1, 1].

    الـ query هو q = [1, 0]. الـ keys: k_1 = [1, 0]، k_2 = [0, 1]، k_3 = [1, 1]. الـ values: v_1 = [1, 0]، v_2 = [0, 1]، v_3 = [1, 1].

  2. Raw scoresالدرجات الخام

    q · k_1 = 1, q · k_2 = 0, q · k_3 = 1·1 + 0·1 = 1.

    q · k_1 = 1، q · k_2 = 0، q · k_3 = 1·1 + 0·1 = 1.

  3. Scale by √d_k = √2 ≈ 1.414القسمة على √d_k = √2 ≈ 1.414

    1/√2 = 0.707, 0, 0.707.

    1/√2 = 0.707، 0، 0.707.

  4. Exponentiate and normalizeاحسب الأُسّ ثم طبّع

    exp(0.707) = 2.028, exp(0) = 1, exp(0.707) = 2.028. The sum is 5.056, so α = [0.401, 0.198, 0.401], which sums to one.

    exp(0.707) = 2.028، exp(0) = 1، exp(0.707) = 2.028. المجموع 5.056، إذن α = [0.401, 0.198, 0.401]، ومجموعها واحد.

  5. Mix the valuesامزج الـ values

    y = 0.401·[1, 0] + 0.198·[0, 1] + 0.401·[1, 1] = [0.401 + 0.401, 0.198 + 0.401].

    y = 0.401·[1, 0] + 0.198·[0, 1] + 0.401·[1, 1] = [0.401 + 0.401, 0.198 + 0.401].

  6. Resultالنتيجة

    y = [0.802, 0.599]. Keys 1 and 3 match the query equally and share most of the weight. Key 2 is orthogonal to the query, yet it still gets 0.198: softmax never gives exactly zero to a finite score.

    y = [0.802, 0.599]. الـ keys رقم 1 و3 يطابقان الـ query بالقدر نفسه ويتقاسمان معظم الوزن. الـ key رقم 2 متعامد (orthogonal) على الـ query، ومع ذلك يحصل على 0.198: الـ softmax لا يعطي صفرًا تامًا أبدًا لدرجة محدودة (finite).

Reproduce the example in the calculator, then change one key and watch the weights move. Make k_2 = [3, 0] and the second token’s weight jumps from 0.198 to 0.673. The causal toggle belongs to the last concept of this part; come back to it there.

أعد إنتاج المثال في الآلة الحاسبة، ثم غيّر key واحدًا وراقب الأوزان وهي تتحرك. اجعل k_2 = [3, 0] فيقفز وزن الـ token الثاني من 0.198 إلى 0.673. أما مفتاح الـ causal فينتمي إلى آخر مفهوم في هذا الجزء؛ عُد إليه هناك.

SimulatorمحاكيScaled dot-product attention for one queryانتباه الضرب النقطي المُحجَّم لاستعلام واحد

Three tokens with d_k = 2. The page computes q · k_j, divides by √2, applies softmax across the visible keys, and mixes the values into y. With the causal mask on, the query sits at position i and every key with j > i gets -∞.ثلاثة رموز مع d_k = 2. تحسب الصفحة q · k_j، ثم تقسم على √2، وتطبّق softmax على المفاتيح المرئية، وتمزج القيم لتُنتج y. عند تفعيل القناع السببي يقع الاستعلام في الموضع i، ويأخذ كل مفتاح يحقق j > i القيمة -∞.

Query q
Token 1
Token 2
Token 3
keyq · k÷ √d_kweight α
  • j = 11.0000.7070.401
  • j = 20.0000.0000.198
  • j = 31.0000.7070.401
Output y = Σ α_j v_j[0.802, 0.599]
Softmax denominator5.056Σ expWeights sum to 1.000

Why divide by √d_kلماذا نقسم على √d_k

Suppose the components of q and k are independent with mean 0 and variance 1. Their dot product is a sum of d_k such products, so it has mean 0 and variance d_k (Vaswani et al., 2017). With d_k = 64, typical scores spread with a standard deviation of 8. Two scores of 16 and 8 give softmax weights of 0.9997 and 0.0003: practically one-hot, and in that flat region of the softmax the gradients are tiny. Divide by √64 = 8 and the scores become 2 and 1, giving 0.731 and 0.269, a distribution that can still learn.

افترض أن مكوّنات q وk مستقلة، متوسطها 0 وتباينها 1. حاصل ضربهما النقطي مجموع d_k من هذه الحواصل، فمتوسطه 0 وتباينه d_k (Vaswani et al., 2017). عندما d_k = 64 تنتشر الدرجات المعتادة بانحراف معياري 8. درجتان قيمتاهما 16 و8 تعطيان أوزان softmax قدرها 0.9997 و0.0003: أي one-hot عمليًا، وفي هذه المنطقة المسطحة من الـ softmax تكون الـ gradients ضئيلة. اقسم على √64 = 8 فتصبح الدرجتان 2 و1، وتعطيان 0.731 و0.269، وهو توزيع ما زال قادرًا على التعلّم.

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

Why does scaled dot-product attention divide QKᵀ by √d_k before the softmax?لماذا يقسم الـ scaled dot-product attention المصفوفة QKᵀ على √d_k قبل الـ softmax؟

Recall

Change the worked example so q = [0, 1]. What are the weights and y?عدّل المثال المحلول بحيث q = [0, 1]. ما الأوزان وما قيمة y؟

Raw scores 0, 1, 1; scaled 0, 0.707, 0.707; exponentials 1, 2.028, 2.028 with sum 5.056; α = [0.198, 0.401, 0.401]. Then y = 0.198·[1, 0] + 0.401·[0, 1] + 0.401·[1, 1] = [0.599, 0.802].

الدرجات الخام 0, 1, 1؛ بعد القسمة 0, 0.707, 0.707؛ الأُسّيات 1, 2.028, 2.028 ومجموعها 5.056؛ α = [0.198, 0.401, 0.401]. ثم y = 0.198·[1, 0] + 0.401·[0, 1] + 0.401·[1, 1] = [0.599, 0.802].

In “the chef who ran the kitchen tasted the soup”, the word “tasted” needs at least two different things at once: its subject (“chef”, five words back) and its object (“soup”). One softmax row produces one weighted average, and an average that tries to point at both ends up pointing at neither very clearly.

في الجملة “the chef who ran the kitchen tasted the soup” تحتاج الكلمة “tasted” إلى شيئين مختلفين على الأقل في آن واحد: فاعلها (“chef”، على بعد خمس كلمات إلى الوراء) ومفعولها (“soup”). صف واحد من الـ softmax ينتج متوسطًا موزونًا واحدًا، والمتوسط الذي يحاول الإشارة إلى الاثنين معًا ينتهي بألّا يشير إلى أيٍّ منهما بوضوح.

Several attentions side by sideعدة عمليات attention جنبًا إلى جنب

Multi-head attention runs h attention computations in parallel, each with its own projections. Each head can learn a different relation: one tracks subjects, another nearby words, another coreference. The heads sit at the same depth and see the same input; they differ only in their weights.

الـ multi-head attention يشغّل h عمليات attention بالتوازي، لكلٍّ منها إسقاطاتها الخاصة. يستطيع كل رأس أن يتعلم علاقة مختلفة: رأس يتتبع الفاعل، وآخر الكلمات المجاورة، وثالث الإحالة المشتركة (coreference). الرؤوس تقع على العمق نفسه وترى الدخل نفسه؛ ولا تختلف إلا في أوزانها.

Qi=XWiQ,Ki=XWiK,Vi=XWiV,headi=SelfAttention(Qi,Ki,Vi)Q_i = X W_i^{Q}, \quad K_i = X W_i^{K}, \quad V_i = X W_i^{V}, \qquad \text{head}_i = \text{SelfAttention}(Q_i, K_i, V_i)
Each head has its own three matricesلكل رأس مصفوفاته الثلاث الخاصة
MultiHeadAttn(X)=(head1⊕head2⊕⋯⊕headh) WO\text{MultiHeadAttn}(X) = (\text{head}_1 \oplus \text{head}_2 \oplus \cdots \oplus \text{head}_h)\, W^{O}
⊕ is concatenation; Wᴼ maps h·d_v back to d⊕ تعني الضم (concatenation)؛ وWᴼ تعيد h·d_v إلى d
d = 512 split across 8 heads of 64, each with its own attention pattern, then concatenated back to 512 and mixed by Wᴼيُقسَّم d = 512 على 8 رؤوس بحجم 64، لكل منها نمط attention خاص به، ثم تُضمّ معًا لتعود إلى 512 ويمزجها Wᴼ

The original transformer uses d = 512 and h = 8, so each head works with d_k = d_v = 512 / 8 = 64. Follow the shapes for a sequence of N tokens:

يستخدم الـ transformer الأصلي d = 512 وh = 8، فيعمل كل رأس بـ d_k = d_v = 512 / 8 = 64. تتبّع الأبعاد لتسلسل من N من الـ tokens:

TermالحدShapeالأبعادMeaningالمعنى
W_i^Q, W_i^K, W_i^VW_i^Q, W_i^K, W_i^V512 × 64512 × 64One set per head, eight sets in totalمجموعة واحدة لكل رأس، أي ثماني مجموعات في المجموع
Q_i, K_i, V_iQ_i, K_i, V_iN × 64N × 64The input rows projected into the head’s own small spaceصفوف الدخل بعد إسقاطها في الفضاء الصغير الخاص بالرأس
Q_i K_iᵀQ_i K_iᵀN × NN × NEvery head has its own full pattern of who looks at whomلكل رأس نمطه الكامل الخاص لمن ينظر إلى من
head_ihead_iN × 64N × 64Weighted sum of that head’s valuesالمجموع الموزون لـ values ذلك الرأس
head_1 ⊕ … ⊕ head_8head_1 ⊕ … ⊕ head_8N × 512N × 512Concatenation: 8 × 64 = 512الضم (concatenation): 8 × 64 = 512
WᴼWᴼ512 × 512512 × 512Mixes the heads and returns to dيمزج الرؤوس ويعيدها إلى d
MultiHeadAttn(X)MultiHeadAttn(X)N × 512N × 512Same shape as X, so blocks can be stackedالأبعاد نفسها التي لـ X، فيمكن رصّ الكتل فوق بعضها
Shapes in one multi-head layer (d = 512, h = 8)الأبعاد في طبقة multi-head واحدة (d = 512، h = 8)

Because each head is a slice of size d/h, the cost barely changes. The eight heads together hold 3 × 8 × 512 × 64 = 786,432 projection weights, exactly the 3 × 512 × 512 of a single full-width head, and Wᴼ adds 262,144, for 1,048,576 in all (ignoring biases). You get eight attention patterns for the price of one.

لأن كل رأس شريحة بحجم d/h، فإن التكلفة بالكاد تتغير. الرؤوس الثمانية معًا تحمل 3 × 8 × 512 × 64 = 786,432 وزنًا للإسقاط، وهو بالضبط 3 × 512 × 512 لرأس واحد بالعرض الكامل، ويضيف Wᴼ مقدار 262,144، فيكون المجموع 1,048,576 (دون احتساب الـ biases). تحصل على ثمانية أنماط attention بثمن نمط واحد.

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

With d = 512 and h = 8 heads, what is the shape of one head's output for N tokens?عندما d = 512 وعدد الرؤوس h = 8، ما أبعاد مخرج رأس واحد لـ N من الـ tokens؟

Recall

What does Wᴼ do, and what are its dimensions for d = 512 and h = 8?ماذا يفعل Wᴼ، وما أبعاده عندما d = 512 وh = 8؟

It takes the concatenated head outputs (N × 512, since 8 × 64 = 512) and mixes information across heads, mapping back to the model dimension. In general it is h·d_v × d, here 512 × 512.

يأخذ مخرجات الرؤوس بعد ضمّها (N × 512، لأن 8 × 64 = 512) ويمزج المعلومات عبر الرؤوس، ويعيدها إلى بُعد النموذج. بشكل عام أبعاده h·d_v × d، وهنا 512 × 512.

Feed “dog bites man” and “man bites dog” into one unmasked self-attention layer with no position information. The vector computed for “dog” is identical in both sentences. Its query meets the same set of keys, and a sum does not care in which order its terms are listed.

أدخل “dog bites man” و“man bites dog” في طبقة self-attention واحدة بلا mask وبلا أي معلومات عن المواضع. المتجه المحسوب لـ “dog” يكون متطابقًا في الجملتين. فالـ query الخاص بها يلتقي بمجموعة الـ keys نفسها، والمجموع لا يبالي بترتيب حدوده.

Attention is blind to orderالـ attention أعمى عن الترتيب

Formally, self-attention is permutation equivariant: shuffle the input rows and the output rows shuffle in exactly the same way, with no value changing. An RNN gets order for free because it reads left to right. A Transformer must be told. The fix on slide 29 is a Positional encoding: a vector for each position, added to the token embedding before the first block.

رياضيًا، الـ self-attention متكافئ مع التبديل (permutation equivariant): بعثِر صفوف الدخل فتتبعثر صفوف المخرج بالطريقة نفسها تمامًا، دون أن تتغير أي قيمة. الـ RNN يحصل على الترتيب مجانًا لأنه يقرأ من اليسار إلى اليمين. أما الـ transformer فيجب أن يُخبَر به. والحل في الشريحة 29 هو positional encoding: متجه لكل موضع يُضاف إلى الـ embedding الخاص بالـ token قبل أول كتلة (block).

xi=ewi+pi,ewi,pi∈Rdx_i = e_{w_i} + p_i, \qquad e_{w_i}, p_i \in \mathbb{R}^{d}
Word embedding plus position vector, same dimension dتضمين الكلمة مضافًا إليه متجه الموضع، بالبعد نفسه d

Addition keeps the dimension at d, so every later matrix keeps its shape. In the figure the green embedding x_1 for “Je” and the yellow position vector t_1 have the same four cells and are summed cell by cell.

الجمع يُبقي البُعد عند d، فتحتفظ كل مصفوفة لاحقة بأبعادها. في الشكل، الـ embedding الأخضر x_1 للكلمة “Je” ومتجه الموضع الأصفر t_1 لهما الخلايا الأربع نفسها، ويُجمعان خلية بخلية.

The sinusoidal recipeالوصفة الجيبية (sinusoidal)

The original transformer uses fixed sines and cosines rather than learned position vectors. Dimension pair (2i, 2i+1) oscillates at its own frequency:

يستخدم الـ transformer الأصلي دوال sin وcos ثابتة بدلًا من متجهات مواضع مُتعلَّمة. كل زوج من الأبعاد (2i, 2i+1) يتذبذب بتردده الخاص:

PE(pos, 2i)=sin⁡ ⁣(pos100002i/d),PE(pos, 2i+1)=cos⁡ ⁣(pos100002i/d)PE_{(pos,\,2i)} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \qquad PE_{(pos,\,2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d}}\right)
Vaswani et al. (2017), Section 3.5Vaswani et al. (2017)، القسم 3.5

The first pair turns fast (one radian per position), later pairs turn ever more slowly, with wavelengths from 2π up to 10000 · 2π. Read together, the pairs act like the hands of a clock: the fast hand distinguishes neighbours, the slow hands distinguish distant positions. Because sin(a + b) and cos(a + b) expand into sines and cosines of a and b, the vector for pos + k is a fixed linear function of the vector for pos, which makes relative offsets easy to learn.

الزوج الأول يدور بسرعة (راديان واحد لكل موضع)، والأزواج اللاحقة تدور أبطأ فأبطأ، بأطوال موجية من 2π حتى 10000 · 2π. إذا قُرئت الأزواج معًا فهي تعمل كعقارب الساعة: العقرب السريع يميّز المواضع المتجاورة، والعقارب البطيئة تميّز المواضع البعيدة. ولأن sin(a + b) وcos(a + b) تُفكّان إلى دوال sin وcos لـ a وb، فإن متجه الموضع pos + k دالة خطية ثابتة لمتجه الموضع pos، وهذا يجعل تعلّم الإزاحات النسبية (relative offsets) سهلًا.

Each dimension is a sinusoid over positions; the encoding of a position is where a vertical line crosses every curve (frequencies schematic)كل بُعد موجة جيبية على امتداد المواضع؛ وترميز الموضع هو النقاط التي يقطع فيها خط رأسي كل منحنى (الترددات توضيحية)

Worked exampleمثال محلول

The paper's formula with d = 4صيغة الورقة عندما d = 4

  1. Frequenciesالترددات

    i = 0: divisor 10000^0 = 1. i = 1: divisor 10000^(2/4) = 100.

    i = 0: المقسوم عليه 10000^0 = 1. i = 1: المقسوم عليه 10000^(2/4) = 100.

  2. Position 1الموضع 1

    [sin 1, cos 1, sin 0.01, cos 0.01] = [0.841, 0.540, 0.010, 1.000].

    [sin 1, cos 1, sin 0.01, cos 0.01] = [0.841, 0.540, 0.010, 1.000].

  3. Position 2الموضع 2

    [sin 2, cos 2, sin 0.02, cos 0.02] = [0.909, -0.416, 0.020, 1.000].

    [sin 2, cos 2, sin 0.02, cos 0.02] = [0.909, -0.416, 0.020, 1.000].

  4. Resultالنتيجة

    Position 0 is always [0, 1, 0, 1]. The fast pair already separates positions 1 and 2 clearly; the slow pair barely moves until positions are far apart.

    الموضع 0 دائمًا [0, 1, 0, 1]. الزوج السريع يفصل بالفعل بين الموضعين 1 و2 بوضوح؛ أما الزوج البطيء فبالكاد يتحرك حتى تتباعد المواضع كثيرًا.

posposPaper (interleaved, 10000^(2i/d))الورقة (تناوب، 10000^(2i/d))Figure (sin half, cos half)الشكل (نصف sin، نصف cos)
00[0, 1, 0, 1][0, 1, 0, 1][0, 0, 1, 1][0, 0, 1, 1]
11[0.841, 0.540, 0.010, 1.000][0.841, 0.540, 0.010, 1.000][0.84, 0.0001, 0.54, 1][0.84, 0.0001, 0.54, 1]
22[0.909, -0.416, 0.020, 1.000][0.909, -0.416, 0.020, 1.000][0.91, 0.0002, -0.42, 1][0.91, 0.0002, -0.42, 1]
d = 4 positional vectors: paper formula versus the slide figureمتجهات الموضع عندما d = 4: صيغة الورقة مقابل شكل الشريحة

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

In an unmasked self-attention layer without positional encoding, what happens to the output for dog when the sentence is shuffled?في طبقة self-attention بلا mask وبلا positional encoding، ماذا يحدث لمخرج dog عندما تُبعثَر الجملة؟

Recall

Compute the paper's positional encoding for pos = 3 with d = 4.احسب الـ positional encoding وفق صيغة الورقة لـ pos = 3 عندما d = 4.

[sin 3, cos 3, sin 0.03, cos 0.03] = [0.141, -0.990, 0.030, 1.000].

[sin 3, cos 3, sin 0.03, cos 0.03] = [0.141, -0.990, 0.030, 1.000].

Translating “the green witch arrived” into Spanish, the decoder has produced “llegó la” and must choose the next word. It needs two sources: what it has written so far, and the full English sentence. Cross-attention is how it reads the second.

عند ترجمة “the green witch arrived” إلى الإسبانية، أنتج الـ decoder “llegó la” وعليه أن يختار الكلمة التالية. يحتاج إلى مصدرين: ما كتبه حتى الآن، والجملة الإنجليزية كاملة. والـ cross-attention هو الطريقة التي يقرأ بها المصدر الثاني.

Queries from the decoder, keys and values from the encoderالـ queries من الـ decoder، والـ keys والـ values من الـ encoder

In an Encoder-decoder (seq2seq) transformer, each decoder block has an extra layer of Cross-attention. It is the same scaled dot-product attention, but the inputs come from two places. The queries are projections of the decoder’s previous layer. The keys and values are projections of the final output of the encoder stack, H^enc, the same for every decoder block.

في transformer من نوع encoder-decoder، تحتوي كل كتلة decoder على طبقة إضافية من الـ cross-attention. إنه الـ scaled dot-product attention نفسه، لكن مدخلاته تأتي من مكانين. الـ queries إسقاطات للطبقة السابقة في الـ decoder. والـ keys والـ values إسقاطات للمخرج النهائي لكومة الـ encoder، H^enc، وهو نفسه لكل كتل الـ decoder.

Q=Hdec[ℓ−1]WQ,K=HencWK,V=HencWVQ = H^{dec[\ell-1]} W^{Q}, \qquad K = H^{enc} W^{K}, \qquad V = H^{enc} W^{V}
SLP3 Eq. 13.11, row formالمعادلة 13.11 في SLP3، بصيغة الصفوف
CrossAttention(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\text{CrossAttention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right) V
Same formula as self-attentionالصيغة نفسها كالانتباه الذاتي

The question comes from the target side (“what do I need next?”); the answers come from the source side. If the source has n tokens and the target has m, then Q is m × d_k, K is n × d_k, and QKᵀ is m × n: one row of weights over the source words for every target position. No causal mask is needed here, because the whole source sentence is known before decoding starts.

السؤال يأتي من جهة الهدف («ماذا أحتاج تاليًا؟»)؛ والإجابات تأتي من جهة المصدر. إذا كان في المصدر n من الـ tokens وفي الهدف m، فإن Q بحجم m × d_k، وK بحجم n × d_k، وQKᵀ بحجم m × n: صف واحد من الأوزان على كلمات المصدر لكل موضع في الهدف. لا حاجة هنا إلى causal mask، لأن جملة المصدر كلها معروفة قبل أن يبدأ فك الترميز (decoding).

Cross-attention: Q rises from the decoder's causal self-attention, while K and V come from the final encoder outputالـ cross-attention: يصعد Q من الـ causal self-attention في الـ decoder، بينما يأتي K وV من المخرج النهائي للـ encoder

The decoder block in orderكتلة الـ decoder بالترتيب

  1. Causal self-attention over the target tokens produced so far.الـ causal self-attention على tokens الهدف التي أُنتجت حتى الآن.
  2. Cross-attention into the encoder output.الـ cross-attention إلى مخرج الـ encoder.
  3. The position-wise feedforward network.شبكة الـ feedforward التي تعمل على كل موضع منفردًا (position-wise).

Each sublayer is wrapped in a Residual connection and Layer normalization, as in the encoder’s Transformer block. The encoder blocks have only the first and last of these, and their self-attention is unmasked.

كل طبقة فرعية مغلّفة بـ residual connection وlayer normalization، كما في الـ transformer block الخاص بالـ encoder. كتل الـ encoder لا تحتوي إلا على الأولى والأخيرة من هذه الطبقات، والـ self-attention فيها بلا mask.

LayerالطبقةQueries fromمصدر الـ queriesKeys and values fromمصدر الـ keys والـ valuesMaskالـ maskScore shapeأبعاد الدرجات
Encoder self-attentionالـ self-attention في الـ encoderEncoder layer belowطبقة الـ encoder السابقةEncoder layer belowطبقة الـ encoder السابقةNone: sees the whole sourceلا يوجد: يرى المصدر كاملًاn × nn × n
Decoder causal self-attentionالـ causal self-attention في الـ decoderDecoder layer belowطبقة الـ decoder السابقةDecoder layer belowطبقة الـ decoder السابقةCausal: j > i set to -∞causal: العناصر التي فيها j > i تُجعل -∞m × mm × m
Cross-attentionالـ cross-attentionDecoder layer belowطبقة الـ decoder السابقةFinal encoder outputالمخرج النهائي للـ encoderNone: the source is fully knownلا يوجد: المصدر معروف بالكاملm × nm × n
The three attentions in an encoder-decoder transformerأنواع الـ attention الثلاثة في transformer من نوع encoder-decoder

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

In the cross-attention layer of a decoder block, where do the queries, keys and values come from?في طبقة الـ cross-attention داخل كتلة الـ decoder، من أين تأتي الـ queries والـ keys والـ values؟

Recall

A source sentence has 6 tokens and the target so far has 4. What is the shape of QKᵀ in cross-attention, and is it masked?جملة مصدر فيها 6 tokens والهدف حتى الآن فيه 4. ما حجم QKᵀ في الـ cross-attention، وهل يُطبَّق عليه mask؟

4 × 6: one row per target position, one column per source token. It is not masked, because the entire source is available from the start.

4 × 6: صف لكل موضع في الهدف، وعمود لكل token في المصدر. لا يُطبَّق عليه mask، لأن المصدر كله متاح منذ البداية.

Train a language model on “the cat sat on the mat” with all six tokens visible to every position. Position 2 has to predict “sat”, and nothing stops it from simply attending to position 3, which is “sat”. Training loss drops to nothing and the model learns to copy, not to predict.

درّب نموذج لغة على “the cat sat on the mat” مع جعل الـ tokens الستة كلها مرئية لكل موضع. على الموضع 2 أن يتنبأ بـ “sat”، ولا شيء يمنعه من أن ينتبه ببساطة إلى الموضع 3، وهو “sat” نفسها. تهبط خسارة التدريب (training loss) إلى لا شيء، ويتعلم النموذج النسخ لا التنبؤ.

Hide everything to the rightأخفِ كل ما على اليمين

Causal self-attention fixes this inside the score matrix. Before the softmax, every entry with j > i (a key in the future of the query) is replaced by -∞. Since exp(-∞) = 0, those keys get exactly zero weight, and row i only mixes v_1 to v_i.

الـ Causal self-attention يعالج هذا داخل مصفوفة الدرجات. قبل الـ softmax، يُستبدل كل عنصر فيه j > i (أي key في مستقبل الـ query) بـ -∞. وبما أن exp(-∞) = 0، تحصل هذه الـ keys على وزن صفر تمامًا، ولا يمزج الصف i إلا v_1 حتى v_i.

softmax⁡ ⁣(QK⊤dk+M)V,Mij={0j≤i−∞j>i\operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}} + M\right) V, \qquad M_{ij} = \begin{cases} 0 & j \le i \\ -\infty & j > i \end{cases}
The mask is added to the N × N scoresيُضاف القناع إلى الدرجات N × N
k1k1k2k2k3k3k4k4
q1q1q1·k1q1·k1-∞-∞-∞-∞-∞-∞
q2q2q2·k1q2·k1q2·k2q2·k2-∞-∞-∞-∞
q3q3q3·k1q3·k1q3·k2q3·k2q3·k3q3·k3-∞-∞
q4q4q4·k1q4·k1q4·k2q4·k2q4·k3q4·k3q4·k4q4·k4
Causal score matrix for N = 4 (before scaling)مصفوفة الدرجات الـ causal عندما N = 4 (قبل القسمة)
N = 4: the lower triangle including the diagonal survives; everything above it is -∞ and gets weight 0N = 4: يبقى المثلث السفلي بما فيه القطر؛ وكل ما فوقه -∞ ويحصل على وزن 0

Read the matrix row by row. Row 1 can only see itself, so its weight on k_1 is always 1. Row 4 sees everything. On slide 31 the left figure shows the same thing as arrows: y_3 receives input from x_1, x_2, x_3 only.

اقرأ المصفوفة صفًّا صفًّا. الصف 1 لا يرى إلا نفسه، فوزنه على k_1 دائمًا 1. والصف 4 يرى كل شيء. في الشريحة 31 يعرض الشكل الأيسر الشيء نفسه على هيئة أسهم: y_3 يتلقى مدخلات من x_1 وx_2 وx_3 فقط.

Try it in the calculator above: switch on the causal mask and set the query at i = 2. Key 3 is now -∞, the remaining weights are 2.028 / 3.028 = 0.670 and 1 / 3.028 = 0.330, and y = [0.670, 0.330].

جرّب ذلك في الآلة الحاسبة أعلاه: فعّل الـ causal mask واجعل الـ query عند i = 2. يصبح الـ key رقم 3 الآن -∞، والأوزان المتبقية 2.028 / 3.028 = 0.670 و1 / 3.028 = 0.330، وy = [0.670, 0.330].

Why this matters beyond correctnessلماذا يهمّ هذا أبعد من مجرد الصحة

The mask is what makes Parallel training possible. With Teacher forcing, the whole correct sentence is fed in at once, and one masked matrix multiplication produces every position’s prediction simultaneously, each one honestly blind to its own answer. An RNN must instead walk through the positions one at a time. At generation time, the same mask matches Autoregressive generation, where future tokens do not exist yet anyway.

الـ mask هو ما يجعل الـ parallel training ممكنًا. مع الـ teacher forcing تُدخَل الجملة الصحيحة كاملة دفعة واحدة، وعملية ضرب مصفوفات واحدة مع الـ mask تنتج تنبؤ كل موضع في آن واحد، وكل تنبؤ أعمى بأمانة عن إجابته. أما الـ RNN فعليه أن يمرّ على المواضع واحدًا تلو الآخر. وفي وقت التوليد يتوافق الـ mask نفسه مع الـ autoregressive generation، حيث لا توجد الـ tokens المستقبلية بعدُ أصلًا.

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

Why does the causal mask place -∞ above the diagonal instead of 0?لماذا يضع الـ causal mask القيمة -∞ فوق القطر بدلًا من 0؟

Recall

In a causal layer with N = 5, how many score entries are kept, and how many are masked?في طبقة causal عندما N = 5، كم عنصرًا من الدرجات يُبقى، وكم عنصرًا يُحجب؟

Kept: the diagonal and below, 1 + 2 + 3 + 4 + 5 = 15. Masked: 25 - 15 = 10. In general N(N+1)/2 kept and N(N-1)/2 masked.

ما يُبقى: القطر وما تحته، 1 + 2 + 3 + 4 + 5 = 15. ما يُحجب: 25 - 15 = 10. وبشكل عام يُبقى N(N+1)/2 ويُحجب N(N-1)/2.

Recapالخلاصة

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

  • Each token is projected three ways: a query that asks, a key that is matched, and a value that is mixed. The three weight matrices are learned.يُسقَط كل token بثلاث طرق: query يسأل، وkey تتم مطابقته، وvalue يُمزَج. والمصفوفات الثلاث للأوزان كلها مُتعلَّمة.
  • Attention(Q, K, V) = softmax(QKᵀ/√d_k)V. QKᵀ is N × N, one score for every pair of positions, and each row of the softmax sums to one.Attention(Q, K, V) = softmax(QKᵀ/√d_k)V. حجم QKᵀ هو N × N، أي درجة واحدة لكل زوج من المواضع، ومجموع كل صف بعد الـ softmax يساوي واحدًا.
  • Dividing by √d_k keeps the variance of the dot products near one, so softmax does not saturate and gradients survive. Slide 27 drops this factor from the per-token score.القسمة على √d_k تُبقي تباين (variance) حواصل الضرب النقطي قريبًا من واحد، فلا يتشبّع الـ softmax وتبقى الـ gradients حيّة. الشريحة 27 تُسقط هذا العامل من درجة الـ token الواحد.
  • Multi-head attention runs h heads with their own W_i^Q, W_i^K, W_i^V, concatenates them and projects with Wᴼ. With d = 512 and h = 8, each head works in 64 dimensions.الـ multi-head attention يشغّل h رؤوس، لكل منها W_i^Q وW_i^K وW_i^V الخاصة به، ثم يضمّها (concatenation) ويُسقطها بـ Wᴼ. عندما d = 512 وh = 8 يعمل كل رأس في 64 بُعدًا.
  • Attention ignores order, so a positional vector of the same size d is added (not concatenated) to each embedding. The sinusoidal version uses sin and cos at geometrically spaced frequencies.الـ attention يتجاهل الترتيب، لذلك يُضاف (لا يُضمّ) متجه موضع بالحجم نفسه d إلى كل embedding. النسخة الجيبية تستخدم sin وcos بترددات متباعدة هندسيًا.
  • Cross-attention: queries from the previous decoder layer, keys and values from the final encoder output. Its score matrix is (target length) × (source length) and is not masked.الـ cross-attention: الـ queries من طبقة الـ decoder السابقة، والـ keys والـ values من المخرج النهائي للـ encoder. مصفوفة درجاته بحجم (طول الهدف) × (طول المصدر) ولا يُطبَّق عليها mask.
  • The causal mask adds -∞ above the diagonal (j > i), so row i only mixes positions 1 to i. This is what lets a decoder train on all positions in parallel.الـ causal mask يضيف -∞ فوق القطر (j > i)، فلا يمزج الصف i إلا المواضع من 1 إلى i. وهذا ما يسمح بتدريب الـ decoder على كل المواضع بالتوازي.

Sourcesالمصادر

Part 07: Decoder-only, encoder-only and encoder-decoder modelsنماذج Decoder-only وEncoder-only وEncoder-decoder

The three ways to build a language model from transformer blocks, what each is trained to do and used for, and why transformer LM training runs in parallel across positions.الطرق الثلاث لبناء نموذج لغة من كتل المحوِّل، وما يُدرَّب عليه كل منها وما يُستخدم له، ولماذا يجري تدريب نماذج اللغة بالمحوِّلات بالتوازي عبر المواضع.

5 concepts5 مفاهيم, ، slides 32-37الشرائح 32-37

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

You now know the transformer block: self-attention, a feedforward layer, residual connections and layer norm. This part answers the natural next question. Given a stack of these blocks, how do you turn it into a language model, and what changes when you want to classify a review, translate a sentence, or chat?

The answer is surprisingly small. The blocks stay the same. What changes is which positions are allowed to attend to which, and what the model is trained to predict. That one wiring choice gives three families: decoder-only models like GPT, encoder-only models like BERT, and encoder-decoder models like the original transformer. Expect a comparison question on the exam: training objective, attention pattern, typical task, and example models for each. Expect a second question on why transformer training parallelizes when RNN training does not. Both are answered here, and the comparison table in the first concept is the page to memorize.

أنت تعرف الآن كتلة الـ transformer: الانتباه الذاتي (self-attention)، وطبقة feedforward، والوصلات المتبقية (residual connections)، وlayer norm. يجيب هذا الجزء عن السؤال الطبيعي التالي: إذا كان لديك مكدس (stack) من هذه الكتل، فكيف تحوّله إلى نموذج لغة، وما الذي يتغير عندما تريد تصنيف مراجعة، أو ترجمة جملة، أو إجراء محادثة؟

الإجابة صغيرة على نحو مفاجئ. الكتل تبقى كما هي. ما يتغير هو أي المواضع يُسمح لها بالانتباه إلى أي مواضع، وما الذي يُدرَّب النموذج على التنبؤ به. هذا الاختيار الواحد في طريقة التوصيل يعطي ثلاث عائلات: نماذج decoder-only مثل GPT، ونماذج encoder-only مثل BERT، ونماذج encoder-decoder مثل الـ transformer الأصلي. توقّع سؤال مقارنة في الامتحان: هدف التدريب، ونمط الانتباه، والمهمة المعتادة، والنماذج الأمثلة لكل عائلة. وتوقّع سؤالًا ثانيًا عن سبب قابلية تدريب الـ transformer للتوازي بينما تدريب الـ RNN ليس كذلك. كلاهما مُجاب عنه هنا، وجدول المقارنة في المفهوم الأول هو الصفحة التي يجب حفظها.

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

  1. Draw the three transformer LM architectures and say which attention links each one has: causal, full, or cross.أن ترسم معماريات نماذج اللغة الثلاث المبنية على الـ transformer وتحدد روابط الانتباه في كل منها: سببي (causal)، أو كامل (full)، أو متقاطع (cross).
  2. Compare decoder-only, encoder-only and encoder-decoder models by training objective, attention pattern, typical task and example models.أن تقارن بين نماذج decoder-only و encoder-only و encoder-decoder من حيث هدف التدريب، ونمط الانتباه، والمهمة المعتادة، والنماذج الأمثلة.
  3. Explain what a masked language model is trained to do and why its outputs are representations rather than words.أن تشرح ما الذي يُدرَّب عليه الـ masked language model، ولماذا تكون مخرجاته تمثيلات (representations) لا كلمات.
  4. Give the three synonyms for decoder-only models and explain what each name says.أن تذكر الأسماء المرادفة الثلاثة لنماذج decoder-only وتشرح ما يعنيه كل اسم.
  5. Explain why transformer LM training runs in parallel across positions while generation stays sequential, and compute the averaged loss for a short sentence.أن تشرح لماذا يجري تدريب نموذج اللغة المبني على الـ transformer بالتوازي عبر المواضع بينما يبقى التوليد تسلسليًا، وأن تحسب متوسط الخسارة لجملة قصيرة.

Take the phrase So long and thanks for, five tokens, and push it through one layer of a transformer. Each position produces an output vector by attending to other positions. The only design decision left is this: when position 3 (the word and) builds its output, which of the five inputs may it look at?

خذ العبارة So long and thanks for، وهي خمسة رموز (tokens)، ومرّرها عبر طبقة واحدة من transformer. كل موضع ينتج متجه مخرجات بالانتباه إلى مواضع أخرى. القرار التصميمي الوحيد المتبقي هو: عندما يبني الموضع 3 (الكلمة and) مخرجاته، فإلى أي من المدخلات الخمسة يُسمح له أن ينظر؟

One block, three wiringsكتلة واحدة، ثلاث طرق توصيل

There are exactly three useful answers, and each defines a model family that slide 33 draws side by side.

هناك ثلاث إجابات مفيدة بالضبط، وكل منها تحدد عائلة من النماذج ترسمها الشريحة 33 جنبًا إلى جنب.

  1. Only to the left. Position 3 may read positions 1, 2 and 3, never 4 or 5. This is causal (masked) self-attention, and the model built from it is a decoder-only model. Because it never sees the future, it can be trained to predict the next word, and it can generate text. In the slide figure every arrow points straight up or up and to the right.إلى اليسار فقط. يمكن للموضع 3 أن يقرأ المواضع 1 و2 و3، ولا يقرأ أبدًا 4 أو 5. هذا هو causal (masked) self-attention أي الانتباه الذاتي السببي (المقنّع)، والنموذج المبني عليه هو decoder-only model. ولأنه لا يرى المستقبل أبدًا، يمكن تدريبه على التنبؤ بالكلمة التالية، ويمكنه توليد النص. في شكل الشريحة، كل سهم يتجه إلى الأعلى مباشرة أو إلى الأعلى واليمين.
  2. Everywhere. Position 3 may read all five positions, left and right. This is ordinary bidirectional self-attention, and the model is an encoder-only model. Its arrows in the figure cross in both directions. Seeing the future makes next-word prediction trivial (the answer is in the input), so it is trained on a different task, and its outputs are drawn as empty ovals: vectors that represent each token in context, not predicted words.في كل مكان. يمكن للموضع 3 أن يقرأ المواضع الخمسة كلها، يسارًا ويمينًا. هذا هو self-attention العادي ثنائي الاتجاه، والنموذج هو encoder-only model. أسهمه في الشكل تتقاطع في الاتجاهين. رؤية المستقبل تجعل التنبؤ بالكلمة التالية أمرًا تافهًا (فالإجابة موجودة في المدخلات)، لذلك يُدرَّب على مهمة مختلفة، وتُرسم مخرجاته كأشكال بيضاوية فارغة: متجهات تمثل كل رمز في سياقه، لا كلمات متنبأ بها.
  3. Two stacks talking. An encoder reads a whole source sequence bidirectionally. A separate decoder writes the target sequence causally, and every decoder position also reads every final encoder state through cross-attention. This is the encoder-decoder transformer. In the figure, the fan of lines from the left stack to the top of the right stack is cross-attention.مكدسان يتحاوران. يقرأ encoder تسلسل المصدر كاملًا بشكل ثنائي الاتجاه. ويكتب decoder منفصل التسلسل الهدف بشكل سببي، وكل موضع في الـ decoder يقرأ أيضًا كل حالة نهائية للـ encoder عبر cross-attention. هذا هو الـ transformer من نوع encoder-decoder. في الشكل، مروحة الخطوط الممتدة من المكدس الأيسر إلى أعلى المكدس الأيمن هي الـ cross-attention.
Same five-by-five grid of query rows and key columns: the causal mask keeps the lower triangle (15 links) and sets the rest to minus infinity, while a bidirectional encoder keeps all 25الشبكة نفسها بحجم خمسة في خمسة من صفوف الاستعلامات (queries) وأعمدة المفاتيح (keys): القناع السببي يُبقي المثلث السفلي (15 رابطًا) ويضع الباقي سالب ما لا نهاية، بينما يُبقي الـ encoder ثنائي الاتجاه الروابط الـ 25 كلها

The grid makes the difference countable. With NN tokens, bidirectional attention computes N2N^2 scores. Causal attention keeps only N(N+1)/2N(N+1)/2 of them, because every score with key position j>ij > i is replaced by −∞-\infty before the softmax, which turns it into a weight of exactly zero. For N = 5 that is 15 of 25.

تجعل الشبكة الفرق قابلًا للعدّ. مع NN رمزًا، يحسب الانتباه ثنائي الاتجاه N2N^2 درجة (score). أما الانتباه السببي فيُبقي N(N+1)/2N(N+1)/2 منها فقط، لأن كل درجة يكون فيها موضع المفتاح j>ij > i تُستبدل بـ −∞-\infty قبل الـ softmax، مما يحوّلها إلى وزن يساوي صفرًا تمامًا. عندما N = 5 يكون ذلك 15 من 25.

SimulatorمحاكيArchitecture switcher: who attends to whom?مبدّل المعماريات: من ينتبه إلى من؟
Solongandthanksforlongandthanksforall
  • Causal self-attentionانتباه ذاتي سببي

Click an output position at the top to keep only the links it reads from.انقر على موضع مخرج في الأعلى لتُبقي فقط الروابط التي يقرأ منها.

Training objectiveهدف التدريب
Predict the next word from the words to its left.التنبؤ بالكلمة التالية من الكلمات التي على يسارها.
Attention patternنمط الانتباه
Causal: position i sees positions 1 to i only.سببي: الموضع i يرى المواضع من 1 إلى i فقط.
Typical tasksالمهام النموذجية
Generation: chat, completion, story writing.التوليد: المحادثة، والإكمال، وكتابة القصص.
Examplesأمثلة
GPT family, GPT-2
Attention links shown15
Focused position readsnone

The comparison to memorizeالمقارنة التي يجب حفظها

ArchitectureالمعماريةAlso calledتُسمى أيضًاAttention patternنمط الانتباهTraining objectiveهدف التدريبOutput per positionالمخرج في كل موضعTypical tasksالمهام المعتادةExamplesأمثلة
Decoder-onlyDecoder-onlyCausal, autoregressive or left-to-right LLMنموذج LLM سببي (causal)، أو ذاتي الانحدار (autoregressive)، أو من اليسار إلى اليمين (left-to-right)Causal self-attention: position i sees 1 to iCausal self-attention: الموضع i يرى المواضع من 1 إلى iPredict the next wordالتنبؤ بالكلمة التاليةA probability over the vocabulary at every positionتوزيع احتمالي على المفردات في كل موضعGeneration: chat, completion, writingالتوليد: المحادثة، والإكمال، والكتابةGPT familyعائلة GPT
Encoder-onlyEncoder-onlyMasked language model (MLM), bidirectional encoderنموذج لغة مقنّع (masked language model أو MLM)، أو encoder ثنائي الاتجاهFull self-attention: every position sees every positionانتباه ذاتي كامل (full self-attention): كل موضع يرى كل المواضعPredict masked words from both sidesالتنبؤ بالكلمات المقنّعة من الجانبينOne contextual vector per tokenمتجه سياقي (contextual vector) واحد لكل رمزClassification and tagging after fine-tuning (sentiment, NER)التصنيف والوسم بعد الـ fine-tuning (تحليل المشاعر sentiment، وNER)BERT, RoBERTaBERT, RoBERTa
Encoder-decoderEncoder-decoderSeq2seq transformertransformer من نوع seq2seqEncoder full; decoder causal plus cross-attention to encoder statesالـ encoder كامل، والـ decoder سببي مع cross-attention إلى حالات الـ encoderMap an input sequence to an output sequenceتحويل تسلسل مدخلات إلى تسلسل مخرجاتOutput words, generated left to rightكلمات المخرج، تُولَّد من اليسار إلى اليمينMachine translation, speech recognition, summarizationالترجمة الآلية، والتعرف على الكلام، والتلخيصOriginal transformer, T5, BART, Whisperالـ transformer الأصلي، وT5، وBART، وWhisper
Three transformer language model architecturesثلاث معماريات لنماذج اللغة المبنية على الـ transformer

Recall

For each architecture, which attention links exist: causal, full bidirectional, or cross?في كل معمارية، ما روابط الانتباه الموجودة: سببية، أم ثنائية الاتجاه كاملة، أم متقاطعة (cross)؟

Decoder-only: causal only (position i attends to 1 to i). Encoder-only: full bidirectional only (every position attends to every position). Encoder-decoder: full bidirectional in the encoder, causal in the decoder, and cross-attention from every decoder position to every final encoder state.
Decoder-only: سببية فقط (الموضع i ينتبه إلى المواضع من 1 إلى i). Encoder-only: ثنائية الاتجاه كاملة فقط (كل موضع ينتبه إلى كل موضع). Encoder-decoder: ثنائية الاتجاه كاملة في الـ encoder، وسببية في الـ decoder، وcross-attention من كل موضع في الـ decoder إلى كل حالة نهائية للـ encoder.

Hide one word: So long [MASK] thanks for all the fish. You can fill the gap with and almost instantly, and you used both sides to do it. So long on the left suggests a farewell, and thanks on the right demands a conjunction. A model that may only look left would have to guess from So long alone.

أخفِ كلمة واحدة: So long [MASK] thanks for all the fish. يمكنك ملء الفراغ بـ and فورًا تقريبًا، وقد استخدمت الجانبين لفعل ذلك. فـ So long على اليسار توحي بالوداع، وthanks على اليمين تتطلب أداة عطف. أما النموذج الذي لا يُسمح له إلا بالنظر إلى اليسار فعليه أن يخمّن من So long وحدها.

A masked language model fills [MASK] using context from both sides: arcs from the left and from the right converge on the hidden wordيملأ الـ masked language model الرمز [MASK] مستخدمًا السياق من الجانبين: أقواس من اليسار ومن اليمين تلتقي عند الكلمة المخفية

What an encoder is trained to doما الذي يُدرَّب عليه الـ encoder

That gap-filling game is the training objective of the most popular encoders, the masked language models (MLMs) of the BERT family. A bidirectional encoder cannot be trained to predict the next word, because full attention would let each position simply read the next word from the input. So the input is corrupted instead. In BERT, 15% of the tokens are chosen for prediction. Of those, 80% are replaced by the special token [MASK], 10% by a random word, and 10% are left unchanged. The model then predicts the original token at each chosen position, using cross-entropy as before. The targets come from the raw text itself, so this is still self-supervised training.

لعبة ملء الفراغات هذه هي هدف التدريب لأشهر الـ encoders، أي نماذج اللغة المقنّعة (masked language models أو MLMs) من عائلة BERT. لا يمكن تدريب encoder ثنائي الاتجاه على التنبؤ بالكلمة التالية، لأن الانتباه الكامل يسمح لكل موضع بأن يقرأ الكلمة التالية ببساطة من المدخلات. لذلك تُفسَد المدخلات بدلًا من ذلك. في BERT يُختار 15% من الرموز للتنبؤ بها. ومن هذه، يُستبدل 80% بالرمز الخاص [MASK]، و10% بكلمة عشوائية، و10% تُترك دون تغيير. ثم يتنبأ النموذج بالرمز الأصلي في كل موضع مختار، مستخدمًا cross-entropy كما سبق. الأهداف تأتي من النص الخام نفسه، لذلك يظل هذا self-supervised training أي تدريبًا ذاتي الإشراف.

Representations, then fine-tuningتمثيلات، ثم fine-tuning

The purpose of an encoder is not to generate text. Its output is one contextual vector per input token, the ovals at the top of the encoder panel on slide 33. The vector for bank in river bank differs from the one in bank loan, because each was built by attending to the whole sentence. To use these vectors, you add a small task head and continue training on labeled data, which is fine-tuning. For sentiment, a classifier reads one vector that summarizes the sentence and outputs positive or negative. For named entity recognition, a classifier reads every token's vector and outputs a tag such as person or location.

الغرض من الـ encoder ليس توليد النص. مخرجاته متجه سياقي واحد لكل رمز من المدخلات، وهي الأشكال البيضاوية في أعلى لوحة الـ encoder في الشريحة 33. متجه bank في river bank (ضفة النهر) يختلف عن متجهها في bank loan (قرض بنكي)، لأن كلًا منهما بُني بالانتباه إلى الجملة كاملة. ولاستخدام هذه المتجهات، تضيف رأسًا صغيرًا للمهمة (task head) وتواصل التدريب على بيانات موسومة، وهذا هو fine-tuning. في تحليل المشاعر (sentiment)، يقرأ مصنِّف متجهًا واحدًا يلخص الجملة ويُخرج إيجابي أو سلبي. وفي التعرف على الكيانات المسماة (named entity recognition)، يقرأ مصنِّف متجه كل رمز ويُخرج وسمًا مثل شخص أو مكان.

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

What is the pretraining objective of a BERT-style encoder-only model?ما هدف التدريب المسبق (pretraining) لنموذج encoder-only على طريقة BERT؟

Translate merci pour tout into English. The output, thanks for everything, is a new sequence in a different language, and its length need not match the input. Neither family so far fits cleanly. An encoder alone outputs one vector per French word, not English words. A decoder alone can write English, but it has no special place for a source sentence it must stay faithful to.

ترجم merci pour tout إلى الإنجليزية. المخرج، thanks for everything، تسلسل جديد بلغة مختلفة، ولا يلزم أن يطابق طوله طول المدخل. لا تناسب أي من العائلتين السابقتين هذه المهمة بشكل نظيف. فالـ encoder وحده يُخرج متجهًا واحدًا لكل كلمة فرنسية، لا كلمات إنجليزية. والـ decoder وحده يستطيع كتابة الإنجليزية، لكن ليس لديه مكان خاص لجملة مصدر يجب أن يبقى وفيًا لها.

Read everything, then write left to rightاقرأ كل شيء، ثم اكتب من اليسار إلى اليمين

The encoder-decoder transformer is trained to map one sequence to another. The encoder reads the entire source bidirectionally, exactly like an encoder-only model, and produces one contextual vector per source token. The decoder generates the target one token at a time with causal self-attention over the target words so far. Between the two sits cross-attention: in each decoder block, the queries come from the decoder, while the keys and values come from the final encoder output. So when the decoder is about to write everything, it can put most of its attention weight on tout.

يُدرَّب الـ transformer من نوع encoder-decoder على تحويل تسلسل إلى تسلسل آخر. يقرأ الـ encoder المصدر كاملًا بشكل ثنائي الاتجاه، تمامًا مثل نموذج encoder-only، وينتج متجهًا سياقيًا واحدًا لكل رمز في المصدر. ويولّد الـ decoder الهدف رمزًا بعد رمز مع causal self-attention على الكلمات الهدف حتى الآن. وبين الاثنين يوجد cross-attention: في كل كتلة decoder تأتي الاستعلامات (queries) من الـ decoder، بينما تأتي المفاتيح والقيم (keys وvalues) من المخرج النهائي للـ encoder. لذلك عندما يوشك الـ decoder على كتابة everything، يستطيع أن يضع معظم وزن انتباهه على tout.

CrossAttn(Hdec,Henc)=softmax ⁣((HdecWQ)(HencWK)⊤dk)HencWV\text{CrossAttn}(H^{dec}, H^{enc}) = \mathrm{softmax}\!\left(\frac{(H^{dec}W^Q)(H^{enc}W^K)^{\top}}{\sqrt{d_k}}\right) H^{enc}W^V
Queries from the decoder, keys and values from the encoderالاستعلامات من المفكِّك، والمفاتيح والقيم من المرمِّز (encoder)

This is the same encoder-decoder idea you met with RNNs, with one big repair. An RNN encoder squeezed the whole source into a single final hidden state, a bottleneck for long sentences. A transformer decoder can look at every encoder state directly, at every step, with its own attention weights. It is also the architecture of the original transformer paper, which was built for machine translation.

هذه هي فكرة الـ encoder-decoder نفسها التي قابلتها مع الـ RNNs، مع إصلاح كبير واحد. كان encoder الـ RNN يضغط المصدر كله في حالة مخفية نهائية واحدة (hidden state)، وهذا عنق زجاجة للجمل الطويلة. أما decoder الـ transformer فيستطيع النظر إلى كل حالة من حالات الـ encoder مباشرة، في كل خطوة، بأوزان انتباه خاصة به. وهي أيضًا معمارية ورقة الـ transformer الأصلية، التي بُنيت للترجمة الآلية.

Where it is usedأين يُستخدم

  • Machine translation: one language in, another language out. The canonical seq2seq task.الترجمة الآلية: لغة تدخل، ولغة أخرى تخرج. إنها مهمة الـ seq2seq النموذجية.
  • Speech recognition: a sequence of acoustic feature frames in, a sequence of words out. Whisper is an encoder-decoder transformer of this kind.التعرف على الكلام: تسلسل من إطارات الخصائص الصوتية (acoustic feature frames) يدخل، وتسلسل من الكلمات يخرج. وWhisper هو transformer من نوع encoder-decoder من هذا الصنف.
  • Other sequence-to-sequence text tasks such as summarization, which T5 and BART handle by casting every task as text in, text out.مهام نصية أخرى من نوع تسلسل إلى تسلسل مثل التلخيص، التي يتعامل معها T5 وBART بصياغة كل مهمة على أنها نص يدخل ونص يخرج.

Recall

In an encoder-decoder transformer, where do the queries, keys and values of cross-attention come from, and which parts are causal?في transformer من نوع encoder-decoder، من أين تأتي الـ queries والـ keys والـ values في الـ cross-attention، وأي الأجزاء سببية؟

Queries come from the decoder; keys and values come from the final encoder output. The encoder is bidirectional; the decoder's own self-attention is causal. Cross-attention can read every source position.
الـ queries تأتي من الـ decoder، والـ keys والـ values تأتي من المخرج النهائي للـ encoder. الـ encoder ثنائي الاتجاه، والـ self-attention الخاص بالـ decoder سببي. والـ cross-attention يستطيع قراءة كل موضع في المصدر.

Type So long and thanks into a chatbot. To continue, it must choose the next word using only what is already written, because nothing to the right exists yet. It picks for, appends it, and repeats. This is the whole job of a decoder-only model, and it is how GPT-style LLMs work.

اكتب So long and thanks في روبوت محادثة. ليكمل، يجب أن يختار الكلمة التالية مستخدمًا فقط ما كُتب بالفعل، لأنه لا شيء موجود على اليمين بعد. فيختار for، ويضيفها، ويكرر. هذه هي وظيفة نموذج decoder-only كلها، وهكذا تعمل نماذج LLMs على طريقة GPT.

Three names, one modelثلاثة أسماء، نموذج واحد

A decoder-only model predicts words left to right. The slides list its three other names, and each one describes a different face of the same rule.

الـ decoder-only model يتنبأ بالكلمات من اليسار إلى اليمين. تذكر الشرائح أسماءه الثلاثة الأخرى، وكل اسم يصف وجهًا مختلفًا للقاعدة نفسها.

  • Causal LLM: the output at position i depends only on causes, positions 1 to i, never on effects to its right. This is the causal mask.Causal LLM (سببي): المخرج في الموضع i يعتمد فقط على الأسباب، أي المواضع من 1 إلى i، ولا يعتمد أبدًا على النتائج التي على يمينه. هذا هو causal mask.
  • Autoregressive LLM: each generated token is fed back as input for the next one, so the model regresses on its own previous outputs. This is autoregressive generation.Autoregressive LLM (ذاتي الانحدار): كل رمز مولَّد يُعاد إدخاله كمدخل للرمز التالي، فالنموذج ينحدر (regresses) على مخرجاته السابقة نفسها. هذا هو autoregressive generation.
  • Left-to-right LLM: the direction in which it reads and writes. For Arabic text the order is really first-to-last token in reading order, which is right to left on the page; the model does not care about screen direction, only sequence order.Left-to-right LLM (من اليسار إلى اليمين): الاتجاه الذي يقرأ ويكتب به. في النص العربي يكون الترتيب في الحقيقة من الرمز الأول إلى الأخير بترتيب القراءة، وهو من اليمين إلى اليسار على الصفحة. النموذج لا يهتم باتجاه الشاشة، بل بترتيب التسلسل فقط.
P(w1:n)=∏t=1nP(wt∣w1:t−1)P(w_{1:n}) = \prod_{t=1}^{n} P(w_t \mid w_{1:t-1})
The chain rule a decoder-only model implements: each factor is one position's next-word distributionقاعدة السلسلة التي ينفذها نموذج decoder-only: كل عامل هو توزيع الكلمة التالية لموضع واحد

The training objective is the one from the RNN language model: at every position, predict the next word, and pay −log⁡y^[wtrue]-\log \hat{y}[w_{\text{true}}]. Why is it called a decoder when there is no encoder? It is the decoder half of the original encoder-decoder transformer with the cross-attention removed. The original transformer came first; the decoder-only language model was carved out of it later.

هدف التدريب هو نفسه هدف نموذج اللغة المبني على الـ RNN: في كل موضع، تنبأ بالكلمة التالية، وادفع −log⁡y^[wtrue]-\log \hat{y}[w_{\text{true}}]. لماذا يُسمى decoder مع أنه لا يوجد encoder؟ لأنه نصف الـ decoder من الـ transformer الأصلي من نوع encoder-decoder بعد إزالة الـ cross-attention. الـ transformer الأصلي جاء أولًا، ثم اقتُطع منه نموذج اللغة decoder-only لاحقًا.

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

Which name describes a decoder-only transformer language model?أي اسم يصف نموذج لغة transformer من نوع decoder-only؟

PracticeتدريبPick the architecture for the taskاختر المعمارية المناسبة للمهمة

Label a product review as positive or negative.تصنيف مراجعة منتج بأنها إيجابية أو سلبية.

Ask two questions: is the whole input known before you answer, and is the output a label or new text?اسأل سؤالين: هل المدخل كله معروف قبل أن تجيب، وهل المخرج تصنيف أم نص جديد؟

Task1 / 6
Score0 / 0

Recall

Give the three synonyms for decoder-only models and say what each one emphasizes.اذكر الأسماء المرادفة الثلاثة لنماذج decoder-only وقل ما الذي يبرزه كل منها.

Causal LLM: each position depends only on earlier positions (the causal mask). Autoregressive LLM: generated tokens are fed back as the next input. Left-to-right LLM: the order in which it reads and predicts.
Causal LLM: كل موضع يعتمد فقط على المواضع السابقة (القناع السببي). Autoregressive LLM: الرموز المولَّدة تُعاد إدخالها كمدخل تالٍ. Left-to-right LLM: الترتيب الذي يقرأ ويتنبأ به.

Train an RNN language model on So long and thanks for all. It must compute hidden state 1, then use it for hidden state 2, then 3: five dependent steps, each waiting for the last. A transformer computes all five positions' predictions, and all five losses, in a single forward pass. Slide 37 states the payoff in one line: training can be in parallel.

درّب نموذج لغة مبنيًا على RNN على So long and thanks for all. يجب أن يحسب الحالة المخفية 1، ثم يستخدمها للحالة المخفية 2، ثم 3: خمس خطوات متتابعة يعتمد بعضها على بعض، كل منها تنتظر سابقتها. أما الـ transformer فيحسب تنبؤات المواضع الخمسة كلها، والخسائر الخمس كلها، في تمرير أمامي واحد. تذكر الشريحة 37 الفائدة في سطر واحد: يمكن أن يكون التدريب متوازيًا.

Why the positions do not have to wait for each otherلماذا لا تحتاج المواضع إلى انتظار بعضها

Two facts combine. First, teacher forcing: during training the input at every position is the true previous text, not the model's own guess, so the entire input row So long and thanks for and the entire target row long and thanks for all are known before the pass begins. Second, the causal mask: although all five positions are computed together as one matrix product, position 2 cannot attend to positions 3 to 5, so it never sees its own target and. Each position is therefore an honest next-word prediction, and all of them are computed at once. An input of N tokens, with the target row shifted one place to the right, gives N training examples per forward pass. That is parallel training, and it is what made pretraining on enormous corpora practical.

حقيقتان تجتمعان. الأولى teacher forcing: أثناء التدريب يكون المدخل في كل موضع هو النص السابق الحقيقي، لا تخمين النموذج نفسه، لذلك يكون صف المدخلات كاملًا So long and thanks for وصف الأهداف كاملًا long and thanks for all معروفين قبل بدء التمرير. الثانية causal mask: مع أن المواضع الخمسة تُحسب معًا كضرب مصفوفات واحد، لا يستطيع الموضع 2 الانتباه إلى المواضع من 3 إلى 5، فلا يرى أبدًا هدفه and. لذلك كل موضع هو تنبؤ نزيه بالكلمة التالية، وكلها تُحسب دفعة واحدة. مدخل من N رمزًا، مع إزاحة صف الأهداف موضعًا واحدًا إلى اليمين، يعطي N مثالًا تدريبيًا في كل تمرير أمامي. هذا هو parallel training أي التدريب المتوازي، وهو ما جعل التدريب المسبق على مدوّنات نصية ضخمة أمرًا عمليًا.

The figure on slide 37 shows the pipeline per position: input embedding, the shared transformer block, a linear layer, a softmax over the vocabulary, and a loss box −log⁡ylong-\log y_{\text{long}}, −log⁡yand-\log y_{\text{and}}, and so on. The loss is the cross-entropy from part 4: the negative log of the probability given to the correct next word.

يُظهر الشكل في الشريحة 37 خط المعالجة لكل موضع: تضمين المدخل (input embedding)، ثم transformer block المشتركة، ثم طبقة خطية (linear layer)، ثم softmax على المفردات، ثم صندوق الخسارة −log⁡ylong-\log y_{\text{long}}، −log⁡yand-\log y_{\text{and}}، وهكذا. الخسارة هي cross-entropy من الجزء 4: سالب لوغاريتم الاحتمال المعطى للكلمة التالية الصحيحة.

Put numbers on it. Suppose that in one forward pass the softmax at each position gives the correct next word the probabilities below. All five rows come out of the same pass.

لنضع أرقامًا. افترض أنه في تمرير أمامي واحد يعطي الـ softmax في كل موضع الكلمة التالية الصحيحة الاحتمالات أدناه. الصفوف الخمسة كلها تخرج من التمرير نفسه.

PositionالموضعVisible contextالسياق المرئيTrue next wordالكلمة التالية الصحيحةŷ[w_true]ŷ[w_true]-ln ŷ[w_true]-ln ŷ[w_true]
11SoSolonglong0.200.201.6091.609
22So longSo longandand0.500.500.6930.693
33So long andSo long andthanksthanks0.400.400.9160.916
44So long and thanksSo long and thanksforfor0.800.800.2230.223
55So long and thanks forSo long and thanks forallall0.250.251.3861.386
Per-position losses for So long and thanks for all (natural log)الخسارة في كل موضع للجملة So long and thanks for all (باللوغاريتم الطبيعي)

Worked exampleمثال محلول

Averaging into the training lossحساب المتوسط للحصول على خسارة التدريب

  1. Sum the five lossesاجمع الخسائر الخمس

    1.609 + 0.693 + 0.916 + 0.223 + 1.386 = 4.827
    1.609 + 0.693 + 0.916 + 0.223 + 1.386 = 4.827
  2. Average over positionsخذ المتوسط على المواضع

    L=15∑t=15−log⁡y^t[wt+1]=4.8275≈0.965L = \frac{1}{5}\sum_{t=1}^{5} -\log \hat{y}_t[w_{t+1}] = \frac{4.827}{5} \approx 0.965
    L=15∑t=15−log⁡y^t[wt+1]=4.8275≈0.965L = \frac{1}{5}\sum_{t=1}^{5} -\log \hat{y}_t[w_{t+1}] = \frac{4.827}{5} \approx 0.965
  3. Resultالنتيجة

    The training loss for this sequence is about 0.965, obtained from one pass. Backpropagation then updates all weights from all five positions together. Note where the pain is: position 1, with only So as context, gives long just 0.20 and pays the largest loss.
    خسارة التدريب لهذا التسلسل تساوي تقريبًا 0.965، وقد حصلنا عليها من تمرير واحد. ثم يحدّث الـ backpropagation كل الأوزان من المواضع الخمسة معًا. لاحظ أين يكمن الألم: الموضع 1، الذي سياقه So فقط، يعطي long احتمال 0.20 فقط ويدفع أكبر خسارة.

Generation is still one token at a timeالتوليد ما زال رمزًا واحدًا في كل مرة

At inference time the trick disappears. To write the continuation, the model must sample word t + 1 before it can use it as input for word t + 2. There is no known target row to feed in. Producing N new tokens therefore needs N forward passes in sequence, exactly as in autoregressive generation with an RNN.

عند الاستدلال (inference) تختفي هذه الحيلة. لكتابة التكملة، يجب أن يختار النموذج الكلمة t + 1 قبل أن يستطيع استخدامها كمدخل للكلمة t + 2. لا يوجد صف أهداف معروف لإدخاله. لذلك يحتاج إنتاج N رمزًا جديدًا إلى N تمريرًا أماميًا متتابعًا، تمامًا كما في autoregressive generation مع الـ RNN.

Training lights all five next-word predictions at once in a single pass; generation must produce each token before feeding it back for the nextالتدريب يُضيء تنبؤات الكلمة التالية الخمسة كلها دفعة واحدة في تمرير واحد، أما التوليد فيجب أن ينتج كل رمز قبل إعادة إدخاله للرمز التالي
PhaseالمرحلةRNN LMنموذج لغة RNNTransformer LMنموذج لغة transformer
TrainingالتدريبSequential: each hidden state needs the previous one, so N dependent stepsتسلسلي: كل حالة مخفية تحتاج إلى سابقتها، لذلك توجد N خطوة متتابعة يعتمد بعضها على بعضParallel: all N positions in one pass (teacher forcing plus causal mask)متوازٍ: المواضع الـ N كلها في تمرير واحد (teacher forcing مع القناع السببي)
GenerationالتوليدSequential: one token per stepتسلسلي: رمز واحد في كل خطوةSequential: one token per forward passتسلسلي: رمز واحد في كل تمرير أمامي
RNN versus transformer language modelsنماذج اللغة المبنية على الـ RNN مقابل المبنية على الـ transformer

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

Why can a transformer language model compute every position's loss in one forward pass during training?لماذا يستطيع نموذج لغة مبني على الـ transformer حساب خسارة كل موضع في تمرير أمامي واحد أثناء التدريب؟

Recall

A transformer LM is trained on a 7-token sentence. How many next-word losses does one forward pass produce, and how many forward passes does it take to generate 6 new tokens?يُدرَّب نموذج لغة مبني على الـ transformer على جملة من 7 رموز. كم خسارة للكلمة التالية ينتج تمرير أمامي واحد، وكم تمريرًا أماميًا يلزم لتوليد 6 رموز جديدة؟

Six losses from one forward pass (tokens 1 to 6 each predict the next one; token 7 has no target), averaged into the training loss, just as the 6-word example above gave 5 losses. Generating six new tokens takes six sequential forward passes, because each token must exist before it can be the next input.
ست خسائر من تمرير أمامي واحد (الرموز من 1 إلى 6 يتنبأ كل منها بالرمز التالي، والرمز 7 ليس له هدف)، ويُؤخذ متوسطها لتصبح خسارة التدريب، تمامًا كما أعطى مثال الكلمات الست أعلاه 5 خسائر. وتوليد ستة رموز جديدة يتطلب ستة تمريرات أمامية متتابعة، لأن كل رمز يجب أن يوجد قبل أن يصبح المدخل التالي.

Recapالخلاصة

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

  • The same transformer block builds three model families. The difference is which positions may attend to which.كتلة الـ transformer نفسها تبني ثلاث عائلات من النماذج. والفرق هو أي المواضع يُسمح لها بالانتباه إلى أي مواضع.
  • Decoder-only (causal, autoregressive, left-to-right): causal mask, next-word prediction, used for generation. GPT family.Decoder-only (سببي، ذاتي الانحدار autoregressive، من اليسار إلى اليمين): قناع سببي (causal mask)، والتنبؤ بالكلمة التالية، ويُستخدم للتوليد. عائلة GPT.
  • Encoder-only: full bidirectional attention, trained to predict masked words from both sides, outputs contextual vectors, usually fine-tuned for classification or tagging. BERT family.Encoder-only: انتباه ثنائي الاتجاه كامل، يُدرَّب على التنبؤ بالكلمات المقنّعة من الجانبين، ويُخرج متجهات سياقية (contextual vectors)، وعادة يُعاد ضبطه (fine-tuned) للتصنيف أو الوسم (tagging). عائلة BERT.
  • Encoder-decoder (seq2seq): bidirectional encoder, causal decoder, plus cross-attention from every decoder position to every encoder state. Translation and speech recognition. Original transformer, T5, BART, Whisper.Encoder-decoder (seq2seq): مُرمِّز (encoder) ثنائي الاتجاه، ومفكِّك (decoder) سببي، إضافة إلى cross-attention من كل موضع في الـ decoder إلى كل حالة من حالات الـ encoder. يُستخدم في الترجمة والتعرف على الكلام. الـ transformer الأصلي، و T5، و BART، و Whisper.
  • Two different masks: the causal mask hides future positions inside attention; the [MASK] token hides input words in BERT's training data.قناعان مختلفان: القناع السببي يخفي المواضع المستقبلية داخل الانتباه، ورمز [MASK] يخفي كلمات من المدخلات في بيانات تدريب BERT.
  • Training is parallel: with teacher forcing the whole target sentence is known, and the causal mask stops any position from seeing its own answer, so all N losses -log ŷ[w_true] come out of one forward pass.التدريب متوازٍ: مع teacher forcing تكون الجملة الهدف كلها معروفة، ويمنع القناع السببي أي موضع من رؤية إجابته، فتخرج كل الخسائر الـ N وهي -log ŷ[w_true] من تمرير أمامي (forward pass) واحد.
  • Generation is sequential: token t+1 does not exist until token t has been sampled, so producing N tokens needs N forward passes.التوليد تسلسلي: الرمز t+1 لا يوجد قبل أن يُختار (sampled) الرمز t، لذلك يحتاج توليد N رمزًا إلى N تمريرًا أماميًا.

Sourcesالمصادر

Part 08: The language modeling head, weight tying and end-to-end trainingرأس نمذجة اللغة وربط الأوزان والتدريب من الطرف إلى الطرف

How the final hidden vector becomes a probability over the vocabulary through an unembedding layer tied to the embedding matrix, how a token is sampled, and how the full stacked model is trained with averaged cross-entropy.كيف يتحول المتجه المخفي الأخير إلى احتمال على المفردات عبر طبقة فك التضمين (unembedding) المربوطة بمصفوفة التضمين، وكيف يُسحب رمز (token)، وكيف يُدرَّب النموذج المكدس كاملا بمتوسط الإنتروبيا المتقاطعة.

3 concepts3 مفاهيم, ، slides 38-43الشرائح 38-43

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

Part 7 left a stack of transformer blocks producing one vector per position. This part adds the last piece, the circuit that turns a vector into a word, and then assembles the whole model and trains it. After this part you can draw a transformer language model from the input tokens up to the loss and label every arrow with its shape.

The ideas build in order. First, the language modeling head and its shapes, including the trick of reusing the embedding matrix. Second, how the head closes the generation loop by sampling a token. Third, how the full model is trained end to end. Exam questions here are precise: trace the shapes from h_N^L to y, define weight tying and say why it is used, separate logits from probabilities, and describe training step by step.

انتهى الجزء 7 بمجموعة مكدّسة من كتل transformer تُنتج متجهًا واحدًا لكل موضع. يضيف هذا الجزء القطعة الأخيرة، أي الدائرة التي تحوّل المتجه إلى كلمة، ثم يجمّع النموذج كاملًا ويدرّبه. بعد هذا الجزء ستستطيع رسم نموذج لغة من نوع transformer بدءًا من رموز المدخل وحتى دالة الخسارة، وتكتب على كل سهم أبعاده.

تتسلسل الأفكار بالترتيب. أولًا، رأس نمذجة اللغة وأبعاده، بما في ذلك حيلة إعادة استخدام مصفوفة التضمين (embedding matrix). ثانيًا، كيف يُغلق الرأس حلقة التوليد عبر سحب رمز. ثالثًا، كيف يُدرَّب النموذج كاملًا من البداية إلى النهاية. أسئلة الاختبار هنا دقيقة: تتبّع الأبعاد من h_N^L إلى y، وعرّف ربط الأوزان (weight tying) واذكر سبب استخدامه، وميّز الـlogits عن الاحتمالات، وصِف التدريب خطوة بخطوة.

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

  1. Trace the shapes through the language modeling head: h_N^L is 1 × d, U = Eᵀ is d × |V|, the logits u and the probabilities y are both 1 × |V|.تتبّع الأبعاد عبر رأس نمذجة اللغة: h_N^L بأبعاد 1 × d، وU = Eᵀ بأبعاد d × |V|، وكلٌّ من الـ logits u والاحتمالات y بأبعاد 1 × |V|.
  2. Explain weight tying, why E is reused as Eᵀ at the top, and compute how many parameters it saves.اشرح ربط الأوزان (weight tying)، ولماذا يُعاد استخدام E على هيئة Eᵀ في الأعلى، واحسب عدد المعاملات التي يوفّرها.
  3. Tell logits and probabilities apart, and turn a small logit vector into probabilities by hand.ميّز بين الـ logits والاحتمالات، وحوّل متجه logits صغيرًا إلى احتمالات يدويًا.
  4. Describe how a token is sampled from y and appended, closing the autoregressive generation loop.صِف كيف يُسحب رمز (token) من y ثم يُلحق بالمدخل، فتُغلق بذلك حلقة التوليد الانحداري الذاتي (autoregressive).
  5. Describe end-to-end training of a transformer LM: input encoding, stacked blocks, a head at every position, and the averaged cross-entropy loss.صِف التدريب الكامل من البداية إلى النهاية لنموذج لغة من نوع transformer: ترميز المدخل، والكتل المكدّسة، ورأس عند كل موضع، ودالة خسارة الإنتروبيا المتقاطعة المحسوبة كمتوسط.

Feed the model the words So long and thanks for. After the last of its L transformer blocks, the column above for holds a single vector of d = 768 numbers. That vector has seen the whole context through causal attention, but it is not a word. To predict the next token we need one score for each of the 50,000 tokens in the vocabulary, and then a proper probability for each.

أعطِ النموذج الكلمات So long and thanks for. بعد آخر كتلة من كتل transformer البالغ عددها L، يحمل العمود الواقع فوق for متجهًا واحدًا من d = 768 رقمًا. هذا المتجه رأى السياق كله عبر الانتباه السببي (causal attention)، لكنه ليس كلمة. لكي نتنبأ بالرمز التالي نحتاج إلى درجة (score) واحدة لكل رمز من الرموز البالغ عددها 50,000 في المفردات، ثم إلى احتمال حقيقي لكل منها.

What the head doesماذا يفعل الرأس

The Language modeling head is that missing circuit. It takes h_N^L, the output of the final layer L at the last token N, and outputs a distribution over the vocabulary V. It has exactly two steps: a linear map to one score per word, then a Softmax that turns the scores into probabilities. The word head is borrowed from the general idea of a task-specific circuit placed on top of a pretrained transformer; this one is the head for language modeling. At inference only the last position matters, because only its prediction is new. During training the same head runs at every position, which we return to in the third concept.

رأس نمذجة اللغة language modeling head هو تلك الدائرة الناقصة. يأخذ h_N^L، وهو مخرج الطبقة الأخيرة L عند آخر رمز N، ويُخرج توزيعًا احتماليًا على المفردات V. له خطوتان فقط: تحويل خطي إلى درجة واحدة لكل كلمة، ثم دالة softmax التي تحوّل الدرجات إلى احتمالات. كلمة «رأس» مستعارة من الفكرة العامة لدائرة خاصة بمهمة معينة توضع فوق transformer مدرَّب مسبقًا، وهذا هو الرأس الخاص بنمذجة اللغة. عند الاستدلال (inference) لا يهم إلا الموضع الأخير، لأن تنبؤه وحده هو الجديد. أما أثناء التدريب فيعمل الرأس نفسه عند كل موضع، وسنعود إلى ذلك في المفهوم الثالث.

Trace the shapesتتبّع الأبعاد

Read the head as a chain of matrix products on row vectors. The hidden vector is a row of d numbers. The Unembedding layer U has d rows and |V| columns, so the product has one entry per vocabulary item. Those entries are the Logits. Softmax keeps the shape and changes only the values.

اقرأ الرأس على أنه سلسلة من عمليات ضرب المصفوفات على متجهات صفّية (row vectors). المتجه المخفي صفّ من d رقمًا. ومصفوفة إلغاء التضمين unembedding U لها d صفًّا و|V| عمودًا، لذلك يحتوي حاصل الضرب على عنصر واحد لكل عنصر في المفردات. هذه العناصر هي الـlogits. أما softmax فتحافظ على الأبعاد وتغيّر القيم فقط.

u=hNL E⊤,y=softmax⁡(u)u = h_N^L\,E^{\top}, \qquad y = \operatorname{softmax}(u)
The language modeling head (SLP3 Eq. 7.47 and 7.48)رأس نمذجة اللغة (المعادلتان 7.47 و7.48 في SLP3)
[1×d]⏟hNL  ⋅  [d×∣V∣]⏟U=E⊤  =  [1×∣V∣]⏟u  → softmax   [1×∣V∣]⏟y\underbrace{[1 \times d]}_{h_N^L}\;\cdot\;\underbrace{[d \times |V|]}_{U = E^{\top}} \;=\; \underbrace{[1 \times |V|]}_{u} \;\xrightarrow{\ \text{softmax}\ }\; \underbrace{[1 \times |V|]}_{y}
Inner dimensions d cancel; the vocabulary dimension survivesالأبعاد الداخلية d تختفي؛ ويبقى بعد المفردات

Every object in the head, with the running example d = 768 and |V| = 50,000كل عنصر في الرأس، مع المثال المستمر d = 768 و|V| = 50,000

h_N^L, final layer, last tokenh_N^L، الطبقة الأخيرة، آخر رمز
1 × d (1 × 768)1 × d (1 × 768)
U = Eᵀ, the unembeddingU = Eᵀ، مصفوفة إلغاء التضمين (unembedding)
d × |V| (768 × 50,000)d × |V| (768 × 50,000)
u = h_N^L Eᵀ, the logitsu = h_N^L Eᵀ، الـ logits
1 × |V| (1 × 50,000)1 × |V| (1 × 50,000)
y = softmax(u), the probabilitiesy = softmax(u)، الاحتمالات
1 × |V| (1 × 50,000)1 × |V| (1 × 50,000)
E, the embedding matrixE، مصفوفة التضمين (embedding matrix)
|V| × d (50,000 × 768)|V| × d (50,000 × 768)

There is a useful way to read one logit. Column k of Eᵀ is row k of E, which is the input embedding e_k of word k. So uk=hNL⋅eku_k = h_N^L \cdot e_k: the score of a word is the dot product between the model's final vector and that word's own embedding. The head asks, for every word in the vocabulary, how well its embedding lines up with what the model now wants to say.

هناك طريقة مفيدة لقراءة logit واحد. العمود k من Eᵀ هو الصف k من E، وهو تضمين المدخل e_k للكلمة k. إذن uk=hNL⋅eku_k = h_N^L \cdot e_k: درجة الكلمة هي حاصل الضرب النقطي (dot product) بين المتجه النهائي للنموذج وتضمين تلك الكلمة نفسها. فالرأس يسأل، لكل كلمة في المفردات، إلى أي مدى يتوافق تضمينها مع ما يريد النموذج قوله الآن.

Recall

Without looking: give the shape of h_N^L, U, u and y, and say which dimension cancels in the product.دون أن تنظر: اذكر أبعاد h_N^L وU وu وy، وحدّد أي بُعد يُختصر في حاصل الضرب.

h_N^L is 1 × d, U = Eᵀ is d × |V|, and both u and y are 1 × |V|. The model dimension d cancels in the product, leaving one entry per vocabulary item.

h_N^L أبعاده 1 × d، وU = Eᵀ أبعادها d × |V|، وكلٌّ من u وy أبعاده 1 × |V|. بُعد النموذج d يُختصر في حاصل الضرب، فيبقى عنصر واحد لكل عنصر في المفردات.

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

A model has d = 512 and a vocabulary of 32,000 tokens. What is the shape of its unembedding matrix?نموذج له d = 512 ومفردات من 32,000 رمز. ما أبعاد مصفوفة إلغاء التضمين (unembedding) فيه؟

Weight tying: one matrix, two directionsربط الأوزان (weight tying): مصفوفة واحدة واتجاهان

Look at the bottom of the model. The Embedding matrix E E has one row per token and one column per dimension, so it is |V| × d. A token enters as a one-hot row of shape 1 × |V|; multiplying it by E selects that token's row and gives a 1 × d vector. Now look at the top. The head needs a matrix that goes the other way, from 1 × d back to 1 × |V|. The transpose Eᵀ has exactly that shape. Using it is called Weight tying: the same numbers convert word to vector at the bottom and vector to word scores at the top, which is why SLP3 calls Eᵀ the unembedding.

انظر إلى أسفل النموذج. مصفوفة التضمين embedding matrix E لها صف واحد لكل رمز وعمود واحد لكل بُعد، لذلك أبعادها |V| × d. يدخل الرمز على هيئة صف من نوع one-hot بأبعاد 1 × |V|، وضربه في E يختار صف ذلك الرمز ويعطي متجهًا بأبعاد 1 × d. انظر الآن إلى الأعلى. يحتاج الرأس إلى مصفوفة تسير في الاتجاه المعاكس، من 1 × d عودةً إلى 1 × |V|. والمدوّر Eᵀ له هذه الأبعاد بالضبط. استخدامه يُسمّى ربط الأوزان weight tying: الأرقام نفسها تحوّل الكلمة إلى متجه في الأسفل، وتحوّل المتجه إلى درجات للكلمات في الأعلى، ولهذا يسمّي كتاب SLP3 المصفوفة Eᵀ بالـunembedding (إلغاء التضمين).

Row k of E embeds word k at the bottom; the same numbers, as column k of Eᵀ, score word k at the topالصف k من E يضمّن الكلمة k في الأسفل، والأرقام نفسها، بوصفها العمود k من Eᵀ، تعطي الكلمة k درجتها في الأعلى

Worked exampleمثال محلول

How many parameters does tying save?كم معاملًا يوفّر الربط؟

  1. Size of Eحجم E

    |V| × d = 50,000 × 768 = 38,400,000, about 38.4 M parameters.
    |V| × d = 50,000 × 768 = 38,400,000، أي نحو 38.4 M معامل.
  2. Without tyingبدون ربط

    A separate learned unembedding is another d × |V| matrix, another 38.4 M. Embedding and unembedding together cost 76.8 M.
    مصفوفة unembedding منفصلة ومتعلَّمة هي مصفوفة أخرى بأبعاد d × |V|، أي 38.4 M معامل إضافية. فيكلّف التضمين وإلغاء التضمين معًا 76.8 M معامل.
  3. With tyingمع الربط

    Only E is stored, so the head adds no new weight matrix. The saving is the full 38.4 M, which at 4 bytes per FP32 weight is about 154 MB of memory.
    تُخزَّن E وحدها، فلا يضيف الرأس أي مصفوفة أوزان جديدة. التوفير هو الـ38.4 M كاملة، وهذا يعادل نحو 154 MB من الذاكرة بحساب 4 bytes لكل وزن بدقة FP32.
  4. Resultالنتيجة

    Tying removes 38.4 M parameters. For scale, the smallest GPT-2 has d = 768 and |V| = 50,257, so its embedding alone is about 38.6 M parameters, roughly a third of the whole model, and Hugging Face's GPT-2 head is tied by default.
    الربط يحذف 38.4 M معامل. وللمقارنة، أصغر نسخة من GPT-2 لها d = 768 و|V| = 50,257، لذلك يبلغ التضمين وحده نحو 38.6 M معامل، أي قرابة ثلث النموذج كله، ورأس GPT-2 في Hugging Face مربوط افتراضيًا.

Fewer parameters is the first reason. The second is consistency. With tying, a word gets a high score at the top exactly when the final vector points in the same direction as that word's input embedding, so input and output vectors live in one space. Every gradient that reaches the head also updates E, so rare words whose input rows are seldom used still learn from being predicted. Press and Wolf showed that tying the two matrices lowers perplexity across several language models, Inan, Khosravi and Socher derived the same tie from a loss framework, and the original transformer shares this matrix between its embeddings and its pre-softmax layer.

قلة المعاملات هي السبب الأول. والسبب الثاني هو الاتساق. مع الربط، تحصل الكلمة على درجة عالية في الأعلى تمامًا عندما يشير المتجه النهائي في الاتجاه نفسه لتضمين تلك الكلمة في المدخل، فتعيش متجهات المدخل والمخرج في فضاء واحد. كل تدرّج (gradient) يصل إلى الرأس يحدّث E أيضًا، لذلك فإن الكلمات النادرة التي نادرًا ما تُستخدم صفوفها في المدخل تظل تتعلّم من كونها هدفًا للتنبؤ. بيّن Press وWolf أن ربط المصفوفتين يخفّض الـperplexity في عدة نماذج لغة، واشتق Inan وKhosravi وSocher الربط نفسه من إطار لدالة الخسارة، كما أن الـtransformer الأصلي يشارك هذه المصفوفة بين طبقات التضمين والطبقة التي تسبق softmax.

Recall

State weight tying in one sentence and give its two benefits.عرّف ربط الأوزان (weight tying) في جملة واحدة واذكر فائدتيه.

Weight tying reuses the transpose of the input embedding matrix as the unembedding, U = Eᵀ. It saves a whole |V| × d matrix of parameters, and it keeps input and output word representations in one consistent space, which in practice also tends to improve perplexity.

ربط الأوزان يعيد استخدام مدوّر مصفوفة تضمين المدخل بوصفه مصفوفة إلغاء التضمين، U = Eᵀ. فهو يوفّر مصفوفة كاملة من المعاملات بأبعاد |V| × d، ويُبقي تمثيلات الكلمات في المدخل والمخرج في فضاء واحد متّسق، وهذا يميل عمليًا أيضًا إلى تحسين الـperplexity.

Logits are scores, probabilities are a distributionالـlogits درجات، والاحتمالات توزيع

Shrink the vocabulary to three words and suppose the head produces u = [2.0, 1.0, 0.1]. These numbers are not probabilities. They sum to 3.1, and the head could just as well have produced a negative logit. Softmax fixes both problems: exponentiate each logit so it becomes positive, then divide by the total so the results sum to 1.

قلّص المفردات إلى ثلاث كلمات، وافترض أن الرأس ينتج u = [2.0, 1.0, 0.1]. هذه الأرقام ليست احتمالات. مجموعها 3.1، وكان بإمكان الرأس أيضًا أن ينتج logit سالبًا. تعالج softmax المشكلتين معًا: ارفع كل logit أسيًا ليصبح موجبًا، ثم اقسم على المجموع لكي يكون مجموع النتائج 1.

yk=softmax⁡(u)k=exp⁡(uk)∑j=1∣V∣exp⁡(uj)y_k = \operatorname{softmax}(u)_k = \frac{\exp(u_k)}{\sum_{j=1}^{|V|} \exp(u_j)}
Softmax over the vocabularysoftmax على المفردات

Worked exampleمثال محلول

Softmax of u = [2.0, 1.0, 0.1]حساب softmax للمتجه u = [2.0, 1.0, 0.1]

  1. Exponentiateالرفع الأسي

    e^2.0 = 7.389, e^1.0 = 2.718, e^0.1 = 1.105.
    e^2.0 = 7.389، e^1.0 = 2.718، e^0.1 = 1.105.
  2. Sumالجمع

    7.389 + 2.718 + 1.105 = 11.212.
    7.389 + 2.718 + 1.105 = 11.212.
  3. Normalizeالتطبيع

    7.389 / 11.212 = 0.659, 2.718 / 11.212 = 0.242, 1.105 / 11.212 = 0.099.
    7.389 / 11.212 = 0.659، 2.718 / 11.212 = 0.242، 1.105 / 11.212 = 0.099.
  4. Resultالنتيجة

    y = [0.659, 0.242, 0.099], which sums to 1. The ranking is the same as the logits, but the gaps are exaggerated: a logit gap of 1.0 means a probability ratio of e ≈ 2.72.
    y = [0.659, 0.242, 0.099]، ومجموعها 1. الترتيب هو نفسه ترتيب الـlogits، لكن الفجوات تتضخّم: فرق قدره 1.0 بين logit وآخر يعني نسبة احتمال قدرها e ≈ 2.72.

One consequence is worth knowing for the exam. Adding the same constant to every logit changes nothing: [3.0, 2.0, 1.1] gives the same [0.659, 0.242, 0.099], because the factor e^1 cancels between numerator and denominator. Only differences between logits matter.

هناك نتيجة تستحق أن تعرفها للاختبار. إضافة الثابت نفسه إلى كل logit لا تغيّر شيئًا: [3.0, 2.0, 1.1] تعطي النتيجة نفسها [0.659, 0.242, 0.099]، لأن العامل e^1 يُختصر بين البسط والمقام. الفروق بين الـlogits هي وحدها المهمة.

PropertyالخاصيةLogits uالـ logits uProbabilities yالاحتمالات y
Range of each entryمدى كل عنصرAny real number, negative allowedأي عدد حقيقي، والقيم السالبة مسموحةBetween 0 and 1بين 0 و1
Sum over the vocabularyالمجموع على المفرداتAnythingأي قيمةExactly 1يساوي 1 بالضبط
Add the same constant to allإضافة الثابت نفسه إلى الجميعValues changeتتغير القيمUnchanged (softmax is shift invariant)لا يتغير شيء (لأن softmax لا تتأثر بالإزاحة)
Produced byينتج عنThe unembedding, a linear mapمصفوفة إلغاء التضمين (unembedding)، وهي تحويل خطيSoftmax, a nonlinear normalizationدالة softmax، وهي تطبيع غير خطي
Used forتُستخدم فيRanking, temperature scaling, numerically stable lossالترتيب، والتحجيم بدرجة الحرارة (temperature)، وحساب خسارة مستقرة عدديًاSampling and computing −log ŷالسحب العشوائي (sampling) وحساب −log ŷ
Logits u versus probabilities y, both of shape 1 × |V|الـ logits u مقابل الاحتمالات y، وكلاهما بأبعاد 1 × |V|

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

The head outputs logits u = [1.0, 1.0, 1.0] for a three-word vocabulary. What does softmax return?يُخرج الرأس الـ logits u = [1.0, 1.0, 1.0] لمفردات من ثلاث كلمات. ماذا تُعيد softmax؟

The head has produced y, a probability for every token. The model still has not written anything. Something outside the network has to choose one token, write it down, and ask the model again. That choose-append-repeat cycle is what turns a next-word predictor into a text generator.

أنتج الرأس y، أي احتمالًا لكل رمز. لكن النموذج لم يكتب شيئًا بعد. لا بد أن يقوم شيء خارج الشبكة باختيار رمز واحد، وكتابته، ثم سؤال النموذج من جديد. دورة «اختر، ألحِق، كرّر» هذه هي ما يحوّل أداة التنبؤ بالكلمة التالية إلى مولّد للنصوص.

Sample, append, run againاسحب، ألحِق، شغّل من جديد

Slide 41 draws the finished model in a slightly different notation: the final-layer vector at position i, h_i^L, goes through U and softmax to give the distribution for position i + 1, and a token w_{i+1} is sampled from it. When i is the last position N, this is exactly the head from the previous concept. The sampled token is appended to the input, the model runs again on the longer sequence, and the loop continues until it produces an end token or reaches a length limit. This is Autoregressive generation, the same loop you saw for the RNN language model in Part 3, now driven by a Decoder-only model.

ترسم الشريحة 41 النموذج المكتمل بترميز مختلف قليلًا: متجه الطبقة الأخيرة عند الموضع i، أي h_i^L، يمر عبر U وsoftmax ليعطي التوزيع الخاص بالموضع i + 1، ثم يُسحب منه رمز w_{i+1}. عندما يكون i هو الموضع الأخير N، يكون هذا هو الرأس نفسه من المفهوم السابق بالضبط. يُلحق الرمز المسحوب بالمدخل، ويُشغَّل النموذج من جديد على التسلسل الأطول، وتستمر الحلقة حتى ينتج رمز النهاية أو يبلغ حدًّا للطول. هذا هو التوليد الانحداري الذاتي autoregressive generation، وهو الحلقة نفسها التي رأيتها مع نموذج اللغة RNN في الجزء 3، لكنها الآن تُدار بنموذج من نوع decoder-only.

The last position's vector becomes a distribution, a token is drawn from it, and that token becomes the next inputمتجه الموضع الأخير يصبح توزيعًا احتماليًا، ويُسحب منه رمز، ثم يصبح ذلك الرمز هو المدخل التالي

Worked exampleمثال محلول

Drawing one token from y = [0.659, 0.242, 0.099]سحب رمز واحد من y = [0.659, 0.242, 0.099]

  1. Lay the probabilities end to endرتّب الاحتمالات متتالية على خط واحد

    Word 1 owns [0, 0.659), word 2 owns [0.659, 0.901), word 3 owns [0.901, 1.0).
    الكلمة 1 تملك المجال [0, 0.659)، والكلمة 2 تملك [0.659, 0.901)، والكلمة 3 تملك [0.901, 1.0).
  2. Draw a uniform random numberاسحب رقمًا عشوائيًا منتظم التوزيع

    Suppose r = 0.73.
    افترض أن r = 0.73.
  3. Find its intervalحدّد المجال الذي يقع فيه

    0.73 falls in [0.659, 0.901), so word 2 is generated.
    0.73 يقع في [0.659, 0.901)، لذلك تُولَّد الكلمة 2.
  4. Resultالنتيجة

    Word 2 is appended even though word 1 was more likely. Over many draws word 1 appears about 66% of the time, word 2 about 24%, word 3 about 10%.
    تُلحق الكلمة 2 رغم أن الكلمة 1 كانت أرجح. وعلى مدى سحبات كثيرة تظهر الكلمة 1 في نحو 66% من المرات، والكلمة 2 في نحو 24%، والكلمة 3 في نحو 10%.

Always taking the most likely token, greedy decoding, is the deterministic alternative. It tends to produce repetitive, generic text, which is why sampling is the usual choice; SLP3 also shows how dividing the logits by a temperature before softmax sharpens or flattens y before the draw. Try both in the panel below: each click runs the head on the last token, shows h, the unembedding, the logits and the probabilities, and appends the chosen token.

أخذ الرمز الأرجح دائمًا، أي فك الترميز الجشع (greedy decoding)، هو البديل الحتمي. وهو يميل إلى إنتاج نص مكرر وعام، ولهذا يكون السحب العشوائي (sampling) هو الخيار المعتاد. ويبيّن SLP3 أيضًا كيف أن قسمة الـlogits على درجة حرارة (temperature) قبل softmax تجعل y أكثر حدّة أو أكثر تسطّحًا قبل السحب. جرّب الطريقتين في اللوحة أدناه: كل نقرة تشغّل الرأس على الرمز الأخير، وتعرض h، ومصفوفة إلغاء التضمين، والـlogits، والاحتمالات، ثم تُلحق الرمز المختار.

InteractiveتفاعليRun the language modeling head one token at a timeشغّل رأس نمذجة اللغة رمزًا بعد رمز
Solongandthanksfor
h1 × d
U = Eᵀd × |V|
logits u1 × |V|
  • all2.0
  • the1.0
  • fish0.1
  • and-0.6
  • .-1.2
y = softmax(u)1 × |V|
  • all0.613
  • the0.225
  • fish0.092
  • and0.045
  • .0.025
Input positionforlast tokentoy head: logits keyed to this word alone, a real h_N^L has attended to the whole contextرأس تجريبي: الـ logits مرتبطة بهذه الكلمة وحدها، بينما h_N^L الحقيقي قد انتبه إلى السياق كله
Sum of y1.000always 1
Last picknoneyetappended, then the head runs againأُلحقت الكلمة، ثم يعمل الرأس مرة أخرى

Recall

Describe one step of generation, starting from h_N^L and ending with a longer input.صِف خطوة واحدة من التوليد، تبدأ من h_N^L وتنتهي بمدخل أطول.

Multiply h_N^L by Eᵀ to get logits, apply softmax to get y, draw a token index from y (or take the maximum for greedy decoding), append that token to the input sequence, and run the whole model again so the new last position produces the next distribution.

اضرب h_N^L في Eᵀ لتحصل على الـlogits، وطبّق softmax لتحصل على y، ثم اسحب فهرس رمز من y (أو خذ القيمة العظمى في فك الترميز الجشع)، وألحِق ذلك الرمز بتسلسل المدخل، ثم شغّل النموذج كله من جديد لكي ينتج الموضع الأخير الجديد التوزيع التالي.

Take the training sentence So long and thanks for all. The model reads So long and thanks for and, at each of those five positions, must predict the word that actually comes next: long, and, thanks, for, all. One sentence gives five training examples, and the labels come free from the text itself. That is Self-supervised training.

خذ جملة التدريب So long and thanks for all. يقرأ النموذج So long and thanks for، وعليه عند كل موضع من هذه المواضع الخمسة أن يتنبأ بالكلمة التي تأتي بعده فعلًا: long، and، thanks، for، all. جملة واحدة تعطي خمسة أمثلة تدريب، والتسميات (labels) تأتي مجانًا من النص نفسه. هذا هو التعلّم الذاتي الإشراف self-supervised learning.

The model from bottom to topالنموذج من الأسفل إلى الأعلى

  1. Input encoding. Each token is looked up in E to get its token embedding, and a learned positional embedding for its position (the boxed 1, 2, 3, 4, 5 on slide 42) is added: xi=E[wi]+Epos[i]x_i = E[w_i] + E_{\text{pos}}[i]. The Positional encoding is needed because attention alone ignores word order.ترميز المدخل. يُبحث عن كل رمز في E للحصول على تضمين الرمز (token embedding)، ثم يُضاف إليه تضمين موضعي متعلَّم (positional embedding) خاص بموضعه (الأرقام المؤطّرة 1, 2, 3, 4, 5 في الشريحة 42): xi=E[wi]+Epos[i]x_i = E[w_i] + E_{\text{pos}}[i]. الترميز الموضعي positional encoding ضروري لأن الانتباه وحده يتجاهل ترتيب الكلمات.
  2. Stacked blocks. The vectors x_1 … x_T pass through L identical transformer blocks. Each uses causal self-attention, so position t sees only tokens 1 … t and cannot peek at the word it must predict.الكتل المكدّسة. تمر المتجهات x_1 … x_T عبر L كتلة متطابقة من transformer blocks. تستخدم كل كتلة causal self-attention (الانتباه الذاتي السببي)، لذلك لا يرى الموضع t إلا الرموز 1 … t، ولا يستطيع أن يختلس النظر إلى الكلمة التي عليه أن يتنبأ بها.
  3. A head at every position. The same language modeling head, with the same U = Eᵀ, runs on every final vector h_t^L, giving a distribution ŷ_t for the next token.رأس عند كل موضع. يعمل رأس نمذجة اللغة نفسه، بالمصفوفة نفسها U = Eᵀ، على كل متجه نهائي h_t^L، فيعطي توزيعًا ŷ_t للرمز التالي.
  4. Loss per position. With a one-hot target, Cross-entropy loss reduces to the negative log probability of the true next token, −log ŷ_t[w_{t+1}]. Slide 42 writes these as −log y_long, −log y_and and so on.الخسارة لكل موضع. مع هدف من نوع one-hot، تختزل خسارة الإنتروبيا المتقاطعة cross-entropy loss إلى سالب لوغاريتم احتمال الرمز التالي الصحيح، −log ŷ_t[w_{t+1}]. وتكتبها الشريحة 42 على هيئة −log y_long و−log y_and وهكذا.
  5. Average and backpropagate. The loss for a sequence of length T is the mean of the per-position losses. Its gradient flows back through the heads, every block and the input encoding, so all weights are learned together, including E, which with tying is updated from both ends.خذ المتوسط ثم طبّق الانتشار العكسي. الخسارة لتسلسل طوله T هي متوسط خسائر المواضع. ويتدفق تدرّجها عائدًا عبر الرؤوس، وكل الكتل، وترميز المدخل، فتُتعلَّم جميع الأوزان معًا، بما فيها E التي تُحدَّث من الطرفين في حال الربط.
LCE(sequence of length T)=1T∑t=1T−log⁡y^t[wt+1]L_{CE}(\text{sequence of length } T) = \frac{1}{T}\sum_{t=1}^{T} -\log \hat{y}_t\left[w_{t+1}\right]
Averaged cross-entropy over the positions (SLP3 Eq. 7.55)متوسط الإنتروبيا المتقاطعة على المواضع (المعادلة 7.55 في SLP3)

Worked exampleمثال محلول

Averaging the loss over five positionsحساب متوسط الخسارة على خمسة مواضع

  1. Probabilities the model gives the true next tokenالاحتمالات التي يعطيها النموذج للرمز التالي الصحيح

    long 0.20, and 0.50, thanks 0.10, for 0.40, all 0.25.
    long 0.20، and 0.50، thanks 0.10، for 0.40، all 0.25.
  2. Per-position losses, −ln pخسارة كل موضع، −ln p

    1.61, 0.69, 2.30, 0.92, 1.39.
    1.61، 0.69، 2.30، 0.92، 1.39.
  3. Averageالمتوسط

    (1.61 + 0.69 + 2.30 + 0.92 + 1.39) / 5 = 6.91 / 5 ≈ 1.38.
    (1.61 + 0.69 + 2.30 + 0.92 + 1.39) / 5 = 6.91 / 5 ≈ 1.38.
  4. Resultالنتيجة

    The sequence loss is about 1.38. The worst position, thanks at p = 0.10, contributes the most, so gradient descent pushes hardest on it. Exponentiating the average, e^1.38 ≈ 4.0, gives the model's perplexity on this sequence.
    خسارة التسلسل نحو 1.38. الموضع الأسوأ، thanks باحتمال p = 0.10، يساهم بالقدر الأكبر، لذلك يدفع الانحدار التدرّجي (gradient descent) بأقصى قوة عليه. ورفع المتوسط أسيًا، e^1.38 ≈ 4.0، يعطي الـperplexity الخاصة بالنموذج على هذا التسلسل.
One bar per position: −log of the probability given to the true next token, with the averaged loss as the dashed lineعمود واحد لكل موضع: سالب لوغاريتم الاحتمال المعطى للرمز التالي الصحيح، والخط المتقطع هو متوسط الخسارة

Why it all happens in one passلماذا يحدث كل شيء في تمريرة واحدة

During training every position is fed the true previous tokens, never the model's own guesses. That is Teacher forcing. Because all targets are known in advance and the causal mask stops each position from seeing its own target, all T predictions and losses can be computed in a single forward pass with matrix operations. This Parallel training is the practical advantage over an RNN, which must step through the sequence one token at a time, and it is what makes training on trillions of tokens feasible.

أثناء التدريب يُعطى كل موضع الرموز السابقة الصحيحة، وليس تخمينات النموذج نفسه أبدًا. هذا هو الـteacher forcing. ولأن جميع الأهداف معروفة مسبقًا، ولأن القناع السببي (causal mask) يمنع كل موضع من رؤية هدفه، يمكن حساب جميع التنبؤات والخسائر البالغ عددها T في تمريرة أمامية واحدة بعمليات المصفوفات. هذا التدريب المتوازي parallel training هو الميزة العملية مقارنةً بالـRNN، التي يجب أن تمر على التسلسل رمزًا رمزًا، وهو ما يجعل التدريب على تريليونات الرموز ممكنًا.

AspectالجانبTrainingالتدريبGenerationالتوليد
Where the head runsأين يعمل الرأسAt every position t = 1 … Tعند كل موضع t = 1 … TOnly at the last position Nعند الموضع الأخير N فقط
What feeds position t + 1ما الذي يُغذّي الموضع t + 1The true token from the corpus (teacher forcing)الرمز الصحيح من المدوّنة (teacher forcing)The token just sampled from yالرمز الذي سُحب للتو من y
Output usedالمخرج المستخدم−log ŷ_t[w_{t+1}], averaged−log ŷ_t[w_{t+1}]، ثم يؤخذ متوسطهOne sampled token per stepرمز واحد مسحوب في كل خطوة
Positions computedالمواضع المحسوبةAll T in one parallel passجميع المواضع البالغ عددها T في تمريرة واحدة متوازيةOne new token per forward passرمز جديد واحد في كل تمريرة أمامية
The same network at training time and at generation timeالشبكة نفسها وقت التدريب ووقت التوليد

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

At two positions the model gives the true next token probabilities 0.5 and 0.25. What is the averaged cross-entropy loss?عند موضعين يعطي النموذج الرمز التالي الصحيح الاحتمالين 0.5 و0.25. ما متوسط خسارة الإنتروبيا المتقاطعة (cross-entropy)؟

Recall

Name three things that differ between training a transformer LM and generating with it.اذكر ثلاثة أمور تختلف بين تدريب نموذج لغة من نوع transformer والتوليد به.

In training the head runs at every position, in generation only at the last one. In training each position receives the true previous tokens (teacher forcing), in generation it receives sampled tokens. Training computes all positions in one parallel pass and averages −log ŷ_t[w_{t+1}]; generation produces one new token per forward pass and computes no loss.

في التدريب يعمل الرأس عند كل موضع، وفي التوليد عند الموضع الأخير فقط. في التدريب يتلقى كل موضع الرموز السابقة الصحيحة (teacher forcing)، وفي التوليد يتلقى رموزًا مسحوبة. التدريب يحسب جميع المواضع في تمريرة واحدة متوازية ويأخذ متوسط −log ŷ_t[w_{t+1}]، أما التوليد فينتج رمزًا جديدًا واحدًا في كل تمريرة أمامية ولا يحسب أي خسارة.

Recapالخلاصة

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

  • The language modeling head sits on top of the last transformer block. It turns one 1 × d vector into a probability for every one of the |V| vocabulary items.يقع رأس نمذجة اللغة فوق آخر كتلة transformer. وهو يحوّل متجهًا واحدًا بأبعاد 1 × d إلى احتمال لكل عنصر من عناصر المفردات البالغ عددها |V|.
  • Shape trace: h_N^L (1 × d) times U = Eᵀ (d × |V|) gives the logits u (1 × |V|), and softmax(u) gives y (1 × |V|).تتبّع الأبعاد: h_N^L (1 × d) مضروبًا في U = Eᵀ (d × |V|) يعطي الـ logits u (1 × |V|)، وsoftmax(u) يعطي y (1 × |V|).
  • E is |V| × d. At the bottom it maps a token to a vector, at the top its transpose maps a vector back to one score per token. Reusing it is weight tying.أبعاد E هي |V| × d. في الأسفل تحوّل الرمز إلى متجه، وفي الأعلى يحوّل مدورها المتجه مرة أخرى إلى درجة (score) واحدة لكل رمز. إعادة استخدامها هي ربط الأوزان (weight tying).
  • Tying saves a whole |V| × d matrix: 38.4 M parameters for d = 768 and |V| = 50,000. It also keeps input and output word vectors in one shared space.يوفّر الربط مصفوفة كاملة بأبعاد |V| × d: أي 38.4 M معامل عندما d = 768 و|V| = 50,000. كما يُبقي متجهات الكلمات في المدخل والمخرج في فضاء واحد مشترك.
  • Logits are unbounded scores that do not sum to 1. Softmax exponentiates and normalizes them: [2.0, 1.0, 0.1] becomes [0.659, 0.242, 0.099].الـ logits درجات غير محدودة ولا يساوي مجموعها 1. تقوم softmax برفعها أسيًا ثم تطبيعها: [2.0, 1.0, 0.1] تصبح [0.659, 0.242, 0.099].
  • Generation samples w_{i+1} from y, appends it to the input, and runs the model again. The model outputs a distribution; the decoding rule picks the token.في التوليد يُسحب w_{i+1} من y، ويُلحق بالمدخل، ثم يُشغَّل النموذج من جديد. النموذج يُخرج توزيعًا احتماليًا، وقاعدة فك الترميز (decoding rule) هي التي تختار الرمز.
  • Training: token embedding plus positional embedding, L stacked causal blocks, a head at every position, loss −log ŷ_t[w_{t+1}] per position, averaged over T positions, all computed in one parallel pass.التدريب: تضمين الرمز (token embedding) زائد التضمين الموضعي (positional embedding)، ثم L كتلة سببية (causal) مكدّسة، ثم رأس عند كل موضع، والخسارة −log ŷ_t[w_{t+1}] لكل موضع، ثم المتوسط على T موضعًا، وكل ذلك يُحسب في تمريرة واحدة متوازية.

Sourcesالمصادر