v9.1.1
Menu

Best-of-N Sampling

hardPROReward ModelingLLM 2: Training & Alignment

Implement Best-of-N (rejection) sampling for LLM generation.

Given N candidate responses with their reward scores, select the best one. Also compute the KL cost of this selection strategy.

The expected KL divergence cost of Best-of-N sampling is approximately: KLBoN≈log⁡(N)−N−1N\text{KL}_{\text{BoN}} \approx \log(N) - \frac{N-1}{N}

Input:

  • Line 1: N (number of candidates)
  • Next N lines: reward_score response_text

Output:

  • Line 1: The best response text (highest reward)
  • Line 2: The best reward score, rounded to 4 decimal places
  • Line 3: The KL cost approximation, rounded to 4 decimal places

Example

Input
3
1.5 Hello world
2.3 Hi there
0.8 Hey
Output
Hi there
2.3000
0.4319
Reasoning
  • We read the input values: N=3N = 3, and the reward scores with their corresponding responses: (1.5,Hello world)(1.5, \text{Hello world}), (2.3,Hi there)(2.3, \text{Hi there}), and (0.8,Hey)(0.8, \text{Hey}).
  • We select the best response by finding the highest reward score, which is 2.32.3 for the response Hi there\text{Hi there}.
  • We calculate the KL cost approximation using the formula: KLBoN≈log⁡(N)−N−1N=log⁡(3)−3−13≈0.4319\text{KL}_{\text{BoN}} \approx \log(N) - \frac{N-1}{N} = \log(3) - \frac{3-1}{3} \approx 0.4319.
  • The final output is the best response text, the best reward score rounded to 4 decimal places (2.30002.3000), and the KL cost approximation rounded to 4 decimal places (0.43190.4319).

Constraints

  • 1 <= N <= 100
  • If tied, pick the first one encountered
  • Round to 4 decimal places

Learn this in

More from LLM 2: Training & Alignment

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.