Repository navigation
[New Model]Add DeepSeek V4 model support - #3634
Conversation
|
|
|
@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? |
|
@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". |
|
@tianyu-l Understood, thanks for the correction! Out of curiosity, are you interested in the deepseek_v4 model? |
|
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. |
|
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. |
There was a problem hiding this comment.
@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?
There was a problem hiding this comment.
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.
|
@Matrix-Z97 Are you planning to add MTP support for this model? If not, I’d be happy to add it. |
|
@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
left a comment
There was a problem hiding this comment.
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"): |
There was a problem hiding this comment.
We are in the migration to "spmd_types". Could you remove "default" and "full_dtensor" support from this new model?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
There are still some issues when enabling --debug.spmd_typechecking. I am currently debugging this.
There was a problem hiding this comment.
@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
| deepseek_v4_configs = { | ||
| "debugmodel": _debugmodel, | ||
| } |
There was a problem hiding this comment.
why only debug model, can we include the full set?
There was a problem hiding this comment.
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.
| pipelining_fn: Callable | None | ||
| post_optimizer_build_fn: Callable | None | ||
| state_dict_adapter: type[BaseStateDictAdapter] | None | ||
| metrics_fn: Callable | None = None |
There was a problem hiding this comment.
@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.
|
|
||
|
|
||
| @spmd.register_autograd_function | ||
| class AuxLossInjection(torch.autograd.Function): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
could you please add verification (e.g. at least in PR summary) following https://github.com/pytorch/torchtitan/tree/main/scripts/checkpoint_conversion#comprehensive-check-kl-divergence
cc @shuhuayu
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Got it. @shuhuayu since you've done it for Kimi, could you help verify this PR gets to similar level of numerical parity?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I see. Small scale verification sounds fine.
There was a problem hiding this comment.
Thanks. Could you share what config was used for the customized 16B Kimi numerical test?
I used the kimi-vl variant, see https://github.com/pytorch/torchtitan/pull/3532/changes#diff-5a13a40a31333dd8b095a114b15d9580c2744ac09211c6b551a02c2989032c9b
There was a problem hiding this comment.
I used the kimi-vl variant, see https://github.com/pytorch/torchtitan/pull/3532/changes#diff-5a13a40a31333dd8b095a114b15d9580c2744ac09211c6b551a02c2989032c9b
Got it, will try it out soon. Thanks!
There was a problem hiding this comment.
@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:
- The HF inference script uses a TileLang sparse attention kernel, while TorchTitan uses the current FlexAttention-based path, so minor rounding differences are expected.
- 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.
30b3d5e to
ba882e8
Compare
|
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: |
There was a problem hiding this comment.
for mtp configs, tp + sp is not supported yet per my local test, is this intended or this is missed?
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]>
## 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`
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.
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.
Description
This PR adds deepseek_v4 model support and registers it in TorchTitan’s supported model list.
Main Changes
Parallelism Support
Additional Notes
If needed, I can further improve and complete this implementation.