Repository navigation
Conversation
This was referenced Oct 5, 2026
ivy-zhou
marked this pull request as ready for review
October 13, 2026 16:25
ivy-zhou
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
October 13, 2026 16:25
tianyu-l
approved these changes
Oct 13, 2026
ivy-zhou
added a commit
that referenced
this pull request
Oct 14, 2026
Summary: An HF load calls `to_hf` on the destination state dict to get the keys to read. Some quantized checkpoints store a tensor under a different name than the unquantized checkpoint does: compressed-tensors MXFP4 (Kimi K3) stores `X.weight_packed` and `X.weight_scale` where the bf16 checkpoint has `X.weight`. The adapter has no way to tell which one is being read. This adds keyword-only `to_hf(state_dict, *, to_quantized_layout=False)` and `from_hf(hf_state_dict, *, is_quantized_layout=False)` to the state dict adapter protocol, and the DCP load passes its `from_quantized` to both. `to_quantized_layout` makes `to_hf` return the quantized checkpoint's key names; only the names change, and no values are quantized. The storage reader then fills those entries with dequantized tensors, so the dict `from_hf` receives is in the quantized checkpoint's layout without being quantized, and `is_quantized_layout` tells `from_hf` to read the names `to_hf` chose instead of inferring the format from the keys. These are per-call arguments rather than adapter state because the same adapter also converts state dicts for HF saves, RL weight sync, and the conversion scripts, which always want unquantized names. Every in-tree adapter accepts both arguments: - DeepSeek V4 and Kimi K2.7 wrap DeepSeek V3 and forward them. - DeepSeek V3 and GPT-OSS, which already load quantized checkpoints, ignore them for now. - Adapters that cannot load a quantized checkpoint (Flux, Llama 3, Qwen3, Qwen3.5, Muse Glimmer, Kimi K3 and the HF transformers backend) raise `ValueError`. Before, the base storage reader only logged a warning and read the checkpoint as unquantized. The `torch_checkpointing` HF load path is left alone for now. Test Plan: ``` pytest -q tests/unit_tests/cpu/components/checkpointer/test_checkpoint.py tests/unit_tests/cpu/models/test_state_dict_adapter.py tests/unit_tests/cpu/components/checkpointer/test_torch_checkpointing.py SKIP=lychee-link-checker pre-commit run --files <changed files> ``` 128 passed, and pre-commit passes. The new `test_quantized_hf_load_requests_quantized_names` checks that a quantized DCP load calls `to_hf(..., to_quantized_layout=True)` and `from_hf(..., is_quantized_layout=True)`. The new `test_adapters_without_quantized_loads_reject_quantized_layout` checks that the Flux, Llama 3 and Qwen3 adapters raise for both, and fails if the Flux check is removed. This change was written with the help of an AI assistant. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/5063). * #5337 * #5065 * #5064 * __->__ #5063
ivy-zhou
force-pushed
the
pr5064
branch
2 times, most recently
from
October 17, 2026 17:46
8a6ee3e to
8cc5437
Compare
ivy-zhou
force-pushed
the
pr5065
branch
2 times, most recently
from
October 19, 2026 22:17
9b6886a to
149af97
Compare
ivy-zhou
added a commit
that referenced
this pull request
Oct 20, 2026
#5064) Summary: With E experts, D = hidden dim, and F = expert hidden dim, TorchTitan stores the gate/up projections (D -> F) as `w13.weight [E, 2, F, D]` and the down projection (F -> D) as `w2.weight [E, D, F]`: output size first, like nn.Linear. `GptOssStateDictAdapter.to_hf` always emitted the MXFP4 names `gate_up_proj_blocks` and `down_proj_blocks` in that layout, which is what the quantized reader dequantizes to. That is only right for a quantized load. Unquantized GPT-OSS checkpoints (and HF transformers, which computes x @ W) name these `gate_up_proj [E, D, 2F]` and `down_proj [E, F, D]`, input size first; `unsloth/gpt-oss-20b-BF16` has `gate_up_proj [32, 2880, 5760]`. So a bf16 GPT-OSS checkpoint could not be loaded, and `last_save_in_hf` wrote tensors under MXFP4 names with the wrong layout. `to_hf` now uses the unquantized names and layout by default, and the `_blocks` names with the TorchTitan layout when `to_quantized_layout=True`. `from_hf` with `is_quantized_layout=True` reads only those names, so both directions share one name map (`from_hf_map` or `from_hf_map_quantized`). The biases have the same names in both formats. The released checkpoint's `model.safetensors.index.json` names the MXFP4 tensors, so `fqn_to_index_mapping` maps `X_blocks` to `X` and drops `X_scales`. HF saves keep the released file sharding. Test Plan: ``` pytest -q tests/unit_tests/cpu/models/test_state_dict_adapter.py tests/unit_tests/cpu/components/checkpointer/test_checkpoint.py SKIP=lychee-link-checker pre-commit run --files tests/unit_tests/cpu/models/test_state_dict_adapter.py torchtitan/models/gpt_oss/state_dict_adapter.py ``` 87 passed, and pre-commit passes. The GPT-OSS round trip now runs with the quantized layout off and on. It checks that the quantized expert weights are the transpose of the unquantized ones, and that `from_hf` with a mismatched flag leaves the expert weights out. A new test covers the index remapping. Expert names and shapes were checked against the `unsloth/gpt-oss-20b-BF16` safetensors headers. This change was written with the help of an AI assistant. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/5064). * #5337 * #5065 * __->__ #5064
…writes
Summary:
`fqn_to_index_mapping` comes from `hf_assets_path`'s
`model.safetensors.index.json`, and only HF saves read it, to decide which
file each tensor goes into. Consolidation creates an output header entry for
every name in the mapping. A name the save never writes gets
`{"shape": [], "dtype": ""}`, and `safetensors` then refuses to open that
file (`unknown variant ''`). DCP's HF reader opens every file, so loading
the saved checkpoint fails.
The released `deepseek-ai/DeepSeek-V3` index (91,991 entries) lists three
kinds of tensors a TorchTitan HF save did not write:
- 45,808 FP8 `X.weight_scale_inv` scales. Saves are unquantized, so these
are dropped from the mapping.
- The MTP layer, `model.layers.61.*` (788 entries), when the config has
`num_mtp_layers=0`. The model has no such layer, so these are dropped too.
- `model.layers.61.embed_tokens.weight` and
`model.layers.61.shared_head.head.weight` with `num_mtp_layers=1`. The
checkpoint stores a copy of the shared embedding and output head under the
MTP layer, while TorchTitan has one `tok_embeddings.weight` and one
`lm_head.weight`. `to_hf` clones the shared tensors for the MTP names so
safetensors can serialize both entries into the same file, including CPU
exports. The saved bytes are duplicated like the released checkpoint.
`from_hf` skips these copies and restores the main names.
On a load, `to_hf` also allocates temporary MTP copies. DCP reads these
independent buffers as well as the main tensors, adding about 3.7 GB of
reads for the released 671B BF16 embedding/head copies. In the
released checkpoint the copies match the main tensors on every sampled row
(rows 0, 1, 43093, 64640, and 129279 of each). `DeepSeekV4` converts its MTP
layers to its own names and opts out with an empty `_MTP_SHARED_COPIES`.
`KimiK25` inherits the change.
Test Plan:
```
pytest -q -o addopts= --tb=short tests/unit_tests/cpu/models/test_state_dict_adapter.py tests/unit_tests/cpu/components/checkpointer/test_checkpoint.py
pre-commit run --all-files
```
89 tests passed. The MTP regression covers one and two layers, checks
independent storage with identical values, and saves/reloads the main and
MTP embedding/head entries through the HF writer and reader without an
index map. The index-filter tests cover `num_mtp_layers` 0 and 1.
Formatting and lint hooks passed. Full pre-commit's type checker reports
two pre-existing `l2norm(..., autotune=...)` signature errors in the unchanged
KDA module with the local Attention Gym installation.
Earlier validation on the full `671B` config with the released index found
that the mapping and `to_hf` output match exactly: 45,395 names with
`num_mtp_layers=0` and 46,183 with `num_mtp_layers=1`.
This change was written with the help of an AI assistant.
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary:
fqn_to_index_mappingcomes fromhf_assets_path'smodel.safetensors.index.json, and only HF saves read it, to decide whichfile each tensor goes into. Consolidation creates an output header entry for
every name in the mapping. A name the save never writes gets
{"shape": [], "dtype": ""}, andsafetensorsthen refuses to open thatfile (
unknown variant ''). DCP's HF reader opens every file, so loadingthe saved checkpoint fails.
The released
deepseek-ai/DeepSeek-V3index (91,991 entries) lists threekinds of tensors a TorchTitan HF save did not write:
X.weight_scale_invscales. Saves are unquantized, so theseare dropped from the mapping.
model.layers.61.*(788 entries), when the config hasnum_mtp_layers=0. The model has no such layer, so these are dropped too.model.layers.61.embed_tokens.weightandmodel.layers.61.shared_head.head.weightwithnum_mtp_layers=1. Thecheckpoint stores a copy of the shared embedding and output head under the
MTP layer, while TorchTitan has one
tok_embeddings.weightand onelm_head.weight.to_hfclones the shared tensors for the MTP names sosafetensors can serialize both entries into the same file, including CPU
exports. The saved bytes are duplicated like the released checkpoint.
from_hfskips these copies and restores the main names.On a load,
to_hfalso allocates temporary MTP copies. DCP reads theseindependent buffers as well as the main tensors, adding about 3.7 GB of
reads for the released 671B BF16 embedding/head copies. In the
released checkpoint the copies match the main tensors on every sampled row
(rows 0, 1, 43093, 64640, and 129279 of each).
DeepSeekV4converts its MTPlayers to its own names and opts out with an empty
_MTP_SHARED_COPIES.KimiK25inherits the change.Test Plan:
89 tests passed. The MTP regression covers one and two layers, checks
independent storage with identical values, and saves/reloads the main and
MTP embedding/head entries through the HF writer and reader without an
index map. The index-filter tests cover
num_mtp_layers0 and 1.Formatting and lint hooks passed. Full pre-commit's type checker reports
two pre-existing
l2norm(..., autotune=...)signature errors in the unchangedKDA module with the local Attention Gym installation.
Earlier validation on the full
671Bconfig with the released index foundthat the mapping and
to_hfoutput match exactly: 45,395 names withnum_mtp_layers=0and 46,183 withnum_mtp_layers=1.This change was written with the help of an AI assistant.
Stack created with Sapling. Best reviewed with ReviewStack.