Skip to content

[3/3][Refactor]: Extract HFSpecDecMixin for HF spec-decoding plugins - #1297

Closed
h-guo18 wants to merge 3 commits into
mainfrom
haoguo/spec-mixin-new
Closed

h-guo18 wants to merge 3 commits into
mainfrom
haoguo/spec-mixin-new

Conversation

@h-guo18

@h-guo18 h-guo18 commented Apr 19, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: refactoring

Part 3 of a 3-PR series splitting #1271:

Changes:

  • New modelopt/torch/speculative/plugins/hf_spec_mixin.py containing HFSpecDecMixin with:
    • Properties: _base_model, _base_model_embeddings, _base_model_lm_head, _base_llm_config (VLM-aware).
    • modify() MRO hook — auto-discovers base-model paths after the algorithm base's modify() runs, so subclasses no longer need to call _find_base_model_parts() explicitly.
    • _nvtx_range() and _activate_torch_compile() driven by subclass _compile_targets / _enable_nvtx.
    • get_exporter() declared as @abstractmethod so missing implementations fail at instantiation time.
  • HFEagleModel now (HFSpecDecMixin, EagleModel); drops the duplicated _find_base_model_parts and base-model property helpers; sets _compile_targets and self._enable_nvtx in modify().
  • HFDFlashModel now (HFSpecDecMixin, DFlashModel); drops the duplicated helpers.

Testing

No behavioral change expected. Verified MRO includes HFSpecDecMixin and existing Eagle/DFlash training scripts run unchanged.

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?: ✅ — internal refactor; no public API change.
  • 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?: N/A — pure refactor.
  • Did you update Changelog?: ❌

Additional Information

Base branch is #1295. Retarget to main once #1296 and #1295 merge.

Summary by CodeRabbit

  • Refactor
    • Reorganized internal speculative decoding model implementations to reduce code duplication and improve long-term maintainability.
    • Consolidated shared base-model discovery and torch compilation functionality across speculative decoding models.

Review Change Stack

@copy-pr-bot

copy-pr-bot Bot commented Apr 19, 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 Apr 19, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Speculative-decoding model classes HFEagleModel and HFDFlashModel are refactored to inherit from a new HFSpecDecMixin mixin class. The mixin centralizes base-model submodule discovery, NVTX profiling, and torch-compilation behavior previously duplicated across models. Both models now declare abstract interface methods and remove old implementations.

Changes

Speculative Decoding Model Refactoring

Layer / File(s) Summary
HFSpecDecMixin mixin class definition
modelopt/torch/speculative/plugins/hf_spec_mixin.py
New mixin provides base-model discovery by iterating candidate submodule paths, lifecycle integration through modify(), optional NVTX-guarded profiling, torch-compilation with per-method fallback, and abstract interface methods get_exporter() and get_dummy_inputs() for subclasses.
HFEagleModel integration with mixin
modelopt/torch/speculative/plugins/hf_eagle.py
HFEagleModel now inherits from HFSpecDecMixin and removes previous base-model property implementations; defines _compile_targets class attribute for torch compilation; sets _enable_nvtx during modify() from eagle_enable_nvtx; removes explicit _find_base_model_parts() call.
HFDFlashModel integration with mixin
modelopt/torch/speculative/plugins/hf_dflash.py
HFDFlashModel now inherits from HFSpecDecMixin and removes previous base-model property and discovery implementations; adds get_dummy_inputs() method raising NotImplementedError as required by export interface.
Documentation reference update
modelopt/torch/speculative/plugins/modeling_fakebase.py
Comment describing candidate module paths updated to reference HFSpecDecMixin._find_base_model_parts instead of the removed HFEagleModel._find_base_model_parts.

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 6
✅ Passed checks (6 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately describes the main refactoring work: extracting a new HFSpecDecMixin and updating HF spec-decoding plugins to use it.
Docstring Coverage ✅ Passed Docstring coverage is 81.25% which is sufficient. The required threshold is 80.00%.
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 No security anti-patterns found: no unsafe torch.load, numpy.load, trust_remote_code, eval/exec, nosec comments, or new dependencies.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch haoguo/spec-mixin-new

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Comment @coderabbitai help to get the list of available commands and usage tips.

@h-guo18 h-guo18 changed the title [Refactor]: HFSpecDecMixin shared across HF spec-decoding plugins [3/3][Refactor]: Extract HFSpecDecMixin for HF spec-decoding plugins Apr 19, 2026
@h-guo18
h-guo18 force-pushed the haoguo/dflash-offline branch 2 times, most recently from f7a27dc to e063406 Compare April 23, 2026 21:45
Base automatically changed from haoguo/dflash-offline to haoguo/spec-file-reorg April 23, 2026 22:05
@h-guo18
h-guo18 force-pushed the haoguo/spec-file-reorg branch from aedd188 to 536ea48 Compare April 23, 2026 22:08
@h-guo18 h-guo18 mentioned this pull request Apr 23, 2026
1 task done
h-guo18 added a commit that referenced this pull request Apr 24, 2026
### What does this PR do?

Type of change: refactoring

Part 1 of a 3-PR series splitting #1271:
- **[1/3] this PR**: File reorg + deprecate `ParallelDraft`
- **[2/3] #1295**: Offline DFlash training
- **[3/3] #1297**: Extract `HFSpecDecMixin`

Changes:
- **File reorg**: `transformers.py` → `hf_eagle.py`; extract
`HFMedusaModel` → `hf_medusa.py`; extract `EagleModule` /
`EagleBaseModelOutput` → `modeling_eagle.py`; extract `DFlashModule` /
`DFlashAttention` / `DFlashDecoderLayer` / `build_target_layer_ids` /
`apply_rotary_pos_emb` → `modeling_dflash.py`.
- **Deprecate `ParallelDraft`**: remove `parallel_draft_step`,
`parallel_draft_heads_num_layers`, and the `ParallelDraft` module from
HF Eagle; remove the `EagleMedusaExporter` branch from
`HFEagleModel.get_exporter()` (the `EagleMedusaExporter` class itself
still lives in `hf_spec_export.py` for Megatron parity).
- **Rename**: `_draft_model_config` → `eagle_config` in export plugin.
- Update imports in `examples/speculative_decoding/` and
`modelopt/torch/speculative/utils.py` to follow the module rename.

### Testing

Validated with existing Eagle and DFlash training scripts (re-run after
`9ae5302729 revert behavior change`).

### 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?: ❌ — renames
`modelopt.torch.speculative.plugins.transformers` → `.hf_eagle`; removes
`parallel_draft_step` / `parallel_draft_heads_num_layers` from Eagle
config; renames `_draft_model_config` → `eagle_config` in export plugin.
- 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?: N/A — pure refactor; existing
tests updated for the rename. `test_hf_spec_rope_export.py` assertions
were also corrected to reflect the actual production path (the old
assertions were masked by `MagicMock` not invoking the
`_draft_model_config` `@property`).
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
❌

### Additional Information

Breaking changes:
- `modelopt.torch.speculative.plugins.transformers` → `.hf_eagle`
- `parallel_draft_step` / `parallel_draft_heads_num_layers` removed from
Eagle config
- `_draft_model_config` → `eagle_config` in export plugin

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Refactoring**
* Reorganized speculative-decoding plugins into focused modules,
converting the legacy "transformers" entry into a deprecated shim that
re-exports the new plugin surface.
* Consolidated DFlash implementation into a shared modeling component
and introduced a dedicated EAGLE decoder module.

* **New Features**
* Added a Medusa speculative-decoding plugin with configurable heads and
combined-loss training behavior.

* **Chores**
  * Updated pre-commit license-hook exclusion and feature-flag wiring.

* **Tests**
  * Updated export tests to expect rope-scaling fallback semantics.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: h-guo18 <[email protected]>
Base automatically changed from haoguo/spec-file-reorg to main April 24, 2026 21:46
@h-guo18 h-guo18 mentioned this pull request Apr 24, 2026
1 task done
ChenhanYu pushed a commit that referenced this pull request Apr 26, 2026
### What does this PR do?

Type of change: new feature

Part 2 of a 3-PR series splitting #1271:
- **[1/3] #1296**: File reorg + deprecate `ParallelDraft`
- **[2/3] this PR**: Offline DFlash training (depends on #1296)
- **[3/3] #1297**: Extract `HFSpecDecMixin`

Changes:
- Add `dflash_offline` flag to `DFlashConfig` for training from
pre-computed hidden states; deletes base model layers to save memory.
- Add Pydantic validators on `DFlashConfig`:
- `_derive_dflash_offline` — auto-derive `dflash_offline` from
`data_args.offline_data_path` in validation context. Not
user-configurable: any user-supplied value is overridden by the derived
value.
- `_resolve_mask_token_id` — auto-detect `dflash_mask_token_id` from
`tokenizer.mask_token_id`.
  - `_check_mask_token_id` — fail fast if unset after resolution.
- `HFDFlashModel.modify()`: select `num_orig_hidden_layers` when
offline; pick `_base_model_lm_head` device when no base layers present;
drop base-model `layers` module.
- `HFDFlashModel.forward()`: add offline branch — consumes precomputed
`base_model_outputs` via `DFlashBaseModelOutput.from_offline_dict`, and
when `dflash_self_logit_distillation` is enabled with
`base_model_logits` absent, recomputes logits from
`base_model_hidden_states` via `_base_model_lm_head`. Raises a clear
error from the non-training / `pseudo_speculative_generate` paths when
`dflash_offline=True`, since base-model layers have been deleted.
- `DFlashBaseModelOutput` dataclass in `modeling_dflash.py` (with
`from_offline_dict` classmethod) to unify online/offline output shapes.
`aux_hidden_states` is required in `from_offline_dict` so missing keys
fail fast at the entry point rather than deeper in the forward.
- `examples/speculative_decoding/main.py`: replace inline
`mask_token_id` auto-detect with
`DFlashConfig.model_validate(dflash_cfg, context={"tokenizer":
tokenizer, "data_args": data_args})`.

### Silent bug fix — `add_generation_template` → `add_generation_prompt`

The pre-refactor `compute_hidden_states_hf.py` passed
`add_generation_template=False` to `tokenizer.apply_chat_template`. This
kwarg does not exist on HF `apply_chat_template` and was being silently
ignored, so the intended "don't append a generation prompt" behavior was
never actually applied. The new `tokenize_with_loss_mask` helper in
`examples/speculative_decoding/collect_hidden_states/common.py` uses the
correct `add_generation_prompt=False`. **This is a real behavior
change** for anyone re-dumping hidden states: trailing generation
prompts that were previously appended to the tokenized sequences will no
longer be included.


### Testing
- New tests:
- `tests/unit/torch/speculative/plugins/test_hf_dflash_offline.py` — CPU
unit tests for convert path (online keeps base layers, offline deletes
them; `num_orig_hidden_layers` drives `target_layer_ids` in offline
mode) and `DFlashConfig._derive_dflash_offline` validator.
- `TestDFlashOfflineForwardGPU` in
`tests/gpu/torch/speculative/plugins/test_hf_dflash.py` — GPU forward
smoke with precomputed `base_model_outputs`, plus the
`dflash_self_logit_distillation` logit-recompute path.

- training test:
<img width="454" height="317" alt="image"
src="https://github.com/user-attachments/assets/79b92790-4d15-4313-bb9b-f35665b012e6"
/> <img width="456" height="310" alt="image"
src="https://github.com/user-attachments/assets/4558559f-9c35-49ed-b36e-82fbc99eab23"
/>


### 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?: ✅ — additive `dflash_offline`
flag defaulting to `False`; validators fall through when context not
provided.
- 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?: ✅ — see Testing section above.
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅

### TODO (follow-up)

- [x] Update
`examples/speculative_decoding/collect_hidden_states/compute_hidden_states_*.py`
to support DFlash offline data. Current scripts are Eagle-specific —
they hardcode the `[2, N/2, N-3]` aux-layer selection and emit
`{input_ids, hidden_states, aux_hidden_states}`. DFlash offline needs:
- Aux layer indices driven by
`build_target_layer_ids(num_orig_hidden_layers, num_draft_layers)` (or a
configurable list), not the Eagle triplet.
- `base_model_hidden_states` key (last-layer hidden) so
`DFlashBaseModelOutput.from_offline_dict` + the
`dflash_self_logit_distillation` recompute path can consume it.
- Optional `base_model_logits` dump so offline training can skip the
self-distillation logit recomputation when logits are available.

### Additional Information

Base branch is #1296 (file reorg). Retarget to `main` once #1296 merges.



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Offline DFlash speculative-decoding training from precomputed
base-model hidden states
* Answer-only-loss training with persisted loss masks and optional
chat-template support
* Flexible auxiliary-layer selection via CLI and an exposed default
aux-layer helper
* Auto-derived offline flag in config and automatic memory optimization
during offline conversion

* **Documentation**
* Updated guides for offline pipeline, aux-layer selection, and
loss-masking options

* **Tests**
* New unit, GPU, and regression tests covering offline conversion,
training, and config derivation
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: h-guo18 <[email protected]>
Extract duplicated base-model discovery, forward pass, NVTX profiling, and
torch.compile logic from HFEagleModel / HFDFlashModel into a shared mixin
(hf_spec_mixin.py). HFEagleModel and HFDFlashModel now inherit from
(HFSpecDecMixin, EagleModel/DFlashModel).

Signed-off-by: h-guo18 <[email protected]>
@h-guo18
h-guo18 force-pushed the haoguo/spec-mixin-new branch from 9e4eeb0 to 4be6deb Compare April 27, 2026 04:02
@github-actions

github-actions Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://NVIDIA.github.io/Model-Optimizer/pr-preview/pr-1297/

Built to branch gh-pages at 2026-04-27 06:13 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@codecov

codecov Bot commented Apr 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.01587% with 17 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.70%. Comparing base (1ec931c) to head (4be6deb).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...odelopt/torch/speculative/plugins/hf_spec_mixin.py 70.17% 17 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1297      +/-   ##
==========================================
- Coverage   75.72%   75.70%   -0.03%     
==========================================
  Files         471      472       +1     
  Lines       50375    50367       -8     
==========================================
- Hits        38146    38129      -17     
- Misses      12229    12238       +9     
Flag Coverage Δ
unit 52.74% <73.01%> (-0.03%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 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 added 2 commits April 27, 2026 06:03
Signed-off-by: h-guo18 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
grzegorz-k-karch pushed a commit that referenced this pull request Apr 28, 2026
### What does this PR do?

Type of change: refactoring

Part 1 of a 3-PR series splitting #1271:
- **[1/3] this PR**: File reorg + deprecate `ParallelDraft`
- **[2/3] #1295**: Offline DFlash training
- **[3/3] #1297**: Extract `HFSpecDecMixin`

Changes:
- **File reorg**: `transformers.py` → `hf_eagle.py`; extract
`HFMedusaModel` → `hf_medusa.py`; extract `EagleModule` /
`EagleBaseModelOutput` → `modeling_eagle.py`; extract `DFlashModule` /
`DFlashAttention` / `DFlashDecoderLayer` / `build_target_layer_ids` /
`apply_rotary_pos_emb` → `modeling_dflash.py`.
- **Deprecate `ParallelDraft`**: remove `parallel_draft_step`,
`parallel_draft_heads_num_layers`, and the `ParallelDraft` module from
HF Eagle; remove the `EagleMedusaExporter` branch from
`HFEagleModel.get_exporter()` (the `EagleMedusaExporter` class itself
still lives in `hf_spec_export.py` for Megatron parity).
- **Rename**: `_draft_model_config` → `eagle_config` in export plugin.
- Update imports in `examples/speculative_decoding/` and
`modelopt/torch/speculative/utils.py` to follow the module rename.

### Testing

Validated with existing Eagle and DFlash training scripts (re-run after
`9ae5302729 revert behavior change`).

### 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?: ❌ — renames
`modelopt.torch.speculative.plugins.transformers` → `.hf_eagle`; removes
`parallel_draft_step` / `parallel_draft_heads_num_layers` from Eagle
config; renames `_draft_model_config` → `eagle_config` in export plugin.
- 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?: N/A — pure refactor; existing
tests updated for the rename. `test_hf_spec_rope_export.py` assertions
were also corrected to reflect the actual production path (the old
assertions were masked by `MagicMock` not invoking the
`_draft_model_config` `@property`).
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
❌

### Additional Information

Breaking changes:
- `modelopt.torch.speculative.plugins.transformers` → `.hf_eagle`
- `parallel_draft_step` / `parallel_draft_heads_num_layers` removed from
Eagle config
- `_draft_model_config` → `eagle_config` in export plugin

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Refactoring**
* Reorganized speculative-decoding plugins into focused modules,
converting the legacy "transformers" entry into a deprecated shim that
re-exports the new plugin surface.
* Consolidated DFlash implementation into a shared modeling component
and introduced a dedicated EAGLE decoder module.

* **New Features**
* Added a Medusa speculative-decoding plugin with configurable heads and
combined-loss training behavior.

* **Chores**
  * Updated pre-commit license-hook exclusion and feature-flag wiring.

* **Tests**
  * Updated export tests to expect rope-scaling fallback semantics.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: h-guo18 <[email protected]>
Signed-off-by: Grzegorz Karch <[email protected]>
grzegorz-k-karch pushed a commit that referenced this pull request Apr 28, 2026
### What does this PR do?

Type of change: new feature

Part 2 of a 3-PR series splitting #1271:
- **[1/3] #1296**: File reorg + deprecate `ParallelDraft`
- **[2/3] this PR**: Offline DFlash training (depends on #1296)
- **[3/3] #1297**: Extract `HFSpecDecMixin`

Changes:
- Add `dflash_offline` flag to `DFlashConfig` for training from
pre-computed hidden states; deletes base model layers to save memory.
- Add Pydantic validators on `DFlashConfig`:
- `_derive_dflash_offline` — auto-derive `dflash_offline` from
`data_args.offline_data_path` in validation context. Not
user-configurable: any user-supplied value is overridden by the derived
value.
- `_resolve_mask_token_id` — auto-detect `dflash_mask_token_id` from
`tokenizer.mask_token_id`.
  - `_check_mask_token_id` — fail fast if unset after resolution.
- `HFDFlashModel.modify()`: select `num_orig_hidden_layers` when
offline; pick `_base_model_lm_head` device when no base layers present;
drop base-model `layers` module.
- `HFDFlashModel.forward()`: add offline branch — consumes precomputed
`base_model_outputs` via `DFlashBaseModelOutput.from_offline_dict`, and
when `dflash_self_logit_distillation` is enabled with
`base_model_logits` absent, recomputes logits from
`base_model_hidden_states` via `_base_model_lm_head`. Raises a clear
error from the non-training / `pseudo_speculative_generate` paths when
`dflash_offline=True`, since base-model layers have been deleted.
- `DFlashBaseModelOutput` dataclass in `modeling_dflash.py` (with
`from_offline_dict` classmethod) to unify online/offline output shapes.
`aux_hidden_states` is required in `from_offline_dict` so missing keys
fail fast at the entry point rather than deeper in the forward.
- `examples/speculative_decoding/main.py`: replace inline
`mask_token_id` auto-detect with
`DFlashConfig.model_validate(dflash_cfg, context={"tokenizer":
tokenizer, "data_args": data_args})`.

### Silent bug fix — `add_generation_template` → `add_generation_prompt`

The pre-refactor `compute_hidden_states_hf.py` passed
`add_generation_template=False` to `tokenizer.apply_chat_template`. This
kwarg does not exist on HF `apply_chat_template` and was being silently
ignored, so the intended "don't append a generation prompt" behavior was
never actually applied. The new `tokenize_with_loss_mask` helper in
`examples/speculative_decoding/collect_hidden_states/common.py` uses the
correct `add_generation_prompt=False`. **This is a real behavior
change** for anyone re-dumping hidden states: trailing generation
prompts that were previously appended to the tokenized sequences will no
longer be included.

### Testing
- New tests:
- `tests/unit/torch/speculative/plugins/test_hf_dflash_offline.py` — CPU
unit tests for convert path (online keeps base layers, offline deletes
them; `num_orig_hidden_layers` drives `target_layer_ids` in offline
mode) and `DFlashConfig._derive_dflash_offline` validator.
- `TestDFlashOfflineForwardGPU` in
`tests/gpu/torch/speculative/plugins/test_hf_dflash.py` — GPU forward
smoke with precomputed `base_model_outputs`, plus the
`dflash_self_logit_distillation` logit-recompute path.

- training test:
<img width="454" height="317" alt="image"
src="https://github.com/user-attachments/assets/79b92790-4d15-4313-bb9b-f35665b012e6"
/> <img width="456" height="310" alt="image"
src="https://github.com/user-attachments/assets/4558559f-9c35-49ed-b36e-82fbc99eab23"
/>

### 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?: ✅ — additive `dflash_offline`
flag defaulting to `False`; validators fall through when context not
provided.
- 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?: ✅ — see Testing section above.
- Did you update
[Changelog](https://github.com/NVIDIA/Model-Optimizer/blob/main/CHANGELOG.rst)?:
✅

### TODO (follow-up)

- [x] Update
`examples/speculative_decoding/collect_hidden_states/compute_hidden_states_*.py`
to support DFlash offline data. Current scripts are Eagle-specific —
they hardcode the `[2, N/2, N-3]` aux-layer selection and emit
`{input_ids, hidden_states, aux_hidden_states}`. DFlash offline needs:
- Aux layer indices driven by
`build_target_layer_ids(num_orig_hidden_layers, num_draft_layers)` (or a
configurable list), not the Eagle triplet.
- `base_model_hidden_states` key (last-layer hidden) so
`DFlashBaseModelOutput.from_offline_dict` + the
`dflash_self_logit_distillation` recompute path can consume it.
- Optional `base_model_logits` dump so offline training can skip the
self-distillation logit recomputation when logits are available.

### Additional Information

Base branch is #1296 (file reorg). Retarget to `main` once #1296 merges.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Offline DFlash speculative-decoding training from precomputed
base-model hidden states
* Answer-only-loss training with persisted loss masks and optional
chat-template support
* Flexible auxiliary-layer selection via CLI and an exposed default
aux-layer helper
* Auto-derived offline flag in config and automatic memory optimization
during offline conversion

* **Documentation**
* Updated guides for offline pipeline, aux-layer selection, and
loss-masking options

* **Tests**
* New unit, GPU, and regression tests covering offline conversion,
training, and config derivation
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: h-guo18 <[email protected]>
Signed-off-by: Grzegorz Karch <[email protected]>
@h-guo18
h-guo18 marked this pull request as ready for review May 15, 2026 20:05
@h-guo18
h-guo18 requested a review from a team as a code owner May 15, 2026 20:05
@h-guo18
h-guo18 requested a review from yeyu-nvidia May 15, 2026 20:05

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
modelopt/torch/speculative/plugins/hf_spec_mixin.py (2)

154-154: ⚡ Quick win

Use logger.warning() instead of print() for error messages.

The module already has a logger configured at line 27. Using print() bypasses the logging infrastructure, making these messages harder to capture/filter in production.

♻️ Proposed fix
-            print(f"Failed to create NVTX range {name}: {e}")
+            logger.warning("Failed to create NVTX range %s: %s", name, e)
-                print(f"Disabling torch.compile for {name} due to compilation error.")
+                logger.warning("Disabling torch.compile for %s due to compilation error.", name)

Also applies to: 171-171

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/speculative/plugins/hf_spec_mixin.py` at line 154, Replace the
direct print calls used when NVTX range creation fails with the module logger
(defined at the top of hf_spec_mixin.py) and log the exception via
logger.warning including the exception object; specifically, in the NVTX range
creation method (the code that prints "Failed to create NVTX range {name}: {e}"
at the two occurrences), swap print(...) for logger.warning("Failed to create
NVTX range %s: %s", name, e) (or equivalent) so messages flow through the
configured logging infrastructure and include the exception details.

163-165: 💤 Low value

Global suppress_errors affects all torch.compile calls in the process.

This is intentional for graceful fallback, but consider adding a brief comment explaining why this global setting is acceptable here (e.g., "Safe to set globally because speculative decoding plugins are loaded early and fallback-to-eager is always acceptable").

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/speculative/plugins/hf_spec_mixin.py` around lines 163 - 165,
Add a short explanatory comment above the global setting of
torch._dynamo.config.suppress_errors in hf_spec_mixin (the lines importing
torch._dynamo and setting suppress_errors = True) that states why the global
change is acceptable here (e.g., plugins load early and speculative decoding
must gracefully fall back to eager execution, so a global suppress is
intentional and safe). Keep the comment concise and reference that this is done
to allow fallback-to-eager for speculative decoding and that these plugins are
initialized early in the process.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@modelopt/torch/speculative/plugins/hf_spec_mixin.py`:
- Line 40: The class declaration for HFSpecDecMixin causes an MRO conflict
because _Host (which is object at runtime) is placed before ABC; change the base
class order in the HFSpecDecMixin definition to inherit from ABC first and _Host
second (i.e., class HFSpecDecMixin(ABC, _Host):) so the C3 linearization is
respected and test collection succeeds.

---

Nitpick comments:
In `@modelopt/torch/speculative/plugins/hf_spec_mixin.py`:
- Line 154: Replace the direct print calls used when NVTX range creation fails
with the module logger (defined at the top of hf_spec_mixin.py) and log the
exception via logger.warning including the exception object; specifically, in
the NVTX range creation method (the code that prints "Failed to create NVTX
range {name}: {e}" at the two occurrences), swap print(...) for
logger.warning("Failed to create NVTX range %s: %s", name, e) (or equivalent) so
messages flow through the configured logging infrastructure and include the
exception details.
- Around line 163-165: Add a short explanatory comment above the global setting
of torch._dynamo.config.suppress_errors in hf_spec_mixin (the lines importing
torch._dynamo and setting suppress_errors = True) that states why the global
change is acceptable here (e.g., plugins load early and speculative decoding
must gracefully fall back to eager execution, so a global suppress is
intentional and safe). Keep the comment concise and reference that this is done
to allow fallback-to-eager for speculative decoding and that these plugins are
initialized early in the process.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: e2f93e76-dbb9-4bd8-b183-25535a1d363a

📥 Commits

Reviewing files that changed from the base of the PR and between 1ec931c and c9b169e.

📒 Files selected for processing (4)
  • modelopt/torch/speculative/plugins/hf_dflash.py
  • modelopt/torch/speculative/plugins/hf_eagle.py
  • modelopt/torch/speculative/plugins/hf_spec_mixin.py
  • modelopt/torch/speculative/plugins/modeling_fakebase.py

__all__ = ["HFSpecDecMixin"]


class HFSpecDecMixin(_Host, ABC):

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.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

MRO conflict causes test collection failure.

At runtime _Host = object, so this declaration becomes class HFSpecDecMixin(object, ABC). Since ABC already inherits from object, placing object before ABC in the MRO violates C3 linearization—Python cannot resolve the inheritance order.

Swap the base class order so ABC comes first:

🐛 Proposed fix
-class HFSpecDecMixin(_Host, ABC):
+class HFSpecDecMixin(ABC, _Host):
🧰 Tools
🪛 GitHub Actions: Unit tests / 5_linux.txt

[error] 40-40: TypeError during test collection: Cannot create a consistent method resolution order (MRO) for bases object, ABC (in class HFSpecDecMixin(_Host, ABC)).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@modelopt/torch/speculative/plugins/hf_spec_mixin.py` at line 40, The class
declaration for HFSpecDecMixin causes an MRO conflict because _Host (which is
object at runtime) is placed before ABC; change the base class order in the
HFSpecDecMixin definition to inherit from ABC first and _Host second (i.e.,
class HFSpecDecMixin(ABC, _Host):) so the C3 linearization is respected and test
collection succeeds.

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

/claude review

Comment on lines +163 to +169
def get_dummy_inputs(self) -> dict:
"""Not yet implemented for DFlash."""
raise NotImplementedError(
"HFDFlashModel.get_dummy_inputs() is not yet implemented. "
"Required by unified HF quantization export (modelopt.torch.export.unified_export_hf). "
"Implement to enable quantization-export of DFlash speculative decoding models."
)

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.

[IMPORTANT Compatibility] Adding this stub silently changes the unified-quant-export dispatch for DFlash.

In modelopt/torch/export/unified_export_hf.py:384, the dummy-forward path is gated by hasattr(model, "get_dummy_inputs"):

elif hasattr(model, "get_dummy_inputs"):
    model(**model.get_dummy_inputs())
else:
    model(fake_input)

Before this PR, HFDFlashModel had no get_dummy_inputs, so hasattr(...) was False and the export fell through to model(fake_input) — which works because DFlash's forward() delegates to the base model in eval mode. After this PR, hasattr(...) is True (the abstract contract is satisfied by this raising stub), so unified HF quant export of a DFlash model goes from "works via base-model dispatch" to "hard-fails with NotImplementedError".

The PR description says "no behavioral change expected", but this is a behavioral change for any user running export_hf_checkpoint on a DFlash-converted model. Two options:

  1. (Preferred) Drop this stub and remove @abstractmethod from get_dummy_inputs in the mixin (make it optional). The unified-export caller already gates on hasattr, so an opt-in protocol matches that intent better than a mandatory abstract method.
  2. Keep the stub, but call this out in the PR description as an intentional fail-loud change for the export path so reviewers and downstream users aren't surprised.

Comment on lines +29 to +35
if TYPE_CHECKING:
# At type-check time, pretend the mixin is an nn.Module so attribute access
# like self.get_submodule(...) type-checks. At runtime it remains a plain
# mixin (object) and gets nn.Module via the sibling base class in the MRO.
_Host: TypeAlias = torch.nn.Module
else:
_Host = object

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.

[SUGGESTION] Declaring class HFSpecDecMixin(_Host, ABC) with _Host = object at runtime puts both object and ABC in the bases tuple. Because ABC already inherits from object, Python's C3 linearization rejects this: object is in the tail of [ABC, object] and ABC is in the tail of [object, ABC], so neither can be picked as a "good head" — the class definition raises TypeError: Cannot create a consistent method resolution order.

If CI is currently passing, double-check that the test suite actually imports hf_spec_mixin (e.g. via tests/unit/torch/speculative/plugins/test_hf_speculative.py) — a green CI here would refute the analysis above.

Either way, the cleaner pattern is to drop the _Host runtime base entirely (object is implicit) and keep the type-only annotation. Two equivalent options:

if TYPE_CHECKING:
    class HFSpecDecMixin(torch.nn.Module, ABC):
        ...
else:
    class HFSpecDecMixin(ABC):
        ...

or, simpler, keep one runtime class and use cast/Protocol on the few self.get_submodule(...) callsites for type-checking. Removing the explicit object base also avoids the MRO foot-gun if anyone later adds a third base that conflicts.

@claude

claude Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor

Claude Review Summary

Findings: 0 CRITICAL · 1 IMPORTANT · 3 SUGGESTION

Most impactful

  • [IMPORTANT Compatibility] Adding the get_dummy_inputs raising-stub to HFDFlashModel flips the dispatch in unified_export_hf.py:384 (gated on hasattr(model, "get_dummy_inputs")) from the silent fallback path model(fake_input) to a hard NotImplementedError. The PR description states "no behavioral change expected", but this changes export behavior for any user running unified HF quant export on a DFlash-converted model. Either drop the stub + @abstractmethod (keep the optional-protocol shape the export caller already relies on), or call out the deliberate fail-loud change in the PR description.

Other notes

  • [SUGGESTION] class HFSpecDecMixin(_Host, ABC) with _Host = object at runtime declares (object, ABC) as bases; by C3 linearization this should be rejected as inconsistent MRO. Worth confirming the unit tests under tests/unit/torch/speculative/plugins/ actually import this module in CI. Cleaner pattern: drop the runtime _Host base entirely (object is implicit) and keep the type-only declaration under TYPE_CHECKING.
  • [SUGGESTION] _compile_targets: list[...] = [] — mutable class-level default. Currently safe (read-only iteration) but a subclass that mutates in-place would corrupt the shared class state. Prefer tuple[..., ...] = ().
  • [SUGGESTION] _nvtx_range and _activate_torch_compile still emit warnings via bare print(...) even though the new file defines a module logger; switch to logger.warning(..., exc_info=True) for consistency.

Algorithmic / state correctness

The mechanical refactor itself is sound:

  • The MRO-driven modify() chain on HFEagleModel(HFSpecDecMixin, EagleModel) and HFDFlashModel(HFSpecDecMixin, DFlashModel) resolves to Sub.modify → Mixin.modify (which calls super().modify(config) → algorithm-base, then _find_base_model_parts) → rest of subclass body. Moving discovery earlier vs. the previous code is fine — the pre-discovery sections of both modify() bodies only use self.config (via _base_llm_config), never _base_model_path.
  • _find_base_model_parts body is functionally identical to the prior Eagle/DFlash copies, modulo the dropped assert isinstance(submodule, torch.nn.Module) (redundant) and print → logger.debug.
  • No modelopt_state schema or registration changes; @EagleDMRegistry.register / @DFlashDMRegistry.register paths are unchanged.

Risk: low-medium

Pure refactor with one inadvertent export-path behavior change to clean up. Once the get_dummy_inputs stub question is resolved, this is good to merge.

Comment on lines +142 to +155
def _nvtx_range(self, name):
"""Optionally create an NVTX range for profiling.

Enabled when the subclass sets ``self._enable_nvtx = True`` in ``modify()``.
"""
if not self._enable_nvtx:
return contextlib.nullcontext()
try:
import torch.cuda.nvtx as nvtx

return nvtx.range(name)
except Exception as e:
print(f"Failed to create NVTX range {name}: {e}")
return contextlib.nullcontext()

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.

[SUGGESTION] This file already defines logger = logging.getLogger(__name__) at line 27, but _nvtx_range and _activate_torch_compile still emit warnings via bare print(...). Using logger.warning(...) (and logger.warning("...", exc_info=True) for the NVTX exception) would be consistent with the rest of the file, route through the project's logging configuration, and respect quiet/verbose settings. This was pre-existing in hf_eagle.py, but moving the code into a freshly-organized mixin is a good moment to clean it up — e.g.:

except Exception:
    logger.warning("Failed to create NVTX range %s", name, exc_info=True)
    return contextlib.nullcontext()

and

except Exception:  # noqa: PERF203
    logger.warning("Disabling torch.compile for %s due to compilation error.", name, exc_info=True)


# List of (method_name, compile_kwargs) for _activate_torch_compile().
# Example: [("_eagle_forward", {"mode": "max-autotune"}), ("_eagle_loss", {"fullgraph": True})]
_compile_targets: list[tuple[str, dict]] = []

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.

[SUGGESTION] Mutable list as a class-level default. Currently safe because _compile_targets is only iterated read-only, but if a future subclass does self._compile_targets.append(...) (or any in-place mutation) it will mutate the shared class default and silently affect every other subclass. Since the value is conceptually a frozen tuple of (method, kwargs) pairs, prefer:

Suggested change
_compile_targets: list[tuple[str, dict]] = []
_compile_targets: tuple[tuple[str, dict], ...] = ()

(HFEagleModel already overrides at the class level so the type change is compatible — see hf_eagle.py:61.)

@kevalmorabia97

Copy link
Copy Markdown
Collaborator

This PR is stale, hence closed. The branch has been deleted; feel free to reopen or restore it if still needed.

@kevalmorabia97
kevalmorabia97 deleted the haoguo/spec-mixin-new branch November 3, 2026 07:08
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.

2 participants