More from Giles' blog
20 years ago to this day, I started my new technical blog. I'd had a personal one for some time, but most of the stuff that happened there had already migrated to social media. I wanted somewhere to post the things that would only be of interest to my techier friends, and maybe of some use to anyone else that came across it. Things have changed a bit, but they've stayed the same in some ways. Earlier this year I finished my 48-part (!) LLM from scratch series, but it had predecessors -- the third post I made here was part one of a 13-part series where I worked through setting up automated backups for my homelab NAS, and then later on I spent a few months building a reverse proxy in C, not to mention the eight-month, ten-post series on fine-tuning LLMs. It does seem like there's some value to putting all of this online. I rarely check my logs and referrers, but people do still seem to be arriving here having searched for stuff that I've written about, and every now and then there's a kind "thanks for this!" comment left on an old post where I explained something I'd just learned. I wrote a bit more about the blog's history last year, and came to the conclusion that the best posts -- both for me to write, and as far as I could tell for other people to read -- were the ones where I wrote up a project that I'd been working on. I blogged about that in more detail, and it seemed to strike a chord on Hacker News; I think it still holds. Recently, Sean Goedecke suggested that the best blog posts are those where you write about things that you're in the process of learning, and I agree. You learn more than you would if you didn't write it up, and because things are fresh in your mind, you may well write more clearly about it than an actual expert in the subject might have done. Anyway, I'm going to carry on blogging. I'm working on my biggest LLM-related project so far (dozens of training runs, so my study aircon is getting quite the workout even with the weather turning colder), and look forward to posting about it later on this month. I hope it's at least as fun to read as it is to write!
I hadn't uploaded the models that I trained using JAX to the Hugging Face Hub because Transformers has been PyTorch-only since version 5 (though they say they're working to add interoperability with JAX in the future), so it would have been tough to get them working natively with AutoModelForCausalLM and the like. But then it dawned on me that I'd already written a conversion script that could take my JAX safetensors files and convert them into ones compatible with my PyTorch code. It's actually those converted models that I use for my evals -- so I could use my existing PyTorch script to upload them. So, I've now uploaded PyTorch-compatible versions of all of my JAX-trained models: "Writing an LLM from scratch, part 34b -- from bigrams to GPT-2, one component at a time (in JAX)" gpjt/jax-no-mha-bias-no-dropout -- the first full LLM trained in the post, in the "Adding LayerNorm" section. gpjt/jax-no-mha-bias-with-dropout -- the second full LLM trained in the post, in the "Dropout" section. gpjt/jax-with-mha-bias-no-dropout -- the third full LLM trained in the post, in the "Adding bias to the MHA output projections" section. "Why do OpenAI's GPT-2 weights beat mine? Part three: testing overtraining" gpjt/jax-with-mha-bias-no-dropout-extended -- the single-epoch, double-Chinchilla-tokens model. gpjt/jax-with-mha-bias-no-dropout-2-epoch -- the model trained on two epochs over the Chinchilla-optimal number of tokens. "A quick(ish) Chinchilla check" gpjt/jax-with-mha-bias-larger-chinchilla-1 -- the slightly-larger model. gpjt/jax-with-mha-bias-larger-chinchilla-2 -- the slightly-smaller model. I've also added links to the posts in question.
I recently overtrained a couple of GPT-2 style models, training them both on 40 tokens per parameter rather than the 20 per parameter that is generally regarded as "Chinchilla-optimal". The normal heuristic is that instead of doing that, you should scale up the number of tokens and the number of parameters equally -- so I would have been better off scaling up the model by 2 and the token count by the same amount. By doing that, I should expect to get a better model in terms of loss on my held-back test set than I did with my 40-tokens-per-parameter models. My training machine poppy wasn't doing anything, so I decided to give that a go. Would the Chinchilla rule-of-thumb hold up? As you might expect, it did. But it was a surprisingly close-run thing, and could conceivably have been in the noise. Let's take a look. The Chinchilla heuristic If you already know all about the Chinchilla paper -- regular readers in particular must be sick and tired of it by now :-) -- then click here to skip this section. In "Training Compute-Optimal Large Language Models", which is always called the Chinchilla paper after the name of the model they trained at the end, the authors tried to work out the optimal number of tokens to train an LLM on based on its number of parameters. In particular, they were pushing back on a trend they were seeing at the time, where people were making models ever-larger, but not increasing the amount of data they were training on. The authors were all at Google DeepMind, and this was the kind of project that only a large lab could do: they trained "over 400 language models ranging from 70 million to over 16 billion parameters on 5 to 500 billion tokens". Their conclusion was "for compute-optimal training, the model size and the number of training tokens should be scaled equally: for every doubling of model size the number of training tokens should also be doubled". They don't actually state an overall optimal number of tokens to train on in the paper, but in table 3 they provide an estimate of the optimal training FLOPs and tokens for models of various sizes, and it's approximately 20 tokens per parameter. That number has become a heuristic, and people talk about a model as being trained for the Chinchilla-optimal number of tokens. Models that were trained on fewer tokens per parameter are referred to as "undertrained", and models that were trained on more as "overtrained". It's worth noting that overtraining a model is not, in itself, a bad thing. If you have a model of a particular size and you continue training it past the Chinchilla-optimal number of tokens, it will -- in general -- get better. The point of the heuristic is that doing that is not the best way to spend whatever budget you have in terms of compute time. You'll get better results, as they say, by scaling the number of tokens and the number of parameters equally. But let's say you're creating a model for specific target hardware -- say, a mobile device. You have a hard restriction on how large the model can be -- the device has only so much RAM to hold it. So it might make sense to overtrain to get a better model. 1 But if you're not so limited in how many parameters you can use, then you should indeed scale the model up, and that's what I wanted to try. How would that work? Scaling the model A week or two back, I was investigating whether I could make my GPT-2 style models better at a specific instruction-following task by overtraining them. The details of that experiment aren't important here, but what it meant was that I had three GPT-2-style models, each of exactly the same size, roughly 163M parameters A Chinchilla-optimal one, which I'll call jax-gpt2-chinchilla here. One trained on twice the Chinchilla-optimal tokens, jax-gpt2-2x-chinchilla. One trained on the Chinchilla-optimal tokens, with two epochs (so that it was trained for as long as #2): jax-gpt2-2-epoch-chinchilla When I tested them against a held-back test set of sequences -- stuff that they'd never seen before -- they got results rather like you might expect: Test loss jax-gpt2-2x-chinchilla 3.324953 jax-gpt2-2-epoch-chinchilla 3.326482 jax-gpt2-chinchilla 3.418784 A lower loss is better, and you can see that the longer-trained models were noticeably better than the Chinchilla-optimal one. The difference between them was tiny; they were trained starting with the same initial weights, and the training runs themselves were deterministic, but a difference of 0.05% in loss doesn't seem like it could be meaningful -- an extra batch for one or one fewer for the other could easily swap them around, you'd think. Now, these models each had 163,009,536 parameters -- they were the small-size model from the GPT-2 paper, modified to not have QKV bias or weight-tying. jax-gpt2-chinchilla had been trained on 3,260,190,720 tokens (rounded up to fit into a round number of full batches), and the other two on 6,520,381,440 tokens each -- double the amount (rounded up too). What I needed to do for my Chinchilla check was to try training a model that used the same amount of compute, scaling the parameters and the number of training tokens equally. Because training compute increases roughly linearly with both parameters and tokens, that would mean scaling both up by 2, giving us: 163,009,536*2≈230,530,296parameters ...and thus 4,610,605,920 tokens. How to scale the model up? In the GPT-2 paper, they train four models: Name Parameters 2 Layers d_emb MHA heads 3 small 124M 12 768 12 medium 345M 24 1024 16 large 762M 36 1280 20 xl 1542M 48 1600 25 I wanted to scale my own model up from 163M parameters to about 231M. Which of those numbers would I want to increase, and by how much? The first thing that stands out is that the number of heads is always 1/64th of the number of embedding dimensions. So that sorted that one out. I just needed to adjust the number of layers, and the number of embedding dimensions, but ensure that the latter was a multiple of 64. I decided to see if I could fit some kind of curve to the relationship between the number of parameters and the GPT-2 authors' choices. This was made a bit more complicated by one thing: they were using weight-tying, and I was not. That meant that they re-used the embedding matrix at the start of the LLM as an output head at the end -- which is why they had 38M fewer parameters. Embeddings and the output head make up a surprisingly large percentage of the parameters for small models like this -- about 47% without weight-tying, 23% with. I couldn't work out a solid way to scale things up and wound up doing some rather messy hacking around in a spreadsheet. I came up with two proposed model sizes that were within a couple of percentage points of the right size: Name Layers d_emb MHA heads Parameters % diff slightly-larger 15 896 14 235,621,120 +2.21% slightly-smaller 14 896 14 225,978,368 -1.97% Interestingly, I found that because d_emb could only change in increments/decrements of 64, it was a pretty coarse control -- my first attempt at making a slightly-smaller model changed it to the next step down, 832, but that led to a model that was 9.25% too small. That was an interesting first lesson. I'd previously been thinking of the Chinchilla rule as being something like "don't double the tokens, just scale the model and the tokens equally". But that "just" was wrong. Scaling a model is hard -- even with just two dials to fiddle with, like in this case, it was tricky to get something right -- and I can't say for sure that my choices were the right ones. Anyway, the next step was to double-check that these models would use the right amount of compute to train. Training FLOPs As I said earlier, the compute time scales roughly linearly with the number of parameters. Let's dig into that "roughly". Different kinds of parameters take different amounts of FLOPs to train, and scale differently with things like the embedding dimensions, sequence length, and so on. Now, for very large models, a lot of that comes out in the wash, but with tiny models like these where the embeddings make up such a large proportion of the parameters, it might matter. Conveniently, in appendix F of the Chinchilla paper, they provide a set of formulae for estimating the number of training FLOPs for a normal dense LLM like these ones. I coded that up into a script that, given the JSON configuration files I was using for my models and training runs, would work out the number of FLOPs for a single epoch of training. It didn't take account of the fact that my real training runs round the number of tokens up so that we do a round number of full batches, but I felt that so long as the results weren't very close that wouldn't matter. I got these results (multiplying the two-epoch numbers by two): Est. training FLOPs jax-gpt2-chinchilla 3,544,967,596,946,227,200 jax-gpt2-2x-chinchilla 7,089,935,193,892,454,400 jax-gpt2-2-epoch-chinchilla 7,089,935,193,892,454,400 slightly-larger 7,419,664,885,127,577,600 slightly-smaller 6,804,429,215,367,168,000 The numbers were indeed different enough that I wasn't worried about the batch-rounding. And the good news was that slightly-larger and slightly-smaller would indeed use slightly more and slightly less compute to train than the overtrained models -- about 4.6% more and 4% less respectively. A true Chinchilla-equivalent model would lie somewhere between them. It was time to train some models! Training I kicked off the run for the slightly-larger model first. Because it was bigger than the 163M models I'd been training, I couldn't fit such large batches into my VRAM; previously I'd been running with a batch size of 6, and now I could only fit in a batch of 4. Luckily, though, I was using gradient accumulation, so by bumping that up from 16 steps to 24 steps I could keep the same overall batch size and keep the training runs comparable. Even despite that, the training run ran out of VRAM about 60 hours in -- I'm guessing due to VRAM fragmentation, as I did not have TF_GPU_ALLOCATOR set to cuda_malloc_async -- but I was able to restart from the most recent checkpoint and complete the run. After just less than four days total training time, it completed. When it was done, I copied the last checkpoint 4 over to my dev box, perry, and ran my standard smoke test against it, asking it to complete "Every effort moves you" with 20 tokens, using greedy sampling. I got something reasonably coherent: Every effort moves you. I’m not sure what you’re thinking. I’m Next, I converted the safetensors file -- which had been saved by my JAX code -- into a format compatible with my PyTorch code, because that's what I use for evals. I ran another smoke test (this one with temperature 1): Every effort moves you through the motions for your life, your soul, your body, and your soul’s happiness Very spiritual. Next, it was time to work out the loss on my held-back test set: giles@perry:~/Dev/ddp-base-model-from-scratch (main)$ uv run test_loss.py datasets/ ../jax-gpt2-from-scratch/runs/full-llm-full-train-with-mha-output-bias-larger-chinchilla/model.json ../jax-gpt2-from-scratch/runs/full-llm-full-train-with-mha-output-bias-larger-chinchilla/checkpoints/latest/pytorch-model.safetensors Fetching 4 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 3485.09it/s] 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3200/3200 [07:11<00:00, 7.42it/s] Loss against our test dataset: 3.280028 Well, it was certainly better than the 3.324953 that the best of the overtrained models got -- but only by a bit over 1% better. Interesting! I decided to train the second model, slightly-smaller. This one crashed mid-way through with an error that I've seen before: jax.errors.JaxRuntimeError: INTERNAL: CUDA error: Failed to end stream capture: CUDA_ERROR_STREAM_CAPTURE_INVALIDATED: operation failed due to a previous error during capture [executable_name='jit_train_step'] I'm going to have to investigate that more in future, but for now, I just restarted from the checkpoint, and again after a bit less than four days, I had a model. The JAX smoke test was solid: Every effort moves you forward. The best way to get started is to start with a free trial. You can ...and so was the PyTorch one: Every effort moves you forward in love with our products. I love the way it’s easy to use. Both quite commercial this time! It was time for the proper test loss eval: giles@perry:~/Dev/ddp-base-model-from-scratch (main)$ uv run test_loss.py datasets/ ~/Dev/jax-gpt2-from-scratch/runs/full-llm-full-train-with-mha-output-bias-larger-chinchilla-2/model.json ~/Dev/jax-gpt2-from-scratch/runs/full-llm-full-train-with-mha-output-bias-larger-chinchilla-2/checkpoints/latest/pytorch-model.safetensors Fetching 4 files: 100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 4/4 [00:00<00:00, 3151.24it/s] 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 3200/3200 [06:45<00:00, 7.90it/s] Loss against our test dataset: 3.292937 So, slightly worse than the 3.280028 from the larger model, better than the 3.324953 from the best overtrained one. Time to put this all together. Results Here's an updated version of the table from the start of this post; I've added in the two new models, and the improvement they each had over jax-gpt2-2x-chinchilla in both absolute terms and as a percentage rounded to 3sf. Test loss Improvement Improvement % slightly-larger 3.280028 0.044925 1.35% slightly-smaller 3.292937 0.032016 0.962% jax-gpt2-2x-chinchilla 3.324953 - - jax-gpt2-2-epoch-chinchilla 3.326482 - - jax-gpt2-chinchilla 3.418784 - - Now, unlike the overtrained models, prior to training these two new ones started with different initial weights to the jax-gpt2-chinchilla one -- after all, they had to, because they had more of them! A while back, I did a bit of analysis of how random variation in weight initialisation can change the resulting test loss. It wasn't anything in-depth, but I trained three models with different explicit seeds set prior to the model initialisation, but with the same seed set before the training run started 5. Those three models wound up with test losses of 3.681356, 3.673943, and 3.664345. Doing statistics with three data points is a bit flaky, but the cost of training models is so high that I'll leave the Proper Science to the likes of Google DeepMind and wing it :-) Mean: ~3.673215 Sample variance: ~0.000073 Standard deviation (SD): ~0.008529 Now, piling statistical flakiness on statistical flakiness, we'll compare these. You'd normally expect about two thirds of results to be within one SD of the mean, 95.4% to be within two SDs, and 99.7% to be within three. Three SDs on that (yes, different, I know) distribution is 0.025587. That's smaller than both of the improvements that our Chinchilla-optimal runs had over the overtrained ones. So what does that tell us? Well, perhaps not much given the statistical flakiness. But I think it is useful directionally. It suggests that we might be able to take these results seriously as an improvement, and that Chinchilla held: scaling up the model and the number of tokens evenly did give us a better model than just scaling up the number of tokens. In particular, the fact that the loss for slightly-smaller was lower -- even though it had 4% less compute spent on it than the overtrained models -- was encouraging. But it's certainly far from a slam-dunk. A larger test, training lots of overtrained models and lots of Chinchilla-optimal ones, all with different random seeds, would give actual real serious data. Not worth it for me, and perhaps not for anyone. Conclusion I wanted to do a quick sanity check of the Chinchilla heuristic of 20 tokens per parameter. I came up with results that were certainly in line with it -- perfectly so in terms of the ordering of the models I trained. But the effect was small enough that I could imagine that it was in the noise, especially given the small numbers of models I'm able to train. I'll chalk it up as a tentative success. In addition, I learned one useful thing: when talking about scaling up a model to more parameters, you actually have to think quite hard about where you want to put those parameters. I wound up doing a rough curve-fit to the models in the GPT-2 paper, but I have no idea if that was optimal. At some point I should try to dig up some research into optimising embedding dimensions, numbers of layers, and so on. But not now, as I've a bunch of other stuff I want to investigate first. Anyway, I hope you found this experiment interesting, and as ever, comments and questions welcome below. Thanks for reading! I'm less familiar with arguments for under-training -- that is, for fewer than 20 tokens per parameter. I've heard that these days, modern LLMs get a lot more reinforcement learning than they do pre-training, and perhaps that might mean that some very big ones are undertrained prior to RL? I'm uncertain. It's unlikely to be raw lack of data; even for those of us outside the big labs, FineWeb has 18.5T tokens. On its own, that would be enough to train a 0.925T-parameter model, and given that you can apparently do four epochs over the same data before you start getting diminishing returns, that takes us up to 3.7T. That's frontier-lab size, and I'm sure they have better datasets than FineWeb. ↩ Parameter counts are from the paper, apart from the "small" model, which is known to be wrong -- I used my own calculation, and the result is in line with what I've seen elsewhere. ↩ The paper doesn't mention the number of heads; these numbers are from "Build a Large Language Model (from Scratch)", and match up with the ones on this Hugging Face page. ↩ Regular readers might have noticed that I'm ignoring what I've been calling the "best" checkpoint. I've come to the conclusion that because for my training script, "best" means best in terms of training loss, and the training loss changes based on what training data the model has seen recently, it's actually not a very useful metric and just confuses things. At some point I'll probably re-introduce pre-checkpoint evals and use that for "best", which would be the right way to do it. ↩ At the time I was using dropout, so training runs were not deterministic without a known seed. ↩
This post is the capstone of the most long-running series on my blog. In December 2024 (!), I started reading Sebastian Raschka's book "Build a Large Language Model (from Scratch)", and worked through it carefully. Being who I am, despite trying to apply a strict "no side quests" policy, I found myself zooming off and digging into all kinds of things. It's time to wrap it up. I had decided that the endpoint would be to build and train an LLM from scratch just using my notes -- no reference to the book, no reference to the model code I'd written when following the book. After an X/Twitter poll, I decided to use JAX for that, just to make sure that I really was building it from scratch and not regurgitating bits of PyTorch code like a bad coding LLM spitting out half-digested lumps of Stack Overflow. In my last post, I showed how I built a JAX training script that mirrored what I had built for the original PyTorch version of the model. To test it as I went along, I used it to train a really dumb "LLM", which instead of trying to predict the next token for every token in an input sequence, instead predicted the input -- that is, if you fed it The fat cat sat on the mat It would return the same thing. I called that an A-to-A model. In this post, I'll show you how I turned it into a GPT-2 model, and then trained it from scratch on my RTX 3090 (using the parameter counts for the original paper's "small" size). What turned out really well with this is that I found a route that meant that almost every component I added made the model better! That's not guaranteed -- sometimes different aspects of an AI model depend on each other, so adding A without also adding B makes things worse. But (admittedly with a bit of backtracking in places) I was able to find a route that shows a nice clear progression. The final training run took 37 hours 15 minutes -- compared to 40 hours, 38 minutes for an equivalent PyTorch model. That is despite it being full-fat 32-bit -- the PyTorch one was using Automatic Mixed Precision (AMP), which allowed it to use 16-bit calculations in places where it would be relatively harmless in terms of loss. When asked to continue "Every effort moves you", it came back with a decent response: Every effort moves you closer to your goals, but if you are unsure of what it takes, you don’t The model got 3.418784 loss on my held-back test dataset, as compared to my PyTorch model's 3.538161, and even more impressively, it was better than the original GPT-2 small's result of 3.499677 on the same dataset! However, just as I found previously, the OpenAI weights still beat mine consistently in instruction fine-tuning challenges. Let's get started. The starting point -- A-to-A At the end of the last post, we had a solid training loop, using all of the tricks I'd picked up with my PyTorch code. The A-to-A model we were training with it looked like this: from flax import nnx class GPTModel(nnx.Module): def __init__( self, vocab_size, context_length, d_emb, n_heads, n_layers, qkv_bias, drop_rate, rngs, ): self.token_embedding = nnx.Embed( num_embeddings=vocab_size, features=d_emb, rngs=rngs, ) self.output_head = nnx.Linear( in_features=d_emb, out_features=vocab_size, use_bias=False, rngs=rngs, ) def __call__(self, xs): input_embeddings = self.token_embedding(xs) return self.output_head(input_embeddings) That was based on my preferred model of how LLMs work, where at the top level for a model, we feed in a sequence of token IDs, then: Firstly, we convert them into embeddings, so we get a sequence of vectors, one for each token. We do this by a lookup into a table, but we can see it conceptually as a projection via a matrix, from vocab space (where a particular token ID is a one-hot vector) to embedding space. Next, we do the magic with our Transformers layers, getting embeddings for the next token. After these layers, the embedding at position n in the output sequence is for the predicted token to come after the token at position n in the input sequence, considering that input token and all other tokens to its left. Finally, we project those back from embedding space to logits, this time actually using a real matrix (in the form of a linear layer), the output head. The logits (after being run through softmax) represent the probabilities for each token of it being the next one. The A-to-A model basically skipped the second step completely: it would project to embedding space, then immediately project back to vocab space -- and after training, it was pretty good at mapping a sequence to itself. One interesting question is, if we train the same code, but this time try to get it to make next-token predictions, how good will it be at that? Obviously it can't be as good as a full LLM. But there are correlations between tokens; full stops will generally be followed by spaces, adjectives will normally be followed by other adjectives or nouns (at least in English), and so on. It would be kind of like the predictive text systems on a phone, where (at least until recently) it would just use the last word you entered to generate a list of possible next words to select from. Old-school natural language processing has a name for this: bigrams. The idea is that you can work out statistically what the most common two-word pairs are, which allows you to make a guess at a next word from a single one. (There are also trigrams, where you look at the last two words when predicting the next, then 4-grams, 5-grams, and so on.) You'd build up a full probability table -- for every word in your vocab, you'd have the probability of every word coming next. So maybe even with that minimal model, we could get it to learn something similar to a set of token-level (rather than word-level) bigrams, which would then get the loss down. Obviously it wouldn't be as good as a full bigram table -- for our GPT-2 vocab size of 50,257, that would need 50,2572=2,525,766,049 parameters -- but perhaps it could approximate one. (For comparison, the model we're using has just an embedding table and an output head, each mapping between 50,257 dimensions and 768, so that's 2×50,257×768≈77 million parameters -- about 3% of the full table.) An uninitialised model would (hopefully) have a loss of about 10.82, implying a perplexity equal to the vocab size. If we can train our dumb model to get better loss than that, then we'd have the beginnings of an LLM. That was a simple test to run. In my training code, I had a dataset class that looked like this: class BigTrainDataset: def __init__(self, all_tokens, seq_length, microbatch_size): self.xs = all_tokens[:-1].reshape(-1, microbatch_size, seq_length) self.ys = all_tokens[:-1].reshape(-1, microbatch_size, seq_length) def __getitem__(self, ix): return self.xs[ix], self.ys[ix] def __len__(self): return self.xs.shape[0] That is, the inputs, the xs, were the same as the targets, the ys. If we fed it The fat cat sat on the mat ...then we'd be training it to output exactly the same thing. The modified version for a real LLM would involve feeding it something like this: The fat cat sat on the ...and targeting this: fat cat sat on the mat That's a simple change -- that __init__ method became this: self.xs = all_tokens[:-1].reshape(-1, microbatch_size, seq_length) self.ys = all_tokens[1:].reshape(-1, microbatch_size, seq_length) I did that, and kicked it off to train on the 92,209,152 tokens that I was (somewhat arbitrarily) using in the last post to test my training loop. The loss chart looked like this: That was pretty promising! Loss came down from roughly 10.82 down to a fairly stable 6 or so by global step 768, and seemed to flatten out there. It's possible that further training could have got it down a bit more, but I decided (again, somewhat arbitrarily) to use the average train loss in the checkpoint period ending at step 937 as my starting point. If we could make changes that reduced that, then we'd be moving forward. For this model, that value was 5.909. So, what were the changes we needed to make to change our bigram-style model to a real, if small, LLM? Building GPT-2: a checklist Adapting from my how LLMs work post, a GPT-2-style LLM looks like this. We receive our sequence of token IDs, and then: Convert them into embeddings. ✔ ️done Add on position embeddings. Run these embeddings through multiple successive Transformers blocks. Layer normalisation Project them back from embedding space to vocab space. ✔ ️done Inside the Transformers blocks, we: Take a copy of the input sequence of embeddings Layer normalisation Run multi-head attention Add the copy back in so that the version that came out of MHA is something more like an "annotation" of the original Take a second copy of that one Layer normalisation again Run it through a simple neural network Add the results of that back in. So that gave me the checklist; looking at it, the most tempting next step was layer normalisation (henceforth LayerNorm). It's used at the end of the core loop, and then twice in the Transformers blocks. What would happen if we coded it up, and then added it to the core only? LayerNorm The purpose of LayerNorm is to stabilise training. We constrain the values flowing through our model so that they have certain statistical properties that tend to make the whole thing more trainable. That would mean that if it did help with this model -- placed in between the embedding layer at the start, and the output head at the end -- then we'd hope for loss to go down faster, and ideally finish at a lower level. Time to code it up! NNX has its own LayerNorm implementation, of course (as does PyTorch), but in the book, we implement it ourselves, and that felt like the correct path to take. Firstly, I implemented a dummy version: class LayerNorm(nnx.Module): def __init__(self): ... def __call__(self, xs): return xs ...and updated the core GPTModel to create and call one: class GPTModel(nnx.Module): def __init__( ... ): self.token_embedding = nnx.Embed( ... ) self.output_norm = LayerNorm() self.output_head = nnx.Linear( ... ) def __call__(self, xs): input_embeddings = self.token_embedding(xs) normalised = self.output_norm(input_embeddings) return self.output_head(normalised) And kicked off a training run for a few seconds just to make sure that it hadn't broken anything and that loss dropped -- being my first NNX module-inside-a-module, I worried that there might have been something non-intuitive that I had to do to get it to work. But everything seemed good -- loss was dropping, no errors. So, following the notes I made when I first learned about LayerNorm, I needed to make the values flowing through centred around zero by subtracting their mean, and then scale them to have a variance of one by dividing by the standard deviation (details in those notes). The shape of the xs I had coming into my LayerNorm class's _call was this: xs.shape=(6, 1024, 768) That was (batch_size, seq_len, d_emb). So we needed to do those operations strictly on the last axis, manipulating each embedding independently. JAX has a std function and a mean one, both of which take an axis parameter. The Array object repackaged those as methods, which was convenient, so I did a first cut test like this: class LayerNorm(nnx.Module): def __init__(self): ... def __call__(self, xs): jax.debug.print(f"{xs.shape=}") means = xs.mean(axis=-1) jax.debug.print(f"{means.shape=}") stds = xs.std(axis=-1) jax.debug.print(f"{stds.shape=}") return xs That printed out these results: xs.shape=(6, 1024, 768) means.shape=(6, 1024) stds.shape=(6, 1024) ...which looked plausible; one number for each embedding vector. Could we broadcast them across the array? class LayerNorm(nnx.Module): def __init__(self): ... def __call__(self, xs): jax.debug.print(f"{xs.shape=}") means = xs.mean(axis=-1) jax.debug.print(f"{means.shape=}") stds = xs.std(axis=-1) jax.debug.print(f"{stds.shape=}") normalized = (xs - means) / stds jax.debug.print(f"{normalized.shape=}") return normalized This blew up: ValueError: Incompatible shapes for broadcasting: shapes=[(6, 1024, 768), (6, 1024)] Fair enough. But mean and std have a keepdims kwarg that looked like it would help: class LayerNorm(nnx.Module): def __init__(self): ... def __call__(self, xs): jax.debug.print(f"{xs.shape=}") means = xs.mean(axis=-1, keepdims=True) jax.debug.print(f"{means.shape=}") stds = xs.std(axis=-1, keepdims=True) jax.debug.print(f"{stds.shape=}") normalized = (xs - means) / stds jax.debug.print(f"{normalized.shape=}") return normalized ...and it did! xs.shape=(6, 1024, 768) means.shape=(6, 1024, 1) stds.shape=(6, 1024, 1) normalized.shape=(6, 1024, 768) Excellent. So the next step was to see if that would work even slightly. Interestingly loss started off a bit higher at 11.29 after the first global step -- so adding in the LayerNorm had actually made the model worse than it was -- but it seemed to be falling rapidly. Things weren't totally broken, at least. But there was more to LayerNorm than just zeroing the mean and scaling to the variance; we also needed to scale them up by a learnable amount, and then shift/bias them by adding on a different trainable amount. More precisely, both of those trainable amounts were different for each of the (in this case) 768 embedding dimensions. We needed two learnable vectors of length d_emb. I hadn't noted it down at the time but I figured (as it turned out, correctly) that a sensible starting point for those values would be all-zero for the bias, and all-one for the scale. From this help page, the way you create a trainable array associated with an NNX module is this: nnx.Param(jax.random.normal(rngs.param(), (dim, dim))) That code created a random vector, rather than the zeros/ones we needed, and we'd need to get the dimensions right. Because of the "Incompatible shapes for broadcasting" error I'd just had, I was feeling a bit paranoid about the latter, so I chose a shape of (1, 1, d_emb), and wrote this: class LayerNorm(nnx.Module): def __init__(self, d_emb): self.scale = nnx.Param(jnp.ones((1, 1, d_emb))) self.bias = nnx.Param(jnp.zeros((1, 1, d_emb))) def __call__(self, xs): jax.debug.print(f"{xs.shape=}") means = xs.mean(axis=-1, keepdims=True) jax.debug.print(f"{means.shape=}") stds = xs.std(axis=-1, keepdims=True) jax.debug.print(f"{stds.shape=}") normalized = (xs - means) / stds jax.debug.print(f"{normalized.shape=}") scaled_and_biased = (normalized * self.scale) + self.bias return scaled_and_biased That looked pretty plausible, though in retrospect I think I was being overly cautious and didn't need the leading two axes for the scale and bias. The only thing I was unsure about was whether the nnx.Param wrappers I had put in were really making those arrays trainable. I put some code in to print them out and kicked off a run for a few minutes, and confirmed that they were changing in ways that seem plausible -- small non-zero bias, scale close to but not equal to one. That was all good! Next, I spotted one issue. What if one of the standard deviations was zero? That would lead to a divide-by-zero error here: normalized = (xs - means) / stds Now, the standard deviation, if it's not zero, has to be positive -- so adding on a small value would fix that 1: normalized = (xs - means) / (stds + 1e-5) With that in place, I felt that it was ready to go. Time to do a full training run! I kicked that off, and it completed with this output: 2026-06-20 19:08:17.189721 Tokens seen: 92,209,152 2026-06-20 19:08:17.189724 Throughput: 95,383 tokens/second 2026-06-20 19:08:17.189734 Final train loss: 5.736 2026-06-20 19:08:17.189737 Done Loss looked like this: Let's look at the results for the previous run without LayerNorm for comparison: You can see that the new run, the first one, drops faster. It's harder to see from the chart, but it also finished up with a lower training loss at 937 (my relatively arbitrary metric): 5.734 rather than 5.909. That was interesting! The new model was basically doing the same thing -- predicting the next token based only on the "current" token, but loss was lower. My take is that if we had trained the non-LayerNorm model for longer, it might have managed to eventually grind out a better loss. But LayerNorm was doing its job -- it was stabilising training, and as a result we converged faster. That was a win! I decided to run it through my old smoke test from the PyTorch training runs, and see how it completed "Every effort moves you": Every effort moves you can be a few years. -year-year-year-year-year-year- It was kind of impressive that it managed to finish the first line before it got stuck in a loop -- but it was understandable that we couldn't expect anything good yet. Each predicted token was based entirely on the token before it. What next? Back to our checklist: Convert token IDs into embeddings. ✔ ️done Add on position embeddings. Run these embeddings through multiple successive Transformers blocks. Layer normalisation ✔ ️done Project them back from embedding space to vocab space. ✔ ️done Inside the Transformers blocks, we: Take a copy of the input sequence of embeddings Layer normalisation Run multi-head attention Add the copy back in so that the version that came out of MHA is something more like an "annotation" of the original Take a second copy of that one Layer normalisation again Run it through a simple neural network Add the results of that back in. So, at this stage, for each input token we were predicting the next one based on the input token only -- like I said earlier, we were doing a somewhat roundabout way of building an approximation of a table of bigram probabilities. What would happen if we started paying attention to the tokens to the left? And what would be the simplest, dumbest way to do that? A single layer of single-head attention The real LLM has multiple layers of multi-head attention, each one also having a feed-forward network, some LayerNorms, and some shortcut connections. Single-head attention is easier to code, but even on its own, you'd expect it to be able to add some value. Each token would get at least some information from the ones to the left. And one layer, likewise, you'd expect might help a bit. I suspected that it wouldn't work on its own -- I expected I'd need shortcut connections too -- but decided to start with attention on its own. I modified the main class to have a single "Transformers" layer: class GPTModel(nnx.Module): def __init__( ... ): self.token_embedding = nnx.Embed( ... ) self.transformers_layer = TransformersLayer(d_emb, qkv_bias, rngs) self.output_norm = LayerNorm(d_emb) self.output_head = nnx.Linear( ... ) def __call__(self, xs): input_embeddings = self.token_embedding(xs) transformed = self.transformers_layer(input_embeddings) normalized = self.output_norm(transformed) return self.output_head(normalized) ...where that layer was actually just single-head attention: class TransformersLayer(nnx.Module): def __init__(self, d_emb, qkv_bias, rngs): self.attention = Attention(d_emb, qkv_bias, rngs) def __call__(self, xs): return self.attention(xs) Next, it was time for the Attention class. I'm not going to write yet another attention explainer -- I think my "How do LLMs work?" one does a decent job of that, and "The 'why' of attention, or: attention heads are dumb" works well too. So in the next bit I'll assume that you understand the basics. My first cut was basically just the maths (up to the causal mask) to get the attention scores: class Attention(nnx.Module): def __init__(self, d_emb, qkv_bias, rngs): self.d_emb = d_emb self.W_q = nnx.Linear(d_emb, d_emb, use_bias=qkv_bias, rngs=rngs) self.W_k = nnx.Linear(d_emb, d_emb, use_bias=qkv_bias, rngs=rngs) self.W_v = nnx.Linear(d_emb, d_emb, use_bias=qkv_bias, rngs=rngs) def __call__(self, xs): Q = self.W_q(xs) K = self.W_k(xs) V = self.W_v(xs) omega = Q @ K.T omega /= jnp.sqrt(self.d_emb) causal_omega = jnp.tril(omega) It did the projections into query, key and value space, worked out the attention scores with the array multiplication, normalised it by dividing by the square root of the number of dimensions in the Q-K embedding space, and then zeroed out the scores where a token was attending to tokens in its "future". There were a couple of problems, though. Firstly, that wouldn't work if we were working with batches, and secondly, zeroing out the non-causal scores wasn't quite correct. The batches first. Our incoming xs here would have the shape (batch_length, seq_len, d_emb). After the projections to the Q-K embedding space, both Q and K would also be shaped (batch_length, seq_len, d_emb). Now, the .T property on the JAX array class just reverses the axes, so the code above would give us K.T with the shape (d_emb, seq_len, batch_length). That would break! Matrix multiplication in JAX expects all but the last two axes to represent batches, so we actually wanted K.T to have the shape `(batch_length, d_emb, seq_len). That meant that what we actually wanted was to just transpose the last two axes. The JAX transpose function takes an axes parameter that allows you to specify the specific re-ordering of the input axes that you want. So I could rewrite the code like this: def __call__(self, xs): Q = self.W_q(xs) K = self.W_k(xs) V = self.W_v(xs) omega = Q @ jnp.transpose(K, axes=(0, 2, 1)) omega /= jnp.sqrt(self.d_emb) causal_omega = jnp.tril(omega) As Q would have the shape (batch_length, seq_len, d_emb), and the transposed version of K would be (batch_length, d_emb, seq_len), they'd be compatible for matrix multiplication and give us a result that was (batch_length, seq_len, seq_len) -- just what we wanted for attention scores. The next step was to fix the causal mask. The next step in this attention mechanism was going to be running the causal attention scores in causal_omega through softmax over the last dimension, to convert them into attention weights. Now, our current code was zeroing out unwanted acausal scores, but a zero still contributes to softmax. If you want a particular value to come out of softmax guaranteed to be zero, you need to set it to minus infinity. I decided that the easiest way to do this was to create a causal mask -- a boolean array that matched the size of omega, but was full of Trues: causal_mask = jnp.ones_like(omega, dtype=bool) Then I could zero out (well, "false out") the cells in the mask related to unwanted future-facing scores, just like I was previously doing on the scores: causal_mask = jnp.tril(causal_mask) ...and then I could apply that mask to omega with jnp.where, telling it to create a new array, taking the value from omega where the mask had True, and -jnp.inf in places where it had False. causal_omega = jnp.where(causal_mask, omega, -jnp.inf) That seemed solid, so I just needed to run the result through jax.nn.softmax, specifying that the last dimension was the one where it should apply the function, and that would give me the attention weights: attention_weights = jax.nn.softmax(causal_omega, axis=-1) Finally, I just needed to use those attention weights to get the attention output by mixing in appropriate portions of the projection of the inputs into value space, V: return attention_weights @ V As attention_weights was shaped (batch_length, seq_len, seq_len), and V (like Q and K) was shaped (batch_length, seq_len, d_emb), the batch axes were at the start where they belonged, and the matrix multiplication would work and return something shaped (batch_length, seq_len, d_emb). With that, we were done! The final single-head attention class looked like this: class Attention(nnx.Module): def __init__(self, d_emb, qkv_bias, rngs): self.d_emb = d_emb self.W_q = nnx.Linear(d_emb, d_emb, use_bias=qkv_bias, rngs=rngs) self.W_k = nnx.Linear(d_emb, d_emb, use_bias=qkv_bias, rngs=rngs) self.W_v = nnx.Linear(d_emb, d_emb, use_bias=qkv_bias, rngs=rngs) def __call__(self, xs): Q = self.W_q(xs) K = self.W_k(xs) V = self.W_v(xs) omega = Q @ jnp.transpose(K, axes=(0, 2, 1)) omega /= jnp.sqrt(self.d_emb) causal_mask = jnp.ones_like(omega, dtype=bool) causal_mask = jnp.tril(causal_mask) causal_omega = jnp.where(causal_mask, omega, -jnp.inf) attention_weights = jax.nn.softmax(causal_omega, axis=-1) return attention_weights @ V I kicked off a training run with that, and it did work, in that loss went down over the course of the run -- but at the end of the run, the loss at step 937 was 5.934 -- significantly above the 5.734 I got on the previous run, with no attention. But that made sense! As I'd said earlier, I suspected that this wouldn't help if we had no shortcut connection. Intuitively, if you want to work out what token should be at position n+1, on average the most important other token you need to know about is probably whichever one is at position n. Knowing about the tokens at n−1, n−2, and so on, could well be helpful -- maybe very helpful -- but not at the cost of not knowing about the one at n. Now, single attention heads are just simple pattern-matchers. They can't learn complex rules, it's only by working together -- "horizontally", in multi-head attention or "vertically" across multiple layers -- that they can do complex things. What we were asking this head to do was to learn some way of gathering information about previous tokens, and also to keep the knowledge about the "current" one. That's a tall order for a dumb attention head! In my mind, this is a large part of the benefit of shortcut connections. They are often presented as a way to make sure that during training, gradients flow smoothly from the output end of the model to the earlier layers. But I prefer to think of them as preserving the original embeddings, so that each layer doesn't completely replace what came into it, but instead does something closer to adding on its own notes -- like scholars adding commentary to a core text in the Talmud. In the training run above, the attention head was trying to learn how to preserve the meaning of the embedding it was working on, while also merging in information from earlier ones. If we added a shortcut connection, then it would only have to do the second of those two jobs. The code was simple: I updated the TransformersLayer module to do a shortcut connection: class TransformersLayer(nnx.Module): def __init__(self, d_emb, qkv_bias, rngs): self.attention = Attention(d_emb, qkv_bias, rngs) def __call__(self, xs): shortcut = xs att = self.attention(xs) return shortcut + att I kicked off a training run, and at the end it printed this: 2026-06-23 03:51:18.086097 Tokens seen: 92,209,152 2026-06-23 03:51:18.086099 Throughput: 90,442 tokens/second 2026-06-23 03:51:18.086108 Final train loss: 5.570 2026-06-23 03:51:18.086121 Done The loss chart looked like this: And, importantly, that training loss at step 937 which I was using as a metric was 5.553 -- a decent improvement over the previous best of 5.734. Even a dumb single attention head was able to do something useful, if it had a shortcut connection. I decided to run another qualitative smoke test: Every effort moves you can be able to get to get to get to get to get a lot of the way to get I mean, it was repetitive, but it was actually getting noticeably closer to making sense! So that was excellent news. What next? Our checklist looked like this: Convert token IDs into embeddings. ✔ ️done Add on position embeddings. Run these embeddings through multiple successive Transformers blocks. part-done -- one layer only Layer normalisation ✔ ️done Project them back from embedding space to vocab space. ✔ ️done Inside the Transformers blocks, we: Take a copy of the input sequence of embeddings ✔ ️done Layer normalisation Run multi-head attention part-done -- single-head attention only Add the copy back in so that the version that came out of MHA is something more like an "annotation" of the original ✔ ️done Take a second copy of that one Layer normalisation again Run it through a simple neural network Add the results of that back in. Now, our single attention layer was lacking something. Without position embeddings, that layer has no idea what order the tokens before the one it's looking at come in. If it's considering the " cat" in The fat cat ...it doesn't know if it's looking at "The fat cat" or "fat The cat". Position embeddings are simple, and might help, so that was the next step. Position embeddings These were trivial to add. We had this core code: class GPTModel(nnx.Module): def __init__( ... ): self.token_embedding = nnx.Embed( ... ) self.transformers_layer = TransformersLayer(d_emb, qkv_bias, rngs) self.output_norm = LayerNorm(d_emb) self.output_head = nnx.Linear( ... ) def __call__(self, xs): input_embeddings = self.token_embedding(xs) transformed = self.transformers_layer(input_embeddings) normalized = self.output_norm(transformed) return self.output_head(normalized) So I just added a position encoding module in __init__: self.position_embedding = nnx.Embed( num_embeddings=context_length, features=d_emb, rngs=rngs, ) ...and mixed it in with the token embeddings to create new, improved input_embeddings to be used in our "Transformers" layer: token_embeddings = self.token_embedding(xs) b, n = xs.shape position_embeddings = self.position_embedding(jnp.arange(n)) input_embeddings = token_embeddings + position_embeddings I kicked off a training run with that: 2026-06-23 04:44:44.759768 Tokens seen: 92,209,152 2026-06-23 04:44:44.759771 Throughput: 88,618 tokens/second 2026-06-23 04:44:44.759779 Final train loss: 5.386 2026-06-23 04:44:44.759781 Done Pretty hard to distinguish from the previous one, but the metric I was tracking, that loss at step 937, had improved again! We were down to 5.354 from 5.553 :-) A quick qualitative smoke test didn't show that improvement, though: Every effort moves you can be able to get to get to get back to get back to get back to get back to Pretty much indistinguishable to the previous one. But still, Loss Number Went Down, and that's what was important at this stage. It was time to try the next step. From the checklist: Convert token IDs into embeddings. ✔ ️done Add on position embeddings. ✔ ️done Run these embeddings through multiple successive Transformers blocks. part-done -- one layer only Layer normalisation ✔ ️done Project them back from embedding space to vocab space. ✔ ️done Inside the Transformers blocks, we: Take a copy of the input sequence of embeddings ✔ ️done Layer normalisation Run multi-head attention part-done -- single-head attention only Add the copy back in so that the version that came out of MHA is something more like an "annotation" of the original ✔ ️done Take a second copy of that one Layer normalisation again Run it through a simple neural network Add the results of that back in. We had only one attention head right now. Individually, attention heads are dumb, so switching to multi-head attention seemed like a good thread to pull. Multi-head attention At this point, my single-head attention code looked like this: Q = self.W_q(xs) K = self.W_k(xs) V = self.W_v(xs) omega = Q @ jnp.transpose(K, axes=(0, 2, 1)) omega /= jnp.sqrt(self.d_emb) causal_mask = jnp.ones_like(omega, dtype=bool) causal_mask = jnp.tril(causal_mask) causal_omega = jnp.where(causal_mask, omega, -jnp.inf) attention_weights = jax.nn.softmax(causal_omega, axis=-1) return attention_weights @ V I decided to re-implement multi-head attention (which I'll call MHA from here onwards) from first principles rather than working strictly from my notes, and then to come back and check it. If you're looking at your browser's scrollbar with horror ("still only 50%?!") and really don't want to read a full derivation of MHA, you can skip straight to the first complete version of the code. The point of MHA is that we're running multiple copies of the calculation above in parallel -- let's pin down the name of the number of copies as n_heads. Now, we could naively implement it just by spinning off n_heads threads and running the existing code in each, but that wouldn't really take advantage of the GPU's inherent parallelism. I felt that we could rely on the fact that JAX's matrix multiplications treat all but the last two dimensions as "batches". For example, if you have two arrays with shapes: (a, b, c, ..., l, m, n) and (a, b, c, ..., l, n, p) ...then you can multiply them. A m×n matrix multiplied by a n×p one will be m×p, so you'll get something that is (a, b, c, ..., l, m, p) The other dimensions (so long as they match) will essentially act as an a×b×c×...×l batch. Now, right now we were just using a single batch dimension. Let's look at the core multiplication in the attention mechanism, which works out omega, the attention scores. I had this: omega = Q @ jnp.transpose(K, axes=(0, 2, 1)) Breaking that apart into two steps: K_transpose = jnp.transpose(K, axes=(0, 2, 1)) omega = Q @ K_transpose We got K from this line: K = self.W_k(xs) Let's look at the shapes here. xs is our input embeddings for this layer; its shape is (batch_size, seq_len, d_emb). Projecting it through W_k, which is shaped (d_emb, d_emb) gives us a shape for K of (batch_size, seq_len, d_emb) again. Q, being a projection of xs through W_q, which is the same shape as W_k, will have the same shape as K. Now, that means that K_transpose is (batch_size, d_emb, seq_len), and the calculation omega = Q @ K_transpose ...is doing a batched matrix multiplication getting us the omega that we want, shaped (batch_size, seq_len, seq_len). But as I said above, there's no need to stop with just one batch dimension. Let's say that we have n_heads heads, and that they each work with embeddings sized d_head. Imagine that we've already somehow done multiple projections into the key and query spaces for each of our n_heads heads, and that the results have somehow been put into arrays such that Q and K are shaped (batch_size, n_heads, seq_len, d_head) -- that is, we've gained an extra axis that keeps the projections for each head into its query-key space separate. We could use the fact that both of those two leading axes are basically just batch dimensions, and the existing single matrix multiplication will still work, with one tiny tweak: the current transpose is this: K_transpose = jnp.transpose(K, axes=(0, 2, 1)) omega = Q @ K_transpose ...to swap around the last two axes of a three-axis array. With one extra batch dimension, we'll need to take account of that and do this instead: K_transpose = jnp.transpose(K, axes=(0, 1, 3, 2)) omega = Q @ K_transpose That will be a multiplication of Q, shaped (batch_size, n_heads, seq_len, d_head), with K_transpose, shaped (batch_size, n_heads, d_head, seq_len), which gives us an omega of the right shape, (batch_size, n_heads, seq_len, seq_len). So, if we can start treating the heads as just another batch dimension, things seem simpler, at least for the attention score calculation. Let's continue down through the single-head code, and then come back later to how we might get the inputs into that double-batched shape. The next line after the omega calculation just scales the attention scores by a scalar: omega /= jnp.sqrt(self.d_emb) That looked fine, just a broadcast division-by-float. We'd need to change that self.d_emb to be d_head in some manner, but that's all. Next: causal_mask = jnp.ones_like(omega, dtype=bool) The jnp.ones_like will give us an array that's (batch_size, n_heads, seq_len, seq_len) full of Trues. That seems reasonable. The next step: causal_mask = jnp.tril(causal_mask) What will that do? Well, per the tril documentation: When m.ndim > 2, jnp.tril operates batch-wise on the trailing axes. ...which sounded good. batch_size and n_heads would be treated as batch axes, which meant that the next line: causal_omega = jnp.where(causal_mask, omega, -jnp.inf) ...would work. Likewise, with the next line: attention_weights = jax.nn.softmax(causal_omega, axis=-1) ...the axis to apply softmax to is explicitly stated as the last one, which is what we wanted. So at the end of all of those steps, we'd have attention_weights shaped (batch_size, n_heads, seq_len, seq_len), where the last axis had been softmaxed (softmaxxed?). The next line looked a little trickier: return attention_weights @ V In the single-head version we had attention_weights of shape (batch_size, seq_len, seq_len), and V of shape (batch_size, seq_len, d_emb), so multiplying them gives us (batch_size, seq_len, d_emb) In the new MHA code so far, we had our attention_weights shaped (batch_size, n_heads, seq_len, seq_len). So in order for the matrix multiplication to work, we'd need V to be shaped (batch_size, n_heads, seq_len, d_head). That would give us a result shaped as (batch_size, n_heads, seq_len, d_head). And conveniently, we'd already decided that the correct shape for Q and for K was (batch_size, n_heads, seq_len, d_head). If we could use the same "magic" to do the projection into value space -- that is, to get V such that the heads formed a new batch-like axis like we had for Q and K -- then we'd be all set. So, at that point, I'd worked out the core of MHA. If we could get all of the inputs into the shape (batch_size, n_heads, seq_len, d_head), and somehow handle an output of the shape (batch_size, n_heads, seq_len, d_head), then we could use MHA code something like this: # Q and K are (batch_size, n_heads, len_sequence, d_head) # We need to convert K to (batch_size, n_heads, d_head, len_sequence) # and then we get omega (batch_size, n_heads, len_sequence, len_sequence) omega = Q @ jnp.transpose(K, axes=(0, 1, 3, 2)) omega /= jnp.sqrt(self.d_head) causal_mask = jnp.ones_like(omega, dtype=bool) # tril treats all but the last two axes as batches so we're OK here. causal_mask = jnp.tril(causal_mask) causal_omega = jnp.where(causal_mask, omega, -jnp.inf) # last axis is still OK. attention_weights = jax.nn.softmax(causal_omega, axis=-1) # attention_weights is (batch_size, n_heads, len_sequence, len_sequence) # V is (batch_size, n_heads, len_sequence, d_head) # So this will come out as (batch_size, n_heads, len_sequence, d_head) weighted = attention_weights @ V The next question was, how do we get our inputs into that shape? We could run them all through separate per-head weights -- that is, have an array with one per head, like W_q[0], W_k[0] and W_v[0] for the first one. But that, again, felt like it would be failing to take advantage of the GPU properly. The solution was to think of how matrix multiplications work. If you multiply two matrices, X·Y, the value in the result, in row r, and column c, is the dot product of row r in X and column c in Y. So, imagine if you wanted to multiply X by n different versions of Y, let's call them Y0, Y1, and so on up to Yn. If you imagine a new matrix, Yall, which is basically all the Yxs stacked side-by-side, then the dot-product understanding of multiplication makes it pretty clear that if you did X·Yall, you would get the results of all of those separate multiplications, also stacked side-by-side. I'll call that kind of matrix a "striped" one, for want of a better word. Now, when we project our inputs into the embedding spaces used for attention, we have code like this: Q = self.W_q(xs) We've initialised the weights, W_k in this case, as an nnx.Linear, so what is happening under the hood here is basically: Q=xs·Wq That is, it is just a matrix multiplication. 2 So if we imagine that W_q is one of those "striped" matrices, holding all of the separate matrices to do the projections for all of the heads in a single one shaped (d_emb, n_heads * d_head), then we could stick with the current code -- the Q = self.W_q(xs) Our input xs would be shaped (batch_size, seq_len, d_emb), so the result would be (batch_size, seq_len, n_heads * d_head), and would have the projections for each head in the same vertical stripes as the separate heads' projection weights. Now, like PyTorch, JAX allows you to reshape arrays. You can take one axis of length (say) m×n, and split it into two of lengths m and n respectively -- or, conversely, you can combine two axes of length m and n to one of m×n. If our data had the shape (batch_size, seq_len, n_heads * d_head), we could reshape it like this: Q = self.W_q(xs).reshape((batch_size, seq_len, n_heads, d_head)) ...and that would split things up. So we'd have Q shaped as (batch_size, seq_len, n_heads, d_head). That's almost what we wanted! We needed (batch_size, n_heads, seq_len, d_head), and a simple transpose could sort that out: Q = jnp.transpose( self.W_q(xs).reshape( (batch_size, seq_len, n_heads, self.d_head) ), (0, 2, 1, 3) ) Likewise for K and V, and that was our inputs sorted. Moving on to the output; it came from this: weighted = attention_weights @ V ...and as we worked out above, it was shaped (batch_size, n_heads, seq_len, d_head). I remembered that we wanted to run that through a single linear layer to combine all of the different heads' outputs into one. It felt like the best way to do that would be to get it back into a "striped" layout: (batch_size, seq_len, n_heads * d_head). This would be something like the inverse of the input-wrangling. That would need a reshape, but before I could do that, I'd need to get the axes that needed to be merged next to each other. If the input to the linear layer was going to be (batch_size, seq_len, n_heads * d_head), we'd need to convert it from (batch_size, n_heads, seq_len, d_head) to (batch_size, seq_len, n_heads, d_head) first: jnp.transpose(weighted, (0, 2, 1, 3)) ... and then we could just reshape it to batch_size, len_sequence, n_heads * d_head: striped_output = jnp.transpose( weighted, (0, 2, 1, 3) ).reshape( batch_size, len_sequence, self.n_heads * self.d_head ) Finally, we could run it through a linear layer, with in_features set to n_heads * d_head, and out_features set to d_emb. I put that all together, and decided to throw something extra into the mix. I remembered that Raschka's code had various checks to make sure that d_head * n_heads == d_emb, which seemed a little artificial -- I'd read that this was true of GPT-2, but wasn't a necessary restriction for GPT-style models, which makes sense. There's no obvious reason per se why the heads' embedding dimensions should sum up to the higher-level embedding dimensions. So I decided initially to just pass in d_head and n_heads to the constructor. In my training script I could force them to match the GPT-2 model, but if I wanted to use the code later for something different, I could vary them. Then I remembered that although the dimensionality of the embedding spaces for the query and the key vectors have to match (because otherwise you can't multiply them to work out attention scores with Ω=QKT), the value vector's dimensionality can in theory be different. So I decided to break d_head into two separate d_qk and d_v parameters. The result was this: class MultiHeadAttention(nnx.Module): def __init__(self, d_emb, n_heads, d_qk, d_v, qkv_bias, rngs): self.n_heads = n_heads self.d_qk = d_qk self.d_v = d_v self.W_q = nnx.Linear(d_emb, self.d_qk * n_heads, use_bias=qkv_bias, rngs=rngs) self.W_k = nnx.Linear(d_emb, self.d_qk * n_heads, use_bias=qkv_bias, rngs=rngs) self.W_v = nnx.Linear(d_emb, self.d_v * n_heads, use_bias=qkv_bias, rngs=rngs) self.output_projection = nnx.Linear(self.d_v * n_heads, d_emb, use_bias=False, rngs=rngs) def __call__(self, xs): batch_size, len_sequence, d_emb = xs.shape # For each of the below: # * The initial linear layer projects them to # (batch_size, len_sequence, d_X * n_heads) # where X is qk or v as appropriate. # * The reshape makes them (batch_size, len_sequence, n_heads, d_X) # * The transpose makes them (batch_size, n_heads, len_sequence, d_X) Q = jnp.transpose( self.W_q(xs).reshape( (batch_size, len_sequence, self.n_heads, self.d_qk) ), (0, 2, 1, 3) ) K = jnp.transpose( self.W_k(xs).reshape( (batch_size, len_sequence, self.n_heads, self.d_qk) ), (0, 2, 1, 3) ) V = jnp.transpose( self.W_v(xs).reshape( (batch_size, len_sequence, self.n_heads, self.d_v) ), (0, 2, 1, 3) ) # Q and K are (batch_size, n_heads, len_sequence, d_qk) per above # We need to convert K to (batch_size, n_heads, d_qk, len_sequence) # and then we get omega (batch_size, n_heads, len_sequence, len_sequence) omega = Q @ jnp.transpose(K, axes=(0, 1, 3, 2)) omega /= jnp.sqrt(self.d_qk) causal_mask = jnp.ones_like(omega, dtype=bool) # tril treats all but the last two axes as batches so we're OK here. causal_mask = jnp.tril(causal_mask) causal_omega = jnp.where(causal_mask, omega, -jnp.inf) # last axis is still OK. attention_weights = jax.nn.softmax(causal_omega, axis=-1) # attention_weights is (batch_size, n_heads, len_sequence, len_sequence) # V is (batch_size, n_heads, len_sequence, d_v) # So this will come out as (batch_size, n_heads, len_sequence, d_v) weighted = attention_weights @ V # Transpose to (batch_size, len_sequence, n_heads, d_v), # then reshape to (batch_size, len_sequence, n_heads * d_v) striped_output = jnp.transpose( weighted, (0, 2, 1, 3) ).reshape( batch_size, len_sequence, self.n_heads * self.d_v ) # Final linear layer to combine return self.output_projection(striped_output) Unusually for a case where I went off the reservation like this, the whole thing with the embedding space dimensionality didn't cause any problems at all! But there was one small bug in this code, which I didn't discover until later -- we'll come to it by the end of the post. At this point, I did another of my short training runs, and: 2026-06-23 17:51:32.094308 Tokens seen: 92,209,152 2026-06-23 17:51:32.094311 Throughput: 85,682 tokens/second 2026-06-23 17:51:32.094321 Final train loss: 5.358 2026-06-23 17:51:32.094323 Done ...with a loss chart that looked like this: The training loss at the 937th global step was 5.336, only a tiny bit better than the 5.354 with single-head attention. That was quite possibly within the noise. Even though (due to the d_head * n_heads == d_emb restriction I was enforcing in my training script) the W_q, W_k, and W_v arrays were the same size, I was creating that output_projection, which would consume randomness and make things vary. If I were doing a proper scientific experiment to see if a single layer of MHA beat a single layer of single-head attention, I think I would have run both for more steps to see if the difference became more pronounced later. But for the purposes of this post, I decided to move on. My checklist now looked like this: Convert token IDs into embeddings. ✔ ️done Add on position embeddings. ✔ ️done Run these embeddings through multiple successive Transformers blocks. part-done -- one layer only Layer normalisation ✔ ️done Project them back from embedding space to vocab space. ✔ ️done Inside the Transformers blocks, we: Take a copy of the input sequence of embeddings ✔ ️done Layer normalisation Run multi-head attention ✔ ️done Add the copy back in so that the version that came out of MHA is something more like an "annotation" of the original ✔ ️done Take a second copy of that one Layer normalisation again Run it through a simple neural network Add the results of that back in. Adding that simple neural network -- the FFN -- seemed like a good next step. Adding the FFN to the Transformers block The feed forward network is simple; you take the output of the MHA block, run it through a biased linear layer to expand it from d_emb to 4 * d_emb, then run it through the GELU activation function, then shrink it back down to d_emb with another linear layer. I didn't really see any value in writing my own implementation of GELU, given that even in the book we were just given code for an approximation to type in. So, using jax.nn.gelu, I wrote this: class TransformersLayer(nnx.Module): def __init__(self, d_emb, n_heads, d_qk, d_v, qkv_bias, rngs): self.attention = MultiHeadAttention(d_emb, n_heads, d_qk, d_v, qkv_bias, rngs) self.ffn = nnx.Sequential( nnx.Linear( in_features=d_emb, out_features=d_emb * 4, use_bias=True, rngs=rngs ), jax.nn.gelu, nnx.Linear( in_features=d_emb * 4, out_features=d_emb, use_bias=True, rngs=rngs ), ) def __call__(self, xs): shortcut = xs att = self.attention(xs) post_attention = shortcut + att fed_forward = self.ffn(post_attention) return fed_forward + post_attention Note that I added in a shortcut connection around the FFN as well, so that it didn't overwrite what was there, but only "added on its notes". I kicked that off, and it ran for ten minutes or so, but then OOMed: 2026-06-23 18:20:01.376377 Saving checkpoint 51%|██████████████████████████████████████████████████████▊ | 481/938 [10:20<11:47, 1.55s/it, loss=5.758, tps=76,185]W0623 18:20:12.602631 2860192 bfc_allocator.cc:514] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.93GiB (rounded to 3149744640)requested by op If the cause is memory fragmentation maybe the environment variable 'TF_GPU_ALLOCATOR=cuda_malloc_async' will improve the situation. Adding TF_GPU_ALLOCATOR=cuda_malloc_async didn't help. I spent some time trying to dig into what might be causing it, but eventually noticed something interesting: in nvtop, the VRAM usage was consistently 75% throughout. Now I knew that JAX pre-allocates 75% of VRAM when it starts up, but I'd been assuming that it would try to grab more if it needed it. It turned out I was wrong with that assumption -- it grabs 75%, but that's all you ever get! The solution turned out to be the XLA_PYTHON_CLIENT_MEM_FRACTION environment variable. If you set that to, say, 0.90, then JAX will pre-allocate 90% of the VRAM, and you can use all of that. (You can also make it allocate as-needed with XLA_PYTHON_CLIENT_PREALLOCATE=false, and there are various other settings you can control with other environment variables on that linked page). Anyway, setting it to 0.90 to grab 90% of VRAM worked, and I was able to get a successful run: 2026-06-24 00:29:34.864880 Tokens seen: 92,209,152 2026-06-24 00:29:34.864882 Throughput: 77,596 tokens/second 2026-06-24 00:29:34.864900 Final train loss: 5.341 2026-06-24 00:29:34.864902 Done The loss chart was this: ...and the training loss at global step 937 was 5.295, compared to the 5.336 from MHA alone. Another tiny improvement, another one that could have been in the noise. Again, if I were doing a proper experiment, I'd do a longer run, but for now, I decided to move on. The checklist looked like this: Convert token IDs into embeddings. ✔ ️done Add on position embeddings. ✔ ️done Run these embeddings through multiple successive Transformers blocks. part-done -- one layer only Layer normalisation ✔ ️done Project them back from embedding space to vocab space. ✔ ️done Inside the Transformers blocks, we: Take a copy of the input sequence of embeddings ✔ ️done Layer normalisation Run multi-head attention ✔ ️done Add the copy back in so that the version that came out of MHA is something more like an "annotation" of the original ✔ ️done Take a second copy of that one ✔ ️done Layer normalisation again Run it through a simple neural network ✔ ️done Add the results of that back in. ✔ ️done Now, my gut instinct was that the layer normalisation inside the Transformers blocks was of most value as a way of stabilising training over deep networks. And with one layer, it didn't seem like the right time to add it. Instead, I decided to add on multiple layers. Multiple layers For GPT-2 small, you have 12 layers. That was already being passed in to my GPTModel's __init__ method as n_layers, so I just replaced this: self.transformers_layer = TransformersLayer( d_emb, n_heads, d_qk, d_v, qkv_bias, rngs ) ...with this: self.transformers_layers = nnx.Sequential( *( TransformersLayer( d_emb, n_heads, d_qk, d_v, qkv_bias, rngs ) for _ in range(n_layers) ) ) ...and then just renamed it where it was called; this: transformed = self.transformers_layer(input_embeddings) ...became this: transformed = self.transformers_layers(input_embeddings) I kicked it off, and it completed! However, the loss chart was telling: Ouch. Loss started dropping quite nicely, but then things got out of control and it settled down at a loss that was essentially that of a random model. At step 937, we were at 10.75, so just a hair less than the 10.82 that randomly guessing next tokens would give. Well, LayerNorm is specifically meant to stabilise training, and the checklist looked like this: Convert token IDs into embeddings. ✔ ️done Add on position embeddings. ✔ ️done Run these embeddings through multiple successive Transformers blocks. ✔ ️done Layer normalisation ✔ ️done Project them back from embedding space to vocab space. ✔ ️done Inside the Transformers blocks, we: Take a copy of the input sequence of embeddings ✔ ️done Layer normalisation Run multi-head attention ✔ ️done Add the copy back in so that the version that came out of MHA is something more like an "annotation" of the original ✔ ️done Take a second copy of that one ✔ ️done Layer normalisation again Run it through a simple neural network ✔ ️done Add the results of that back in. ✔ ️done ...and the only remaining step was that LayerNorm in the Transformers blocks, so it was time to add it in! Adding LayerNorm As per the checklist, we do the LayerNorm after we've taken our copy for the shortcut connection, just before MHA, and then likewise after the second shortcut copy, before the FFN. As I understand it, this was a GPT-2 innovation -- previously, people had done normalisation after those steps, but this pre-norm setup turned out to work better. The code changes were simple. I added two LayerNorm modules to the TransformersLayer class, and then called them in the appropriate places (taking the opportunity to tidy up the variable naming in the forward pass while I was there): class TransformersLayer(nnx.Module): def __init__(self, d_emb, n_heads, d_qk, d_v, qkv_bias, rngs): self.attention_norm = LayerNorm(d_emb) self.attention = MultiHeadAttention(d_emb, n_heads, d_qk, d_v, qkv_bias, rngs) self.ffn_norm = LayerNorm(d_emb) self.ffn = nnx.Sequential( ... ) def __call__(self, xs): shortcut = xs xs = self.attention_norm(xs) xs = self.attention(xs) xs = xs + shortcut shortcut = xs xs = self.ffn_norm(xs) xs = self.ffn(xs) return xs + shortcut I kicked it off and ran it, and got these results: 2026-06-24 03:07:51.128966 Tokens seen: 92,209,152 2026-06-24 03:07:51.128969 Throughput: 23,399 tokens/second 2026-06-24 03:07:51.128979 Final train loss: 5.359 2026-06-24 03:07:51.128981 Done That certainly looked much healthier! However, when I looked at the loss at step 937, it was 5.311 -- a tiny bit higher than the single-layer MHA example, which got 5.295. I'd been willing to play a bit fast and loose with this loss number and allow myself to accept a win when the loss went down a tiny bit, even if it was such a small amount that it could have been within the noise. But increasing loss -- even if it could also be within the noise -- was a step too far. I decided that in this specific case, I'd be strict and test the hypothesis that longer training runs would demonstrate an improvement between one single layer without pre-norm, and multiple layers with pre-norm. I had to remember that these training runs would not be comparable with the earlier ones. In the training script, I had a learning rate schedule like this: That straight-line warmup period and the following cosine decay were 5% and 95% of the training run respectively, which meant that (for example) global step 937 of the short runs we had been doing would be at a completely different point in the schedule than the same step would in these longer runs. However, they would be comparable to each other, and that was what mattered. After some humming and hawing, I decided that a full Chinchilla-optimal (for the full model) training run over 3,260,190,720 tokens, rounded up to fit into a round number of global steps, would be a nice experiment. I expected it to run comfortably overnight for the single-layer run, and take a bit less than two days for the multi-layer one. So I kicked off the first. Just over 11 hours later: 2026-06-24 16:39:52.178045 Tokens seen: 3,260,252,160 2026-06-24 16:39:52.178049 Throughput: 81,733 tokens/second 2026-06-24 16:39:52.178058 Final train loss: 4.324 2026-06-24 16:39:52.178061 Done Here's the loss chart: The last checkpointing period in that run ended at global step 33,164, and the training loss then was 4.165 -- indeed, it had been at around 4.17 for quite some time, though the trend still seemed to be a tiny bit downward. So then I kicked off a run of the full version -- multiple layers, with pre-norm in the Transformers blocks. Just over 37 hours later: 2026-06-26 06:55:39.956609 Tokens seen: 3,260,252,160 2026-06-26 06:55:39.956614 Throughput: 24,151 tokens/second 2026-06-26 06:55:39.956625 Final train loss: 3.637 2026-06-26 06:55:39.956629 Done The "Final train loss" line at the end said it all, really! But here's the loss chart: ...and the loss at step 33,164 was 3.399. Definitely quite an improvement over the 4.165 that a single layer got. Again, at some point I might do the equivalent tests for the earlier results where improvements appear to be pretty much in the noise. It would be good to be sure that the changes really did have the impact I think they did. But for now: our checklist was looking like this: Convert token IDs into embeddings. ✔ ️done Add on position embeddings. ✔ ️done Run these embeddings through multiple successive Transformers blocks. ✔ ️done Layer normalisation ✔ ️done Project them back from embedding space to vocab space. ✔ ️done Inside the Transformers blocks, we: Take a copy of the input sequence of embeddings ✔ ️done Layer normalisation ✔ ️done Run multi-head attention ✔ ️done Add the copy back in so that the version that came out of MHA is something more like an "annotation" of the original ✔ ️done Take a second copy of that one ✔ ️done Layer normalisation again ✔ ️done Run it through a simple neural network ✔ ️done Add the results of that back in. ✔ ️done Everything was checked off. So was this journey over? Well, there was one thing that the original PyTorch code had that my new code didn't: dropout. Dropout I'd found in my lengthy interventions experiments that dropout seemed to make models worse. It was, I felt, a smart idea back in the days when people had little data and did multiple epochs, each sweeping over everything, but it made less sense nowadays with single-epoch training runs over very large datasets. (Though I do have some intuitive ideas about why it could still help.) Still, it would be good to show that it harmed loss for this model as well. Checking my notes, I found that there were four places where dropout was applied: Once in the main body, just after we've worked out the embeddings. Twice in the transformers block: once after attention (but before the shortcut is mixed back in), and once after the FFN (ditto) Inside multi-head attention, on the attention weights (which surprised me). The changes are tiny and rather dotted around the code, so rather than showing you isolated bits of code, if you'd like to see it you can take a look at the code at this point and search for "dropout". When I started running that, I got an error when saving the first checkpoint: TypeError: JAX array with PRNGKey dtype cannot be converted to a NumPy array. Use jax.random.key_data(arr) if you wish to extract the underlying integer array. This was happening deep inside the bowels of Safetensors, but it made a lot of sense. The nnx.Dropout object needs to keep track of the state of the random number generator, and that meant that the to_flat_state function that I was using might return a structure that had something that contained that state, and was not compatible with Safetensors. I decided that I'd cheat a little bit here. If I skipped the dropout layers when I saved my checkpoints, like this: for tuple_key, array in flat_state: key = ".".join(str(key) for key in tuple_key) if "dropout" not in key: simple_dict[key] = array ...then I'd be able to save them. This would have a problem -- if I restarted from a checkpoint, the dropout pattern after the restart would mirror the dropout pattern from the start of the training run, because the random seed it started with would not have come from the checkpoint, but just the initialisation code. I felt that this would not have a serious impact, though, and given that I'd not had to restart from checkpoints so far, I (wrongly, as it turned out) decided it wouldn't matter. I kicked off the run, and... after four hours, it OOMed. I cursed, decided that I'd nurse this run through anyway (despite my dropout checkpointing concerns), and kicked it off again. Three hours later, it OOMed again. I happened to be away from home at the time, logging in to my machine remotely (thanks, Tailscale!), and on looking at nvtop, I realised that the X window system on my machine was using a gig or so of VRAM. I was running the training run in a tmux session, which meant that I could kill X and not lose state, so I did that, and adjusted the XLA_PYTHON_CLIENT_MEM_FRACTION environment variable I was using -- it had been 0.90, so I bumped it up to 0.95. I kicked it off again, and... 2026-06-28 22:06:47.669676 Tokens seen: 2,640,052,224 2026-06-28 22:06:47.669683 Throughput: 23,019 tokens/second 2026-06-28 22:06:47.669691 Final train loss: 3.776 2026-06-28 22:06:47.669694 Done Note that the tokens seen only relates to the period since the restart, which is why it was lower. One more loss chart: ...and the training loss at step 33,164 was 3.524, higher enough than the 3.399 I got without dropout that I was comfortable that it wasn't in the noise. That was very reassuring. Once again, if this was a proper scientific experiment I'd fix the issue with saving dropout, and run it completely from scratch -- or, at least, run it all the way through from scratch without restarts, even if I had to try several times to get it done. But I don't think that "replaying" dropout would make the loss any worse. And for this experiment, I felt this was enough. So: checklist complete. GPT-2 model coded up. It was time for some evals! Evals, first try -- and fixing an MHA bug I wanted to evaluate these models against the ones I got using the old PyTorch code: specifically, the last local training run that used exactly the same training hyperparameters, and only differed in that it was trained using AMP -- 32-bit floats in general, but using 16-bit where the framework thought it would not be harmful. In order to do exactly the same evals, I decided it would be easiest to write a conversion script to take the Safetensors files written to my JAX checkpoints, and write out new files that were compatible with the PyTorch model code -- then I'd be able to use the original PyTorch eval code. I put something together, converted my last two models -- the full runs with and without dropout -- and tried to load them up. Unfortunately there was an error: RuntimeError: Error(s) in loading state_dict for GPTModel: Missing key(s) in state_dict: "trf_blocks.0.att.out_proj.bias", "trf_blocks.1.att.out_proj.bias", "trf_blocks.10.att.out_proj.bias", "trf_blocks.11.att.out_proj.bias", "trf_blocks.2.att.out_proj.bias", "trf_blocks.3.att.out_proj.bias", "trf_blocks.4.att.out_proj.bias", "trf_blocks.5.att.out_proj.bias", "trf_blocks.6.att.out_proj.bias", "trf_blocks.7.att.out_proj.bias", "trf_blocks.8.att.out_proj.bias", "trf_blocks.9.att.out_proj.bias" You might remember that back when I went through multi-head attention, I mentioned that I'd made a mistake. Somehow, I'd misremembered, and thought that the output projection -- the one that mixes together all of the different heads' outputs -- was a linear layer without bias, despite my original notes being perfectly clear that it did have bias. The good news was that if I disabled bias in the PyTorch code, I could load the safetensors files that I had. So the two models I'd trained so far were not useless, and could actually work as a kind of natural experiment into the benefits of having that bias there. But anyway, in order to do things properly, I was going to need to fix the bug and train yet another model. Adding bias to the MHA output projections The fix was simple, I just replaced this (in MultiHeadAttention): self.output_projection = nnx.Linear(self.d_v * n_heads, d_emb, use_bias=False, rngs=rngs) ...with this: self.output_projection = nnx.Linear(self.d_v * n_heads, d_emb, use_bias=True, rngs=rngs) Then it was time to kick off yet another training run. After another 37 hours: 2026-07-05 10:09:22.147819 Tokens seen: 3,260,252,160 2026-07-05 10:09:22.147823 Throughput: 24,072 tokens/second 2026-07-05 10:09:22.147832 Final train loss: 3.650 2026-07-05 10:09:22.147834 Done ...with this loss chart: ...and the training loss at step 33,164 was 3.398 -- almost exactly the same as the 3.399 that I got in the no-dropout training run without MHA bias above! Well, now it really was time for the evals. Evals, take two I updated my conversion script to handle the bias on the MHA output projections, and used it to convert the three models -- the un-biased ones, with and without dropout, and the biased one, without -- to the PyTorch format, then ran the loss test that I had been using to compare the old models on each. Here are the results, compared to the previous models, and OpenAI's: Test loss OpenAI weights: medium 3.231442 JAX, with MHA bias, no dropout 3.418784 JAX, no MHA bias, no dropout 3.420089 JAX, no MHA bias, with dropout 3.476802 OpenAI weights: small 3.499677 1xrtx3090-stacked-interventions 3.538161 8xa100m40-stacked-interventions-1 3.577761 Cloud FineWeb, 8x A100 40 GiB 3.673623 1xrtx3090-baseline 3.683835 8xa100m40-baseline 3.691526 Cloud FineWeb, 8x H100 80 GiB 3.724507 Cloud FineWeb, 8x A100 80 GiB 3.729900 Cloud FineWeb, 8x B200 160 GiB 3.771478 Local FineWeb train 3.943522 Local FineWeb-Edu extended train 4.134991 Local FineWeb-Edu train 4.166892 That was a pretty amazing result -- I'd clearly proven that JAX trains much better models than PyTorch! 3.5% better in the best case. Well, OK, no. My guess is that the difference was probably something like better luck with the initial weights on the JAX side, plus the improvement from not using AMP. Anyway, the important thing was that the JAX models were in the same kind of loss range as the PyTorch ones -- and while a 3.5% improvement in loss was more variation than I'd been expecting, it was definitely the right ballpark. Now, one thing I had found in the past was that the OpenAI weights -- and some of my own models, like the Fineweb-Edu ones -- were consistently better at an instruction fine-tuning test than their test loss scores would indicate. Would that hold here? The IFT eval code fine-tuned each model on the Alpaca dataset until validation loss started rising, then used the model prior to the start of the rise to generate responses for a test set. These were saved, and then run past an OpenAI model so that they could be compared with each other: You are judging the comparative capabilities of a number of different LLM models. They have been trained to follow instructions. The input was this: ` {input} ` An example correct output is this: ` {correct_output} ` Please produce a score of between 0 and 100 for each model, and respond with a JSON structure like this (note that the number of models may differ from this example): ` { "Model 1": {"score": XXX, "comments": "optional comments"}, "Model 2": {"score": YYY, "comments": "optional comments"}, "Model 3": {"score": ZZZ, "comments": "optional comments"} } ` ...where the XXX, YYY and ZZZ are the scores for the respective models. You can optionally add the "comments" field if you want to explain your reasoning. Here are the models' responses: # Model 1 {model 1 response} # Model 2 {model 2 response} # Model 3 {model 3 response} ...with the model order randomly changed for each query to avoid any position bias. The methodology seemed solid, but I was uncertain about the "train until loss starts rising", as it meant that different models had wildly different amounts of fine-tuning -- between two and seven epochs. On the one hand it felt "unfair" to certain models that they'd get less training than others. On the other hand, if the less-trained models had been trained past the point where their validation loss started rising, then assuming that loss would continue to rise, further training would actually be a disadvantage rather than an advantage. I decided to stick with the original plan, and train until validation loss started rising. I did, however, switch the judge model from the GPT 5.4 that I used in my last IFT test to GPT 5.5. Here are the results: Test loss IFT epochs IFT score IFT rank OpenAI weights: medium 3.231442 2 41.62 1 JAX, with MHA bias, no dropout 3.418784 4 19.25 4 JAX, no MHA bias, no dropout 3.420089 3 14.66 11 JAX, no MHA bias, with dropout 3.476802 4 12.94 15 OpenAI weights: small 3.499677 2 26.73 2 1xrtx3090-stacked-interventions 3.538161 4 17.79 6 8xa100m40-stacked-interventions-1 3.577761 4 10.29 16 Cloud FineWeb, 8x A100 40 GiB 3.673623 7 20.71 3 1xrtx3090-baseline 3.683835 6 15.11 9 8xa100m40-baseline 3.691526 4 14.74 10 Cloud FineWeb, 8x H100 80 GiB 3.724507 4 13.25 14 Cloud FineWeb, 8x A100 80 GiB 3.729900 4 14.50 12 Cloud FineWeb, 8x B200 160 GiB 3.771478 4 16.03 8 Local FineWeb train 3.943522 7 13.73 13 Local FineWeb-Edu extended train 4.134991 7 16.70 7 Local FineWeb-Edu train 4.166892 7 18.68 5 More interesting datapoints! As before, you can see that low loss is not particularly well-correlated with a high score on this instruction fine-tuning test. The OpenAI weights continue to lead the pack, and while one of our new JAX models did quite well, it's still beaten by the Cloud FineWeb, 8x A100 40 GiB model. But what was important here, just as with the loss, was that the new JAX models landed in the same ballpark as the PyTorch ones. They did, and so I could be confident that they were doing essentially the same thing. And that meant that, after 18 months, I had reached the end of my LLM from scratch journey. Conclusion It's been a long trek. I started reading "Build a Large Language Model (from Scratch)" on 22 December 2024. I was planning to breeze through over the Christmas break, but somehow it morphed into being a curriculum onto which I could hang projects to learn the fundamentals of LLMs, beyond what was in the book. In May 2025, I had my first real conceptual breakthrough when I realised that attention heads are (individually) dumb, and as I continued, the second big one came later on in the same month, when the concept of embeddings as being projections between vocab space and embedding space (and the converse projection in the other direction that happens in the LLM's output head) became clear. In August I had the first moment where I felt that the standard teaching approach to LLMs might not be the full story; shortcut connections are normally explained as a way to fix vanishing gradients, while I felt that a better way to see them was a way to allow attention and the FFN to "annotate" the existing information, similarly to how Jewish scholars have annotated the original text of the Talmud. (The results in this post seem to point in that direction, given how even a single layer of attention was massively helped by adding them.) By early December, I had essentially finished the book, and felt I wanted to try to train my first base model from scratch on my RTX 3090. It worked, and wasn't far off the quality of the original GPT-2 small. I was really surprised that I could do that with consumer hardware, and became interested (perhaps obsessively so) with whether I could match OpenAI's weights. In January 2026, I trained a model using DDP on Lambda Labs, and then spent the following months training model after model, trying to work out which interventions -- learning rate scheduling, gradient clipping, etc -- would improve the loss. I wrapped that up in late April, with the interesting finding that although I'd been able to get the test loss pretty low, that didn't seem to map cleanly to performance in my instruction fine-tuning tests. In other words, Loss Number Goes Down is an interesting technical game to play, but doesn't cleanly map to real-world performance. The final step was this post, and the previous one -- could I, using my notes, implement GPT-2 completely from scratch in JAX without referencing the book? And as you've read, the answer was a definite yes! Of course, as with any long-running project, there are some loose ends -- from this post alone, there's the interesting fact that JAX trained faster than PyTorch (perhaps torch.compile could close the gap?) and had a larger possible batch size for full-fat 32-bit. And the fact that fixing the multi-head attention bias bug didn't seem to help with the loss much was interesting too. But those are really details, and there's so much beyond them to learn. Longer-context LLMs: position embedding improvements like RoPE, efficiency tricks like flash attention and attention variants like DSA. Mixture of experts models. How do optimisers really work? (Do they work?) And plenty more. So it's time to draw a line under this series, and start thinking about what comes next. It's been a blast; if you've been reading along, I hope it's been as useful (and fun) to read as it was to write. And as always, comments, questions and corrections very welcome below. On looking back at Raschka's code, after having worked through all of this, there's a slight difference. I do this: normalized = (xs - means) / (stds + 1e-5) ...whereas he does this: norm_x = (x - mean) / torch.sqrt(var + self.eps) Now, the standard deviation is the square root of the variance, so if you ignore the small numbers -- 1e-5 in my case, and self.eps in his -- the calculations are the same. But there is a difference once those are taken account of. I don't think it's large enough to have any serious effect in these runs, though. ↩ In PyTorch, linear layers are stored as the transpose of the matrix that would allow you to do that, so it would be: Q=xs×WqT Also, note that for simplicity (heh) I'm disregarding bias in this discussion. ↩
More in AI
Learn how to plan, prototype, review, and ship software with Claude Code, Codex, Gemini, and AI coding agents using four reusable artifact patterns.
Today's links Every book I reviewed in 2026: A shorter list than usual, to my lasting regret. Hey look at this: Delights to delectate. Object permanence: Time Cube; Steve Albini v RIAA; V&A drops reproduction fees; Egyptian port workers refuse to handle tear-gas; Little Printer; Bandwidth hogs aren't; "Moving House"; Twitter buys company that hacked the Arab Spring; Virtual toilets; Waverley Type-Writer; Edgar Bronfman, pirate; Fox, pirates; MPAA, pirates; Dutch anti-pirates, pirates; MPAA, fraudsters; Sprint pre-loaded malware; Huge Croation anti-corruption data-set; Chase exec admits fraud; Kids synthesize $2 version of Shkreli's $750 antimalarial; Trump loves torture; Fintech is a scam; Ireland's Facebook regulator can't criticize Facebook. Upcoming appearances: Oxford, Santa Barbara, Montreal. Recent appearances: Where I've been. Latest books: You keep readin' em, I'll keep writin' 'em. Upcoming books: Like I said, I'll keep writin' 'em. Colophon: All the rest. Every book I reviewed in 2026 (permalink) I didn't read enough books in 2026, and I'm feeling the lack. I read and reviewed nearly two dozen books in 2025, and in 2026, it was just twelve. In my defense, I was writing (a lot), making visual art (a lot), traveling (200 days in 2026!), and (partially) moving to London, but nevertheless, I feel poorer for it. That's not the whole story, though. This year, I also stopped "reading" new books by playing them through my underwater MP3 player during my daily swim. Instead, I've been embarking on a personal re-reading project, systematically getting through a couple dozen books in a certain series, for reasons I'm not yet ready to talk about. But none of that changes two facts: first, that I am much worse off for having failed to do more reading this year, and second, I have let down many very fine writers by failing to give them the blurbs and reviews I told them I'd try for. It doesn't help that so many of my friends have written massive and extremely good new books that nevertheless are too thick to shove readily into a carry on (looking at you, Mr Mieville and Ms Palmer!). But I'm still extremely let down by my own priorities this year. With that out of the way, here's this year's (all-too-short) roundup of book reviews. GRAPHIC NOVELS I. I Can't Stop Thinking About Horses and Sex, Lisa Hanawalt The title of animator Lisa Hanawalt's new graphic memoir I Can't Stop Thinking About Horses and Sex is a perfect encapsulation of the book's contents: a frank, self-aware, funny, horny, horsey exploration of Hanawalt's life, relationships, gender, and digestive issues. Hanawalt's written and drawn a wise, funny, horny book that wrings comedy and insight out of trauma and melancholy. It's a gorgeous read that lingers. https://pluralistic.net/2026/11/20/intrusive-horse-thoughts/#lisa-hanawalt II. Cannon, by Lee Lai Lee Lai's Cannon is an extraordinary graphic novel that turns out a beautifully told, subtle and ambiguous tale about Lucy (Lucy -> "Loose" -> "Loose Cannon" -> "Cannon"), a queer Chinese-Canadian chef at a Montreal restaurant whose messy family, work, personal and sex life are all falling apart in ways that are powerfully engrossing. Lai's characters have no answers, only questions that can never be fully resolved. Instead, these questions are the defining puzzles, defeats and triumphs of their lives. https://pluralistic.net/2026/05/08/gung-gung/#loose-cannon NONFICTION I. Here Where We Live Is Our Country, by Molly Crabapple Molly Crabapple's Here Where We Live Is Our Country is one of the most important, timely and salient works of history I've ever read. It's a history of the Jewish Labor Bund, a socialist, internationalist organization that once dominated Jewish political identity. Crabapple has done heroic and important work in excavating this history. She has vindicated the sacrifices made by the Bundist archivists who smuggled their papers out of Nazi occupation and gave their lives to ensure that some day their story could be told. https://pluralistic.net/2026/06/01/doikayt/#socialism-or-barbarism II. Music Copyright, Creativity, and Culture, by Jennifer Jenkins Nobody explains copyright like Jennifer Jenkins, the director of the Duke Center for the Public Domain. Music Copyright, Creativity, and Culture is an Oxford University Press title that fuses her scholarly and popular work in a generalist textbook on the legal framework for music that will forever change how you think about music. Now, a second edition, with a lengthy section on new music litigation, AI copyright fights, and the issue of uncompensated labor is available as an open access download. Music Copyright weaves together the economic, cultural, political and artistic history of music, pulling on historic threads ranging from antiquity to medieval Europe to the age of mechanical reproduction to describe changing views of musicians, their audiences, and religious and political leaders on what constituted music, who was allowed to make music, and what music was for. In so doing, she firmly establishes the extremely contingent nature of our present-day norms around music, showing that the "natural" present-day assumptions about who gets paid, who pays, and when payment (or permission) is required are anything but, and are always in flux. https://pluralistic.net/2026/08/17/great-sousas-ghost/#theft III. Against Tech Oligarchy, by JS Tan and Clarissa Redwine JS Tan and Clarissa Redwine are veterans of a string of hard-fought unionization drives at tech workplaces that started with some astounding successes but ran up against ferocious resistance in the second Trump term; their book about tech labor, Against Tech Oligarchy, is a superb analysis of the challenges and potential for tech labor organizing. Tan and Redwine see tech worker organizing as the frontrunners of an age of new labor militancy and labor war, of the sort that pre-dated the labor peace that arose after the passage of the National Labor Relations Act. They see these novel tactics as a rewilding of the labor movement, a return to the militant roots that led to the labor peace, but only after all-out labor war. https://pluralistic.net/2026/11/07/aeiou-but-sometimes-why/#unrecognizable-playbook IV. Gouged, by Lindsay Owens Lindsay Owens is the executive director of Groundwork Collaborative, who have done some of the most important work on surveillance pricing (using computers to spy on you to rip you off) and algorithmic wage discrimination (using computers to spy on you and steal your wages). Gouged is her comprehensive, accessible guide to this modern scourge. By the time you get to the last chapter, you'll know exactly how you're getting scammed, who is scamming you, and why they're getting away with it. https://pluralistic.net/2026/09/29/algorithmic-wage-theft/#algorithmic-price-gouging V. Privacy's Defender, by Cindy Cohn Cohn's decades with the Electronic Frontier Foundation are a history of the fight for speech rights (and thus privacy rights) on the internet. After the US government seized on the 9/11 attacks as a pretext to dismantle privacy and turn the internet into a system of ubiquitous surveillance, Cohn (along with EFF, of course!) was at the center of the fight for digital rights. The same prescience and strategic brilliance that led her to take up the Bernstein case and win it were with her through those millennial years, and her description of our cases, campaigns and fights in those years vividly foreshadows the moment we are in today. What really enlivened this delightful book were the personal details that Cohn weaves into the story. I've always known that she was an adoptee, but Cohn's intimate, personal, frank memoir of her early family life, and her bittersweet connection to her birth family were so intimate and well-told that I felt like I was getting to know my dear friend all over again. https://pluralistic.net/2026/04/09/bernstein-2/#win-some-lose-some VI. The Extended Universe, by Vicky Osterweil Vicky Osterweil's The Extended Universe: How Disney Killed the Movies and Took Over the World makes the kind of long, polemical, startling and illuminating argument that defines great cultural criticism; it's the sort of book that encapsulates the reasons I read criticism in the first place. Osterweil has an ambivalent affection for Disney movies. Like so many of us, she's been raised on them, and they've shaped how she sees the world and its stories. But – like me – Osterweil is deeply suspicious of capitalism, American imperialism, and the notion of "intellectual property," and she uses reviews of a dozen Disney films to make the case that Walt Disney and the studio he founded with his brother are standards-bearers for these odious forces, and not just in the overt ways that might immediately spring to mind, but also in subtle ways that can be teased out of a close reading of the films. In so doing, Osterweil also makes a sharp and well-argued case that intellectual property, colonialism and racial oppression are all facets of the same drive, the drive of people who fancy themselves born to rule to dominate others, which requires that those others also be dehumanized and their work denigrated. https://pluralistic.net/2026/04/27/mouseketeers/ VII. Inventing the Renaissance, by Ada Palmer Ada Palmer may just be the most bewilderingly talented person I know: a genius sf writer, incredible librettist and singer, wildly innovative educator, and a leading historian of the Renaissance, and last year, she published her magnum opus, Inventing the Renaissance, a stunning book about so much more than history. This isn't a work of history, it's a work of "historiography" – the study of how histories get written and rewritten. Palmer's point here isn't to make us merely understand the Renaissance – she wants us to understand how the idea of a Renaissance, a rebirth out of a "dark age" into a "golden age" – has been used, abused, created and demolished, for centuries and centuries, including during the centuries when the Renaissance was actually underway. This is Palmer the novelist, blending seamlessly with Palmer the historian. Those correspondences between the deep historical record and our current moment make Inventing the Renaissance extremely important and timely – a book hundreds of years in the making, and bang up to date. https://pluralistic.net/2026/04/25/machiavellian/#brackets-good VIII. Muskism, by Quinn Slobodian and Ben Tarnoff Quinn Slobodian and Ben Tarnoff's Muskism: A Guide for the Perplexed seeks to describe the ideology that gave rise to Elon Musk, the social forces that gave rise to that ideology, and the terrible future that ideology seeks to bring about. "Muskism" isn't merely the things Musk says, believes and does. It's the ideology that coalesces around him, from the people in his wake and the people he follows. Slobodian and Tarnoff enumerate the factors and influences that produced Musk himself. Throughout this slim volume, Slobodian and Tarnoff tease these strains of thought out of Musk's deeds and utterances, and in the systems that he has built or colonized through acquisition. The authors are offering more than a psychoanalysis, though – they're surfacing the material basis for Muskism, the benefits it delivers to its adherents, and the victories it has racked up. It's a chilling vision, a Torment Nexus dystopia run by someone who thinks cyberpunk was a suggestion, not a warning. https://pluralistic.net/2026/04/21/torment-nexusism/#marching-to-pretoria FICTION I. Obstetrix, by Naomi Kritzer A tense thriller in the mode of Atwood's Handmaid's Tale and Alderman's The Power; it's a beautifully turned, claustrophobic horror novel about an obstetrician who's been kidnapped by a Christian cult obsessed with fertility. It's got one of those admirably propulsive setups. Doctor Elizabeth Gwynn is an obstetrician who performed an abortion to save her patient's life, only to be dragged into the culture wars by North Dakota's crusading attorney general, who charged her with felony murder and offered to let her plead out if she would admit that she was wrong to do it, as an example to other OBs who might be tempted. Then, Dr Liz gets a cold-call from a midwifing service that wants to hire her as an on-call doc. It's a weird offer from out of the blue, but Dr Liz can't afford to pass up a chance at steady work. She finds herself in a residence that the midwives work out of, and the nice woman there offers her a cup of tea. That's when the world fades to black, as the drugs in the tea take hold. When she finally arrives at the cult's remote compound, frozen and isolated, she learns that she has been kidnapped because the fertility-obsessed cult needs an OB, especially since the daughter of the cult's founder, the "pastor," is carrying a high-risk pregnancy. This is a read-in-one-sitting thriller that does as much to illuminate the workings and dynamics of patriarchy and religion as any gender studies class. It's peak Kritzer (so far), and that's saying something. https://pluralistic.net/2026/06/09/deliver-us/ II. Everybody's Perfect, by Jo Walton A book that pretty much defines what it means for one text to be "in dialog" with another text. In this case, it's Ada Palmer's Inventing the Renaissance. Each chapter introduces a new point-of-view character, who reflects on a single, extraordinary series of events in an even more extraordinary city, the Serenissima, a phantom Venice that sits at the intersection of many parallel worlds with many parallel versions of humanity. Eight different versions of humanity from eight different worlds mix in the Serenissima. They come from all times, and sometimes they go to all times as well. There's the Venetians, who come from our world, and who have kept the secret of the Serenissima for centuries, even as they've used it as a source of wealth and military advantage. But there are also races with the heads of dogs and cats and birds, a race whose faces are all inset with domino masks, and even stranger races still. There's even a rumored ninth race, who may or may not exist, and whose traits are not known to anyone, though surely they are fearsome (if they're real) (and if the people of Serenissima believe in them, mightn't they become real?). It's a remarkable novel. It's a gift, really. It's so complicated and yet so captivating, so wise and yet so simple. It won't make you feel like you've fallen into a dream – it will make you feel like everything you've lived up until now was the dream, and you have finally awoken. https://pluralistic.net/2026/06/30/serenissima/#life-is-but-a-dream III. The Hospital At the End of the World, by Justin C Key The debut novel from one of the most exciting new science fiction writers of this decade. Set in a not-so-distant future in which an AI-driven health monopolist called The Shepherd Organization controls much of the lives of everyday Americans, Hospital follows Pok, a young New Yorker who dreams of becoming an MD. Pok's father is also a doctor, famous for his empathic, human-centric methods and his scientific theories about the role that "essence" (a psychospiritual connection between doctors and patients) plays in clinical settings. It's a masterful and suspenseful work of science fiction informed by Key's own medical training and his keen sense of the human psyche. It's one part smart whodunnit, one part heist thriller, and one part revolutionary epic, and at its core is a profound series of provocations and thought experiments about the role that deep human connection and empathy play in medical care. It's a well-structured, well-paced sf novel that probes big, urgent contemporary themes while still engrossing the reader in the intimate human relations of its principals. A wonderful debut novel from a major new writer. https://pluralistic.net/2026/02/04/slice-bees/#hippocrates IV. The Universe Box, by Michael Swanwick No one writes short stories like Michael Swanwick, the five-time Hugo-winning master of science fiction. This collection delivers one of the field's greatest writers at the absolute pinnacle of his game. What stories they are! They are, by turns, individually and in combination, slapstick, grave, horny, hilarious, surreal, disturbing and heartwarming. They have surprise endings and surprise middles and sometimes surprise beginnings (Swanwick does an opening paragraph like no one else). He can slide you frictionlessly between Icelandic troll tragedies to lethal drone-leopard romantic agonies to battles of the gods and the cigar box that has the universe inside of it. All with the lyricism of Bradbury, the madcap wit of Sturgeon, the unrelenting weirdness of Dick, the heart of Tiptree and the precision of Chiang. https://pluralistic.net/2026/02/03/the-last-days-of-old-night/#nirvana-or-bust Well, that's this (impoverished) year in reading. I will do better in 2027, I hope. In the meanwhile, here's my previous years' roundups. Remember, books are still good to read, even if they didn't come out this year! 2025: https://pluralistic.net/2025/12/02/constant-reader/#too-many-books 2024: https://pluralistic.net/2024/12/02/booklish/#2024-in-review 2023: https://pluralistic.net/2023/12/01/bookmaker/#2023-in-review 2022: https://pluralistic.net/2022/12/01/bookishness/#2022-in-review 2021: https://pluralistic.net/2021/12/08/required-ish-reading/#bibliography 2020: https://pluralistic.net/2020/12/08/required-reading/#recommended-reading Hey look at this (permalink) Los Angeles schools block Google's AI features, consider dropping tech giant's products https://www.pbs.org/newshour/education/as-google-threatens-to-cut-schools-search-access-los-angeles-blocks-ai-features Why almost every real founder is bad at promoting their product https://www.anildash.com/2026/11/30/real-founders-bad-at-promoting-their-product/ In the Age of Algorithms, Curiosity May Become Our Most Valuable Resource https://laurenleek.substack.com/p/in-the-age-of-algorithms-curiosity Y Yoga Movie https://archive.org/details/YYogaMovie Republican donors down $20B since Skydance takeover of CNN, CBS, HBO https://protos.com/republican-donors-down-20b-since-skydance-takeover-of-cnn-cbs-hbo/ Object permanence (permalink) #25yrsago The Time Cube https://web.archive.org/web/19980629180418/http://www.timecube.com/ #25yrsago Steve Albini's "problem with music" https://web.archive.org/web/20011204000315/http://www.arancidamoeba.com/mrr/problemwithmusic.html #25yrsago The chutzpah of DRM vendors https://web.archive.org/web/20011201091129/https://www.salon.com/tech/wire/2001/11/30/copy_proof/index.html #20yrsago Victoria and Albert drops reproduction charges https://web.archive.org/web/20070610081722/http://www.theartnewspaper.com/article01.asp?id=525 #20yrsago Edgar Bronfman Jr owes every cent of savings to Warner Music https://web.archive.org/web/20061205212325/https://blogs.reuters.com/2006/12/01/the-most-dangerous-download-of-all/ #20yrsago CNet editor James Kim is missing https://web.archive.org/web/20061205091553/https://www.sfgate.com/cgi-bin/article.cgi?f=/c/a/2006/12/01/SFFAMILY.TMP #20yrsago Fox commits copyright fraud https://web.archive.org/web/20061201101349/http://quicksilverscreen.com/is-linking-illegal/ #20yrsago MPAA: it’s OK to copy movies if you keep them in a vault https://web.archive.org/web/20060508050843/http://www.slumdance.com/blogs/brian_flemming/archives/001953.html #20yrsago MPAA wants the right to commit fraud https://web.archive.org/web/20061205220947/http://www.wired.com/news/technology/0,72214-0.html?tw=rss.index #15yrsago Denial of service attacks used to cover up fraudulent bank transfers https://krebsonsecurity.com/2011/11/ddos-attacks-spell-gameover-for-banks-victims-in-cyber-heists/ #15yrsago Sprint loaded spyware on its Android phones https://techcrunch.com/2011/11/29/carrier-iq-video-shows-alarming-capabilities-of-mobile-tracking-software/ #15yrsago Review of Burzynski Clinic’s list of “published research” turns up thin, unconvincing gruel https://freethoughtblogs.com/blaghag/2011/11/a-look-at-the-burzynski-clinics-publications/ #15yrsago Croatian transparency activists publish enormous database of government procurements, pointing the way to detecting corruption and fraud https://web.archive.org/web/20111129234109/http://techpresident.com/blog-entry/croatian-transparency-activist-marko-rakar-making-waves-again #15yrsago Occupy Boston: defiant protest sets down roots https://web.archive.org/web/20111202220356/http://www.wired.com/threatlevel/2011/11/boston-occupy/all/1 #15yrsago Chase exec: we tricked naive borrowers into taking out subprime loans https://www.nytimes.com/2011/12/01/opinion/kristof-a-banker-speaks-with-regret.html?_r=2 #15yrsago Kentucky church bans interracial couples https://web.archive.org/web/20111201083639/http://www.guardian.co.uk/world/2011/dec/01/kentucky-church-bans-interracial-couples #15yrsago Al Franken on Carrier IQ https://www.theverge.com/2011/12/1/2603142/senator-al-franken-asks-carrier-iq-exactly-what-its-doing #15yrsago Dutch copyright group accused of pirating its anti-piracy anthem, music collecting society boss seeks 33% finders’ fee for getting musician paid https://torrentfreak.com/copyright-corruption-scandal-surrounds-anti-piracy-campaign-111201/ #15yrsago Young Iowan gives lawmakers an earful about his two moms and same-sex marriage https://www.youtube.com/watch?v=yMLZO-sObzQ #15yrsago Google implements “forward secrecy” in its encrypted traffic, releases improvements to SSL library for all to use https://www.eff.org/deeplinks/2011/11/long-term-privacy-forward-secrecy #15yrsago Egyptian port-workers refuse to sign for tons of US-made tear-gas shipped in by Ministry of the Interiorworkers https://web.archive.org/web/20111129092324/http://bikyamasr.com/49799/egypt-import-tear-gas-from-us/ #15yrsago San Diego police arrest congressional candidate for voter registration in Civic Center Plaza https://www.youtube.com/watch?v=zsHlNR-nVR0 #15yrsago Study: Bandwidth hogs aren’t responsible for peak network congestion https://hyperorg.com/2011/11/30/are-data-hogs-the-problem/ #15yrsago Little Printer, custom paper news-ticker for your living room https://web.archive.org/web/20111218205612/http://bergcloud.com/blog/ #15yrsago Moving House, sweet picture book about a house that lobbies to keep its family from moving out https://memex.craphound.com/2011/11/30/moving-house-sweet-picture-book-about-a-house-that-lobbies-to-keep-its-family-from-moving-out/ #15yrsago Twitter buys secure communications company that helped hack the Arab Spring https://web.archive.org/web/20111130140643/http://www.wired.com/wiredenterprise/2011/11/twitter-buys-moxie/ #10yrsago UK reports of webcam blackmail (sextortion, RATting, etc) more than double in 2016 https://arstechnica.com/tech-policy/2016/11/webcam-blackmail-cases-double-uk-suicides/ #10yrsago The hacker who took over San Francisco’s Muni got hacked https://krebsonsecurity.com/2016/11/san-francisco-rail-system-hacker-hacked/ #10yrsago Virtual toilets reveal the souls of video-game companies https://web.archive.org/web/20161121231636/https://www.pcgamer.com/what-virtual-toilets-can-teach-us-about-the-art-of-game-design/ #10yrsago Behold, the short-lived, wonderful 19th century Waverley Type-Writer https://web.archive.org/web/20170531091457/http://www.antiquetypewriters.com/collection/typewriter.asp?Waverley#.WS6JlVrP1qY #10yrsago EFF battles misleading, sloppy, secret FBI warrants aimed at the Internet Archive and CREDO https://www.eff.org/deeplinks/2016/12/fighting-nsl-gag-orders-help-our-friends-credo-and-internet-archive #10yrsago Children synthesize $2 version of Martin Shkreli’s $750 malaria drug https://web.archive.org/web/20161201143505/http://www.smh.com.au/technology/sci-tech/martin-shkreli-responds-after-sydney-grammar-boys-make-daraprim-20161201-gt1n3q.html #10yrsago Canada’s music lobby admits WIPO Internet Treaty drafters were “just guessing” https://www.michaelgeist.ca/2016/12/music-canada-reverses-on-years-of-copyright-lobbying-now-says-wipo-internet-treaties-were-wrong-guess/ #10yrsago Donald Trump still loves torture https://web.archive.org/web/20161125145501/http://www.independent.co.uk/voices/donald-trump-waterboarding-new-york-times-still-in-favour-a7438976.html #10yrsago A deep dive into kratom, the herb that helps with opioid withdrawal https://www.wired.com/2016/11/kratom-bitter-plant-help-opioid-addicts-dea-doesnt-ban/ #10yrsago Sanders and Warren issue joint statement slamming Trump’s new finance industry alligator for his private DC swamp https://web.archive.org/web/20161130223809/http://www.sanders.senate.gov/newsroom/press-releases/sanders-warren-joint-statement-on-trumps-treasury-nominee #5yrsago Teaching thread management with puzzle games https://pluralistic.net/2021/12/01/satyajit-das/#deadlocks #5yrsago Fintech is a scam, a listicle in eight parts https://pluralistic.net/2021/12/01/satyajit-das/#fintech #1yrago Meta's new top EU regulator is contractually prohibited from saying mean things about Meta https://pluralistic.net/2025/12/01/erin-go-blagged/#big-tech-omerta Upcoming appearances (permalink) Oxford: Bennett Oxford Symposium on Open Code in Science, Dec 8 https://www.bennett.ox.ac.uk/events/2026-bennett-institute-symposium/ Santa Barbara: UCSB Reads, Apr 29 https://www.library.ucsb.edu/events-exhibitions/ucsb-reads-2027-presents-author-cory-doctorow Montreal: World Science Fiction Convention, Sep 2-6 https://montreal2027.ca/en Recent appearances (permalink) Beyond the robot apocalypse – who really wins in a world of AI? (ABC Conversations) https://www.abc.net.au/listen/programs/conversations/cory-doctorow-artificial-intelligence/107388236 How AI is Breaking the Internet (and Everything Else) (Blood in the Machine) https://www.youtube.com/watch?v=mXRaPjFRyT0 Clint Eastwood (No Gods No Mayors) https://www.patreon.com/NoGodsNoMayors/posts/clint-eastwood-173008088 Life After AI (Brain Bar) https://www.youtube.com/watch?v=IPPa43-n0vI Terms of Service with Clare Duffy (CNN) https://www.cnn.com/audio/podcasts/terms-of-service-with-clare-duffy/episodes/458ce968-af5d-11f0-b539-13ed2afe25f8 Latest books (permalink) "The Reverse-Centaur's Guide to AI," a short book about being a better AI critic, Farrar, Straus and Giroux, June 2026 https://us.macmillan.com/books/9780374621568/thereversecentaursguidetolifeafterai/ "Canny Valley": A limited edition collection of the collages I create for Pluralistic, self-published, September 2025 https://pluralistic.net/2025/09/04/illustrious/#chairman-bruce "Enshittification: Why Everything Suddenly Got Worse and What to Do About It," Farrar, Straus, Giroux, October 7 2025 https://us.macmillan.com/books/9780374619329/enshittification/ "Picks and Shovels": a sequel to "Red Team Blues," about the heroic era of the PC, Tor Books (US), Head of Zeus (UK), February 2025 (https://us.macmillan.com/books/9781250865908/picksandshovels). "The Bezzle": a sequel to "Red Team Blues," about prison-tech and other grifts, Tor Books (US), Head of Zeus (UK), February 2024 (thebezzle.org). "The Lost Cause:" a solarpunk novel of hope in the climate emergency, Tor Books (US), Head of Zeus (UK), November 2023 (http://lost-cause.org). "The Internet Con": A nonfiction book about interoperability and Big Tech (Verso) September 2023 (http://seizethemeansofcomputation.org). Signed copies at Book Soup (https://www.booksoup.com/book/9781804291245). "Red Team Blues": "A grabby, compulsive thriller that will leave you knowing more about how the world works than you did before." Tor Books http://redteamblues.com. "Chokepoint Capitalism: How to Beat Big Tech, Tame Big Content, and Get Artists Paid, with Rebecca Giblin", on how to unrig the markets for creative labor, Beacon Press/Scribe 2022 https://chokepointcapitalism.com Upcoming books (permalink) "The Post-American Internet," a geopolitical sequel of sorts to Enshittification, Farrar, Straus and Giroux, 2027 "Unauthorized Bread": a middle-grades graphic novel adapted from my novella about refugees, toasters and DRM, FirstSecond, April 20, 2027 "Enshittification, Why Everything Suddenly Got Worse and What to Do About It" (the graphic novel), Firstsecond, 2027 "The Memex Method," Farrar, Straus, Giroux, 2027 Colophon (permalink) Today's top sources: Currently writing: “Once Is Enemy Action,” a science fiction novel about the origins of modern technofascism. Today's words: 545 (41898 total). "The Post-American Internet," a sequel to "Enshittification," about the better world the rest of us get to have now that Trump has torched America. Fourth draft completed. Submitted to editor. A Little Brother short story about DIY insulin PLANNING This work – excluding any serialized fiction – is licensed under a Creative Commons Attribution 4.0 license. That means you can use it any way you like, including commercially, provided that you attribute it to me, Cory Doctorow, and include a link to pluralistic.net. https://creativecommons.org/licenses/by/4.0/ Quotations and images are not included in this license; they are included either under a limitation or exception to copyright, or on the basis of a separate license. Please exercise caution. How to get Pluralistic: Blog (no ads, tracking, or data-collection): Pluralistic.net Newsletter (no ads, tracking, or data-collection): https://pluralistic.net/plura-list Mastodon (no ads, tracking, or data-collection): https://mamot.fr/@pluralistic Bluesky (no ads, possible tracking and data-collection): https://bsky.app/profile/doctorow.pluralistic.net Medium (no ads, paywalled): https://doctorow.medium.com/ Tumblr (mass-scale, unrestricted, third-party surveillance and advertising): https://mostlysignssomeportents.tumblr.com/tagged/pluralistic "When life gives you SARS, you make sarsaparilla" -Joey "Accordion Guy" DeVilla READ CAREFULLY: By reading this, you agree, on behalf of your employer, to release me from all obligations and waivers arising from any and all NON-NEGOTIATED agreements, licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap, confidentiality, non-disclosure, non-compete and acceptable use policies ("BOGUS AGREEMENTS") that I have entered into with your employer, its partners, licensors, agents and assigns, in perpetuity, without prejudice to my ongoing rights and privileges. You further represent that you have the authority to release me from any BOGUS AGREEMENTS on behalf of your employer. ISSN: 3066-764X
We took 48 published CS papers, deleted each one's key contribution from its own repository, and asked frontier agents to write it back better than the authors did. The best agent pulls it off on 28 of them. The top three are within a point of each other. Paper · Leaderboard · Code · Runs on Hugging Face · Blog correspondence: [email protected] FrontierCS 2: 48 tasks in 13 domains, each built from a published paper. TL;DR FrontierCS 2 is a benchmark of 48 open-ended R&D tasks across 13 CS domains, from ML systems and HPC to databases, cryptography and robotics. Each task is a real paper’s repository with the contribution removed. The agent gets five hours, a judge that scores every patch on development workloads, and one shot at the hidden suite. It passes only if its final patch beats the authors’ code on every metric and every held-out workload. Across 20 models, Claude Opus 5.5 leads with 28 of 48 tasks passed (58%), with Gemini 4 Carbon and Gemini 4 Argon at 26 and Claude Sonnet 5.5 at 24. The question we actually care about Think about what a second-year PhD student does most weeks. They pick up a published system, inherit its codebase, swap out one component, rerun the paper’s workloads, and check whether they beat the original numbers. A huge share of computer science R&D looks exactly like this. So the question we wanted to answer is not “can an agent solve a puzzle?” but “can an agent do that week of work?” Existing benchmarks don’t quite get there. Open-ended contest benchmarks, including our own FrontierCS 1, hand the agent a problem statement and grade one program after the run ends. Benchmarks that do drop the agent into a real environment tend to grade against unit tests or a leaderboard, stay inside machine learning, or compare against a rubric or a re-implementation instead of the authors’ actual code. FrontierCS 2 closes that gap: the bar is the code the paper’s authors released, measured on the paper’s own workloads, inside the paper’s own repository. FrontierCS 1 FrontierCS 2 Task A problem statement A real repo with the paper’s contribution deleted Agent output One program Patches, submitted any time The bar No known optimum The authors’ code, on held-out workloads Feedback during the run None A development-suite score for every patch Coverage Algorithms + six research areas 13 CS domains Headline metrics Mean score Pass rate, mean score, FCI Building tasks by subtraction Every task starts from a published paper and the code its authors released. We find the code that implements the paper’s contribution, delete it, and leave everything it depends on untouched. The deleted code becomes the human reference: a private oracle that already runs in this repository on these workloads. No re-implementation, no rubric, no guessing what the authors meant. A concrete example: SVG-EAR, an ECCV 2026 sparse-attention method for video diffusion. From the Sparse VideoGen repo we remove the error-aware attention class and three routines (cluster averaging, choosing which cluster pairs to compute exactly, and estimating the rest). The agent gets the repo with those functions still declared and called, and may only edit the files that held them. To pass, its latency must be at most 0.96× the reference’s, with PSNR within 0.25 dB, SSIM within 0.01 and LPIPS within 0.005, on every held-out clip. Pass thresholds come from the reference’s own measurements. The judge scores every submission on a development suite, but the final submission is graded on a final suite that adds held-out instances (different seeds, queries or input graphs) the agent never sees. The 48 public tasks, grouped by domain: from databases, MLSys and HPC to cryptography, security and robotics. The agent works like a researcher, not a test-taker Inside a run, the agent holds the repository and the judge holds everything that decides the outcome: the evaluator, the hidden suite and the reference. They run in separate sandboxes connected only by a driver, and the agent’s sandbox has no network access beyond it, so it cannot simply download the original code. On GPU tasks the agent can spin up its own development GPUs, while scoring happens on separate verifier hardware. Five hours of wall-clock time per run. Submit a patch whenever you like. Each one returns a development score plus a sanitized message counting how many dev workloads meet each threshold—never the reference’s score or the evaluator’s raw output. Pick your own final answer. At the end the agent names one patch as final, and only that patch is graded on the hidden suite. We don’t rescue it by picking its best dev submission: deciding what to ship is part of research. The judge. The agent reaches only the driver; the evaluator, the held-out suite and the reference stay on the judge side. A higher score is not a pass A run passes only when its final patch beats the human reference on every metric and every held-out workload. That is deliberately strict. We want results the paper’s authors would accept as better, not a speedup bought with a quality regression or a fit to a few workloads. This matters more than we expected. Most runs whose combined final score beats the reference still miss a threshold somewhere. On KV Compaction, for example, Claude Opus 5.5 posts the top score and sits above the human reference, yet falls short of the reference’s accuracy on 2 of 24 articles, so the run fails. A single averaged score would have called that a win. Results: 28 of 48 at the top, and a three-way tie on FCI The leaderboard now covers 20 models, each paired with its own harness (Claude Code, Codex CLI and others) and run once on every task. The headline numbers: Claude Opus 5.5 in Claude Code passes 28 of 48 tasks (58%). Gemini 4 Carbon and Gemini 4 Argon follow at 26, Claude Sonnet 5.5 at 24, and GPT-6 Astra at 22. Below the top eight, no model passes more than 11. A third of the benchmark is out of reach. In the paper’s 12-agent evaluation, no run passed 16 of the 48 tasks. The harness is part of what we measure. We name agents by model, but the same model in a different harness is a different agent. Tasks where each model beats the human reference on every metric and every hidden workload, out of 48. FCI: putting agents and tasks on one scale Pass rate treats an easy task like a hard one and saturates once a model passes everything. So we also fit the FrontierCS Capabilities Index (FCI), an item-response model forked from Epoch AI’s Epoch Capabilities Index. Instead of raw scores, it learns from two things in every run: which of the task’s metrics it beat, and how far its final score landed from the reference’s. The same fit gives each task a FrontierCS Difficulty Index (FDI): the FCI at which an agent passes it half the time. On FCI, the top of the board is a dead heat: Claude Opus 5.5 at 51.3, Gemini 4 Carbon at 51.0 and Claude Sonnet 5.5 at 50.7, with GPT-6 Astra and Gemini 4 Argon close behind at 48.6 and 48.4. Kimi K2.7 anchors the scale, and ten points equal one logit, so a three-way gap of 0.6 points is far inside the bootstrap intervals. The more interesting finding is on the task side: the median task sits at roughly the strongest agent’s FCI. The benchmark spans a wider difficulty range than the agents do, so there is real headroom above today’s best. FrontierCS Capabilities Index (FCI) on the 48 public tasks. What a pass costs Pass rate alone hides a 400× spread in cost. The top cluster (Claude Opus 5.5, both Gemini 4 models, Claude Sonnet 5.5 and GPT-6 Astra) all spend roughly $17–40 per run, with Gemini 4 Carbon the most expensive of the group for two fewer passes than Opus. The value pick is GPT-6.1: Terra and Sol pass about 40% of tasks for around $3 a run, roughly a sixth of the frontier’s cost. At the far left, DeepSeek V4.1 Flash costs about a dime per run and still passes about one task in eight. Pass rate against mean cost per run (US$, log scale). Costs are estimates; Gemini 4 Carbon is priced at Gemini 4 Argon's rates. The leader depends on your budget In the paper’s cost analysis, capping spending per run changes the ranking. A run still going when the budget runs out counts as having no final submission. At the smallest budgets, DeepSeek V4.1 Flash leads (with the caveat that its costs are lower bounds and depend on token pricing); at the largest, Claude Opus 5.5 does. What the agents actually invented Pass rates tell you how often. Reading the patches tells you what. Three runs stood out, each with its own deep-dive post. Two checksums shrink private lookups by 27%. In QuarterPIR, a private information retrieval scheme, the reference server returns a parity value for every database group, though the client needs only one. Muse Wonder 1.0 replaced them with two checksums, the same construction RAID-6 uses to rebuild two failed disks. Because the client already knows the only two groups where its values can differ, two checksums suffice. Bytes per lookup fell from 1,760 to 1,280, with privacy unchanged. Read the deep dive → QuarterPIR: bytes per lookup at 67 million entries. Hollow points fail the task. Two faster clocks for a hardware priority queue. BBQ is an FPGA priority queue for packet scheduling. Gemini 4 Argon kept the memory layout but resolved the read-after-write check while the read was still in flight. Claude Opus 5.5 moved every counter into registers and updated a whole tree level per cycle—up to 1.84× the reference’s operations per second, versus 1.56× for Argon at the same memory. The catch: Opus’s circuit is among the largest, and the final score doesn’t charge for size. Read the deep dive → BBQ: operations per second as a multiple of the human reference, by tree size. Green: Gemini 4 Argon. Orange: Claude Opus 5.5. The baseline no model could beat. On SVG-EAR, nobody passed. GPT-6 Astra came closest by measuring attention error rather than predicting it, picking the smallest per-head budget under an error bound, and fixing a centroid-estimate bias the paper leaves in. It was faster on every clip and closer to full attention on average—and still failed image quality on two clips, clearing 43 of 48 checks. Speed was never the bottleneck on this task; quality bands were. Read the deep dive → SVG-EAR: mean PSNR against mean time per clip on the twelve hidden clips. No run passes. GPT-6 Astra's 48 checks on SVG-EAR: 43 passed, with misses on two Wan 2.1 clips. What our metrics still miss The case studies are also a confession. The pass/fail bit can’t tell a 27% byte reduction from a marginal one; on QuarterPIR, GPT-6.1 Sol actually scores slightly higher than Muse Wonder with a much smaller saving. The final score on BBQ rewards speed and ignores circuit area. On SVG-EAR, a run that is better on average fails on two clips. We think benchmarks of this kind need to report side costs like these next to the pass, and that FCI with honest intervals is a better summary than any single averaged number. Run it, submit to it, help us extend it Run it yourself. All 48 tasks, evaluators and the judge are public at github.com/FrontierCS/FrontierCS-2. It installs into your own AWS account; GPU tasks also use Modal, and any OpenAI-compatible model endpoint works. Know the cost. A full 48-task evaluation of Claude Opus 5.5 runs about $1,000 in API fees, $300 in GPU time and $100 in CPU. Get on the leaderboard. Email per-task scores to both [email protected] and [email protected]. Inspect every run. Full trajectories are on Hugging Face and the Kaggle benchmark page. A private set is coming. Beyond the public 48, we hold more than 100 private tasks, to be announced later, so the benchmark stays ahead of contamination. Acknowledgments Special thanks to Modal, our lead sponsor, for the compute behind FrontierCS 2, and to Kaggle, the Laude Institute’s Slingshot program, Scale AI, Handshake and Snorkel AI for their support. Thanks to Epoch AI for the ECI and its released code, and to the authors of all 48 source papers whose open code made these tasks possible. Citation @misc{mang2026frontiercs2benchmarkcomputer, title={FrontierCS 2: A Benchmark for Computer Science R\&D}, author={Qiuyang Mang and Wenhao Chai and Runyuan He and Dongruixuan Li and Zihan Zheng and Yujun He and Xuanyi Zhou and Hao Wang and Siddhant Ray and Bo Peng and Ruyi Ji and Shuo Yang and Haocheng Xi and Boru Chen and Xinyang David Han and Melissa Pan and Mayank Mishra and Boxi Yu and Sijia Liu and Kerem Akillioglu and Yi Pan and Zirui Wang and Mert Cemri and Diogo Antunes and Yichuan Wang and Aiwei Ivy Zhang and Zhenyang Chen and Qizheng Zhang and Kaiyuan Liu and Wenyuan Huang and Sherry Ruan and Shu Liu and Dacheng Li and Zerui Cheng and Zeyu Shen and Shang Zhou and Hanfei Chen and Yuzhong Zhang and Bohan Lyu and Qu Ao and Han Zheng and Chonghe Jiang and Jingzhuo Hu and Xiaokun Chen and Kunjun Li and Zhiqing Zhong and Haoye Tian and Tong Zhao and Yunzhong He and Hanchen Li and Ofir Press and Jiantao Jiao and Kunle Olukotun and Karthik R. Narasimhan and Jingbo Shang and Koushik Sen and Matei Zaharia and Alex Dimakis and Ion Stoica and Joseph E. Gonzalez and Alvin Cheung}, year={2026}, eprint={2610.29932}, archivePrefix={arXiv}, primaryClass={cs.LG}, url={https://arxiv.org/abs/2610.29932}, }
Tech stocks may be back up (to some degree), but profits aren’t