TorchSpec icon indicating copy to clipboard operation
TorchSpec copied to clipboard

DFlash/DSpark trainer missing norm layer

Open man2machine opened this issue 3 months ago • 2 comments

DFlash/DSpark trainer distills against pre-final-norm target hidden states (missing final RMSNorm) — L1/confidence targets are wrong

(Issue is written by an LLM)

Summary

Impact up front: reproducing the DSpark Qwen3-4B draft training with TorchSpec produces a draft with materially worse acceptance rates than the officially released deepseek-ai/dspark_qwen3_4b_block7 checkpoint, and we believe this bug is the primary cause. This is an important issue to solve — as it stands, TorchSpec does not reproduce the paper's DSpark results for Qwen3-4B. Under an identical, trusted eval harness (where the official checkpoint reproduces the paper's Table 1 almost exactly), our TorchSpec-trained checkpoint under-accepts by roughly 6–33%, with the deficit concentrated in math/reasoning and small in chat.

The mechanism: when last_hidden_states_prenorm=True (the default produced by the vLLM online-extraction path), the DFlash and DSpark trainers compute the target distribution for the L1 distillation and confidence-head losses by applying the target LM head directly to the pre-final-norm hidden state, i.e. lm_head(h_prenorm) instead of lm_head(final_norm(h_prenorm)). The target model's real next-token distribution is softmax(lm_head(final_norm(h))), so the distillation target is systematically wrong.

The Eagle3 trainer already handles this correctly (it loads the final norm and applies it before the LM head). The DFlash/DSpark path is missing the equivalent step.

Because the L1 term typically dominates the DSpark objective (l1_loss_alpha=0.9 vs ce_loss_alpha=0.1), and the confidence head is trained against the accept-rate derived from the same target, this corrupts the primary training signal while leaving the hard-label CE term intact.

Environment

  • Component: torchspec.training.dflash_trainer.DFlashTrainer / torchspec.training.dspark_trainer.DSparkTrainer
  • Target model used when observed: Qwen3-4B (final model.norm RMSNorm before lm_head)
  • Hidden-state source: vLLM online extraction (inference/engine/vllm_engine.py), which stores the reserved pre-norm slot.

Root cause

vLLM intentionally captures the pre-norm last-hidden slot and documents that training is expected to apply the final norm itself:

torchspec/inference/engine/vllm_engine.py (~L173–184)

# Append the model's final layer to capture last_hidden_states
# (pre-norm) for target logit computation.  Index `num_hidden_layers`
# is vllm's reserved post-last-layer / pre-`norm` slot, so training
# can apply the model's final norm itself on top of this.
final_layer_id = num_layers
if final_layer_id not in self.aux_hidden_state_layer_ids:
    self.aux_hidden_state_layer_ids.append(final_layer_id)

TargetLMHead supports loading that final norm (load_norm=True → self.norm), and its forward is a bare lm_head(x):

torchspec/models/target/target_utils.py

class TargetLMHead(nn.Module):
    # "When load_norm=True, also loads the final RMSNorm weights so the
    #  trainer can normalise pre-norm hidden states before the lm_head projection."
    ...
    def forward(self, hidden_states):
        return self.lm_head(hidden_states)   # no norm here by design

Eagle3 (correct):

torchspec/training/eagle3_trainer.py

self._last_hs_prenorm = getattr(self.args, "last_hidden_states_prenorm", False)
...
self.target_lm_head = TargetLMHead.from_pretrained(
    model_path=target_model_path,
    lm_head_key=...,
    norm_key=getattr(self.args, "norm_key", "model.norm.weight"),
    load_norm=self._last_hs_prenorm,          # <-- loads the final norm
    ...
)
self.verifier_norm = self.target_lm_head.norm
...
def _forward(self, batch):
    target_hidden_states = padding(batch["last_hidden_states"], left=False).cuda()
    if self.verifier_norm is not None:
        with torch.no_grad():
            target_hidden_states = self.verifier_norm(target_hidden_states)   # <-- applied
    ...

DFlash/DSpark (bug):

torchspec/training/dflash_trainer.py — _init_target_lm_head never passes load_norm, so self.norm stays None, and only the raw head weight is kept:

self.target_lm_head = TargetLMHead.from_pretrained(
    model_path=target_model_path,
    lm_head_key=getattr(self.args, "lm_head_key", "lm_head.weight"),
    device="cuda",
    dtype=torch.bfloat16,
)   # no load_norm, no norm_key -> self.norm is None
...
self.target_lm_head_weight = self.target_lm_head.lm_head.weight

_forward passes the pre-norm last_hidden_states straight to the model, with no norm applied:

last_hidden_states = batch.get("last_hidden_states", None)
...
self.model(
    input_ids=input_ids,
    hidden_states_list=hidden_states_list,
    loss_mask=loss_mask,
    lm_head_weight=self.target_lm_head_weight,
    last_hidden_states=last_hidden_states,   # pre-norm, un-normalized
)

torchspec/models/dspark.py then applies the LM head directly to the pre-norm hidden:

aligned_target_logits = F.linear(aligned_hidden, lm_head_weight).view(
    bsz, n_blocks, self.block_size, vocab_size
)   # == lm_head(h_prenorm); missing final_norm(h_prenorm)

The same pattern applies to the DFlash L1 path in torchspec/models/dflash.py.

For reference, DeepSeek's DeepSpec computes this target from the post-final-norm hidden and applies the LM head to that (correct), which is what the draft is meant to be distilled toward:

# DeepSpec scripts/data/prepare_target_cache.py
target_last_hidden_states = target_output.last_hidden_state.detach()  # post-final-norm
# DeepSpec deepspec/modeling/dspark/qwen3/modeling.py
def compute_logits(self, hidden_states):
    return self.lm_head(hidden_states)  # correct only because input is post-norm

Impact

  • Reproduction result (the headline problem): a TorchSpec-trained Qwen3-4B DSpark draft under-accepts relative to the released deepseek-ai/dspark_qwen3_4b_block7 checkpoint under the same eval harness. Measured mean acceptance lengths (official reproduces paper Table 1; our trained checkpoint is a full ~10-epoch run):

    Benchmark Official (paper repro) TorchSpec-trained Gap
    gsm8k 6.12 5.03 −17.9%
    math500 5.71 4.23 −25.9%
    aime25 4.90 3.28 −33.1%
    humaneval 5.45 4.92 −9.7%
    mbpp 5.14 4.75 −7.6%
    livecodebench 4.97 4.62 −7.0%
    mt-bench 3.59 3.35 −6.8%
    alpaca 3.55 3.34 −6.0%
    arena-hard-v2 3.26 2.86 −12.3%

    The gap concentrates in math/reasoning (where the target distribution is most peaked/informative) and is small in chat — exactly the signature of a corrupted distillation target rather than an eval or hyperparameter problem (hyperparameters were matched field-for-field to DeepSpec's dspark_qwen3_4b.py).

  • The L1 distribution-distillation target and the confidence-head target are computed from a distribution that omits the target model's final RMSNorm. RMSNorm applies a per-channel learned weight (not just a global scale), so softmax(lm_head(h)) differs from softmax(lm_head(norm(h))) in shape, not merely temperature.

  • With l1_loss_alpha=0.9, this corrupts the dominant training signal; the ce_loss_alpha=0.1 hard-label term is unaffected, so the draft still learns basic next-token structure but is distilled toward a wrong distribution.

  • Note the in-training simulated_acc_len metric is computed against the same corrupted target, so it can look healthy (~4.55 in our run) while real-serving acceptance lags — which is why this went unnoticed until an end-to-end eval against the official checkpoint.

Expected behavior

DFlash/DSpark should match Eagle3: when the stored last_hidden_states are pre-norm (last_hidden_states_prenorm=True), load the target's final norm and apply it before the LM head so the distillation/confidence target equals the target model's true next-token distribution.

Proposed fix

Mirror the Eagle3 wiring in the DFlash/DSpark trainer:

  1. In DFlashTrainer._init_target_lm_head, pass load_norm=getattr(self.args, "last_hidden_states_prenorm", False) (and norm_key) to TargetLMHead.from_pretrained, add the same rank-sync of norm presence used in eagle3_trainer, and expose self.verifier_norm = self.target_lm_head.norm.
  2. Apply the norm before the LM head. Either:
    • normalize in the trainer _forward before calling the model: if self.verifier_norm is not None: last_hidden_states = self.verifier_norm(last_hidden_states); or
    • thread the norm into models/dspark.py / models/dflash.py and apply it to aligned_hidden before F.linear(..., lm_head_weight).

The trainer-side normalization is the smaller change and requires no model-signature change.

Suggested tests

  • Numeric: on a real target forward, assert lm_head(verifier_norm(h_prenorm)) matches the model's own logits, and that softmax(lm_head(h_prenorm)) vs softmax(lm_head(norm(h_prenorm))) differ materially (mean L1 / KL ≫ 0).
  • Wiring: with last_hidden_states_prenorm=True, assert DFlashTrainer.verifier_norm is not None and that the aligned target logits equal lm_head(norm(pre_norm_hidden)).
  • Regression: a short from-scratch DSpark run with the fix should raise simulated_acc_len and improve measured acceptance vs the pre-fix baseline, with no change to the Eagle3 path.

man2machine avatar Aug 10 '26 21:08 man2machine

Hi @man2machine , thanks for reporting.

I believe it is already fixed by https://github.com/lightseekorg/TorchSpec/pull/162

torchspec-bot avatar Aug 11 '26 05:08 torchspec-bot

I see, thanks. It was a recent fix, so I didn't have it in my clone yet.

man2machine avatar Aug 11 '26 18:08 man2machine