Skip to content

[None][fix] DSpark: keep the drafter's trained mask-token embedding - #19842

Closed
vsabavat wants to merge 4 commits into
NVIDIA:mainfrom
vsabavat:k3-up/wip-comm16-dspark-mask
Closed

vsabavat wants to merge 4 commits into
NVIDIA:mainfrom
vsabavat:k3-up/wip-comm16-dspark-mask

Conversation

@vsabavat

@vsabavat vsabavat commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Description

What goes wrong. A GQA DSpark drafter (GQADSparkForCausalLM) shares the target's embedding and LM head:
DFlashForCausalLM.load_weights_from_target_model (tensorrt_llm/_torch/models/modeling_dflash.py:1000-1004)
replaces the drafter's embed_tokens with the target's, and GQADSparkForCausalLM
(tensorrt_llm/_torch/models/modeling_dspark.py:2646, load_weights at :2673) inherits that and keeps nothing of
its own. The DFlash worker then builds every masked slot of the drafter's input block from that shared embedding:
DFlashWorker.prepare_1st_drafter_inputs (tensorrt_llm/_torch/speculative/dflash.py:1950, :2001-2004) embeds the
mask token id through embed_tokens and copies that row into slots 1..K.

A DSpark drafter checkpoint can ship its own embedding with a trained row for its mask token. The Kimi K3 DSpark
drafter (RedHatAI/Kimi-K3-speculator.dspark) does: embed_tokens.weight [163840, 7168] bf16, mask token id
163837. That row is what the drafter was trained on. With the target's row instead, the drafts degrade: on Kimi K3
(MXFP4), 16 GB200, max_draft_len 7, the acceptance (avg_decoded_tokens_per_iter) on a set of fixed prompts is 2.45 where
the trained row gives 3.40. Outputs are unaffected: greedy verification still decides every token.

Fix.

  • GQADSparkForCausalLM.load_weights keeps the checkpoint's row for the mask token as mask_token_embedding when the
    checkpoint ships embed_tokens.weight (or model.embed_tokens.weight).
  • The worker's noise block is built by dflash_noise_block_embedding (the same computation, moved into a function).
    It uses mask_token_embedding for every masked slot when the drafter has one for the mask id in use; slot 0 stays
    the bonus token's row from the shared lookup. The lookup itself (embed_tokens.forward on the bonus tokens and the
    mask id) is unchanged, so every rank still makes the same TP-sharded embedding call.

Blast radius. Only GQA DSpark drafters whose checkpoint ships an embedding, and the DFlash worker's noise block
for generation requests:

  • plain DFlash drafters (GQA checkpoints that ship no embedding) and MLA DSpark drafters (which keep their own
    embedding already) set no mask_token_embedding, so the worker builds the same block as before;
  • a mask_token_id override in the speculative config that differs from the drafter's keeps the shared lookup;
  • other speculative modes and the target model are untouched.

Drafts change, and with them the acceptance; under greedy verification the generated tokens do not.

Test Coverage

tests/unittest/_torch/speculative/hw_agnostic/test_kimi_k3_dspark_semantics.py::test_gqa_dspark_keeps_its_trained_mask_row_over_the_target_embedding
(GPU): a tiny GQA DSpark drafter whose checkpoint ships an embedding, given a target embedding with a different mask
row. After load_weights_from_target_model, the drafter's mask_token_embedding equals the checkpoint's row, and
dflash_noise_block_embedding returns the bonus token's shared row in slot 0 and the trained row in every other
slot.

Results on GB200, main's own build:

  • main: the new test fails, AttributeError: 'GQADSparkForCausalLM' object has no attribute 'mask_token_embedding';
  • this PR: it passes;
  • the rest of test_kimi_k3_dspark_semantics.py and test_dflash_worker.py, test_dspark_worker.py,
    test_dspark_draft.py, test_dflash.py, test_dspark_cuda_graph.py: the same results on main and with this PR
    (no new failure).

End to end, Kimi K3 (MXFP4) with its DSpark drafter on 16 GB200 (TP16), max_draft_len 7, batch 8, CUDA graphs, main
and main with this PR:

  • 8 fixed prompts of 128 output tokens: the generated texts are identical; the acceptance
    (avg_decoded_tokens_per_iter, weighted by tokens) goes from 2.45 to 3.40 (per-prompt mean 2.58 to 3.80);
  • GSM8K, all 1319 problems: accuracy 96.74 on main and 96.66 with this PR (one problem, within the 0.49 standard
    error). The verify steps fall from 55,076 to 32,196, so the acceptance rises from about 2.5 to 4.3 tokens per
    step (137,404 generated tokens, from a run without speculation);
  • 32 requests of 1024 output tokens at concurrency 8: the mean time per output token drops from 12.46 ms to 9.27 ms
    (-26 %) and the output throughput rises from 588 to 759 tokens/s (+29 %).

k3rest (#19841) carries the same commit (cherry-pick, same patch-id) so its DSpark acceptance is right; it drops out of k3rest when this PR merges.

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • If PR introduces API changes, an appropriate PR label is added - either api-compatible or api-breaking. For api-breaking, include BREAKING in the PR title. (No API change.)

  • Any new dependencies have been scanned for license and vulnerabilities (No new dependencies.)

  • CODEOWNERS updated if ownership changes (No ownership change.)

  • Documentation updated as needed (No documentation change.)

  • Update tava architecture diagram if there is a significant design change in PR. (No design change.)

  • The reviewers assigned automatically/manually are appropriate for the PR. (To check once the PR is open.)

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

To see a list of available CI bot commands, please comment /bot help.

…ken embedding

GQADSparkForCausalLM takes the target's embedding in
load_weights_from_target_model, so the DFlash worker built every masked
block slot from the target's row for the mask token, which the target never
trained. A drafter checkpoint that ships its own embedding has trained that
row. load_weights now keeps it as mask_token_embedding, and the worker's
noise block (dflash_noise_block_embedding, the same computation moved into a
function) uses it for every masked slot when the drafter has one for the
mask id in use; slot 0 stays the bonus token's shared lookup. Every rank
still embeds the mask id through embed_tokens.forward, as before.

Drafts change; under greedy verification the target's tokens do not. Plain
DFlash and MLA DSpark drafters set no mask_token_embedding and are unchanged.

Signed-off-by: Vasanth Sabavat <[email protected]>

@longlee0622 longlee0622 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the clear write-up and the E2E numbers. The diagnosis is convincing, and the change is safe: the shared embed_tokens.forward call is kept, so TP collectives stay symmetric. A few points before merge:

  1. Why keep only the mask row instead of the drafter's whole embedding?
    MLADSparkForCausalLM sets WEIGHTS_SHARED_WITH_TARGET = ("lm_head",) and keeps its own embed_tokens, because its values differ from the target's. The K3 GQA drafter also ships a full [163840, 7168] embedding. If any rows besides the mask token also differ from the target's, then slot 0 (the bonus token) still gets the target's row, which is the same train/inference mismatch, and there may be more acceptance to gain. Could you check whether the drafter's embedding is bit-exact with the target's outside the mask row?

    • If it is not, I'd suggest following the MLA approach: don't share embed_tokens when the checkpoint ships one. That keeps one rule for both DSpark flavours instead of adding a third "share all but one row" behaviour. It also removes the special case in the worker. The cost is about 147 MB per rank at TP16.
    • If it is, a short comment saying so would help the next reader understand why only the mask row is kept.
  2. Validate the row at load time. weight[self.mask_token_id : self.mask_token_id + 1].reshape(-1) doesn't check that mask_token_id < weight.shape[0] or that the row width equals hidden_size. An out-of-range id gives an empty tensor, and the failure only shows up later as an unclear expand error in the worker. An explicit check in _keep_trained_mask_embedding would make this fail early with a clear message.

  3. Minor:

    • .to("cuda") relies on the current device being set correctly. Using the drafter's own parameter device (e.g. self.fc.weight.device) would be more robust.
    • trained_mask_embedding.to(embed_mask.dtype) runs on every step. Casting once at load time to the model dtype avoids that.
  4. Related to 1 (pre-existing, not introduced here): when the checkpoint ships embed_tokens.weight, the full embedding is first loaded into the drafter in DFlashForCausalLM.load_weights and then thrown away by load_weights_from_target_model. Going the MLA route would fix this as well.

…ast it once

Follow-ups on the trained mask-token row this branch keeps:
- The row is checked at load, before any weight is copied: the shipped
  embedding must be [rows, hidden_size], and the drafter's mask_token_id
  must be one of its rows. A ValueError names the problem. Before, an id
  past the rows kept an empty row, which failed later in the worker's
  noise block.
- The row is cast to the drafter's dtype and placed on the device of the
  drafter's own fc weight once, at load. The noise block uses it as given,
  with no per-step cast and no reliance on the current CUDA device.
- The docstring says why only the mask row is kept: in the Kimi K3 drafter
  (RedHatAI/Kimi-K3-speculator.dspark) it is the only one of the 163,840
  embedding rows that differs from the target's, and the shipped lm_head
  is bit-exact with the target's.

Tests: test_gqa_dspark_mask_row_takes_the_drafter_dtype_and_device_at_load
and test_gqa_dspark_rejects_a_mask_row_the_shipped_embedding_does_not_have
(out-of-range, negative and wrong-width cases).

Signed-off-by: Vasanth Sabavat <[email protected]>
… mask id

eda9db2 raised for any mask id outside the shipped embedding, including
DFlash's default (vocab_size). The drafter takes that default when its
config names no mask token in a key it reads. The speculative config can
still name the mask token then (a user value, or a key only it reads, such
as dspark_noise_token_id), and such a drafter loaded before.

It now keeps no row, as a checkpoint without an embedding does. Any other
id outside the shipped rows still raises.

Test: test_gqa_dspark_keeps_no_mask_row_when_its_config_names_no_mask_token.
The out-of-range case of the rejection test now uses vocab_size + 1.

Signed-off-by: Vasanth Sabavat <[email protected]>
@vsabavat

vsabavat commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Points 1-3 are addressed in eda9db2 and 0cbb559; point 4 is answered below.

  1. The drafter's embedding is bit-exact with the target's outside the mask row. We compared the two checkpoints'
    tensors bitwise, row by row: RedHatAI/Kimi-K3-speculator.dspark embed_tokens.weight against Kimi K3's
    language_model.model.embed_tokens.weight, both BF16 [163840, 7168].

    • Only the mask token's row (163837) differs: 7159 of its 7168 values, with cosine similarity 0.006 to the
      target's row.
    • The other 163,839 rows are bit-exact, and so is the shipped lm_head.weight (0 rows differ).

    So slot 0 (the bonus token) already gets the drafter's trained values through the shared lookup, and owning the
    whole embedding would gain no acceptance. We kept the mask-row design and added the comment you suggested, in
    _trained_mask_row's docstring.

  2. The row is checked at load. _trained_mask_row raises a ValueError before any weight is copied if:

    • the shipped embedding is not [rows, hidden_size], or
    • the mask id the drafter config names is not one of its rows. Negative ids are rejected too, since the row is
      now read with a single index.

    One case still loads, keeping no row: a drafter config that names no mask token in a key the drafter reads. DFlash
    then defaults the id to vocab_size, one past the rows. The speculative config can still name the mask token (a
    user value, or a key only it reads, such as dspark_noise_token_id), and such a drafter loads today, so it should
    not fail here.

    Tests: test_gqa_dspark_rejects_a_mask_row_the_shipped_embedding_does_not_have (3 cases) and
    test_gqa_dspark_keeps_no_mask_row_when_its_config_names_no_mask_token.

  3. Device and dtype are set once, at load.

    • The row is cast to the drafter's dtype (model_config.torch_dtype) and placed on self.fc.weight.device, after
      DFlash's load builds fc.
    • dflash_noise_block_embedding uses it as given, with no per-step .to().

    Test: test_gqa_dspark_mask_row_takes_the_drafter_dtype_and_device_at_load. An fp32 checkpoint row comes out
    bf16 on fc's device.

  4. No change here.

    • The embedding is bit-exact outside the mask row (point 1). Owning it would add ~147 MB per rank at TP16 for
      identical values.
    • The double load is pre-existing for any DFlash drafter whose checkpoint ships an embedding. The drafter's
      embed_tokens is allocated when the drafter is built, whether or not the checkpoint ships one.
      load_weights_from_target_model then replaces it, so the drafter's copy is not kept after load. The cost is the
      load-time copy of the shipped tensor.
    • Skipping embed_tokens.weight in DFlashForCausalLM.load_weights would remove that copy. It is independent of
      this fix, so we would leave it to a separate change.

Validation of 0cbb559:

  • Unit tests (GB200, main's build).
    • The five new cases fail on ba20fa1 and pass with the follow-ups:
      • the row was kept as float32;
      • two ids outside the rows loaded without an error;
      • a wrong width failed only later, in the embedding copy, as a size-mismatch RuntimeError;
      • the default id kept an empty row.
    • test_kimi_k3_dspark_semantics.py: 47 passed / 6 failed before, 52 / 1 after. The remaining failure,
      test_mla_dspark_auto_backend_resolves_to_cutedsl, fails the same way on main.
    • The DFlash / DSpark worker tests: 46 passed / 5 failed with and without the change. The 5 need gated HF models.
  • End to end: Kimi K3 with the RedHatAI drafter on 16 GB200 (TP16, max_draft_len 7), on the K3 branch that
    carries this PR, with and without the follow-ups.
    • GSM8K, all 1319 problems, natural acceptance: 96.21 / 96.13 (flexible / strict) both ways. Every response is
      identical, and so is the number of verify steps (~4.28 accepted tokens per step).
    • Forced acceptance (AL 6), 8 fixed prompts: identical outputs.
    • Decode TPOT at batch 1 / 2 / 4 / 8: 1.009 / 1.695 / 1.904 / 2.562 ms with the follow-ups, 1.010 / 1.699 / 1.924 /
      2.518 ms without. That is within run-to-run noise: at batch 8 the five repeats span 2.512-2.573 ms with and
      2.488-2.573 ms without.

@longlee0622

Copy link
Copy Markdown
Collaborator

Thanks for the updates and the bitwise comparison. Points 1-4 look resolved to me. One remaining concern, about the default-id branch you added in _trained_mask_row:

A GQA DSpark checkpoint that names its mask token only as dspark_noise_token_id silently falls back to the target's row, which is the bug this PR fixes.

Here is how the two sides pick the mask id:

  • The spec config: when spec_cfg.mask_token_id is None, llm_args.py (~L6732) reads it from the checkpoint as _dspark_get("mask_token_id", "dspark_noise_token_id"). The worker then uses spec_config.mask_token_id first.
  • The drafter: DFlashForCausalLM.__init__ (modeling_dflash.py ~L454) reads only dflash_config.mask_token_id / mask_token_id. Otherwise it defaults to vocab_size.

So for such a checkpoint:

  1. spec_config.mask_token_id is the trained id (e.g. 163837), while drafter.mask_token_id == vocab_size.
  2. _trained_mask_row takes the new == vocab_size branch and keeps nothing.
  3. In the worker, mask_token_id == getattr(draft_model, "mask_token_id", None) (dflash.py ~L2029) is False, so every masked slot gets the target's untrained row again.

There is no error and no log message. Only the acceptance drops. The K3 RedHatAI checkpoint isn't affected, since its config names a key the drafter reads, but the next DSpark checkpoint could hit this.

The row we should keep is actually known at load time: it's the id the worker will use. Could _trained_mask_row resolve the id the same way the worker does (spec_config.mask_token_id if set, else self.mask_token_id), and the worker compare against that? Another option is for the drafter to also read dspark_noise_token_id. At minimum, please log a warning when the checkpoint ships an embedding but no row is kept.

…mask id

The worker embeds the speculative config's mask id when it has one, and
that config also reads a checkpoint key the drafter's own config
resolution does not: dspark_noise_token_id. For a checkpoint that names
its mask token only that way, the drafter fell back to DFlash's default
id (vocab_size) and kept no trained row. The worker's id check then
failed, so every masked slot silently got the target's row again.

The drafter's own ModelConfig carries no spec_config, so
_build_dspark_draft now hands the speculative config's mask id to
GQADSparkForCausalLM, which adopts it. The drafter keeps the row of the
id the worker uses, and the worker's check matches. MLA DSpark keeps its
own embedding and is unchanged.

When a shipped embedding still keeps no row (no config names a mask
token), the drafter logs a warning.

Tests: test_gqa_dspark_keeps_the_trained_row_of_the_speculative_configs_mask_id
and test_gqa_dspark_warns_when_its_shipped_embedding_keeps_no_mask_row.

Signed-off-by: Vasanth Sabavat <[email protected]>
@vsabavat

vsabavat commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks, good catch. Confirmed and fixed in b83f960, following your first option.

  • Fix.
    • The drafter's own ModelConfig carries no spec_config, so _build_dspark_draft now passes
      spec_config.mask_token_id to GQADSparkForCausalLM, through a new keyword-only argument spec_mask_token_id.
    • When it is set, the drafter adopts it. That is the id the worker embeds, so _trained_mask_row keeps that id's
      trained row, and the existing check in the worker (dflash.py ~L2029) matches.
    • dflash.py is unchanged, and so is MLADSparkForCausalLM, which keeps its own embedding.
  • Warning. When a checkpoint ships an embedding but the mask id is still DFlash's default (vocab_size: no
    config names a mask token), _trained_mask_row logs a warning. It says no trained mask row is kept and the masked
    slots use the shared embedding's row.
  • Tests (GB200; both fail on 0cbb559 and pass on b83f960):
    • test_gqa_dspark_keeps_the_trained_row_of_the_speculative_configs_mask_id: a drafter config that names its mask
      token only as dspark_noise_token_id, built through _build_dspark_draft with the speculative config's id. It
      keeps that id's trained row, and its mask_token_id is the worker's id. Before the fix it held vocab_size.
    • test_gqa_dspark_warns_when_its_shipped_embedding_keeps_no_mask_row. Before the fix nothing was logged.
    • test_kimi_k3_dspark_semantics.py: 52 passed / 3 failed before, 54 / 1 after. The remaining failure,
      test_mla_dspark_auto_backend_resolves_to_cutedsl, fails the same way on main. The DFlash / DSpark worker tests:
      46 passed / 5 failed both ways; the 5 need gated HF models.
  • Kimi K3 is unaffected. We checked through the real config resolution. For the RedHatAI drafter, the speculative
    config's mask id and the drafter's own id are both 163837, before and after this commit. The drafter that
    _build_dspark_draft builds holds 163837 in both cases, so this commit leaves the K3 path unchanged.

@vsabavat

vsabavat commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by the consolidated draft PR: #19988. Source commits and follow-ups are retained; prior reviews remain historical evidence, not approval of the replacement heads.

@vsabavat vsabavat closed this Oct 8, 2026
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.

4 participants