The earlier lessons of this track were about learning from a reward signal. But if a larger model (a teacher) that already does the job well exists, the story changes. Instead of waiting for a single reward, we can use the teacher’s entire probability distribution as the signal. Many of the small open reasoning models were trained on the outputs of larger models, and much of post-training data is synthetic data made by models. This lesson organises those methods around one question: which distribution do we sample from, and in which direction do we reduce the KL?
The original distillation: soft targets
The distillation of Hinton et al. (2015) matches the distributions obtained by softening the teacher’s logits and the student’s logits with a temperature .
This carries far more information than a single correct label. The relative sizes — “this photo is a dog, the probability that it is a cat is 1%, and that it is a car is 0.0001%” — are the structure the teacher has learned, the so-called dark knowledge. is a factor that keeps gradient magnitudes matched. Differentiating the cross-entropy with respect to gives
and when is large, (when the logits have zero mean), so the gradient shrinks as . Multiplying by keeps the ratio to the hard-label term fixed when the temperature changes. In the high-temperature limit, distillation is the same as matching logits directly.
In LLMs this becomes token-level distillation, matching the next-token distribution at every position. The remaining question is “on which sequences do we match?”.
Sequence-level distillation and synthetic data
The most common method is to SFT the student on responses generated by the teacher (sequence-level distillation, Kim & Rush 2016). Let us see which KL this is. The NLL on teacher samples is
does not depend on the student, so SFT on teacher samples = minimising sequence-level forward KL. With this one line, many of post-training’s synthetic-data pipelines fit into the same frame.
- Self-Instruct (Wang et al. 2023): starting from a small set of seed tasks, the model writes new instructions and responses, and duplicates and low-quality items are filtered out to grow the instruction data. Alpaca collected the outputs of a strong model this way.
- Reasoning data made by rejection sampling: generate several solutions per problem and keep only the ones that reach the correct answer (STaR, Zelikman et al. 2022; the rejection sampling lesson). The distribution that passes the filter is “the teacher distribution conditioned on being correct”, so this is still forward-KL distillation.
- Distilling reasoning models: DeepSeek-R1 SFT-ed small dense models of the Qwen and Llama families on about 800k samples made by R1, and reported that the distilled models were better than running large-scale RL directly on base models of the same size. The reasoning patterns a large model found with RL are hard for a small model to find on its own, but it can imitate them once shown.
Constitutional AI and RLAIF
Instead of writing responses, the teacher can give judgements. Anthropic’s Constitutional AI (Bai et al. 2022b) has two stages.
- SL stage (critique → revision). Have the model respond to potentially harmful prompts, then have the model itself critique and rewrite that response according to a principle drawn from a list of principles (the constitution). SFT on the revised responses. This is sequence-level distillation with “oneself, following the principles” as the teacher.
- RL stage (RLAIF). Show the model two responses and have it choose which one is better in light of the principles. Train a reward model on these AI preference labels and do RL. It is RLHF with human preference labels replaced by AI judgements.
The paper reported that models trained this way are less harmful and also less evasive (explaining their reasons instead of refusing unconditionally). Later, Lee et al. (2023) reported that RLAIF reaches a level similar to RLHF on tasks such as summarization. Since the judge model’s biases go straight into the reward, every caveat of over-optimization applies as well.
Forward KL and reverse KL
SFT on teacher samples reduces the forward KL ; having the student sample and the teacher grade reduces the reverse KL . If the student can imitate the teacher perfectly, both reach the same answer (student = teacher), but when the student is too small to do so they pick entirely different solutions (losses as probability).
- Forward KL punishes heavily where but , since . The student spreads out widely, trying to cover everywhere the teacher goes (mode covering).
- Reverse KL punishes heavily where but . The student stays only where the teacher is sure is good (mode seeking).
이 트랙의 앞 레슨들은 보상 신호에서 배우는 방법이었다. 그런데 이미 그 일을 잘하는 더 큰 모델(교사)이 있다면 이야기가 달라진다. 보상 하나를 기다릴 필요 없이 교사의 확률분포 전체를 신호로 쓸 수 있다. 공개된 작은 추론 모델의 상당수가 큰 모델의 출력으로 학습되었고, 사후학습 데이터의 많은 부분이 모델이 만든 합성 데이터다. 이 레슨은 그 방법들을 하나의 질문으로 정리한다. 어느 분포에서 샘플을 뽑고, 어떤 방향의 KL을 줄이는가?
증류의 원형: soft target
Hinton et al.(2015)의 증류는 교사의 logits 와 학생의 logits 를 온도 로 부드럽게 만든 분포를 맞춘다.
정답 레이블 하나보다 정보가 훨씬 많다. “이 사진은 개인데, 고양이일 확률은 1%이고 자동차일 확률은 0.0001%“라는 상대적 크기가 교사가 배운 구조, 이른바 dark knowledge다. 는 gradient 크기를 맞추는 계수다. cross-entropy를 로 미분하면
이고, 가 크면 (logits 평균이 0일 때)라서 gradient가 로 작아진다. 그래서 를 곱해 온도를 바꿔도 hard label 항과의 비율이 유지되게 한다. 높은 온도의 극한에서 증류는 logits를 직접 맞추는 것과 같다.
LLM에서 이것은 위치마다 다음 토큰 분포를 맞추는 토큰 수준 증류가 된다. 남은 질문은 “어느 시퀀스 위에서 맞추는가”다.
시퀀스 수준 증류와 합성 데이터
가장 흔한 방법은 교사가 생성한 응답으로 학생을 SFT하는 것이다(시퀀스 수준 증류, Kim & Rush 2016). 이것이 어떤 KL인지 보자. 교사 샘플 위에서의 NLL은
이다. 는 학생과 무관하니 교사 샘플로 SFT = 시퀀스 수준 forward KL 최소화다. 이 한 줄로 사후학습의 많은 합성 데이터 파이프라인이 같은 틀에 들어온다.
- Self-Instruct(Wang et al. 2023): 소수의 seed 과제에서 출발해 모델이 새 지시문과 응답을 만들고, 중복·저품질을 걸러 instruction 데이터를 키운다. Alpaca가 이 방식으로 강한 모델의 출력을 모았다.
- Rejection sampling으로 만든 추론 데이터: 문제마다 여러 풀이를 생성해 정답에 도달한 것만 남긴다(STaR, Zelikman et al. 2022; rejection sampling 레슨). 필터를 통과한 분포는 “정답 조건부 교사 분포”이므로 여전히 forward KL 증류에 해당한다.
- 추론 모델 증류: DeepSeek-R1은 R1이 만든 약 80만 개의 샘플로 Qwen과 Llama 계열의 작은 dense 모델을 SFT했고, 같은 크기의 base 모델에 대규모 RL을 직접 돌린 것보다 증류한 모델이 더 좋았다고 보고했다. 큰 모델이 RL로 찾은 추론 패턴을 작은 모델은 스스로 찾기 어렵지만, 보여 주면 따라 할 수는 있다는 뜻이다.
Constitutional AI와 RLAIF
교사가 응답을 쓰는 대신 판정을 줄 수도 있다. Anthropic의 Constitutional AI(Bai et al. 2022b)는 두 단계다.
- SL 단계 (critique → revision). 유해할 수 있는 프롬프트에 모델이 응답하게 하고, 원칙 목록(constitution)에서 고른 원칙에 따라 모델 스스로 그 응답을 비평하고 고쳐 쓰게 한다. 고친 응답으로 SFT한다. 이것은 “원칙을 따르는 자기 자신”을 교사로 쓴 시퀀스 수준 증류다.
- RL 단계 (RLAIF). 응답 두 개를 모델에게 보여 주고 원칙에 비추어 어느 쪽이 나은지 고르게 한다. 이 AI 선호 레이블로 보상모델을 학습하고 RL을 한다. 사람 선호 레이블을 AI 판정으로 대체한 RLHF다.
논문은 이렇게 학습한 모델이 덜 유해하면서도 덜 회피적(무조건 거절하지 않고 이유를 설명)이라고 보고했다. 이후 Lee et al.(2023)은 요약 등의 과제에서 RLAIF가 RLHF와 비슷한 수준을 낸다고 보고했다. 판정 모델의 편향이 그대로 보상에 들어간다는 점에서 과최적화의 모든 주의사항이 그대로 적용된다.
forward KL과 reverse KL
교사 샘플로 SFT하면 forward KL 를, 학생이 샘플하고 교사가 채점하면 reverse KL 를 줄이게 된다. 학생이 교사를 완벽히 흉내 낼 수 있다면 둘 다 같은 답(학생 = 교사)에 도달하지만, 학생이 작아서 그럴 수 없을 때는 전혀 다른 해를 고른다(확률로 보는 손실).
- forward KL은 인데 인 곳에서 라 큰 벌을 준다. 학생은 교사가 쓰는 모든 곳을 덮으려고(mode covering) 넓게 퍼진다.
- reverse KL은 인데 인 곳에서 큰 벌을 준다. 학생은 교사가 확실히 좋다고 하는 곳에만(mode seeking) 머문다.
- In the default setting, red (forward) stretches widely across the valley between the two peaks. It puts the most probability in the middle, which the teacher hardly uses. Translated to LLMs, that is an output mixing two solution styles that is neither one.
- Blue (reverse) clings exactly to one peak near its starting point. Move μ₀ towards −2 and it picks the other peak. It loses diversity, but what it picks matches the teacher.
- Shrink the peak separation to about 1.5 and the two students become similar. The closer the teacher distribution is to a shape the student can represent, the less the direction of the KL matters.
On-policy distillation
Sequence-level distillation (SFT) has one more problem. During training the student only sees prefixes written by the teacher. At inference it sees prefixes it wrote itself; once it makes a mistake it enters a state absent from the teacher data, has never learned what to do there, and the mistakes compound. This is the well-known compounding error of imitation learning. In the DAgger analysis of Ross et al. (2011), the error of behaviour cloning trained only on expert states grows as in the worst case over a horizon , and shrinks to when expert labels are collected in the states the learner visits.
On-policy distillation applies this prescription directly to LLMs. The student samples a response, and the teacher reports its own distribution at each position of that response. The objective is the per-token reverse KL over the prefixes the student visited.
There are two ways to implement it. Like GKD (Agarwal et al. 2024), you can compute the KL exactly over the whole vocabulary at each position (requiring the same tokenizer and the teacher’s full logits), or you can estimate it from the single sampled token. The latter takes exactly the same shape as an RL loss. With student and teacher in state ,
That is, a policy gradient that uses the token reward as its advantage is an unbiased estimate of the reverse-KL gradient in that state. It ignores the effect on future tokens (discount 0). Thinking Machines’ On-Policy Distillation post (2025) puts this on top of an RL training loop and describes it as RL in which the teacher’s per-token log-probs take the place of the reward model. The Qwen3 technical report also states that, to build its small models, it used on-policy distillation — reducing the KL to the teacher on responses generated by the student — as the step after off-policy distillation.
- 기본 설정에서 빨강(forward)은 두 봉우리 사이 골짜기에 넓게 걸친다. 교사가 거의 쓰지 않는 가운데에 확률을 가장 많이 준다. LLM으로 옮기면 두 가지 풀이 방식을 섞은, 어느 쪽도 아닌 출력이다.
- 파랑(reverse)은 시작점 근처의 봉우리 하나에 정확히 붙는다. μ₀를 −2 쪽으로 옮기면 다른 봉우리를 고른다. 다양성은 잃지만 고른 것은 교사와 같다.
- 봉우리 간격을 1.5 정도로 줄이면 두 학생이 비슷해진다. 교사 분포가 학생이 표현할 수 있는 모양에 가까울수록 KL의 방향은 덜 중요하다.
On-policy 증류 (on-policy distillation)
시퀀스 수준 증류(SFT)에는 하나 더 문제가 있다. 학생은 학습 때 교사가 쓴 접두사만 본다. 추론 때는 자기가 쓴 접두사를 보는데, 한 번 실수하면 교사 데이터에 없던 상태에 들어가고, 거기서 어떻게 해야 할지 배운 적이 없어 실수가 쌓인다. 모방 학습에서 잘 알려진 compounding error다. Ross et al.(2011)의 DAgger 분석에서 전문가 상태만으로 학습한 behavior cloning의 오차는 horizon 에 대해 최악의 경우 으로 커지고, 학습자가 방문한 상태에서 전문가 레이블을 받으면 로 줄어든다.
On-policy distillation은 이 처방을 LLM에 그대로 쓴다. 학생이 응답을 샘플하고, 교사는 그 응답의 각 위치에서 자기 분포를 알려 준다. 목적함수는 학생이 방문한 접두사 위에서의 토큰별 reverse KL이다.
구현은 두 갈래다. GKD(Agarwal et al. 2024)처럼 각 위치에서 어휘 전체에 대해 KL을 정확히 계산할 수도 있고(같은 tokenizer와 교사 logits 전체가 필요), 샘플된 토큰 하나만으로 추정할 수도 있다. 후자는 RL 손실과 똑같은 모양이 된다. 상태 에서 학생 , 교사 라 하면
이다. 즉 토큰 보상 를 advantage로 쓰는 policy gradient가 그 상태의 reverse KL gradient의 불편 추정이다. 미래 토큰에 대한 영향은 무시한다(할인 0). Thinking Machines의 On-Policy Distillation 글(2025)은 이 방식을 RL 학습 루프 위에 얹어, 보상 모델 자리에 교사의 토큰별 log-prob이 들어간 RL로 설명한다. Qwen3 기술 보고서도 작은 모델을 만들 때 off-policy 증류 다음 단계로, 학생이 생성한 응답 위에서 교사와의 KL을 줄이는 on-policy 증류를 썼다고 밝혔다.
This figure shows the key advantages of on-policy distillation.
- The signal is dense. In B (an arithmetic slip), RL’s outcome reward sprinkles the single fact “wrong” equally over every token. The teacher’s per-token log-probs point exactly at “78” as the problem. The information obtained from one response is not one bit but as many as there are tokens.
- It learns in the student’s states. The ”= 418” after “78” is a calculation consistent with the preceding context even in the teacher’s eyes, so it is barely punished. The teacher tells the student, on the student’s own prefix, even “how to continue correctly after this mistake”. With SFT the teacher never made this mistake, so this state can never be seen.
- The room for reward hacking is different. In C, RL reinforces even the filler (“um… wait”) thanks to the correct answer, while the teacher’s log-probs punish those tokens. Conversely, the student cannot become better than the teacher, because the target is the teacher itself.
A teacher model uses two different solution styles half the time each on the same problem. If you SFT a low-capacity student on teacher samples (forward KL), what is likely to happen?
Forward KL pushes the student to cover everywhere the teacher puts probability, so with too little capacity it spreads widely between the two peaks (red in the figure). In an LLM this can show up as an incoherent output that mixes the first half of one solution with the second half of the other. Reverse KL (on-policy) picks one style and follows it exactly (blue in the figure), at the cost of losing the other style.
Try it yourself
First, in the same setting as the figure, fit a Gaussian student with forward KL and with reverse KL, from three different starting points.
import numpy as np
x = np.linspace(-6, 6, 161)
def normalize(w): return w / w.sum()
def gauss(mu, log_sig): return normalize(np.exp(-0.5 * ((x - mu) / np.exp(log_sig))**2) + 1e-300)
# teacher: two peaks (e.g. two different solution styles for the same problem)
p = normalize(0.6 * np.exp(-0.5 * ((x + 2.2) / 0.6)**2) + 0.4 * np.exp(-0.5 * ((x - 2.0) / 0.6)**2))
def kl(a, b):
m = a > 1e-300
return float((a[m] * (np.log(a[m]) - np.log(b[m] + 1e-300))).sum())
fwd = lambda th: kl(p, gauss(*th)) # KL(p‖q): same as SFT on teacher samples (up to a constant)
rev = lambda th: kl(gauss(*th), p) # KL(q‖p): the student samples, the teacher grades
def fit(loss, th, lr=0.1, steps=1200, h=1e-4):
th = np.array(th, float)
for _ in range(steps): # only 2 parameters, so numerical differentiation is enough
g = np.array([(loss(th + h * e) - loss(th - h * e)) / (2 * h) for e in np.eye(2)])
th -= lr * g
return th
print("target start μ → μ σ KL(p‖q) KL(q‖p)")
for name, loss in [("forward", fwd), ("reverse", rev)]:
for mu0 in [-3.0, 0.5, 3.0]:
th = fit(loss, [mu0, 0.0])
print(f"{name:8s} {mu0:6.1f} {th[0]:6.2f} {np.exp(th[1]):5.2f} {fwd(th):7.3f} {rev(th):7.3f}")
mean = (x * p).sum(); sd = np.sqrt(((x - mean)**2 * p).sum())
print(f"\nteacher mean {mean:.2f}, std {sd:.2f} ← the forward-KL solution is close to moment matching")Forward KL goes to the same solution regardless of the starting point (a wide Gaussian with almost the teacher’s mean and standard deviation). Within the Gaussian family, the optimum of forward KL is moment matching. Reverse KL stays at the left peak, the right peak, or a wide local solution in the middle, depending on the start. Reverse KL is not convex and has several local solutions — the same reason on-policy learning ends up in different places depending on the initial policy.
Next, we implement on-policy distillation on an autoregressive toy. The teacher is a bigram model that follows the cycle 0→1→2→3→0 with probability 90%, and the student starts from a nearly uniform bigram. With the same number of student samples we compare (1) on-policy distillation using the teacher’s per-token log-probs as reward and (2) RL with a single outcome reward, “did it follow the teacher’s correct path exactly?”, and (3) also include SFT on teacher samples for reference.
import numpy as np
rng = np.random.default_rng(0)
V, L = 8, 12 # 8 vocabulary items (= states), sequence length 12
# teacher: a bigram model. Follows the cycle 0→1→2→3→0 with probability 90%,
# and knows to "return" to 0 with probability 90% when it falls into the rare states 4–7.
P = np.full((V, V), 0.1 / (V - 1))
for s in range(V):
nxt = (s + 1) % 4 if s < 4 else 0
P[s, nxt] = 0.9
logP = np.log(P)
def softmax_rows(Z):
E = np.exp(Z - Z.max(1, keepdims=True)); return E / E.sum(1, keepdims=True)
def sample(Pm, n): # n sequences from Pm (start state 0)
seqs = np.zeros((n, L + 1), int)
for t in range(L):
cum = Pm[seqs[:, t]].cumsum(1)
seqs[:, t + 1] = (rng.random((n, 1)) > cum).sum(1)
return np.minimum(seqs, V - 1)
def state_dists(Pm): # state distribution d_t at each time step
d = np.zeros(V); d[0] = 1; out = []
for _ in range(L):
out.append(d); d = d @ Pm
return out
def seq_kls(Q): # exact sequence-level KL (sum over time steps)
rev = sum(d @ (Q * (np.log(Q) - logP)).sum(1) for d in state_dists(Q)) # E_{student states} KL(q‖p)
fwd = sum(d @ (P * (logP - np.log(Q))).sum(1) for d in state_dists(P)) # E_{teacher states} KL(p‖q)
return rev, fwd
Z0 = rng.normal(0, 0.5, (V, V)) # student's initial logits (nearly uniform)
# (1) on-policy distillation: the student samples, the teacher only gives the log-prob of that token.
# token reward r_t = log p(y_t|s_t) − log q(y_t|s_t) (= one sample of −reverse KL), discount 0
def opd(n_iters, batch=4, lr=2.0):
Z = Z0.copy(); used = 0
for _ in range(n_iters):
Q = softmax_rows(Z); S = sample(Q, batch)
s, y = S[:, :-1].ravel(), S[:, 1:].ravel()
adv = logP[s, y] - np.log(Q[s, y]) # teacher log-prob queries = number of tokens
G = np.zeros_like(Z)
np.add.at(G, s, -adv[:, None] * (np.eye(V)[y] - Q[s])) # −A ∇log q(y|s)
Z -= lr * G / len(s); used += len(s)
return softmax_rows(Z), used
PATH = [t % 4 for t in range(L + 1)] # the teacher's "correct path" 0→1→2→3→0→…
def success(Q): # probability the student follows the correct path exactly (exact)
return float(np.prod([Q[a, b] for a, b in zip(PATH[:-1], PATH[1:])]))
# (2) RL for comparison: same student samples, a single reward at the end (1 if correct path, else 0), batch-mean baseline
def rl_outcome(n_iters, batch=4, lr=2.0):
Z = Z0.copy(); hits = 0
for _ in range(n_iters):
Q = softmax_rows(Z); S = sample(Q, batch)
R = (S == np.array(PATH)).all(1).astype(float); hits += R.sum()
A = np.repeat(R - R.mean(), L) # broadcast the outcome reward to every token
s, y = S[:, :-1].ravel(), S[:, 1:].ravel()
G = np.zeros_like(Z)
np.add.at(G, s, -A[:, None] * (np.eye(V)[y] - Q[s]))
Z -= lr * G / len(s)
return softmax_rows(Z), hits
# (3) reference: SFT on teacher samples (= forward KL, only in states the teacher visits)
def sft(n_seqs, steps=300, lr=2.0):
Z = Z0.copy(); S = sample(P, n_seqs)
s, y = S[:, :-1].ravel(), S[:, 1:].ravel()
for _ in range(steps):
Q = softmax_rows(Z); G = np.zeros_like(Z)
np.add.at(G, s, Q[s] - np.eye(V)[y]) # ∇(−log q(y|s)) = q − onehot
Z -= lr * G / len(s)
return softmax_rows(Z), len(s)
print(f"teacher's correct-path probability {success(P):.3f}, initial student {success(softmax_rows(Z0)):.1e}\n")
print("method student/teacher tokens reverse KL correct-path prob")
for it in [20, 80, 300]:
Q, used = opd(it); r, _ = seq_kls(Q)
print(f"on-policy distill ({it:3d} iters) {used:6d} {r:7.3f} {success(Q):.3f}")
for it in [20, 80, 300]:
Q, hits = rl_outcome(it); r, _ = seq_kls(Q)
print(f"RL, outcome reward ({it:3d} iters) {it*4*L:6d} {r:7.3f} {success(Q):.3f} ({int(hits)} successful samples)")
for n in [20, 100]:
Q, used = sft(n); r, _ = seq_kls(Q)
print(f"SFT on teacher samples (n={n:3d}) {used:6d} {r:7.3f} {success(Q):.3f}")Outcome-reward RL never succeeds even once. The probability that a nearly uniform student happens to follow the 12-token correct path is on the order of , and with no successes the signal is 0, just like a zero-variance group. With the same student samples, on-policy distillation receives a signal at every token from the first iteration and converges to the teacher. In this toy the student can represent the teacher exactly, so SFT also works well. SFT’s correct-path probability is higher than the teacher’s (0.28) because it overfits the few samples and becomes a more deterministic policy than the teacher, and its reverse KL decreases correspondingly less. The advantage of on-policy over SFT shows up strongly when the student lacks capacity (the KL figure above) or when the horizon is long and the student frequently enters states the teacher has never visited.
Finally, three distillation losses in PyTorch. We assume the teacher and the student use the same tokenizer.
import torch
import torch.nn.functional as F
def hinton_kd_loss(student_logits, teacher_logits, T=2.0):
"""Per-position soft-target distillation. logits: (B, L, V). T² keeps gradient magnitudes matched."""
log_q = F.log_softmax(student_logits / T, -1)
p = F.softmax(teacher_logits / T, -1)
return F.kl_div(log_q, p, reduction="batchmean") * T * T # KL(p‖q)
def full_reverse_kl_loss(student_logits, teacher_logits, mask):
"""GKD-style: KL(q‖p) over the whole vocabulary at each position of a student-generated sequence."""
log_q = F.log_softmax(student_logits.float(), -1)
log_p = F.log_softmax(teacher_logits.float(), -1)
kl = (log_q.exp() * (log_q - log_p)).sum(-1) # (B, L)
m = mask.float()
return (kl * m).sum() / m.sum().clamp(min=1)
def sampled_token_opd_loss(student_logp, teacher_logp, mask):
"""Estimate from the single sampled token (the form that drops straight into an RL loop).
student_logp, teacher_logp: (B, L) — log-probs of the tokens the student sampled.
advantage = log π_T − log π_S (detached), discount 0. Its expectation equals the gradient of KL(q‖p)."""
adv = (teacher_logp - student_logp).detach()
m = mask.float()
return -(adv * student_logp * m).sum() / m.sum().clamp(min=1)
# training-loop sketch
# y = student.generate(x) # on-policy samples
# s_logp = token_logprobs(student, x, y) # with grad
# t_logp = token_logprobs(teacher, x, y).detach() # the teacher only grades (one forward pass)
# loss = sampled_token_opd_loss(s_logp, t_logp, response_mask)In math RLVR, a small student model's initial accuracy is nearly 0, so GRPO gets no signal at all. If a strong teacher model exists for the same problems, what is the most direct fix?
An outcome reward produces a signal only if the student gets it right at least once (). The teacher’s per-token log-probs tell the student how plausible each token is by the teacher’s standard even when the student writes a wrong solution, so a dense signal arises at every token even at 0% accuracy. Scaling up the reward does not fix the problem of zero advantage. Starting with SFT on teacher samples is also a good starting point, but learning in the student’s own states is what on-policy distillation does.
이 그림이 on-policy distillation의 핵심 장점을 보여 준다.
- 신호가 dense하다. B(계산 실수)에서 RL의 결과 보상은 “틀렸다”는 사실 하나를 모든 토큰에 똑같이 뿌린다. 교사의 토큰별 log-prob은 정확히 “78”이 문제라고 짚는다. 응답 하나에서 얻는 정보가 비트 하나가 아니라 토큰 수만큼이다.
- 학생의 상태에서 배운다. “78” 뒤의 ”= 418”은 교사가 보기에도 앞 문맥과 일관된 계산이라 벌을 거의 받지 않는다. 교사는 “이 실수 다음에는 어떻게 이어 가는 게 맞는가”까지 학생의 접두사 위에서 알려 준다. SFT로는 교사가 이 실수를 한 적이 없으니 이 상태를 볼 수 없다.
- 보상 해킹의 여지가 다르다. C에서 RL은 군말(“음… 잠깐”)도 정답 덕분에 강화하지만, 교사 log-prob은 그 토큰들을 벌한다. 반대로 학생은 교사보다 나아질 수 없다. 목표가 교사 자체이기 때문이다.
교사 모델이 같은 문제에 두 가지 서로 다른 풀이 방식을 반반 쓴다. 용량이 작은 학생을 교사 샘플로 SFT하면(forward KL) 어떤 일이 생기기 쉬운가?
forward KL은 교사가 확률을 주는 모든 곳을 덮도록 학생을 밀어서, 표현력이 부족하면 두 봉우리 사이에 넓게 퍼진다(그림의 빨강). LLM에서는 두 풀이의 앞부분과 뒷부분이 섞인 일관성 없는 출력으로 나타날 수 있다. reverse KL(on-policy)은 한 방식을 골라 정확히 따라 한다(그림의 파랑). 대신 다른 방식은 잃는다.
직접 해 보기
먼저 그림과 같은 설정에서 가우시안 학생을 forward KL과 reverse KL로 맞춘다. 시작점을 세 곳에서 해 본다.
import numpy as np
x = np.linspace(-6, 6, 161)
def normalize(w): return w / w.sum()
def gauss(mu, log_sig): return normalize(np.exp(-0.5 * ((x - mu) / np.exp(log_sig))**2) + 1e-300)
# 교사: 두 봉우리 (예: 같은 문제의 서로 다른 두 풀이 방식)
p = normalize(0.6 * np.exp(-0.5 * ((x + 2.2) / 0.6)**2) + 0.4 * np.exp(-0.5 * ((x - 2.0) / 0.6)**2))
def kl(a, b):
m = a > 1e-300
return float((a[m] * (np.log(a[m]) - np.log(b[m] + 1e-300))).sum())
fwd = lambda th: kl(p, gauss(*th)) # KL(p‖q): 교사 샘플로 SFT 하는 것과 같다 (상수 차이)
rev = lambda th: kl(gauss(*th), p) # KL(q‖p): 학생이 샘플하고 교사가 채점
def fit(loss, th, lr=0.1, steps=1200, h=1e-4):
th = np.array(th, float)
for _ in range(steps): # 파라미터 2개라 수치 미분으로 충분하다
g = np.array([(loss(th + h * e) - loss(th - h * e)) / (2 * h) for e in np.eye(2)])
th -= lr * g
return th
print("목표 시작 μ → μ σ KL(p‖q) KL(q‖p)")
for name, loss in [("forward", fwd), ("reverse", rev)]:
for mu0 in [-3.0, 0.5, 3.0]:
th = fit(loss, [mu0, 0.0])
print(f"{name:8s} {mu0:6.1f} {th[0]:6.2f} {np.exp(th[1]):5.2f} {fwd(th):7.3f} {rev(th):7.3f}")
mean = (x * p).sum(); sd = np.sqrt(((x - mean)**2 * p).sum())
print(f"\n교사의 평균 {mean:.2f}, 표준편차 {sd:.2f} ← forward KL 해는 moment matching에 가깝다")forward KL은 시작점과 무관하게 같은 해(교사의 평균·표준편차와 거의 같은 넓은 가우시안)에 간다. 가우시안 족에서 forward KL의 최적해는 moment matching이다. reverse KL은 시작점에 따라 왼쪽 봉우리, 오른쪽 봉우리, 또는 가운데의 넓은 국소해에 머문다. reverse KL은 볼록하지 않고 국소해가 여럿이다. on-policy 학습이 초기 정책에 따라 다른 곳에 도착하는 것과 같은 이유다.
다음은 자기회귀 장난감에서 on-policy distillation을 직접 구현한다. 교사는 0→1→2→3→0 순환을 90% 확률로 따르는 bigram 모델이고, 학생은 거의 균등한 bigram에서 시작한다. 같은 학생 샘플 수로 (1) 교사의 토큰별 log-prob을 보상으로 쓰는 on-policy distillation과 (2) “교사의 정답 경로를 그대로 따랐는가”라는 결과 보상 하나로 하는 RL을 비교하고, (3) 교사 샘플로 하는 SFT도 참고로 둔다.
import numpy as np
rng = np.random.default_rng(0)
V, L = 8, 12 # 어휘 8개(= 상태), 시퀀스 길이 12
# 교사: bigram 모델. 0→1→2→3→0 순환을 90% 확률로 따르고,
# 드문 상태 4–7에 빠지면 90% 확률로 0으로 "복귀"하는 법을 안다.
P = np.full((V, V), 0.1 / (V - 1))
for s in range(V):
nxt = (s + 1) % 4 if s < 4 else 0
P[s, nxt] = 0.9
logP = np.log(P)
def softmax_rows(Z):
E = np.exp(Z - Z.max(1, keepdims=True)); return E / E.sum(1, keepdims=True)
def sample(Pm, n): # Pm에서 n개 시퀀스 (시작 상태 0)
seqs = np.zeros((n, L + 1), int)
for t in range(L):
cum = Pm[seqs[:, t]].cumsum(1)
seqs[:, t + 1] = (rng.random((n, 1)) > cum).sum(1)
return np.minimum(seqs, V - 1)
def state_dists(Pm): # 각 시점의 상태 분포 d_t
d = np.zeros(V); d[0] = 1; out = []
for _ in range(L):
out.append(d); d = d @ Pm
return out
def seq_kls(Q): # 정확한 시퀀스 수준 KL (시점별 합)
rev = sum(d @ (Q * (np.log(Q) - logP)).sum(1) for d in state_dists(Q)) # E_{학생 상태} KL(q‖p)
fwd = sum(d @ (P * (logP - np.log(Q))).sum(1) for d in state_dists(P)) # E_{교사 상태} KL(p‖q)
return rev, fwd
Z0 = rng.normal(0, 0.5, (V, V)) # 학생 초기 logits (거의 균등)
# (1) on-policy distillation: 학생이 샘플하고, 교사는 그 토큰의 log-prob만 준다.
# 토큰 보상 r_t = log p(y_t|s_t) − log q(y_t|s_t) (= −reverse KL의 한 표본), 할인 0
def opd(n_iters, batch=4, lr=2.0):
Z = Z0.copy(); used = 0
for _ in range(n_iters):
Q = softmax_rows(Z); S = sample(Q, batch)
s, y = S[:, :-1].ravel(), S[:, 1:].ravel()
adv = logP[s, y] - np.log(Q[s, y]) # 교사 log-prob 질의 = 토큰 수만큼
G = np.zeros_like(Z)
np.add.at(G, s, -adv[:, None] * (np.eye(V)[y] - Q[s])) # −A ∇log q(y|s)
Z -= lr * G / len(s); used += len(s)
return softmax_rows(Z), used
PATH = [t % 4 for t in range(L + 1)] # 교사의 "정답 경로" 0→1→2→3→0→…
def success(Q): # 학생이 정답 경로를 그대로 따를 확률 (정확히)
return float(np.prod([Q[a, b] for a, b in zip(PATH[:-1], PATH[1:])]))
# (2) 비교용 RL: 같은 학생 샘플, 보상은 끝에 한 번 (정답 경로면 1, 아니면 0), 배치 평균 baseline
def rl_outcome(n_iters, batch=4, lr=2.0):
Z = Z0.copy(); hits = 0
for _ in range(n_iters):
Q = softmax_rows(Z); S = sample(Q, batch)
R = (S == np.array(PATH)).all(1).astype(float); hits += R.sum()
A = np.repeat(R - R.mean(), L) # 결과 보상을 모든 토큰에 방송
s, y = S[:, :-1].ravel(), S[:, 1:].ravel()
G = np.zeros_like(Z)
np.add.at(G, s, -A[:, None] * (np.eye(V)[y] - Q[s]))
Z -= lr * G / len(s)
return softmax_rows(Z), hits
# (3) 참고: 교사 샘플로 SFT (= forward KL, 교사가 방문한 상태에서만)
def sft(n_seqs, steps=300, lr=2.0):
Z = Z0.copy(); S = sample(P, n_seqs)
s, y = S[:, :-1].ravel(), S[:, 1:].ravel()
for _ in range(steps):
Q = softmax_rows(Z); G = np.zeros_like(Z)
np.add.at(G, s, Q[s] - np.eye(V)[y]) # ∇(−log q(y|s)) = q − onehot
Z -= lr * G / len(s)
return softmax_rows(Z), len(s)
print(f"교사의 정답 경로 확률 {success(P):.3f}, 초기 학생 {success(softmax_rows(Z0)):.1e}\n")
print("방법 학생/교사 토큰 reverse KL 정답 경로 확률")
for it in [20, 80, 300]:
Q, used = opd(it); r, _ = seq_kls(Q)
print(f"on-policy distill ({it:3d} iters) {used:6d} {r:7.3f} {success(Q):.3f}")
for it in [20, 80, 300]:
Q, hits = rl_outcome(it); r, _ = seq_kls(Q)
print(f"RL, 결과 보상 ({it:3d} iters) {it*4*L:6d} {r:7.3f} {success(Q):.3f} (성공 샘플 {int(hits)}개)")
for n in [20, 100]:
Q, used = sft(n); r, _ = seq_kls(Q)
print(f"SFT on teacher samples (n={n:3d}) {used:6d} {r:7.3f} {success(Q):.3f}")결과 보상 RL은 한 번도 성공하지 못한다. 거의 균등한 학생이 12토큰짜리 정답 경로를 우연히 따를 확률은 수준이고, 성공이 없으면 zero-variance 그룹처럼 신호가 0이다. 같은 학생 샘플로 on-policy distillation은 첫 iteration부터 모든 토큰에서 신호를 받아 교사에 수렴한다. 이 장난감은 학생이 교사를 정확히 표현할 수 있어서 SFT도 잘 된다. SFT의 정답 경로 확률이 교사(0.28)보다 높은 것은 적은 샘플에 과적합해 교사보다 결정적인 정책이 되었기 때문이고, 그만큼 reverse KL은 덜 줄었다. on-policy의 장점이 SFT와 비교해 크게 드러나는 것은 학생의 용량이 부족하거나(위의 KL 그림) horizon이 길어 학생이 교사가 가 보지 않은 상태에 자주 들어갈 때다.
마지막으로 PyTorch에서의 세 가지 증류 손실이다. 교사와 학생이 같은 tokenizer를 쓴다고 가정한다.
import torch
import torch.nn.functional as F
def hinton_kd_loss(student_logits, teacher_logits, T=2.0):
"""위치별 soft target 증류. logits: (B, L, V). T²로 gradient 크기를 맞춘다."""
log_q = F.log_softmax(student_logits / T, -1)
p = F.softmax(teacher_logits / T, -1)
return F.kl_div(log_q, p, reduction="batchmean") * T * T # KL(p‖q)
def full_reverse_kl_loss(student_logits, teacher_logits, mask):
"""GKD식: 학생이 생성한 시퀀스의 각 위치에서 어휘 전체에 대한 KL(q‖p)."""
log_q = F.log_softmax(student_logits.float(), -1)
log_p = F.log_softmax(teacher_logits.float(), -1)
kl = (log_q.exp() * (log_q - log_p)).sum(-1) # (B, L)
m = mask.float()
return (kl * m).sum() / m.sum().clamp(min=1)
def sampled_token_opd_loss(student_logp, teacher_logp, mask):
"""샘플된 토큰 하나로 추정 (RL 루프에 그대로 얹는 형태).
student_logp, teacher_logp: (B, L) — 학생이 샘플한 토큰의 log-prob.
advantage = log π_T − log π_S (detach), 할인 0. 기대값이 KL(q‖p)의 gradient와 같다."""
adv = (teacher_logp - student_logp).detach()
m = mask.float()
return -(adv * student_logp * m).sum() / m.sum().clamp(min=1)
# 학습 루프 스케치
# y = student.generate(x) # on-policy 샘플
# s_logp = token_logprobs(student, x, y) # grad 있음
# t_logp = token_logprobs(teacher, x, y).detach() # 교사는 채점만 (forward 1회)
# loss = sampled_token_opd_loss(s_logp, t_logp, response_mask)수학 RLVR에서 작은 학생 모델의 초기 정답률이 거의 0이라 GRPO가 아무 신호도 얻지 못한다. 같은 문제에 강한 교사 모델이 있을 때 가장 직접적인 해결책은?
결과 보상은 학생이 한 번이라도 맞혀야 신호가 생긴다(). 교사의 토큰별 log-prob은 학생이 틀린 풀이를 쓰더라도 각 토큰이 교사 기준으로 얼마나 그럴듯한지 알려 주므로, 정답률이 0이어도 모든 토큰에서 dense한 신호가 생긴다. 보상의 스케일을 키우는 것은 advantage가 0인 문제를 해결하지 못한다. 교사 샘플로 SFT부터 하는 것도 좋은 출발점이지만, 학생 자신의 상태에서 배우는 것은 on-policy distillation이다.
A menu of per-token losses: GKD and the generalised JSD
So far we have used two divergences, forward and reverse KL, and two data sources, teacher samples and student samples. GKD (Agarwal et al. 2024) treats these as two independent knobs. With a fixed dataset (ground truth or teacher samples) and a student-data fraction ,
where averages a token-level divergence over the positions of , and no gradient flows through the student’s sampling. with forward KL is supervised KD; is on-policy. The divergence slot can hold the generalised Jensen–Shannon divergence: with ,
Here is the teacher and the student. The two limits are worth deriving because the direction is easy to get backwards. As , . The first term is . The second term is
so : small β behaves like forward KL (mode covering). The same argument with the roles swapped gives as : β near 1 behaves like reverse KL (mode seeking). GKD states the first limit (after Huszár 2015) and that the gradients behave like forward and reverse KL near 0 and 1. Two more properties follow from and : each KL term is at most or , so . Unlike either KL, it stays bounded when one distribution puts near-zero probability where the other does not. Libraries do not all assign and the same way, so check which argument is the teacher before copying a β from a paper.
There is no universally best choice. In GKD’s experiments, on-policy JSD(0.9) and reverse KL did best on XSum summarisation with temperature sampling, on-policy JSD(0.1) was the best variant on WMT translation, reverse KL clearly beat forward KL for instruction tuning, and on GSM8K forward KL already worked well, and adding on-policy data helped once at least 25% of the data was on-policy.
The losses in this lesson, side by side ( = vocabulary size, per student token):
| Loss | What the teacher must send | Bias / behaviour | Cost and caveats |
|---|---|---|---|
| Forward KL, full vocabulary, | all log-probs | exact; mode covering | numbers per token; same tokenizer |
| Reverse KL, full vocabulary, | all log-probs | exact; mode seeking | same as above |
| JSD(β), full vocabulary | all log-probs | exact; forward-like as β→0, reverse-like as β→1; bounded by | same as above, plus the mixture |
| Sampled-token reverse KL (per-token reward ) | one log-prob, | unbiased per-state gradient of reverse KL, but high variance; ignores effects on later tokens (discount 0) | 1 number per token; drops into an RL loop |
| Top-k sparse KL | (log-prob, index) pairs | under-reports the KL as shrinks; what happens to the student’s tail depends on how the tail is handled | bytes per token; suits a remote, asynchronous teacher |
The last two rows exist because of transport. The rest of this lesson explains when each one wins.
Multi-teacher on-policy distillation
A frontier post-training run wants one model that is good at math, code, agentic search, chat and safety. Training a single RL run across all of them mixes reward scales and data ratios. Training them in sequence lets later stages erode earlier ones. The Nemotron-Cascade 2 report says that its domain-by-domain Cascade RL reduces forgetting but “does not fully eliminate capability drift as the number of training environments increases”, and gives examples: RLVR can lower entropy and shorten reasoning, which hurts math. Multi-teacher on-policy distillation (MOPD) splits the problem. First obtain one teacher per domain, then run on-policy distillation in which each prompt is graded by the teacher of its own domain.
Here is the domain of prompt and is a truncated importance weight. It corrects for the mismatch between the inference engine that sampled and the trainer, and drops tokens where the two disagree too much (see train–inference mismatch). The advantage is the sampled-token reward from the on-policy distillation section above, so the machinery is an ordinary RL loop with one teacher server per domain.
Why routing matters, in one line. Suppose instead that each prompt went to a teacher chosen at random. In expectation the loss is
so the student is distilled towards the normalised geometric mean of the teachers, which mixes in every teacher’s off-domain weakness. Routing replaces that blend with the best available teacher for each domain. A single generalist teacher, the other extreme, caps every domain at that one teacher’s level.
The two public reports differ in where the teachers come from.
- MiMo-V2-Flash (Xiaomi 2026) trains domain-specialised teachers “through independent RL optimization on focused tasks”. The agentic domains are search, coding and general tool use. The non-agentic ones are math reasoning, general reasoning and safety. The report notes that a teacher can also be a different SFT model or the student itself. By default the advantage adds an outcome-reward term, (e.g. a GRPO advantage), which is what lets the student go past a teacher. In its table the student moves from 89.3 to 94.1 on AIME 2025 (best teacher 93.9), from 77.5 to 83.2 on LiveCodeBench (best teacher 82.6) and from 67.8 to 73.4 on SWE-Bench Verified (best teacher 74.2). The gain is not uniform: BrowseComp ends at 45.4 against a 51.7 teacher, and Arena-Hard creative writing drops from 90.1 to 86.2.
- Nemotron-Cascade 2 (NVIDIA 2026) takes its teachers from its own cascade, “choosing the strongest validation checkpoint for each benchmark category”. The math teacher is the initial SFT checkpoint, another teacher is a checkpoint after RLHF, and the third comes from after the instruction-following and multi-domain RL stages. Because all of them share the SFT initialisation, they share the student’s tokenizer. MOPD sits in the middle of the cascade, after IF-RL and multi-domain RL and before RLHF, long-context, code and SWE RL. The advantage is computed only on the sampled token, with truncated importance weights at and . The report says MOPD typically converges within 40–50 steps. In a math-only comparison it reaches 92.0 on AIME25 within 30 steps, while GRPO goes from 89.9 to 91.0 in 25. On ArenaHard v2 hard prompts it goes from 71.5 to 85.5 in 52 steps, where RLHF had reached 80.7 after 160 steps.
The second recipe is the anti-forgetting use of on-policy distillation mentioned earlier, made systematic. Any earlier checkpoint that was best at something can serve as that domain’s teacher.
토큰별 손실의 메뉴: GKD와 일반화 JSD
지금까지 divergence 두 개(forward KL, reverse KL)와 데이터 출처 두 개(교사 샘플, 학생 샘플)를 썼다. GKD(Agarwal et al. 2024)는 이 둘을 독립된 손잡이로 다룬다. 고정 데이터셋 (정답이나 교사 샘플)와 학생 데이터 비율 에 대해
이고, 는 의 위치들에 대해 토큰 수준 divergence를 평균한 것이다. 학생의 샘플링 과정으로는 gradient를 흘리지 않는다. 에 forward KL이면 supervised KD, 이면 on-policy다. divergence 자리에는 일반화 Jensen–Shannon divergence를 넣을 수 있다. 라 하면
이다. 여기서 가 교사, 가 학생이다. 방향을 거꾸로 기억하기 쉬우니 두 극한을 직접 유도해 둘 만하다. 이면 다. 첫 항은 이고, 둘째 항은
이므로 다. β가 작으면 forward KL처럼(mode covering) 동작한다. 역할을 바꿔 같은 논리를 쓰면 에서 , 즉 β가 1에 가까우면 reverse KL처럼(mode seeking) 동작한다. GKD는 첫 번째 극한을 (Huszár 2015를 인용해) 적고, β가 0과 1 근처일 때 gradient가 각각 forward와 reverse KL처럼 행동한다고 쓴다. 와 에서 성질 두 개가 더 나온다. 각 KL 항은 , 이하이므로 다. 어느 KL과도 달리, 한쪽 분포가 다른 쪽이 쓰는 곳에 거의 0의 확률을 줘도 유한하게 남는다. 라이브러리마다 와 를 배정하는 방식이 같지 않으니, 논문의 β 값을 옮겨 쓰기 전에 어느 인자가 교사인지 확인해야 한다.
모든 경우에 가장 좋은 선택은 없다. GKD 실험에서 XSum 요약은 temperature 샘플링일 때 on-policy JSD(0.9)와 reverse KL이 가장 좋았고, WMT 번역은 on-policy JSD(0.1)이 가장 좋은 변형이었으며, instruction tuning에서는 reverse KL이 forward KL을 확실히 앞섰다. GSM8K에서는 forward KL로도 이미 잘 됐고, 데이터의 25% 이상이 on-policy일 때 on-policy 데이터를 늘리면 성능이 좋아졌다.
이 레슨의 손실들을 나란히 놓으면 다음과 같다( = 어휘 크기, 학생 토큰 하나당).
| 손실 | 교사가 보내야 하는 것 | 편향 / 행동 | 비용과 주의점 |
|---|---|---|---|
| forward KL, 어휘 전체, | log-prob 개 전부 | 정확; mode covering | 토큰당 숫자 개; 같은 tokenizer |
| reverse KL, 어휘 전체, | log-prob 개 전부 | 정확; mode seeking | 위와 같음 |
| JSD(β), 어휘 전체 | log-prob 개 전부 | 정확; β→0이면 forward, β→1이면 reverse에 가까움; 로 유계 | 위와 같음 + 혼합 계산 |
| 샘플 토큰 reverse KL (토큰 보상 ) | log-prob 하나, | 상태별 reverse KL gradient의 불편 추정이지만 분산이 큼; 뒤 토큰에 대한 영향 무시(할인 0) | 토큰당 숫자 1개; RL 루프에 그대로 들어감 |
| top-k sparse KL | (log-prob, index) 쌍 개 | 가 줄수록 KL을 과소평가; 학생의 꼬리가 어떻게 되는지는 꼬리 처리 방식에 달림 | 토큰당 바이트; 원격·비동기 교사에 맞음 |
마지막 두 줄은 전송 비용 때문에 존재한다. 이 레슨의 나머지는 각각이 언제 유리한지를 설명한다.
다중 교사 on-policy distillation
프런티어 사후학습은 수학, 코드, agentic 검색, 대화, 안전성을 모두 잘하는 모델 하나를 원한다. 모든 도메인을 RL 한 번에 몰아 돌리면 보상 스케일과 데이터 비율이 섞이고, 차례로 학습하면 뒤 단계가 앞 단계의 능력을 깎는다. Nemotron-Cascade 2 보고서는 도메인별로 이어 가는 Cascade RL이 망각을 줄이지만 학습 환경이 늘수록 능력 drift를 완전히 없애지는 못한다고 쓰고, RLVR이 엔트로피를 낮추고 추론을 짧게 만들어 수학을 해칠 수 있다는 예를 든다. 다중 교사 on-policy distillation(MOPD) 은 문제를 둘로 나눈다. 먼저 도메인마다 교사 하나를 얻고, 그다음 각 프롬프트를 그 도메인의 교사가 채점하는 on-policy distillation을 돌린다.
는 프롬프트 의 도메인이고, 는 잘라낸 importance weight다. 를 샘플한 추론 엔진과 학습기 사이의 불일치를 보정하고, 둘이 너무 다른 토큰은 버린다(학습–추론 불일치 참고). advantage는 위의 on-policy distillation 절에서 본 샘플 토큰 보상이므로, 장치 자체는 도메인마다 교사 서버가 하나씩 붙은 평범한 RL 루프다.
라우팅이 왜 중요한지 한 줄로. 대신 프롬프트마다 교사를 무작위로 골랐다고 하자. 기대 손실은
이라서, 학생은 교사들의 정규화된 기하평균으로 증류된다. 여기에는 모든 교사의 도메인 밖 약점이 섞여 있다. 라우팅은 이 혼합을 도메인마다 가장 좋은 교사로 바꾼다. 반대쪽 극단인 범용 교사 하나는 모든 도메인을 그 교사 수준에서 멈추게 한다.
두 공개 보고서는 교사를 어디서 얻느냐가 다르다.
- MiMo-V2-Flash(Xiaomi 2026)는 도메인 특화 교사를 좁은 과제에 대한 독립적인 RL로 학습한다. agentic 도메인은 검색, 코딩, 일반 tool use이고, 비agentic 도메인은 수학 추론, 일반 추론, 안전성이다. 교사는 다른 SFT 모델이나 학생 자신일 수도 있다고 적는다. advantage에는 기본으로 결과 보상 항을 더한다. (예: GRPO advantage)이고, 이 항 덕분에 학생이 교사를 넘어설 수 있다. 표에서 학생은 AIME 2025에서 89.3 → 94.1(최고 교사 93.9), LiveCodeBench에서 77.5 → 83.2(최고 교사 82.6), SWE-Bench Verified에서 67.8 → 73.4(최고 교사 74.2)로 오른다. 고르게 오르지는 않는다. BrowseComp는 교사 51.7에 비해 45.4에 그치고, Arena-Hard creative writing은 90.1에서 86.2로 내려간다.
- Nemotron-Cascade 2(NVIDIA 2026)는 교사를 자기 cascade에서 가져온다. 벤치마크 범주마다 검증 성능이 가장 좋은 체크포인트를 고른다. 수학 교사는 초기 SFT 체크포인트, 다른 교사는 RLHF 이후 체크포인트, 세 번째는 instruction-following RL과 multi-domain RL 이후 체크포인트다. 모두 같은 SFT 초기화에서 나왔으니 학생과 tokenizer가 같다. MOPD는 cascade 중간, IF-RL과 multi-domain RL 다음이자 RLHF, long-context, 코드, SWE RL 앞에 놓인다. advantage는 샘플된 토큰에서만 계산하고, , 의 잘라낸 importance weight를 쓴다. 보고서는 MOPD가 보통 40–50 step 안에 수렴한다고 쓴다. 수학만 비교한 실험에서 AIME25를 30 step 안에 92.0까지 올렸고, GRPO는 25 step에 89.9에서 91.0이 됐다. ArenaHard v2 hard prompt에서는 52 step에 71.5 → 85.5로, RLHF가 160 step에 도달한 80.7을 넘었다.
두 번째 레시피는 앞에서 말한 on-policy distillation의 망각 방지 용도를 체계화한 것이다. 무언가를 가장 잘하던 이전 체크포인트라면 무엇이든 그 도메인의 교사가 될 수 있다.
- With domain routing, all three domains climb to the teachers’ 0.9. Early in training (press Retrain and watch) the reward strip is blue on the ✓ tokens and red elsewhere. A wrong token in a code rollout is punished by the code teacher, which is the one model that knows it is wrong. As the student converges, every reward fades towards 0, because is a one-sample estimate of .
- Switch to one teacher (math). Math still reaches 0.9, but code and chat settle at 0.3. Early in training the strip now also gives positive reward to the math teacher’s favourite wrong token: outside its domain, the teacher’s log-probs are a confident wrong signal, not noise. A reward model with that bias would be called hackable. Here the student simply converges to the bias.
- Random teacher per prompt converges to the geometric mean from the derivation above, which in this toy gives about 0.61 everywhere. It is better than one teacher on two domains and worse than routing on all three.
- Raise the off-domain skill to 0.9 and the three modes give the same result. Routing pays off in proportion to how specialised the teachers are.
- Raise α. With the outcome-reward term the student’s fixed point moves past the teacher, because the reverse-KL term pulls it towards 0.9 while the outcome term keeps pushing towards the right token. This is the mechanism behind a student that “exceeds the best teacher”. Without α (or another reward), pure distillation’s ceiling is the teacher.
On-policy self-distillation
MOPD still needs strong teachers. On-policy self-distillation (OPSD) (Zhao et al. 2026) takes the teacher out entirely: the same model plays both roles under different contexts. For a problem with a reference solution , the student sees only . The teacher sees , and an instruction to understand the reference and then solve the problem in its own way. Both score the student’s own rollout :
Gradients flow only through the student, and the teacher is frozen at the initial policy rather than tracking the updated weights. Some details matter in practice:
- Divergence and estimator. The paper ablates forward KL, reverse KL and JSD(0.5), adopts full-vocabulary forward KL, and clips each token’s divergence contribution. The sampled-token variant, with advantage , was worse in its ablation (AIME25 82.1 vs 84.1, HMMT25 57.3 vs 60.0). Full logits are affordable here because teacher and student are the same model on the same GPUs. The cost the paper reports is higher peak memory.
- Results. On Qwen3-1.7B/4B/8B with up to 30k math problems from OpenThoughts, OPSD’s peak average over AIME24/AIME25/HMMT25 is 43.4 / 63.6 / 64.8, against GRPO peaks of 37.7 / 62.7 / 64.0. OPSD samples 1,024 tokens per problem, where GRPO samples 8 rollouts of 16k tokens. At 4B and 8B the gain over GRPO is small and holds only at OPSD’s peak. The largest gain is at 1.7B.
- Limits stated in the paper. Experiments stop at 8B. Training past about 100 steps can collapse. A problem beyond the model’s comprehension gives no useful signal even when the solution is in the context.
One way to read OPSD: it turns the RLVR setting (problems with a known answer) into a dense signal. The reference solution, seen in hindsight, tells the model which of its own tokens were on track. The failure mode to watch is leakage. A teacher that has seen can assign high probability to tokens that only make sense if you already know the answer, such as stating the final number early. A student without cannot learn those tokens honestly, which is one reason the teacher is told to solve the problem “in its own way” rather than copy the reference.
Shipping the teacher signal: top-k logits and asynchronous pipelines
A full-vocabulary loss needs the teacher’s whole distribution at every student token. For a 150k-token vocabulary in bf16 that is about 300 kB per token, or about 4.9 GB for a single 16k-token rollout. That is fine when teacher and student share GPUs and the logits never leave the device, as in OPSD. It is not fine when the teacher is a separate, larger model behind a network. There are two ways out. The sampled-token reward sends one number per token, at the cost of variance. Top-k sparse KL sends (log-prob, index) pairs per token, about 512 bytes at .
verl’s “Async On-Policy Knowledge Distillation Trainer” recipe describes the second design. A teacher service returns top-k log-probs and token indices for every valid response position, and the student minimises a token-wise on the teacher’s top-k support. The recipe also pipelines the three stages, which in the strictly synchronous version left “pipeline bubbles and underutilized GPUs”. A one-step-off scheduler rolls out the next batch while the actor updates, and overlaps weight sync with teacher retrieval. A two-step-off scheduler, for slow teachers, also overlaps rollout and update with teacher retrieval. The doc states the trade-off plainly: the overlap gives up “some strict on-policy guarantees” for throughput. The student’s samples are one or two policy versions old, which is the same staleness question as in asynchronous RL (async RL and staleness).
Truncating the teacher at changes the loss in two ways. The value is biased, because the tail term is missing. The optimum moves, and where it moves depends on what you do with the tail mass , where . With the teacher’s top-k set:
- Truncated sum, . Minimising over means maximising subject to , so the minimiser is on and elsewhere. The student is pushed to delete its tail and becomes sharper than the teacher. Using the teacher’s top-k, renormalised to sum to 1, as a cross-entropy target gives the same gradient up to the factor , so it has the same minimiser. Renormalising both sides on (the “renormalised” estimate in the figure) is different again: that loss never sees the student’s tail, and the tail logits get no gradient at all.
- Tail bucket: add the term , i.e. the KL between the two -category distributions in which the whole tail is one category. By the log-sum inequality this is a lower bound on the full KL. Its logit gradient is on and off , so the tail mass is matched while the student keeps its own tail shape.
- Sparse target: use the zero-padded top-k probabilities as a cross-entropy target, so the logit gradient is . Its stationary point puts the same probability on every tail token, which flattens the tail towards uniform.
Which one a trainer implements is a detail worth reading in the code. The bias shrinks quickly when the teacher is sharp, because within a few dozen tokens. That is typical of most positions in a reasoning trace. It matters most for high-entropy positions such as open-ended chat or creative writing.
- 도메인 라우팅이면 세 도메인 모두 교사의 0.9까지 오른다. 학습 초반에는(다시 학습을 누르고 보자) 보상 띠가 ✓ 토큰에서 파랗고 나머지에서 빨갛다. 코드 rollout의 오답 토큰을 벌하는 것은 코드 교사, 즉 그것이 틀렸다는 것을 아는 유일한 모델이다. 학생이 수렴하면 가 의 표본 하나짜리 추정이므로 모든 보상이 0 쪽으로 옅어진다.
- 교사 하나(수학) 로 바꿔 보자. 수학은 여전히 0.9에 가지만 코드와 대화는 0.3에 머문다. 학습 초반의 띠는 이제 수학 교사가 좋아하는 오답 토큰에도 양의 보상을 준다. 자기 도메인 밖에서 교사의 log-prob은 잡음이 아니라 자신 있게 틀린 신호다. 보상 모델이 이런 편향을 가졌다면 hackable하다고 불렀을 것이다. 여기서 학생은 그 편향으로 그냥 수렴한다.
- 프롬프트마다 무작위 교사 는 위 유도의 기하평균으로 수렴하고, 이 장난감에서는 모든 도메인에서 0.61 정도다. 두 도메인에서는 교사 하나보다 낫지만, 세 도메인 모두에서 라우팅보다 못하다.
- 도메인 밖 실력을 0.9로 올리면 세 방식의 결과가 같아진다. 라우팅의 이득은 교사가 얼마나 특화되어 있느냐에 비례한다.
- α를 올려 보자. 결과 보상 항이 있으면 학생의 고정점이 교사를 넘어선다. reverse KL 항은 0.9 쪽으로 당기고 결과 항은 계속 정답 토큰 쪽으로 밀기 때문이다. “최고 교사를 넘는” 학생의 기제가 이것이다. α(나 다른 보상)가 없으면 순수 증류의 상한은 교사다.
On-policy 자기 증류 (self-distillation)
MOPD도 강한 교사가 필요하다. On-policy self-distillation(OPSD)(Zhao et al. 2026)은 교사를 아예 없앤다. 같은 모델이 서로 다른 문맥에서 두 역할을 맡는다. 참고 풀이 가 있는 문제 에서 학생은 만 본다. 교사는 , , 그리고 “참고 풀이를 이해한 뒤 자기 방식으로 풀라”는 지시를 본다. 둘 다 학생 자신의 rollout 위에서 평가된다.
gradient는 학생 쪽으로만 흐르고, 교사는 갱신되는 가중치를 따라가지 않고 초기 정책으로 고정된다. 실전에서 중요한 세부 사항이 몇 가지 있다.
- divergence와 추정량. 논문은 forward KL, reverse KL, JSD(0.5)를 비교한 뒤 어휘 전체에 대한 forward KL을 택하고, 토큰별 divergence 기여를 clip한다. advantage가 인 샘플 토큰 변형은 ablation에서 더 나빴다(AIME25 82.1 vs 84.1, HMMT25 57.3 vs 60.0). 교사와 학생이 같은 GPU 위의 같은 모델이라 logits 전체를 쓸 수 있는 것이고, 논문이 밝힌 대가는 더 큰 최대 메모리다.
- 결과. OpenThoughts의 수학 문제 최대 3만 개로 Qwen3-1.7B/4B/8B를 학습했을 때, AIME24/AIME25/HMMT25 평균의 최고치는 OPSD가 43.4 / 63.6 / 64.8, GRPO가 37.7 / 62.7 / 64.0이다. OPSD는 문제당 1,024 토큰을 샘플하고, GRPO는 16k 토큰짜리 rollout 8개를 샘플한다. 4B와 8B에서는 GRPO 대비 이득이 작고 OPSD의 최고치에서만 성립한다. 이득이 가장 큰 것은 1.7B다.
- 논문이 밝힌 한계. 실험은 8B까지다. 약 100 step 넘게 학습하면 무너질 수 있다. 모델의 이해 범위를 넘는 문제는 풀이를 문맥에 넣어 줘도 쓸 만한 신호를 주지 못한다.
OPSD를 이렇게 읽을 수 있다. RLVR 설정(답이 알려진 문제)을 dense한 신호로 바꾼 것이다. 사후에 본 참고 풀이가, 모델 자신의 토큰 중 어느 것이 올바른 방향이었는지 알려 준다. 조심할 실패 양상은 누설(leakage)이다. 를 본 교사는 답을 이미 알아야만 말이 되는 토큰(예: 최종 숫자를 일찍 말하기)에 높은 확률을 줄 수 있고, 가 없는 학생은 그런 토큰을 정직하게 배울 수 없다. 교사에게 참고 풀이를 베끼지 말고 “자기 방식으로” 풀라고 지시하는 이유 중 하나다.
교사 신호 보내기: top-k logits와 비동기 파이프라인
어휘 전체 손실은 학생 토큰마다 교사의 분포 전체가 필요하다. 150k 어휘를 bf16으로 보내면 토큰당 약 300 kB, 16k 토큰 rollout 하나에 약 4.9 GB다. OPSD처럼 교사와 학생이 GPU를 공유해 logits가 장치 밖으로 나가지 않으면 괜찮다. 교사가 네트워크 너머의 별도의 더 큰 모델이면 그렇지 않다. 빠져나갈 길은 둘이다. 샘플 토큰 보상은 토큰당 숫자 하나를 보내고 분산을 대가로 치른다. top-k sparse KL은 토큰당 (log-prob, index) 쌍 개, 에서 약 512바이트를 보낸다.
verl의 “Async On-Policy Knowledge Distillation Trainer” 레시피가 두 번째 설계를 설명한다. 교사 서비스가 유효한 응답 위치마다 top-k log-prob과 토큰 index를 돌려주고, 학생은 교사의 top-k support 위에서 토큰별 를 줄인다. 이 레시피는 세 단계도 파이프라인으로 겹친다. 완전히 동기식인 버전은 파이프라인 bubble과 노는 GPU를 남겼다. one-step-off scheduler는 actor가 갱신되는 동안 다음 배치를 rollout하고, 가중치 동기화를 교사 조회와 겹친다. 느린 교사를 위한 two-step-off scheduler는 rollout과 갱신까지 교사 조회와 겹친다. 문서는 이 겹침이 엄밀한 on-policy 보장을 일부 내주고 처리량을 얻는 것이라고 분명히 적는다. 학생의 샘플은 정책 한두 버전만큼 오래된 것이고, 비동기 RL과 같은 staleness 문제다(비동기 RL과 staleness).
교사를 에서 자르면 손실이 두 가지로 바뀐다. 꼬리 항 가 빠지므로 값이 편향된다. 그리고 최적점이 옮겨 가는데, 어디로 옮겨 가는지는 꼬리 질량 (단 )를 어떻게 다루느냐에 달렸다. 를 교사의 top-k 집합이라 하자.
- 잘라낸 합 . 에 대해 최소화하면 아래에서 를 최대화하는 것이므로, 최적해는 위에서 , 나머지에서 이다. 학생은 자기 꼬리를 지우도록 밀리고 교사보다 뾰족해진다. 교사의 top-k를 합이 1이 되게 재정규화해 cross-entropy target으로 쓰면 gradient가 배 차이일 뿐이라 최적해가 같다. 양쪽을 모두 위에서 재정규화하는 것(그림의 “재정규화” 추정)은 또 다르다. 그 손실은 학생의 꼬리를 아예 보지 못하고, 꼬리 logits에는 gradient가 전혀 가지 않는다.
- tail bucket: 항을 더한다. 꼬리 전체를 범주 하나로 묶은 범주 분포 사이의 KL이다. log-sum 부등식에 의해 전체 KL의 하한이다. logit gradient는 위에서 , 밖에서 라서, 꼬리 질량은 맞추되 학생은 자기 꼬리 모양을 유지한다.
- sparse target: 0으로 채운 top-k 확률을 cross-entropy target으로 써서 logit gradient가 가 되게 한다. 그 정류점은 모든 꼬리 토큰에 같은 확률 를 주므로 꼬리를 균등 쪽으로 평평하게 만든다.
학습기가 이 중 어느 것을 구현하는지는 코드에서 읽어 볼 만한 세부 사항이다. 교사가 뾰족하면 몇십 개 토큰 안에서 이 되므로 편향이 빨리 줄어든다. 추론 trace의 대부분 위치가 그렇다. 열린 대화나 창작처럼 엔트로피가 높은 위치에서 가장 중요해진다.
- At the default (sharpness 1, a flat Zipf teacher) even out of 8,192 misses a large part of the KL. All three estimates lie below the dashed line: the truncated sum and the tail bucket because the tail term is missing or coarse-grained, the renormalised one because it ignores how much mass the student puts outside .
- Raise the sharpness to 2–3. The teacher’s top few tokens now hold almost all its mass, the curves meet the dashed line by –, and the payload stays under a kilobyte per token.
- Raise σ. A student that disagrees more with the teacher has more of its KL in the tail, so the gap at a fixed grows.
Try it: GKD limits, top-k KL and routed token rewards
The block below checks four things. (1) The two JSD(β) limits. (2) The top-k estimates against the full forward KL on a 32k vocabulary, for a flat and a sharp teacher. (3) Where each way of handling the tail drives the student when we actually optimise it. (4) The per-token reverse-KL reward of a code rollout graded by the routed (code) teacher and by the math teacher, a Monte Carlo check that is the per-position reverse KL, and the three routings of the figure.
import numpy as np
g = np.random.default_rng(7)
def lsm(z): # log-softmax along the last axis
z = z - z.max(-1, keepdims=True)
return z - np.log(np.exp(z).sum(-1, keepdims=True))
def kl(lp, lq): # KL(p‖q) from log-probs, per row
return (np.exp(lp) * (lp - lq)).sum(-1)
# ---- 1. generalised JSD(β) and its two limits ---------------------------------
lp = lsm(2.0 * g.normal(size=50)) # teacher P
lq = lsm(2.0 * g.normal(size=50)) # student Q
def jsd(beta):
lm = np.logaddexp(np.log(beta) + lp, np.log1p(-beta) + lq) # log(βP + (1−β)Q)
return beta * kl(lp, lm) + (1 - beta) * kl(lq, lm)
print(f"forward KL(P‖Q) = {kl(lp, lq):.4f} reverse KL(Q‖P) = {kl(lq, lp):.4f}")
for b in [1e-2, 1e-4, 1e-6]:
print(f" β = {b:<6g} JSD(β)/β = {jsd(b) / b:.4f}")
for b in [0.99, 0.9999, 0.999999]:
print(f" β = {b:<6g} JSD(β)/(1−β) = {jsd(b) / (1 - b):.4f}")
# ---- 2. top-k sparse forward KL vs the full KL, as k shrinks ------------------
V, N = 32768, 32 # a realistic vocabulary, 32 token positions
zipf = -1.1 * np.log(np.arange(1, V + 1))
for sharp, name in [(1.0, "flat teacher (open-ended chat)"), (3.0, "sharp teacher (a reasoning step)")]:
zt = sharp * (zipf + g.normal(size=(N, V))) # teacher logits; `sharp` = inverse temperature
zs = zt + 0.8 * g.normal(size=(N, V)) # student = teacher + mismatch
lpT, lqS = lsm(zt), lsm(zs)
order = np.argsort(-lpT, axis=1) # teacher's ranking per position
a_all = np.take_along_axis(lpT, order, 1)
b_all = np.take_along_axis(lqS, order, 1)
print(f"\n{name}: full forward KL(P‖Q) = {kl(lpT, lqS).mean():.3f}")
print(" k teacher mass truncated +tail bucket renormalised")
for k in [1, 8, 64, 512, 4096]:
a, b = a_all[:, :k], b_all[:, :k]
mP, mQ = np.exp(a).sum(1), np.exp(b).sum(1)
trunc = (np.exp(a) * (a - b)).sum(1) # Σ_top-k P log(P/Q)
tP, tQ = np.clip(1 - mP, 1e-300, 1), np.clip(1 - mQ, 1e-300, 1)
bucket = trunc + tP * (np.log(tP) - np.log(tQ)) # k+1 categories (tail = one bucket)
renorm = kl(a - np.log(mP)[:, None], b - np.log(mQ)[:, None]) # both renormalised on top-k
print(f"{k:6d} {mP.mean():.4f} {trunc.mean():7.3f} {bucket.mean():7.3f} {max(renorm.mean(), 0.0):7.3f}")
# ---- 3. where each top-k loss drives the student (one position, k = 20) --------
V1, k = 2000, 20
lp1 = lsm(-1.1 * np.log(np.arange(1, V1 + 1)) + g.normal(size=V1))
P1 = np.exp(lp1)
head = np.zeros(V1, bool); head[np.argsort(-lp1)[:k]] = True
mP1 = P1[head].sum()
PK = np.where(head, P1, 0.0)
def bucket_grad(q): # ∇_z of the (k+1)-category KL: q − target
mQ = q[head].sum()
return q - np.where(head, P1, q * (1 - mP1) / (1 - mQ))
losses = {
"full KL (all V logits)": lambda q: q - P1,
"top-k truncated sum": lambda q: mP1 * q - PK, # ∇ of −Σ_top-k P log q
"top-k sparse target": lambda q: q - PK, # gradient q − P_k
"top-k + tail bucket": bucket_grad,
}
z0 = lp1 + 1.0 * g.normal(size=V1) # a student that already has its own (imperfect) tail
print(f"\nstart: full KL(P‖Q) {kl(lp1, lsm(z0)):.3f}")
print(f"teacher: top-{k} mass {mP1:.3f}, tail mass {1 - mP1:.3f}, entropy {-(P1 * lp1).sum():.2f} nats")
print("loss student tail mass full KL(P‖Q) student entropy")
for name, grad in losses.items():
z = z0.copy() # the same pretrained student each time
for _ in range(2000):
z -= 5.0 * grad(np.exp(lsm(z)))
lq1 = lsm(z)
print(f"{name:24s} {np.exp(lq1)[~head].sum():.3f} {kl(lp1, lq1):6.3f} {-(np.exp(lq1) * lq1).sum():.2f}")
# ---- 4. per-token reverse-KL reward, routed to the prompt's domain teacher ----
D, L, A = 3, 8, 6 # 3 domains, 8 positions, 6 tokens per position
correct = g.integers(0, A, size=(D, L)).astype(np.intp) # each domain's right token per position
def teacher(d): # teacher d: expert in its own domain, weak elsewhere
T = np.empty((D, L, A))
for e in range(D):
if e == d: # own domain: 0.9 on the right token
T[e] = 0.1 / (A - 1); T[e, np.arange(L), correct[e]] = 0.9
else: # elsewhere: 0.3 right, 0.49 on its own favourite wrong token
T[e] = 0.21 / (A - 2); T[e, np.arange(L), correct[e]] = 0.3
T[e, np.arange(L), (correct[e] + 1 + d) % A] = 0.49
return np.log(T)
teachers = [teacher(d) for d in range(D)]
zS = 0.3 * g.normal(size=(D, L, A)) # student logits, per domain and position:
zS[np.arange(D)[:, None], np.arange(L), correct] += 1.2 # half-trained, p(right) ≈ 0.4
lqS4 = lsm(zS)
dom = 1 # a "code" prompt
y = np.array([g.choice(A, p=np.exp(lqS4[dom, t])) for t in range(L)], dtype=np.intp)
r_routed = teachers[dom][dom, np.arange(L), y] - lqS4[dom, np.arange(L), y]
r_wrong = teachers[0][dom, np.arange(L), y] - lqS4[dom, np.arange(L), y]
print("\nsampled tokens ", y, " right tokens", correct[dom])
print("r_t, routed teacher ", np.round(r_routed, 2))
print("r_t, math teacher ", np.round(r_wrong, 2))
# the sampled-token reward is an unbiased one-sample estimate of −KL(q‖p) per position
M = 20000
ys = np.array([g.choice(A, size=M, p=np.exp(lqS4[dom, t])) for t in range(L)]).astype(np.intp) # (L, M)
r = teachers[dom][dom, np.arange(L)[:, None], ys] - lqS4[dom, np.arange(L)[:, None], ys]
exact = kl(lqS4[dom], teachers[dom][dom])
print("exact KL(q‖p) per pos", np.round(exact, 3))
print("MC mean(−r_t) ", np.round(-r.mean(1), 3))
print("std of one-sample −r_t", np.round(r.std(1), 3), " ← the price of not sending full logits")
# train with the exact reverse-KL gradient under three routings
def train_route(target, steps=400, lr=1.0):
z = 0.3 * np.random.default_rng(3).normal(size=(D, L, A))
for _ in range(steps):
lq = lsm(z); q = np.exp(lq)
inner = lq - target
z -= lr * q * (inner - (q * inner).sum(-1, keepdims=True)) # ∇_z KL(q‖p)
q = np.exp(lsm(z))
return " ".join(f"{q[d, np.arange(L), correct[d]].mean():.3f}" for d in range(D))
routed = np.stack([teachers[d][d] for d in range(D)]) # each domain graded by its own teacher
single = teachers[0] # everything graded by the math teacher
geo = lsm(np.mean(teachers, axis=0)) # random teacher per prompt, in expectation
print("\np(right token) per domain math code chat")
print("MOPD (domain teacher) ", train_route(routed))
print("single teacher (math) ", train_route(single))
print("random teacher per prompt ", train_route(geo))What to read off the output:
- approaches the forward KL and the reverse KL, but slowly. The correction is times terms like that are large wherever the student puts little mass.
- For the flat teacher, covers only about 60% of the teacher’s mass and the truncated estimate sees a bit over half of the KL. For the sharp teacher, is exact to three decimals. The renormalised estimate is exactly 0 at , whatever the student does.
- Optimising the student shows the three tail behaviours derived above. The truncated sum drives the student’s tail mass from about 0.49 to almost 0 and ends with about half the teacher’s entropy, so the full KL ends up worse than where it started. The sparse target matches the tail mass but flattens it (entropy above the teacher’s). The tail bucket matches the mass and keeps the student’s own tail shape, so the full KL falls but not to 0. Only the full-vocabulary loss reaches ≈ 0.
- In the code rollout, the routed teacher rewards exactly the tokens that match the right answer and punishes the rest. The math teacher’s rewards are uninformative and positive on its own favourite wrong token. The Monte Carlo mean of matches the exact per-position KL, but a single token’s reward has a standard deviation larger than the mean. This is the variance you accept when the teacher sends one number instead of a distribution.
A remote teacher returns its top-8 log-probs per token. You renormalise those 8 probabilities to sum to 1 and use them as a cross-entropy target over the student's full vocabulary. On open-ended chat prompts, what happens to the student over training?
The renormalised target is on the top-8 set and 0 elsewhere. Cross-entropy towards it is minimised at , so every token outside is driven towards probability 0, even though the teacher gives the tail of its mass. On a flat (chat) teacher is large, so the student ends up much sharper, and less diverse, than the teacher. Options that keep the tail: add a tail bucket , raise , or use the sampled-token reverse-KL reward, which needs only the teacher’s log-prob of the token the student actually sampled.
Summary
- Distillation is organised by “which distribution do we sample from, and in which direction do we reduce the KL”. SFT on teacher samples = sequence-level forward KL; student samples + teacher grading = reverse KL.
- Hinton’s soft targets match distributions softened by a temperature and correct the gradient magnitude with . In LLMs this means matching the next-token distribution at every position.
- Synthetic data (Self-Instruct, rejection-sampled reasoning, R1 distillation) and Constitutional AI/RLAIF differ in whether the teacher gives demonstrations or judgements.
- Forward KL is mode covering, reverse KL is mode seeking. When the student lacks capacity, they give entirely different solutions. GKD’s interpolates between them (forward-like as , reverse-like as ) and is bounded by .
- On-policy distillation uses the teacher’s per-token log-probs as reward in the states the student visits. The sampled-token estimate is an unbiased estimate of the reverse-KL gradient, and it combines the advantage of on-policy RL (no exposure bias) with the dense signal of distillation. Its ceiling is the teacher unless an outcome reward is added.
- MOPD routes each prompt to its domain’s teacher. Random routing would distil towards the teachers’ geometric mean. MiMo-V2-Flash trains RL specialists as teachers, and Nemotron-Cascade 2 reuses its own best checkpoints to undo capability drift. OPSD makes the model its own teacher by conditioning on a reference solution.
- Transport decides the estimator. Full logits cost per token. The sampled-token reward costs 1 number but adds variance. Top-k sparse KL costs bytes but under-reports the KL and, depending on how the tail is handled, deletes, flattens or freezes the student’s tail.
- 기본값(sharpness 1, 평평한 Zipf 교사)에서는 8,192개 중 여도 KL의 상당 부분을 놓친다. 세 추정 모두 점선 아래에 있다. 잘라낸 합과 tail bucket은 꼬리 항이 빠지거나 거칠게 묶였기 때문이고, 재정규화는 학생이 밖에 얼마나 질량을 두는지를 무시하기 때문이다.
- sharpness를 2–3으로 올려 보자. 교사의 상위 몇 개 토큰이 질량을 거의 다 가지므로 곡선이 –에서 점선과 만나고, 전송량은 토큰당 1킬로바이트 아래에 머문다.
- σ를 올려 보자. 교사와 더 많이 다른 학생은 KL의 더 많은 부분이 꼬리에 있으므로, 같은 에서 차이가 커진다.
직접 해 보기: GKD 극한, top-k KL, 라우팅된 토큰 보상
아래 블록은 네 가지를 확인한다. (1) JSD(β)의 두 극한. (2) 32k 어휘에서 평평한 교사와 뾰족한 교사에 대해 top-k 추정을 전체 forward KL과 비교. (3) 꼬리를 다루는 각 방식으로 실제로 학생을 최적화했을 때 학생이 어디로 가는지. (4) 라우팅된(코드) 교사와 수학 교사가 채점한 코드 rollout의 토큰별 reverse-KL 보상, 가 위치별 reverse KL이라는 Monte Carlo 확인, 그리고 그림의 세 가지 라우팅.
import numpy as np
g = np.random.default_rng(7)
def lsm(z): # 마지막 축의 log-softmax
z = z - z.max(-1, keepdims=True)
return z - np.log(np.exp(z).sum(-1, keepdims=True))
def kl(lp, lq): # log-prob으로 KL(p‖q), 행마다
return (np.exp(lp) * (lp - lq)).sum(-1)
# ---- 1. 일반화 JSD(β)와 두 극한 ----------------------------------------------
lp = lsm(2.0 * g.normal(size=50)) # 교사 P
lq = lsm(2.0 * g.normal(size=50)) # 학생 Q
def jsd(beta):
lm = np.logaddexp(np.log(beta) + lp, np.log1p(-beta) + lq) # log(βP + (1−β)Q)
return beta * kl(lp, lm) + (1 - beta) * kl(lq, lm)
print(f"forward KL(P‖Q) = {kl(lp, lq):.4f} reverse KL(Q‖P) = {kl(lq, lp):.4f}")
for b in [1e-2, 1e-4, 1e-6]:
print(f" β = {b:<6g} JSD(β)/β = {jsd(b) / b:.4f}")
for b in [0.99, 0.9999, 0.999999]:
print(f" β = {b:<6g} JSD(β)/(1−β) = {jsd(b) / (1 - b):.4f}")
# ---- 2. k를 줄일 때 top-k sparse forward KL vs 전체 KL ------------------------
V, N = 32768, 32 # 현실적인 어휘 크기, 토큰 위치 32개
zipf = -1.1 * np.log(np.arange(1, V + 1))
for sharp, name in [(1.0, "평평한 교사 (열린 대화)"), (3.0, "뾰족한 교사 (추론의 한 단계)")]:
zt = sharp * (zipf + g.normal(size=(N, V))) # 교사 logits; `sharp` = 1/온도
zs = zt + 0.8 * g.normal(size=(N, V)) # 학생 = 교사 + 차이
lpT, lqS = lsm(zt), lsm(zs)
order = np.argsort(-lpT, axis=1) # 위치별 교사 순위
a_all = np.take_along_axis(lpT, order, 1)
b_all = np.take_along_axis(lqS, order, 1)
print(f"\n{name}: 전체 forward KL(P‖Q) = {kl(lpT, lqS).mean():.3f}")
print(" k 교사 질량 잘라낸 합 +tail bucket 재정규화")
for k in [1, 8, 64, 512, 4096]:
a, b = a_all[:, :k], b_all[:, :k]
mP, mQ = np.exp(a).sum(1), np.exp(b).sum(1)
trunc = (np.exp(a) * (a - b)).sum(1) # Σ_top-k P log(P/Q)
tP, tQ = np.clip(1 - mP, 1e-300, 1), np.clip(1 - mQ, 1e-300, 1)
bucket = trunc + tP * (np.log(tP) - np.log(tQ)) # k+1개 범주 (꼬리 = bucket 하나)
renorm = kl(a - np.log(mP)[:, None], b - np.log(mQ)[:, None]) # 둘 다 top-k 위에서 재정규화
print(f"{k:6d} {mP.mean():.4f} {trunc.mean():7.3f} {bucket.mean():7.3f} {max(renorm.mean(), 0.0):7.3f}")
# ---- 3. 각 top-k 손실이 학생을 어디로 끌고 가는가 (위치 하나, k = 20) -------
V1, k = 2000, 20
lp1 = lsm(-1.1 * np.log(np.arange(1, V1 + 1)) + g.normal(size=V1))
P1 = np.exp(lp1)
head = np.zeros(V1, bool); head[np.argsort(-lp1)[:k]] = True
mP1 = P1[head].sum()
PK = np.where(head, P1, 0.0)
def bucket_grad(q): # (k+1)범주 KL의 ∇_z: q − target
mQ = q[head].sum()
return q - np.where(head, P1, q * (1 - mP1) / (1 - mQ))
losses = {
"전체 KL (logits V개)": lambda q: q - P1,
"top-k 잘라낸 합": lambda q: mP1 * q - PK, # −Σ_top-k P log q의 ∇
"top-k sparse target": lambda q: q - PK, # gradient가 q − P_k
"top-k + tail bucket": bucket_grad,
}
z0 = lp1 + 1.0 * g.normal(size=V1) # 이미 자기 (불완전한) 꼬리를 가진 학생
print(f"\n시작: 전체 KL(P‖Q) {kl(lp1, lsm(z0)):.3f}")
print(f"교사: top-{k} 질량 {mP1:.3f}, 꼬리 질량 {1 - mP1:.3f}, 엔트로피 {-(P1 * lp1).sum():.2f} nats")
print("손실 학생 꼬리 질량 전체 KL(P‖Q) 학생 엔트로피")
for name, grad in losses.items():
z = z0.copy() # 매번 같은 사전학습 학생
for _ in range(2000):
z -= 5.0 * grad(np.exp(lsm(z)))
lq1 = lsm(z)
print(f"{name:24s} {np.exp(lq1)[~head].sum():.3f} {kl(lp1, lq1):6.3f} {-(np.exp(lq1) * lq1).sum():.2f}")
# ---- 4. 토큰별 reverse-KL 보상, 프롬프트의 도메인 교사로 라우팅 --------------
D, L, A = 3, 8, 6 # 도메인 3개, 위치 8개, 위치당 토큰 6개
correct = g.integers(0, A, size=(D, L)).astype(np.intp) # 도메인·위치별 정답 토큰
def teacher(d): # 교사 d: 자기 도메인 전문가, 다른 곳에선 약함
T = np.empty((D, L, A))
for e in range(D):
if e == d: # 자기 도메인: 정답 토큰에 0.9
T[e] = 0.1 / (A - 1); T[e, np.arange(L), correct[e]] = 0.9
else: # 다른 도메인: 정답 0.3, 자기가 좋아하는 오답 0.49
T[e] = 0.21 / (A - 2); T[e, np.arange(L), correct[e]] = 0.3
T[e, np.arange(L), (correct[e] + 1 + d) % A] = 0.49
return np.log(T)
teachers = [teacher(d) for d in range(D)]
zS = 0.3 * g.normal(size=(D, L, A)) # 도메인·위치별 학생 logits:
zS[np.arange(D)[:, None], np.arange(L), correct] += 1.2 # 반쯤 학습됨, p(정답) ≈ 0.4
lqS4 = lsm(zS)
dom = 1 # "코드" 프롬프트
y = np.array([g.choice(A, p=np.exp(lqS4[dom, t])) for t in range(L)], dtype=np.intp)
r_routed = teachers[dom][dom, np.arange(L), y] - lqS4[dom, np.arange(L), y]
r_wrong = teachers[0][dom, np.arange(L), y] - lqS4[dom, np.arange(L), y]
print("\n샘플된 토큰 ", y, " 정답 토큰", correct[dom])
print("r_t, 라우팅된 교사 ", np.round(r_routed, 2))
print("r_t, 수학 교사 ", np.round(r_wrong, 2))
# 샘플 토큰 보상은 위치별 −KL(q‖p)의 표본 하나짜리 불편 추정
M = 20000
ys = np.array([g.choice(A, size=M, p=np.exp(lqS4[dom, t])) for t in range(L)]).astype(np.intp) # (L, M)
r = teachers[dom][dom, np.arange(L)[:, None], ys] - lqS4[dom, np.arange(L)[:, None], ys]
exact = kl(lqS4[dom], teachers[dom][dom])
print("정확한 위치별 KL(q‖p) ", np.round(exact, 3))
print("MC 평균(−r_t) ", np.round(-r.mean(1), 3))
print("표본 하나 −r_t의 std ", np.round(r.std(1), 3), " ← logits 전체를 보내지 않는 대가")
# 세 가지 라우팅에서 정확한 reverse-KL gradient로 학습
def train_route(target, steps=400, lr=1.0):
z = 0.3 * np.random.default_rng(3).normal(size=(D, L, A))
for _ in range(steps):
lq = lsm(z); q = np.exp(lq)
inner = lq - target
z -= lr * q * (inner - (q * inner).sum(-1, keepdims=True)) # ∇_z KL(q‖p)
q = np.exp(lsm(z))
return " ".join(f"{q[d, np.arange(L), correct[d]].mean():.3f}" for d in range(D))
routed = np.stack([teachers[d][d] for d in range(D)]) # 도메인마다 자기 교사가 채점
single = teachers[0] # 전부 수학 교사가 채점
geo = lsm(np.mean(teachers, axis=0)) # 프롬프트마다 무작위 교사 (기대값)
print("\n도메인별 p(정답 토큰) 수학 코드 대화")
print("MOPD (도메인 교사) ", train_route(routed))
print("교사 하나 (수학) ", train_route(single))
print("프롬프트마다 무작위 교사 ", train_route(geo))출력에서 읽을 것:
- 는 forward KL에, 는 reverse KL에 다가가지만 느리다. 보정 항이 에 같은 항을 곱한 것이라, 학생이 질량을 적게 두는 곳에서 크다.
- 평평한 교사에서 는 교사 질량의 약 60%만 덮고, 잘라낸 추정은 KL의 절반 남짓만 본다. 뾰족한 교사에서는 가 소수점 셋째 자리까지 정확하다. 재정규화 추정은 학생이 무엇을 하든 에서 정확히 0이다.
- 학생을 최적화해 보면 위에서 유도한 세 가지 꼬리 행동이 그대로 나온다. 잘라낸 합은 학생의 꼬리 질량을 약 0.49에서 거의 0으로 몰고 엔트로피를 교사의 절반 정도로 만들어, 전체 KL이 시작보다 나빠진다. sparse target은 꼬리 질량은 맞추지만 평평하게 만든다(엔트로피가 교사보다 높다). tail bucket은 질량을 맞추고 학생 자신의 꼬리 모양을 유지해서, 전체 KL이 줄지만 0까지는 가지 않는다. ≈ 0에 도달하는 것은 어휘 전체 손실뿐이다.
- 코드 rollout에서 라우팅된 교사는 정답과 일치하는 토큰에 정확히 보상을 주고 나머지는 벌한다. 수학 교사의 보상은 정보가 없고, 자기가 좋아하는 오답 토큰에는 양수다. 의 Monte Carlo 평균은 정확한 위치별 KL과 맞지만, 토큰 하나의 보상은 표준편차가 평균보다 크다. 교사가 분포 대신 숫자 하나를 보낼 때 받아들이는 분산이다.
원격 교사가 토큰마다 top-8 log-prob을 돌려준다. 이 8개 확률을 합이 1이 되게 재정규화해 학생의 어휘 전체에 대한 cross-entropy target으로 쓴다. 열린 대화 프롬프트에서 학습이 진행되면 학생은 어떻게 되는가?
재정규화된 target은 top-8 집합 위에서 , 나머지에서 0이다. 이를 향한 cross-entropy는 에서 최소이므로, 교사가 꼬리에 질량 를 주는데도 밖의 모든 토큰이 확률 0 쪽으로 밀린다. 평평한(대화) 교사에서는 가 크므로 학생은 교사보다 훨씬 뾰족하고 덜 다양해진다. 꼬리를 지키는 선택지는 tail bucket 를 더하기, 키우기, 또는 학생이 실제로 샘플한 토큰의 교사 log-prob만 있으면 되는 샘플 토큰 reverse-KL 보상이다.
정리
- 증류는 “어느 분포에서 샘플하고 어느 방향의 KL을 줄이는가”로 정리된다. 교사 샘플로 SFT = 시퀀스 수준 forward KL, 학생 샘플 + 교사 채점 = reverse KL.
- Hinton의 soft target은 온도 로 부드럽게 한 분포를 맞추고 로 gradient 크기를 보정한다. LLM에서는 위치별 다음 토큰 분포를 맞추는 것이다.
- 합성 데이터(Self-Instruct, rejection-sampled 추론, R1 증류)와 Constitutional AI/RLAIF는 교사가 시연을 주느냐 판정을 주느냐의 차이다.
- forward KL은 mode covering, reverse KL은 mode seeking이다. 학생 용량이 부족할 때 둘은 전혀 다른 해를 낸다. GKD의 는 둘 사이를 보간하고(이면 forward, 이면 reverse에 가까움) 로 유계다.
- On-policy distillation은 학생이 방문한 상태에서 교사의 토큰별 log-prob을 보상으로 쓴다. 샘플 토큰 추정은 reverse KL gradient의 불편 추정이고, on-policy RL의 장점(exposure bias 없음)과 증류의 dense한 신호를 함께 갖는다. 결과 보상을 더하지 않는 한 상한은 교사다.
- MOPD는 각 프롬프트를 그 도메인의 교사에게 보낸다. 무작위 라우팅이면 교사들의 기하평균으로 증류된다. MiMo-V2-Flash는 RL 전문가들을 교사로 학습하고, Nemotron-Cascade 2는 자기 최고 체크포인트를 재사용해 능력 drift를 되돌린다. OPSD는 참고 풀이를 조건으로 넣어 모델을 자기 자신의 교사로 만든다.
- 전송 비용이 추정량을 정한다. logits 전체는 토큰당 , 샘플 토큰 보상은 숫자 1개지만 분산이 더해지고, top-k sparse KL은 바이트지만 KL을 과소평가하며 꼬리 처리 방식에 따라 학생의 꼬리를 지우거나, 평평하게 하거나, 그대로 둔다.
더 읽을거리Further reading
- Hinton, Vinyals, Dean, Distilling the Knowledge in a Neural Network (2015) — temperature를 쓴 soft target 증류와 T² 스케일링의 원전.The original source of soft-target distillation with a temperature, and of T² scaling.
- Kim & Rush, Sequence-Level Knowledge Distillation (EMNLP 2016) — 교사가 생성한 시퀀스로 학생을 학습하는 시퀀스 수준 증류.Sequence-level distillation, which trains the student on sequences generated by the teacher.
- Wang et al., Self-Instruct: Aligning Language Models with Self-Generated Instructions (ACL 2023) — 모델이 지시문과 응답을 스스로 만들어 instruction 데이터를 키우는 합성 데이터 파이프라인.A synthetic-data pipeline in which a model writes its own instructions and responses to grow instruction data.
- Bai et al., Constitutional AI: Harmlessness from AI Feedback (2022) — 원칙(constitution)에 따른 자기 비평·수정 SL 단계와 AI 선호로 학습하는 RL 단계(RLAIF).An SL stage of self-critique and revision guided by principles (a constitution), and an RL stage trained on AI preferences (RLAIF).
- Agarwal et al., On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes (ICLR 2024) — GKD. 학생이 생성한 시퀀스 위에서 토큰별 divergence(forward, reverse, JSD)로 증류.GKD. Distillation with per-token divergences (forward, reverse, JSD) on sequences generated by the student.
- Gu et al., MiniLLM: Knowledge Distillation of Large Language Models (ICLR 2024) — 생성 모델 증류에서 reverse KL을 policy gradient로 최적화.Optimizes reverse KL with policy gradients for distilling generative models.
- Thinking Machines Lab, On-Policy Distillation (2025, blog) — 교사의 토큰별 log-prob을 보상으로 쓰는 on-policy distillation을 RL 학습 루프 위에서 설명하고 비용 대비 효과를 논의.Explains on-policy distillation, which uses the teacher's per-token log-probs as reward, on top of an RL training loop, and discusses its cost-effectiveness.
- Ross, Gordon, Bagnell, A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning (AISTATS 2011) — DAgger. 학습자가 방문한 상태에서 전문가 레이블을 받아야 하는 이유(compounding error).DAgger. Why expert labels must be collected in the states the learner visits (compounding error).
- DeepSeek-AI, DeepSeek-R1 (2025) — R1이 만든 추론 데이터로 작은 dense 모델들을 SFT 증류. 같은 크기에서 RL을 직접 돌린 것보다 증류가 나았다는 비교.SFT-distills small dense models on reasoning data produced by R1, with a comparison showing distillation beat running RL directly at the same size.
- Xiaomi, MiMo-V2-Flash Technical Report (2026) — 다중 교사 on-policy distillation(MOPD). 도메인별 RL 전문가 교사, 토큰 log-ratio advantage + 결과 보상 항, 잘라낸 importance weight.Multi-teacher on-policy distillation (MOPD). Domain-specialist RL teachers, a token log-ratio advantage plus an outcome-reward term, truncated importance weights.
- NVIDIA, Nemotron-Cascade 2 (2026) — cascade RL 중간에 MOPD를 넣어, 자기 최고 체크포인트들을 도메인 교사로 써서 능력 drift를 되돌린다.Places MOPD in the middle of a cascade RL pipeline, using its own best checkpoints as domain teachers to undo capability drift.
- Zhao et al., Self-Distilled Reasoner: On-Policy Self-Distillation for Large Language Models (2026) — OPSD. 참고 풀이를 본 자기 자신을 교사로 쓰는 on-policy 증류. divergence·추정량 ablation 포함.OPSD. On-policy distillation in which the model, conditioned on a reference solution, is its own teacher. Includes divergence and estimator ablations.
- verl, Recipe: Async On-Policy Knowledge Distillation Trainer (2025) — 교사가 top-k log-prob을 돌려주는 sparse KL 증류와 one/two-step-off 비동기 scheduler.Sparse-KL distillation from a teacher that returns top-k log-probs, with one-/two-step-off asynchronous schedulers.
- Qwen Team, Qwen3 Technical Report (2025) — 작은 모델을 off-policy 증류 다음 on-policy 증류로 만든다. RL 대비 GPU 시간 비교.Builds small models with off-policy then on-policy distillation, with a GPU-hour comparison against RL.
- Lambert, RLHF Book — Synthetic Data & Distillation chapter — 사후학습에서 합성 데이터와 증류가 차지하는 위치.Where synthetic data and distillation sit in post-training.