Open
feat(mxfp8_qat): checkpoint convert with serializable MXFP8 weights #192
feat(mxfp8_qat): checkpoint convert with serializable MXFP8 weights #192
Open
weixuanAdd on 3 days ago
Total: 17 files changed+1650-599
Mdocs/MXFP8_QAT_usage.md+1-1File content is under review, please try again later
@@ -0,0 +1,254 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""NPU tests: full checkpoint roundtrip through the pack entry.
4+ 
5+Covers the padding-block behavioral guard (packed output feeds the real
6+kernel), the pack entry driven from a prepared model on device, and the
7+four-mode (Dense/MoE x W8A16/W8A8) disk save/reload byte roundtrip on
8+the NPU host.
9+"""
10+ 
11+import sys
12+import tempfile
13+import unittest
14+from unittest.mock import MagicMock
15+ 
16+import torch
17+from torch import nn
18+ 
19+try:
20+ import torch_npu # noqa: F401
21+except ImportError:
22+ sys.modules.setdefault("torch_npu", MagicMock())
23+ 
24+import torchao # noqa: F401
25+from torchao.quantization import quantize_ # noqa: F401
26+ 
27+import torchao_ascend # noqa: F401
28+from torchao_ascend.features.inference.mxfp8 import ( # noqa: F401
29+ MXFP8DenseTensor,
30+ MXFP8GMMTensor,
31+)
32+from torchao_ascend.features.qat.mxfp8_qat import ( # noqa: F401
33+ MXFP8GMMQATConfig,
34+ MXFP8LinearQATConfig,
35+ is_experts_container,
36+ mxfp8_fake_quant,
37+ pack_checkpoint_weights,
38+)
39+from torchao_ascend.features.qat.mxfp8_qat.weight_conversion import ( # noqa: F401
40+ PADDING_SCALE_BYTE,
41+ _WeightSpec,
42+ pack_one_projection,
43+)
44+from torchao_ascend.ops import npu
45+from torchao_ascend.ops.npu.mx_ops import mx_quant_matmul
46+from torchao_ascend.serialization import load_safetensors, save_safetensors # noqa: F401
47+ 
48+DEVICE = "npu:0" if torch.npu.is_available() else "cpu"
49+ 
50+_NPU_REQUIRED = unittest.skipUnless(
51+ DEVICE.startswith("npu"), "requires an Ascend NPU")
52+ 
53+DENSE_W8A8 = _WeightSpec(is_moe=False, weight_only=False, block_size=32)
54+ 
55+ 
56+class HFStyleExperts(nn.Module):
57+ def __init__(self, num_experts=2, hidden=32, intermediate=64):
58+ super().__init__()
59+ self.gate_up_proj = nn.Parameter(
60+ torch.empty(num_experts, 2 * intermediate, hidden))
61+ self.down_proj = nn.Parameter(
62+ torch.empty(num_experts, hidden, intermediate))
63+ nn.init.normal_(self.gate_up_proj, std=0.02)
64+ nn.init.normal_(self.down_proj, std=0.02)
65+ 
66+ def forward(self, *a, **kw):
67+ raise AssertionError("forward must be swapped by MXFP8GMMQAT.from_float")
68+ 
69+ 
70+def _prepared_model():
71+ torch.manual_seed(11)
72+ model = nn.ModuleDict({
73+ "dense8": nn.Linear(96, 8),
74+ "experts8": HFStyleExperts(2, 96, 32),
75+ "plain": nn.Linear(8, 8),
76+ }).to(torch.bfloat16)
77+ quantize_(model["dense8"], MXFP8LinearQATConfig(block_size=32, weight_only=False),
78+ filter_fn=lambda m, f: isinstance(m, nn.Linear))
79+ quantize_(model["experts8"], MXFP8GMMQATConfig(block_size=32, weight_only=False),
80+ filter_fn=lambda m, f: is_experts_container(m))
81+ return model.to(DEVICE)
82+ 
83+ 
84+_FOUR_MODE_KEYS = (
85+ "dense16.weight", "dense8.weight",
86+ "experts16.gate_up_proj", "experts16.down_proj",
87+ "experts8.gate_up_proj", "experts8.down_proj",
88+)
89+ 
90+ 
91+def _four_mode_model():
92+ """Dense/MoE x W8A16/W8A8 in one model plus an unprepared plain layer."""
93+ torch.manual_seed(11)
94+ model = nn.ModuleDict({
95+ "dense16": nn.Linear(96, 8),
96+ "dense8": nn.Linear(96, 8),
97+ "experts16": HFStyleExperts(2, 96, 32),
98+ "experts8": HFStyleExperts(2, 96, 32),
99+ "plain": nn.Linear(8, 8),
100+ }).to(torch.bfloat16)
101+ quantize_(model["dense16"], MXFP8LinearQATConfig(block_size=32, weight_only=True),
102+ filter_fn=lambda m, f: isinstance(m, nn.Linear))
103+ quantize_(model["dense8"], MXFP8LinearQATConfig(block_size=32, weight_only=False),
104+ filter_fn=lambda m, f: isinstance(m, nn.Linear))
105+ quantize_(model["experts16"], MXFP8GMMQATConfig(block_size=32, weight_only=True),
106+ filter_fn=lambda m, f: is_experts_container(m))
107+ quantize_(model["experts8"], MXFP8GMMQATConfig(block_size=32, weight_only=False),
108+ filter_fn=lambda m, f: is_experts_container(m))
109+ return model.to(DEVICE)
110+ 
111+ 
112+@_NPU_REQUIRED
113+class TestPaddingByteGuard(unittest.TestCase):
114+ """Padded blocks must contribute zero in the real kernel."""
115+ 
116+ def test_padding_blocks_contribute_zero_in_kernel(self):
117+ """Packed output with its real padding feeds ``mx_quant_matmul``.
118+ 
119+ Asserts finite output and agreement with the unpadded QAT
120+ reference: appended blocks must contribute exactly zero. This is
121+ the behavioral guard for ``PADDING_SCALE_BYTE`` — a bad byte (255,
122+ E8M0 NaN) surfaces here as non-finite output, so changing the
123+ constant fails this test, not just the constant pin.
124+ """
125+ torch.manual_seed(0)
126+ w = (torch.randn(8, 96, dtype=torch.float32) * 0.1).to(torch.bfloat16).to(DEVICE)
127+ x = (torch.randn(4, 96, dtype=torch.float32) * 0.3).to(torch.bfloat16).to(DEVICE)
128+ # K=96 (odd block count) packs to 128: 32 zero FP8 bytes + padding byte
129+ qdata, scale = pack_one_projection(w, DENSE_W8A8, DEVICE)
130+ x_pad = torch.nn.functional.pad(x, (0, 32)) # match the padded K
131+ x_q, x_s = npu.dynamic_mx_quant(
132+ x_pad, axis=-1, dst_type=torch.float8_e4m3fn,
133+ scale_alg=1, block_size=32)
134+ w_scale = scale.to(DEVICE).reshape(8, 2, 2).transpose(0, 1)
135+ # x2 must carry the float8 dtype (uint8 storage is checkpoint-only)
136+ w_q = qdata.to(DEVICE).view(torch.float8_e4m3fn)
137+ y = mx_quant_matmul(
138+ x_q, w_q.t(), w_scale, pertoken_scale=x_s,
139+ output_dtype=torch.bfloat16, group_sizes=[1, 1, 32])
140+ y_f = y.float().cpu() # NaN would propagate through the copy
141+ self.assertTrue(torch.isfinite(y_f).all(),
142+ "padding byte must not inject non-finite values")
143+ # reference: QAT fake quant on the real (unpadded) region
144+ w_fq = mxfp8_fake_quant(w.cpu(), qdim=-1, block_size=32)
145+ x_fq = mxfp8_fake_quant(x.cpu(), qdim=-1, block_size=32)
146+ y_ref = x_fq.float() @ w_fq.float().t()
147+ rel = ((y_f - y_ref).norm() / y_ref.norm().clamp_min(1e-6)).item()
148+ self.assertLess(rel, 1e-2,
149+ f"padded blocks must contribute zero; rel_L2={rel:.3e}")
150+ 
151+ def test_padding_byte_constant_is_kernel_native_zero(self):
152+ self.assertEqual(PADDING_SCALE_BYTE, 0)
153+ 
154+ 
155+@_NPU_REQUIRED
156+class TestPackEntryOnDevice(unittest.TestCase):
157+ 
158+ def test_pack_from_device_model_and_state(self):
159+ model = _prepared_model()
160+ state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
161+ keys_before = set(state)
162+ before = {k: v.clone() for k, v in state.items() if k != "dense8.weight"
163+ and not k.startswith("experts8.")}
164+ model_before = {k: v.detach().clone() for k, v in model.state_dict().items()}
165+ 
166+ pack_checkpoint_weights(
167+ state, model=model,
168+ dense_names=["dense8"], expert_names=["experts8"], device=DEVICE)
169+ 
170+ self.assertEqual(set(state), keys_before) # in-place, no key churn
171+ dense = state["dense8.weight"]
172+ self.assertIsInstance(dense, MXFP8DenseTensor)
173+ self.assertEqual(tuple(dense.shape), (8, 96)) # wrapper logical view
174+ self.assertEqual(dense.dtype, torch.bfloat16)
175+ self.assertEqual(dense.qdata.shape, (8, 128)) # W8A8 64-aligned grid
176+ self.assertEqual(dense.scale.shape, (8, 4))
177+ for key in ("experts8.gate_up_proj", "experts8.down_proj"):
178+ self.assertTrue(hasattr(state[key], "qdata"))
179+ self.assertEqual(state[key].qdata.shape[-1] % 64, 0)
180+ # unselected plain weight untouched
181+ for key, value in before.items():
182+ if key in state:
183+ self.assertTrue(torch.equal(state[key], value), key)
184+ # the model is read-only: parameters never modified
185+ for key, value in model_before.items():
186+ self.assertTrue(torch.equal(model.state_dict()[key], value), key)
187+ 
188+ def test_disk_roundtrip_four_modes(self):
189+ """Dense/MoE x W8A16/W8A8: packed on device, saved, reloaded."""
190+ for shard_size in (None, "1KB"):
191+ with self.subTest(shard_size=shard_size):
192+ model = _four_mode_model()
193+ state = {k: v.detach().cpu().clone()
194+ for k, v in model.state_dict().items()}
195+ pack_checkpoint_weights(
196+ state, model=model,
197+ dense_names=["dense16", "dense8"],
198+ expert_names=["experts16", "experts8"], device=DEVICE)
199+ with tempfile.TemporaryDirectory() as tmp:
200+ kwargs = {"max_shard_size": shard_size} if shard_size else {}
201+ save_safetensors(state, tmp, **kwargs)
202+ restored = load_safetensors(tmp)
203+ self.assertEqual(set(restored), set(state))
204+ for key in _FOUR_MODE_KEYS:
205+ src, dst = state[key], restored[key]
206+ self.assertIs(type(dst), type(src), key)
207+ self.assertEqual(dst.weight_only, src.weight_only, key)
208+ self.assertEqual(dst.block_size, src.block_size, key)
209+ self.assertEqual(tuple(dst.orig_shape), tuple(src.orig_shape), key)
210+ self.assertEqual(dst.orig_dtype, src.orig_dtype, key)
211+ self.assertTrue(torch.equal(dst.qdata, src.qdata), key)
212+ self.assertTrue(torch.equal(dst.scale, src.scale), key)
213+ # wrapper presents the original parameter shape/dtype
214+ dense = restored["dense8.weight"]
215+ self.assertIsInstance(dense, MXFP8DenseTensor)
216+ self.assertEqual(tuple(dense.shape), (8, 96))
217+ self.assertEqual(dense.dtype, torch.bfloat16)
218+ gate = restored["experts16.gate_up_proj"]
219+ self.assertIsInstance(gate, MXFP8GMMTensor)
220+ self.assertEqual(tuple(gate.shape), (2, 64, 96))
221+ # W8A16 keeps the native 32-grid; W8A8 packs to the 64 grid
222+ self.assertEqual(restored["dense16.weight"].qdata.shape, (8, 96))
223+ self.assertEqual(restored["dense8.weight"].qdata.shape, (8, 128))
224+ # unselected plain weights pass through unchanged
225+ for key in ("plain.weight", "plain.bias"):
226+ self.assertTrue(torch.equal(restored[key], state[key]), key)
227+ 
228+ def test_packed_bytes_match_qat_kernel(self):
229+ """Packed storage equals the RCEIL kernel bytes (training parity)."""
230+ torch.manual_seed(5)
231+ w = (torch.randn(8, 96, dtype=torch.float32) * 0.1).to(torch.bfloat16).to(DEVICE)
232+ qdata_u8, scale_u8 = pack_one_projection(w, DENSE_W8A8, DEVICE)
233+ # direct kernel call on the same weight
234+ nb = 3
235+ q_ref, s_raw = npu.dynamic_mx_quant(
236+ w.contiguous(), axis=-1, dst_type=torch.float8_e4m3fn,
237+ scale_alg=1, block_size=32)
238+ s_ref = s_raw.reshape(8, -1)[..., :nb]
239+ q_ref_u8 = q_ref.view(torch.uint8).cpu()
240+ s_ref_cpu = s_ref.cpu()
241+ self.assertTrue(torch.equal(qdata_u8[:, :96], q_ref_u8))
242+ self.assertTrue(torch.equal(scale_u8[:, :3], s_ref_cpu))
243+ # the W8A16 fake-quant forward on the master matches dequant of the pair
244+ from torchao_ascend.features.qat.mxfp8_qat.weight_conversion import _dequant_natural
245+ restored = _dequant_natural(
246+ q_ref_u8.view(torch.float8_e4m3fn), s_ref_cpu, 32, torch.bfloat16)[..., :96]
247+ w_cpu = w.cpu()
248+ torch.testing.assert_close(
249+ restored, mxfp8_fake_quant(w_cpu, qdim=-1, block_size=32),
250+ rtol=0.0, atol=0.0)
251+ 
252+ 
253+if __name__ == "__main__":
254+ unittest.main()
@@ -0,0 +1,143 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""NPU tests for the weight-conversion core (device path).
4+ 
5+Verifies quantize_native_grid byte parity with a direct kernel call,
6+pack_one_projection on-device shapes / append-only padding / per
7+expert staging, and the PADDING_SCALE_BYTE contract on the real kernel.
8+"""
9+ 
10+import sys
11+import unittest
12+from unittest.mock import MagicMock
13+ 
14+import torch
15+ 
16+try:
17+ import torch_npu # noqa: F401
18+except ImportError:
19+ sys.modules.setdefault("torch_npu", MagicMock())
20+ 
21+import torchao # noqa: F401
22+from torchao_ascend.features.qat.mxfp8_qat import mxfp8_fake_quant # noqa: F401
23+from torchao_ascend.ops import npu
24+from torchao_ascend.features.qat.mxfp8_qat.weight_conversion import ( # noqa: F401
25+ PADDING_SCALE_BYTE,
26+ _WeightSpec,
27+ _dequant_natural,
28+ pack_one_projection,
29+ quantize_native_grid,
30+)
31+ 
32+DEVICE = "npu:0" if torch.npu.is_available() else "cpu"
33+ 
34+_NPU_REQUIRED = unittest.skipUnless(
35+ DEVICE.startswith("npu"), "requires an Ascend NPU")
36+ 
37+DENSE_W8A16 = _WeightSpec(is_moe=False, weight_only=True, block_size=32)
38+DENSE_W8A8 = _WeightSpec(is_moe=False, weight_only=False, block_size=32)
39+MOE_W8A8 = _WeightSpec(is_moe=True, weight_only=False, block_size=32)
40+MOE_W8A16 = _WeightSpec(is_moe=True, weight_only=True, block_size=32)
41+ 
42+ 
43+def _weight(shape, seed=0):
44+ g = torch.Generator().manual_seed(seed)
45+ return (torch.randn(*shape, generator=g, dtype=torch.float32) * 0.1).to(torch.bfloat16)
46+ 
47+ 
48+@_NPU_REQUIRED
49+class TestQuantizeNativeGridNpu(unittest.TestCase):
50+ 
51+ def test_byte_parity_with_direct_kernel_call(self):
52+ """Same kernel, same params: quantize_native_grid == direct call."""
53+ for k in (96, 100, 256):
54+ w = _weight((6, k), seed=3).to(DEVICE)
55+ qdata, scale_u8 = quantize_native_grid(w, 32)
56+ nb = (k + 31) // 32
57+ pad = nb * 32 - k
58+ padded = torch.nn.functional.pad(w, (0, pad)) if pad else w
59+ q_ref, s_raw = npu.dynamic_mx_quant(
60+ padded.contiguous(), axis=-1, dst_type=torch.float8_e4m3fn,
61+ scale_alg=1, block_size=32)
62+ s_ref = s_raw.reshape(*s_raw.shape[:-2], -1)[..., :nb]
63+ self.assertTrue(torch.equal(qdata.view(torch.uint8), q_ref.view(torch.uint8)))
64+ self.assertTrue(torch.equal(scale_u8, s_ref))
65+ 
66+ def test_dequant_parity_with_fake_quant(self):
67+ w = _weight((5, 100), seed=7).to(DEVICE)
68+ w[1, :32] = 0 # zero block: keep the kernel byte, not the CPU 127
69+ qdata, scale_u8 = quantize_native_grid(w, 32)
70+ restored = _dequant_natural(qdata, scale_u8, 32, torch.bfloat16)[..., :100]
71+ torch.testing.assert_close(
72+ restored, mxfp8_fake_quant(w, qdim=-1, block_size=32),
73+ rtol=0.0, atol=0.0)
74+ 
75+ def test_block_size_variants(self):
76+ for b in (32, 64, 128):
77+ w = _weight((4, 100), seed=9).to(DEVICE)
78+ qdata, scale_u8 = quantize_native_grid(w, b)
79+ self.assertEqual(qdata.shape[-1], ((100 + b - 1) // b) * b)
80+ self.assertEqual(scale_u8.shape[-1], (100 + b - 1) // b)
81+ 
82+ 
83+@_NPU_REQUIRED
84+class TestPackOneProjectionNpu(unittest.TestCase):
85+ 
86+ def test_dense_w8a8_k96_append_only(self):
87+ w = _weight((8, 96), seed=4).to(DEVICE)
88+ qdata_u8, scale_u8 = pack_one_projection(w, DENSE_W8A8, DEVICE)
89+ self.assertEqual(qdata_u8.shape, (8, 128))
90+ self.assertEqual(scale_u8.shape, (8, 4))
91+ self.assertEqual(qdata_u8.device.type, "cpu") # staged back to CPU
92+ qn, sn = quantize_native_grid(w, 32)
93+ # real region byte-identical; appended zeros + PADDING_SCALE_BYTE
94+ self.assertTrue(torch.equal(qdata_u8[:, :96], qn.view(torch.uint8).cpu()))
95+ self.assertTrue(torch.equal(scale_u8[:, :3], sn.cpu()))
96+ self.assertTrue(torch.equal(qdata_u8[:, 96:], torch.zeros(8, 32, dtype=torch.uint8)))
97+ self.assertTrue(torch.equal(scale_u8[:, 3:],
98+ torch.full((8, 1), PADDING_SCALE_BYTE, dtype=torch.uint8)))
99+ 
100+ def test_dense_w8a8_native_grid_needs_no_extra_block(self):
101+ """Native 32-grid already 64-aligned (K=100 -> 128, K=256 -> 256)."""
102+ for k, kpad in ((100, 128), (256, 256)):
103+ w = _weight((8, k), seed=5).to(DEVICE)
104+ qdata_u8, scale_u8 = pack_one_projection(w, DENSE_W8A8, DEVICE)
105+ qn, sn = quantize_native_grid(w, 32)
106+ self.assertEqual(qdata_u8.shape, (8, kpad))
107+ self.assertTrue(torch.equal(qdata_u8, qn.view(torch.uint8).cpu()))
108+ self.assertTrue(torch.equal(scale_u8, sn.cpu()))
109+ 
110+ def test_dense_w8a16_native(self):
111+ w = _weight((6, 96), seed=6).to(DEVICE)
112+ qdata_u8, scale_u8 = pack_one_projection(w, DENSE_W8A16, DEVICE)
113+ qn, sn = quantize_native_grid(w, 32)
114+ self.assertEqual(qdata_u8.shape, (6, 96))
115+ self.assertTrue(torch.equal(qdata_u8, qn.view(torch.uint8).cpu()))
116+ self.assertTrue(torch.equal(scale_u8, sn.cpu()))
117+ 
118+ def test_moe_w8a8_per_expert_staging(self):
119+ w = _weight((3, 6, 96), seed=8).to(DEVICE)
120+ qdata_u8, scale_u8 = pack_one_projection(w, MOE_W8A8, DEVICE)
121+ self.assertEqual(qdata_u8.shape, (3, 6, 128))
122+ self.assertEqual(scale_u8.shape, (3, 6, 4))
123+ # whole-tensor native quantize parity on the real region (rows are
124+ # independent, so per-expert staging must not change bytes)
125+ qn, sn = quantize_native_grid(w, 32)
126+ self.assertTrue(torch.equal(qdata_u8[..., :96], qn.view(torch.uint8).cpu()))
127+ self.assertTrue(torch.equal(scale_u8[..., :3], sn.cpu()))
128+ # appended region follows the padding rule for every expert
129+ self.assertTrue(torch.equal(qdata_u8[..., 96:], torch.zeros(3, 6, 32, dtype=torch.uint8)))
130+ self.assertTrue(torch.equal(scale_u8[..., 3:],
131+ torch.full((3, 6, 1), PADDING_SCALE_BYTE, dtype=torch.uint8)))
132+ 
133+ def test_moe_w8a16_native(self):
134+ w = _weight((2, 5, 100), seed=10).to(DEVICE)
135+ qdata_u8, scale_u8 = pack_one_projection(w, MOE_W8A16, DEVICE)
136+ qn, sn = quantize_native_grid(w, 32)
137+ self.assertEqual(qdata_u8.shape, (2, 5, 128))
138+ self.assertTrue(torch.equal(qdata_u8, qn.view(torch.uint8).cpu()))
139+ self.assertTrue(torch.equal(scale_u8, sn.cpu()))
140+ 
141+ 
142+if __name__ == "__main__":
143+ unittest.main()
@@ -36,8 +36,6 @@ from torchao_ascend.features.qat.mxfp8_qat import (
36 MXFP8GMMQATConfig,36 MXFP8GMMQATConfig,
37 MXFP8LinearQAT,37 MXFP8LinearQAT,
38 MXFP8LinearQATConfig,38 MXFP8LinearQATConfig,
39- convert_mxfp8_linear_qat_,
40- is_mxfp8_linear_frozen,
41 prepare_mxfp8_linear_qat_,39 prepare_mxfp8_linear_qat_,
42 mxfp8_fake_quant,40 mxfp8_fake_quant,
43 w8a16_experts_forward,41 w8a16_experts_forward,
@@ -78,6 +76,26 @@ class TestW8A16Namespace:
78 from torchao.quantization.transform_module import _QUANTIZE_CONFIG_HANDLER76 from torchao.quantization.transform_module import _QUANTIZE_CONFIG_HANDLER
79 assert MXFP8LinearQATConfig in _QUANTIZE_CONFIG_HANDLER77 assert MXFP8LinearQATConfig in _QUANTIZE_CONFIG_HANDLER
80 78 
79+ def test_public_surface(self):
80+ """The public ``__all__`` surface is exact (no accidental exports)."""
81+ import torchao.mxfp8_qat as m
82+ expected = {
83+ "MXFP8GMMQATConfig",
84+ "MXFP8FakeQuantization", "MXFP8GMMQAT",
85+ "MXFP8LinearQAT", "MXFP8LinearQATConfig",
86+ "pack_checkpoint_weights",
87+ "prepare_mxfp8_linear_qat_",
88+ "is_experts_container", "module_name_match",
89+ "mxfp8_fake_quant", "mxfp8_gmm_qat_filter_fn",
90+ "reshape_for_gmm",
91+ "w8a16_experts_forward",
92+ "w8a16_grouped_matmul",
93+ "mxfp8_linear_qat_filter_fn", "w8a8_experts_forward",
94+ }
95+ assert set(m.__all__) == expected
96+ for name in m.__all__:
97+ assert hasattr(m, name), name
98+ 
81 99 
82class _TinyModel(nn.Module):100class _TinyModel(nn.Module):
83 """Minimal model with attention + MLP + lm_head for QAT testing."""101 """Minimal model with attention + MLP + lm_head for QAT testing."""
@@ -157,7 +175,7 @@ class TestMXFP8FakeQuant:
157 175 
158 @pytest.mark.skipif(not torch.npu.is_available(), reason='CPU/NPU alignment needs a real NPU')176 @pytest.mark.skipif(not torch.npu.is_available(), reason='CPU/NPU alignment needs a real NPU')
159 def test_cpu_npu_fake_quant_alignment(self):177 def test_cpu_npu_fake_quant_alignment(self):
160- """P2-1: lock CPU emulation (_fq_torch) to the NPU kernel path178+ """Lock CPU emulation (_fq_torch) to the NPU kernel path
161 (scale_alg=1) — bit-level parity on the same input.179 (scale_alg=1) — bit-level parity on the same input.
162 """180 """
163 torch.manual_seed(0)181 torch.manual_seed(0)
@@ -296,15 +314,20 @@ class TestW8A16Configs:
296 314 
297 for config_type in (MXFP8LinearQATConfig, MXFP8GMMQATConfig):315 for config_type in (MXFP8LinearQATConfig, MXFP8GMMQATConfig):
298 assert config_type().step == QATStep.PREPARE316 assert config_type().step == QATStep.PREPARE
299- assert config_type(step="convert").step == QATStep.CONVERT317+ for form in ("convert", "CONVERT"):
318+ with pytest.raises(ValueError, match="pack_checkpoint_weights"):
319+ config_type(step=form)
300 320 
301 def test_gmm_config_from_linear(self):321 def test_gmm_config_from_linear(self):
302 """MXFP8GMMQATConfig.from_linear derives the shared fields."""322 """MXFP8GMMQATConfig.from_linear derives the shared fields."""
303- dense = MXFP8LinearQATConfig(block_size=64, apply_modules=["*.layers.*"])323+ dense = MXFP8LinearQATConfig(
324+ block_size=64, apply_modules=["*.layers.*"], ignored_modules=["*.mlp.gate"])
304 gmm = MXFP8GMMQATConfig.from_linear(dense)325 gmm = MXFP8GMMQATConfig.from_linear(dense)
305 assert isinstance(gmm, MXFP8GMMQATConfig)326 assert isinstance(gmm, MXFP8GMMQATConfig)
306 assert gmm.block_size == 64327 assert gmm.block_size == 64
307 assert gmm.apply_modules == ["*.layers.*"]328 assert gmm.apply_modules == ["*.layers.*"]
329+ assert gmm.ignored_modules == ["*.mlp.gate"]
330+ assert gmm.step == dense.step
308 331 
309 def test_both_handlers_registered(self):332 def test_both_handlers_registered(self):
310 """Both config types are registered with torchao's handler table."""333 """Both config types are registered with torchao's handler table."""
@@ -418,33 +441,16 @@ class TestQATLifecycle:
418 assert m.weight.dtype == torch.bfloat16441 assert m.weight.dtype == torch.bfloat16
419 assert m.weight.requires_grad442 assert m.weight.requires_grad
420 443 
421- def test_convert_freezes_weight(self):444+ def test_convert_step_rejected_at_construction(self):
422- """convert step: write MXFP8-grid values back and freeze."""445+ """step='convert' is rejected by the config constructor (prepare-only)."""
423- torch.manual_seed(0)446+ with pytest.raises(ValueError, match="pack_checkpoint_weights"):
424- lin = nn.Linear(64, 64).to(DEVICE).to(torch.bfloat16)447+ MXFP8LinearQATConfig(step="convert")
425- prepare_mxfp8_linear_qat_(lin, block_size=32)
426- orig = lin.weight.data.clone()
427- assert not is_mxfp8_linear_frozen(lin)
428- convert_mxfp8_linear_qat_(lin)
429- assert is_mxfp8_linear_frozen(lin)
430- assert not lin.weight.requires_grad
431- assert torch.equal(lin.weight.data, mxfp8_fake_quant(orig))
432 448 
433- def test_convert_idempotent(self):449+ def test_prepare_train_pack_pipeline(self):
434- """A second convert is a no-op (weights already on the grid)."""450+ """Full dense pipeline: prepare -> train -> pack_checkpoint_weights.
435- torch.manual_seed(0)
436- lin = nn.Linear(64, 64).to(DEVICE).to(torch.bfloat16)
437- prepare_mxfp8_linear_qat_(lin, block_size=32)
438- convert_mxfp8_linear_qat_(lin)
439- snapshot = lin.weight.data.clone()
440- assert convert_mxfp8_linear_qat_(lin) is lin
441- assert torch.equal(lin.weight.data, snapshot)
442 451 
443- def test_convert_via_quantize_two_step(self):452+ The packed state carries the W8A8 64-aligned grid; the model keeps
444- """Full dense two-step pipeline: prepare → train → convert.453+ its BF16 master weights (read-only pack).
445- 
446- Frozen weights sit on the grid and online fake quant is idempotent,
447- so eval output must match the pre-convert one.
448 """454 """
449 torch.manual_seed(42)455 torch.manual_seed(42)
450 model = _make_model()456 model = _make_model()
@@ -452,9 +458,7 @@ class TestQATLifecycle:
452 def _filter(m, fqn):458 def _filter(m, fqn):
453 return isinstance(m, nn.Linear) and "lm_head" not in fqn459 return isinstance(m, nn.Linear) and "lm_head" not in fqn
454 460 
455- quantize_(model, MXFP8LinearQATConfig(step="prepare"), filter_fn=_filter)461+ quantize_(model, MXFP8LinearQATConfig(), filter_fn=_filter)
456- frozen_before = [m for m in model.modules() if isinstance(m, MXFP8LinearQAT)]
457- assert frozen_before and not any(is_mxfp8_linear_frozen(m) for m in frozen_before)
458 462 
459 optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)463 optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
460 x = torch.randn(2, 64, dtype=torch.bfloat16, device=DEVICE)464 x = torch.randn(2, 64, dtype=torch.bfloat16, device=DEVICE)
@@ -464,14 +468,21 @@ class TestQATLifecycle:
464 optimizer.zero_grad()468 optimizer.zero_grad()
465 469 
466 model.eval()470 model.eval()
467- with torch.no_grad():471+ weights_before = {n: m.weight.data.clone() for n, m in model.named_modules()
468- y_before = model(x)472+ if isinstance(m, MXFP8LinearQAT)}
469- quantize_(model, MXFP8LinearQATConfig(step="convert"), filter_fn=_filter)473+ state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
470- assert all(is_mxfp8_linear_frozen(m) for m in frozen_before)474+ from torchao_ascend.features.qat.mxfp8_qat import pack_checkpoint_weights
471- assert all(not m.weight.requires_grad for m in frozen_before)475+ pack_checkpoint_weights(
472- with torch.no_grad():476+ state, model=model,
473- y_after = model(x)477+ dense_names=[n for n, m in model.named_modules()
474- assert torch.allclose(y_before, y_after, atol=1e-2)478+ if isinstance(m, MXFP8LinearQAT)],
479+ expert_names=[], device=DEVICE)
480+ packed_keys = [f"{n}.weight" for n in weights_before]
481+ for key in packed_keys:
482+ assert state[key].qdata.shape[-1] % 64 == 0
483+ assert state[key].scale.dtype == torch.uint8
484+ for n, w in weights_before.items():
485+ assert torch.equal(model.get_submodule(n).weight.data, w)
475 486 
476 def test_ste_backward(self):487 def test_ste_backward(self):
477 """STE backward: gradient passes through as identity."""488 """STE backward: gradient passes through as identity."""
@@ -544,9 +555,17 @@ class TestQATLifecycle:
544 optimizer.step()555 optimizer.step()
545 optimizer.zero_grad()556 optimizer.zero_grad()
546 557 
547- # convert: freeze weights onto the MXFP8 grid558+ # checkpoint convert: pack the trained state (prepare-only configs)
548- quantize_(model, MXFP8LinearQATConfig(step="convert"),559+ from torchao_ascend.features.qat.mxfp8_qat import pack_checkpoint_weights
549- filter_fn=lambda m, fqn: isinstance(m, nn.Linear) and "lm_head" not in fqn)560+ state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
561+ pack_checkpoint_weights(
562+ state, model=model,
563+ dense_names=[n for n, m in model.named_modules()
564+ if isinstance(m, MXFP8LinearQAT)],
565+ expert_names=[], device=DEVICE)
566+ for key in state:
567+ if hasattr(state[key], "qdata"):
568+ assert state[key].qdata.shape[-1] % 64 == 0 # W8A8 grid
550 model.eval()569 model.eval()
551 with torch.no_grad():570 with torch.no_grad():
552 qat_out = model(x)571 qat_out = model(x)
@@ -595,8 +614,8 @@ class TestMoEExpertsNPU:
595 """MoE container QAT on NPU: BF16 grouped GEMM kernel path."""614 """MoE container QAT on NPU: BF16 grouped GEMM kernel path."""
596 615 
597 def test_experts_forward_npu_parity(self):616 def test_experts_forward_npu_parity(self):
598- """检视 #8: module.experts_forward (EP bypass entry) on real NPU —617+ """module.experts_forward (EP bypass entry) on real NPU — same
599- same per-expert-loop reference as test_experts_forward_parity.618+ per-expert-loop reference as test_experts_forward_parity.
600 """619 """
601 torch.manual_seed(0)620 torch.manual_seed(0)
602 e, hidden, inter, tokens = 4, 64, 128, 6621 e, hidden, inter, tokens = 4, 64, 128, 6
@@ -633,8 +652,8 @@ class TestMoEExpertsNPU:
633 counts = torch.full((e,), m_per, dtype=torch.int64, device=DEVICE)652 counts = torch.full((e,), m_per, dtype=torch.int64, device=DEVICE)
634 got = w8a16_grouped_matmul(x, w, counts)653 got = w8a16_grouped_matmul(x, w, counts)
635 want = torch.cat([x[i * m_per:(i + 1) * m_per] @ w[i].t() for i in range(e)])654 want = torch.cat([x[i * m_per:(i + 1) * m_per] @ w[i].t() for i in range(e)])
636- # tightened (检视 #1): group_list_type branch divergence must pierce655+ # group_list_type branch divergence must pierce the tolerance;
637- # the tolerance; determinism lock on the same impl/args656+ # determinism lock on the same impl/args
638 assert torch.allclose(got.float(), want.float(), atol=1e-2)657 assert torch.allclose(got.float(), want.float(), atol=1e-2)
639 assert torch.equal(got, w8a16_grouped_matmul(x, w, counts))658 assert torch.equal(got, w8a16_grouped_matmul(x, w, counts))
640 659 
@@ -670,7 +689,7 @@ class TestMoEExpertsNPU:
670 h2 = fn(gate) * up689 h2 = fn(gate) * up
671 h3 = h2 @ experts.down_proj[e_i].t()690 h3 = h2 @ experts.down_proj[e_i].t()
672 want.index_add_(0, token_idx, h3 * wts[token_idx, k_pos, None])691 want.index_add_(0, token_idx, h3 * wts[token_idx, k_pos, None])
673- # tightened (检视 #1): branch divergence must pierce the tolerance692+ # branch divergence must pierce the tolerance
674 assert torch.allclose(combined.float(), want.float(), atol=1e-1)693 assert torch.allclose(combined.float(), want.float(), atol=1e-1)
675 # determinism lock: same impl/args -> bit-identical rerun694 # determinism lock: same impl/args -> bit-identical rerun
676 got2 = w8a16_experts_forward(695 got2 = w8a16_experts_forward(
@@ -38,9 +38,6 @@ from torchao_ascend.features.qat.mxfp8_qat import (
38 MXFP8GMMQAT,38 MXFP8GMMQAT,
39 MXFP8LinearQAT,39 MXFP8LinearQAT,
40 MXFP8LinearQATConfig,40 MXFP8LinearQATConfig,
41- convert_mxfp8_linear_qat_,
42- convert_w8a8_gmm_qat_,
43- is_mxfp8_linear_frozen,
44 mxfp8_fake_quant,41 mxfp8_fake_quant,
45 prepare_mxfp8_linear_qat_,42 prepare_mxfp8_linear_qat_,
46 w8a8_experts_forward,43 w8a8_experts_forward,
@@ -187,14 +184,10 @@ class TestW8A8GMMClassSwap(TestCase):
187 assert torch.isfinite(experts.gate_up_proj.grad).all()184 assert torch.isfinite(experts.gate_up_proj.grad).all()
188 assert torch.isfinite(experts.down_proj.grad).all()185 assert torch.isfinite(experts.down_proj.grad).all()
189 186 
190- def test_convert_raises(self):187+ def test_convert_rejected_at_construction(self):
191- """Handler W8A8 convert (weight_only=False) raises NotImplementedError."""188+ """step='convert' is rejected by the config constructor (prepare-only)."""
192- experts = _HFStyleExperts(4, 64, 128).to(DEVICE)189+ with self.assertRaises(ValueError):
193- config = MXFP8GMMQATConfig(block_size=32, weight_only=False)190+ MXFP8GMMQATConfig(block_size=32, weight_only=False, step="convert")
194- MXFP8GMMQAT.from_float(experts, config=config)
195- with self.assertRaises(NotImplementedError):
196- quantize_(experts, MXFP8GMMQATConfig(block_size=32, weight_only=False, step="convert"),
197- filter_fn=lambda mod, fqn: True)
198 191 
199 def test_experts_forward_ep_bypass(self):192 def test_experts_forward_ep_bypass(self):
200 """experts_forward (EP bypass entry) produces same result as module forward."""193 """experts_forward (EP bypass entry) produces same result as module forward."""
@@ -408,31 +401,18 @@ class TestW8A8LinearQAT:
408 assert not torch.allclose(dw_a16.float(), dw_a8.float(), atol=1e-6), \401 assert not torch.allclose(dw_a16.float(), dw_a8.float(), atol=1e-6), \
409 "dW should differ: W8A8 wgrad uses FQ'd activation"402 "dW should differ: W8A8 wgrad uses FQ'd activation"
410 403 
411- def test_convert_freezes_weight(self):404+ def test_prepare_keeps_online_fq(self):
412- """convert freezes weight onto grid; forward still does online FQ."""405+ """W8A8 prepared forward applies online FQ to both x and w."""
413 torch.manual_seed(0)406 torch.manual_seed(0)
414 lin = nn.Linear(64, 64).to(DEVICE).to(torch.bfloat16)407 lin = nn.Linear(64, 64).to(DEVICE).to(torch.bfloat16)
415 config = MXFP8LinearQATConfig(block_size=32, weight_only=False)408 config = MXFP8LinearQATConfig(block_size=32, weight_only=False)
416 prepare_mxfp8_linear_qat_(lin, config=config, block_size=32)409 prepare_mxfp8_linear_qat_(lin, config=config, block_size=32)
417- orig = lin.weight.data.clone()
418- convert_mxfp8_linear_qat_(lin)
419- assert is_mxfp8_linear_frozen(lin)
420- assert not lin.weight.requires_grad
421- assert torch.equal(lin.weight.data, mxfp8_fake_quant(orig))
422- 
423- def test_convert_still_online_fq(self):
424- """After convert, W8A8 forward still applies online FQ to new inputs."""
425- torch.manual_seed(0)
426- lin = nn.Linear(64, 64).to(DEVICE).to(torch.bfloat16)
427- config = MXFP8LinearQATConfig(block_size=32, weight_only=False)
428- prepare_mxfp8_linear_qat_(lin, config=config, block_size=32)
429- convert_mxfp8_linear_qat_(lin)
430 x = torch.randn(4, 64, dtype=torch.bfloat16, device=DEVICE)410 x = torch.randn(4, 64, dtype=torch.bfloat16, device=DEVICE)
431 out = lin(x)411 out = lin(x)
432 # Should differ from raw F.linear (FQ was applied to both x and w)412 # Should differ from raw F.linear (FQ was applied to both x and w)
433 raw = torch.nn.functional.linear(x, lin.weight)413 raw = torch.nn.functional.linear(x, lin.weight)
434 assert not torch.allclose(out.float(), raw.float(), atol=1e-6), \414 assert not torch.allclose(out.float(), raw.float(), atol=1e-6), \
435- "Converted W8A8 should still apply online FQ"415+ "W8A8 prepare should apply online FQ"
436 416 
437 417 
438if __name__ == "__main__":418if __name__ == "__main__":
@@ -0,0 +1,162 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""CPU tests for the MXFP8 inference weight tensors (validation contracts).
4+ 
5+The four-mode (Dense/MoE x W8A16/W8A8) disk rebuild runs in the NPU
6+suite; this file keeps from_packed validation errors, the dotted-FQN
7+writer rule and the device-migration byte contract.
8+"""
9+ 
10+import sys
11+from unittest.mock import MagicMock
12+ 
13+import pytest
14+import torch
15+from torch import nn
16+ 
17+try:
18+ import torch_npu # noqa: F401
19+except ImportError:
20+ sys.modules.setdefault("torch_npu", MagicMock())
21+ 
22+import torchao # noqa: E402,F401 (registers the inference tensors)
23+from torchao.quantization import quantize_ # noqa: E402
24+ 
25+import torchao_ascend # noqa: E402,F401
26+from torchao_ascend.features.inference.mxfp8 import ( # noqa: E402
27+ MXFP8DenseTensor,
28+ MXFP8GMMTensor,
29+)
30+from torchao_ascend.features.qat.mxfp8_qat import ( # noqa: E402
31+ MXFP8GMMQATConfig,
32+ MXFP8LinearQATConfig,
33+ is_experts_container,
34+)
35+from torchao_ascend.features.qat.mxfp8_qat.weight_conversion import ( # noqa: E402
36+ pack_checkpoint_weights,
37+)
38+from torchao_ascend.serialization import save_safetensors # noqa: E402
39+ 
40+DEV = "cpu"
41+ 
42+ 
43+class HFStyleExperts(nn.Module):
44+ def __init__(self, num_experts=2, hidden=32, intermediate=64):
45+ super().__init__()
46+ self.gate_up_proj = nn.Parameter(
47+ torch.empty(num_experts, 2 * intermediate, hidden))
48+ self.down_proj = nn.Parameter(
49+ torch.empty(num_experts, hidden, intermediate))
50+ nn.init.normal_(self.gate_up_proj, std=0.02)
51+ nn.init.normal_(self.down_proj, std=0.02)
52+ 
53+ def forward(self, *a, **kw):
54+ raise AssertionError("forward must be swapped by MXFP8GMMQAT.from_float")
55+ 
56+ 
57+def _prepare_dense(lin, weight_only=False, block_size=32):
58+ quantize_(lin, MXFP8LinearQATConfig(block_size=block_size, weight_only=weight_only),
59+ filter_fn=lambda m, f: isinstance(m, nn.Linear))
60+ return lin
61+ 
62+ 
63+def _prepare_experts(experts, weight_only=False):
64+ quantize_(experts, MXFP8GMMQATConfig(block_size=32, weight_only=weight_only),
65+ filter_fn=lambda m, f: is_experts_container(m))
66+ return experts
67+ 
68+ 
69+def _four_mode_model():
70+ """Dense/MoE x W8A16/W8A8 in one model (fixed seed for reproducibility)."""
71+ torch.manual_seed(11)
72+ model = nn.ModuleDict({
73+ "dense16": _prepare_dense(nn.Linear(96, 8), weight_only=True),
74+ "dense8": _prepare_dense(nn.Linear(96, 8), weight_only=False),
75+ "experts16": _prepare_experts(HFStyleExperts(2, 96, 32), weight_only=True),
76+ "experts8": _prepare_experts(HFStyleExperts(2, 96, 32), weight_only=False),
77+ "plain": nn.Linear(8, 8), # not prepared, not selected
78+ }).to(torch.bfloat16)
79+ return model
80+ 
81+ 
82+_DENSE = ["dense16", "dense8"]
83+_EXPERTS = ["experts16", "experts8"]
84+ 
85+ 
86+def _packed_state():
87+ model = _four_mode_model()
88+ state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
89+ pack_checkpoint_weights(
90+ state, model=model, dense_names=_DENSE, expert_names=_EXPERTS, device=DEV)
91+ return model, state
92+ 
93+ 
94+# ---- from_packed validation ----
95+ 
96+ 
97+def _dense_pair(k=96, weight_only=False, kpad=None):
98+ n = 4
99+ kpad = kpad if kpad is not None else (96 if weight_only else 128)
100+ qdata = torch.randint(0, 200, (n, kpad), dtype=torch.uint8)
101+ nb = kpad // 32
102+ scale = torch.randint(0, 250, (n, nb), dtype=torch.uint8)
103+ return qdata, scale, torch.Size((n, k)), torch.bfloat16
104+ 
105+ 
106+def test_from_packed_dense_validation_errors():
107+ ok = _dense_pair(96, False, 128)
108+ q, s, shape, dt = ok
109+ # wrong dtype (fp8 storage instead of uint8)
110+ with pytest.raises(TypeError, match="uint8"):
111+ MXFP8DenseTensor(q.view(torch.float8_e4m3fn), s, shape, dt, False)
112+ # W8A8 storage not 64-aligned
113+ bad = _dense_pair(96, False, 96)
114+ with pytest.raises(ValueError, match="padded K"):
115+ MXFP8DenseTensor(*bad, False)
116+ # W8A16 storage over-padded to 64 (native grid expected)
117+ bad16 = _dense_pair(96, True, 128)
118+ with pytest.raises(ValueError, match="padded K"):
119+ MXFP8DenseTensor(*bad16, True)
120+ # scale block count mismatch (W8A16-native grid: kpad=96, nb=3)
121+ with pytest.raises(ValueError, match="scale shape"):
122+ MXFP8DenseTensor(q[:, :96], s[:, :2], shape, dt, True)
123+ # 3D shape into the dense class
124+ with pytest.raises(ValueError, match="orig_shape"):
125+ MXFP8DenseTensor(q.unsqueeze(0), s.unsqueeze(0),
126+ torch.Size((1, 4, 96)), torch.bfloat16, False)
127+ 
128+ 
129+def test_from_packed_gmm_validation():
130+ qdata = torch.randint(0, 200, (2, 6, 128), dtype=torch.uint8)
131+ scale = torch.randint(0, 250, (2, 6, 4), dtype=torch.uint8)
132+ t = MXFP8GMMTensor.from_packed(
133+ qdata, scale, torch.Size((2, 6, 96)), torch.bfloat16, weight_only=False)
134+ assert tuple(t.shape) == (2, 6, 96)
135+ with pytest.raises(ValueError, match="orig_shape"):
136+ MXFP8GMMTensor.from_packed(
137+ qdata[0], scale[0], torch.Size((6, 96)), torch.bfloat16, False)
138+ with pytest.raises(ValueError, match="qdata leading"):
139+ MXFP8GMMTensor.from_packed(
140+ qdata, scale, torch.Size((3, 6, 96)), torch.bfloat16, False)
141+ 
142+ 
143+# ---- writer / migration contracts ----
144+ 
145+ 
146+def test_writer_rejects_bare_key(tmp_path):
147+ """The serializer requires dotted FQNs for tensor subclasses."""
148+ lin = _prepare_dense(nn.Linear(96, 8)).to(torch.bfloat16)
149+ state = {"weight": lin.weight.detach().cpu().clone()}
150+ pack_checkpoint_weights(state, model=lin, dense_names=[""], expert_names=[], device=DEV)
151+ with pytest.raises(ValueError, match="dotted FQN"):
152+ save_safetensors(state, tmp_path)
153+ 
154+ 
155+def test_device_migration_preserves_bytes():
156+ """CPU -> (device) -> CPU keeps storage bytes (no requantization)."""
157+ _, state = _packed_state()
158+ dense = state["dense8.weight"]
159+ migrated = dense.to("cpu") # identity path; meta/cpu roundtrip via clone
160+ assert torch.equal(migrated.qdata, dense.qdata)
161+ assert torch.equal(migrated.scale, dense.scale)
162+ assert migrated.weight_only == dense.weight_only
@@ -2,18 +2,16 @@
2 2 
3"""W8A16 MXFP8 QAT unit tests (CPU, no Ascend NPU required).3"""W8A16 MXFP8 QAT unit tests (CPU, no Ascend NPU required).
4 4 
5-Dense prepare/convert two-step lifecycle; MoE single-step class swap.5+Device-path behavior (fake quant, class swap, training lifecycle,
6-Covers (merged suites — every assertion from the pre-merge version kept):6+namespace/config surface, grouped GEMM parity) is covered by the NPU
7- - Import surface, exports, handler registration7+suites; this file keeps the CPU-only contracts:
8- - Config validation (block sizes, step, from_linear field flow)8+ - convert rejection via quantize_ (prepare-only contract)
9- - Dense fake-quant numerics (SNR/idempotent/zero/padding/qdim), STE,9+ - prepare guards (invalid module/block size, re-prepare)
10- prepare/convert lifecycle (freeze, idempotency, meta skip, guards)10+ - container detection, filter semantics and the equivalence matrix
11- - MoE: container detection, filter semantics + equivalence matrix,11+ - grouped-matmul counts contract (error paths)
12- grouped GEMM parity/contract, expert forward parity, class swap,12+ - experts_forward override machinery, forward edges, layout guards
13- forward edge cases (empty tokens, top_k=1, dual-exit activation)13+ - config-object contract and dual-config quantize_
14- - Dual-config quantize_ end-to-end
15"""14"""
16- 
17import re15import re
18import sys16import sys
19from unittest.mock import MagicMock17from unittest.mock import MagicMock
@@ -0,0 +1,236 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""CPU tests for the pack entry point (selection and failure contracts).
4+ 
5+The device-side happy path (packed types, grids, unselected keys,
6+read-only model) and the four-mode disk rebuild are covered by the NPU
7+suite; this file keeps name resolution, spec validation errors,
8+transactionality and the state-as-source contract.
9+"""
10+ 
11+import sys
12+from unittest.mock import MagicMock
13+ 
14+import pytest
15+import torch
16+from torch import nn
17+ 
18+try:
19+ import torch_npu # noqa: F401
20+except ImportError:
21+ sys.modules.setdefault("torch_npu", MagicMock())
22+ 
23+import torchao # noqa: E402,F401
24+from torchao.quantization import quantize_ # noqa: E402
25+ 
26+import torchao_ascend # noqa: E402,F401
27+from torchao_ascend.features.qat.mxfp8_qat import ( # noqa: E402
28+ MXFP8GMMQATConfig,
29+ MXFP8LinearQATConfig,
30+ is_experts_container,
31+)
32+from torchao_ascend.features.inference.mxfp8 import ( # noqa: E402
33+ MXFP8DenseTensor,
34+)
35+from torchao_ascend.features.qat.mxfp8_qat.weight_conversion import ( # noqa: E402
36+ collect_selected_weight_specs,
37+ pack_checkpoint_weights,
38+ validate_specs_against_state,
39+)
40+ 
41+DEV = "cpu"
42+ 
43+ 
44+class HFStyleExperts(nn.Module):
45+ """Out-first fused experts container (bare Parameters)."""
46+ 
47+ def __init__(self, num_experts=2, hidden=32, intermediate=64):
48+ super().__init__()
49+ self.gate_up_proj = nn.Parameter(
50+ torch.empty(num_experts, 2 * intermediate, hidden))
51+ self.down_proj = nn.Parameter(
52+ torch.empty(num_experts, hidden, intermediate))
53+ nn.init.normal_(self.gate_up_proj, std=0.02)
54+ nn.init.normal_(self.down_proj, std=0.02)
55+ self.to(torch.bfloat16)
56+ 
57+ def forward(self, *a, **kw):
58+ raise AssertionError("forward must be swapped by MXFP8GMMQAT.from_float")
59+ 
60+ 
61+class _Proj(nn.Module):
62+ def __init__(self, tensor):
63+ super().__init__()
64+ self.weight = nn.Parameter(tensor)
65+ 
66+ 
67+class SubmoduleExperts(nn.Module):
68+ def __init__(self, num_experts=2, hidden=32, intermediate=64):
69+ super().__init__()
70+ self.gate_up_proj = _Proj(torch.empty(num_experts, 2 * intermediate, hidden))
71+ self.down_proj = _Proj(torch.empty(num_experts, hidden, intermediate))
72+ for mod in (self.gate_up_proj, self.down_proj):
73+ nn.init.normal_(mod.weight, std=0.02)
74+ self.to(torch.bfloat16)
75+ 
76+ 
77+def _prepare_dense(lin, weight_only=False, block_size=32):
78+ quantize_(lin, MXFP8LinearQATConfig(block_size=block_size, weight_only=weight_only),
79+ filter_fn=lambda m, f: isinstance(m, nn.Linear))
80+ return lin
81+ 
82+ 
83+def _prepare_experts(experts, weight_only=False, block_size=32):
84+ quantize_(experts, MXFP8GMMQATConfig(block_size=block_size, weight_only=weight_only),
85+ filter_fn=lambda m, f: is_experts_container(m))
86+ return experts
87+ 
88+ 
89+def _mixed_model():
90+ model = nn.Sequential(
91+ _prepare_dense(nn.Linear(96, 8)),
92+ nn.Linear(8, 8), # not prepared, not selected
93+ _prepare_experts(HFStyleExperts(2, 96, 32)),
94+ ).to(torch.bfloat16)
95+ return model
96+ 
97+ 
98+def _cpu_state(model):
99+ return {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
100+ 
101+ 
102+# ---- collect_selected_weight_specs ----
103+ 
104+ 
105+def test_collect_submodule_container_keys():
106+ experts = _prepare_experts(SubmoduleExperts(2, 96, 32))
107+ specs = collect_selected_weight_specs(experts, dense_names=[], expert_names=[""])
108+ assert set(specs) == {"gate_up_proj.weight", "down_proj.weight"}
109+ 
110+ 
111+def test_collect_missing_name():
112+ model = _mixed_model()
113+ with pytest.raises(ValueError, match="module not found"):
114+ collect_selected_weight_specs(model, dense_names=["missing"], expert_names=[])
115+ 
116+ 
117+def test_collect_unprepared_module():
118+ model = _mixed_model()
119+ with pytest.raises(TypeError, match="not a prepared MXFP8 dense module"):
120+ collect_selected_weight_specs(model, dense_names=["1"], expert_names=[])
121+ 
122+ 
123+def test_collect_wrong_kind():
124+ model = _mixed_model()
125+ with pytest.raises(TypeError, match="not a prepared MXFP8 dense module"):
126+ collect_selected_weight_specs(model, dense_names=["2"], expert_names=[])
127+ with pytest.raises(TypeError, match="not a prepared MXFP8 expert module"):
128+ collect_selected_weight_specs(model, dense_names=[], expert_names=["0"])
129+ 
130+ 
131+def test_collect_duplicate_names():
132+ model = _mixed_model()
133+ with pytest.raises(ValueError, match="duplicate weight key"):
134+ collect_selected_weight_specs(model, dense_names=["0", "0"], expert_names=[])
135+ 
136+ 
137+def test_collect_empty_selection():
138+ with pytest.raises(ValueError, match="no MXFP8 QAT modules"):
139+ validate_specs_against_state({}, {})
140+ 
141+ 
142+# ---- validate_specs_against_state ----
143+ 
144+ 
145+def test_validate_missing_key():
146+ model = _mixed_model()
147+ specs = collect_selected_weight_specs(model, ["0"], [])
148+ state = _cpu_state(model)
149+ del state["0.weight"]
150+ with pytest.raises(KeyError):
151+ validate_specs_against_state(specs, state)
152+ 
153+ 
154+def test_validate_rejects_non_bf16():
155+ model = _mixed_model()
156+ specs = collect_selected_weight_specs(model, ["0"], [])
157+ state = _cpu_state(model)
158+ state["0.weight"] = state["0.weight"].to(torch.float16)
159+ with pytest.raises(TypeError, match="BF16"):
160+ validate_specs_against_state(specs, state)
161+ 
162+ 
163+def test_validate_rejects_nan():
164+ model = _mixed_model()
165+ specs = collect_selected_weight_specs(model, ["0"], [])
166+ state = _cpu_state(model)
167+ state["0.weight"][0, 0] = float("nan")
168+ with pytest.raises(ValueError, match="NaN/Inf"):
169+ validate_specs_against_state(specs, state)
170+ 
171+ 
172+def test_validate_rejects_shape_mismatch():
173+ model = _mixed_model()
174+ specs = collect_selected_weight_specs(model, ["0"], [])
175+ state = _cpu_state(model)
176+ state["0.weight"] = state["0.weight"][:, :64].contiguous()
177+ with pytest.raises(ValueError, match="state shape"):
178+ validate_specs_against_state(specs, state)
179+ 
180+ 
181+def test_validate_rejects_shared_storage():
182+ model = _mixed_model()
183+ specs = collect_selected_weight_specs(model, ["0"], ["2"])
184+ state = _cpu_state(model)
185+ state["2.gate_up_proj"] = state["0.weight"] # wrong tensor AND aliased
186+ with pytest.raises(Exception):
187+ validate_specs_against_state(specs, state)
188+ 
189+ 
190+# ---- pack_checkpoint_weights ----
191+ 
192+ 
193+def test_pack_w8a8_rejects_block_size_64():
194+ model = nn.Sequential(
195+ _prepare_dense(nn.Linear(96, 8), weight_only=False, block_size=64)
196+ ).to(torch.bfloat16)
197+ state = _cpu_state(model)
198+ with pytest.raises(ValueError, match="block_size=32"):
199+ pack_checkpoint_weights(state, model=model, dense_names=["0"],
200+ expert_names=[], device=DEV)
201+ assert state["0.weight"].dtype == torch.bfloat16 # state untouched
202+ 
203+ 
204+def test_pack_state_source_not_model_parameters():
205+ """state values are the quantization source; the model is never read."""
206+ model = _mixed_model()
207+ state = _cpu_state(model)
208+ # perturb the live model after the snapshot: packed bytes must follow state
209+ with torch.no_grad():
210+ model[0].weight.fill_(0.5)
211+ pack_checkpoint_weights(state, model=model, dense_names=["0"], expert_names=[], device=DEV)
212+ packed = state["0.weight"]
213+ # The spec shapes come from the model; the quantized values come from the
214+ # pre-fill snapshot held in `state` (the live parameter was perturbed
215+ # after the snapshot, which must not influence the packed bytes).
216+ assert packed.orig_shape == (8, 96)
217+ 
218+ 
219+def test_pack_transactional_on_validation_failure():
220+ model = _mixed_model()
221+ state = _cpu_state(model)
222+ state["2.down_proj"][0, 0, 0] = float("inf") # one bad weight
223+ snapshot = {k: v.clone() for k, v in state.items()} # after the mutation
224+ with pytest.raises(ValueError, match="NaN/Inf"):
225+ pack_checkpoint_weights(state, model=model, dense_names=["0"], expert_names=["2"], device=DEV)
226+ # nothing was replaced: dense (which would have packed fine) is still BF16
227+ for key, value in snapshot.items():
228+ assert torch.equal(state[key], value), key
229+ 
230+ 
231+def test_pack_module_without_prefix():
232+ """A bare prepared module (no FQN) maps to the bare 'weight' key."""
233+ lin = _prepare_dense(nn.Linear(96, 8)).to(torch.bfloat16)
234+ state = {"weight": lin.weight.detach().cpu().clone()}
235+ pack_checkpoint_weights(state, model=lin, dense_names=[""], expert_names=[], device=DEV)
236+ assert isinstance(state["weight"], MXFP8DenseTensor)
@@ -0,0 +1,70 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""CPU tests for the weight-conversion core (validation contracts).
4+ 
5+Device-path byte parity, padding layout and per-expert staging are
6+covered by the NPU suite; this file keeps the CPU-side error contracts
7+and the per-projection K independence of MoE packing.
8+"""
9+ 
10+import sys
11+from unittest.mock import MagicMock
12+ 
13+import pytest
14+import torch
15+ 
16+try:
17+ import torch_npu # noqa: F401
18+except ImportError:
19+ sys.modules.setdefault("torch_npu", MagicMock())
20+ 
21+import torchao # noqa: E402,F401
22+from torchao_ascend.features.qat.mxfp8_qat.weight_conversion import ( # noqa: E402
23+ _WeightSpec,
24+ pack_one_projection,
25+ quantize_native_grid,
26+)
27+ 
28+DEV = "cpu"
29+ 
30+MOE_W8A8 = _WeightSpec(is_moe=True, weight_only=False, block_size=32)
31+ 
32+ 
33+def _weight(m, k, seed=0):
34+ g = torch.Generator().manual_seed(seed)
35+ return (torch.randn(m, k, generator=g, dtype=torch.float32) * 0.1).to(torch.bfloat16)
36+ 
37+ 
38+# ---- quantize_native_grid: input validation ----
39+ 
40+ 
41+def test_quantize_native_grid_validation():
42+ with pytest.raises(ValueError, match="materialized"):
43+ quantize_native_grid(torch.randn(4, 8, device="meta"), 32)
44+ with pytest.raises(ValueError, match="invalid weight shape"):
45+ quantize_native_grid(torch.randn(8), 32)
46+ bad = torch.randn(4, 64)
47+ bad[0, 0] = float("nan")
48+ with pytest.raises(ValueError, match="NaN/Inf"):
49+ quantize_native_grid(bad, 32)
50+ with pytest.raises(ValueError, match="block_size"):
51+ quantize_native_grid(torch.randn(4, 64), 16)
52+ 
53+ 
54+# ---- pack_one_projection: MoE per-projection K independence ----
55+ 
56+ 
57+def _moe_weight(e, rows, k, seed=0):
58+ g = torch.Generator().manual_seed(seed)
59+ return (torch.randn(e, rows, k, generator=g, dtype=torch.float32) * 0.1).to(torch.bfloat16)
60+ 
61+ 
62+def test_pack_moe_w8a8_two_projections_different_k():
63+ """gate_up [E,2I,H] and down [E,H,I] pack independently with their own K."""
64+ e, hidden, inter = 3, 96, 64
65+ gate = _moe_weight(e, 2 * 4, hidden, seed=8)
66+ down = _moe_weight(e, 4, inter, seed=9)
67+ gq, gs = pack_one_projection(gate, MOE_W8A8, DEV)
68+ dq, ds = pack_one_projection(down, MOE_W8A8, DEV)
69+ assert gq.shape == (e, 8, 128) and gs.shape == (e, 8, 4)
70+ assert dq.shape == (e, 4, 64) and ds.shape == (e, 4, 2)
@@ -3,8 +3,10 @@
3"""Inference features for torchao_ascend.3"""Inference features for torchao_ascend.
4 4 
5The W4A16 conversion uses a native W4A16 operator for dense layers and5The W4A16 conversion uses a native W4A16 operator for dense layers and
6-dequantizes MoE expert weights for BF16 computation.6+dequantizes MoE expert weights for BF16 computation. The MXFP8 tensors
7+are serializable checkpoint carriers for W8A8/W8A16; forward dispatch is
8+not registered yet.
7"""9"""
8-from . import w4a1610+from . import mxfp8, w4a16
9 11 
10-__all__ = ["w4a16"]12+__all__ = ["mxfp8", "w4a16"]
@@ -0,0 +1,213 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+ 
3+"""MXFP8 inference weight tensors: serializable checkpoint carriers.
4+ 
5+Two TorchAOBaseTensor subclasses store the packed MXFP8 pair in the uint8
6+checkpoint contract:
7+ 
8+- ``qdata``: uint8 storage, one byte per E4M3FN value, last dim padded to
9+ the ``block_size`` grid — and to a 64 multiple for W8A8 (pack-time
10+ alignment; ``PADDING_SCALE_BYTE``-padded zero blocks);
11+- ``scale``: uint8 storage, natural block order E8M0 bytes
12+ (byte = exp + 127, RCEIL; zero blocks carry the kernel byte).
13+ 
14+The wrapper presents the original parameter shape/dtype; both activation
15+modes share the same storage and are distinguished by ``weight_only``.
16+Current scope: validation, device migration and safetensors roundtrip.
17+Forward dispatch (aten.linear / grouped matmul) is not registered yet.
18+"""
19+from __future__ import annotations
20+ 
21+import torch
22+from torchao.utils import TorchAOBaseTensor
23+ 
24+from torchao_ascend.serialization import register_safetensors_tensor_subclass
25+ 
26+__all__ = ["MXFP8DenseTensor", "MXFP8GMMTensor"]
27+ 
28+_SUPPORTED_BLOCK_SIZES = (32, 64, 128)
29+ 
30+ 
31+def _expected_kpad(logical_k: int, block_size: int, weight_only: bool) -> int:
32+ """Native 32-grid length; W8A8 packs to the 64-multiple kernel grid."""
33+ native = (logical_k + block_size - 1) // block_size * block_size
34+ if weight_only:
35+ return native
36+ if block_size != 32:
37+ raise ValueError(
38+ f"W8A8 MXFP8 inference requires block_size=32, got {block_size}")
39+ return (native + 63) // 64 * 64
40+ 
41+ 
42+def _validate_packed(
43+ qdata: torch.Tensor,
44+ scale: torch.Tensor,
45+ orig_shape: torch.Size,
46+ weight_only: bool,
47+ block_size: int,
48+ ndim: int,
49+) -> int:
50+ """Shared storage validation; returns the padded K length."""
51+ if qdata.dtype != torch.uint8 or scale.dtype != torch.uint8:
52+ raise TypeError(
53+ f"MXFP8 checkpoint storage is uint8 (qdata/scale), got "
54+ f"{qdata.dtype}/{scale.dtype}")
55+ if block_size not in _SUPPORTED_BLOCK_SIZES:
56+ raise ValueError(
57+ f"unsupported MXFP8 block_size: {block_size}, "
58+ f"expected one of {_SUPPORTED_BLOCK_SIZES}")
59+ if len(orig_shape) != ndim:
60+ raise ValueError(
61+ f"expected orig_shape with {ndim} dims, got {tuple(orig_shape)}")
62+ if qdata.dim() != ndim or tuple(qdata.shape[:-1]) != tuple(orig_shape[:-1]):
63+ raise ValueError(
64+ f"qdata leading shape {tuple(qdata.shape[:-1])} != orig "
65+ f"{tuple(orig_shape[:-1])}")
66+ k = orig_shape[-1]
67+ kpad = qdata.shape[-1]
68+ expected = _expected_kpad(k, block_size, weight_only)
69+ if kpad != expected:
70+ raise ValueError(
71+ f"padded K {kpad} != expected {expected} for logical K={k}, "
72+ f"block_size={block_size}, weight_only={weight_only}")
73+ if tuple(scale.shape) != (*orig_shape[:-1], kpad // block_size):
74+ raise ValueError(
75+ f"scale shape {tuple(scale.shape)} != expected "
76+ f"{(*orig_shape[:-1], kpad // block_size)}")
77+ return kpad
78+ 
79+ 
80+class MXFP8DenseTensor(TorchAOBaseTensor):
81+ """Logical ``[N, K]`` weight stored as a uint8 MXFP8 pair (dense)."""
82+ 
83+ tensor_data_names = ["qdata", "scale"]
84+ tensor_attribute_names = ["orig_shape", "orig_dtype", "weight_only", "block_size"]
85+ 
86+ def __new__(
87+ cls,
88+ qdata: torch.Tensor,
89+ scale: torch.Tensor,
90+ orig_shape: torch.Size,
91+ orig_dtype: torch.dtype,
92+ weight_only: bool,
93+ block_size: int = 32,
94+ ) -> "MXFP8DenseTensor":
95+ return torch.Tensor._make_wrapper_subclass(
96+ cls,
97+ torch.Size(orig_shape),
98+ dtype=orig_dtype,
99+ device=qdata.device,
100+ requires_grad=False,
101+ )
102+ 
103+ def __init__(
104+ self,
105+ qdata: torch.Tensor,
106+ scale: torch.Tensor,
107+ orig_shape: torch.Size,
108+ orig_dtype: torch.dtype,
109+ weight_only: bool,
110+ block_size: int = 32,
111+ ):
112+ super().__init__()
113+ orig_shape = torch.Size(orig_shape)
114+ block_size = int(block_size)
115+ _validate_packed(qdata, scale, orig_shape, bool(weight_only), block_size, ndim=2)
116+ self.qdata = qdata
117+ self.scale = scale
118+ self.orig_shape = orig_shape
119+ self.orig_dtype = orig_dtype
120+ self.weight_only = bool(weight_only)
121+ self.block_size = block_size
122+ 
123+ @classmethod
124+ def from_packed(
125+ cls,
126+ qdata: torch.Tensor,
127+ scale: torch.Tensor,
128+ orig_shape: torch.Size,
129+ orig_dtype: torch.dtype,
130+ weight_only: bool,
131+ block_size: int = 32,
132+ ) -> "MXFP8DenseTensor":
133+ """Validate and wrap existing packed data without requantizing."""
134+ return cls(qdata, scale, orig_shape, orig_dtype, weight_only, block_size)
135+ 
136+ def __repr__(self) -> str:
137+ return (
138+ f"{type(self).__name__}(orig_shape={tuple(self.orig_shape)}, "
139+ f"orig_dtype={self.orig_dtype}, weight_only={self.weight_only}, "
140+ f"block_size={self.block_size})")
141+ 
142+ 
143+class MXFP8GMMTensor(TorchAOBaseTensor):
144+ """Logical ``[E, N, K]`` expert projection stored as a uint8 MXFP8 pair.
145+ 
146+ One instance carries ONE projection (``gate_up_proj`` [E, 2I, H] or
147+ ``down_proj`` [E, H, I]); a MoE layer's state has two entries.
148+ """
149+ 
150+ tensor_data_names = ["qdata", "scale"]
151+ tensor_attribute_names = ["orig_shape", "orig_dtype", "weight_only", "block_size"]
152+ 
153+ def __new__(
154+ cls,
155+ qdata: torch.Tensor,
156+ scale: torch.Tensor,
157+ orig_shape: torch.Size,
158+ orig_dtype: torch.dtype,
159+ weight_only: bool,
160+ block_size: int = 32,
161+ ) -> "MXFP8GMMTensor":
162+ return torch.Tensor._make_wrapper_subclass(
163+ cls,
164+ torch.Size(orig_shape),
165+ dtype=orig_dtype,
166+ device=qdata.device,
167+ requires_grad=False,
168+ )
169+ 
170+ def __init__(
171+ self,
172+ qdata: torch.Tensor,
173+ scale: torch.Tensor,
174+ orig_shape: torch.Size,
175+ orig_dtype: torch.dtype,
176+ weight_only: bool,
177+ block_size: int = 32,
178+ ):
179+ super().__init__()
180+ orig_shape = torch.Size(orig_shape)
181+ block_size = int(block_size)
182+ _validate_packed(qdata, scale, orig_shape, bool(weight_only), block_size, ndim=3)
183+ self.qdata = qdata
184+ self.scale = scale
185+ self.orig_shape = orig_shape
186+ self.orig_dtype = orig_dtype
187+ self.weight_only = bool(weight_only)
188+ self.block_size = block_size
189+ 
190+ @classmethod
191+ def from_packed(
192+ cls,
193+ qdata: torch.Tensor,
194+ scale: torch.Tensor,
195+ orig_shape: torch.Size,
196+ orig_dtype: torch.dtype,
197+ weight_only: bool,
198+ block_size: int = 32,
199+ ) -> "MXFP8GMMTensor":
200+ """Validate and wrap existing packed data without requantizing."""
201+ return cls(qdata, scale, orig_shape, orig_dtype, weight_only, block_size)
202+ 
203+ def __repr__(self) -> str:
204+ return (
205+ f"{type(self).__name__}(orig_shape={tuple(self.orig_shape)}, "
206+ f"orig_dtype={self.orig_dtype}, weight_only={self.weight_only}, "
207+ f"block_size={self.block_size})")
208+ 
209+ 
210+# Serialization registration (idempotent per class name; mirrors W4A16).
211+register_safetensors_tensor_subclass(MXFP8DenseTensor)
212+register_safetensors_tensor_subclass(MXFP8GMMTensor)
213+torch.serialization.add_safe_globals([MXFP8DenseTensor, MXFP8GMMTensor])
@@ -2,16 +2,20 @@
2 2 
3"""MXFP8 QAT: MXFP8-grid weights (W8A16) or weights + activations (W8A8).3"""MXFP8 QAT: MXFP8-grid weights (W8A16) or weights + activations (W8A8).
4 4 
5-File layout: ``config.py`` (config + handler) / ``mxfp8_fake_quantization.py``5+File layout: ``config.py`` (prepare-only configs + handlers) /
6-(Q→D/STE autograd Function) / ``gmm.py`` (BF16 grouped GEMM, routing,6+``mxfp8_fake_quantization.py`` (Q→D/STE autograd Function) / ``gmm.py``
7-``MXFP8GMMQAT`` module class, w8a16/w8a8 expert compute wrappers) /7+(BF16 grouped GEMM, routing, ``MXFP8GMMQAT`` module class,
8-``linear.py`` (dense Linear carrier, ``MXFP8LinearQAT``) / ``filters.py``.8+w8a16/w8a8 expert compute wrappers) / ``linear.py`` (dense Linear carrier,
9+``MXFP8LinearQAT``) / ``filters.py`` / ``weight_conversion.py``
10+(checkpoint convert: ``pack_checkpoint_weights`` + the packed-storage
11+quantize core).
9 12 
10Workflow::13Workflow::
11 14 
12 from torchao.quantization import quantize_15 from torchao.quantization import quantize_
13 from torchao_ascend.features.qat.mxfp8_qat import (16 from torchao_ascend.features.qat.mxfp8_qat import (
14 MXFP8LinearQATConfig, MXFP8GMMQATConfig, mxfp8_linear_qat_filter_fn,17 MXFP8LinearQATConfig, MXFP8GMMQATConfig, mxfp8_linear_qat_filter_fn,
18+ pack_checkpoint_weights,
15 )19 )
16 20 
17 linear_cfg = MXFP8LinearQATConfig(block_size=32, weight_only=False)21 linear_cfg = MXFP8LinearQATConfig(block_size=32, weight_only=False)
@@ -19,6 +23,10 @@ Workflow::
19 gmm_cfg = MXFP8GMMQATConfig.from_linear(linear_cfg)23 gmm_cfg = MXFP8GMMQATConfig.from_linear(linear_cfg)
20 quantize_(model, gmm_cfg, filter_fn=mxfp8_gmm_qat_filter_fn(gmm_cfg))24 quantize_(model, gmm_cfg, filter_fn=mxfp8_gmm_qat_filter_fn(gmm_cfg))
21 train_loop(model)25 train_loop(model)
26+ state = {k: v.detach().cpu() for k, v in model.state_dict().items()}
27+ pack_checkpoint_weights(state, model=model,
28+ dense_names=[...], expert_names=[...], device=npu)
29+ # state now holds serializable MXFP8 inference weight tensors; save it.
22"""30"""
23from __future__ import annotations31from __future__ import annotations
24 32 
@@ -30,7 +38,6 @@ from .filters import (
30)38)
31from .gmm import (39from .gmm import (
32 MXFP8GMMQAT,40 MXFP8GMMQAT,
33- convert_w8a8_gmm_qat_,
34 is_experts_container,41 is_experts_container,
35 reshape_for_gmm,42 reshape_for_gmm,
36 w8a16_experts_forward,43 w8a16_experts_forward,
@@ -40,11 +47,10 @@ from .gmm import (
40from .linear import (47from .linear import (
41 MXFP8FakeQuantization,48 MXFP8FakeQuantization,
42 MXFP8LinearQAT,49 MXFP8LinearQAT,
43- convert_mxfp8_linear_qat_,
44- is_mxfp8_linear_frozen,
45 mxfp8_fake_quant,50 mxfp8_fake_quant,
46 prepare_mxfp8_linear_qat_,51 prepare_mxfp8_linear_qat_,
47)52)
53+from .weight_conversion import pack_checkpoint_weights
48 54 
49__all__ = [55__all__ = [
50 "MXFP8FakeQuantization",56 "MXFP8FakeQuantization",
@@ -52,14 +58,12 @@ __all__ = [
52 "MXFP8GMMQATConfig",58 "MXFP8GMMQATConfig",
53 "MXFP8LinearQAT",59 "MXFP8LinearQAT",
54 "MXFP8LinearQATConfig",60 "MXFP8LinearQATConfig",
55- "convert_mxfp8_linear_qat_",
56- "convert_w8a8_gmm_qat_",
57 "is_experts_container",61 "is_experts_container",
58- "is_mxfp8_linear_frozen",
59 "module_name_match",62 "module_name_match",
60 "mxfp8_fake_quant",63 "mxfp8_fake_quant",
61 "mxfp8_gmm_qat_filter_fn",64 "mxfp8_gmm_qat_filter_fn",
62 "mxfp8_linear_qat_filter_fn",65 "mxfp8_linear_qat_filter_fn",
66+ "pack_checkpoint_weights",
63 "prepare_mxfp8_linear_qat_",67 "prepare_mxfp8_linear_qat_",
64 "reshape_for_gmm",68 "reshape_for_gmm",
65 "w8a16_experts_forward",69 "w8a16_experts_forward",
Mtorchao_ascend/features/qat/mxfp8_qat/config.py+21-23File content is under review, please try again later
@@ -21,7 +21,6 @@ __all__ = [
21 "BF16GroupedMMFunction",21 "BF16GroupedMMFunction",
22 "MXFP8GMMQAT",22 "MXFP8GMMQAT",
23 "bf16_grouped_matmul",23 "bf16_grouped_matmul",
24- "convert_w8a8_gmm_qat_",
25 "is_experts_container",24 "is_experts_container",
26 "mxfp8_experts_forward",25 "mxfp8_experts_forward",
27 "reshape_for_gmm",26 "reshape_for_gmm",
@@ -386,12 +385,3 @@ def w8a8_experts_forward(
386 385 
387# Backward-compatible alias for the shared BF16 grouped GEMM.386# Backward-compatible alias for the shared BF16 grouped GEMM.
388w8a16_grouped_matmul = bf16_grouped_matmul387w8a16_grouped_matmul = bf16_grouped_matmul
389- 
390- 
391-def convert_w8a8_gmm_qat_(module: nn.Module, *, block_size: int = 32) -> nn.Module:
392- """Convert step for W8A8 GMM QAT (not yet implemented)."""
393- raise NotImplementedError(
394- "W8A8 GMM QAT convert is not yet supported: the MXFP8 grouped-GEMM "
395- "inference path is not implemented. The module remains in the QAT "
396- "prepared state (MXFP8GMMQAT with BF16 master weights)."
397- )
@@ -25,18 +25,10 @@ if TYPE_CHECKING:
25__all__ = [25__all__ = [
26 "MXFP8FakeQuantization",26 "MXFP8FakeQuantization",
27 "MXFP8LinearQAT",27 "MXFP8LinearQAT",
28- "convert_mxfp8_linear_qat_",
29- "is_mxfp8_linear_frozen",
30 "mxfp8_fake_quant",28 "mxfp8_fake_quant",
31 "prepare_mxfp8_linear_qat_",29 "prepare_mxfp8_linear_qat_",
32]30]
33 31 
34-_FROZEN = "_mxfp8_linear_frozen"
35- 
36- 
37-def is_mxfp8_linear_frozen(module: nn.Module) -> bool:
38- return bool(getattr(module, _FROZEN, False))
39- 
40 32 
41class MXFP8LinearQAT(nn.Linear):33class MXFP8LinearQAT(nn.Linear):
42 """MXFP8 QAT Linear (W8A16 / W8A8 via ``config.weight_only``, class swap).34 """MXFP8 QAT Linear (W8A16 / W8A8 via ``config.weight_only``, class swap).
@@ -92,28 +84,6 @@ class MXFP8LinearQAT(nn.Linear):
92 return y84 return y
93 85 
94 86 
95-def freeze_weight_inplace(weight: torch.Tensor, block_size: int,
96- qdim: int = -1) -> None:
97- """Write the MXFP8-grid values back into ``weight`` and freeze it.
98- 
99- DTensor-aware (writes the local shard); meta tensors skip the quantize
100- write-back but are still frozen.
101- """
102- local = weight
103- try:
104- local = weight.to_local()
105- except (AttributeError, TypeError):
106- pass
107- if local.device.type != "meta":
108- with torch.no_grad():
109- q = mxfp8_fake_quant(local, qdim=qdim, block_size=block_size)
110- if local is weight:
111- weight.data = q
112- else:
113- weight.to_local().copy_(q)
114- weight.requires_grad_(False)
115- 
116- 
117def prepare_mxfp8_linear_qat_(module: nn.Module, *,87def prepare_mxfp8_linear_qat_(module: nn.Module, *,
118 config: Optional["MXFP8LinearQATConfig"] = None,88 config: Optional["MXFP8LinearQATConfig"] = None,
119 block_size: int = 32) -> nn.Module:89 block_size: int = 32) -> nn.Module:
@@ -139,30 +109,3 @@ def prepare_mxfp8_linear_qat_(module: nn.Module, *,
139 module.block_size = block_size109 module.block_size = block_size
140 return module110 return module
141 return MXFP8LinearQAT.from_float(module, config=config, block_size=block_size)111 return MXFP8LinearQAT.from_float(module, config=config, block_size=block_size)
142- 
143- 
144-def convert_mxfp8_linear_qat_(module: nn.Module) -> nn.Module:
145- """Freeze the prepared module's weight onto the MXFP8 grid (convert step).
146- 
147- In-place by design: the class is NOT swapped back — the frozen weight is
148- already on-grid, so the online fake quant in :meth:`MXFP8LinearQAT.forward`
149- is idempotent and numerically a no-op. Requires a prepared
150- (``MXFP8LinearQAT``) module.
151- 
152- The weight is frozen using ``module.block_size`` (the block size the
153- forward path actually quantizes on); the block size cannot be overridden
154- here — re-prepare the module with the desired ``block_size`` instead.
155- Repeated calls are no-ops once the module is frozen. After convert, W8A8
156- forward still applies online FQ to new activations; the frozen weight
157- keeps online weight FQ idempotent.
158- """
159- if not isinstance(module, MXFP8LinearQAT):
160- raise TypeError(
161- "MXFP8 Linear QAT convert targets a prepared MXFP8LinearQAT; got "
162- f"{type(module).__name__}. Run prepare (step='prepare') first."
163- )
164- if is_mxfp8_linear_frozen(module):
165- return module
166- freeze_weight_inplace(module.weight, module.block_size, qdim=-1)
167- setattr(module, _FROZEN, True)
168- return module
Mtorchao_ascend/features/qat/mxfp8_qat/mxfp8_fake_quantization.py+58-10File content is under review, please try again later
Atorchao_ascend/features/qat/mxfp8_qat/weight_conversion.py+370-0File content is under review, please try again later