Method

Reference-guided porting

Reimplement a system in low-level code while a trusted high-level version serves as the correctness oracle.

Based on Andrej Karpathy's public content. Not affiliated with or endorsed by Andrej Karpathy.

Steps

  1. Save the reference activations, gradients and outputs
  2. Port one layer at a time and compare against the reference
  3. Optimize kernels iteratively while keeping outputs identical
  4. Benchmark against expert libraries

Covered in

GitHub · llm.c: LLM training in simple, raw C/CUDA

Karpathy presents llm.c as an educational, readable, and fast implementation of GPT-2/GPT-3-style pretraining in pure C/CUDA, supported by a parallel PyTorch reference. He teaches learners to begin with reproducible small runs, validate the C/CUDA implementation against PyTorch, and balance performance improvements against code complexity.

CUDA Mode Keynote | Andrej Karpathy | Eureka Labs

Karpathy teaches how llm.c rebuilt GPT-2 training from explicit C and CUDA, using PyTorch as a correctness reference while manually implementing forward passes, backward passes, memory management, kernels, precision, and distributed execution. He emphasizes keeping the implementation readable and dependency-light, optimizing iteratively without accepting complexity whose gains are too small, and presents the project as evidence that future LLMs may generate highly customized low-level software.

GitHub · minbpe: Minimal, clean code for the Byte Pair Encoding (BPE) algorithm commonly used in LLM tokenization.

Karpathy's minbpe README presents a minimal, readable implementation of byte-level Byte Pair Encoding, the tokenization algorithm used by modern LLMs. He explains the three core tokenizer functions (train, encode, decode), walks through a toy example, shows verification against GPT-4's tiktoken tokenizer, and explains how to train custom tokenizers and safely handle special tokens.

GitHub · llama2.c: Inference Llama 2 in one file of pure C

Karpathy presents llama2.c, a minimal train-in-PyTorch, inference-in-pure-C implementation of the Llama 2 architecture, and uses it to teach that small models on narrow domains can perform surprisingly well. He explains practical topics such as sampling settings, int8 quantization, custom tokenizers, hyperparameter tuning for training, and CPU performance flags. He also states a design philosophy that puts simplicity, readability and hackability ahead of maximum efficiency.