فيديو المحاضرة
فيديو المحاضرة
بعد الفيديو: الأمثلة والاختبار والتمارين والمشروع الصغير تحت.
رسوم متحركة
أمثلة 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
اختبار قصير
اختبر فهمك
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)
import numpy as np s = np.array([1.0, 1.0, 1.0]) e = np.exp(s) print(np.round(e / e.sum(), 3))
Output
[0.333 0.333 0.333]
التمرين 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)
import numpy as np w = np.array([0.7, 0.3]) V = np.array([[1.0, 0.0], [0.0, 1.0]]) print(w @ V)
Output
[0.7 0.3]
مشروع صغير في آخر المحاضرة
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
الخطوات
- حمّل digits واقسم ٨٠/٢٠. كل صورة ٨ tokens (الصفوف).
- اعمل Wq و Wk و Wv عشوائية ثابتة وطبّق الـ scaled dot-product attention.
- درّب LogisticRegression على المخرجات بعد ما تفردها.
- قارن بمتوسط الصفوف. المتوقع: الـ 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.