Skip to content

[TorchTitan] Load Kimi K3 compressed-tensors MXFP4 checkpoints - #5337

Merged
ivy-zhou merged 1 commit into
mainfrom
pr5336
Oct 20, 2026
Merged

ivy-zhou merged 1 commit into
mainfrom
pr5336

Conversation

@ivy-zhou

@ivy-zhou ivy-zhou commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary:
Select DCP's quantized Hugging Face reader for Kimi K3. The checkpoint stores routed experts as weight_packed and weight_scale, so to_hf(..., to_quantized_layout=True) names them weight_packed for the reader to dequantize, and from_hf(..., is_quantized_layout=True) maps them back, replacing the ValueError both raised for the quantized layout. A mismatched flag raises on the unmapped expert keys. The released index names the MXFP4 tensors, so fqn_to_index_mapping maps X.weight_packed to X.weight and drops X.weight_scale, as GPT-OSS does, instead of being set to None. HF saves now keep the released 96-file layout instead of writing one consolidated file. Preserve KDA parameter layouts while adapting the released checkpoint's padded A_log and flattened dt_bias shapes. Pad A_log only with to_quantized_layout=True; ordinary HF exports retain n_heads entries for the Hugging Face model.

Text-only configs omit vision_tower.* and mm_projector.* from the HF save map. This prevents DCP consolidation from writing empty dtype headers for parameters that were not exported.

This change was prepared with assistance from an AI coding tool and reviewed by the author.

Test Plan:

PATH=/home/ivyzhou/local/torchtitan-venv/bin:$PATH python -m pytest -q tests/unit_tests/cpu/models/test_state_dict_adapter.py tests/unit_tests/cpu/components/checkpointer/test_checkpoint.py tests/unit_tests/cpu/components/checkpointer/test_state_dict_keys.py tests/unit_tests/cpu/components/checkpointer/test_torch_checkpointing.py -k 'not MuseGlimmerVisionStateDictAdapterTest'
PATH=/home/ivyzhou/local/torchtitan-venv/bin:$PATH pre-commit run --all-files

149 tests passed; the Muse Glimmer vision test was deselected because the local environment lacks FlashAttention 3, a failure also reproduced on main. The A_log regression tests failed on the unguarded padding and passed after the fix. Plain tensors and three-rank DTensors cover both layout flags, including an empty shard, with exact-value comparisons. The text-only export regression failed when consolidation retained vision entries, then passed real DCP save/consolidate/load after filtering them. The multimodal index test verifies that both vision and projector entries are retained when the encoder is enabled.

Formatting and all other pre-commit hooks passed except Pyrefly, which reports the same four dependency errors reproduced on main: two unsupported autotune arguments in AttentionGym and two missing renderers.CustomRendererConfig imports.

The earlier full Kimi-K3 config check found 249,924 HF names and the same 249,924 names in the remapped released index across 96 files.

@ivy-zhou
ivy-zhou changed the base branch from main to pr5065 October 12, 2026 20:07
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 12, 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
ivy-zhou marked this pull request as ready for review October 17, 2026 20:52
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 17, 2026
@shuhuayu

Copy link
Copy Markdown
Contributor

thanks @ivy-zhou! so we are waiting this pr pytorch/pytorch#201291 to be merged right?

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

thx, needs to address a pp compatibility issue.

# The released index contains MXFP4 packed/scale FQNs, while this
# adapter exports unquantized weights.
self.fqn_to_index_mapping = None
# fqn_to_index_mapping always uses unquantized names: only HF saves read

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.

maybe make the comment more explicit: after loading from hf quantized ckpt, we only support saving unquantized ckpt in bf16, to do so, in fqn_to_index_mapping, we remove X.weight_scale and replace X.weight_packed with X.weight.

for key, index in self.fqn_to_index_mapping.items()
if not key.endswith(".weight_scale")
}
self._kda_parameter_layouts: dict[

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.

can you add incline comments on why A_log and dt_bias need special treatment?

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.

there is a pre-existing issue here, this is not pp safe. can you help add the following:

  1. in the condition branch, add and "layers.0.ffn_res_norm.weight" in state_dict to make it pp safe.

  2. use layers.0.ffn_res_norm.weight as norm template

  3. use layers.0.ffn_res_proj.weight as proj template.

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

thx, let's wait for the pytorch pr before merging this one.

@ivy-zhou
ivy-zhou force-pushed the pr5336 branch 3 times, most recently from d9394a1 to 1fc80ee Compare October 20, 2026 06:00
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
ivy-zhou added a commit that referenced this pull request Oct 20, 2026
…writes (#5065)

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.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with
[ReviewStack](https://reviewstack.dev/pytorch/torchtitan/pull/5065).
* #5337
* __->__ #5065
Summary:
Select DCP's quantized Hugging Face reader for Kimi K3. The checkpoint stores routed experts as `weight_packed` and `weight_scale`, so `to_hf(..., to_quantized_layout=True)` names them `weight_packed` for the reader to dequantize, and `from_hf(..., is_quantized_layout=True)` maps them back, replacing the `ValueError` both raised for the quantized layout. A mismatched flag raises on the unmapped expert keys. The released index names the MXFP4 tensors, so `fqn_to_index_mapping` maps `X.weight_packed` to `X.weight` and drops `X.weight_scale`, as GPT-OSS does, instead of being set to `None`. HF saves now keep the released 96-file layout instead of writing one consolidated file. Preserve KDA parameter layouts while adapting the released checkpoint's padded A_log and flattened dt_bias shapes. Pad A_log only with `to_quantized_layout=True`; ordinary HF exports retain `n_heads` entries for the Hugging Face model.

Text-only configs omit `vision_tower.*` and `mm_projector.*` from the HF save map. This prevents DCP consolidation from writing empty dtype headers for parameters that were not exported.

This change was prepared with assistance from an AI coding tool and reviewed by the author.

Test Plan:
```
PATH=/home/ivyzhou/local/torchtitan-venv/bin:$PATH python -m pytest -q tests/unit_tests/cpu/models/test_state_dict_adapter.py tests/unit_tests/cpu/components/checkpointer/test_checkpoint.py tests/unit_tests/cpu/components/checkpointer/test_state_dict_keys.py tests/unit_tests/cpu/components/checkpointer/test_torch_checkpointing.py -k 'not MuseGlimmerVisionStateDictAdapterTest'
PATH=/home/ivyzhou/local/torchtitan-venv/bin:$PATH pre-commit run --all-files
```

149 tests passed; the Muse Glimmer vision test was deselected because the local environment lacks FlashAttention 3, a failure also reproduced on main. The A_log regression tests failed on the unguarded padding and passed after the fix. Plain tensors and three-rank DTensors cover both layout flags, including an empty shard, with exact-value comparisons. The text-only export regression failed when consolidation retained vision entries, then passed real DCP save/consolidate/load after filtering them. The multimodal index test verifies that both vision and projector entries are retained when the encoder is enabled.

Formatting and all other pre-commit hooks passed except Pyrefly, which reports the same four dependency errors reproduced on main: two unsupported `autotune` arguments in AttentionGym and two missing `renderers.CustomRendererConfig` imports.

The earlier full `Kimi-K3` config check found 249,924 HF names and the same 249,924 names in the remapped released index across 96 files.
@ivy-zhou
ivy-zhou changed the base branch from pr5065 to main October 20, 2026 06:27
@ivy-zhou
ivy-zhou merged commit 7d56322 into main Oct 20, 2026
wwwjn added a commit to wwwjn/torchtitan that referenced this pull request Oct 21, 2026
…layout after

The released checkpoint stores KDA dt_bias flat ([n_heads * head_dim]); to_hf
flattened TorchTitan's [n_heads, head_dim] DTensor in place. The full-size
generator (DP 64 x EP 64) shards dt_bias on its 96 heads across 64 ranks, which
DTensor cannot flatten ('Cannot flatten unevenly sharded tensor'), so loading
K3 weights failed on every rank. Replicate before flattening and restore the
recorded mesh and placements in from_hf, as main's adapter does (pytorch#5337).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl 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.

3 participants