Skip to content

About

No description, website, or topics provided.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

🧠 Transformer From Scratch

Python 3.8+ PyTorch License: MIT

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.

🎯 What You'll Learn

This repository takes you on a journey from basic building blocks to a complete working Transformer:

  1. Token Embeddings β€” Converting discrete tokens to continuous representations
  2. Positional Encodings β€” Injecting sequence order information
  3. Scaled Dot-Product Attention β€” The core attention mechanism
  4. Multi-Head Attention β€” Parallel attention perspectives
  5. Feed-Forward Networks β€” Position-wise transformations
  6. Encoder Layers β€” Understanding the input
  7. Decoder Layers β€” Generating outputs
  8. Complete Transformer β€” Putting it all together

Each module includes:

  • βœ… Clear mathematical explanations
  • βœ… Detailed code comments
  • βœ… Visualization utilities
  • βœ… Example usage and demonstrations

πŸš€ Quick Start

Installation

# 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 .

Running Your First Transformer

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()}")

πŸ“š Learning Path

Quick Start: Google Colab (Recommended!)

No installation required! Run all tutorials directly in your browser:

Transformer Foundations (Start Here):

  • Open In Colab Tutorial 1: Embeddings & Positional Encoding
  • Open In Colab Tutorial 2: Scaled Dot-Product Attention
  • Open In Colab Tutorial 3: Multi-Head Attention
  • Open In Colab Tutorial 4: Feed-Forward Networks
  • Open In Colab Tutorial 5: Encoder & Decoder
  • Open In Colab Tutorial 6: Complete Transformer
  • Open In Colab Tutorial 7: Emergent Reasoning

LLM Fine-Tuning (Advanced):

  • Open In Colab Tutorial 1: Introduction to Fine-Tuning
  • Open In Colab Tutorial 2: LoRA Implementation
  • Open In Colab Tutorial 3: Data Preparation
  • Open In Colab Tutorial 4: Instruction Tuning
  • Open In Colab Tutorial 5: Evaluation Metrics
  • Open In Colab Tutorial 6: QLoRA Quantization

Click any badge above to open that tutorial directly in Google Colab and start learning immediately!


For Beginners

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.py

For Visual Learners

Explore the Jupyter notebooks in the transformer-foundation/ directory:

  1. 01_embeddings_and_positional_encoding.ipynb β€” Visualize embeddings and position encodings
  2. 02_scaled_dot_product_attention.ipynb β€” Core attention mechanism
  3. 03_multi_head_attention.ipynb β€” Interactive attention visualizations
  4. 04_feed_forward_networks.ipynb β€” FFN and layer normalization
  5. 05_encoder_decoder.ipynb β€” Encoder and decoder architecture
  6. 06_complete_transformer.ipynb β€” Build and train a Transformer
  7. 07_emergent_reasoning.ipynb β€” Explore advanced capabilities with DeepSeek
# Launch Jupyter Lab
jupyter lab

For Practitioners

Explore the comprehensive fine-tuning tutorial series in llm-fine-tune/:

  1. 01_introduction_to_fine_tuning.ipynb β€” Fine-tuning strategies, LoRA theory
  2. 02_lora_implementation.ipynb β€” Implement LoRA from scratch
  3. 03_data_preparation.ipynb β€” Dataset formats and tokenization
  4. 04_instruction_tuning.ipynb β€” Complete training pipeline
  5. 05_evaluation_metrics.ipynb β€” BLEU, ROUGE, perplexity
  6. 06_qlora_quantization.ipynb β€” QLoRA and 4-bit quantization

See llm-fine-tune/README.md for detailed learning path

πŸ—οΈ Project Structure

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

πŸ”¬ Key Features

1. Educational Focus

Every line of code is documented with:

  • Clear variable names
  • Inline comments explaining the "why"
  • Mathematical formulations in docstrings
  • References to the original paper

2. Modular Design

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)

3. Modern Extensions

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)

4. Visualization Tools

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)

5. Fine-Tuning Techniques

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

πŸ“– Architecture Details

Model Configuration (Original Paper)

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 length

Parameter Count

For 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)

πŸŽ“ DeepSeek-R1 Insights

Modern large language models like DeepSeek-R1 build upon the Transformer foundation with:

Architectural Improvements

  • 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

Training Techniques

  • Large Batch Training: 1000s of examples per batch
  • Curriculum Learning: Progressive difficulty
  • Advanced Optimizers: AdamW with learning rate scheduling
  • Gradient Checkpointing: Memory efficiency

Emergent Capabilities

  • 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.

πŸ§ͺ Testing

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 -v

πŸ“Š Notebooks

1. Embeddings and Positional Encoding

Explore how tokens are converted to continuous representations and how position information is injected:

  • Visualize embedding spaces
  • Plot positional encoding patterns
  • Understand wavelength hierarchies

2. Attention Mechanism

Interactive visualizations of the attention mechanism:

  • Self-attention patterns
  • Cross-attention in encoder-decoder
  • Effect of masking
  • Attention head diversity

3. Complete Transformer

Build and train a complete Transformer:

  • Data preparation and batching
  • Training loop with loss computation
  • Evaluation and generation
  • Attention visualization during inference

4. Emergent Reasoning

Explore how Transformers can exhibit reasoning capabilities:

  • Pattern recognition and completion
  • Arithmetic and logical operations
  • Compositional generalization
  • In-context learning examples

🀝 Contributing

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.

πŸ“š Resources

Papers

Additional Learning Materials

Related Projects

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • 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

πŸ“¬ Contact

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!

About

No description, website, or topics provided.

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages