Skip to content

fix(speculative): one label alignment per projector_type; DSpark and Domino export the head they built - #2762

Merged
h-guo18 merged 8 commits into
mainfrom
haoguo/dflash-label-alignment
Nov 15, 2026
Merged

h-guo18 merged 8 commits into
mainfrom
haoguo/dflash-label-alignment

Conversation

@h-guo18

@h-guo18 h-guo18 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

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 k on the token at anchor + k + 1: next-token, so the anchor is itself a prediction. DFlash, DFlash2 and LiLiCorr train it on anchor + k: each masked position predicts itself. Since #2757 the class constant _label_shift drives the training targets, but on main the same fact is still written in four more places, and the exports read it from the user's config:

  • DSparkModule.shift_label, hard-coded True.
  • DominoModule.shift_label, read from the config.
  • A NotImplementedError in HFDominoModel.modify.
  • The exporters' getattr(draft_config, "shift_label", True), plus a literal sample_from_anchor: True in the vanilla DSpark export.

Three bugs follow:

  1. shift_label in the config is ignored or contradicted.
    • DSpark with shift_label: false trains next-token alignment anyway and exports shift_label: false, so a loader that honors the field reads every drafted position one token off.
    • Domino refuses it, but only after building the draft.
    • DFlash, DFlash2 and LiLiCorr accept the field and ignore it.
  2. The exporters re-read head fields from the raw config.
    • DSparkModule casts markov_rank to int, so a rank written as 64.0 trains a rank-64 head and exports 64.0.
    • The vanilla export copies that value to the top level, where vLLM's Qwen3DSparkModel sizes its Markov table.
    • use_confidence_head and Domino's pure_draft_prefix_len are re-read with defaults of their own.
  3. Domino's HF AR validation drafts one position off, without its head. HFDominoModel inherits DFlash's pseudo_speculative_generate, which decodes block positions 1..bs-1 with the backbone alone, so every draft is scored against the wrong target. Shipped training is unaffected: domino.yaml keeps AR validation off.

The fixes:

  • The alignment comes from projector_type alone.
    • shift_label is deprecated and will be removed in 0.50. Before converting the model, convert_to_dflash_model compares it with the wrapper class's _label_shift:
      • A matching value is dropped with a FutureWarning. Configs copied from the old Domino recipe (shift_label: true) keep working through the migration window in the README's deprecation policy.
      • A contradicting value raises, because it never took effect.
    • Why the check does not warn and override, as HFDFlashModel.modify does for RoPE: on main a contradicting value was already ignored or refused. DFlash, DFlash2 and LiLiCorr ignored it, DSpark trained next-token anyway, and Domino refused false. Overriding it with a warning would let a run go on that does not train what its config says.
    • Why it is not a DFlashConfig validator: 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_model drops the key unchecked before replaying convert, so checkpoints that carry it still load. DSpark ones saved with shift_label: false now re-export true.
    • Both halves read one table, _DEPRECATED_ARCHITECTURE_KEYS in dflash/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.
    • The exports write shift_label, and DSpark's sample_from_anchor (vLLM's name for the same alignment), from _label_shift.
    • The modules' shift_label attributes and Domino's own check are gone. The Domino recipe, the skill sheets and the test configs no longer set the key.
  • The exporters read the built head for markov_rank, markov_head_type, use_confidence_head, pure_draft_prefix_len, gru_hidden_dim and emb_dim, as LiLiCorrExporter already does.
  • Domino's pseudo_speculative_generate raises NotImplementedError.
    • 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:

      • The inherited decode drafts with the backbone alone, one block position off.
      • The export declares DFlashDraftModel, so vLLM would serve it the same way.
      • examples/specdec_bench has 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 forward docstring and the skill sheet now note that eval loss and accuracy exclude the correction head; the recipe sets do_eval: false.

    • During training, the AR callback already catches the error and logs AR validation not available.

  • Changelog (0.49.0): a Deprecations entry for shift_label, and a Bug Fixes entry for the exports and Domino's AR validation.

Usage

Remove shift_label from DFlash-family configs, since projector_type fixes the alignment. Until 0.50 a value that matches the variant only warns:

dflash:
  dflash_architecture_config:
    projector_type: domino
    # shift_label: true  # deprecated: warns until 0.50; false raises

Testing

  • New and changed tests:
    • test_deprecated_shift_label[dflash|dspark|domino x true|false] restores a modelopt_state that carries shift_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.
      • All 6 cases fail on main (09a14b9).
      • With the previous revision's refusal (39ffc25), the 3 matching cases fail.
      • Without the restore filter, the 3 contradicting cases fail at restore.
    • test_export_config_has_dspark_fields converts with markov_rank given as a float and expects an int at both config levels. All 8 cases fail without the exporter change.
    • TestDominoForward::test_ar_validation_is_refused fails without the override, because the inherited decode then runs.
  • Rebased onto main (ef893e7) as bd19e2d. git range-diff shows the same changes commit for commit; only the skill sheets' new location under skills/modelopt-speculative-decoding/ and CHANGELOG context differ.
  • At bd19e2d, Python 3.12, transformers 5.18.0, torch 2.13: 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.py and tools/launcher/tests/test_examples_resolve.py: 987 passed.
  • Before the rebase, at a944d85, Python 3.12, transformers 5.18.0, torch 2.10: test_hf_{dflash,dflash2,dspark,domino,lilicorr}.py, 318 passed.
  • At 39ffc25, which differs from the head only in the shift_label check, Domino's error text and docs:
    • Those five files plus tests/unit/recipe/test_loader.py, tests/unit/torch/export/test_hf_spec_rope_export.py and tests/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.py on 2 GPUs (torch 2.13): 16 passed.
  • Not run:
    • transformers 5.5 and 5.12, which CI's multi-version job covers. An earlier revision passed 792 of these tests on 5.5.4, 5.12.1 and 5.18.0.
    • A bitwise A/B, because no training code changes.

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

  • Is this change backward compatible?:
    • ✅ for a shift_label that matches the variant, including the shipped Domino recipe's true. Such configs convert as before, with a deprecation warning.
    • ❌ for a contradicting shift_label, which now raises at convert: it never took effect. That is DFlash, DFlash2 or LiLiCorr with true, and DSpark or Domino with false.
    • Existing checkpoints still load.
    • Domino with shift_label: false raises ValueError instead of NotImplementedError.
    • Domino's HF AR validation raises instead of returning misaligned drafts.
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: ✅ 0.49.0: a Deprecations entry for shift_label, and a Bug Fixes entry, since DSpark and Domino have shipped since 0.46.0.
  • Did you get Claude approval on this PR?: ✅ Approved at 39ffc25. Its one suggestion is addressed at the head.

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: with DFlashModule as its own FSDP2 unit, DSpark and Domino training fails with got mixed torch.Tensor and DTensor, because their heads run outside DFlashModule.forward.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Corrected DSpark and Domino export settings to reflect the built model configuration.
    • Fixed a validation error in Domino’s Hugging Face autoregressive validation; this validation is not supported for Domino.
  • Deprecations
    • shift_label is 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.
  • Documentation
    • Updated speculative decoding guidance to reflect the deprecation and Domino’s evaluation limitations.

@copy-pr-bot

copy-pr-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

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.

@coderabbitai

coderabbitai Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The changes deprecate shift_label in architecture configuration, update DSpark and Domino export fields to use built-head values, and make Domino Hugging Face pseudo-speculative generation raise NotImplementedError.

Changes: Speculative decoding configuration and validation

Layer / File(s) Summary
Label alignment configuration and compatibility
modelopt/torch/speculative/dflash/conversion.py, modelopt/torch/speculative/plugins/modeling_*.py, tests/unit/torch/speculative/plugins/test_hf_dflash.py, modelopt_recipes/general/speculative_decoding/domino.yaml, skills/modelopt-speculative-decoding/references/algorithms/*.md, CHANGELOG.rst
Conversion warns and removes matching legacy shift_label values, rejects mismatches, and drops the key during restore. DSpark and Domino modules no longer store the setting. Tests and guidance cover the compatibility behavior.
Head-derived export configuration
modelopt/torch/export/plugins/hf_spec_export.py, tests/unit/torch/speculative/plugins/test_hf_dspark.py, CHANGELOG.rst
Domino and DSpark exporters source fields from built modules and derive alignment fields from model._label_shift. DSpark export tests check integer markov_rank values.
Domino Hugging Face autoregressive validation
modelopt/torch/speculative/plugins/hf_domino.py, tests/unit/torch/speculative/plugins/test_hf_domino.py, modelopt_recipes/general/speculative_decoding/domino.yaml, tools/launcher/examples/Qwen/Qwen3-8B/hf_online_domino.yaml, skills/modelopt-speculative-decoding/references/algorithms/domino.md
Domino pseudo-speculative generation raises NotImplementedError. Tests and supporting guidance describe the unavailable Hugging Face autoregressive validation path.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Suggested reviewers: chenhanyu, cjluo-nv

Merge Risk: Minimal · up to bd19e

This change makes label alignment follow the projector type and makes Domino acceptance validation fail explicitly instead of producing misleading numbers. No merge-blocking risk was identified.

Architecture risk: Low · up to bd19e

The change affects 6 systems.

Changed systems: modelopt, tests, skills, CHANGELOG.rst, modelopt_recipes, tools

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — modelopt (service) was modified; 5 changed files map to changed impact.
  • observed — tests (service) was modified; 3 changed files map to changed impact.
  • observed — skills (service) was modified; 2 changed files map to changed impact.
  • observed — CHANGELOG.rst (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in modelopt/torch/export/plugins/hf_spec_export.py: DominoExporter._export_config now reads head dimensions from the built module instead of dflash_config and its defaults, and sets shift_label from model._label_shift instead of the config value/default.
  • observed — Modified behavior in modelopt/torch/export/plugins/hf_spec_export.py: DSparkExporter._export_config now takes markov_rank, markov_head_type, and use_confidence_head from the built head rather than mixing config and module values; shift_label now comes from model._label_shift instead of the config value/default.
  • observed — Modified behavior in modelopt/torch/export/plugins/hf_spec_export.py: For vanilla DSpark exports, sample_from_anchor now follows model._label_shift rather than always being True.
  • observed — Modified behavior in modelopt/torch/speculative/plugins/modeling_domino.py: The self.shift_label assignment, which read config.shift_label with a default of True, was removed.
Pre-merge checks: Passed 5

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the two main themes of the changeset: label alignment is now chosen once per projector_type (shift_label is deprecated and removed from configs), and DSpark and Domino exports now take…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed The check looks for six security anti-patterns in the PR's changes. I ran the PR range diff (refs/coderabbit/pre-merge-check/base to head) and searched every added line for weights_only, `allow_pick…
Full details: Title check

Explanation

The title names the two main themes of the changeset: label alignment is now chosen once per projector_type (shift_label is deprecated and removed from configs), and DSpark and Domino exports now take their fields from the head the code actually built. The changeset matches both parts, including the shift_label deprecation, the export-source changes in hf_spec_export.py, and the Domino pseudo_speculative_generate change. The title is specific and uses a conventional commit prefix. It does not mention the Domino NotImplementedError, which is a notable behavior change, but that is a secondary point and not required for the title to pass.

Full details: Security Anti-Patterns

Explanation

The check looks for six security anti-patterns in the PR's changes. I ran the PR range diff (refs/coderabbit/pre-merge-check/base to head) and searched every added line for weights_only, allow_pickle, trust_remote_code, eval(, exec(, nosec, pickle, torch.load, np.load/numpy.load, and dependency keywords. There were no matches. The changed files are CHANGELOG.rst, the DFlash/DSpark/Domino export, conversion and plugin modules, the Domino recipe YAML, skill docs, one launcher YAML, and three unit test files. None of them changes pyproject.toml, requirements*.txt, setup.py or setup.cfg, so no new pip dependency was added. The PR adds no nosec bypass and no new torch.load, numpy.load or trust_remote_code call. The supplied review findings are zero. The PR does not introduce any of the listed security anti-patterns.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a944d85 and bd19e2d.

Files selected for processing: 3

  • CHANGELOG.rst
  • skills/modelopt-speculative-decoding/references/algorithms/domino.md
  • skills/modelopt-speculative-decoding/references/algorithms/dspark.md
Files skipped from review as they are similar to previous changes: 1

  • CHANGELOG.rst

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.2
Preview removed because the pull request was closed.
2026-11-15 15:20 UTC

@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.15%. Comparing base (ef893e7) to head (bd19e2d).
⚠️ Report is 2 commits behind head on main.

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     
Flag Coverage Δ
examples-diffusers 19.90% <28.57%> (+<0.01%) ⬆️
examples-gpt-oss 13.54% <28.57%> (+<0.01%) ⬆️
examples-hf_ptq 24.30% <28.57%> (-0.85%) ⬇️
examples-llm_distill 13.60% <28.57%> (+<0.01%) ⬆️
examples-llm_eval 17.53% <28.57%> (+<0.01%) ⬆️
examples-llm_qat 17.35% <28.57%> (-0.03%) ⬇️
examples-llm_sparsity 16.88% <28.57%> (+<0.01%) ⬆️
examples-megatron_bridge 26.11% <28.57%> (-0.14%) ⬇️
examples-specdec_bench 13.32% <28.57%> (+<0.01%) ⬆️
examples-speculative_decoding 17.75% <28.57%> (-0.06%) ⬇️
examples-torch_onnx 21.00% <28.57%> (-0.02%) ⬇️
examples-torch_trt 15.26% <28.57%> (+<0.01%) ⬆️
examples-vllm_serve 17.60% <28.57%> (+<0.01%) ⬆️
gpu 59.33% <50.00%> (+3.80%) ⬆️
regression 15.01% <57.14%> (+<0.01%) ⬆️
unit 64.33% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@h-guo18 h-guo18 changed the title fix(speculative): DSpark and Domino label alignment and exported head fields fix(speculative): one label alignment per projector_type; DSpark and Domino export the head they built Nov 8, 2026
@h-guo18
h-guo18 marked this pull request as ready for review November 8, 2026 09:06
@h-guo18
h-guo18 requested review from a team as code owners November 8, 2026 09:06
@h-guo18

h-guo18 commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

/claude review

@ChenhanYu ChenhanYu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.py and test_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.md and CONTRIBUTING.md read at 09a14b9ae89522363ffca9b0ac2245cbbb073fdd.
  • Tests were not executed; current-head CI results were unavailable. Duplicate checking covers the supplied bounded history, which contains no substantive prior findings.

Review baseline: https://github.com/NVIDIA/Model-Optimizer/blob/86bd9b78425a23a45b329c7c9b86ea772d7a9e77/.agents/review-guidelines/code-review.md

Review run: d7bedb27945848d78d5539667612d5fa

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_shift is 1 for HFDSparkModel/HFDominoModel and 0 for HFDFlashModel, each variant has exactly one wrapper class with its own get_exporter, so bool(self.model._label_shift) and sample_from_anchor are right for every export path. head.markov_rank/markov_head_type/use_confidence_head are the int/lower-cased/bool values the module built, so the config.json stays JSON-clean.
  • Convert refuses retired keys before init_modellike, and restore_dflash_model filters the same table after model_copy, so old checkpoints (including DSpark ones saved with shift_label: false) replay convert and keep the alignment they trained with. No remaining reader of the deleted shift_label attributes.
  • Domino's pseudo_speculative_generate signature matches the parent's, and the trainer's AR callback catches Exception, so training logs AR 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: false in the recipe limits the impact.
  • Baseline commit 09a14b9; reviewed head 39ffc25. I did not run tests or CI — the PR's reported results are unverified here. Skill edits are net-shorter; no licensing surface.

@meenchen meenchen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_label values through README’s migration window; explain hard rejection versus DFlashConfig validation 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.py comment).

No action needed:

  • Existing test edits are justified: removing retired fixture keys and strengthening export-type assertions retain the previous coverage.

h-guo18 and others added 8 commits November 15, 2026 14:40
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]>
… 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]>
@h-guo18
h-guo18 force-pushed the haoguo/dflash-label-alignment branch from a944d85 to bd19e2d Compare November 15, 2026 14:47
@h-guo18
h-guo18 enabled auto-merge (squash) November 15, 2026 14:50
@h-guo18
h-guo18 merged commit 9047bbd into main Nov 15, 2026
49 checks passed
@h-guo18
h-guo18 deleted the haoguo/dflash-label-alignment branch November 15, 2026 15:20
h-guo18 added a commit that referenced this pull request Nov 16, 2026
…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]>
h-guo18 added a commit that referenced this pull request Nov 25, 2026
…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]>
h-guo18 added a commit that referenced this pull request Nov 25, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants