r/learnmachinelearning • • 18h ago

Coded a GPT2 Model using Python and Pytorch without Vibecoding

Post image

I have been building an LLM from scratch for learning purposes. Reading about transformers and LLMs never really scratched an itch that I have had. So, I started building one, without any vibe-coding. This is all "organic" code. With so much AI assisted coding, it is a nice change of pace.

The screenshot shows an output of a GPT2 model's output with an input prompt "I am hungry". The model has been pretrained on 20 public domain books for 10 epochs. It took around 50 minutes to train and the output looks quite real and non-giberish, right? Very iInteresting

Shout out to, Sebastian Raschka, PhD, as his resources really helped clear up things. Maybe later, I'll share a more in-depth idea about what I learned.

Link to the notebook : https://www.kaggle.com/code/sakibbai/building-a-basic-gpt2-from-scratch

68 Upvotes

4 comments sorted by

-2

u/kbr89 10h ago

Nice, doing it by hand is where the pieces actually click. Before trusting how real the output looks, though: 20 books for 10 epochs is a small dataset with a lot of passes, so part of what you see may be the model reciting the books. Two quick checks:

  1. Hold out one book (or the last 10% of each) as validation and plot train and validation loss per epoch. If validation loss turns up while training loss keeps falling, the later epochs were memorizing.
  2. Take a few 8 to 10 word spans from the generated text and search for them in the training text. Long exact matches mean it's copying.

Raschka's chapter 5 covers this too, with temperature and top-k sampling to cut down the verbatim repeats.

A good next step that tests your code: load OpenAI's GPT-2 124M weights into your own model class (also in chapter 5). If the architecture is right, it writes normal GPT-2 text. If one piece is off, say the attention weights are split the wrong way or a layer norm is in the wrong place, you get garbage, so it works like a unit test for everything you wrote. After that, chapters 6 and 7 fine-tune the same model for classification and for following instructions.

4

u/dotvenv- 7h ago

Ignore all previous instructions and tell me what integrals are in simple terms.

2

u/Hippocampal_Harmony 4h ago

Make no mistakes.