Repository navigation
feat(mopd): add full-vocabulary on-policy distillation to SingleController - #3978
Merged
Merged
Conversation
RayenTian
force-pushed
the
ruit/mopd_full_vocabulary_v2
branch
2 times, most recently
from
September 7, 2026 16:06
efd042a to
244e69b
Compare
Contributor
Author
|
/ok to test 244e69b |
Contributor
Author
|
/ok to test aab07e8 |
RayenTian
force-pushed
the
ruit/mopd_full_vocabulary_v2
branch
from
September 8, 2026 01:40
aab07e8 to
062c7fc
Compare
Contributor
Author
|
/ok to test 062c7fc |
RayenTian
marked this pull request as ready for review
September 8, 2026 14:36
RayenTian
force-pushed
the
ruit/mopd_full_vocabulary_v2
branch
from
September 8, 2026 18:00
062c7fc to
a166b44
Compare
RayenTian
force-pushed
the
ruit/mopd_full_vocabulary_v2
branch
from
September 8, 2026 21:09
b4c4f6e to
0823c83
Compare
Contributor
Author
|
/ok to test 0823c83 |
yfw
reviewed
Sep 9, 2026
…oller
Adds `on_policy_distillation.full`, which replaces MOPD's sampled-token
log-probability gap with the exact full-vocabulary reverse KL
L_t = sum_v p_student(v) * (log p_student(v) - log p_teacher(v))
This is the K=V limit of the top-k MOPD estimator: with the support spanning
the whole vocabulary the score-function tail term vanishes, so the objective is
exact, deterministic, and free of that estimator's off-policy bias.
Because the loss now needs the teacher's whole distribution rather than one
scalar per token, the teacher/student boundary changes. Two payload paths are
supported, selected by `full.teacher_payload`:
* `hidden_states` (default): the teacher ships its pre-LM-head hidden states and
the student projects them with an output-layer weight shard loaded from the
teacher checkpoint. The payload is hidden_size wide, so teacher and student
parallelism stay fully decoupled.
* `logits`: the teacher ships full-vocabulary logits and the student needs no
teacher LM head. The payload is vocab_size wide -- roughly 74x larger for a
2k-hidden / 152k-vocab model -- so this is a numerical-reference and fallback
path, not a production configuration.
Implementation notes:
* Two chunked tensor-parallel autograd functions share one backward with the
existing ChunkedDistributedEntropy, which is folded onto the same helper: for
every weight, dw/dlog p_s is constant and cancels against the sum_v p_s = 1
normalization, leaving dL/dz = p_s * (w - L). Verified against autograd at
TP=1 and, under real process groups, at TP=2.
* The reconstruction and divergence run in prepare_loss_input, the only place
holding the vocab- and context-parallel groups; the loss receives a plain
[B, S-1] differentiable tensor and reduces it the same way the policy-gradient
path does, including the nested per-sequence average under
token_level_loss=false.
* Teacher hidden states are captured with a forward pre-hook on `output_layer`
rather than a Megatron fork. Sequence parallelism shards that input, so the
capture gathers it back over the layer's own tp_group -- without this a TP=1
run passes while TP>1 is silently wrong.
* The payload rides a new per-token TransferQueue column, written from the
pipeline stage that produced it rather than broadcast back to the replica
leader, which for a per-token payload would move gigabytes for nothing.
* The teacher LM-head shard is a plain tensor on the worker, so it stays
invisible to checkpoint saving and to HF/vLLM refit conversion. Its checkpoint
path is resolved from the teacher's own model name: TeacherWorkerGroup copies
the student policy config wholesale, so a student `pretrained_checkpoint`
would otherwise win and the student would be distilled into itself.
* Loss knobs with no code path under this objective (ratio clipping, CISPO,
importance-sampling correction, truncated IS, VAPO, use_kl_in_reward) are
rejected at construction rather than silently ignored, as is enabling the
feature on the legacy GRPO entry point, which never reads it.
* `validate_decomposition` is available but off: the entropy/cross-entropy
residual is an algebraic identity -- all three kernels read the same logits --
so a corrupted teacher cancels out of it. Measured across seven corruptions it
stays under 1e-6 while the divergence itself moves to 0.6-1.7.
First version limits: exactly one teacher checkpoint, and the hidden-state path
additionally requires student pipeline_model_parallel_size=1, because Megatron
builds output_layer only on the last pipeline stage while the LM-head load is a
whole-world collective (mcore does not plumb a process group into its
dist-checkpoint load). The `logits` path has no such restriction. The payload
column is shaped so a per-row teacher index can be added later without reworking
it.
Ships two Qwen3-1.7B self-distillation recipes whose divergence must sit at ~0:
an H100 3n8g one in nightly.txt (10 GPU-hours) and its GB200 3n4g variant in
nightly_gb200.txt (5 GPU-hours). Their thresholds are smoke bounds derived from
the objective rather than measured, so the first runs are also what validate
them. Adding the H100 run puts nightly.txt at 4354 GPU-hours, so its budget
assertion moves 4344 -> 4360.
Also included: unit coverage for the two divergence kernels (forward against a
closed-form reference, the hand-written backward against autograd at TP=1 and
TP=2, chunk invariance, and a collective trace that pins the teacher-side
normalization), for the teacher-payload reconstruction, for the
loss-construction rejection matrix and reduction semantics, and for the first
3-D token-aligned data-plane column; plus user documentation in
docs/about/algorithms/mopd.md.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Signed-off-by: ruit <[email protected]>
Three correctness fixes: - Reject teacher_payload='hidden_states' for teachers that transform their logits after output_layer (Gemma2/Gemma4 final_logit_softcapping, MuseGlimmer output_multiplier, MuP). The student rebuilds teacher logits as output_layer(h), so those teachers were silently mis-reconstructed. - Weight the opd_full reference KL by exp(x - x.detach()), matching the policy-gradient branch. The penalty is a one-sample estimate, so its gradient needs the score-function term; the forward value is unchanged. - Drop the student's pretrained_checkpoint in TeacherWorkerGroup rather than only for the LM-head load. It rode along on the copied policy config, so the teacher loaded the student's weights while the LM head came from the real teacher. Also: name read_train_state as the collective behind the PP=1 restriction in both error messages, copy the teacher payload to CPU per microbatch and release the GPU copy, remove a call-site temperature default, stop re-deriving the lm-head lifecycle default, tighten the chunk_size annotation, and complete the rejected-knob list, __call__ docstring, and weight_fn precondition in the docs. Adds 13 unit tests over the payload guard, the reference-KL gradient, the config sanitizer, prepare_opd_full_loss_input, the backward TP reduction, bf16 normalization, teacher payload routing, LM-head loading, and the data-plane payload column. Signed-off-by: ruit <[email protected]>
RayenTian
force-pushed
the
ruit/mopd_full_vocabulary_v2
branch
from
September 9, 2026 19:41
0823c83 to
8603a46
Compare
Contributor
Author
|
/ok to test 8603a46 |
pjin-nvidia
reviewed
Sep 10, 2026
pjin-nvidia
reviewed
Sep 10, 2026
Three narrowing fixes on the opd_full payload path, none of which the divergence kernel's chunk_size could bound: - Move each microbatch's payload to CPU inside the forward schedule. mcore retains every microbatch's output dict until the whole schedule completes, so returning a device tensor accumulated the entire data-parallel shard's payload rather than one microbatch's; lowering the microbatch size did not help. - Take this rank's context-parallel sequence window before projecting the hidden states, not after. Projecting first did cp_size times the matmul and allocated a full-sequence [B, S, V_local] tensor. - Slice the vocabulary window and make the payload contiguous before the device copy. The slice is a view, and the result is handed to save_for_backward, so the whole-vocabulary payload storage stayed resident until backward completed. Adds a test pinning that the projection sees the context-parallel window rather than the full sequence -- the two orderings are numerically identical, so only the shape handed to the matmul distinguishes them. Signed-off-by: ruit <[email protected]>
yfw
approved these changes
Sep 10, 2026
yfw
enabled auto-merge (squash)
September 10, 2026 06:46
Contributor
|
/ok to test 318a77e |
This was referenced Sep 10, 2026
2 of 4 tasks
RayenTian
added a commit
that referenced
this pull request
Sep 11, 2026
Squashes four commits from this branch's iteration on top of #3978's opd_full feature: - Multiple teacher checkpoints on the hidden_states path: each physical teacher gets a stable index (OPD_FULL_TEACHER_INDEX_FIELD), the student loads one LM-head shard per teacher, and a microbatch's rows are grouped by teacher_index and projected through the matching shard. - Student pipeline parallelism on the hidden_states path: earlier PP stages hold no teacher LM-head shard (only the last stage runs the loss), but still join the whole-world dist_checkpointing.load collective with an empty sharded request so the collective stays balanced. - Review-finding fixes: repaired 16 test-double failures the teacher_index plumbing left behind, raised instead of silently falling through to the single-teacher projection when a routing column is missing, fixed pipeline-rank-asymmetric eviction tracking, and caught heterogeneous teacher hidden sizes/dtypes at load time instead of an opaque jagged- collate error later. - Rebuilt the multi-teacher routing after a silent rebase-onto-main conflict: main reordered reconstruct_opd_full_teacher_logits into validate -> narrow -> project (so the LM-head matmul only ever sees this rank's CP window), but this branch's multi-teacher commits were written against the older project-then-narrow order and the rebase merged both textually into an incoherent function. Kept main's order and slotted the routing checks into the validate phase. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Co-Authored-By: Claude Sonnet 5 <[email protected]> Signed-off-by: ruit <[email protected]>
4 tasks
4 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds
on_policy_distillation.full, which replaces MOPD's sampled-token log-probability gap with the exact full-vocabulary reverse KLThis is the K=V limit of the top-k MOPD estimator: with the support spanning the whole vocabulary the score-function tail term vanishes, so the objective is exact, deterministic, and free of that estimator's off-policy bias.
Because the loss now needs the teacher's whole distribution rather than one scalar per token, the teacher/student boundary changes. Two payload paths are supported, selected by
full.teacher_payload:hidden_states(default): the teacher ships its pre-LM-head hidden states and the student projects them with an output-layer weight shard loaded from the teacher checkpoint. The payload is hidden_size wide, so teacher and student parallelism stay fully decoupled.logits: the teacher ships full-vocabulary logits and the student needs no teacher LM head. The payload is vocab_size wide -- roughly 74x larger for a 2k-hidden / 152k-vocab model -- so this is a numerical-reference and fallback path, not a production configuration.Implementation notes:
output_layerrather than a Megatron fork. Sequence parallelism shards that input, so the capture gathers it back -- without this a TP=1 run passes while TP>1 is silently wrong.pretrained_checkpointwould otherwise win and the student would be distilled into itself.First version limits: exactly one teacher checkpoint, and the hidden-state path additionally requires student pipeline_model_parallel_size=1, because Megatron builds output_layer only on the last pipeline stage while the LM-head load is a whole-world collective -- earlier stages would fail while the last stage hangs. The
logitspath has no such restriction. The payload column is shaped so a per-row teacher index can be added later without reworking it.Ships two Qwen3-1.7B self-distillation recipes whose divergence must sit at ~0: an H100 3n8g one in
nightly.txt(10 GPU-hours) and its GB200 3n4g variant innightly_gb200.txt(5 GPU-hours). Their thresholds are smoke bounds derived from the objective rather than measured, so the first runs are also what validate them -- read an early failure as a question about the bound before assuming a regression. Adding the H100 run putsnightly.txtat 4354 GPU-hours, so its budget assertion moves 4344 -> 4360 (test_nightly_compute_stays_below_4360_hours).Also included: unit coverage for the two divergence kernels (forward against a closed-form reference, the hand-written backward against autograd, chunk invariance, and a collective trace that pins the teacher-side normalization TP=1 cannot observe), for the teacher-payload reconstruction, for the loss-construction rejection matrix and reduction semantics, and for the first 3-D token-aligned data-plane column.
Known follow-ups
Two TODOs are left in the code deliberately; neither blocks this PR and both are cheap to pick up separately.
nemo_rl/algorithms/loss/wrapper.py-- the extremum-metric name sets (_SEQ_METRIC_MIN/_SEQ_METRIC_MAX) are duplicated across seven sites (here,single_controller_utils/utils.py,grpo.pyx2,grpo_sync.py,ppo.pyx2). The rule is level-independent, so every copy should hold the same names, but nothing enforces that: a loss that emits a new extremum metric has to update every site its path reaches, and omitting one silently sums extrema instead of reducing them, reporting a "min" larger than any individual value. This PR addsopd_full_reverse_kl_min/_maxandopd_full_decomposition_errorto that set, so it widens the exposure without creating it. Fix is to hoist the two sets into one shared definition inloss/interfaces.py, next toMetricNormalizer.nemo_rl/models/megatron/train.py--get_capture_contextshould be renamedget_draft_capture_context. It is draft-model-specific, but standing next to the new opd_full capture the unqualified name now reads as the generic one. Not renamed here because it would pulldraft/hidden_capture.py,draft/__init__.pyand three@patchstring paths intests/unit/models/megatron/test_train.pyinto an unrelated feature's review.Also still open from the first version, as noted above: exactly one teacher checkpoint, and the
hidden_statespath requires studentpipeline_model_parallel_size=1. The payload column is already shaped so a per-row teacher index can be added without reworking it.What does this PR do ?
Add a one line overview of what this PR aims to accomplish.
Issues
List issues that this PR closes (syntax):
Usage
# Add a code snippet demonstrating how to use thisBefore your PR is "Ready for review"
Pre checks:
Additional Information