Track 0 · Math Foundations · 10/10

정지 기울기와 대리 목적함수Stop-gradient and surrogate objectives

sg[·](.detach())의 정확한 의미, 값은 무의미하지만 gradient는 맞는 대리 목적함수, 샘플링 분포가 θ에 의존할 때 빠지는 score 항, score-function과 pathwise 추정량, straight-through를 유도하고, RL 손실 코드의 detach가 각각 무엇을 하는지 읽을 수 있게 한다.What sg[·] (.detach()) means exactly; surrogate objectives whose value is meaningless but whose gradient is right; the score term that disappears when the sampling distribution depends on θ; score-function vs pathwise estimators; straight-through — so that every detach in an RL loss can be read.

35 분min stop-gradient · detach · surrogate objective · score function · REINFORCE · reparameterization · pathwise gradient · straight-through · KL estimator · PPO 먼저 볼 것:Before this: 미분·연쇄법칙·JacobianDerivatives, the chain rule and Jacobians, 확률Probability

Open any RL training loop on this site and the “loss” is not the objective. It is a function built so that autograd returns an estimate of the objective’s gradient, and its value — printed in the logs — often means nothing. The tool that builds such functions is the stop-gradient sg⁡[⋅]\operatorname{sg}[\cdot], .detach() in PyTorch. Sixteen lessons use it; this one defines it and derives the handful of patterns they rely on.

What sg means

sg⁡[x]\operatorname{sg}[x] has the value of xx and is treated as a constant by differentiation: sg⁡[x]=x\operatorname{sg}[x] = x, ∇θsg⁡[x(θ)]=0\nabla_\theta\operatorname{sg}[x(\theta)] = 0. That makes it not a function of θ\theta in the ordinary sense (a function equal to x(θ)x(\theta) everywhere would have the same derivative), but a statement about which occurrences of θ\theta to differentiate. Precisely: for L(θ)=f(θ,sg⁡[g(θ)])L(\theta) = f\big(\theta, \operatorname{sg}[g(\theta)]\big),

∇L(θ)=∂1f(θ,g(θ)),\nabla L(\theta) = \partial_1 f\big(\theta, g(\theta)\big),

the partial derivative in the first slot, with the second slot frozen at its current value. In reverse-mode autograd this is literally cutting the edge from gg into the graph. Four identities cover almost every use:

expressionvaluegradientused for
x−sg⁡[x]x - \operatorname{sg}[x]00∇x\nabla xadding a gradient without changing the value
e x−sg⁡[x]e^{\,x - \operatorname{sg}[x]}11∇x\nabla xratios πθ/sg⁡[πθ]\pi_\theta/\operatorname{sg}[\pi_\theta] that equal 1 but carry ∇log⁡π\nabla\log\pi
sg⁡[a]+b−sg⁡[b]\operatorname{sg}[a] + b - \operatorname{sg}[b]aa∇b\nabla blog one quantity, differentiate another (k3+, straight-through)
sg⁡[w]⋅ℓ(θ)\operatorname{sg}[w]\cdot \ell(\theta)wℓw\ellw∇ℓw\nabla\ellper-sample weights: IS ratios, advantages, masks

In code, exp⁡(log⁡π−log⁡π.detach())\exp(\log\pi - \log\pi\text{.detach()}) is how GSPO and others attach a token-level gradient to a sequence-level weight, and k3.detach() + (k2 - k2.detach()) is the k3+ loss.

Surrogates: right gradient, meaningless value

The policy-gradient objective is J(θ)=Ey∼πθ[R(y)]J(\theta) = \mathbb{E}_{y\sim\pi_\theta}[R(y)]. Its gradient (the log-derivative trick) is

∇J=∑y∇πθ(y) R(y)=∑yπθ(y) ∇log⁡πθ(y) R(y)=Ey∼πθ[R(y) ∇log⁡πθ(y)].\nabla J = \sum_y \nabla\pi_\theta(y)\,R(y) = \sum_y \pi_\theta(y)\,\nabla\log\pi_\theta(y)\,R(y) = \mathbb{E}_{y\sim\pi_\theta}\big[R(y)\,\nabla\log\pi_\theta(y)\big].

Autograd cannot differentiate “sampling from πθ\pi_\theta”. So we draw y1,…,yny_1, \ldots, y_n from the current policy, hold them fixed, and write a function whose gradient is the estimator:

L(θ)=1n∑isg⁡[R(yi)−b] log⁡πθ(yi),∇L=1n∑i(R(yi)−b)∇log⁡πθ(yi).L(\theta) = \frac1n\sum_i \operatorname{sg}\big[R(y_i) - b\big]\,\log\pi_\theta(y_i), \qquad \nabla L = \frac1n\sum_i \big(R(y_i) - b\big)\nabla\log\pi_\theta(y_i).

LL is a surrogate. Its gradient at the current θ\theta is an unbiased estimate of ∇J\nabla J (the baseline bb adds b E[∇log⁡π]=0b\,\mathbb{E}[\nabla\log\pi] = 0). Its value is not JJ: it depends on bb, and it is negative whenever R−b>0R - b > 0. Since ∇L\nabla L estimates ∇J\nabla J, LL is maximised by gradient ascent; a framework minimiser is handed loss=−L\text{loss} = -L. Even so, optimising it to convergence on one fixed batch would be wrong, because the samples are only valid at the θ\theta that drew them. PPO’s Eπold[ρθA]\mathbb{E}_{\pi_{\text{old}}}[\rho_\theta A] with ρθ=πθ/πold\rho_\theta = \pi_\theta/\pi_{\text{old}} is the same idea with importance weights, so that several gradient steps can reuse one batch: at θ=θold\theta = \theta_{\text{old}}, ∇ρ=∇log⁡πθ\nabla\rho = \nabla\log\pi_\theta and the gradient is again E[A∇log⁡π]\mathbb{E}[A\nabla\log\pi]; away from it, the surrogate is a first-order model of JJ that is only trusted nearby, which is what the clip enforces.

이 사이트의 RL 학습 루프 어느 것을 열어도 “손실”은 목적함수가 아니다. autograd가 목적함수 gradient의 추정값을 돌려주도록 만든 함수이고, 로그에 찍히는 그 값은 아무 의미가 없을 때가 많다. 그런 함수를 만드는 도구가 stop-gradient sg⁡[⋅]\operatorname{sg}[\cdot], PyTorch의 .detach()다. 열여섯 개 레슨이 이것을 쓴다. 이 레슨은 그것을 정의하고 그 레슨들이 기대는 몇 가지 패턴을 유도한다.

sg의 뜻

sg⁡[x]\operatorname{sg}[x]는 값은 xx이고 미분에서는 상수로 취급된다: sg⁡[x]=x\operatorname{sg}[x] = x, ∇θsg⁡[x(θ)]=0\nabla_\theta\operatorname{sg}[x(\theta)] = 0. 그러니 보통 뜻의 θ\theta의 함수가 아니다(어디서나 x(θ)x(\theta)와 같은 함수라면 도함수도 같았을 것이다). θ\theta가 나오는 자리 중 어느 것을 미분할지에 대한 진술이다. 정확히는 L(θ)=f(θ,sg⁡[g(θ)])L(\theta) = f\big(\theta, \operatorname{sg}[g(\theta)]\big)에 대해

∇L(θ)=∂1f(θ,g(θ)),\nabla L(\theta) = \partial_1 f\big(\theta, g(\theta)\big),

곧 두 번째 자리를 현재 값에 얼려 둔 채 첫 번째 자리로 편미분한 것이다. reverse-mode autograd에서는 gg에서 그래프로 들어오는 간선을 문자 그대로 끊는 일이다. 네 개의 항등식이 거의 모든 쓰임을 덮는다.

식값gradient쓰임
x−sg⁡[x]x - \operatorname{sg}[x]00∇x\nabla x값을 바꾸지 않고 gradient만 더하기
e x−sg⁡[x]e^{\,x - \operatorname{sg}[x]}11∇x\nabla x값은 1이지만 ∇log⁡π\nabla\log\pi를 실어 나르는 비율 πθ/sg⁡[πθ]\pi_\theta/\operatorname{sg}[\pi_\theta]
sg⁡[a]+b−sg⁡[b]\operatorname{sg}[a] + b - \operatorname{sg}[b]aa∇b\nabla b한 양을 기록하고 다른 양을 미분 (k3+, straight-through)
sg⁡[w]⋅ℓ(θ)\operatorname{sg}[w]\cdot \ell(\theta)wℓw\ellw∇ℓw\nabla\ell표본별 가중치: IS 비율, advantage, 마스크

코드에서 exp⁡(log⁡π−log⁡π.detach())\exp(\log\pi - \log\pi\text{.detach()})는 GSPO 등이 시퀀스 단위 가중치에 토큰 단위 gradient를 붙이는 방법이고, k3.detach() + (k2 - k2.detach())가 k3+ 손실이다.

대리 함수: gradient는 맞고 값은 무의미하다

policy gradient의 목적함수는 J(θ)=Ey∼πθ[R(y)]J(\theta) = \mathbb{E}_{y\sim\pi_\theta}[R(y)]이고, 그 gradient(log-derivative trick)는

∇J=∑y∇πθ(y) R(y)=∑yπθ(y) ∇log⁡πθ(y) R(y)=Ey∼πθ[R(y) ∇log⁡πθ(y)].\nabla J = \sum_y \nabla\pi_\theta(y)\,R(y) = \sum_y \pi_\theta(y)\,\nabla\log\pi_\theta(y)\,R(y) = \mathbb{E}_{y\sim\pi_\theta}\big[R(y)\,\nabla\log\pi_\theta(y)\big].

autograd는 “πθ\pi_\theta에서 샘플링하기”를 미분하지 못한다. 그래서 현재 정책에서 y1,…,yny_1, \ldots, y_n을 뽑아 고정해 두고, gradient가 추정량이 되는 함수를 쓴다.

L(θ)=1n∑isg⁡[R(yi)−b] log⁡πθ(yi),∇L=1n∑i(R(yi)−b)∇log⁡πθ(yi).L(\theta) = \frac1n\sum_i \operatorname{sg}\big[R(y_i) - b\big]\,\log\pi_\theta(y_i), \qquad \nabla L = \frac1n\sum_i \big(R(y_i) - b\big)\nabla\log\pi_\theta(y_i).

LL은 대리 함수(surrogate) 다. 현재 θ\theta에서의 gradient는 ∇J\nabla J의 비편향 추정이다(baseline bb는 b E[∇log⁡π]=0b\,\mathbb{E}[\nabla\log\pi] = 0을 더할 뿐이다). 값은 JJ가 아니다. bb에 따라 바뀌고, R−b>0R - b > 0이면 음수다. ∇L\nabla L이 ∇J\nabla J를 추정하므로 LL은 gradient ascent로 최대화하고, 최소화기(optimizer)에는 loss=−L\text{loss} = -L을 넘긴다. 그래도 고정된 한 배치에서 수렴할 때까지 최적화하면 틀린다. 표본은 그것을 뽑은 θ\theta에서만 유효하기 때문이다. PPO의 Eπold[ρθA]\mathbb{E}_{\pi_{\text{old}}}[\rho_\theta A], ρθ=πθ/πold\rho_\theta = \pi_\theta/\pi_{\text{old}}는 같은 생각에 importance weight를 붙여 한 배치로 여러 번 gradient step을 밟게 한 것이다. θ=θold\theta = \theta_{\text{old}}에서 ∇ρ=∇log⁡πθ\nabla\rho = \nabla\log\pi_\theta이므로 gradient는 다시 E[A∇log⁡π]\mathbb{E}[A\nabla\log\pi]다. 거기서 멀어지면 대리 함수는 근처에서만 믿을 수 있는 JJ의 1차 모형이고, clip이 그것을 강제한다.

dJ/dθ – dLlog/dθ – dLratio/dθ – dLclip/dθ – Llog(θold) –
A policy πθ = softmax(θ·(1, 0, −1)) over three actions with rewards (1, 0.4, 0). Black: the true improvement J(θ) − J(θold). Blue: the REINFORCE surrogate Σ πold·sg[A]·log πθ (shifted to pass through 0) — a different function. Green: the ratio surrogate Eold[ρA] (in a one-step problem it coincides with black; with states it would not). Red: PPO's clipped surrogate. Drag θold: all four curves share one tangent (dashed) at θold, so all give the same gradient there, and nowhere else. Shrink ε: the clipped surrogate goes flat sooner, removing the incentive to move far. 세 행동 위의 정책 πθ = softmax(θ·(1, 0, −1)), 보상은 (1, 0.4, 0). 검정: 실제 개선량 J(θ) − J(θold). 파랑: REINFORCE 대리 함수 Σ πold·sg[A]·log πθ(0을 지나도록 옮김) — 다른 함수다. 초록: ratio 대리 함수 Eold[ρA](한 step짜리 문제에서는 검정과 겹치고, 상태가 있으면 그렇지 않다). 빨강: PPO의 clip된 대리 함수. θold를 끌면 네 곡선이 θold에서 접선(점선) 하나를 공유한다. 그러니 거기서는 모두 같은 gradient를 주고, 다른 곳에서는 아니다. ε를 줄이면 clip된 대리 함수가 더 일찍 평평해져 멀리 움직일 유인이 사라진다.

The missing score term: value estimators are not gradient estimators

Suppose the quantity is itself an expectation under the policy, with an integrand that also depends on θ\theta: F(θ)=Ey∼πθ[fθ(y)]F(\theta) = \mathbb{E}_{y\sim\pi_\theta}[f_\theta(y)]. The product rule gives two terms:

∇F=Ey∼πθ[∇fθ(y)]⏟what autograd sees+Ey∼πθ[fθ(y) ∇log⁡πθ(y)]⏟the score term — invisible to autograd.\nabla F = \underbrace{\mathbb{E}_{y\sim\pi_\theta}\big[\nabla f_\theta(y)\big]}_{\text{what autograd sees}} + \underbrace{\mathbb{E}_{y\sim\pi_\theta}\big[f_\theta(y)\,\nabla\log\pi_\theta(y)\big]}_{\text{the score term — invisible to autograd}} .

Differentiating a sample average 1n∑ifθ(yi)\frac1n\sum_i f_\theta(y_i) with the samples held fixed computes only the first term. The KL penalty is the standard trap. With fθ=k1=log⁡πθπreff_\theta = k_1 = \log\frac{\pi_\theta}{\pi_{\text{ref}}}, the sample mean of k1k_1 is an unbiased estimate of KL(πθ∥πref)\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}}), but ∇k1=∇log⁡πθ\nabla k_1 = \nabla\log\pi_\theta has expectation zero: as a loss, k1k_1 does nothing on average. The fixes, all derived from the formula above:

  • Add the score term explicitly: L~=fθ+sg⁡[fθ]log⁡πθ\tilde L = f_\theta + \operatorname{sg}[f_\theta]\log\pi_\theta. Its gradient is ∇f+f∇log⁡π\nabla f + f\nabla\log\pi, both terms. For k1k_1 that gives k1∇log⁡πk_1\nabla\log\pi, the true ∇KL\nabla\mathrm{KL}. This is the general rule for stochastic computation graphs (Schulman et al., 2015).
  • Choose an integrand whose naive gradient happens to be right: k2=12(log⁡πθπref)2k_2 = \tfrac12(\log\frac{\pi_\theta}{\pi_{\text{ref}}})^2 has ∇k2=k1∇log⁡π\nabla k_2 = k_1\nabla\log\pi — exactly the score term for k1k_1. That is why ”k2k_2 as a loss” gives the reverse-KL gradient.
  • Put the KL in the reward: use sg⁡[k1]\operatorname{sg}[k_1] as a negative reward inside the REINFORCE surrogate; the score-function machinery then supplies k1∇log⁡πk_1\nabla\log\pi.
  • Know what the others give: k3=r−1−log⁡rk_3 = r - 1 - \log r with r=πref/πθr = \pi_{\text{ref}}/\pi_\theta has ∇k3=(1−r)∇log⁡πθ\nabla k_3 = (1 - r)\nabla\log\pi_\theta, whose expectation under πθ\pi_\theta is −Eπref[∇log⁡πθ]=∇KL(πref∥πθ)-\mathbb{E}_{\pi_{\text{ref}}}[\nabla\log\pi_\theta] = \nabla\mathrm{KL}(\pi_{\text{ref}}\|\pi_\theta) — the forward KL’s gradient, not the reverse.
NumPy sg identities with a 30-line autograd, and the straight-through trick
import math

class V:
    """A scalar with reverse-mode autodiff. detach() returns the same value with no history: sg[x]."""
    def __init__(self, x, parents=()):
        self.x, self.g, self.parents = float(x), 0.0, parents   # parents: (node, local derivative)
    def __add__(a, b): b = b if isinstance(b, V) else V(b); return V(a.x + b.x, ((a, 1.0), (b, 1.0)))
    def __sub__(a, b): b = b if isinstance(b, V) else V(b); return V(a.x - b.x, ((a, 1.0), (b, -1.0)))
    def __mul__(a, b): b = b if isinstance(b, V) else V(b); return V(a.x * b.x, ((a, b.x), (b, a.x)))
    __radd__, __rmul__ = __add__, __mul__
    def __rsub__(a, b): return V(b) - a
    def exp(a): e = math.exp(a.x); return V(e, ((a, e),))
    def log(a): return V(math.log(a.x), ((a, 1 / a.x),))
    def detach(a): return V(a.x)                                # value kept, graph cut
    def backward(self):
        order, seen = [], set()
        def topo(v):
            if id(v) in seen:
                return
            seen.add(id(v))
            for p, _ in v.parents:
                topo(p)
            order.append(v)
        topo(self)
        self.g = 1.0
        for v in reversed(order):
            for p, d in v.parents:
                p.g += d * v.g

def value_and_grad(f, x0):
    x = V(x0)
    y = f(x)
    y.backward()
    return y.x, x.g

x0 = 0.7
for name, f in [("x - sg[x]",            lambda x: x - x.detach()),
                ("exp(x - sg[x])",       lambda x: (x - x.detach()).exp()),
                ("x^2 * sg[x]",          lambda x: x * x * x.detach()),
                ("sg[x^3] + x^2 - sg[x^2]", lambda x: (x * x * x).detach() + x * x - (x * x).detach())]:
    v, g = value_and_grad(f, x0)
    print(f"{name:24s} value {v:8.4f}   d/dx {g:8.4f}")
print(f"(compare: x^3 = {x0**3:.4f}, d(x^3)/dx = {3*x0**2:.4f}, d(x^2)/dx = {2*x0:.4f})")

# Straight-through: forward rounds, backward pretends the rounding was the identity
v, g = value_and_grad(lambda x: x + (V(round(x.x)) - x).detach(), 2.3)
print(f"\nstraight-through round(2.3): value {v}, gradient {g}")
 
NumPy Which losses give which gradients: REINFORCE, k1, k2, k3, and the score-term fix
import numpy as np
rs = np.random.default_rng(0)

K = 5
theta = rs.normal(0, 1, K)                     # policy logits
ref = rs.normal(0, 1, K)                       # reference logits
r = rs.normal(0, 1, K)                         # reward of each action
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
p, q = softmax(theta), softmax(ref)
J = lambda th: softmax(th) @ r

# d log pi(a) / d theta = onehot(a) - p   (softmax score function)
score = np.eye(K) - p                          # row a = grad of log pi(a)

# exact gradients, by central differences of the exact expectations
def numgrad(F, th, h=1e-6):
    return np.array([(F(th + h * e) - F(th - h * e)) / (2 * h) for e in np.eye(K)])
KLf = lambda th: softmax(th) @ (np.log(softmax(th)) - np.log(q))      # KL(pi || ref)
KLr = lambda th: q @ (np.log(q) - np.log(softmax(th)))                # KL(ref || pi)
gJ, gKLf, gKLr = numgrad(J, theta), numgrad(KLf, theta), numgrad(KLr, theta)

n = 200_000
a = rs.choice(K, n, p=p)                       # samples from the current policy (fixed: no gradient)
S = score[a]                                   # (n, K) per-sample grad log pi(a)
lr = np.log(p[a]) - np.log(q[a])               # per-sample log ratio log pi/ref

def report(name, per_sample_grad, target):
    g = per_sample_grad.mean(0)
    print(f"{name:30s} |mean grad| {np.abs(g).max():.3f}   |target| {np.abs(target).max():.3f}   error {np.abs(g - target).max():.4f}")

# 1) REINFORCE surrogate  L = sg[r(a) - b] * log pi(a):  grad = (r - b) * score
b = p @ r
report("sg[r-b] log pi -> grad J", (r[a] - b)[:, None] * S, gJ)
# differentiating r(a) itself gives nothing: r does not depend on theta, sampling is not differentiated
# 2) KL estimators used directly as losses (samples held fixed)
report("k1 -> grad KL(pi||ref)", S, gKLf)                              # grad k1 = score
report("k2 -> grad KL(pi||ref)", lr[:, None] * S, gKLf)              # grad k2 = k1 * score
report("k3 -> grad KL(ref||pi)", (1 - q[a] / p[a])[:, None] * S, gKLr)
# 3) the score-function surrogate fixes k1:  L = k1 + sg[k1] * log pi
report("k1 + sg[k1] log pi -> grad KL", S + lr[:, None] * S, gKLf)
print(f"\nmean of k1 itself: {lr.mean():.4f}  = KL(pi||ref) {KLf(theta):.4f}   (a fine VALUE estimator)")

# The same per-sample gradient from the scalar autograd above, for one sample: L = k1 + sg[k1] * log pi(a)
th = [V(t) for t in theta]
logp_a = th[a[0]] - sum((t.exp() for t in th), V(0.0)).log()
k1 = logp_a - math.log(q[a[0]])
(k1 + k1.detach() * logp_a).backward()
print("autograd:", np.round([t.g for t in th], 4), "\nformula: ", np.round(S[0] + lr[0] * S[0], 4))
 

Score function vs pathwise

The log-derivative trick is one of two ways to differentiate an expectation. If the sample can be written as a differentiable function of θ\theta and parameter-free noise — x=μ+σϵx = \mu + \sigma\epsilon, ϵ∼N(0,1)\epsilon\sim\mathcal N(0,1) — the derivative can move inside:

∇θ Ex∼pθ[f(x)]=Eϵ[∇θf(g(θ,ϵ))](pathwise / reparameterisation),=Ex∼pθ[f(x) ∇θlog⁡pθ(x)](score function).\nabla_\theta\,\mathbb{E}_{x\sim p_\theta}[f(x)] = \mathbb{E}_{\epsilon}\big[\nabla_\theta f(g(\theta,\epsilon))\big] \quad\text{(pathwise / reparameterisation)}, \qquad = \mathbb{E}_{x\sim p_\theta}\big[f(x)\,\nabla_\theta\log p_\theta(x)\big] \quad\text{(score function)}.

Both are unbiased; they differ in variance and in what they need. The pathwise estimator uses f′f' and is usually far less noisy — VAEs rely on it. The score-function estimator needs only values of ff, which is all a reward model or a verifier provides, and it works for discrete samples such as tokens, where no reparameterisation exists. Its variance is the price, and baselines (control variates) are the standard way to pay less of it.

빠진 score 항: 값 추정량은 gradient 추정량이 아니다

구하려는 양이 정책 아래의 기댓값이고, 피적분 함수도 θ\theta에 의존한다고 하자: F(θ)=Ey∼πθ[fθ(y)]F(\theta) = \mathbb{E}_{y\sim\pi_\theta}[f_\theta(y)]. 곱의 미분법이 두 항을 준다.

∇F=Ey∼πθ[∇fθ(y)]⏟autograd가 보는 것+Ey∼πθ[fθ(y) ∇log⁡πθ(y)]⏟score 항 — autograd에는 안 보인다.\nabla F = \underbrace{\mathbb{E}_{y\sim\pi_\theta}\big[\nabla f_\theta(y)\big]}_{\text{autograd가 보는 것}} + \underbrace{\mathbb{E}_{y\sim\pi_\theta}\big[f_\theta(y)\,\nabla\log\pi_\theta(y)\big]}_{\text{score 항 — autograd에는 안 보인다}} .

표본을 고정한 채 표본 평균 1n∑ifθ(yi)\frac1n\sum_i f_\theta(y_i)를 미분하면 첫 항만 계산된다. KL 벌점이 대표적인 함정이다. fθ=k1=log⁡πθπreff_\theta = k_1 = \log\frac{\pi_\theta}{\pi_{\text{ref}}}로 두면 k1k_1의 표본 평균은 KL(πθ∥πref)\mathrm{KL}(\pi_\theta\|\pi_{\text{ref}})의 비편향 추정이지만, ∇k1=∇log⁡πθ\nabla k_1 = \nabla\log\pi_\theta의 기댓값은 0이다. 손실로 쓴 k1k_1은 평균적으로 아무것도 하지 않는다. 위 식에서 나오는 처방들.

  • score 항을 명시적으로 더한다: L~=fθ+sg⁡[fθ]log⁡πθ\tilde L = f_\theta + \operatorname{sg}[f_\theta]\log\pi_\theta. gradient가 ∇f+f∇log⁡π\nabla f + f\nabla\log\pi, 두 항 모두다. k1k_1에 대해서는 k1∇log⁡πk_1\nabla\log\pi, 곧 참 ∇KL\nabla\mathrm{KL}이다. 확률적 계산 그래프의 일반 규칙이다(Schulman et al., 2015).
  • 순진한 gradient가 마침 맞는 피적분 함수를 고른다: k2=12(log⁡πθπref)2k_2 = \tfrac12(\log\frac{\pi_\theta}{\pi_{\text{ref}}})^2는 ∇k2=k1∇log⁡π\nabla k_2 = k_1\nabla\log\pi — 정확히 k1k_1의 score 항이다. “손실로 쓴 k2k_2“가 reverse KL의 gradient를 주는 이유다.
  • KL을 보상에 넣는다: sg⁡[k1]\operatorname{sg}[k_1]을 REINFORCE 대리 함수 안의 음의 보상으로 쓰면 score-function 기계가 k1∇log⁡πk_1\nabla\log\pi를 공급한다.
  • 나머지가 무엇을 주는지 알아 둔다: r=πref/πθr = \pi_{\text{ref}}/\pi_\theta일 때 k3=r−1−log⁡rk_3 = r - 1 - \log r은 ∇k3=(1−r)∇log⁡πθ\nabla k_3 = (1 - r)\nabla\log\pi_\theta이고, πθ\pi_\theta 아래 기댓값은 −Eπref[∇log⁡πθ]=∇KL(πref∥πθ)-\mathbb{E}_{\pi_{\text{ref}}}[\nabla\log\pi_\theta] = \nabla\mathrm{KL}(\pi_{\text{ref}}\|\pi_\theta) — reverse가 아니라 forward KL의 gradient다.
NumPy 30줄짜리 autograd로 보는 sg 항등식, 그리고 straight-through
import math

class V:
    """reverse-mode 자동미분을 하는 스칼라. detach()는 이력 없이 같은 값을 돌려준다: sg[x]."""
    def __init__(self, x, parents=()):
        self.x, self.g, self.parents = float(x), 0.0, parents   # parents: (노드, 국소 도함수)
    def __add__(a, b): b = b if isinstance(b, V) else V(b); return V(a.x + b.x, ((a, 1.0), (b, 1.0)))
    def __sub__(a, b): b = b if isinstance(b, V) else V(b); return V(a.x - b.x, ((a, 1.0), (b, -1.0)))
    def __mul__(a, b): b = b if isinstance(b, V) else V(b); return V(a.x * b.x, ((a, b.x), (b, a.x)))
    __radd__, __rmul__ = __add__, __mul__
    def __rsub__(a, b): return V(b) - a
    def exp(a): e = math.exp(a.x); return V(e, ((a, e),))
    def log(a): return V(math.log(a.x), ((a, 1 / a.x),))
    def detach(a): return V(a.x)                                # 값은 유지, 그래프는 끊김
    def backward(self):
        order, seen = [], set()
        def topo(v):
            if id(v) in seen:
                return
            seen.add(id(v))
            for p, _ in v.parents:
                topo(p)
            order.append(v)
        topo(self)
        self.g = 1.0
        for v in reversed(order):
            for p, d in v.parents:
                p.g += d * v.g

def value_and_grad(f, x0):
    x = V(x0)
    y = f(x)
    y.backward()
    return y.x, x.g

x0 = 0.7
for name, f in [("x - sg[x]",            lambda x: x - x.detach()),
                ("exp(x - sg[x])",       lambda x: (x - x.detach()).exp()),
                ("x^2 * sg[x]",          lambda x: x * x * x.detach()),
                ("sg[x^3] + x^2 - sg[x^2]", lambda x: (x * x * x).detach() + x * x - (x * x).detach())]:
    v, g = value_and_grad(f, x0)
    print(f"{name:24s} value {v:8.4f}   d/dx {g:8.4f}")
print(f"(compare: x^3 = {x0**3:.4f}, d(x^3)/dx = {3*x0**2:.4f}, d(x^2)/dx = {2*x0:.4f})")

# Straight-through: 순방향은 반올림, 역방향은 반올림이 항등함수였던 척
v, g = value_and_grad(lambda x: x + (V(round(x.x)) - x).detach(), 2.3)
print(f"\nstraight-through round(2.3): value {v}, gradient {g}")
 
NumPy 어떤 손실이 어떤 gradient를 주나: REINFORCE, k1, k2, k3, score 항 처방
import numpy as np
rs = np.random.default_rng(0)

K = 5
theta = rs.normal(0, 1, K)                     # 정책 logit
ref = rs.normal(0, 1, K)                       # reference logit
r = rs.normal(0, 1, K)                         # 행동별 보상
softmax = lambda z: np.exp(z - z.max()) / np.exp(z - z.max()).sum()
p, q = softmax(theta), softmax(ref)
J = lambda th: softmax(th) @ r

# d log pi(a) / d theta = onehot(a) - p   (softmax의 score function)
score = np.eye(K) - p                          # a번째 행 = log pi(a)의 gradient

# 정확한 기댓값을 중심 차분해서 얻은 정확한 gradient
def numgrad(F, th, h=1e-6):
    return np.array([(F(th + h * e) - F(th - h * e)) / (2 * h) for e in np.eye(K)])
KLf = lambda th: softmax(th) @ (np.log(softmax(th)) - np.log(q))      # KL(pi || ref)
KLr = lambda th: q @ (np.log(q) - np.log(softmax(th)))                # KL(ref || pi)
gJ, gKLf, gKLr = numgrad(J, theta), numgrad(KLf, theta), numgrad(KLr, theta)

n = 200_000
a = rs.choice(K, n, p=p)                       # 현재 정책의 샘플 (고정: gradient 없음)
S = score[a]                                   # (n, K) 표본별 grad log pi(a)
lr = np.log(p[a]) - np.log(q[a])               # 표본별 로그 비율 log pi/ref

def report(name, per_sample_grad, target):
    g = per_sample_grad.mean(0)
    print(f"{name:30s} |mean grad| {np.abs(g).max():.3f}   |target| {np.abs(target).max():.3f}   error {np.abs(g - target).max():.4f}")

# 1) REINFORCE 대리 함수  L = sg[r(a) - b] * log pi(a):  grad = (r - b) * score
b = p @ r
report("sg[r-b] log pi -> grad J", (r[a] - b)[:, None] * S, gJ)
# r(a) 자체를 미분하면 아무것도 없다: r은 theta에 의존하지 않고, 샘플링은 미분되지 않는다
# 2) KL 추정량을 그대로 손실로 쓰기 (표본 고정)
report("k1 -> grad KL(pi||ref)", S, gKLf)                              # grad k1 = score
report("k2 -> grad KL(pi||ref)", lr[:, None] * S, gKLf)              # grad k2 = k1 * score
report("k3 -> grad KL(ref||pi)", (1 - q[a] / p[a])[:, None] * S, gKLr)
# 3) score-function 대리 함수가 k1을 고친다:  L = k1 + sg[k1] * log pi
report("k1 + sg[k1] log pi -> grad KL", S + lr[:, None] * S, gKLf)
print(f"\nmean of k1 itself: {lr.mean():.4f}  = KL(pi||ref) {KLf(theta):.4f}   (a fine VALUE estimator)")

# 위의 스칼라 autograd로 표본 하나에 대해 같은 gradient: L = k1 + sg[k1] * log pi(a)
th = [V(t) for t in theta]
logp_a = th[a[0]] - sum((t.exp() for t in th), V(0.0)).log()
k1 = logp_a - math.log(q[a[0]])
(k1 + k1.detach() * logp_a).backward()
print("autograd:", np.round([t.g for t in th], 4), "\nformula: ", np.round(S[0] + lr[0] * S[0], 4))
 

Score function vs pathwise

log-derivative trick은 기댓값을 미분하는 두 방법 중 하나다. 표본을 θ\theta와 매개변수 없는 잡음의 미분 가능한 함수로 쓸 수 있으면 — x=μ+σϵx = \mu + \sigma\epsilon, ϵ∼N(0,1)\epsilon\sim\mathcal N(0,1) — 미분이 안으로 들어간다.

∇θ Ex∼pθ[f(x)]=Eϵ[∇θf(g(θ,ϵ))](pathwise / reparameterisation),=Ex∼pθ[f(x) ∇θlog⁡pθ(x)](score function).\nabla_\theta\,\mathbb{E}_{x\sim p_\theta}[f(x)] = \mathbb{E}_{\epsilon}\big[\nabla_\theta f(g(\theta,\epsilon))\big] \quad\text{(pathwise / reparameterisation)}, \qquad = \mathbb{E}_{x\sim p_\theta}\big[f(x)\,\nabla_\theta\log p_\theta(x)\big] \quad\text{(score function)}.

둘 다 비편향이고, 분산과 필요한 것이 다르다. pathwise 추정량은 f′f'을 쓰고 대개 훨씬 조용하다. VAE가 이것에 기댄다. score-function 추정량은 ff의 값만 있으면 되는데, 보상모델이나 verifier가 주는 것이 딱 그것뿐이고, 재매개변수화가 없는 토큰 같은 이산 표본에도 통한다. 대가는 분산이고, baseline(control variate)이 그 대가를 덜 치르는 표준 방법이다.

참값true ∇ – score – score − b – pathwise –
Each row is a histogram of 4000 one-sample estimates of the same derivative, d/dμ E[f(x)] with x ~ N(μ, 1); the black line is the true value and each row's readout is mean ± sd. The score-function estimator f(x)·(x−μ) needs only f's values (it is what the log-derivative trick and every RL policy gradient use) but is noisy; subtracting a baseline b = E[f] removes much of the noise without bias. The pathwise estimator f′(x), from x = μ + ε, is far less noisy — until you pick the step function: f′ = 0 almost everywhere, so the pathwise estimate is 0 while the true derivative is not. 각 줄은 같은 미분 d/dμ E[f(x)], x ~ N(μ, 1)의 표본 하나짜리 추정값 4000개의 히스토그램이다. 검은 선이 참값이고, 각 줄의 수치는 평균 ± 표준편차다. score-function 추정량 f(x)·(x−μ)는 f의 값만 있으면 되지만(log-derivative trick과 모든 RL policy gradient가 이것이다) 잡음이 크다. baseline b = E[f]를 빼면 편향 없이 잡음이 크게 준다. pathwise 추정량 f′(x)(x = μ + ε로 미분)는 훨씬 조용하다 — 계단 함수를 고르기 전까지는. f′가 거의 모든 곳에서 0이므로 pathwise 추정은 0인데, 참값은 0이 아니다.

Straight-through

Some operations have a useless derivative: rounding, argmax, quantisation, sampling a discrete code. The straight-through estimator runs the real operation forward and pretends it was the identity backward:

y^=x+sg⁡[q(x)−x],y^=q(x),∇y^=∇x.\hat y = x + \operatorname{sg}\big[q(x) - x\big], \qquad \hat y = q(x),\quad \nabla\hat y = \nabla x .

It is biased — the gradient of a function that was not computed — but it points somewhere useful when q(x)≈xq(x) \approx x, and it is the workhorse of quantisation-aware training and vector-quantised codebooks. The k3+ loss is the same construction with a different pair: k3’s value for logging, k2’s gradient for training.

확인 문제Check yourself

An RL loss adds beta * mean(k1) over sampled tokens, with k1 = logp - ref_logp and logp NOT detached. What does that KL term contribute to the expected gradient?

With the samples fixed, ∇k1=∇log⁡πθ(y)\nabla k_1 = \nabla\log\pi_\theta(y), and Ey∼πθ[∇log⁡πθ(y)]=∇∑yπθ(y)=0\mathbb{E}_{y\sim\pi_\theta}[\nabla\log\pi_\theta(y)] = \nabla\sum_y\pi_\theta(y) = 0. The score term k1∇log⁡πk_1\nabla\log\pi is missing. Use k2k_2, put sg⁡[k1]\operatorname{sg}[k_1] in the reward, or add sg⁡[k1]log⁡π\operatorname{sg}[k_1]\log\pi to the loss. (k3k_3 in the loss would give the forward-KL gradient.)

PyTorch PyTorch idioms: what each detach does 로컬에서 실행run locally (pip install torch)
import torch

def policy_loss(logp, old_logp, ref_logp, adv, mask, beta=0.01, eps=0.2):
    """logp: (B, T) log-probs of the sampled tokens under the current policy (requires grad)."""
    ratio = torch.exp(logp - old_logp)                 # old_logp has no grad: a constant pi_old
    pg = -torch.min(ratio * adv, ratio.clamp(1 - eps, 1 + eps) * adv)   # adv is data: no grad
    # at the first step ratio == 1, but d ratio = ratio * d logp  ->  REINFORCE gradient

    lr = logp - ref_logp                               # k1 per token
    k2 = 0.5 * lr ** 2                                 # grad = k1 * grad logp  (reverse-KL gradient)
    k3 = torch.exp(-lr) - 1 + lr                       # value: unbiased KL; grad: forward-KL direction
    k3_plus = k3.detach() + (k2 - k2.detach())         # log k3, train with k2

    seq_w = torch.exp(((logp - old_logp) * mask).sum(1) / mask.sum(1)).detach()   # a sequence weight
    tok = seq_w[:, None] * torch.exp(logp - logp.detach())   # value seq_w, grad seq_w * grad logp
    loss = ((pg + beta * k3_plus) * mask).sum() / mask.sum()
    return loss, tok
 

Summary

  • sg⁡[x]\operatorname{sg}[x]: value xx, derivative 0 — a rule about which occurrences of θ to differentiate: ∇f(θ,sg⁡[g])=∂1f\nabla f(\theta, \operatorname{sg}[g]) = \partial_1 f.
  • Four identities: x−sg⁡[x]x - \operatorname{sg}[x], ex−sg⁡[x]e^{x - \operatorname{sg}[x]}, sg⁡[a]+b−sg⁡[b]\operatorname{sg}[a] + b - \operatorname{sg}[b], sg⁡[w]ℓ\operatorname{sg}[w]\ell.
  • A surrogate has the right gradient at the sampling θ and a meaningless value; PPO’s ratio surrogate is a first-order model trusted only near θold\theta_{\text{old}}.
  • ∇Eπθ[fθ]=E[∇fθ]+E[fθ∇log⁡πθ]\nabla\mathbb{E}_{\pi_\theta}[f_\theta] = \mathbb{E}[\nabla f_\theta] + \mathbb{E}[f_\theta\nabla\log\pi_\theta]; autograd on fixed samples drops the second term. k1k_1 as a loss gives 0, k2k_2 gives reverse KL, k3k_3 gives forward KL, f+sg⁡[f]log⁡πf + \operatorname{sg}[f]\log\pi gives the full gradient.
  • Pathwise gradients are low-variance but need a differentiable path; score-function gradients need only values and work for tokens.
  • Straight-through: x+sg⁡[q(x)−x]x + \operatorname{sg}[q(x) - x] — forward qq, backward identity.

Where this is used

Straight-through

어떤 연산은 도함수가 쓸모없다. 반올림, argmax, 양자화, 이산 코드 샘플링. straight-through 추정량은 순방향에서는 진짜 연산을 돌리고 역방향에서는 항등함수였던 척한다.

y^=x+sg⁡[q(x)−x],y^=q(x),∇y^=∇x.\hat y = x + \operatorname{sg}\big[q(x) - x\big], \qquad \hat y = q(x),\quad \nabla\hat y = \nabla x .

편향이 있다 — 계산하지 않은 함수의 gradient다 — 하지만 q(x)≈xq(x) \approx x이면 쓸모 있는 방향을 가리키고, quantisation-aware training과 vector-quantised 코드북의 일꾼이다. k3+ 손실도 짝만 다른 같은 구성이다. 기록에는 k3의 값, 학습에는 k2의 gradient.

확인 문제Check yourself

RL 손실에 샘플된 토큰들에 대한 beta * mean(k1)을 더한다. k1 = logp - ref_logp이고 logp는 detach하지 않았다. 이 KL 항이 기대 gradient에 기여하는 것은?

표본이 고정이면 ∇k1=∇log⁡πθ(y)\nabla k_1 = \nabla\log\pi_\theta(y)이고 Ey∼πθ[∇log⁡πθ(y)]=∇∑yπθ(y)=0\mathbb{E}_{y\sim\pi_\theta}[\nabla\log\pi_\theta(y)] = \nabla\sum_y\pi_\theta(y) = 0이다. score 항 k1∇log⁡πk_1\nabla\log\pi가 빠졌다. k2k_2를 쓰거나, sg⁡[k1]\operatorname{sg}[k_1]을 보상에 넣거나, sg⁡[k1]log⁡π\operatorname{sg}[k_1]\log\pi를 손실에 더한다. (손실에 k3k_3를 넣으면 forward KL의 gradient가 된다.)

PyTorch PyTorch 관용구: 각 detach가 하는 일 로컬에서 실행run locally (pip install torch)
import torch

def policy_loss(logp, old_logp, ref_logp, adv, mask, beta=0.01, eps=0.2):
    """logp: (B, T) 현재 정책에서 샘플된 토큰의 log-prob (grad 필요)."""
    ratio = torch.exp(logp - old_logp)                 # old_logp에는 grad가 없다: 상수 pi_old
    pg = -torch.min(ratio * adv, ratio.clamp(1 - eps, 1 + eps) * adv)   # adv는 데이터: grad 없음
    # 첫 step에서 ratio == 1이지만 d ratio = ratio * d logp  ->  REINFORCE gradient

    lr = logp - ref_logp                               # 토큰별 k1
    k2 = 0.5 * lr ** 2                                 # grad = k1 * grad logp  (reverse-KL gradient)
    k3 = torch.exp(-lr) - 1 + lr                       # 값: 비편향 KL, grad: forward-KL 방향
    k3_plus = k3.detach() + (k2 - k2.detach())         # 기록은 k3, 학습은 k2

    seq_w = torch.exp(((logp - old_logp) * mask).sum(1) / mask.sum(1)).detach()   # 시퀀스 가중치
    tok = seq_w[:, None] * torch.exp(logp - logp.detach())   # 값은 seq_w, grad는 seq_w * grad logp
    loss = ((pg + beta * k3_plus) * mask).sum() / mask.sum()
    return loss, tok
 

정리

  • sg⁡[x]\operatorname{sg}[x]: 값은 xx, 도함수는 0. θ가 나오는 자리 중 어느 것을 미분할지에 대한 규칙이다: ∇f(θ,sg⁡[g])=∂1f\nabla f(\theta, \operatorname{sg}[g]) = \partial_1 f.
  • 네 항등식: x−sg⁡[x]x - \operatorname{sg}[x], ex−sg⁡[x]e^{x - \operatorname{sg}[x]}, sg⁡[a]+b−sg⁡[b]\operatorname{sg}[a] + b - \operatorname{sg}[b], sg⁡[w]ℓ\operatorname{sg}[w]\ell.
  • 대리 함수는 샘플을 뽑은 θ에서 gradient가 맞고 값은 무의미하다. PPO의 ratio 대리 함수는 θold\theta_{\text{old}} 근처에서만 믿는 1차 모형이다.
  • ∇Eπθ[fθ]=E[∇fθ]+E[fθ∇log⁡πθ]\nabla\mathbb{E}_{\pi_\theta}[f_\theta] = \mathbb{E}[\nabla f_\theta] + \mathbb{E}[f_\theta\nabla\log\pi_\theta]. 고정 표본 위의 autograd는 둘째 항을 버린다. 손실로 쓴 k1k_1은 0, k2k_2는 reverse KL, k3k_3는 forward KL, f+sg⁡[f]log⁡πf + \operatorname{sg}[f]\log\pi는 전체 gradient를 준다.
  • pathwise gradient는 분산이 작지만 미분 가능한 경로가 필요하고, score-function gradient는 값만 있으면 되며 토큰에도 통한다.
  • Straight-through: x+sg⁡[q(x)−x]x + \operatorname{sg}[q(x) - x] — 순방향은 qq, 역방향은 항등함수.

이 사이트에서 쓰이는 곳

더 읽을거리Further reading