Repository navigation
[DeepSeek V3] Add MTP1 eager pipeline parallelism - #5329
sanketpurandare wants to merge 1 commit into
Conversation
f035f5c to
b36228c
Compare
b36228c to
0f92f97
Compare
There was a problem hiding this comment.
Renamed the file to pipeline.py, keeping pipeline_dsv3() as the entry point.
| ) | ||
|
|
||
|
|
||
| def _finalize_mtp_embedding_gradients(model_parts: list[DeepSeekV3Model]) -> None: |
There was a problem hiding this comment.
This looks quite intrusive, in the sense that the TrainingEngine needs to be changed to overfit MTP + PP.
Can we achieve this grad reduction in pipelining fn, e.g. by registering a grad hook?
There was a problem hiding this comment.
Moved gradient combination and logical norm selection into the model's native optimizer-owned clipper. It runs after all PP/FSDP backward work, inside the optimizer update and its CUDA graph, rather than relying on a tensor hook that could run before sharded gradients are finalized.
|
|
||
| _finalize_mtp_embedding_gradients(cast(list[DeepSeekV3Model], model_parts)) | ||
|
|
||
| def _get_grad_norm_parameters(self) -> Iterator[torch.nn.Parameter]: |
There was a problem hiding this comment.
can this be achieved with an alternative GradClipper, introduced in https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/optim/optim.py#L76-L78
There was a problem hiding this comment.
Used the native GradientClipper extension. It counts one logical embedding while clipping and updating both physical copies; the constructor stays config-only, with runtime owners bound once by the optimizer.
| dist.broadcast( | ||
| _local_tensor(owner.tok_embeddings.weight), | ||
| src=owner._mtp_embedding_src_rank, | ||
| group=owner._mtp_embedding_group, | ||
| ) |
There was a problem hiding this comment.
I didn't expect this -- are you not replicating optimizer states so that not both embeddings get the same optimizer updates?
Similar to previous comments, can we achieve this with a tensor hook.
There was a problem hiding this comment.
Both physical embeddings retain optimizer states and receive the same summed gradient and update. This copy is init/load synchronization, not a substitute for updating the replica; the PP2/PP4 model and optimizer tensor comparisons passed.
| *, | ||
| inputs: list[tuple[torch.Tensor, ...]] | None, | ||
| labels: list[torch.Tensor] | None, | ||
| labels: list[torch.Tensor | tuple[torch.Tensor, ...]] | None, |
There was a problem hiding this comment.
Correction: this annotation is still needed for microbatches carrying an LM-label tensor plus MTP-label tensors. I kept it as a typing change only; preprocessing and loss math are unchanged.
0f92f97 to
ed14215
Compare
ed14215 to
2b72143
Compare
|
@claude review |
There was a problem hiding this comment.
Verdict: changes suggested. The core MTP+PP design looks right, but one correctness gap should be fixed before landing, and part of the scope should be trimmed.
The PP mechanics hold up:
- Only hidden activations cross stage boundaries.
- Shifted IDs are passed as root kwargs.
pipeline_llmis reused rather than duplicated.- The FSDP
layerskey fix for non-contiguous stage layer IDs (apply_fsdp_to_mtp_decoder) is correct. split_groupuses group-local ranks, andbroadcastuses a globalsrc.- The combine-then-clip arithmetic counts the embedding once in the norm and clips both copies, which is correct.
- Moving gradient finalization out of
TrainingEngineaddresses the earlier intrusiveness concern.
Must fix
- The two embedding copies can silently diverge unless the recipe also sets
MTPGradientClipper. Gradient combination only happens inside that clipper, and any DSV3 MTP1 + PP config that keeps the default clipper trains the two copies apart with no error. (inline:pipeline.py)
Should fix
2. config/validation.py now imports and isinstance-checks DeepSeekV3Model. Move that check into MTPDecoder.pipeline() / DeepSeekV3Model.pipeline(). (inline)
3. Scope: ChunkedLossWrapper.validation_only, which touches loss, validator and engine, and MTPDecoder.coalesce_lm_head aren't enabled by any recipe and aren't needed for PP stage ownership. Split them out, or wire them into a tested recipe. (inline)
4. The PP integration recipe swaps ChunkedLossWrapper for a plain MTPLoss, so MTP+PP+ChunkedLossWrapper is never tested. Either support and test it, or reject it explicitly. (inline)
Minor / questions
pipeline_dsv3rejects thefakebackend, but the PR carriesciflow/fake-pg. What fails under fake PG? If it's onlysplit_group, the fake-PG dry-run path could still cover the partitioning.- Pipeline-only state (
_mtp_pipeline_enabled,_mtp_embedding_group, ...) now sits on the sharedMTPDecoder, which Kimi K2.7 also inherits. Consider keeping it in the DSV3 subclass. - The PR shows parity checks but no loss comparison against a non-PP MTP1 run with the same seed and deterministic settings. That curve would back up the gradient-combination claim directly.
| if fqn not in module_fqns[-1]: | ||
| module_fqns[-1].append(fqn) | ||
| parallelism.pipeline_parallel_module_fqns_per_model_part = module_fqns | ||
| model._mtp_pipeline_enabled = True |
There was a problem hiding this comment.
Silent divergence if the recipe doesn't set MTPGradientClipper. The embedding gradients only get summed inside MTPGradientClipper.clip_grad_norm_. Only deepseek_v3_debugmodel_mtp sets that clipper. Any other config that builds build_model_config(..., num_mtp_layers=1) and enables PP gets the default GradientClipper. In that case:
- the stage-0 copy is updated with only the main-path gradient,
- the last-stage copy is updated with only the MTP-path gradient,
- both copies are still saved under the same
tok_embeddings.weightFQN, so DCP dedup keeps one of them arbitrarily.
None of this raises an error or prints a warning. The optimizer is built after pipeline(), so this function can't easily check it. Possible ways to close the gap:
- Make the training-time combine independent of which clipper the user picks: register it from
_register_optimizer_hooks(DSV3 already overrides it) as an optimizer step pre-hook. ThenMTPGradientClipperonly has to handle the logical-norm dedup. - Or raise a
ValueErrorfrom_register_optimizer_hooks(or fromvalidation.py, see the comment there) when_mtp_pipeline_enabledis set andoptim.gradient_clipperisn't anMTPGradientClipper.
Either way, please add a unit test showing that the misconfigured case raises or is handled.
| raise NotImplementedError("MTP does not support pipeline parallelism yet.") | ||
| from torchtitan.models.deepseek_v3.model import DeepSeekV3Model | ||
|
|
||
| if not isinstance(model, DeepSeekV3Model.Config) or len(mtp_layers) != 1: |
There was a problem hiding this comment.
Core config validation now imports a specific model class (DeepSeekV3Model) and branches on it, which is the "don't add if model_x: to core" pattern. These checks are also already repeated in pipeline_dsv3 (num_mtp_layers != 1, cp_enabled).
Suggestion: make the default MTPDecoder.pipeline() raise NotImplementedError("MTP does not support pipeline parallelism yet."). That covers Kimi K2.7, which inherits MTPDecoder. DeepSeekV3Model.pipeline() overrides it, as it already does. The model-specific check then stays in model code, and this hunk can go back to the generic check or be dropped.
If you want the early config-time failure, add a capability hook on the model config instead of using isinstance.
| num_chunks = self.num_chunks | ||
| lm_head = self.lm_head | ||
| assert lm_head is not None, "Set lm_head before calling ChunkedLossWrapper" | ||
| if self.validation_only and lm_head.training: |
There was a problem hiding this comment.
validation_only is not used by any recipe or integration test in this PR. The MTP recipe uses ChunkedLossWrapper without it, and the PP2 recipe replaces the loss with a plain MTPLoss. It still adds a new mode to three core files:
ChunkedLossWrapperswitches behavior onlm_head.training, which makes a module's train/eval flag control the loss path,Validatorusescast(Any, ...)and toggles the private_skip_lm_head,TrainingEnginegets an extra branch.
This repeats the earlier concern about core intrusiveness, just in different files. Unless MTP+PP actually needs it, please move it to a separate PR with a recipe that uses it and a loss comparison. If it is needed for PP evaluation, wire it into the PP recipe so the integration test runs it.
| @dataclass(kw_only=True, slots=True) | ||
| class Config(Decoder.Config): | ||
| mtp_layers: list = field(default_factory=list) | ||
| coalesce_lm_head: bool = False |
There was a problem hiding this comment.
Same scoping question for coalesce_lm_head. It defaults to False, and no recipe turns it on, so the "Coalesce the two training projections through one LM head" in the PR description doesn't run anywhere outside unit tests. It's also separate from PP stage ownership. I'd split it out with its own memory/throughput numbers, or enable it in the MTP recipe and show loss parity with it on.
| expert_parallel_degree=2, | ||
| ) | ||
| config = deepseek_v3_debugmodel_mtp(seq_len=128, parallelism=parallelism) | ||
| config.loss = MTPLoss.Config( |
There was a problem hiding this comment.
Why does the PP recipe replace the ChunkedLossWrapper from deepseek_v3_debugmodel_mtp with a plain MTPLoss? The wrapper is the default MTP loss path, and with PP it gives lm_head_in_loss=True and _skip_lm_head=True on the last stage. That combination is never tested here. If MTP+PP+ChunkedLossWrapper doesn't work, pipeline_dsv3 should reject it with a clear error. If it does work, please keep the wrapper in this recipe, or add a second integration entry for it.
2b72143 to
b8fbd4b
Compare
Prepared with AI assistance. Keep model-specific stage ownership in pipeline.py/pipeline_dsv3() and reuse pipeline_llm for partitioning, parallelization and scheduling. Send only hidden activations; prepare shifted IDs and masks as rank-local root kwargs. Preserve the current four-part input/label/model-kwargs/loss-kwargs preprocessing API. Replicate the canonical token embedding on the last MTP stage. Synchronize its FSDP/TP shards after init/loading. Reuse native optimizer-owned GradientClipper for final owner-gradient combination and logical norm selection. Both copies retain optimizer states and identical updates; count one logical embedding, clip both. Configure MTPGradientClipper in the MTP recipe rather than placing MTP-specific pre-update behavior in the training engine. Coalesce the two training projections through one LM head. Sequential evaluation projects/releases each objective through the validation-only loss wrapper; preserve native alignment, objective denominators and detached loss metrics. GraphTrainer and MTP+PP+CP remain downstream work, not compatibility fallbacks. Verification: focused owning loss/pipeline suites passed 101 tests, excluding one documented pre-existing CPU FlexAttention/LoRA case. Includes repeated exact AdamW weights/moments/logical norm for same-rank embedding owners and existing stage ownership/lifetime tests. Full final PP2/PP4 checkpoint/capture, docs/lint and current-review publication audit remain pending.
b8fbd4b to
88b096b
Compare
Prepared with AI assistance.
Keep model-specific stage ownership in pipeline.py/pipeline_dsv3() and reuse
pipeline_llm for partitioning, parallelization and scheduling. Send only hidden
activations; prepare shifted IDs and masks as rank-local root kwargs. Preserve
the current four-part input/label/model-kwargs/loss-kwargs preprocessing API.
Replicate the canonical token embedding on the last MTP stage. Synchronize its
FSDP/TP shards after init/loading. Reuse native optimizer-owned GradientClipper
for final owner-gradient combination and logical norm selection. Both copies
retain optimizer states and identical updates; count one logical embedding,
clip both. Configure MTPGradientClipper in the MTP recipe rather than placing
MTP-specific pre-update behavior in the training engine.
Coalesce the two training projections through one LM head. Sequential evaluation
projects/releases each objective through the validation-only loss wrapper;
preserve native alignment, objective denominators and detached loss metrics.
GraphTrainer and MTP+PP+CP remain downstream work, not compatibility fallbacks.
Verification
Owning-commit CPU checks: 102 passed, 1 deselected in 38.25s.
Strict relevant Sphinx builds and all non-type repository hooks passed.
Three unchanged main type findings remain attributed, not reported as a clean
full type run. External reviewer and CI acceptance are separate, still pending.
Complete-stack integration (not this PR in isolation): real four-GPU PP2/DP2/
EP2 and PP4/DP1/EP1 ran ten updates with exact model/optimizer tensor parity,
optimizer graphs and sequential validation. A fresh native PP2/PP4 checkpoint
matrix matched resumed state exactly. These are debug-model contract checks,
not 671B throughput or convergence results.
The final 207-case GPU matrix covers in-place gradients, dense attention, PP/FSDP train/eval graphs, shared-stream backward/capture and fused numerical contracts.
The unchanged ARM CPU FlexAttention/LoRA case was reproduced on upstream main and excluded from these CPU results.
Pipeline evaluation depends on PyTorch#200643; GraphTrainer-specific integration remains downstream work.