Module contents
Lesson 28 of 28Advanced 115 min

Knowledge distillation II: language models, reverse KL and on-policy distillation

Study token- and sequence-level distillation, forward and reverse KL, student-generated prefixes and sparse teacher logits. A local SmolLM2 experiment compares four objectives on a small arithmetic task on an RTX 3060.

After this lesson you can

  • Implement token distillation with full and sparse logits and sequence-level distillation.
  • Choose forward, reverse or intermediate divergences according to the desired behavior.
  • Implement on-policy distillation and explain its relationship to exposure bias.
  • Use empirical distillation scaling laws to reason about costs.
  • Distill a small LLM from a larger teacher and compare methods on a verifiable task.

Before you start

What behavior is transferred

An autoregressive model assigns a distribution to each next token conditioned on the prefix. Token- or sequence-level distillation determines which part of that behavior to use as a target. Token-level distillation reproduces a teacher distribution for each observed prefix; sequence-level distillation learns from particular continuations produced by the teacher. Both can be combined, but do not necessarily optimize the same loss or see the same prefixes.

With prompt xx, sequence y=(y1,…,yL)y=(y_1,\ldots,y_L) and teacher and student distributions PP and QQ,

P(y∣x)=∏t=1LP(yt∣x,y<t),Q(y∣x)=∏t=1LQ(yt∣x,y<t).P(y\mid x)=\prod_{t=1}^L P(y_t\mid x,y_{<t}),\qquad Q(y\mid x)=\prod_{t=1}^L Q(y_t\mid x,y_{<t}).

End of sequence is treated as a token or a common horizon is fixed. The probability of a variable-length sequence includes the event of ending; truncating generation without stating it changes the outcome space. Kim and Rush studied word- and sequence-level distillation in translation, where teacher-generated sequences provide targets distinct from human references.

Proof

Substitute the autoregressive factorization into log⁡(P/Q)\log(P/Q) and turn the product into a sum. The expectation of each term under P(Y∣x)P(Y\mid x) depends only on the prefix and current token; marginalizing later tokens leaves conditional KL averaged over prefixes from PP. If PP assigns positive mass where QQ assigns zero, KL is infinite. The identity does not automatically permit replacing prefixes from PP with prefixes from QQ.

∎

In teacher forcing, a fixed sequence is fed in and next-token distributions compared. If that sequence comes from a human corpus, expectation is over that corpus, not the full teacher model. If it comes from exact sampling of PP, it approximates the identity’s expectation. Using one greedy continuation concentrates the target on one output and is not equivalent to integrating all teacher sequences. Continuation quality matters: a teacher can make mistakes, invent an answer or produce a style that does not match the deployment objective.

Three sources of prefixes

Distinguish three data distributions. A human reference corpus can contain prefixes to which the teacher assigns low probability. Sequences sampled from the teacher follow its distribution, with variation between samples and possible accumulation of its errors. Greedy or search sequences are a high-probability selection, not an unbiased sample of that distribution. Student prefixes show errors it visits during deployment, but change as it trains and must be queried again to reflect the current policy.

In a cell with human answers, token-level KL teaches the teacher’s distribution over reference prefixes. In a sequence cell, the student can train with cross-entropy on teacher-produced text without access to its logit vector. These are different forms of supervision: a particular answer loses information about alternatives present in a full distribution. At the same time, generating more synthetic answers can broaden coverage, though a synthetic label does not become true merely because it comes from a larger model.

Length and termination matter too. A model can assign high probability to the correct prefix and then stop too soon, or produce the correct answer followed by text incompatible with the evaluator. When comparing sequences, specify the end token, maximum length and whether the decoder applies temperature, search or truncation. Dividing loss by token count changes the relative weighting of long and short sequences compared with the total sum.

Two directions of KL

The choice of divergence changes which disagreements weigh most. Forward KL KL⁡(P∥Q)\operatorname{KL}(P\|Q) strongly penalizes the student ignoring a region where the teacher assigns mass. Reverse KL⁡(Q∥P)\operatorname{KL}(Q\|P) penalizes the student placing mass where the teacher has almost none. For a restricted student family, this can favor respectively a solution covering several modes or selecting one. It is not a universal law: if the student can represent the teacher and the global optimum is reached, both KLs are minimized at Q=PQ=P.

InteractiveCover or choose a mode

Blue: bimodal teacher. Orange: optimized unimodal Gaussian student.

-4-2024

In the ordinary family two KLs are mixed; in the skewed family two KLs with smoothed denominator and α = 0.1 are mixed. KLs shown in controls are ordinary ones. The grid shows one solution under symmetry; distributions are normalized over the interval.

0
0
Familyordinary
Chosen objective0.535
Reverse weight0.0
Student mean0.00
Deviation2.30
Forward KL0.535
Reverse KL1.092
A grid search fits a unimodal normal to a bimodal mixture with ordinary or skewed losses.

The figure calculates both KLs over a finite grid of positions, means and deviations. At the reverse endpoint there are two symmetric solutions; only one is drawn. The ordinary family mixes the two KLs. The skewed family fixes a=0.1a=0.1 and mixes KL⁡(P∥aP+(1−a)Q)\operatorname{KL}(P\|aP+(1-a)Q) with KL⁡(Q∥aQ+(1−a)P)\operatorname{KL}(Q\|aQ+(1-a)P). Ordinary KLs are also shown in each case, so the skewed objective is not confused with them. On this grid the skewed reverse variant retains a wide solution: reversing direction does not always select one mode. Chosen shape, separation and family determine the result; they do not prove how a real LLM will respond.

Reverse KL can also be infinite. For P=(0.5,0.5,0)P=(0.5,0.5,0) and Q=(0.9,0.05,0.05)Q=(0.9,0.05,0.05), KL⁡(P∥Q)≈0.8574\operatorname{KL}(P\|Q)\approx0.8574, while KL⁡(Q∥P)=∞\operatorname{KL}(Q\|P)=\infty because QQ assigns mass to the third event and PP does not. Adding a small floor changes the problem and its value, though it may prevent numerical overflow. Finite softmax values generally have mathematically positive support, but rounding can produce zeros in an implementation.

MiniLLM studies reverse KL in generative models and on-policy optimization; Wen and colleagues examine other sequence-level divergences. An intermediate divergence can change the tradeoff between modes, but its definition and gradient must be checked: not all probability or loss mixtures are the same divergence family. Diversity, fidelity, accuracy and cost are distinct metrics.

Support, modes and small numbers

KL asymmetry is especially visible when a probability approaches zero. In forward KL, pilog⁡(pi/qi)p_i\log(p_i/q_i) grows if pip_i remains positive and qiq_i decreases. In reverse the analogous effect occurs with pp and qq exchanged. A narrow normal approximating a bimodal distribution must choose where to place its mean; a wide normal can cover both regions at the cost of assigning probability to intermediate values the teacher rarely produces. The figure shows this tension for one family, not a definitive classification of every student as diverse or precise.

A practical detail is that a per-token average and sequence KL sum do not answer the same question if length changes. There may also be multiple samples per prompt and different temperatures for generation and objective calculation. Recording these choices helps interpret whether a change comes from divergence or data distribution. Better teacher agreement does not guarantee a correct answer either: if the teacher is wrong, fidelity and accuracy can move in opposite directions.

Student prefixes and exposure bias

With teacher forcing, the student may succeed on correct prefixes and enter an unseen state after its own mistake. On-policy distillation queries the teacher on prefixes generated by the student itself. GKD explores this idea with different divergences. It is related to interactive data collection in DAgger: states visited by the learned policy are incorporated, although a particular distillation recipe is not identical to that algorithm.

InteractiveAccumulating errors

Blue: off-policy; orange: hypothetical on-policy. The teacher always returns to the correct state.

10step 20

In the incorrect state the student stays wrong with probability 0.95 or 0.30, respectively. These are assumed parameters, not training results; on-policy does not guarantee this improvement.

20
8
Final off-policy error57.7 %
Final on-policy error10.3 %
A two-state chain calculates error probability with two assumed recovery rules.

The figure uses an exact recurrence, not a learning experiment: if btb_t is the probability of an incorrect state, ee the probability of leaving the correct state and rr the probability of remaining incorrect, then bt+1=(1−bt)e+btrb_{t+1}=(1-b_t)e+b_t r. Values r=0.95r=0.95 and r=0.30r=0.30 illustrate two possible behaviors. The toy teacher always proposes returning to the correct state. A real teacher may not know how to correct an incoherent prefix and querying may be expensive; observing student states does not guarantee improvement.

For reverse sequence KL, sampling from QθQ_\theta itself depends on the parameters. If fθ(y)=log⁡Qθ(y)−log⁡P(y)f_\theta(y)=\log Q_\theta(y)-\log P(y) and support is shared, the score-function estimator gives

∇θKL⁡(Qθ∥P)=EY∼Qθ[(log⁡Qθ(Y)−log⁡P(Y)+1)∇θlog⁡Qθ(Y)].\nabla_\theta\operatorname{KL}(Q_\theta\|P) =\mathbb E_{Y\sim Q_\theta}\left[\left(\log Q_\theta(Y)-\log P(Y)+1\right)\nabla_\theta\log Q_\theta(Y)\right].

The +1+1 term has zero expectation because EQ[∇log⁡Q]=0\mathbb E_Q[\nabla\log Q]=0; it can be omitted or replaced by an action-independent baseline. One sample has variance, and clipping or a truncated sampling distribution changes the estimator unless the appropriate correction is made. Treating sampled tokens as constants and differentiating only conditional KL on those prefixes is a different practical objective; it is not generally equivalent to differentiating the full reverse sequence KL. The lab distinguishes both.

Sparse logits and remaining mass

Saving a full vector per token is expensive. Sparse-logit distillation keeps the kk largest values and their indices, together with information needed to calculate their mass. Keeping only top-k values without the full normalizer or remaining mass cannot reconstruct total omitted probability. One way to store the target is to save log⁡ZT=log⁡∑ievi/T\log Z_T=\log\sum_i e^{v_i/T}, the kk logits and their indices; changing TT requires sufficient information for the new normalizer.

Define SS as the retained indices, prest=1−∑i∈Spip_\mathrm{rest}=1-\sum_{i\in S}p_i and qrest=1−∑i∈Sqiq_\mathrm{rest}=1-\sum_{i\in S}q_i. Aggregated KL treats the entire tail as one class:

∑i∈Spilog⁡piqi+prestlog⁡prestqrest.\sum_{i\in S}p_i\log\frac{p_i}{q_i}+p_\mathrm{rest}\log\frac{p_\mathrm{rest}}{q_\mathrm{rest}}.

By the data-processing inequality it cannot exceed full KL; the difference is information about proportions within the tail. If k=Vk=V and the whole vocabulary is retained, it equals full KL. If remaining mass is zero, its contribution is defined by continuity. In computation use stable log-softmax and prevent cancellation when calculating the tail; truncating or rounding probabilities can alter very small values.

InteractiveHow many logits to save

Real prefix: “The capital of France is”. Probability mass retained by k.

141664256102410

k is shown at discrete positions. These are three BF16 prefixes on RTX 3060: they do not predict other data distributions. GB are decimal, with no metadata except the normalizer.

0
2
k16
Retained mass71.1 %
Full KL0.7965
Aggregated KL0.5515
KL gap0.2451
Billion tokens100 GB
Mass and aggregated KL measured for three prefixes with SmolLM2-1.7B as teacher and SmolLM2-135M as student.

The models use the same vocabulary of 49,152 tokens and revisions effd688a12921b4cc83e3312b6feb579f70f9c71 and 93efa2f097d58c2a74874c7e644dbc9b0cee75a2. Measurements use three explicit prefixes and BF16 on an RTX 3060, with softmax evaluated in FP32. The KL curve uses those FP32 values and does not include rounding when saving logits in FP16; displayed cost corresponds to the proposed storage format. For example, for the first prefix k=64k=64 retains approximately 81.9% of mass, but aggregated KL remains below full KL. The figure calculates storage for one billion positions as 6k+46k+4 decimal GB: each pair costs two bytes for the logit and four for the index, plus four normalizer bytes. It excludes headers, compression, writes and other outputs. A small vocabulary may permit narrower indices if the format declares them.

If tokenizers differ, the teacher’s index ii does not necessarily correspond to the same student event; comparing vectors position by position no longer makes sense. Valid alignment to common units, a string-level approximation or full outputs as sequence data is needed. Even with the same vocabulary, check normalization, special tokens and prefix boundaries, not only vector size.

What an aggregated tail loses

The tail event preserves exact total missing mass but hides how it is distributed. Two students can assign the same mass to the tail with very different internal distributions and obtain the same aggregated KL. Renormalizing only top-k to sum to one removes the signal of how much weight remains outside and changes the task; retaining the tail avoids that error without magically reconstructing each omitted token. The gap drawn in the figure is a difference between two KLs on the three measured prefixes, not a universal bound for another corpus.

When serializing data, the temperature convention must accompany the normalizer. If top-k logits are stored at reduced precision and the normalizer at another precision, probabilities can sum slightly above one; a robust implementation should detect or correct that error and explain introduced bias. Indices must retain vocabulary and tokenizer revision. Saving a seed or text sample does not replace metadata needed to interpret each index.

Cost, data and pruned models

The distillation scaling law empirically models quality by teacher and student size and compute. Busbridge and colleagues distinguish an available teacher from one that must be trained for a single student. The marginal cost of using an existing teacher does not involve the same investment decision as creating one from scratch; amortizing it across many students changes the comparison. Comparing parameter counts is insufficient: teacher tokens, student optimization, storage and data generation must be counted alongside inference.

Gemma 2 describes using distillation in pretraining for some sizes. Do not extrapolate a curve fitted for one family, corpus and budget to every architecture. For a specific decision, measure a baseline with the same student budget, validate on relevant tasks and record teacher cost. A student that improves perplexity may fail at arithmetic or instructions; improvement on one sample does not establish general quality.

Combining pruning and distillation starts from a large model, removes structure and uses subsequent training to recover capacity. Minitron studies pruning and distillation recovery in one family; Sheared LLaMA uses structured pruning and dynamic data selection to continue pretraining. These are different recipes. A distilled student can also act as a draft in speculative decoding: usefulness depends on its cost and acceptance measured with the target, not only size or mean fidelity.

Before training on a service’s outputs or distributing a derived checkpoint, review conditions applicable to the model and data. Prompt provenance, licenses and deduplication against test are part of the protocol. A closed teacher may offer only text, not logits; in that case token-level KL cannot be claimed without access to suitable probabilities.

NumPy lab: sequence distributions

The teacher generates three-token binary sequences and depends on the previous two. The student uses only the previous token and therefore cannot represent the full dependence. All eight sequences are enumerated, KL gradients checked and four objectives trained: forward KL, greedy teacher sequences conditioned on both initial tokens, reverse KL via score function, and conditional KL on student prefixes. Enumeration removes sampling noise in this example; it does not reproduce LLM cost or variance. Modes are compared with both KLs, not only one.

[ ]Binary sequences and gradientsBrowser
import itertools, numpy as np
seq=np.array(list(itertools.product([0,1],repeat=3)),dtype=int)
# p(x0)=1/2; p(x1=x0)=.9; p(x2=x1)=.95 when x0=x1, otherwise .2
P=[]
for a,b,c in seq:
 p1=.9 if b==a else .1
 stay=.95 if a==b else .2
 P.append(.5*p1*(stay if c==b else 1-stay))
P=np.array(P);assert np.isclose(P.sum(),1)
def sigmoid(z):return 1/(1+np.exp(-z))
def model(theta):
 prob=sigmoid(theta);q=[];scores=[]
 for a,b,c in seq:
  q1=prob[a] if b else 1-prob[a];q2=prob[b] if c else 1-prob[b]
  q.append(.5*q1*q2);g=np.zeros(2);g[a]+=b-prob[a];g[b]+=c-prob[b];scores.append(g)
 return np.array(q),np.array(scores)
def loss_and_grad(theta,mode):
 q,score=model(theta)
 if mode=='forward':return np.sum(P*np.log(P/q)), -np.sum(P[:,None]*score,axis=0)
 if mode=='reverse':return np.sum(q*np.log(q/P)),np.sum((q*(np.log(q/P)+1))[:,None]*score,axis=0)
 raise ValueError(mode)
# Gradient score-function exact compared to central differences.
for mode in ('forward','reverse'):
 theta=np.array([-.3,.8]);val,grad=loss_and_grad(theta,mode);eps=1e-5
 numeric=np.array([(loss_and_grad(theta+np.eye(2)[j]*eps,mode)[0]-loss_and_grad(theta-np.eye(2)[j]*eps,mode)[0])/(2*eps) for j in range(2)])
 assert np.allclose(numeric,grad,atol=1e-8);print(mode,'error finito',np.max(np.abs(numeric-grad)))
# off-policy KL, reverse KL with score function, and deterministic teacher sequences.
def train(mode,steps=600,lr=.4):
 theta=np.array([-.2,.2])
 for _ in range(steps):
  if mode in ('forward','reverse'):
   _,g=loss_and_grad(theta,mode)
  elif mode=='sequence':
   q,score=model(theta);idx=np.array([0,7]);g=-score[idx].mean(axis=0)
  else:
   # Distribución de prefijos del alumno: su probabilidad se trata fija en este paso.
   probs=sigmoid(theta);g=np.zeros(2)
   for a,b,c in seq:
    mass0=.5; target1=.9 if a==1 else .1
    g[a]+=mass0*(probs[a]-target1)/4  # dos c y dos b duplican cada prefijo cuatro veces
    mass1=.5*(probs[a] if b else 1-probs[a]); target2=(.95 if a==b else .2) if b else (1-(.95 if a==b else .2))
    g[b]+=mass1*(probs[b]-target2)/2 # dos c duplican cada prefijo
  theta-=lr*g
 q,_=model(theta);return theta,np.sum(P*np.log(P/q)),np.sum(q*np.log(q/P))
for m in ('forward','sequence','reverse','onpolicy'):
 theta,fp,rp=train(m);print(m,'probabilidad de emitir 1 por token previo',np.round(sigmoid(theta),4),'KL P||Q',round(fp,5),'KL Q||P',round(rp,5))

Local lab: SmolLM2 teacher and student

The cell uses SmolLM2-1.7B and SmolLM2-135M with pinned revisions and checks vocabulary equality. By default it downloads missing checkpoints; HF_LOCAL_ONLY=1 requires local copies. The teacher and student backbone are frozen. The output head is untied from the input and only that head is trained in FP32; the rest of the student and the teacher use BF16 if the GPU supports it. This is not equivalent to tuning all parameters or reproducing MiniLLM.

The 16 training sums and eight test sums are distinct pairs. The hard control learns the exact training answer; sequence, the teacher’s greedy continuation; topk, aggregated forward KL with 32 logits and a tail on correct-answer prefixes; onpolicy, a score-function estimator for reverse KL on sequences sampled from the student. Sampling uses full softmax, not top-k. Incremental cached generation and BF16 probability recomputation can differ due to rounding; bitwise equality is neither measured nor assumed here. The horizon is limited to three tokens and the on-policy objective uses no baseline, so it can have high variance. The code clips gradient norm to stabilize the example: the clipped step is no longer an unbiased estimator of the original gradient. All variants start from the same initial head and receive the same number of updates, but query the teacher differently and do not cost the same.

The first integer is extracted from the greedy continuation and compared with the true sum; each answer is shown along with the number correct. In an RTX 3060 run, the teacher got 6 of 8, the initial student 0 of 8 and each of the four variants 0 of 8 after 32 updates. This negative result does not show distillation is useless: it shows this budget, head and data did not solve the test. Score-function loss is a gradient surrogate and can be negative; it is not a direct KL estimate. There are few examples, one initialization, two default epochs and one task; results do not compare general capabilities or demonstrate convergence. KD_EPOCHS can increase duration. In that run PyTorch reported a peak of 4.117 GiB allocated and 4.137 GiB reserved by its allocator, with teacher and student on an RTX 3060. This does not necessarily include the whole driver context or other processes; longer sequences, another optimizer or training more layers change the peak. It is compatible with planning for 8 GB in this trial, but does not guarantee it fits every environment; it was not tested on the RTX 4060 mentioned in the design.

[ ]Four objectives for a small studentLocal GPU
import os, re, time, random
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from transformers import AutoTokenizer, AutoModelForCausalLM

TEACHER='HuggingFaceTB/SmolLM2-1.7B'; STUDENT='HuggingFaceTB/SmolLM2-135M'
TREV='effd688a12921b4cc83e3312b6feb579f70f9c71'; SREV='93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
DEVICE='cuda' if torch.cuda.is_available() else 'cpu'
if DEVICE=='cuda': torch.cuda.reset_peak_memory_stats()
DTYPE=torch.bfloat16 if DEVICE=='cuda' and torch.cuda.is_bf16_supported() else torch.float32
LOCAL=os.environ.get('HF_LOCAL_ONLY','0')=='1'
EPOCHS=int(os.environ.get('KD_EPOCHS','2')); K=32; STEPS=3
random.seed(28);np.random.seed(28);torch.manual_seed(28);torch.set_num_threads(4)
tok=AutoTokenizer.from_pretrained(TEACHER,revision=TREV,local_files_only=LOCAL)
stok=AutoTokenizer.from_pretrained(STUDENT,revision=SREV,local_files_only=LOCAL)
assert tok.get_vocab()==stok.get_vocab() and tok.eos_token_id==stok.eos_token_id
teacher=AutoModelForCausalLM.from_pretrained(TEACHER,revision=TREV,local_files_only=LOCAL,dtype=DTYPE).to(DEVICE).eval()
student=AutoModelForCausalLM.from_pretrained(STUDENT,revision=SREV,local_files_only=LOCAL,dtype=DTYPE).to(DEVICE).eval()
for p in teacher.parameters():p.requires_grad_(False)
for p in student.parameters():p.requires_grad_(False)
# Desligar salida y entrada permite entrenar solo la cabeza y mantener congelada la columna.
class FloatHead(nn.Linear):
 def forward(self,x):return F.linear(x.float(),self.weight)
old=student.get_output_embeddings();head=FloatHead(old.in_features,old.out_features,bias=False,device=DEVICE,dtype=torch.float32)
with torch.no_grad():head.weight.copy_(old.weight)
student.set_output_embeddings(head)
initial=head.weight.detach().clone()
print('device',DEVICE,'dtype',DTYPE,'trainable',sum(p.numel() for p in student.parameters() if p.requires_grad),flush=True)
# Particiones de sumas exactas; la respuesta se comprueba computacionalmente, no con el maestro.
train_pairs=[(2,3),(4,7),(8,6),(9,2),(5,8),(3,9),(6,6),(7,4),(11,3),(12,4),(5,11),(10,8),(6,9),(13,2),(8,11),(14,4)]
test_pairs=[(3,4),(8,9),(12,5),(7,11),(13,5),(6,13),(10,7),(9,9)]
assert not set(train_pairs)&set(test_pairs)
def prompt(a,b):return f'{a} + {b} ='
def enc(text):return tok(text,return_tensors='pt',add_special_tokens=False).input_ids.to(DEVICE)
def generate(model,ctx,n=STEPS,sample=False):
 with torch.no_grad():
  opts={'top_k':0,'top_p':1.0,'temperature':1.0} if sample else {}
  return model.generate(ctx,max_new_tokens=n,do_sample=sample,pad_token_id=tok.eos_token_id,eos_token_id=None,use_cache=True,**opts)
def answer(model,a,b):
 x=enc(prompt(a,b));y=generate(model,x);txt=tok.decode(y[0,x.shape[1]:],skip_special_tokens=True)
 match=re.match(r'^\s*(\d+)',txt)
 return (int(match.group(1)) if match else None),txt

def evaluate(model,pairs):
 rows=[]
 for a,b in pairs:
  got,txt=answer(model,a,b);rows.append({'a':a,'b':b,'expected':a+b,'got':got,'text':txt})
 return sum(r['got']==r['expected'] for r in rows),rows

# Los objetivos se calculan con el maestro en los prefijos de la respuesta correcta.
records=[]
for a,b in train_pairs:
 ctx=enc(prompt(a,b));gold=enc(' '+str(a+b)+'\n');seq=torch.cat([ctx,gold],dim=1)
 with torch.no_grad():
  teacher_seq=generate(teacher,ctx)
  logits=teacher(seq[:,:-1],use_cache=False).logits[0,ctx.shape[1]-1:].float()
  vals,idx=torch.topk(logits,K,dim=-1);logz=torch.logsumexp(logits,dim=-1)
 records.append((ctx,gold,teacher_seq[:,ctx.shape[1]:],idx.detach(),vals.detach(),logz.detach()))

def coarse_kl(student_logits,idx,teacher_vals,teacher_logz):
 # Conserva la masa fuera de top-k como una clase extra.
 lp=teacher_vals-teacher_logz[:,None];p=lp.exp()
 lq=F.log_softmax(student_logits.float(),dim=-1);lqt=lq.gather(-1,idx);q=lqt.exp()
 pr=(1-p.sum(dim=-1)).clamp_min(1e-12);qr=(1-q.sum(dim=-1)).clamp_min(1e-12)
 return ((p*(lp-lqt)).sum(-1)+pr*(pr.log()-qr.log())).mean()

def teacher_force(ctx,continuation):
 seq=torch.cat([ctx,continuation],dim=1)
 return student(seq[:,:-1],use_cache=False).logits[0,ctx.shape[1]-1:]

def onpolicy_loss(ctx):
 # Muestra exactamente de q, sin top-k, y usa REINFORCE para KL(Q||P) de secuencias.
 seq=generate(student,ctx,n=STEPS,sample=True)
 # generate puede detenerse en EOS; se conserva la secuencia observada.
 if seq.shape[1]==ctx.shape[1]:raise RuntimeError('no se generó ningún token')
 continuation=seq[:,ctx.shape[1]:];student_logits=teacher_force(ctx,continuation).float()
 with torch.no_grad():teacher_logits=teacher(seq[:,:-1],use_cache=False).logits[0,ctx.shape[1]-1:].float()
 chosen=continuation[0,:,None]
 logq=F.log_softmax(student_logits,dim=-1).gather(-1,chosen).sum()
 logp=F.log_softmax(teacher_logits,dim=-1).gather(-1,chosen).sum()
 reward=(logq-logp).detach()
 return reward*logq, float(reward)

print('maestro aciertos, detalle',evaluate(teacher,test_pairs),flush=True)
print('alumno inicial aciertos, detalle',evaluate(student,test_pairs),flush=True)
for mode in ('hard','sequence','topk','onpolicy'):
 with torch.no_grad():head.weight.copy_(initial)
 torch.manual_seed(28)
 opt=torch.optim.AdamW([head.weight],lr=3e-5)
 losses=[];start=time.perf_counter()
 for epoch in range(EPOCHS):
  for ctx,gold,teacher_generated,idx,vals,logz in records:
   if mode=='hard':
    z=teacher_force(ctx,gold);loss=F.cross_entropy(z.float(),gold[0])
   elif mode=='sequence':
    z=teacher_force(ctx,teacher_generated);loss=F.cross_entropy(z.float(),teacher_generated[0])
   elif mode=='topk':
    z=teacher_force(ctx,gold);loss=coarse_kl(z,idx,vals,logz)
   else:
    loss,_=onpolicy_loss(ctx)
   opt.zero_grad();loss.backward();torch.nn.utils.clip_grad_norm_([head.weight],1.0);opt.step()
   losses.append(float(loss.detach()))
 count,rows=evaluate(student,test_pairs)
 print(mode,'epochs',EPOCHS,'steps',len(losses),'loss_last',losses[-1],
       'accuracy',count,'/',len(test_pairs),'seconds',round(time.perf_counter()-start,1),'detail',rows,flush=True)
if DEVICE=='cuda':
 print('pico memoria asignada y reservada GiB',round(torch.cuda.max_memory_allocated()/2**30,3),round(torch.cuda.max_memory_reserved()/2**30,3),flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Numeric
How many decimal GB do 32 FP16 logits and 32-bit indices occupy for one billion positions, without normalizer or metadata?
Numeric
For p = (0.5, 0.5, 0) and q = (0.9, 0.05, 0.05), calculate KL(p || q) in nats.
Quiz
With the previous distributions, what is KL(q || p)?
Proof
Prove: Prove the KL chain rule for two autoregressive models.
0
Both use the same support and fixed horizon.

Step 1 of 2. What happens to the logarithm of the ratio of sequence probabilities?

Quiz
For a speculative-decoding draft, which comparison is most informative?
Code
Implement topk_kd_loss(student_logits, teacher_topk_vals, teacher_topk_idx, T). teacher_topk_vals is the pair (unscaled top-k logits, full log Z_T per row); aggregate remaining mass and return mean KL multiplied by T².
import numpy as np
def topk_kd_loss(student_logits, teacher_topk_vals, teacher_topk_idx, T):
  pass
Shift+Enter to run
Key idea
In autoregressive models, the prefix-generating distribution, optimized divergence and information lost when compressing teacher targets all matter.