ICS 582Lecture 06المحاضرة 06Part 08الجزء 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)، وكيف يُدرَّب النموذج المكدس كاملا بمتوسط الإنتروبيا المتقاطعة.
- Conceptsالمفاهيم
- 3
- Slidesالشرائح
- 38-43
- Readingمدة القراءة
- 18 min18 دقيقة
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في نهاية هذا الجزء ستستطيع
- 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|.
- Explain weight tying, why E is reused as Eᵀ at the top, and compute how many parameters it saves.اشرح ربط الأوزان (weight tying)، ولماذا يُعاد استخدام E على هيئة Eᵀ في الأعلى، واحسب عدد المعاملات التي يوفّرها.
- Tell logits and probabilities apart, and turn a small logit vector into probabilities by hand.ميّز بين الـ logits والاحتمالات، وحوّل متجه logits صغيرًا إلى احتمالات يدويًا.
- Describe how a token is sampled from y and appended, closing the autoregressive generation loop.صِف كيف يُسحب رمز (token) من y ثم يُلحق بالمدخل، فتُغلق بذلك حلقة التوليد الانحداري الذاتي (autoregressive).
- 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 فتحافظ على الأبعاد وتغيّر القيم فقط.
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 : 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. إذن : درجة الكلمة هي حاصل الضرب النقطي (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 (إلغاء التضمين).
Worked exampleمثال محلول
How many parameters does tying save?كم معاملًا يوفّر الربط؟
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 معامل.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 معامل.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.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.
Worked exampleمثال محلول
Softmax of u = [2.0, 1.0, 0.1]حساب softmax للمتجه u = [2.0, 1.0, 0.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.Sumالجمع
7.389 + 2.718 + 1.105 = 11.212.7.389 + 2.718 + 1.105 = 11.212.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.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 u | Probabilities 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 ŷ |
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.
Worked exampleمثال محلول
Drawing one token from y = [0.659, 0.242, 0.099]سحب رمز واحد من y = [0.659, 0.242, 0.099]
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).Draw a uniform random numberاسحب رقمًا عشوائيًا منتظم التوزيع
Suppose r = 0.73.افترض أن r = 0.73.Find its intervalحدّد المجال الذي يقع فيه
0.73 falls in [0.659, 0.901), so word 2 is generated.0.73 يقع في [0.659, 0.901)، لذلك تُولَّد الكلمة 2.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، والاحتمالات، ثم تُلحق الرمز المختار.
- all2.0
- the1.0
- fish0.1
- and-0.6
- .-1.2
- all0.613
- the0.225
- fish0.092
- and0.045
- .0.025
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النموذج من الأسفل إلى الأعلى
- 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: . The Positional encoding is needed because attention alone ignores word order.ترميز المدخل. يُبحث عن كل رمز في E للحصول على تضمين الرمز (token embedding)، ثم يُضاف إليه تضمين موضعي متعلَّم (positional embedding) خاص بموضعه (الأرقام المؤطّرة 1, 2, 3, 4, 5 في الشريحة 42): . الترميز الموضعي positional encoding ضروري لأن الانتباه وحده يتجاهل ترتيب الكلمات.
- 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، ولا يستطيع أن يختلس النظر إلى الكلمة التي عليه أن يتنبأ بها.
- 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 للرمز التالي.
- 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 وهكذا.
- 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 التي تُحدَّث من الطرفين في حال الربط.
Worked exampleمثال محلول
Averaging the loss over five positionsحساب متوسط الخسارة على خمسة مواضع
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.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.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.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 الخاصة بالنموذج على هذا التسلسل.
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 … T | Only at the last position Nعند الموضع الأخير N فقط |
| What feeds position t + 1ما الذي يُغذّي الموضع t + 1 | The 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رمز جديد واحد في كل تمريرة أمامية |
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المصادر
- Speech and Language Processing, Chapter 7: Transformers and PretrainingBookJurafsky and Martin, StanfordSection 7.5 (language modeling head, weight tying, Eq. 7.47 and 7.48) and 7.7 (pretraining, Eq. 7.55).القسم 7.5 (رأس نمذجة اللغة، وربط الأوزان، والمعادلتان 7.47 و7.48) والقسم 7.7 (التدريب المسبق، والمعادلة 7.55).(opens in a new tab)(يفتح في تبويب جديد)
- Speech and Language Processing (3rd ed. draft)BookJurafsky and Martin, StanfordThe textbook the lecture slides are built from; earlier drafts, including January 2026, are linked there.الكتاب الذي بُنيت عليه شرائح المحاضرة، وتوجد فيه روابط للمسودات السابقة، ومنها مسودة يناير 2026.(opens in a new tab)(يفتح في تبويب جديد)
- Using the Output Embedding to Improve Language ModelsPaperPress and Wolf, EACL 2017Shows that tying input and output embeddings reduces perplexity and model size.تبيّن أن ربط تضمينات المدخل والمخرج يخفّض الـ perplexity وحجم النموذج.(opens in a new tab)(يفتح في تبويب جديد)
- Tying Word Vectors and Word Classifiers: A Loss Framework for Language ModelingPaperInan, Khosravi and Socher, arXivDerives weight tying from a loss framework and reports fewer trainable parameters.تشتق ربط الأوزان من إطار لدالة الخسارة، وتذكر انخفاض عدد المعاملات القابلة للتدريب.(opens in a new tab)(يفتح في تبويب جديد)
- Attention Is All You NeedPaperVaswani et al., arXivSection 3.4 shares one weight matrix between the embedding layers and the pre-softmax linear layer.في القسم 3.4 تُشارَك مصفوفة أوزان واحدة بين طبقات التضمين والطبقة الخطية التي تسبق softmax.(opens in a new tab)(يفتح في تبويب جديد)
- Language Models are Unsupervised Multitask LearnersPaperRadford et al., OpenAIGPT-2: vocabulary of 50,257 tokens; the smallest model has d_model = 768 and 117M parameters (Table 2).GPT-2: مفردات من 50,257 رمزًا، وأصغر نموذج له d_model = 768 و117M معامل (الجدول 2).(opens in a new tab)(يفتح في تبويب جديد)
- GPT-2 model documentationDocsHugging Face TransformersDefaults vocab_size = 50,257, n_embd = 768, tie_word_embeddings = True; the LM head is tied to the input embeddings.القيم الافتراضية vocab_size = 50,257 وn_embd = 768 وtie_word_embeddings = True، ورأس نمذجة اللغة مربوط بتضمينات المدخل.(opens in a new tab)(يفتح في تبويب جديد)