Repository navigation
[MTP] Add MTP module for deepseek_v3 model - #3392
Conversation
|
Hi @Matrix-Z97! Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at [email protected]. Thanks! |
|
|
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
@tianyu-l Could you help review this code? |
|
@tianyu-l Hi, could you help review this MTP implementation when you have time? The MTP module is implemented as a common MTPBlock / MTPTransformerBlock, configured through Trainer.Config.mtp, and wired into Decoder.forward() so model-specific code only needs to provide sharding/state-dict details. The CP path uses dataloader-prepared [S + K] sequences and keeps the extra shifted tokens local after CP sharding so each rank can compute the MTP depths. There are still a few limitations in the current version: MTPLoss is implemented as a weighted auxiliary CE loss rather than a more general loss composition mechanism, and PP is not supported for MTP yet. If needed, I’d be happy to further improve and polish these parts based on your feedback. Do you have any plans or preferred direction for supporting MTP? I’d appreciate any guidance on whether this common-module approach matches the direction you’d like TorchTitan to take. |
|
@Matrix-Z97 sorry I apologize for the delay, will definitely get to it before end of week |
|
tianyu-l
left a comment
There was a problem hiding this comment.
Sorry for the delay! Left some initial reviews.
Also fyi I'll be afk for two days, during which I'd have limited access for further review.
| loss: BaseLoss.Config = field(default_factory=BaseLoss.Config) | ||
| # Multi-Token Prediction training config. Trainer wires this shared | ||
| # config into both the model and MTPLoss before either component builds. | ||
| mtp: MTPBlock.Config | None = None |
There was a problem hiding this comment.
Trainer shouldn't be aware of MTP. In general let's try to make this file oblivious to MTP.
| ) | ||
|
|
||
|
|
||
| def apply_fsdp_to_decoder( |
There was a problem hiding this comment.
This is a function that applies FSDP to decoder. I feel Decoder + MTP form it's own model structure which is worth its own FSDP application logic, potentially calling this one as a sub-function.
There was a problem hiding this comment.
That makes sense. The reason I reused the decoder FSDP path here is that mtp_block is also composed of transformer-block-like modules, so it can share the same FSDP treatment as the main decoder layers.
This keeps the change minimal while still covering the MTP parameters correctly. If preferred, I can split this into an explicit apply_fsdp_to_mtp_decoder() wrapper that prepares the combined block list and then reuses the existing decoder FSDP logic as a sub-function.
There was a problem hiding this comment.
let's be conservative and create a separate apply_fsdp_to_mtp_decoder used by deepseek_v3 only for now
There was a problem hiding this comment.
Done. I kept the generic decoder FSDP path unchanged and added a separate apply_fsdp_to_mtp_decoder() in mtp.py
The MTP-specific wrapper temporarily exposes mtp_layers through the decoder-style model.layers interface, calls the existing apply_fsdp_to_decoder() to reuse the battle-tested FSDP/MoE handling, and then removes the temporary entries. This keeps the change conservative and scoped to DeepSeek-V3 MTP for now.
There was a problem hiding this comment.
Given the complexity, I would worry about CP in a separate PR.
There was a problem hiding this comment.
OK, the CP-related parts have already been removed. If needed, I can further improve this in a follow-up.
| self._maybe_compile(compile_config) | ||
|
|
||
|
|
||
| class MTPLoss(BaseLoss): |
There was a problem hiding this comment.
I imagine it'd be trickier to apply Chunked CE loss with MTP, which is the current default in torchtitan.
In the first PR, I agree that let's not worry about that.
There was a problem hiding this comment.
I have to admit that I haven't tried to implement MTP in torchtitan by myself, so the direction I'm giving below may have problems, but here's the high level idea I would propose based on my limited understanding looking at the Figure 3 in DeepSeek V3 paper:
- Decoder + MTP should be the model itself, instead of putting MTP into trainer.
- the new high level module (e.g. MTPDecoder) should inherit Decoder and add MTP blocks, or compose with Decoder by owning Decoder and MTP blocks as attributes.
- The output of this new module should be a tuple/list from [Main Decoder, MTP Module 1, MTP Module 2, etc.].
- The loss function (e.g. MTPCrossEntropyLoss) should consume one labels and the tuple above, with MTP weights being in a config.
There was a problem hiding this comment.
Thanks for the suggestion. I agree with this direction, and I updated the implementation to follow this model-centric structure.
In the current version:
-
MTPDecoderinherits fromDecoderand owns theMTPBlock. -
DeepSeek-V3 now uses
MTPDecoder, soDecoder + MTPis represented as the model itself. -
The forward output is a list:
[main_logits, mtp_logits_1, mtp_logits_2, ...]
-
MTPLossconsumes the single labels tensor together with that list of logits, and applies the configured auxiliary MTP loss weight. -
Trainer no longer owns or wires an
mtp_config. It only uses the model config’sextra_mtp_tokensto request the additional future tokens needed by prepared-input MTP.
|
what about PP? for PP it will be tricky. we are also very interested in having MTP for our model training, i will be back to work next week and can help review more. |
Good question. A straightforward implementation for PP would be to ensure that the MTP block is placed on the last pipeline stage together with the final decoder output, though there may be better designs. Given the complexity, I’d suggest handling PP support in a follow-up PR after the current MTP architecture becomes more mature. I also fully agree with your suggestion to make MTP a common component. The current MTP implementation is already moving in that direction, and we can keep refining it to make it more reusable across models. Looking forward to your help and feedback. |
| ) | ||
|
|
||
|
|
||
| class MTPDecoder(Decoder): |
There was a problem hiding this comment.
let's put this in mtp.py and leave decoder.py intact
| return self.mtp_norm(h) | ||
|
|
||
|
|
||
| class MTPBlock(Module): |
There was a problem hiding this comment.
I don't feel we need this abstraction. A MTPDecoder can directly own the list of MTP modules?
| ) | ||
|
|
||
|
|
||
| def mtp_labels_for_depth( |
There was a problem hiding this comment.
Is this used? Let's try to make the PR minimal
| *, | ||
| num_mtp_modules: int, | ||
| ) -> MTPSequenceSlices: | ||
| """Split ``[B, S + K]`` into main ``[B, S]`` and K shifted ``[B, S]`` views.""" |
There was a problem hiding this comment.
Does this work with document packing? Seems not
| # Keep the inner transformer block intact and wrap only the MTP | ||
| # fusion/projection modules around it. This lets model-specific | ||
| # block construction stay in the original block config. | ||
| return cls( |
There was a problem hiding this comment.
It's confusing for this cls to accept attention, feed_forward, etc. and inner_block, and enorm, etc.
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class Config(TransformerBlock.Config): | ||
| inner_block_config: TransformerBlock.Config |
There was a problem hiding this comment.
would inheriting TransformerBlock (instead of composition) makes it easier?
| self.tokenizer = config.tokenizer.build(tokenizer_path=config.hf_assets_path) | ||
|
|
||
| # build dataloader | ||
| dataloader_seq_len = config.training.seq_len + self.extra_mtp_tokens |
There was a problem hiding this comment.
I'm not comfortable with this change
- MTP is modeling behavior
- dataloader seq len is infra behavior
Let's say the dataloader previous loads a single row with seq_len=8 and two documents
[A0, A1, A2, B0, B1, B2, B3, B4]
How are you handling MTP for each document? Would TP / CP (which would shard on seq dim at some point) behavior change?
Maybe should have an RFC before code change?
There was a problem hiding this comment.
Thanks for pointing this out! It's important to keep the MTP module decoupled from the dataloader for TP/CP correctness, and the sequence sharding you mentioned is an excellent point.
I’ll rethink how to properly decouple the design. Regarding the RFC, do you prefer I post the draft directly under this PR, or should I open a new issue/doc for it?
There was a problem hiding this comment.
post under this PR is fine, but however you prefer
There was a problem hiding this comment.
I updated the implementation so the dataloader no longer needs to change seq_len or load extra MTP tokens. The model still receives the normal [B, S] input, and MTP shifted inputs are generated inside the model with a length-preserving shift. For packed documents, the shift uses reset-style positions to avoid crossing document boundaries. For example:
tokens: [A0, A1, A2, B0, B1, B2, B3, B4]
positions: [ 0, 1, 2, 0, 1, 2, 3, 4]
shift=1: [A1, A2, 0, B1, B2, B3, B4, 0]
The loss side uses the same shifting logic for MTP labels, with invalid document-tail positions filled as ignore labels, so A2 will not be trained to predict B0.
For CP/SP, this likely needs extra communication, such as exchanging boundary tokens between neighboring ranks or all-gathering the sequence before shifting and re-sharding.
There was a problem hiding this comment.
For SP (on TP axis) it should work out-of-box, because the labels are never sharded, assuming we don't use Chunked CE loss. Is this right?
For CP it indeed sounds tricky, especially considering we would like to push CP input sharding into dataloader. cc @fegin @jinsooihm
There was a problem hiding this comment.
In the current MTP path, the main decoder hidden states become SP-sharded after the transformer layers, while the shifted-token validity mask/labels are produced from unsharded tokens / positions. That caused layout mismatches in practice, for example when multiplying mtp_prev_embed with the valid-token mask and when using torch.where to build packed-document-correct MTP labels.
| num_mtp_layers: int = 0 | ||
| mtp_layer_config: TransformerBlock.Config | None = None |
There was a problem hiding this comment.
each mtp layer should have its own config, like https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/decoder.py#L82
| class Config(Decoder.Config): | ||
| num_mtp_layers: int = 0 | ||
| mtp_layer_config: TransformerBlock.Config | None = None | ||
| detach_heads: bool = False |
There was a problem hiding this comment.
Interesting flag. In reality is this always False? If so can we not introduce this flag right now?
| load_balancer_type, | ||
| ) | ||
| extra_kwargs["positions"] = positions | ||
| if attention_masks is not None: |
| if isinstance(grad_output, DTensor): | ||
| grad_output = grad_output.to_local() |
| self._maybe_compile(compile_config) | ||
|
|
||
|
|
||
| class MTPLoss(BaseLoss): |
There was a problem hiding this comment.
let's put this in mtp.py to isolate the change for now
| if ( | ||
| self.num_mtp_layers > 0 | ||
| and parallelism.pipeline_parallel_degree > 1 | ||
| ): | ||
| raise NotImplementedError( | ||
| "DeepSeek-V3 MTP does not support pipeline parallelism yet." | ||
| ) |
There was a problem hiding this comment.
What's the difficulty? In dsv3, there's only 1 mtp layer, so we can always put it on layer PP rank, similar to lm_head.
That said, I'm OK with supporting it in another PR.
There was a problem hiding this comment.
Good point. For the current DeepSeek-V3 setting with a single MTP layer, a simple policy could place the MTP layer on the last PP stage together with lm_head, which should be much more manageable than a fully general PP design.
The main difficulty I had in mind is the more general case: multiple MTP layers, how to partition them across PP stages, how to pass the main decoder hidden state into the MTP path, and how to aggregate the list of logits/losses cleanly through the PP schedule.
I agree this can be supported in a follow-up PR.
| **kwargs, | ||
| ) -> None: | ||
| Decoder.Config.update_from_config(self, config=config, **kwargs) | ||
| MTPDecoder.Config.update_from_config(self, config=config, **kwargs) |
There was a problem hiding this comment.
The PP / CP check below should be put in MTPDecoder's update_from_config, as they are not dsv3-specific
| self.tokenizer = config.tokenizer.build(tokenizer_path=config.hf_assets_path) | ||
|
|
||
| # build dataloader | ||
| dataloader_seq_len = config.training.seq_len + self.extra_mtp_tokens |
There was a problem hiding this comment.
For SP (on TP axis) it should work out-of-box, because the labels are never sharded, assuming we don't use Chunked CE loss. Is this right?
For CP it indeed sounds tricky, especially considering we would like to push CP input sharding into dataloader. cc @fegin @jinsooihm
| with self.train_context(): | ||
| pred = model_parts[0](inputs, **extra_kwargs) | ||
| loss, _ = self.loss_fn(pred, labels, global_valid_tokens) | ||
| loss_inputs = {} |
There was a problem hiding this comment.
no need to introduce this variable
| pred, | ||
| labels, | ||
| global_valid_tokens, | ||
| **loss_inputs, |
There was a problem hiding this comment.
| **loss_inputs, | |
| positions=extra_kwargs["positions"], |
might need to adjust the if-else a bit
There was a problem hiding this comment.
i wondering why dont we put "MTP" just into torchtitan comments? this file seems does not rely on any of "deepseek_v3", and merge mtp loss into torchtitan's loss and merge "apply_fsdp_to_mtp_decoder" into "apply_fsdp_to_decoder" instead of creating more branches
There was a problem hiding this comment.
I think this is just staying on the conservative side in terms of new features -- Is there any tech reports showing MTP is used beyond DeepSeek (v3) (in pretraining)?
There was a problem hiding this comment.
mimo
GLM-4&5
nemotron-3-super
step-flash-3.5
qwen (no report but it does support MTP)
i think it will be suprise if any frontier model is not using MTP
There was a problem hiding this comment.
oh then it's my ignorance -- sorry about that
But it indeed makes it awkward to support chunked loss at least with our current ChunkedLossWrapper. I guess we can start with no chunked loss.
There was a problem hiding this comment.
i think we can actually take advantages of using ChunkedLossWrapper? just cat all logits to let MTP return single tesnor. and on MTP loss wrapper side to chunk or re-sumup loss.
| return [ | ||
| self.lm_head(item) if self.lm_head is not None else item | ||
| for item in outputs | ||
| ] |
There was a problem hiding this comment.
i wonder actually if we want to cat the logits together? return single tensor will make PP work easier (but we will need tell MTP loss how many mtp blocks we have)
also if new version pytorch compiler is smart, it should be able to optimize the lm-head + ce loss on stacked giant logits without OOM
There was a problem hiding this comment.
Yeah, that sounds reasonable to me. Returning one concatenated logits tensor would probably make the PP interface much simpler than passing around a list.
The only extra thing is that MTPLoss would need to know how many MTP blocks there are, so it can split main logits vs MTP logits and apply the right shifted labels. I think this is a good direction, but maybe better as a follow-up once the current MTP behavior is clearly documented and aligned.
|
it might be good to seprealy logging out the main loss and mtp loss per mtp block and sum up loss. do you actually have test run on it already? if we are doing it correctly, train with MTP should make model slightly converge faster.. |
tianyu-l
left a comment
There was a problem hiding this comment.
There's still too much slop in the code. This is a complicated feature, at least the integration into torchtitan seems complex.
If you couldn't make the code clear at one time, consider making a design doc for alignment first, listing what you are trying to solve, and what remain as TODO items.
| grad_output: torch.Tensor, | ||
| ) -> tuple[torch.Tensor, None, None, None, None]: | ||
| if isinstance(grad_output, DTensor): | ||
| grad_output = grad_output.to_local() |
There was a problem hiding this comment.
Sorry, this was from an earlier change for the default SPMD backend. This issue no longer exists under the current spmd_types backend, so I have removed it.
| apply_cp_to_forward( | ||
| # pyrefly: ignore [missing-attribute] | ||
| [block.attention.inner_attention for block in model.layers.values()], | ||
| _get_inner_attentions_for_context_parallel(model), |
There was a problem hiding this comment.
is this necessary? can we revert?
There was a problem hiding this comment.
This was from an earlier attempt to make CP work with MTP. Since CP is not supported by MTP yet, I removed this change and reverted the path back to the simpler form.
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class Config(Decoder.Config): | ||
| num_mtp_layers: int = 0 |
There was a problem hiding this comment.
this field can be removed, it can be derived from mtp_layers
There was a problem hiding this comment.
Thanks, I have removed it.
| self.layers.extend(self.mtp_layers) | ||
| try: | ||
| Decoder.Config.update_from_config(self, config=config, **kwargs) | ||
| finally: | ||
| del self.layers[num_main_layers:] |
There was a problem hiding this comment.
Yeah, agree this is hacky. I added it as a compromise to reuse the existing torchtitan decoder config path for MTP layers.
I’m thinking about a cleaner way to share that logic. Open to suggestions if you have a preferred structure.
| finally: | ||
| for key in mtp_layer_keys: | ||
| del model.layers[key] |
| """Left-roll an MTP sequence while preserving packed-document boundaries. | ||
|
|
||
| Without ``positions``, this is a regular left shift with the tail filled. | ||
| With reset-style positions, each document slice is shifted independently: | ||
| ``[A0, A1, A2, B0, B1]`` becomes ``[A1, A2, fill, B1, fill]``. | ||
| """ |
There was a problem hiding this comment.
It's hard to understand what this function is doing. Please add comments, including explanation of args and return values to the docstring
There was a problem hiding this comment.
Sorry about that. I’ve added a more detailed docstring now, including what the function does, the args, and the return values.
|
|
||
| mtp_outputs = [] | ||
| for depth, layer in enumerate(self.mtp_layers, 1): | ||
| offset_tokens, valid_offset_tokens = roll_mtp_sequence( |
There was a problem hiding this comment.
why they are called offset_tokens, valid_offset_tokens? The names are confusing enough that I could not understand what's going on.
There was a problem hiding this comment.
Yes, there is a small difference from the figure.
In the figure, the MTP examples are shown as clean continuous sequences, like main input t1...t4, MTP1 input t2...t5, and MTP2 input t3...t6.
In our implementation, the main model still consumes the original packed input row, for example:
[A0, A1, B1, B2, B3, C1, C2]
Then MTP inputs are derived by shifting inside each packed document boundary:
- MTP1 input:
[A1, fill, B2, B3, fill, C2, fill] - MTP2 input:
[fill, fill, B3, fill, fill, fill, fill]
So we follow the same idea of using t_{i+k} for MTP depth k, but we also mask out positions that would cross packed document boundaries. The main module is not extended with extra future tokens.
| return_valid_mask=True, | ||
| valid_mask_target=mtp_prev_embed, | ||
| ) | ||
| input_offset = self.tok_embeddings(offset_tokens) |
There was a problem hiding this comment.
these should've been computed in h?
There was a problem hiding this comment.
I considered reusing the first self.tok_embeddings(tokens) output, but I think it is unsafe under SP.
If we roll the embedding output directly, the roll happens after the embedding has already followed the configured activation placement. With sequence parallel enabled, that output is sequence-sharded, so a local roll would only shift within the local shard and would be wrong at shard boundaries.
Rolling token ids first keeps the shift in the logical token sequence, then calling tok_embeddings(mtp_input_tokens) lets the embedding module and its ShardingConfig produce the correct TP/SP placement. So this costs one extra embedding call per MTP depth, but avoids making MTP depend on manual cross-shard activation shifting.
| ) | ||
|
|
||
|
|
||
| def _maybe_redistribute_valid_mask_to_target( |
There was a problem hiding this comment.
do you really need to call redistribute explicitly in the code? Could you utilize the ShardingConfig?
There was a problem hiding this comment.
Thanks for the suggestion. I integrated this into the MTP transformer block as mtp_input_valid_mask, so it can now reuse ShardingConfig instead of calling redistribute explicitly in the forward code.
| valid_mask, | ||
| current_spmd_mesh(), | ||
| dense_activation_placement(tp=spmd.R, cp=spmd.R).per_axis_spmd_types(), | ||
| dense_activation_placement(tp=spmd.S(1), cp=spmd.R).per_axis_spmd_types(), |
There was a problem hiding this comment.
If SP is turned off, would you still do this??
There was a problem hiding this comment.
ow this is handled through ShardingConfig, and the behavior depends on enable_sp.
Thanks for the feedback. I agree this feature needs clearer alignment before adding more integration complexity. I have added a design note under And some unclear parts in the implementation based on the review comments were cleaned up. |
I agree that logging main_loss and per-block mtp_loss separately would make this easier to diagnose, and I can add that in the next update. And we ran experiments based on the deepseek_v3_16B model. Unfortunately, we did not observe a clear faster loss decrease with MTP enabled so far. |
|
|
||
|
|
||
| def deepseek_v3_debugmodel_mxfp8() -> Trainer.Config: | ||
| def deepseek_v3_debugmodel_mtp() -> Trainer.Config: |
There was a problem hiding this comment.
does numerics match the DTensor version you used to have?
| _set_deepseek_v3_layer_sharding( | ||
| layer_cfg, enable_sp=enable_sp, enable_ep=enable_ep | ||
| ) | ||
| if len(getattr(config, "mtp_layers", [])) > 0: |
There was a problem hiding this comment.
| if len(getattr(config, "mtp_layers", [])) > 0: | |
| if len(config.mtp_layers) > 0: |
| with self.train_context(): | ||
| pred = model_parts[0](inputs, **extra_kwargs) | ||
| loss, _ = self.loss_fn(pred, labels, global_valid_tokens) | ||
| if "positions" in extra_kwargs: |
There was a problem hiding this comment.
nit: let's do
loss_kwargs = {}
if "positions" in extra_kwargs:
loss_kwargs["positions"] = extra_kwargs["positions"]
loss, _ = self.loss_fn(pred, labels, global_valid_tokens, **loss_kwargs)
| if self._skip_lm_head: | ||
| return outputs |
|
|
||
| def __call__( | ||
| self, | ||
| pred: torch.Tensor | list[torch.Tensor], |
There was a problem hiding this comment.
can we only support list, not single tensor? Your MTPDecoder is outputing a list anyway.
| main_loss = self.fn( | ||
| pred[0], | ||
| labels[:, : pred[0].shape[1]], | ||
| global_vocab_size=self.global_vocab_size, | ||
| ) |
There was a problem hiding this comment.
Yes, there is a small difference from the figure.
In the figure, the MTP examples are shown as clean continuous sequences, like main input t1...t4, MTP1 input t2...t5, and MTP2 input t3...t6.
In our implementation, the main model still consumes the original packed input row
I can see the trade-off, as the paper way is wasting signals (but maintain the same amount of signal for main module and MTP modules?)
In the MTP.md, could you
- clarify this PR's behavior
- elaborate this difference from the original paper
- compare with what other mainstream OSS repo is doing
There was a problem hiding this comment.
I've updated the MTP.md and observed a similar roll_tensor operation in Megatron-LM's MTP implementation, which shifts the token input for each MTP depth instead of only shifting labels in the loss.
References:
| for depth, layer in enumerate(self.mtp_layers, 1): | ||
| # Shift token ids before embedding. Reusing the main embedding | ||
| # output would locally shift a sequence-parallel shard. | ||
| mtp_input_tokens, mtp_input_valid_mask = roll_mtp_sequence( |
There was a problem hiding this comment.
I'm not convinced that you need to roll the inputs and compute embedding for every depth.
Why couldn't we NOT roll the inputs at all, just get the outputs from each of main, MTP1, MTP2, etc. with exactly the same inputs, and then only worry about rolling when computing loss??
There was a problem hiding this comment.
I think we still need to roll the MTP input embeddings.
For example, with input tokens [t0, t1, t2, t3], the main model produces hidden states [h0, h1, h2], where each h_i is used to predict the next token.
For MTP1, the paper-style module should concatenate shifted token embeddings with the main hidden states:
- input embedding branch:
[Emb(t1), Emb(t2), Emb(t3)] - previous hidden branch:
[h0, h1, h2] - target:
[t2, t3, t4]
So each position uses h_i together with Emb(t_{i+1}).
If we do not roll the input tokens, MTP1 would instead concatenate:
- input embedding branch:
[Emb(t0), Emb(t1), Emb(t2)] - previous hidden branch:
[h0, h1, h2]
That misaligns the embedding branch by one step. Another way to view it is that the main hidden states are already shifted for next-token prediction, so the MTP embedding branch needs the same shift to stay aligned with the MTP depth.
| prev_depth_hidden, | ||
| mtp_input_valid_mask, | ||
| attention_masks, | ||
| positions, |
There was a problem hiding this comment.
sending this positions which has not been rolled seems wrong???
There was a problem hiding this comment.
I think keeping positions unrolled is intentional here.
The MTP hidden state is still anchored at position i; we only shift the token embedding branch to provide Emb(t_{i+k}). So for MTP1 we combine:
[h0, h1, h2] + [Emb(t1), Emb(t2), Emb(t3)]
and the output is still produced at positions [0, 1, 2], then supervised with shifted labels [t2, t3, t4].
If we also roll positions, the block would treat those outputs as if they were located at [1, 2, 3], which would change the RoPE/attention semantics and break the alignment with h_i.
| Example: | ||
| ``sequence=[A0, A1, A2, B0, B1]`` and | ||
| ``positions=[0, 1, 2, 0, 1]`` with ``shift=1`` returns | ||
| ``[A1, A2, fill, B1, fill]``. |
There was a problem hiding this comment.
If I originally have tokens [t0, t1, ..., t6] and labels [l0, ... l6], I understand that our main module is seeing tokens [t0, t1, ..., t5] and labels [l1, ..., l6] (dataloader behavior) as model inputs.
- how about MTP1, does it see tokens [t1, ..., t5, FILL] and labels [l1, ..., l6]?? Could you write in the .md how you are aligning inputs with labels for different MTP depths?
There was a problem hiding this comment.
I've updated MTP.md
170fbde to
74577c6
Compare
|
@tianyu-l Hi, are you still reviewing this code? |
| | Path | Model input tokens | Loss labels | | ||
| | --- | --- | --- | | ||
| | Main | `[t0, t1, t2, t3, t4, t5]` | `[t1, t2, t3, t4, t5, t6]` | | ||
| | MTP depth 1 | `[t1, t2, t3, t4, t5, FILL]` | `[t2, t3, t4, t5, t6, IGNORE]` | | ||
| | MTP depth 2 | `[t2, t3, t4, t5, FILL, FILL]` | `[t3, t4, t5, t6, IGNORE, IGNORE]` | |
There was a problem hiding this comment.
Please comment that this is different from the paper figures?
I also have a maybe noob question on how MTP helps inference:
During inference if I only have [t1, t2, t3, t4], I could use main module to predict [t5] but I couldn't predict anything beyond using [t1 -- t4], with all the MTP heads. Is the idea that I could feed [t1 -- t5] back to MTP1 to get a drafted [t6] and [t1 -- t6] to MTP2 to get a drafted [t7]?
There was a problem hiding this comment.
Thanks, I added a note clarifying how our fixed-length input alignment differs from the paper figure.
Your inference understanding is close, but we do not need to feed the full prefix back into each MTP module. The main model predicts t5; MTP1 then combines the main model's last hidden state with Emb(t5) to draft t6; MTP2 combines MTP1's hidden state with Emb(t6) to draft t7. These drafted tokens can then be verified by the main model through speculative decoding.
|
|
||
|
|
||
| def deepseek_v3_debugmodel_mxfp8() -> Trainer.Config: | ||
| def deepseek_v3_debugmodel_mtp() -> Trainer.Config: |
There was a problem hiding this comment.
the losses are almost identical.
It would be great if we could explain the difference.
c0c05cd to
7bc7a7b
Compare
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
…e checked Largest sync in a while (31 files) and the first in a while that needed real replay analysis: 45ea2f0 (pytorch#3996) rewrites models/common/moe_sharding.py (+325/-170) and moe.py, which ezpz/moe imports from. Checked rather than assumed, four ways: - MoE / RoutedExperts / TokenChoiceTopKRouter / GroupedExperts all still exist after the rewrite (AST check, not grep) - pytorch#3996 changed no class or __init__/forward signatures in common/moe.py - our one direct call, set_moe_sharding_config at ezpz/moe/sharding.py:167, matches the current signature exactly (moe_cfg, *, enable_ep, enable_sp, expert_param_layout) - ezpz/moe/*.py and the three rewritten shared modules all parse So: no replay. Also inert for ezpz -- MTP (pytorch#3392) and Muse Glimmer are additive new code we do not import, and nothing touched llama3/. Flagged explicitly: this is a STATIC check only. Sunspot is down (oneCCL allgatherv_ring cluster-wide, PBS returning empty results), so ezpz/moe could not be smoke-tested. Since pytorch#3996 rewrote sharding internals, run a MoE smoke before trusting an EP/SP run on this sync.
## Summary (human-written)
DeepSeek V3 applies double RMS normalization between MTP layers:
- The first MTP layer returns the RMS-normalized hidden state, which is
fed to the MTP head.
- The second MTP layer receives only the previously RMS-normalized
hidden state and applies another RMS normalization to it.
DeepSeek V4 handles this correctly. This PR mirrors the V4
implementation.
## Why
With `num_mtp_layers >= 2`, each DeepSeek-V3 MTP depth after the first
gets the
*normed* output of the previous depth (`mtp_norm`, i.e.
`shared_head.norm`),
and immediately normalizes it again with its own `hnorm`. Two RMSNorms
run back
to back on the hidden path. The reference (DeepSeek-V3 paper; vLLM
`deepseek_mtp.py`, which applies `shared_head` only when computing
logits)
chains the pre-norm hidden state. The main decoder here already does
this
(`prev_depth_hidden = h` is taken before the final norm), and so does
`DeepSeekV4MTPBlock`.
The chained tensor has also already been TP-gathered by
`maybe_gather_tp_input`.
Under SP, the next depth therefore receives a replicated `prev_embed`,
even
though `DeepSeekV3MTPBlock.forward` says it arrives `Shard(0)`.
**Example.** (depth 2 of a 2-layer MTP)
```text
main: h1 -> mtp_norm -> gather -> hnorm -> eh_proj -> ... (double norm)
\-> lm_head
after: h1 -> hnorm -> eh_proj -> ...
\-> mtp_norm -> gather -> lm_head
```
The bug has been there since MTP was added (#3392). Depth 1 is
unaffected, and
so are released checkpoints, which have a single MTP layer.
## What changed
- `DeepSeekV3MTPBlock.forward` returns `(h, gathered mtp_norm(h))`
instead of
only the normed output, matching `DeepSeekV4MTPBlock`.
- `DeepSeekV3Model.forward` chains the first value to the next depth and
sends
the second to `lm_head`.
## Numerics
- `num_mtp_layers=1` (all released DSV3 checkpoints): unchanged. The
depth-1
computation path is not touched.
- `num_mtp_layers>=2`: depth 2 and later change on purpose, because the
double
norm is removed. TODO: loss comparison.
## Testing
- GPU check, debugmodel with 2 MTP layers: depth 2's `hnorm` input is
bit-identical to depth 1's pre-`mtp_norm` hidden state.
- `tests/unit_tests/gpu/models/deepseek_v3/test_mtp_remat.py` (2 MTP
layers,
full and default remat): passes.
- CPU: `tests/unit_tests/cpu/models/deepseek_v3/`,
`tests/unit_tests/cpu/models/common/test_transformer_block.py`: pass.
## Known issues / follow-ups
-
`tests/unit_tests/cpu/components/test_loss.py::TestChunkedLossWrapper::test_lora_head_only_matches_cross_entropy`
fails 3 subtests both on this branch and on its parent commit, so the
failure
is unrelated.

Summary
Integrate shared Multi-Token Prediction (MTP) support for DeepSeek V3 into the current upstream codebase, using the common decoder module path, declarative config build mechanism, class-based loss framework, and current parallel/sharding APIs.
Model Structure
DeepSeekV3ModelinheritsMTPDecoder. If MTP is disabled,MTPDecoder.forward()falls back toDecoder.forward().MTPDecoderowns the normal decoder fields (tok_embeddings,layers,norm,lm_head) plusmtp_layers: ModuleList[MTPTransformerBlock] | None.When MTP is enabled, output is a list:
Config
MTP fields are directly part of
MTPDecoder.Config:mtp_layer_configmay be provided by a model flavor. If absent,MTPDecoder.materialize_mtp_config()derives it fromconfig.layers[-1]andcreates an
MTPTransformerBlock.ConfigduringConfig.update_from_config(),before model build and before model-specific sharding config is applied.
Example config:
MTP Block
MTPTransformerBlockinheritsTransformerBlock. Its config extends the normalblock config with MTP-only modules:
Each MTP layer follows:
Input Organization
The dataloader still provides normal decoder inputs:
tokens: [B, S],labels: [B, S], and optionalpositions: [B, S].MTP shifted tokens are generated inside the model with
roll_mtp_sequence().The operation preserves length and uses reset-style positions to avoid crossing
packed-document boundaries:
MTPLossuses the same helper to generate shifted labels, filling invaliddocument-tail targets with
IGNORE_INDEX.Forward And Loss
MTPDecoder.forward()runs the main decoder, keeps the pre-final-norm hiddenstate for MTP, applies final norm for the main output, then runs each MTP depth.
MTPLossconsumes the list output and computesmain_loss + loss_scaling_factor * average(mtp_losses).Parallelism Status
FSDP includes MTP layers in decoder transformer block traversal. TP/EP use
model-specific sharding rules. PP, CP, and Chunked CE are unsupported here.
Limitations
positions, it falls back to sequence-wide shift and is only correct for
unpacked samples.
Open Questions
MTPTransformerBlock.Configfromconfig.layers[-1]appropriate,or should model flavors explicitly provide
mtp_layer_config?cu_seqlens/PackedSeqParamsinstead of reset-style positions?