الرئيسية / مقرر Deep Learning / الفصل 9 الجزء 1

الفصل 9 (الجزء 1): Attention

Queries, keys and values

على طول: إزاي كل عنصر في التسلسل يبص على باقي العناصر ويختار المهم.

فيديو المحاضرة

فيديو المحاضرة

بعد الفيديو: الأمثلة والاختبار والتمارين والمشروع الصغير تحت.

رسوم متحركة

أوزان الـ attention

أمثلة Python

أمثلة قصيرة وبسيطة

الكود قصير والنتيجة اتجرّبت فعلاً. عدّل في المحرر واضغط شغّل.

المثال ١: أوزان الـ attention

Sample output (press Run to produce your own):
weights [0.659 0.242 0.099] sum 1.0

المثال ٢: attention كاملة

Sample output (press Run to produce your own):
weights row sums: [1. 1. 1. 1.]
output shape: (4, 8)

المثال ٣: ليه بنقسم على sqrt(d)

Sample output (press Run to produce your own):
d 4  std raw 2.0  std scaled 1.0
d 64  std raw 8.0  std scaled 1.01
d 1024  std raw 32.3  std scaled 1.01

افتح الفصل المقابل في كتاب d2l.ai

اختبار قصير

اختبر فهمك

1. The attention score of token i for token j is:

2. What do attention weights in one row sum to?

3. Why divide by sqrt(d)?

4. In self-attention, Q, K and V come from:

5. What is the benefit of multiple heads?

تمارين برمجة

جرّب بإيدك

التمرين 1

احسب softmax للسكورات [1, 1, 1] واطبع الأوزان.

Compute the softmax of the scores [1, 1, 1] and print the weights.

(output appears here)

التمرين 2

خد الأوزان [0.7, 0.3] والـ values [[1, 0], [0, 1]] واحسب الـ output.

Take the weights [0.7, 0.3] and the values [[1, 0], [0, 1]]. Compute the output.

(output appears here)

مشروع صغير في آخر المحاضرة

self-attention على صفوف الأرقام

الداتا: Optical Recognition of Handwritten Digits: 1797 images of 8x8 pixels. Source: UCI Machine Learning Repository.

License / source: Ships with scikit-learn. Dataset page

الخطوات

  1. حمّل digits واقسم ٨٠/٢٠. كل صورة ٨ tokens (الصفوف).
  2. اعمل Wq و Wk و Wv عشوائية ثابتة وطبّق الـ scaled dot-product attention.
  3. درّب LogisticRegression على المخرجات بعد ما تفردها.
  4. قارن بمتوسط الصفوف. المتوقع: الـ attention حوالي 0.77 ومتوسط الصفوف حوالي 0.48.
Expected output (press Run to produce your own):
mean of rows        : 0.481
attention (no pos)  : 0.769

Credits: the topic order follows the book "Dive into Deep Learning" (d2l.ai) by Zhang, Lipton, Li and Smola, whose text is licensed CC BY-SA 4.0. The explanations, diagrams and code in this lecture are our own and are not copied from the book. Reference: d2l.ai, Attention Mechanisms and Transformers.