Open the workspace
Algorithms 101

BOND (Best-of-N distillation), explained

How BOND distils Best-of-N sampling into one policy: the exact BoN distribution, Jeffreys divergence, J-BOND with an EMA anchor, costs and a toy run.

BOND (Best-of-N Distillation) is an RLHF method that trains a policy to produce, in one sample, the distribution of answers you would get by drawing samples from the reference model and keeping the one a reward model scores highest. Best-of-N sampling is one of the strongest and simplest ways to spend a reward model at inference time, but it multiplies serving cost by . BOND moves that cost into training. It treats alignment as distribution matching: derive the Best-of-N distribution analytically, then minimise a divergence between the policy and that target, using a mix of supervised learning on Best-of-N samples and a policy-gradient term. Its practical form, J-BOND, distils Best-of-2 of a slowly moving anchor over and over, which compounds into Best-of- without ever choosing or a KL coefficient. It sits in the post-training stack where PPO-style RLHF or REINFORCE with a leave-one-out baseline would, after SFT and reward modelling.

The problem and where it came from#

Best-of-N has been part of RLHF since Stiennon et al. (2020) used it as a baseline for summarisation, and Gao, Schulman and Hilton (2022) used it to measure reward over-optimisation because it is so well behaved: the policy it defines is a simple reweighting of the reference, and its KL from the reference grows only logarithmically in . Fine-tuning on Best-of-N outputs (the forward-KL direction, as in rejection-sampling fine-tuning) was already common, but it only covers the mode-covering half of the problem.

BOND was introduced by Sessa, Dadashi, Hussenot, Ferret, Vieillard, Ramé and colleagues at Google DeepMind (2024). The paper makes four contributions: an exact expression for the Best-of-N distribution, the observation that this distribution is the solution of a KL-regularised RL problem with a specific reward and coefficient, the use of the Jeffreys divergence (a mix of forward and backward KL) as the matching objective, and an iterative scheme with a moving anchor that reaches large effective cheaply. They reported a better KL-reward Pareto front than REINFORCE on Gemma 7B and stated that J-BOND was used to fine-tune Gemma 1.1, RecurrentGemma and CodeGemma 1.1. Concurrently, Amini, Vieira, Ash and Cotterell (2024) proposed variational BoN, which matches the same target with the backward KL only.

The objective, with every symbol defined#

The Best-of-N distribution

Fix a prompt and drop it from the notation. is the reference policy, is the reward of a generation , and ties are broken by any fixed strict order. Define the probability that a fresh reference sample is strictly worse than , and the probability that it is not better:

Best-of-N returns exactly when the best of independent samples is . The probability that all samples are at most as good as is , and that all are strictly worse is ; the difference is the probability that the maximum is . BOND's Theorem 1 writes the same quantity in a factored form:

Term (A) is an exponential penalty on generations with low reward quantile. Term (B) is a correction for the chance of drawing the same generation more than once; it lies in and equals for continuous distributions, so for long text outputs it is essentially a constant.

Best-of-N is a KL-regularised RL solution

The policy that maximises for any reward is , the same closed form that DPO builds on. Taking logs of Theorem 1 shows that has exactly this form with

Two consequences follow. plays the role of the KL coefficient, so choosing is choosing how far the policy may move. And the effective reward is the log of the reward quantile, which depends only on how ranks against reference samples: it is invariant to any monotone transformation of the reward model's scores, and because the log is concave it punishes being bad much more than it rewards being excellent. The authors conjecture both properties help against reward hacking. Beirami et al. (2024) showed that the widely quoted value for is an upper bound, tight only when individual generations have negligible probability.

The Jeffreys objective and its two gradients

BOND minimises the generalised Jeffreys divergence with weight (a different from the RL coefficient):

The forward term is supervised learning on Best-of-N samples, mode-covering:

The backward term is a policy gradient, mode-seeking, with the BOND reward and an implicit KL penalty to the reference:

The quantile is estimated by Monte Carlo: draw reference samples and set . The paper's XSum experiments used , and the correction term (B) was dropped because it made no measurable difference. Forward KL alone spreads mass and lags on reward; backward KL alone collapses entropy; reduced both divergences to and raised reward quantiles about as fast as the pure backward objective.

Iterating with a moving anchor, and J-BOND

Best-of-N of a Best-of-N distribution is Best-of- of the original. So instead of picking a large , BOND can repeatedly distil Best-of- of an anchor policy and then move the anchor to the current policy: after rounds the target is Best-of- of . J-BOND fixes and replaces the periodic anchor swap by an exponential moving average of the policy weights, . With only two anchor samples per prompt, is too noisy, so the backward term uses a calibrated surrogate:

A generation is punished only when it loses to both anchor samples, which mimics the concavity of . The constant makes the surrogate exact in expectation for a median generation: if , the chance of losing to both anchors is and . The full update is , where is the negative log-likelihood gradient on the better of the two anchor samples, is a policy gradient with return and a leave-one-out baseline, and is an extra KL penalty toward the anchor with weight .

One J-BOND step for one prompt policy πθ 1 sample y EMA anchor 2 samples y′1, y′2 reward model only rankings used forward KL (weight 1 − β) NLL on the better anchor sample backward KL (weight β) y loses to both: reward −log 16 KL to anchor (weight γ) then θ_anchor ← (1 − η) θ_anchor + η θ Three generations per prompt per step; no value network; anchor log-probs come from a second set of weights.
J-BOND per prompt: one policy sample, two anchor samples, one comparison against the reward model, three gradient terms. Each round distils Best-of-2 of the anchor; because the anchor tracks the policy, the effective N keeps doubling.

Worked example: Best-of-2 on four answers#

Suppose a prompt has four possible answers with reference probabilities and rewards , so the best answer is the least likely. The cumulative probabilities are and . For :

The worst answer drops from 40% to 16% (it must be drawn twice), the best almost doubles, and the expected reward rises from 2.00 to 2.54. The KL from the reference is nats, below the textbook because these answers have large individual probabilities. For the same formula gives , expected reward 3.08 and KL 0.587 against the bound 0.636. Term (B) matters at this scale: dropping it and renormalising would give for , a visibly different distribution. For real text, where no single answer has meaningful probability, (B) is a constant and can be ignored, which is what the paper does.

Now the J-BOND surrogate for the second answer, whose quantile is . It loses to both anchor samples when both are strictly better, probability , so its expected surrogate reward is , against the ideal . The surrogate is exact at the median and somewhat optimistic above it, which is a deliberate trade for using only two anchor samples.

A toy run: exact Best-of-N, J-BOND and REINFORCE#

We built a single-prompt problem with 200 possible responses, reference logits drawn from and rewards from (numpy, seed 0), so the reference has entropy 4.58 nats and expected reward . First we checked Theorem 1: for the analytic matched 200,000 simulated Best-of-N draws to a total variation distance between 0.009 and 0.0015, which is sampling noise. The exact KLs were 0.193, 0.636, 1.203, 1.826 and 3.071 nats against bounds of 0.193, 0.636, 1.204, 1.835 and 3.175: tight for small and loose by 0.1 nats at , where the best responses start to repeat. Expected reward rose to 0.468, 1.052, 1.603, 2.099 and 2.771.

Then we trained a tabular softmax policy with sampled gradients, batch 64, learning rate 0.02, 6,000 steps, using J-BOND as specified above (, EMA , ) and, for comparison, REINFORCE on with a leave-one-out baseline.

Reward against KL from the reference (toy, 200 responses) -0.5 0 0.5 1 1.5 2 2.5 3 0 0.5 1 1.5 2 2.5 3 3.5 KL(policy || reference), nats expected reward optimal KL-regularised policy exact Best-of-N, N = 1 to 64 J-BOND trajectory (6,000 steps) REINFORCE, beta = 1
Expected reward against KL from the reference in the 200-response toy. Green points are the exact Best-of-N distributions; the solid cobalt line is one J-BOND run sampled every 50 steps; the dashed cobalt line is REINFORCE with KL coefficient 1; the grey dashed line is the analytic optimum for each KL. Seeded numpy run.

Three results are worth stating plainly. First, J-BOND traced the Best-of-N curve: it passed through KL 0.34 at reward 0.65 (step 1,500) and KL 1.67 at reward 1.80 (step 2,000), close to and slightly below the exact Best-of-N points, and both sit below the optimal KL-regularised frontier , which by construction is the best reward for a given KL. Second, it never stopped: by step 6,000 it had reached KL 3.21 and reward 2.535 with an expected log-quantile of , essentially the top response, because a moving anchor keeps compounding the effective . The KL budget is set by when you stop, not by a coefficient. REINFORCE with instead converged toward its fixed point (KL 0.73, reward 1.25 at step 6,000), and with it went to the top response within about 1,500 steps. Third, the invariance is real and exact: multiplying every reward by 10 produced a bit-identical J-BOND trajectory, while REINFORCE at with the scaled reward jumped to KL 3.17 within 250 steps. In this toy the reward-KL frontier of J-BOND was not better than REINFORCE's; what it bought was robustness to the reward scale and the absence of a coefficient to tune. The paper's reported Pareto improvement on Gemma comes from a setting (a learned reward model, long generations, many prompts) that a tabular toy cannot reproduce.

The algorithm step by step#

inputs: prompts D, SFT policy pi_ref, reward model r, beta=0.5, eta=0.02, gamma>=0
pi = copy(pi_ref); anchor = copy(pi_ref)               # anchor is an EMA of pi's weights
for step in range(T):
    x = sample_batch(D)                                 # e.g. 128 prompts
    y      = pi.generate(x)                             # 1 policy sample per prompt
    a1, a2 = anchor.generate(x), anchor.generate(x)     # 2 anchor samples per prompt
    s, s1, s2 = r(x, y), r(x, a1), r(x, a2)
    best = where(s1 >= s2, a1, a2)
    # forward KL: supervised loss on Best-of-2 of the anchor
    L_fw = -logp(pi, x, best)
    # backward KL: policy gradient with the J-BOND reward and an anchor KL in the return
    r_j = where(s < min(s1, s2), -log(16), 0.0)
    R   = r_j - (logp(pi, x, y) - logp(anchor, x, y)).detach()
    A   = R - leave_one_out_mean(R)
    L_bw = -(A * logp(pi, x, y))
    L_reg = ((logp(pi, x, y) - logp(anchor, x, y)).detach() * logp(pi, x, y))   # score-function KL estimate
    loss = mean((1 - beta) * L_fw + beta * L_bw + gamma * L_reg)
    loss.backward(); opt.step(); opt.zero_grad()
    anchor.weights = (1 - eta) * anchor.weights + eta * pi.weights
    log: reward of y, KL(pi || pi_ref) estimate, win rate of y vs anchor samples

Data needs are those of online RLHF: a prompt set (thousands to hundreds of thousands of prompts), a reward model, and no labelled responses. Every step generates three completions per prompt, one from the policy and two from the anchor, and scores them. There is no critic. The anchor is a second set of weights that must be kept in memory and used for generation and log-probabilities, which is the main structural cost compared with REINFORCE against a fixed reference.

Non-iterative BOND, as in the paper's XSum experiments, is also simple: fix , draw reference samples per prompt to estimate quantiles (16 in the paper), compute for policy samples, and combine the supervised loss on a Best-of-N sample with the policy gradient. It is useful when you have a specific you want to match, for example to replace an existing Best-of-16 serving setup.

Hyperparameters that matter#

HyperparameterPaper valueEffect and tuning
Jeffreys weight 0.50 is supervised Best-of-N distillation (spread out, slow on reward); 1 is pure policy gradient (entropy collapse risk)
Anchor EMA rate 0.02 (also 0.01 to 0.1 ablated)Faster anchor, faster reward gain and faster KL growth. 0.02 behaved like a hard update every 50 steps but with lower KL
Anchor KL weight 0 to 2 ablatedLarger slows movement away from the reference and improved the reward-KL trade-off on Gemma 2B
Learning rate3e-6, Adam, 100 warm-up stepsIn the usual range for full-weight RLHF of a 2B to 7B model
Batch128 promptsLeave-one-out baseline needs at least 2
and (non-iterative BOND), Larger means more KL budget and more sensitivity to quantile errors, since

The one decision J-BOND leaves you is when to stop. Treat it like a KL budget: log the KL to the reference and a held-out reward or win rate at regular checkpoints, and pick the checkpoint on that curve, as you would pick for Best-of-N serving.

Compute and memory cost#

Per prompt and step, J-BOND generates three sequences, scores three, and runs forward and backward on two (the policy sample and the Best-of-2 anchor sample) plus anchor forward passes for log-ratios. REINFORCE with a leave-one-out baseline and two samples generates two and backpropagates through two; PPO generates fewer but trains a critic. Generation dominates wall-clock time in online RLHF, so expect J-BOND to cost about 1.5 times a two-sample REINFORCE step. Memory holds the policy with optimiser state (about 16 bytes per parameter in mixed precision), an anchor copy in bf16 (2 bytes per parameter), the reward model, and optionally the frozen reference for monitoring. That is one more model copy than REINFORCE against a fixed reference. The amortisation argument is the point of the method: if the alternative is serving Best-of-16, every request costs 16 generations and 16 reward-model calls forever, while BOND pays once in training.

Failure modes and how to detect them#

Running past the useful KL

Because the anchor keeps moving, J-BOND keeps increasing the effective . In our toy it ended on the single top response. With a learned reward model, that end point is where over-optimisation lives (Gao et al., 2022). Watch held-out reward from a different reward model or human or LLM-judge win rates as a function of KL; stop where the curve bends.

Entropy collapse

Too much backward-KL weight or a fast anchor drives per-token entropy down and makes samples repetitive. Track mean token entropy and distinct-n over a fixed prompt set. Lower , lower or raise .

Noisy quantiles

For non-iterative BOND with large , errors in are amplified by the power . Symptoms are high-variance policy gradients and a reward curve that does not improve with more steps. Use more reference samples per prompt or switch to the iterative form with small .

Reward model ties and miscalibration

Only rankings matter, so a reward model that gives many responses the same score (or saturates near a maximum) makes and diverge and turns comparisons into coin flips. Check the fraction of tied comparisons in a batch. Rank invariance also means a reward model that is well ranked but poorly calibrated is fine for BOND and not for REINFORCE.

When to use it, and what to use instead#

SituationUse
You already serve Best-of-N with a reward model and want the quality at one sampleBOND with that , or J-BOND stopped at the matching KL
Online RLHF where the reward scale drifts or differs across promptsJ-BOND, which uses only rankings
Verifiable rewards (tests, exact answers)GRPO or RLVR; binary rewards make quantiles coarse
Offline preference pairs, no reward modelDPO or its variants
Simplest possible use of a reward modelRejection-sampling fine-tuning (the forward-KL half of BOND)
Compact, critic-free online RL with scalar rewardsRLOO

Minimal implementation#

A J-BOND loss in PyTorch for a causal LM, given sequence log-probabilities computed with response masks. Generation and reward scoring are left to whatever rollout stack you use; the open-source TRL library provides the sampling and log-probability plumbing for online methods.

import math, torch

def seq_logp(model, input_ids, attn, resp_mask):
    logits = model(input_ids=input_ids, attention_mask=attn).logits[:, :-1]
    lp = torch.log_softmax(logits.float(), -1).gather(-1, input_ids[:, 1:, None]).squeeze(-1)
    return (lp * resp_mask[:, 1:]).sum(-1)

def jbond_loss(policy, anchor, batch_y, batch_best, r_y, r_a1, r_a2, beta=0.5, gamma=0.0):
    # batch_y: the policy sample; batch_best: the better of two anchor samples (tuples of ids, mask, resp_mask)
    lp_best = seq_logp(policy, *batch_best)
    lp_y = seq_logp(policy, *batch_y)
    with torch.no_grad():
        lpa_y = seq_logp(anchor, *batch_y)
        log_ratio = lp_y.detach() - lpa_y
        r_j = torch.where(r_y < torch.minimum(r_a1, r_a2), -math.log(16.0), 0.0)
        R = r_j - log_ratio
        n = R.numel()
        A = R - (R.sum() - R) / (n - 1)                      # leave-one-out baseline
    loss_fw = -lp_best.mean()
    loss_bw = -(A * lp_y).mean()
    loss_reg = (log_ratio * lp_y).mean()                     # gradient of KL(pi || anchor)
    return (1 - beta) * loss_fw + beta * loss_bw + gamma * loss_reg

@torch.no_grad()
def ema_update(anchor, policy, eta=0.02):
    for pa, pp in zip(anchor.parameters(), policy.parameters()):
        pa.mul_(1 - eta).add_(pp.detach().to(pa.dtype), alpha=eta)

Keep the anchor in bf16 and do the EMA in fp32 if you can afford it; at a bf16 accumulator rounds away much of each update. In POFE, J-BOND is a recipe next to RLOO and GRPO, with KL-to-reference and held-out win rate logged at every checkpoint so the stopping point is a choice you make from a curve.

Further reading#

Sessa et al. (2024) is the BOND paper; Section 3 has the derivation and Section 5 the practical algorithm. Amini et al. (2024) is the concurrent variational BoN, with the same target and backward KL only. Beirami et al. (2024) corrects the KL formula and bounds the win rate of Best-of-N by . Gao, Schulman and Hilton (2022) is the reference for over-optimisation as a function of KL, and Ramé et al. (2024, WARP) motivates the EMA anchor. Ahmadian et al. (2024) describes the REINFORCE leave-one-out baseline that J-BOND's backward term uses and that the paper compares against.

Frequently asked questions#

What is the Best-of-N distribution?

The probability that a generation y is returned by Best-of-N equals p_le(y)^N minus p_lt(y)^N, where p_le and p_lt are the probabilities that a reference sample scores no better, or strictly worse, than y. For long text this is approximately N times pi_ref(y) times p_le(y)^(N-1).

How is BOND related to standard RLHF?

Best-of-N is exactly the solution of KL-regularised RL with reward equal to the log reward quantile and KL coefficient 1/(N-1). So N acts as the regularisation strength, and the reward depends only on rankings, not on the reward model's scale.

Why does BOND use the Jeffreys divergence?

Forward KL (supervised learning on Best-of-N samples) covers modes but spreads mass and lags on reward. Backward KL (a policy gradient) seeks modes but can collapse entropy. A 50/50 mix reduced both divergences and raised reward quantiles about as fast as backward KL alone in the paper's XSum experiments.

What is J-BOND?

The practical algorithm: per prompt, draw one policy sample and two samples from an exponential moving average anchor, do supervised learning on the better anchor sample, and give the policy sample a reward of minus log 16 if it loses to both. Repeated Best-of-2 distillation of a moving anchor compounds into Best-of-2^M.

How do I choose N or the KL coefficient with J-BOND?

You do not set either. KL from the reference grows as training proceeds, so you choose a checkpoint by plotting held-out reward or win rate against KL and stopping where gains flatten or over-optimisation starts.

Is BOND better than PPO or REINFORCE?

The paper reports a better KL-reward Pareto front than REINFORCE with several KL coefficients on Gemma 7B. In our tabular toy the frontier was similar; the clear advantages were invariance to reward scale and not having to pick a coefficient.

References#

  1. Pier Giuseppe Sessa, Robert Dadashi, Léonard Hussenot, Johan Ferret, Nino Vieillard, Alexandre Ramé, et al. (2024). BOND: Aligning LLMs with Best-of-N Distillation. arxiv.org/abs/2407.14622
  2. Afra Amini, Tim Vieira, Elliott Ash, Ryan Cotterell (2024). Variational Best-of-N Alignment. arxiv.org/abs/2407.06057
  3. Ahmad Beirami, Alekh Agarwal, Jonathan Berant, Alexander D'Amour, Jacob Eisenstein, Chirag Nagpal, Ananda Theertha Suresh (2024). Theoretical guarantees on the best-of-n alignment policy. arxiv.org/abs/2401.01879
  4. Leo Gao, John Schulman, Jacob Hilton (2022). Scaling Laws for Reward Model Overoptimization. arxiv.org/abs/2210.10760
  5. Nisan Stiennon, Long Ouyang, Jeff Wu, Daniel M. Ziegler, Ryan Lowe, Chelsea Voss, Alec Radford, Dario Amodei, Paul Christiano (2020). Learning to summarize from human feedback. arxiv.org/abs/2009.01325
  6. Alexandre Ramé, Johan Ferret, Nino Vieillard, Robert Dadashi, Léonard Hussenot, et al. (2024). WARP: On the Benefits of Weight Averaged Rewarded Policies. arxiv.org/abs/2406.16768
  7. Arash Ahmadian, Chris Cremer, Matthias Gallé, Marzieh Fadaee, Julia Kreutzer, Olivier Pietquin, Ahmet Üstün, Sara Hooker (2024). Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs. arxiv.org/abs/2402.14740

Bring a model and a metric.

Tell us what the model should get better at. A post-training engineer replies within one business day with a plan, a compute estimate and an eval design.