How Much of a Batch Does It Take to Change the Gradient?

This is the first post in my personal study of how LLMs work. If you read this blog or have spoken with me, you probably know how dissatisfied I am with how little we understand about LLMs and their training. Some of this knowledge may exist inside industrial labs, but little of it arrives in the academic world. So, I decided to investigate each part of a pre-training pipeline myself, with the help of coding agents. Follow me in this journey!

At update 2,507 of a language model training run, the gradient suddenly got larger. Looking at the web text in that batch, I found a long stretch of DNA. An unusual thing to read, perhaps, but the batch contained half a million tokens. How much difference could one passage make?

TL;DR: Replacing 1% of a batch with a chosen pattern of repeated common words made the gradient norm about 15–334 times larger, depending on the model, while the loss didn’t increase much and may even have decreased.

Code: The repository contains the code, the exact token patterns, and all 1,200 batch comparisons across four models, including the gradient RMS and mean token loss for each original and modified batch.

1. What Was a DNA Sequence Doing to My Gradient?

I was training a Transformer-based language model, modded-nanogpt, to predict the next token in text collected from the web. The DNA came from a patent application. It opens with the title and inventors. Farther down, the last bibliography entry runs straight into a sequence listing. Here is what that transition looks like in the training text.

Patent application title: BACTERIAL VACCINE

Arthur Keith Turner (Cambridge, GB)

Judith Greenwood (Cambridge, GB)

[…]

35. Wolf M. K. et al (1997) Ferns Microbiol Lett 148(1): 35-42.

411703DNAEscherichia coligene(114)..(629)cooA 1atcgatagtg […]

[…]

180gtaaagtctg gctatcaccg gtggtggact gcttcgatgg aaaagttgtg agctggtctc

To the model this was another prediction problem. In a sentence like The capital of France is Paris, it has to assign a probability to the next token after is. In the passage above, the same tokenizer turns the letters, numbers, and spaces into tokens, and the model makes a prediction at each position. If it assigns probability {p} to the observed token, it incurs a loss of {-\log p}. The training loss averages those numbers over the batch. Its gradient tells us how that average changes when we move the parameters.

What puzzled me was the arithmetic. One update used 512 windows of text with 1,024 predictions apiece. The DNA passage touched 26 windows. Even if every prediction in those windows cost an extra unit of loss, the batch average would rise by only {26/512}, about 0.05. Yet the gradient spike was visible. Was the passage responsible?

So, to see what the DNA contributed, I trained modded-nanogpt from scratch on FineWeb up to update 2,506. Then, I ran the next update twice, starting from the same model and optimizer state. The first time I used the original batch. The second time I took the 26 windows containing the DNA passage and replaced them with 26 ordinary windows copied from elsewhere in that batch. This changes about five percent of the batch, including the text surrounding the DNA. For the next nineteen updates both runs saw the same data.

The upper panel shows full-batch gradient RMS before each update on a logarithmic scale. At update 2,507 the DNA batch (orange) spikes above its replacement (green). The lower panel shows training loss.

The ratio of gradient norms at the branch point was 2.80, with only 5% of the batch replaced. If somebody had told me that beforehand, I would have had a hard time believing it.

Note that the DNA spike is not really noise. The model was learning to predict text from the web, and the web contains DNA sequences. What surprised me was how much weight this one passage effectively carried in a single update. The {2.80\times} ratio tells me how much the gradient norm changed when I replaced those windows. It doesn’t tell me that the model should have ignored them.

2. What Had People Already Measured?

After finding the disruptive DNA sequence, I wanted to know whether anyone had traced a spike back to the text in a batch. The closest experiment I found was in 2 OLMo 2 Furious (Section 3.1, Figure 3). The authors inspected batches where the gradient norm had spiked and found long stretches of repeated token patterns. Masking those sequences in the loss eliminated many of the spikes. Also, a pattern that produced a spike on a larger model could pass through a smaller model without one.

The Mellum2 Technical Report describes a related observation in the training loss. The team traced two early loss spikes to stretches of text with very few distinct tokens. One example was a single token repeated across an entire context. Filtering samples with very low token diversity helped.

What happens if you keep the text and change the checkpoint? The PaLM authors tried exactly that (Section 5.1). They took batches surrounding a loss spike and replayed them from an earlier checkpoint. The spike did not recur. Taken together, these experiments suggest that whether a passage causes trouble depends on the model reading it and on the state of training when it arrives.

There is also a question about the step between a large gradient and a large loss. In Spike No More, Takase and colleagues start from “the assumption that the loss spike is caused by the sudden growth of the gradient norm.” This matches my observations: I was using a new optimizer and observed a loss spike. Only later I realized that the problem was the update before. They study how much a gradient can grow as it passes through the layers of a Transformer. Changing the relative scales of the residual branches and the shortcut helped prevent loss spikes in their runs.

What I couldn’t find was a measurement that answered my quantitative question. If I hold the weights fixed, choose a sequence on one batch, and use it to replace just one percent of another batch, how much can I change the full-batch gradient?

3. How Large a Gradient Could I Make?

DNA seemed like a reasonable suspect because it looks so different from the English around it. But what part of that observation mattered? Could I make an even larger gradient using only words the model had seen countless times? I needed a way to ask the question repeatedly, with control over both the words and how much space they occupied.

Fix the model parameters {\boldsymbol{\theta}\in\mathbb{R}^d}. Split a batch {B} into {m} windows with equal numbers of scored tokens, and let {\ell_i} be the mean next-token loss in window {i}. The gradient the optimizer receives, up to the choice of sum or average, is

\displaystyle \boldsymbol{g}(B) = \frac{1}{m}\sum_{i=1}^m \nabla \ell_i(\boldsymbol{\theta}).

I measure its root mean square across parameters, {\left\|{\boldsymbol{g}(B)}\right\|_2/\sqrt d}. For a modified batch {B'} and its original {B}, the factor {\sqrt d} cancels, so my score is simply {\left\|{\boldsymbol{g}(B')}\right\|_2/\left\|{\boldsymbol{g}(B)}\right\|_2}.

Notice where the sum sits. Two windows can each have a large gradient and cancel one another almost exactly. Conversely, if I put the same sequence in ten complete windows with identical context, its gradient occurs ten times in the sum. This explains why repetition across windows is convenient. It leaves open the question: Which sequence should I repeat inside each window?

For the next experiment, I decided to use models where the checkpoints and training data are available, so that everything is reproducible. I took a checkpoint and original training batches for each of three Pythia models and for OLMo 1B. On one batch I searched over short periodic token patterns, scoring candidates at a replacement size of five percent. Then, I froze the winning pattern and tried it on ten other batches, varying the fraction replaced. One percent here means roughly one in a hundred scored token positions, packed into consecutive windows. All model weights stay fixed.

For a sense of scale, one Pythia batch contains {1{,}024\times2{,}048} predictions. A budget of one percent buys me about 21,000 tokens. I fill ten whole windows and part of one more, restarting the pattern in each window. I put an end-of-sequence token before and after the inserted text; these markers are outside the one-percent content budget. Even the original tokens left at the end of that last window now have a different context, so I recompute their losses too.

I wanted an efficient way to find a large gradient; a guarantee that I had found the largest possible one was unnecessary. I started with single-token patterns, ranked them by the gradient norm of the whole modified batch, and ran four rounds of mutations, changing the length and tokens of patterns drawn from the best eight so far. The search is cheap because I can reuse the gradient of the untouched windows and compute the gradient of each repeated full window just once per candidate. Each checkpoint gets its own search. Testing the winner on fresh batches matters here. A sequence could win because its gradient happened to point in a favorable direction on the batch I used to find it. On each new batch it has to earn its score again, against that batch’s own clean gradient.

4. The Word That Won

For Pythia 1B, restricting the search to common words gave me season than season than and so on. At one percent, the gradient was 223 times as large on average. For OLMo 1B the search found an even shorter pattern, with with with. The mean ratio was 334. Across the ten held-out batches, the ratios ranged from {214\times} to {228\times} for Pythia 1B and from {330\times} to {340\times} for OLMo 1B. On the first OLMo test batch, for example, the mean token loss moved from 2.478 to 2.521. Would you have guessed a 332-fold gradient spike from those two losses?

Here, I summarize all the experiments. Each entry below is the full-batch gradient norm with the repeated common words divided by the norm on the original batch, averaged over ten held-out batches. The first column gives the percentage of scored token positions used for the pattern.

Batch replaced Pythia 14M Pythia 1B Pythia 6.9B OLMo 1B
1% {14.7\times} {223.1\times} {75.0\times} {334.4\times}
2% {29.3\times} {448.1\times} {151.6\times} {664.9\times}
3% {43.9\times} {679.1\times} {230.7\times} {998.3\times}
4% {58.5\times} {913.5\times} {307.4\times} {1{,}329.8\times}
5% {73.1\times} {1{,}137.5\times} {382.3\times} {1{,}662.2\times}
6% {87.8\times} {1{,}362.1\times} {458.6\times} {1{,}994.6\times}
7% {102.4\times} {1{,}592.8\times} {537.7\times} {2{,}326.1\times}
8% {117.0\times} {1{,}827.1\times} {614.7\times} {2{,}659.5\times}
9% {131.6\times} {2{,}052.0\times} {689.6\times} {2{,}990.4\times}
10% {146.2\times} {2{,}276.3\times} {765.6\times} {3{,}324.3\times}

A whole window of with might sound artificial. However, the Mellum2 example in Section 2 says that we should take this result seriously. That said, I also investigate less artificial examples.

5. What If I Use Readable English Text?

I got to pick the words and decide exactly how much of the batch to fill with them. How much of the effect survives if every passage has to be readable? To try this, I selected distinct English passages from the corpus and allowed changes in capitalization.

Here, I had to decide which passages to put together. Picking the passages with the largest individual norms could easily go wrong. My second passage might undo most of what the first one did. So, I used a short vector summary of each passage’s gradient to estimate which passage would add the most to the batch gradient norm at each step, then tried swapping passages. I scored the twelve most promising sets using the full batch gradient and tested capitalization changes on the best set (English search code). Again, this was a quick heuristic search, just to see what I could easily obtain.

For comparison, here is what happens at five percent when I require readable English passages.

Model Repeated common words Selected English
Pythia 14M {73\times} {1.59\times}
Pythia 1B {1{,}138\times} {2.02\times}
Pythia 6.9B {382\times} {1.52\times}
OLMo 1B {1{,}662\times} {3.33\times}

The effect is much smaller than before. Yet increasing the gradient norm by a factor of two or three by changing so little of the batch still surprised me.

6. Where Does the {223\times} Come From?

Now, look again at Pythia 1B. Filling one percent of the batch with season than season than made the gradient norm 223 times as large. Why such a big effect with such a small modification? Each window gradient is already an average over 2,048 predictions. Were the individual gradients large, or did they happen to point in the same direction? I kept the checkpoint fixed and measured the gradient of each prediction separately. For comparison I did the same for the first ordinary window in each of the ten test batches.

Both effects showed up. The mean length of an individual gradient in the repeated window was about 41 times the median of the ten control means. Now imagine laying those gradient vectors end to end. How far do you get compared with the total length you walked? In the repeated window the answer was 99.8%. In the median control it was just 3.1%. The two effects multiply when comparing windows. Against the first control, for example, the gradients were about 49 times as large and preserved about 27 times as much of their length when averaged. That one window had a gradient about 1,339 times as large as its control. This explain the large effect of a relatively small sequence of tokens.

Each position uses its original context. The repeated window is compared with ten windows of ordinary text at the same Pythia 1B checkpoint.

There also was a candidate for an easy explanation. After all those repetitions I ask the model to predict the end-of-sequence token. Perhaps that last surprise accounts for the spike? Its loss was indeed large, 6.54 nats, but its contribution along the window gradient was just 0.015%. Looking across positions, the last half of the window accounts for about 93% of the total signed contribution.

I now know that large gradients reinforce one another in this window. What makes the individual predictions so sensitive as the context grows is still open.

Now consider an easier question. At two percent replacement the batch ratio was 448, almost exactly twice 223. Why should doubling the number of copies nearly double the norm?

Let’s do the arithmetic for whole windows. Suppose the batch contains {m} windows and I replace {k} of them, so the fraction replaced is {\alpha=k/m}. Call the gradient of one replacement window {\boldsymbol{g}_{\rm rep}}. Every copy starts with the same context and sees the same model weights, so every copy contributes the same vector. Together they contribute {k\boldsymbol{g}_{\rm rep}/m=\alpha\boldsymbol{g}_{\rm rep}} to the batch average. Of course, I also took something out. If the {k} windows I removed had average gradient {\boldsymbol{g}_{\rm old}}, their contribution was {\alpha\boldsymbol{g}_{\rm old}}. Thus

\displaystyle \boldsymbol{g}(B') = \underbrace{\boldsymbol{g}(B)}_{\text{original batch}} -\underbrace{\alpha\boldsymbol{g}_{\rm old}}_{\text{windows removed}} +\underbrace{\alpha\boldsymbol{g}_{\rm rep}}_{\text{copies added}}\,.

Now imagine that even at one percent the last term is much larger in norm than the gradient left over from the original windows. The new batch gradient then points almost along {\boldsymbol{g}_{\rm rep}} and has length close to {\alpha\left\|{\boldsymbol{g}_{\rm rep}}\right\|_2}. Going from one percent to two percent doubles the last term. If it still dominates, the new norm should nearly double too. I checked that condition on the ten modified batches at one percent. In every batch, the contribution from all the retained windows together had less than 0.5% of the length of the contribution from the modified windows, including the partially replaced one. That gives a simple way to understand the jump from 223 to 448.

7. And What Would the Optimizer Do?

The above investigation stops at the gradient spike. What happens next is very optimizer specific. If the optimizer is not smart, a gradient spike can become a loss spike on the next batch. In fact, if that step moves the parameters somewhere worse for ordinary text, the loss on subsequent batches can jump. If the loss spikes for this reason, it is already too late: the bad update happened before! This is the sequence of events Takase and colleagues investigated (Section 2).

For gradient descent with a fixed learning rate {\eta}, clearly we have {\left\|{\boldsymbol{\theta}_{t+1}-\boldsymbol{\theta}_t}\right\|_2=\eta\left\|{\boldsymbol{g}_t}\right\|_2}. In that case a 334-fold gradient ratio would give a 334-fold ratio of step lengths. Quite a wild step into the unknown.

You might think that I could just clip the gradient. But if I set the threshold above the spike norm, clipping does nothing. On the other hand, if the norm exceeds the threshold, clipping shortens the gradient but preserves its direction, which might be a problem as well. In fact, imagine that on a typical batch the model would move in the direction of steepest improvement on held-out text. If a repetitive passage rotates the update nearly perpendicular to the direction of steepest improvement on that text, we can spend a full step making little progress.

Different problems arise in optimizers with exponential averaging terms. For example, with an optimizer such as Adam, the gradient also enters running averages of the gradient and squared gradient. A large entry in the latter can shrink subsequent updates in that coordinate even after the unusual batch is gone.

That said, there is a nice correlation between the fact that the most successful optimizers we have, AdamW and Muon, have bounded updates in some norm. So, this might be a general principle we might want to use in any future optimizer.

And this is exactly my take away from this analysis: no matter how clean is your data, you might receive a massive gradient and your optimizer must always be prepared for it.

8. Post Scriptum

Before concluding this investigation, let me also describe an interesting side discovery: FineWeb has chunks of garbled text. Kind of suprising given that FineWeb is considered a very good dataset.

While looking for other gradient spikes on the FineWeb batches, I came across garbled text in the FineWeb dataset. In the training data, ordinary prose gives way to strings of garbled characters. Many tokens of pure garbage. Maybe this was a problem with PDF or font extraction; I’m not sure. Each one of them gave a gradient spike for the fixed checkpoint I used.

The source record gives the per-window measurements and their exact locations in FineWeb. There might be more, I didn’t investigate much this issue.

Leave a Reply