Skip to content

fix(speculative): weigh DFlash-family losses per anchor position, not per sequence - #2986

Draft
h-guo18 wants to merge 1 commit into
mainfrom
haoguo/dflash-per-position-loss
Draft

h-guo18 wants to merge 1 commit into
mainfrom
haoguo/dflash-per-position-loss

Conversation

@h-guo18

@h-guo18 h-guo18 commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Bug fix

DFlash-family training (DFlash, DFlash2, DSpark, Domino) weighs every training sequence the same, whatever its answer length. This is a mismatch with inference, where the drafter runs at every position of a long answer.

Two things cause it:

  • Per-micro-batch averaging. Each training forward averages its loss over the micro-batch's sampled anchors, and EagleTrainerWithAccLog.compute_loss drops HF Trainer's num_items_in_batch. With one sequence per micro-batch, as the DFlash, DFlash2 and DSpark recipes train (per_device_train_batch_size: 1), each sequence gets the same total weight. An anchor position of a 2,000-token answer counts 1/20 as much as one of a 100-token answer.
  • Anchor cap. At most dflash_num_anchors anchors are sampled per sequence. Within a micro-batch of several sequences, long answers are therefore sampled less densely, again without compensation.

The fix makes every anchor position of the global batch count the same:

  • Importance weights. Each sampled anchor's rows are weighted by its sequence's anchor positions per sampled anchor.
  • Global normalization. Each micro-batch's mean loss is scaled by its share of the global batch's tokens, using num_items_in_batch, which HF Trainer counts across micro-batches and ranks. This is HF's standard mechanism for token-level losses under gradient accumulation.
  • Plumbing. The trainer now passes num_items_in_batch to DFlash-family models; other models are unchanged. HFDFlashModel declares accepts_loss_kwargs = True, so HF counts and passes it even on base models that declare otherwise (e.g. Qwen3.5 and other VLM wrappers).

Notes:

  • Gradient accumulation. HF does not divide the loss by the accumulation steps when a model takes num_items_in_batch, so before this change the loss and gradient grew with the number of accumulation steps. They no longer do.
  • Offline and streaming modes. Their labels cover the prompt as well as the answer, so num_items_in_batch counts prompt tokens. Sequences are still weighted by their anchor positions, but each step's loss is scaled by that step's fraction of answer tokens. Making those labels answer-only would remove the scaling; that is left as a follow-up.

Usage

No API change: DFlash-family recipes pick it up as is.

Testing

  • tests/unit/torch/speculative/plugins/test_hf_dflash.py::test_every_anchor_position_weighs_the_same, parametrized over DFlash, DSpark and Domino.
    • Setup: two answers with 13 and 8 anchor positions, 2 sampled anchors each, in one micro-batch.
    • Asserts the loss equals each answer's own mean loss weighted by its positions, over num_items_in_batch.
    • It fails for all three without the fix, and for DSpark or Domino when only that variant's forward is reverted.
  • tests/unit/torch/speculative/plugins/test_hf_speculative_offline.py::test_trainer_hands_num_items_in_batch_to_dflash: the trainer passes num_items_in_batch to a DFlash model. It fails without the trainer change.
  • The DFlash, DFlash2, DSpark, Domino and offline unit tests pass on CPU. The only failures are 4 torch.compile DSpark tests that fail identically on main in my environment (no Python.h for inductor).
  • Not yet run: multi-GPU training, and an AL A/B against main. Both are needed before this leaves draft.

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?: ❌ Training weighting changes; with gradient accumulation, the logged loss and gradient norm drop by the number of accumulation steps.
  • 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?: ✅
  • Did you get Claude approval on this PR?: ❌ Draft

Additional Information

The commit is not yet GPG-signed; it will be re-signed before review.

🤖 Generated with Claude Code

… per sequence

The DFlash-family training forwards average their loss over the micro-batch's
sampled anchors, and the trainer dropped HF Trainer's num_items_in_batch. With
one sequence per micro-batch, as the DFlash, DFlash2 and DSpark recipes train,
every sequence therefore weighed the same whatever its answer length: the
anchor positions of a long answer counted for less than those of a short one,
although the drafter meets them in proportion to their length. Within a
micro-batch, sequences with more anchor positions than dflash_num_anchors were
also undersampled.

Now each sampled anchor stands for its sequence's anchor positions per sampled
anchor, and each micro-batch's mean loss is scaled by its share of the global
batch's tokens (num_items_in_batch, counted by HF Trainer across micro-batches
and ranks). The trainer hands num_items_in_batch to DFlash-family models, which
declare accepts_loss_kwargs so that HF counts it on every base model. A side
effect is that gradient accumulation no longer multiplies the loss by the
number of accumulation steps.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Oct 24, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@github-actions

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-2986/

Built to branch gh-pages at 2026-10-24 05:04 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@codecov

codecov Bot commented Oct 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.82%. Comparing base (0638a27) to head (bb8089e).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2986   +/-   ##
=======================================
  Coverage   79.82%   79.82%           
=======================================
  Files         661      661           
  Lines       74928    74940   +12     
=======================================
+ Hits        59810    59821   +11     
- Misses      15118    15119    +1     
Flag Coverage Δ
unit 61.12% <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 pushed a commit that referenced this pull request Nov 5, 2026
### What does this PR do?

Type of change: Bug fix

EAGLE returns a mean loss for each microbatch. Its forward accepts
`**kwargs`, so Hugging Face Trainer assumes it also consumes
`num_items_in_batch` and skips its usual gradient-accumulation scaling.
The speculative trainer discards that argument, leaving gradients larger
by the accumulation group size.

Declare `HFEagleModel.accepts_loss_kwargs = False` so Trainer averages
the loss over the actual accumulation group, including a partial group
at the end of an epoch. This preserves the existing
mean-of-microbatch-means objective. It does not change token weighting
or the loss formula.

### Usage

No API change. Existing EAGLE recipes use the corrected scaling
automatically.

### Testing

- A focused regression runs a real converted EAGLE model through
`Trainer.training_step` and compares all trainable gradients with an
explicit mean of native microbatch losses. It covers a full
two-microbatch group and a two-microbatch tail with three configured
accumulation steps.
- The offline speculative unit module passes: 39 tests, including the
two new cases (0.03–0.05 s each). Removing the declaration makes both
new cases fail with gradients twice the expected size.
- Tested on CPU with PyTorch 2.13.0, Transformers 5.18.0 and Accelerate
1.15.0. All file-scoped pre-commit checks pass, including Ruff, mypy and
Bandit.

### Before your PR is "Ready for review"

- Is this change backward compatible?: Corrects training gradients when
accumulation is enabled; checkpoint format is unchanged.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A; neither
was added.
- Did you write any new necessary tests?: Yes.
- Did you update Changelog?: Yes.
- Did you get Claude approval on this PR?: Pending.

### Additional Information

[PR #2986](#2986)
addresses DFlash-family loss normalization. This fix changes the EAGLE
model class; the shared trainer and DFlash classes are unchanged.


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

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Fixed gradient accumulation during Hugging Face EAGLE training.
Gradients are now averaged across the accumulation group, preventing
them from being scaled incorrectly when multiple batches are
accumulated.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Signed-off-by: Sandeep Agrawal <[email protected]>
h-guo18 pushed a commit that referenced this pull request Nov 7, 2026
### What does this PR do?

Type of change: Bug fix

Follow-up to merged
[#3229](#3229). The
speculative-decoding example trainer drops `num_items_in_batch` and
returns microbatch-mean losses. It must tell Transformers to average
those losses across the accumulation group. With Transformers 5.5,
Accelerate can divide the loss a second time, making gradients too
small.

Keep this mean-loss contract in `EagleTrainerWithAccLog`. Set
Accelerate's accumulation count to one during `training_step`, then
restore the previous count in `finally`, including when the step fails.
This keeps the correction local to the example trainer and preserves the
model classes' previous behavior with the standard Hugging Face Trainer.

### Usage

Existing EAGLE, Medusa and external-draft recipes using the example
trainer need no changes.

### Testing

- The complete offline speculative unit module passes on Transformers
5.5.0 and 5.18.0: 43 tests each, with PyTorch 2.13.0 and Accelerate
1.15.0.
- Converted EAGLE, Medusa and external drafts match manually averaged
losses and gradients for full and partial accumulation groups. Tests
recreate the accelerator and verify that another live accelerator
retains its accumulation count after each step.
- A Medusa check using the standard Transformers 5.5 Trainer with
gradient accumulation four matches the manually averaged gradient, ratio
1.0.
- Changed-file checks pass, including Ruff, formatting, mypy and Bandit.

### Before your PR is "*Ready for review*"

Follow the [Contributor
guidelines](https://github.com/NVIDIA/Model-Optimizer/blob/main/CONTRIBUTING.md),
including signed commits, and [Security Best
Practices](https://github.com/NVIDIA/Model-Optimizer/blob/main/SECURITY.md#security-coding-practices-for-contributors).

- Is this change backward compatible?: ✅ — checkpoint format and
supported dependency versions are unchanged.
- If you copied code from any other sources or added a new PIP
dependency, did you follow guidance in `CONTRIBUTING.md`: N/A — neither
was added.
- Did you write any new necessary tests?: ✅ — extended the existing
gradient regression.
- Did you update Changelog?: ✅
- Did you get Claude approval on this PR?: Pending.

### Additional Information

[PR #2986](#2986)
addresses DFlash-family loss normalization.


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

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Corrected gradient-accumulation scaling for training with Hugging Face
EAGLE, Medusa, and external-draft speculative decoding. Reported loss
and gradient norms now reflect averaged losses, improving the accuracy
of training metrics across these modes.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Sandeep Agrawal <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant