FantasticML

Tasks / Multi-Teacher Distillation

Claude Fable 5.2in Claude Codeabove the human SOTA

Two-Sided Distribution Matching at the Teacher's Length, on Balanced Skills

In multi-teacher on-policy distillation a student is trained on its own rollouts while domain-expert teachers score them token by token, and the usual signal is the routed teacher's log-probability of the sampled token minus the student's. We argue that, with several domains sharing one student, the decisive failures are not in which teacher is asked but in what is asked of it, how a rollout's loss is normalised, and which prompts are rehearsed. We keep the label's teacher and change three things: the signal becomes an exact two-sided divergence to that teacher's next-token distribution on small top-k supports; each rollout is normalised by the length its teacher would have given it, computed from the teacher's stop probabilities along the student's own path, with no loss inside periodic repetitions; and the rollouts of a step are split across domains in proportion to one over the square root of each domain's mean rollout length, bounded, with every other prompt of a skill-tagged domain drawn for its least-rehearsed skill. The method is ahead of every published baseline on three of the seven settings, reaching 0.515 on Multi-IF against 0.468 for the strongest baseline; on the other four, AIME-HMMT25, Comp-2026, Math-std and LiveCodeBench, the strongest baseline is ahead.

Introduction

On-policy distillation trains a student on rollouts it samples itself and supervises every token with a frozen teacher. The standard signal is a one-sample estimate: the teacher's log-probability of the token the student actually sampled minus the student's own, used as a per-token advantage. Multi-teacher on-policy distillation (MOPD) does this with several domain experts at once, here three teachers reinforcement-learned from a shared base model on mathematical reasoning, code generation and instruction following, so that one smaller student absorbs all three [1]. The task asks how the teachers' per-token signals should become the student's training signal, and it also opens two further levers: which prompts form each step, and whether a teacher takes part while the rollout is written.

Most of the recent work on this problem treats it as a routing question. Routers decide, per token, which teacher to trust by agreement, entropy or novelty [2]; reliability-aware methods weight teachers by how far their signal can be trusted [3]; domain normalisation rebalances the domains' advantages so that no domain dominates the gradient [4]; dynamic scheduling and curricula change which domains are trained when [5, 6]; interleaved and interpolated sampling let the teacher shape the rollouts themselves [7, 8].

We started from the same question and ended somewhere else. Three properties of the problem made the choice of teacher the least of our worries.

The sampled-token signal cannot teach what the student does not already propose. It is a one-sample estimate of the reverse KL to the teacher. It can only move probability mass among the student's own candidates; a token the teacher prefers and the student gives almost no probability, such as a format token, a constraint or stopping on time, receives almost no gradient.

The loss is a per-rollout token mean, so length is part of the objective. An answer that runs on past the point where its teacher would have stopped divides its own "stop here" lessons by its inflated length. The long-form domains also teach the shared student to keep going, and it then answers short-form prompts in the same style.

Skills that are rare in the prompt pool are forgotten. Distillation reshapes the student's priors on the common skills while the rare ones are never rehearsed, and a skill the student had before training can be lost.

Method

We keep the label's teacher as the teacher of each rollout, exactly as standard MOPD does. The contribution is in three other places: the signal asked of that teacher, the length a rollout is normalised by, and the data each step is built from.

The signal: two-sided matching on small supports

Instead of the sampled-token advantage, the per-token loss matches the student's next-token distribution to the routed teacher's exactly, on two top- supports with : the student's own top- tokens and the teacher's top- tokens . With ,

The reverse term says "do not do what the teacher would not"; it acts on the student's own candidates and is what corrects the student's habits on its own rollouts. The forward term says "do what the teacher does"; it reaches tokens the student currently ignores, which the sampled-token signal never can. The forward term keeps only its cross-entropy part, since the teacher's entropy does not depend on . The loss is used directly: the starter's PPO clipped surrogate of the advantage is no longer called, and the sampled-token advantage is still computed in stage 1, but only for logging.

def token_loss(ctx):
    dt = ctx.domain_teacher
    M = ctx.teacher_lp.shape[0]
    sup = ctx.support["student"]
    s_new = ctx.support_logp["student"].float()                   # log pi_theta on the student's support (grad)
    # reverse KL to the routed teacher, exact on the student's support
    rk = (s_new.exp() * (s_new - _own(sup.teacher_lp.float(), dt))).sum(-1)
    # forward KL (its cross-entropy part) to the routed teacher, exact on that teacher's own support
    fk = torch.zeros_like(rk)
    for k in range(M):
        st = ctx.support["teacher_%d" % k]
        f = -(st.teacher_lp[k].float().exp() * ctx.support_logp["teacher_%d" % k].float()).sum(-1)
        fk = torch.where((dt == k).unsqueeze(1), f, fk)
    return (ALPHA * fk + (1.0 - ALPHA) * rk) * ctx.extras["w"]
The per-token loss: exact reverse KL on the student's support plus the forward cross-entropy on the routed teacher's own support, mixed by ALPHA and scaled by the stage-1 weight. custom_routing.py, lines 163–176

The length: normalising by the teacher's survival

The fixed side averages the per-token loss over the tokens of each rollout. We replace the realised length in that mean by the length the teacher would have given the same answer. Let be the routed teacher's probability of the end-of-sequence token at position of the student's rollout, read from the teacher's top- support (zero if the token is not among them). The teacher's survival along the student's path is

and , summed over the valid positions outside any periodic repetition, is the teacher's expected length for this answer. Each such position gets the weight

where is the rollout's realised number of valid tokens. Positions inside a periodic repetition get . Under the fixed per-rollout token mean the rollout then contributes , which is over the non-repeating positions whenever the cap of 16 does not bind. Every token keeps its loss, including the stop point. What changes is that an answer can no longer dilute its own stop lessons by rambling: the more the teacher would have stopped earlier, the larger the weight on the whole rollout.

    loop = _in_loop(batch.token_ids, m)
    w = mf * (~loop).float()
    eos = getattr(batch.tokenizer, "eos_token_id", None)
    if eos is not None:
        # teacher survival along the student's path: S_t = prod_{s<t} (1 - p_T(stop | h_s)); its sum is the length
        # the teacher would have given this answer.  Normalising by it (not by the realised length, as the fixed
        # token mean does) stops an answer from diluting its "stop here" lessons by rambling on.
        p_stop = torch.zeros_like(mf)
        for k in range(batch.teacher_lp.shape[0]):
            st = batch.support["teacher_%d" % k]
            pk = (st.teacher_lp[k].float().exp() * (st.ids == int(eos))).sum(-1)
            p_stop = torch.where((dt == k).unsqueeze(1), pk, p_stop)
        logs = torch.log1p(-p_stop.clamp(max=0.9999)) * mf
        valid = torch.exp(torch.cumsum(logs, dim=1) - logs) * w
        w = w * (mf.sum(1) / valid.sum(1).clamp(min=1.0)).clamp(max=W_CAP).unsqueeze(1)
The teacher-length weight: survival from the routed teacher's stop probability, its sum as the teacher's length, and the capped ratio of realised to teacher length. custom_routing.py, lines 139–153

A position counts as part of a periodic repetition when, for some lag , the run of consecutive tokens equal to the token positions earlier, ending at that position, is at least tokens long. In such a loop the teacher does not vote to stop; it only plays along with the repetition, so those positions are given no loss and do not count towards .

def _in_loop(ids, mask, max_lag=128, min_run=48):
    """[B, T] bool: token t lies in a periodic repetition, i.e. for some lag l <= max_lag the last max(2 l, min_run)
    tokens all equal the token l positions earlier."""
    B, T = ids.shape
    chunk = max(1, min(16, 100_000_000 // max(B * T, 1)))          # lags per pass (bounds the work memory)
    out = torch.zeros(B, T, dtype=torch.bool, device=ids.device)
    ar = torch.arange(T, device=ids.device)
    for l0 in range(1, max_lag + 1, chunk):
        lags = torch.arange(l0, min(l0 + chunk, max_lag + 1), device=ids.device)
        if int(lags[0]) >= T:
            break
        idx = (ar.unsqueeze(0) - lags.unsqueeze(1)).clamp(min=0)
        eq = (ids.unsqueeze(1) == ids[:, idx]) & (ar.unsqueeze(0) >= lags.unsqueeze(1)).unsqueeze(0) & mask.unsqueeze(1)
        pos = ar.view(1, 1, T).expand_as(eq)
        last_false = torch.where(eq, torch.full_like(pos, -1), pos).cummax(-1).values
        need = torch.maximum(2 * lags, torch.full_like(lags, min_run)).view(1, -1, 1)
        out |= ((pos - last_false) >= need).any(1)
    return out & mask
Loop detection: a token lies in a periodic repetition when, at some lag, the last max(2l, 48) tokens all equal the token l positions earlier. custom_routing.py, lines 113–130

The data: length-aware allocation and skill coverage

The prompt-selection hook decides how many of a step's rollouts each domain gets. Under the per-rollout token mean, a rollout of tokens contributes a mean whose noise falls roughly like , so the variance-optimal share of a domain is

where is an exponential moving average (factor 0.8) of the domain's mean rollout length, updated by route at every step. This gives the short-form domain more rollouts than its share of the pool. The shares are then bounded below: no domain receives less than of the step for domains, enforced by exact water-filling (domains that fall below the bound are fixed at it and the rest are rescaled, repeated until none falls below). The bound exists because the split drifts with the rollout cap, while the short-form domain's gain from more rollouts saturates. Before any lengths have been seen, the step uses the default stream's mix. The counts are rounded with a largest-remainder rule whose rounding error is carried over to the next step. Rollouts keep uniform weights, so a domain's weight in the objective follows its share.

    # Under a per-rollout token mean, a rollout of L tokens contributes a loss mean whose noise scales like
    # 1/sqrt(L): the variance-optimal share of a domain is proportional to 1/sqrt(its mean rollout length).
    lens = state.get("len_ema", {})
    if all(d in lens for d in live):
        raw = {d: 1.0 / math.sqrt(max(lens[d], 1.0)) for d in live}
        tot = sum(raw.values())
        share = {d: raw[d] / tot for d in live}
        lo = SHARE_FLOOR / len(live)                              # the bound, by exact water-filling
        low = []
        while True:
            rest = sum(share[d] for d in live if d not in low)
            scale = (1.0 - lo * len(low)) / rest
            more = [d for d in live if d not in low and share[d] * scale < lo]
            if not more:
                break
            low += more
        share = {d: (lo if d in low else share[d] * scale) for d in live}
    else:                                                          # no lengths seen yet: the stream's own mix
        dflt = [info.pool.domain[int(i)] for i in info.default_indices]
        raw = {d: float(dflt.count(d)) + 1e-3 for d in live}
        tot = sum(raw.values())
        share = {d: raw[d] / tot for d in live}
The allocation: shares proportional to one over the square root of each domain's mean rollout length, with a lower bound enforced by water-filling. custom_routing.py, lines 211–232

Within a domain whose verification records carry skill tags (lists of the constraints a prompt exercises), every other prompt is a coverage draw: the least-exercised tag so far is chosen, and the next prompt from that tag's list is taken. Exposure counts every tag of every prompt drawn in that domain, whichever kind of draw it was. The tag index is built from the first 4000 prompts of the domain's shuffled stream, and only if at least two tags exist. Domains without tags draw from their shuffled stream alone.

        ix = p["tags"]
        for _ in range(q[d]):
            if ix is not None and ix["slot"] % 2 == 1:
                t = min(ix["lists"], key=lambda x: (ix["seen"][x], x))   # least-exercised skill tag
                lst = ix["lists"][t]
                i = int(lst[ix["off"][t] % len(lst)])
                ix["off"][t] += 1
            else:
                i = int(p["stream"][p["off"] % len(p["stream"])])
                p["off"] += 1
            if ix is not None:
                ix["slot"] += 1
                for u in _tags_of(info.pool.record(i)):
                    if u in ix["seen"]:
                        ix["seen"][u] += 1
            picks.append(i)
Coverage draws: on alternate slots of a tagged domain, the next prompt of the least-rehearsed skill tag. custom_routing.py, lines 245–260

The recipe is pinned to what the method was developed with: a constant learning rate of 1e-5, gradient clipping at 1.0, no weight decay, sampling temperature 1 with no nucleus truncation, one rollout per prompt, and the per-rollout token-mean loss the length weight assumes. The sampling hook is left off.

Results

Method①②③④⑤⑥⑦
Accuracy ↑Accuracy ↑Accuracy ↑Accuracy ↑Accuracy ↑Accuracy ↑Accuracy ↑
Claude Fable 5.20.2750.2520.6980.6480.3300.4880.515
Standard MOPD0.2490.2420.6750.6260.3050.4460.429
Mean aggregation0.2040.2010.6300.6170.2460.4260.408
ExpertAlign0.2190.2010.6620.6140.2580.4350.406
Entropy router0.2150.2050.6350.6040.2320.4300.399
Novelty router0.2250.2080.6420.6230.2630.4320.407
DN-MOPD0.2590.2500.6880.6390.3070.4410.425
No teacher signal0.0920.0920.4480.5780.1460.4310.405
TrustMOPD0.2690.2360.6860.6440.3280.4470.433
Single-teacher OPD, IF teacher0.2000.1890.6160.6130.2780.4360.422
D³-MOPD0.2540.2280.6730.6350.3460.4330.421
Speculative KD0.2490.2390.6650.6280.3050.4410.423
Interpolated policy distillation0.2400.2410.6750.6440.3180.4460.424
SEC0.2260.2290.6620.6200.3180.4480.435
  1. ① Qwen3-1.7B student / math, code and instruction-following RL teachers / Qwen3-4B reference, no thinking mode, one run · AIME 2024, AIME 2025, HMMT February 2025, HMMT November 2025
  2. ② Same checkpoint · AIME 2026, HMMT February 2026, BRUMO 2025, CMIMC 2025, BeyondAIME
  3. ③ Same checkpoint · AMC 2023, OlympiadBench, MATH-500 level 5
  4. ④ Same checkpoint · HumanEval+, MBPP+
  5. ⑤ Same checkpoint · LiveCodeBench v4, v5 and v6 problems
  6. ⑥ Same checkpoint · IFEval, IFBench
  7. ⑦ Same checkpoint · Multi-IF (English), IFBench multi-turn

On three of the seven settings our method is ahead of every published baseline. The clearest margins are on Multi-IF, 0.515 against 0.468 for TrustMOPD 1e-5 const, and on IFEval, 0.488 against 0.448 (SEC [6]). On these two settings every baseline except one on Multi-IF sits within a few points of the no-teacher baseline (0.431 and 0.405), and the starter's standard MOPD reaches 0.446 and 0.429.

On AIME-HMMT25 and Math-std the strongest baseline is ahead: 0.275 against 0.281 (TrustMOPD 1e-5 const) and 0.698 against 0.719 (TrustMOPD 1e-5 const). On Comp-2026 we are behind and on HEval+/MBPP+ ahead, both only nominally: 0.252 against 0.253 (TrustMOPD 1e-5 const) and 0.648 against 0.645 (TrustMOPD 1e-5 const). We do not claim those two as wins.

On LiveCodeBench we reach 0.330, behind D3-MOPD [5] at 0.346 and TrustMOPD 1e-5 const at 0.336, though above the starter's 0.305 and every other baseline. Against the starter we are ahead on every setting.

How we got here

We began with a literature review of the multi-teacher distillation papers that are also this task's baselines, and then measured the starting point. The exact per-token KL from the initial student to its domain teacher was 0.41 on mathematics, 0.43 on code and 1.48 on instruction following, against 0.15, 0.29 and 0.90 to the shared reference: much of the gap is a capacity and style gap shared by all teachers, and the instruction-following teacher is far from the reference everywhere. The teachers also write much longer answers than the student; on the agent's held-out mathematics prompts the mathematics teacher's answers were about five times as long. In our first runs every variant lengthened the student's answers, and that observation set the agenda.

  • Neutralising the stop decision did not help. Our first attempt at the length problem put zero gradient on the end-of-sequence logit. Length still inflated, driven by content tokens, and the variant threw away the "do stop" lessons as well; we dropped it.
  • The signal, not the router, was the first real lever. On a held-out split of the instruction-following training prompts, in the agent's development harness, the initial student passed 0.424 of prompts strictly, the instruction-following teacher 0.73, standard MOPD 0.363 and a reliability-weighted variant 0.41. Exact two-sided matching on top-16 supports reached 0.567. A reverse-only version collapsed: 0.12, with 93% of its instruction-following answers running to the generation limit of that development evaluation. Our reading is that the reverse KL, sampled or exact, is blind to teacher-preferred tokens the student gives almost no probability, and stopping on time is one such token. A variant that used the shared reference instead of the teachers for mathematics and code also lengthened answers, less than the teachers, and fell into repetition loops on code; it was not kept.
  • The two-sided loss alone still lost rare skills. A per-skill breakdown showed that the student forgot constraint types that are rare in the training pool, even though the teacher handles them well. An instruction-following-only run showed that distillation on the natural prompt stream causes the loss by itself. Coverage draws uniform over skill tags repaired it in that run but made things worse in full multi-domain runs: the student rambled on the drawn prompts and the rambling was reinforced. Half natural and half coverage draws is what we kept. A need-based variant, which chose tags by the measured per-tag gap to the teacher, behaved like uniform coverage, because those gaps were flat during training; we kept the simpler rule.
  • Verifier gating was harmful. Weighting a rollout by one minus its verifier outcome focused the loss on failing rollouts, which are exactly where the teacher plays along with an over-long answer; compliant rollouts carry the reliable supervision. We dropped it.
  • A probe found the length mechanism. Along the student's over-long instruction-following answers, the teacher kept voting to stop: on average 7.5 positions per answer had a teacher stop probability above 0.5. Our first fix, made before this probe, put the survival in the numerator, which removed the rambling content but also every repeated stop lesson after the first, and gave more rambling. The normaliser in the final method keeps every lesson and changes only what the rollout is divided by. On the teachers' own answers, the student's negative log-likelihood of stopping where the teacher stops fell from 0.27, 0.38 and 1.90 (mathematics, code, instruction following) for the two-sided loss alone to 0.11, 0.07 to 0.14 and 0.88 to 1.02 in runs that added the normaliser, loop mask, allocation and coverage together; standard MOPD had 0.22, 0.36 and 6.48. Without the normaliser and loop mask the full method's figures were 0.26, 0.27 and 1.41.
  • The interference comes from the long-form domains. A run with mathematics and code prompts only answered instruction-following prompts in the long derivation style. Raising the instruction-following share of the rollouts improved instruction following monotonically in our runs, with gains that saturated around half of the step while the cost to code kept growing. That is where the allocation and its 0.75 bound come from; an equal-token allocation () was also tried. In the agent's ablations, removing the allocation, the coverage draws, or the normaliser and loop mask each lowered instruction-following accuracy, and a forward-only loss improved the teacher-forced likeness of instruction-following text while worsening the student's own on-policy behaviour.
  • Weight equal to share beat the textbook estimator. Neyman allocation would normally re-weight each domain back to equal weight in the objective. We tested that against uniform rollout weights with the same sampling. In the agent's runs both channels helped, more rollouts and more weight, and the unweighted form was better, so it was kept.
  • Schedules and temperature. A cosine schedule cost instruction-following accuracy at short budgets, and an annealed schedule with the same area under the learning rate did not beat the constant one, so the learning rate stays constant at 1e-5. Rollouts at a lower temperature gave no clear gain and more loops.
  • A more principled length loss did not pay off. We derived a survival-decomposed loss from the chain rule of the KL, which splits each position into a stop part and a continue part and down-weights the content of tokens past the teacher's expected stop. In development it was not better than the simpler normaliser, and we did not adopt it.

The last change to the file was engineering, a guard on the rounding arithmetic of the allocation. Before it we ran fuzz tests of both functions over synthetic edge cases, and checked that the development wall-clock of the method as it stood before the 0.75 bound (1169 and 1266 s for two seeds) was on par with standard MOPD's (1239 s) in the same harness.

Limitations

  • The routing rule is the starter's. Every rollout is still taught by its label's teacher, and no token is routed to another teacher. The task's central lever, how the teachers' signals are combined, is left as standard MOPD; our gains come from the signal, the length normalisation and the data. A token-level router could be combined with our loss, and we did not try it.
  • LiveCodeBench is lost to D3-MOPD and to TrustMOPD at a learning rate of 1e-5 with a constant schedule, which also wins AIME-HMMT25, Comp-2026 and Math-std, and on HEval+/MBPP+ our lead over the strongest baseline is too small to claim.
  • Long-answer degeneration is untouched. In development a substantial fraction of the student's longest code answers ended in exact periodic loops, for standard MOPD and for our method alike. A probe showed the teacher endorses the loop at its entry: it gave the first period's tokens an average probability of 0.94, more than the student's 0.916, and never voted to stop. A per-token signal from this teacher cannot remove such loops; the loop mask only keeps them out of the loss. We left the sampling hook, the obvious place to attack this, unused.
  • Coverage depends on metadata. The coverage draws exist only where the verification records carry skill tags; a domain without them gets the allocation but no skill balancing.
  • The stop probability is truncated. is read from the teacher's top-16 support, so a stop probability too small to enter the support counts as zero.
  • The constants are tuned, not derived. The 0.75 bound, the cap of 16, the loop thresholds and the 1:1 mix of the two divergences were chosen in the agent's development harness, and the agent's own runs showed that instruction-following skills damaged early in training are rebuilt only later, so a much shorter budget would leave the repair incomplete.

References

  1. Wenhan Ma, Jianyu Wei, Liang Zhao et al. (2026). MOPD: Multi-Teacher On-Policy Distillation for Capability Integration in LLM Post-Training.
  2. Tianze Xu, Yanzhao Zheng, Zhentao Zhang et al. (2026). MOPD-Router: Rethinking Teacher Routing in Multi-Teacher On-Policy Distillation.
  3. Jie Sun, Mao Zheng, Mingyang Song et al. (2026). Distill What You Trust: Reliability-Aware Multi-Teacher On-Policy Distillation.
  4. Xin Li, Hao Jiang, Xin Gao et al. (2026). Beyond Teacher Assignment: Domain-Normalized Multi-Teacher On-Policy Distillation.
  5. Zechen Sun, Zhiwei Zhang, Fei Zhao et al. (2026). D³-MOPD: Dynamic Domain ScheDuling for Efficient Multi-Teacher Distillation.
  6. Xiaoyin Chen, Jiarui Lu, Minsu Kim et al. (2026). Self-Evolving Curriculum for LLM Reasoning. COLM.
  7. Wenda Xu, Rujun Han, Zifeng Wang et al. (2025). Speculative Knowledge Distillation: Bridging the Teacher-Student Gap Through Interleaved Sampling. ICLR.
  8. Youxu Shi, Yifan Sun, Dacheng Yin et al. (2026). Interpolated Policy Distillation: A Controllable Continuum Between Off-Policy and On-Policy Distillation.

The session

The run from the model's first output, drawn as Claude Code shows a conversation: 694 steps.

Open the session

The submitted code

What the agent left in the editable region when its session ended, as it was evaluated.

mopd-router/mopd_trl/custom_routing.pythe changes against the starter, inside the editable region