Skip to content

feat(mopd): add full-vocabulary on-policy distillation to SingleController - #3978

Merged
yfw merged 3 commits into
mainfrom
ruit/mopd_full_vocabulary_v2
Sep 10, 2026
Merged

yfw merged 3 commits into
mainfrom
ruit/mopd_full_vocabulary_v2

Conversation

@RayenTian

@RayenTian RayenTian commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

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 sit beside ChunkedDistributedEntropy and share one backward: for both weights, dw/dlog p_s is constant and cancels against the sum_v p_s = 1 normalization, leaving dL/dz = p_s * (w - L). Both recompute their log-softmaxes in backward rather than caching the teacher's, matching the neighbouring kernel.
  • 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 -- 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) are rejected at construction rather than silently ignored.

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 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 -- read an early failure as a question about the bound before assuming a regression. Adding the H100 run puts nightly.txt at 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.py x2, grpo_sync.py, ppo.py x2). 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 adds opd_full_reverse_kl_min / _max and opd_full_decomposition_error to that set, so it widens the exposure without creating it. Fix is to hoist the two sets into one shared definition in loss/interfaces.py, next to MetricNormalizer.

  • nemo_rl/models/megatron/train.py -- get_capture_context should be renamed get_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 pull draft/hidden_capture.py, draft/__init__.py and three @patch string paths in tests/unit/models/megatron/test_train.py into an unrelated feature's review.

Also still open from the first version, as noted above: exactly one teacher checkpoint, and the hidden_states path requires student pipeline_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

  • You can potentially add a usage example below
# Add a code snippet demonstrating how to use this

Before your PR is "Ready for review"

Pre checks:

  • Make sure you read and followed Contributor guidelines
  • Did you write any new necessary tests?
  • Did you run the unit tests and functional tests locally? Visit our Testing Guide for how to run tests
  • Did you add or update any necessary documentation? Visit our Document Development Guide for how to write, build and test the docs.

Additional Information

  • ...

@copy-pr-bot

copy-pr-bot Bot commented Sep 3, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@RayenTian
RayenTian force-pushed the ruit/mopd_full_vocabulary_v2 branch 2 times, most recently from efd042a to 244e69b Compare September 7, 2026 16:06
@RayenTian RayenTian added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Sep 7, 2026
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 244e69b

@RayenTian RayenTian changed the title feat(mopd): add full-vocabulary on-policy distillation to SingleContr… feat(mopd): add full-vocabulary on-policy distillation to SingleController Sep 7, 2026
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test aab07e8

@RayenTian
RayenTian force-pushed the ruit/mopd_full_vocabulary_v2 branch from aab07e8 to 062c7fc Compare September 8, 2026 01:40
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 062c7fc

@RayenTian
RayenTian marked this pull request as ready for review September 8, 2026 14:36
@RayenTian
RayenTian requested review from a team as code owners September 8, 2026 14:36
@RayenTian
RayenTian requested a review from yuki-97 September 8, 2026 15:30
@RayenTian
RayenTian force-pushed the ruit/mopd_full_vocabulary_v2 branch from 062c7fc to a166b44 Compare September 8, 2026 18:00
@RayenTian
RayenTian requested review from terrykong and yfw September 8, 2026 18:07
@RayenTian
RayenTian force-pushed the ruit/mopd_full_vocabulary_v2 branch from b4c4f6e to 0823c83 Compare September 8, 2026 21:09
@RayenTian
RayenTian requested a review from a team as a code owner September 8, 2026 21:09
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Sep 8, 2026
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 0823c83

Comment thread nemo_rl/algorithms/opd.py Resolved
RayenTian and others added 2 commits September 9, 2026 12:04
…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
RayenTian force-pushed the ruit/mopd_full_vocabulary_v2 branch from 0823c83 to 8603a46 Compare September 9, 2026 19:41
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 8603a46

@RayenTian
RayenTian requested a review from yfw September 9, 2026 22:14
Comment thread nemo_rl/models/megatron/train.py Resolved
Comment thread nemo_rl/algorithms/loss/utils.py Resolved
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
yfw enabled auto-merge (squash) September 10, 2026 06:46
@yfw

yfw commented Sep 10, 2026

Copy link
Copy Markdown
Contributor

/ok to test 318a77e

@yfw
yfw merged commit c49d53e into main Sep 10, 2026
94 checks passed
@yfw
yfw deleted the ruit/mopd_full_vocabulary_v2 branch September 10, 2026 08:10
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) Documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants