Skip to content
Self-Attention
step 1/5

Reading — step 1 of 5

Read

~1 min readAttention

Self-Attention

The core innovation. Each token computes weighted sum of values from all tokens.

For each token, generate three vectors via learned projections:

  • Query (Q): "what am I looking for?"
  • Key (K): "what do I represent?"
  • Value (V): "what do I contribute?"
python

Where X is (T, D) for T tokens, D embedding dim.

Attention scores: dot product of each query with each key.

python

Softmax over keys (per query):

python

Weighted sum of values:

python

Each output token = weighted average of all V's, weighted by Q-K similarity.

Putting together:

python

Why dot product? Measures similarity in embedding space.

Why scale by sqrt(d_k)? Without it, dot products grow large with dimension → softmax saturates → gradients vanish.

Causal mask (for GPT-style):

  • Each token can only attend to itself + earlier tokens.
  • Mask future positions: scores[i, j] = -inf if j > i.
  • After softmax: 0 weight on future.
python

In encoder models (BERT): no mask, attend bidirectionally. In decoder (GPT): causal mask.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Self-Attention — Build a Transformer (GPT-style)