Repository navigation
feat(xtoken): replace DP token alignment with offset-based cluster alignment - #3286
Conversation
RayenTian
left a comment
There was a problem hiding this comment.
Took a close look at the offset-cluster rewrite — the O(n) walk replacing Needleman-Wunsch is a nice simplification, and the ~3.3x per-step number with a 100-step 2-node smoke behind it is exactly the kind of evidence that makes this easy to reason about. Three questions below, two of them about scope rather than the algorithm.
Could you rebase onto current main when you get a chance? The branch point (0f629c5b1, 2026-07-18) is about 245 commits behind now.
There's no merge conflict, so this isn't about that. The reason I ask is that this PR changes what the aligner emits, while its consumers live elsewhere — valid_chunk_mask in loss_utils.py and the exact_token_match_only gate in loss_functions.py. If either moved in the last two months, a clean merge could still end up subtly wrong.
Would you be able to re-run the 100-step 2-node smoke afterwards, just to confirm the ~3.3x still holds? Since the tooling is already set up, that might also be a convenient point to add a chat-mode run.
Generated by Claude Code
7dc2c29 to
216faf1
Compare
|
/ok to test 45650a0 |
|
/ok to test 45650a0 |
yuki-97
left a comment
There was a problem hiding this comment.
Nice work — the offset-cluster kernel is a real simplification over the Needleman-Wunsch path it replaces. The strict char-end walker is O(n) and every branch of both loops advances an index, so it cannot spin, and the ~3.3x per-step number has a 100-step 2-node multi-teacher smoke behind it. Routing the drop-first flag as a per-teacher list indexed by the original teacher index — so interleaved same-tokenizer teachers keep their None slot — is the right call.
Scope: the full diff at 45650a0 — the aligner rewrite, the new chat collator mode, the per-teacher config move, and the nightly / functional drivers.
Checked:
- Offset-kernel arithmetic — the cluster walker and the slice-to-full-sequence remap, driven on hand-built offsets.
- The chat path against the real Qwen3 and Llama chat templates, rendered rather than read.
- Config surface — every new key traced to a consumer, and both exemplars, the recipe YAMLs and the
.shoverrides replayed through OmegaConf struct mode. - Removals — every deleted symbol grepped at head, and every
AlignmentBatchfield traced to a reader. - Loss-side coupling —
is_correct, the chunk partition and bothtoken_maskkeys followed to their consumers.
Remaining comments are on the chat path's assistant-span matching and its two loss masks, the new data.* keys' schema and exemplar coverage, the two config-migration validators, and a few duplicated or stale spots in the aligner.
Use each teacher's assistant mask for chat scoring so prompts, template scaffolding, and padding do not affect teacher selection or weighting. Add regression coverage for assistant masks and score sensitivity. Reject the legacy root projection path with an error naming the nested aligner setting, and remove the guard for the unreleased shared setting. Update config validation tests for the explicit rejection behavior. Remove unused alignment partition masks, chunk counts, and the unused alignment reconstruction helper, including their plumbing and tests. Document both collator modes and every constructor argument, and correct the explanation for pairing padding tokens. Addresses the six scoped review comments on PR #3286. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Include retained assistant terminators in CE, same-tokenizer KD, and teacher scoring masks. Locate template suffixes across whitespace without extending content spans or duplicating cross-tokenizer EOT alignment pairs. Move the five collator options into a typed top-level config with centralized defaults, update both exemplars, and reject obsolete data-level settings with migration guidance. Exercise CLI overrides through schema loading and setup. Add a public align_chat API returning AlignmentBatch and use AlignmentPair records throughout chat alignment. Keep batch assembly and padding cleanup inside the aligner rather than the collator. Add regression coverage for loss gradients, unchanged raw cross-tokenizer KD, truncation, multiple turns, template whitespace, and typed public APIs. Document chat configuration and terminator supervision. Validation: 163 focused tests passed, 2 skipped; Ruff lint/import/format and git diff checks passed. Repository-wide pyrefly reports 11 errors in untouched modules, including missing optional dependencies. Addresses review comments 2, 3, and 4 on PR #3286. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
|
Following up on the rebase and smoke-test request: rebased onto Post-rebase validation: 335 focused tests passed (75 alignment, 111 loss/config/EOT, 149 data/native-chat/real-Qwen). The latter suites used the exact upstream Lens revision in an isolated dependency overlay. The known DP multiprocessing timeout case and two GPU collective cases were deselected; GPU training was not run. Scoped type checks, default Ruff lint/format, the secret hook, copyright check, recipe minimization, and driver dry run passed. CI has been requested for the rebased head. The known import-order issue in The requested 100-step two-node rerun, chat GPU smoke, and fresh curves for the two nightlies remain outstanding. The earlier approximately 3.3x throughput result has not been revalidated on this revision. |
|
/ok to test c75fd4b |
Use each teacher's assistant mask for chat scoring so prompts, template scaffolding, and padding do not affect teacher selection or weighting. Add regression coverage for assistant masks and score sensitivity. Reject the legacy root projection path with an error naming the nested aligner setting, and remove the guard for the unreleased shared setting. Update config validation tests for the explicit rejection behavior. Remove unused alignment partition masks, chunk counts, and the unused alignment reconstruction helper, including their plumbing and tests. Document both collator modes and every constructor argument, and correct the explanation for pairing padding tokens. Addresses the six scoped review comments on PR #3286. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Include retained assistant terminators in CE, same-tokenizer KD, and teacher scoring masks. Locate template suffixes across whitespace without extending content spans or duplicating cross-tokenizer EOT alignment pairs. Move the five collator options into a typed top-level config with centralized defaults, update both exemplars, and reject obsolete data-level settings with migration guidance. Exercise CLI overrides through schema loading and setup. Add a public align_chat API returning AlignmentBatch and use AlignmentPair records throughout chat alignment. Keep batch assembly and padding cleanup inside the aligner rather than the collator. Add regression coverage for loss gradients, unchanged raw cross-tokenizer KD, truncation, multiple turns, template whitespace, and typed public APIs. Document chat configuration and terminator supervision. Validation: 163 focused tests passed, 2 skipped; Ruff lint/import/format and git diff checks passed. Repository-wide pyrefly reports 11 errors in untouched modules, including missing optional dependencies. Addresses review comments 2, 3, and 4 on PR #3286. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
c75fd4b to
f0894da
Compare
|
/ok to test f0894da |
RayenTian
left a comment
There was a problem hiding this comment.
Thanks for the rebase and for implementing the held-back knobs rather than deferring them — the alignment_method / same_tokenizer_identity removal and the per-teacher aligner: block both look good. One follow-up on the new native-chat recipe.
Generated by Claude Code
Exercise native chat alignment with SmolLM2-135M and Qwen3-1.7B using different tokenizers, and assert unequal token counts in a valid aligned chunk. Fold the three-step chat smoke into the existing functional test and remove its standalone nightly driver and registration. Generate the arithmetic conversations and projection matrix at runtime. Load the stock Qwen template from its pinned tokenizer instead of keeping a copied Jinja fixture and source manifest. Update documentation and the secret-scan baseline for the moved and removed test assets. Validation: 109 focused CPU tests passed, followed by the relocated config integration recheck. Ruff lint/format, shell syntax, secret scanning, suite accounting, and diff checks passed. GPU training was not run locally. Addresses review comments 4140208831, 4140223825, and 4140278823 on #3286. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
|
/ok to test f173d70 |
Use each teacher's assistant mask for chat scoring so prompts, template scaffolding, and padding do not affect teacher selection or weighting. Add regression coverage for assistant masks and score sensitivity. Reject the legacy root projection path with an error naming the nested aligner setting, and remove the guard for the unreleased shared setting. Update config validation tests for the explicit rejection behavior. Remove unused alignment partition masks, chunk counts, and the unused alignment reconstruction helper, including their plumbing and tests. Document both collator modes and every constructor argument, and correct the explanation for pairing padding tokens. Addresses the six scoped review comments on PR #3286. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Include retained assistant terminators in CE, same-tokenizer KD, and teacher scoring masks. Locate template suffixes across whitespace without extending content spans or duplicating cross-tokenizer EOT alignment pairs. Move the five collator options into a typed top-level config with centralized defaults, update both exemplars, and reject obsolete data-level settings with migration guidance. Exercise CLI overrides through schema loading and setup. Add a public align_chat API returning AlignmentBatch and use AlignmentPair records throughout chat alignment. Keep batch assembly and padding cleanup inside the aligner rather than the collator. Add regression coverage for loss gradients, unchanged raw cross-tokenizer KD, truncation, multiple turns, template whitespace, and typed public APIs. Document chat configuration and terminator supervision. Validation: 163 focused tests passed, 2 skipped; Ruff lint/import/format and git diff checks passed. Repository-wide pyrefly reports 11 errors in untouched modules, including missing optional dependencies. Addresses review comments 2, 3, and 4 on PR #3286. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Exercise native chat alignment with SmolLM2-135M and Qwen3-1.7B using different tokenizers, and assert unequal token counts in a valid aligned chunk. Fold the three-step chat smoke into the existing functional test and remove its standalone nightly driver and registration. Generate the arithmetic conversations and projection matrix at runtime. Load the stock Qwen template from its pinned tokenizer instead of keeping a copied Jinja fixture and source manifest. Update documentation and the secret-scan baseline for the moved and removed test assets. Validation: 109 focused CPU tests passed, followed by the relocated config integration recheck. Ruff lint/format, shell syntax, secret scanning, suite accounting, and diff checks passed. GPU training was not run locally. Addresses review comments 4140208831, 4140223825, and 4140278823 on #3286. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
f173d70 to
247493f
Compare
Main renamed the dtensor_cfg block to automodel_cfg and removed the _v2 key, and reject_outdated_automodel_block now fails on either. Update the native-chat functional config and the multi-teacher unit-test fixture added on this branch. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Provide the checkpoint block required during teacher worker initialization after the recipe replaces the inherited teachers list. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Delete the guard for never-released data collator keys, its migration-message test, and the obsolete upgrade instructions. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Always reject oversized chat documents, remove the test-only truncation mode, and exercise the production rendering helper in the remaining EOT tests. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Document decoded-text equality, NFC-validated native repair, and EOS-role matching, and remove the outdated deferred-mask explanation. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Place the native-chat YAML beside its base config and update the functional command, guide, unit-test reference, and secret-scanner baseline paths. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Store the eight existing JSONL rows directly, point the functional run at the fixture, and remove the generator and its dedicated config-and-dataset test. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Return five-field AlignmentPair objects from the offset kernel and fill decoded-text correctness in place. Remove unused token-string fields and kernel arguments, and update every constructor and tuple-based test. Preserve native Unicode repair, original token ranges, and EOS/EOT matching. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Move native_chat and cross_tokenizer_collate into nemo_rl.data.xtoken, with an explicit package initializer. Keep the shared chat utilities in nemo_rl.data. Update all production and test imports, the guide's source path, and the pyrefly include list. Preserve rendering and batching behavior. Addresses PR #3286 review discussion r4232338807. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Move the teachers[i].projection_matrix_path rejection out of TeacherConfig and into check_outdated_config so startup validation and the shipped-config sweep enforce the same migration. Report the concrete teacher index and the supported teachers[i].aligner.projection_matrix_path location. Cover rejected, accepted, and absent shapes in the shared utility tests, including null legacy values, conflicting old/new keys, and later teachers. Remove the schema-level rejection test and its unused validator import. Addresses: #3286 (comment) Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Always materialize a validated message_loss_mask in kd_data_processor, including the all-assistant default for missing or null masks. Forward supplied masks through OpenAIFormatDataset, prepending zero when a system message is inserted, and require the prepared mask in chat rendering. Update direct renderer/collator fixtures for the explicit mask contract and cover processor defaults, deferred validation, system-message indexing, and unchanged assistant/end-of-turn targets through the loss boundary. Addresses #3286 (comment) Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Extract native-chat projection setup, training, logs, and finite-loss checks into a standalone script. Register it in fast and full functional CI and document independent execution with the checked-in chat fixture. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Load the reference chat template from Qwen3-30B-A3B-Thinking-2507 at an immutable tokenizer revision instead of maintaining a copied fixture. Explicitly disable the upstream history-truncation condition in the comparison test while retaining separate and inline reasoning coverage. Remove the copied reference template; keep the training template unchanged. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Render the complete conversation for each tokenizer, retaining earlier messages as context while restricting CE, teacher scoring, and cross-tokenizer alignment to the final assistant response and its end-of-turn token. Remove shortened-history prefix renders. Locate ordinary-chat targets with a full-context content probe and native targets within the final assistant envelope. Require a final assistant message selected by the message mask. Cover stock Qwen3 multi-turn formatting, repeated answers and reasoning, native tool targets, final-only loss gradients, and invalid final targets. Document the final-turn-only training contract. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Register the public Qwen3-30B-A3B-Thinking-2507 tokenizer revision in the secrets baseline so reproducible template tests pass secret scanning. Refresh the existing Qwen revision's source line metadata. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Supply the empty milestone list required by the single-stage SequentialLR setup so the native-chat functional test can initialize its optimizer. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Use a shared 180-second deadline, matching the two-rank checkpoint test, to allow spawned workers to import Automodel and Transformers before initializing Gloo. Keep the 30-second process-group timeout and all numerical parity checks. Always reap live siblings after a failed rank or timeout, with bounded terminate and kill waits to avoid leaving workers behind. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Update the existing allowlisted tokenizer revision from line 45 to 46 after adding scheduler milestones. Preserve the hash and detector settings. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Update exemplar comments and mask docstrings to describe final-assistant-only supervision while retaining earlier messages as context. Limit ordinary inline-reasoning support to templates that render content verbatim and direct Qwen-style templates to native alignment. Describe the missing-EOT sentinel accurately and rename the corresponding unit test and parameter without changing its assertions. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Require student and teacher assistant masks and EOT lists on both chat alignment entry points. Remove unused None branches and inferred EOT discovery while retaining shape, turn-count, and token-range validation. Update test callers to provide explicit supervision metadata and cover malformed masks and EOT indices. Production collators already supply all four arguments. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
Clarify that ordinary inline reasoning requires templates that render content verbatim in both the collator config docstring and reasoning error message. Direct Qwen-style templates to native thinking alignment. Signed-off-by: Adithyakrishna Hanasoge <[email protected]>
78d75bc to
6f6df9f
Compare
|
/ok to test 6f6df9f |
yuki-97
left a comment
There was a problem hiding this comment.
In ordinary chat mode (native_thinking_alignment=false), a final assistant turn with prose plus tool_calls is silently mis-masked: native_chat.py:311-316 takes <tool_call> as the EOT, so the tool payload and the real <|im_end|> get no CE, and the EOT KD pair is built from <tool_call>. The shipped recipes do not cover this path (the native-chat config uses native_thinking_alignment: true, the default recipes use mode: text).
Not blocking this PR, since it is large and follow-up PRs depend on it. Tracked in #4831; it can be fixed in a separate PR.
What
Moves cross-tokenizer alignment from Needleman-Wunsch DP to an offset-based cluster aligner, and extends it to chat / instruct (and "thinking") data.
Alignment pairs tokens by their character-span offsets (
return_offsets_mapping): consecutive same-span tokens collapse into a cluster, a strict char-end walker pairs clusters covering the same character range, and special tokens (offset(0,0)) pair by role.is_correctis recomputed from canonicalized text, sopair_is_correctand the gold-loss exact partition keep their meaning.Scope / status
Part 1 — offset alignment (done)
nemo_rl/algorithms/x_token/token_aligner.py— DP kernel, anchor segmentation, post-processing, and byte/mojibake canonicalization removed; the offset-cluster kernel (align_by_offsets_cluster) added.canonical_token(still used bytools/x_tokenand theis_correctmask) kept.nemo_rl/data/cross_tokenizer_collate.py—_tokenize_batchemitsoffset_mapping;align()receives student/teacher char offsets.test_token_aligner.pyrewritten for the offset path; the collator's fake tokenizer emits char offsets.Part 2 — chat / native-template alignment (this PR)
Each model renders a conversation with its own chat template, so the two rendered texts — and their offsets — differ, and the full sequence can't be aligned directly. This part aligns per assistant message: isolate each side's assistant content, rebase offsets to a shared coordinate system, align the slice with the same
align_by_offsets_clusterkernel, then map positions back to the full sequence. "Thinking" data is split intoreasoning/close/answerregions (+ an EOT marker).Adds:
token_aligner.py—align_one_offset_per_asst()(per-turn slice → rebase → align → map-back) andalign_one_offset()(canonical + NFC decode-fixis_correct).cross_tokenizer_collate.py— achatmode (__call__→_call_text/_call_chat) with render / assistant-mask / native-region / lockstep-packing helpers and new constructor knobs.chat_templates.py—find_rendered_message_content_span().processors.py—chat_kd_processor()(readsmessages/conversation).collator_mode,include_thinking_in_loss,native_thinking_alignment,drop_first_assistant_chunk_kl,kd_alignment_regions,num_packed_rows.Testing
X-Token nightly validation
On 2026-10-15, both X-Token raw-text nightlies passed at 5625877fe8ec273958da47a58dc3310e7fe4bdb5. Each run completed 100 training steps and all 11 validation points (steps 0, 10, …, 100), with finite metrics, driver exit code 0, and Slurm
COMPLETED 0:0. The launcher reproduced the checked-in nightly projection/training configuration and ran the original assertions unchanged: 8/8 single-teacher and 10/10 multi-teacher passed.Means marked with * follow the source checker’s exclusive upper bound:
mean(..., -5, -1)selects steps 96–99 for these 100-step runs. Validation is held-out distillation KL on 64 samples.Measured values against the original nightly assertions
Configuration and reproducibility. One node / eight GPUs per run; global batch 8, microbatch 1, sequence length 1024; student TP4/CP2 and each teacher TP2/CP2. Multi-teacher aggregation uses equal weights and
sum. Dataset:nvidia/Nemotron-Pretraining-Specialized-v1.1, subsetNemotron-Pretraining-Formal-Logic, with a 64-sample validation split and seed 42. AdamW LR 5e-5, five-step warmup; loss vocab top-k 8192 and projection top-k 4. Checkpointing disabled; W&B, TensorBoard, and GPU monitoring enabled. Source drivers: single, multi. Slurm jobs20286020and20286022completed in 25m39s and 38m57s respectively.Runtime. These runs used the prepared compatibility runtime: Python 3.13.13, Torch 2.11.0+cu130, Ray 2.56.1, Transformers 5.12.1, and Lens 0.2.0+b0f977d, with the existing Automodel overlay. Python/Torch/Ray differ from the source-lock targets (Python ≥3.13.14, Torch 2.13.0, Ray ≥2.58.0); the container/source version check was explicitly bypassed for this runtime.
Comparison with earlier evidence. The results closely match the approximate reference values documented in the original nightly drivers at PR base
33da4fc50: single mean loss ~0.97, accuracy ~86%, final validation KL ~0.029; multi mean loss ~1.0, accuracy ~86%, final validation KL ~0.045. These are rounded documented references, rather than a freshly rerun pre-change baseline. All 18 assertions are identical between the PR base and this tested head.The earlier two-node smoke used a different configuration, so its loss and throughput figures are not a like-for-like baseline. The earlier approximately 3.3× DP-to-offset speedup and the native-chat functional path were not remeasured by these raw-text nightlies.
🤖 Generated with Claude Code