DEEP LEARNING / 6. ATTENTION MECHANISM
Attention Mechanism
The core idea behind every modern model
EXPLANATION
Attention answers the question: for each position in the sequence, which other positions are most relevant? Instead of compressing the entire sequence into one fixed vector (the RNN bottleneck), attention lets each token directly look at all other tokens and weight their contributions. Scaled Dot-Product Attention: • Q (Query) → what am I looking for? • K (Key) → what do I contain? • V (Value) → what do I actually return? Attention(Q,K,V) = softmax(QKᵀ / √d_k) · V The √d_k scaling prevents dot products from exploding in high dimensions, which would push softmax into zero-gradient regions. Multi-Head Attention runs this h times in parallel with different learned projections, letting the model attend to different aspects simultaneously.
DATA FLOW
Input sequence: [x1, x2, x3, x4]
Each xi projected to Q, K, V via learned weight matrices:
Q = X·Wq, K = X·Wk, V = X·Wv
Attention scores (how much each token attends to each other):
x1 x2 x3 x4
x1 [ 0.6 0.2 0.1 0.1 ] ← x1 mostly attends to itself
x2 [ 0.3 0.5 0.1 0.1 ]
x3 [ 0.1 0.2 0.6 0.1 ]
x4 [ 0.1 0.1 0.2 0.6 ]
Output = scores · V ← weighted sum of valuesCODE