Merged
test: QAT MX 场景迁移与 float8 patch CPU 守卫(切片 1/9) #10
zhaiyaxing001Add on Sep 23
test: QAT MX 场景迁移与 float8 patch CPU 守卫(切片 1/9) #10
Merged
zhaiyaxing001Add on Sep 23
Total: 2 files changed+397-0
@@ -0,0 +1,394 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd
2+# Copyright (c) Meta Platforms, Inc. and affiliates.
3+# All rights reserved.
4+#
5+# This source code is licensed under the BSD 3-Clause license found in the
6+# LICENSE file in the root directory of this source tree.
7+ 
8+# -*- coding: utf-8 -*-
9+"""QAT(量化感知训练)NPU 测试。
10+ 
11+本文件包含两组用例:
12+ 
13+1. 上游整改迁移(``TestQATUpstreamAdapted``):上游
14+ ``torchao/test/quantization/test_qat.py`` 中在 NPU 基线未通过(或因生产缺口
15+ 被跳过)、经适配后可在 NPU 通过的用例。方法名与上游保持一致,各 docstring
16+ 注明上游来源与适配内容。
17+2. NPU 场景补充(``TestFP8QATNPU`` / ``TestInt8QATNPU`` / ``TestInt4QATNPU`` /
18+ ``TestIntxQATNPU``):绿灯工作流方案定义、上游无对应的场景覆盖。
19+ 
20+上游在 NPU 上原样通过的用例不在本仓重复维护,由上游 torchao 测试套件直接执行
21+(CI 白名单机制,待接入)。
22+ 
23+kernel 路由:MX 整改用例统一 ``kernel_preference=KernelPreference.NPU``(本仓对
24+上游枚举的就地扩展成员:强制 torch_npu 原生 kernel、无仿真回退),假量化前向经
25+真实 MX matmul 执行;不具备对应算子面的硬件上用例直接失败(不做设备能力探测
26+跳过——探测无法区分硬件不支持与环境故障,检视共识移除)。设备绑定的用例在本
27+文件,设备无关的用例在 ``test_qat_cpu.py``。
28+"""
29+ 
30+ 
31+from __future__ import annotations
32+import copy
33+import torch
34+import torch.nn as nn
35+import torch_npu # noqa: F401 -- register the NPU backend
36+import torchao_ascend # noqa: F401 -- enable TorchAO NPU patches
37+from torch.testing._internal.common_utils import (
38+ instantiate_parametrized_tests,
39+ parametrize,
40+)
41+from torchao.core.config import AOBaseConfig
42+from torchao.quantization import Float8Tensor, quantize_
43+from torchao.quantization.qat import QATConfig
44+from torchao.quantization.quantize_.common import KernelPreference
45+from torchao.quantization.utils import compute_error
46+from torch_npu.testing.testcase import TestCase, run_tests
47+ 
48+ 
49+_FP8_DTYPE = torch.float8_e4m3fn
50+_FP8_MAX = torch.finfo(_FP8_DTYPE).max
51+ 
52+# 实现与独立参考公式一致,阈值取紧;梯度经 STE,阈值适度放宽
53+_OUT_SQNR = 30
54+_GRAD_SQNR = 20
55+# 整层组合反向:被测实现的量化链路使用预计算倒数(input * (1.0/scale))及
56+# 特定算子次序,独立参考在组合反向存在与设备无关的小差异(同场景 CPU 实测
57+# 约 23dB、NPU 约 18dB);前向输出逐位一致、孤立假量化反向已按"掩码 STE"
58+# 逐位对齐,故整层梯度阈值取 15。
59+_LAYER_GRAD_SQNR = 15
60+ 
61+ 
62+class _Sub(nn.Module):
63+ def __init__(self):
64+ super().__init__()
65+ self.linear = nn.Linear(256, 256, bias=False)
66+ 
67+ def forward(self, x):
68+ return self.linear(x)
69+ 
70+ 
71+class _M(nn.Module):
72+ """对齐上游 test_qat.py 的 M:三层无 bias Linear(PTQ 对照用)。"""
73+ 
74+ def __init__(self):
75+ super().__init__()
76+ self.linear1 = nn.Linear(512, 256, bias=False)
77+ self.sub = _Sub()
78+ self.linear2 = nn.Linear(256, 512, bias=False)
79+ 
80+ def example_inputs(self, device=None, dtype=torch.bfloat16):
81+ return (torch.randn(1, 512, dtype=torch.float32).to(dtype).to(device),)
82+ 
83+ def forward(self, x):
84+ return self.linear2(self.sub(self.linear1(x)))
85+ 
86+ 
87+class TestQATUpstreamAdapted(TestCase):
88+ """上游 ``torchao/test/quantization/test_qat.py`` 用例的 NPU 整改迁移。
89+ 
90+ 方法名与上游保持一致;各 docstring 注明上游来源与适配内容(设备解析、
91+ kernel_preference=NPU 原生路由,或因上游 mslk/tinygemm 算子面不可用而收敛的
92+ 降级路线)。
93+ """
94+ SEED = 123
95+ 
96+ def setUp(self):
97+ super().setUp()
98+ self.device = torch.device(torch._C._get_privateuse1_backend_name())
99+ self.assertEqual(self.device.type, "npu")
100+ 
101+ def _test_quantize_api_against_ptq(
102+ self,
103+ base_config: AOBaseConfig,
104+ target_prepare_sqnr: float,
105+ target_convert_sqnr: float,
106+ dtype: torch.dtype = torch.bfloat16,
107+ ):
108+ """prepare/convert 输出对照 PTQ 基线(对齐上游同名 helper,设备 NPU)。"""
109+ torch.manual_seed(0)
110+ m = _M().to(dtype).to(self.device)
111+ example_inputs = (m.example_inputs()[0].to(dtype).to(self.device),)
112+ filter_fn = lambda mod, fqn: isinstance(mod, nn.Linear) # noqa: E731
113+ 
114+ m_baseline = copy.deepcopy(m)
115+ quantize_(m_baseline, base_config, filter_fn)
116+ out_baseline = m_baseline(*example_inputs)
117+ 
118+ quantize_(m, QATConfig(base_config, step="prepare"), filter_fn)
119+ out_prepared = m(*example_inputs)
120+ self.assertGreaterEqual(
121+ compute_error(out_prepared, out_baseline), target_prepare_sqnr
122+ )
123+ 
124+ quantize_(m, QATConfig(base_config, step="convert"), filter_fn)
125+ out_converted = m(*example_inputs)
126+ self.assertGreaterEqual(
127+ compute_error(out_converted, out_baseline), target_convert_sqnr
128+ )
129+ return m
130+ 
131+ # ------------------------------------------------------------------
132+ # MX QAT(上游 CUDA 门控系列:设备 NPU + kernel_preference=NPU 原生路由;
133+ # 依赖 torchao_ascend 的 MX NPU 分支)
134+ # ------------------------------------------------------------------
135+ 
136+ @parametrize("bias", [True, False])
137+ @parametrize("input_shape", [(128, 256), (1, 128, 256), (2, 4, 128, 256)])
138+ @parametrize(
139+ "dtype",
140+ [torch.float4_e2m1fn_x2, torch.float8_e4m3fn, torch.float8_e5m2],
141+ )
142+ def test_mx_fake_quantized_linear_forward(self, bias, input_shape, dtype):
143+ """上游 ``test_mx_fake_quantized_linear_forward`` 整改迁移:设备 NPU +
144+ kernel_preference=NPU(torch_npu 原生 MX kernel,无仿真回退)。
145+ SQNR 阈值与上游一致(fp4 ≥ 5,fp8 ≥ 10)。"""
146+ from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear
147+ 
148+ K, N = 256, 128
149+ 
150+ activation_config = MXFakeQuantizeConfig(
151+ dtype=dtype,
152+ block_size=32,
153+ kernel_preference=KernelPreference.NPU,
154+ )
155+ weight_config = MXFakeQuantizeConfig(
156+ dtype=dtype,
157+ block_size=32,
158+ kernel_preference=KernelPreference.NPU,
159+ )
160+ 
161+ linear = torch.nn.Linear(
162+ K, N, bias=bias, device=self.device, dtype=torch.bfloat16
163+ )
164+ mx_linear = MXFakeQuantizedLinear.from_linear(
165+ linear,
166+ activation_config=activation_config,
167+ weight_config=weight_config,
168+ )
169+ 
170+ x = torch.randn(*input_shape, device=self.device, dtype=torch.bfloat16)
171+ y_ref = linear(x)
172+ y_mx = mx_linear(x)
173+ 
174+ self.assertEqual(y_mx.shape, y_ref.shape)
175+ self.assertEqual(y_mx.dtype, y_ref.dtype)
176+ 
177+ # Check SQNR - MXFP4 has lower precision so use lower threshold
178+ # MXFP8 has higher precision
179+ sqnr = compute_error(y_ref, y_mx)
180+ if dtype == torch.float4_e2m1fn_x2:
181+ self.assertGreaterEqual(sqnr, 5.0)
182+ else:
183+ self.assertGreaterEqual(sqnr, 10.0)
184+ 
185+ @parametrize("bias", [True, False])
186+ def test_mx_fake_quantized_linear_backward(self, bias):
187+ """上游 ``test_mx_fake_quantized_linear_backward`` 整改迁移:设备 NPU +
188+ kernel_preference=NPU。梯度形状与 SQNR 检查与上游一致。"""
189+ from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear
190+ 
191+ M, K, N = 128, 256, 128
192+ 
193+ activation_config = MXFakeQuantizeConfig(
194+ block_size=32,
195+ kernel_preference=KernelPreference.NPU,
196+ )
197+ weight_config = MXFakeQuantizeConfig(
198+ block_size=32,
199+ kernel_preference=KernelPreference.NPU,
200+ )
201+ 
202+ linear = torch.nn.Linear(
203+ K, N, bias=bias, device=self.device, dtype=torch.bfloat16
204+ )
205+ linear_ref = copy.deepcopy(linear)
206+ mx_linear = MXFakeQuantizedLinear.from_linear(
207+ linear,
208+ activation_config=activation_config,
209+ weight_config=weight_config,
210+ )
211+ 
212+ x_ref = torch.randn(
213+ M, K, device=self.device, dtype=torch.bfloat16, requires_grad=True
214+ )
215+ x = x_ref.clone().detach().requires_grad_(True)
216+ grad_output = torch.randn(M, N, device=self.device, dtype=torch.bfloat16)
217+ 
218+ # Forward and backward for reference
219+ y_ref = linear_ref(x_ref)
220+ y_ref.backward(grad_output)
221+ 
222+ # Forward and backward for MX
223+ y_mx = mx_linear(x)
224+ y_mx.backward(grad_output)
225+ 
226+ # Check that gradients are computed
227+ self.assertIsNotNone(x.grad)
228+ self.assertIsNotNone(mx_linear.weight.grad)
229+ 
230+ # Check gradient shapes
231+ self.assertEqual(x.grad.shape, x_ref.grad.shape)
232+ self.assertEqual(mx_linear.weight.grad.shape, linear_ref.weight.grad.shape)
233+ 
234+ # Check gradient SQNR (expect lower due to quantization)
235+ x_grad_sqnr = compute_error(x_ref.grad, x.grad)
236+ w_grad_sqnr = compute_error(linear_ref.weight.grad, mx_linear.weight.grad)
237+ 
238+ # Lower threshold for gradients due to quantization effects
239+ self.assertGreaterEqual(x_grad_sqnr, 3.0)
240+ self.assertGreaterEqual(w_grad_sqnr, 3.0)
241+ 
242+ def test_mx_fake_quantized_linear_to_linear(self):
243+ """上游 ``test_mx_fake_quantized_linear_to_linear`` 整改迁移:设备 NPU +
244+ kernel_preference=NPU。"""
245+ from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear
246+ 
247+ K, N = 256, 128
248+ 
249+ activation_config = MXFakeQuantizeConfig(
250+ block_size=32,
251+ kernel_preference=KernelPreference.NPU,
252+ )
253+ weight_config = MXFakeQuantizeConfig(
254+ block_size=32,
255+ kernel_preference=KernelPreference.NPU,
256+ )
257+ 
258+ original_linear = torch.nn.Linear(
259+ K, N, bias=True, device=self.device, dtype=torch.bfloat16
260+ )
261+ mx_linear = MXFakeQuantizedLinear.from_linear(
262+ original_linear,
263+ activation_config=activation_config,
264+ weight_config=weight_config,
265+ )
266+ 
267+ # Convert back to linear
268+ converted_linear = mx_linear.to_linear()
269+ 
270+ self.assertIsInstance(converted_linear, torch.nn.Linear)
271+ self.assertEqual(converted_linear.in_features, K)
272+ self.assertEqual(converted_linear.out_features, N)
273+ self.assertIsNotNone(converted_linear.bias)
274+ 
275+ # Weights should be the same
276+ torch.testing.assert_close(converted_linear.weight, mx_linear.weight)
277+ torch.testing.assert_close(converted_linear.bias, mx_linear.bias)
278+ 
279+ @parametrize(
280+ "shapes",
281+ [
282+ (128, 64, 256),
283+ (256, 128, 512),
284+ (128, 128, 128),
285+ ],
286+ )
287+ def test_mx_matmul_sqnr(self, shapes):
288+ """上游 ``test_mx_matmul_sqnr`` 整改迁移:设备 NPU + kernel_preference=NPU;
289+ SQNR ≥ 5 与上游一致。"""
290+ from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear
291+ 
292+ M, K, N = shapes
293+ 
294+ activation_config = MXFakeQuantizeConfig(
295+ block_size=32,
296+ kernel_preference=KernelPreference.NPU,
297+ )
298+ weight_config = MXFakeQuantizeConfig(
299+ block_size=32,
300+ kernel_preference=KernelPreference.NPU,
301+ )
302+ 
303+ linear = torch.nn.Linear(
304+ K, N, bias=False, device=self.device, dtype=torch.bfloat16
305+ )
306+ mx_linear = MXFakeQuantizedLinear.from_linear(
307+ linear,
308+ activation_config=activation_config,
309+ weight_config=weight_config,
310+ )
311+ 
312+ x = torch.randn(M, K, device=self.device, dtype=torch.bfloat16)
313+ y_ref = linear(x)
314+ y_mx = mx_linear(x)
315+ 
316+ sqnr = compute_error(y_ref, y_mx)
317+ SQNR_THRESHOLD = 5.0 # Lower threshold for MX
318+ 
319+ self.assertGreaterEqual(sqnr, SQNR_THRESHOLD)
320+ 
321+ def test_mx_training_simulation(self):
322+ """上游 ``test_mx_training_simulation`` 整改迁移:设备 NPU +
323+ kernel_preference=NPU;验证 SGD 训练步进后权重真实更新。"""
324+ from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear
325+ 
326+ M, K, N = 128, 256, 128
327+ num_steps = 5
328+ 
329+ activation_config = MXFakeQuantizeConfig(
330+ block_size=32,
331+ kernel_preference=KernelPreference.NPU,
332+ )
333+ weight_config = MXFakeQuantizeConfig(
334+ block_size=32,
335+ kernel_preference=KernelPreference.NPU,
336+ )
337+ 
338+ model = torch.nn.Sequential(
339+ torch.nn.Linear(K, N, bias=True, device=self.device, dtype=torch.bfloat16),
340+ )
341+ 
342+ # Convert to MX QAT
343+ mx_model = torch.nn.Sequential(
344+ MXFakeQuantizedLinear.from_linear(
345+ model[0],
346+ activation_config=activation_config,
347+ weight_config=weight_config,
348+ ),
349+ )
350+ 
351+ optimizer = torch.optim.SGD(mx_model.parameters(), lr=0.01)
352+ 
353+ # Store initial weight for comparison (must be before training loop)
354+ initial_weight = mx_model[0].weight.clone()
355+ 
356+ # Training loop
357+ for _ in range(num_steps):
358+ x = torch.randn(M, K, device=self.device, dtype=torch.bfloat16)
359+ target = torch.randn(M, N, device=self.device, dtype=torch.bfloat16)
360+ 
361+ optimizer.zero_grad()
362+ output = mx_model(x)
363+ loss = torch.nn.functional.mse_loss(output, target)
364+ loss.backward()
365+ optimizer.step()
366+ 
367+ # Check that weights have been updated
368+ self.assertFalse(torch.allclose(mx_model[0].weight, initial_weight))
369+ 
370+ @parametrize(
371+ "dtype",
372+ [torch.float4_e2m1fn_x2, torch.float8_e4m3fn],
373+ )
374+ def test_quantize_api_mx(self, dtype):
375+ """上游 ``test_quantize_api_mx`` 整改迁移:设备 NPU + kernel_preference=NPU;
376+ 依赖 torchao_ascend 的 MX 分发。prepare/convert SQNR 目标与上游一致(inf)。"""
377+ from torchao.prototype.mx_formats import MXDynamicActivationMXWeightConfig
378+ 
379+ self._test_quantize_api_against_ptq(
Kuteriod
KuteriodKuteriodOct 30

这个切片调用了 _test_quantize_api_against_ptq,但当前类及其父类没有该方法,请确认一下

likedislike
zhaiyaxing001
zhaiyaxing001
Oct 31 Comments:
likedislike
380+ MXDynamicActivationMXWeightConfig(
381+ activation_dtype=dtype,
382+ weight_dtype=dtype,
383+ kernel_preference=KernelPreference.NPU,
384+ ),
385+ target_prepare_sqnr=float("inf"),
386+ target_convert_sqnr=float("inf"),
387+ )
388+ 
389+ 
390+instantiate_parametrized_tests(TestQATUpstreamAdapted)
391+ 
392+ 
393+if __name__ == "__main__":
394+ run_tests()
@@ -44,6 +44,9 @@ def _try_npu_native_quant(
44 if hp_value_lb is not None or hp_value_ub is not None:44 if hp_value_lb is not None or hp_value_ub is not None:
45 return None45 return None
46 46 
47+ if hp_tensor.device.type != "npu":
48+ return None
49+ 
47 act_input = hp_tensor if hp_tensor.is_contiguous() else hp_tensor.contiguous()50 act_input = hp_tensor if hp_tensor.is_contiguous() else hp_tensor.contiguous()
48 51 
49 if isinstance(granularity, PerTensor):52 if isinstance(granularity, PerTensor):