If you have a reward model, you can “improve” a policy without any RL: sample N responses and keep the one with the highest reward. That is best-of-N (BoN). It is so simple that it is usually treated as a baseline, yet BoN comes surprisingly close to the KL-regularised optimum, and its training-time counterpart, rejection sampling fine-tuning, appears in most recipes from Llama 2 to DeepSeek-R1.
Best-of-N: the distribution of the maximum
Let be the policy that draws independently from and returns . Assume rewards are continuous with no ties, and let be the CDF of the reward under . Then the CDF of the maximum is and its density is
As N grows, the whole distribution is pushed up into the upper tail. If rewards are standard normal, the expected maximum grows roughly like (asymptotically). The cost is linear in N, but the gain is . Going from N = 4 to 16 and from 64 to 256 costs the same factor of 4, but the gain keeps shrinking.
The KL of BoN: log N − (N−1)/N
How far does the BoN policy move from the reference policy? A response is selected when ” comes up once and the other samples all have lower reward than ” (continuous, no ties), so
Then
The quantile of the chosen response, , is the maximum of N uniforms, so it has density , i.e. Beta(N, 1), and . Therefore
The surprising part is that this value depends neither on the shape of the reward distribution nor on , because BoN uses only the ranking of rewards. For N = 16 it is about 1.83 nats; for N = 64, about 3.17 nats. Since the KL grows only like , BoN is an optimiser that “spends KL very sparingly”.
보상모델이 있다면 RL 없이도 정책을 “개선”할 수 있다. 응답을 N개 뽑아서 보상이 가장 큰 것을 고르면 된다. 이것이 best-of-N(BoN) 이다. 너무 단순해서 기준선 취급을 받지만, BoN은 KL 정규화 최적해에 놀랄 만큼 가깝고, 그것을 학습으로 옮긴 rejection sampling fine-tuning은 Llama 2부터 DeepSeek-R1까지 대부분의 레시피에 들어 있다.
Best-of-N: 최댓값의 분포
에서 응답 을 독립으로 뽑고 를 내놓는 정책을 이라 하자. 보상이 연속이고 동점이 없다고 하면, 아래 보상의 CDF를 라 할 때 최댓값의 CDF는 이고 밀도는
다. N을 키우면 분포 전체가 위쪽 꼬리로 밀려 올라간다. 보상이 표준정규라면 최댓값의 기댓값은 대략 로 자란다(점근적으로). 비용은 N에 선형인데 이득은 이다. N을 4에서 16으로 늘리는 것과 64에서 256으로 늘리는 것은 비용은 같은 4배지만 이득은 갈수록 작다.
BoN의 KL: log N − (N−1)/N
BoN 정책이 기준 정책에서 얼마나 멀리 갔는지 재 보자. 응답 가 뽑힐 확률은 “한 번 가 나오고, 나머지 개는 보다 보상이 낮을 것”이므로(연속, 동점 없음)
이다. 그러면
BoN이 고른 응답의 분위수 는 균등분포 N개의 최댓값이므로 밀도 , 즉 Beta(N, 1)을 따르고 이다. 따라서
놀라운 점은 이 값이 보상 분포의 모양에도, 에도 의존하지 않는다는 것이다. BoN은 보상의 순위만 쓰기 때문이다. N = 16이면 약 1.83 nats, N = 64이면 약 3.17 nats다. KL이 으로만 자라므로 BoN은 “KL을 아주 조금씩 쓰는” 최적화다.
- With the normal distribution, raise N from 1 → 256 and compare the KL cell with the formula cell. They agree to the third decimal place.
- Switch the distribution to bimodal and the reward gain jumps at small N, because you only need to hit the upper mode (30% of the mass) once in N draws. After that it climbs slowly within that mode. The KL is still the same.
- With the right-tailed distribution, the reward gain for the same KL is larger than for the normal. BoN’s gain depends on how heavy the upper tail is.
- In the right panel, the BoN points sit just below the optimal curve . At the same KL, the expected reward BoN achieves is almost that of the optimal policy from Lesson 3.
BoN vs KL-regularised RL
In Lesson 3 we saw that maximises expected reward at a given KL. BoN’s weight also tilts by a monotonically increasing function of the reward, so the shapes are similar. The difference is that tilts by the reward’s value, BoN by its rank. That the two curves in the figure are close is the qualitative conclusion; Gui et al. (2024) analysed that BoN is essentially optimal in the win-rate-vs-KL trade-off against the reference model.
Then why do RL at all? First, inference cost. BoN generates N times per query and calls the RM N times. RL bakes that improvement into the weights and gets it from a single generation. Second, the KL budget. BoN’s KL grows only like , so reaching a large KL needs exponentially large N. RL can move tens of nats (with correspondingly larger risk of over-optimisation). Gao et al. (2023) optimised against the same RM with both BoN and RL and compared how the true (gold) reward rises and then bends as a function of KL; the two methods’ curves were well fit by different functional forms (over-optimisation lesson).
import numpy as np
rng = np.random.default_rng(0)
# 1) Expected maximum: draw N rewards r ~ N(0,1) and take the largest
print("N E[max] (MC) √(2 log N) (asymptotic)")
for N in [1, 2, 4, 16, 64, 256]:
m = rng.normal(size=(20_000, N)).max(1).mean()
print(f"{N:<4} {m:10.3f} {np.sqrt(2*np.log(N)):10.3f}")
# 2) Exact distribution and KL of the BoN policy on a discrete distribution
def bon_policy(p, r, N):
"""Policy that draws N from π_ref = p and picks the highest reward (assumes no reward ties)"""
order = np.argsort(r) # ascending reward
F = np.cumsum(p[order]) # F(y) = P(r(Y) ≤ r(y))
F_prev = np.concatenate([[0.0], F[:-1]])
q = np.empty_like(p)
q[order] = F ** N - F_prev ** N # P(max is y) = F(y)^N - F(y-)^N
return q
def kl(q, p):
m = q > 0
return np.sum(q[m] * np.log(q[m] / p[m]))
for K, label in [(10_000, "10,000 responses (nearly continuous)"), (8, "8 responses (discrete, large masses)")]:
p = rng.dirichlet(np.ones(K))
r = rng.normal(size=K)
print(f"\n{label}")
print("N KL(BoN‖ref) log N − (N−1)/N E[r] ref → BoN")
for N in [2, 4, 16, 64]:
q = bon_policy(p, r, N)
bound = np.log(N) - (N - 1) / N
print(f"{N:<4} {kl(q, p):11.4f} {bound:14.4f} {p @ r:6.3f} → {q @ r:6.3f}")
# 3) Monte Carlo check: actually draw N and pick the argmax; frequencies match bon_policy
p = rng.dirichlet(np.ones(8)); r = rng.normal(size=8); N = 4
draws = rng.choice(8, size=(50_000, N), p=p)
picked = draws[np.arange(len(draws)), r[draws].argmax(1)]
print("\nMC freq :", np.round(np.bincount(picked.astype(np.intp), minlength=8) / len(picked), 3))
print("exact :", np.round(bon_policy(p, r, N), 3))In the nearly continuous case with 10,000 responses, the exact KL and the formula agree to four digits. With only 8 responses, the exact KL is smaller than the formula, and the gap widens as N grows. If the highest-reward response already has substantial probability, choosing it does not cost much KL. In the extreme, the KL cannot exceed .
Whether the reward distribution is normal, bimodal or long-tailed, if it is continuous with no ties, what is KL(π_BoN‖π_ref) for best-of-16?
BoN uses only the rank of the reward. The quantile of the chosen response, , follows Beta(16, 1) for any continuous distribution, so KL . The shape of the reward distribution changes the expected reward gain, not the KL. If the distribution is discrete with responses of large probability mass, the actual KL is smaller than this value (an upper bound).
Rejection sampling fine-tuning: putting BoN into the weights
Instead of computing BoN at inference time for every query, train the policy on its outputs. Following Lambert’s summary, the procedure is:
- For each prompt , generate responses with the current model.
- Score them with the reward model (or a verifier): .
- Select. Best per prompt: one for each . Or global top-K: the top out of all scores (easy prompts may contribute several responses and hard prompts none).
- Run SFT on the selected . If needed, repeat 1–4 with the new model.
The policy then approximates , and iterating accumulates a little KL each round. Each round is “improve the policy by sampling → distil”, which is the structure of expert iteration (Anthony et al. 2017): search plays the expert, the policy plays the apprentice.
Where it is used. Lambert’s book cites WebGPT, Anthropic’s HH models, Lightman et al.’s PRM work and Llama 2 as representative uses of rejection sampling. Llama 2 used only rejection sampling fine-tuning in the early RLHF rounds and later put PPO on top of its result; rejection sampling was run only with the largest model, and the smaller models were trained on that data (distillation). The same family of methods has also been described under names like RAFT (Dong et al. 2023) and ReST (Gulcehre et al. 2023).
In reasoning. STaR (Zelikman et al. 2022) has the model write a solution process (rationale) and keeps only those whose final answer is correct for further training. Problems it fails are supplemented by rationalization: give the correct answer as a hint and have the model write a rationale. It is rejection sampling with the reward “1 if correct”. DeepSeek-R1, too, after reasoning RL, sampled many solutions from the RL checkpoint, filtered for correct and readable ones, and built a large SFT dataset from them.
Summary
- Best-of-N tilts by the reward’s rank. The density of the maximum is , and for normal rewards the gain grows only roughly like .
- If continuous with no ties, , independent of the reward distribution. For discrete distributions with large-mass responses it is an upper bound (Beirami et al. 2024).
- At the same KL, BoN’s expected reward is close to the KL-regularised optimum. In exchange, inference costs N times more and the KL budget is limited to .
- Rejection sampling fine-tuning distils BoN through SFT. Iterated, it is expert iteration; with a correctness filter, it is STaR- / R1-style data generation. Filtered SFT with 0/1 rewards has the same form as a policy gradient without a baseline.
- 정규 분포에서 N을 1 → 256으로 올리며 KL 칸과 공식 칸을 비교하자. 둘이 소수 셋째 자리까지 같다.
- 분포를 쌍봉으로 바꾸면 작은 N에서 보상 이득이 크게 뛴다. 위쪽 봉우리(전체의 30%)를 N번 중 한 번만 뽑아도 되기 때문이다. 그 뒤로는 그 봉우리 안에서만 천천히 오른다. 그래도 KL은 같다.
- 오른쪽 꼬리 분포에서는 같은 KL로 얻는 보상 이득이 정규 분포보다 크다. BoN의 이득은 위쪽 꼬리가 얼마나 두꺼운지에 달려 있다.
- 오른쪽 그림에서 BoN 점들은 최적 곡선 바로 아래에 있다. 같은 KL에서 BoN이 얻는 기대 보상은 레슨 3의 최적 정책과 거의 같다.
BoN vs KL 정규화 RL
레슨 3에서 가 주어진 KL에서 기대 보상을 최대화한다는 것을 보았다. BoN의 가중치 도 보상의 단조증가 함수로 를 기울인 것이니 모양이 비슷하다. 차이는 가 보상의 값으로, BoN은 보상의 순위로 기울인다는 점이다. 그림의 두 곡선이 가깝다는 것이 정성적인 결론이고, Gui et al.(2024)은 기준 모델 대비 승률–KL 트레이드오프에서 BoN이 사실상 최적임을 분석했다.
그렇다면 왜 RL을 하나? 첫째, 추론 비용이다. BoN은 매 질의마다 N배 생성하고 RM을 N번 호출한다. RL은 그 개선을 가중치에 넣어 한 번의 생성으로 얻는다. 둘째, KL 예산이다. BoN의 KL은 으로만 자라서 큰 KL에 도달하려면 N이 지수적으로 커져야 한다. RL은 수십 nats도 움직일 수 있다(그만큼 과최적화 위험도 크다). Gao et al.(2023)은 같은 RM으로 BoN과 RL을 최적화하면서 진짜(gold) 보상이 KL에 따라 어떻게 오르다 꺾이는지를 비교했는데, 두 방법의 곡선은 다른 함수 형태로 잘 맞았다(과최적화 레슨).
import numpy as np
rng = np.random.default_rng(0)
# 1) 기대 최댓값: 보상 r ~ N(0,1) 에서 N개 뽑아 최댓값을 고른다
print("N E[max] (MC) √(2 log N) (점근식)")
for N in [1, 2, 4, 16, 64, 256]:
m = rng.normal(size=(20_000, N)).max(1).mean()
print(f"{N:<4} {m:10.3f} {np.sqrt(2*np.log(N)):10.3f}")
# 2) 이산 분포에서 BoN 정책의 정확한 분포와 KL
def bon_policy(p, r, N):
"""π_ref = p 에서 N개 뽑아 보상이 가장 큰 것을 고르는 정책 (보상 동점은 없다고 가정)"""
order = np.argsort(r) # 보상 오름차순
F = np.cumsum(p[order]) # F(y) = P(r(Y) ≤ r(y))
F_prev = np.concatenate([[0.0], F[:-1]])
q = np.empty_like(p)
q[order] = F ** N - F_prev ** N # P(최댓값이 y) = F(y)^N - F(y-)^N
return q
def kl(q, p):
m = q > 0
return np.sum(q[m] * np.log(q[m] / p[m]))
for K, label in [(10_000, "응답 10,000개 (거의 연속)"), (8, "응답 8개 (질량이 큰 이산)")]:
p = rng.dirichlet(np.ones(K))
r = rng.normal(size=K)
print(f"\n{label}")
print("N KL(BoN‖ref) log N − (N−1)/N E[r] ref → BoN")
for N in [2, 4, 16, 64]:
q = bon_policy(p, r, N)
bound = np.log(N) - (N - 1) / N
print(f"{N:<4} {kl(q, p):11.4f} {bound:14.4f} {p @ r:6.3f} → {q @ r:6.3f}")
# 3) 몬테카를로로 확인: 실제로 N개 뽑아 argmax를 고른 빈도가 bon_policy와 같다
p = rng.dirichlet(np.ones(8)); r = rng.normal(size=8); N = 4
draws = rng.choice(8, size=(50_000, N), p=p)
picked = draws[np.arange(len(draws)), r[draws].argmax(1)]
print("\nMC 빈도 :", np.round(np.bincount(picked.astype(np.intp), minlength=8) / len(picked), 3))
print("정확한 값:", np.round(bon_policy(p, r, N), 3))응답이 10,000개인 거의 연속인 경우에는 정확한 KL과 공식이 네 자리까지 같다. 응답이 8개뿐이면 정확한 KL이 공식보다 작고, N이 클수록 차이가 벌어진다. 보상이 가장 큰 응답이 이미 상당한 확률을 갖고 있으면, 그것을 고르는 데 KL이 별로 들지 않는다. 극단적으로 KL은 를 넘을 수 없다.
보상 분포가 정규든, 두 봉우리든, 꼬리가 길든, 연속이고 동점이 없다면 best-of-16 정책의 KL(π_BoN‖π_ref)은?
BoN은 보상의 순위만 쓴다. 고른 응답의 분위수 는 어떤 연속 분포에서든 Beta(16, 1)을 따르므로 KL 다. 보상 분포의 모양은 KL이 아니라 기대 보상 이득을 바꾼다. 이산이고 확률 질량이 큰 응답이 있으면 실제 KL은 이 값보다 작다(상한).
Rejection sampling fine-tuning: BoN을 가중치에 넣기
BoN의 결과를 매번 추론 시간에 계산하는 대신 정책에 학습시키면 된다. Lambert의 정리를 따르면 절차는 이렇다.
- prompt 마다 현재 모델로 응답 개 를 생성한다.
- 보상모델(또는 검증기)로 점수 를 매긴다.
- 고른다. prompt별 최고: 각 에서 하나씩. 또는 전체 top-K: 개 점수 전체에서 상위 개(쉬운 prompt의 응답이 여러 개 뽑히고 어려운 prompt는 하나도 안 뽑힐 수 있다).
- 고른 로 SFT한다. 필요하면 새 모델로 1–4를 반복한다.
이렇게 하면 정책은 을 근사하게 되고, 반복하면 매 라운드 KL이 조금씩 누적된다. 각 라운드는 “샘플링으로 정책 개선 → 증류”이고, 이것이 expert iteration(Anthony et al. 2017)의 구조다. 탐색이 전문가 역할을, 정책이 견습생 역할을 한다.
쓰인 곳. Lambert의 책은 WebGPT, Anthropic의 HH 모델, Lightman et al.의 PRM 연구, Llama 2를 rejection sampling을 쓴 대표 사례로 든다. Llama 2는 RLHF의 초기 라운드에서는 rejection sampling fine-tuning만 쓰다가 나중 라운드에서 그 결과 위에 PPO를 얹었고, rejection sampling은 가장 큰 모델로만 수행해 작은 모델들은 그 데이터를 받아 학습했다(증류). 같은 계열의 방법이 RAFT(Dong et al. 2023), ReST(Gulcehre et al. 2023) 같은 이름으로도 정리되었다.
추론에서. STaR(Zelikman et al. 2022)는 모델에게 풀이 과정(rationale)을 쓰게 하고 최종 답이 맞은 것만 남겨 다시 학습한다. 못 맞힌 문제는 정답을 힌트로 주고 rationale을 쓰게 하는 rationalization으로 보충한다. 보상이 “정답이면 1”인 rejection sampling이다. DeepSeek-R1도 추론 RL 뒤에 RL 체크포인트에서 여러 풀이를 뽑아 맞고 읽기 좋은 것만 걸러 대량의 SFT 데이터를 다시 만들었다.
정리
- Best-of-N은 를 보상의 순위로 기울인다. 최댓값의 밀도는 이고, 정규 보상에서 이득은 대략 로만 자란다.
- 연속·무동점이면 이고 보상 분포와 무관하다. 확률 질량이 큰 응답이 있는 이산 분포에서는 이것이 상한이다(Beirami et al. 2024).
- 같은 KL에서 BoN의 기대 보상은 KL 정규화 최적해에 가깝다. 대신 추론 비용이 N배이고 KL 예산이 으로 제한된다.
- Rejection sampling fine-tuning은 BoN을 SFT로 증류한다. 반복하면 expert iteration이고, 정답 필터를 쓰면 STaR·R1식 데이터 생성이다. 0/1 보상의 필터링 SFT는 baseline 없는 policy gradient와 같은 꼴이다.
더 읽을거리Further reading
- Lambert, RLHF Book, Ch. 9 Rejection Sampling (rlhfbook.com) — prompt별 최고 vs 전체 top-K 선택, BoN과의 관계, 사용 사례 정리.Best per prompt vs global top-K selection, the relation to BoN, and use cases.
- Stiennon et al., Learning to Summarize from Human Feedback (NeurIPS 2020) — BoN을 RL과 나란히 놓고 KL 대비 성능을 비교했다. BoN KL 공식 log N − (N−1)/N이 쓰인 초기 문헌 중 하나.Put BoN next to RL and compared performance against KL. One of the early works using the BoN KL formula log N − (N−1)/N.
- Beirami et al., Theoretical Guarantees on the Best-of-n Alignment Policy (2024) — 널리 쓰이는 log N − (N−1)/N이 일반적으로는 상한이며 실제 KL이 훨씬 작을 수 있음을 보였다.Showed that the widely used log N − (N−1)/N is in general an upper bound and the actual KL can be much smaller.
- Gao, Schulman & Hilton, Scaling Laws for Reward Model Overoptimization (ICML 2023) — BoN과 RL의 과최적화를 KL의 함수로 비교한 스케일링 연구.A scaling study comparing over-optimisation of BoN and RL as functions of KL.
- Touvron et al., Llama 2: Open Foundation and Fine-Tuned Chat Models (2023) — rejection sampling fine-tuning을 여러 라운드 하고 그 위에 PPO를 얹은 대표 사례.The canonical example of several rounds of rejection sampling fine-tuning with PPO on top.
- Zelikman et al., STaR: Bootstrapping Reasoning With Reasoning (NeurIPS 2022) — 정답을 맞힌 rationale만 남겨 다시 학습하는 반복. 추론 RL의 조상.Iterate by keeping only rationales that reach the right answer and retraining. An ancestor of reasoning RL.
- Anthony, Tian & Barber, Thinking Fast and Slow with Deep Learning and Tree Search (NeurIPS 2017) — Expert iteration. 탐색(전문가)의 결과를 정책(견습생)에 증류하는 반복.Expert iteration: repeatedly distil the results of search (the expert) into the policy (the apprentice).