Ismail Ben Alla

Tiny LLM

GPT-2 Reimplemented From Scratch

Generative AI · Aug 2023 · Completed

A GPT-2-style language model rebuilt line by line to understand how it works

Built withPyTorchLoRAOpenWebTexttiktokenHugging Face TransformersNumPyKaggle

Tiny LLM — overview

Overview

Large language models are easy to call and hard to understand. During my internship at 3D Smart Factory, I wanted to know exactly what happens inside GPT-2, so I rebuilt a GPT-2-style model from scratch in PyTorch with a small team of fellow interns.

I implemented causal self-attention by hand with a fast path through PyTorch's Flash Attention kernel, pre-LayerNorm decoder blocks, tied input and output embeddings, and my own LoRA layers for parameter-efficient fine-tuning. The model can also load the official GPT-2 weights into the same architecture.

I tokenized about 5 million files from OpenWebText, roughly a quarter of the corpus, with the GPT-2 r50k tokenizer, published that dataset on Kaggle, and trained on Kaggle GPUs. Training and validation loss fell together, from about 6.4 to below 4. It is my most-starred repository, and it was built for understanding, not state-of-the-art perplexity.

The question

Can I reimplement GPT-2 internals from scratch with modern improvements (Flash Attention, pre-LN) and actually train a coherent model?

Key features

How it works

  1. Prepare data

    About a quarter of OpenWebText is tokenized with the GPT-2 r50k tokenizer and stored as memory-mapped binary token streams for training and validation.

  2. Embed tokens

    Token and position embeddings are summed; the token embedding shares its weights with the output layer.

  3. Stack decoder blocks

    Each pre-LayerNorm block applies causal self-attention, then an MLP, each with a residual connection.

  4. Train

    Next-token cross-entropy with AdamW, warmup and learning-rate decay, gradient accumulation, and mixed precision on Kaggle GPUs.

  5. Fine-tune with LoRA

    Base weights are frozen and only small low-rank matrices are trained, then merged back into the weights.

Examples

Training and validation loss on the OpenWebText subset: both fall from about 6.4 to below 4 over roughly 2,250 iterations, staying close together.
Training and validation loss on the OpenWebText subset: both fall from about 6.4 to below 4 over roughly 2,250 iterations, staying close together.

Tech stack

What I learned

Limitations