Skip to content

[TorchTitan] Tell to_hf and from_hf when an HF load is quantized - #5063

Merged
ivy-zhou merged 1 commit into
mainfrom
pr5063
Oct 14, 2026
Merged

ivy-zhou merged 1 commit into
mainfrom
pr5063

Conversation

@ivy-zhou

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

Copy link
Copy Markdown
Contributor

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.


Stack created with Sapling. Best reviewed with ReviewStack.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Oct 5, 2026
@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:23
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 5, 2026
@abstractmethod
def from_hf(self, hf_state_dict: dict[str, Any]) -> dict[str, Any]:
def from_hf(
self, hf_state_dict: dict[str, Any], quantized: bool = False

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.

again see if you agree with #4996 (comment)

here I recommend using from_quantized

  • to align with the arg of get_hf_storage_reader below
  • to make it not ambiguous

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes I think @Zhuoxi2000 and I are basically proposing the same thing here, I will update the naming, thanks for flagging it's the same issue!

@abstractmethod
def to_hf(self, state_dict: dict[str, Any]) -> dict[str, Any]:
def to_hf(
self, state_dict: dict[str, Any], quantized: bool = False

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.

how would we use this quantized field? I assume it means to_quantized. If so, could we generate quantized HF state dict, as I didn't see something like QuantizedHFWriter class before.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This one is used during HF loads actually, there's no quantized checkpoint writing in Titan. The basic flow is that you construct a TorchTitan model / state dict, then you convert to HF side names to load HF state dict into it, and then that allows the QuantizedHuggingFaceStorageReader to read specific quantization keys (e.g. FP8 *.weight with *.weight_scale_inv, or MXFP4 *_blocks with *_scales) so that it can actually do the decoding to full size tensor.

Comment on lines +169 to +171
def to_hf(
self, state_dict: dict[str, Any], from_quantized: bool = False
) -> dict[str, Any]:

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.

should we assert from_quantized=False in the function body, as HF doesn't provide quantized checkpoints and we don't support the feature?

@abstractmethod
def to_hf(self, state_dict: dict[str, Any]) -> dict[str, Any]:
def to_hf(
self, state_dict: dict[str, Any], from_quantized: bool = False

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 precise, shall it be

Suggested change
self, state_dict: dict[str, Any], from_quantized: bool = False
self, state_dict: dict[str, Any], to_quantized: bool = False

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

sounds good, Claude preferred from_quantized because it thought we should always be using it with the from_hf(..., from_quantized=True) function, but I think you're right it doesn't make sense. I will rename.


def to_hf(self, state_dict: dict[str, Any]) -> dict[str, Any]:
def to_hf(
self, state_dict: dict[str, Any], to_quantized_keys: bool = False

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.

Did claude explain why it's "quantized keys"? Although quantized dict and non-quantized dict use different keys, ultimately it's the tensor who gets quantized, not keys.

Is to_quantized and from_quantized not accurate?

@ivy-zhou ivy-zhou Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Oh sorry, this is actually my preference--I was thinking that basically to_hf actually just generates a state dict with the correct quantization state dict keys--it leaves the actual dequantization to the checkpoint loader, which implements the quantization decoding as a part of loading. So the to_hf'd state_dict has the quantization state dict keys, with the correct dequantized tensor shapes, but not the actual dequantized tensors.

To be honest this isn't the best API, you might imagine that you'd want to provide the quantized keys in one step, and then run the dequantization in a separate step. So for example, you might want to load a quantized checkpoint and then you run the dequant(state_dict). This would separate the concerns a bit better but sacrifice some more memory overhead (because you have the full dequantized tensors allocated at the at same time as the quantized tensors).

@tianyu-l tianyu-l Oct 13, 2026 •

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.

I see. Yeah it's not clear to me what would be the best names. I'll stamp but I'll let claude comment one more time.

update: how do you like claude's suggestions?

def to_hf(self, state_dict, *, hf_quantized: bool = False) -> dict[str, Any]: ...
def from_hf(self, hf_state_dict, *, hf_quantized: bool = False) -> dict[str, Any]: ...

@ivy-zhou ivy-zhou Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think it should be:

def to_hf(self, state_dict, *, to_quantized_layout: bool = False) -> dict[str, Any]: ...
def from_hf(self, hf_state_dict, *, is_quantized_layout: bool = False) -> dict[str, Any]: ...

I think this is clearer because in to_hf, we have not yet applied the quantization layout, and without the to_* prefix it might sounds like we are doing to_hf on some state dict with a quantization layout keys. And then for from_hf, the is_quantized_layout is clear that it's about the hf_state_dict.

Claude really prefers the names to be the same so that you know to use the same value w/ the functions, but I don't buy this.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude could you give suggestions on the naming of args for both to_hf and from_hf?

@claude

claude Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

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


Naming suggestion for the to_hf / from_hf quantized flag

  • Read the diff (models/base/state_dict_adapter.py, components/checkpointer/dcp.py, the adapter overrides)
  • Read the review discussion
  • Write up a recommendation

Recommendation: give both methods the same keyword-only name, and have it describe the HF checkpoint rather than a direction. My pick is hf_quantized.

def to_hf(self, state_dict, *, hf_quantized: bool = False) -> dict[str, Any]: ...
def from_hf(self, hf_state_dict, *, hf_quantized: bool = False) -> dict[str, Any]: ...
# dcp.py
hf_state_dict = self.sd_adapter.to_hf(state_dict, hf_quantized=from_quantized)
...
state_dict = self.sd_adapter.from_hf(hf_state_dict, hf_quantized=from_quantized)

Why one name instead of a to_* / from_* pair

  1. The flag describes the same thing in both calls. The method name already gives the direction. The flag only says which layout the HF side uses: a quantized checkpoint (X.weight_packed / X.weight_scale) or a bf16 one (X.weight). A to_/from_ prefix repeats the direction, and on to_hf it suggests the method writes quantized values. That reading confused things earlier in this thread, and none of to_quantized, to_quantized_keys or from_quantized avoids it.
  2. The two values must always match, and one name says so. The current from_hf docstring has to explain "pass the to_quantized_keys value that to_hf was called with". With a shared name, that rule is obvious.
  3. It matches existing naming. The user-facing config is already initial_load_in_hf_quantized, so hf_quantized is the same idea. get_hf_storage_reader(..., from_quantized) can keep its name, because a reader does read from the checkpoint, so the direction is accurate there.
  4. It avoids "quantized keys". @tianyu-l is right that keys aren't quantized; tensors are. @ivy-zhou's point that only the names follow the quantized layout, while dequantization happens in the storage reader, belongs in the docstring, which already says it well. Put descriptions in docstrings, not in names (CLAUDE.md).

If you want the name itself to stress "names only", the next best option is hf_quantized_layout. It's longer but still direction-neutral. I'd steer away from *_keys and from to_/from_ prefixes.

Small related nit: make it keyword-only

CLAUDE.md prefers keyword-only arguments after the first positional one. Right now some callers pass the flag positionally, for example super().from_hf(lm_hf, from_quantized_keys) and super().to_hf(lm_titan, to_quantized_keys) in kimi_k2_7/state_dict_adapter.py, and the same pattern appears in DeepSeek V4. Adding * to the signatures makes every call site name the flag explicitly. That matters for a bool, and it prevents mistakes if more parameters are added later.

Suggested docstrings (ASCII only)

hf_quantized: Whether the HF state dict uses the tensor names of a
    quantized HF checkpoint (e.g. ``weight_packed`` / ``weight_scale``
    instead of ``weight``). Only the names differ; values are never
    quantized here, and on load the storage reader dequantizes them.
    Adapters whose quantized and unquantized checkpoints share names
    can ignore this.

I haven't pushed any code changes; this is only a suggestion. If you go with it, the rename affects all 15 files in the PR, plus the test names and the PR description. Mention me if you'd like me to apply it.

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