Skip to content

feat(speculative): D-PACE position weighting for DSpark and Domino - #2991

Draft
h-guo18 wants to merge 25 commits into
haoguo/dflash-shared-forwardfrom
haoguo/dspark-domino-dpace
Draft

h-guo18 wants to merge 25 commits into
haoguo/dflash-shared-forwardfrom
haoguo/dspark-domino-dpace

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. It changes the default weighting for DSpark and Domino configs that leave dflash_loss_objective unset, and for runs resumed from checkpoints saved before it.

This PR is stacked on #2990 [2/2] (branch haoguo/dflash-shared-forward, which gives the DFlash family one training forward), whose branch is its base; review and merge it after that one. The stack below is #2757 → #2762 → #2989 [1/2] → #2990 [2/2]. Three other PRs also sit on #2990 and are independent of this one: logging draft_metrics in the trainer (#2992), loss terms in config (#2993), and the shared AR-decode helper (#2994).

Since they were added in 0.46.0, DSpark and Domino have ignored dflash_loss_objective. They always weighted block positions with the static dflash_loss_decay_factor decay, while DFlash, DFlash2 and LiLiCorr follow the objective, whose default is dpace. On the shared forward this came down to one override per variant: _position_weighting returning "decay". Meanwhile DFlashModel.modify warned that the decay factor is ignored under D-PACE, which was false for these two.

  • DSpark and Domino follow the objective.
    • The two overrides are removed. So is the _position_weighting hook, since nothing else overrode it; _loss_context now reads dflash_loss_objective directly.
    • Both variants are weighted from their first predicted block position, 0 (1 - _label_shift).
    • D-PACE reads the draft's confidence off the served (final) logits: DSpark's Markov-biased logits and Domino's GRU-corrected ones.
    • One set of weights per step reduces every term: DSpark's CE, TVD and confidence BCE, and both of Domino's objectives, final and backbone. Domino's backbone objective in the λ-curriculum is therefore weighted by the served draft's confidence, not its own.
    • The decay path is unchanged.
  • New runs of the shipped recipes keep their tuned weighting. dspark.yaml and domino.yaml set dflash_loss_decay_factor: 7.0 without an objective, so they would have switched to D-PACE.
    • Both now pin dflash_loss_objective: decay. That commit lands first, so every commit trains them the same.
    • The Kimi-K2.6 and MiniMax-M3 DSpark launchers inherit the pin from dspark.yaml.
    • The Qwen3-8B Domino launcher repeats the recipe's knobs for visibility, so it now lists the pin too, as the LiLiCorr launcher does.
  • Docs.
    • A Backward Breaking Changes entry in the CHANGELOG, under 0.49.0. It also tells users to finish runs started on an earlier version before upgrading.
    • The DSpark and Domino skill sheets list the pinned decay among the recipes' differences from DFlash.
    • Each sheet also gets a known-failures row for a resumed run, keyed on the warning the restore logs.

Behavior change:

  • A DSpark or Domino config that leaves dflash_loss_objective unset now trains with D-PACE and ignores dflash_loss_decay_factor, as the existing warning says.
  • A config that sets dpace now gets it.
  • A run resumed from a checkpoint saved before this change continues with D-PACE, unless its config set decay.
    • The checkpoint's modelopt_state holds the default dpace, which the old code ignored.
    • main.py resumes an HF-format checkpoint, the format DDP writes and the shipped DSpark and Domino recipes use, by restoring that saved config. It never re-reads the recipe, so the new pin does not reach the run.
    • The checkpoint itself loads unchanged. The only sign is the restore's "dflash_loss_decay_factor=7.0 is ignored" warning, which these recipes already printed, wrongly, before this change.
    • Finish such runs on the version that started them.
  • As for DFlash under D-PACE, a step whose only supervised label has weight below 1 takes the zero-loss path. Under decay, a lone label at block position 0 had weight exactly 1 and trained.
  • Generation and export are unaffected.

Usage

dflash:
  dflash_loss_objective: dpace   # `decay` keeps the static schedule, as the shipped recipes do
  dflash_dpace_alpha: 0.5
  dflash_architecture_config:
    projector_type: dspark       # or domino

On top of the shipped recipes: dflash.dflash_loss_objective=dpace.

Testing

  • New test. test_next_token_variants_weight_positions_by_the_objective[dspark|domino-dpace|decay] runs the real training forward and checks, bitwise:

    • the position weights handed to the loss equal _block_position_weights(mask, objective, 0, ...) computed from the final logits' cross-entropy;
    • DSpark's loss_ce and Domino's loss_backbone equal their cross-entropy reduced under those weights.

    It fails on the base for both D-PACE cases, which got decay weights. In scratch runs it also fails when the confidence is read off the backbone, when the first weighted position is 1, and when Domino's backbone objective gets D-PACE weights of its own. Each case takes at most 0.13 s on 4 CPUs (taskset -c 0-3).

  • Unit tests. The test files this PR changes or exercises, on CPU: test_hf_dflash.py, test_hf_dflash2.py, test_hf_dspark.py, test_hf_domino.py, test_hf_lilicorr.py and test_hf_dflash_offline.py under tests/unit/torch/speculative/plugins, and tests/unit/recipe/test_loader.py. 806 passed on each of transformers 5.5.4 and 5.18.0, CI's tf_min and tf_latest pins (802 on the base; the other 4 are the new test's cases).

  • GPU tests. tests/gpu/torch/speculative/plugins on 1 GPU: 20 passed, 1 skipped (that test needs 2 GPUs), as on the base.

  • Bitwise A/B against the base. One training step per case, plus generation at steps 0, 2 and 4 for the online cases, in fp32 and bf16. Compared: loss, every gradient, train_acc, every draft_metrics value and the generated tokens.

    • The 23 existing cases (46 runs) are identical. They cover DFlash (KD and CE), DFlash2 (ce, kd, tv and lambda), LiLiCorr, DSpark (vanilla and rnn heads, with the confidence head) and Domino, offline and online, with D-PACE and decay, including zero-loss steps. All 15 cases with an explicit decay objective are among them.
    • The 5 new DSpark/Domino D-PACE training cases differ, as intended. For example, the DSpark offline loss goes from 0.674028516 to 0.671546638 in fp32, and the Domino online loss from 3.45916319 to 3.43934727. Every gradient changes (28 of 29 in one bf16 run). DSpark's loss_ce, loss_tvd and confidence_loss change, as do Domino's loss_final and loss_backbone. The generated tokens are identical.
    • Each of those 5 cases also equals, bitwise, the base with the two overrides deleted at runtime.
    • The 2 new zero-loss D-PACE cases are identical: both trees take the zero path.
    • Further cases, as expected. 15 are identical: DSpark's gated head, its rnn head online, DSpark and Domino under decay with the KD flag set (which they ignore), zero-loss steps of DFlash2 and LiLiCorr, DFlash2 KD online, and six cases whose labels are -100 on some tokens. 6 more DSpark/Domino D-PACE cases (the gated head, the KD flag set, labels with -100) differ as intended and equal, bitwise, the base with the overrides deleted.
  • Resume across the change, on transformers 5.5.4 and 5.18.0. Tiny DSpark and Domino models were converted from each tree's shipped recipe and saved with save_pretrained. Each was then loaded the way main.py resumes an HF-format checkpoint (load_vlm_or_llm under patch_transformers5_params_loading, then restore_draft_precision) and run for one training step.

    • Saved on the base, both store dflash_loss_objective: dpace with decay factor 7.0. Resumed on the base, the step's position weights equal the static decay. Resumed here, they equal the D-PACE weights, and the restore logs the decay-factor warning.
    • Saved here from the pinned recipes, both store and restore decay, and the step uses the static decay.
  • FSDP2 probe (2 gloo ranks, the draft as its own fully_shard unit, one rank on the zero-loss branch).

    • DFlash with CE and with KD finishes on both ranks, with the same losses as on the base: 3.47548 and 3.48123 under CE, 3.47471 and 3.47468 under KD.
    • DSpark and Domino fail with "mixed torch.Tensor and DTensor" on the base and here alike, under either objective. Their heads call draft submodules outside the draft unit's forward, before any weighting runs.
  • Recipes and pre-commit. Both recipes load through ModelOptDFlashRecipe with objective decay and decay factor 7.0. The launcher's example-resolution tests pass (75). pre-commit run --files <changed files> is 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?: ❌ DSpark and Domino configs that leave dflash_loss_objective unset now train with D-PACE. Set dflash_loss_objective: decay to keep the previous weighting, as the shipped recipes now do. A run resumed from a checkpoint saved before this change restores that checkpoint's objective (dpace unless it was set) instead of the recipe's, so it switches to D-PACE; finish such runs on the version that started them. Checkpoints still load, and export and generation are unaffected.
  • 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?: ✅ One Backward Breaking Changes entry under 0.49.0, since DSpark and Domino have shipped since 0.46.0. It covers runs resumed across the change.
  • Did you get Claude approval on this PR?: ❌ Not run yet.

Additional Information

🤖 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]>
…ecay

dspark.yaml and domino.yaml set dflash_loss_decay_factor: 7.0 without an objective.
DSpark and Domino ignore dflash_loss_objective today and always decay; once they honor
it, the default 'dpace' would switch both recipes to D-PACE and drop the decay factor
they were tuned with. Pin dflash_loss_objective: decay in both, and list it among the
knobs the Qwen3-8B Domino launcher repeats for visibility, as the LiLiCorr launcher
does. The DSpark launchers (Kimi-K2.6, MiniMax-M3) inherit the pin from dspark.yaml.

No behavior change at this commit. Verified that both recipes load through
ModelOptDFlashRecipe with objective 'decay' and decay factor 7.0; pre-commit's recipe
and launcher-reference validators pass.

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

DSpark and Domino overrode the shared forward's _position_weighting hook to return
"decay", so dflash_loss_objective, whose default is "dpace", had no effect on them, and
DFlashModel.modify's warning that the decay factor is ignored under D-PACE was false
for both.

They now follow the objective like the rest of the family, from their first predicted
block position, 0. D-PACE reads the draft's confidence off the served (final) logits,
and that one set of weights reduces every term of the step: DSpark's CE, TVD and
confidence BCE, and both of Domino's objectives, final and backbone. With no override
left, the hook goes and _loss_context reads dflash_loss_objective directly.

The new test pins, for both variants and both objectives, the weights handed to the loss
to _block_position_weights from position 0 on the final logits, and the reported CE
(DSpark) and backbone CE (Domino) to their reduction under those weights. It fails on
the parent for D-PACE, and it fails when the confidence is read off the backbone, when
the first position is 1, and when Domino's backbone CE gets its own D-PACE weights.

Verified against the parent with one training and one generation step per case, in
fp32 and bf16. The 23 existing cases (every variant, offline and online, decay and
D-PACE, zero-loss steps included) are bitwise equal in loss, gradients, metrics and
generated tokens. The five new DSpark/Domino D-PACE training cases change loss and
gradients, as intended, generate the same tokens, and equal bitwise the parent with
the two overrides deleted at runtime; their two zero-loss cases are unchanged.
The DFlash-family plugin tests and the recipe loader tests pass on transformers 5.5 and
5.18 (806, the 4 new cases included), the GPU plugin tests pass, and the FSDP2 DFlash
probes pass on both ranks.

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

Users of a released DSpark or Domino who leave dflash_loss_objective unset move from
the static decay to D-PACE, so the changelog lists it under backward breaking changes
with the one-line way back. That way back does not reach a run resumed across the
upgrade: its checkpoint stores the default 'dpace' the old code ignored, and main.py's
HF-format resume restores it without re-reading the recipe, so the run continues with
D-PACE. The entry says to finish such runs on the version that started them, and the
DSpark and Domino skill sheets key the case on the warning the restore logs. The
sheets also list the pinned static decay among the recipes' deltas from DFlash.

Verified with pre-commit (rst, markdownlint, skill symlink sync), and by resuming
DSpark and Domino checkpoints through main.py's HF-format loader: saved from the
branch base's shipped recipes, they restore 'dpace' and weight the next step with the
static decay on that base but with D-PACE here; saved from the pinned recipes, they
restore 'decay' and keep it.

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.

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