Skip to content

RL

Medical OPD

Code source and cost

  • The complete implementation comes from datawhalechina/agentic-rl-lab/experiments/medical-opd. This page was checked against commit ec51068; the source links and commands below refer to that revision.
  • Following the full reproduction flow (Medical SFT Teacher, SAR-OPD, IDT-OPD, and MedQA-zh / C-Eval evaluations) is estimated at under ¥200 on PyTRIO (the author's broader exploratory runs totaled roughly ¥500). These are reference estimates, not fixed pricing.
  • For a minimal introduction to on-policy distillation and sync/async loops, read the OPD example first. Because this project spans data prep, SFT, multi-stage/dual-teacher OPD, and evaluation scripts, this page covers the core designs and workflow while the source repository remains the runnable reference.

Introduction ​

Running Chinese Medical SFT directly on Qwen/Qwen3.5-4B raises MedQA-zh accuracy from 72.17% to 79.00%, but degrades general capability on non-medical C-Eval from 81.67% down to 69.33% (-12.34 percentage points).

Building on On-Policy Distillation (OPD) from GKD and MiniLLM, this case studies a practical post-training question:

Can a frozen Medical Teacher teach domain reasoning while the original Base Model acts as a general-capability anchor, yielding a Student stronger than Base on both medical and general benchmarks?

Two multi-teacher / multi-stage schemes are implemented and compared on PyTRIO:

  1. SAR-OPD (Staged Anchor-Restoration OPD): train Medical OPD first, then restore the training_state and run Base-anchor OPD with the original Base Model to recover general capability.
  2. IDT-OPD (Interleaved Dual-Teacher OPD): alternate between the Medical Teacher and Base Teacher step by step inside a single training loop on one LoRA Student.

Note: SAR-OPD and IDT-OPD are descriptive names used in this example to distinguish the two training workflows, not standard algorithm names from existing papers.

Results overview ​

All stages are evaluated on two fixed held-out benchmarks:

CapabilityBenchmarkSamplesOutput budgetMetric
MedicalMedQA-zh 4 options6001,024 tokensAccuracy
GeneralC-Eval non-med3008,192 tokensAccuracy

Key checkpoints:

Model / CheckpointMedQA-zh (600)C-Eval non-med (300)
4B Base72.17% (433/600)81.67% (245/300)
Medical SFT epoch 3 (Medical Teacher)79.00% (474/600)69.33% (208/300)
Medical OPD step 30080.00% (480/600)73.00% (219/300)
SAR-OPD step 30084.33% (506/600)84.67% (254/300)
IDT-OPD step 10079.17% (475/600)81.67% (245/300)
IDT-OPD step 20076.50% (459/600)86.00% (258/300)
  • SAR-OPD step 300 achieves the strongest combined result: +12.17 percentage points over Base on MedQA-zh and +3.00 percentage points over Base on C-Eval non-med.
  • IDT-OPD traces a capability trade-off curve: step 100 favors medical (79.17% / 81.67%) while step 200 favors general reasoning (76.50% / 86.00%), and training further to step 600 does not improve either metric—making early stopping and checkpoint selection critical.

How OPD works ​

In OPD, trajectories are sampled on-policy by the current Student. The Teacher never generates a separate answer; it scores the exact prompt + student completion token sequence to compute per-token reverse KL advantages:

Single-step OPD loop: on-policy Student sampling, Teacher logprob scoring, and policy update

For Student πθ\pi_\theta, Teacher πT\pi_T, and sampled token yty_t:

rtKL=log⁡πθ(yt∣x,y<t)−log⁡πT(yt∣x,y<t)r_t^{\mathrm{KL}} = \log \pi_\theta(y_t \mid x, y_{\lt t}) - \log \pi_T(y_t \mid x, y_{\lt t})

At=−βrtKLA_t = -\beta r_t^{\mathrm{KL}}

In code, this takes two lines:

python
reverse_kl = np.asarray(student_logprobs) - np.asarray(teacher_logprobs)
advantages = -args.kl_penalty_coef * reverse_kl

When the Student favors a token more strongly than the Teacher (reverse_kl > 0), the advantage is negative and its probability is pushed down; when the Teacher prefers it more, the advantage is positive. Unlike GRPO, group_size here only generates multiple trajectories per prompt without computing within-group relative rewards—every completion receives direct token-level supervision from the Teacher.

Datasets and isolation boundaries ​

00-download-dataset.py downloads and splits three datasets with a fixed seed:

DatasetRoleFields used in training
FreedomIntelligence/medical-o1-reasoning-SFT (Chinese)Medical SFT, Medical OPD prompt poolSFT uses question + complex_cot + response; OPD uses question only
bigbio/med_qa (MedQA-zh 4 options)Medical evaluationHeld-out evaluation only
ceval/ceval-exam (8 non-medical subsets)Base-anchor OPD, general evaluationOPD uses questions and options only; ignores answer_idx

C-Eval excludes basic_medicine, clinical_medicine, physician, veterinary_medicine, and middle/high-school biology, retaining 8 non-medical subsets (computer_network, college_programming, advanced_mathematics, discrete_mathematics, college_physics, logic, chinese_language_and_literature, college_economics). It splits 80% / 20% into an OPD train pool and held-out test pool, then draws 300 fixed evaluation questions from the test pool.

Both OPD workflows are strictly prompt-only distillation: held-out test questions never enter training, and neither OPD script reads reference answers or chains of thought.

Project layout ​

text
experiments/medical-opd/
├── .env.example                        # Template for PYTRIO_API_KEY used by eval scripts
├── 00-download-dataset.py              # Download and split Medical SFT, MedQA-zh, and C-Eval
├── 01-eval-medical.py                  # Concurrent MedQA-zh 600-question evaluation
├── 01-eval-ceval.py                    # Concurrent C-Eval non-med 300-question evaluation
├── 02-medical-sft.py                   # Stage 1: train Medical SFT Teacher
├── 03-medical-opd-async.py             # Stage 2: asynchronous Medical OPD (recommended)
├── 03-medical-opd-sync.py              # Stage 2: synchronous Medical OPD (for step-by-step reading)
├── 04-ceval-opd-async.py               # Stage 3: SAR-OPD Base-anchor restoration
├── 05-interleaved-multi-teacher-opd.py # Method 2: IDT-OPD interleaved dual-teacher training
├── analysis.py                         # Aggregate evaluation results and generate plots
└── start.md                            # Quick-start command checklist

See the full source at experiments/medical-opd.

Stage 1: Training the Medical SFT Teacher ​

Both methods share the same frozen Medical Teacher. 02-medical-sft.py formats complex_cot and response into <think>...</think> blocks, masks prompt tokens with weight 0.0 (weighting assistant tokens and EOS at 1.0), and trains Qwen/Qwen3.5-4B for 3 epochs:

CheckpointMedQA-zh (600)C-Eval non-med (300)
4B Base72.17% (433/600)81.67% (245/300)
Medical SFT epoch 177.67% (466/600)71.67% (215/300)
Medical SFT epoch 279.17% (475/600)69.33% (208/300)
Medical SFT epoch 379.00% (474/600)69.33% (208/300)

Both downstream workflows freeze epoch 3 sampler_weights as the Medical Teacher. Keep PyTRIO's two checkpoint path types distinct:

Path typeUsage
trio://.../sampler_weights/...Inference, evaluation, or serving as a frozen Teacher
trio://.../training_states/...Resuming a TrainingClient via create_training_client_from_state_async()

Method 1: SAR-OPD (Staged Anchor-Restoration OPD) ​

SAR-OPD separates domain acquisition and general-capability restoration into three sequential stages:

text
Stage 1: Qwen3.5-4B --Medical SFT--> Medical Teacher
Stage 2: Fresh 4B Student --Medical Teacher OPD--> Medical OPD Student
Stage 3: Medical OPD Student --4B Base Teacher OPD--> SAR-OPD Student

SAR-OPD three-stage training pipeline

Stage 2: Medical OPD ​

03-medical-opd-async.py initializes a fresh Qwen/Qwen3.5-4B LoRA Student and points teacher_client to the frozen Medical SFT epoch 3 sampler_weights:

python
training_client = await service_client.create_lora_training_client_async(
    base_model=args.base_model,
    rank=args.lora_rank,
    seed=args.seed,
)
teacher_client = await service_client.create_sampling_client_async(
    base_model=args.teacher_base_model,
    model_path=args.teacher_model_path,
)

Each step refreshes the Student sampler, samples group_size completions per prompt, passes the exact prompt_ids + completion_ids to the Teacher for token logprobs, and updates the Student with PyTRIO's ppo loss:

python
all_ids = prompt_ids + completion_ids
all_logprobs = await teacher_client.compute_logprobs_async(
    trio.ModelInput.from_ints(all_ids)
)
teacher_logprobs = all_logprobs[len(prompt_ids):]

reverse_kl = np.asarray(student_logprobs) - np.asarray(teacher_logprobs)
advantages = -args.kl_penalty_coef * reverse_kl

fwd_bwd_future = await training_client.forward_backward_async(datums, loss_fn="ppo")
optim_future = await training_client.optim_step_async(adam)

The reference run uses 300 steps, batch_size=4, group_size=4, max_tokens=2048, and lr=4e-5. MedQA-zh reaches 80.00%, while C-Eval sits at 73.00% (better than SFT's 69.33%, still below Base).

Stage 3: Base-anchor C-Eval OPD ​

04-ceval-opd-async.py restores the full Stage 2 training_state via create_training_client_from_state_async() and sets the original Qwen/Qwen3.5-4B base model as the frozen Teacher. Training runs for 300 steps on C-Eval non-med prompts with a conservative lr=5e-6 (saving every 50 steps) to restore general behavior without washing out medical gains.

SAR-OPD evaluation trajectory ​

SAR-OPD MedQA-zh and C-Eval restoration trajectory

Stage / CheckpointMedQA-zh (600)C-Eval non-med (300)
4B Base72.17% (433/600)81.67% (245/300)
Medical SFT epoch 3 (Medical Teacher)79.00% (474/600)69.33% (208/300)
Medical OPD step 300 (Stage 3 step 0)80.00% (480/600)73.00% (219/300)
Base-anchor OPD step 5084.17% (505/600)76.67% (230/300)
Base-anchor OPD step 10082.50% (495/600)79.33% (238/300)
Base-anchor OPD step 15083.00% (498/600)80.33% (241/300)
Base-anchor OPD step 20082.17% (493/600)83.67% (251/300)
Base-anchor OPD step 25083.33% (500/600)82.67% (248/300)
Base-anchor OPD step 30084.33% (506/600)84.67% (254/300)

C-Eval recovers steadily from 73.00% to 84.67%, and MedQA-zh rises further from 80.00% to 84.33% rather than regressing—showing that general restoration and medical retention were not zero-sum in this run.

Method 2: IDT-OPD (Interleaved Dual-Teacher OPD) ​

To unify training into a single loop without state-handover stages, 05-interleaved-multi-teacher-opd.py trains one fresh Qwen/Qwen3.5-4B Student with shared Adam state while alternating between the two Teachers on a fixed schedule:

IDT-OPD interleaved dual-teacher training architecture

python
def build_task_schedule(args):
    return (
        ("medical",) * args.medical_steps_per_cycle
        + ("ceval",) * args.ceval_steps_per_cycle
    )

task = schedule[step % len(schedule)]
if task == "medical":
    rows, teacher_client, system_message = medical_rows, medical_teacher, args.medical_system_message
else:
    rows, teacher_client, system_message = ceval_rows, base_teacher, args.ceval_system_message

Each task tracks its own task_steps[task] cursor so alternating global steps never skip half of either dataset. The reference run uses a 1:1 schedule over 600 global steps (M300 + C300), batch_size=4, group_size=4, max_tokens=2048, lr=1e-5, and ppo loss.

IDT-OPD evaluation trajectory ​

IDT-OPD training trajectory and Pareto frontier analysis

CheckpointTask progressMedQA-zh (600)C-Eval non-med (300)
4B Base-72.17% (433/600)81.67% (245/300)
Medical SFT Teacher-79.00% (474/600)69.33% (208/300)
IDT-OPD step 100M50 + C5079.17% (475/600)81.67% (245/300)
IDT-OPD step 200M100 + C10076.50% (459/600)86.00% (258/300)
IDT-OPD step 300M150 + C15076.33% (458/600)84.33% (253/300)
IDT-OPD step 400M200 + C20075.17% (451/600)81.33% (244/300)
IDT-OPD step 500M250 + C25075.33% (452/600)83.67% (251/300)
IDT-OPD step 600M300 + C30075.00% (450/600)82.00% (246/300)

Step 100 (medical-leaning) and Step 200 (general-leaning, +4.33 pp over Base on both benchmarks) form two Pareto-efficient checkpoints, while continuing to step 600 degrades both metrics.

Comparing the two methods ​

AspectSAR-OPDIDT-OPD
StructureSequential multi-stage trainingSingle-loop interleaved dual-teacher training
Student initFresh Base for Stage 2; restored training_state for Stage 3Fresh Base Student throughout
Best MedQA-zh84.33%79.17%
Best C-Eval84.67%86.00%
Key strengthBest combined score; clear restoration curveUnified loop; easy to extend ratios or add Teachers
Key challengeLonger pipeline; strict state vs. sampler path handlingSensitive to schedule ratio, LR, early stopping, and checkpoint choice

Environment and running the workflow ​

Requires Python >=3.13. Run all commands from the repository root:

bash
git clone https://github.com/datawhalechina/agentic-rl-lab.git
cd agentic-rl-lab
git checkout ec51068085d647775915a91ce8441cb3441e4ccf

uv sync
trio login
swanlab login

The evaluation scripts query PyTRIO's OpenAI-compatible API, so create experiments/medical-opd/.env and set PYTRIO_API_KEY:

bash
cp experiments/medical-opd/.env.example experiments/medical-opd/.env

1. Download datasets ​

bash
uv run python experiments/medical-opd/00-download-dataset.py

2. Train the Medical SFT Teacher ​

bash
uv run python experiments/medical-opd/02-medical-sft.py \
    --num-epochs 3 \
    --batch-size 16 \
    --max-length 2048 \
    --swanlab-mode online

Record the epoch 3 sampler_weights path to use as the frozen Medical Teacher below.

3. Run SAR-OPD (Medical OPD → Base-anchor OPD) ​

bash
# Stage 2: Medical OPD
uv run python experiments/medical-opd/03-medical-opd-async.py \
    --teacher-model-path 'trio://RUN_ID/sampler_weights/SFT_WEIGHTS_NAME' \
    --steps 300 \
    --batch-size 4 \
    --group-size 4 \
    --sample-size 0 \
    --max-tokens 2048 \
    --learning-rate 4e-5 \
    --save-every-steps 300 \
    --swanlab-mode online

# Stage 3: Base-anchor C-Eval OPD (must pass Stage 2 training_state path)
uv run python experiments/medical-opd/04-ceval-opd-async.py \
    --student-state-path 'trio://RUN_ID/training_states/MEDICAL_OPD_STATE_NAME' \
    --steps 300 \
    --batch-size 4 \
    --group-size 4 \
    --sample-size 0 \
    --max-tokens 2048 \
    --learning-rate 5e-6 \
    --save-every-steps 50 \
    --swanlab-mode online

4. Run IDT-OPD (interleaved dual-teacher) ​

bash
uv run python experiments/medical-opd/05-interleaved-multi-teacher-opd.py \
    --medical-teacher-model-path 'trio://RUN_ID/sampler_weights/SFT_WEIGHTS_NAME' \
    --steps 600 \
    --medical-steps-per-cycle 1 \
    --ceval-steps-per-cycle 1 \
    --batch-size 4 \
    --group-size 4 \
    --max-tokens 2048 \
    --learning-rate 1e-5 \
    --save-every-steps 50 \
    --swanlab-mode online

Set --save-every-steps to a multiple of the full schedule cycle length (e.g., even for 1:1, multiples of 3 for 2:1).

5. Evaluate and analyze ​

bash
uv run python experiments/medical-opd/01-eval-medical.py \
    --model 'trio://RUN_ID/sampler_weights/WEIGHTS_NAME' \
    --max-tokens 1024 \
    --concurrency 16

uv run python experiments/medical-opd/01-eval-ceval.py \
    --model 'trio://RUN_ID/sampler_weights/WEIGHTS_NAME' \
    --max-tokens 8192 \
    --concurrency 16

Per-question JSONL outputs and summary metrics are written to experiments/medical-opd/eval-results/, and can be plotted via experiments/medical-opd/analysis.py.

Metrics to watch ​

MetricMeaning
opd/reverse_kl_mean / opd/reverse_kl_stdMean and spread of per-token Student–Teacher logprob gap
data/datums / data/completion_tokens_meanActive completions and average completion length per step
step/completion_tokens_per_secondEnd-to-end step throughput (sampling, Teacher scoring, training, and refresh)
trainer/*PyTRIO PPO loss and optimizer metrics
medical/*, ceval/*, train/medical_ratio (IDT-OPD only)Per-task metrics and realized schedule share

A falling reverse KL only indicates that the Student is moving closer to the active Teacher—it does not guarantee benchmark improvement, so periodic checkpoint evaluation remains essential.

Reproduction boundaries ​

  • Single-seed runs without full ablations: Each workflow reflects one primary trajectory without multi-seed variance estimates, and differences between SAR-OPD and IDT-OPD also reflect different learning rates (4e-5 / 5e-6 vs. 1e-5) rather than training topology alone.
  • Multiple-choice benchmark scope: MedQA-zh and C-Eval track capability shifts effectively, but do not measure real-world clinical safety and cannot be interpreted as readiness for medical diagnosis.

For full experiment notes and references, see the upstream Medical OPD README.