On-policy distillation is a reinforcement learning technique in which a student policy learns from a teacher policy while training on trajectories generated by the student’s current behavior. Unlike ordinary supervised imitation, the student continuously visits its own state distribution, making the method useful when distribution shift, exploration, safety, or policy improvement matters.
For AI researchers and product teams, on-policy distillation sits between imitation learning and reinforcement learning. It can compress a large policy into a smaller model, transfer capabilities from an expensive planner, accelerate early training, or combine demonstrations with task rewards. The central engineering challenge is balancing teacher guidance with the student’s own objectives so that the student does not merely copy a policy that is too costly, brittle, or poorly matched to deployment constraints.
What Is On-Policy Distillation?
In policy distillation, a teacher policy provides action preferences, logits, value estimates, trajectories, or explanations to a student policy. “On-policy” means that the training examples are collected from states encountered by the student, typically by rolling out the current student policy in the environment.
Let the teacher and student policies be:
- Teacher: \(\pi_T(a\mid s)\)
- Student: \(\pi_\theta(a\mid s)\)
- Student-generated state distribution: \(d^{\pi_\theta}(s)\)
A basic distillation objective minimizes the expected divergence between teacher and student action distributions:
\[
\mathcal{L}_{\text{distill}}(\theta)=\mathbb{E}_{s\sim d^{\pi_\theta}}\left[D_{KL}(\pi_T(\cdot\mid s)\parallel\pi_\theta(\cdot\mid s))\right]
\]
The distinction from offline imitation is important. If all examples come from the teacher, the student may never learn how to recover from its own mistakes. On-policy data exposes the teacher to states created by the student, including states where correction is essential.
Why Use On-Policy Distillation?
On-policy distillation is valuable when the teacher is capable but impractical to deploy. Common motivations include:
- Model compression: Transfer behavior from a large transformer, ensemble, search procedure, or simulator-based planner into a smaller model.
- Inference-cost reduction: Replace repeated planning or tool calls with a fast feed-forward policy.
- Capability transfer: Teach a student skills learned through reinforcement learning, demonstrations, or privileged information.
- Safety shaping: Use a conservative teacher to discourage unsafe actions while retaining a task reward.
- Curriculum acceleration: Provide action-level guidance during early exploration, then gradually reduce dependence on the teacher.
- Domain adaptation: Train the student in deployment-like environments rather than only on teacher-generated trajectories.
For Indian AI startups, this can be especially relevant when GPU budgets, latency targets, and unreliable connectivity constrain deployment. A distilled policy may run on an edge device, a low-cost cloud instance, or an industrial controller while the teacher remains available only during training or periodic updates.
Core Objective Functions
KL-divergence distillation
For discrete actions, the most common loss is cross-entropy or forward KL divergence:
\[
\mathcal{L}_{KL}=-\mathbb{E}_{s\sim d^{\pi_\theta}}\sum_a \pi_T(a\mid s)\log \pi_\theta(a\mid s)
\]
Temperature \(\tau\) can soften teacher distributions:
\[
\pi_T^\tau(a\mid s)=\text{softmax}(z_T(s)/\tau)
\]
A higher temperature reveals relative preferences among non-greedy actions. The distillation loss is often multiplied by \(\tau^2\) to preserve gradient scale.
Reverse KL and mode-seeking behavior
Reverse KL, \(D_{KL}(\pi_\theta\parallel\pi_T)\), penalizes the student for assigning probability to actions the teacher considers unlikely. It can produce mode-seeking behavior and may be useful when unsafe or invalid actions must be strongly suppressed. However, it can be less forgiving when the student explores outside the teacher’s support.
Advantage-weighted distillation
If the teacher supplies action values or advantages, demonstrations can be weighted by their estimated quality:
\[
\mathcal{L}_{AW}=-\mathbb{E}[w(s,a)\log \pi_\theta(a\mid s)]
\]
where \(w(s,a)\) may be proportional to \(\exp(A_T(s,a)/\beta)\), clipped advantages, or a normalized ranking score. This prevents mediocre teacher actions from receiving the same training weight as high-value actions.
Reward-regularized policy learning
Pure distillation can cap the student at teacher performance. A combined objective allows the student to improve beyond the teacher:
\[
\mathcal{L}=\mathcal{L}_{RL}+\lambda_{D}\mathcal{L}_{distill}+\lambda_{E}\mathcal{L}_{entropy}
\]
Here, \(\mathcal{L}_{RL}\) may be PPO, actor-critic, SAC, or another policy-gradient loss; \(\lambda_D\) controls teacher influence; and entropy regularization supports exploration.
A Practical Training Workflow
1. Define the deployment constraint
Before selecting an algorithm, specify the student’s limits:
- Parameter count and memory footprint
- Maximum latency and throughput
- CPU, GPU, NPU, or edge accelerator availability
- Action frequency and control-loop stability
- Network and power constraints
- Required safety and auditability
Distillation is successful only if the student meets these constraints without unacceptable reward degradation.
2. Choose the teacher interface
The teacher may expose:
- Action probabilities or logits
- A selected action only
- Value functions or advantages
- Search trees or planner scores
- Demonstration trajectories
- Uncertainty estimates or safety masks
Logits and uncertainty are generally more informative than hard labels, but they may reveal more about a proprietary model and increase storage or serving costs.
3. Roll out the student
At each iteration, collect trajectories using the current student. Store observations, actions, rewards, termination flags, teacher outputs, and optional value estimates. For partially observable tasks, store recurrent hidden states or observation histories consistently for both teacher and student.
A minimal loop is:
initialize student policy πθ
repeat:
collect trajectories using πθ
query teacher on student states
compute RL loss and distillation loss
update θ with combined objective
evaluate reward, divergence, safety, and latency4. Schedule teacher strength
A fixed distillation coefficient is rarely optimal. Common schedules include:
- High teacher weight during warm-up, followed by decay
- Confidence-based weighting when the teacher is uncertain
- State-dependent weighting in safety-critical regions
- Teacher guidance only when the student’s value estimate is low
- Alternating policy-improvement and distillation phases
A useful starting point is to monitor the ratio of distillation gradient norm to RL gradient norm. If teacher gradients dominate throughout training, the student may be unable to discover improvements.
5. Evaluate on student-generated states
Measure performance not only on teacher trajectories but also on states induced by the deployed student. Report mean return, tail performance, constraint violations, recovery from perturbations, and out-of-distribution behavior. For Indian deployments, test realistic network outages, sensor noise, regional language inputs, monsoon-related visual changes, and low-connectivity operating conditions where applicable.
On-Policy Distillation Versus Related Methods
Behavioral cloning
Behavioral cloning trains on expert state-action pairs, usually from an offline dataset. It is simple and inexpensive but vulnerable to covariate shift. On-policy distillation repeatedly refreshes the dataset using the student’s state distribution, allowing targeted correction.
DAgger
DAgger aggregates student states and requests expert labels, then trains on the growing dataset. On-policy distillation resembles DAgger when a teacher labels every student state, but it often uses soft distributions, online policy updates, reward signals, and teacher uncertainty rather than only hard expert actions.
Offline policy distillation
Offline distillation uses a fixed replay buffer. It can be cheaper and easier to reproduce, but it may not cover failure states created by the current student. Hybrid systems can begin offline and transition to on-policy data collection.
Knowledge distillation in supervised learning
Classical distillation transfers logits between classifiers. On-policy distillation adds a sequential decision problem: actions change future states, so errors compound and the training distribution evolves with the policy.
Stability Challenges and Solutions
Teacher-student disagreement
Large divergence can create unstable updates, especially when the student’s action space or observation encoder differs from the teacher’s. Use action masking, calibrated temperatures, gradient clipping, and a warm-start phase.
Teacher errors and bias
A teacher is not automatically optimal. It may be overfit to a simulator, fail under sensor corruption, or encode unsafe shortcuts. Combine teacher loss with environment reward, uncertainty weighting, adversarial perturbation tests, and independent safety constraints.
Distribution shift
Even on-policy data can become stale after major policy updates. Use short rollout-to-update cycles, replay a limited recent buffer, and track state-coverage metrics. For long-horizon tasks, prioritize recovery states rather than only frequently visited states.
Catastrophic forgetting
When teacher guidance decays, the student may lose important behaviors. Retain a small anchor set of high-value states, periodically distill critical skills, or use a constraint that preserves performance on safety and regression suites.
Partial observability
A teacher may use privileged state unavailable to the student. Direct imitation is then impossible. Distill action distributions conditioned on observations, use recurrent students, or train an intermediate representation that maps available sensors to teacher-relevant information.
Implementation Details That Matter
Use consistent preprocessing, action scaling, termination semantics, and reward normalization. A surprising number of distillation failures come from mismatched observation normalization or different treatment of truncated versus terminated episodes.
Recommended engineering practices include:
- Calibrate teacher probabilities before using them as targets.
- Mask invalid actions identically for teacher and student.
- Log KL divergence by state type, not only as a global average.
- Track student entropy and action concentration.
- Separate training-time teacher queries from deployment-time inference.
- Version teacher checkpoints, environment versions, and normalization statistics.
- Use deterministic evaluation seeds alongside stochastic robustness tests.
- Quantize or prune only after verifying closed-loop behavior.
For continuous control, distill distribution parameters rather than only sampled actions. Gaussian policies may use mean and covariance matching, while squashed policies require care around tanh transformations. For language-agent policies, distillation can target token distributions, tool-selection policies, trajectories, or structured action plans; sequence-level evaluation remains necessary because token-level agreement does not guarantee task-level success.
Metrics and Experiment Design
A credible evaluation should compare at least four systems:
1. Student trained without a teacher
2. Student trained with offline teacher data
3. Student trained with on-policy distillation
4. Teacher or upper-bound reference system
Track:
- Task return and success rate
- Sample efficiency
- KL divergence and calibration
- Recovery success after induced errors
- Safety violations and constraint costs
- Latency, memory, energy, and infrastructure cost
- Robustness across regions, devices, and environmental conditions
Ablate temperature, distillation coefficient, teacher schedule, rollout horizon, and reward-loss weight. Statistical confidence intervals over seeds are important, particularly when improvements are small.
Applications in India
On-policy distillation has practical potential across Indian sectors:
- Agriculture: Compress a crop-monitoring or irrigation policy for low-connectivity edge devices.
- Manufacturing: Transfer expensive visual inspection or robotic planning into low-latency controllers.
- Logistics: Distill route and dispatch decisions while respecting traffic, delivery, and fleet constraints.
- Healthcare operations: Learn scheduling or triage assistance under strict human-oversight requirements; do not treat the student as an autonomous clinical decision-maker without appropriate validation.
- Public infrastructure: Deploy efficient policies for energy management, water systems, and transport operations.
- Multilingual AI agents: Distill a large tool-using agent into a smaller model while preserving structured workflows and regional-language interaction.
Deployment should account for India’s heterogeneous hardware, intermittent connectivity, privacy obligations, and language diversity. Keep sensitive training data governed, document model limitations, and design human escalation paths for high-impact decisions.
When Should You Use On-Policy Distillation?
Choose it when the teacher is strong but expensive, the student will operate in states different from the teacher’s dataset, and online interaction is available during training. Avoid relying on it alone when environment feedback is unavailable, the teacher is poorly calibrated, or the student cannot observe the information required to reproduce teacher behavior.
A sensible decision rule is:
- Start with supervised or offline imitation if interaction is expensive.
- Add on-policy correction when student-induced failures become significant.
- Add RL objectives when surpassing the teacher matters.
- Retain explicit safety constraints when errors have material consequences.
FAQ
Is on-policy distillation the same as imitation learning?
No. It is a form of imitation or policy transfer, but its defining feature is that training states are generated by the current student. It may also combine teacher targets with reinforcement learning rewards and uncertainty signals.
Can a student outperform its teacher?
Yes, if the objective includes environment rewards, exploration, or policy improvement. Purely minimizing teacher divergence generally encourages matching the teacher rather than exceeding it.
Does on-policy distillation require online production deployment?
No. “On-policy” refers to data generated by the current training policy. Rollouts can occur in a simulator, digital twin, sandbox, or controlled test environment.
How do I distill a teacher with privileged information?
Train the student using observations it will have at deployment, use recurrent memory where appropriate, and evaluate under realistic partial observability. Do not assume that privileged-state actions can be perfectly reproduced from incomplete inputs.
What is the main risk?
The main risk is transferring teacher errors or creating a student that imitates well on familiar states but fails under its own distribution shift. Reward-based evaluation, recovery testing, uncertainty handling, and safety constraints are essential.
Apply for AI Grants India
Building an efficient AI system with on-policy distillation or another deep-tech approach? Indian AI founders can apply through AI Grants India for support, visibility, and relevant grant opportunities.