Skip to content

[TorchTitan] Use unquantized GPT-OSS expert names unless loading MXFP4 - #5064

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

ivy-zhou merged 1 commit into
mainfrom
pr5064

Conversation

@ivy-zhou

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

Copy link
Copy Markdown
Contributor

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.


Stack created with Sapling. Best reviewed with ReviewStack.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 5, 2026
@ivy-zhou
ivy-zhou marked this pull request as ready for review October 5, 2026 18:57
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 5, 2026
@@ -20,12 +20,43 @@


class GptOssStateDictAdapter(MoEStateDictAdapter):

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 you haven't seen the issue -- how does this solution compare with option 2 at #4996 (comment)

cc @Zhuoxi2000

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

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


Review of PR #5064

  • Read diff (origin/pr5063...HEAD)
  • Trace to_hf / from_hf / fqn_to_index_mapping callsites in the checkpointers
  • Check save-path details (non-contiguous tensors, index remapping)
  • Post review

Summary: The fix is correct and the layout table above the class constants is very helpful. I traced every path that reaches the adapter:

  • dcp.py:388-399 (load) passes the same from_quantized to to_hf, get_hf_storage_reader, and from_hf, so the two name maps are always used as a matching pair.
  • dcp.py:289 and torch_checkpointing.py:575 (HF save) call to_hf(state_dict) with the default False. That matches the unquantized fqn_to_index_mapping you build in __init__.
  • torch_checkpointing.py:346 already rejects from_quantized, and the torchft experiment passes False. No other callsites, and nothing under scripts/ uses this adapter.

If the config flag doesn't match the checkpoint, the load should fail loudly rather than load bad weights. With False on the MXFP4 release, HuggingFaceStorageReader can't find gate_up_proj. With True on a bf16 checkpoint, the quantized reader can't find _blocks. DCP's default planner raises in both cases.

I have one compatibility concern and a few minor points.

1. Old TorchTitan HF saves stop loading (please call this out)

Before this PR, last_save_in_hf=True wrote bf16 tensors named gate_up_proj_blocks / down_proj_blocks in the TorchTitan layout, with no _scales. Those checkpoints loaded back fine with initial_load_in_hf_quantized=False, because to_hf asked for the same _blocks names. After this PR, they fail both ways:

  • from_quantized=False looks for gate_up_proj, which doesn't exist.
  • from_quantized=True uses QuantizedHuggingFaceStorageReader, which expects _scales tensors.

Those files were never valid HF checkpoints, so breaking them is reasonable. Per the "protect battle-tested code paths" rule, though, please state the break in the PR description. Something like this would do: "GPT-OSS HF checkpoints saved by TorchTitan before this change use the _blocks names in the TorchTitan layout and won't load; rename and transpose the expert weights, or re-export from a DCP checkpoint." A short conversion snippet would help anyone affected.

2. Expert weights are now saved as non-contiguous views (worth checking on a real save)

state_dict_adapter.py:162-168: on the unquantized path, both expert weights reach the storage writer as transpose(1, 2) views. Previously w13 was contiguous (the earlier flatten copies it) and w2 went through unchanged. Loading is fine: DCP copies into the view, so the data lands in the storage that from_hf transposes back. Saving has no coverage, though: the unit tests only round-trip in memory and never use HuggingFaceStorageWriter or the safetensors consolidation. Please run one last_save_in_hf on the debug model, ideally with FSDP or EP so the Shard(0) DTensor path is exercised. Then confirm the output loads in transformers (or at least that the safetensors headers show [E, D, 2F] / [E, F, D]). If the writer doesn't make tensors contiguous itself, add .contiguous() on the save path.

3. Minor points

  • Repeated condition. state_dict_adapter.py:162-164 and :201-204 both test tt_key in (self._W13_WEIGHT_KEY, self._W2_WEIGHT_KEY) and not from_quantized. A class constant _EXPERT_WEIGHT_KEYS would remove the repetition, and the local expert_weight_keys at :92 could use it too.
  • _scales filter is broad. :55-60 drops every index key ending in _scales and strips _blocks from every key. That's fine for today's GPT-OSS names, but anchoring both to .mlp.experts. would make the intent explicit. Optional.
  • Comment wording. :52, "only HF saves read it": the load path never uses the mapping, so this is accurate. Saying "only to_hf saves (last_save_in_hf) read it" would point readers to the callsite.
  • Tests. test_released_index_maps_to_unquantized_names is a good addition. One gap: if to_hf(False) ever emitted a _blocks key, it would be absent from fqn_to_index_mapping. You could add a check that every key from to_hf(state_dict) is in the remapped mapping when the index holds all expert names.

4. On @tianyu-l's earlier question (option 2 in #4996)

I couldn't open the issue comment from this environment, so I can't compare against option 2 directly. On its own terms, this PR's approach of choosing the name map from from_quantized costs little: it uses the flag the checkpointer already threads through, and HF saves always produce real bf16 HF checkpoints. If option 2 was "always emit unquantized names and have the quantized reader translate them", that would move this mapping into PyTorch's QuantizedHuggingFaceStorageReader. This PR avoids that cross-repo change.

Verdict: The change looks good. My main requests are to document the break in (1) and run the real-save check in (2). I didn't run the tests or pre-commit, because this environment doesn't allow Python or pip commands.

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 changed the base branch from pr5063 to main October 14, 2026 16:01
@ivy-zhou
ivy-zhou force-pushed the pr5064 branch 3 times, most recently from 8cc5437 to 58e1425 Compare October 19, 2026 22:17
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.
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.

2 participants