Skip to content

feat(speculative): log the DFlash family's draft_metrics from the example trainer - #2992

Draft
h-guo18 wants to merge 25 commits into
haoguo/dflash-shared-forwardfrom
haoguo/dflash-log-draft-metrics
Draft

h-guo18 wants to merge 25 commits into
haoguo/dflash-shared-forwardfrom
haoguo/dflash-log-draft-metrics

Conversation

@h-guo18

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

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: New feature

Stacked on #2990 [2/2] (branch haoguo/dflash-shared-forward, head 28f4f45), whose branch is the base; merge it after that one. There, every DFlash-family training forward returns draft_metrics, a dict of detached 0-dim tensors. Nothing logs them: EagleTrainerWithAccLog records only train_acc and EAGLE's component losses. So DFlash2's selector_coverage, LiLiCorr's lattice diagnostics, DSpark's confidence_loss, Domino's lambda_base and the objective terms never reach TensorBoard, wandb or trainer_state.json.

  • Trainer.
    • compute_loss adds each metric to a running sum per name. The sum stays a tensor, so there is no host sync per step.
    • Trainer.log adds each name's mean over the steps that reported it to logs, as draft/<name>. That costs one .tolist() sync per log step.
    • A step with no supervised token takes the forward's early return, which reports no metrics. That step is left out of the mean rather than counted as zero.
    • The trainer names no variant and no metric.
  • Why Trainer.log and not EagleTrainingPlot.on_log. HF registers its reporters (TensorBoard, wandb, ...) as callbacks ahead of user callbacks, and Trainer.log copies logs into log_history before any callback runs. A key added in on_log therefore never reaches TensorBoard, and reaches trainer_state.json only by patching the recorded entry.
    • That is how train_acc/parallel_<i>_step_<j> travels on main: since specdec: stop the training regression gate passing unevaluated #2776, EagleTrainingPlot.on_log copies it into log_history[-1] for the regression gate. It reaches the console, trainer_state.json and EagleTrainingPlot's own wandb.log, but not TensorBoard.
    • Trainer.log is the hook HF documents for this ("Subclass and override this method to inject custom behavior").
    • The on_log comment claimed train_acc is "picked up by TensorBoard". It now says where train_acc actually goes. Its handling is unchanged.
  • Ranks. Each rank averages its own steps, as for train_acc, and nothing is reduced across ranks. So there is no collective for a rank without metrics to hang. The reporters write rank 0's values.
  • Regression gate. tools/launcher/common/check_regression.py reads the last logged entry of the latest checkpoint's trainer_state.json and takes its first key containing acc as the run's accuracy; on main that key is train_acc/parallel_0_step_0. TrainerState.save_to_json writes the entry with sorted keys, so this PR's draft/* keys come first.
    • Unguarded, MIN_FINAL_ACC would start gating DFlash2, DSpark, Domino and LiLiCorr runs on selector_accuracy, backbone_accuracy or lilicorr_slot_acc, which its thresholds were not chosen for.
    • Since [1/8] launcher: make the regression gate machine-readable and opt-in strict #2839 that verdict is machine-readable and can fail the training task. regression_check.json would report the diagnostic as the run's accuracy. The Qwen3-8B DFlash2 online example runs the gate with REGRESSION_STRICT=1, so its training task would pass or fail on the selector's accuracy.
    • The gate now skips draft/* and keeps reading train_acc. The MIN_FINAL_ACC row in the speculative-decoding skill's references/algorithms/dflash.md, which the other DFlash-family references point to, notes the exception.
  • Docs. The dflash_lilicorr_w_ce description now says where its metrics are logged, and there is a CHANGELOG entry under 0.49.0. DFlash2's comment that "the trainer converts them at the logging boundary" is now true as written.

What each variant logs:

projector_type draft/<name>
DFlash loss_ce or loss_kd
DFlash2 its objective term, selector_accuracy, selector_coverage
DSpark loss_ce, loss_tvd, backbone_accuracy, confidence_loss
Domino loss_final, loss_backbone, backbone_accuracy, lambda_base
LiLiCorr 26 names: the lattice diagnostics, each term and its weight, loss_ce or loss_kd, origin_loss, origin_accuracy

Usage

Nothing to configure. TensorBoard shows train/draft/<name>, since HF prefixes training keys with train/. trainer_state.json keeps the metrics too:

import json

history = json.load(open(f"{output_dir}/trainer_state.json"))["log_history"]
coverage = [(h["step"], h["draft/selector_coverage"]) for h in history if "draft/selector_coverage" in h]

Testing

  • New test_trainer_logs_each_draft_metric_mean_per_window in test_hf_speculative_offline.py, the unit module that already loads eagle_utils.
    • It runs the real HF Trainer loop through EagleTrainerWithAccLog: 4 steps, 2 per log window. The model's second step reports no metrics.
    • It checks log_history, which records the dict the reporters receive. Each window must hold each name's mean, and a float64 metric must read back exactly.
    • It fails on the base with KeyError: 'draft/step', and takes 0.3 s on 4 CPUs (taskset -c 0-3).
  • New test_draft_metrics_are_not_the_accuracy in tools/launcher/tests/test_check_regression.py. Its last log entry holds draft/selector_accuracy 0.09 and train_acc/parallel_0_step_0 0.17, written with sorted keys as HF writes them. Against main's check_regression.py it fails, reading 0.09.
  • End to end on 1 GPU (scratch script), on transformers 5.5.4, 5.12.1 and 5.18.0: DFlash, DFlash2, LiLiCorr, DSpark (with its confidence head) and Domino (with DominoLambdaCallback).
    • Each trained 6 steps through EagleTrainerWithAccLog and EagleTrainingPlot with report_to=tensorboard. One batch had no supervised token.
    • Every draft_metrics name appears as train/draft/<name> in the TensorBoard event file and as draft/<name> in log_history. Each value equals the mean of what that window's forwards returned. train_acc is in log_history but not in TensorBoard.
    • Under torch.cuda.set_sync_debug_mode, the per-step accumulation does not sync, and log syncs once when it has metrics.
    • On each run's saved trainer_state.json, main's check_regression.py reads draft/selector_accuracy (DFlash2), draft/lilicorr_slot_acc (LiLiCorr) or draft/backbone_accuracy (DSpark, Domino) as the accuracy. With this PR it reads train_acc/parallel_0_step_0 for all five. DFlash logs no draft/* key containing acc.
  • 2-rank gloo DDP through the HF Trainer, on the same three versions: it finishes on both ranks, each rank logs its own means, and rank 0's TensorBoard holds rank 0's.
  • test_hf_speculative_offline.py, test_hf_{dflash,dflash2,dspark,domino,lilicorr}.py and tools/launcher/tests/test_check_regression.py: 388 passed on each of transformers 5.5.4 and 5.18.0 (CI's tf_min and tf_latest pins), against 386 on the base.
  • tests/gpu/torch/speculative/plugins on 1 GPU: 20 passed, 1 skipped. The skipped test needs 2 GPUs.
  • Bitwise A/B against the base, comparing loss, gradients, metrics and generated tokens: 23 DFlash-family cases plus 15 more, in fp32 and bf16. The extra cases cover DSpark's gated head and its rnn head online, the KD and D-PACE flags on DSpark and Domino, DFlash2 KD online, more zero-loss steps, and labels that are -100 on some tokens. All 76 runs are identical, since no model code changes.
  • FSDP2 probe (2 gloo ranks, the DFlash draft as its own unit, one rank on the zero-loss branch, CE and KD): both ranks OK, with the same losses as on the base.
  • pre-commit run --files on the 7 changed files: clean.

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?: ✅ It only adds log keys, and the regression gate reads the same accuracy key as before.
  • 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?: ✅ Under 0.49.0, Speculative Decoding.
  • Did you get Claude approval on this PR?: ❌ Not run yet.

Additional Information

Stack: #2757 ← #2762 ← #2989 [1/2] ← #2990 [2/2] ← this PR. Merge them in that order. Three other PRs sit on #2990 and are independent of this one: DSpark and Domino following dflash_loss_objective (#2991), loss terms in config (#2993), and the shared AR-decode helper (#2994). This branch merges with each of them. The only conflict is in CHANGELOG.rst with the loss-terms PR (#2993), where both add an entry to the same 0.49.0 list; keeping both entries resolves it.

Not changed here: train_acc still never reaches TensorBoard, for EAGLE as for the DFlash family, because EagleTrainingPlot.on_log adds it after the reporters have run. #2776 copied it into trainer_state.json for the gate. Adding it in Trainer.log, as this PR does for draft/*, would also chart it in TensorBoard. That changes how train_acc is handled, so it is left for a follow-up. The same holds for estimated_training_ar, which reaches only the console and wandb.

🤖 Generated with Claude Code

h-guo18 and others added 25 commits October 24, 2026 09:59
…norm core

The next-token shift -- the base logits that predict the token at position i sit at i - 1 --
was spelled out at each of _teacher_logits' three callers: DFlash KD and DSpark as
(safe_label_indices - 1).clamp(min=0), LiLiCorr as anchor + s for the token at anchor + 1 + s.
A wrong shift trains without an error, just worse, so it now lives once: _teacher_logits
takes the label positions and applies the shift itself, and the callers pass what they
supervise. DFlash2's predecessor gather uses the same offset for a different quantity (the
previous token, not the teacher) and keeps its own.

_maybe_apply_base_final_norm took the producer's whole outputs dict, so _teacher_logits
wrapped its one flag in a single-key dict to call it. The bool now has its own function,
_apply_base_final_norm, which the dict reader delegates to; EAGLE keeps calling the dict
reader, unchanged.

Behavior is unchanged: against this branch's parent, offline DFlash KD, LiLiCorr (penalty and
calibration) and DSpark give bitwise-equal losses and gradients in fp32 and bf16, with pre-
and post-norm captures stored in float64. The teacher tests now pass labels and expect row
label - 1, and fail without the shift; a new test pins that label 0 reads row 0 rather than
wrapping to the last row.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…he DFlash family

Two pieces of the family's forwards were written out once per model.

- The step with nothing to supervise returns a zero loss that every trainable draft parameter
  feeds, so DDP's reduction still sees each of them. There were four copies in two forms:
  DFlash's indexed one element of each trainable parameter, while Domino's forward, DSpark's
  forward and DSpark's degenerate-loss branch summed every whole parameter, reading all draft
  weights to produce a zero. HFDFlashModel._draft_zero_loss now has the cheap form once.
- The concatenation of the base layers the draft's fc reads, hidden_states[lid + 1] for each
  target layer, appeared in the DFlash, DSpark and Domino forwards. It is now
  HFDFlashModel._target_hidden, which also carries the "+ 1" (hidden_states[0] is the
  embedding output) that modify()'s check on negative ids refers to.

Losses and gradients are unchanged; DSpark's DDP-coverage tests, which require a gradient on
every draft parameter for a batch with no valid anchor and for one with zero total weight,
pass on the shared helper.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
_build_generate_swa_mask hand-wrote the draft's visibility rule a second time -- context
before the block, the window counted from each query's real position, block-causal under
dflash_draft_attention="causal" -- and its docstring asked readers to keep it in step with
training. It is the training rule, _draft_mask_mod, for the one block being drafted,
anchored at ctx_len, so it now evaluates that. The grid evaluation and the additive
conversion that the training mask's dense path already did become _dense_additive_mask,
shared by both.

A verbatim copy of the old builder stays in the tests as the reference: over contexts of 1,
5 and 16 tokens, no window, a window of one block and of two, and bidirectional and causal
blocks, the masks are equal element for element (and None where the old one returned None).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
Which token each block position is trained on, which positions count, and how they are
weighted were written out five times: DFlash _compute_loss, DFlash2 _compute_loss (for the
selector), LiLiCorr _block_targets, DSpark _compute_dspark_loss and Domino
_compute_domino_loss. The copies differed only in the label offset (DFlash, DFlash2 and
LiLiCorr train position k on the token at anchor + k; DSpark and Domino on anchor + k + 1)
and in whether slot 0 is skipped, so a fix to one never reached the others.

- _block_targets returns the label token, its sequence position and the supervision mask,
  given the class constant _label_shift (0, or 1 for DSpark and Domino). The teacher reads
  its rows from those positions, including LiLiCorr's candidate logits.
- _block_tokens is the teacher-forced token gather that DSpark's and Domino's heads and
  DFlash2's predecessor ids each wrote by hand.
- _block_position_weights holds the D-PACE and decay weighting. DSpark and Domino pass
  "decay" explicitly, which is what they do today: they never read dflash_loss_objective.
- _masked_top1 replaces five copies of the masked top-1 accuracy.

The in-loss zero branches keep routing through the draft's output (flat_logits.sum() * 0.0)
rather than _draft_zero_loss: with DFlashModule as its own FSDP2 unit (the MiniMax-M2.7
launcher layout), reading the resharded parameters directly skips the unit's backward
collectives on that rank and the job aborts with a collective mismatch.

Behavior is unchanged. Against the previous head, a train step of DFlash (KD and CE),
DFlash2 (ce, tv and lambda, with the selector), LiLiCorr, DSpark (vanilla and rnn heads,
confidence head on) and Domino, offline and online, with D-PACE and decay, and steps that
take the zero-loss branch, gives bitwise-equal loss, gradients and metrics in fp32 and bf16.
DFlash2's predecessor ids now come from the shared gather; they differ from the old
formula only at positions whose label lies past the sequence end, which carry no selector
weight.

A new test pins each variant's labels and supervision on a hand-worked example; it fails if
DSpark's shift is set to 0 or if the anchor slot stops being excluded. No existing test did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…Spark

DFlash's and DSpark's pseudo_speculative_generate repeated the same first half: run the
base model on the prefix, take its greedy next token, gather the target layers onto the
draft's device, build the block (anchor then mask tokens), its position ids and mask, and
run the draft. Only the decoding after that differs (DFlash takes the argmax of positions
1..bs-1; DSpark walks its Markov head over the block).

- _generation_base returns the base model's next token and hidden states, and carries the
  offline check both copies made.
- _draft_block drafts the block that token anchors. Its position ids now come from
  _build_position_ids at anchor = ctx_len -- the training layout -- the way the generation
  mask already comes from the training mask rule. The comment it replaces described a
  uniform-block layout training has not used since the anchors were introduced.
- _target_hidden takes an optional device, so the last two hand-written
  hidden_states[lid + 1] picks go through it.

The docstring's note that generation runs with attention_mask=None was stale since the
generation mask was added and now says what is passed.

Generated tokens are unchanged: DFlash (full attention, sliding window, causal blocks),
DFlash2, LiLiCorr, DSpark and Domino online give bitwise-equal draft tokens in fp32 and bf16
against the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
… a second default

Thirteen variant fields were read as getattr(config, "dflash_...", <default>) although
DFlashConfig declares every one of them with a default, so each default lived twice. One
pair had already drifted: dflash_fp32_master_weights defaults to True in the config and to
False in HFDFlashModel.modify's fallback, which a reader would take for the default. The
fallbacks never run, because modify() always receives a DFlashConfig, so the fields are now
read directly.

convert_to_dflash_model chose the registry for dflash_architecture_config.projector_type
with an if/elif chain and listed the accepted names again by hand in its error. A table
maps each projector type to its registry, and the error lists the table's keys.

No behavior change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…e skill tables

The shared generation step raises one message for the whole family, "An offline
DFlash-family model cannot run AR validation / pseudo_speculative_generate". The
known-failure rows in the DFlash and DSpark skill references still quoted the two
per-variant messages it replaced, so a search for the actual error found no row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…evice

DSpark's pseudo_speculative_generate adds its Markov bias, computed on
the draft's device, to the backbone logits that the base model's lm_head
returns. scripts/ar_validate.py loads with device_map="auto", and
accelerate keeps a tied lm_head with embed_tokens on the first GPU while
the draft can land on a later one. The logits then stay on the first
GPU, so the sum raises "Expected all tensors to be on the same device"
for every sample and AR validation reports nothing. This has been the
case since DSpark was added.

The backbone logits now move to the draft's device before the loop. On
a single device the move is a no-op.

Verified: a new GPU test dispatches the model with accelerate's
dispatch_model, embed_tokens and lm_head on the CPU and everything else
on cuda:0, and generates with DFlash and DSpark. DSpark fails without
the fix and passes with it. The bitwise A/B against #2757 shows DSpark's
drafted tokens unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…nt and head

HFDominoModel did not override pseudo_speculative_generate, so AR
validation ran DFlash's, which decodes block positions 1..bs-1 with the
backbone alone. DFlash trains position k on the token at anchor + k;
Domino trains it on anchor + k + 1 (_label_shift = 1). Every drafted
token was therefore compared with the target one position too early,
so drafts were almost never accepted, and the correction head that
training optimizes and the exporter ships was never applied. domino.yaml
keeps AR validation off, so shipped training did not hit this.

DFlash's default decode now starts at block position 1 - _label_shift
and returns at most bs - 1 + _label_shift tokens. For DFlash, DFlash2
and LiLiCorr (shift 0) that is the same slice as before. Domino
overrides it the way DSpark does for its Markov head: it decodes the
block left to right, stepping the GRU over the anchor and the tokens
drafted so far, and from pure_draft_prefix_len on adds
embed_proj([hidden_k; GRU state]) to the backbone logits, as
_apply_domino_head does in training. As in DSpark's decode, the
backbone logits and the drafted tokens' embeddings are moved to the
draft's device: under device_map="auto" the embedding table, and a tied
lm_head with it, can sit on another GPU.

The eval forward warned that Domino's acceptance rates were
backbone-only, but that method computes no acceptance rate, and AR
validation now runs the head. The warning goes, and so do the other
copies of the claim: the comments in domino.yaml, dspark.yaml and the
Nemotron-3.5 DSpark warm-start recipe, the note in the Domino launcher
example, and the speculative-decoding skill's Domino, DSpark and
validation sheets. DSpark's generation has applied its Markov head
since DSpark was added. The validation sheet keeps its rule against
reporting such an AR as the model's result, now for the heads that AR
validation still skips (LiLiCorr's reranker, DFlash2's selector), and
adds the LiLiCorr and online DFlash2 examples to the ones it lists as
shipping no benchmark task. The Domino sheet and example now say how to
add the HF AR eval: DFlash's task_2 with --steps equal to the block
size, since Domino drafts the whole block. The flag values do not
change.

Verified: a new test checks that Domino's greedy drafts equal the
argmax of _apply_domino_head teacher-forced on them, with head weights
large enough to overturn the backbone. It fails on the parent commit,
and also when the head is skipped, its GRU state lags a step, or the
prefix boundary is off by one. The GPU test that puts lm_head on
another device now covers Domino as well, and fails without the move.
Bitwise A/B against #2757: DFlash and DSpark loss, gradients and drafted
tokens are unchanged; only Domino's drafted tokens change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
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]>
… 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]>
DSpark and Domino have shipped since 0.46.0, so these are fixes to
released features, and two of them ask something of users: drop
shift_label: false from DSpark configs, which now fail to convert, and
re-export DSpark drafters whose export carried shift_label: false. The
entry leaves out markov_head_type: #2902 already exports it as built.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…step

HFDFlashModel.forward built the batch, ran the draft and computed the loss inline, and the
variants built on it got at the loss's pieces piecemeal: DFlash2 asked _compute_loss for
its unreduced terms (return_terms, _DFlashLossTerms) to recompose the block objective, and
DFlash2 and LiLiCorr overrode forward() only to carry out the metrics their _compute_loss
had left on the model (_selector_metrics, _lilicorr_metrics).

The forward now hands the loss one object per step:
- DraftBatch: the batch, its blocks and the draft's hidden states.
- LossContext: the labels (_block_targets), the draft's logits (DraftLogits: the
  distribution the draft serves, and the backbone's before any head) and the position
  weights, with the per-token cross-entropy and the teacher's logits computed lazily, once.
- _compute_loss(ctx) returns a LossOutput: the loss, the accuracy train_acc reports and
  detached 0-dim metrics, which the forward returns as draft_metrics.

What a variant may change becomes a hook: _online_base_outputs (the base model's outputs),
_draft_logits (a head on the backbone's logits), _position_weighting and _compute_loss.
The loss mask comes from _build_loss_mask. The DSpark/Domino padding fix, a separate PR
against main, adds the same helper, with the same text, at the same place (right after
get_exporter), so a merge of the two keeps one copy of it.

DFlash2 and LiLiCorr take the context: DFlash2's tv/lambda blend reads the cross-entropy
and weights from it, and both return their metrics instead of overriding forward(). DSpark
and Domino keep their own forwards for now.

Verified against the previous commit with one train step and one generation step per case,
in fp32 and bf16: DFlash (KD and CE), DFlash2 (ce/tv/lambda with the selector) and LiLiCorr,
offline and online, D-PACE and decay, including zero-loss steps, give bitwise-equal loss,
gradients, train_acc and generated tokens (32/32). The selector and LiLiCorr metrics keep
their names and values under draft_metrics.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…sses.py

The block-supervision helpers (_block_positions, _block_gather, _block_tokens,
_BlockTargets, _block_targets), the position weighting (_dpace_position_weights,
_block_position_weights), _masked_top1, the loss context (DraftLogits, LossOutput,
LossContext) and DSpark's per-token TVD (_tvd_chunk, _tvd_per_token) move unchanged from
hf_dflash.py and hf_dspark.py into one module that names no variant. The next PR in this
stack builds the shared loss terms on them, and hf_dspark.py would otherwise be imported by
the generic loss code for its TVD.

A pure move: every moved definition is byte-identical to its previous text, and only
import lines change elsewhere. The new file carries the SpecForge and DeepSpec notices of
the two files the code came from and is excluded from the license-insertion hook like them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…_losses.py

Update the call sites of the internals the previous two commits changed or moved, keeping
each test's intent:
- _compute_loss tests (D-PACE/decay/KD branches, trailing padding blocks, KD from the base
  hidden vs. full logits) go through _loss_context and _compute_loss on given draft logits.
- "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.
- The selector and LiLiCorr metrics are read from draft_metrics, LiLiCorr's as tensors.
- _block_targets, _dpace_position_weights and DSpark's TVD helpers are imported from
  dflash_losses, where the move put them.

One new test pins which objectives keep the per-token cross-entropy's gradient. The
context computes the CE once and sets its grad mode from ce_grad, overriding the no_grad
under which D-PACE reads it first. The test inspects the context that a real DFlash2
training forward under D-PACE hands _compute_loss: ce, tv and lambda keep the CE's
gradient, and KD does not.

Mutation check. If _loss_context always asks for the gradient, LossContext ignores
ce_grad, or the CE always keeps its graph, then each KD step under D-PACE (the default
configuration) holds a vocab-wide graph that it never backpropagates. The loss and
gradients stay bitwise equal (DFlash, DFlash2 and LiLiCorr KD, fp32 and bf16: 6/6), and
the rest of the suite passes (512 passed); only [kd] fails. Dropping the gradient instead
already failed three existing tests, and now also fails [ce], [tv] and [lambda].

tests/unit/torch/speculative and test_hf_spec_rope_export.py: 513 passed on transformers
5.5.4, 5.12.1 and 5.18.0. On 4 CPUs, the changed tests take at most 3.4 s each and the new
cases under 0.1 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…ing changes

DFlash2's selector_metrics and LiLiCorr's lilicorr_metrics arrive in 0.48.0, which this
change follows. The first commit of this series replaces both keys with draft_metrics, keeps
their inner keys, and returns tensors where LiLiCorr returned Python floats. Nothing in the
repo reads these keys, but user code that reads them breaks.

The entry goes under the 0.49.0 heading: release/0.48.0 is branched and ships both keys,
so this change first reaches users in 0.49.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…ivergence terms

The block objective was a branch in HFDFlashModel._compute_loss (KD or CE), and DFlash2's
dflash_lk_loss_type replaced it after the fact: _lk_loss recomputed the loss from the
context's per-token cross-entropy and weights, outside the gate that turns a step with
nothing to train into a zero loss.

The divergences are now components in dflash_losses.py that name no variant, a closed
registry of callables (ctx, source) -> 0-dim loss, each reducing under the step's position
weights the way the old code did: ce, kd (soft cross-entropy against the base model), tvd
(L1 to the base model's distribution, DSpark's term), tv (1 - q(gold)) and lambda (the
acceptance-weighted CE/TV blend, still reduced term by term and blended with a detached
scalar). Each term declares whether it reads the teacher and whether it backpropagates
through the per-token cross-entropy.

An objective is an ordered [(name, weight, term)] list that modify() builds through the
_build_objective hook: DFlash and LiLiCorr keep kd or ce, DFlash2 picks tv or lambda.
_compute_loss sums it left to right and reports each term as loss_<name>, plus the
backbone's accuracy when a head sits on it. The declarations replace the per-variant
flags: offline training reconstructs the teacher's logits when a term needs them, and the
context computes the cross-entropy with gradient only when a term backpropagates through
it. LossContext gains the per-token TVD, and the TVD chunk compiles under
dflash_use_torch_compile for every variant, no longer only DSpark's modify().

One disclosed behavior change: a DFlash2 step under tv or lambda whose total position
weight is <= 1 now takes the zero-loss gate like every other objective; before, the blend
was computed over that tiny weight sum. The selector term is unchanged, still computed on
every step.

Verified against the previous commit with one train step and one generation step per case,
in fp32 and bf16: DFlash (KD and CE), DFlash2 (ce/kd/tv/lambda with the selector) and
LiLiCorr, offline and online, D-PACE and decay, including zero-loss steps, give
bitwise-equal loss, gradients, train_acc, metrics and generated tokens (30/32). The other
two runs are the change above on a step that keeps one label of weight < 1: the fp32 loss
goes from 0.96958977 to 0 (bf16: 0.968748331 to 0), the 33 backbone gradients lose the TV
term, and the 3 selector gradients and all metrics are unchanged. The new loss_<name>
metrics equal the loss for DFlash and origin_loss for LiLiCorr, bitwise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
HFDSparkModel.forward was a copy of the DFlash training forward (base model, loss mask,
anchors, draft inputs, draft) followed by _apply_markov_head and _compute_dspark_loss,
which rebuilt the labels, weights, gate and accuracy that the shared loss now provides.
Copies of the forward are where the family's fixes went missing: the loss-mask rule DFlash
gained for padding never reached it.

DSpark now changes only its hooks:
- _build_objective: [("ce", dflash_ce_loss_alpha), ("tvd", dflash_l1_loss_alpha)].
- _draft_logits: the Markov transition bias on the backbone's logits (the old
  _apply_markov_head without the confidence head).
- _online_base_outputs: the inner model and its final hidden, which the loss projects
  only at the rows it reads.
- _position_weighting: "decay", as before (dflash_loss_objective is not wired for DSpark).
- _compute_loss: the objective, plus the confidence head's BCE against 1 - 0.5 * TVD,
  sharing the TVD term's per-token values. A step with nothing to train keeps returning
  _draft_zero_loss, which also feeds the confidence head for DDP.

With the shared forward DSpark adopts DFlash's loss mask (labels, attention_mask and
loss_mask intersected), the fix the padding PR makes on main; it is identical whenever
attention_mask is all ones where labels are valid, as in every shipped recipe and in
streaming and offline batches. Offline batches now fail at the entry when the TVD term has
no teacher to read, rather than after the draft has run.

Metrics move to draft_metrics: ce_loss, l1_loss and base_accuracy become loss_ce, loss_tvd
and backbone_accuracy; confidence_loss keeps its name.

Verified against the previous commit with one train step and one generation step per case,
in fp32 and bf16: the vanilla and rnn heads with the confidence head on, offline and
online, and a step that takes the zero-loss branch give bitwise-equal loss, gradients,
train_acc, metrics (under the names above) and generated tokens (8/8).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
HFDominoModel.forward was the second copy of the DFlash training forward, followed by
_apply_domino_head and _compute_domino_loss, which again rebuilt the labels, weights, gate
and accuracies. Domino now changes only its hooks:
- _build_objective: [("ce", 1.0)].
- _draft_logits: the GRU correction on the backbone's logits (the old _apply_domino_head).
- _online_base_outputs: the inner model; Domino reads no teacher.
- _position_weighting: "decay", as before.
- _compute_loss: (1 - lambda_base) * objective("final") + lambda_base *
  objective("backbone"), behind the shared zero-loss gate.

Domino no longer overrides forward(): its eval branch already delegated to the shared
forward, so with training on the hooks above nothing is left to override.

Like DSpark, Domino adopts DFlash's loss mask (labels, attention_mask and loss_mask
intersected): identical whenever attention_mask is all ones where labels are valid.

Metrics move to draft_metrics: final_loss, base_loss and base_accuracy become loss_final,
loss_backbone and backbone_accuracy; lambda_base keeps its name.

Verified against the previous commit with one train step and one generation step per case,
in fp32 and bf16: offline and online steps and a step that takes the zero-loss branch give
bitwise-equal loss, gradients, train_acc, metrics (under the names above) and generated
tokens (6/6).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…nd loss

Update the call sites of the internals the previous commits removed or renamed, keeping
each test's intent:
- DSpark's zero-weight DDP test runs the real _loss_context/_compute_loss instead of the
  removed _apply_markov_head/_compute_dspark_loss.
- Domino's AR-validation test teacher-forces the drafts through _draft_logits instead of
  the removed _apply_domino_head. It still fails when either the drafting or the training
  side skips the correction head or feeds it the wrong prefix.
- The DSpark and Domino metrics are read from draft_metrics, under the new names where
  they changed, and as tensors.

One new test pins the disclosed behavior change: a DFlash2 step whose position weights
sum to <= 1 takes the zero loss under ce, tv and lambda alike. Before, tv and lambda gave
0.968 and 3.352 on it.

tests/unit/torch/speculative and test_hf_spec_rope_export.py: 516 passed on transformers
5.5.4, 5.12.1 and 5.18.0. The changed tests take at most 0.7 s each on 4 CPUs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
Before the terms were shared, DFlash2's _lk_loss carried its own copy of the cross-entropy
reduction, so test_zero_decay_and_unit_scale_is_exactly_cross_entropy compared two copies.
Now the lambda blend calls the ce term, and that test compares the term with itself. The
kd, tvd and tv reductions were never compared with anything. A parametrized test now runs
ce, kd, tvd and tv through the real _loss_context and _compute_loss under decay weights, and
compares each loss bitwise with a verbatim copy of the old reduction:
HFDFlashModel._compute_loss for ce and kd, DSpark's _compute_dspark_loss for tvd, and
DFlash2's _lk_loss for tv.

The terms' needs_ce_grad declarations need no new test. They now set the per-token
cross-entropy's grad mode, which test_cross_entropy_gradient_follows_the_objective already
pins for ce, tv, lambda and KD. If the tv or lambda declaration is flipped, the loss value
does not change, but the backbone trains through the selector alone; the shipped
dflash2.yaml uses lambda with the selector.

Mutation check. Each source change below passes the rest of tests/unit/torch/speculative
and test_hf_spec_rope_export.py (519 passed), and fails exactly the case named:
- ce, kd, tvd or tv divides by the supervised count instead of the weight sum: the new
  test's [ce], [kd], [tvd] or [tv]. Reducing ce under the mask instead of the weights also
  fails [ce].
- tv or lambda declares needs_ce_grad = False, or kd declares it True:
  test_cross_entropy_gradient_follows_the_objective's [tv], [lambda] or [kd].
Flipping ce's own declaration fails four existing tests and that test's [ce].

Each new case takes under 0.1 s on 4 CPUs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
DSpark's dspark_metrics and Domino's domino_metrics have been in every release since 0.46.0.
The DSpark and Domino commits remove both keys, rename three inner keys of each, and return
tensors where both returned Python floats. Nothing in the repo reads these keys, but user
code that reads them breaks.

The backward-breaking entry for DFlash2's and LiLiCorr's keys now also names these two keys
and the renamed inner keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…rics

The next commit has the speculative-decoding example trainer log each DFlash-family
variant's training metrics as draft/<name>, which also puts them in trainer_state.json.
check_regression.py takes the first key containing "acc" in the last logged entry as the
run's accuracy, and TrainerState.save_to_json writes that entry with sorted keys, so the
draft/ keys come before train_acc/parallel_0_step_0, the key EagleTrainingPlot copies into
the entry for this gate. MIN_FINAL_ACC would then silently start gating DFlash2, DSpark,
Domino and LiLiCorr runs on a head diagnostic (selector_accuracy, backbone_accuracy,
lilicorr_slot_acc) instead of the training accuracy its thresholds were chosen for:
regression_check.json would report that diagnostic as the run's accuracy, and the DFlash2
online example, which runs the gate with REGRESSION_STRICT=1, would pass or fail its
training task on it. Skip draft/* so the gate keeps reading train_acc.

The new test_check_regression.py case writes such an entry, a draft/selector_accuracy of
0.09 beside a train_acc of 0.17, and fails without the skip, which reads 0.09. The file's
19 tests pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
…mple trainer

Every DFlash-family training forward returns draft_metrics, but the example trainer never
logged them, so DFlash2's selector_coverage, LiLiCorr's lattice diagnostics, DSpark's
confidence_loss and Domino's lambda_base never reached TensorBoard or wandb.

EagleTrainerWithAccLog now sums each metric as a tensor per micro-batch, so no host sync,
and Trainer.log adds each name's mean over the steps that reported it as draft/<name>,
with one sync per log step. It has to be Trainer.log, not EagleTrainingPlot.on_log: the
HF reporters are callbacks registered ahead of ours, so a key added in on_log never
reaches TensorBoard, and log_history is recorded before any callback runs, so such a key
reaches trainer_state.json only by patching the recorded entry, as EagleTrainingPlot does
for train_acc. train_acc therefore still never reaches TensorBoard; the comment saying it
does is corrected, its handling left as is. The trainer names no variant or metric. Each
rank averages its own steps, as for train_acc. The LiLiCorr weight description now says
where the metrics are logged.

Verified:
- the new unit test, which fails on the parent with KeyError 'draft/step';
- DFlash, DFlash2, LiLiCorr, DSpark and Domino each trained through the real HF Trainer on
  GPU with report_to=tensorboard, on transformers 5.5.4, 5.12.1 and 5.18.0: every
  draft_metrics name lands as train/draft/<name> and in log_history, equal to the window
  mean of what the forwards returned, including a window with a step that had no
  supervised token; train_acc lands in log_history only;
- on the trainer_state.json each of those runs saves, check_regression.py reads
  train_acc/parallel_0_step_0 as the accuracy; without the previous commit it reads
  draft/selector_accuracy (DFlash2), draft/lilicorr_slot_acc (LiLiCorr) or
  draft/backbone_accuracy (DSpark, Domino);
- torch.cuda.set_sync_debug_mode: no sync in the per-step accumulation, one per log call
  that has metrics;
- 2-rank gloo DDP through the HF Trainer: no hang, each rank logs its own means and rank 0
  writes them to TensorBoard;
- test_hf_speculative_offline.py, the DFlash-family plugin tests and the launcher's
  test_check_regression.py on transformers 5.5.4 and 5.18.0 (388 passed on each);
- tests/gpu/torch/speculative/plugins (20 passed, 1 skipped);
- bitwise A/B of all 23 DFlash-family cases and 15 more, fp32 and bf16, against the
  parent: 76 MATCH;
- FSDP2 probe, dflash draft branch ce/kd: both ranks OK, same losses as the parent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: h-guo18 <[email protected]>
Users of examples/speculative_decoding get new draft/<name> scalars in TensorBoard, wandb
and trainer_state.json; say what they are and that they are interval means. Checked with
the rst pre-commit hooks.

The entry goes under the 0.49.0 heading: release/0.48.0 is branched, so this change first
reaches users in 0.49.0.

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

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

@h-guo18
h-guo18 force-pushed the haoguo/dflash-shared-forward branch 3 times, most recently from da2d4d4 to acc269d Compare November 16, 2026 12:12
@h-guo18
h-guo18 force-pushed the haoguo/dflash-shared-forward branch from b7bfe0f to b73d41b Compare November 25, 2026 09:11

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