Learn Transformers step by step β A comprehensive educational repository implementing the Transformer architecture from "Attention Is All You Need" (Vaswani et al., 2017), enriched with modern insights from DeepSeek-R1 and other recent advances.
This repository takes you on a journey from basic building blocks to a complete working Transformer:
- Token Embeddings β Converting discrete tokens to continuous representations
- Positional Encodings β Injecting sequence order information
- Scaled Dot-Product Attention β The core attention mechanism
- Multi-Head Attention β Parallel attention perspectives
- Feed-Forward Networks β Position-wise transformations
- Encoder Layers β Understanding the input
- Decoder Layers β Generating outputs
- Complete Transformer β Putting it all together
Each module includes:
- β Clear mathematical explanations
- β Detailed code comments
- β Visualization utilities
- β Example usage and demonstrations
# Clone the repository
git clone https://github.com/yourusername/transformer-from-scratch.git
cd transformer-from-scratch
# Create virtual environment (recommended)
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Or install in development mode
pip install -e .import torch
from src.transformer import Transformer
# Create a Transformer model
model = Transformer(
src_vocab_size=10000,
tgt_vocab_size=10000,
d_model=512,
n_heads=8,
n_encoder_layers=6,
n_decoder_layers=6,
d_ff=2048
)
# Example forward pass
src = torch.randint(0, 10000, (2, 20)) # Batch of 2, sequence length 20
tgt = torch.randint(0, 10000, (2, 15)) # Batch of 2, sequence length 15
output = model(src, tgt) # Shape: (2, 15, 10000)
print(f"Output logits shape: {output.shape}")
# Generate sequences
generated = model.generate(src, max_len=50, temperature=0.8)
print(f"Generated sequence: {generated[0].tolist()}")No installation required! Run all tutorials directly in your browser:
Transformer Foundations (Start Here):
Tutorial 1: Embeddings & Positional Encoding
Tutorial 2: Scaled Dot-Product Attention
Tutorial 3: Multi-Head Attention
Tutorial 4: Feed-Forward Networks
Tutorial 5: Encoder & Decoder
Tutorial 6: Complete Transformer
Tutorial 7: Emergent Reasoning
LLM Fine-Tuning (Advanced):
Tutorial 1: Introduction to Fine-Tuning
Tutorial 2: LoRA Implementation
Tutorial 3: Data Preparation
Tutorial 4: Instruction Tuning
Tutorial 5: Evaluation Metrics
Tutorial 6: QLoRA Quantization
Click any badge above to open that tutorial directly in Google Colab and start learning immediately!
Start with the modules in order, running the example code in each file:
# Run individual modules to see examples
python src/modules/embeddings.py
python src/modules/positional_encoding.py
python src/modules/attention.py
python src/modules/multi_head_attention.py
python src/modules/feed_forward.py
python src/modules/encoder.py
python src/modules/decoder.py
python src/transformer.pyExplore the Jupyter notebooks in the transformer-foundation/ directory:
- 01_embeddings_and_positional_encoding.ipynb β Visualize embeddings and position encodings
- 02_scaled_dot_product_attention.ipynb β Core attention mechanism
- 03_multi_head_attention.ipynb β Interactive attention visualizations
- 04_feed_forward_networks.ipynb β FFN and layer normalization
- 05_encoder_decoder.ipynb β Encoder and decoder architecture
- 06_complete_transformer.ipynb β Build and train a Transformer
- 07_emergent_reasoning.ipynb β Explore advanced capabilities with DeepSeek
# Launch Jupyter Lab
jupyter labExplore the comprehensive fine-tuning tutorial series in llm-fine-tune/:
- 01_introduction_to_fine_tuning.ipynb β Fine-tuning strategies, LoRA theory
- 02_lora_implementation.ipynb β Implement LoRA from scratch
- 03_data_preparation.ipynb β Dataset formats and tokenization
- 04_instruction_tuning.ipynb β Complete training pipeline
- 05_evaluation_metrics.ipynb β BLEU, ROUGE, perplexity
- 06_qlora_quantization.ipynb β QLoRA and 4-bit quantization
See llm-fine-tune/README.md for detailed learning path
transformer_from_scratch/
β
βββ src/ # Main source code
β βββ modules/ # Individual components
β β βββ embeddings.py # Token embeddings
β β βββ positional_encoding.py # Positional encodings
β β βββ attention.py # Scaled dot-product attention
β β βββ multi_head_attention.py # Multi-head attention
β β βββ feed_forward.py # Feed-forward networks
β β βββ encoder.py # TransformerEncoder and EncoderLayer
β β βββ decoder.py # TransformerDecoder and DecoderLayer
β βββ transformer.py # Complete Transformer model
β βββ __init__.py
β
βββ transformer-foundation/ # Jupyter notebooks (tutorials)
β βββ 01_embeddings_and_positional_encoding.ipynb
β βββ 02_scaled_dot_product_attention.ipynb
β βββ 03_multi_head_attention.ipynb
β βββ 04_feed_forward_networks.ipynb
β βββ 05_encoder_decoder.ipynb
β βββ 06_complete_transformer.ipynb
β βββ 07_emergent_reasoning.ipynb
β βββ TUTORIALS_OVERVIEW.md
β
βββ tests/ # Unit tests
β βββ test_embeddings.py
β βββ test_attention.py
β βββ test_encoder.py
β βββ test_decoder.py
β βββ test_transformer.py
β
βββ llm-fine-tune/ # LLM fine-tuning tutorials
β βββ 01_introduction_to_fine_tuning.ipynb
β βββ 02_lora_implementation.ipynb
β βββ 03_data_preparation.ipynb
β βββ 04_instruction_tuning.ipynb
β βββ 05_evaluation_metrics.ipynb
β βββ 06_qlora_quantization.ipynb
β βββ archive/ # Older examples
β β βββ text_generation.py
β β βββ attention_visualization.py
β βββ README.md
β
βββ papers/ # Reference papers
β βββ attention-is-all-you-need.pdf
β βββ DeepSeek-R1-paper.pdf
β
βββ pyproject.toml # Project configuration
βββ requirements.txt # Dependencies
βββ README.md # This file
βββ LICENSE # MIT License
Every line of code is documented with:
- Clear variable names
- Inline comments explaining the "why"
- Mathematical formulations in docstrings
- References to the original paper
Each component can be understood and used independently:
from src.modules.attention import ScaledDotProductAttention
from src.modules.multi_head_attention import MultiHeadAttention
from src.modules.positional_encoding import PositionalEncoding
# Use individual components
attention = ScaledDotProductAttention(dropout=0.1)
Q, K, V = torch.randn(2, 8, 10, 64), torch.randn(2, 8, 10, 64), torch.randn(2, 8, 10, 64)
output, weights = attention(Q, K, V)While staying true to the original paper, we include modern variants:
- GLU Feed-Forward Networks (SwiGLU, used in LLaMA)
- Pre-LayerNorm vs Post-LayerNorm
- Learned Positional Encodings (BERT-style)
- Advanced Generation (top-k, nucleus sampling)
Built-in utilities to understand model behavior:
from src.modules.attention import compute_attention_entropy
from src.modules.embeddings import get_nearest_neighbors
# Analyze attention patterns
entropy = compute_attention_entropy(attention_weights)
# Find similar tokens
neighbors = get_nearest_neighbors(embedding_layer, token_idx=42, top_k=5)Comprehensive tutorials on modern fine-tuning methods:
- LoRA (Low-Rank Adaptation): Efficient parameter-efficient fine-tuning
- QLoRA (4-bit Quantization): Memory-efficient training for 7B+ models
- Data Preparation: Tokenization, dataset formats, quality control
- Instruction Tuning: Training pipelines with learning rate scheduling
- Evaluation Metrics: BLEU, ROUGE, perplexity, F1 scores
- Memory Optimization: Gradient accumulation, checkpointing, quantization
d_model = 512 # Model dimension
n_heads = 8 # Number of attention heads
d_ff = 2048 # Feed-forward dimension (4x expansion)
n_layers = 6 # Both encoder and decoder
dropout = 0.1 # Dropout rate
max_seq_len = 5000 # Maximum sequence lengthFor the default configuration:
- Total Parameters: ~65M (depends on vocabulary size)
- Encoder: ~37M parameters
- Decoder: ~56M parameters (includes cross-attention)
- Embeddings: ~10M parameters (for 20K vocabulary)
Modern large language models like DeepSeek-R1 build upon the Transformer foundation with:
- Scaling: Billions of parameters vs millions
- Sparse Attention: More efficient for long sequences
- Mixture of Experts (MoE): Conditional computation
- Better Normalizations: RMSNorm instead of LayerNorm
- Large Batch Training: 1000s of examples per batch
- Curriculum Learning: Progressive difficulty
- Advanced Optimizers: AdamW with learning rate scheduling
- Gradient Checkpointing: Memory efficiency
- Chain-of-Thought Reasoning: Step-by-step problem solving
- Few-Shot Learning: Learning from examples
- Tool Use: Integrating with external systems
- Multimodal Understanding: Beyond just text
This repository focuses on the core architecture, providing a foundation for understanding these advanced techniques.
Run the test suite to verify all components:
# Run all tests
pytest tests/
# Run with coverage
pytest tests/ --cov=src --cov-report=html
# Run specific test file
pytest tests/test_attention.py -vExplore how tokens are converted to continuous representations and how position information is injected:
- Visualize embedding spaces
- Plot positional encoding patterns
- Understand wavelength hierarchies
Interactive visualizations of the attention mechanism:
- Self-attention patterns
- Cross-attention in encoder-decoder
- Effect of masking
- Attention head diversity
Build and train a complete Transformer:
- Data preparation and batching
- Training loop with loss computation
- Evaluation and generation
- Attention visualization during inference
Explore how Transformers can exhibit reasoning capabilities:
- Pattern recognition and completion
- Arithmetic and logical operations
- Compositional generalization
- In-context learning examples
Contributions are welcome! Whether it's:
- π Bug fixes
- π Documentation improvements
- β¨ New features or examples
- π¨ Visualization enhancements
Please open an issue or submit a pull request.
- Attention Is All You Need β Original Transformer paper
- BERT: Pre-training of Deep Bidirectional Transformers
- GPT-3: Language Models are Few-Shot Learners
- LLaMA: Open and Efficient Foundation Language Models
- The Illustrated Transformer by Jay Alammar
- The Annotated Transformer by Harvard NLP
- Formal Algorithms for Transformers
- minGPT by Andrej Karpathy
- nanoGPT by Andrej Karpathy
- Transformers by Hugging Face
This project is licensed under the MIT License - see the LICENSE file for details.
- Vaswani et al. for the original Transformer architecture
- The PyTorch team for an excellent deep learning framework
- The open-source community for countless educational resources
- DeepSeek for pushing the boundaries of what's possible with Transformers
Questions? Suggestions? Feel free to:
- Open an issue on GitHub
- Start a discussion in the Discussions tab
- Contribute to the wiki
Happy Learning! π
"Attention Is All You Need" β and now you'll understand why!