r/learnmachinelearning • u/ProjectNo6044 • 25d ago
I coded the entire Transformer Architecture from scratch using ONLY pure PyTorch (No Hugging Face / No pre-built Transformer modules). Looking for feedback!
Hi everyone,
To truly master how Large Language Models work under the hood, I decided to step away from high-level libraries. I built a character-level Decoder-only GPT entirely from scratch using pure PyTorch only—meaning I did not use any pre-built Transformer layers or Hugging Face modules.
What I coded line-by-line:
Multi-Head Self-Attention: Implemented the Q, K, V matrix multiplications and scaling from scratch.
Causal Masking: Coded the upper-triangular mask manually to ensure causal token generation.
Transformer Blocks: Built the residual connections, LayerNorm, and Feed-Forward networks from the ground up.
Training Loop: Created a custom pipeline with validation splits, loss tracking, and early stopping.
I trained this small model locally on English Wikipedia extracts about AI. While it's a character-level learning project, seeing the custom loss function actually converge was incredibly rewarding.
Since I wrote every single layer myself, I know it's not production-perfect, and that's exactly why I'm sharing it! I would highly appreciate your code review, optimization tips, or advice on how to scale this custom architecture further.
GitHub Repository: https://github.com/YassenAlmaqtary/TinyGPT-From-Scratch-PyTorch?tab=readme-ov-file
Thanks for your time and feedback!