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 , .detach() in PyTorch. Sixteen lessons use it; this one defines it and derives the handful of patterns they rely on.
What sg means
has the value of and is treated as a constant by differentiation: , . That makes it not a function of in the ordinary sense (a function equal to everywhere would have the same derivative), but a statement about which occurrences of to differentiate. Precisely: for ,
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 into the graph. Four identities cover almost every use:
| expression | value | gradient | used for |
|---|---|---|---|
| adding a gradient without changing the value | |||
| ratios that equal 1 but carry | |||
| log one quantity, differentiate another (k3+, straight-through) | |||
| per-sample weights: IS ratios, advantages, masks |
In code, 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 . Its gradient (the log-derivative trick) is
Autograd cannot differentiate “sampling from ”. So we draw from the current policy, hold them fixed, and write a function whose gradient is the estimator:
is a surrogate. Its gradient at the current is an unbiased estimate of (the baseline adds ). Its value is not : it depends on , and it is negative whenever . Since estimates , is maximised by gradient ascent; a framework minimiser is handed . Even so, optimising it to convergence on one fixed batch would be wrong, because the samples are only valid at the that drew them. PPO’s with is the same idea with importance weights, so that several gradient steps can reuse one batch: at , and the gradient is again ; away from it, the surrogate is a first-order model of that is only trusted nearby, which is what the clip enforces.
이 사이트의 RL 학습 루프 어느 것을 열어도 “손실”은 목적함수가 아니다. autograd가 목적함수 gradient의 추정값을 돌려주도록 만든 함수이고, 로그에 찍히는 그 값은 아무 의미가 없을 때가 많다. 그런 함수를 만드는 도구가 stop-gradient , PyTorch의 .detach()다. 열여섯 개 레슨이 이것을 쓴다. 이 레슨은 그것을 정의하고 그 레슨들이 기대는 몇 가지 패턴을 유도한다.
sg의 뜻
는 값은 이고 미분에서는 상수로 취급된다: , . 그러니 보통 뜻의 의 함수가 아니다(어디서나 와 같은 함수라면 도함수도 같았을 것이다). 가 나오는 자리 중 어느 것을 미분할지에 대한 진술이다. 정확히는 에 대해
곧 두 번째 자리를 현재 값에 얼려 둔 채 첫 번째 자리로 편미분한 것이다. reverse-mode autograd에서는 에서 그래프로 들어오는 간선을 문자 그대로 끊는 일이다. 네 개의 항등식이 거의 모든 쓰임을 덮는다.
| 식 | 값 | gradient | 쓰임 |
|---|---|---|---|
| 값을 바꾸지 않고 gradient만 더하기 | |||
| 값은 1이지만 를 실어 나르는 비율 | |||
| 한 양을 기록하고 다른 양을 미분 (k3+, straight-through) | |||
| 표본별 가중치: IS 비율, advantage, 마스크 |
코드에서 는 GSPO 등이 시퀀스 단위 가중치에 토큰 단위 gradient를 붙이는 방법이고, k3.detach() + (k2 - k2.detach())가 k3+ 손실이다.
대리 함수: gradient는 맞고 값은 무의미하다
policy gradient의 목적함수는 이고, 그 gradient(log-derivative trick)는
autograd는 “에서 샘플링하기”를 미분하지 못한다. 그래서 현재 정책에서 을 뽑아 고정해 두고, gradient가 추정량이 되는 함수를 쓴다.
은 대리 함수(surrogate) 다. 현재 에서의 gradient는 의 비편향 추정이다(baseline 는 을 더할 뿐이다). 값은 가 아니다. 에 따라 바뀌고, 이면 음수다. 이 를 추정하므로 은 gradient ascent로 최대화하고, 최소화기(optimizer)에는 을 넘긴다. 그래도 고정된 한 배치에서 수렴할 때까지 최적화하면 틀린다. 표본은 그것을 뽑은 에서만 유효하기 때문이다. PPO의 , 는 같은 생각에 importance weight를 붙여 한 배치로 여러 번 gradient step을 밟게 한 것이다. 에서 이므로 gradient는 다시 다. 거기서 멀어지면 대리 함수는 근처에서만 믿을 수 있는 의 1차 모형이고, 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 : . The product rule gives two terms:
Differentiating a sample average with the samples held fixed computes only the first term. The KL penalty is the standard trap. With , the sample mean of is an unbiased estimate of , but has expectation zero: as a loss, does nothing on average. The fixes, all derived from the formula above:
- Add the score term explicitly: . Its gradient is , both terms. For that gives , the true . This is the general rule for stochastic computation graphs (Schulman et al., 2015).
- Choose an integrand whose naive gradient happens to be right: has — exactly the score term for . That is why ” as a loss” gives the reverse-KL gradient.
- Put the KL in the reward: use as a negative reward inside the REINFORCE surrogate; the score-function machinery then supplies .
- Know what the others give: with has , whose expectation under is — the forward KL’s gradient, not the reverse.
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}")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 and parameter-free noise — , — the derivative can move inside:
Both are unbiased; they differ in variance and in what they need. The pathwise estimator uses and is usually far less noisy — VAEs rely on it. The score-function estimator needs only values of , 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 추정량이 아니다
구하려는 양이 정책 아래의 기댓값이고, 피적분 함수도 에 의존한다고 하자: . 곱의 미분법이 두 항을 준다.
표본을 고정한 채 표본 평균 를 미분하면 첫 항만 계산된다. KL 벌점이 대표적인 함정이다. 로 두면 의 표본 평균은 의 비편향 추정이지만, 의 기댓값은 0이다. 손실로 쓴 은 평균적으로 아무것도 하지 않는다. 위 식에서 나오는 처방들.
- score 항을 명시적으로 더한다: . gradient가 , 두 항 모두다. 에 대해서는 , 곧 참 이다. 확률적 계산 그래프의 일반 규칙이다(Schulman et al., 2015).
- 순진한 gradient가 마침 맞는 피적분 함수를 고른다: 는 — 정확히 의 score 항이다. “손실로 쓴 “가 reverse KL의 gradient를 주는 이유다.
- KL을 보상에 넣는다: 을 REINFORCE 대리 함수 안의 음의 보상으로 쓰면 score-function 기계가 를 공급한다.
- 나머지가 무엇을 주는지 알아 둔다: 일 때 은 이고, 아래 기댓값은 — reverse가 아니라 forward KL의 gradient다.
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}")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은 기댓값을 미분하는 두 방법 중 하나다. 표본을 와 매개변수 없는 잡음의 미분 가능한 함수로 쓸 수 있으면 — , — 미분이 안으로 들어간다.
둘 다 비편향이고, 분산과 필요한 것이 다르다. pathwise 추정량은 을 쓰고 대개 훨씬 조용하다. VAE가 이것에 기댄다. score-function 추정량은 의 값만 있으면 되는데, 보상모델이나 verifier가 주는 것이 딱 그것뿐이고, 재매개변수화가 없는 토큰 같은 이산 표본에도 통한다. 대가는 분산이고, baseline(control variate)이 그 대가를 덜 치르는 표준 방법이다.
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:
It is biased — the gradient of a function that was not computed — but it points somewhere useful when , 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.
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, , and . The score term is missing. Use , put in the reward, or add to the loss. ( in the loss would give the forward-KL gradient.)
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, tokSummary
- : value , derivative 0 — a rule about which occurrences of θ to differentiate: .
- Four identities: , , , .
- 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 .
- ; autograd on fixed samples drops the second term. as a loss gives 0, gives reverse KL, gives forward KL, 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: — forward , backward identity.
Where this is used
- Policy gradient, Actor-critic, PPO — the REINFORCE surrogate, the stopped-gradient TD target, the ratio and clipped surrogates.
- KL-regularised RL, Regularisation — KL in the reward vs the loss, k1/k2/k3 gradients, k3+.
- Off-policy mismatch, Clipping and IS, verl rollout correction — TIS/CISPO weights as , masks.
- Sequence vs token, RL landscape — GSPO’s , the token-weighted policy-gradient frame.
- Async and staleness, Mismatch engineering — behaviour-policy weights held constant.
- Distillation — teacher log-probs as constants, on-policy distillation as a reward.
- Backprop — the reverse-mode graph that sg cuts.
- Related: Probability for the log-derivative trick and control variates.
Straight-through
어떤 연산은 도함수가 쓸모없다. 반올림, argmax, 양자화, 이산 코드 샘플링. straight-through 추정량은 순방향에서는 진짜 연산을 돌리고 역방향에서는 항등함수였던 척한다.
편향이 있다 — 계산하지 않은 함수의 gradient다 — 하지만 이면 쓸모 있는 방향을 가리키고, quantisation-aware training과 vector-quantised 코드북의 일꾼이다. k3+ 손실도 짝만 다른 같은 구성이다. 기록에는 k3의 값, 학습에는 k2의 gradient.
RL 손실에 샘플된 토큰들에 대한 beta * mean(k1)을 더한다. k1 = logp - ref_logp이고 logp는 detach하지 않았다. 이 KL 항이 기대 gradient에 기여하는 것은?
표본이 고정이면 이고 이다. score 항 가 빠졌다. 를 쓰거나, 을 보상에 넣거나, 를 손실에 더한다. (손실에 를 넣으면 forward KL의 gradient가 된다.)
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정리
- : 값은 , 도함수는 0. θ가 나오는 자리 중 어느 것을 미분할지에 대한 규칙이다: .
- 네 항등식: , , , .
- 대리 함수는 샘플을 뽑은 θ에서 gradient가 맞고 값은 무의미하다. PPO의 ratio 대리 함수는 근처에서만 믿는 1차 모형이다.
- . 고정 표본 위의 autograd는 둘째 항을 버린다. 손실로 쓴 은 0, 는 reverse KL, 는 forward KL, 는 전체 gradient를 준다.
- pathwise gradient는 분산이 작지만 미분 가능한 경로가 필요하고, score-function gradient는 값만 있으면 되며 토큰에도 통한다.
- Straight-through: — 순방향은 , 역방향은 항등함수.
이 사이트에서 쓰이는 곳
- 정책 경사, Actor-critic, PPO — REINFORCE 대리 함수, gradient를 멈춘 TD 타깃, ratio·clip 대리 함수.
- KL 정규화 RL, 정규화 — 보상 vs 손실에 넣은 KL, k1/k2/k3의 gradient, k3+.
- Off-policy 불일치, Clipping과 IS, verl rollout 보정 — 로서의 TIS/CISPO 가중치, 마스크.
- 시퀀스 vs 토큰, RL 지형도 — GSPO의 , 토큰 가중 policy gradient 틀.
- 비동기와 staleness, 불일치 엔지니어링 — 상수로 고정한 behaviour 정책 가중치.
- 증류 — 상수로서의 교사 log-prob, 보상으로서의 on-policy 증류.
- 역전파 — sg가 끊는 reverse-mode 그래프.
- 관련: log-derivative trick과 control variate는 확률.
더 읽을거리Further reading
- Schulman, Heess, Weber & Abbeel, Gradient Estimation Using Stochastic Computation Graphs (NeurIPS 2015) — 확률적 노드가 있는 계산 그래프에서 대리 손실을 만드는 일반 규칙. 이 레슨의 "score 항 더하기"가 여기서 나온다.The general rule for building surrogate losses on graphs with stochastic nodes; this lesson's "add the score term" comes from it.
- Foerster et al., DiCE: The Infinitely Differentiable Monte-Carlo Estimator (ICML 2018) — exp(x − sg[x]) "magic box"로 고차 미분까지 맞는 대리 함수를 만든다.The exp(x − sg[x]) "magic box", giving surrogates that are right for higher derivatives too.
- Mohamed, Rosca, Figurnov & Mnih, Monte Carlo Gradient Estimation in Machine Learning (JMLR, 2020) — score-function, pathwise, measure-valued 추정량의 개관과 분산 비교.A survey of score-function, pathwise and measure-valued gradient estimators and their variances.
- Williams, Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning (Machine Learning, 1992) — REINFORCE의 원전.The original REINFORCE paper.
- Schulman et al., Trust Region Policy Optimization (ICML 2015) — importance-ratio 대리 함수가 θ_old에서 목적함수와 1차까지 일치함을 보이고 그 위에 trust region을 세운다.Shows the importance-ratio surrogate matches the objective to first order at θ_old and builds a trust region on it.
- Bengio, Léonard & Courville, Estimating or Propagating Gradients Through Stochastic Neurons (2013) — straight-through 추정량.The straight-through estimator.