Verl On-Policy Distillation Guide

This guide provides a comprehensive technical deep dive into implementing On-Policy Distillation using the Verl framework. It bridges theoretical concepts from the Thinking Machines “On-Policy Distillation” blog with specific, verified implementation details from the Verl codebase.

1. Mathematical Deep Dive

The Core Objective

On-policy distillation differs from standard Supervised Fine-Tuning (SFT) by changing the direction of the Kullback-Leibler (KL) divergence minimization. We treat the Teacher model () as the “environment” or reward signal, and the Student model () as the agent.

1. Forward KL: The SFT approach (MLE)

Standard SFT minimizes the Forward KL divergence: .

  • Method: Maximum Likelihood Estimation (MLE).
  • Behavior: Mean-seeking (or zero-avoiding). The Student attempts to cover the entire support of the Teacher’s distribution.
  • Distillation Context: Behavior Cloning. The Student learns to copy the Teacher’s output for a given prompt.
  • Limitation: Can lead to “hallucinations” if the Student’s capacity is lower than the Teacher’s, as it tries to match low-probability tails.

2. Reverse KL: The On-Policy approach

On-policy distillation minimizes the Reverse KL divergence: .

  • Method: Reinforcement Learning (RL). The expectation is over the Student’s own distribution , requiring gradient estimators (like REINFORCE).
  • Behavior: Mode-seeking (or zero-forcing). The Student penalizes itself for generating samples that the Teacher assigns low probability to. It effectively focuses on the “peaks” (high-quality outputs) of the Teacher and ignores the long tails.

3. Connection to PPO & Mirror Descent (Advanced)

We solve the Reverse KL objective using Proximal Policy Optimization (PPO). PPO can be understood as a practical approximation of Mirror Descent (MD) or Trust Region methods.

1. Terminology: Forward vs. Reverse KL
To be precise about the optimization direction, we follow this convention:

  • Forward KL: Minimizing with respect to . This is mean-seeking (Equation: ).
  • Reverse KL: Minimizing with respect to . This is mode-seeking (Equation: ).

2. The Mirror Descent Update (Reverse KL Trust Region)
Classical Entropic Mirror Descent updates the policy by minimizing a linearized loss plus a proximity term to the old policy :

Here, the proximity term places the variable in the first argument. By our definition, this is a Reverse KL trust region.

  • Closed Form Solution:

    Substituting the variational gradient :

    This geometric interpolation is characteristic of Reverse KL (Zero-Forcing) dynamics. If , the new policy remains 0.

3. Contrast with Natural Gradient / TRPO (Forward KL Trust Region)
Natural Gradient Descent and TRPO are typically motivated by a second-order expansion of the Forward KL trust region: .

  • Minimizing ensures the new policy covers the likelihood of the old policy (mean-seeking).
  • This leads to the Fisher Information Matrix (FIM) metric.

Verl’s Implementation:
Verl’s PPO setup effectively combines:

  1. Objective: Reverse KL Distillation ().
  2. Optimizer: PPO, which approximates a trust region. While often related to TRPO (Forward KL), the clipped objective and the resulting behavior closely mimic the conservative updates of Mirror Descent.

Verl implements this by incorporating the KL penalty directly into the reward. The “reward” becomes the log-ratio of the Teacher to the Student.


2. Implementation Deep Dive (Exact Code)

IMPORTANT: The on-policy distillation in Verl uses a dedicated GKD (Generalized Knowledge Distillation) recipe located in recipe/gkd/, NOT the standard PPO trainer. The architecture is fundamentally different from standard RLHF.

2.0 Architecture Overview

The GKD recipe implements a distributed architecture with three separate components:

┌─────────────────────────────────────────────────────────────────────────────┐
│                         ON-POLICY DISTILLATION ARCHITECTURE                 │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │                    EXTERNAL TEACHER SERVER                          │   │
│  │  ┌───────────────────────────────────────────────────────────────┐ │   │
│  │  │  vLLM Server (ZMQ REQ/REP on port 15555)                      │ │   │
│  │  │  - Serves top-k log-probabilities per token                   │ │   │
│  │  │  - Runs on separate GPU pool / K8s pod                        │ │   │
│  │  └───────────────────────────────────────────────────────────────┘ │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                    ▲                                        │
│                                    │ ZMQ queries                            │
│  ┌─────────────────────────────────┴───────────────────────────────────┐   │
│  │                        DRIVER PROCESS                                │   │
│  │  OnPolicyDistillTrainer (ray_trainer.py)                            │   │
│  │  ├─ TeacherClient: queries teacher for top-k logprobs               │   │
│  │  ├─ Scheduler: one_step_off / two_step_off                          │   │
│  │  └─ Orchestrates: Rollout → Teacher → Actor Update                  │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                    │                              │                         │
│         ┌─────────┘                              └─────────┐                │
│         ▼                                                  ▼                │
│  ┌────────────────────────────┐    ┌─────────────────────────────────────┐ │
│  │   ROLLOUT WORKER GROUP     │    │      ACTOR WORKER GROUP             │ │
│  │  Engine: vLLM or SGLang    │    │  Engine: Megatron ONLY              │ │
│  │  Purpose: Generate samples │    │  Purpose: KL loss + weight update   │ │
│  │  Resource: rollout pool    │    │  Resource: trainer pool             │ │
│  └────────────────────────────┘    └─────────────────────────────────────┘ │
│              │                              ▲                               │
│              └──────── NCCL Sync ──────────┘                               │
└─────────────────────────────────────────────────────────────────────────────┘

Key Differences from Standard PPO/RLHF:

AspectStandard PPO (main_ppo)On-Policy Distillation (gkd/main_gkd)
Teacher/RefColocated worker (same process)External server (ZMQ + vLLM)
SignalScalar reward per sequenceToken-level top-k logprobs
LossPolicy gradient + KL penaltySparse KL divergence on top-k
Training EngineFSDP or MegatronMegatron ONLY
Rollout EnginevLLM/SGLang/HFvLLM or SGLang

2.1 The Core Loss: Sparse KL on Top-k Tokens

The distillation loss is computed in megatron_workers.py using an external megatron_distill_losses module.

File: recipe/gkd/megatron/megatron_workers.py

# Lines ~317-329 in megatron_workers.py
def logits_processor(logits, teacher_topk_logps, teacher_topk_indices, calc_kl_mask, kl_losses):
    assert logits.shape[:2] == calc_kl_mask.shape[:2]
    assert logits.shape[:2] == teacher_topk_indices.shape[:2]
    assert logits.shape[:2] == teacher_topk_logps.shape[:2]
 
    masked_logits = logits[calc_kl_mask]
    masked_teacher_topk_logps = teacher_topk_logps[calc_kl_mask]
    masked_teacher_topk_indices = teacher_topk_indices[calc_kl_mask]
 
    # Compute sparse KL divergence on teacher's top-k support
    kl_losses[calc_kl_mask] = self.distill_loss_op(
        masked_logits, masked_teacher_topk_logps, masked_teacher_topk_indices
    )
    return {"kl_losses": kl_losses, "calc_kl_mask": calc_kl_mask}

The distill_loss_op is built at actor initialization:

# Line ~190 in megatron_workers.py
self.distill_loss_op = build_vocab_parallel_distill_loss(self.config.get("distill_loss", None)).cuda()

2.2 The Teacher Server (External Service)

Unlike standard RLHF where the reference model is colocated, the Teacher in GKD is an external vLLM server that provides top-k log-probabilities.

Configuration (on_policy_distill_trainer.yaml):

actor_rollout_ref:
  teacher:
    server_ip: localhost
    server_port: 15555
    n_server_workers: 1

TeacherClient Usage (ray_trainer.py):

# Lines ~170-172 in ray_trainer.py
self.teacher_client = TeacherClient(
    self.teacher_config.server_ip, self.teacher_config.server_port, n_server_workers=self.n_server_workers
)

2.3 Actor Worker (Megatron-based Training)

The actor is implemented as a Megatron-specific worker that performs the forward-backward pass with the KL loss.

File: recipe/gkd/megatron/megatron_workers.py

# Lines ~446-458 in megatron_workers.py
class MegatronOnPolicyDistillActorWorker(ActorRolloutRefWorker):
    """
    Actor-only worker: owns the trainable Megatron model and optimizer, performs update_actor.
    """
    def __init__(self, config: DictConfig, role: str):
        super().__init__(config, role)
        assert self._is_actor and not self._is_rollout, "Actor worker must be actor-only."

Update Actor (update_actor method):

# Lines ~544-570 in megatron_workers.py
@register(dispatch_mode=make_nd_compute_dataproto_dispatch_fn(mesh_name="actor"))
def update_actor(self, data: DataProto):
    assert self._is_actor and not self._is_rollout
    with Timer(name="update_policy", logger=None) as timer:
        metrics = self.actor.update_policy(data=data)
    # ... metrics collection ...
    return output

3. Feasibility & Integration Support

Backend Support

CRITICAL: The GKD recipe only supports Megatron for actor training. FSDP is NOT supported.

ComponentSupport StatusDetails
Actor TrainingMegatron ONLYmain_gkd.py:148-161 explicitly raises NotImplementedError for non-Megatron strategies.
FSDP/FSDP2NOT SupportedStandard PPO supports FSDP, but the GKD distillation recipe does not.
Rollout EnginevLLM or SGLangmegatron_workers.py:765-794 supports both engines for sequence generation.
Teacher ServervLLM (ZMQ)External vLLM server accessed via ZeroMQ REQ/REP pattern.

Code Evidence (main_gkd.py:148-161):

# Megatron-only workers, split into rollout and actor
if config.actor_rollout_ref.actor.strategy == "megatron":
    from .megatron_workers import (
        MegatronOnPolicyDistillActorWorker,
        MegatronOnPolicyDistillRolloutWorker,
    )
    rollout_cls = MegatronOnPolicyDistillRolloutWorker
    actor_cls = MegatronOnPolicyDistillActorWorker
else:
    raise NotImplementedError  # <-- FSDP is NOT supported!

SGLang Support Evidence (megatron_workers.py:765-794):

if rollout_name == "vllm":
    inference_model = self.rollout.inference_engine.llm_engine.model_executor...
elif rollout_name == "sglang":
    from sglang.srt.weight_sync.utils import update_weights as sgl_update_weights
    # SGLang weight sync implementation...
else:
    raise NotImplementedError(f"Unknown rollout name: {rollout_name}")

Architecture: Three Separate GPU Pools

The GKD recipe uses three separate resource allocations:

PoolConfigurationEnginePurpose
Actor Pooltrainer.nnodes × trainer.n_gpus_per_nodeMegatronStudent weight updates
Rollout Poolrollout.nnodes × rollout.n_gpus_per_nodevLLM/SGLangStudent sequence generation
Teacher PoolExternal (K8s pod)vLLM ServerTop-k logprobs serving

Key Point: The Teacher is NOT a colocated Ref worker like in standard PPO. It runs as an external service that must be launched separately before training.


4. Implementation & Execution

This section provides a detailed blueprint for executing on-policy distillation, directly mirroring the system design described in the Async On-Policy Distillation Recipe.

IMPORTANT

On-policy distillation in Verl uses a dedicated GKD (Generative Knowledge Distillation) recipe, NOT the generic verl.trainer.main_ppo. This recipe includes a Teacher Server architecture for efficient, distributed top-k log-probability retrieval.


4.1 System Architecture Overview

The GKD recipe has four key components:

ComponentLocationEngineFunction
Actor (Student Training)recipe.gkd.main_gkdMegatronUpdates student weights using KL loss.
Rollout (Student Generation)actor_rollout_ref.rolloutvLLM / SGLangGenerates new samples ().
Teacher Serverrecipe/gkd/teacher/vLLMServes top-k log-probabilities for generated samples.
Async Schedulerray_trainer.pyRayOverlaps generation, teacher queries, and training.

Key Difference from Standard PPO:
The Teacher is not a collocated Ref worker. Instead, it is an external service that the training loop queries via ZeroMQ, allowing for massive Teacher models to run on dedicated hardware.


4.2 Step 1: Launch the Teacher Server

Before starting training, the Teacher model must be running as a service.

Location: recipe/gkd/teacher/

Configuration:
Edit start_server.sh to set:

  • --tp-size: Tensor Parallelism for the Teacher model.
  • --n-logprobs: The top-k value for the teacher’s output.
  • --ckpt-path: Path to the Teacher model checkpoint.

Launch Command:

cd recipe/gkd/teacher
# Edit start_server.sh with your paths and TP size
bash start_server.sh

Verification:

telnet localhost 15555
# You should see a connection. Type 'quit' to exit.
TIP

For multi-node teacher servers, use start_server.sh on the main node and join_server.sh on slave nodes. Ensure $PROXY_IP and $PROXY_BACKEND_PORT are correctly configured.


4.3 Step 2: Configure the Training Job

The training job uses a Hydra-based configuration. The key sections are:

Config SectionPurposeKey Parameters
actor_rollout_ref.modelStudent model pathpath
actor_rollout_ref.teacherTeacher server connectionserver_ip, server_port, n_server_workers
trainerTraining controltotal_epochs, scheduler, nnodes, n_gpus_per_node
rolloutRollout resource allocationnnodes, n_gpus_per_node

Resource Allocation:

  • Actor Pool: trainer.nnodes * trainer.n_gpus_per_node GPUs.
  • Rollout Pool: rollout.nnodes * rollout.n_gpus_per_node GPUs.
  • Teacher Pool: Managed externally via the Teacher Server.

4.4 Step 3: Launch Training

Entry Point: python3 -m recipe.gkd.megatron.main_gkd

Note: The entry point is in the megatron subdirectory, reflecting that only Megatron is supported.

Minimal Launch Command:

python3 -m recipe.gkd.megatron.main_gkd \
  --config-path=config \
  --config-name=on_policy_distill_trainer \
  \
  # Student Model
  actor_rollout_ref.model.path=/path/to/STUDENT_MODEL \
  \
  # Data
  data.train_files=/path/to/train.parquet \
  \
  # Training & Rollout Resources (e.g., 4 GPUs for training, 2 for rollout)
  trainer.total_epochs=2 \
  trainer.n_gpus_per_node=4 \
  rollout.n_gpus_per_node=2 \
  \
  # Teacher Server Connection
  actor_rollout_ref.teacher.server_ip=127.0.0.1 \
  actor_rollout_ref.teacher.server_port=15555 \
  \
  # Async Scheduling
  trainer.scheduler=one_step_off

4.5 Async Scheduling Options

To improve throughput, the GKD recipe supports overlapping the generation, teacher-querying, and training phases.

Schedulertrainer.schedulerDescriptionUse Case
One-Step-Offone_step_offOverlaps rollout with actor update.General use (default).
Two-Step-Offtwo_step_offDeeper overlap for slow Teachers.Large Teacher models.

Note: There is no synchronous (null) scheduler in the current implementation. Both schedulers are async.

One-Step-Off Scheduler Diagram:

┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                          ONE-STEP-OFF SCHEDULER TIMELINE                                 │
├─────────────────────────────────────────────────────────────────────────────────────────┤
│                                                                                          │
│  Timeline ──────────────────────────────────────────────────────────────────────────►   │
│                                                                                          │
│  ┌─────────────────────────────────────────────────────────────────────────────────┐   │
│  │ STEP 0 (Initialization)                                                          │   │
│  │                                                                                   │   │
│  │   sync_weights ─► async_rollout(batch_0) ─► wait_gen ─► async_teacher(batch_0)  │   │
│  │   ═══════════      ════════════════════      ════════    ════════════════════    │   │
│  └─────────────────────────────────────────────────────────────────────────────────┘   │
│                                                                                          │
│  ┌─────────────────────────────────────────────────────────────────────────────────┐   │
│  │ STEP 1 (No sync - actor not yet updated)                                         │   │
│  │                                                                                   │   │
│  │   async_rollout(batch_1) ─► wait_teacher ─► TRAIN(batch_0) ─► wait_gen          │   │
│  │   ═════════════════════      ════════════    ═══════════════    ════════         │   │
│  │                                                    │                              │   │
│  │                                                    └─► async_teacher(batch_1)    │   │
│  └─────────────────────────────────────────────────────────────────────────────────┘   │
│                                                                                          │
│  ┌─────────────────────────────────────────────────────────────────────────────────┐   │
│  │ STEP N (Steady state)                                                            │   │
│  │                                                                                   │   │
│  │   sync_weights ─► async_rollout(batch_N) ─► wait_teacher ─► TRAIN(batch_{N-1})  │   │
│  │   ═══════════      ═══════════════════       ════════════    ═════════════════   │   │
│  │                                                                    │              │   │
│  │                                                                    └─► wait_gen  │   │
│  │                                                                        ════════  │   │
│  │                                                           async_teacher(batch_N) │   │
│  └─────────────────────────────────────────────────────────────────────────────────┘   │
│                                                                                          │
│  Legend:                                                                                 │
│    ═══  = Blocking operation                                                            │
│    ───► = Triggers next operation                                                       │
│    TRAIN = Actor weight update (forward-backward + optimizer step)                      │
│                                                                                          │
└─────────────────────────────────────────────────────────────────────────────────────────┘

Two-Step-Off Scheduler Diagram:

┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                          TWO-STEP-OFF SCHEDULER TIMELINE                                 │
├─────────────────────────────────────────────────────────────────────────────────────────┤
│                                                                                          │
│  The two-step-off scheduler maintains TWO batches in flight:                            │
│                                                                                          │
│  ┌─────────────────────────────────────────────────────────────────────────────────┐   │
│  │ Pipeline View (Steady State):                                                    │   │
│  │                                                                                   │   │
│  │   Batch N-2:  [TRAIN]                                                            │   │
│  │   Batch N-1:  [teacher_query] ─────────────►                                     │   │
│  │   Batch N:    [rollout] ───────────────────────────────►                         │   │
│  │   Batch N+1:  [sync_weights] ─► [rollout_start]                                  │   │
│  │                                                                                   │   │
│  │   Time ──────────────────────────────────────────────────────────────────────►   │   │
│  └─────────────────────────────────────────────────────────────────────────────────┘   │
│                                                                                          │
│  Benefits:                                                                               │
│    - Better overlap when teacher queries are slow                                       │
│    - Reduced idle time between phases                                                   │
│    - Higher GPU utilization                                                             │
│                                                                                          │
│  Trade-offs:                                                                             │
│    - Higher memory usage (2 batches in flight)                                          │
│    - Slightly more "off-policy" (training on older samples)                             │
│                                                                                          │
└─────────────────────────────────────────────────────────────────────────────────────────┘

Key Timing Metrics (from ray_trainer.py):

  • sync_rollout_weights: Time to sync actor weights to rollout workers via NCCL
  • wait_prev_gen: Time waiting for previous rollout to complete
  • wait_prev_teacher / wait_prev_prev_teacher: Time waiting for teacher knowledge

4.6 Key Metrics & Monitoring

Successful runs emit metrics to WandB or TensorBoard:

MetricMeaningAction if High
timing/wait_prev_teacherTime waiting for Teacher top-k.Scale n_server_workers, allocate more Teacher GPUs, or use two_step_off.
timing/wait_prev_genTime waiting for Student rollout.Allocate more rollout GPUs.
timing/sync_rollout_weightsTime syncing Actor weights to Rollout.Check NCCL config, try actor_rollout_ref.rollout.update_weights_bucket_megabytes.
actor/kl_lossThe token-level KL divergence.Monitors distillation objective. Should decrease.

4.7 Checklist Before Running

  • Teacher server is running and reachable (telnet <ip> <port>).
  • actor_rollout_ref.model.path points to a valid Megatron/HF checkpoint.
  • data.train_files points to a compatible parquet dataset.
  • NCCL environment variables are set (check config/runtime_env.yaml in the recipe).
  • Resource allocation (trainer.nnodes, rollout.nnodes) matches your cluster.

4.8 Comparison: GKD Recipe vs. Standard PPO

Featureverl.trainer.main_ppo (RLHF)recipe.gkd.megatron.main_gkd (Distillation)
Teacher/Reference ModelColocated Ref worker (FSDP/Megatron).External Teacher Server (ZMQ + vLLM).
Reward SignalScalar reward from RM per sequence.Token-level top-k logprobs per position.
ObjectiveMaximize reward, constrain policy drift.Minimize sparse on top-k.
Training EngineFSDP or Megatron.Megatron ONLY.
Rollout EnginevLLM, SGLang, or HF.vLLM or SGLang.
ScalabilityTeacher must fit with actor.Teacher scales independently on separate nodes/pods.
Entry Pointverl.trainer.main_pporecipe.gkd.megatron.main_gkd
K8s DeploymentSingle job (colocated).Requires separate Teacher pod before training.

5. Answering Your Questions

Q: Do I need to create a K8s pod that works as an inference server manually?

Yes. The on-policy distillation recipe requires you to manually launch the Teacher server as a separate service before starting training. This is fundamentally different from standard PPO where the reference model is colocated.

Deployment options:

  1. Same cluster, separate pod: Launch teacher server on dedicated GPU nodes
  2. Same node, different port: For smaller teachers, can colocate with training
  3. External service: Teacher can run anywhere accessible via network

Q: Can I just provide the path of the model and use the PPO trainer?

No, not for on-policy distillation. The standard PPO trainer (verl.trainer.main_ppo) uses a colocated reference model for KL penalty, but that’s a different objective than distillation:

ApproachUse CaseTeacher Handling
Standard PPO + KL penaltyPrevent policy drift from SFT modelColocated Ref worker
On-Policy Distillation (GKD)Transfer knowledge from larger teacherExternal Teacher Server

If you just want to prevent drift from a reference model (not distill from a larger teacher), you can use verl.trainer.main_ppo with a colocated Ref worker. But for true distillation with a separate (potentially larger) teacher model, you need the GKD recipe with an external teacher server.


6. Quick Start Summary

# Step 1: Launch Teacher Server (separate terminal/pod)
cd recipe/gkd/teacher
bash start_server.sh  # Configure: --ckpt-path, --tp-size, --n-logprobs
 
# Step 2: Verify Teacher is Running
telnet localhost 15555
 
# Step 3: Launch Training
python3 -m recipe.gkd.megatron.main_gkd \
  --config-path=config \
  --config-name=on_policy_distill_trainer \
  actor_rollout_ref.model.path=/path/to/student \
  actor_rollout_ref.teacher.server_ip=<teacher_ip> \
  actor_rollout_ref.teacher.server_port=15555 \
  data.train_files=/path/to/data.parquet \
  trainer.n_gpus_per_node=4 \
  rollout.n_gpus_per_node=2 \
  trainer.scheduler=one_step_off