Repository navigation
fix(speculative): one label alignment per projector_type; DSpark and Domino export the head they built - #2762
Conversation
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
9377aa7 to
025e18a
Compare
8f4bfb2 to
403439a
Compare
403439a to
63ab708
Compare
63ab708 to
b7c2c0b
Compare
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2762 +/- ##
==========================================
+ Coverage 79.46% 81.15% +1.69%
==========================================
Files 720 719 -1
Lines 80734 80792 +58
==========================================
+ Hits 64152 65567 +1415
+ Misses 16582 15225 -1357
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
/claude review |
ChenhanYu
left a comment
There was a problem hiding this comment.
Pensieve lgtm review using chenhany's profile (revision 13).
LGTM: the fixes are sound in source and covered by focused tests; human sign-off remains for justified existing-test edits.
Needs action:
- Confirm human sign-off on edits in
test_hf_domino.pyandtest_hf_dspark.py: fixtures remove the retired setting, and export assertions strengthen normalized-rank coverage without dropping existing checks.
No action needed:
- Conversion rejects the retired key before draft construction; restore filters it from a copied config. Exporters consistently read algorithm alignment and built-head fields.
- Tests cover both legacy alignment values across DFlash, DSpark and Domino, integer export ranks at both config levels, and Domino's AR refusal.
- Fewer than 50 added core-logic lines; no licensing changes. Skill edits replace obsolete guidance concisely.
- Baseline commit:
86bd9b78425a23a45b329c7c9b86ea772d7a9e77. Base review guidance,AGENTS.mdandCONTRIBUTING.mdread at09a14b9ae89522363ffca9b0ac2245cbbb073fdd. - Tests were not executed; current-head CI results were unavailable. Duplicate checking covers the supplied bounded history, which contains no substantive prior findings.
Review run: d7bedb27945848d78d5539667612d5fa
There was a problem hiding this comment.
Approving: the alignment now has one source (_label_shift / projector_type), the exporters describe the head they built, and each fix carries a test.
No action needed.
- Traced the three bugs end to end:
_label_shiftis 1 forHFDSparkModel/HFDominoModeland 0 forHFDFlashModel, each variant has exactly one wrapper class with its ownget_exporter, sobool(self.model._label_shift)andsample_from_anchorare right for every export path.head.markov_rank/markov_head_type/use_confidence_headare the int/lower-cased/bool values the module built, so the config.json stays JSON-clean. - Convert refuses retired keys before
init_modellike, andrestore_dflash_modelfilters the same table aftermodel_copy, so old checkpoints (including DSpark ones saved withshift_label: false) replay convert and keep the alignment they trained with. No remaining reader of the deletedshift_labelattributes. - Domino's
pseudo_speculative_generatesignature matches the parent's, and the trainer's AR callback catchesException, so training logsAR validation not available.rather than crashing. - One non-blocking SUGGESTION inline on
hf_domino.py:265: the removed warning also covered eval loss/accuracy being backbone-only;do_eval: falsein the recipe limits the impact. - Baseline commit
09a14b9; reviewed head39ffc25. I did not run tests or CI — the PR's reported results are unverified here. Skill edits are net-shorter; no licensing surface.
meenchen
left a comment
There was a problem hiding this comment.
Bot review (gpt-6.1-sol) — DM the bot to share feedback.
Comment: the blanket shift_label refusal breaks correctly aligned legacy configs without the promised deprecation window.
Needs action:
- Preserve valid legacy
shift_labelvalues through README’s migration window; explain hard rejection versusDFlashConfigvalidation or the existing warn-and-enforce approach in the PR body (see conversion comment). - Correct Domino’s error, changelog, and skill advice: name a working head-aware serving runtime, or explicitly state acceptance evaluation is unavailable (see
hf_domino.pycomment).
No action needed:
- Existing test edits are justified: removing retired fixture keys and strengthening export-type assertions retain the previous coverage.
DSpark and Domino train block position k on the token at anchor + k + 1 (HFDFlashModel._label_shift = 1). The same fact was also written as DSparkModule.shift_label = True, as DominoModule.shift_label read from the config, as a NotImplementedError in HFDominoModel.modify, and as the exporters' getattr(draft_config, "shift_label", True), which read the user's raw architecture config. A DSpark config with shift_label: false therefore trained with the shift but exported shift_label: false, so a loader that honors the field would read every drafted position one token off. Domino refused the same config, but only after building the draft. HFDFlashModel.modify now refuses shift_label: false for every variant whose _label_shift is 1, before anything is built; unset or true converts as before. Both exporters write shift_label from _label_shift, and the vanilla DSpark export copies it into sample_from_anchor, vLLM's name for the same alignment, instead of writing a second literal True. The modules' shift_label attributes and Domino's own check go, since nothing reads them any more. Domino's error becomes a ValueError, like the other convert-time config checks, and the skill's Domino and DSpark sheets list it. The refusal applies at convert only. Restore replays convert, so restore_dflash_model drops shift_label from the saved architecture config, as it already drops the warm-start path. A DSpark checkpoint saved with shift_label: false trained next-token alignment all the same: it still loads, and now re-exports shift_label: true. Verified: a new test converts DSpark and Domino with shift_label unset, as the recipes leave it, restores a modelopt_state that carries shift_label: false, and expects shift_label: false to be refused at convert. On the parent commit DSpark does not raise and Domino raises NotImplementedError; without the restore change the restore raises. A tiny DSpark checkpoint saved by 0.47.0 with shift_label: false loads through from_pretrained and exports shift_label: true. The existing export tests still read shift_label: true and, for vanilla heads, sample_from_anchor: true. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: h-guo18 <[email protected]> # Conflicts: # tests/unit/torch/speculative/plugins/test_hf_dflash.py
… was built with DSparkModule resolves its head fields from the architecture config as it builds them: it lower-cases markov_head_type, casts markov_rank to int and use_confidence_head to bool, and fills in defaults for the ones left out. #2902 made DSparkExporter read markov_head_type off the built module, but markov_rank and use_confidence_head were still read from the raw config dict, the latter with a second default. A markov_rank given as a float (64.0) therefore trained a rank-64 head but exported 64.0, and the vanilla export copies that value to the top level, where vLLM's Qwen3DSparkModel sizes its Markov table from it. DominoExporter likewise re-derived pure_draft_prefix_len with a second default. Both exporters now read every head field off the built module, as LiLiCorrExporter already does for its reranker, so the exported config describes the head that the saved weights belong to. Verified: the DSpark export-config test now converts with markov_rank given as a float and expects an int at both levels of config.json; all eight cases fail on the parent commit. Domino's exported values and DSpark's use_confidence_head are unchanged for every config, since the modules store them as given or cast them the same way. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: h-guo18 <[email protected]>
…ing it one position off HFDominoModel inherited DFlash's pseudo_speculative_generate, which drafts block positions 1..bs-1 with the backbone alone. Domino trains position k on the token at anchor + k + 1 and corrects it with its GRU head, so every draft was scored one position off and without the head. It now raises NotImplementedError rather than gaining a decode of its own: HF AR validation is being retired in favour of measuring acceptance in a serving engine, and Domino's recipe already keeps ar_validate_steps at 0. The eval-time warning that called the reported acceptance rates backbone-only goes, along with the skill sheet's advice to treat it as expected. The sheet, the recipe comment and the launcher example now say AR validation is refused. Verified: a new test expects the refusal; without the override the inherited decode runs and the test fails. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: h-guo18 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: h-guo18 <[email protected]>
… refuse shift_label in config dflash_architecture_config.shift_label could only repeat or contradict the alignment each variant trains (_label_shift): DSpark and Domino predict the token at anchor + k + 1; DFlash, DFlash2 and LiLiCorr the token at anchor + k. The previous commit refused only false on the next-token variants, so a DFlash, DFlash2 or LiLiCorr config with shift_label: true was still ignored without a word. Convert now refuses the key for every variant. The exports keep writing shift_label, and DSpark's sample_from_anchor, from _label_shift, since serving reads them. Restore still drops the key, so checkpoints that carry it load: DSpark ones saved with false, and Domino ones from the recipe, which set true. The Domino recipe, the Domino and DSpark skill sheets and the test configs no longer set it. Breaking for configs that set it, even to the value the variant trains: the convert-time error says to remove it. The changelog moves it to Backward Breaking Changes. Verified: the refusal test now covers dflash, dspark and domino with shift_label true and false, and a restore carrying either value; 232 DFlash/DSpark/Domino unit tests and 500 recipe tests pass. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: h-guo18 <[email protected]>
…able
Refusing shift_label at convert and dropping it at restore are two halves of one fact, and
they were written in two files: the refusal in HFDFlashModel.modify, the drop in
restore_dflash_model. Had the two ever disagreed, either old checkpoints would fail to load,
or a new config naming a retired key would be ignored without a word.
dflash/conversion.py now lists the keys dflash_architecture_config once accepted, each with why
it is gone. convert_to_dflash_model refuses them before it changes anything, with that reason in
the error, so every DFlash plugin, not only the HF one, gets the check; restore_dflash_model
drops them before it replays convert. Retiring the next key is one entry.
Behavior is unchanged apart from the error wording ("is no longer a setting"), which the test
and the skill sheets follow. 703 DFlash/DSpark/Domino unit and recipe tests pass.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…ift directly sample_from_anchor is vLLM's name for the same next-token alignment as shift_label, so take it from _label_shift like shift_label is, rather than through the exported dict. The exported value is unchanged (true for DSpark). DSpark export tests: 30 passed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: h-guo18 <[email protected]>
…mino acceptance cannot be measured README's deprecation policy gives a removed parameter one release of continued operation with warnings, and the Domino recipe shipped `shift_label: true` from 0.46 to 0.48. Convert now drops a shift_label that matches the variant's _label_shift with a FutureWarning (removal in 0.50) and still refuses a contradicting one, which never took effect; it checks before converting the model. Restore keeps dropping it unchecked. Domino's AR refusal, the changelog and the skill sheet no longer point to a serving engine: the export declares DFlashDraftModel, so vLLM would run the backbone alone, one block position off. The forward docstring and the skill sheet now also say eval loss and accuracy exclude the correction head. test_deprecated_shift_label fails 6/6 on main, 3/6 with the previous refusal, and 3/6 without the restore filter. DFlash-family unit tests: 318 passed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: h-guo18 <[email protected]>
a944d85 to
bd19e2d
Compare
…step HFDFlashModel.forward built the batch, ran the draft and computed the loss inline, and the variants built on it got at the loss's pieces piecemeal: DFlash2 asked _compute_loss for its unreduced terms (return_terms, _DFlashLossTerms) to recompose the block objective, and DFlash2 and LiLiCorr overrode forward() only to carry out the metrics their _compute_loss had left on the model (_selector_metrics, _lilicorr_metrics). The forward now hands the loss one object per step: - DraftBatch: the batch, its blocks and the draft's hidden states. - LossContext: the labels (_block_targets), the draft's logits (DraftLogits: the distribution the draft serves, and the backbone's before any head) and the position weights, with the per-token cross-entropy and the teacher's logits computed lazily, once. - _compute_loss(ctx) returns a LossOutput: the loss, the accuracy train_acc reports and detached 0-dim metrics, which the forward returns as draft_metrics. What a variant may change becomes a hook: _online_base_outputs (the base model's outputs), _draft_logits (a head on the backbone's logits), _position_weighting and _compute_loss. The loss mask comes from _build_loss_mask. The DSpark/Domino padding fix, a separate PR against main, adds the same helper, with the same text, at the same place (right after get_exporter), so a merge of the two keeps one copy of it. DFlash2 and LiLiCorr take the context: DFlash2's tv/lambda blend reads the cross-entropy and weights from it, and both return their metrics instead of overriding forward(). DSpark and Domino keep their own forwards for now. Rebased onto main after #2757 and #2762 merged, so the context now carries main's rules: the position weights start at _first_predicted_position, the teacher is read by keyword, and a step with nothing to train returns _draft_zero_loss through the draft's logits rather than a bare zero. The selector and LiLiCorr metrics keep their names and values under draft_metrics. Verified: the DFlash-family unit suite passes, and a bitwise A/B against main over one train step and one generation step per case, in fp32 and bf16, is reported in the PR description. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: h-guo18 <[email protected]>
…step HFDFlashModel.forward built the batch, ran the draft and computed the loss inline, and the variants built on it got at the loss's pieces piecemeal: DFlash2 asked _compute_loss for its unreduced terms (return_terms, _DFlashLossTerms) to recompose the block objective, and DFlash2 and LiLiCorr overrode forward() only to carry out the metrics their _compute_loss had left on the model (_selector_metrics, _lilicorr_metrics). The forward now hands the loss one object per step: - DraftBatch: the batch, its blocks and the draft's hidden states. - LossContext: the labels (_block_targets), the draft's logits (DraftLogits: the distribution the draft serves, and the backbone's before any head) and the position weights, with the per-token cross-entropy and the teacher's logits computed lazily, once. - _compute_loss(ctx) returns a LossOutput: the loss, the accuracy train_acc reports and detached 0-dim metrics, which the forward returns as draft_metrics. What a variant may change becomes a hook: _online_base_outputs (the base model's outputs), _draft_logits (a head on the backbone's logits), _position_weighting and _compute_loss. The loss mask comes from _build_loss_mask. The DSpark/Domino padding fix, a separate PR against main, adds the same helper, with the same text, at the same place (right after get_exporter), so a merge of the two keeps one copy of it. DFlash2 and LiLiCorr take the context: DFlash2's tv/lambda blend reads the cross-entropy and weights from it, and both return their metrics instead of overriding forward(). DSpark and Domino keep their own forwards for now. Rebased onto main after #2757 and #2762 merged, so the context now carries main's rules: the position weights start at _first_predicted_position, the teacher is read by keyword, and a step with nothing to train returns _draft_zero_loss through the draft's logits rather than a bare zero. The selector and LiLiCorr metrics keep their names and values under draft_metrics. Verified: the DFlash-family unit suite passes, and a bitwise A/B against main over one train step and one generation step per case, in fp32 and bf16, is reported in the PR description. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: h-guo18 <[email protected]>
…per training step (#2989) ### What does this PR do? Type of change: Refactor. Training behavior is unchanged. One backward-breaking API change: DFlash2's and LiLiCorr's training metrics move under a single key (see **Metrics**). #2757 and #2762, which this PR was stacked on, have merged, so it is now rebased onto `main` and carries only its own four commits. It is the first of two PRs: merge it first, then #2990, which builds the shared loss terms on this seam and moves DSpark and Domino onto the shared forward. - **One loss context per step.** `HFDFlashModel.forward` built the batch, ran the draft and computed the loss inline. The variants built on it reached the loss's pieces piecemeal. DFlash2 asked `_compute_loss` for its unreduced terms (`return_terms`, `_DFlashLossTerms`) to recompose the block objective. DFlash2 and LiLiCorr overrode `forward()` only to carry out the metrics their `_compute_loss` had left on the model. The forward now hands the loss one object per step: - `DraftBatch`: the batch, its blocks and the draft's hidden states. - `LossContext`: the labels, the draft's logits and the position weights. `DraftLogits` holds the distribution the draft serves and the backbone's logits before any head. The per-token cross-entropy and the teacher's logits are computed lazily, each at most once. The cross-entropy keeps its gradient only when the objective trains through it, not under KD, even though D-PACE reads it first under `no_grad`. - `_compute_loss(ctx)` returns a `LossOutput`: the loss, the accuracy `train_acc` reports, and detached 0-dim metrics, which the forward returns as `draft_metrics`. - **Hooks.** What a variant may change becomes a hook on `HFDFlashModel`: - `_online_base_outputs`: what the base model provides online. - `_draft_logits`: a head on the backbone's logits. - `_position_weighting`: D-PACE or decay. - `_compute_loss`: the loss on the context. DFlash2's `tv`/`lambda` blend reads the cross-entropy and the weights from the context. DFlash2 and LiLiCorr return their metrics instead of overriding `forward()`. DSpark and Domino keep their own forwards in this PR. The forward's loss mask now comes from `_build_loss_mask`. #2761, the DSpark/Domino padding fix against `main`, adds the same helper, with the same text, at the same place (right after `get_exporter`), so a merge of the two keeps one copy of it. - **A byte-identical move.** The block-supervision helpers, the position weighting, `_masked_top1` and DSpark's per-token TVD move from `hf_dflash.py` and `hf_dspark.py` into the new `dflash_losses.py`, where the loss context joins them. The new module names no variant. Every moved definition is byte-identical to its text on `main`, and only import lines change elsewhere. The move is its own commit, separate from the reshaping. - **Metrics (backward breaking).** DFlash2's `selector_metrics` and LiLiCorr's `lilicorr_metrics` are replaced by one key, `draft_metrics`, as detached 0-dim tensors with no host sync. - Inner key names stay as they were. - LiLiCorr's values change from Python floats to tensors, so a reader calls `.item()` where it needs a float. DFlash2's were already tensors. - Both keys ship in 0.48.0. Nothing in the repo reads them. Code outside it that does must switch to `draft_metrics`. The CHANGELOG lists this under Backward Breaking Changes. - DSpark and Domino keep `dspark_metrics` and `domino_metrics` until #2990, which also reports DFlash's objective terms. Until then DFlash's own `draft_metrics` is empty. - **Removed:** `return_terms`, `_DFlashLossTerms` and its TODO. Also removed: DFlash2's and LiLiCorr's `forward()` overrides, with the `_selector_metrics`/`_lilicorr_metrics` side channels. What the rebase onto `main` changed, beyond the commits it dropped: the context takes its rules from `main` rather than from the pre-review versions this PR was written against. - The position weights start at `_first_predicted_position(self._label_shift)`, and that helper moves into `dflash_losses.py` with `_block_targets`, which calls it. - `LossContext` passes `decay_factor` and `dpace_alpha` to `_block_position_weights` by keyword, and D-PACE without a `target_ce` raises there. - The teacher is read as `_teacher_logits(base_outputs, label_positions=...)`. - A step with nothing to train returns `_draft_zero_loss(final.device, through=(final,))` rather than a bare `final.sum() * 0.0`. - DFlash2's selector keeps the backbone's own mask **and** position weights, as #2617 made it do; it reads them off the context (`ctx.targets.mask`, `ctx.weights`, `ctx.weight_sum`) instead of the removed `_DFlashLossTerms`. The zero losses stay as they are on `main`: - Inside the loss, the gate routes through the draft's output, so an FSDP2 unit around the draft still runs its backward. - The forward's early return, where no draft has run, reads the draft's parameters instead. ### Usage Configs are unchanged. A variant changes its head and its loss through hooks: ```python class HFMyDraftModel(HFDFlashModel): def _draft_logits(self, batch): backbone = super()._draft_logits(batch).backbone return DraftLogits(final=backbone + self.my_head(batch), backbone=backbone) def _compute_loss(self, ctx): out = super()._compute_loss(ctx) # the block objective on ctx.logits.final return out._replace(loss=out.loss + self.my_head_loss(ctx)) outputs = model(**batch) outputs.draft_metrics["selector_accuracy"] # DFlash2: detached 0-dim tensor; .item() for a float ``` ### Testing Re-run on the rebased revision: - `tests/unit/torch/speculative`: 591 passed on transformers 5.18.0, which is CI's `tf_latest` pin. - Bitwise A/B against `main`, the PR's base. It compares loss, every gradient, `train_acc`, the metrics with DFlash2's and LiLiCorr's keys mapped onto `draft_metrics`, and the generated draft tokens. One training step for each of 23 cases, plus one generation step for the online ones, in fp32 and bf16. The cases cover DFlash (KD and CE), DFlash2 (ce, kd, tv and lambda, with the selector), LiLiCorr, DSpark (vanilla and rnn heads, with the confidence head) and Domino, offline and online, with D-PACE and with decay, including zero-loss steps. 44 of the 46 pairs are identical, with no difference anywhere. The other two are the one online Domino case, which runs on neither side: since #2762, `HFDominoModel.pseudo_speculative_generate` raises `NotImplementedError`, which the harness predates. This branch raises the same error at the same line as `main`, and Domino's offline cases match. - The second commit (the move), checked mechanically by parsing both trees: the 11 definitions that leave `hf_dflash.py` and `hf_dspark.py` reappear byte-identically in `dflash_losses.py`. The only other definitions in the new module are `DraftLogits`, `LossOutput` and `LossContext`, which the first commit adds. - Merged with #2761 in a scratch worktree: no conflict, and one `_build_loss_mask` in the result. Run before the rebase, on the old base, and not re-run since: - `tests/unit/torch/speculative` plus `tests/unit/torch/export/test_hf_spec_rope_export.py` on transformers 5.5.4 and 5.12.1. CI's `tf_min` leg covers 5.5. - `tests/gpu/torch/speculative/plugins` on one GPU: 20 passed, 1 skipped (it needs 2 GPUs). - 15 A/B cases beyond the 23 above, all identical: the DSpark gated head, the rnn head online, the KD flag and D-PACE on DSpark and Domino, steps whose position weights sum to <= 1 under DFlash2 (`ce` and `lambda`) and LiLiCorr KD, DFlash2 KD online, and six cases whose labels are -100 on some tokens. - FSDP2: 2 ranks on gloo, the draft as its own `fully_shard` unit, and one rank on the in-loss zero branch. Both ranks finish, under CE and under KD, with the same losses as on the base. DFlash2 and LiLiCorr under the same wrapping stop with the same mixed `Tensor`/`DTensor` error on the base and on this branch; this PR does not change that. New and updated tests: - New: under D-PACE, the context that a real DFlash2 training forward passes to the loss keeps the cross-entropy's gradient for `ce`, `tv` and `lambda` but not for KD. - Mutation check: if `_loss_context` always asks for the gradient, `LossContext` ignores `ce_grad`, or `LossContext.ce` always keeps its graph, the rest of the suite still passes and only the KD case fails. - The bitwise A/B cannot see that change: on the DFlash, DFlash2 and LiLiCorr KD cases the loss and every gradient stay identical. Each KD step under D-PACE, the default configuration, would just hold a vocab-wide graph that it never backpropagates. - Dropping the gradient instead already failed three existing tests, and now also fails the `ce`, `tv` and `lambda` cases. - Updated: the `_compute_loss` tests go through `_loss_context` and `_compute_loss`, and the selector and LiLiCorr metrics are read from `draft_metrics`. "KD without base_outputs raises" becomes "KD without a teacher raises": the context always carries the base outputs, so the remaining failure is a batch with neither the base logits nor its final hidden. ### Before your PR is "*Ready for review*" Make sure you read and follow [Contributor guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md) and your commits are signed (`git commit -s -S`). Make sure you read and follow the [Security Best Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors) (e.g. avoiding hardcoded `trust_remote_code=True`, `torch.load(..., weights_only=False)`, `pickle`, etc.). - Is this change backward compatible?: ❌ Configs and checkpoints are unchanged. However, `draft_metrics` replaces the forward output's `selector_metrics` and `lilicorr_metrics`, and LiLiCorr's values that were Python floats are now 0-dim tensors (see **Metrics** and the CHANGELOG entry). - If you copied code from any other sources or added a new PIP dependency, did you follow guidance in `CONTRIBUTING.md`: ✅ `dflash_losses.py` carries the SpecForge and DeepSpec notices of the two files its code moved from. Like them, it is excluded from the license-insertion hook. - Did you write any new necessary tests?: ✅ One new test pins which objectives keep the cross-entropy's gradient, which the bitwise A/B cannot see. The existing tests now drive the new seam (`_loss_context`, `_compute_loss`, `draft_metrics`), and the A/B covers the rest. - Did you update [Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?: ✅ One Backward Breaking Changes entry for the two metrics keys. - Did you get Claude approval on this PR?: ❌ Not run yet. ### Additional Information Against `main`, the diff is 13 files, +593 / −523; under `modelopt/` alone, 7 files, +507 / −482. By the contributor guide's count, which skips tests, docs and config, 444 lines are added. `dflash_losses.py` is 291 of them: 141 are the eleven definitions moved byte-identically, 68 are `DraftLogits`, `LossOutput` and `LossContext`, and 45 are the license and module headers. Reshaping and moving stay in separate commits. Merge order: this PR, then #2990. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Updates** * DFlash2 and LiLiCorr training forwards now return detached scalar metric tensors together in `draft_metrics`, replacing the separate `selector_metrics` and `lilicorr_metrics` outputs. Integrations that read these metrics should use the consolidated dictionary. * DFlash loss calculations support D-PACE, exponential-decay, and unweighted position weighting. Invalid positions are excluded from the loss, and batches with no trainable positions return zero loss and accuracy. D-PACE settings are validated, and its weights do not receive gradients. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: h-guo18 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
What does this PR do?
Type of change: Bug fix
A DFlash-family drafter's label alignment belongs to its algorithm. DSpark and Domino train block position
kon the token atanchor + k + 1: next-token, so the anchor is itself a prediction. DFlash, DFlash2 and LiLiCorr train it onanchor + k: each masked position predicts itself. Since #2757 the class constant_label_shiftdrives the training targets, but onmainthe same fact is still written in four more places, and the exports read it from the user's config:DSparkModule.shift_label, hard-codedTrue.DominoModule.shift_label, read from the config.NotImplementedErrorinHFDominoModel.modify.getattr(draft_config, "shift_label", True), plus a literalsample_from_anchor: Truein the vanilla DSpark export.Three bugs follow:
shift_labelin the config is ignored or contradicted.shift_label: falsetrains next-token alignment anyway and exportsshift_label: false, so a loader that honors the field reads every drafted position one token off.DSparkModulecastsmarkov_rankto int, so a rank written as64.0trains a rank-64 head and exports64.0.Qwen3DSparkModelsizes its Markov table.use_confidence_headand Domino'spure_draft_prefix_lenare re-read with defaults of their own.HFDominoModelinherits DFlash'spseudo_speculative_generate, which decodes block positions1..bs-1with the backbone alone, so every draft is scored against the wrong target. Shipped training is unaffected:domino.yamlkeeps AR validation off.The fixes:
projector_typealone.shift_labelis deprecated and will be removed in 0.50. Before converting the model,convert_to_dflash_modelcompares it with the wrapper class's_label_shift:FutureWarning. Configs copied from the old Domino recipe (shift_label: true) keep working through the migration window in the README's deprecation policy.HFDFlashModel.modifydoes for RoPE: onmaina contradicting value was already ignored or refused. DFlash, DFlash2 and LiLiCorr ignored it, DSpark trained next-token anyway, and Domino refusedfalse. Overriding it with a warning would let a run go on that does not train what its config says.DFlashConfigvalidator: the alignment lives on the plugin's wrapper class, which the config layer does not import. A validator would also run on restore, where old checkpoints carry contradicting values.restore_dflash_modeldrops the key unchecked before replaying convert, so checkpoints that carry it still load. DSpark ones saved withshift_label: falsenow re-exporttrue._DEPRECATED_ARCHITECTURE_KEYSindflash/conversion.py. It pairs each key with the model attribute that now fixes its value, and the reason, so the check and the restore filter cannot drift apart.shift_label, and DSpark'ssample_from_anchor(vLLM's name for the same alignment), from_label_shift.shift_labelattributes and Domino's own check are gone. The Domino recipe, the skill sheets and the test configs no longer set the key.markov_rank,markov_head_type,use_confidence_head,pure_draft_prefix_len,gru_hidden_dimandemb_dim, asLiLiCorrExporteralready does.pseudo_speculative_generateraisesNotImplementedError.HF AR validation is being deprecated (Deprecate HF acceptance-rate validation of draft models #3107), so Domino gets no decode of its own.
Domino acceptance cannot be measured anywhere yet:
DFlashDraftModel, so vLLM would serve it the same way.examples/specdec_benchhas no Domino route.The error, the changelog and the skill sheet now say so, matching the launcher example's note.
The eval-time warning that called acceptance rates "backbone-only" is removed. The
forwarddocstring and the skill sheet now note that eval loss and accuracy exclude the correction head; the recipe setsdo_eval: false.During training, the AR callback already catches the error and logs
AR validation not available.shift_label, and a Bug Fixes entry for the exports and Domino's AR validation.Usage
Remove
shift_labelfrom DFlash-family configs, sinceprojector_typefixes the alignment. Until 0.50 a value that matches the variant only warns:Testing
test_deprecated_shift_label[dflash|dspark|domino x true|false]restores a modelopt_state that carriesshift_label, then converts with it. A matching value warns, converts, and is not saved in the new modelopt_state. A contradicting one raises and leaves the model unconverted.main(09a14b9).test_export_config_has_dspark_fieldsconverts withmarkov_rankgiven as a float and expects an int at both config levels. All 8 cases fail without the exporter change.TestDominoForward::test_ar_validation_is_refusedfails without the override, because the inherited decode then runs.main(ef893e7) as bd19e2d.git range-diffshows the same changes commit for commit; only the skill sheets' new location underskills/modelopt-speculative-decoding/and CHANGELOG context differ.test_hf_{dflash,dflash2,dspark,domino,lilicorr}.py,tests/unit/recipe,tests/unit/torch/export/test_hf_spec_rope_export.py,tests/unit/examples/test_deepseek_v4_recipe.pyandtools/launcher/tests/test_examples_resolve.py: 987 passed.test_hf_{dflash,dflash2,dspark,domino,lilicorr}.py, 318 passed.shift_labelcheck, Domino's error text and docs:tests/unit/recipe/test_loader.py,tests/unit/torch/export/test_hf_spec_rope_export.pyandtests/unit/examples/test_deepseek_v4_recipe.py: 834 passed.tools/launcher/tests/test_examples_resolve.py: 75 passed.tests/gpu/torch/speculative/plugins/test_hf_dflash.pyon 2 GPUs (torch 2.13): 16 passed.Before your PR is "Ready for review"
Make sure you read and follow Contributor guidelines and your commits are signed (
git commit -s -S).Make sure you read and follow the Security Best Practices (e.g. avoiding hardcoded
trust_remote_code=True,torch.load(..., weights_only=False),pickle, etc.).shift_labelthat matches the variant, including the shipped Domino recipe'strue. Such configs convert as before, with a deprecation warning.shift_label, which now raises at convert: it never took effect. That is DFlash, DFlash2 or LiLiCorr withtrue, and DSpark or Domino withfalse.shift_label: falseraisesValueErrorinstead ofNotImplementedError.CONTRIBUTING.md: N/Ashift_label, and a Bug Fixes entry, since DSpark and Domino have shipped since 0.46.0.Additional Information
Follow-up to #2757, now merged. The shared-forward PRs, #2989 [1/2] and then #2990 [2/2], build on this branch and will be restacked onto it.
Found while testing and not fixed here; it fails the same way on
main: withDFlashModuleas its own FSDP2 unit, DSpark and Domino training fails withgot mixed torch.Tensor and DTensor, because their heads run outsideDFlashModule.forward.🤖 Generated with Claude Code
Summary by CodeRabbit
shift_labelis deprecated and planned for removal in version 0.50. Matching values are ignored with a warning; conflicting values cause an error. Existing checkpoints containing the setting can still be loaded.