AI Wiki中文/EN

LLM distillation: which behavior can a smaller student retain?

语言模型蒸馏

Compare exact forward and reverse sequence KL under an explicit student-capacity constraint.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A student that cannot remember the first token

Consider an invented language with only two-token sequences: 00,01,10,11. A teacher assigns probabilities 0.49,0.01,0.01,0.49. It strongly prefers matching pairs. Now restrict the student: both positions independently use the same probability p of producing 1. No choice of p can express “choose either first token, then copy it.” Before comparing training losses, notice this missing dependency.

Knowledge distillation trains a student using information from a teacher. In language models that information can include generated answers or probability distributions over next tokens. Generated-answer training can work without teacher logits, but discards alternatives not sampled. Distribution matching offers richer targets while requiring access to probabilities and usually compatible token events. Neither turns a teacher’s errors into facts.

Hinton and colleagues describe temperature-softened targets and a combined hard/soft-target objective. The soft-target gradient contribution is scaled by T² when temperature is changed, compensating its large-temperature scaling. This is the origin of a useful training device, not a theorem that every smaller model can preserve its teacher. Distillation paper

KL direction changes which approximation a restricted student selects.
KL direction changes which approximation a restricted student selects.

The direction of approximation matters

For sequence s with two bits and k ones, our restricted student’s distribution is:

p=σ(θ),qθ(s)=pk(1−p)2−k,k=s1+s2.p=\sigma(\theta),\qquad q_\theta(s)=p^k(1-p)^{2-k},\qquad k=s_1+s_2.

Call the teacher distribution P. Forward KL takes its expectation under the teacher; reverse KL takes it under the student. All four probabilities are positive in this experiment, so both quantities are finite.

DF=∑sP(s)log⁡P(s)qθ(s),DR=∑sqθ(s)log⁡qθ(s)P(s).D_{\mathrm{F}}=\sum_s P(s)\log\frac{P(s)}{q_\theta(s)},\qquad D_{\mathrm{R}}=\sum_s q_\theta(s)\log\frac{q_\theta(s)}{P(s)}.

The sequence score, meaning the derivative of its log probability, follows by differentiating the two Bernoulli factors:

∂log⁡qθ(s)∂θ=k−2p.\frac{\partial\log q_\theta(s)}{\partial\theta}=k-2p.

The teacher expects one 1 per sequence. Forward KL therefore has gradient 2p−1 and is minimized at p=0.5. For reverse KL, differentiate both the weight and the logarithm. The extra constant term vanishes because the derivative of total probability is zero:

∂DF∂θ=2p−1,∂DR∂θ=∑sqθ(s)log⁡qθ(s)P(s)(k−2p).\frac{\partial D_{\mathrm{F}}}{\partial\theta}=2p-1,\qquad \frac{\partial D_{\mathrm{R}}}{\partial\theta}=\sum_s q_\theta(s)\log\frac{q_\theta(s)}{P(s)}(k-2p).

This explains the tradeoff. Forward KL must cover both common teacher sequences, but the independent student then spends half its mass on mismatched pairs. Reverse KL penalizes student mass where the teacher gives little support and can favor one matching-pair mode. It then neglects the other teacher mode. “Mode seeking” describes this example’s geometry, not a universal improvement in answer quality.

For a real autoregressive student, sequence probability factors by prefix:

qθ(s∣x)=∏t=1Lqθ(st∣x,s<t).q_\theta(s\mid x)=\prod_{t=1}^{L}q_\theta(s_t\mid x,s_{<t}).

There are V^L possible fixed-length sequences for vocabulary size V. Full enumeration is normally impossible; the choice of sampled prefixes and gradient estimator becomes part of the method. Gu and colleagues’ first-version MiniLLM work uses reverse KL with sampling and optimization machinery. Our four-state calculation isolates KL direction and implements none of that large-model training pipeline. MiniLLM v1

The teacher’s dependency is visible in its conditional probabilities:

P(s1=1)=0.5,P(s2=1∣s1=0)=0.02,P(s2=1∣s1=1)=0.98.P(s_1=1)=0.5,\qquad P(s_2=1\mid s_1=0)=0.02,\qquad P(s_2=1\mid s_1=1)=0.98.

An autoregressive student with sufficient conditional parameters could represent this teacher exactly. The difficulty is imposed by our shared independent Bernoulli family, not by the existence of a small sequence alphabet.

Four states, two losses, three outcomes

Use Python 3.12 and NumPy 1.26.4. The program evaluates exact sums and runs 2,000 projected gradient steps with rate 0.2. It starts forward KL at theta=2; reverse KL starts at −2,2 and 0. Projection to [−12,12] keeps the numerical search bounded. There is no sampled data or random initialization.

"""Exact sequence KL for an under-capacity two-token student; not MiniLLM training."""
import itertools,json,math
import numpy as np

STATES=np.array(list(itertools.product([0,1],repeat=2)))
TEACHER=np.array([.49,.01,.01,.49])


def distribution(theta):
    if isinstance(theta,bool) or not np.isscalar(theta) or not math.isfinite(theta) or abs(theta)>20:raise ValueError('finite scalar logit in[-20,20] required')
    p=1/(1+math.exp(-theta));ones=STATES.sum(axis=1);q=p**ones*(1-p)**(2-ones)
    return p,q


def objective(theta,direction,teacher=TEACHER):
    teacher=np.asarray(teacher,dtype=float)
    if teacher.shape!=(4,) or not np.isfinite(teacher).all() or np.any(teacher<=0) or not np.isclose(teacher.sum(),1):raise ValueError('positive normalized four-sequence teacher required')
    p,q=distribution(theta);score=STATES.sum(axis=1)-2*p
    if direction=='forward':return float(teacher@np.log(teacher/q)),float(-teacher@score)
    if direction=='reverse':
        ratio=np.log(q/teacher);return float(q@ratio),float((q*ratio)@score)
    raise ValueError('direction must be forward or reverse')


def train(direction,start,steps=2000,rate=.2):
    distribution(start)
    if type(steps) is not int or not 1<=steps<=10000 or not math.isfinite(rate) or not 0<rate<=1:raise ValueError('bounded steps and learning rate required')
    theta=float(start);history=[]
    for i in range(steps):
        loss,grad=objective(theta,direction)
        if i%100==0:history.append(dict(step=i,loss=loss))
        theta=float(np.clip(theta-rate*grad,-12,12))
    p,q=distribution(theta);loss,grad=objective(theta,direction);history.append(dict(step=steps,loss=loss))
    return dict(theta=theta,token_one=p,sequences=q.tolist(),forward_kl=objective(theta,'forward')[0],reverse_kl=objective(theta,'reverse')[0],off_mode_mass=float(q[1]+q[2]),gradient=grad,history=history)


def demo():
    runs={'forward':train('forward',2),'reverse_left':train('reverse',-2),'reverse_right':train('reverse',2),'reverse_symmetric':train('reverse',0)}
    grid=np.linspace(-5,5,101);curve=[dict(theta=float(t),forward=objective(t,'forward')[0],reverse=objective(t,'reverse')[0]) for t in grid]
    return dict(states=STATES.tolist(),teacher=TEACHER.tolist(),teacher_first_one=.5,teacher_next_one_given_zero=.02,teacher_next_one_given_one=.98,runs=runs,objective_curve=curve)

if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

Forward KL reaches p=0.5 and assigns 0.25 to every sequence. Reverse KL from the asymmetric starts reaches about p=0.024011 and p=0.975989; mismatched-pair mass falls from 0.5 to about 0.046870. Reverse KL is about 0.669229 there, but forward KL rises from about 0.595108 to 2.962347. A better score for one objective need not be better for the other.

Starting reverse KL at exactly zero leaves the gradient at zero and the student at p=0.5. Nearby nonzero parameters lower that reverse objective. A stationary point is not automatically a minimum. The independent tests check the analytic derivatives with finite differences, so the stuck run is an intended symmetry example rather than an unexamined optimizer result.

Each step visits four states: O(4J) work for J steps, plus stored history. General enumeration costs O(JV^L) state evaluations, with sequence-length work per evaluation. The tiny program needs no GPU; full language-model distillation requires teacher/student computation, training data, optimizer memory and evaluation beyond this example.

Choose what the student must preserve

Begin an engineering comparison with a student trained on available ground-truth examples, then compare teacher-generated targets under the same student architecture and data budget. Separate training, selection and final evaluation. Inspect accuracy, coverage of rare outputs, harmful teacher errors, inference cost and whether the student follows the intended task. A teacher-distribution objective alone does not measure truthfulness.

Forward and reverse KL require care when distributions have zeros: the unsupported direction can be infinite. Our code rejects zero teacher probabilities to keep the demonstration within its stated domain. Tokenizer differences require an explicit mapping or sequence-level interface; equal array sizes do not establish equal events. Sampling, temperature, student capacity and loss direction are separate design choices. See self-distillation for a different teacher–student relationship.

What can the student represent?

  1. Why can this student not exactly match the teacher?

Answer: Its second-token probability is always p, independent of the first token. The teacher requires two different conditionals, 0.02 and 0.98.

  1. At p=0.5, how much probability goes to 01 and 10 together?

Answer: Each has probability 0.25, so the total is 0.5. The teacher gives them only 0.02 together.

  1. Reverse KL has zero gradient at theta=0. Does this prove the fitted student is optimal?

Answer: No. Nearby nonzero theta lowers the objective, and the asymmetric runs find lower values. Zero first derivative alone does not classify a stationary point.

  1. A student must cover both equally important teacher modes. Should it be selected solely by the lowest reverse KL?

Answer: No. Measure mode coverage and the actual task objective. A more expressive conditional student may preserve both modes; choosing a loss cannot remove a representational restriction.

Soft targets and sequence-level objectives

Read Hinton’s target-temperature construction alongside Gu’s sequence-distribution objective. Their methods address different parts of the training problem. The MiniLLM source here is the original version titled “Knowledge Distillation of Large Language Models”; the program is an independent exact KL experiment, not a reproduction of its policy-gradient implementation or reported model scores.

Make a prediction, then check

Can choosing reverse KL restore a dependency absent from the student family?

Choose one answer

Learning objectives

  • Explain the role of teacher targets, student capacity, KL direction and sequence sampling.
  • Run the original finite experiment and explain its counterexample and scope.

Prerequisites & connections

Explore related knowledge →

References

  1. Distilling the Knowledge in a Neural Network — arXiv v1
    Geoffrey Hinton; Oriol Vinyals; Jeff Dean · 2015
  2. Knowledge Distillation of Large Language Models — v1
    Yuxian Gu; Li Dong; Furu Wei; Minlie Huang · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author. New reading: viewed PDF2/3, temperature-softened targets and T squared gradient compensation. Existing Source object preserved. Viewed PDF3/4: reverse KL, sampling/gradient approximations; retain original v1 title. Printed length-normalization denominator not implemented. 6 paired equations and four explained exercises. Exact four-state forward/reverse KL and analytic gradients checked against finite differences; capacity restriction and symmetric stationary failure explicit. No MiniLLM reproduction.

  • Exact four-state forward/reverse KL and analytic gradients checked against finite differences; capacity restriction and symmetric stationary failure explicit. No MiniLLM reproduction.
  • Four computed SVG variants per topic;11 numeric/geometry tests and36 responsive cases passed. Twelve selected final captures directly viewed. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.