This repository contains an implementation of a GPT model from scratch, covering everything from tokenization to text generation. Everything is implemented in PyTorch in a single annotated notebook. The implementation follows the structure of Sebastian Raschka's book Build a Large Language Model (From Scratch); all code was written and annotated by me while working through it.
- Loaded a text file containing a legal verdict.
- Used regular expressions to split text into meaningful tokens.
- Preprocessed the tokens by removing unnecessary spaces and normalizing punctuation.
- Constructed a vocabulary where each token is mapped to a unique integer.
- Developed a class to encode text into token IDs and decode token IDs back into readable text.
- Included logic to handle spacing before punctuation.
- Implemented a frequency-based subword tokenization technique.
- Merged frequently occurring character pairs iteratively to improve efficiency.
- Prepared sequences where the input is a text segment, and the target is the next word.
- Tokenized the entire text.
- Used a sliding window technique to generate overlapping text sequences.
- Defined dataset properties to return the number of rows and fetch a specific data row when needed.
- Converted token IDs into dense vector representations for better semantic understanding.
- Incorporated positional encodings to retain the order of words within a sequence.
- Designed an attention mechanism to compute importance scores for tokens.
- Introduced learnable weight matrices to enhance context awareness.
- Encapsulated self-attention logic in a reusable class.
- Modified self-attention to prevent tokens from attending to future words.
- Implemented multiple attention heads to capture diverse relationships between tokens.
- Extended self-attention to use multiple independent attention heads.
- Created a simple version of a GPT model with embeddings and attention layers.
- Integrated normalization layers to stabilize model training.
- Used the GELU activation function for improved performance.
- Implemented skip connections to improve gradient flow and training stability.
- Combined all previous elements into a modular transformer block.
- Integrated embedding layers, multi-head attention, feedforward layers, and normalization into a full GPT model.
- Used the trained model to generate coherent text sequences.