Skip to content

[New Model]Add DeepSeek V4 model support - #3634

Merged
tianyu-l merged 23 commits into
pytorch:mainfrom
Matrix-Z97:deepseek_v4
Sep 2, 2026
Merged

tianyu-l merged 23 commits into
pytorch:mainfrom
Matrix-Z97:deepseek_v4

Conversation

@Matrix-Z97

Copy link
Copy Markdown
Contributor

Description

This PR adds deepseek_v4 model support and registers it in TorchTitan’s supported model list.

Main Changes

  • Add the new torchtitan/models/deepseek_v4/ model directory
  • Implement the DeepSeek V4 model architecture, sparse attention, compressor, MoE, mHC, sharding, parallelization, and state dict adapter
  • Add a deepseek_v4 debug model configuration
  • Register deepseek_v4 in torchtitan/models/init.py

Parallelism Support

  • FSDP is currently supported
  • EP (Expert Parallel) is currently supported
  • TP (Tensor Parallel) is currently supported
  • CP (Context Parallel) is not supported yet and explicitly raises NotImplementedError

Additional Notes

  • The attention implementation is currently based on small operators rather than a fused/custom kernel.
  • Only the debug model configuration is included for now.

If needed, I can further improve and complete this implementation.

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

pytorch-bot Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@Matrix-Z97

Copy link
Copy Markdown
Contributor Author

@tianyu-l I noticed that you added deepseek_v4 to the roadmap. However, I'm sorry that I just force-pushed a new version of the code, which caused the roadmap content to disappear. Could you please add it back?

@tianyu-l tianyu-l moved this from Done to In Progress in TorchTitan Development Jun 12, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@Matrix-Z97 you mean the "26H1 TorchTitan Development"?

Oh that's not a roadmap but just for tracking what this repo is doing. I re-marked the status from "Done" to "In Progress".

@Matrix-Z97

Copy link
Copy Markdown
Contributor Author

@tianyu-l Understood, thanks for the correction! Out of curiosity, are you interested in the deepseek_v4 model?

@tianyu-l

Copy link
Copy Markdown
Contributor

Yes, of course. We have plans, but were lacking bandwidth.

This PR comes in very timely, and the quality looks very high. We just need some time to review. Many thanks!

Btw @shuhuayu is working on adding latest Kimi model.

@Matrix-Z97

Copy link
Copy Markdown
Contributor Author

Thanks a lot for the feedback! Happy to help with the bandwidth. Let me know if there's anything I can do to help move this PR forward or if you need any adjustments. And awesome news about the latest Kimi model @shuhuayu.

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.

cc @drisspg to review the attention part

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.

@tianyu-l How do you feel about the current FlexAttention-based DSV4 attention implementation?

It relies on the passed-in topk_idxs to construct the attention mask. However, because the resulting mask is quite sparse, the attention computation performance is not ideal. Do you have any suggestions here? For example, would it be better to use a custom sparse attention kernel based on TileLang, Triton, Helion, or another approach?

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 think the major concern is that flex is optimized for block masks, while topk_idxs is a token-wise selection, so scattered picks leave few empty blocks for flex to skip. Since the selection is untrained for now, I'd suggest we first land the aux loss to train it, then revisit this optimization.

@tianyu-l tianyu-l mentioned this pull request Jun 26, 2026
1 task done
@floatingtrees

Copy link
Copy Markdown
Contributor

@Matrix-Z97 Are you planning to add MTP support for this model? If not, I’d be happy to add it.

@Matrix-Z97

Copy link
Copy Markdown
Contributor Author

@floatingtrees Thanks, MTP has definitely been on our roadmap, and we’ve also been iterating on it continuously in our internal versions. Our current thinking is more along the lines of providing DeepSeek-V3 support in the spirit of #3392. Do you have any better ideas or suggestions?

@tianyu-l tianyu-l 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.

having some high level feedback before looking into details

({parallel_dims.tp}) and 2 * CP degree ({parallel_dims.cp}).
"""

if parallelism.spmd_backend in ("full_dtensor", "spmd_types"):

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.

We are in the migration to "spmd_types". Could you remove "default" and "full_dtensor" support from this new model?

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.

Understood. So this new model only needs to support the spmd backend for now? Does this mean all torchtitan models will transition to supporting only the spmd backend in the future?

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.

yes

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.

not addressed

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.

There are still some issues when enabling --debug.spmd_typechecking. I am currently debugging this.

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.

@tianyu-l To support spmd_types, we made the following changes:

  • Marked local topk_idxs / compress_topk_idxs as [B, S]-aligned metadata so they can be concatenated safely.
  • Disabled SPMD type checking around FlexAttention mask construction, where symbolic indexing is used.
  • Reworked compressor overlap logic to avoid {R} tensor in-place writes from {V} slices.
  • Replaced external Hadamard transform dependency with cached Hadamard matrix + F.linear.
  • Added sharding metadata for the hash-routing tid2eid buffer.

For details, please refer to:
85b3292

Comment on lines +584 to +586
deepseek_v4_configs = {
"debugmodel": _debugmodel,
}

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 only debug model, can we include the full set?

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.

I've included deepseek_v4_flash and deepseek_v4_pro now to expand the set. Just a heads-up: due to hardware constraints, I haven't actually tested them yet.

Comment thread torchtitan/protocols/model_spec.py Outdated
pipelining_fn: Callable | None
post_optimizer_build_fn: Callable | None
state_dict_adapter: type[BaseStateDictAdapter] | None
metrics_fn: Callable | None = 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.

@felipemello1 do you have a plan on in-model metric logging that we could share?

Let's add a TODO in dsv4 model code, and remove the model logging in this PR.

Comment thread torchtitan/distributed/aux_loss.py Outdated


@spmd.register_autograd_function
class AuxLossInjection(torch.autograd.Function):

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 see similar contribution in #3864

Can we make sure the design in #3000 suits the need for both?

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.

Yes, this implementation was referenced from #3864. I'll need to look closer into #3000 to see if the design can cover both use cases. Will update this thread once I have more clarity.

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.

From a quick look, #3000 seems more like a MoE-specific interface, while here we would like to call the aux-loss capability through a common/shared interface that can also cover non-MoE losses such as the DSA indexer loss.

So for the current DeepSeek V4 use case, the #3864-style implementation seems more suitable to me.

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'll take a look at both

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.

Thanks for the suggestion. Running the KL check with deepseek_v4_flash or deepseek_v4_pro as the baseline is not feasible for me due to hardware limits.

Would it be acceptable to run the same HF-vs-TorchTitan KL / max-diff comparison on a custom small DeepSeek V4 config instead?

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.

Got it. @shuhuayu since you've done it for Kimi, could you help verify this PR gets to similar level of numerical parity?

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.

Would it be acceptable to run the same HF-vs-TorchTitan KL / max-diff comparison on a custom small DeepSeek V4 config instead?

We also did a customized 16b kimi configs to compare numerics so it sounds good to me to do the same for dsv4. @tianyu-l, do you think we need to test it in the original 862b configs, doable but needs some additional setups.

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.

Thanks. Could you share what config was used for the customized 16B Kimi numerical test? In particular, which dimensions were reduced, e.g. number of layers, hidden size, heads/head dim, MoE experts, or sequence length?
I can follow the same strategy for DSV4 and build a smaller custom config for the KL/numerical comparison.

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 see. Small scale verification sounds fine.

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.

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.

@tianyu-l I added a verification note based on the debug model comparison against the HuggingFace-style inference script.

The debug model now includes attention blocks with compress_ratios=(0, 0, 4, 128) and also covers the hash-routing MoE path, so it exercises the main algorithmic structures used by the current DeepSeek V4 implementation.

With the same weights and input tokens, the last-logits comparison between HF inference and TorchTitan gives cosine similarity:

    cosine = 0.99999237

It is not bitwise identical mainly because:

  1. The HF inference script uses a TileLang sparse attention kernel, while TorchTitan uses the current FlexAttention-based path, so minor rounding differences are expected.
  2. The HF MoE path uses per-expert looped small matmuls, while TorchTitan uses grouped MM, which can also introduce small accumulation-order differences.

In addition, I also ran numerical validation across different parallelism strategies. With the same input, the loss comparison between FSDP and FSDP+EP+TP is:

    [LOSS_COMPARE] Step-by-step loss comparison:
    [LOSS_COMPARE] Step    Baseline Loss    Test Loss   Difference
    [LOSS_COMPARE] ----    -------------    ---------   ----------
    [LOSS_COMPARE] 1       8.082977294921875    8.082967758178711   -0.000010
    [LOSS_COMPARE] 2       6.74751091003418     6.7473907470703125  -0.000120
    [LOSS_COMPARE] 3       5.032241344451904    5.032076358795166   -0.000165
    [LOSS_COMPARE] 4       4.599724769592285    4.599623680114746   -0.000101
    [LOSS_COMPARE] 5       4.25457763671875     4.254598140716553    0.000021
    [LOSS_COMPARE] 6       4.076618194580078    4.076696395874023    0.000078
    [LOSS_COMPARE] 7       3.9123473167419434   3.9121904373168945  -0.000157
    [LOSS_COMPARE] 8       3.7830865383148193   3.7829692363739014  -0.000117
    [LOSS_COMPARE] 9       4.035467147827148    4.035507678985596    0.000041
    [LOSS_COMPARE] 10      3.6527910232543945   3.6526951789855957  -0.000096

    [LOSS_COMPARE] Summary statistics:
    [LOSS_COMPARE] Average baseline loss:  4.817734217643737
    [LOSS_COMPARE] Average test loss:      4.81767156124115
    [LOSS_COMPARE] Average difference:    -0.000063

Given the debug model coverage, the high HF-vs-TorchTitan logits agreement, and the close distributed loss comparison, I think this provides a reasonable numerical verification for this PR.

@tianyu-l

Copy link
Copy Markdown
Contributor

could you take another look at test failures

layer_cfg, enable_sp=enable_sp, enable_ep=enable_ep
)

if config.mtp_layers is not 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.

for mtp configs, tp + sp is not supported yet per my local test, is this intended or this is missed?

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.

thanks,will test

@shuhuayu shuhuayu 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.

lgtm overall, thanks! please fix tests.

Align the DeepSeek V4 code with upstream api changes that pyrefly
checks project-wide: add pyrefly ignores for intentional overrides,
adapt helion_rope overrides to the new parent forward signatures,
and register deepseek_v4_debugmodel in the frozen CLI test.

Co-Authored-By: Claude <[email protected]>
@tianyu-l
tianyu-l merged commit 0ff2464 into pytorch:main Sep 2, 2026
19 checks passed
@github-project-automation github-project-automation Bot moved this from Under Review to Done in TorchTitan Development Sep 2, 2026
tianyu-l pushed a commit that referenced this pull request Sep 10, 2026
## Why

DeepSeek V4 (`#3634`) already has debug recipes and CPU unit tests, but
it does not appear in `tests/integration_tests/models.py`. The models
suite never exercises V4 sparse attention / mHC / hash routing end to
end.

## What

- Add a 4-GPU Fake-PG V4 case: FSDP2 + TP2 + EP2, no CP (V4
`update_from_config` rejects CP). Matches the smoke command in the V4
README. Skip ROCm; no golden.
- Register the name in `test_models_select_fake_and_real_pg_cases` and
document it in `tests/README.md`.

An earlier revision also added a Qwen3.8 twin of the existing Qwen3.5
FSDP4+TP2+EP4 case. That is dropped: Qwen3.8 shares the Qwen3.5
architecture, so the extra job did not add coverage.

## Test plan

- [x] AST-parse the edited Python files
- [x] CPU: `pytest
tests/unit_tests/cpu/test_integration_test_definitions.py -k
fake_and_real`
- [ ] GPU CI models suite Fake-PG: `deepseek_v4_fsdp+tp+ep`
sdmyzlp added a commit to sdmyzlp/torchtitan that referenced this pull request Sep 13, 2026
DeepSeek V4.1's attention output projection is block-diagonal over query-head
groups: wo_a projects each query-head group on its own. Expressed as one dense
Linear plus a view/einsum at the call site, the group structure is invisible to
sharding and to kernels.

Add BatchedLinear: input [T, B, I], weight [B, O, I], output [T, B, O], with
the matmul batched over B, so per-group sharding and grouped GEMMs have
something to attach to. Only wo_a is grouped: wo_b mixes the per-group results
back into the model dimension and stays a plain Linear over the concatenated
groups.

deepseek_v4_1 also holds the attention sink as a plain fp32 nn.Parameter
instead of a Linear wrapping a one-column matrix, so the near-future
state-dict adapter has to handle that parameter without its trailing dim.

TODO: how the per-group weight is placed under spmd_types is still open -- a
group-wise projection may need cross-group communication once the group axis
and the tensor-parallel axis disagree (see pytorch#3634). Its only user rejects tensor
parallelism, so the sharding story can be settled before that changes.
sdmyzlp added a commit to sdmyzlp/torchtitan that referenced this pull request Sep 14, 2026
DeepSeek V4.1's attention output projection is block-diagonal over query-head
groups: wo_a projects each query-head group on its own. Expressed as one dense
Linear plus a view/einsum at the call site, the group structure is invisible to
sharding and to kernels.

Add BatchedLinear: input [T, B, I], weight [B, O, I], output [T, B, O], with
the matmul batched over B, so per-group sharding and grouped GEMMs have
something to attach to. The per-group results are mixed back into the model
dimension by a plain Linear over the concatenated groups.

TODO: how the per-group weight is placed under spmd_types is still open -- a
group-wise projection may need cross-group communication once the group axis
and the tensor-parallel axis disagree (see pytorch#3634). Its only user rejects tensor
parallelism, so the sharding story can be settled before that changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

6 participants