Repository navigation
Conversation
… 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]>
Contributor
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
Comment |
Contributor
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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 was referenced Nov 11, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
EagleTrainerWithAccLog.compute_lossdrops HF Trainer'snum_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.dflash_num_anchorsanchors 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:
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.num_items_in_batchto DFlash-family models; other models are unchanged.HFDFlashModeldeclaresaccepts_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:
num_items_in_batch, so before this change the loss and gradient grew with the number of accumulation steps. They no longer do.num_items_in_batchcounts 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.num_items_in_batch.tests/unit/torch/speculative/plugins/test_hf_speculative_offline.py::test_trainer_hands_num_items_in_batch_to_dflash: the trainer passesnum_items_in_batchto a DFlash model. It fails without the trainer change.torch.compileDSpark tests that fail identically onmainin my environment (noPython.hfor inductor).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.).CONTRIBUTING.md: N/AAdditional Information
The commit is not yet GPG-signed; it will be re-signed before review.
🤖 Generated with Claude Code