TL;DR
Floats round, and the order of a sum changes the result, so the same weights can give different numbers. On a laptop, 8 answers scored alone and in a batch of 32 differed by 0.028 nats per token; 7 left GSPO’s window. A checkpoint stored in fp16 put 13.04% of the weights on bf16 rounding ties, so one tiny update flipped 6.52% of all the weights, half the tied ones. On 8×H100, the first GSPO update was off by a median 4.9e-3 in log-ratio, 16× GSPO’s clip, where one GPU gave exactly zero. Two evaluations of the same weights agreed on only 198 of 500 greedy answers, yet avg@8 moved by 0.33 points.
What you’ll learn
- How bf16 stores a number, how far apart its neighbouring values are, and why a small update can round away.
- Why adding numbers in a different order changes the result, and what batch invariance means.
- GSPO’s sequence ratio and the k3 KL estimator, and the two free checks they give: ratio exactly 1 and KL exactly 0.
- Four cases in this project where the same weights gave different numbers, and the cause of each.
- What reproducing a run takes: deterministic mode, seeds, a pinned environment and checksums.
Precision, from scratch
How a float stores a number
A floating-point number stores a sign, an exponent and a fraction:
where \(s\) is the sign bit, \(f\) the fraction stored as an \(m\)-bit whole number, and \(e\) the exponent.
In words: a float is a number between 1 and 2, written with \(m\) binary digits after the point, times a power of two.
| Format | Total bits | Exponent bits | Fraction bits \(m\) |
|---|---|---|---|
| fp32 | 32 | 8 | 23 |
| fp16 | 16 | 5 | 10 |
| bf16 | 16 | 8 | 7 |
bf16 keeps fp32’s 8 exponent bits, so it covers the same range of magnitudes, but with 7 fraction bits instead of 23. fp16 makes the opposite trade: 3 more fraction bits than bf16, and a far smaller range.
The gap between neighbouring values
Between two powers of two, a format with \(m\) fraction bits has \(2^m\) evenly spaced values. The gap between neighbours is
where \(e\) is the exponent of \(x\) and \(m\) the number of fraction bits.
In words: the gap is a fixed fraction, \(2^{-m}\), of the power of two just below the number.
For bf16 between 1 and 2, the gap is \(2^{-7} = 0.0078125\), so the next bf16 value after 1 is 1.0078125 (illustrative; checked in PyTorch). For fp32 it is \(2^{-23} \approx 1.19 \times 10^{-7}\). Arithmetic rounds each result to the nearest representable value, and an exact tie goes to the neighbour whose last bit is even:
where \(\operatorname{fl}(x)\) is \(x\) rounded to the format, \(\delta\) the relative rounding error, and \(u\) the unit roundoff.
In words: with its implicit leading 1, bf16 has 8 bits of precision, so one rounding moves a value by at most \(2^{-8}\) of itself.
That is about 0.39% for bf16; for fp32 the same bound is \(2^{-24}\), about \(6 \times 10^{-8}\) (my arithmetic).
Why a small update rounds away
Take a weight \(w\) that is a bf16 value, and add an update \(\Delta w\). The sum rounds back to \(w\) when the update is under half a gap:
where \(\Delta(w)\) is the gap from equation (2) at \(w\).
In words: in bf16, a weight moves only when its update reaches halfway to the next representable value.
An illustrative case: a weight of 0.01 lies between \(2^{-7}\) and \(2^{-6}\), where the bf16 gap is \(2^{-14} \approx 6.1 \times 10^{-5}\). Any update below about \(3 \times 10^{-5}\) leaves it unchanged.
Adam’s first step moves each weight by about the learning rate. On the laptop, 91.3% of weights moved by the learning rate of 1e-6, to within 1%. RL learning rates in this project were 1e-7 to 1e-6, so in pure bf16 most first updates would vanish.
That is why mixed precision keeps an fp32 master copy of every weight, the recipe of Micikevicius et al. (2018). The update accumulates in fp32, and the bf16 copy changes only when the fp32 value crosses a rounding boundary. On the laptop, one update at 1e-6 changed about 2% of the bf16 weights that were not on a tie, and almost none at 1e-7.
Why the order of a sum matters
Floating-point addition is not associative: each step rounds, so the grouping changes the result.
where \(a\), \(b\) and \(c\) are floats and \(\operatorname{fl}\) rounds as in equation (3).
In words: adding the same three numbers in two groupings can give two different answers.
An illustrative bf16 case is \(a = 1\) and \(b = c = 2^{-8}\). Left to right, \(1 + 2^{-8}\) lies exactly halfway between 1 and 1.0078125, and the tie goes to 1; adding \(2^{-8}\) again gives 1 again. The other way round, \(2^{-8} + 2^{-8} = 2^{-7}\) exactly, and \(1 + 2^{-7} = 1.0078125\) is a bf16 value.
import torch
bf16 = torch.bfloat16
a, b = torch.tensor(1.0, dtype=bf16), torch.tensor(2**-8, dtype=bf16)
print((a + b) + b, a + (b + b))
# tensor(1., dtype=torch.bfloat16) tensor(1.0078, dtype=torch.bfloat16)
A GPU adds long lists: each output of our attention projections sums 2,048 products, one per hidden dimension. A matrix-multiply kernel picks how to split each sum from the shape of the batch it is handed. So the same row can come out with different low bits in a different batch. Thinking Machines show the effect with \((0.1 + 10^{20}) - 10^{20} = 0\) but \(0.1 + (10^{20} - 10^{20}) = 0.1\).
What stays in fp32
In the Megatron runs:
- matrix multiplications run in bf16 (
--bf16); - gradients are accumulated and summed across GPUs in fp32, which Megatron sets by default for bf16 runs (only
--grad-reduce-in-bf16turns it off); - the optimizer keeps fp32 master weights and fp32 Adam moments;
- the router runs in fp32 (
--moe-router-dtype fp32), with limits covered below.
On the laptop, after the second bug below, GSPO’s log-probabilities were computed in fp32 as well.
The number that must be exactly 1
GSPO’s sequence ratio
GSPO (Group Sequence Policy Optimization) is the RL method in this project (Part 9). It compares two models on the same answer, token by token:
where \(x\) is the prompt, \(y_{i,t}\) the \(t\)-th token of answer \(y_i\), \(\pi_\theta\) the model being trained, and \(\pi_{\theta_{\text{old}}}\) the model that wrote the answers.
In words: the token log-ratio says how much more or less likely the trained model finds each token than the sampling model did.
GSPO averages these over the answer and exponentiates:
where \(\lvert y_i \rvert\) is the answer’s length in tokens.
In words: the sequence ratio is the geometric mean of the token ratios, one number per answer.
GSPO then trusts an answer only while its ratio stays inside a narrow window:
where \(G\) is the number of answers and \(A_i\) answer \(i\)’s advantage, its reward relative to its group. \(\epsilon_{\text{low}}\) and \(\epsilon_{\text{high}}\) are the clip bounds, \(3 \times 10^{-4}\) and \(4 \times 10^{-4}\) in the GSPO paper.
In words: an answer stops pushing the model once its ratio leaves the window from 0.9997 to 1.0004.
Before the first update, the two models are the same weights, so every \(\ell_{i,t}\) is 0 and every \(s_i\) is exactly 1. Any deviation then measures arithmetic, not learning. The window is narrow: since \(\log s_i\) is a mean over tokens, a steady difference of \(4 \times 10^{-4}\) nats per token takes an answer outside it.
The KL estimator we log
GSPO also pulls the model toward a frozen reference copy, the SFT model, with a KL penalty. We estimate the KL divergence per token with Schulman’s “k3” estimator:
where \(\pi_{\text{ref}}\) is the reference model and \(r\) the per-token probability ratio; the estimate is averaged over each answer’s tokens, then over answers.
In words: k3 is zero on a token where the two models agree, positive everywhere else, and never negative.
Our laptop trainer and Megatron’s RL loss both use exactly this form. At step 0 the policy and the reference are the same file, so \(r = 1\) and \(\hat{k}_3 = 0\) exactly: the second free check. k3 is also a tail statistic: on one rollout’s trained tokens, the top 1% held 77% of its mean in fp32. So I report its median and 99th percentile too.
Derivation
Why k3 estimates the KL divergence, with tokens drawn from \(\pi_\theta\):
where the sums run over the vocabulary at one position and \(\mathrm{KL}(\pi_\theta \Vert \pi_{\text{ref}})\) is the Kullback–Leibler divergence of the policy from the reference.
In words: the \(r - 1\) part averages to zero and the \(-\log r\) part to the KL, and \(\log r \le r - 1\) keeps every term non-negative.
Case 1: an answer’s score depended on its batch
Phase 0 ran on a laptop RTX 3060 with 6 GB, training MiniMind, a 64M-parameter dense model. The first GSPO run from MiniMind’s trained weights broke both checks. The KL to the reference averaged 0.94 over the first updates, and about 50% of tokens were clipped, with ratios from 0.81 to 1.12.
A diagnostic scored one batch of answers five ways with identical weights, changing one thing at a time. Only one comparison differed: a group of 8 answers scored as its own batch, against the same 8 inside the full batch of 32. The difference was 0.028 nats per token on average (worst token 0.312), and 7 of the 8 answers left GSPO’s window.
The cause was batch composition. MiniMind’s attention uses a fused kernel when no row in the batch is padded, and a manual path otherwise. My trainer scored the old and reference log-probs on the full, padded batch, and the new ones on smaller, often unpadded mini-batches. A later audit added a caveat: the route was asserted, not isolated, and kernels that depend on batch size also play a part.
The fix: score old, new and reference log-probs on exactly the same mini-batches, with every old score taken before any update. After it, the first mini-batch’s ratio was exactly 1 and the KL exactly 0 at every step with an update. In fp32, the same “alone versus inside 32” test still differed, by 2.47e-6 nats per token (worst 4.58e-5). Far smaller, but not zero, so the identical-batch rule stayed.
Case 2: the fp16 → bf16 trap
One number was still wrong. After a single update at learning rate 1e-6, the KL on the next mini-batch was 6.4 per token.
The learning-rate scaling test
The test that settled it: one update at two learning rates, from identical weights. A real effect of learning scales with the learning rate \(\eta\), and rounding does not. For a small step,
where \(\Delta \log p\) is the change in a token’s log-probability and \(\eta\) the learning rate.
In words: to first order, ten times the step moves log-probabilities ten times as far, and the quadratic KL a hundred times.
| One update from the same weights | LR 1e-6 | LR 1e-7 | Ratio |
|---|---|---|---|
| Median change in log-prob, trained tokens, fp32 forward | 7.15e-3 | 6.91e-4 | 10.3× |
| Median change in log-prob, trained tokens, bf16 forward | 4.33e-2 | 4.10e-2 | ≈1× |
| Weights whose bf16 value changed | 8.54% | 6.52% |
The fp32 change scaled with the learning rate; the bf16 change, the one training actually used, did not. In bf16 the change after one update was 6× the true change at 1e-6 and 60× at 1e-7: rounding, not learning. Run 2b later tested equation (11) on fixed inputs. After one update, 3× and 10× the rate gave 3.0× and 9.96× the log-prob change, and 9.0× and 100× the KL.
Why: rounding ties
MiniMind saved its checkpoint in fp16, with 10 fraction bits, while training computed in bf16, with 7. Rounding an fp16 value to bf16 drops its 3 extra bits. If they are exactly 100 in binary, the value sits exactly halfway between two bf16 neighbours: a tie. For evenly spread bits that happens 1 time in 8, or 12.5%.
Round-half-to-even sends each tie to one neighbour. The smallest update breaks the tie, and about half the tied weights then jump a full bf16 step, whatever the learning rate.
w = torch.tensor(1 + 2**-8, dtype=torch.float16).float() # an fp16 weight, 1.00390625
print(hex(w.view(torch.int32).item() & 0xFFFF)) # 0x8000: exactly on a bf16 tie
for dw in (1e-7, -1e-7, 1e-6):
print(dw, w.to(bf16).item(), (w + dw).to(bf16).item())
# 1e-07 1.0 1.0078125 <- a jump of 2**-7 from an update of 1e-7
# -1e-07 1.0 1.0
# 1e-06 1.0 1.0078125 <- the same jump from ten times the update
On MiniMind, 13.04% of the 63,912,192 parameters sat on bf16 ties, and one update at 1e-7 changed 6.52% of the bf16 values. I wrote the 12.5% and 6.25% explanation after that measurement, so it is an explanation, not a prediction.
The fix was to compute old, new and reference log-probs in fp32. Both checks held exactly again, and on step 1’s second mini-batch the KL fell from 6.42 to 0.027. For any later checkpoint conversion, the test is simple: count the weights whose lower 16 fp32 bits are 0x8000.
The router in fp32
In an MoE, the router makes a discrete choice: 8 of 64 experts per token. A tiny numerical difference can flip a choice, and the token then takes a different path through the layer. The tested launch script computes the router in fp32, with --moe-router-dtype fp32.
At our Megatron commit, that flag covers the router’s logits, scores, expert bias and top-k choice. It does not cover the router’s inputs, which are bf16 hidden states.
Nor does it cover the combine. In our all-to-all path, each expert’s output is weighted inside the expert and cast back to bf16. The eight outputs are then summed by a bf16 scatter-add. Megatron switches that sum to a deterministic index_add_ only when PyTorch’s deterministic mode is on.
Microsoft AI’s RL team handles this step differently: after the all-to-all, they “compute the weighted sum locally in FP32”. Matching its precision and order between sampler and learner, they write, “eliminates discrepancies introduced by expert combination”.
Case 3: on 8 GPUs, the first update was not exactly on-policy
The one-GPU rehearsal used a shrunk version of our MoE, and its first GSPO update passed both checks: ratio exactly 1, KL exactly 0. I expected the same on 8 GPUs, where the GPUs’ answers meet in the same expert matrix multiplications, but one GPU could not test that. On the main run’s first update, before any weight change, both checks failed.
| First update, before any weight change | One GPU (rehearsal) | 8 GPUs, expert parallelism 8 |
|---|---|---|
| Median absolute log-ratio | 0 | 0.0049 |
| 90th / 99th percentile | 0 / 0 | 0.014 / 0.034 |
| Largest | 0 | 0.038 |
| Answers with a non-zero log-ratio | none | 98 of 128 |
| KL to the reference (same weights) | 0 | 0.0027 |
In ratio terms, the median answer had \(s_i = e^{\pm 0.0049}\), between 0.9951 and 1.0049 (my arithmetic). At the 99th percentile it reached 0.967 or 1.034, against a window of 0.9997 to 1.0004. The median noise was 16 times the clip. Noise alone clipped 19.5%, 13.3% and 3.9% of the first update’s answers in the three calibration runs.
What I ruled out, by reading Megatron’s code at our commit:
- Routing: quantile balancing picks experts from the scores minus a stored bias, the same way in every pass.
- Batch composition: each GPU scores its 64 answers one row at a time, in order, and training takes the same rows in the same order.
- Dropout: zero in the scripts and in the log.
What is left is a kernel-level difference between Megatron’s no-gradient log-prob pass and its training pass at expert parallelism 8. Still, 30 of the 128 answers came out exactly 1, and I do not know why those and not the others. Megatron’s principled fix is its batch-invariant mode, with batch-invariant kernels and an ordered expert-parallel combine. It needs FlashAttention 3 or 4, and the node had FlashAttention 2.7.4.
So I widened GSPO’s clip to \(2 \times 10^{-2}\) below and \(2.7 \times 10^{-2}\) above, just outside the noise. Recomputed from the logged ratios, that clip removed 0% of the first update’s answers. The trade-off is a looser trust region: each update may move the policy further than GSPO intends.
Is expert parallelism the cause? That is untested. The control run later added a one-GPU data point: a dense 1.5B model, with KL 0.0000 and no ratio alarm on its first update. But the model, its size, the GPU count and the kernels all changed together, so neither comparison isolates expert parallelism.
Batch invariance
Thinking Machines’ post “Defeating Nondeterminism in LLM Inference” separates two properties. A computation is run-to-run deterministic if the same inputs, in the same batch, give the same bits every time. It is batch-invariant if one request’s result does not depend on the other requests in its batch, or on the batch’s size. Their finding: “the forward pass in an LLM is in fact “run-to-run deterministic.””
Results still vary between calls, they write, “because our forward pass lacks “batch invariance””. Sha Li puts it concretely: “The same sequence scored in a batch of 8 and in a batch of 512 accumulates in a different order”. In the Thinking Machines test, 1,000 temperature-0 completions of one prompt gave 80 different texts; with batch-invariant kernels, all 1,000 were identical.
Our learner gets batch invariance where it matters, by construction. GSPO in Megatron trains one answer per forward pass, and every pass visits the answers in the same order. So an answer’s old, new and reference log-probs always come from identical layouts. The first-update ratio of exactly 1 is the measurement that would fail if this broke.
It does not make the kernels batch-invariant, and the sampler batches up to 128 requests together. That shows up as the sampler–learner gap: 0.0133 nats per token in the rehearsal, 0.0072 in the control run, about 0.035 in the main run. Zhoutong Fu states the limit plainly: “using BF16 in both engines does not fix differences in kernel arithmetic or reduction order”.
Case 4: greedy answers that change with the batch
The control run trained Qwen2.5-Math-1.5B with our GSPO pipeline on one H100 (Part 14). After its last update, Megatron evaluated the same update-100 weights a second time, with new samples. That gave a free measure of the evaluation’s own noise. The main metric, avg@8, samples 8 answers per problem at temperature 1 and averages their correctness:
where \(N\) is the number of problems and \(c_j\) the number of correct answers, out of 8, for problem \(j\).
In words: avg@8 is the share of all sampled answers that are right.
| MATH-500, same weights | First evaluation | Repeat | Paired comparison |
|---|---|---|---|
| avg@8 | 53.95% | 53.62% | −0.33 points (SE 0.86; sign-flip p 0.72; 95% bootstrap [−2.02, +1.38]) |
| Greedy accuracy | 68.8% | 67.0% | 9 wrong → right, 18 right → wrong (McNemar p 0.12) |
| Identical greedy texts | 198 of 500 |
The paired test found nothing between identical weights, as it should. But 302 of the 500 greedy answers changed (my arithmetic: 500 − 198). Greedy decoding takes the most likely token at each step, \(\hat{y}_t = \arg\max_v z_{t,v}\), where \(z_{t,v}\) is the logit of token \(v\). When the top two logits are closer than the batch-dependent rounding, the choice can flip, and every later token follows a different prefix.
Megatron’s dynamic batching changes each batch’s makeup between evaluations, so the bf16 arithmetic changes with it. The avg@8 score averages over 8 samples per problem, and it moved 0.33 points, against greedy accuracy’s 1.8. So I compare checkpoints with avg@8 and a paired test, and I check model conversions by log-probs, never by greedy texts.
Thinking Machines’ 80 unique texts in 1,000 identical requests and our 198 identical pairs out of 500 are different metrics. Both say the same thing: under dynamic batching, greedy output is not one fixed answer.
Determinism: what I claimed, and the correction
Same seed, same result? Not guaranteed
On the laptop, Run 2b repeated Run 2 with about 40 new metrics switched on. All 180 of 180 steps were bit-identical, and I wrote that training on this GPU was deterministic. Then a replay of Run 3 matched it for 40 steps and diverged at step 41. A second replay did the same, so three runs gave three different values of one logged number.
| Run | ratio_min at step 41 |
|---|---|
| Run 3 | 0.98361425 |
| First replay | 0.98361514 |
| Second replay | 0.98361361 |
The difference arose inside step 40’s last update. At step 41 the KL differed at the 7th significant digit, ratio_min at the 6th and the loss at the 5th. PyTorch’s deterministic mode, torch.use_deterministic_algorithms(True) with CUBLAS_WORKSPACE_CONFIG=:4096:8, made two runs identical over 45 steps. On identical rollouts it made each step 1.20× slower, nearly all of it in generation.
The audit narrowed that claim. The 45-step test ran where default mode was already repeatable, so it shows that deterministic mode runs and repeats. It does not show that deterministic mode removes the step-41 drift. The audit also found a warning my parser had missed: the memory-efficient attention backward is non-deterministic by default.
The results list now says “not guaranteed”, next to the original claim. The rule I took from it: a check must be able to fail, so test determinism where nondeterminism is known to appear.
On 8×H100
I restarted the dense baseline once on the 8-GPU node, from the same seed and data. The first loss matched exactly, 12.15001, but later losses differed by up to about 0.3%. At iteration 37 they read 7.6240 and 7.6408, and only 2 of the 37 shared iterations were identical. Megatron is not bit-deterministic without --deterministic-mode.
Megatron’s own code lists what bit-exact runs need:
NVTE_ALLOW_NONDETERMINISTIC_ALGO=0, so Transformer Engine uses only deterministic algorithms;CUBLAS_WORKSPACE_CONFIG=:4096:8andNCCL_ALGO=Ring;- the fused cross-entropy loss and tensor-parallel communication overlap both off;
- PyTorch’s deterministic algorithms on.
Our launch, copied from the tested script, sets NVTE_ALLOW_NONDETERMINISTIC_ALGO=1 and turns the fused cross-entropy on. So a same-seed re-run of an H100 stage is a close replica, not an exact control.
Seeds
A seed fixes the random numbers a run uses: the starting weights, the data order and the sampling. The Megatron scripts use seed 1234 throughout. Repeating a run with new seeds measures training luck, which a confidence interval over test problems cannot. On the laptop, the headline GSPO result held in 3 of 3 seeds.
Seeds can also pair runs. When two arms share each seed’s starting weights and data order, one arm winning all 3 pairs happens by chance with probability \((1/2)^3 = 1/8\). I had first written 1 in 20, and an external review caught it. A same-seed re-run of a deterministic pipeline is not a replication either; a result needs a new training seed.
On 8×H100, each GSPO comparison rests on one run per arm.
The pinned environment
Reproducing a number needs the same code, packages, data and settings. For the laptop work, code/reproducibility/ holds two files. requirements-lock.txt lists the exact 144 Python packages, for Python 3.12.3 and PyTorch 2.11.0 with CUDA 13.0. inputs.sha256 holds the SHA-256 of 22 inputs: data, released weights, slices and the RL curriculum.
code/scripts/day1_setup.sh rebuilds all of it at pinned commits and dataset revisions, checks every input, and refuses to finish if one differs. On a fresh clone it finished in 6 min 36 s, 106 tests passed, and two analysis scripts reproduced our saved outputs byte for byte. Not verified: other Python versions, a machine with empty caches, and GPUs other than the laptop’s RTX 3060.
For the H100 runs, the pins are:
- the container image
nvcr.io/nvidia/pytorch:26.08-py3, with PyTorch 2.14.0a0, CUDA 13.4.1, Python 3.12 and Transformer Engine 2.18; - Megatron-LM at commit d6316eb45 with our patch, refused on any other commit;
- exact versions of the packages the image lacks, taken from Megatron’s own lock file where it has one;
- the data and the tokenizer, checked against SHA-256 manifests;
- a
pip freezesaved on every node; - for every launch, a
run_meta.txtwith the scripts’ SHA-256, the Megatron commit, the data manifest’s hash and every argument.
The saved-weights check
Saving can also change a model: MiniMind’s fp16 saves can round RL updates away. So, is the checkpoint on disk the model the run evaluated? On the laptop, re-evaluating Run 3’s saved fp32 weights at step 300 reproduced the in-run evaluation exactly: 0 of 200 problems differed.
Under dynamic batching, exact agreement is out of reach, so the control run compared the saved checkpoint against its noise floor:
| Comparison (166-problem dev split, greedy) | Accuracy | Answers changed | Identical texts |
|---|---|---|---|
| Saved update-100 weights evaluated alone, vs the run’s own evaluation | 67.47% vs 66.87% | 9 | 75 of 166 |
| The run’s evaluation vs its repeat (same weights in memory) | 66.87% vs 67.47% | 5 | 63 of 166 |
The saved checkpoint agrees with the run as closely as two evaluations of the same in-memory weights do. The copies were checked too: the weights’ SHA-256 matched on both ends of the transfer.
Run it yourself
Hardware and time. Cases 1 and 2 ran on a laptop RTX 3060 with 6 GB; any CUDA GPU of that size will do. The determinism diagnostic took about 35 minutes there. Case 3 needs 8 GPUs, and case 4 one H100. The setup guide, the RL guide and the evaluation guide give the full steps.
On the laptop (from the repository’s top folder):
# Rebuild the environment and check all 22 inputs against their SHA-256.
bash code/scripts/day1_setup.sh 2>&1 | tee day1_setup.log
sha256sum -c code/reproducibility/inputs.sha256
cd code
# Case 1: score the same answers several ways with identical weights.
../.venv/bin/python -u scripts/diag_gspo_ratio.py --from_weight full_sft
# Case 2: one update at two learning rates, with fp32 and bf16 forward passes.
../.venv/bin/python -u scripts/diag_single_update.py --from_weight full_sft --lrs 1e-6 1e-7
# GSPO with fp32 log-probs and PyTorch's deterministic mode on.
../.venv/bin/python -u rl/minimind_gspo.py --from_weight full_sft --steps 60 --adjust_every 20 \
--start_tier warmup --logprob_precision fp32 --deterministic on --tag fp32_det
On the H100s:
# Case 3: the first-update checks of a GSPO run (ratio exactly 1, KL 0) and clipping per mini-batch.
python -I code/scripts/gspo_run_report.py /workspace/runs/gspo --updates-per-step 4
# Case 4: two in-run evaluations of the same weights, compared problem by problem.
python3 code/scripts/analyze_control.py eval <run>/eval_results.jsonl <run>/eval_results.jsonl \
--before-eval 2 --after-eval 3 --json update100_vs_repeat.json
Megatron appends each in-run evaluation to one file, and --before-eval and --after-eval pick two of them.
Results to expect (ours, one run each):
- Case 1, in bf16: only “alone versus inside the batch” differs. Ours was 0.028 nats per token; its mask included padding positions, and its output was not saved.
- Case 2: the fp32 change about 10× larger at 1e-6 than at 1e-7, and the bf16 change about the same at both.
- Case 3: on one GPU, ratio exactly 1; at expert parallelism 8 we saw a median absolute log-ratio of 4.9e-3.
- Case 4: avg@8 within about 0.3 points between the two evaluations, and about 40% identical greedy texts.
The code: code/rl/gspo.py (the ratio and k3), code/patches/megatron-d6316eb45.patch (the same in Megatron), code/scripts/diag_gspo_ratio.py, code/scripts/diag_single_update.py, code/scripts/determinism_check.sh, code/scripts/run_deterministic.py, code/scripts/gspo_run_report.py, code/scripts/analyze_control.py, and code/reproducibility/.
What to take away
- bf16 carries 8 bits of precision. Neighbours between 1 and 2 are \(2^{-7}\) apart, so updates under half a gap vanish; keep master weights in fp32.
- Check stored precision against compute precision. An fp16 checkpoint in bf16 compute put 13.04% of the weights on rounding ties.
- Score everything you compare in identical batches. Sums depend on their order, and kernels pick the order from the batch’s shape.
- Build in the free checks: the first update’s ratio exactly 1 and the KL exactly 0. They caught the laptop’s first bug and the 8-GPU noise.
- Tell learning from rounding with the learning-rate scaling test. Real changes scale with \(\eta\), and the KL with \(\eta^2\); rounding does not.
- Measure your noise floor. Two evaluations of the same weights agreed on 198 of 500 greedy texts, but within 0.33 points of avg@8.
References
- Horace He, in collaboration with others at Thinking Machines, “Defeating Nondeterminism in LLM Inference”, Thinking Machines Lab: Connectionism, September 2025, doi:10.64434/tml.20250910. thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference
- Chujie Zheng et al., “Group Sequence Policy Optimization”, arXiv:2507.18071, 2025. arxiv.org/abs/2507.18071
- John Schulman, “Approximating KL Divergence”, 2020. joschu.net/blog/kl-approx.html
- Sha (Zoey) Li, “A Field Guide to Training–Inference Corrections”, September 2026. zoeyli.com/blog/Field-Guide-Training-Inference-Corrections
- Zhoutong Fu, “Rollout–Training Mismatch in LLM RL”, November 2026. zhoutongfu.github.io/zhoutong-ai-blog/posts/rl-mismatch-mitigation
- The Microsoft AI Team, “RL infrastructure at Microsoft AI”, Microsoft AI, November 2026. microsoft.ai/news/rl-infrastructure-at-microsoft-ai
- Paulius Micikevicius et al., “Mixed Precision Training”, arXiv:1710.03740, 2018. arxiv.org/abs/1710.03740
- Nouamane Tazi et al., “The Ultra-Scale Playbook: Training LLMs on GPU Clusters”, Hugging Face, 2025. huggingface.co/spaces/nanotron/ultrascale-playbook
- NVIDIA, Megatron-LM at commit d6316eb45: megatron/training/determinism.py and megatron/core/transformer/moe/moe_utils.py.
Cite this
@misc{aboagye2026minidsv4part05,
author = {Aboagye, Prince Osei},
title = {Mini DeepSeek V4, Part 5: Numerics and reproducibility: why the same weights gave different numbers},
year = {2026},
howpublished = {\url{https://poaboagye.github.io/blog/05-numerics-and-reproducibility/}}
}