Skip to content

[PyTorch][DCP] Dequantize compressed-tensors MXFP4 weights (#201291) - #201291

Closed
ivy-zhou wants to merge 1 commit into
pytorch:mainfrom
ivy-zhou:export-D124826603
Closed

ivy-zhou wants to merge 1 commit into
pytorch:mainfrom
ivy-zhou:export-D124826603

Conversation

@ivy-zhou

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

Copy link
Copy Markdown
Contributor

Summary:

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: X.weight_packed is [out, in/2] uint8 with two E2M1 values per byte, and X.weight_scale is [out, in/32] uint8 E8M0 scales, one per 32 values. QuantizedHuggingFaceStorageReader handles FP8 (weight_scale_inv) and GPT-OSS MXFP4 (_blocks/_scales), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a [out, in/2] tensor are laid out like one GPT-OSS expert, [rows, groups, 16]. So the reader reuses _dequantize_tensor_mxfp4 with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports X.weight_packed under its own name with the dequantized shape [out, in], and a caller asks for X.weight_packed to get bf16 values back. TorchTitan's to_hf(..., quantized=True) requests these names. The alternative was to report the tensor as X.weight, so callers could use unquantized names, but that would make this the only format the reader renames.

read_metadata also replaces the tensor's chunk list, because the load planner builds read items from chunks, not size, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same weight_packed/weight_scale names: NVFP4 (float8_e4m3fn scales, one per 16 values) and int4 pack-quantized (int32 [out, in/8] with a float scale, which at group_size=128 matches the MXFP4 scale shape). So a pair is dequantized only when weight_packed is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:

cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py xplat/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py fbcode/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py

Pass 19, Fail 0, Skip 6.

  • test_compressed_tensors_mxfp4_loading dequantizes a synthetic weight_packed/weight_scale pair through dist_cp.load, with the scale stored in a different file, and loads it again with target_dtype=torch.bfloat16, checking exact bf16 values. It then loads the checkpoint into an empty state dict with _load_state_dict_from_keys, once with the default target_dtype and once with torch.bfloat16, and checks the MXFP4 tensor comes back in that dtype with exactly the expected values; without the dtype fix it comes back as torch.uint8. (It loads the whole checkpoint: _load_state_dict_from_keys with explicit keys reads metadata.planner_data, which HF readers never set, so key filtering fails for any HF reader.)
  • test_compressed_tensors_non_mxfp4_loads_raw is parametrized over seven non-MXFP4 pairs, each in its own checkpoint, and checks the bytes round-trip through dist_cp.load into tensors of their stored shape and dtype: NVFP4 (float8_e4m3fn scale), MXFP4 shapes with an int8 weight_packed, MXFP4 shapes with a float8_e4m3fn scale, a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 pack-quantized (int32 [out, in/8], bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])), and a 3D weight_packed aborted read_metadata on the 2D unpack.
  • TestQuantizedHfStorage.test_compressed_tensors_mxfp4_slice_read builds a read item for rows 1:3, cols 40:90 with the planner's create_read_items_for_chunk_list from the reader's own metadata and checks _process_read_request commits exactly that slice.
  • TestCompressedTensorsMXFP4ShardedLoad.test_shard_starts_mid_group (CPU/gloo, so it runs here) loads a 160-column tensor into a Shard(1) DTensor. Every shard boundary falls mid-group for 2, 3 or 4 ranks (DTensorTestBase uses 4, or the GPU count on 2- or 3-GPU hosts), so the planner's overlap computation runs on the rewritten chunk. With the earlier 96-column version, removing the chunk rewrite made it fail with 163 / 384 elements mismatched.

To check the new cases catch regressions, I temporarily removed both uint8 checks from is_mxfp4 and hardcoded torch.float32 in place of self.target_dtype: test_compressed_tensors_mxfp4_loading and the packed_not_uint8, scale_not_uint8 and int4 cases failed.

The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change and TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change, use the plain HuggingFaceStorageReader/HuggingFaceStorageWriter and failed the same way on master b5c36964ae40 without this change.

arc lint reports no issues. The GitHub PYFMT lint (isort 6.0.1, usort 1.1.3, ruff 0.14.4, run through tools/linter/adapters/pyfmt_linter.py) reports no changes to the lines this diff adds. pyrefly reports no new errors in quantized_hf_storage.py, the two test files, or checkpoint_utils.py, which now holds the MXFP4 reference encoder and checkpoint writer the tests share. The fbcode and xplat copies are identical.

Reviewed By: fegin, shuhuayu

Differential Revision: D124826603

@pytorch-bot

pytorch-bot Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

This PR teaches QuantizedHuggingFaceStorageReader to dequantize
compressed-tensors MXFP4 X.weight_packed / X.weight_scale pairs (Kimi K3 format)
by rewriting the tensor's size, dtype and chunks in read_metadata and reusing
_dequantize_tensor_mxfp4 with an expert dim of 1. Recommendation: Needs
Discussion. The implementation and tests look correct, and the only blocker is
an undocumented change in behavior that needs a release-note entry and a check
of downstream callers that load these checkpoints raw today.

Findings (1):

[minor] torch/distributed/checkpoint/quantized_hf_storage.py:157
Existing checkpoints now load differently, with no release note (also :114-124).
Before: the mapping never picked up `.weight_scale`, so a compressed-tensors
MXFP4 checkpoint loaded raw through this reader. `read_metadata` reported
`X.weight_packed` as `uint8 [out, in/2]`, and `_load_state_dict_from_keys`
returned those bytes. After: the same checkpoint reports `X.weight_packed` as
`target_dtype [out, in]`. Who breaks: a caller that pre-allocates `uint8 [out,
in/2]` destinations (for example, to dequantize the weights itself) now fails
with the size-mismatch AssertionError. A caller that

Reviewed commit: bdc4c37 (NOT the current head b18e698)

Review run

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/201291

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (9 Unrelated Failures)

As of commit b18e698 with merge base e5e5dde (image):

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@meta-codesync

meta-codesync Bot commented Oct 17, 2026

Copy link
Copy Markdown

@ivy-zhou has exported this pull request. If you are a Meta employee, you can view the originating Diff in D124826603.

@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 17, 2026
github-actions[bot]

This comment was marked as outdated.

@meta-codesync meta-codesync Bot changed the title [PyTorch][DCP] Dequantize compressed-tensors MXFP4 weights [PyTorch][DCP] Dequantize compressed-tensors MXFP4 weights (#201291) Oct 17, 2026
ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 17, 2026
…01291)

Summary:

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`. NVFP4 uses the same tensor names with one scale per 16 values, so a scale whose shape doesn't match MXFP4 raises a `ValueError` instead of decoding garbage.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py
```
Pass 10, Fail 2, Skip 4. The new `test_compressed_tensors_mxfp4_loading` passes. It dequantizes a synthetic `weight_packed`/`weight_scale` pair, including a scale stored in a different file and a slice read at rows 1:3, cols 40:90, and checks that an NVFP4-shaped scale raises. The two failures, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter`, and fail the same way on master `b5c36964ae40` without this change (Pass 9, Fail 2, Skip 4). Lint reports no issues.

Differential Revision: D124826603
ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 17, 2026
…01291)

Summary:
Pull Request resolved: pytorch#201291

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`. NVFP4 uses the same tensor names with one scale per 16 values, so a scale whose shape doesn't match MXFP4 raises a `ValueError` instead of decoding garbage.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py
```
Pass 10, Fail 2, Skip 4. The new `test_compressed_tensors_mxfp4_loading` passes. It dequantizes a synthetic `weight_packed`/`weight_scale` pair, including a scale stored in a different file and a slice read at rows 1:3, cols 40:90, and checks that an NVFP4-shaped scale raises. The two failures, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter`, and fail the same way on master `b5c36964ae40` without this change (Pass 9, Fail 2, Skip 4). Lint reports no issues.

Differential Revision: D124826603
github-actions[bot]

This comment was marked as outdated.

ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 17, 2026
…01291)

Summary:

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same `weight_packed`/`weight_scale` names: NVFP4 (`float8_e4m3fn` scales, one per 16 values) and int4 `pack-quantized` (int32 `[out, in/8]` with a float scale, which at `group_size=128` matches the MXFP4 scale shape). So a pair is dequantized only when `weight_packed` is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py
```
Pass 10, Fail 0, Skip 6. The new `test_compressed_tensors_mxfp4_loading` passes. It dequantizes a synthetic `weight_packed`/`weight_scale` pair through `dist_cp.load`, including a scale stored in a different file and a slice read at rows 1:3, cols 40:90. It loads the checkpoint into an empty state dict with `_load_state_dict_from_keys` and checks the MXFP4 tensor comes back as float32 with the expected values; without the dtype fix it comes back as `torch.uint8`. (It loads the whole checkpoint: `_load_state_dict_from_keys` with explicit keys reads `metadata.planner_data`, which HF readers never set, so key filtering fails for any HF reader.) It then `dist_cp.load`s five non-MXFP4 pairs into tensors of their stored shape and dtype and checks the bytes round-trip: NVFP4 (`float8_e4m3fn` scale), a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 `pack-quantized` (int32 `[out, in/8]`, bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (`Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])`), and a 3D `weight_packed` aborted `read_metadata` on the 2D unpack. The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter` and failed the same way on master `b5c36964ae40` without this change. `arc lint -e extra` reports no issues, and pyrefly reports no errors in `quantized_hf_storage.py`.

Differential Revision: D124826603
github-actions[bot]

This comment was marked as outdated.

ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 17, 2026
…01291)

Summary:

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same `weight_packed`/`weight_scale` names: NVFP4 (`float8_e4m3fn` scales, one per 16 values) and int4 `pack-quantized` (int32 `[out, in/8]` with a float scale, which at `group_size=128` matches the MXFP4 scale shape). So a pair is dequantized only when `weight_packed` is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py
```
Pass 10, Fail 0, Skip 6. The new `test_compressed_tensors_mxfp4_loading` passes. It dequantizes a synthetic `weight_packed`/`weight_scale` pair through `dist_cp.load`, including a scale stored in a different file and a slice read at rows 1:3, cols 40:90. It loads the checkpoint into an empty state dict with `_load_state_dict_from_keys` and checks the MXFP4 tensor comes back as float32 with the expected values; without the dtype fix it comes back as `torch.uint8`. (It loads the whole checkpoint: `_load_state_dict_from_keys` with explicit keys reads `metadata.planner_data`, which HF readers never set, so key filtering fails for any HF reader.) It then `dist_cp.load`s five non-MXFP4 pairs into tensors of their stored shape and dtype and checks the bytes round-trip: NVFP4 (`float8_e4m3fn` scale), a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 `pack-quantized` (int32 `[out, in/8]`, bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (`Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])`), and a 3D `weight_packed` aborted `read_metadata` on the 2D unpack. The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter` and failed the same way on master `b5c36964ae40` without this change. `arc lint -e extra` reports no issues, and pyrefly reports no errors in `quantized_hf_storage.py`.

Differential Revision: D124826603
github-actions[bot]

This comment was marked as outdated.

ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 18, 2026
…01291)

Summary:

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same `weight_packed`/`weight_scale` names: NVFP4 (`float8_e4m3fn` scales, one per 16 values) and int4 `pack-quantized` (int32 `[out, in/8]` with a float scale, which at `group_size=128` matches the MXFP4 scale shape). So a pair is dequantized only when `weight_packed` is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py
```
Pass 11, Fail 0, Skip 6. The new `test_compressed_tensors_mxfp4_loading` passes. It dequantizes a synthetic `weight_packed`/`weight_scale` pair through `dist_cp.load`, including a scale stored in a different file and a slice read at rows 1:3, cols 40:90, and loads it again with `target_dtype=torch.bfloat16`, checking exact bf16 values. The new `TestCompressedTensorsMXFP4ShardedLoad.test_shard_starts_mid_group` (CPU/gloo, 4 ranks, so it runs here) loads a 96-column tensor into a `Shard(1)` DTensor, so each rank's 24 columns start partway into a 32-value group and the planner's overlap computation runs on the rewritten chunk; without the chunk rewrite it fails with 163 / 384 elements mismatched. It loads the checkpoint into an empty state dict with `_load_state_dict_from_keys` and checks the MXFP4 tensor comes back as float32 with the expected values; without the dtype fix it comes back as `torch.uint8`. (It loads the whole checkpoint: `_load_state_dict_from_keys` with explicit keys reads `metadata.planner_data`, which HF readers never set, so key filtering fails for any HF reader.) It then `dist_cp.load`s five non-MXFP4 pairs into tensors of their stored shape and dtype and checks the bytes round-trip: NVFP4 (`float8_e4m3fn` scale), a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 `pack-quantized` (int32 `[out, in/8]`, bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (`Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])`), and a 3D `weight_packed` aborted `read_metadata` on the 2D unpack. The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter` and failed the same way on master `b5c36964ae40` without this change. `arc lint -e extra` reports no issues, and pyrefly reports no errors in `quantized_hf_storage.py`.

Differential Revision: D124826603
ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 18, 2026
…01291)

Summary:
Pull Request resolved: pytorch#201291

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same `weight_packed`/`weight_scale` names: NVFP4 (`float8_e4m3fn` scales, one per 16 values) and int4 `pack-quantized` (int32 `[out, in/8]` with a float scale, which at `group_size=128` matches the MXFP4 scale shape). So a pair is dequantized only when `weight_packed` is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py
```
Pass 11, Fail 0, Skip 6. The new `test_compressed_tensors_mxfp4_loading` passes. It dequantizes a synthetic `weight_packed`/`weight_scale` pair through `dist_cp.load`, including a scale stored in a different file and a slice read at rows 1:3, cols 40:90, and loads it again with `target_dtype=torch.bfloat16`, checking exact bf16 values. The new `TestCompressedTensorsMXFP4ShardedLoad.test_shard_starts_mid_group` (CPU/gloo, 4 ranks, so it runs here) loads a 96-column tensor into a `Shard(1)` DTensor, so each rank's 24 columns start partway into a 32-value group and the planner's overlap computation runs on the rewritten chunk; without the chunk rewrite it fails with 163 / 384 elements mismatched. It loads the checkpoint into an empty state dict with `_load_state_dict_from_keys` and checks the MXFP4 tensor comes back as float32 with the expected values; without the dtype fix it comes back as `torch.uint8`. (It loads the whole checkpoint: `_load_state_dict_from_keys` with explicit keys reads `metadata.planner_data`, which HF readers never set, so key filtering fails for any HF reader.) It then `dist_cp.load`s five non-MXFP4 pairs into tensors of their stored shape and dtype and checks the bytes round-trip: NVFP4 (`float8_e4m3fn` scale), a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 `pack-quantized` (int32 `[out, in/8]`, bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (`Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])`), and a 3D `weight_packed` aborted `read_metadata` on the 2D unpack. The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter` and failed the same way on master `b5c36964ae40` without this change. `arc lint -e extra` reports no issues, and pyrefly reports no errors in `quantized_hf_storage.py`.

Differential Revision: D124826603
github-actions[bot]

This comment was marked as outdated.

ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 18, 2026
…01291)

Summary:

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same `weight_packed`/`weight_scale` names: NVFP4 (`float8_e4m3fn` scales, one per 16 values) and int4 `pack-quantized` (int32 `[out, in/8]` with a float scale, which at `group_size=128` matches the MXFP4 scale shape). So a pair is dequantized only when `weight_packed` is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py fbcode/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py
```
Pass 17, Fail 0, Skip 6.

- `test_compressed_tensors_mxfp4_loading` dequantizes a synthetic `weight_packed`/`weight_scale` pair through `dist_cp.load`, with the scale stored in a different file, and loads it again with `target_dtype=torch.bfloat16`, checking exact bf16 values. It then loads the checkpoint into an empty state dict with `_load_state_dict_from_keys` and checks the MXFP4 tensor comes back as float32 with the expected values; without the dtype fix it comes back as `torch.uint8`. (It loads the whole checkpoint: `_load_state_dict_from_keys` with explicit keys reads `metadata.planner_data`, which HF readers never set, so key filtering fails for any HF reader.)
- `test_compressed_tensors_non_mxfp4_loads_raw` is parametrized over five non-MXFP4 pairs, each in its own checkpoint, and checks the bytes round-trip through `dist_cp.load` into tensors of their stored shape and dtype: NVFP4 (`float8_e4m3fn` scale), a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 `pack-quantized` (int32 `[out, in/8]`, bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (`Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])`), and a 3D `weight_packed` aborted `read_metadata` on the 2D unpack.
- `TestQuantizedHfStorage.test_compressed_tensors_mxfp4_slice_read` builds a read item for rows 1:3, cols 40:90 with the planner's `create_read_items_for_chunk_list` from the reader's own metadata and checks `_process_read_request` commits exactly that slice.
- `TestCompressedTensorsMXFP4ShardedLoad.test_shard_starts_mid_group` (CPU/gloo, so it runs here) loads a 160-column tensor into a `Shard(1)` DTensor. Every shard boundary falls mid-group for 2, 3 or 4 ranks, so the planner's overlap computation runs on the rewritten chunk; it skips with fewer than 2 ranks. With the earlier 96-column version, removing the chunk rewrite made it fail with 163 / 384 elements mismatched.

The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter` and failed the same way on master `b5c36964ae40` without this change.

`arc lint` reports no issues. The GitHub PYFMT lint (isort 6.0.1, usort 1.1.3, ruff 0.14.4, run through `tools/linter/adapters/pyfmt_linter.py`) reports no changes to the lines this diff adds. pyrefly reports no new errors in `quantized_hf_storage.py` or the two test files. The fbcode and xplat copies are identical.

Differential Revision: D124826603
github-actions[bot]

This comment was marked as outdated.

ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 18, 2026
…01291)

Summary:

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same `weight_packed`/`weight_scale` names: NVFP4 (`float8_e4m3fn` scales, one per 16 values) and int4 `pack-quantized` (int32 `[out, in/8]` with a float scale, which at `group_size=128` matches the MXFP4 scale shape). So a pair is dequantized only when `weight_packed` is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py xplat/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py fbcode/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py
```
Pass 17, Fail 0, Skip 6.

- `test_compressed_tensors_mxfp4_loading` dequantizes a synthetic `weight_packed`/`weight_scale` pair through `dist_cp.load`, with the scale stored in a different file, and loads it again with `target_dtype=torch.bfloat16`, checking exact bf16 values. It then loads the checkpoint into an empty state dict with `_load_state_dict_from_keys` and checks the MXFP4 tensor comes back as float32 with the expected values; without the dtype fix it comes back as `torch.uint8`. (It loads the whole checkpoint: `_load_state_dict_from_keys` with explicit keys reads `metadata.planner_data`, which HF readers never set, so key filtering fails for any HF reader.)
- `test_compressed_tensors_non_mxfp4_loads_raw` is parametrized over five non-MXFP4 pairs, each in its own checkpoint, and checks the bytes round-trip through `dist_cp.load` into tensors of their stored shape and dtype: NVFP4 (`float8_e4m3fn` scale), a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 `pack-quantized` (int32 `[out, in/8]`, bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (`Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])`), and a 3D `weight_packed` aborted `read_metadata` on the 2D unpack.
- `TestQuantizedHfStorage.test_compressed_tensors_mxfp4_slice_read` builds a read item for rows 1:3, cols 40:90 with the planner's `create_read_items_for_chunk_list` from the reader's own metadata and checks `_process_read_request` commits exactly that slice.
- `TestCompressedTensorsMXFP4ShardedLoad.test_shard_starts_mid_group` (CPU/gloo, so it runs here) loads a 160-column tensor into a `Shard(1)` DTensor. Every shard boundary falls mid-group for 2, 3 or 4 ranks, so the planner's overlap computation runs on the rewritten chunk; it skips with fewer than 2 ranks. With the earlier 96-column version, removing the chunk rewrite made it fail with 163 / 384 elements mismatched.

The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter` and failed the same way on master `b5c36964ae40` without this change.

`arc lint` reports no issues. The GitHub PYFMT lint (isort 6.0.1, usort 1.1.3, ruff 0.14.4, run through `tools/linter/adapters/pyfmt_linter.py`) reports no changes to the lines this diff adds. pyrefly reports no new errors in `quantized_hf_storage.py`, the two test files, or `checkpoint_utils.py`, which now holds the MXFP4 reference encoder and checkpoint writer the tests share. The fbcode and xplat copies are identical.

Differential Revision: D124826603
github-actions[bot]

This comment was marked as outdated.

@github-actions
github-actions Bot dismissed stale reviews from themself October 18, 2026 19:01

Withdrawn: the automated review of 1eb9eb8 found nothing blocking.

ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 18, 2026
…01291)

Summary:
Pull Request resolved: pytorch#201291

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same `weight_packed`/`weight_scale` names: NVFP4 (`float8_e4m3fn` scales, one per 16 values) and int4 `pack-quantized` (int32 `[out, in/8]` with a float scale, which at `group_size=128` matches the MXFP4 scale shape). So a pair is dequantized only when `weight_packed` is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py xplat/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py fbcode/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py
```
Pass 19, Fail 0, Skip 6.

- `test_compressed_tensors_mxfp4_loading` dequantizes a synthetic `weight_packed`/`weight_scale` pair through `dist_cp.load`, with the scale stored in a different file, and loads it again with `target_dtype=torch.bfloat16`, checking exact bf16 values. It then loads the checkpoint into an empty state dict with `_load_state_dict_from_keys`, once with the default `target_dtype` and once with `torch.bfloat16`, and checks the MXFP4 tensor comes back in that dtype with exactly the expected values; without the dtype fix it comes back as `torch.uint8`. (It loads the whole checkpoint: `_load_state_dict_from_keys` with explicit keys reads `metadata.planner_data`, which HF readers never set, so key filtering fails for any HF reader.)
- `test_compressed_tensors_non_mxfp4_loads_raw` is parametrized over seven non-MXFP4 pairs, each in its own checkpoint, and checks the bytes round-trip through `dist_cp.load` into tensors of their stored shape and dtype: NVFP4 (`float8_e4m3fn` scale), MXFP4 shapes with an int8 `weight_packed`, MXFP4 shapes with a `float8_e4m3fn` scale, a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 `pack-quantized` (int32 `[out, in/8]`, bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (`Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])`), and a 3D `weight_packed` aborted `read_metadata` on the 2D unpack.
- `TestQuantizedHfStorage.test_compressed_tensors_mxfp4_slice_read` builds a read item for rows 1:3, cols 40:90 with the planner's `create_read_items_for_chunk_list` from the reader's own metadata and checks `_process_read_request` commits exactly that slice.
- `TestCompressedTensorsMXFP4ShardedLoad.test_shard_starts_mid_group` (CPU/gloo, so it runs here) loads a 160-column tensor into a `Shard(1)` DTensor. Every shard boundary falls mid-group for 2, 3 or 4 ranks (`DTensorTestBase` uses 4, or the GPU count on 2- or 3-GPU hosts), so the planner's overlap computation runs on the rewritten chunk. With the earlier 96-column version, removing the chunk rewrite made it fail with 163 / 384 elements mismatched.

To check the new cases catch regressions, I temporarily removed both uint8 checks from `is_mxfp4` and hardcoded `torch.float32` in place of `self.target_dtype`: `test_compressed_tensors_mxfp4_loading` and the `packed_not_uint8`, `scale_not_uint8` and `int4` cases failed.

The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter` and failed the same way on master `b5c36964ae40` without this change.

`arc lint` reports no issues. The GitHub PYFMT lint (isort 6.0.1, usort 1.1.3, ruff 0.14.4, run through `tools/linter/adapters/pyfmt_linter.py`) reports no changes to the lines this diff adds. pyrefly reports no new errors in `quantized_hf_storage.py`, the two test files, or `checkpoint_utils.py`, which now holds the MXFP4 reference encoder and checkpoint writer the tests share. The fbcode and xplat copies are identical.

Differential Revision: D124826603

@github-actions github-actions Bot 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.

Automated review of bdc4c37: nothing blocking; ready for human review.

This PR teaches QuantizedHuggingFaceStorageReader to dequantize compressed-tensors MXFP4 X.weight_packed / X.weight_scale pairs (Kimi K3 format) by rewriting the tensor's size, dtype and chunks in read_metadata and reusing _dequantize_tensor_mxfp4 with an expert dim of 1. Recommendation: Needs Discussion. The implementation and tests look correct, and the only blocker is an undocumented change in behavior that needs a release-note entry and a check of downstream callers that load these checkpoints raw today.

⚪ 1 non-blocking finding

elif tensor_name.endswith(".weight_scale"):

Existing checkpoints now load differently, with no release note (also :114-124). Before: the mapping never picked up .weight_scale, so a compressed-tensors MXFP4 checkpoint loaded raw through this reader. read_metadata reported X.weight_packed as uint8 \[out, in/2\], and _load_state_dict_from_keys returned those bytes. After: the same checkpoint reports X.weight_packed as target_dtype \[out, in\]. Who breaks: a caller that pre-allocates uint8 \[out, in/2\] destinations (for example, to dequantize the weights itself) now fails with the size-mismatch AssertionError. A caller that

This review is AI-generated and advisory. Each new automated review replaces the previous one.

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Oct 18, 2026

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

LGTM!

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 19, 2026
@fegin

fegin commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Claude finished @fegin's task in 1m 12s —— View job


The PR is close to approvable. There are no blocking findings, and one low-confidence question about the scale dtype is worth a quick check before landing.

PR Review: #201291 (AI-generated, Claude Code)

Summary

The PR teaches QuantizedHuggingFaceStorageReader to dequantize compressed-tensors MXFP4 X.weight_packed/X.weight_scale pairs. It rewrites the size, dtype and chunks that read_metadata reports for those tensors, and reuses _dequantize_tensor_mxfp4 with an expert dim of 1. No REVIEW.md applies.

I checked the decoding against the compressed-tensors packing: low nibble first, the same E2M1 lookup table, and E8M0 scales with bias 127. I also checked the detection gate (quantized_hf_storage.py:102-113), the group-aligned slice read (:497-512), the per-tensor TensorProperties mutation (hf_storage.py:346-347 creates a new instance for each key, so mutating it is safe), and the tests. I found no correctness bugs.

Code Quality

  • Low confidence: quantized_hf_storage.py:107 requires scale_metadata.properties.dtype == torch.uint8. Some writers save E8M0 scales as torch.float8_e8m0fnu (safetensors F8_E8M0) rather than raw uint8. Such a checkpoint would fail detection and fall back to loading raw. A caller asking for an [out, in] float tensor would then hit a generic Size mismatch with no hint that MXFP4 detection was skipped. If any target checkpoint (Kimi K3 or another compressed-tensors MXFP4 export) stores scales as F8_E8M0, accept torch.float8_e8m0fnu too and .view(torch.uint8) the scale before decoding. If they are all confirmed uint8, ignore this.
  • The two items deferred in review threads should get a tracked follow-up issue linked from the PR, so they are not lost:
    • The GPT-OSS _blocks branch (:82-91) still rewrites only size, not chunks or properties.dtype. That is the same root cause this PR fixes for weight_packed.
    • :553-557 builds a 3D ReadItem via dataclasses.replace for a 2D tensor. This is correct only because _dequantize_tensor_mxfp4 reads nothing but storage_offsets[0:2] and lengths[2] from req.

Recommendation

Approve. Nothing blocks. Confirm the on-disk scale dtype of the target checkpoints (first bullet) before landing. The BC change, where existing uint8 pairs now load dequantized, is covered by the release notes: distributed (checkpoint) label and the author's reasoning in the review thread.

ivy-zhou added a commit to ivy-zhou/pytorch that referenced this pull request Oct 19, 2026
…01291)

Summary:

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same `weight_packed`/`weight_scale` names: NVFP4 (`float8_e4m3fn` scales, one per 16 values) and int4 `pack-quantized` (int32 `[out, in/8]` with a float scale, which at `group_size=128` matches the MXFP4 scale shape). So a pair is dequantized only when `weight_packed` is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py xplat/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py fbcode/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py
```
Pass 19, Fail 0, Skip 6.

- `test_compressed_tensors_mxfp4_loading` dequantizes a synthetic `weight_packed`/`weight_scale` pair through `dist_cp.load`, with the scale stored in a different file, and loads it again with `target_dtype=torch.bfloat16`, checking exact bf16 values. It then loads the checkpoint into an empty state dict with `_load_state_dict_from_keys`, once with the default `target_dtype` and once with `torch.bfloat16`, and checks the MXFP4 tensor comes back in that dtype with exactly the expected values; without the dtype fix it comes back as `torch.uint8`. (It loads the whole checkpoint: `_load_state_dict_from_keys` with explicit keys reads `metadata.planner_data`, which HF readers never set, so key filtering fails for any HF reader.)
- `test_compressed_tensors_non_mxfp4_loads_raw` is parametrized over seven non-MXFP4 pairs, each in its own checkpoint, and checks the bytes round-trip through `dist_cp.load` into tensors of their stored shape and dtype: NVFP4 (`float8_e4m3fn` scale), MXFP4 shapes with an int8 `weight_packed`, MXFP4 shapes with a `float8_e4m3fn` scale, a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 `pack-quantized` (int32 `[out, in/8]`, bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (`Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])`), and a 3D `weight_packed` aborted `read_metadata` on the 2D unpack.
- `TestQuantizedHfStorage.test_compressed_tensors_mxfp4_slice_read` builds a read item for rows 1:3, cols 40:90 with the planner's `create_read_items_for_chunk_list` from the reader's own metadata and checks `_process_read_request` commits exactly that slice.
- `TestCompressedTensorsMXFP4ShardedLoad.test_shard_starts_mid_group` (CPU/gloo, so it runs here) loads a 160-column tensor into a `Shard(1)` DTensor. Every shard boundary falls mid-group for 2, 3 or 4 ranks (`DTensorTestBase` uses 4, or the GPU count on 2- or 3-GPU hosts), so the planner's overlap computation runs on the rewritten chunk. With the earlier 96-column version, removing the chunk rewrite made it fail with 163 / 384 elements mismatched.

To check the new cases catch regressions, I temporarily removed both uint8 checks from `is_mxfp4` and hardcoded `torch.float32` in place of `self.target_dtype`: `test_compressed_tensors_mxfp4_loading` and the `packed_not_uint8`, `scale_not_uint8` and `int4` cases failed.

The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter` and failed the same way on master `b5c36964ae40` without this change.

`arc lint` reports no issues. The GitHub PYFMT lint (isort 6.0.1, usort 1.1.3, ruff 0.14.4, run through `tools/linter/adapters/pyfmt_linter.py`) reports no changes to the lines this diff adds. pyrefly reports no new errors in `quantized_hf_storage.py`, the two test files, or `checkpoint_utils.py`, which now holds the MXFP4 reference encoder and checkpoint writer the tests share. The fbcode and xplat copies are identical.

Reviewed By: fegin, shuhuayu

Differential Revision: D124826603
…01291)

Summary:
Pull Request resolved: pytorch#201291

Kimi K3 releases its routed experts in the compressed-tensors MXFP4 format: `X.weight_packed` is `[out, in/2]` uint8 with two E2M1 values per byte, and `X.weight_scale` is `[out, in/32]` uint8 E8M0 scales, one per 32 values. `QuantizedHuggingFaceStorageReader` handles FP8 (`weight_scale_inv`) and GPT-OSS MXFP4 (`_blocks`/`_scales`), but not this format.

The encoding is the same as GPT-OSS's, and the bytes of a `[out, in/2]` tensor are laid out like one GPT-OSS expert, `[rows, groups, 16]`. So the reader reuses `_dequantize_tensor_mxfp4` with an expert dim of 1. Slice reads fetch whole 32-value groups and trim the result.

Names follow the GPT-OSS convention: the reader reports `X.weight_packed` under its own name with the dequantized shape `[out, in]`, and a caller asks for `X.weight_packed` to get bf16 values back. TorchTitan's `to_hf(..., quantized=True)` requests these names. The alternative was to report the tensor as `X.weight`, so callers could use unquantized names, but that would make this the only format the reader renames.

`read_metadata` also replaces the tensor's chunk list, because the load planner builds read items from `chunks`, not `size`, and reports the dequantized dtype, because empty-state-dict loads allocate their destination from the metadata.

Other compressed-tensors formats use the same `weight_packed`/`weight_scale` names: NVFP4 (`float8_e4m3fn` scales, one per 16 values) and int4 `pack-quantized` (int32 `[out, in/8]` with a float scale, which at `group_size=128` matches the MXFP4 scale shape). So a pair is dequantized only when `weight_packed` is 2D and a whole number of 16-byte groups wide, both tensors are uint8, and the scale is one per 32 values; any other pair (including 3D int4 MoE weights) loads raw, as it did before this change.

The DCPv2 resharder is not changed here.

The fbcode and xplat copies are identical. This change was written with the help of an AI assistant.

Test Plan:
```
cd fbcode
buck2 test //caffe2/test/distributed/checkpoint:test_hf_safetensor_e2e //caffe2/test/distributed/checkpoint:test_quantized_hf_storage
arc lint fbcode/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py fbcode/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py xplat/caffe2/torch/testing/_internal/distributed/checkpoint_utils.py fbcode/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py fbcode/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py xplat/caffe2/torch/distributed/checkpoint/quantized_hf_storage.py xplat/caffe2/test/distributed/checkpoint/test_hf_safetensor_e2e.py xplat/caffe2/test/distributed/checkpoint/test_quantized_hf_storage.py
```
Pass 19, Fail 0, Skip 6.

- `test_compressed_tensors_mxfp4_loading` dequantizes a synthetic `weight_packed`/`weight_scale` pair through `dist_cp.load`, with the scale stored in a different file, and loads it again with `target_dtype=torch.bfloat16`, checking exact bf16 values. It then loads the checkpoint into an empty state dict with `_load_state_dict_from_keys`, once with the default `target_dtype` and once with `torch.bfloat16`, and checks the MXFP4 tensor comes back in that dtype with exactly the expected values; without the dtype fix it comes back as `torch.uint8`. (It loads the whole checkpoint: `_load_state_dict_from_keys` with explicit keys reads `metadata.planner_data`, which HF readers never set, so key filtering fails for any HF reader.)
- `test_compressed_tensors_non_mxfp4_loads_raw` is parametrized over seven non-MXFP4 pairs, each in its own checkpoint, and checks the bytes round-trip through `dist_cp.load` into tensors of their stored shape and dtype: NVFP4 (`float8_e4m3fn` scale), MXFP4 shapes with an int8 `weight_packed`, MXFP4 shapes with a `float8_e4m3fn` scale, a uint8 scale that is not one per 32 values, a 40-byte width that is not a whole number of 16-byte groups, int4 `pack-quantized` (int32 `[out, in/8]`, bf16 scale per 128 values), and 3D int4 MoE weights. Before the rank/alignment check, the 40-byte case was misclassified as MXFP4 (`Size mismatch between saved torch.Size([4, 80]) and current: torch.Size([4, 40])`), and a 3D `weight_packed` aborted `read_metadata` on the 2D unpack.
- `TestQuantizedHfStorage.test_compressed_tensors_mxfp4_slice_read` builds a read item for rows 1:3, cols 40:90 with the planner's `create_read_items_for_chunk_list` from the reader's own metadata and checks `_process_read_request` commits exactly that slice.
- `TestCompressedTensorsMXFP4ShardedLoad.test_shard_starts_mid_group` (CPU/gloo, so it runs here) loads a 160-column tensor into a `Shard(1)` DTensor. Every shard boundary falls mid-group for 2, 3 or 4 ranks (`DTensorTestBase` uses 4, or the GPU count on 2- or 3-GPU hosts), so the planner's overlap computation runs on the rewritten chunk. With the earlier 96-column version, removing the chunk rewrite made it fail with 163 / 384 elements mismatched.

To check the new cases catch regressions, I temporarily removed both uint8 checks from `is_mxfp4` and hardcoded `torch.float32` in place of `self.target_dtype`: `test_compressed_tensors_mxfp4_loading` and the `packed_not_uint8`, `scale_not_uint8` and `int4` cases failed.

The six skipped tests are the multi-GPU DTensor and consolidation tests, which skip on this ASAN build because it disables CUDA. On an earlier version with CUDA available, two of them, `TestDTensorReshardPlacementChange.test_2d_to_2d_reshard_placement_change` and `TestDTensorReshardMeshChange.test_2d_to_1d_reshard_mesh_change`, use the plain `HuggingFaceStorageReader`/`HuggingFaceStorageWriter` and failed the same way on master `b5c36964ae40` without this change.

`arc lint` reports no issues. The GitHub PYFMT lint (isort 6.0.1, usort 1.1.3, ruff 0.14.4, run through `tools/linter/adapters/pyfmt_linter.py`) reports no changes to the lines this diff adds. pyrefly reports no new errors in `quantized_hf_storage.py`, the two test files, or `checkpoint_utils.py`, which now holds the MXFP4 reference encoder and checkpoint writer the tests share. The fbcode and xplat copies are identical.

Reviewed By: fegin, shuhuayu

Differential Revision: D124826603
shuhuayu
shuhuayu approved these changes Oct 19, 2026 •
@meta-codesync

meta-codesync Bot commented Oct 20, 2026

Copy link
Copy Markdown

@pytorchbot merge

(Initiating merge automatically since Phabricator Diff has merged)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

danieldale2026 added a commit to danieldale2026/pytorch that referenced this pull request Oct 28, 2026
Mark the single-rank save/load tests as GENERIC and the multi-rank
consolidation and resharding tests as ACCELERATOR, and instantiate the latter
with instantiate_device_type_tests(except_for=("cpu",), allow_xpu=True) so any
registered accelerator collects them.

The resharding classes keep DTensorContinuousTestBase from pytorch#197677; its process
pool is spawned lazily to support device-type instantiation, as in
test_fsdp_dtensor_state_dict.py. Test bodies keep using self.device_type; the
`device` argument is only accepted to satisfy device-type instantiation.
TestCompressedTensorsMXFP4ShardedLoad (added in pytorch#201291) is left unchanged.

This replaces the earlier version of this PR, which targeted the file before
pytorch#197677.

Test Plan:

```bash
spin quicklint test/distributed/checkpoint/test_hf_safetensor_e2e.py
```

No runtime available locally: the file depends on DCP helpers newer than the
available NPU nightly, and there is no local CUDA build. Relying on CI.

Prepared with AI assistance and reviewed by the contributor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018dErhVMhZwJQXMUAkGfe9X
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged meta-exported ready for review Automated review passed, ready for a final review by a maintainer. release notes: distributed (checkpoint)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants