Skip to content

refactor(speculative): draft DSpark and Domino through one AR-validation loop - #2994

Draft
h-guo18 wants to merge 24 commits into
haoguo/dflash-shared-forwardfrom
haoguo/dflash-shared-ar-decode
Draft

h-guo18 wants to merge 24 commits into
haoguo/dflash-shared-forwardfrom
haoguo/dflash-shared-ar-decode

Conversation

@h-guo18

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

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: Refactor. No behavior change: the drafted tokens are bitwise identical.

This PR is stacked on #2990 (branch haoguo/dflash-shared-forward, head 28f4f45), whose branch is its base; merge it after that one. The stack below it, on main 0638a27, is #2757 ← #2762 ← #2989 [1/2] (branch haoguo/dflash-loss-context) ← #2990 [2/2]. Three other PRs also sit on #2990 and are independent of this one: #2991 (DSpark and Domino follow dflash_loss_objective), #2992 (logging draft_metrics) and #2993 (loss terms in config). This branch merges with each of them without conflicts, and none of them touches the generation path.

#2762 gave Domino an AR-validation decode modeled on DSpark's, so pseudo_speculative_generate in hf_dspark.py and hf_domino.py carried the same loop over the block:

Only the step at each block position differed. A fix to the loop had to be made twice, and a third variant with a sequential head would have copied it again.

  • One loop. HFDFlashModel._decode_left_to_right(input_ids, steps) holds the loop and the device handling. Block position k drafts the token after the anchor and the k tokens drafted before it (_label_shift = 1).
  • One step per variant. A variant supplies _correction_step(k, prev_token, hidden, state). It returns the correction to position k's backbone logits, or None to leave them as they are, together with the head's new state.
    • DSpark: markov_step. Only the rnn head carries state.
    • Domino: steps the GRU over the previous token's embedding, which it still moves onto the draft's device. From pure_draft_prefix_len on, it returns embed_proj's correction.
  • Unchanged. Both pseudo_speculative_generate overrides keep their docstrings and call the shared loop. DFlash's parallel decode, which DFlash2 and LiLiCorr also use, is unchanged.
  • New test. DSpark's decode had only shape tests. TestDSparkGenerate mirrors fix(speculative): one label alignment per projector_type; DSpark and Domino export the head they built #2762's TestDominoGenerate for the vanilla, gated and rnn heads: with head weights large enough to overturn the backbone, the greedy drafts must equal the argmax of _draft_logits teacher-forced on them. It lands first and passes on [2/2] refactor(speculative): train DSpark and Domino through the shared DFlash forward #2990's head.

Usage

No API or config change. A variant with a sequential head now plugs in like this:

class HFMyDraftModel(HFDFlashModel):
    _label_shift = 1

    @torch.no_grad()
    def pseudo_speculative_generate(self, input_ids, steps=1):
        return self._decode_left_to_right(input_ids, steps)

    def _correction_step(self, k, prev_token, hidden, state):
        # The correction to block position k's backbone logits (or None), and the new state.
        return self.dflash_module.my_head_step(prev_token, hidden, state)

Testing

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?: ✅ Only private methods change; configs, checkpoints and pseudo_speculative_generate's outputs 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
  • Did you write any new necessary tests?: ✅ TestDSparkGenerate.
  • Did you update Changelog?: N/A Refactor with no user-visible change.
  • Did you get Claude approval on this PR?: ❌ Not run yet.

Additional Information

Source changes: +50 / −41 lines in hf_dflash.py, hf_dspark.py and hf_domino.py. Two commits: the DSpark test, which passes on the parent, then the refactor.

Each variant opts in with a one-line pseudo_speculative_generate override rather than by defining _correction_step alone. Switching on whether a variant defines the step would need a None sentinel on HFDFlashModel and a branch in DFlash's decode. Making the loop the family's only decode, with no correction for DFlash, would turn DFlash's parallel decode into a loop and move DFlash2 and LiLiCorr onto it. Both are larger than this refactor. The base _correction_step raises NotImplementedError, so a variant that opts in without a step fails on its first draft.

Merge order: #2757, #2762, #2989, #2990, then this PR.

🤖 Generated with Claude Code

h-guo18 and others added 24 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]>
…head

DSpark's pseudo_speculative_generate drafts the block left to right, one
markov_step per position, while training applies the Markov head to the
whole block at once through _draft_logits. Only shape tests covered the
decode, so nothing checked that the two agree, and the next commit moves
the decode loop into HFDFlashModel.

The test mirrors Domino's TestDominoGenerate: with head weights large
enough to overturn the backbone, the greedy drafts must equal the argmax
of _draft_logits teacher-forced on the anchor and those drafts. It runs
for the vanilla, gated and rnn heads.

Verified: passes on the parent commit for all three heads, in under
0.2 s per case on 4 CPUs. On the next commit it is the only unit test
that fails when DSpark's step drops the rnn head's state.

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

DSpark's and Domino's pseudo_speculative_generate each carried the same
left-to-right loop over the block. Each copy ran the base forward and the
draft block, and moved the lm_head's logits onto the draft's device (the
#2762 fix, present in both copies). Each also kept the previous token and
the head's state, capped the drafts at the block size, stacked them and
moved them back to the caller's device. Only the step at each position
differed.

The loop is now HFDFlashModel._decode_left_to_right. A variant supplies
_correction_step(k, prev_token, hidden, state), which returns the
correction to block position k's backbone logits (None for none) and the
head's new state:
- DSpark's step is markov_step.
- Domino's step runs the GRU over the previous token's embedding, which
  it still moves onto the draft's device, and adds embed_proj's
  correction from pure_draft_prefix_len on.
Both pseudo_speculative_generate overrides keep their docstrings and call
the shared loop. DFlash's parallel decode, which DFlash2 and LiLiCorr
also use, is unchanged.

Verified against the parent commit:
- Bitwise A/B: the drafted tokens of the online DSpark (vanilla, gated
  and rnn heads) and Domino (pure_draft_prefix_len 1 and 0) cases are
  identical in fp32 and bf16, at init scale and with head weights large
  enough to decide the drafts. Loss, gradients and metrics of all 30
  cases, offline and online, are identical too.
- Sharded on one GPU with the CPU as the first device: accelerate
  dispatch with embed_tokens and lm_head on the CPU, and a split that
  also puts base layers 0-1 there. The drafts are identical for DFlash,
  DSpark and Domino in fp32 and bf16.
- Unit tests in test_hf_{dflash,dflash2,dspark,domino,lilicorr}.py and
  test_hf_spec_rope_export.py: 348 passed on transformers 5.5.4, 5.12.1
  and 5.18.0. GPU plugin tests: 20 passed, 1 skipped (needs 2 GPUs).
- Mutation check: 11 of 12 edits to the loop or the steps fail a unit
  test, the lm_head GPU test or the A/B. Dropping Domino's embedding move
  passes everything, because accelerate's hook on the GRU moves its input.

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