Prince Osei Aboagye
← All posts
Mini DeepSeek V4 / Part 00·Dec 2026

Start herethe whole project on one page

Spoiler: I trained a 6.86B-parameter DeepSeek-V4-style MoE from scratch; RL gained little, and a control run showed why: the base model, not the RL code.

TL;DR

I built a DeepSeek-V4-style mixture-of-experts model with 6.86B parameters, 1.22B of them active per token, and trained it from scratch on 8×H100. Pretraining ran 1,240 steps on 2.6B tokens to a validation loss of 3.046 (perplexity 21.0), after quantile balancing fixed a router collapse. Reinforcement learning with GSPO then raised held-out pass@8 only from 10.5% to 13.2% (paired p = 0.038).

The same RL code, with its own learning rate, KL weight and clipping and PocketRL’s batch shape, took Qwen2.5-Math-1.5B from 21.77% to 53.95% MATH-500 avg@8 in 100 updates, level with the published curve. So my RL pipeline works, and my model’s weak base explains its small gain.

// § 01

What you’ll learn

  • What I built: the model, the training system and the pipeline, in one picture.
  • What every stage measured: its key number, how noisy that number is, and the part that explains it.
  • Which parts to read first, whether you care about RL, about systems, or are new to both.
  • What the jargon means, with the formula wherever there is one.
  • What hardware each level of the project needs, from a 6 GB laptop GPU to 8×H100.
// § 02

The promise of the series

One engineer, a laptop and 8×H100: a DeepSeek-V4-style mixture of experts built end to end, with every number measured and checked against its noise.

Each part teaches one topic from scratch, shows what I built and measured, and ends with the commands to run it yourself. Every part stands on its own, so you can start anywhere. This page is the map. The code is public, and every number comes from the project’s records: the lab notebook, the plans, the code and the run outputs.

Three threads run through the whole series:

  • Rules fixed before the data. The laptop’s held-out learning test, the router decision and the control run’s pass line were written down before I saw their results.
  • The same weights should give the same numbers, and often they do not. It starts with a batch-dependent score on the laptop. It returns as an RL ratio that is not exactly 1 on 8 GPUs, and ends with greedy answers that change between evaluations.
  • Each stage catches failures before the next, larger one. A laptop, then one H100, then 8×H100: many failures that would have stopped the big run were found on smaller hardware first. Part 15 lists them, and the ones that slipped through.
// § 03

The whole pipeline in one picture

The whole project in one pictureTop: the hardware stages, in order. Bottom: the model pipeline of the main run on 8×H100.The hardware pathPart 9Laptop RTX 3060(6 GB), MiniMind 64Mthe RL loop's bugs fixed1Part 15One H100every stage rehearsedwith shrunk models2Part 48×H100the main run:the full 6.86B model3Part 14One H100the control run onQwen2.5-Math-1.5B4Inside the main run on 8×H100Part 3Data2.6B FineWeb-Edu tokens55,083 SFT questionsPart 6Router study (B1)every recipe collapsed;chose quantile balancingParts 2, 4, 6Pretraining (B2)1,240 steps;validation loss 3.046Part 7SFT (B4)format, notarithmeticParts 9, 10GSPO (B5)pass@810.5% → 13.2%Part 13Evaluationgreedy, pass@8,avg@8Part 11Serving (B6)1,731 tokens/son 8 GPUsthe same RL code on a strong base:MATH-500 avg@8 21.8% → 54.0%
Figure 1. the project in one picture. The top lane is the order of the hardware stages; the bottom lane is the model pipeline that ran on 8×H100. Each box names the part that covers it. Source: the project’s results list (Results).

What each box is, and where the series covers it:

  1. Data (Part 3). Pretraining used 2,600,591,645 tokens of FineWeb-Edu, a filtered set of educational web pages, with 26,012,769 more held out for validation. SFT used 55,083 GSM8K-style math word problems, each with one checked worked solution. RL drew from a curriculum of arithmetic and math word problems in four tiers, and six held-out test sets measured every model.
  2. The model (Part 2). It is a 16-layer decoder with hidden size 2048 and 32 query heads that share 4 key-value groups. Every layer’s feed-forward block is a mixture of 64 routed experts; each token uses 8, and there is no shared expert. It reads the Llama 3.2 tokenizer’s 128,256 tokens and uses rotary position embeddings with base 500,000. From DeepSeek V4 it keeps the router’s scores, normalized queries and keys, and a SwiGLU clamped at 10; its routed scaling of 2.5 is DeepSeek-V3’s value at top-8 (V4-Flash ships 1.5 at top-6).
  3. What it leaves out. V4’s attention and memory innovations stay out: MLA, mHC, CSA/HCA, DSA, multi-token prediction, Engram and the FP4 KV cache. Part 2 explains each one and why.
  4. The training system (Part 4). Megatron-LM at a pinned commit, d6316eb45, plus my patch, which adds the GSPO loss and several fixes. Each layer’s 64 experts are split 8 ways across the GPUs, and every other weight is replicated and trained data-parallel. Tokens reach their experts through an all-to-all exchange, and training runs in bf16 with Megatron’s distributed optimizer.
  5. The router study, B1 (Part 6). Short 40-step runs compared ways of keeping the experts evenly loaded. Every recipe collapsed: by step 10, each layer sent every token to the same 8 experts. A rule written before the fix test chose DeepSeek V4’s scores with quantile balancing, the only arm clearly recovering by step 40.
  6. Pretraining, B2 (Part 6). It ran 1,240 steps of 512 sequences of 4,096 tokens: 2.6B tokens in 4.09 hours at 194.7 TFLOP/s per GPU. The base model then scored 0 on every test set, because its answers looped until the ~1,500-token stop.
  7. SFT, B4 (Part 7). Supervised fine-tuning taught the answer format but not the arithmetic. I kept step 175 of a 6-epoch run (validation loss 0.748); GSM8K reached 2.0% greedy and 12.0% pass@8.
  8. GSPO, B5 (Part 9, Part 10). RL ran 45 steps, each of 16 problems × 32 answers, on the medium tier of the curriculum. Held-out pass@8 rose from 10.5% to 13.2%, and the six-set avg@8 from 1.46% to 2.04% (p = 0.002).
  9. Evaluation (Part 13). From SFT on, every model was scored on the same problems three ways, greedy, pass@8 and avg@8, with paired tests between models.
  10. Serving, B6 (Part 11). Megatron’s inference engine served the RL model at 68.3 ms per token for one request, and 1,731 tokens/s for 512 requests on 8 GPUs.
  11. Distillation and 4-bit training (Part 12). Both ran end to end on the one-H100 rehearsal with shrunk models, then were cut from the main run for time.
  12. The control run (Part 14). The same GSPO code on Qwen2.5-Math-1.5B with PocketRL’s data, prompt, grader and batch shape, on one H100.
// § 04

What happened, in five steps

1. The laptop. Before touching an H100, I tested the RL loop on a laptop RTX 3060 (6 GB) with MiniMind, a 64M-parameter dense model. The trainer’s score for an answer depended on which other answers shared its batch, so GSPO’s ratio was wrong before any learning happened. Scoring the old, new and reference models in identical mini-batches made the first ratio exactly 1 and the KL exactly 0.

With an on-policy sampler, GSPO then raised held-out final-answer accuracy in 3 of 3 seeds, from 0.81% to 5.4–5.9%. Then came the laptop’s limit: even a small 198M-parameter MoE’s RL rollout, not its update, does not fit in 6 GB.

2. The data and the one-H100 rehearsal. About 11% of NVIDIA’s new GSM8K-style questions had no exact answer. NVIDIA’s decontamination also kept copies of test questions with only the numbers changed. I then rehearsed every stage on one H100 with shrunk models of 2 layers and hidden size 512.

The rehearsal found failures that would have been silent on 8 GPUs. An evaluation of random weights exited cleanly, and a crashed RL run hung for 24 minutes. A policy with nothing to learn still drifted, pushed first by the expert-bias update and then by the router’s balance loss.

3. The main run on 8×H100. Every router recipe collapsed within 10 steps; quantile balancing fixed it, and pretraining reached validation loss 3.046. The base model answered nothing, SFT taught the format but not the arithmetic, and GSPO added 2.7 points of pass@8. Training only on the 418 problems the model could sometimes solve sped up learning on that pool, not on the held-out tests.

On 8 GPUs, GSPO’s first update was not exactly on-policy: the median absolute log-ratio was 4.9e-3, where one GPU gives exactly 0. The router held steady through RL: its z-loss moved from 25.3 to 25.9.

4. The doubt. PocketRL, a recent paper with a similar recipe, gained far more: its 7B model went from 13.4% to 43.0% six-set avg@8. Was my small gain the fault of my model, or of my pipeline?

5. The control run. I ran my RL code, with its own learning rate, KL weight and clipping, on the smaller base model PocketRL also trains, Qwen2.5-Math-1.5B, on one H100. The pass line, written before the run, was a MATH-500 avg@8 gain of at least 11.5 points by update 50. It passed with +19.65 points, and by update 100 it reached 53.95%, level with PocketRL’s matching arm at about 53.5%.

What it means. RL mostly sharpens what a model can already do some of the time. Qwen’s base solved 69.6% of MATH-500 in at least one of 8 samples, but only 21.8% of its samples were right. My SFT model got none of 16 tries right on 78% of its medium-tier training problems, so RL had little to sharpen.

// § 05

Results at a glance

Every stage’s headline number, the yardstick for how much noise to expect in it, and the part that explains it. A noise yardstick is the change you would see with nothing real changing: a confidence interval, a repeat measurement or a control run. All results has the full list with every source.

Stage (hardware) Key result Noise yardstick Read
Laptop GSPO on MiniMind 64M (RTX 3060) Held-out final-answer accuracy 0.81% → 5.4–5.9% (+4.62 to +5.06 points), 3 of 3 seeds 95% bootstrap over problems, e.g. [+3.19, +7.19]; the seeds share one test set Part 9
Data (laptop) 2.60B pretraining tokens; 55,083 SFT questions; 7,997 of 73,643 source questions dropped for having no exact answer Blind label check: 0 of 50 wrong (95% upper bound 7.1%) Part 3
Rehearsal, shrunk models (one H100) Every stage ran end to end; GSPO learned from a real signal (z = 6.5 against its control) The control with nothing to learn: reward −0.074 ± 0.036, KL exactly 0 Part 15
Router study, 40-step arms (8×H100) Every recipe at MaxVio 7.0, the maximum, in all 16 layers; only quantile balancing recovering (5.19 at step 40) Forced-even routing reads 0.009–0.011, the measurement’s floor; one seed Part 6
Pretraining (8×H100) 1,240 steps, 2.6B tokens, 4.09 h; validation loss 3.046 (perplexity 21.0); 194.7 TFLOP/s per GPU One run; hold-out perplexity 20.97 on the 26M-token hold-out Part 6
Base model (8×H100) 0 correct on every test set; answers loop to the ~1,500-token stop None needed: 0 of 1,430 problems Part 6
SFT (8×H100) Format 74.5%; GSM8K 2.0% greedy, 12.0% pass@8; hold-out perplexity 20.97 → 22.74 Greedy flips with batching: the same 35 dev problems scored 3, then 2 Part 7
GSPO-A (8×H100) Pooled pass@8 10.5% → 13.2% (p = 0.038); six-set avg@8 1.46% → 2.04% (+0.58 points, p = 0.002) Paired tests on the same 1,178 problems; one seed Part 9
GSPO-B, learnable problems only (8×H100) 418 of 1,905 problems learnable; its training trend t 5.4 against GSPO-A’s 1.7 Against GSPO-A on held-out tests: greedy p = 0.31, pass@8 p = 0.22 Part 9
RL numerics at expert parallelism 8 First update: median absolute log-ratio 4.9e-3 (p99 0.034), KL 0.0027 On one GPU: exactly 0 and 0 Part 10
RL step time (8×H100) A median of 111 s a step; generating and grading took 57.5% of the logged time GSPO-A’s 44 complete steps Part 10
Router through RL (8×H100) z-loss 25.3 → 25.9 (+2.4%); entropy of the 8 chosen weights 1.996 → 1.989 nats For scale, the maximum entropy is ln 8 = 2.079 nats Part 9
Serving (8×H100) 149 ms to the first token and 68.3 ms per token at batch 1; 1,731 tokens/s for 512 requests One run per mode Part 11
Distillation, 4-bit (rehearsal only) Distilled student’s KL to the teacher 0.215 against 0.293 without; plain 4-bit (PTQ) KL to bf16 1.815e-3, after quantization-aware distillation 1.800e-3 Shrunk models: plumbing, not results Part 12
Control run, Qwen2.5-Math-1.5B (one H100) MATH-500 avg@8 21.77% → 53.95% (+32.17, t 22.9, 95% interval [+29.45, +35.00]); six-set mean 9.67% → 23.21% Same weights twice: avg@8 −0.33 (SE 0.86); 198 of 500 greedy texts identical Part 14

How to read it:

  • p is a paired test’s p-value: the chance of a difference at least this large if nothing had changed. It says nothing about the size of the gain.
  • One seed, one run. Unless a row says otherwise, I ran each arm once, so the yardstick covers the evaluation’s noise, not training luck.
  • About. PocketRL’s curves are read off its plots, so its numbers carry a “~” in the parts that use them.
// § 06

How to read the series

Part Post The question it answers
1 Planning the project How do you size the model, choose the path from laptop to 8×H100, and fix decision rules before the data?
2 The model What is a mixture of experts, and what did I keep from DeepSeek V4?
3 Data and the tokenizer Where the tokens came from, and what traps sit in public math data
4 The training system How Megatron-LM spreads a mixture of experts over 8 GPUs, and where the time goes
5 Numerics and reproducibility Why the same weights give different numbers, and what to do about it
6 Pretraining How every router collapsed, how quantile balancing fixed it, and how the long run went
7 Supervised fine-tuning Why SFT taught the format but not the arithmetic
8 Rewards and graders How a math grader works, how to audit it, and how it can hang training
9 RL: GRPO and GSPO The algorithms from scratch, the laptop experiments and the RL runs on my model
10 The RL system Synchronous or asynchronous RL, and where an RL step’s time goes
11 Serving Megatron’s inference engine, CUDA graphs, the KV cache and decoding speed
12 Distillation and 4-bit training What the rehearsal showed, and why both were cut from the main run
13 Evaluation Greedy against pass@k against avg@k, noise floors and paired tests
14 The control run Was it the model or the RL code?
15 Lessons What broke, what I would change, and what comes next

Four ways through it:

To run any of it, start with the setup guide. Troubleshooting lists every bug I hit as symptom, cause and fix.

// § 07

Three hardware levels for running it yourself

Level What it runs Time it took me Start with
A laptop RTX 3060 (6 GB) The unit tests; data preparation; the RL experiments on MiniMind’s 64M dense model Four 300-step GSPO runs: 4 h 46 min Part 9
One H100 (80 GB) Every stage with shrunk models (the rehearsal); the control run on Qwen2.5-Math-1.5B The rehearsal: 5.6 h; the control run: about 4.1 h Part 14
8×H100 (SXM, NVLink) The full 6.86B model: router study, pretraining, SFT, GSPO, evaluation, serving 13.95 h of node time; pretraining alone 4.09 h Part 4

What sets the limits:

  • The laptop cannot run RL even for a 198M-parameter MoE: a full-length rollout of 128 answers ran out of memory despite every memory saving.
  • One H100 runs the real code path, Megatron and all, but nothing that needs several GPUs. Part 15 lists what it missed.
  • The 8×H100 node needs NVLink: at 2 GB messages, the all-to-all ran at 341 GB/s with NVLink and about 11 GB/s without.

The setup guide covers each level: the container, the pinned environment and the health checks.

// § 08

Glossary

Terms in roughly the order you meet them. Where a term has a formula, the formula comes with a line in words. The metrics glossary and the statistics primer go further.

The model

Token, loss and perplexity. A token is a piece of text, often part of a word; my model’s tokenizer, Llama 3.2’s, has 128,256 of them. Training minimizes the cross-entropy loss, and perplexity is its exponential:

\[\mathcal{L} = -\frac{1}{T}\sum_{t=1}^{T} \log p_\theta(x_t \mid x_{<t}), \qquad \mathrm{PPL} = e^{\mathcal{L}}\]

In words: the loss is the average surprise at each real next token, in nats. Perplexity is roughly how many tokens the model is torn between.

An untrained model guesses uniformly, so its loss starts near \(\ln 128{,}256 = 11.76\). My pretrained model ended at 3.046, a perplexity of \(e^{3.046} \approx 21.0\).

Mixture of experts (MoE). A layer that holds many feed-forward networks, the experts, but runs only a few of them for each token. A router picks the experts, and the layer’s output is their weighted sum:

\[\mathbf{y} = \sum_{i \in \mathcal{T}(\mathbf{x})} g_i(\mathbf{x})\, E_i(\mathbf{x}), \qquad |\mathcal{T}(\mathbf{x})| = k\]

In words: for a token \(\mathbf{x}\), add up the outputs of the \(k\) chosen experts \(E_i\), each scaled by its gate weight \(g_i\). The other experts do no work for that token.

My model has 64 routed experts per layer and \(k = 8\).

Total and active parameters. Total parameters count every expert; active parameters count only what one token uses. Mine are 6.86B total and 1.22B active. Each token’s 8 experts hold \(8 \times 3 \times 2048 \times 1024 \approx 50.3\text{M}\) parameters per layer: three matrices each, of 2048 by 1024.

Router and top-k. The router is a small linear layer that gives each expert a logit \(z_i\) for each token. DeepSeek V4 turns logits into scores with \(s_i = \sqrt{\operatorname{softplus}(z_i)}\). The token goes to the \(k\) best experts after a per-expert balancing bias is applied. The chosen experts’ scores, renormalized to sum to 1 and multiplied by 2.5, are the gate weights \(g_i\).

Load balance and MaxVio. If the router sends most tokens to a few experts, their GPUs do most of the work while the others wait. MaxVio measures the imbalance from the token counts \(c_i\) of the experts:

\[\mathrm{MaxVio} = \frac{\max_i c_i}{\bar{c}} - 1\]

In words: how much more work the busiest expert gets than an even share, where 0 is perfect balance.

If every token picks the same \(k\) of \(E\) experts, MaxVio reaches its maximum, \(E/k - 1 = 64/8 - 1 = 7\). My V4 and aux-loss routers hit it in all 16 layers by step 10.

Auxiliary loss and the expert bias. Two classic ways to balance the load. An auxiliary loss adds a small penalty for uneven loads to the training loss; my aux-loss arm used a coefficient of 1e-3. DeepSeek’s expert bias instead nudges each expert’s selection score by a fixed step after every training step:

\[b_i \leftarrow b_i + \eta \, \operatorname{sign}(\bar{c} - c_i)\]

In words: raise the bias of every under-loaded expert and lower the bias of every over-loaded one, all by the same small amount \(\eta\).

At \(\eta = 10^{-3}\) a bias moves at most 0.04 in 40 steps, while balancing my model needed biases of about ±1.5 in score units (±4–6 in logits): the sign rule was about 40× too slow at \(10^{-3}\), and 4× at \(10^{-2}\).

Quantile balancing. It keeps the bias but solves for it at each step instead of stepping it. For each expert it finds the score that only its fair share of tokens beats, \(k/E = 8/64\) of them, and sets the bias from it. In my pretraining it pulled every layer out of the collapse, to a mean MaxVio of 0.437 by step 200.

The system

Expert parallelism. Splitting each layer’s experts across GPUs. At expert parallelism 8, each of my 8 GPUs holds 8 of the 64 experts in every layer. Every other weight is replicated on all 8 GPUs.

All-to-all. The exchange that sends each token to the GPUs holding its experts, then brings the results back. Every GPU sends to every other GPU, so it needs fast links. Even with perfectly balanced routing, communication took 30.8% of a training step on my node.

bf16. A 16-bit number format with the range of 32-bit floats (fp32) but fewer digits of precision. fp16 keeps 3 more bits of precision, so about 1 weight in 8 of an fp16 checkpoint lands exactly halfway between two bf16 values. I measured 13.04% on the laptop; those ties made one tiny update look huge, and scoring in fp32 restored the exact first-update checks and halved the KL.

MFU. Model FLOPs utilization, \(\mathrm{MFU} = \text{achieved FLOP/s} \,/\, \text{peak FLOP/s}\). Pretraining ran at 194.7 TFLOP/s per GPU: an MFU of 19.7% of the H100’s dense bf16 peak of 989 TFLOP/s.

Checkpoint. A saved copy of the weights; a full checkpoint also holds the optimizer state, so training can resume exactly. My full pretraining checkpoint was 89.46 GiB, and a weights-only copy about 13.7 GB.

CUDA graphs. A way to record a sequence of GPU kernel launches once and replay it, which removes launch overhead when batches are small. Without them my model decoded at 68.3 ms per token for a single request. In the control run, CUDA graphs cut a decoding step from about 43 ms to about 6 ms.

Batch invariance. A computation is batch-invariant when a row’s result does not depend on which other rows share its batch. GPU kernels often are not, because they add numbers in a different order for different batch shapes. It sits behind three surprises in this series: the laptop’s ratio bug, the 8-GPU ratio noise and greedy answers that change between evaluations.

Reinforcement learning

SFT (supervised fine-tuning). Training on worked examples of the task, with the same next-token loss as pretraining. My SFT taught the format, a <think> block then an <answer> block, but not the arithmetic.

RL with verifiable rewards. The model writes answers, a program checks them, and the update makes well-scored answers more likely. When the answer can be checked by a program, no human labels or learned reward model are needed.

Rollout and group. A rollout is one sampled answer to a training prompt, with its reward. Group methods sample \(G\) answers per prompt; my main run used 16 prompts × 32 answers, 512 rollouts per step. A group is mixed when it holds at least one right and one wrong answer, and only mixed groups carry a learning signal. Part 15 has the formula for how often that happens.

Grader and reward. The grader is the program that scores an answer. The control run used Dr. GRPO’s \boxed{} grader, which reads the last boxed answer and scores 0 for answers cut off at 3,000 tokens. An audit of my main-run checker found it rejected 0 of 20,528 correct numeric gold answers and accepted no wrong numeric answer; on LaTeX answers, 35 wrong answers passed on 28 problems, 6 of them real holes.

Advantage. How much better an answer did than the others in its group:

\[\hat{A}_i = \frac{r_i - \operatorname{mean}(r_1, \dots, r_G)}{\operatorname{std}(r_1, \dots, r_G)}\]

In words: an answer’s reward minus its group’s average, in units of the group’s spread.

If all \(G\) answers score the same, every advantage is 0 and the group teaches nothing. My runs gave every all-right or all-wrong group advantage 0, even when the format bonus or length penalty made its rewards differ, through Megatron’s correctness filter.

Importance ratio. The probability of an answer under the model being trained, divided by its probability under the model that sampled it. GRPO uses one ratio per token. GSPO uses one per answer, the geometric mean of the token ratios:

\[s_i(\theta) = \left(\frac{\pi_\theta(y_i \mid x)}{\pi_{\theta_\text{old}}(y_i \mid x)}\right)^{1/|y_i|} = \exp\!\left(\frac{1}{|y_i|}\sum_{t=1}^{|y_i|} \log \frac{\pi_\theta(y_{i,t} \mid x, y_{i,<t})}{\pi_{\theta_\text{old}}(y_{i,t} \mid x, y_{i,<t})}\right)\]

In words: average the per-token change in log-probability over the whole answer, then exponentiate.

On the first update the trained model is the sampling model, so \(s_i\) must be exactly 1. I checked that at every stage.

GRPO. Group Relative Policy Optimization, introduced with DeepSeekMath [2]: PPO without a value network. It uses group advantages and clips each token’s ratio to a window around 1.

GSPO. Group Sequence Policy Optimization [3]: GRPO with the ratio and the clipping moved from tokens to whole answers:

\[J(\theta) = \mathbb{E}\left[\frac{1}{G}\sum_{i=1}^{G} \min\Big(s_i(\theta)\,\hat{A}_i,\ \operatorname{clip}\big(s_i(\theta),\, 1-\varepsilon_\text{low},\, 1+\varepsilon_\text{high}\big)\,\hat{A}_i\Big)\right]\]

In words: push up answers with a positive advantage and push down those with a negative one. Stop pushing an answer once its ratio leaves a narrow window around 1.

The paper’s window is \(3 \times 10^{-4}\) below 1 and \(4 \times 10^{-4}\) above. On 8 GPUs I widened it to \(2 \times 10^{-2}\) and \(2.7 \times 10^{-2}\), above the numerical noise. My runs also add a KL penalty with weight \(\beta = 0.01\).

KL divergence. How far the trained model \(\pi_\theta\) has moved from a frozen reference \(\pi_\text{ref}\), here the model RL started from:

\[D_\text{KL}(\pi_\theta \,\|\, \pi_\text{ref}) = \mathbb{E}_{y \sim \pi_\theta}\left[\log \frac{\pi_\theta(y \mid x)}{\pi_\text{ref}(y \mid x)}\right]\]

In words: the average extra log-probability the trained model gives its own answers, compared with the reference. It is zero when the two are identical.

Before the first update it must be exactly 0, the twin of the ratio check.

On-policy, and the sampler–learner gap. On-policy means the training answers come from exactly the model being trained: temperature 1, with no top-k or top-p truncation. In practice the inference engine and the trainer compute slightly different log-probabilities; the per-token difference is the sampler–learner gap. It was 0.0133 nats per token on the rehearsal and 0.0072 in the control run.

Measuring

Greedy decoding. Always take the most likely next token. It should be deterministic, but batch-dependent bf16 arithmetic flips near-ties. Two evaluations of the same weights gave identical greedy text on only 198 of 500 problems.

pass@k and avg@k. Sample \(k\) answers per problem at temperature 1, and let \(c_n\) be the number that are right for problem \(n\) of \(N\):

\[\text{pass@}k = \frac{1}{N}\sum_{n=1}^{N} \mathbb{1}\!\left[c_n \ge 1\right], \qquad \text{avg@}k = \frac{1}{N}\sum_{n=1}^{N} \frac{c_n}{k}\]

In words: pass@k is the share of problems that at least one of the \(k\) answers solves. avg@k is the share of all answers that are right.

So pass@k measures reach and avg@k measures reliability. Before RL, Qwen2.5-Math-1.5B had a MATH-500 pass@8 of 69.6% but an avg@8 of 21.8%. Because avg@k uses every answer, it detects smaller changes: GSPO-A’s gain had p = 0.002 by avg@8, against p = 0.038 by pass@8.

Noise floor. The change you see when nothing real has changed. I evaluated the control run’s final weights twice: avg@8 moved by −0.33 points (SE 0.86). By chance alone, 22 problems were newly reached and 21 lost (any of 9 tries). A gain counts only once it clears this floor.

Paired test. Score both models on the same problems and test the per-problem differences, so problem difficulty cancels out:

\[d_n = a_n^{\text{after}} - a_n^{\text{before}}, \qquad t = \frac{\bar{d}}{s_d / \sqrt{N}}\]

In words: average the per-problem gains, then divide by their standard error. A large \(t\) means the gain sits many standard errors from zero.

The control run’s MATH-500 gain was +32.17 points, with a standard error of 1.41 and \(t = 22.9\). For right-or-wrong outcomes I used McNemar’s test, which compares the problems that went wrong → right with those that went right → wrong.

Held-out set and MATH-500. Held-out problems are never trained on. MATH-500 is a 500-problem subset of the MATH competition benchmark, and the set my control run’s pass line used.

// § 09

Run it yourself

Hardware and time. See the three levels above:

  • a 6 GB laptop GPU for the tests and the small-model RL experiments;
  • one H100 for the rehearsal and the control run;
  • 8×H100 for the full model.

Both H100 levels use the container nvcr.io/nvidia/pytorch:26.08-py3 and Megatron-LM at commit d6316eb45 with my patch.

Before any GPU. Check every launch script against Megatron’s own parser, cross-flag checks and model config, on the CPU:

python -I code/scripts/megatron/check_flags.py --validate "$MEGATRON_PATH"

Level 1, a laptop RTX 3060 (6 GB). Linux, Python 3.12, a driver for CUDA 13.0 and about 10 GB of disk.

bash code/scripts/day1_setup.sh          # venv with pinned packages, MiniMind, data; checks every input's SHA-256
cd code
../.venv/bin/python -m unittest discover -s tests    # the unit tests; no GPU needed
bash scripts/step3.sh ab                 # on-policy GSPO on MiniMind 64M: four 300-step runs

Level 2, one H100: the control run. The full sequence is in the control-run guide. Its RL step, and the paired comparison that reads the result:

EVAL_RESULTS=/workspace/runs/control_gspo/eval_results.jsonl \
RUN_DIR=/workspace/runs/control_gspo RUN_NAME=control_gspo SFT_CKPT=/workspace/qwen/megatron GSPO_LR=1e-6 \
    PROMPTS_PER_STEP=16 GROUP_SIZE=8 UPDATES_PER_STEP=1 RL_PROMPTS_PER_EVAL=500 RL_SEQ=3584 RL_CUDA_GRAPHS=1 \
    RL_ENV_CONFIG=code/rl/control_env.yaml GSPO_SAMPLES=12800 EXIT_MINS=420 \
    bash code/scripts/megatron/gspo.sh > /workspace/runs/control_gspo.log 2>&1

# On any CPU afterwards: the base model against update 100, paired
python3 code/scripts/analyze_control.py eval <runs>/control_base/eval_results.jsonl \
    <runs>/control_gspo/eval_results.jsonl --after-eval 2

Level 3, 8×H100: the main pretraining. After the node setup in the setup guide, each run goes through a helper that stops it if its logs go quiet:

run() { export RUN_NAME=$1 RUN_DIR=/workspace/runs/$1; mkdir -p "$RUN_DIR"; shift
        python -I code/scripts/stall_guard.py --log "$RUN_DIR.log" --watch /workspace/runs -- "$@"; }
export MAIN_ROUTER=qb                    # DeepSeek V4's scores with quantile balancing
CKPT_DIR=/workspace/ckpt/pretrain run pretrain bash code/scripts/megatron/moe_pretrain.sh

Config files.

Results to expect. My numbers are in the results table above. For the control run, expect MATH-500 avg@8 near 53.95% at update 100. Two evaluations of the same weights differed by 0.33 points of avg@8, and gave 68.8% against 67.0% greedy, so read smaller gaps as noise.

Code. code/scripts/megatron/gspo.sh, code/rl/rewards.py, code/scripts/analyze_control.py and code/patches/megatron-d6316eb45.patch. The Guide has every command in order.

// § 10

What to take away

  • I built a 6.86B-parameter DeepSeek-V4-style mixture of experts and took it from scratch through pretraining, SFT and GSPO on 8×H100.
  • RL gained little on my model, 2.7 points of pass@8, and a control run showed why. The same code took a strong base from 21.8% to 54.0% on MATH-500.
  • RL sharpens what a model can already do some of the time. A base that almost never finds the answer gives it nothing to sharpen.
  • Read every number next to its noise yardstick: the same weights, evaluated twice, gave identical greedy text on only 198 of 500 problems.
  • Small hardware first: a laptop, then one H100, then 8×H100, each stage catching failures before the next.

References

  1. DeepSeek-AI. DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence. arXiv:2606.19348, 2026. arxiv.org/abs/2606.19348
  2. Shao et al. “DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models” (GRPO). arXiv:2402.03300
  3. Zheng et al. “Group Sequence Policy Optimization”. arXiv:2507.18071
  4. Liu et al. “Understanding R1-Zero-Like Training: A Critical Perspective” (Dr. GRPO). arXiv:2503.20783
  5. Chung and Du. “PocketRL: Training a 7B Language Model with Reinforcement Learning on One RTX 5090”. arXiv:2611.37942; code: github.com/dualverse-ai/pocketrl
  6. Hugging Face. “The Ultimate MoE Training Handbook”. huggingface.co/spaces/huggingface/moe-blogpost
  7. NVIDIA. Megatron-LM. github.com/NVIDIA/Megatron-LM
  8. Thinking Machines. “Defeating Nondeterminism in LLM Inference”. thinkingmachines.ai/blog/defeating-nondeterminism-in-llm-inference

Cite this

@misc{aboagye2026minidsv4part00,
  author       = {Aboagye, Prince Osei},
  title        = {Mini DeepSeek V4, Part 0: Start here: the whole project on one page},
  year         = {2026},
  howpublished = {\url{https://poaboagye.github.io/blog/00-start-here/}}
}