Skip to content

refactor(xtoken): move same-tokenizer KD math into shared helpers - #4721

Merged
yuki-97 merged 4 commits into
mainfrom
avenkateshha/xtoken-csd-same-tokenizer
Oct 27, 2026
Merged

yuki-97 merged 4 commits into
mainfrom
avenkateshha/xtoken-csd-same-tokenizer

Conversation

@avenkateshha

@avenkateshha avenkateshha commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Moves the same-tokenizer KD math out of CrossTokenizerDistillationLossFn into shared helpers in nemo_rl/algorithms/x_token/loss_utils.py, so other losses can reuse it. X-Token now calls the helpers. Apart from one lm_head-padding fix in the averaged_logits full-vocab path (see Behavior), losses and gradients are bitwise identical to the base.

Builds on #3286, which is now merged; this PR targets main. #4680 will be restacked on this branch and switched to the same helpers separately.

Changes

  • New same_tokenizer_topk_kl and same_tokenizer_full_vocab_kl in loss_utils.py. The KD mask, sample mask and global KD-token count are explicit keyword-only inputs, along with vocab_size, vocab_topk (top-K only), temperature, reverse_kl, tp_group and cp_group. Both helpers cut student and teacher to the shared tokenizer vocab vocab_size, dropping lm_head padding columns.
  • The top-K vocab list is unchanged: the per-vocab max over every teacher row (select_teacher_topk_indices, MAX-reduced across CP). The next-token-shifted KD mask times the sample mask is used only for the masked mean.
  • CrossTokenizerDistillationLossFn: _compute_same_vocab_kl and the averaged_logits fast path now call the helpers. They pass align.student_token_mask as the KD mask, global_valid_toks as the KD-token count and self.student_vocab_size (len(student_tokenizer)) as vocab_size. _direct_topk_kl, _direct_full_vocab_kl and _same_vocab_masked_kl are removed.
  • Docs: vocab_topk is documented as used by same-tokenizer teachers too, not P-KL only (config field doc, both X-Token exemplar configs, and the guide).

Behavior

No change, with one exception: the averaged_logits full-vocab path now drops the student's lm_head padding columns (ids past len(student_tokenizer)), as the top-K path already did. This changes the loss only for kd_loss_mode: averaged_logits with all same-tokenizer teachers and a student whose lm_head is wider than its tokenizer (for example a Qwen student). No shipped X-Token config or nightly uses that combination.

Everything else, including every student without lm_head padding, is bitwise identical to the base for any KD and sample mask. Cross-tokenizer P-KL / gold paths, configs and entry points are unchanged.

Testing

CPU runs in the NeMo-RL container:

  • tests/unit/algorithms/x_token/ and tests/unit/algorithms/test_loss_functions.py: 531 passed, 49 skipped (48 GPU-only, 1 existing parametrization skip), 0 failed. On main at the base commit: 273 passed, 49 skipped.
  • New tests in tests/unit/algorithms/x_token/test_loss_utils.py:
    • Bitwise parity of loss and gradient with a frozen copy of the previous math, for any KD and sample mask (students without lm_head padding): fp32/bf16 teacher, with and without lm_head padding, K below, at and above the vocab, T in {1, 2}, forward and reverse KL. The full-vocab path is checked the same way.
    • Forward and reverse KL, top-K and full-vocab paths, against a float64 reference.
    • Normalization by the given KD-token count, and lm_head-padding slicing.
    • A student with lm_head padding gives the same full-vocab loss and gradient as the same student without it (zero gradient on the padding columns), and matches the top-K helper when K covers the vocab.
    • A CP=2 gloo test: both ranks choose the single-process top-K list, including a column that wins only on rank 1; the CP-aware next-token shift reads across the rank boundary; and the per-rank losses and gradients sum to the single-process result.
  • test_chat_eot_supervision.py: X-Token's _compute_same_vocab_kl forwards temperature / reverse_kl / vocab_topk and the masks to the helper.
  • test_xtoken_off_policy_distillation.py: the averaged_logits fast path forwards temperature / reverse_kl / vocab_size and the masks to the helper.
  • One-off check against the base commit, whose same-tokenizer code is identical to main's (students without lm_head padding): 18,432 single-process and 3,744 per-rank CP=2 / TP=2 gloo comparisons of loss, student gradient and kl_loss are all bitwise identical. The TP=2 full-vocab case needs Megatron and could not run on CPU; that code path is unchanged.
  • ruff (all three pre-commit hooks) is clean. pyrefly reports no new errors.

GPU tests and the multi-teacher nightly were not re-run for this revision.

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? (CPU unit tests; GPU tests not re-run for this revision)
  • Did you add or update any necessary documentation? (vocab_topk field doc, X-Token exemplar config comments, and docs/guides/xtoken-off-policy-distillation.md)

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 14, 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.

@avenkateshha avenkateshha left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Multi-agent review (RL expert, two bug-finders, test agent, design reviewer, devil's-advocate verification, completeness critic). Every claim below was reproduced on CPU in the NeMo-RL container.

Confirmed. Both bitwise-parity claims match the base implementation: 576/576 loss and grad cases equal on each of the top-K and full-vocab paths. The CP=2 path and a 4-rank TP2×CP2 gloo check of same_tokenizer_topk_kl agree with single-process references. x_token/ + test_loss_functions.py give 395 passed, 48 skipped. The ruff hooks are clean, and pinned pyrefly shows no new errors.

4 inline comments: a memory regression in the masked top-K picker (introduced by this PR), a forwarding test gap on the averaged_logits path (introduced by this PR), the same_tokenizer_full_vocab_kl docstring, and the vocab_topk field doc (predates this PR).

Generated by Claude Code

@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-csd-same-tokenizer branch from 2b871b8 to fef7b51 Compare October 15, 2026 21:10
@avenkateshha avenkateshha changed the title feat(xtoken): share same-tokenizer KD helper; top-K from KD positions only refactor(xtoken): move same-tokenizer KD math into shared helpers Oct 15, 2026
@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-offset-alignment branch from ca90d1d to fc7fc7f Compare October 15, 2026 21:36
@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 15, 2026
@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-csd-same-tokenizer branch from 451625c to ddd556f Compare October 16, 2026 08:47
@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-offset-alignment branch from 67455e9 to 78d75bc Compare October 19, 2026 09:53
@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-csd-same-tokenizer branch from 447cc5a to 75d5b8b Compare October 19, 2026 10:52
@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-offset-alignment branch from 78d75bc to 6f6df9f Compare October 20, 2026 10:12
Base automatically changed from avenkateshha/xtoken-offset-alignment to main October 21, 2026 06:32
@RayenTian

RayenTian commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Hi, @avenkateshha. Would you please rebase this PR and solve the conflicts. Now it mixes in some previous commits. Thanks a lot.

avenkateshha and others added 4 commits October 26, 2026 00:34
Move the same-tokenizer KD math out of CrossTokenizerDistillationLossFn
into nemo_rl/algorithms/x_token/loss_utils.py so other losses can reuse
it:

- same_tokenizer_topk_kl / same_tokenizer_full_vocab_kl take the KD mask,
  sample mask and global KD-token count as explicit keyword arguments.
- The top-K vocab list is unchanged: the per-vocab max over every teacher
  row (select_teacher_topk_indices), MAX-reduced across CP.

X-Token passes its token_mask as the KD mask and global_valid_toks as
the KD-token count. _direct_topk_kl, _direct_full_vocab_kl and
_same_vocab_masked_kl are removed; _compute_same_vocab_kl and the
averaged_logits fast path call the shared helpers. Losses and gradients
are bitwise identical to before for any KD and sample mask.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
The averaged_logits fast path passes temperature, reverse_kl, the KD and
sample masks and the KD-token count to same_tokenizer_full_vocab_kl
explicitly. Its test stubbed the helper without looking at the
arguments, so hard-coding reverse_kl=False or temperature=1.0 at the
call site went unnoticed. Record the stub's keyword arguments and check
them against non-default values.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
…b KD

same_tokenizer_full_vocab_kl sliced the teacher to the student logits
width, so columns that a student lm_head pads past the tokenizer vocab
stayed in both softmaxes, while same_tokenizer_topk_kl already drops
them via vocab_size. Give the full-vocab helper the same vocab_size
argument: cut student and teacher to it and renormalize the student.
The averaged_logits fast path passes len(student_tokenizer).

Only kd_loss_mode=averaged_logits with same-tokenizer teachers and a
padded student (e.g. Qwen) changes; unpadded students are bitwise
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
vocab_topk was documented as P-KL only and inert when gold_loss=True,
but every same-tokenizer teacher uses it for its top-K KL whatever
gold_loss is; only the all-same-tokenizer averaged_logits path uses the
full vocab. Update the CrossTokenizerDistillationLossConfig field doc,
the vocab_topk comments in both X-Token exemplar configs and the guide,
which also described the multi-teacher example's same-tokenizer teacher
as a full-vocab KL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-csd-same-tokenizer branch from 75d5b8b to 6c27c72 Compare October 26, 2026 07:48
@avenkateshha

Copy link
Copy Markdown
Contributor Author

@RayenTian Thanks! Rebased onto main now that #3286 is merged. The old #3286 commits are gone and the conflicts are resolved, so the PR shows only its own 4 commits (head 6c27c72) and is mergeable. The unit tests pass locally on the rebased branch. #4728, which is stacked on this PR, is restacked as well.

@RayenTian RayenTian left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM.

@RayenTian RayenTian added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Oct 27, 2026
@RayenTian

Copy link
Copy Markdown
Contributor

/ok to test 6c27c72

@yuki-97
yuki-97 merged commit 00d9f6d into main Oct 27, 2026
97 checks passed
@yuki-97
yuki-97 deleted the avenkateshha/xtoken-csd-same-tokenizer branch October 27, 2026 16:48
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