Compute a token-level clipped policy loss with asymmetric clipping

HardAlignmentPro

Why it matters Clip-higher and token-level averaging are among the changes recent open RL recipes for reasoning models introduced on top of GRPO.

Recent RL recipes for reasoning models make two changes to the PPO-style objective: a larger upper clip range (clip-higher) so rare good tokens can grow, and averaging over all tokens in the batch instead of per sequence so long answers are not under-weighted.

Write token_clip_loss(logp_new, logp_old, adv, mask, eps_low=0.2, eps_high=0.28). logp_new and logp_old are (B, T) token log-probs, adv is (B,) one advantage per sequence, mask is (B, T) with 1 on generated tokens. With ratio = exp(logp_new - logp_old) and A broadcast over tokens:
obj = min(ratio * A, clip(ratio, 1 - eps_low, 1 + eps_high) * A)
loss = -sum(obj * mask) / sum(mask)
clip_frac = fraction of masked tokens where the clipped term is strictly smaller than the unclipped one.
Return (loss, clip_frac) as floats.

Signaturedef token_clip_loss(logp_new, logp_old, adv, mask, eps_low=0.2, eps_high=0.28)

Example

logp_new = [[0, 0]], logp_old = [[0, 0]], adv = [1], mask = [[1, 1]] gives (-1.0, 0.0).

Understand the idea

PPO-style training limits how far one update can move each token's probability, using the ratio new / old. If the ratio leaves [1 - eps, 1 + eps], the gradient is cut. Two refinements came from RL on long reasoning answers.

Clip-higher: a token with old probability 0.01 can only rise to 0.012 with eps = 0.2. A larger upper bound (for example 0.28) lets rare but good tokens grow faster, which helps keep exploration alive.

Token-level averaging: if you average per sequence, a 2000-token answer and a 20-token answer each count once, so every token in the long one gets 100 times less weight.

Example: ratio 1.35 with advantage +1 and range [0.8, 1.28]. Unclipped 1.35, clipped 1.28: the objective uses 1.28 and that token counts as clipped.

Rule: obj = min(r A, clip(r, 1 - eps_low, 1 + eps_high) A); loss = -sum(obj m) / sum(m).

These changes were popularised by the DAPO recipe.

Shapes and data flow

logp_new, logp_old, mask (B, T); adv (B,) -> (B, 1) -> obj (B, T) -> scalar loss
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampletoken_clip_loss([[0.0, 0.0]], [[0.0, 0.0]], [1.0], [[1, 1]])
  • Sample 2: long vs shorttoken_clip_loss([[0.1, 0.4, -0.2, 0.0], [0.5, 0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]...