cd /news/artificial-intelligence/nanogpt-speedrun · home topics artificial-intelligence article
[ARTICLE · art-107475] src=github.com ↗ pub= topic=artificial-intelligence verified=true sentiment=↑ positive

NanoGPT Speedrun

The NanoGPT speedrun repository reports that a collaborative effort has trained a language model to 3.28 cross-entropy loss on the FineWeb validation set in under 75 seconds on 8 NVIDIA H100 GPUs, a dramatic improvement over Andrej Karpathy's llm.c GPT-2 replication which required 45 minutes and 10B tokens. The speedup, achieved through techniques like rotary embeddings, QK-Norm, ReLU², the Muon optimizer, FP8 precision, and Flash Attention 3, reduces token usage to under 400M.

read13 min views1 publishedAug 23, 2026
NanoGPT Speedrun
Image: Michielbdejong (auto-discovered)

This repository hosts the NanoGPT speedrun, in which we (collaboratively|competitively) search for the fastest algorithm to use 8 NVIDIA H100 GPUs to train a language model that attains 3.28 cross-entropy loss on the FineWeb validation set.

(Note: Besides the main track, there is also an optimization track where we try to minimize steps subject to fixed arch/data/bsz and with unlimited wallclock budget.)

The target (3.28 validation loss on FineWeb) follows Andrej Karpathy's GPT-2 replication in llm.c, which attains that loss after running for 45 minutes. The speedrun code also descends from llm.c's PyTorch trainer, which itself descends from NanoGPT, hence the name of the repo. Thanks to the efforts of many contributors, this repo now contains a training algorithm which attains the target performance in:

  • Under 75 seconds on 8xH100 (the llm.c GPT-2 replication needed 45 minutes)
  • under 400M tokens (the llm.c GPT-2 replication needed 10B)

This improvement in training speed has been brought about by the following techniques:

  • Modernized architecture: Rotary embeddings, QK-Norm, and ReLU²
  • The Muon optimizer [ writeup] [repo] - Use FP8 for head, and asymmetric rescale and softcap logits
  • Use FP8 on MLP forward pass
  • Initialization of projections to zero (muP-like)
  • Skip connections from embedding to every block as well as from block 3 to 6
  • Extra embeddings which are mixed into the values in attention layers (inspired by Zhou et al. 2024)
  • Flash Attention 3 with long-short sliding window attention pattern (inspired by Gemma 2) and window size warmup with YaRN
  • Align training batch starts with EoS and set a max document length
  • Accumulate gradients for 2 steps for embedding and lm_head before updating parameters
  • Single activation input for last 3 attention layers
  • Polar Express implementation in Muon
  • Smear module to enable 1 token look back
  • Sparse attention gate
  • NorMuon
  • Cautious Weight Decay w/ schedule tied to LR
  • Exponential decay of residual stream
  • Batch size schedule
  • Max seq length schedule
  • Partial Key Offset
  • Multi token prediction
  • Untie embed and lm_head at 2/3 of training
  • Additional gating on value embeddings and skip connection
  • Paired head attention
  • Bigram hash embedding on 1/4 of model_dim w/ sign trick
  • MUDD skip connections to residual stream and attention values
  • Learnable XSA
  • Lightweight Dynamically Composable MHA
  • Prefix token prediction auxiliary loss

As well as many systems optimizations.

Contributors list (growing with each new record): @bozavlado; @brendanh0gan; @fernbear.bsky.social; @Grad62304977; @jxbz; @kellerjordan0; @KoszarskyB; @leloykun; @YouJiacheng; @jadenj3o; @KonstantinWilleke, @alexrgilbert, @adricarda, @tuttyfrutyee, @vdlad; @ryanyang0, @vagrawal, @classiclarryd, @byronxu99, @varunneal, @EmelyanenkoK, @bernard24/https://www.hiverge.ai/, @Gusarich, @li_zichong, @akash5474, @snimu, @roeeshenberg, @ChrisJMcCormick, @dominikkallusky, @acutkosky, @manikbhandari, @andrewbriand, @jrauvola, @soren_dunn_, @photon_mz, @srashedll, @dhrvji, @EmmettBicker, @dualverse-ai, @sisovicm, @moof2x, @samacqua, @Lisennlp, @_djdumpling, @TrianX, @aryavohra, @cong_ml, @jvarho, @Mister-dev-oss, @CerovazS, @MarioPaerle, @GabrieleCirillo, @crisostomi

To run the current record, run the following commands.

git clone https://github.com/KellerJordan/modded-nanogpt.git && cd modded-nanogpt
pip install -r requirements.txt
python data/cached_fineweb10B.py 9
./run.sh

Add torchrun to path if ./run.sh gives error torchrun: command not found

.

Note: torch.compile will add around 7 minutes of latency the first time you run the code.

Official records are timed on 8 NVIDIA H100 GPUs from https://app.primeintellect.ai/. PrimeIntellect has generously sponsored recent validation runs.

For cases where CUDA or NCCL versions aren't compatible with your current system setup, Docker can be a helpful alternative. This approach standardizes versions for CUDA, NCCL, CUDNN, and Python, reducing dependency issues and simplifying setup. Note: an NVIDIA driver must already be installed on the system (useful if only the NVIDIA driver and Docker are available).

git clone https://github.com/KellerJordan/modded-nanogpt.git && cd modded-nanogpt
sudo docker build -t modded-nanogpt .
sudo docker run -it --rm --gpus all -v $(pwd):/modded-nanogpt modded-nanogpt python data/cached_fineweb10B.py 8
sudo docker run -it --rm --gpus all -v $(pwd):/modded-nanogpt modded-nanogpt sh run.sh

To get an interactive docker, you can use

sudo docker run -it --rm --gpus all -v $(pwd):/modded-nanogpt modded-nanogpt bash

The following is the historical progression of world speed records for the following competitive task:

Train a neural network to ≤3.28 validation loss on FineWeb using 8x NVIDIA H100s.

Note: The 3.28 target was selected to match Andrej Karpathy's GPT-2 (small) reproduction.

# Record time Description Date Log Contributors
1 45 minutes

logTuned learning rate & rotary embeddingslogIntroduced the Muon optimizerMuon improvementslogPad embeddings, ReLU², zero-init projections, QK-normlogDistributed the overhead of MuonlogUpgraded PyTorch 2.5.0logUntied embedding and headlogValue and embedding skip connections, momentum warmup, logit softcaplogBfloat16 activationslogU-net pattern skip connections & double lrlog1024-ctx dense causal attention → 64K-ctx FlexAttentionlogAttention window warmuplogValue EmbeddingslogU-net pattern value embeddings, assorted code optimizationslogSplit value embeddings, block sliding window, separate block masklogSparsify value embeddings, improve rotary embeddings, drop an attn layerlogLower logit softcap from 30 to 15logFP8 head, offset logits, lr decay to 0.1 instead of 0.0logMerged QKV weights, long-short attention, attention scale, lower Adam epsilon, batched MuonlogReduced batch sizeloglogupdated ruleslogFaster gradient all-reducelogOverlap computation and gradient communicationlogloglogloglog,PRlog,PRlog,PRlog,PRlog,PRlog,PRhiverge.ailog,PRlog,PRlog,PRlog,PRlog,PRlog,PRlog,PRlog,PRNorMuonlog,PRlog,PRlog,PRProfiling 101log,PRlog,PRBatch size schedulelog,PRMultiply attn lambda with weight instead of data, fix warmuplog,PRSpeed up Muon, additional pre-multiply lambda, reshape matrices, update lr, update NorMuon axislog,PRPartial Key Offsetlog,PRExtend Cautious Weight Decay to Adam parameterslog,PRRetie Embed to lm_head, retune fp8 scaleslog,PRSmooth scalars via beta increase, decrease smear gate lr, freeze scalars during transitions, adam all reducelog,PRMulti-token prediction, untie embed/lm_head at 2/3 training, lr update, tweak CWDlog,PRAsymmetric Logit Rescalelog,PRGates on value embeds and skip connectionlog,PROptimize and compile Adam, increase Adam buffer precision, move gates from Muon to Adam parameter bankslog,PRBfloat16 attn/mlp weights, mixed precision Muon, interweave Adam/Muon, finer-grain Adam betalog,PRPaired Head Attentionlog,PRFused triton kernel for linear relu square MLP steplog,PRFused triton kernel for softcapped multi-token prediction cross entropy steplog,PRLocusUnified Optimizers and Transposed LM Headlog,PRBigram Hash Embeddinglog,PRUntie Value Embedslog,PRTuned nonzero Attn V and O initlog,PRGroup Value Embeds into single parameterlog,PRTune fused softcap kernels and fuse fp8 quantization in LM headlog,PRMove bigram hash to GPUlog,PRKernel Optimizationslog,PRAsterTune value embed layout and ve_gateslog,PRSparse bigram gradient comms and optimized on CPUlog,PRIncrease minimum lr and add max_seq_len schedulelog,PRStationPartitioned Hyperconnectionslog,PRFlattened GPT forward, removed post attention lambdas, added transpose kernelslog,PRCross Entropy Kernel Optimizationslog,PRReuse and tune backward transpose kernellog,PRReplace partitioned hyperconnections with single saved activationlog,PRTighten bounds on fa3 max_num_docs to match fineweb distributionlog,PRFuse Cross Entropy Fwd/Bwk Kernel, to avoid recalc on softcap sigmoidlog,PRIn Muon orthogonize Q and K matrices in pairs of heads, instead of across the full 6 head matrixlog,PRMUDD Skip Connectionslog,PRLearnable XSAlog,PRSign Trick on Bigram Embedlog,PRFP8 on MLP up-projection forward passlog,PRMUDD gates and Lightweight Dynamically Composable MHAlog,PRAlgebraic rewrite of XSA, same math faster executionPRFaster Implementation of Relu^2 Kernellog,PRRecursivePrefix token prediction auxiliary losslog,PRMLP down projection in FP8 with efficient delayed scaling metriclog,PRNew records must:

  • Not modify the train or validation data pipelines. (You can change the batch size, sequence length, attention structure etc.; just don't change the underlying streams of tokens.)
  • Attain ≤3.28 mean val loss. (Due to inter-run variance, submissions must provide enough run logs to attain a statistical significance level of p<0.01 that their mean val loss is ≤3.28. Example code to compute p-value can be found here. For submissions which improve speed by optimizing the systems performance, without touching the ML, this requirement is waived.) - Not use any extra torch._inductor.config

ortorch.compile

flags. (These can save a few seconds, but they can also make compilation take >30min. This rule was introduced after the 21st record.) - Run faster than the prior record when baselined on the same hardware.

Incorporating open PRs into a new record is strongly encouraged. This speeds up merges through peer validation and prevents new PRs from going stale due to conflicts with earlier, still-open PRs.

Discretionary reasons why a PR may not be accepted:

  • Disproportionately degrades the readability of the codebase. A 200 line kernel to drop 300ms is considered worthwhile. 500 lines that convolute the optimizer layout for a 50ms gain will likely be rejected.
  • The current record is intentionally kept roughly 0.001-0.002 loss below 3.28 to make validation simpler. If a PR substantially consumes this buffer, it should do so in a way that outperforms a simple step count decrease, when measured at equivalent loss.

Note:

torch._inductor.config.coordinate_descent_tuning

is allowed for GPT-2 Medium track (a.k.a. 2.92 track).

Other than that, anything and everything is fair game!

The target metric is cross-entropy loss on the FineWeb val set. To speak mathematically, the goal of the speedrun is *to obtain a probability model of language which assigns a probability of at least math.exp(-3.28 * 10485760)

to the first 10,485,760 tokens of the FineWeb valset. Hence, e.g., we allow evaluation at any sequence length, so long as we still have a valid probability model of language.

After the 21st record, we made two changes to the timing. First, there used to be an initial "grace period" of 10 untimed steps to allow kernel warmup. We replaced this with an explicit kernel-warmup section which is untimed and uses dummy data. This results in an extra runtime of 850ms from the 10 extra timed steps. Second, we banned the use of torch._inductor.config.coordinate_descent_tuning

. This saves ~25min of untimed pre-run compilation, but results in an extra runtime of ~3s.

Notable runs:

@alexjc's 01/20/2025 2.77-minute TokenMonster-based record. This record is technically outside the rules of the speedrun, since we specified that the train/val tokens must be kept fixed. However, it's very interesting, and worth including. The run is not more data-efficient; rather, the speedup comes from the improved tokenizer allowing the vocabulary size to be reduced (nearly halved!) while preserving the same bytes-per-token, which saves lots of parameters and FLOPs in the head and embeddings.@samacqua's 1/23/2026 test time training run. Sam found that prediction accuracy on the later portions of a given document could be improved by performing a training update on Adam parameters based on the early portion of the document. This 'parameter nudging' is repeated independently for each document. Interestingly, these gradient updates prove effective while only using ~500 tokens, substantially less than the over 200k tokens typically used on a normal training step. While technically a valid probability model, we are not allowing untimed backward passes.

Notable forks:

The target loss for this track is lowered from 3.28 to 2.92, as per Andrej Karpathy's 350M-parameter llm.c baseline. This baseline generates a model with performance similar to the original GPT-2 Medium, whereas the first track's baseline generates a model on par with GPT-2 Small. All other rules remain the same.

Note:

torch._inductor.config.coordinate_descent_tuning

is turned on after the record 6 (*).

# Record time Description Date Log Contributors
1 5.8 hours

logInitial record based on scaling up the GPT-2 small track speedrunlogAdded standard weight decaylogTuned Muon Newton-Schulz coefficientslogIncreased learning rate cooldown phase durationlog2x MLP wd, qkv norm, all_reduce/opt.step() overlap, optimized skip patternlogRemove FP8 head; ISRU logits softcap; New sharded mixed precision Muon; merge weightslogCubic sliding window size schedule, 2× max window size (24.84 minutes)24.5min reprologAdd two value embeddingslog,PRSecond input embeddinglog,PRlog,PRlog,PRlog,PRlog,PRlog,PRlog,PRlog,PRA: The officially stated goal of NanoGPT speedrunning is as follows: gotta go fast

. But for something a little more verbose involving an argument for good benchmarking, here's some kind of manifesto, adorned with a blessing from the master. https://x.com/karpathy/status/1846790537262571739

A: Because it is a competitive benchmark. In particular, if you attain a new speed record (using whatever method you want), there is an open invitation for you to post that record (on arXiv or X) and thereby vacuum up all the clout for yourself. I will even help you do it by reposting you as much as I can.

Q: NanoGPT speedrunning is cool and all, but meh it probably won't scale and is just overfitting to val loss

A: This is hard to refute, since "at scale" is an infinite category (what if the methods stop working only for >100T models?), making it impossible to fully prove. Also, I would agree that some of the methods used in the speedrun are unlikely to scale, particularly those which impose additional structure on the network, such as logit softcapping. But if the reader cares about 1.5B models, they might be convinced by this result:

Straightforwardly scaling up the speedrun (10/18/24 version) to 1.5B parameters yields a model with GPT-2 (1.5B)-level HellaSwag performance 2.5x more cheaply than @karpathy's baseline ($233 instead of $576):

Muon is defined as follows:

Where NewtonSchulz5 is the following Newton-Schulz iteration [2, 3], which approximately replaces G

with U @ V.T

where U, S, V = G.svd()

.

@torch.compile
def zeroth_power_via_newtonschulz5(G, steps=5, eps=1e-7):
    assert len(G.shape) == 2
    a, b, c = (3.4445, -4.7750,  2.0315)
    X = G.bfloat16() / (G.norm() + eps)
    if G.size(0) > G.size(1):
        X = X.T 
    for _ in range(steps):
        A = X @ X.T
        B = b * A + c * A @ A
        X = a * X + B @ X
    if G.size(0) > G.size(1):
        X = X.T 
    return X.to(G.dtype)

For this training scenario, Muon has the following favorable properties:

  • Lower memory usage than Adam
  • ~1.5x better sample-efficiency
  • <2% wallclock overhead

Many of the choices made to generate this optimizer were obtained experimentally by our pursuit of CIFAR-10 speedrunning. In particular, we experimentally obtained the following practices:

  • Using Nesterov momentum inside the update, with orthogonalization applied after momentum.
  • Using a specifically quintic Newton-Schulz iteration as the method of orthogonalization.
  • Using non-convergent coefficients for the quintic polynomial in order to maximize slope at zero, and thereby minimize the number of necessary Newton-Schulz iterations. It turns out that the variance doesn't actually matter that much, so we end up with a quintic that rapidly converges to the range 0.68, 1.13 upon repeated application, rather than converging more slowly to 1.
  • Running the Newton-Schulz iteration in bfloat16 (whereas Shampoo implementations often depend on inverse-pth-roots run in fp32 or fp64).

Our use of a Newton-Schulz iteration for orthogonalization traces to Bernstein & Newhouse (2024), who suggested it as a way to compute Shampoo [5, 6] preconditioners, and theoretically explored Shampoo without preconditioner accumulation. In particular, Jeremy Bernstein @jxbz sent us the draft, which caused us to experiment with various Newton-Schulz iterations as the orthogonalization method for this optimizer. If we had used SVD instead of a Newton-Schulz iteration, this optimizer would have been too slow to be useful. Bernstein & Newhouse also pointed out that Shampoo without preconditioner accumulation is equivalent to steepest descent in the spectral norm, and therefore Shampoo can be thought of as a way to smooth out spectral steepest descent. The proposed optimizer can be thought of as a second way of smoothing spectral steepest descent, with a different set of memory and runtime tradeoffs compared to Shampoo.

  • To run experiments on fewer GPUs, simply modify run.sh

to have a different--nproc_per_node

. This should not change the behavior of the training. - If you're running out of memory, you may need to reduce the sequence length for FlexAttention (which does change the training. see herefor a guide)

Guilherme Penedo et al. "The fineweb datasets: Decanting the web for the finest text data at scale." arXiv preprint arXiv:2406.17557 (2024).- Nicholas J. Higham. Functions of Matrices. Society for Industrial and Applied Mathematics (2008). Equation 5.22.

@misc{modded_nanogpt_2024,
  author       = {Keller Jordan and Jeremy Bernstein and Brendan Rappazzo and
                  @fernbear.bsky.social and Boza Vlado and You Jiacheng and
                  Franz Cesista and Braden Koszarsky and @Grad62304977},
  title        = {modded-nanogpt: Speedrunning the NanoGPT baseline},
  year         = {2024},
  url          = {https://github.com/KellerJordan/modded-nanogpt}
}
── more in #artificial-intelligence 4 stories · sorted by recency
promptcube3.com · · #artificial-intelligence
LTX-2.
── more on @nanogpt 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
Live at https://your-agent.zahid.host
Get free account → Pricing
from €0/mo · no card required
LIVE [news/nanogpt-speedrun] indexed:0 read:13min 2026-08-23 ·