Track V · RL for LLMs & Agents · 02/10

보상모델Reward models

쌍 비교 선호에서 Bradley–Terry 모델을 유도하고 보상모델을 학습할 수 있다. 보상의 어떤 부분이 데이터로 정해지고 어떤 부분이 정해지지 않는지, ORM·PRM·가치함수·LLM-as-judge가 각각 무엇을 예측하는지 구분할 수 있다.Derive the Bradley–Terry model from pairwise preferences and train a reward model. Tell apart which parts of a reward the data determines and which it does not, and what ORMs, PRMs, value functions and LLM-as-judge each predict.

40 분min reward model · bradley-terry · plackett-luce · prm · orm · llm-as-judge · rewardbench 먼저 볼 것:Before this: RLHF와 사후학습 개관Overview of RLHF and post-training, 확률로 보는 손실Losses through probability, 선형 모델Linear models

RL wants a scalar reward, and people give comparisons. Turning hundreds of thousands of labels of the form “A is better than B” into a function rϕ(x,y)r_\phi(x, y) that outputs one number per response is the job of the reward model (RM). In this lesson we derive the probability model behind that conversion (Bradley–Terry) and see what that model can and cannot learn from data. Then we tell apart the various kinds of “reward function” used in RLHF: preference RMs, ORMs, PRMs, value functions and LLM judges.

From comparisons to scores: Bradley–Terry

Suppose each response yy has a hidden utility u(y)u(y), and the labeller picks the one with the larger utility. The labeller’s judgement, however, is noisy.

u(y)=r(x,y)+εy,εy∼iidGumbel(0,1)u(y) = r(x, y) + \varepsilon_y, \qquad \varepsilon_y \overset{\text{iid}}{\sim} \text{Gumbel}(0, 1)

We pick the Gumbel distribution because the algebra comes out cleanly. The difference of two independent Gumbel(0,1) variables follows the standard logistic distribution, whose CDF is exactly the sigmoid. Therefore

P(yw≻yl)=P(εyl−εyw<r(x,yw)−r(x,yl))=σ(r(x,yw)−r(x,yl))P(y_w \succ y_l) = P\big(\varepsilon_{y_l} - \varepsilon_{y_w} < r(x,y_w) - r(x,y_l)\big) = \sigma\big(r(x,y_w) - r(x,y_l)\big)

This is the Bradley–Terry (BT) model. Writing pi=erip_i = e^{r_i} gives the original form P(i≻j)=pi/(pi+pj)P(i \succ j) = p_i/(p_i + p_j). Making the noise Gaussian instead yields the Thurstone model, with the normal CDF in place of the sigmoid; in practice the two differ little and BT is the standard.

Maximising the log-likelihood of the data D={(x,yw,yl)}\mathcal{D} = \{(x, y_w, y_l)\} gives the reward model’s loss.

L(ϕ)=− E(x,yw,yl)∼D[log⁡σ(rϕ(x,yw)−rϕ(x,yl))]\mathcal{L}(\phi) = -\,\mathbb{E}_{(x, y_w, y_l)\sim\mathcal{D}}\Big[\log \sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big)\Big]

The gradient shows at once what this loss does. With Δ=rϕ(x,yw)−rϕ(x,yl)\Delta = r_\phi(x,y_w) - r_\phi(x,y_l),

∇ϕL=− E[(1−σ(Δ))(∇ϕrϕ(x,yw)−∇ϕrϕ(x,yl))]\nabla_\phi \mathcal{L} = -\,\mathbb{E}\Big[\big(1 - \sigma(\Delta)\big)\big(\nabla_\phi r_\phi(x,y_w) - \nabla_\phi r_\phi(x,y_l)\big)\Big]

It raises the chosen score and lowers the rejected score, with strength 1−σ(Δ)1 - \sigma(\Delta) — the probability that the model currently gets that pair wrong. Pairs it already gets right by a wide margin contribute almost nothing. This structure reappears unchanged in the DPO lesson.

RL은 스칼라 보상을 원하고, 사람은 비교를 준다. “A가 B보다 낫다”는 라벨 수십만 개를 응답마다 숫자 하나를 내는 함수 rϕ(x,y)r_\phi(x, y)로 바꾸는 것이 보상모델(reward model, RM) 의 일이다. 이 레슨에서는 그 변환의 확률 모델(Bradley–Terry)을 유도하고, 그 모델이 데이터로부터 무엇을 알 수 있고 무엇을 알 수 없는지 본다. 그다음 RLHF에서 쓰이는 여러 종류의 “보상 함수”, 즉 선호 RM, ORM, PRM, 가치함수, LLM judge를 구분한다.

비교에서 점수로: Bradley–Terry

응답 yy마다 숨은 효용 u(y)u(y)가 있고, 라벨러는 효용이 큰 쪽을 고른다고 하자. 다만 라벨러의 판단에는 잡음이 섞인다.

u(y)=r(x,y)+εy,εy∼iidGumbel(0,1)u(y) = r(x, y) + \varepsilon_y, \qquad \varepsilon_y \overset{\text{iid}}{\sim} \text{Gumbel}(0, 1)

Gumbel 분포를 고르는 이유는 계산이 깔끔해서다. 독립인 두 Gumbel(0,1) 변수의 차이는 표준 로지스틱 분포를 따르고, 그 CDF가 바로 시그모이드다. 그러므로

P(yw≻yl)=P(εyl−εyw<r(x,yw)−r(x,yl))=σ(r(x,yw)−r(x,yl))P(y_w \succ y_l) = P\big(\varepsilon_{y_l} - \varepsilon_{y_w} < r(x,y_w) - r(x,y_l)\big) = \sigma\big(r(x,y_w) - r(x,y_l)\big)

이것이 Bradley–Terry(BT) 모델이다. pi=erip_i = e^{r_i}로 쓰면 P(i≻j)=pi/(pi+pj)P(i \succ j) = p_i/(p_i + p_j)라는 원래 형태가 된다. 잡음을 가우시안으로 두면 시그모이드 대신 정규 CDF가 나오는 Thurstone 모델이 되는데, 실제로는 둘의 차이가 작고 BT가 표준이다.

데이터 D={(x,yw,yl)}\mathcal{D} = \{(x, y_w, y_l)\}의 로그우도를 최대화하면 보상모델의 손실이 된다.

L(ϕ)=− E(x,yw,yl)∼D[log⁡σ(rϕ(x,yw)−rϕ(x,yl))]\mathcal{L}(\phi) = -\,\mathbb{E}_{(x, y_w, y_l)\sim\mathcal{D}}\Big[\log \sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big)\Big]

gradient를 보면 이 손실이 무엇을 하는지 바로 보인다. Δ=rϕ(x,yw)−rϕ(x,yl)\Delta = r_\phi(x,y_w) - r_\phi(x,y_l)라 하면

∇ϕL=− E[(1−σ(Δ))(∇ϕrϕ(x,yw)−∇ϕrϕ(x,yl))]\nabla_\phi \mathcal{L} = -\,\mathbb{E}\Big[\big(1 - \sigma(\Delta)\big)\big(\nabla_\phi r_\phi(x,y_w) - \nabla_\phi r_\phi(x,y_l)\big)\Big]

chosen의 점수는 올리고 rejected의 점수는 내리는데, 그 세기가 1−σ(Δ)1 - \sigma(\Delta), 즉 모델이 현재 그 쌍을 틀릴 확률이다. 이미 큰 차이로 맞히는 쌍은 거의 기여하지 않는다. 이 구조는 DPO 레슨에서 그대로 다시 나온다.

Δr = – P(yw ≻ yl) = σ(Δr) = – 손실loss −log σ(Δr) = – gradient 크기gradient size 1−σ(Δr) = –
The number line on top shows the two responses' rewards; below is the preference probability σ(Δr). Move c and the two points slide together, but Δr and the probability stay put: the absolute position of the reward is not determined by the data. Move k and the probability changes while the order stays the same. Scaling the rewards by k is the same as changing BT's "temperature" to 1/k. The loss gradient 1−σ(Δr) vanishes to 0 on pairs that are already well separated (Δr ≫ 0). 위 수직선은 두 응답의 보상, 아래는 선호 확률 σ(Δr). c를 움직이면 두 점이 함께 미끄러지지만 Δr과 확률은 그대로다: 보상의 절대 위치는 데이터로 정해지지 않는다. k를 움직이면 같은 순서인데 확률이 바뀐다. 보상을 k배 하는 것은 BT의 "온도"를 1/k로 바꾸는 것과 같다. 손실의 기울기 1−σ(Δr)는 이미 잘 맞힌 쌍(Δr ≫ 0)에서 0으로 사라진다.

What part of the reward does the data determine?

Only the difference r(yw)−r(yl)r(y_w) - r(y_l) enters the loss. Two things follow.

The shift is not determined. Adding the same constant to every reward — more generally, a different constant c(x)c(x) per prompt — leaves the loss unchanged. The absolute value of a reward model’s output means nothing; only differences within the same prompt mean something. This is why it is fine to normalise rewards (subtract the mean, whiten) or subtract a baseline in the RL stage.

The scale is tied to the noise level. In the derivation above we fixed the noise scale at 1. If real labellers are TT times noisier, then P=σ(Δr/T)P = \sigma(\Delta r / T), and the scores fitted by BT estimate r/Tr/T. In other words, BT scores are “rewards measured in units of label noise”. In the extreme where labels never waver (the better one is always chosen), the loss keeps decreasing as the scale grows, so the MLE does not exist. In RL this scale only enters together with β\beta as r/βr/\beta anyway (next lesson), so changing the reward scale is the same as changing the KL coefficient.

Check it yourself in the figure below. We generate noisy comparisons from the hidden scores of ten items and fit BT by gradient ascent.

보상의 무엇이 데이터로 정해지나

손실에는 차이 r(yw)−r(yl)r(y_w) - r(y_l)만 들어간다. 그래서 두 가지가 생긴다.

이동(shift)은 정해지지 않는다. 모든 보상에 같은 상수, 더 일반적으로 prompt마다 다른 상수 c(x)c(x)를 더해도 손실은 똑같다. 보상모델 출력의 절대값은 의미가 없고, 같은 prompt 안에서의 차이만 의미가 있다. RL 단계에서 보상을 정규화(평균 빼기, whitening)하거나 baseline을 빼도 괜찮은 이유가 이것이다.

스케일은 잡음 크기와 묶여 있다. 위 유도에서 잡음의 스케일을 1로 고정했다. 실제 라벨러의 잡음이 TT배 크다면 P=σ(Δr/T)P = \sigma(\Delta r / T)이고, BT로 맞춘 점수는 r/Tr/T를 추정한다. 즉 BT 점수는 “라벨 잡음 단위로 잰 보상” 이다. 라벨이 전혀 흔들리지 않는 극단(항상 더 나은 쪽을 고름)에서는 손실이 스케일을 키울수록 계속 줄어들어 MLE가 존재하지 않는다. RL에서는 이 스케일이 어차피 β\beta와 함께 r/βr/\beta로만 들어가므로(다음 레슨), 보상 스케일을 바꾸는 것은 KL 계수를 바꾸는 것과 같다.

아래 그림에서 직접 확인해 보자. 항목 10개의 숨은 점수에서 잡음 섞인 비교를 만들고, BT를 경사상승으로 맞춘다.

iter 0 쌍 순서 정확도pairwise order accuracy – Kendall τ – 적합 기울기fitted slope – (1/T = –)
Ten items have hidden scores si, and the labeller picks with P(i ≻ j) = σ((si − sj)/T). Left: scores fitted by BT maximum likelihood (centred to mean 0) against the true scores; right: the log-likelihood. Reduce the number of comparisons and the ranking gets shuffled; raise T and the fitted scores flatten even with the same order (slope ≈ 1/T). All BT knows is "score differences measured in units of noise". (Includes weak L2 regularisation.) 항목 10개에 숨은 점수 si가 있고, 라벨러는 P(i ≻ j) = σ((si − sj)/T)로 고른다. 왼쪽은 BT 최대우도로 맞춘 점수(평균 0으로 맞춤)와 진짜 점수, 오른쪽은 로그우도. 비교 수를 줄여 보면 순위가 뒤섞이고, T를 키우면 같은 순서라도 맞춘 점수가 납작해진다(기울기 ≈ 1/T). BT가 아는 것은 "노이즈 단위로 잰 점수 차이"뿐이다. (약한 L2 정규화 포함)
  1. Reduce the number of comparisons to around 10 and some pairs are never compared at all; the ranking accuracy swings wildly. This is why RMs need a lot of data.
  2. With the number of comparisons at its maximum, change T: the order stays almost the same, but the slope of the fitted scores follows 1/T1/T.
  3. With large T (labellers disagree a lot), the ranking is less accurate for the same number of comparisons, because each label carries less information.

Implementation: a linear reward model

A real RM is an LLM, but the loss and gradient are the same for a linear model. Each response has a feature vector ϕ(y)\phi(y) (only here, ϕ\phi is a feature, not the RM parameters) and r(y)=w⊤ϕ(y)r(y) = w^\top\phi(y). We generate BT labels from a hidden w⋆w^\star and then recover ww.

NumPy Bradley–Terry reward model — linear features
import numpy as np

rng = np.random.default_rng(0)
d, n_items = 8, 400
w_true = rng.normal(size=d)                 # hidden "true" reward: r*(y) = w_true · φ(y)
Phi = rng.normal(size=(n_items, d))         # a feature vector φ(y) per response
r_true = Phi @ w_true

def sigmoid(z): return 1 / (1 + np.exp(-z))

def make_pairs(n_pairs, rng):
    i = rng.integers(0, n_items, n_pairs)
    j = rng.integers(0, n_items, n_pairs)
    i, j = i[i != j], j[i != j]
    i_wins = rng.random(len(i)) < sigmoid(r_true[i] - r_true[j])   # Bradley–Terry labeller
    return np.where(i_wins, i, j), np.where(i_wins, j, i)          # (y_w, y_l)

yw, yl = make_pairs(3000, rng)
yw_te, yl_te = make_pairs(2000, rng)

def loss_and_grad(w, D):
    """D[k] = φ(y_w) - φ(y_l), so D @ w = r(y_w) - r(y_l)."""
    delta = D @ w
    loss = -np.mean(np.log(sigmoid(delta) + 1e-12))
    # d/dw [-log σ(Δ)] = -(1 - σ(Δ)) (φ_w - φ_l)
    grad = -((1 - sigmoid(delta))[:, None] * D).mean(0)
    return loss, grad

def train(yw, yl, steps, lr=0.5, log_every=None, on_step=None):
    D = Phi[yw] - Phi[yl]
    w = np.zeros(d)
    for step in range(steps + 1):
        loss, g = loss_and_grad(w, D)
        if on_step: on_step(step, w, loss)
        if log_every and step % log_every == 0:
            sw, sl = Phi[yw_te] @ w, Phi[yl_te] @ w
            acc = np.mean(sw > sl) + 0.5 * np.mean(sw == sl)      # ties count as half
            print(f"step {step:3d}  loss {loss:.4f}  test pair accuracy {acc:.3f}")
        w -= lr * g
    return w, loss

w, _ = train(yw, yl, 300, log_every=100)
ceiling = np.mean(r_true[yw_te] > r_true[yl_te])
print(f"even ranking by the true reward r* gives accuracy {ceiling:.3f} (a ceiling set by the labels being random)")
cos = w @ w_true / np.linalg.norm(w) / np.linalg.norm(w_true)
print(f"cos(w, w_true) = {cos:.3f},  |w| / |w_true| = {np.linalg.norm(w)/np.linalg.norm(w_true):.2f}")

# 1) shift invariance: adding the same constant to every reward leaves the loss unchanged
delta = (Phi[yw] @ w + 3.7) - (Phi[yl] @ w + 3.7)
print(f"loss after shifting rewards by +3.7: {-np.mean(np.log(sigmoid(delta))):.4f} (unchanged)")

# 2) scale: with deterministic labels (the better one always wins) |w| grows without bound
better = r_true[yw] > r_true[yl]
yw_d, yl_d = np.where(better, yw, yl), np.where(better, yl, yw)
def report(step, w, loss):
    if step in (100, 1000, 3000):
        print(f"deterministic labels, step {step:4d}: loss {loss:.4f}  |w|/|w_true| = {np.linalg.norm(w)/np.linalg.norm(w_true):.2f}")
_ = train(yw_d, yl_d, 3000, on_step=report)
 

There are three things to see in the output. The test pair accuracy is almost the same as the accuracy obtained by ranking with the true reward; that is, the ceiling on RM accuracy is set by how consistent the labels are. With BT labels, ∣w∣|w| is recovered almost equal to ∣w⋆∣|w^\star| (because the noise scale matches 1), but with deterministic labels ∣w∣|w| keeps growing. This overconfidence is one of the reasons real RMs are trained for only about 1 epoch.

In PyTorch it looks like this. The backbone can be any decoder LM.

PyTorch PyTorch: an LLM reward-model head and the pairwise loss 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import AutoModel

class RewardModel(nn.Module):
    def __init__(self, name: str):
        super().__init__()
        self.backbone = AutoModel.from_pretrained(name)          # transformer without an LM head
        self.head = nn.Linear(self.backbone.config.hidden_size, 1)

    def forward(self, input_ids, attention_mask):
        h = self.backbone(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state  # (B, T, H)
        last = attention_mask.sum(dim=1) - 1                      # assumes right padding: position of the last real token
        h_last = h[torch.arange(h.size(0), device=h.device), last]  # (B, H)
        return self.head(h_last).squeeze(-1)                      # (B,) scalar reward

def preference_loss(model, chosen, rejected, margin=None):
    """chosen / rejected: batches of (input_ids, attention_mask) for the same prompts."""
    r_w = model(**chosen)
    r_l = model(**rejected)
    delta = r_w - r_l
    if margin is not None:                  # Llama 2: margin m(y_w, y_l) by preference strength
        delta = delta - margin
    loss = -F.logsigmoid(delta).mean()      # using log σ directly is numerically stable
    acc = (r_w > r_l).float().mean()
    return loss, acc
 

Variants: margins and K-wise

Margin. Llama 2 put the preference strength chosen by the labeller (“significantly better”, “slightly better”, etc.) into the loss.

L(ϕ)=−log⁡σ(rϕ(x,yw)−rϕ(x,yl)−m(yw,yl))\mathcal{L}(\phi) = -\log \sigma\big(r_\phi(x,y_w) - r_\phi(x,y_l) - m(y_w, y_l)\big)

The stronger the preference, the larger the mm, demanding a wider score gap for that pair. According to Lambert’s book, Llama 3 dropped this term because the gain shrank as they scaled up.

K-wise (Plackett–Luce). Given a full ranking σ\sigma of K responses, use a probability model that repeats “pick the best of the remaining ones by softmax”.

P(σ∣x)=∏k=0K−1exp⁡(r(x,yσ(k)))∑j=kK−1exp⁡(r(x,yσ(j)))P(\sigma \mid x) = \prod_{k=0}^{K-1} \frac{\exp\big(r(x, y_{\sigma(k)})\big)}{\sum_{j=k}^{K-1}\exp\big(r(x, y_{\sigma(j)})\big)}

With K = 2 this is BT. It also meshes with the Gumbel derivation: add Gumbel noise to the utilities and take the argmax, and the result follows exactly a softmax distribution (the Gumbel-max trick); repeating that gives Plackett–Luce.

확인 문제Check yourself

Reward model A outputs r(x,y); reward model B outputs r(x,y) + 5·len(x) (a term that depends only on the prompt length is added). How do the two RMs compare in BT loss and in use for RL?

Only the within-prompt difference r(x,yw)−r(x,yl)r(x,y_w) - r(x,y_l) enters the BT loss, so a term c(x)c(x) that depends only on the prompt vanishes. In the policy gradient, too, c(x)c(x) contributes nothing to the expected gradient because Ey∼π[∇log⁡π(y∣x)]=0\mathbb{E}_{y\sim\pi}[\nabla\log\pi(y|x)] = 0, and with a baseline that subtracts the per-prompt mean or GRPO-style group normalisation it vanishes exactly even in the sample. The relative size against the KL term, however, depends on the scale, so multiplication — unlike a constant shift — does change the result.

Kinds of reward function

In the RLHF literature, quite different things are mixed under the name “reward model”. Sorting them by what they predict makes it clear.

KindInputWhat it predictsTraining signal
Preference RM (BT)the whole (x,y)(x, y)a preference logit; only differences are meaningfulpairwise comparisons, −log⁡σ(rw−rl)-\log\sigma(r_w - r_l)
ORM (outcome)(x,y)(x, y), at every tokenthe probability that this response is ultimately correctcorrectness (0/1), BCE at every token
PRM (process)(x,s1,…,sk)(x, s_1, \dots, s_k)the probability that each reasoning step is correctstep-level labels, BCE at step boundaries
Value function V(st)V(s_t)partial response (x,y≤t)(x, y_{\le t})the expected return from following the current policyreturns of on-policy rollouts (TD/GAE)
LLM judge / generative RMprompt + response(s) + criteriaa verdict in text (score, winner)prompting, or fine-tuning on verdict data

ORM. The GSM8K verifier of Cobbe et al. (2021) is the prototype. Collect solutions that got the right answer and ones that did not, and train a binary classifier at every token of the response on “is this solution ultimately correct?”.

LORM=− E[1T∑t=1T(clog⁡pθ(y≤t)+(1−c)log⁡(1−pθ(y≤t)))],c∈{0,1}\mathcal{L}_{\text{ORM}} = -\,\mathbb{E}\Big[\tfrac{1}{T}\textstyle\sum_{t=1}^{T} \big(c \log p_\theta(y_{\le t}) + (1-c)\log(1 - p_\theta(y_{\le t}))\big)\Big], \quad c \in \{0, 1\}

PRM. Lightman et al. (2023) built PRM800K, in which people labelled each step of MATH solutions as positive / neutral / negative, and trained a PRM with the loss applied only at step boundaries. In best-of-N, choosing one of the same generator’s candidates, the PRM was clearly better than the ORM, because it is a denser signal that points at the wrong step. The price is the labelling cost, and later work moved toward generating step labels automatically with Monte Carlo rollouts.

How it differs from a value function. ORMs and value functions both have the shape “predict the outcome from a partial response”, so they are easy to confuse. The difference is under which policy the expectation is taken. An ORM is a correctness probability learned offline from fixed data; a value function is an expected return refitted continually on rollouts of the policy currently being trained, and its purpose is computing advantages (variance reduction) (actor-critic lesson). A reward model says “what is good”; a value function says “how much the current policy will get from here”.

LLM-as-judge and generative reward models

Giving a strong LLM criteria and asking it to pick the better of two responses, or to score one from 1 to 10, is cheap and fast, and agrees with human judgement fairly well (Zheng et al. 2023). The AI feedback of Constitutional AI, the preference-data labelling of Tülu 3, and most open evaluations (MT-Bench, AlpacaEval, Arena-Hard) work this way. Generative RMs, which generate a rationale before the verdict, are in the same family.

The known biases are these.

  • Position bias: prefers the response presented first (or last). Ask twice with the order swapped, and treat a flipped verdict as a tie.
  • Verbosity / length bias: prefers longer responses. This is why length-controlled evaluations, which correct for length by regression, appeared. If RL optimises this bias as is, responses keep getting longer.
  • Self-enhancement: prefers the style written by itself (or by models of the same family).

Lambert’s book summarises that, on RM benchmarks, generative judging generally lags behind dedicated classifier RMs, and notes that it is common to sample verdicts at temperature 0 to reduce variance.

확인 문제Check yourself

In best-of-64, where you pick one of 64 MATH solutions to submit, which verifier is likely to do better for the same data budget?

This is the key result of Lightman et al. (2023). An ORM learns only from outcomes, so its signal for telling a solution that went wrong midway but got the right answer from a clean one is weak. A PRM gets labels at every step and learns where the first error is. A value function is the expected return of a particular policy, not a correctness judge, and it is not trained to pick among the candidates of a different generator.

→ Go deeper: Rewards and environments — reward design in frontier RL: verifiers, rubric and generative rewards, multi-environment RLVR.

Summary

  • Bradley–Terry comes from a choice model that adds Gumbel noise to utilities: P(yw≻yl)=σ(rw−rl)P(y_w \succ y_l) = \sigma(r_w - r_l). The RM loss is its negative log-likelihood.
  • The strength of the gradient is 1−σ(Δ)1 - \sigma(\Delta), the probability of currently getting it wrong. Pairs that are already right contribute almost nothing to learning.
  • The shift of the reward (a per-prompt constant) is not determined by the data, and its scale is tied to label noise. In RL only r/βr/\beta matters.
  • Margins (Llama 2) and Plackett–Luce (K-wise) are variants that use richer labels.
  • An ORM predicts the probability of a correct final answer, a PRM the probability that each step is correct, a value function the current policy’s expected return, and an LLM judge a verdict in text. LLM judges have position, length and self-preference biases.
  1. 비교 수를 10개 근처로 줄이면 한 번도 비교되지 않은 쌍이 생기고, 순위 정확도가 크게 흔들린다. RM 데이터가 많이 필요한 이유다.
  2. 비교 수를 최대로 두고 T를 바꾸면, 순서는 거의 그대로인데 맞춘 점수의 기울기가 1/T1/T를 따라간다.
  3. T가 크면(라벨러끼리 의견이 많이 갈리면) 같은 비교 수로도 순위가 덜 정확하다. 정보가 적은 라벨이기 때문이다.

구현: 선형 보상모델

실제 RM은 LLM이지만, 손실과 gradient는 선형 모델에서도 똑같다. 응답마다 특징 벡터 ϕ(y)\phi(y)가 있고(여기서만 ϕ\phi는 RM 파라미터가 아니라 특징이다) r(y)=w⊤ϕ(y)r(y) = w^\top\phi(y)라고 하자. 숨은 w⋆w^\star로 BT 라벨을 만든 뒤 ww를 복원한다.

NumPy Bradley–Terry 보상모델 — 선형 특징
import numpy as np

rng = np.random.default_rng(0)
d, n_items = 8, 400
w_true = rng.normal(size=d)                 # 숨은 "진짜" 보상: r*(y) = w_true · φ(y)
Phi = rng.normal(size=(n_items, d))         # 응답마다 특징 벡터 φ(y)
r_true = Phi @ w_true

def sigmoid(z): return 1 / (1 + np.exp(-z))

def make_pairs(n_pairs, rng):
    i = rng.integers(0, n_items, n_pairs)
    j = rng.integers(0, n_items, n_pairs)
    i, j = i[i != j], j[i != j]
    i_wins = rng.random(len(i)) < sigmoid(r_true[i] - r_true[j])   # Bradley–Terry 라벨러
    return np.where(i_wins, i, j), np.where(i_wins, j, i)          # (y_w, y_l)

yw, yl = make_pairs(3000, rng)
yw_te, yl_te = make_pairs(2000, rng)

def loss_and_grad(w, D):
    """D[k] = φ(y_w) - φ(y_l) 이므로 D @ w = r(y_w) - r(y_l)."""
    delta = D @ w
    loss = -np.mean(np.log(sigmoid(delta) + 1e-12))
    # d/dw [-log σ(Δ)] = -(1 - σ(Δ)) (φ_w - φ_l)
    grad = -((1 - sigmoid(delta))[:, None] * D).mean(0)
    return loss, grad

def train(yw, yl, steps, lr=0.5, log_every=None, on_step=None):
    D = Phi[yw] - Phi[yl]
    w = np.zeros(d)
    for step in range(steps + 1):
        loss, g = loss_and_grad(w, D)
        if on_step: on_step(step, w, loss)
        if log_every and step % log_every == 0:
            sw, sl = Phi[yw_te] @ w, Phi[yl_te] @ w
            acc = np.mean(sw > sl) + 0.5 * np.mean(sw == sl)      # 동점은 반으로
            print(f"step {step:3d}  loss {loss:.4f}  테스트 쌍 정확도 {acc:.3f}")
        w -= lr * g
    return w, loss

w, _ = train(yw, yl, 300, log_every=100)
ceiling = np.mean(r_true[yw_te] > r_true[yl_te])
print(f"진짜 보상 r*로 매겨도 정확도는 {ceiling:.3f} (라벨 자체가 확률적이라 생기는 천장)")
cos = w @ w_true / np.linalg.norm(w) / np.linalg.norm(w_true)
print(f"cos(w, w_true) = {cos:.3f},  |w| / |w_true| = {np.linalg.norm(w)/np.linalg.norm(w_true):.2f}")

# 1) 이동 불변성: 모든 보상에 같은 상수를 더해도 손실은 그대로다
delta = (Phi[yw] @ w + 3.7) - (Phi[yl] @ w + 3.7)
print(f"보상 +3.7 이동 후 손실 {-np.mean(np.log(sigmoid(delta))):.4f} (그대로)")

# 2) 스케일: 라벨이 결정적이면(항상 더 좋은 쪽을 고름) |w|가 끝없이 커진다
better = r_true[yw] > r_true[yl]
yw_d, yl_d = np.where(better, yw, yl), np.where(better, yl, yw)
def report(step, w, loss):
    if step in (100, 1000, 3000):
        print(f"결정적 라벨, {step:4d} step: loss {loss:.4f}  |w|/|w_true| = {np.linalg.norm(w)/np.linalg.norm(w_true):.2f}")
_ = train(yw_d, yl_d, 3000, on_step=report)
 

결과에서 볼 것은 세 가지다. 테스트 쌍 정확도가 진짜 보상으로 매긴 정확도와 거의 같다. 즉 RM 정확도의 천장은 라벨의 일관성이 정한다. BT 라벨에서는 ∣w∣|w|가 ∣w⋆∣|w^\star|와 거의 같게 복원되지만(잡음 스케일이 1로 맞기 때문), 결정적 라벨에서는 ∣w∣|w|가 계속 커진다. 실제 RM이 1 epoch 정도만 학습되는 이유 중 하나가 이 과신(overconfidence)이다.

PyTorch로 쓰면 다음과 같다. backbone은 어떤 decoder LM이든 된다.

PyTorch PyTorch: LLM 보상모델 head와 쌍 손실 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import AutoModel

class RewardModel(nn.Module):
    def __init__(self, name: str):
        super().__init__()
        self.backbone = AutoModel.from_pretrained(name)          # LM head 없는 transformer
        self.head = nn.Linear(self.backbone.config.hidden_size, 1)

    def forward(self, input_ids, attention_mask):
        h = self.backbone(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state  # (B, T, H)
        last = attention_mask.sum(dim=1) - 1                      # 오른쪽 padding 가정: 마지막 실제 토큰 위치
        h_last = h[torch.arange(h.size(0), device=h.device), last]  # (B, H)
        return self.head(h_last).squeeze(-1)                      # (B,) 스칼라 보상

def preference_loss(model, chosen, rejected, margin=None):
    """chosen / rejected: 같은 prompt에 대한 (input_ids, attention_mask) 배치."""
    r_w = model(**chosen)
    r_l = model(**rejected)
    delta = r_w - r_l
    if margin is not None:                  # Llama 2: 선호 강도에 따른 margin m(y_w, y_l)
        delta = delta - margin
    loss = -F.logsigmoid(delta).mean()      # log σ 를 직접 쓰면 수치적으로 안정하다
    acc = (r_w > r_l).float().mean()
    return loss, acc
 

변형: margin과 K-wise

Margin. Llama 2는 라벨러가 고른 선호 강도(“훨씬 낫다”, “약간 낫다” 등)를 손실에 반영했다.

L(ϕ)=−log⁡σ(rϕ(x,yw)−rϕ(x,yl)−m(yw,yl))\mathcal{L}(\phi) = -\log \sigma\big(r_\phi(x,y_w) - r_\phi(x,y_l) - m(y_w, y_l)\big)

강한 선호일수록 큰 mm을 써서 그 쌍의 점수 차가 더 벌어지도록 요구한다. Lambert의 책에 따르면 Llama 3에서는 규모를 키우자 이득이 줄어 이 항을 뺐다.

K-wise (Plackett–Luce). K개 응답의 전체 순위 σ\sigma를 받았다면, “남은 것 중 1등을 softmax로 고르는 일”을 반복하는 확률 모델을 쓴다.

P(σ∣x)=∏k=0K−1exp⁡(r(x,yσ(k)))∑j=kK−1exp⁡(r(x,yσ(j)))P(\sigma \mid x) = \prod_{k=0}^{K-1} \frac{\exp\big(r(x, y_{\sigma(k)})\big)}{\sum_{j=k}^{K-1}\exp\big(r(x, y_{\sigma(j)})\big)}

K = 2이면 BT와 같다. Gumbel 유도와도 맞물린다. 효용에 Gumbel 잡음을 더하고 argmax를 고르면 그 결과는 정확히 softmax 분포를 따르고(Gumbel-max trick), 그것을 반복한 것이 Plackett–Luce다.

확인 문제Check yourself

보상모델 A의 출력은 r(x,y), 보상모델 B의 출력은 r(x,y) + 5·len(x) (prompt 길이에만 의존하는 항을 더함)이다. 두 RM의 BT 손실과 RL에서의 쓰임은?

BT 손실에는 같은 prompt 안의 차이 r(x,yw)−r(x,yl)r(x,y_w) - r(x,y_l)만 들어가므로 prompt에만 의존하는 항 c(x)c(x)는 사라진다. policy gradient에서도 c(x)c(x)는 Ey∼π[∇log⁡π(y∣x)]=0\mathbb{E}_{y\sim\pi}[\nabla\log\pi(y|x)] = 0이라 기대 gradient에 기여하지 않고, prompt별 평균을 빼는 baseline이나 GRPO식 그룹 정규화를 쓰면 표본에서도 정확히 사라진다. 다만 KL 항과의 상대적 크기는 스케일에 좌우되므로, 상수 이동이 아니라 곱셈은 결과를 바꾼다.

보상 함수의 종류

RLHF 문헌에서 “보상모델”이라는 이름 아래 꽤 다른 것들이 섞여 있다. 무엇을 예측하는지로 구분하면 명확하다.

종류입력예측하는 것학습 신호
선호 RM (BT)(x,y)(x, y) 전체선호 로짓. 차이만 의미 있음쌍 비교, −log⁡σ(rw−rl)-\log\sigma(r_w - r_l)
ORM (outcome)(x,y)(x, y), 토큰마다이 응답이 최종적으로 맞을 확률정답 여부(0/1), 토큰마다 BCE
PRM (process)(x,s1,…,sk)(x, s_1, \dots, s_k)각 추론 단계가 옳을 확률단계별 라벨, 단계 경계에서 BCE
가치함수 V(st)V(s_t)부분 응답 (x,y≤t)(x, y_{\le t})현재 정책을 따랐을 때의 기대 returnon-policy rollout의 return (TD/GAE)
LLM judge / 생성형 RMprompt + 응답(들) + 기준텍스트로 된 판정(점수, 승자)프롬프팅, 또는 판정 데이터로 미세조정

ORM. Cobbe et al.(2021)의 GSM8K 검증기가 원형이다. 정답을 맞힌 풀이와 틀린 풀이를 모아, 응답의 모든 토큰에서 “이 풀이는 결국 맞는가”를 이진 분류로 학습한다.

LORM=− E[1T∑t=1T(clog⁡pθ(y≤t)+(1−c)log⁡(1−pθ(y≤t)))],c∈{0,1}\mathcal{L}_{\text{ORM}} = -\,\mathbb{E}\Big[\tfrac{1}{T}\textstyle\sum_{t=1}^{T} \big(c \log p_\theta(y_{\le t}) + (1-c)\log(1 - p_\theta(y_{\le t}))\big)\Big], \quad c \in \{0, 1\}

PRM. Lightman et al.(2023)은 MATH 풀이의 각 단계에 사람이 긍정/중립/부정 라벨을 단 PRM800K를 만들고, 단계 경계에서만 손실을 거는 PRM을 학습했다. 같은 생성기의 후보 중 하나를 고르는 best-of-N에서 PRM이 ORM보다 뚜렷이 좋았다. 틀린 단계를 짚어 주는 더 촘촘한 신호이기 때문이다. 대가는 라벨 비용이고, 이후 연구들은 Monte Carlo rollout으로 단계 라벨을 자동으로 만드는 방향으로 갔다.

가치함수와의 차이. ORM과 가치함수는 둘 다 “부분 응답에서 결과를 예측”하는 모양이라 헷갈리기 쉽다. 차이는 어떤 정책 아래의 기대값인가다. ORM은 고정된 데이터에서 오프라인으로 학습한 정답 확률이고, 가치함수는 지금 학습 중인 정책의 rollout으로 계속 다시 맞추는 기대 return이며, 그 용도는 advantage 계산(분산 감소)이다(actor-critic 레슨). 보상모델은 “무엇이 좋은가”를, 가치함수는 “지금 정책이 여기서 얼마나 받을 것인가”를 말한다.

LLM-as-judge와 생성형 보상모델

강한 LLM에게 기준을 주고 두 응답 중 나은 쪽을 고르게 하거나 1–10점을 매기게 하는 방법은 싸고 빠르며, 사람 판단과의 일치도도 꽤 높다(Zheng et al. 2023). Constitutional AI의 AI 피드백, Tülu 3의 선호 데이터 라벨링, 대부분의 오픈 평가(MT-Bench, AlpacaEval, Arena-Hard)가 이 방식이다. 판정 전에 근거를 생성하게 하는 생성형 RM도 같은 계열이다.

알려진 편향은 다음과 같다.

  • 위치 편향(position bias): 먼저(또는 나중에) 제시된 응답을 더 고른다. 순서를 바꿔 두 번 묻고, 판정이 뒤집히면 무승부로 처리한다.
  • 장황함 편향(verbosity / length bias): 더 긴 응답을 선호한다. 길이를 회귀로 보정하는 length-controlled 평가가 나온 이유다. RL이 이 편향을 그대로 최적화하면 응답이 계속 길어진다.
  • 자기 선호(self-enhancement): 자기 자신(또는 같은 계열 모델)이 쓴 스타일을 선호한다.

Lambert의 책은 RM 벤치마크 기준으로 생성형 판정이 전용 분류기 RM보다 대체로 뒤처져 있다고 정리하고, 분산을 줄이려 판정은 temperature 0으로 샘플링하는 것이 흔하다고 적는다.

확인 문제Check yourself

MATH 풀이 64개 중 하나를 골라 제출하는 best-of-64에서, 같은 데이터 예산이라면 어떤 검증기가 더 유리할 가능성이 큰가?

Lightman et al.(2023)의 핵심 결과다. ORM은 결과만 보고 학습하므로 중간에 틀렸지만 답이 맞은 풀이와 깔끔한 풀이를 구분하는 신호가 약하다. PRM은 단계마다 라벨을 받아 첫 오류 지점을 학습한다. 가치함수는 특정 정책의 기대 return이지 정답 판정기가 아니며, 다른 생성기의 후보를 고르는 용도로 학습된 것이 아니다.

→ 더 깊이: 보상과 환경 — 검증기, rubric·생성형 보상, 다중 환경 RLVR까지 프론티어 RL의 보상 설계.

정리

  • Bradley–Terry는 효용에 Gumbel 잡음을 더한 선택 모델에서 나온다: P(yw≻yl)=σ(rw−rl)P(y_w \succ y_l) = \sigma(r_w - r_l). RM 손실은 그 음의 로그우도다.
  • gradient의 세기는 1−σ(Δ)1 - \sigma(\Delta), 즉 현재 틀릴 확률이다. 잘 맞힌 쌍은 학습에 거의 기여하지 않는다.
  • 보상의 이동(prompt별 상수)은 데이터로 정해지지 않고, 스케일은 라벨 잡음과 묶여 있다. RL에서는 r/βr/\beta만 의미가 있다.
  • Margin(Llama 2)과 Plackett–Luce(K-wise)는 더 풍부한 라벨을 쓰는 변형이다.
  • ORM은 최종 정답 확률, PRM은 단계별 정답 확률, 가치함수는 현재 정책의 기대 return, LLM judge는 텍스트 판정이다. LLM judge에는 위치·길이·자기 선호 편향이 있다.

더 읽을거리Further reading