On-Policy & Off-Policy Distillation for LLMs: Mode-Seeking vs Mode-Covering, Exploration with RND, and Reinforcement with Verifiers

These notes unify supervised/off-policy distillation, on-policy reverse-KL distillation, “mode-seeking vs mode-covering” control, intrinsic-motivation exploration (RND), and RL with verifiers (process vs outcome rewards) into one practical toolkit for post-training.


Table of Contents


Setup & Notation

Let a state be the prefix and an action the next token .

  • Teacher policy .
  • Student policy .
  • State occupancy under policy (undiscounted for LMs; discount (\gamma) optional).
  • Entropy .

We use expectations both per-state (condition on ) and population (over ).


Off-Policy Distillation (Forward KL / SFT)

Data: teacher trajectories ((s,a)\sim d^{p},,a\sim p(\cdot\mid s)).
Objective:

  • Global optimum (unconstrained model): () for in teacher support.
  • Mode-covering: missing teacher support is heavily penalized (if where (), forward KL ()).
  • Exposure bias: you learn in teacher states (s\sim d^{p}), not the student’s (d^{q_\theta}).

On-Policy Distillation (Reverse KL)

Data: student samples ; teacher scores them.
Objective:

  • Mode-seeking: concentrates where teacher is strong; gentler about covering all teacher modes.
  • Exposure fixed: you train on states you actually visit, reducing compounding error.

Per-state optimum:
Fix (s). Maximizing yields .


Mode-Seeking vs Mode-Covering: How to Add & Control Both

4.1 Temper the teacher (per-state (\alpha))

Introduce weight (\alpha>0) on entropy:

Closed-form solution (per state):

  • : exact match (q=p) (reverse KL).
  • : sharper than teacher (more mode-seeking).
  • : flatter than teacher (more mode-covering within teacher support).

Support: if (hard mask), then . To explore beyond hard masks, soften the teacher (no zeros) or add exploration bonuses (below).

4.2 Mix forward & reverse KL (λ-blend)

Blend both divergences and (optionally) both state occupancies:

  • : stronger mode-covering (off-policy SFT).
  • : stronger mode-seeking on student states (on-policy).

In practice this is implemented as a data mixture (teacher vs student states) and/or a loss mixture (SFT loss + reverse-KL loss).

4.3 Mix state occupancies (DAGGER / scheduled sampling)

Iteratively sample states from a mixture policy , with annealed down. Label actions by the teacher and train the student. This reduces exposure bias while preserving coverage.

4.4 α-divergences (Amari/Tsallis family)

Generalize beyond KLs (optional):

For (\alpha\to 1) you recover forward KL; for (\alpha\to 0) (in the appropriate limiting sense) reverse KL. Tuning (\alpha) trades covering vs seeking. In practice, KL blends or temperature control already provide clean knobs.


Implementation in an LLM Stack

5.1 Off-Policy (Teacher-Dataset / Logit Distillation)

Data: from a curated teacher dataset (may include CoT/process tokens).
Losses:

  • Token NLL: (-\log q_\theta(a\mid s)).
  • Logit distill: KL on full next-token distributions at each step:
    Compute tips:
  • Use teacher logits with temperature (T) (soft targets).
  • Optionally top- the teacher distribution for efficiency; renormalize.
  • Mixed precision; gradient checkpointing on long contexts.

5.2 On-Policy (Student-Sampling + Teacher Scoring)

Loop per batch:

  1. Sample prompts; roll out student (greedy or nucleus/temperature).
  2. For each step (t), query teacher log-prob of the student token: .
  3. Compute reverse-KL loss via its equivalent:
  • \underbrace{\mathbb{E}{a\sim q}\log q(a\mid s)}{\text{(neg.) entropy}}.
    With entropy weight $\alpha$: $L = -\mathbb{E}_{a\sim q}\log p\ -\ \alpha \cdot H(q)$.
  1. Backprop through student only (teacher is frozen).

Notes

  • One Monte-Carlo token per state is unbiased. Multiple samples reduce variance.
  • Optionally stop gradients through the sampling path (REINFORCE view), or simply treat (\log q) and (\log p) on the sampled token as standard losses (common and stable in practice).

5.3 Combined Objective & Practical Schedules

A robust recipe that adds both behaviors and exploration:

  • : off-policy SFT strength (mode-covering).
  • Reverse-KL term: on policy (mode-seeking).
  • : intrinsic exploration bonus (e.g., RND).
  • : PPO-style trust region to avoid drift from a reference (e.g., SFT) model.

Schedules: start with , (flatter than teacher), anneal and , decay (\beta) as novelty saturates.


Exploration Beyond Entropy: Intrinsic Motivation & Bandit Tricks

6.1 Random Network Distillation (RND) for LLMs

Goal: give higher reward to novel prefixes (states) or (state, action) pairs.

Standard RND (state novelty):

  • Fixed random target (MLP), frozen.
  • Predictor (MLP), trainable.
  • State embedding (z(s)): derive from your LLM, e.g. the final hidden of last token, mean-pool over a window, or a projection head on prefix representations (detach from student to avoid trivial solutions).
  • Intrinsic reward:
  • Train (\phi) online to minimize this MSE on visited states—novel states have large error (\Rightarrow) large reward; as you visit, error shrinks.

(State, Action) novelty: concatenate action embedding (e(a)) (LM’s token embedding) to the state: , and run RND on (u). This rewards trying new tokens in context.

Normalization & stability:

  • Maintain running mean/std of ; use whitened bonus .
  • Clip and cap its contribution ((\beta)).
  • Use a slow predictor optimizer (e.g., small LR) so novelty decays gradually.
  • Compute RND on downsampled steps or chunked prefixes to reduce cost.

Where to add it:
Use inside your reverse-KL (or RL) update. With the reverse-KL view, this is equivalent to adding an exploration-shaping reward to the teacher score.

6.2 Disagreement / UCB / Thompson Sampling

Disagreement bonus: train a small ensemble of student heads that share a backbone. Define

High variance uncertain explore.

UCB sampling: when choosing actions during rollouts, bias the sampling logits:

where is an uncertainty proxy (e.g., ensemble variance) and (N) are visit counts.

Thompson sampling: at rollout start, sample one head (or enable dropout) and act greedily/stochastically under that sampled model.

All three can be layered on top of the same training objective (J) (reverse-KL + bonuses).


Reinforcement with Verifiers: Process vs Outcome Rewards

Let

  • Process (step) verifier : e.g., PRM that judges each reasoning step or a programmatic checker (unit tests, invariants).
  • Outcome verifier : e.g., exact answer match, multi-turn task success, pass@k.

Unified on-policy objective (token-level RL view):

  • Set coefficients to zero to recover special cases:
    • Pure reverse-KL: .
    • RL with verifiers only (no teacher): drop (\log p), keep (\lambda,\kappa>0).
    • RLHF-style regularization: use (\eta>0) with (q_{\text{ref}}) the SFT policy.

Outcome rewards can be credit-assigned via advantage estimation (e.g., GAE) or shaped back to steps (e.g., via process verifiers).


All Objectives at a Glance

  • Off-policy SFT / forward KL
  • On-policy reverse KL (α-weighted)
  • Teacher-score only (degenerate)
  • Reverse+Forward blend (λ)
  • Reverse KL + intrinsic (RND)
  • RL with verifiers (process + outcome)

Pseudo-Code Templates

The following pseudo-code sketches show how to wire losses in a PyTorch-style training loop. They omit boilerplate (optimizers, fp16, data loaders, padding, etc.) to focus on what to compute.

A. Off-Policy SFT (Forward KL / Logit Distillation)

# batch: teacher prefixes S, teacher next-token distributions P_logits (or samples A)
student_logits = student(S)[:, -1, :]          # next-token logits
if have_teacher_full_logits:
    loss = kl_divergence_with_logits(
        teacher_logits=P_logits, student_logits=student_logits, reduction="batchmean"
    )
else:
    A = teacher_sampled_tokens                  # ints
    loss = cross_entropy(student_logits, A)     # token NLL
 
loss.backward(); opt.step()

B. On-Policy Reverse KL with Temperature α and Entropy

# 1) Rollout with student
with torch.no_grad():
    A, S_traj, logq_tokens = sample_tokens_and_logprobs(student, prompts, sampling_cfg)
 
# 2) Teacher scores student tokens
with torch.no_grad():
    logp_tokens = teacher_logprobs(teacher, S_traj, A)
 
# 3) Reverse-KL equivalent loss:  -E_q[log p] - α * H(q)
#    Approximate E_q[...] per step with the sampled token.
#    H(q) term: compute from student logits at each step.
student_step_logits = cached_student_logits  # from rollout
entropy = categorical_entropy(student_step_logits)  # per step
 
loss = -(logp_tokens).mean() - alpha * (entropy).mean()
 
loss.backward(); opt.step()

Note: Many implementations simply compute (-\log p(a_t|s_t)) on sampled tokens plus an explicit entropy bonus from the student logits; this is equivalent (up to MC noise) to minimizing reverse KL.

C. Reverse+Forward KL Blend (λ) and Reference KL (η)

# On-policy part (reverse KL surrogate)
loss_on = -(logp_tokens).mean() - alpha * entropy.mean()
 
# Off-policy SFT part (forward KL)
teacher_logits_off = teacher_logits_on_teacher_data
student_logits_off = student(teacher_prefixes)[:, -1, :]
loss_off = kl_divergence_with_logits(teacher_logits_off, student_logits_off, reduction="batchmean")
 
# PPO-style reference KL to prevent drift
ref_logits_on = ref_model(S_traj)[:, -1, :]
loss_ref = kl_divergence_with_logits(student_step_logits, ref_logits_on, reduction="batchmean")
 
loss = (1-lambda_) * loss_on + lambda_ * loss_off + eta * loss_ref
loss.backward(); opt.step()

D. Random Network Distillation (state or state+action)

# Build embeddings for RND
z = state_embedder(S_traj).detach()                  # [B, d]
if use_state_action:
    a_embed = token_embed(A)                         # [B, d_tok]
    u = torch.cat([z, a_embed], dim=-1)              # [B, d + d_tok]
else:
    u = z
 
with torch.no_grad():
    target = rnd_target(u)                           # frozen random net
 
pred = rnd_predictor(u)                              # trainable
rnd_error = ((pred - target)**2).mean(dim=-1)        # per step
rnd_bonus = whiten_and_clip(rnd_error)               # normalize
 
# Add to reverse-KL objective
loss = (-(logp_tokens) - alpha * entropy - beta * rnd_bonus).mean()
 
# Update student AND predictor (separate opts/lrs recommended)
(loss).backward(); opt_student.step()
(rnd_error.mean()).backward(); opt_rnd.step()

E. RL with Verifiers (process + outcome)

# After rollout, compute:
proc_scores = process_verifier_score(S_traj, A, stepwise=True)      # per step
out_score   = outcome_verifier_score(S_traj, A, final_only=True)     # scalar per traj
 
# Broadcast outcome to steps with advantages or uniform credit:
adv_steps = advantage_estimator(proc_scores, out_score)
 
loss = (-(logp_tokens) - alpha * entropy
        - lambda_ * proc_scores
       ).mean() - kappa * out_score.mean()
 
loss.backward(); opt.step()

Practical Tips & Debugging

  • Teacher temperature: use to calibrate softness; combine with (\alpha) for fine control.
  • α schedule: start (flatter, safer exploration), anneal to , optionally <1 near the end for decisiveness.
  • λ blend: begin with , decay as on-policy stabilizes.
  • Length & stop-token handling: normalize by tokens, not sequences; include EOS/stop tokens consistently in both teacher scoring and student entropy.
  • Support mismatches: if teacher masks tokens, the student cannot discover them via reverse-KL alone; soften teacher or add intrinsic bonuses that allow off-support trials (then label with a verifier or a softer teacher).
  • Reference KL (η): prevents drift and gaming of verifiers; set small but non-zero (e.g., ).
  • RND stability: normalize bonus, slow predictor LR, EMA of target (optional), and clip combined reward.
  • Compute: cache teacher logits for student tokens only (log-prob lookup), not full vocab, to save FLOPs; or compute full logits periodically.
  • Evaluation: report both teacher-match metrics (KL/NLL on teacher states) and on-policy metrics (accuracy under your sampler), plus diversity (self-BLEU, distinct-n) to detect mode collapse.

TL;DR Recipe

  1. Warm-up SFT (forward KL on teacher data).
  2. Switch to on-policy reverse-KL with , add RND bonus on prefix embeddings, and a small forward-KL mix .
  3. Anneal and ; keep a reference-KL as a guardrail.
  4. For hard tasks, add process verifier (PRM) and an outcome verifier; shape credit with advantages.
  5. Monitor diversity and on-policy accuracy; tune .

This framework gives you a single, coherent way to:

  • recover off-policy SFT and on-policy reverse-KL,
  • dial mode-covering vs mode-seeking,
  • add principled exploration (RND, UCB/TS), and
  • fold in verifiers (process + outcome) for robust, on-policy post-training.