Skip to content

Fix DeepSeek V4 checkpoint conversion with optional MTP - #4498

Merged
tianyu-l merged 2 commits into
pytorch:mainfrom
ZenAlexa:contrib/4496-deepseek-v4-checkpoint-conversion-fails-with-and-witho
Sep 6, 2026
Merged

tianyu-l merged 2 commits into
pytorch:mainfrom
ZenAlexa:contrib/4496-deepseek-v4-checkpoint-conversion-fails-with-and-witho

Conversation

@ZenAlexa

@ZenAlexa ZenAlexa commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4496.

DeepSeek V4 currently raises len(None) when restoring the default model and a missing-key error when exporting an MTP attention sink. The shared V3 conversion also uses a different MTP layer layout from the official V4 checkpoint, which stores these weights under mtp.<index>.

This patch reuses the existing layer-mapping helpers, handles optional MTP layers, and translates the V4 MTP prefix at the adapter boundary. Reusing the helper for routed experts also preserves their original TorchTitan key when recording DTensor metadata, so MTP expert weights retain their placements during restoration.

Validation on Ubuntu 24.04 ARM64 with PyTorch 2.14.0+cpu:

  • python3 -m unittest tests.unit_tests.cpu.test_state_dict_adapter tests.unit_tests.cpu.test_deepseek_v4_flops -v: six tests completed successfully. Coverage includes V3 and GPT-OSS regression tests, initialized V4 models with 0/1/2 MTP layers, and MTP expert placements.
  • Actual Hugging Face checkpoint files were saved and loaded with HuggingFaceStorageWriter / HuggingFaceStorageReader. All 118/150/182 state entries retained their values, shapes, and dtypes for the three V4 configurations.
  • Two-process CPU/Gloo checks cover V4 and V3 with 0/1/2 MTP layers. Fresh adapters convert reordered HF dictionaries with exact per-entry checks. Separate safetensors files load into newly built, zeroed models through the actual CheckpointManager.dcp_load method and ModelWrapper. Native DCP save/clear/load restores every entry exactly, including shapes and dtypes; expert tensors also retain their strides and Shard(0) placements. The checkpoint manager constructor and GPU training are outside this check.
  • The full FLASH configuration's exported keys cover every non-scale key in the official checkpoint index. Four selected, unquantized MTP tensors were read from that pinned official checkpoint: the attention sink, mHC head projection (hc_head_fn), embedding norm, and output norm. Their converted shapes match the FLASH model, and the reverse conversion preserves their exact bytes and dtypes.

pre-commit run --all-files reported an existing import-formatting change in torchtitan/experiments/rl/tests/test_dapo_math.py and a missing local pyrefly executable. The changed files satisfy the formatting and lint hooks; a separate Pyrefly 0.45.1 check of all three changed files reports zero errors.

Validation covers checkpoint conversion and restoration. Full quantized-weight loading and multi-GPU training remain outside the executed scope.

@ZenAlexa
ZenAlexa requested a review from tianyu-l as a code owner September 6, 2026 06:17
Copilot AI lite review requested due to automatic review settings September 6, 2026 06:17
@meta-cla

meta-cla Bot commented Sep 6, 2026

Copy link
Copy Markdown

Hi @ZenAlexa!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@meta-cla

meta-cla Bot commented Sep 6, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 6, 2026
@tianyu-l

tianyu-l commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

@claude review this PR, describe what's the problem and what's the fix, evaluate if the fix is the most proper way. In particular, why do we need to make changes in both deepseek v3 and v4 state dict adapters.

@claude

claude Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 6m 55s —— View job


PR Review: Fix DeepSeek V4 checkpoint conversion with optional MTP

  • Read the PR diff and both adapters (pre- and post-change)
  • Trace the two failure modes and the MTP-prefix mismatch
  • Evaluate the fix and answer why both V3 and V4 change

What's the problem

Issue #4496 is really three distinct bugs, two of which live in the shared V3 adapter that V4 inherits from:

  1. len(None) on the default (no-MTP) model. _map_from_hf_layer_key in the V3 adapter guarded MTP handling with len(getattr(self.model_config, "mtp_layers", [])). V4's config declares mtp_layers: list["MTPBlock.Config"] | None = None (deepseek_v4/model.py:113), so with n_mtp_layers=0 the attribute is None and len(None) raises TypeError. The getattr default of [] never kicks in because the attribute exists and is None.

  2. Missing-key error exporting the MTP attention sink. V4's old _map_layer did mapping[self._abstract_key(key, count=1)]. For an MTP sink the titan key is mtp_layers.0.attention.attn_sink.weight, whose abstract form mtp_layers.{}.attention.attn_sink.weight is not a key in to_hf_map (the map only holds layers.{}...), so it KeyErrors. _map_layer had no MTP-prefix awareness.

  3. Wrong on-disk MTP layout. The shared V3 conversion numbers MTP layers after the main layers (layers.{N+i}), but the official V4 checkpoint stores them under mtp.<index>. So even when conversion didn't crash, the exported keys didn't match the real checkpoint.

There is also a latent placement-restoration bug in V3 that this PR fixes (see below).

What's the fix

  • V3 _map_from_hf_layer_key: len(...) > 0 -> truthiness check getattr(self.model_config, "mtp_layers", None), which handles both None and []. (bug 1)
  • V3 to_hf: the inline, duplicated MTP-expert prefix logic is replaced by a call to the already-existing _map_to_hf_layer_key helper. (bug + dedup, see below)
  • V4: drops _map_layer; the sink branches now use _map_to_hf_layer_key / _map_from_hf_layer_key (bug 2), and a boundary translation renames layers.{N+i} <-> mtp.{i} in to_hf / from_hf (bug 3).

Why both V3 and V4 must change (tianyu-l's question)

Two independent reasons, both because V4 delegates the bulk of conversion to super().to_hf()/super().from_hf():

  1. Bugs 1 live in V3. _map_from_hf_layer_key is a V3 method that V4 inherits unchanged; the len(None) crash happens inside V3 code the moment V4 delegates. It cannot be fixed from V4.

  2. The V3 to_hf change fixes a real placement round-trip bug, not just cosmetics. In the old V3 to_hf, for an MTP expert the local abstract_key was mutated from mtp_layers.{}.moe... to layers.{}.moe... and then used as the metadata key:

    self.grouped_expert_weight_placements[abstract_key] = value.placements  # stored under layers.{}...

    But from_hf looks the metadata back up under the key returned by _map_from_hf_layer_key, which for MTP experts is mtp_layers.{}.moe.... Stored-key != lookup-key, so _concatenate_expert_weights_dtensor misses the cached placements/mesh/shape and MTP expert weights lose their Shard(0) placements on restore. Switching to _map_to_hf_layer_key leaves the local abstract_key as mtp_layers.{}..., so store and lookup agree. This is exactly why V4's test_roundtrip_loads_sharded_mtp_experts can now assert placements survive - and V4 relies on this V3 path for its own experts.

So V3 changes are load-bearing for correctness (not refactoring for its own sake), and V4 changes handle the V4-specific mtp. naming and the sink mapping. Both are necessary.

Is this the most proper way?

Overall yes - it reuses the existing helpers rather than adding parallel logic, keeps the V4-specific naming quirk isolated at the adapter boundary, and is well covered by the new tests (0/1/2 MTP layers, sink round-trip, sharded-expert placements). A few observations:

  • Two-hop translation (minor, acceptable). MTP keys now go mtp_layers.i -> layers.{N+i} (V3 helper) -> mtp.i (V4 post-pass), and the reverse on load. An alternative is to override _map_to_hf_layer_key/_map_from_hf_layer_key in V4 to emit mtp. directly, avoiding the extra full-dict rename pass. The current approach is simpler to audit and localizes the V4 difference, so it's a reasonable trade-off - just worth a one-line comment noting the intermediate layout is never persisted.

  • Pre-existing dead branch in _map_from_hf_layer_key (not introduced here). The if not any(...) / else both execute the identical new_key.replace("layers.{}.", "mtp_layers.{}.", 1):

    if not any(new_key.startswith(f"layers.{{}}.{name}.") for name in (...)):
        new_key = new_key.replace("layers.{}.", "mtp_layers.{}.", 1)
    else:
        new_key = new_key.replace("layers.{}.", "mtp_layers.{}.", 1)

    Since the PR is already editing this method, collapsing both branches to a single .replace() would remove confusing dead code. Fix this →

  • Verify V3 numerics are unchanged. Because the V3 to_hf metadata key changes for MTP experts, please confirm a V3 MTP-model HF export/import still round-trips bit-identically (the new V3 test covers a single expert key; a full-model V3+MTP round-trip would be reassuring, per CLAUDE.md's "protect battle-tested code paths").

  • Guard robustness (good). The key.startswith("layers.") post-pass is correctly gated by layer_num >= self.num_main_layers, so main layers and expert sub-keys are handled right; iterating list(hf_state_dict) while mutating is safe.

I could not run pytest/pre-commit in this environment (network fetch and test execution are blocked here), so the assessment is from code reading; the author's reported local test runs look appropriate.
• branch contrib/4496-deepseek-v4-checkpoint-conversion-fails-with-and-witho

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

to be honest, I couldn't follow the details, but I don't mind these converters being reviewed / maintained by agents.

cc @Matrix-Z97

@tianyu-l
tianyu-l merged commit a423dde into pytorch:main Sep 6, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DeepSeek V4 checkpoint conversion fails with and without MTP

3 participants