Train a GPT from the ground up
Build the full GPT stack yourself: BPE tokenizer, data pipeline, attention, blocks, a 124M-shaped model, a training loop, weight loading, then classifier tuning, SFT, DPO and an eval report on your own corpus.
Build it step by step
- 1BPE Tokenizer From ScratchPhase 19: Capstone projects
- 2Tokenized Dataset with Sliding WindowPhase 19: Capstone projects
- 3Token and Positional EmbeddingsPhase 19: Capstone projects
- 4Multi-Head Self-AttentionPhase 19: Capstone projects
- 5Transformer Block from ScratchPhase 19: Capstone projects
- 6GPT Model AssemblyPhase 19: Capstone projects
- 7Training Loop and EvaluationPhase 19: Capstone projects
- 8Loading Pretrained WeightsPhase 19: Capstone projects
- 9Capstone Lesson 38: Classifier Fine-Tuning by Head SwapPhase 19: Capstone projects
- 10Capstone Lesson 39: Instruction Tuning by Supervised Fine-TuningPhase 19: Capstone projects
- 11Capstone Lesson 40: Direct Preference Optimization from ScratchPhase 19: Capstone projects
- 12Capstone Lesson 41: Full Evaluation PipelinePhase 19: Capstone projects
What You'll Build
A complete decoder-only language model stack in PyTorch, written from primitives without transformers: a byte-level BPE tokenizer trained on a corpus you choose, a sliding-window dataset, embeddings, causal multi-head attention, pre-LN and post-LN blocks, a GPT model that matches the 124M reference shape, a measured training loop, a safetensors weight loader, and the three post-training stages (classifier head swap, instruction SFT, DPO) scored by a four-part eval pipeline. You train a small config end to end on your own text and report your own numbers.
Requirements
- Tokenizer. Byte-level BPE trained on a corpus you picked (at least 50 KB of text, for example public-domain books, your own notes, or a Wikipedia slice; say what it is). Reserve
<|endoftext|>and<|pad|>, apply merges by rank, and show exact round-trip on unseen text containing an emoji and a literal<|endoftext|>. Report encoded length of one held-out paragraph at two vocab sizes. - Data pipeline. A sliding-window
Datasetreturning shift-by-one(input, target)pairs, the example-count formulamax(0, 1 + (N - (T + 1)) // S), and a per-epoch seeded shuffle that repeats exactly across runs. - Embeddings and attention. Token, learned positional and sinusoidal embeddings with printed parameter counts; fused-QKV causal multi-head attention with
sqrt(d_head)scaling and a registered mask buffer. A test proves causality: changing tokens after position t does not change outputs at or before t. - Blocks and model. A
TransformerBlockwith apre_lnflag and a printed gradient-norm comparison of 6-layer pre-LN vs post-LN stacks. AGPTModelwhose 124M config (vocab 50257, context 1024, d_model 768, 12 heads, 12 layers, tied head) reports a unique parameter count of about 124 million, and a test that the head and token embedding share storage. - Generation. Temperature, top-k, multinomial sampling and a sliding context window; greedy mode is deterministic.
- Training. AdamW with the decay split (no decay on LayerNorm and bias), linear warmup plus cosine schedule, gradient clipping, held-out
evaluate_model, a sample from a fixed prompt every K steps, andlosses.jsonl. Train a small config on your corpus until validation loss clearly falls, and save a loss plot. - Weight loading. A loader that maps GPT-2 names to your local names, transposes the Conv1D-style weights, refuses shape mismatches before assigning, aliases the tied head and returns a
LoadReport(loaded, missing, unexpected, shape_mismatch). A stub safetensors fixture is fine; show a before-and-after generation that differs. - Classifier fine-tuning. Head swap with mask-weighted mean pooling, trained head-only and full fine-tune with one shared loop; report precision, recall, F1 and a confusion matrix for both on a held-out split.
- SFT.
<INST>/<RESP>formatting with a collate function that sets instruction, boundary and pad positions to -100; held-out exact-match with a per-category breakdown, before and after training. - DPO. Frozen reference, policy initialised as a copy, masked sequence log-probs, the DPO loss, a test of the gradient sign, and a printed chosen-minus-rejected margin that grows over training.
- Eval pipeline. Pad-excluded perplexity, normalised exact-match, token F1, a judge on a 1 to 5 scale (the deterministic mock judge, or a real one via an OpenAI-compatible endpoint), and a weighted aggregate written to
results/eval_report.json.
Constraints
- PyTorch on CPU is enough for every requirement. The 124M config is only built, counted and run for one forward pass (about 0.5 GB of RAM in fp32); you are not expected to train it.
- Train a small config (for example d_model 64 to 256, 2 to 6 layers, context 64 to 256) for minutes to about an hour on a laptop. A free GPU such as a Colab T4 is optional for a bigger run; say which hardware you used.
- Real GPT-2 weights (about 0.5 GB download) are optional; the stub fixture satisfies requirement 7. Fine-tuning datasets may be the lesson fixtures or small labelled sets you built yourself.
- No paid API key. A judge model is optional and may be any OpenAI-compatible endpoint, including the KatalockAi API or a local model.
Stretch Goals
- Load the real GPT-2 small weights into your model and compare its perplexity on your corpus with your own trained model.
- Add RoPE, RMSNorm and SiLU to turn the model into a LLaMA-style variant and compare loss curves.
- Add length normalisation or the IPO loss to DPO and compare margins.
How to Submit
Public repo with tokenizer/, model/, train.py, finetune/ (classifier, SFT, DPO), eval/, tests/ and results/ (losses.jsonl, loss plot PNG, eval_report.json, classifier and SFT metrics). The README must say how to run each stage in order, describe your corpus and why you chose it, give your config and hardware, show your loss curve and final numbers, explain the pre-LN vs post-LN and weight-tying results, and list what did not work the first time.
How It's Reviewed
Professor Katalock reads your repository and the evidence you paste, and scores each criterion out of 100. You pass with a weighted total of 70 or more and no criterion below 40. A copied or padded submission is flagged and fails.
Submit
Push your work to a public GitHub repository with a README that explains how to run it, then paste the evidence below. Up to 3 reviews a day, free.
- Terminal output of the tokenizer demo with round-trip checks and the two compression numbers
- Training log excerpt with eval loss and generated samples at probe steps, plus the loss plot image
- Parameter count output for the 124M config and the LoadReport summary
- Classifier, SFT and DPO metric printouts
- Contents of results/eval_report.json
- Output of `python -m pytest -q`
- One paragraph on what broke during training and how you diagnosed it
Reviews are done by AI against the rubric above. They check the evidence in your repository; they are not a substitute for a human code review, and a review can be wrong. If you think it is, improve the README so the evidence is unmistakable and resubmit.