Skip to content

feat(csd): add cross-tokenizer distillation and sub-token preparation - #4680

Open
avenkateshha wants to merge 76 commits into
mainfrom
avenkateshha/csd
Open

avenkateshha wants to merge 76 commits into
mainfrom
avenkateshha/csd

Conversation

@avenkateshha

@avenkateshha avenkateshha commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do ?

Adds CSD (Common-Support Distillation), a second cross-tokenizer off-policy distillation method next to X-Token. CSD aligns the student and teacher tokenizations of the same text into chunks and compares the two models only on events both tokenizers can express — shared tokens and shared token chains, looked up in bidirectional sub-token tables — with a REST bucket for the remaining probability mass. Student next-token CE is added to the KD term, and only the student is trained.

X-Token CSD
Selector algorithm: xtoken (default) algorithm: csd
Vocabulary artifact Projection matrix (tools/x_token/) Student-to-teacher and teacher-to-student sub-token tables (tools/csd/)
Entrypoint / exemplars run_xtoken_off_policy_distillation.py run_csd.py, csd.yaml, csd_multiteacher.yaml
Backends Automodel Automodel or Megatron, per model
Teacher transport Dense CUDA IPC Sparse top-K (default K=128) or dense CUDA IPC
Sequence packing Unpacked Unpacked, or optional lockstep packing

Main changes

  • Loss (nemo_rl/algorithms/loss/csd.py): CSDLossFn / CSDLossConfig. 1:1 chunks compare common tokens; 1:many and many:1 chunks compare prefix-support alternatives (or only the realized chains with csd_realized_only_mismatch); many:many chunks compare realized chains. Defaults: JSD (β=0.5), mismatch chunks weighted ×5, normalized by the DP-global valid chunk count × T², dynamic KD/CE scaling. Same-tokenizer teachers use the shared top-K KL from refactor(xtoken): move same-tokenizer KD math into shared helpers #4721. Multi-teacher sum / averaged_logits / select_teacher.
  • Sub-token tables (tools/csd/): a CPU builder (one direction per call; complete chains, role-mapped special tokens, no truncation) and a validator (fingerprints, ID ranges, every mapped event). Fast BPE tokenizers with a ByteLevel decoder.
  • Teacher transport: sparse top-K IPC (top-K logits, exact log-normalizer, forced realized labels) from Automodel and Megatron teachers, plus Megatron dense full-logit export. The default teacher_topk_ipc_k: 128 changes the objective (top-128 + REST instead of the full vocabulary); set 0 for dense.
  • Distributed execution: TP/CP-sharded loss without gathering the vocabulary; eligible Megatron students (PP=1, unpacked, static sum) evaluate KD owner-local on each CP rank. New primitives in nemo_rl/distributed/model_utils.py.
  • Data: durable sample_id on arrow_text, openai_format and ResponseDataset; CSDCrossTokenizerCollator is a thin subclass of the shared collator with feat(xtoken): cross-tokenizer collator options and pad text to longest row #4728's options on. Overlength text rows are clipped to a prefix that fits every model.
  • Lockstep sequence packing (optional, CSD only): the student and every teacher pack the same samples into the same bins (nemo_rl/data/packing/lockstep.py, docs/design-docs/csd-lockstep-sequence-packing.md).
  • Configs and docs: exemplars; three nightly recipes (Automodel TP4CP2 single- and multi-teacher, Megatron TP2CP2); docs/guides/xtoken-off-policy-distillation.md renamed to docs/guides/cross-tokenizer-distillation.md, with a new CSD section next to X-Token; README "Cross-Tokenizer Distillation" section covering X-Token and CSD.

Shared changes that also affect X-Token and other algorithms:

  • Megatron CP > 1 no longer requires sequence packing for cross-tokenizer distillation, whose setup sets megatron_cfg.allow_unpacked_context_parallel; logprob, top-k and full-payload export still need packing, so other algorithms keep that requirement. Packed Megatron runs pass a CP-local MoE router padding mask.
  • With policy.offload_optimizer_for_logprob: true, the off-policy distillation controller (X-Token and CSD) offloads the student optimizer state after every training step and every validation, before the next teacher forward. Both X-Token exemplars set it; the X-Token nightly recipes set it to false.
  • Megatron-FSDP (megatron_cfg.distributed_data_parallel_config.use_megatron_fsdp, or the older use_custom_fsdp) is honored for every algorithm; HF weights then load directly into the FSDP shards instead of through a cached torch_dist conversion.
  • New optional policy keys: freeze_parameter_patterns (Automodel and Megatron), automodel_cfg.load_precision and automodel_cfg.shard_before_load, and megatron_cfg.distributed_data_parallel_config.reduce_scatter_with_fp32_accumulation.
  • The arrow_text packed-cache schema version changes, so existing characters_per_sample caches are rebuilt on first use.
  • rebuild_teacher_full_logits_from_ipc returns (logits, fallback_count); the strict exact-token map selects every row whose top weight is 1.0.
  • Teacher table paths are accepted only under teachers[i].aligner.

Issues

Builds on #3286, #4721 and #4728, all merged into main.

Usage

uv run python -m tools.csd.build_subtoks_table --source-tokenizer meta-llama/Llama-3.2-1B --destination-tokenizer Qwen/Qwen3-4B --output cross_tokenizer_data/csd/student_to_teacher.pt
uv run python -m tools.csd.build_subtoks_table --source-tokenizer Qwen/Qwen3-4B --destination-tokenizer meta-llama/Llama-3.2-1B --output cross_tokenizer_data/csd/teacher_to_student.pt
uv run python -m tools.csd.validate_subtoks_tables --student-tokenizer meta-llama/Llama-3.2-1B --teacher-tokenizer Qwen/Qwen3-4B \
  --student-to-teacher cross_tokenizer_data/csd/student_to_teacher.pt --teacher-to-student cross_tokenizer_data/csd/teacher_to_student.pt
uv run python examples/run_csd.py

See the CSD section of the cross-tokenizer guide for table format, loss options, transports and lockstep packing.

Before your PR is "Ready for review"

  • Read and followed the Contributor guidelines.
  • Added and updated necessary tests.
  • Added and updated documentation.
  • Completed GPU qualification.

Additional Information

Validation so far

Check Result
CPU unit suites (CSD, X-Token, data, distributed, tools) Pass; remaining failures are offline Hugging Face downloads, identical on the base
GPU unit tests, default markers 499 passed, 0 failed
GPU smoke, csd-qwen3-4b-to-llama3.2-1b-1n8g-dtensor-tp4cp2 8 steps + validation, finite loss
Megatron owner-local vs. replicated KD (TP2×CP2, K=0, 20 steps) Step 1: logits bitwise equal, loss/CE identical, KD rel. diff 9e-8; grad-norm rel. diff 2.2e-4. K=128: finite for 20 steps
Same-tokenizer KD and collator vs. pre-refactor CSD Bitwise identical (28 KD cases; 21 of 24 collator cases, the rest are intended behavior changes)
copyright-check Was red: tests/unit/tools/csd/test_subtoks_tables.py had no header; added in 3f92c61

Open items

  • The single-teacher Automodel CSD suite moved to disabled.txt and the nightly GPU-hour cap rose to 4953 (d1af5c2); the remaining CSD nightlies still need 100-step runs to set NUM_MINUTES.
  • Megatron-marked unit tests need an image newer than nemo_rl_main_20260803 on the current base. The two Megatron-marked failures first attributed to the image were test bugs (test_train.py:335, test_megatron_setup.py:205), fixed in 7e79fde.
  • The multi-teacher recipe and lockstep packing have no GPU run on the current head; no convergence claims yet (results will be added to the guide).

Suggested review order: docs/guides/cross-tokenizer-distillation.md (CSD section) → tools/csd/ → nemo_rl/algorithms/loss/csd.py → nemo_rl/algorithms/x_token/loss_utils.py and nemo_rl/distributed/model_utils.py → nemo_rl/algorithms/xtoken_off_policy_distillation.py → nemo_rl/data/cross_tokenizer/csd_collate.py and nemo_rl/data/packing/lockstep.py → backend/worker changes under nemo_rl/models/ → tests.

🤖 Generated with Claude Code

@avenkateshha

Copy link
Copy Markdown
Contributor Author

/ok to test 22ebcf7

@copy-pr-bot

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

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 12, 2026
@avenkateshha
avenkateshha marked this pull request as ready for review October 12, 2026 18:33
@avenkateshha
avenkateshha marked this pull request as draft October 12, 2026 18:33
@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-offset-alignment branch from 42fc8ce to 98d6069 Compare October 13, 2026 18:31
@avenkateshha
avenkateshha changed the base branch from avenkateshha/xtoken-offset-alignment to avenkateshha/xtoken-csd-shared-collator October 15, 2026 18:06
@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-csd-shared-collator branch 4 times, most recently from 2d5df0d to 205dc30 Compare October 16, 2026 12:26
@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-csd-shared-collator branch from a04b753 to e6fe651 Compare October 19, 2026 11:00
@avenkateshha
avenkateshha marked this pull request as ready for review October 19, 2026 16:41

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

Self-review of the CSD PR at c516f035b. It was run with an agent team: RL guidelines, three bug-finders, an upstream-API expert, design and tests. Three devil's-advocate passes then re-checked every finding at this head; findings below 80% confidence were dropped. Everything actionable is inline; this body holds context and follow-ups.

Fix in this PR (details inline):

  1. megatron/data.py:2032: TE infers pad_between_seqs=True for every Megatron packed run, so the grpo-cispo-…-megatron-cispo nightly fails. This affects non-CSD algorithms.
  2. megatron_policy_worker.py:1607: empty mb_losses on an all-padding DP rank → torch.stack([]) crash (Megatron SFT/DPO validation).
  3. csd.py:654: Automodel CP>1 dynamic loss scaling makes KD CP× too strong (both Automodel CP=2 nightlies).
  4. nightly.txt:324: nightly GPU-hours 4955 > 4947 cap (L0 unit failure).
  5. test_subtoks_tables.py:1: copyright header (CI red).
  6. test_train.py:335: the new Megatron test fails on the pinned MCore (a test bug).

PR description: remaining gaps (the latest rewrite fixed the rest):

  • "Shared changes" doesn't mention that X-Token now offloads the student optimizer after every step and every validation when policy.offload_optimizer_for_logprob: true (controller#L2348-L2356). Both X-Token exemplars set it; the nightly recipes override it to false.
  • Megatron-FSDP (use_megatron_fsdp / use_custom_fsdp: true) is now honored for every algorithm, with HF weights loaded directly (setup.py#L669-L677, #L983-L991); the base ignored the flag.
  • New shared policy keys aren't listed: freeze_parameter_patterns (Automodel-only, see inline), automodel_cfg.load_precision / shard_before_load, the Megatron optimizer dtype pass-throughs, and reduce_scatter_with_fp32_accumulation.
  • "CP > 1 no longer requires sequence packing" should note that logprob, top-k and full-payload export still need it (see setup.py:1344).
  • The two Megatron-marked failures attributed to the image are test-side (test_train.py:335, test_megatron_setup.py:205).
  • The validation section doesn't mention the red copyright-check.

Docs: docs/design-docs/csd-lockstep-sequence-packing.md L51-53, L602-604 and L608 still describe limitations this PR removed. For example, "Both teacher IPC entry points in Policy explicitly reject sequence packing" is no longer true: get_full_logits_ipc now takes a packing plan (lm_policy.py#L921-L1005). Reword those passages as history, or delete them.

Follow-ups (not blocking):

  • About 330 lines of multi-teacher aggregation in CSDLossFn are near-copies of X-Token's CrossTokenizerDistillationLossFn (similarity: _teacher_weight_score 1.00, _compute_dynamic_weights 0.99, _teacher_score_inputs 0.94, …). The select_teacher / CP crash (inline at controller L1557) already lives in both copies. The CSD copy also reduces over a per-call side-channel group (_dp_cp_group / _sum_window_kd_over_cp, csd.py#L331-L334, set at L557-L558). A shared helper that takes the group explicitly would fix both.
  • CSDSequencePackingLossWrapper._accumulate_metrics adds an 8th copy of the min/max metric sets (csd_packing.py#L455-L456), the duplication the TODO in wrapper.py#L29-L46 asks to remove. CSD emits no _min/_max metrics, so import _SEQ_METRIC_MIN/_MAX or drop the branches.

Worth keeping: the algorithm-free CP/TP primitives in distributed/model_utils.py; owner_local_config_violations / csd_owner_local_ineligibility as pure reason-list functions reused by __init__ and setup; and the CPU-testable CSD math with its gloo TP2/CP2 parity tests.

Generated by Claude Code

Comment thread nemo_rl/models/megatron/data.py Outdated
packed_seq_params = PackedSeqParams(
cu_seqlens_q=cu_seqlens_padded,
cu_seqlens_kv=cu_seqlens_padded,
cu_seqlens_q=cu_seqlens,

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.

1 action item, please fix in this PR. nemo_rl/models/megatron/data.py:2032 · PR-introduced; affects every Megatron sequence-packed run, not only CSD.

TL;DR: TE 2.18 now infers pad_between_seqs=True for every packed Megatron forward, which disables FlashAttention 2/4; the grpo-cispo-…-megatron-cispo nightly (packing + attention_backend: flash) will fail with "No dot product attention backend is available".

PackedSeqParams carries raw and padded boundaries; TE uses them to pick the attention backend.

  1. The base passed the same cu_seqlens_padded object to all four fields (base L1832-L1836). This PR passes raw cu_seqlens for q/kv; with no padding cu_seqlens_padded is cu_seqlens.clone() (L2027), so it is always a distinct tensor.
  2. MCore forwards pad_between_seqs=None (transformer_engine.py#L2314-L2340), so TE infers it by object identity: if cu_seqlens_q_padded is cu_seqlens_q and cu_seqlens_kv_padded is cu_seqlens_kv: pad_between_seqs = False (TE dot_product_attention.py#L1549-L1561).
  3. With it True, TE disables FA2/FA4 and unfused attention for THD (TE utils.py#L976-L991).
  4. grpo-cispo-…-megatron-cispo.yaml (nightly.txt#L101) sets packing + attention_backend: flash, which turns fused/unfused off (MLM utils.py#L63-L82); the default flash_attention_version=2 turns FA3 off (setup.py#L1906-L1909). Nothing is left: ValueError: No dot product attention backend is available (TE#L1687-L1693) on the first packed forward. On sm<90 with attention_backend: auto, packed runs silently move from FA2 to cuDNN.

Probe (real function body + TE's rule): base → False; head → True, even for [0,5,12,16] vs [0,5,12,16].

The raw boundaries look intentional (FullLogitsPostProcessor and _packed_row_geometry read them), so a revert doesn't work, and neither does pad_between_seqs=not torch.equal(...): TP2+SP (divisor 2) pads odd rows, so it is still True for cispo.

Action: keep the raw PackedSeqParams for NeMo-RL consumers, but hand the model a copy whose q/kv boundaries are the padded tensors, at both call sites: model_forward (train.py#L262-L264) and the draft/Eagle call (train.py#L475-L480). One way to do it:

def _te_packed_seq_params(params: Optional[PackedSeqParams]) -> Optional[PackedSeqParams]:
    """Packed boundaries as TE expects them: q/kv point at the padded tensors."""
    if params is None:
        return None
    return dataclasses.replace(
        params,
        cu_seqlens_q=params.cu_seqlens_q_padded,
        cu_seqlens_kv=params.cu_seqlens_kv_padded,
    )

Add a model_forward test asserting kwargs["packed_seq_params"].cu_seqlens_q is kwargs["packed_seq_params"].cu_seqlens_q_padded; the existing pins at test_megatron_data.py L2912-2913 / L3053 stay valid. Not GPU-verified; GPU numbers taken at this head went through cuDNN.

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.

fixed in 2804467, by restoring the note instead of handing the model a copy. _pack_sequences_for_megatron again puts the padded tensor in all four PackedSeqParams boundary fields, as on main, so TE sees one object, infers pad_between_seqs=False, and FA2/FA4 are eligible again. Every model call gets the pre-PR note without a call-site change. That includes the critic's get_values, which calls the model directly and would have needed the copy as well.

The two CSD readers that needed raw lengths now take them from input_lengths, the lengths the packer was given:

  • FullLogitsPostProcessor drops its packed_seq_params argument and reads data_dict["input_lengths"]. It now takes only data_dict and cu_seqlens_padded, like the logprob, top-k and sparse post-processors. Its stored lengths and exported rows are unchanged: the four packed export tests pass with their expected outputs untouched.
  • LossPostProcessor gives CSDSequencePackingLossWrapper cu_seqlens_q = (0, *accumulate(input_lengths)), so its zero-fill past each real length is unchanged. The generic and fused packing wrappers keep reading the note, which again holds the pre-PR values.

This also covers packed runs the comment didn't list: Megatron-Bridge's Nemotron-H and Gemma providers default to attention_backend: flash, and on sm<90 a packed run had no backend at all (cuDNN's THD kernel needs sm90+) rather than moving to cuDNN.

New tests pin one tensor object in all four fields (with and without filler), the exact FullLogitsPostProcessor dispatch kwargs, the CSD wrapper boundaries, and that non-CSD packed losses still read the note. On CPU the mcore unit lane gives the same result as the previous head for every existing test, and the new tests fail against the previous head's sources. Not yet checked on GPU: no packed run has logged FA2 selection.

logical_metrics if logical_metrics is not None else [x]
)
for metric_record in metric_records:
if metric_record["num_valid_samples"] <= 0:

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.

1 action item, please fix in this PR. megatron_policy_worker.py:1607 · PR-introduced; hits every algorithm on Megatron.

The new skip of num_valid_samples <= 0 records can leave mb_losses == [] on a DP rank whose shard is all padding. all(...) over [] is True, so L1641-L1642 runs torch.stack([]) → RuntimeError: stack expects a non-empty TensorList. The base appended every record, and the Automodel worker already handles this case.

Breaking case (reproduced on CPU with the real maybe_pad_last_batch + shard_by_batch_size): Megatron SFT, DP=8, val_micro_batch_size=1, last validation batch of 3 samples (drop_last=False, sft.py#L574-L585) → padded to 8 rows with sample_mask=0 (utils.py#L558-L577) → ranks 3-7 hold only padding → every record skipped → crash. Same for DPO validation, and for GRPO when a DP shard is fully zeroed (grpo.py#L3697).

Action: at L1641 (outside the diff), so the else branch yields tensor(0.):

                if mb_losses and all(isinstance(loss, torch.Tensor) for loss in mb_losses):

plus a Megatron worker test with an all-sample_mask=0 DP shard.

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.

Fixed in 4f71039.

The skip stays: CSD and X-Token mean-reduce per-microbatch diagnostics (MEAN_REDUCED_MB_METRICS in xtoken_off_policy_distillation.py), so zero records from padding rows would drag those means down. The other algorithms only mean-reduce constants (lr, wd, global_valid_*) and sum the rest, so skipping padding records doesn't change their metrics.

The guard is the suggested one-liner, if mb_losses and all(isinstance(loss, torch.Tensor) for loss in mb_losses):. When every record of a global batch is skipped, the else branch appends torch.tensor([], device=global_valid_toks.device).sum(), a float32 zero on the same device as the other losses. Each rank still appends one loss per global batch, so the DP all-reduce in aggregate_training_statistics gets the same shape on every rank. The rank adds no metric rows, which is fine because Policy.train merges metric keys rank by rank.

A rank holds only padding when maybe_pad_last_batch pads up to a multiple of mbs * dp_size and the sample_mask=0 rows fill whole DP shards, as in the 3-sample validation example at DP=8 (ranks 3-7). Under CSD packing an all-padding bin takes the same path, since CSDSequencePackingLossWrapper drops records with num_valid_samples == 0.

Regression test: test_train_all_padding_dp_shard_reports_zero_loss in tests/unit/models/policy/test_megatron_worker.py runs MegatronPolicyWorkerImpl.train on CPU, in train and eval mode, on a one-row shard whose sample_mask is 0. It checks that train() finishes, reports one zero loss for the global batch, and adds no metric rows. Without the fix it fails with RuntimeError: stack expects a non-empty TensorList; every other test in the mcore and CSD unit lanes keeps its outcome.

The Automodel worker needs no change: it sums with torch.tensor(mb_losses).sum().item(), which is already 0 for an empty list.

Comment on lines +654 to +657
# Combine the aggregated KD term with the single student CE term.
loss, _, kl_scale = self._combine_kd_and_ce(
total_kd, ce_loss, total_kd.detach(), ce_loss.detach()
)

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.

2 action items, please fix in this PR. csd.py:654-657 · PR-introduced.

TL;DR: on Automodel with CP>1 and dynamic_loss_scaling: true (the csd.yaml default, inherited by both Automodel CP=2 nightlies), the dynamic KD scale is built from a CP-partial KD, so the KD gradient is CP× too large relative to CE and kl_loss is logged at 1/CP.

  1. On Automodel CP the worker multiplies the chunk count by cp_size (automodel_policy_worker.py#L517-L525), so each rank's cross-tokenizer KD is KD_true / CP (same-tokenizer KD is a per-window share); cp_normalized_by_caller is False there (loss_input.py#L395).
  2. CE is forward-summed over CP, so every rank holds the full CE (csd.py#L1266-L1272).
  3. This call gives kl_scale = |CE| / |KD_rank| = CP·|CE| / |KD_true|; after the DP×CP gradient sum (automodel/train.py#L604-L614) the KD gradient is CP× the intended one.
  4. The owner-local path already uses the CP sum (_detached_cp_sum, L581-L582).

Probe (Automodel CP=2 vs a CP=1 reference): dynamic=True: ref scale=14.3198 | cp2 scale=28.6397 | max|grad diff|=5.065e-01. With only a same-tokenizer teacher the per-rank scales even diverge (8.76 / 12.20 vs 5.10). With the fix: same scale, grad diff ≤ 9e-8. Megatron is unchanged (_sum_window_kd_over_cp is True there). The nightlies only check isfinite, so they can't catch this.

AI-1

Use the CP-summed KD for the scale and the reported value (metric wiring in the next comment):

Suggested change
# Combine the aggregated KD term with the single student CE term.
loss, _, kl_scale = self._combine_kd_and_ce(
total_kd, ce_loss, total_kd.detach(), ce_loss.detach()
)
# Combine the aggregated KD term with the single student CE term.
# Without caller-side CP division (Automodel CP) each rank's KD is its
# CP share while CE is complete, so the dynamic scale and the reported
# KD use the CP sum, as on the owner-local path.
reported_kd = (
total_kd.detach()
if self._sum_window_kd_over_cp
else self._detached_cp_sum(total_kd, cp_group)
)
loss, reported_loss, kl_scale = self._combine_kd_and_ce(
total_kd, ce_loss, reported_kd, ce_loss.detach()
)

AI-2

Add a CP=2 gloo test with the Automodel contract (cp_normalized_by_caller=False) and dynamic scaling next to _run_same_vocab_megatron_cp in tests/unit/algorithms/csd/test_csd_loss_functions.py; the existing dynamic-scaling CP test only covers cp_normalized_by_caller=True.

Follow-up

Per-teacher kl_loss_t{i} / teacher_{i}/weighted_kl are also CP-partial on Automodel CP (logged at 1/CP); this fix doesn't cover them.

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.

Fixed in 50e792c.

When the caller does not divide the loss by the CP size, the replicated path of CSDLossFn.__call__ now takes the dynamic KD scale and the reported KD from the CP sum of the KD term, as the owner-local path already does. This is the suggested change: reported_kd is total_kd.detach() when _sum_window_kd_over_cp is set and _detached_cp_sum(total_kd, cp_group) otherwise, and _loss_metrics now gets reported_loss / reported_kd (the csd.py:678 thread). On Automodel with CP>1 every rank now computes the scale as CE over the complete KD, so the KD gradient keeps its intended weight against CE, and kl_loss / kl_loss_scale match a CP=1 run. Megatron (cp_normalized_by_caller=True) and Automodel at CP=1 (no CP sharder, so the flag is also True) take the unchanged branch.

Regression test: test_dynamic_scaling_on_automodel_cp2_matches_cp1 in tests/unit/algorithms/csd/test_csd_loss_functions.py, next to the Megatron CP test. It runs CP=2 over gloo with dynamic scaling and the Automodel contract: contiguous windows, sequence-local CE log-probs, chunk count × CP, and cp_normalized_by_caller=False. It compares the result against a CP=1 run. kl_loss_scale, kl_loss, ce_loss and loss must match, and the gradient summed over both ranks must equal the CP=1 gradient. It covers a cross-tokenizer teacher and a same-tokenizer teacher. Against the previous head both cases fail on the scale: 10.16 vs 5.08 with the cross-tokenizer teacher (2×), and 7.84 on rank 0 and 10.41 on rank 1 vs 4.47 with the same-tokenizer teacher. On CPU, every other test in the CSD/X-Token default lane and the automodel lane keeps its outcome.

One correction to the description: with dynamic scaling on (the csd.yaml default), the logged loss was already right, because it equals 2 × CE whatever the scale. Only kl_loss (1/CP) and kl_loss_scale (×CP) were off. loss was low only with fixed weights, where its KD part was at 1/CP; the metric change covers that case too. Step-1 GPU metrics at the previous head, Automodel TP4×CP2 vs Megatron TP2×CP2 on the same data, seed and weights:

Metric Automodel Megatron
CE 1.9108 1.9114
kl_loss 0.0854 0.1708
kl_loss_scale 22.68 11.35
loss 3.8216 3.8229

The per-teacher kl_loss_t{i} / teacher_{i}/weighted_kl metrics stay CP-partial on Automodel CP; they are left for the follow-up listed in the review. The fix has not been run on GPU yet.

Comment thread nemo_rl/algorithms/loss/csd.py Outdated
Comment on lines +677 to +678
loss=loss,
kd=total_kd,

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.

Part of the csd.py:654 comment (same action). csd.py:677-678

Report the same CP-summed values the scale uses, so loss / kl_loss aren't logged at 1/CP on Automodel CP (only CP rank 0's metrics are kept, lm_policy.py#L1186-L1190):

Suggested change
loss=loss,
kd=total_kd,
loss=reported_loss,
kd=reported_kd,

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.

Fixed in 50e792c (see the csd.py:654 thread).

Comment thread tests/test_suites/nightly.txt Resolved
Comment thread examples/configs/csd.yaml
csd_mismatch_loss_beta: 5.0
csd_noise_filter_topk: 0
csd_realized_only_mismatch: false
teacher_topk_ipc_k: 128 # 0 sends dense teacher logits

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.

1 action item (low priority). examples/configs/csd.yaml:28 · PR-introduced.

With teacher_topk_ipc_keep_realized: true (the exemplar default), sparse KD adds each chunk's realized label to its support and lowers the mismatch minimum support from 2 to 1 (csd.py#L2618-L2623). So K=128 and K=0 optimize different losses even when K covers the whole vocabulary. Probe at K=V: dense 0.2297 vs sparse 0.3085, max |Δgrad| 0.037; with keep_realized: false they agree to 1e-9. The guide says the two "optimize different objectives" (guide#L543) but blames only the top-K cut, and this comment still reads as a pure transport choice:

Suggested change
teacher_topk_ipc_k: 128 # 0 sends dense teacher logits
teacher_topk_ipc_k: 128 # 0 sends dense teacher logits (a different KD objective; see the guide)

Do the same for csd_multiteacher.yaml L28. In the guide at L543, consider adding: "With teacher_topk_ipc_keep_realized: true the sparse KD also adds each chunk's realized label to its support, so the two differ even when K covers the vocabulary."

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.

fixed in 462c9eb, by removing the difference instead of documenting it. The realized-pair rules behind teacher_topk_ipc_keep_realized were gated on teacher_topk_ipc_k > 0; they now apply to dense rows too (replicated and owner-local), so dense K=0 equals sparse K=V for either keep setting. Your K=V probe now gives 0.3085 for both (max |Δgrad| ≤ 4e-9), and keep_realized: false still reproduces the previous dense loss (0.2297). This changes the default dense K=0 loss of existing runs. The YAML comment (0 sends dense teacher logits) is accurate as is, so it's unchanged. The guide now says the two forms differ only by the top-K limit and documents teacher_topk_ipc_keep_realized in the field table. New CPU tests check that dense K=0 equals sparse K=V for five chunk cases × both keep settings, plus the owner-local path.

Comment thread nemo_rl/algorithms/loss/csd.py Resolved
NUM_RUNS=$(( (MAX_STEPS + STEPS_PER_RUN - 1) / STEPS_PER_RUN )) # Round up
NUM_MINUTES=30
STUDENT_MODEL=meta-llama/Llama-3.2-1B
TEACHER0_MODEL=Qwen/Qwen3-4B # cross-tokenizer (P-KL via projection)

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.

1 action item. …-dtensor-tp4cp2.sh:12 · PR-introduced. This teacher uses CSD sub-token tables, not P-KL:

Suggested change
TEACHER0_MODEL=Qwen/Qwen3-4B # cross-tokenizer (P-KL via projection)
TEACHER0_MODEL=Qwen/Qwen3-4B # cross-tokenizer (CSD sub-token tables)

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.

fixed in 8e983df. Applied the suggestion: the comment now reads # cross-tokenizer (CSD sub-token tables). Comment only; no other CSD script or config had the P-KL label.

Comment on lines +506 to +508
student_to_teacher_table_path: Path to this teacher's forward pseudo-target table
(student-to-teacher sub-token chains). ``None`` for a same-tokenizer
teacher.

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.

1 action item. xtoken_off_policy_distillation.py:506 · PR-introduced.

TeacherAlignerConfig.projection_matrix_path's docstring (L500-L502, just above the diff) still says None marks a same-tokenizer teacher. For algorithm: csd, a null projection with a table pair is a cross-tokenizer teacher (L821-L825). Suggested wording: "X-Token: None marks a same-tokenizer teacher. CSD: the table pair below selects cross-tokenizer." The validate_csd_tokenizer_reuse docstring (L1458, "every null-projection teacher") needs the same fix.

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.

fixed in 2885ef5. Applied the suggestion: the projection_matrix_path docstring now reads "X-Token: None marks a same-tokenizer teacher, which bypasses projection and alignment and uses direct per-position KL. CSD: the table pair below selects cross-tokenizer.", and the validate_csd_tokenizer_reuse docstring now says "Validate every teacher with no CSD table pair before any worker is created." Docstrings only.

@avenkateshha

Copy link
Copy Markdown
Contributor Author

Addressed review items E1, E2, E4, E5 and E6 from the self-review in two commits on top of 9946ac4:

  • 3f92c61: copyright header on tests/unit/tools/csd/test_subtoks_tables.py (the red copyright-check).
  • 7e79fde: test_model_forward_passes_cp_local_router_padding_mask sets sequence_parallel=False; test_megatron_fsdp_uses_local_hf_snapshot unsets HF_HUB_OFFLINE; TestFullLogitsPostProcessorSeqPacking gets @pytest.mark.automodel; the unpacked-CP process_microbatch test runs through the real shard helper.

Checked on CPU in the NeMo-RL container (main_20260803 image, branch-pinned Megatron-Bridge ec835530 and Automodel b916107a5):

  • --mcore-only on test_train.py, test_megatron_setup.py and test_megatron_data.py: 475 passed, 7 failed (at c516f03: 473 passed, 9 failed). The difference is the two fixed tests. The other 7 fail the same way at both commits with "Found no NVIDIA driver", so they need a GPU.
  • --automodel-only on test_automodel_train.py: TestFullLogitsPostProcessorSeqPacking is now collected and passes. The 5 failures are the same no-GPU error.
  • Unpacked-CP test mutant: with (cp_rank, cp_size) swapped in data.py, the new test fails and the old one passes.

The nightly GPU-hour cap item (nightly.txt:324) is handled separately.

@avenkateshha
avenkateshha force-pushed the avenkateshha/xtoken-csd-shared-collator branch from 16ea4c3 to d7e38de Compare October 26, 2026 07:56
Base automatically changed from avenkateshha/xtoken-csd-shared-collator to main October 29, 2026 14:44
@avenkateshha

Copy link
Copy Markdown
Contributor Author

Addressed the two docs items from the self-review body: the PR description gaps and the stale design-doc passages.

PR description, updated in place:

  • "Shared changes" now covers the student-optimizer offload after every training step and validation under policy.offload_optimizer_for_logprob: true, Megatron-FSDP being honored for every algorithm (HF weights load straight into the FSDP shards), and the new optional policy keys freeze_parameter_patterns, automodel_cfg.load_precision / shard_before_load and reduce_scatter_with_fp32_accumulation.
  • The Megatron CP bullet now says unpacked CP is for cross-tokenizer distillation (megatron_cfg.allow_unpacked_context_parallel), and that logprob, top-k and full-payload export still need packing. It no longer says packed runs pass raw cu_seqlens_q/kv, since 2804467 restored the padded boundaries.
  • The Megatron optimizer dtype pass-throughs are not listed: since the PR was retargeted, main already passes them to Megatron-Core.
  • The validation table lists the copyright-check fix (3f92c61). The open items say the two Megatron failures first attributed to the image were test bugs fixed in 7e79fde, and replace the old nightly-cap failure with the current state (cap 4953 after d1af5c2; the CSD nightlies' NUM_MINUTES still need 100-step runs).

Design doc, fixed in 409a296: docs/design-docs/csd-lockstep-sequence-packing.md no longer says that both teacher IPC entry points reject packing (get_full_logits_ipc takes the lockstep plan), that aggregate_per_sample_handles orders handles only by position (packed batches are ordered by batch_item_id), or that the full-logit postprocessors reject packing. The dense-IPC requirements stay as design text.

@RayenTian
RayenTian self-requested a review November 3, 2026 02:28
@terrykong terrykong added CI:L1 Run doctests, unit tests, and functional tests CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L1 Run doctests, unit tests, and functional tests labels Nov 5, 2026
avenkateshha and others added 17 commits November 16, 2026 02:24
projection_matrix_path = None marks a same-tokenizer teacher only in X-Token;
CSD selects cross-tokenizer by the sub-token table pair. Fix the
TeacherAlignerConfig and validate_csd_tokenizer_reuse docstrings to match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
The Qwen3-4B teacher runs through CSD sub-token tables, not P-KL projection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
teacher_topk_ipc_keep_realized only took effect when teacher_topk_ipc_k > 0,
so dense K=0 and sparse K=V scored identical teacher logits differently
(0.2297 vs 0.3085 on the with_mismatch parity fixture). The realized-pair
rules change what the loss compares, not how logits travel, so dense rows
now apply them too:

- 1-to-many and many-to-1 chunks keep the realized pair, and a chunk with
  fewer than two table alternatives, or a chain longer than the tables,
  is scored as realized vs REST instead of being skipped.
- 1-to-1 chunks drop common pairs that share only one token with the
  realized pair, as the sparse path does. The replicated dense path masks
  at most two columns per row in place rather than building full
  [rows x common] copies.
- Owner-local dense follows the same flag, and realized-only mismatch
  keeps the realized pair for both transports.

keep_realized=false reproduces the previous dense loss; the default (true)
changes the dense K=0 KD value of existing runs. The guide now states that
the two transports differ only by the top-K limit and documents the flag.

Tests: dense K=0 vs sparse K=V parity for five cases and both keep settings,
owner-local dense vs sparse K=V and vs replicated; the CSD CPU suite passes.
The GPU TP/CP CSD tests in tests/unit/algorithms/x_token/test_loss_utils.py
were not run.

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

The single-slot and two-slot builders of the realized labels that sparse
teacher IPC must keep looped in Python over every chunk and teacher label,
with several small tensor calls per label, on the driver before each teacher
forward. Both now expand the chunk spans into per-label reads with a few
whole-batch tensor ops (_teacher_force_include_requests):

- Single slot: a row keeps the label of the highest-indexed chunk that reads
  it, as before.
- Two slots: a row is only read for the token at its own position (unshifted
  chunks) or at the next one (shifted chunks), so the builder keys reads by
  (shift, row) and orders the two candidates by their first reader. The
  ">2 distinct labels" ValueError is dropped rather than vectorized: no input
  can reach it.

Forced labels are now built only for sparse transport (teacher_topk_ipc_k >
0). Dense transport never read them, but with csd_noise_filter_topk > 0 the
single-slot loop still ran and its result was dropped.

On collator batches the outputs are bit-identical to the loops: 70,336 of
70,336 old-vs-new comparisons (random, adversarial, edge-case and 12 real
Llama-3.2-1B <- Qwen3-4B batches) under torch 2.8 and 2.11. Per teacher per
step on the real batches (torch 2.11, CPU, 16 threads): csd.yaml as shipped
0.33-0.39 s -> 2.0-2.3 ms; rows filled to 2048 tokens 2.3-2.7 s -> 3.7-4.4 ms.

Tests: both builders against a per-label loop on random alignments (shuffled
pair ids, -1 labels); a dense export with the noise filter builds no forced
labels (fails on the old call site). unit/algorithms/csd and
test_xtoken_off_policy_distillation.py pass (290).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
Automodel loads the unsharded model first only with PP, TP, EP and LoRA off
and dp_shard == 1, which in NeMo-RL means TP=1 with every GPU in one CP
group. Normal TP=1 FSDP layouts already shard first, so the flag is a no-op
there. Fix the _force_shard_before_load docstring and the PolicyConfig
comment to match.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
Transformer Engine 2.18 decides whether a packed THD batch has padding
between sequences by object identity: only when cu_seqlens_q_padded is
cu_seqlens_q (and kv likewise) does it treat the batch as unpadded. With
the raw boundaries in cu_seqlens_q/kv, every standard packed Megatron
forward disabled FlashAttention 2/4 and unfused attention. Flash-only runs
(the cispo nightly, and the Nemotron-H and Gemma provider defaults) are
left with no backend ("No dot product attention backend is available"),
and packed runs on pre-Hopper GPUs lose their only kernel.

The packer puts the padded tensor back in all four fields, as on main, so
every model call gets the pre-PR note. The CSD readers that need real
lengths take them from input_lengths instead:

- FullLogitsPostProcessor no longer takes the note, like the other
  post-processors; its stored lengths and exported rows are unchanged.
- LossPostProcessor gives the CSD packing wrapper cumsum(input_lengths),
  so its zero-fill past each real length is unchanged. Other packed
  losses keep reading the note, which again holds the pre-PR values.

Tests: one tensor object in all four fields with and without filler, the
teacher-export dispatch kwargs, the CSD wrapper boundaries, and non-CSD
packed losses reading the note. On CPU the mcore unit lane gives the same
outcome as the PR head for every existing test and the new tests pass;
the new tests fail against the PR-head sources. No GPU run.

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

The replicated (Automodel) sparse path kept one forced label per teacher
row: the single-slot builder let the later chunk's label overwrite the
earlier one, and the producer merged that one label into the top-k by
evicting the lowest score. On the row read by both an unshifted first chunk
and the next shifted chunk, the first chunk's realized label could be
missing, so owner-local (Megatron) and replicated evaluation differed.

The Automodel path now follows the Megatron design:

- SparseLogitsPostProcessor calls distributed_vocab_topk_logz_force and
  returns the natural top-k (sorted by id), log Z, the score-rank-k id and
  the [B, T, F] forced-label sidecar (raw logits, ids, natural
  top-membership_k membership); the worker exports all of them over IPC.
- The replicated CSD loss builds one K-wide support per request with the
  rule SparseTeacherRowReader uses (the natural top-k if the realized label
  is in it, else the score-rank-k token is replaced by that request's
  label). The rule moves into materialize_sparse_teacher_rows, shared by
  both paths, and SparseTeacherLogits.gather_rows returns what the reader
  returns. The sparse noise filter reads each request's own membership.
- The trainer builds the two-slot labels for every sparse cross-tokenizer
  teacher; the single-slot builder and its pinned test are removed.

Behaviour changes on the Automodel sparse path: cutoff ties now resolve as
on Megatron (higher value, then lower id), and with
teacher_topk_ipc_keep_realized=false rows stay the natural top-k instead of
taking the noise-filter label. SPARSE_TEACHER_ROW_CHUNK_SIZE moves to
model_utils so both producers share it.

Tests: replicated vs owner-local on a row read for two labels (loss,
gradient and every shared metric; K=1 and 4; default, noise filter,
realized-only with and without keep_realized), per-request rows equal the
reader's, pure ALM sparse equals dense, rows stay natural without
keep_realized, and the producer's seven fields. A CPU harness over 160
random batches (exact logit ties, noise filter, realized-only) matches
owner-local within 2e-7 relative loss with identical top-1 accuracy and
chunk counts; the previous code differed by up to 1.2e-2 and changed chunk
counts in most batches. CSD and X-Token trainer tests: 366 passed. The GPU
IPC export path was not run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
CSDLossFn cached its sub-token tables, common-token map,
teacher-to-common-student map and prefix support index on the instance.
Ray hands every worker a fresh copy of the loss on every Policy.train call
(each training step and each validation batch), so every call reloaded both
tables and rebuilt the prefix index, about 0.5 s per call per
cross-tokenizer teacher on the GPU nodes.

Move these to process-wide caches keyed by the source tables (plus teacher
vocabulary size and device for derived tensors, and the pre-dedup flag for
the prefix index), like the projection caches in x_token.loss_utils. The
loss values and gradients are unchanged. The prefix index never depended
on the device, so its builder no longer takes one.

Add a test that two fresh loss instances load each table once and share
one prefix index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
maybe_pad_last_batch pads a batch to a multiple of mbs * dp_size with
sample_mask=0 rows, and rows go to DP ranks in order, so a rank can hold
only padding (for example a 3-sample validation batch at DP=8, mbs=1).
train() skips every loss record with num_valid_samples <= 0, so on such a
rank mb_losses is empty; all() over an empty list is True and
torch.stack([]) raises "stack expects a non-empty TensorList" on every
algorithm that trains on Megatron.

Take the else branch when mb_losses is empty. The rank then appends a
float32 zero on the global_valid_toks device, so losses keeps one entry
per global batch on every DP rank and the DP loss all-reduce stays
aligned. It adds no metric rows, which Policy.train already merges per
rank. The skip stays: CSD and X-Token mean-reduce per-microbatch
diagnostics that zero padding records would dilute.

Tests: test_train_all_padding_dp_shard_reports_zero_loss drives
MegatronPolicyWorkerImpl.train on CPU, in train and eval mode, with a
one-row shard whose sample_mask is 0. Without the fix it fails with
"stack expects a non-empty TensorList". On CPU the mcore unit lane and
the CSD lane give the same outcome as the PR head for every existing
test. No GPU run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
Four loss-setting combinations that CSD cannot run passed config
validation and failed only after the cluster and every model were up
(2-5 min into a 1-node run), or at the first loss call:
- sum_weights_metric or normalize_teacher_by_vocab outside
  kd_loss_mode='sum' (both are ignored there)
- csd_loss_fn='bce' without csd_pure_alm (BCE needs a binary
  realized-vs-rest support; common chunks carry a multi-token one)
- csd_last_pos_loss_fn='bce' without csd_pure_alm or
  csd_realized_only_mismatch
- kd_loss_mode='averaged_logits' with teacher weights summing to zero

CSDLossConfig now rejects the first three with an after-validator, and
CSDMasterConfig rejects the zero weight-sum using teachers[i].weight,
so the entrypoint fails in seconds, before Ray starts. The duplicate
checks in CSDLossFn.__init__ are removed.

The owner-local violations test builds its BCE cases with
model_construct. New tests cover the rejected and accepted
combinations, and the zero weight-sum test now validates csd.yaml
through CSDMasterConfig.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
On Automodel with CP>1 the caller does not divide the loss by the CP
size (cp_normalized_by_caller=False), so each rank's KD term is its CP
share: the cross-tokenizer KD is replicated and normalized by the chunk
count x CP, and a same-tokenizer KD covers only the rank's window. CE is
forward-summed over CP, so every rank holds the full CE. The replicated
path built the dynamic scale |CE| / |KD| from the rank's share, so the
KD gradient was CP times too strong relative to CE (a same-tokenizer
teacher got a different scale on each rank), and kl_loss and
kl_loss_scale were reported from the share (1/CP and CP times the CP=1
values for a cross-tokenizer teacher).

Take the dynamic scale and the reported KD from the CP sum of the KD
term when the caller does not divide by CP, as the owner-local path
already does, and report that loss and KD in the metrics. Megatron
(cp_normalized_by_caller=True) and Automodel at CP=1 keep the old
values.

Tests: test_dynamic_scaling_on_automodel_cp2_matches_cp1 runs CP=2 over
gloo with the Automodel contract and dynamic scaling, for a
cross-tokenizer and a same-tokenizer teacher, and checks kl_loss_scale,
kl_loss, ce_loss, loss and the rank-summed gradient against a CP=1 run.
Without the fix both cases fail on the scale (cross-tokenizer: 10.16 vs
5.08). On CPU the CSD/X-Token default lane and the automodel lane give
the same outcome as the PR head for every other test. No GPU run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
validate_csd_packing_setup only checked that each side's packing bin
(train_mb_tokens for the student, logprob_mb_tokens for each teacher)
is positive. A bin smaller than the longest row the collator admits
passed setup, and the lockstep planner then raised "does not fit side"
at the first step whose batch held such a row, after the cluster and
every model were up. With max_total_sequence_length=2048 and
train_mb_tokens=1024 on the csd.yaml data, that is step 1.

Each side's bin must now hold its context rounded up to its
make_sequence_length_divisible_by. A same-tokenizer teacher packs the
student's rows, so it is checked against the student's context with
its own divisor. The entrypoint runs this check before Ray starts, and
every shipped CSD config already satisfies it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
CSD setup read its typed CSDLossConfig through a model_dump() dict.
validate_csd_packing_setup used .get("teacher_topk_ipc_k", 0), whose 0
contradicts the field default of 128, and setup re-checked by hand bounds
the model already enforces (Field(ge=0) on teacher_topk_ipc_k,
Literal["row_topk"] on the support mode) before validating the dict back
into a CSDLossConfig for the owner-local checks.

Read master_config.loss_fn directly instead: attribute access in
validate_csd_packing_setup, teacher_topk_ipc_k read off the typed config
(0 for X-Token), no hand re-checks, and the config itself passed to
csd_owner_local_ineligibility.

Drop teacher_topk_ipc_support_mode. Its only legal value is row_topk, so
it selected nothing: setup and the Automodel worker re-checked it,
Policy.get_topk_logits_ipc threaded it through, and Megatron never read
it. Removing it before it reaches main avoids a deprecated-key entry
later. CSDLossConfig keeps extra="allow", so configs that still set the
key load unchanged.

X-Token keeps reading its TypedDict loss config as before, and the loss
function is still built from one merged dict for both algorithms. No
behavior change.

Tests: on CPU the CSD, X-Token and exemplar config-validation unit tests
give the same outcome before and after for all 2266 tests (1905 passed,
361 skipped). The driver and Automodel sparse-IPC entry points import
and no longer take support_mode. No GPU run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
The CSD loss read five NRL_CSD_* environment variables that no config,
test, doc or launch script in the repo sets:
- NRL_CSD_LOSS_DUMP_DIR enabled _maybe_dump_loss, which nothing calls.
- NRL_CSD_PREDEDUP_PREFIX_INDEX and NRL_CSD_BATCHED_HELPER_NUMPY kept
  older copies of the prefix-index build and the batched mismatch
  helper for A/B checks; both defaulted to the faster code.
- NRL_CSD_SPARSE_LOOKUP_ROWS and NRL_CSD_COMMON_LOOP_MB set memory
  tiles outside the typed config.

Delete the dump hook and the two older code paths and keep their
defaults: the prefix index is always deduplicated, so its cache key
loses the flag and its readers pass assume_unique=True, and the
batched helper always takes the NumPy path. The sparse lookup tile
becomes the constant CSD_SPARSE_LOOKUP_ROW_CHUNK_SIZE (2048, as
before). The replicated common-chunk loop now reads
csd_support_chunk_batch_size, the chunk batch size owner-local
evaluation already uses. A config value is the same on every rank, so
the TP/CP override that guarded against per-rank env values is gone.
Its default (16) replaces the 64-chunk tile and the single pass dense
teacher logits got at TP=CP=1; the loss is unchanged. Also drop the
seq_index arguments: nothing fills data["seq_index"].

Tests: on CPU the CSD/X-Token default lane and the automodel lane give
the same outcome as the PR head for every test. No GPU run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
The lockstep packing design doc still described limitations this PR
removed: that both teacher IPC entry points in Policy reject sequence
packing (get_full_logits_ipc takes the lockstep plan), that
aggregate_per_sample_handles can only order handles positionally (it
orders packed batches by batch_item_id), and that the DTensor and
Megatron full-logit postprocessors reject packing (both have packed
export paths). Delete those statements and keep the dense-IPC
requirements as design text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
With the student at CP>1 and dense teacher logits, each CP rank holds
only its contiguous window of every teacher's logits, but teacher
scoring (kd_loss_mode='select_teacher' and sum_weights_metric) paired
that window with the teacher's full token ids and mask from the batch.
A cross-tokenizer teacher crashed at step 1 ("Expected input batch_size
(4) to match target batch_size (10)" for ce, a size mismatch for
entropy / max_prob), and a same-vocab teacher dropped the next-token
pair at each CP border.

_teacher_score_inputs now returns this rank's window of the scored
tokens: ids, token mask, and each position's next token and mask from
cp_shift_next, which takes the first token of the next CP rank's window
at the border. For a cross-tokenizer teacher the mask window comes from
the new LocalizedAlignment.teacher_token_mask, filled next to
teacher_input_ids in prepare_csd_cross_tokenizer_loss_input.
_dp_global_masked_mean already sums the masked scores and counts over
the DP x CP group, so every rank gets the whole-sequence score and picks
the same teacher and weights. select_teacher and the 'ce' weight share
one next-token CE helper. CP=1 scores are unchanged.

test_teacher_scoring_on_cp2_matches_cp1 runs a cross-tokenizer and a
same-vocab teacher on 2 gloo ranks for select_teacher and each weight
metric. It checks the selected teacher and the weights against a
full-sequence oracle, and the loss and gradients against CP=1. A valid
token sits on the CP border and decides which teacher is selected. On
the previous head all four cases fail with the errors above. The CSD
prepare test now checks the teacher id and mask windows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
X-Token's CrossTokenizerDistillationLossFn had the same CP>1 teacher
scoring bug that fb7d40e fixed for CSD. With the student at CP>1,
each rank holds only its contiguous window of every teacher's dense
logits, but _teacher_score_inputs paired that window with the
teacher's full token ids and mask from the batch. kd_loss_mode=
'select_teacher' or any sum_weights_metric crashed at step 1 for a
cross-tokenizer teacher, and a same-vocab teacher dropped the
next-token pair at each CP border.

The fix mirrors the CSD one. _teacher_score_inputs returns this
rank's window of the scored tokens with next-token targets from
cp_shift_next, and prepare_xtoken_cross_tokenizer_loss_input now
fills the alignment's teacher_input_ids / teacher_token_mask with the
teacher-logit window (the first teacher-logit-width positions at
CP=1). _dp_global_masked_mean already sums over WORLD, so every rank
gets the whole-sequence score. CP=1 scores are unchanged.

test_teacher_scoring_on_cp2_matches_cp1 checks select_teacher and
each weight metric on 2 gloo ranks against a full-sequence oracle,
with a CP-border pair that decides the selection. On fb7d40e all
four cases fail with the shape mismatch. The prepare tests check the
teacher windows at CP=2 and CP=1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
avenkateshha and others added 2 commits November 16, 2026 02:46
Main's #4973 makes LossPostProcessor read
megatron_cfg.reuse_logits_storage on the fused packing path, so the fused
case of test_non_csd_packing_wrapper_reads_boundaries_from_the_note failed
with KeyError: 'megatron_cfg' after the rebase onto main. Give its config
stub an empty megatron_cfg, as every Megatron config has one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adithya Hanasoge <[email protected]>
Main's #3320 removed the is_reward_model parameter from
prepare_model_forward and dropped it at the five existing call sites. The
PR's get_topk_logits_ipc call merged without a textual conflict and still
passed is_reward_model=False, so its first teacher microbatch would raise
"TypeError: prepare_model_forward() got an unexpected keyword argument
'is_reward_model'". That is the CSD path for an Automodel student with
teacher_topk_ipc_k > 0 (128 by default). Drop the keyword so the call
matches the other five.

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

This branch has not been deployed

No deployments
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)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants