Skip to content

[DeepSeek V3] Add MTP1 eager pipeline parallelism - #5329

Open
sanketpurandare wants to merge 1 commit into
dsv3-shared-parameter-hooksfrom
dsv3-mtp1-pipeline
Open

sanketpurandare wants to merge 1 commit into
dsv3-shared-parameter-hooksfrom
dsv3-mtp1-pipeline

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 12, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

rename: pipeline.py

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Renamed the file to pipeline.py, keeping pipeline_dsv3() as the entry point.

)


def _finalize_mtp_embedding_gradients(model_parts: list[DeepSeekV3Model]) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread torchtitan/models/deepseek_v3/model.py Outdated

_finalize_mtp_embedding_gradients(cast(list[DeepSeekV3Model], model_parts))

def _get_grad_norm_parameters(self) -> Iterator[torch.nn.Parameter]:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +167 to +171
dist.broadcast(
_local_tensor(owner.tok_embeddings.weight),
src=owner._mtp_embedding_src_rank,
group=owner._mtp_embedding_group,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why need this

@sanketpurandare sanketpurandare Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@sanketpurandare
sanketpurandare removed this pull request from stack #5331 October 20, 2026 15:21
@sanketpurandare
sanketpurandare removed this pull request from stack #5567 October 23, 2026 21:49
@sanketpurandare
sanketpurandare marked this pull request as ready for review October 23, 2026 21:51
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 23, 2026
@tianyu-l

tianyu-l commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 31s —— View job


Changes suggested: the two embedding copies can silently diverge unless the recipe also sets MTPGradientClipper, and part of the scope should be trimmed. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_llm is reused rather than duplicated.
  • The FSDP layers key fix for non-contiguous stage layer IDs (apply_fsdp_to_mtp_decoder) is correct.
  • split_group uses group-local ranks, and broadcast uses a global src.
  • The combine-then-clip arithmetic counts the embedding once in the norm and clips both copies, which is correct.
  • Moving gradient finalization out of TrainingEngine addresses the earlier intrusiveness concern.

Must fix

  1. 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_dsv3 rejects the fake backend, but the PR carries ciflow/fake-pg. What fails under fake PG? If it's only split_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 shared MTPDecoder, 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.weight FQN, 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. Then MTPGradientClipper only has to handle the logical-norm dedup.
  • Or raise a ValueError from _register_optimizer_hooks (or from validation.py, see the comment there) when _mtp_pipeline_enabled is set and optim.gradient_clipper isn't an MTPGradientClipper.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  • ChunkedLossWrapper switches behavior on lm_head.training, which makes a module's train/eval flag control the loss path,
  • Validator uses cast(Any, ...) and toggles the private _skip_lm_head,
  • TrainingEngine gets 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

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.

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

ciflow/fake-pg Run 1-GPU Fake PG integration tests CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

2 participants