Medical OPD
Code source and cost
- The complete implementation comes from
datawhalechina/agentic-rl-lab/experiments/medical-opd. This page was checked against commitec51068; 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:
- SAR-OPD (Staged Anchor-Restoration OPD): train Medical OPD first, then restore the
training_stateand run Base-anchor OPD with the original Base Model to recover general capability. - 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-OPDandIDT-OPDare 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:
| Capability | Benchmark | Samples | Output budget | Metric |
|---|---|---|---|---|
| Medical | MedQA-zh 4 options | 600 | 1,024 tokens | Accuracy |
| General | C-Eval non-med | 300 | 8,192 tokens | Accuracy |
Key checkpoints:
| Model / Checkpoint | MedQA-zh (600) | C-Eval non-med (300) |
|---|---|---|
| 4B Base | 72.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 | 80.00% (480/600) | 73.00% (219/300) |
| SAR-OPD step 300 | 84.33% (506/600) | 84.67% (254/300) |
| IDT-OPD step 100 | 79.17% (475/600) | 81.67% (245/300) |
| IDT-OPD step 200 | 76.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:

For Student , Teacher , and sampled token :
In code, this takes two lines:
reverse_kl = np.asarray(student_logprobs) - np.asarray(teacher_logprobs)
advantages = -args.kl_penalty_coef * reverse_klWhen 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:
| Dataset | Role | Fields used in training |
|---|---|---|
FreedomIntelligence/medical-o1-reasoning-SFT (Chinese) | Medical SFT, Medical OPD prompt pool | SFT uses question + complex_cot + response; OPD uses question only |
bigbio/med_qa (MedQA-zh 4 options) | Medical evaluation | Held-out evaluation only |
ceval/ceval-exam (8 non-medical subsets) | Base-anchor OPD, general evaluation | OPD 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
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 checklistSee 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:
| Checkpoint | MedQA-zh (600) | C-Eval non-med (300) |
|---|---|---|
| 4B Base | 72.17% (433/600) | 81.67% (245/300) |
| Medical SFT epoch 1 | 77.67% (466/600) | 71.67% (215/300) |
| Medical SFT epoch 2 | 79.17% (475/600) | 69.33% (208/300) |
| Medical SFT epoch 3 | 79.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 type | Usage |
|---|---|
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:
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
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:
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:
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

| Stage / Checkpoint | MedQA-zh (600) | C-Eval non-med (300) |
|---|---|---|
| 4B Base | 72.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 50 | 84.17% (505/600) | 76.67% (230/300) |
| Base-anchor OPD step 100 | 82.50% (495/600) | 79.33% (238/300) |
| Base-anchor OPD step 150 | 83.00% (498/600) | 80.33% (241/300) |
| Base-anchor OPD step 200 | 82.17% (493/600) | 83.67% (251/300) |
| Base-anchor OPD step 250 | 83.33% (500/600) | 82.67% (248/300) |
| Base-anchor OPD step 300 | 84.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:

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_messageEach 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

| Checkpoint | Task progress | MedQA-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 100 | M50 + C50 | 79.17% (475/600) | 81.67% (245/300) |
| IDT-OPD step 200 | M100 + C100 | 76.50% (459/600) | 86.00% (258/300) |
| IDT-OPD step 300 | M150 + C150 | 76.33% (458/600) | 84.33% (253/300) |
| IDT-OPD step 400 | M200 + C200 | 75.17% (451/600) | 81.33% (244/300) |
| IDT-OPD step 500 | M250 + C250 | 75.33% (452/600) | 83.67% (251/300) |
| IDT-OPD step 600 | M300 + C300 | 75.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
| Aspect | SAR-OPD | IDT-OPD |
|---|---|---|
| Structure | Sequential multi-stage training | Single-loop interleaved dual-teacher training |
| Student init | Fresh Base for Stage 2; restored training_state for Stage 3 | Fresh Base Student throughout |
| Best MedQA-zh | 84.33% | 79.17% |
| Best C-Eval | 84.67% | 86.00% |
| Key strength | Best combined score; clear restoration curve | Unified loop; easy to extend ratios or add Teachers |
| Key challenge | Longer pipeline; strict state vs. sampler path handling | Sensitive 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:
git clone https://github.com/datawhalechina/agentic-rl-lab.git
cd agentic-rl-lab
git checkout ec51068085d647775915a91ce8441cb3441e4ccf
uv sync
trio login
swanlab loginThe evaluation scripts query PyTRIO's OpenAI-compatible API, so create experiments/medical-opd/.env and set PYTRIO_API_KEY:
cp experiments/medical-opd/.env.example experiments/medical-opd/.env1. Download datasets
uv run python experiments/medical-opd/00-download-dataset.py2. Train the Medical SFT Teacher
uv run python experiments/medical-opd/02-medical-sft.py \
--num-epochs 3 \
--batch-size 16 \
--max-length 2048 \
--swanlab-mode onlineRecord the epoch 3 sampler_weights path to use as the frozen Medical Teacher below.
3. Run SAR-OPD (Medical OPD → Base-anchor OPD)
# 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 online4. Run IDT-OPD (interleaved dual-teacher)
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 onlineSet
--save-every-stepsto a multiple of the full schedule cycle length (e.g., even for1:1, multiples of 3 for2:1).
5. Evaluate and analyze
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 16Per-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
| Metric | Meaning |
|---|---|
opd/reverse_kl_mean / opd/reverse_kl_std | Mean and spread of per-token Student–Teacher logprob gap |
data/datums / data/completion_tokens_mean | Active completions and average completion length per step |
step/completion_tokens_per_second | End-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-6vs.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.