I keep the main llm.c repository focused on C and CUDA, and I welcome links to separate ports and rewrites as notable forks. These alternatives cover different languages, frameworks, and hardware targets; the source does not compare their performance or recommend one for a particular use case.
The anthonix llm.c fork offers support for AMD devices, such as the 7900 XTX.
The azret llm.cs project is a C# port of this project.
The nietras Llm.cs project is a C# port of this project with focus on easy to get started on any platform. Clone and run ✅
The gevtushenko llm.cpp project is a port of this project using the CUDA C++ Core Libraries.
A presentation this fork was covered in this lecture in the GPU MODE Discord Server.
The zhangpiu llm.cpp project is a port of this project using the Eigen, supporting CPU/CUDA.
The AnswerDotAI gpu.cpp project is a library for portable GPU compute in C++ using native WebGPU. Aims to be a general-purpose library, but also porting llm.c kernels to WGSL.
The GaoYusong llm.cpp project is a port of this project featuring a C++ single-header tinytorch.hpp library.
The joshcarp llm.go project is a Go port of this project.
The harryjackson llm.java project is a Java port of this project.
The otabuzzman llm.swift project is a Swift port of this project.
The dorjeduck llm.🔥 project is a Mojo port of this project.
The krrishnarraj llm.c project is an OpenCL port of this project.
The Yijun Yu llm.rs project is a Rust rewrite with the aim to have same performance.
The ToJen llm.rs project is a Rust port of this project.
The Saimirbaci llm.zig project is a Zig port of this project.
The abhilash1910 llm.tpc project is a Habana Gaudi2 port of this project.
The Vindaar llm.nim project is a Nim port of this project.
For concrete repository issues, I recommend Issues for concrete repository issues.
For code contributions, I recommend opening a PR.
For repository chat and questions, I recommend Discussions for chat and questions.
For faster communication, I created a new #llmc channel on my Zero to Hero Discord channel.
I license llm.c under MIT.
I list the llm.metal project as LLM training in simple, raw C/Metal Shading Language.
I want llm.c to be both an educational resource and a practically useful, very fast training codebase.
I want dev/cuda to contain a well-documented library of manually written kernels for all layers, progressing from simple implementations to more complex or faster ones.
I welcome contributions of kernels with different tradeoffs.
My initial practical training target is reproducing the big GPT-2 (1.6B) training run.
I want to incorporate the fastest available kernels, including libraries such as cuBLAS, cuBLASLt, CUTLASS, and cuDNN, both to make training fast and to establish an expert upper bound for comparison.
I see an expert upper bound as an educational unit of measurement; for example, a manually written kernel might reach 80% of cuBLAS speed.
I want people to be able to choose a super-fast run or selectively use manual kernels alongside the library-backed path.
I want the mainline llm.c in the root folder to remain simple and readable, and I weigh performance gains against added complexity: a hypothetical 2% improvement might not justify 500 lines of complex C code and an exotic third-party dependency.
I consider cuBLAS the default for matmuls in the root training loop a no-brainer: it makes the mainline much faster through one interpretable line of code and a common dependency.
I want manual implementations that can compete with cuBLAS to live in dev/cuda; I am more sensitive to complexity in the root folder, while dev/ is a more flexible scratch space where locally complex kernel, class, and educational code can be appropriate.
I present the CPU example as fine-tuning GPT-2 small (124M) to output Shakespeare-like text, rather than training from scratch.
I recommend CPU training mainly as a demo/reference; unless the CPU is beefy, CPU training is unlikely to get far.
I can increase the number of OMP threads in the launch command for CPU training.
The CPU fine-tuning workflow initializes from GPT-2 (124M) weights in C and trains for 40 steps on Tiny Shakespeare with AdamW, batch size 4, and context length 64.
I can run make train_gpt2cu USE_CUDNN=1 to enable cuDNN Flash Attention.
For Ubuntu 22.04 with CUDA 12.x, the documented cuDNN installation includes sudo apt-get -y install libcudnn9-dev-cuda-12.
The cuDNN frontend is available from the cuDNN frontend repository and consists of header files.
I can run one of the repository’s training scripts under ./scripts/.
The multi-node NCCL examples include ./scripts/multi_node/run_gpt2_124M_mpi.sh.
The multi-node NCCL examples include ./scripts/multi_node/run_gpt2_124M_fs.sbatch.
The multi-node NCCL examples include ./scripts/multi_node/run_gpt2_124M_tcp.sbatch.
In a Slurm environment without PMIx support, I use the shared-filesystem or TCP approach for multi-node training.
The Slurm-WLM environment described in the documentation dropped PMIx support.
My dataset files use this layout: 1024-byte header followed by GPT-2-tokenizer token IDs stored as uint16.
On my MacBook Pro with Apple Silicon M3 Max, the CPU example reported 124439808 parameters; initial validation loss 5.252026; final validation loss 4.107781.
The selected CPU training results were: step 0: train loss 5.356189 (took 1452.121000 ms); step 1: train loss 4.301069 (took 1288.673000 ms); step 2: train loss 4.623322 (took 1369.394000 ms); step 3: train loss 4.600470 (took 1290.761000 ms); step 39: train loss 3.970751 (took 1323.779000 ms).
The CPU example reported these model and dataset dimensions: max_seq_len 1024; vocab_size 50257; 12 layers; 12 heads; 768 channels; 1192 training batches; 128 validation batches; 73323776 activations.
The Tiny Shakespeare data script wrote 32,768 validation tokens; 305,260 training tokens.
My tests check this coverage and expected result: CPU C/PyTorch comparison includes forward pass, logits, loss, and 10 Adam iterations; GPU tests cover fp32 and mixed precision; expected output overall okay: 1.
My layernorm tutorial is documented at doc/layernorm/layernorm.md; step-by-step guide to implementing one GPT-2 layer in C.
As of May 1, 2024, cuDNN Flash Attention was disabled by default; compile time increases from a few seconds to about a minute; code path is new.
For cuDNN setup, cuDNN dev package is sufficient; frontend consists of header files; Makefile searches home or current directory; CUDNN_FRONTEND_PATH can specify another location.
For multi-GPU training, the setup is MPI and NCCL; install OpenMPI with sudo apt install openmpi-bin openmpi-doc libopenmpi-dev; launch with mpirun -np <number of GPUs> ./train_gpt2cu.
My documented NCCL initialization methods are OpenMPI exchange, shared filesystem, or TCP sockets; none of the three methods is superior.
For multi-node setup, check PMIx with srun --mpi=list; without PMIx use shared filesystem or TCP; without Slurm use mpirun with OpenMPI initialization.
My learning-rate sweep used four rates 3e-5, 1e-4, 3e-4, 1e-3 on four GPUs and four screen sessions; -v 250, -s 250, -g 144; logs stories$i.log; plotting example dev/vislog.ipynb.
I built a low-level neural-network training implementation by manually implementing layer operations, managing memory, and then porting the work to CUDA. I shared early GPT-2 forward-pass benchmarks and documented the optimization techniques and next steps. This work connects to gpt 2 training benchmarks and low level model implementations.
My current focus in llm.c is pretraining, especially reproducing the GPT-2 and GPT-3 miniseries, alongside a parallel PyTorch reference implementation in train_gpt2.py.
I describe train_gpt2.py as a slightly tweaked version of my earlier nanoGPT project.
I coordinate llm.c development through GitHub Discussions and Discord: #llmc on Zero to Hero or #llmdotc on GPU MODE.
I can reproduce other models from the GPT-2 and GPT-3 series in both llm.c and the parallel PyTorch implementation; the scripts README has further details.
For the legacy 1-GPU fp32 learning path, I use the frozen code when I do not need multi-node training or mixed precision and want a simpler, more portable way to learn CUDA. The starter-pack script supplies the model, test data, tokenizer, and Tiny Shakespeare data before I build and run the training binary.
I recommend reproducing GPT-2 (124M) as the best introduction to llm.c; Discussion #481 walks through it in detail.
The README reports that llm.c is faster than PyTorch Nightly by about 7%.
I want this repository to maintain only C and CUDA code; ports to other languages or repositories should live separately, and I am happy to link them in the notable forks section.
The reference CPU fp32 implementation is about 1,000 lines of clean code in one file, train_gpt2.c.
When debugging a build, I replace -O3 with -g so I can step through the binary in an IDE such as vscode.
chmod u+x ./dev/download_starter_pack.sh
./dev/download_starter_pack.sh
make train_gpt2fp32cu
./train_gpt2fp32cu
The starter pack includes GPT-2 124M weights saved in fp32 and bfloat16, a unit-testing debug state with a small data batch plus target activations and gradients, the GPT-2 tokenizer, and tokenized Tiny Shakespeare data. I can instead generate the artifacts manually:
pip install -r requirements.txt
python dev/data/tinyshakespeare.py
python train_gpt2.py
The repository metadata lists 31,583 stars and 3,844 forks.
The repository started in 2024-04 and was last updated in 2025-06.
The README describes llm.c as avoiding the need for 245MB of PyTorch or 107MB of cPython.
I allocate all the required memory a single time in the beginning in one large block of 1D memory, then point the model weights and activations into that array.
During training, no memory gets created or destroyed, so we stay at constant memory footprint while streaming data batches through.
I manually implement the forward and backward pass of all the individual layers and then string them together; I described this as tedious and masochistic to write.
I have to make sure all the pointers and tensor offsets are correctly arranged, with careful pointer arithmetic connecting the memory layout.
Once I have the forward/backward, the rest of it (data loader, Adam update, etc) are mostly trivial.
I am now porting this to CUDA layer by layer so that it can be made efficient, perhaps even coming within reasonable fraction of PyTorch but without the heavy dependencies.
I'm a few layers in already, and I found it a fun CUDA exercise.
I considered extensions including lowering the precision from fp32 to fp16/below and adding layers such as RoPE to support modern architectures like llama 2, mistral, and gemma.
Once the implementation was a bit more stable, I planned videos on building this in more detail and from scratch.
I made a first quick pass of naive CUDA kernels for the GPT-2 forward pass and pushed the code into one file, llm.c, which was still only about 1,000 lines.
On my Lambda box with an A100 40GB PCIe, B=4, and T=1024, per-iteration timings were llm.c: 111ms, PyTorch: 180ms, +torch.compile: 86ms, and +fp32 tensor cores: 26ms.
I said there was a gap to close and invited people: “Come hack, make fast”.
A few new CUDA hacker friends joined the effort; I reported that llm.c was only 2X slower than PyTorch on the fp32 forward pass, compared with 4.2X slower four days earlier.
I also described the earlier result as 4.6X slower and the current result as 2X slower, so the post gives both 4.2X and 4.6X for the earlier comparison.
I turn on TF32 (NVIDIA TensorFLoat-32) instead of FP32 for matmuls; I described this as a nearly free optimization that sacrifices some precision for a large performance increase by using tensor cores.
With TF32, the mantissa is chopped to only 10 bits and the least significant 19 bits of the float get lost; inputs, outputs, and internal accumulates remain fp32 while multiplies are lower precision.
I noted that this TF32 setting is equivalent to PyTorch torch.set_float32_matmul_precision('high').
I call cuBLASLt API instead of cuBLAS for the sGEMM because it lets me fuse the bias into the matmul, eliminating a separate add_bias kernel and its global-memory round trip for one addition.
- For a more efficient attention kernel, I listed cooperative_groups reductions, the online softmax algorithm used in flash attention, a fused attention scaling-factor multiply, and built-in autoregressive mask bounds.
I said cooperative_groups reductions look much cleaner and that I had only just learned about them.
I thanked GitHub contributors ademeure, ngc92, lancerts for writing or helping with the kernels.
I was going to focus on the backward pass personally so that the full training loop would run in CUDA.
On 2024-04-13, I reported that llm.c reached 26.2ms/iteration, exactly matching PyTorch on a TF32 forward pass.
We found that a bug had us calling cuBLAS in fp32 mathmode instead of the intended TF32 mode.
ademeure contributed a more optimized softmax kernel for rows of 50,257 elements in the last logits layer.
At that stage, our attention kernel was naive rather than flash attention and materialized preattention and postattention matrices with shape (B, NH, T, T).
I identified unfused GeLU nonlinearities and permute/unpermute operations inside attention as unnecessary round-trips to remove.
I described training LLMs faster than PyTorch with only ~2,000 lines of C code as within reach.
In the earlier update I said llm.c was only 2X slower than PyTorch on an fp32 forward pass, compared with 4.2X slower four days earlier.
I described turning on TF32 instead of FP32 for matmuls as a very nice, ~free optimization: it trades a little precision for a large performance increase by running matmuls on tensor cores.
I said TF32 is a math mode on GPUs starting with Ampere+.
My next stated focus was the backward pass; I also named CUDA Graphs, flash attention, fusion, avoiding matrix materialization, and “lossless compressible memory (?)” as possible further optimizations rather than completed work.
On an A100 80GB, which I said had higher memory bandwidth, I reported llm.c at 23.026892, PyTorch 2.2 at 22.408ms, PyTorch nightly at 21.090ms, nightly with F.sdpa at 19.224ms, and nightly with F.sdpa plus coordinate descent tuning at 18.809ms.
With PyTorch team member @cHHillee's help, I improved the PyTorch baseline by upgrading to nightly, using the compound F.sdpa layer directly, and enabling TORCHINDUCTOR_COORDINATE_DESCENT_TUNING=1.
I characterized the best PyTorch configuration as about a 20% speedup and linked a fork for details: https://t.co/LT34GjWq9f.
I noted that torch compile can generate and emit C++ code: https://t.co/nQYoc8GTrG.
On 2024-04-19, I reported that a single file of 2,000 ~clean lines of C/CUDA trained GPT-2 (124M) on a GPU at speeds roughly matching PyTorch in fp32 without flash attention.
On my A100, I measured 78ms/iter for llm.c and 80ms/iter for PyTorch, using a slightly stale PyTorch 2.1.0.
llm.c directly implements the training loop and backpropagation in C/CUDA, compiles and runs instantly, removes the need for the Python interpreter and a deep learning library, and allocates all memory once at startup.
I compared manually writing custom CUDA kernels and inspecting CUDA PTX/SASS to programming in assembly, while seeing it as a way to hyperoptimize and explore optimizations torch.compile might find difficult.
For the backward pass, we used only a few buffers needed to propagate gradients, saving memory capacity.
One fused classifier kernel performed the last-layer forward pass, computed the loss, and kicked off the backward pass.
Our attention kernels gained performance by carefully constraining execution within the autoregressive mask.
We used cuBLAS(Lt) for heavy matrix multiplications and fused bias accumulation.
I credited CUDA experts ngc92 and ademeure with helping the open-source project.
My stated next steps were further fp32 kernel optimization, flash attention, fp16 mixed-precision training, multi-GPU training starting with DDP, setting up data and evaluations, reproducing GPT-2 (1.6B), exploring architectures such as Llama 3, and creating educational materials.
On May 3, 2024, at llm.c Day 24, I reported multi-GPU training, bfloat16, and flash attention in approximately 3,000 lines of C/CUDA.
I reported llm.c running approximately 7% faster than PyTorch nightly and approximately 46% faster than stable PyTorch 2.3.0; the nightly baseline included mixed precision, torch compile, flash attention, and manually padded vocabulary.
I said the speed comparison was meant to show that llm.c is fast, not to cast shade on PyTorch, whose generic support for arbitrary neural networks and many platforms I called really amazing; I see the projects as having different, complementary goals.
I started llm.c with upcoming educational videos in mind, to explain what PyTorch does under the hood.
Over approximately 1.5 weeks, we added bfloat16 training, kernel optimizations, FusedClassifier, cuDNN flash attention, and Packed128, which forces A100 128-bit LDG.128 loads and STS.128 stores.
FusedClassifier avoids materializing normalized logits, unlike current torch.compile.
The first version of llm.c multi-GPU training used MPI+NCCL, and I reported profiling full training runs with NVIDIA Nsight Compute.
I said a PR for stage 1 of ZeRO, optimizer-state sharding, was expected to merge imminently.
I said the project was still at 3,000 lines of C/CUDA, compared with roughly 3 million lines.
I split the fp32 codebase into its own file, planned to make it pure CUDA kernels without cuBLAS or cuDNN, and saw it as a possible endpoint for a CUDA course beginning with the pure-CPU gpt2.c implementation.
My goal was a reliable, clean, tested, minimal, hardened, sufficiently optimized LLM stack that reproduces the GPT-2 miniseries from 124M to 1.6B directly in C/CUDA.
Related: llama2 c, low level model implementations, minimal gpt training code