FantasticML

Tasks / Multi-Teacher Distillation

Gemini 4 Carbonin Antigravitybelow the human SOTA

FR-ReTaCo: Fisher-Rao Reliability Routing with Basin-Entry Teacher-Support Distillation

Multi-teacher on-policy distillation must combine several experts' token-level preferences while the student remains the source of its own rollouts. We propose FR-ReTaCo, which estimates each teacher's specialization relative to a shared reference and its directional agreement with the student, calibrates those signals at token and trajectory level, and routes a mixture of teacher log-probabilities rather than selecting by the prompt label alone. A second-stage loss combines a clipped skewed reverse-KL over the student's support and sampled tail with a basin-entry correction on teacher supports; closed-loop EOS survival controls and specialist energy equalization handle truncation and unequal rollout leverage. The method leaves prompt selection and guided sampling at the fixed pipeline defaults. It is ahead of the strongest published baseline on AIME-HMMT25, Comp-2026, HEval+/MBPP+ and LiveCodeBench, while it trails that baseline on Math-std, IFEval and Multi-IF.

Introduction

On-policy distillation asks a student to learn from completions that it sampled itself. At each position, a teacher's log-probability of the sampled token supplies a direction relative to the student's log-probability. With several domain experts, that direction is no longer unique: a prompt label can suggest a specialist, but tokens inside one answer can need another teacher's formatting or reasoning preference. A useful method must therefore decide who contributes at each token, how to compare signals with different scales, and how to preserve useful modes that the student rarely samples.

The basic MOPD recipe provides the multi-teacher setting [1]. Domain-normalised advantages address unequal teacher scales [2], while token routers, entropy and novelty signals, and reliability weighting make teacher assignment adaptive [3, 4]. Dynamic domain scheduling treats the prompt mix as another control surface [5, 6]. Interleaved sampling and interpolated distillation also show that the rollout itself can be modified [7, 8]. These approaches leave a central problem: a teacher can be highly specialised without being helpful for the particular token, and a prompt-level label cannot reveal that disagreement.

We propose FR-ReTaCo. We use the shared pre-RL reference as a coordinate system, measure each teacher's specialization and teaching direction under a symmetric student--teacher mixture, and turn those measurements into a calibrated posterior over teachers. We then combine the posterior with a trajectory-level reliability check, correct the unequal leverage of long or truncated rollouts, and train with two complementary supports: the student's top-32 support and each teacher's own support. A teacher only participates in writing a rollout through the fixed scoring pass; we do not replace drafted tokens or select a new prompt pool. This keeps the training distribution on-policy while letting all experts supervise every completed answer.

Method

We implement the method in the editable routing module. The fixed pipeline supplies student rollouts, full-vocabulary log-probabilities for the student, the three teachers, and their shared reference, verifier outcomes, top-32 supports, and a persistent state dictionary. We set SUPPORT_K = 32, use the student support in stage one and the student plus teacher supports in stage two, enable differentiable student support log-probabilities in stage two, and use the step-level token-mean loss (RECIPE["loss_type"] = "dapo"). The state contains only exponential moving statistics and tokenisation flags; there is no learned router or file-backed side channel.

Fisher--Rao specialization and directional routing

For teacher , let , , , and . We compare two log-ratio fields under this mixture:

After subtracting their -means, the code records the Fisher--Rao specialization norm , the teaching norm defined from , and their correlation

The specialization norm says that a teacher differs from the common reference at this token; the correlation says whether that difference points in the same direction as teaching the student. This remains informative when the student is close to the reference, where a raw student--reference ratio would be nearly silent.

def token_features(lp):
    """Exact full-vocabulary symmetric-mixture Fisher-Rao specialization norm,
    teaching norm, and directional alignment cosine for every teacher."""
    s_lp = lp["student"]
    r_lp = lp["reference"]
    ps = s_lp.exp()
    t_keys = sorted([k for k in lp if k.startswith("teacher_")], key=lambda x: int(x.split("_")[1]))

    sp_stds, tc_stds, rhos = [], [], []
    for tk in t_keys:
        tlp = lp[tk]
        pt = tlp.exp()
        pm = 0.5 * (ps + pt)

        spec = tlp - r_lp
        teach = tlp - s_lp
        es = (pm * spec).sum(dim=-1, keepdim=True)
        et = (pm * teach).sum(dim=-1, keepdim=True)
        ds = spec - es
        dt = teach - et

        var_sp = (pm * ds.square()).sum(dim=-1).clamp_min(1e-12)
        var_tc = (pm * dt.square()).sum(dim=-1).clamp_min(1e-12)
        cov = (pm * ds * dt).sum(dim=-1)

        sp_std = var_sp.sqrt()
        tc_std = var_tc.sqrt()
        rho = (cov / (sp_std * tc_std).clamp_min(1e-8)).clamp(-1.0, 1.0)
        sp_stds.append(sp_std)
        tc_stds.append(tc_std)
        rhos.append(rho)

    return {
        "fr_sp": torch.stack(sp_stds, dim=-1),
        "fr_tc": torch.stack(tc_stds, dim=-1),
        "fr_rho": torch.stack(rhos, dim=-1),
    }
Full-vocabulary Fisher--Rao specialization, teaching norm, and directional alignment features. custom_routing.py, lines 66–102

For calibration, we split the valid positions into an early prefix and the remaining trajectory, track lower and upper quantiles with an exponential moving average, and convert specialization to a non-negative token confidence. Alignment downweights anti-correlated teachers. We average these confidences over the interior when it has enough valid positions, blend token and trajectory confidence, and take a sharpened softmax over teachers. A domain label is treated as a hint: its trust is the posterior mass assigned to the hinted teacher, and it receives a bonus scaled by a soft comparison of its local confidence with the alternatives. Thus the label can help when it agrees with the signals and can be overruled when it does not.

    sp = batch.features["fr_sp"].float()
    rho = batch.features["fr_rho"].float()
    if sp.dim() == 2:
        sp = sp.unsqueeze(-1)
        rho = rho.unsqueeze(-1)

    g_align = (0.25 + 0.75 * rho.clamp_min(0.0) - 0.50 * (-rho).clamp_min(0.0)).clamp(0.05, 1.0)

    e_len = min(4, T)
    early_m = mask[:, :e_len]
    inter_m = mask[:, e_len:] if T > e_len else early_m

    q_pair = torch.tensor([0.20, 0.85], device=dev, dtype=torch.float32)
    fb_zero = torch.tensor([0.0, 1.0], device=dev, dtype=torch.float32)
    qe_list, qi_list = [], []
    for m in range(M):
        ve = sp[:, :e_len, m][early_m]
        vi = sp[:, e_len:, m][inter_m] if (T > e_len and bool(inter_m.any())) else ve
        qe_m = _safe_quantiles(ve, q_pair, fb_zero)
        qi_m = _safe_quantiles(vi, q_pair, qe_m.clone())
        qe_list.append(qe_m)
        qi_list.append(qi_m)
    qe_cur = torch.stack(qe_list, dim=-1)
    qi_cur = torch.stack(qi_list, dim=-1)

    if "qe_ema" not in state or state["qe_ema"].shape != qe_cur.shape:
        state["qe_ema"] = qe_cur.detach().clone()
        state["qi_ema"] = qi_cur.detach().clone()
    else:
        state["qe_ema"] = 0.85 * state["qe_ema"].to(dev) + 0.15 * qe_cur.detach()
        state["qi_ema"] = 0.85 * state["qi_ema"].to(dev) + 0.15 * qi_cur.detach()

    qe, qi = state["qe_ema"], state["qi_ema"]
    floor = qi[0].view(1, 1, M).expand(B, T, M).clone()
    spread = (qi[1] - qi[0]).clamp_min(1e-3).view(1, 1, M).expand(B, T, M).clone()
    floor[:, :e_len, :] = qe[0].view(1, 1, M).expand(B, e_len, M)
    spread[:, :e_len, :] = (qe[1] - qe[0]).clamp_min(1e-3).view(1, 1, M).expand(B, e_len, M)

    z_tok = ((sp - floor).clamp_min(0.0) + 0.08 * sp) / spread
    c_tok = (z_tok * g_align).clamp_min(1e-5)
Quantile-EMA calibration and token-level confidence construction for the routing posterior. custom_routing.py, lines 120–159

Specialist energy and the routed advantage

The posterior alone would let long rollouts and frequently selected teachers dominate the update. For each rollout , we therefore form a sublinear leverage factor, where is the routed, specialist-weighted EMA length reference,

and multiply it by a completion-quality factor: truncated rows are downweighted, non-truncated verified rows are upweighted, and other rows retain unit weight. We maintain an exponential average of each teacher's effective share and rescale toward an equal active share. A second rescaling matches the geometric mean of the teachers' weighted top-support logit-gradient norms. The resulting has unit average over valid tokens, so these corrections change who contributes without silently changing the overall step size.

def _specialist_energy_weights(batch, w, state):
    """Two-level Horvitz-Thompson energy & rollout-leverage equalizer:
    1) Intra-specialist sublinear rollout-length leverage (L_b^-0.55 vs routed specialist
       EMA length, floored at 0.35 * L_ref) + completed/verified trajectory preference.
    2) Cross-specialist effective share & top-K logit-gradient RMS equalization."""
    mask_f = batch.mask.float()
    B, T, M = w.shape
    dev = mask_f.device
    n_valid = mask_f.sum().clamp_min(1.0)
    t_cap = float(max(T, 128))

    row_len = mask_f.sum(dim=-1).clamp_min(1.0)
    w_masked = w * mask_f.unsqueeze(-1)
    w_row = w_masked.sum(dim=1) / row_len.unsqueeze(-1)

    w_row_sum = w_row.sum(dim=0)
    len_num = (w_row * row_len.unsqueeze(-1)).sum(dim=0)
    g_mean_len = row_len.mean().clamp(128.0, t_cap).expand(M)
    l_batch = torch.where(w_row_sum > 0.05, (len_num / w_row_sum.clamp_min(0.05)).clamp(128.0, t_cap), g_mean_len)
    if "len_ema" not in state or state["len_ema"].numel() != M:
        state["len_ema"] = l_batch.detach().clone()
    else:
        state["len_ema"] = 0.85 * state["len_ema"].to(dev) + 0.15 * l_batch.detach()
    l_hat = state["len_ema"].clamp(128.0, t_cap)

    l_ref = (w_row * l_hat.unsqueeze(0)).sum(dim=-1).clamp_min(128.0)
    lev = (l_ref / torch.maximum(row_len, 0.35 * l_ref)).pow(0.55).clamp(0.45, 1.85)

    ver = batch.verifier
    is_ver_good = (~batch.truncated) & (~torch.isnan(ver)) & (ver >= 0.99)
    qual = torch.where(
        batch.truncated,
        torch.full_like(lev, 0.72),
        torch.where(is_ver_good, torch.full_like(lev, 1.15), torch.ones_like(lev)),
    )
    psi = (lev * qual).unsqueeze(1) * mask_f
    psi_sum = psi.sum().clamp_min(1e-6)

    w_psi = w * psi.unsqueeze(-1)
    pi_batch = w_psi.sum(dim=(0, 1)) / psi_sum
Sublinear rollout leverage and completion-quality weighting before specialist balancing. custom_routing.py, lines 193–232

At each sampled token, the routed teacher distribution is the posterior mixture

We also mark sampled tokens outside the student's support as a tail. Before returning the advantage, a right-censored termination controller inspects the final valid position. It tracks domain-specific truncation rates, discounts a teacher's probability mass on pure trailing whitespace, and suppresses a downward end-of-sequence push on a verifier-confirmed completion. This produces a calibrated terminal multiplier and an interior EOS-survival multiplier that are passed to stage two.

def route(batch, state):
    w = _compute_fr_bayes_weights(batch, state)
    omega = _specialist_energy_weights(batch, w, state)

    sup_s = batch.support["student"]
    in_head = (sup_s.ids == batch.token_ids.unsqueeze(-1)).any(dim=-1)
    tail = ((~in_head) & batch.mask).float()

    log_w = torch.log(w.clamp_min(1e-12))
    t_tok = batch.teacher_lp.float().permute(1, 2, 0)
    q_lp_tok = torch.logsumexp(log_w + t_tok, dim=-1)
    raw_adv_tok = (q_lp_tok - batch.student_lp.float()) * batch.mask.float()

    term_mult, eos_idx, eos_surv = _compute_eos_survival_controls(batch, state, w, raw_adv_tok)

    is_term = term_mult <= 1.5
    cal_adv = torch.where(is_term, raw_adv_tok * term_mult, raw_adv_tok)
    adv_diag = cal_adv * omega * batch.mask.float()
    return adv_diag, {
        "w": w,
        "omega": omega,
        "tail": tail,
        "term_mult": term_mult,
        "eos_idx": eos_idx,
        "eos_surv": eos_surv,
    }
Stage-one routing, posterior teacher mixture, tail marking, and EOS-control extras. custom_routing.py, lines 375–400

Basin-entry support loss

Stage two uses the student's top-32 support and the teacher supports. On the student's support we mix the routed teacher log-probability with a small detached copy of the current student distribution, form a detached advantage, and apply asymmetric dual clipping to the live-to-old probability ratio. The same skewed mixture is used for the sampled tail, so tokens absent from the support still receive a residual update.

For a teacher-support token , let be the student's old probability, the teacher probability, and . We add a teacher-specific correction only inside the teacher's under-covered basin:

The correction is a support cross-entropy difference between the partially admitted teacher distribution and its detached optimum. It is weighted by and by a Monte-Carlo factor that grows when the routed teacher mass captured by the student's support is small. Once the old student probability reaches , the correction is exactly off; the ordinary clipped objective then sharpens a mode without continually amplifying it.

    loss_retaco = torch.zeros_like(loss_head)
    for m in range(M):
        t_key = f"teacher_{m}"
        if t_key not in ctx.support or t_key not in ctx.support_logp:
            continue
        sup_m = ctx.support[t_key]
        tlp_m = sup_m.teacher_lp[m].float()
        q_m = tlp_m.exp()
        slp_m = ctx.support_logp[t_key].float().clamp(min=-30.0)
        p_m_old = slp_m.detach().exp()

        alpha_m = (1.0 - 2.5 * p_m_old / q_m.clamp_min(1e-8)).clamp(0.0, 1.0).detach()
        qm_s = alpha_m * q_m
        Qm_s = qm_s.sum(dim=-1).clamp(0.0, 1.0 - 1e-4)
        Pm_s = (alpha_m * slp_m.exp()).sum(dim=-1).clamp(0.0, 1.0 - 1e-4)

        ce_head = -(qm_s * slp_m).sum(dim=-1) - (1.0 - Qm_s) * torch.log1p(-Pm_s)
        ce_opt = (-(qm_s * tlp_m).sum(dim=-1) - (1.0 - Qm_s) * torch.log1p(-Qm_s)).detach()
        loss_retaco = loss_retaco + w[..., m] * (ce_head - ce_opt)

    loss_tok = loss_head + loss_tail + lam_mc * loss_retaco
    loss_tok = torch.where(is_term, loss_tok * term_mult, loss_tok)
    return loss_tok * omega * ctx.mask.float()
Teacher-support basin-entry correction, support coverage factor, terminal multiplier, and specialist weighting in the loss. custom_routing.py, lines 455–477

The fixed pipeline's prompt selector and guided-draft hook remain unprovided, so each step uses the pool and rollout procedure supplied by the pipeline. All teachers score the same finished student completion in their own context. This makes the routing decision token-local while preserving the on-policy data contract and avoids treating an unreleased guided draft as training data.

Results

Method①②③④⑤⑥⑦
Accuracy ↑Accuracy ↑Accuracy ↑Accuracy ↑Accuracy ↑Accuracy ↑Accuracy ↑
Gemini 4 Carbon0.2890.2670.7150.6660.3490.4350.415
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

Our accuracy is above the strongest published baseline on AIME-HMMT25, Comp-2026, HEval+/MBPP+ and LiveCodeBench. On AIME-HMMT25, we obtain 0.289 versus 0.281 for TrustMOPD 1e-5 const; on Comp-2026, 0.267 versus 0.253 for TrustMOPD 1e-5 const. The same comparison is 0.666 versus 0.645 on HEval+/MBPP+, and 0.349 versus 0.346 on LiveCodeBench.

The advantage does not hold everywhere. On Math-std our accuracy is 0.715, below 0.719 from TrustMOPD 1e-5 const. On IFEval our accuracy is 0.435, below 0.448 from SEC [6]. On Multi-IF it is 0.415, below 0.468 from TrustMOPD 1e-5 const. These results are consistent with the method's emphasis on token-level evidence: it can combine complementary teacher signals, but it does not guarantee that the routed mixture is the best teacher on every distribution.

How we got here

The trace records a sequence of development runs in which we isolated failure modes before settling on the submitted file. We began from the starter's domain-label advantage, then added Fisher--Rao token features and reference-relative calibration so that a teacher could be useful outside its nominal domain. Early experiments exposed a termination problem: treating every truncated completion as an ordinary negative end-of-sequence example pushed the student toward the wrong stopping behaviour. We therefore added the truncation EMA, verifier guard, and trailing-whitespace check.

The next failure was unequal rollout leverage. Long completions supplied too many tokens and rarely selected teachers supplied too few, so we introduced sublinear length leverage and the share and gradient equalizers. A sharper support-coverage cutoff then suppressed the very teacher modes that the student needed to discover; the trace reports that this variant was abandoned in favour of the smooth basin-entry gate. A hierarchical trajectory router also misassigned some mixed-format trajectories to survival buckets, so we retained the simpler domain-indexed survival state and kept the Fisher--Rao hint check for cross-domain formatting.

We tested prompt selection as a separate hook and removed it after the trace found censoring feedback from changing the prompt mix. A within-domain inverse-censoring refinement likewise increased truncation in development. The final ablation retained the domain-hint trust term and the basin-entry correction, while leaving prompt selection and guided sampling off.

Limitations

  • The method depends on full-vocabulary log-probabilities to compute the Fisher--Rao features. That gives a richer signal than a sampled-token ratio, but it increases the work of every routing pass and may be impractical when those distributions are unavailable.

  • The teacher-support correction sees only the configured top-32 supports. Teacher probability outside those supports is represented through the sampled tail, so a mode that is neither sampled nor retained in a support cannot be discovered by this loss.

  • The routing posterior is calibrated by moving quantiles and several fixed constants. Its exponential averages and the domain-hint gate can lag after a distribution shift, and the method has no learned uncertainty model or convergence guarantee.

  • EOS handling assumes a usable tokenizer decoder and a verifier signal. Missing or noisy verification reduces the protection against right-censoring, while the whitespace heuristic is language- and tokenizer-dependent.

  • We leave the prompt and sampling hooks at their defaults. The method therefore does not exploit adaptive domain scheduling or teacher-guided token replacement, even though those are available surfaces in the pipeline.

  • The strongest baseline remains ahead on Math-std, IFEval and Multi-IF: our accuracies are 0.715, 0.435 and 0.415, versus 0.719, 0.448 and 0.468. The routing rule should therefore be treated as a distribution-dependent combination strategy rather than a universal improvement.

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. Xin Li, Hao Jiang, Xin Gao et al. (2026). Beyond Teacher Assignment: Domain-Normalized Multi-Teacher On-Policy Distillation.
  3. Tianze Xu, Yanzhao Zheng, Zhentao Zhang et al. (2026). MOPD-Router: Rethinking Teacher Routing in Multi-Teacher On-Policy Distillation.
  4. Jie Sun, Mao Zheng, Mingyang Song et al. (2026). Distill What You Trust: Reliability-Aware 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 Antigravity shows a conversation: 465 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