← Back to Projects
Transformer from Scratch
Implement a scaled-down GPT-style decoder-only transformer in PyTorch. Train it on a tiny text corpus to generate characters.
What you'll learn
- The inner mechanics of Self-Attention and Multi-Head Attention
- Implementing Positional Encodings
- Building a decoder-only architecture
- Training an autoregressive language model
Architecture
Input Tokens
→ Embedding + Positional Encoding
→ N x Transformer Blocks (Self-Attention + Feed Forward)
→ Linear Projection to Vocabulary
→ Autoregressive Generation
Steps
- (Highly recommended: Watch Andrej Karpathy's "Let's build GPT" tutorial).
- Prepare a small text dataset (e.g., the complete works of Shakespeare in a single
.txtfile). - Build a character-level tokenizer (mapping every unique character to an integer).
- Implement a single
SelfAttentionhead in PyTorch using query, key, and value matrices. - Expand it to a
MultiHeadAttentionmodule. - Build a
TransformerBlockcontaining the attention module, layer normalization, and a feed-forward network. - Stack multiple blocks to create the final
GPTLanguageModel. - Train the model for a few thousand iterations on an Apple Silicon Mac or a Colab GPU.
- Write a generation function that seeds the model with a starting character and autoregressively generates a paragraph of text.