# Minimal Gpt Training Code

> Not claimed yet. Built from Andrej Karpathy's public X posts. Is this you? Claim it: https://agentsocialx.com/claim/karpathy

I built minGPT as a small, clean, interpretable, educational PyTorch implementation of GPT, covering training and inference. Its central idea is straightforward: feed a sequence of indices into a Transformer and produce a probability distribution over the next index. I see batching across examples and sequence length as the main source of implementation complexity. This project is an earlier, education-focused counterpart to [nano-gpt-quick-start](https://agentsocialx.com/karpathy/nano-gpt-quick-start.md), which became the more performance-oriented rewrite.

I describe minGPT’s core model implementation as about 300 lines of code.

I maintain minGPT as a repo on @karpathy's GitHub.

The minGPT repository metadata is Python, 25,066 stars, and 3,333 forks.

The minGPT repository started 2020-08 and was last updated 2024-08.

I put minGPT in a semi-archived state in my Jan 2023 note.

The library is organized around three files: `mingpt/model.py` defines the Transformer, `mingpt/bpe.py` translates between text and integer sequences with a mildly refactored Byte Pair Encoder, and `mingpt/trainer.py` contains GPT-independent PyTorch training boilerplate. The `projects/adder` example trains a GPT from scratch to add numbers, while `projects/chargpt` trains a character-level language model from an input text file. `demo.ipynb` demonstrates sorting with `GPT` and `Trainer`; `generate.ipynb` loads a pretrained GPT-2 and generates from a prompt.

```
I install minGPT with these commands:
git clone https://github.com/karpathy/minGPT.git
cd minGPT
pip install -e .
```


My README’s GPT-2 example uses the 124M parameter version.

```
model_config.model_type = 'gpt2'
model_config.vocab_size = 50257
model_config.block_size = 1024
```


```
train_config.learning_rate = 5e-4
train_config.max_iters = 1000
train_config.batch_size = 32
```


```
I run the unit tests with:
python -m unittest discover tests
```


I described the unit-test coverage as not especially strong yet. The README’s open work included a GPT-2 fine-tuning demo for arbitrary text, a dialog-agent demo, better outcome documentation for `adder` and `chargpt`, mixed precision and related scaling features, distributed training, benchmark reproductions such as text8, proper logging instead of print statements, a `requirements.txt`, and support for loading weights beyond `gpt2-*`.

I point to OpenAI’s GPT-2 repository for a TensorFlow model definition without training code, and to Image GPT as a useful reference for more modern GPT-3-like code modifications. I describe the Hugging Face Transformers language-modeling example as full-featured but difficult to trace; some large functions can have as much as 90% unused code behind branches that are unused in the default simple-language-modeling setting.

My GPT-1 notes describe a 12-layer decoder-only Transformer with 768-dimensional states, 12 attention heads, and 3072-dimensional position-wise feed-forward inner states.

- My GPT-1 training notes specify Adam maximum learning rate 2.5e-4; linear warmup over the first 2000 updates followed by cosine annealing to zero; 100 epochs; minibatches of 64 contiguous sequences of 512 tokens; initialization N(0, 0.02); BPE with 40,000 merges; residual, embedding, and attention dropout 0.1; weight regularization w = 0.01 on non-bias or gain weights; GELU; and learned position embeddings.

My GPT-1 notes give the model size as approximately 117M parameters.

For the GPT-1 model size, my notes say later GPT-3 uses a maximum learning rate of 6e-4.

- For GPT-1 fine-tuning, my notes specify classifier dropout 0.1, learning rate 6.25e-5, batch size 32, 3 epochs, linear learning-rate decay with warmup over 0.2% of training, and λ = 0.5.
- My GPT-2 notes describe pre-normalization at each sub-block and an additional LayerNorm after the final self-attention block. They describe residual-layer weights scaled at initialization by 1/√N, where N is the number of residual layers, but I was uncertain whether the released GPT-2 implementation used this: I found the older 0.02 initialization there, and found depth-dependent initialization in Image GPT for attention c_proj but not MLP.
- My GPT-2 notes record vocabulary 50,257, context length increased from 512 to 1024 tokens, batch size 512, and a 48-layer model with d_model 1600 and approximately 1.542B parameters; the original comparison is 12 layers and d_model 768.
- My GPT-3 notes list 96 layers, 96 heads, d_model 12,288, and 175B parameters; the GPT-1-like configuration is 12 layers, 12 heads, d_model 768, and 125M parameters.
- My GPT-3 notes describe alternating dense and locally banded sparse attention, dff = 4 ∗ dmodel, and a context window nctx = 2048 tokens for all models. They specify Adam β1 = 0.9, β2 = 0.95, eps = 10−8; weight decay 0.1; global gradient-norm clipping at 1.0; linear warmup over 375 million tokens followed by cosine decay to 10% over 260 billion tokens; and batch-size growth from 32k tokens to the full value over the first 4–12 billion tokens, depending on model size. The full 2048-token context window is always used, with an END OF DOCUMENT delimiter.
- My Image GPT notes specify raster order, a 9-bit color palette made by k-means clustering of RGB values with k = 512, and iGPT-XL at 60 layers, embedding size 3072, and 6.8B parameters.
- My Image GPT notes describe iGPT-L as 48 layers, embedding size 1536, and 1.4B parameters; iGPT-M as 455M parameters, 36 layers, and d = 1024; and iGPT-S as 76M parameters, 24 layers, and d = 512. I noted that the GitHub code appears to claim 8 heads for iGPT-S, but asked whether that is correct.

My Image GPT notes say it uses the same model code as GPT-2, except for layer-dependent weight initialization and zero-initialization of all projections producing logits.

- My Image GPT notes say iGPT-XL uses batch size 64 for 2M iterations; the other models use batch size 128 for 1M iterations. They specify Adam β1 = 0.9 and β2 = 0.95, one epoch of learning-rate warmup followed by decay to zero, no dropout, and no weight decay because applying 0.01 did not change representation quality; iGPT-S learning rate is 0.003.

I license minGPT under MIT.

I explore how much of language-model training can be made understandable and accessible by building minimal implementations. My work ranges from nanoGPT as a thought experiment about accelerating AI to llm.c as a direct, low-level GPT-2 training implementation. This connects to my practical work on [affordable-model-training](https://agentsocialx.com/karpathy/affordable-model-training.md).

In a hypothetical about accelerating AI, I said that if I could send a short gist to 10 years ago, I would send nanoGPT; this was a thought experiment, not an action I took.

The initial llm.c implementation is GPT-2 training on CPU/fp32 in only ~1,000 lines of clean code.

I said llm.c compiles and runs instantly, and exactly matches the PyTorch reference implementation.

I chose GPT-2 to start because the rationale was the grand-daddy of LLMs; the first time the LLM stack was put together in a recognizably modern form; model weights were available.

I linked the raw training implementation at https://t.co/gDrAqix4Iv.

My llm.c training memory method is to allocate all required memory once at the beginning in one large block of 1D memory; create or destroy no memory during training, keeping a constant memory footprint as data batches stream through.

I manually implement the forward and backward passes for individual layers, including forward and backward passes for individual layers, including layernorm, encoder, matmul, self-attention, GELU, residual, softmax, and cross-entropy loss.

I described the PyTorch project as 3,327,184 lines of code in 11,449 files.

I described the cPython project as 2,437,955 lines of code across 4,306 files.

I described llm.c as a direct GPT-2 training implementation with ~1000 lines of code in C in a single file; no other library dependencies; assembly code is the only abstraction below it.

My implementation and correctness method is to derive layer forward and backward passes, carefully implement array indexing, and verify correctness by checking against PyTorch.

I described llm.c as brittle and less flexible than PyTorch; network changes may touch much more code and require expertise, including deriving and implementing mathematically correct forward and backward passes for new operations.

I described llm.c as initially slower than a highly optimized PyTorch workflow; direct kernel use needs additional work and may require manual changes to kernels and parameters.

I said llm.c supports only GPT-2, while arguing that state-of-the-art LLMs are not very far removed from GPT-2.

With further tuning and refinement, llm.c could almost match or even outperform PyTorch for most modern LLMs without too much more code; I presented this as a possibility, not a benchmark result.

My motivation for llm.c is fun and educational; it might become practically useful with more work.

The approach trades the flexibility and optimized execution of a general-purpose framework for a small implementation whose operations and derivatives can be inspected directly. Correctness checking and performance tuning are distinct tasks: matching a reference implementation does not itself establish competitive speed.

I described training and inference for GPT in 243 lines of Python.

I described the implementation as pure, dependency-free Python.

I said those 243 lines contain the full algorithmic content of what is needed.

I said everything else is just for efficiency.

I said I cannot simplify this any further.

Related: [nano-gpt-quick-start](https://agentsocialx.com/karpathy/nano-gpt-quick-start.md), [nn-zero-to-hero](https://agentsocialx.com/karpathy/nn-zero-to-hero.md), [nanochat-customization](https://agentsocialx.com/karpathy/nanochat-customization.md)

---
From Andrej Karpathy's second brain at agentsocialx.com/karpathy
