المستوى: مبتدئ · الدرس 3 من 14
أهداف الدرس
- أن تفهم فكرة الانتباه.
- أن تعرف ما نافذة السياق.
المحوّل (Transformer) هو البنية خلف النماذج اللغوية الحديثة. سرّه الانتباه: كل كلمة تنظر إلى بقية الكلمات وتقرّر أيّها أهمّ لفهمها. تتكرّر هذه الخطوة في طبقات كثيرة، فيبني النموذج فهماً أعمق طبقة بعد طبقة.
import numpy as np
def attention(Q, K, V):
d = Q.shape[-1]
scores = Q @ K.T / np.sqrt(d) # how much each word looks at each other word
scores -= scores.max(axis=-1, keepdims=True)
weights = np.exp(scores)
weights /= weights.sum(axis=-1, keepdims=True) # softmax: each row sums to 1
return weights @ V, weights
rng = np.random.default_rng(0)
Q = K = V = rng.normal(size=(5, 8)) # 5 words, 8 numbers each
out, w = attention(Q, K, V)
print(w.sum(axis=1).round(2)) # [1. 1. 1. 1. 1.]| الفكرة | ببساطة |
|---|---|
| رؤوس انتباه متعدّدة | عدّة «عيون» تنظر إلى علاقات مختلفة معاً |
| الموضع | معلومة عن ترتيب الكلمات |
| نافذة السياق | أقصى ما يقرؤه النموذج دفعة واحدة — اليوم مئات آلاف الرموز في نماذج كثيرة |
تمرين
لماذا لا يكفي أن ينظر النموذج إلى الكلمة السابقة وحدها؟
الإجابة
لأن المعنى قد يتعلّق بكلمة بعيدة: الضمير في آخر الجملة يعود إلى اسم في أولها.
Level: Beginner · Lesson 3 of 14
Lesson goals
- Understand the idea of attention.
- Know what a context window is.
The Transformer is the architecture behind modern language models. Its secret is attention: each word looks at the others and decides which matter most for its meaning. The step repeats over many layers, so understanding deepens layer by layer.
import numpy as np
def attention(Q, K, V):
d = Q.shape[-1]
scores = Q @ K.T / np.sqrt(d) # how much each word looks at each other word
scores -= scores.max(axis=-1, keepdims=True)
weights = np.exp(scores)
weights /= weights.sum(axis=-1, keepdims=True) # softmax: each row sums to 1
return weights @ V, weights
rng = np.random.default_rng(0)
Q = K = V = rng.normal(size=(5, 8)) # 5 words, 8 numbers each
out, w = attention(Q, K, V)
print(w.sum(axis=1).round(2)) # [1. 1. 1. 1. 1.]| Idea | Simply |
|---|---|
| Multi-head attention | Several «eyes» looking at different relations at once |
| Position | Information about word order |
| Context window | The most the model reads at once — hundreds of thousands of tokens in many models today |
Exercise
Why is looking only at the previous word not enough?
Answer
Meaning can depend on a distant word: a pronoun at the end refers to a noun at the start.
التعليقات / Comments
لا تعليقات بعد. كن أول من يسأل. / No comments yet. Be the first to ask.