Compute RLOO leave-one-out baselines

Why it matters RLOO is a simple, strong baseline for RL fine-tuning of LLMs that needs no value network.

RLOO (REINFORCE leave-one-out) samples k answers per prompt and uses the average reward of the OTHER k - 1 answers as each answer's baseline, so the baseline never depends on the answer itself.

Write rloo_advantages(rewards). rewards is (P, k) with k >= 2. For each element, adv = r_i - (sum of the row - r_i) / (k - 1). Return the (P, k) float array. Raise ValueError if k < 2.

Signaturedef rloo_advantages(rewards)

Example

rloo_advantages([[1, 0, 0, 1]]) is [[0.6667, -0.6667, -0.6667, 0.6667]].

Understand the idea

A policy gradient needs a baseline: you reward an answer for being better than expected, not just for being good. RLOO uses the other answers to the same prompt as "what to expect", like judging a runner against the average of the other runners in the race, not including themselves.

Example: four answers with rewards 1, 0, 0, 1. For the first answer, the others average (0 + 0 + 1) / 3 = 0.333, so its advantage is 1 - 0.333 = 0.667. For the second, the others average 2 / 3, so its advantage is -0.667.

Rule: A_i = r_i - (sum_j r_j - r_i) / (k - 1).

Leaving the sample out keeps the gradient estimate unbiased, since the baseline does not depend on the answer being scored. Note RLOO's advantage equals the group-mean advantage times k / (k - 1), so the difference is a scale, but it matters when mixing group sizes.

Shapes and data flow

rewards (P, k) -> row sums (P, 1) -> baselines (P, k) -> adv (P, k)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplerloo_advantages([[1, 0, 0, 1]])
  • Sample 2: two promptsrloo_advantages([[0.2, 0.8], [0.5, 0.1]])
  • Test 3: one sample_raises(lambda: rloo_advantages([[1.0]]))