The Trap of a 0.1 Format Reward: How GRPO Std-Normalization Silently Kills Reasoning

2026-12-06     5155 字  25 分钟

TL;DR

  • The Paradox: Switching a 7B masked diffusion LM (Dream-v0-Instruct-7B, lr = 5e-7, verl FSDP2) from bf16 to fp32 master weights boosted MATH500 and GSM8K across every length—and immediately drove Countdown straight to 0.00%. bf16 mantissa swamping had been acting as an accidental step-size damper; once weights could actually move, every latent bug in our RL stack woke up at once.
  • Layer 1 — The Format-Bonus Amplifier (length 128): Sweeping lr, entropy_coeff, cosine schedules, and rollout temperature (0.2 → 0.8) pushed peak accuracy to 42.58% and cured zero-grad deadlocks—yet still washed accuracy back to 0.00% with grad_norm = 16.95. Under GRPO std-normalization, Countdown’s tiny format_score = 0.1 turns an all-wrong group of 8 rollouts ($s \approx 0.035$) into $\pm 2.47$ advantages—matching the gradient strength of solving the arithmetic. Switching to a pure binary $\lbrace 0, 1 \rbrace$ reward fixed length 128 out of the box (46.09% peak, zero collapses).
  • Layer 2 — Sequence-Length Systems Bugs (lengths 256 & 512): Scaling that exact binary-reward recipe to 256 and 512 tokens collapsed again. Inside the D1 actor loop, data = {**data, ...} shadowed a TensorDict into a Python dict, turning len(data) / ppo_mini_batch_size into $10 / 16$ per micro-batch—a 2× / 3× gradient multiplier once sequences crossed 5,120 tokens per GPU. Combined with AdamW drift across 63–82% zero-gradient steps (and an FSDP2 DTensor norm-sync trap), long runs slowly destabilized.
  • The Proof & The Boundary: Exact token-mean micro-batch weighting + FSDP2-synced zero-grad step skipping + weight_decay = 0.0 (while keeping post-EOS tokens unmasked) stabilized D1 at 256/512 (39.84% / 35.55% peaks) and Coupled-GRPO across 128/256/512—yet still failed on Sudoku, proving systems fixes cannot rescue dense partial-credit noise (correct_cells / 9) under zero-KL GRPO.

The blog is co-authored with Gemini.

In a previous note, we saw how four overlooked bfloat16 FSDP overrides silently froze >95% of a 7B model’s parameters during small-LR reinforcement learning (lr = 5e-7), and how restoring standard fp32 master weights immediately added +7.2 points on MATH500 and +21.3 points on GSM8K.

There is a less comforting sequel to that lesson: when your optimizer is silently frozen, half your downstream RL bugs stay asleep. The moment we restored fp32 master weights and our parameters could actually move, our math benchmarks soared—and Countdown (combining given integers once each with + - * / inside <answer> tags to hit a target number) fell off a cliff to 0.00%, four times in a row, across two different diffusion-RL algorithms. Untangling why took two weeks, over a dozen controlled ablations, three code-level root causes, one humbling failed fix, and a counterexample on Sudoku that showed us exactly where our fix stops working.


1. The Paradox: FP32 Supercharged Math and Killed Countdown

We were training Dream-v0-Instruct-7B (a 7B masked diffusion language model) with d1-style GRPO in a verl-based PyTorch FSDP2 stack (train_batch_size = 16, rollout.n = 8, lr = 5e-7, rollout.temperature = 0.2, use_kl_loss = False, 1 epoch across 8 GPUs).

Restoring fp32 master weights (keeping bf16 forward/backward compute) was an unambiguous win across every sequence length on Math (MATH500 + GSM8K, 929 steps)—and an immediate disaster on Countdown (1,250 steps, evaluated every 100 steps on 256 test problems):

The Precision Paradox: Math Soars vs Countdown Collapses

Look at the two panels together:

  • Math soared everywhere (Panel a): Across response lengths 128, 256, and 512, switching to fp32 master weights lifted MATH500 by +7.2 / +7.6 / +4.8 points (42.25% / 47.69% / 47.89%) and GSM8K by +21.3 / +9.7 / +19.3 points (78.32% / 84.99% / 85.60%).
  • Countdown died on impact (Panel b): Under bf16 master weights, Countdown-128 had crawled sideways between 12.5% and 18.0% (finishing at 16.41%; Countdown-256 finished at 11.72% and Countdown-512 at 33.20%) because mantissa swamping discarded almost every $5 \times 10^{-7}$ update. Under fp32, Countdown-128 jumped to 18.75% at Step 100—then around Step 190, actor/entropy_loss plunged to 0.0004, training reward hit 0.000, and actor/grad_norm flatlined to 0.00. For the next 1,050+ steps, all 8 GPUs spun on empty outputs ([]). Countdown-256 collapsed before Step 100—and our parallel Coupled-GRPO runs on Countdown-128 and 256 crashed the exact same way (four consecutive 0.00% collapses, at which point we paused the queue before launching Countdown-512).

Why did bf16 survive while fp32 blew up? Checking our training telemetry revealed that our setup had zero trust region by construction:

  • train_batch_size = 16, ppo_mini_batch_size = 16, and ppo_epochs = 1 mean each rollout batch takes exactly one gradient step. At loss time, $\log \pi_\theta \equiv \log \pi_{\text{old}}$, so the importance ratio $r_t = \exp(\log \pi_\theta - \log \pi_{\text{old}}) \equiv 1.0$. In the logs, actor/pg_clipfrac $\equiv$ 0.0000 and actor/ppo_kl $\equiv$ 0.0000 across every run—PPO clipping never fired once.
  • Combined with use_kl_loss = False, D1 was running unclipped, unregularized REINFORCE with full-mask single-step log-probability approximations (mc_num = 1).

Under bf16, precision rounding had acted as an accidental step-size damper. Under fp32, the brakes were off. Still, Math ran the exact same unclipped, zero-KL setup and thrived—so what was killing Countdown?


2. Act I — Chasing the “Entropy Collapse” Mirage: LR, Entropy, and Temperature

Before reading a single line of reward or actor code, every surface symptom pointed to textbook entropy collapse: temperature = 0.2 was too greedy, driving entropy near zero so all 8 rollouts per prompt became identical, group variance vanished, and gradients hit zero.

So we did what any RL practitioner would do first—we swept the three classic stabilizers one variable at a time on fp32 Countdown-128:

Wave 1: Testing LR, Entropy Bonus, and Rollout Temperature (Arms A, B, C)

  • Arm A — Lowering Learning Rate (lr: 5e-7 → 1e-7): Survived past Step 200 and climbed steadily from 17.58% (Step 100) to 29.30% (Step 400). Just when step size looked like the culprit, entropy slipped again and accuracy cratered to 3.12% (Step 500) and 0.39% (Step 600), locking into permanent zero-grad deadlock at Step 615. Smaller steps only bought time.
  • Arm B — Adding an Entropy Bonus (entropy_coeff: 0 → 0.1): Reached 30.08% at Step 100—and then collapsed even faster than the baseline! By Steps 128–142, every batch locked onto uniform wrong <answer> tags (rewards/mean = rewards/max = 0.1000, zero policy-gradient advantage) while grad_norm lingered at 0.24–0.47 purely from differentiating the entropy term. (Why would an entropy bonus accelerate collapse into uniform wrong outputs? Hold that question—we will find the bug when we open the actor source.)
  • Arm C — Raising Rollout Temperature (temperature: 0.2 → 0.6): Breakthrough! Exploration stayed alive, and validation accuracy more than doubled the baseline, climbing from 21.48% (Step 100) to 40.23% at Step 600.

Wave 2: Fine-Tuning LR Around temp = 0.6 (Arms D, C-resume, E, F)

Our celebration lasted ten steps. At Step 610, Arm C abruptly hit 25+ consecutive batches of zero reward and zero gradient (stopped at Step 635)—except this time, logged entropy spiked up to 0.21 instead of dropping to zero. The model wasn’t repeating one deterministic string; it was generating 8 diverse rollouts that were all wrong.

Because temp = 0.6 had unlocked strong learning up to 40.23% and logged a large pre-clip gradient (grad_norm = 21) at Step 609 right before dying, our working hypothesis seemed obvious: temperature fixed exploration, and now we just need gentler late-stage step sizes around Step 600.

We tested four targeted LR variations around temp = 0.6—and every single one failed:

ArmConfiguration (all with temp = 0.6)Hypothesis TestedWhat Actually Happened
Arm Dlr = 1e-7 from scratchSmaller constant LR avoids overshootingLearned at 0.6× speed; peaked at 25.39% (Step 400) and already slid to 21.48% by Step 500
Arm C-resumeResume Step 600 (40.23%) at lr = 5e-7Was Step 610 just one unlucky batch?Collapsed again within 50 steps (Steps 646–653 zero-reward deadlock); instability was structural
Arm EResume Step 600 (40.23%) + drop lr to 1e-7Warm-start at peak, then slow downFell off the plateau within 16 steps (Steps 616–623 had zero correct answers across 8 straight batches despite lr = 1e-7)
Arm FCosine decay 5e-7 → 1e-8 over 1,250 stepsSmoothly anneal step size before Step 600Learned sluggishly (dipping to 1.17% at Step 300) and capped at 28.12% (Steps 600–700) before exiting at Step 706—still 12 points behind Arm C

Wave 3: Pushing Temperature to 0.8 (Arm G) Breaks the Illusion

With LR schedules exhausted, we pushed rollout temperature higher to temperature = 0.8 (Arm G).

At first, Arm G looked triumphant: it surged to a new record of 42.58% pass@1 at Step 400, and completely cured zero-gradient deadlock—running all 1,250 steps with healthy entropy (0.080 at Step 1250) and active gradients throughout.

Yet right after Step 400, accuracy still collapsed all the way to 0.00%! Placing strict arithmetic accuracy (pass@1) side-by-side with mean validation score (mean@1, which includes a 0.1 format bonus) tore the mask off what was happening:

StepBaseline (temp=0.2) pass@1 (mean@1)Arm C (temp=0.6) pass@1 (mean@1)Arm G (temp=0.8) pass@1 (mean@1)
10018.75% (26.84%)21.48% (28.48%)20.70% (28.12%)
2000.00% (0.00%)25.00% (32.38%)26.56% (33.87%)
4000.00% (0.00%)37.11% (43.40%)42.58% (48.32%)
6000.00% (0.00%)40.23% (46.21%)12.89% (21.60%)
8000.00% (0.00%)(stopped after s610 deadlock)10.55% (17.38%)
10000.00% (0.00%)—0.00% (9.69%)
11000.00% (0.00%)—0.39% (8.95%)
12000.00% (0.00%)—0.00% (8.01%)

Stare at the final row of Arm G (Step 1200):

  • pass@1 was 0.00%—zero correct equations out of 256 test problems, and in training critic/rewards/max sat capped at 0.1000.
  • Yet mean@1 stood at 8.01% (nearly every wrong rollout still earned 0.1), logged entropy was 0.036, and actor/grad_norm was roaring at 16.95!

How can a batch with zero correct answers generate massive gradients of 16.95? Hyperparameter tuning had hit a wall. It was time to read the source code line by line.


3. Layer 1 Root Cause — How format_score = 0.1 Hijacks GRPO

Tracing the forward-and-backward path from reward computation to advantage normalization (reward → advantage → policy_loss) immediately answered every mystery from Act I.

The Mechanism: 0.1 Format Bonus × GRPO Std-Normalization = Full-Strength Poison

Comparing Math and Countdown in verl/utils/reward_score/math_reward.py revealed a critical difference:

  • Math uses a strict binary reward $\lbrace 0.0, 1.0 \rbrace$. When all 8 rollouts on a hard problem fail, the group reward vector is $[0, \dots, 0]$—zero variance, zero advantage, zero harmful update.
  • Countdown uses a three-tier reward $\lbrace 0.0, 0.1, 1.0 \rbrace$:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# verl/utils/reward_score/math_reward.py
def countdown_reward_func(solution_str, target, numbers, format_score=0.1):
    answer_pattern = r"<answer>(.*?)</answer>"
    matches = re.findall(answer_pattern, solution_str, re.DOTALL)
    equation = matches[-1].strip() if matches else None

    if equation is None:
        return equation, 0
    if not validate_equation(equation, numbers):
        return equation, format_score      # 0.1 for using wrong numbers!
    result = evaluate_equation(equation)
    if result is None:
        return equation, format_score      # 0.1 for unparseable syntax!
    if abs(result - target) < 1e-5:
        return equation, 1.0
    else:
        return equation, format_score      # 0.1 for wrong arithmetic!

Now plug an all-wrong Countdown group into GRPO’s default advantage estimator (verl/trainer/ppo/core_algos.py, norm_adv_by_std_in_grpo=True, sample standard deviation torch.std with Bessel’s correction, $\epsilon = 10^{-6}$):

1
2
if norm_adv_by_std_in_grpo:
    scores[i] = (scores[i] - id2mean[index[i]]) / (id2std[index[i]] + epsilon)

Suppose none of the $n = 8$ rollouts solve a hard prompt: 7 emit <answer>garbage</answer> (0.1) and 1 fails to close the tag (0.0):

$$
\mathbf{r} = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.0], \qquad \bar{r} = 0.0875, \qquad s = \frac{0.1}{\sqrt{8}} \approx 0.03536
$$

$$
\hat{A}{0.1} = \frac{0.1 - 0.0875}{0.03536 + 10^{-6}} \approx \mathbf{+0.35}, \qquad \hat{A}{0.0} = \frac{0.0 - 0.0875}{0.03536 + 10^{-6}} \approx \mathbf{-2.47}
$$

Symmetrically, if 1 wrong rollout closes <answer>...</answer> while 7 don’t, that wrong answer receives $\hat{A} = +2.47$—the exact same normalized advantage as genuinely solving the problem ($[1.0, 0, \dots, 0]$)!

Checking Step 1 of training showed Dream-v0-Instruct-7B already achieved critic/rewards/max = 1.0 from the very first batch—it never needed format_score = 0.1 to learn <answer> tags. Instead, on every unsolved prompt, dividing a 0.1 tag-formatting fluctuation by $s \approx 0.035$ pumped full-strength gradients into confidently formatted wrong arithmetic. Once accuracy dipped slightly, more groups turned all-wrong, creating a runaway feedback loop that washed pass@1 down to 0.00% while keeping actor/grad_norm around 17 purely on tag-formatting noise.

Mystery Solved: Why Arm B (entropy_coeff = 0.1) Collapsed at Step 141

Auditing verl/workers/actor/llada_dp_actor_d1.py also solved the baffling crash of Arm B. The actor computed “entropy” as:

1
2
probs = log_prob.exp()
entropy = -probs * log_prob  # single sampled token y_t ONLY, not -sum_v p(v) log p(v)!

True vocabulary Shannon entropy is $-\sum_{v \in V} p(v) \log p(v)$. The single-token curve $f(p) = -p \log p$ equals $0$ at both $p = 0$ and $p = 1$, and peaks at $p = 1/e \approx 0.368$. Subtracting entropy_coeff * entropy from the loss did not encourage exploration—it actively pulled high-confidence correct tokens ($p > 0.37$) down toward $0.37$ and low-probability wrong tokens up toward $0.37$! (Note: actor/entropy_loss in our logs records the mean of this same -p(y_t) log p(y_t) surrogate. Because $-p \log p \to 0$ as $p \to 1$, it still validly flags deterministic collapse as a passive metric—it only turns toxic when differentiated as a maximized bonus.)

The Single-Variable Proof (Arms I, J, K)

Armed with the exact mechanism, we stopped guessing schedules and ran three clean 1,250-step tests on Countdown-128:

  • Arm I (temp = 0.8 + Dr.GRPO norm_adv_by_std_in_grpo=False, keeping format_score = 0.1): Same as Arm G, except dividing by $s$ is disabled (shrinking 0.1 vs 0.0 advantages by ~28×).
  • Arm J (temp = 0.2 + strict binary $\lbrace 0, 1 \rbrace$ reward, format_score = 0.0): Strict single-variable control against the collapsing temp = 0.2 baseline—keep every default hyperparameter untouched and only delete the 0.1 format bonus.
  • Arm K (temp = 0.8 + strict binary $\lbrace 0, 1 \rbrace$ reward): High temperature + binary reward.

Countdown-128 Debugging Arc: Act I Mirage vs Layer 1 Proof

Arm (Countdown-128, 1,250 Steps)Step 100Peak pass@1 (Step)Step 1000Final Step 1200Collapsed?
Baseline (temp=0.2 + 0.1 fmt)18.75%18.75% (100)0.00%0.00%Yes (Step ~190 deadlock)
Arm G (temp=0.8 + 0.1 fmt)20.70%42.58% (400)0.00%0.00%Yes (format-hacking washout)
Arm I (temp=0.8 + Dr.GRPO)23.44%38.28% (1200)14.06%38.28%No (mid-run 0.1 drift, late rebound)
Arm K (temp=0.8 + Binary {0,1})14.06%39.06% (600)30.08%8.98%Late high-grad decay (grad ~ 40)
Arm J (temp=0.2 + Binary {0,1})25.00%46.09% (1100)34.77%40.62%No (calm grad 1–6 all 1,250 steps)

Panel (b) settled Countdown-128 decisively: changing format_score from 0.1 to 0.0 alone (Arm J) took the default temp = 0.2 configuration from 0.00% deadlock to 46.09% peak accuracy with zero collapses across all 1,250 steps.

At this point, we thought the case was closed.


4. Act II — Scaling the Winning Recipe to 256 & 512 Broke It Again

We took Arm J’s exact winning recipe (temperature = 0.2, lr = 5e-7, strict binary $\lbrace 0, 1 \rbrace$ reward) and launched Countdown-256 and Countdown-512.

Both collapsed anyway:

  • Countdown-256 (Pre-Fix Binary RM): Started at 13.28% (Step 100), climbed to 39.45% at Step 400, then eroded steadily after Step 500 before cratering to 2.73% at Step 900—staying deadlocked around 3% across 344 consecutive zero-reward, zero-gradient steps (Step 878 to the end).
  • Countdown-512 (Pre-Fix Binary RM): Suffered 84% zero-gradient steps in its first 65 iterations (3.91% at Step 100), clawed up to 29.69% at Step 400, and crashed straight to 6.25% at Step 500 with 40 consecutive zero-gradient steps.
  • Around the same time, our pre-fix Coupled-GRPO run (a variant evaluating three coupled complementary masks per rollout) on Math-512 hit a sudden late cliff too—peaking at 52.52% MATH500 at Step 400, then plummeting in training reward from 0.6328 to 0.0000 at Steps 526–535 (0.00% / 0.00% at Step 600).

Something about crossing from 128 tokens to 256 and 512 tokens was systematically destabilizing training. Comparing the opening-step logs of D1 length 128 vs lengths 256 and 512 gave away the clue: raw actor/grad_norm in early active steps jumped from ~2–5 on Countdown-128 to 16–37 on Countdown-256 and 512—even though the learning rate, batch size, and binary reward were identical.


5. Layer 2 — Two Hidden Systems Bugs (and One Diffusion Detour)

Auditing the actor update loop (verl/workers/actor/llada_dp_actor_d1.py, inherited by verl/workers/actor/dream_dp_actor_d1.py) uncovered two interlocking systems bugs that stayed invisible at 128 tokens and detonated at 256 and 512.

Bug 1: len(data) on a Python dict — A Sequence-Length-Activated Gradient Multiplier

Look closely at what happens inside update_policy() when use_dynamic_bsz = True:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# BEFORE (verl/workers/actor/llada_dp_actor_d1.py)
micro_batches, _ = rearrange_micro_batches(batch=mini_batch, max_token_len=max_token_len)

for data in micro_batches:                      # data is a TensorDict -> len(data) == micro_bsz
    data = data.to(device)
    ...
    for i in range(mc_num):
        data = {                                # BUG: rebinds `data` to a plain Python dict!
            **data,
            "perturbed_seq": perturbed_seq[:, i:i+1],
            "mask_indices": mask_indices[:, i:i+1],
            "p_mask": p_mask[:, i:i+1],
        }
        ...
        if self.config.use_dynamic_bsz:
            # len(data) is NOW 10 (the number of dict keys), NOT micro_bsz!
            loss = policy_loss * (len(data) / self.config.ppo_mini_batch_size)
        loss /= self.mc_num
        loss.backward()

Read that again—it is a textbook Python duck-typing landmine:

  1. rearrange_micro_batches returns a list of TensorDicts. For a TensorDict, len(data) returns the batch size (micro_bsz).
  2. On the very first line of for i in range(mc_num):, data = {**data, ...} shadows data and converts it into a plain Python dict holding the actor’s 10 pre-selected batch tensors (the 3 mask keys overwrite existing entries, leaving 10 keys when use_kl_loss=False and 11 when True).
  3. For a plain dict, len(data) returns the number of keys (10), not the number of samples!

Now do the token arithmetic for Countdown across our 8-GPU setup (train_batch_size = 16, rollout.n = 8 → 16 trajectories per GPU per mini-batch, mean prompt length 167.5 tokens, ppo_max_token_len_per_gpu = 5120):

Response LengthPer-GPU Mini-Batch Tokens $16 \times (167.5 + L)$Dynamic Micro-Batches $K$ ($\le 5120$ tok)True Total Weight $\sum \frac{b_k}{16}$Buggy Total Weight $K \times \frac{10}{16}$Effective Multiplier vs. Length 128
128~4,728 tok1 ([16])1.000×0.625×1.0× (bug hidden!)
256~6,776 tok2 ([8, 8])1.000×1.250×2.0×
512~10,872 tok3 ([6, 5, 5])1.000×1.875×3.0× (+ per-sample skew!)

That single line explains the entire length-dependent mystery on D1:

  • At length 128, the whole 16-sample per-GPU mini-batch fit inside 5,120 tokens (1 micro-batch), so $10 / 16 = 0.625\times$ silently acted as a harmless constant damping factor.
  • Crossing 5,120 tokens at length 256 doubled the effective loss and gradient scale (2.0× vs length 128).
  • At length 512, splitting into 3 micro-batches tripled the effective gradient scale (3.0× vs length 128) and over-weighted smaller micro-batches (5 samples got the exact same $10 / 16$ weight as 6 samples).

The Fix: Remove data variable shadowing (mini_batch / micro_batch / mc_batch), precompute mini_batch_active_tokens before splitting, and weight token-mean loss by the exact active-token fraction so gradients are mathematically invariant to how rearrange_micro_batches partitions the mini-batch:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# AFTER (verl/workers/actor/llada_dp_actor_d1.py)
if loss_agg_mode == "token-mean":
    # Exact mini-batch token-mean weighting: invariant to micro-batch partition
    step_active_tokens = step_response_mask.sum().to(dtype=policy_loss.dtype)
    total_active_tokens = mini_batch_active_tokens[i].to(
        device=policy_loss.device, dtype=policy_loss.dtype
    )
    loss = policy_loss * (step_active_tokens / (total_active_tokens + 1e-8))
elif self.config.use_dynamic_bsz:
    loss = policy_loss * (micro_bsz / mini_batch_size)
else:
    loss = policy_loss / self.gradient_accumulation

While auditing the dynamic-batching path, we also fixed a missing entropys = entropys[revert_indices] permutation bug in compute_log_prob() and replaced an unstable torch.log(1 + diff) KL formula with a numerically safe token-level KL helper (compute_d1_kl_penalty).

Bug 2: AdamW Drift on Zero-Gradient Steps — and the FSDP2 DTensor Sync Trap

Even after fixing len(data), binary $\lbrace 0, 1 \rbrace$ reward at temperature = 0.2 has a distinct training geometry: 63% to 82% of mini-batches have zero group reward variance (every prompt’s 8 rollouts are either all-0 or all-1), producing exact zero gradients ($g_t \equiv 0$).

When self.actor_optimizer.step() runs unconditionally on a zero-gradient step, AdamW is not a no-op:

  1. Decoupled weight decay (weight_decay = 0.01) shrinks every parameter on every empty step: $w_{t+1} = (1 - \eta \lambda) w_t$.
  2. Adam’s moments keep stepping and decaying ($m_t \leftarrow \beta_1 m_t$, $v_t \leftarrow \beta_2 v_t$). (In fact, looking back at our collapsing Countdown-128 baseline in Figure 1b, grad_norm hit exact 0.00 at Step 191 with entropy at 0.0033, yet entropy kept sliding down to 0.0004 by Step 200 purely from residual Adam momentum + weight decay stepping the weights!) Worse, after 20–40 consecutive zero-grad steps, $v_t$ shrinks—so the next rare active gradient hits a depleted denominator and spikes. This exact mechanism also drove Coupled-GRPO Math-512’s sudden Step 526–535 collapse.

Setting weight_decay = 0.0 and skipping optimizer.step() when grad_norm == 0.0 fixes this cleanly—except for one nasty PyTorch FSDP2 gotcha:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# AFTER (verl/workers/actor/llada_dp_actor_d1.py)
def _optimizer_step(self):
    if isinstance(self.actor_module, FSDP):
        grad_norm = self.actor_module.clip_grad_norm_(max_norm=self.config.grad_clip)
    elif isinstance(self.actor_module, FSDPModule):
        grad_norm = fsdp2_clip_grad_norm_(self.actor_module.parameters(), max_norm=self.config.grad_clip)
    else:
        grad_norm = torch.nn.utils.clip_grad_norm_(self.actor_module.parameters(), max_norm=self.config.grad_clip)

    # CRITICAL under PyTorch FSDP2: fsdp2_clip_grad_norm_ returns a DTensor with
    # _NormPartial placement. Materialize the replicated global norm BEFORE .item(),
    # otherwise DP ranks read different local shard norms and diverge on skipping!
    if hasattr(grad_norm, "full_tensor"):
        grad_norm = grad_norm.full_tensor()

    grad_norm_val = grad_norm.detach().item()
    if not math.isfinite(grad_norm_val):
        self.actor_optimizer.zero_grad()
        self._last_step_skipped_zero_grad = False
    elif self.config.get("skip_zero_grad_step", False) and grad_norm_val == 0.0:
        self.actor_optimizer.zero_grad()
        self._last_step_skipped_zero_grad = True
    else:
        self.actor_optimizer.step()
        self._last_step_skipped_zero_grad = False
    return grad_norm

Why .full_tensor() Is Mandatory Under FSDP2

Under PyTorch FSDP2, fsdp2_clip_grad_norm_ returns a DTensor carrying _NormPartial placement. Calling .item() directly evaluates only each rank’s local shard norm—not the global norm! If Rank 0’s local shard happens to have zero gradient while Rank 1’s shard is non-zero, Rank 0 skips optimizer.step() while Rank 1 steps, silently desynchronizing sharded Adam states across data-parallel ranks (and breaking actor/grad_norm logging). Calling grad_norm = grad_norm.full_tensor() first forces the reduction so every rank branches identically. We verified this directly with 2-rank gloo FSDP2 unit tests before touching GPUs.

The Honest Detour: Why Truncating Post-EOS Masks Broke Diffusion RL

Before landing on our final recipe, we made one tempting extra change in our first patched Countdown-256 run: we enabled eos_truncate_loss_mask = True, masking out all tokens strictly after the first <|endoftext|> in each 256-token response.

On paper, it sounded obviously right—Countdown solutions only take 40–80 tokens, so 75–88% of a 256- or 512-token canvas is trailing EOS padding. Why backpropagate policy gradients through 200 EOS tokens?

In practice, EOS truncation backfired spectacularly:

  • Validation stalled between 19.92% and 28.52% (23.83% at Step 600, far behind the old run’s 35–39% climb).
  • Starting around Step 91, average active response length collapsed down to ~18 tokens!
  • actor/pg_loss spiked to +0.47, actor/grad_norm exploded to 484, and from Step 391 to Step 689, 299 consecutive steps (100%) hit zero group variance and froze (our skip_zero_grad_step guard prevented collapse to 0%, leaving the weights frozen in amber).

Two mechanisms collided here:

  1. Length-advantage coupling under token-mean: In Countdown, failed reasoning attempts tend to ramble long while early correct solutions are concise. Truncating post-EOS tokens shrank the token-mean denominator on short batches, creating sharp per-token gradient amplification (actor/grad_norm hitting 484) that rapidly pushed the policy to emit ultra-short ~18-token completions.
  2. Fixed-canvas masked diffusion semantics: Autoregressive LMs stop generating at EOS, so post-EOS tokens never exist at inference. Masked diffusion LMs denoise a fixed-length canvas in parallel—masking out post-EOS positions during RL removes the supervision signal that keeps the trailing canvas cleanly populated with EOS.

So we cut the clever trick and settled on the minimal systems patch: keep eos_truncate_loss_mask = False, retaining only exact dynamic-batch token-mean weighting (fixing len(data)), FSDP2-synced skip_zero_grad_step = True, and weight_decay = 0.0 on top of the binary $\lbrace 0, 1 \rbrace$ reward.


6. The Controlled Proof: D1 (256 / 512) and Porting to Coupled-GRPO

Keeping every D1 hyperparameter strictly identical (temperature = 0.2, lr = 5e-7, train_batch_size = 16, rollout.n = 8, ppo_max_token_len_per_gpu = 5120, binary $\lbrace 0, 1 \rbrace$ reward), switching from the pre-fix actor to the minimal systems patch completely eliminated collapse at both 256 and 512 response lengths—and combining the binary reward + systems patch stabilized Coupled-GRPO (ppo_max_token_len_per_gpu = 4096, enable_gradient_checkpointing = True) out of the box:

Layer 2 Proof: D1 256 & 512 and Coupled-GRPO Generalization

Run (Binary {0,1} RM, temp=0.2, lr=5e-7)Step 100Peak pass@1 (Step)Step 1000Latest / FinalOutcome
D1 Countdown-256 Pre-Fix13.28%39.45% (400)3.52%3.12% (1200)Crashed; 344 zero-grad steps from s878
D1 Countdown-256 (+EOS Detour)19.92%28.52% (500)—23.83% (600)~18-token collapse; 299 frozen steps
D1 Countdown-256 Fixed11.33%39.84% (1000)39.84%38.67% (1200)Complete (1,250 steps, 0 collapse)
D1 Countdown-512 Pre-Fix3.91%29.69% (400)—6.25% (500)Crashed at s500; 40 zero-grad steps
D1 Countdown-512 Fixed11.72%35.55% (1000)35.55%32.81% (1100)0 collapse (74h wall-clock cap at s1159)
Coupled-GRPO Countdown-128 Fixed34.77%38.67% (1200)36.72%37.89% (1250)Complete (1,250 steps, 0 collapse)
Coupled-GRPO Countdown-256 Fixed26.17%35.55% (200)—31.64% (800)Running cleanly (Step 836 / 1250)
Coupled-GRPO Countdown-512 Fixed35.16%35.16% (100)—35.16% (100)Running cleanly (Step 188 / 1250)

What Porting to Coupled-GRPO Uncovered

Unlike D1, pre-fix verl/workers/actor/llada_dp_actor_coupled_grpo.py evaluated all mc_num = 3 coupled masks in one forward call without an inner loop, so its text-only path avoided D1’s dict shadowing (only its multimodal DataProto branch hit len(dict)), though it still lacked exact active-token token-mean micro-batch weighting, FSDP2 zero-grad step skipping, weight_decay = 0.0, and safe KL. Auditing the file line by line while porting those fixes turned up three additional Coupled-GRPO bugs:

  1. Missing entropys = entropys[revert_indices] after dynamic-bsz unpacking in compute_log_prob().
  2. Missing [:, -response_length:] slicing when passing entropy and ref_log_probs into agg_loss() (causing shape mismatches whenever entropy_coeff != 0 or use_kl_loss = True).
  3. Dividing logged actor/pg_loss by mc_num = 3 even though Coupled-GRPO already returns a single aggregated policy loss across the three coupled masks.

With all fixes verified by 35/35 unit tests across both actors, Coupled-GRPO Countdown-128 ran all 1,250 steps cleanly (38.67% peak at Step 1200, 37.89% final at Step 1250) and Countdown-512 jumped to 35.16% on Step 100 alone.


7. Where the Fix Stops Working: The Sudoku Counterexample

It is tempting to end a debugging post on a victory lap. Sudoku kept us honest.

We applied the exact same patched D1 actor (fixed len(data), exact token-mean, FSDP2-synced skip_zero_grad_step=True, weight_decay=0.0, eos_truncate_loss_mask=False, use_kl_loss=False) to 4×4 Sudoku at response lengths 128, 256, and 512—keeping Sudoku’s default continuous cell-level reward function (sudoku_reward_func, which scores correct_cells / num_empty_cells, typically out of 9 empty cells).

The systems patch prevented the instant Step-100 crash we had seen pre-fix—yet Sudoku still degenerated across all three lengths:

  • Sudoku-128: Held 24–26% cell accuracy (mean@1) through Step 1250, with 0.00% full-grid solve rate (pass@1) after Step 500. Inspecting completions revealed classic reward hacking: the model converged to outputting constant 1111111111111111..., locking in a risk-free ~25% cell match!
  • Sudoku-256: Peaked at 26.30% cell accuracy (0.80% pass@1) at Step 200, held 22.25% through Step 800, then collapsed at Step 841 into emitting empty <answer>\n</answer> tags (22.25% → 2.30% → 0.00%).
  • Sudoku-512: Peaked at 26.55% cell accuracy at Step 400 (pass@1 never exceeded 0.60% at Step 100 and hit 0.00% at Step 1000 as cell accuracy drifted down to 13.85% before the 74-hour cap at Step 1074).

Comparing the internal training telemetry of Countdown vs. Sudoku over the first 800 steps under the identical patched actor immediately exposed why one stabilized and the other collapsed:

Metric (First 800 Steps, Identical Patched Actor)D1 Countdown-256 / 512 (Binary {0, 1})D1 Sudoku-128 / 256 / 512 (Continuous cells / 9)
Active Non-Zero-Grad Update Rate36.6% / 25.5% (29.5% / 18.0% full run)100.0% (0% skipped)
Median Active Unclipped actor/grad_norm5.02 / 8.3468.81 / 62.64 / 32.35 (4–14× larger!)
Peak Unclipped actor/grad_norm151.67 / 53.84662.17 / 641.20 / 252.17
Late-Stage Failure Mode (use_kl_loss=False)None (sustained 33–40% solve rate)Constant 1111... hacking (128) or empty <answer> collapse (256)

The underlying mechanism is the exact same reward-geometry trap as format_score = 0.1, just disguised as dense partial credit:

  • Dream-v0-Instruct-7B starts near 0% full-grid Sudoku solve rate, yet random digit guesses on 9 empty cells produce noisy scores like $2/9$ vs $3/9$ in every single group of 8 rollouts.
  • Because group variance is never zero, skip_zero_grad_step never triggers, and norm_adv_by_std_in_grpo = True normalizes random-guess fluctuations into full-strength updates on 100% of steps—pumping an order of magnitude stronger noisy gradients into an unregularized (use_kl_loss = False) policy until it slips into a degenerate attractor (1111... or empty tags).

The boundary is clear: systems fixes (len(data), FSDP2 skip_zero_grad_step, weight_decay = 0.0) protect a clean, sparse binary signal from being destroyed by optimizer and batching bugs—but they cannot turn a dense-noise, zero-KL reward landscape into a learnable one.


8. Practical Checklist & Open Caveats

Pre-Flight Checklist for GRPO & Diffusion RL

  1. Audit your reward against GRPO std-normalization before tuning anything. Any small auxiliary reward (format_score = 0.1) or dense partial-credit metric (correct_cells / num_empty_cells when full-solve rate is near 0%) gets magnified by $1 / s$ on all-wrong groups into full-strength destructive gradients. If your base model already knows the output format, use strict binary $\lbrace 0, 1 \rbrace$ rewards—or turn off std-normalization (norm_adv_by_std_in_grpo = False) and add KL anchoring.
  2. Audit actor/pg_clipfrac, actor/ppo_kl, and critic/rewards/max—never just mean reward. Seeing actor/pg_clipfrac $\equiv$ 0 immediately tells you PPO has degraded into unclipped REINFORCE (ppo_mini_batch_size == train_batch_size with ppo_epochs = 1); seeing critic/rewards/max capped at 0.10 with actor/grad_norm around 17 immediately exposes format-score hacking.
  3. Never trust len(batch) under use_dynamic_bsz = True. Python dict unpacking ({**td, ...}) silently changes len() from batch size to key count. Write a unit test asserting exact gradient equivalence across 1, 2, 3, and $k$ micro-batches under token-mean.
  4. Guard zero-gradient steps—and materialize FSDP2 DTensor norms first. Under sparse binary rewards, skip optimizer.step() when global grad_norm == 0.0 (with weight_decay = 0.0), and always call grad_norm = grad_norm.full_tensor() before .item() under PyTorch FSDP2 so ranks never diverge on skipping.
  5. Don’t blindly port autoregressive EOS truncation to masked diffusion LMs. Fixed-canvas diffusion models denoise trailing positions in parallel; truncating post-EOS loss masks under token-mean can trigger length-advantage coupling and severe length collapse.
  6. When a bug only appears at longer sequence lengths (256 / 512), suspect token-budget micro-batching thresholds first. Check ppo_max_token_len_per_gpu before blaming the learning rate or sequence difficulty.

Open Caveats

  • Coupled systems fixes in the final patch: Our minimal systems patch landed three fixes simultaneously (exact token-mean / len(data) scaling, FSDP2-synced skip_zero_grad_step = True, and weight_decay = 0.0). While each has an explicit analytical mechanism and standalone unit-test coverage, running separate single-variable ablations of len(data) alone vs. skip_zero_grad_step + weight_decay = 0.0 alone would cleanly quantify how much of the 256/512 stability gain belongs to each.
  • Evaluation variance & single seed: Countdown’s validation set contains 256 test problems, giving a binomial standard error of ~3.0 percentage points around 35–40%. That explains normal 2–5 point evaluation jitter across adjacent checkpoints, while the separation between collapse (0–6%) and sustained plateaus (35–46%) exceeds 10 standard errors.
  • Wall-clock limits & in-progress runs: D1 Countdown-512 (Fixed) reached a 74-hour job wall-clock limit cleanly at Step 1159 (Step 1000 = 35.55%, Step 1100 = 32.81%, zero errors). At the time of writing, Coupled-GRPO Countdown-128 has completed all 1,250 steps (38.67% peak at Step 1200 / 37.89% final at Step 1250), while Coupled-GRPO Countdown-256 (Step 836, 35.55% peak) and Countdown-512 (Step 188, 35.16% at Step 100) are still running toward Step 1250.