
Author of tutorials and example code for machine learning and nlp. GPT speedrun contributor / addict.
Santa Barbara, CA
Joined April 2009
- Tweets91
- Following79
- Followers1.4K
- Likes83
Pinned Tweet
I've started writing my model code as a single, compilable `forward_backward` function:
1 - No more autograd. The backward math is written out, same as forward.
2 - No torch.nn module abstractions, just matrices and math. (Glorious!)
3 - Attach a `.gacc` to each parameter to store its gradients.
4 - Intermediate activations are explicitly stashed for use in backward.
The screenshot shows the activation stash for the 24-layer nanochat architecture, where Claude cleverly skipped a few with high footprint and low compute cost.
Most notably, the MLP needs the activation values both pre and post-ReLU, and they're 18GB each! We just store pre, and re-apply ReLU in backward.
(A recent modded-nanogpt PR did something similar-but-different, need to look at it more)
I'm not familiar with the backward math (Claude wrote it all), but I'm excited to gradually build up the same familiarity with it as the forward path.
(1/3) - Here's how my September "speedrun the backward pass" project (decoder-rtx) played out.
Halfway through the month, a swarm of AIs run by rekursiv.ai set a new record on almost exactly this task, and porting their techniques is really what got us down to 12 minutes.
Their model uses giant n-gram tables, and needs a 141GB H200. We got it all to fit on the 96GB RTX 6000, though, by inlining the table optimizations into the backward pass so we could forgo 22.5GB in gradient buffers.
I've come to really like the architecture, and wrote it up as a blog post, published as the project README: github.com/chrisjmccormick/s…
A couple highlights are in this thread.
(2/3) - There are distinct 2M-row bigram and trigram tables added to every other layer, and they're used as value embeddings instead of being added directly to the residual stream.
(This made me realize that "value embeddings" serve as unigram tables, which are taught the bigram distribution (among other things).)
Adding the n-grams to the values is clever; all of the embeddings have per-head gates, so the model has more control over what information is retrieved from the tables.
There's a full tutorial on n-gram tables in the README here: github.com/chrisjmccormick/s…
1
1
105
(3/3) - The model makes the delineation of "context layers" vs. "prediction layers" explicit.
The final 3 layers (of 8) attend only to the output of the 5th layer. This means the final three MLPs can read context, but they cannot contribute to it! They can only work on predicting the next token.
The model's MLPs start narrow (2x) and get progressively wider in deeper layers (6x). That's interesting in its own right, but it also re-distributes the MLP parameters such that ~53% go exclusively to next token prediction.
Finally, think about what this would mean for the prefill part of text generation: you only need to run the first 5 of 8 MLPs and FlashAttention calls on the prefill tokens.
41
Big stack of improvements in baseline 4 cut the time by 40%.
Also, this "gpt-2 small" model is now 7 billion parameters trained on 350 million tokens. Ha!
Two particularly fun changes:
- Dropped .grad buffers from the hash tables and *inlined the optimizer* in their backward math.
- Added a 2M row tri-gram stats table (tallied from dataset, frozen), projected and added to values.
Some big efficiency gains in baseline 4:
- Learned you can run max-autotune once and preserve / ship the results alongside the model. Huge.
- Fable found "the right spelling" of ReLU^2 backward so Inductor would fuse it correctly.
Several other ideas were lifted from / inspired by an auto-research run published by rekursive.ai last week: nitter.cf/hyperparticle/status/2… (worth checking out, the results are more interesting / innovative than just hyperparameter tuning)
What I borrowed:
- Batch size of 192K
- Added gates to x0 lambdas
- Two huge bi-gram hash tables:
- 2M rows, added to x0
- 1M rows, added to values
- To optimize these 5.25B parameters: sparse, no first moment, and only per-row magnitude.
Unlike the auto-research run:
- Codebase is still ~clean / not Clauded-up 😜
- No FP8, custom ops / triton
PR: github.com/chrisjmccormick/s…
This is the last week! There's more to lift from the rekursive run and modded', but I'm going to try and focus on innovations in backward.
We sent a swarm of AI agents to solve Karpathy’s NanoChat benchmark, and they crushed SoTA in 3 days.
We built our own harness on top of a graph database to do auto-autoresearch, each iteration learning from mistakes to do research better.
The team wrote >15,000 entries. 🧵
10
992
Managed to shave about 70 seconds for this week's baseline, so we're just under 26 minutes.
Code's published in a pull request here, but I'll need another day to finish the write-ups:
github.com/chrisjmccormick/s…
7
699
Let's speedrun the backward pass.
To encourage more explanation of backward, I've set up a single-file, single-GPU challenge for the month of September.
The target GPU is the 96GB RTX Pro 6000, and the pipeline currently runs in 30 minutes end-to-end.
The handwritten backward pass + single GPU setup create interesting new opportunities.
And what better way to test out the new Fable 5.1 or GPT-6 this weekend than to tell them "see what you can do to speed this up." 😁
I won't be running the typical individual PR-based leaderboard--I'll be assembling a new baseline every Monday, through September 28th, and crediting everyone whose contributions make it in.
Check out the README for more:
github.com/chrisjmccormick/s…
Chris McCormick retweeted
Come hang out, in person, with me, @JayAlammar, @MaartenGr, @SerranoAcademy and @ChrisJMcCormick
📅 Saturday, September 12, 2026
⏱ Starting at 7 pm
Brouwerij t' IJ Proeflokaal de Molen Funenkade
Funenkade 7, 1018 AL, Amsterdam
Register at: forms.gle/rk1kpVtqBDtejsd89
(1/3) Going to try and illustrate 'backward' as I work my way through it.
Here's the very beginning. Just like the forward pass, it starts with embeddings:
- In the example sentence, the input token is "are" and the correct target is "the".
- The forward stream began as the input embedding for "are".
- The backward stream begins as the head embedding for "the", blended with the model's other predictions.
The blend is determined entirely by the softmax probabilities. Each head embedding is weighted by how much the model needs to change its prediction of that token.
- The target token gets a positive weight of (1-p), which is smaller the more confident the model already was in that choice:
- Medium confidence: p = 0.48 --> 0.52 * 'the'
- High confidence: p = 0.99 --> 0.01 * 'the'
Every other token gets a negative weight equal to its -p.
We take this probability-weighted sum over the entire vocabulary, but the illustration shows that often only a small number of tokens meaningfully contribute.
2
6
828
(2/3) That was the backward stream for one token, here's the stream for an input batch of 1,590 tokens.
At this point, they're very interpretable--each one is carrying an update that says "make it look more like the correct token and less like the incorrect ones".
A few interesting "issues" stand out:
(1) Cross entropy loss rebalances the predictions by stealing mass primarily from the other high probability options. If reasonable alternatives are also the highest probability alternatives (like in the example), they get hit the hardest.
(2) High confidence correct predictions appear to have dead streams. I assume they'll go through the whole backward process computing zeros, but we'll see!
That detail gets particularly interesting when you train on deterministic tasks like math and code--in a trained model, 80%+ of those tokens are deterministic. (See the "forking tokens" paper)
1
3
196
(3/3) Some details / clarifications:
(1) If you're familiar with the CE math, you'll notice that I have it backwards. That's because I multiplied by -1 at the start of the process so that we don't have to think in double negatives.
The effect is that:
- The positive target adds to the stream and to the weights, the rest subtract.
- The gradient and momentum buffers move in the same direction as the parameters.
- And the optimizer gets to be: weight = weight + update.
Equivalent, and so much easier to reason about!
(2) The speedrun model I'm playing with here uses a "softcap" function on the logits that deserves its own post. As the logits get larger during training, it scales down those head embedding weighting factors ("grad components"), which is pretty interesting.
(3) I'm postponing the loss scaling term to later in the process, because it means dividing every value by 512K, making them harder to read and think about.
Next up is the actual LM head weight update, though I might share some speedrunny thoughts first. :)
2
105
I’m looking to relocate to the San Jose / Santa Clara area, let me know if your team has any openings for an internal educator or something similar 👍🏼
1
5
1,592
Reading through the backward pass has been an absolute delight. It’s like I’m exploring a secret garden that’s been hiding there all this time.
A big surprise has been that I haven’t needed to think about derivatives at all in order to work through it. It has the same core architecture: a residual stream with building blocks reading from it and writing back to it!
Forward: x = x + mlp(x)
Backward: x = x + bwd_mlp(x, activations)
The weight update is read-only: w = w + mlp_update(x, activations)
The other thing that has me excited about it is the opportunity for improvement. Calculating gradients, taking their mean, and trusting optimizer theory to do the rest is the naïve baseline. We build forward with ingenuity and practical insight, while backward feels like adhering to the math is more important than improving the model.
One easy improvement so far: I don't need an element-wise multiply and reduce on a 1M token mini-batch to tell me that the backout lambda should wobble up and down a little over the course of training. A fraction of the batch is enough to optimize that scalar (and the other scalars as well, it seems).
And unlike forward, where we're limited by "it has to work at inference time", in backward we're free to leverage anything and everything to improve the signal, so long as it pays off. (There must be some interesting work out there already on all this?)
This is going to be fun.
If you'd like to wade through the backward pass with me, I put together a Colab Notebook in here: github.com/chrisjmccormick/s…
It's a flattened version of the nanochat training pipeline, with the model's forward and backward written as ~plain math in a single `forward_backward` function.
(There's also a raw .py version in there stripped of markdown if you'd prefer that over the notebook)
2
142
It's incredible how much data the optimizer demands in order to nudge our weights.
[AdamW to a token]: You want to adjust the model? Nah, bring me 1M more of you (mini-batch size) and then we'll talk.
(5.1 petaflops later...) Yeah, still don't trust you. I'll see what the last ~200M tokens suggested (Beta1=0.99), and you can have 1% of the vote (1-Beta1 = 0.01).
That settles direction, now for distance. I'll take a weighted average of what the last ~2B tokens asked for (Beta2=0.999), and we'll rescale your proposal in terms of that.
Alright, I think we're settled!
Now divide that by 1,000 (lr=1e-3) and you may proceed.
I’ve always been curious about the early parameter swings in the speedruns, and I think I mostly have a handle on the mechanism now.
Training starts with some huge gradient swings, and these enter into AdamW’s state.
When an EMA takes on an enormous value, the gradient’s influence is effectively zero until the EMAs decay back down to reasonable magnitudes.
So the key is to protect the buffers themselves (as opposed to just protecting the parameters with an LR warmup).
An approach that seems to be working is to add a warm-up to the (1-β) coefficient (the coefficient that controls the gradient's contribution to the EMAs).
I’m eager to see whether this can help later in training as well, where more gradient spikes occur at transition points (like suddenly increasing bs and lr).
Also still catching up on Claude's rationale for the shape of warmup ramp.
3
11
861
Compared to the last code I shared:
- This adds pre-computed schedules for the 1-beta terms.
- The `lerp_` (linear interpolation) operator no longer applies, since the coefficients don't sum to 1.0 during warmup, so it's written as in-place mul_ and add_
1
128
AdamW's bias correction terms can be factored out and viewed as part of the learning rate warm-up. The plot shows its shape for a variety of common (β₁, β₂) pairings. β₂ controls its width, and β₁ controls its height and depth.
It cancels out with early behavior from the grad and grad² EMAs (that's the point), so in that sense it's not actually influencing our learning rate.
The main takeaway for me is that we can simplify our AdamW code by folding this correction into the learning rate schedule.
To make that refactor fully correct, ε ends up with its own warm-up schedule as well:
ε_t = ε * sqrt(1 − β₂^t)
I've started pre-calculating these schedules and storing them in device-side buffers, which allows us to calculate them in fp64 (before casting), eliminate the "0-D cpu tensor" torch.compile workaround, and simplify the code a bit.















