-
Notifications
You must be signed in to change notification settings - Fork 898
[New Model]Add DeepSeek V4 model support #3634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Matrix-Z97
wants to merge
8
commits into
pytorch:main
Choose a base branch
from
Matrix-Z97:deepseek_v4
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,987
−8
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
90c57d1
Add deepseek_v4 model support
Matrix-Z97 c2d8a7a
Update torchtitan/models/deepseek_v4/compressor.py
Matrix-Z97 9a47905
Merge branch 'pytorch:main' into deepseek_v4
Matrix-Z97 2991579
Refactor DeepSeek V4 sparse attention routing
Matrix-Z97 78de492
[aux loss] framework: gradient injection and cross-rank reduction
sdmyzlp 7811710
Add DeepSeek V4 indexer aux loss
Matrix-Z97 811953e
Update DeepSeek V4 configs and sharding
Matrix-Z97 7d49617
Refactor DeepSeek V4 attention, RoPE, and aux loss
Matrix-Z97 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| # Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| # All rights reserved. | ||
| # | ||
| # This source code is licensed under the BSD-style license found in the | ||
| # LICENSE file in the root directory of this source tree. | ||
|
|
||
| """Model-internal auxiliary losses: gradient injection and logging. | ||
|
|
||
| Auxiliary objectives computed inside the model (MoE load-balance, DSA KL, ...) | ||
| cannot reach the trainer's loss function under pipeline parallelism. The | ||
| gradient injection decouples the gradient from the scalar output, and the | ||
| logging framework accumulates per-step values with PP-safe collection. | ||
| """ | ||
|
|
||
| from collections import defaultdict | ||
| from dataclasses import dataclass | ||
| from typing import ClassVar | ||
|
|
||
| import spmd_types as spmd | ||
| import torch | ||
| from torch.distributed._functional_collectives import all_reduce as _all_reduce | ||
|
|
||
| from torchtitan.protocols.module import Module | ||
| from torchtitan.tools.utils import device_type | ||
|
|
||
| __all__ = [ | ||
| "LoggedAuxLoss", | ||
| "collect_aux_loss_metrics", | ||
| ] | ||
|
|
||
|
|
||
| @spmd.register_autograd_function | ||
| class _AuxLossInjection(torch.autograd.Function): | ||
| """Identity-forward autograd that injects an aux-loss gradient on backward.""" | ||
|
|
||
| @staticmethod | ||
| # pyrefly: ignore [bad-override] | ||
| def forward(ctx, carrier: torch.Tensor, aux_loss: torch.Tensor) -> torch.Tensor: | ||
| ctx.save_for_backward(aux_loss) | ||
| return carrier | ||
|
|
||
| @staticmethod | ||
| def typecheck_forward( | ||
| carrier: torch.Tensor, aux_loss: torch.Tensor | ||
| ) -> torch.Tensor: | ||
| return _AuxLossInjection.apply(carrier, aux_loss) | ||
|
|
||
| @staticmethod | ||
| def backward( # pyrefly: ignore [bad-override] | ||
| ctx, grad_carrier: torch.Tensor | ||
| ) -> tuple[torch.Tensor, torch.Tensor]: | ||
| (aux_loss,) = ctx.saved_tensors | ||
| return grad_carrier, torch.ones_like(aux_loss) | ||
|
|
||
|
|
||
| class LoggedAuxLoss(Module): | ||
| """Accumulates per-microbatch aux losses via ``inject()`` with deferred readout. | ||
|
|
||
| Subclasses call ``inject()`` each microbatch to inject the gradient and | ||
| accumulate the scalar value. ``pop()`` reads and resets the accumulator. | ||
| """ | ||
|
|
||
| # Populated during model build (before PP splitting) so counts and keys are | ||
| # identical on every rank. PP stages without aux loss modules still join | ||
| # collectives via pre-allocated zero accumulators in collect_aux_loss_metrics. | ||
| _group_counts: ClassVar[dict[tuple[str, str], int]] = defaultdict(int) | ||
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class Config(Module.Config): | ||
| coeff: float | ||
| """Aux loss coefficient. Scales the gradient contribution.""" | ||
| tag: str = "aux_loss" | ||
| """Metric name prefix for ``collect_aux_loss_metrics``.""" | ||
| reduce_mesh: str = "loss" | ||
| """Mesh to average logged values over. PP is reduced separately.""" | ||
| global_batch_size: int | None = None | ||
| """Per-token denominator, set by ``Decoder.update_from_config``.""" | ||
| ac_doubled: bool = False | ||
| """AC double-count flag, set by ``Decoder.update_from_config``.""" | ||
|
|
||
| def __init__(self, config: Config): | ||
| super().__init__() | ||
| self.coeff = config.coeff | ||
| self.tag = config.tag | ||
| self.reduce_mesh = config.reduce_mesh | ||
| self.global_batch_size = config.global_batch_size | ||
| self.ac_doubled = config.ac_doubled | ||
| self.register_buffer( | ||
| "_acc", torch.zeros((), dtype=torch.float32), persistent=False | ||
| ) | ||
| LoggedAuxLoss._group_counts[(config.reduce_mesh, config.tag)] += 1 | ||
|
|
||
| def _init_self_buffers(self, *, buffer_device: torch.device | None = None) -> None: | ||
| if buffer_device is None: | ||
| buffer_device = self._acc.device | ||
| with torch.device(buffer_device): | ||
| self._acc = torch.zeros((), dtype=torch.float32) | ||
|
|
||
| def inject(self, carrier: torch.Tensor, raw_sum: torch.Tensor) -> torch.Tensor: | ||
| """Inject aux loss gradient into the forward graph and accumulate for logging.""" | ||
| if self.training: | ||
| self._acc.add_(raw_sum.detach().float() / self.global_batch_size) | ||
| return _AuxLossInjection.apply( | ||
| carrier, raw_sum * (self.coeff / self.global_batch_size) | ||
| ) | ||
|
|
||
| def pop(self) -> torch.Tensor: | ||
| """Pop and reset the accumulated value, correcting for AC double-write.""" | ||
| val = self._acc.detach().clone() | ||
| if self.ac_doubled: | ||
| val = val / 2 | ||
| self._acc.zero_() | ||
| return val | ||
|
|
||
|
|
||
| def collect_aux_loss_metrics(model_parts, parallel_dims) -> dict[str, float]: | ||
| """Collect and reduce aux loss metrics from all model parts for logging. | ||
|
|
||
| Returns ``{tag}/mean`` per group; ``{}`` when no aux losses are configured. | ||
| """ | ||
| if not LoggedAuxLoss._group_counts: | ||
| return {} | ||
|
|
||
| pp_mesh = parallel_dims.get_optional_mesh("pp") | ||
| local_sums = { | ||
| key: torch.zeros((), dtype=torch.float32, device=device_type) | ||
| for key in LoggedAuxLoss._group_counts | ||
| } | ||
|
|
||
| for part in model_parts: | ||
| for block in getattr(part, "layers", {}).values(): | ||
| for module in block.modules(): | ||
| if isinstance(module, LoggedAuxLoss): | ||
| local_sums[(module.reduce_mesh, module.tag)] += module.pop() | ||
|
|
||
| metrics = {} | ||
| for key, total in sorted(local_sums.items()): | ||
| mesh_name, tag = key | ||
| for mesh in (parallel_dims.get_optional_mesh(mesh_name), pp_mesh): | ||
| if mesh is not None: | ||
| total = _all_reduce(total, reduceOp="sum", group=mesh) | ||
| metrics[f"{tag}/mean"] = float(total.item()) / LoggedAuxLoss._group_counts[key] | ||
| return metrics |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@tianyu-l Hi, it looks like the existing community RoPE interface only supports (query, key) pair inputs, while some DeepSeek V4 RoPE call sites operate on a single tensor, such as in the compressor and indexer. Without a single-tensor API, these paths would need awkward patterns like rope(x, x)[0].
To avoid that, we added SingleComplexRoPE for explicit single-tensor complex RoPE usage. It also supports inverse=True, which is needed to match the HF inference logic in the DeepSeek V4 attention post phase.
Does this form of change look acceptable to the community?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@shuhuayu I vaguely remember there's a model using single-field rope, but I couldn't find it any more. My worry is that after recent refactor the single-field rope is gone. Was it originally added by you or do you have clue?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I searched and did not find a single field one neither. rather than a new
SingleComplexRoPEclass, how about just makekeyoptional in the existingRoPE.forward / apply_rotary_emb (return a single tensor when key is None)and add aninverse=Falseflag ? That covers both the single-tensor call sites and the inverse-rope post-phase without a parallel class, sharing one implementation, and a no-op for existing models.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@shuhuayu
my only concern is that it also need to work with the helion kernels (https://github.com/pytorch/torchtitan/blob/main/torchtitan/overrides/helion_rope.py), but maybe AI can just do it
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is not urgent for dsv4 since it uses
ComplexRoPEand helion kernels is only forCosSineRoPEnow. but it leaves the work to people who wants to add helionComplexRoPEkernels.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@shuhuayu
See #3767
I think at least we shouldn't break existing key, query pair version of Helion override.