Source

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

Open the source

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.

- The repository provides simple C/CUDA implementations alongside PyTorch reference code for reproducing GPT-2 and GPT-3-series models. - Beginners can use frozen fp32 GPU or CPU implementations because they are simpler, more portable, and easier to understand. - Correctness is checked by comparing forward-pass outputs, losses, and training behavior against the PyTorch implementation. - The repository separates simple, readable mainline code from a more experimental `dev/` area for kernels and locally complex work. - Fast library kernels provide an expert performance upper bound against which manually written kernels can be measured. - Multi-GPU experiments can assign separate learning rates to separate GPUs and record logs for later plotting.

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

Supports these rules

Quotes from this video

“The best introduction to the llm.c repo today is reproducing the GPT-2 (124M) model.”

“I am also attaching a simple unit test for making sure our C code agrees with the PyTorch code.”

“This now loads the `gpt2_124M_debug_state.bin` file that gets written by train_gpt2.py, runs a forward pass, compares the logits and loss with the PyTorch reference implementation, then it does 10 iterations of training with Adam and makes sure the losses match PyTorch.”

“However, as a constraint, I want to keep the mainline `llm.c` in the root folder simple and readable.”

“If there is a PR that e.g. improves performance by 2% but it "costs" 500 lines of complex C code, and maybe an exotic 3rd party dependency, I may reject the PR because the complexity is not worth it.”

“I also think doing so serves an educational purpose to establish an expert upper bound, and a unit of measurement, e.g. you could say that your manually written kernels are 80% of cuBLAS speed,”

“Then you can choose to do a super fast run, or you can choose to "drag and drop" whatever manual kernels you wish to use, and run with those.”

“Lastly, I will be a lot more sensitive to complexity in the root folder of the project, which contains the main default files of the project.”

“In comparison, the `dev/` folder is a bit more of a scratch space for us to develop a library of kernels or classes and share useful or related or educational code, and some of this code could be ok to be (locally) complex.”

“debugging tip: when you run the `make` command to build the binary, modify it by replacing `-O3` with `-g` so you can step through the code in your favorite IDE (e.g. vscode).”

Topics