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

ICS 582Lecture 06المحاضرة 06Part 06الجزء 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) المستقبل.

Conceptsالمفاهيم
5
Slidesالشرائح
27-31
Readingمدة القراءة
30 min30 دقيقة
Understoodما فهمته
0/5 conceptsمفاهيم

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