The Transformer architecture, introduced in "Attention Is All You Need" (Vaswani et al., 2017), has become the backbone of modern deep learning. This post walks through the key components from scratch.
Self-Attention Mechanism
The core of the Transformer is the scaled dot-product attention:
Attention(Q,K,V)=softmax(dkQKT)V
where:
Q∈Rn×dk are the queries
K∈Rn×dk are the keys
V∈Rn×dv are the values
dk is the dimension of keys (scaling factor)
Multi-Head Attention
Instead of a single attention function, we use multiple heads:
MultiHead(Q,K,V)=Concat(head1,...,headh)WO
where each head is:
headi=Attention(QWiQ,KWiK,VWiV)
This allows the model to attend to information from different representation subspaces.
Positional Encoding
Since attention is permutation invariant, we add positional information:
PE(pos,2i)=sin(100002i/dmodelpos)
PE(pos,2i+1)=cos(100002i/dmodelpos)
Feed-Forward Network
Each layer contains a position-wise feed-forward network:
FFN(x)=max(0,xW1+b1)W2+b2
This is applied identically to each position.
Layer Normalization & Residual Connections
Each sub-layer uses a residual connection followed by layer normalization:
output=LayerNorm(x+SubLayer(x))
Encoder-Decoder Architecture
Encoder: Stack of N identical layers, each with multi-head self-attention + FFN
Decoder: Stack of N identical layers, with masked self-attention + cross-attention + FFN
Why Transformers Work
Parallelization: Unlike RNNs, all positions are processed simultaneously
Long-range dependencies: Direct connections between any two positions
Scalability: Efficiently scales with data and compute
Conclusion
The Transformer has enabled GPT, BERT, Vision Transformers, and countless other breakthroughs. Understanding its components from scratch is essential for modern ML research.
References
Vaswani et al., "Attention Is All You Need," NeurIPS 2017.
Devlin et al., "BERT: Pre-training of Deep Bidirectional Transformers," NAACL 2019.