KatalockAi AcademyBack to KatalockAi
Build track, required for the Phase 10 certificate

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.

about 40 h 12 guided steps Reviewed against a 7-point rubric
Submit your project Get coached by Professor Katalock

Build it step by step

  1. 1BPE Tokenizer From ScratchPhase 19: Capstone projects
  2. 2Tokenized Dataset with Sliding WindowPhase 19: Capstone projects
  3. 3Token and Positional EmbeddingsPhase 19: Capstone projects
  4. 4Multi-Head Self-AttentionPhase 19: Capstone projects
  5. 5Transformer Block from ScratchPhase 19: Capstone projects
  6. 6GPT Model AssemblyPhase 19: Capstone projects
  7. 7Training Loop and EvaluationPhase 19: Capstone projects
  8. 8Loading Pretrained WeightsPhase 19: Capstone projects
  9. 9Capstone Lesson 38: Classifier Fine-Tuning by Head SwapPhase 19: Capstone projects
  10. 10Capstone Lesson 39: Instruction Tuning by Supervised Fine-TuningPhase 19: Capstone projects
  11. 11Capstone Lesson 40: Direct Preference Optimization from ScratchPhase 19: Capstone projects
  12. 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

  1. 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.
  2. Data pipeline. A sliding-window Dataset returning shift-by-one (input, target) pairs, the example-count formula max(0, 1 + (N - (T + 1)) // S), and a per-epoch seeded shuffle that repeats exactly across runs.
  3. 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.
  4. Blocks and model. A TransformerBlock with a pre_ln flag and a printed gradient-norm comparison of 6-layer pre-LN vs post-LN stacks. A GPTModel whose 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.
  5. Generation. Temperature, top-k, multinomial sampling and a sliding context window; greedy mode is deterministic.
  6. 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, and losses.jsonl. Train a small config on your corpus until validation loss clearly falls, and save a loss plot.
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. 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.

CriterionWeightHow it's checked
Tokenizer and data pipeline15Round-trip test passes on emoji and special-token input; compression numbers at two vocab sizes are reported for the learner's own corpus; dataset tests pin the window-count formula, shift-by-one and seeded shuffle.
Model correctness15Causality test exists and passes; 124M config prints a count of about 124M with tying; shared-storage test passes; pre-LN vs post-LN gradient norms are printed.
Training results20losses.jsonl and the plot show train and validation loss falling on the learner's corpus; code has the decay split, warmup plus cosine and clipping; pasted samples change across probe steps.
Post-training stages20Classifier P/R/F1 and confusion matrix for both regimes, SFT exact-match before and after with -100 masking visible in the collate code, DPO margin increasing in the pasted log and a gradient-sign test, plus a LoadReport from the loader.
Eval pipeline10results/eval_report.json holds perplexity, EM, token F1, judge score and a weighted aggregate; perplexity code excludes padding and shifts targets correctly.
Code quality and tests10Modules split by stage, shared components imported rather than duplicated, pytest suite passes, seeds set for reproducibility.
README and explanation10README covers run order, corpus choice, config and hardware, the learner's own numbers, interpretation of results and an honest list of failures.

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.