Share from 0:00
0:00
/

Learning ML by doing Part1 | GPT-2

Replicating the 124M parameter model on a single consumer GPU.

Link to GitHub Repository


“What I cannot create, I do not understand.” — Richard Feynman

In the age of massive API-based LLMs, the art of training your own model from scratch can feel like lost knowledge. It is often assumed that you need a cluster of H100s to do anything meaningful. But I wanted to challenge that assumption.

My goal was simple yet ambitious: Replicate the 124M parameter GPT-2 Small model from scratch on a single consumer GPU (RTX 5080) and engineer it to run as fast as possible.

This post describes the journey from a blank Python file to a highly optimized training pipeline that processes over 92,000 tokens per second—a 3.1x speedup over the baseline implementation.

Subscribe for free to receive new posts weeks in advance of Linkedin posts

1. The Architecture: What is GPT-2?

At its core, GPT-2 is a Decoder-only Transformer. Unlike BERT (which uses an Encoder) or T5 (Encoder-Decoder), GPT-2 is built to predict the next token in a sequence. This autoregressive property is what makes it a “Generative” model.

Our implementation (model.py) mirrors the original OpenAI specifications for the 124M model:

  • Parameters: ~124 Million

  • Layers: 12 Transformer Blocks

  • Attention Heads: 12

  • Embedding Dimension: 768

  • Context Length: 1024 tokens

  • Tokenizer: Byte Pair Encoding (BPE) using OpenAI’s tiktoken library.

Key Components

  1. Causal Self-Attention: The heart of the model. It allows each token to attend to previous tokens but masks future tokens so the model can’t “cheat” by seeing the answer.

  2. Learned Positional Embeddings: Since Transformers process tokens in parallel, they have no inherent sense of order. We learn a vector for each position (0 to 1023) to give the model spatial awareness.

  3. Weight Tying: A clever memory-saving trick where the embedding layer weights are reused for the final output projection.

2. The Implementation

We started with a clean slate. The dataset of choice was TinyShakespeare, a classic character modeling benchmark that fits easily into memory but is complex enough to learn grammar and structure.

Everything was written in pure PyTorch. The training loop was standard:

  1. Sample a batch of text.

  2. Forward pass (compute logits).

  3. Compute Cross-Entropy Loss against the targets (shifted input).

  4. Backward pass (compute gradients).

  5. Optimizer step (update weights).

The “Naive” Baseline

My first attempt was functional but fragile.

  • Batch Size: 4 (The GPU ran out of memory at 8 or 12).

  • Throughput: ~29,000 tokens/second.

  • GPU Utilization: Spiky and inefficient.

It worked, but it was painfully slow. At this rate, convergence would take days.

3. Engineering the Speedup 🚀

I didn’t want to wait days. I wanted to engineer my way out of the bottleneck. Here is how we optimized the pipeline to achieve a 3.1x speedup.

Flash Attention 2 ⚡

The standard attention mechanism requires calculating an N×N matrix (Attention Scores). For long sequences, this consumes massive amounts of VRAM (O(N^2) memory complexity).

We switched to torch.nn.functional.scaled_dot_product_attention, which leverages Flash Attention 2. This fused kernel computes attention without materializing the full matrix in high-bandwidth memory.

  • Result: Memory usage plummeted. I could instantly double the batch size from 4 to 8, and later 16.

Vocabulary Padding 📏

The standard GPT-2 vocabulary size is 50,257. This is an odd number that plays poorly with GPU hardware, which prefers powers of 2 (or multiples of 64/128) for efficient tiling.

  • Fix: We padded the vocabulary to 50,304 (the nearest multiple of 64).

  • Result: The final linear projection layer became significantly faster due to memory alignment.

Feeding the Beast (Data Loading) 🍽️

Profiling via nvidia-smi showed the GPU dropping to 0% utilization periodically. This meant the GPU was starving—waiting for the CPU to load the next batch of data.

  • Fix: We implemented a custom GPT2Dataset and used PyTorch’s DataLoader with num_workers=4 and pin_memory=True.

  • Result: Asynchronous data prefetching kept the GPU pinned at 99% usage. Throughput jumped to 63k tokens/sec.

Fused AdamW 🔥

The AdamW optimizer updates all 124 million parameters. Doing this sequentially in Python is slow due to interpreter overhead.

  • Fix: We set fused=True in torch.optim.AdamW.

  • Result: The entire optimizer step is launched as a single CUDA kernel, removing CPU overhead.

torch.compile (The Final Boss) 🛠️

PyTorch 2.0 introduced torch.compile, which JIT-compiles your model into optimized kernels (Triton). It fuses operations (like LayerNorm + Linear) to reduce memory access.

  • Result: This provided the final massive boost, pushing us over 92,000 tokens/sec.

4. The Results 📈

After all optimizations, the training run was stable and lightning-fast.

Loss Curve: Over 150 iterations, we can see loss droping continuously and shows model converging.

Performance Breakdown:

What did it learn?

After training for just a few hours, the model learned to generate Shakespearean-style text. It captures the vocabulary, the archaic grammar, and the dramatic structure of plays (Speakers, dialogue, stage directions).

Sample Output:

KING RICHARD II:
What implies this silence?
Tell me, what is the matter?

BOLINGBROKE:
My lord, I have acceptance of your grace,
And with a soul of love, I do beseech needed
remedy.

Next Steps:

As a next step, I am going to change the architecture to use recent advancements

1. Rotary Positional Embeddings (RoPE) 🔄

  • What it replaces: Learned Absolute Positional Embeddings (nn.Embedding(block_size, n_embd)).

  • Benefits:

    • Better generalization to sequence lengths longer than seen during training.

    • Relative position encoding property (tokens know how far apart they are).

    • Standard in Llama, PaLM, Mistral.

  • Implementation: Requires modifying

    CausalSelfAttention to rotate Q and K vectors.

2. RMSNorm (Root Mean Square Normalization) 📏

  • What it replaces: nn.LayerNorm.

  • Benefits:

    • Computationally cheaper (re-scaling invariance, no mean calculation).

    • Often leads to slightly better training stability.

  • Implementation: Drop-in replacement for LayerNorm.

3. SwiGLU Activation ⚡

  • What it replaces: GELU (Gaussian Error Linear Unit).

  • Benefits:

    • Demonstrated better performance than GELU/ReLU in compute-matched experiments (PaLM paper).

  • Implementation: Changes the MLP structure from x -> gelu(x * W_1) W_2

    to

    This adds parameters, so we usually reduce the hidden dimension from 4d to 8/3d (or similar) to keep parameter count roughly the same.

4. Grouped Query Attention (GQA) 🏎️

  • What it replaces: Multi-Head Attention (MHA).

  • Benefits:

    • Massively reduces KV cache size during interference.

    • Faster inference decoding speed.

    • Slightly degrades performance compared to MHA, but huge efficiency win.

  • Implementation: Sharing Key/Value heads across multiple Query heads.

5. Mixture of Experts (MoE) 🧠

  • What it replaces: Dense MLP layers.

  • Benefits:

    • Scale total parameters (capacity) without increasing compute per token (only top-k experts active).

    • “Sparse” model.

  • Complexity: High. Requires complex routing logic and balancing loss to prevent expert collapse. Might be overkill for a small 124M experiment, but fun to try.

Takeaway

You don’t always need more GPUs. Sometimes you just need better engineering.

By respecting the hardware—aligning memory, fusing kernels, and asynchronous loading—we squeezed 300% more performance out of the same card.

Check out the full code and try it yourself: View Project on GitHub

Connect with Vish on LinkedIn

Disclaimer: These are the personal opinions of the author(s). Any assumptions, opinions stated here are theirs and not representative of or attributable to their current or any prior employer(s). Apart from publicly available information, any other information here is not claimed to refer to any company including ones the author(s) may have worked in or been associated with.

Discussion about this video

User's avatar

Ready for more?