Self-Attention
Goal
Turn one sequence into context-aware token representations.
Shape Contract
- input
x:(T, D) - projected
Q,K,V: each(T, D) - scores:
(T, T) - weights:
(T, T) - output:
(T, D)
Attention Equation
Attention(Q, K, V) = softmax((Q K^T) / sqrt(D)) V
Row view:
- score row
icompares tokenito all tokens - softmax row
iis a probability distribution - output row
iis weighted sum of allV[j]
Causal Mask (Autoregressive)
- allow
j <= i - block
j > iwith-1e9 - add mask to scores before softmax
Numerical Stability
Stable softmax per row:
m = max(row)exp(row - m)- normalize by row sum
Module Build Order
softmax(scores)attention_scores(Q, K, d_k)causal_mask(seq_len)apply_attention(weights, V)SelfAttention.forward
Complexity
- time:
O(T^2 * D) - memory:
O(T^2)
Failure Modes
- wrong softmax axis
- mask applied after softmax
- missing
/ sqrt(d_k) - breaking
Valuegraph by raw float ops
1 / 1