Skip to content

feat(xtoken): support TP/CP/diff-DP sharded cross-tokenizer distillation - #2745

Merged
yuki-97 merged 5 commits into
mainfrom
ruit/xtoken-tp-cp
Jun 25, 2026
Merged

yuki-97 merged 5 commits into
mainfrom
ruit/xtoken-tp-cp

Conversation

@RayenTian

@RayenTian RayenTian commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Adds TP / CP / heterogeneous-DP sharding support to the cross-tokenizer (xtoken) off-policy distillation loss (P-KL + gold) on the DTensor v2 worker, fixes a context-parallel loss-invariance bug, and adds a parallelism-invariance nightly.

Issues

Closes #2682

Following:

  1. feat(xtoken): auto-build the cross-tokenizer projection matrix on the fly (online) #2792 (Make building the (student, teacher) projection matrix inflight )
  2. xtoken cross-tokenizer distillation: teacher→student logit IPC transport is node-local (no multi-node support) #2927 (Multi node support)

Result

Teacher : Qwen/Qwen3-4B TP2 CP2 DP2
Student : meta-llama/Llama-3.2-1B TP4 CP2 DP1

KL Loss

image

Gold Loss

image

XT Loss

image

Usage

# 1. Build the (student, teacher) projection matrix from the tokenizer pair (one-time, offline) -> writes <output-dir>/<output-filename>_special.pt.
uv run python -m tools.x_token.minimal_projection_via_multitoken --student-model meta-llama/Llama-3.2-1B --teacher-model Qwen/Qwen3-4B --top-k 4 --enable-special-token-mapping --enable-exact-match --disable-reverse-pass --disable-scale-trick --output-filename xtoken_proj --output-dir /tmp/xtoken_proj
# 2. Distill: student TP4×CP2 from a teacher running TP2×CP2 (heterogeneous layout); the loss stays parallelism-invariant across TP/CP/DP.
uv run examples/run_xtoken_off_policy_distillation.py --config examples/configs/recipes/llm/xtoken-off-policy-distillation-qwen3-4b-to-llama3.2-1b-1n8g-dtensor-tp4cp2.yaml loss_fn.projection_matrix_path=/tmp/xtoken_proj/xtoken_proj_special.pt
# key knobs: policy.dtensor_cfg.{tensor_parallel_size=4,context_parallel_size=2}, teacher.dtensor_cfg.{tensor_parallel_size=2,context_parallel_size=2}

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 Jun 9, 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/xtoken-tp-cp branch from cb37de4 to 1537d7d Compare June 9, 2026 14:32
@RayenTian
RayenTian force-pushed the ruit/xtoken-tp-cp branch from 1537d7d to bbe782f Compare June 10, 2026 04:57
@RayenTian
RayenTian force-pushed the ruit/xtoken-tp-cp branch from 39cf1b2 to 5185829 Compare June 11, 2026 02:36
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 17bec2f

@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test b02211f

@yuki-97 yuki-97 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.

thanks @RayenTian , nice work!

Comment thread nemo_rl/distributed/model_utils.py Resolved
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 1513dd6

yuki-97
yuki-97 previously approved these changes Jun 23, 2026

@yuki-97 yuki-97 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, @terrykong could you take a look as well?

@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 18ebb7f

@terrykong terrykong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks @RayenTian — this is a substantial, well-structured extension (heterogeneous TP/CP/DP teacher to student, CUDA-IPC shard transport, CP-aware loss reductions) with loss-invariance curves and a dedicated parallelism-invariance nightly. Reviewed by a team of agents (RL/loss, distributed bug-finder, tests, comment threads) with leader verification; local unit tests pass here including the 2-GPU NCCL helper tests.

One higher-priority item to confirm (KL-vs-CE normalization scope under student TP>1) plus three minor suggestions, all inline. No open threads.

Generated by Claude Code

Comment thread nemo_rl/models/policy/lm_policy.py Resolved
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test ca46ce9

@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 0cffdaa

RayenTian and others added 5 commits June 24, 2026 17:28
Extend cross-tokenizer off-policy distillation to run with the student under
tensor- and context-parallelism (and a data-parallel degree that may differ
from the teacher's) on the automodel/DTensor policy worker.

- Teacher full-vocab logits are exported per rank and shipped to the student
  via CUDA IPC (FullLogitsPostProcessor), then reassembled on the consumer
  across its CP group for heterogeneous teacher/student TP/CP layouts.
- The loss runs TP/CP-aware: vocab-parallel log-softmax / argmax / projection,
  CP load-balanced -> contiguous re-layout, CP-aware next-token shift, and
  partial chunk-average + grad-preserving all-reduce. The generic collectives
  live in model_utils; the cross-tokenizer orchestration in x_token/loss_utils.
- TP/CP process groups are derived from the student logits' own device mesh
  instead of being threaded through the generic LossPostProcessor, so the
  SFT / GRPO / distillation LOGPROB paths keep using the DTensor branch.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: ruit <[email protected]>
…on nightly

- Unit tests for the TP/CP/diff-DP setup grid and the vocab-/CP-parallel loss
  helpers (real 2-GPU NCCL actors), plus per-step IPC buffer release. Adds the
  x_token unit-test package __init__.py so the Ray actor FQN is importable.
- Nightly recipe distillation-xtoken-off-policy-qwen3-4b-to-llama3.2-1b-1n8g-
  dtensor-tp4cp2 (student TP4xCP2 <- teacher TP2xCP2) and its driver, wired into
  nightly.txt; guards sharded-loss parallelism-invariance.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: ruit <[email protected]>
…r cleanups

Resolves the review comments on PR #2745:

- next_token_accuracy was biased at CP>1: it fed raw load-balanced
  logits/input_ids/token_mask into cp_shift_next (which assumes a contiguous
  CP layout). prepare_xtoken_cross_tokenizer_loss_input now relays the student
  input_ids/token_mask to contiguous and stashes them on LocalizedAlignment;
  the call site reuses student_logits_contig + those fields. Verified
  CP-invariant end-to-end (CP1 vs CP2 accuracy match).
- student_next_token_ce DTensor branch double-dropped the last position
  ([B,T-2] vs the local branch's [B,T-1]); get_logprobs_from_vocab_parallel_logits
  already drops the CP-roll wrap-around, so the extra [:, :-1] is removed.
- Renamed dp_all_reduce_sum -> group_all_reduce_sum and added an explicit
  group= param; it reduces over WORLD (DP×CP×TP) by default, not DP.
- Fixed a missing Optional import in policy/utils.py that broke import of
  ensure_teacher_ipc_buffer.
- ensure_teacher_ipc_buffer is now called unconditionally (drop the
  if-storage-is-None guard); its needs_realloc logic subsumes the first-call
  case and microbatch shapes are constant within a get_full_logits_ipc call.
- Added a cp_size=2/rank=1 zero-copy fastpath test that exercises the
  seq-offset slice (the cp_size=1 case can't catch a dropped offset).
- Docstring fixes: localize_alignment (load-balanced, not contiguous) and the
  module-level group_all_reduce_sum cross-reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: ruit <[email protected]>
…s/test cleanups

- Unify the TP/CP SUM all-reduce helpers behind one autograd primitive
  (`_AllReduceSum`) with two named wrappers: `group_all_reduce_sum_with_grad`
  (differentiable; numerator reductions) and `group_all_reduce_sum` (no-grad;
  normalizers). Make the KL denominator's WORLD scope and float32 cast explicit
  at the call sites in loss_functions.py.
- Keep the xtoken P-KL/gold KL denominator reduced over WORLD: the numerator is
  TP/CP-replicated (projection + chunk-average all-reduces), so the WORLD count
  cancels that replication. Verified parallelism-invariant via a student-TP1 vs
  student-TP4 overlay (DP×CP-only normalization over-weights KL by tp_size).
- Make `val_teacher_micro_batch_size` a required field and default it to
  `teacher.train_micro_batch_size` via exemplar interpolation instead of a hidden
  call-site fallback (setup + validate read it directly).
- `assemble_teacher_logits_from_shards`: assert full_seq_len is divisible by the
  student CP size, and add a CPU TP2×CP2 reassembly unit test (monkeypatched IPC).
- Fix the stale `get_full_logits_ipc` driver-side docstring and document the
  post-construction `LocalizedAlignment.student_input_ids/token_mask` fields.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: ruit <[email protected]>
The teacher->student logit transport uses node-local CUDA IPC
(`cudaIpcOpenMemHandle` only maps buffers created on the same host), so a
multi-node run is only safe when every student rank's teacher shards live on
its own node. Add `assert_xtoken_ipc_node_local` (in x_token/utils.py) and call
it from `setup()`: single-node is always allowed; >1 node requires teacher and
student to share the data_parallel degree and a node-aligned model-parallel
group (`tp*cp` equal, `<= gpus_per_node`, and dividing `gpus_per_node`).
Otherwise it fails fast with a clear message instead of crashing mid-validation
with `cudaErrorMapBufferObjectFailed`. Add CPU unit tests for the pass case and
each failure mode.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: ruit <[email protected]>
@RayenTian

Copy link
Copy Markdown
Contributor Author

/ok to test 75e43f9

@qiaochuz-nv

Copy link
Copy Markdown
Contributor

RL POR Test Summary — NVIDIA-NeMo/RL PR #2745

feat(xtoken): support TP/CP/diff-DP sharded cross-tokenizer distillation

Result: ✅ PASS

Field Value
Testcase test_xtoken_off_policy_distillation_basic (suite rl, tier function, 8 GPU)
run_id 20260629T210828Z-963551a9
SLURM job 5531857
host ipp2-1658
cluster eos (coreai_dlalgo_ci)
duration 353s
exit_code 0
summary.json status passed
container nemo-rl-nightly-20260629.sqsh
pinned merge SHA 9e6c2d5ffe25296bbd70e7e4926957e8a894f0a9
commit e23cd89 on qiaochuz/por_2745_xtoken (DLQASH/nmfw_tests)

What this PR adds (feature surface under test)

PR #2745 introduces off-policy cross-tokenizer distillation where the student
and teacher use different tokenizers AND different parallelism layouts, with
the distillation loss computed identically (parallelism-invariant) across
mismatched TP/CP/DP sharding. New code surface:

  1. Product entrypoint — examples/run_xtoken_off_policy_distillation.py
    • Enforces the cross-tokenizer contract: distinct policy/teacher tokenizers
      • a non-null projection_matrix_path.
  2. Shipped recipe (heterogeneous layout) —
    examples/configs/recipes/llm/distillation-xtoken-off-policy-qwen3-4b-to-llama3.2-1b-1n8g-dtensor-tp4cp2.yaml
    • student Llama-3.2-1B sharded TP4×CP2
    • teacher Qwen3-4B sharded TP2×CP2
    • differing DP across student/teacher (diff-DP) on one 8-GPU node
    • mixed-KL cross-tokenizer loss (loss_fn.projection_matrix_path)
  3. Projection-matrix build tool — tools/x_token/build_projection_matrix.sh
    • Constructs the (student-vocab × teacher-vocab) token-alignment projection
      matrix that maps teacher logits into student token space.

What the test exercises (step by step)

Step 1 — Projection matrix build (PR tool):
Runs build_projection_matrix.sh for (student Llama-3.2-1B, teacher Qwen3-4B),
runtime-top-k 4. Asserts the .pt artifact is produced.
→ Observed: 128×256 projection built, 0.05% rounding; BOTH directions ran
(student→teacher pass + teacher→student pass).

Step 1.5 — Offline dataset staging:
Materializes nvidia/Nemotron-Pretraining-Specialized-v1.1
(Nemotron-Pretraining-Formal-Logic/part_000000.parquet) via named-file
hf_hub_download, rewrites data.train.data_files to a LOCAL glob so the
recipe's hf://...*.parquet wildcard doesn't hit the Hub under HF_HUB_OFFLINE=1.

Step 2 — Heterogeneous cross-tokenizer distillation (the feature):
Drives the SHIPPED recipe through the new entrypoint. Overrides limited to:
projection_matrix_path (required), local data glob, and CI-shrink knobs
(max_num_steps=3, val_period=3, seq_len=256). The feature-defining knobs —
TP4/CP2 student, TP2/CP2 teacher, diff-DP, mixed-KL loss config — are inherited
unchanged from the recipe, so the heterogeneous sharded loss path the PR adds
is genuinely exercised.

Step 3 — Metric extraction + smoke assertion:
Dumps TB logs → metrics.json, then asserts the cross-tokenizer loss produced a
finite train/loss at the final step.


Assertions & evidence (stdout.log lines 1331–1332)

PASS  data["train/loss"]["3"] > 0.0      → 2.6068239212036133
PASS  data["train/loss"]["3"] < 1000.0   → 2.6068239212036133

(validation/loss 2.58722, validation/kl_loss 0.0707011 at step 3)

Policy: presence + finiteness only — NOT a distillation-gain claim (3 steps is
far too short to assert convergence).


What is / isn't covered

Covered:

  • New entrypoint end-to-end on the shipped heterogeneous recipe
  • Projection-matrix build tool (both alignment directions)
  • Cross-tokenizer mixed-KL loss across TP4/CP2 ↔ TP2/CP2 + diff-DP
  • train + validation forward/backward over 3 steps, finite loss

NOT covered (out of scope for a function-tier smoke):

  • Convergence / distillation-quality gain
  • Multi-node (e2e tier) scaling of the same layout
  • Alternative TP/CP combinations or other model pairs

Guards (false-signal protection)

  1. Source-level (quoted heredoc): SKIP if entrypoint / recipe / build tool
    absent, or if entrypoint no longer references projection_matrix_path.
  2. Runtime cherry-pick: pins PR merge SHA 9e6c2d5 → clean SKIP if a checkout
    predates the merged behavior.

Both → clean SKIP (exit 0), never a false PASS/FAIL.

CI-shrink (within policy): only step count + seq length reduced; disk-precheck
fix is env-only (HF_DATASETS_CACHE → tmpfs). Feature knobs untouched.

RCA note: runs 1–4 failed on infra only (offline-cache / disk-precheck), NOT PR
defects; run 5 is the clean green after the tmpfs fix. ~2.5h delay was eos scheduler
congestion, not a test issue.


Artifacts

  • stdout.log — …/logs/20260629T210828Z-963551a9/tests/test_xtoken_off_policy_distillation_basic/stdout.log
  • summary.json — …/logs/20260629T210828Z-963551a9/.../summary.json

MR

Branch pushed; create the MR (pre-filled, targets main):
https://gitlab-master.nvidia.com/dl/DLQASH/nmfw_tests/-/merge_requests/new?merge_request%5Bsource_branch%5D=qiaochuz%2Fpor_2745_xtoken&merge_request%5Btarget_branch%5D=main

This branch was previously deployed

2 inactive deployments
public — 75e43f90 Deployed Jun 25, 2026 by copy-pr-bot[bot] via release / finalize / publish-docs #1424
test — 75e43f90 Deployed Jun 25, 2026 by copy-pr-bot[bot] via Wait in test approval queue #12686
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) QA:Verified

Projects

None yet

Development

Successfully merging this pull request may close these issues.

test(xtoken): add nightly with heterogeneous TP/CP parallel plan for cross-tokenizer distillation

4 participants