Merged
test: QAT FP8 整改用例(切片 2/9) #202
zhaiyaxing001Add on 1 day ago
test: QAT FP8 整改用例(切片 2/9) #202
Merged
Merged fromzhaiyaxing001/torchao_npuqat/pr2intoAscend/torchao-ascendmain
Total: 1 files changed+92-48
| @@ -5,26 +5,21 @@ | |||
| 5 | # This source code is licensed under the BSD 3-Clause license found in the | 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. | 6 | # LICENSE file in the root directory of this source tree. |
| 7 | 7 | ||
| 8 | -# -*- coding: utf-8 -*- | 8 | +"""QAT (quantization-aware training) NPU tests. Two groups of cases: |
| 9 | -"""QAT(量化感知训练)NPU 测试。 | ||
| 10 | 9 | ||
| 11 | -本文件包含两组用例: | 10 | +1. Upstream adapted migration (``TestQATUpstreamAdapted``): upstream |
| 11 | + ``torchao/test/quantization/test_qat.py`` cases adapted for NPU; method | ||
| 12 | + names and thresholds match upstream, docstrings note each adaptation. | ||
| 13 | +2. NPU scenario additions (``TestFP8QATNPU`` / ``TestInt8QATNPU`` / | ||
| 14 | + ``TestInt4QATNPU`` / ``TestIntxQATNPU``): greenlight-workflow coverage | ||
| 15 | + with no upstream counterpart. | ||
| 12 | 16 | ||
| 13 | -1. 上游整改迁移(``TestQATUpstreamAdapted``):上游 | 17 | +Cases passing on NPU unmodified run in the upstream torchao suite (CI |
| 14 | - ``torchao/test/quantization/test_qat.py`` 中在 NPU 基线未通过(或因生产缺口 | 18 | +whitelist, pending wiring). MX cases set kernel_preference=KernelPreference.NPU |
| 15 | - 被跳过)、经适配后可在 NPU 通过的用例。方法名与上游保持一致,各 docstring | 19 | +(in-place extension of the upstream enum: native torch_npu kernel, no emulation |
| 16 | - 注明上游来源与适配内容。 | 20 | +fallback); without the operator surface they fail directly (no capability-probe |
| 17 | -2. NPU 场景补充(``TestFP8QATNPU`` / ``TestInt8QATNPU`` / ``TestInt4QATNPU`` / | 21 | +skips, per review consensus). Device-bound cases live here, device-agnostic |
| 18 | - ``TestIntxQATNPU``):绿灯工作流方案定义、上游无对应的场景覆盖。 | 22 | +ones in ``test_qat_cpu.py``. |
| 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 | """ | 23 | """ |
| 29 | 24 | ||
| 30 | 25 | ||
| @@ -40,7 +35,17 @@ from torch.testing._internal.common_utils import ( | |||
| 40 | ) | 35 | ) |
| 41 | from torchao.core.config import AOBaseConfig | 36 | from torchao.core.config import AOBaseConfig |
| 42 | from torchao.quantization import Float8Tensor, quantize_ | 37 | from torchao.quantization import Float8Tensor, quantize_ |
| 38 | +from torchao.quantization.granularity import Granularity, PerRow, PerTensor | ||
| 43 | from torchao.quantization.qat import QATConfig | 39 | from torchao.quantization.qat import QATConfig |
| 40 | +from torchao.quantization.qat.fake_quantize_config import ( | ||
| 41 | + Float8FakeQuantizeConfig, | ||
| 42 | + Int4WeightFakeQuantizeConfig, | ||
| 43 | +) | ||
| 44 | +from torchao.quantization.qat.fake_quantizer import ( | ||
| 45 | + Float8FakeQuantizer, | ||
| 46 | + Int4WeightFakeQuantizer, | ||
| 47 | +) | ||
| 48 | +from torchao.quantization.quant_api import Float8DynamicActivationFloat8WeightConfig | ||
| 44 | from torchao.quantization.quantize_.common import KernelPreference | 49 | from torchao.quantization.quantize_.common import KernelPreference |
| 45 | from torchao.quantization.utils import compute_error | 50 | from torchao.quantization.utils import compute_error |
| 46 | from torch_npu.testing.testcase import TestCase, run_tests | 51 | from torch_npu.testing.testcase import TestCase, run_tests |
| @@ -49,13 +54,11 @@ from torch_npu.testing.testcase import TestCase, run_tests | |||
| 49 | _FP8_DTYPE = torch.float8_e4m3fn | 54 | _FP8_DTYPE = torch.float8_e4m3fn |
| 50 | _FP8_MAX = torch.finfo(_FP8_DTYPE).max | 55 | _FP8_MAX = torch.finfo(_FP8_DTYPE).max |
| 51 | 56 | ||
| 52 | -# 实现与独立参考公式一致,阈值取紧;梯度经 STE,阈值适度放宽 | 57 | +# Tight thresholds (same formula as the standalone reference); looser for STE grads |
| 53 | _OUT_SQNR = 30 | 58 | _OUT_SQNR = 30 |
| 54 | _GRAD_SQNR = 20 | 59 | _GRAD_SQNR = 20 |
| 55 | -# 整层组合反向:被测实现的量化链路使用预计算倒数(input * (1.0/scale))及 | 60 | +# Whole-layer backward: impl uses precomputed reciprocals + fixed op order, so the |
| 56 | -# 特定算子次序,独立参考在组合反向存在与设备无关的小差异(同场景 CPU 实测 | 61 | +# standalone reference deviates slightly (device-independent, ~23dB CPU / ~18dB NPU). |
| 57 | -# 约 23dB、NPU 约 18dB);前向输出逐位一致、孤立假量化反向已按"掩码 STE" | ||
| 58 | -# 逐位对齐,故整层梯度阈值取 15。 | ||
| 59 | _LAYER_GRAD_SQNR = 15 | 62 | _LAYER_GRAD_SQNR = 15 |
| 60 | 63 | ||
| 61 | 64 | ||
| @@ -69,7 +72,7 @@ class _Sub(nn.Module): | |||
| 69 | 72 | ||
| 70 | 73 | ||
| 71 | class _M(nn.Module): | 74 | class _M(nn.Module): |
| 72 | - """对齐上游 test_qat.py 的 M:三层无 bias Linear(PTQ 对照用)。""" | 75 | + """Mirrors upstream test_qat.py model M: three bias-free Linear layers (PTQ baseline).""" |
| 73 | 76 | ||
| 74 | def __init__(self): | 77 | def __init__(self): |
| 75 | super().__init__() | 78 | super().__init__() |
| @@ -85,12 +88,7 @@ class _M(nn.Module): | |||
| 85 | 88 | ||
| 86 | 89 | ||
| 87 | class TestQATUpstreamAdapted(TestCase): | 90 | class TestQATUpstreamAdapted(TestCase): |
| 88 | - """上游 ``torchao/test/quantization/test_qat.py`` 用例的 NPU 整改迁移。 | 91 | + """NPU adapted migration of upstream torchao test_qat.py; docstrings record each adaptation.""" |
| 89 | - | ||
| 90 | - 方法名与上游保持一致;各 docstring 注明上游来源与适配内容(设备解析、 | ||
| 91 | - kernel_preference=NPU 原生路由,或因上游 mslk/tinygemm 算子面不可用而收敛的 | ||
| 92 | - 降级路线)。 | ||
| 93 | - """ | ||
| 94 | SEED = 123 | 92 | SEED = 123 |
| 95 | 93 | ||
| 96 | def setUp(self): | 94 | def setUp(self): |
| @@ -105,7 +103,7 @@ class TestQATUpstreamAdapted(TestCase): | |||
| 105 | target_convert_sqnr: float, | 103 | target_convert_sqnr: float, |
| 106 | dtype: torch.dtype = torch.bfloat16, | 104 | dtype: torch.dtype = torch.bfloat16, |
| 107 | ): | 105 | ): |
| 108 | - """prepare/convert 输出对照 PTQ 基线(对齐上游同名 helper,设备 NPU)。""" | 106 | + """prepare/convert outputs vs the PTQ baseline (mirrors the upstream helper, device NPU).""" |
| 109 | torch.manual_seed(0) | 107 | torch.manual_seed(0) |
| 110 | m = _M().to(dtype).to(self.device) | 108 | m = _M().to(dtype).to(self.device) |
| 111 | example_inputs = (m.example_inputs()[0].to(dtype).to(self.device),) | 109 | example_inputs = (m.example_inputs()[0].to(dtype).to(self.device),) |
| @@ -128,10 +126,17 @@ class TestQATUpstreamAdapted(TestCase): | |||
| 128 | ) | 126 | ) |
| 129 | return m | 127 | return m |
| 130 | 128 | ||
| 131 | - # ------------------------------------------------------------------ | 129 | + @parametrize("granularity", [PerTensor(), PerRow()]) |
| 132 | - # MX QAT(上游 CUDA 门控系列:设备 NPU + kernel_preference=NPU 原生路由; | 130 | + def test_quantize_api_fp8_fp8(self, granularity: Granularity): |
| 133 | - # 依赖 torchao_ascend 的 MX NPU 分支) | 131 | + """Upstream ``test_quantize_api_fp8_fp8``: device NPU, sm89/MI300 gates removed, |
| 134 | - # ------------------------------------------------------------------ | 132 | + subTest reorganized as parametrize; prepare SQNR>=15, convert bit-exact.""" |
| 133 | + m = self._test_quantize_api_against_ptq( | ||
| 134 | + Float8DynamicActivationFloat8WeightConfig(granularity=granularity), | ||
| 135 | + target_prepare_sqnr=15, | ||
| 136 | + target_convert_sqnr=float("inf"), | ||
| 137 | + ) | ||
| 138 | + for lin in (m.linear1, m.linear2, m.sub.linear): | ||
| 139 | + self.assertIsInstance(lin.weight, Float8Tensor) | ||
| 135 | 140 | ||
| 136 | @parametrize("bias", [True, False]) | 141 | @parametrize("bias", [True, False]) |
| 137 | @parametrize("input_shape", [(128, 256), (1, 128, 256), (2, 4, 128, 256)]) | 142 | @parametrize("input_shape", [(128, 256), (1, 128, 256), (2, 4, 128, 256)]) |
| @@ -140,9 +145,8 @@ class TestQATUpstreamAdapted(TestCase): | |||
| 140 | [torch.float4_e2m1fn_x2, torch.float8_e4m3fn, torch.float8_e5m2], | 145 | [torch.float4_e2m1fn_x2, torch.float8_e4m3fn, torch.float8_e5m2], |
| 141 | ) | 146 | ) |
| 142 | def test_mx_fake_quantized_linear_forward(self, bias, input_shape, dtype): | 147 | def test_mx_fake_quantized_linear_forward(self, bias, input_shape, dtype): |
| 143 | - """上游 ``test_mx_fake_quantized_linear_forward`` 整改迁移:设备 NPU + | 148 | + """Upstream ``test_mx_fake_quantized_linear_forward``: device NPU + |
| 144 | - kernel_preference=NPU(torch_npu 原生 MX kernel,无仿真回退)。 | 149 | + kernel_preference=NPU; SQNR thresholds match upstream (fp4>=5, fp8>=10).""" |
| 145 | - SQNR 阈值与上游一致(fp4 ≥ 5,fp8 ≥ 10)。""" | ||
| 146 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear | 150 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear |
| 147 | 151 | ||
| 148 | K, N = 256, 128 | 152 | K, N = 256, 128 |
| @@ -184,8 +188,8 @@ class TestQATUpstreamAdapted(TestCase): | |||
| 184 | 188 | ||
| 185 | @parametrize("bias", [True, False]) | 189 | @parametrize("bias", [True, False]) |
| 186 | def test_mx_fake_quantized_linear_backward(self, bias): | 190 | def test_mx_fake_quantized_linear_backward(self, bias): |
| 187 | - """上游 ``test_mx_fake_quantized_linear_backward`` 整改迁移:设备 NPU + | 191 | + """Upstream ``test_mx_fake_quantized_linear_backward``: device NPU + |
| 188 | - kernel_preference=NPU。梯度形状与 SQNR 检查与上游一致。""" | 192 | + kernel_preference=NPU; gradient shape/SQNR checks match upstream.""" |
| 189 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear | 193 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear |
| 190 | 194 | ||
| 191 | M, K, N = 128, 256, 128 | 195 | M, K, N = 128, 256, 128 |
| @@ -240,8 +244,7 @@ class TestQATUpstreamAdapted(TestCase): | |||
| 240 | self.assertGreaterEqual(w_grad_sqnr, 3.0) | 244 | self.assertGreaterEqual(w_grad_sqnr, 3.0) |
| 241 | 245 | ||
| 242 | def test_mx_fake_quantized_linear_to_linear(self): | 246 | def test_mx_fake_quantized_linear_to_linear(self): |
| 243 | - """上游 ``test_mx_fake_quantized_linear_to_linear`` 整改迁移:设备 NPU + | 247 | + """Upstream ``test_mx_fake_quantized_linear_to_linear``: device NPU + kernel_preference=NPU.""" |
| 244 | - kernel_preference=NPU。""" | ||
| 245 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear | 248 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear |
| 246 | 249 | ||
| 247 | K, N = 256, 128 | 250 | K, N = 256, 128 |
| @@ -285,8 +288,7 @@ class TestQATUpstreamAdapted(TestCase): | |||
| 285 | ], | 288 | ], |
| 286 | ) | 289 | ) |
| 287 | def test_mx_matmul_sqnr(self, shapes): | 290 | def test_mx_matmul_sqnr(self, shapes): |
| 288 | - """上游 ``test_mx_matmul_sqnr`` 整改迁移:设备 NPU + kernel_preference=NPU; | 291 | + """Upstream ``test_mx_matmul_sqnr``: device NPU + kernel_preference=NPU. SQNR>=5, matching upstream.""" |
| 289 | - SQNR ≥ 5 与上游一致。""" | ||
| 290 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear | 292 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear |
| 291 | 293 | ||
| 292 | M, K, N = shapes | 294 | M, K, N = shapes |
| @@ -319,8 +321,7 @@ class TestQATUpstreamAdapted(TestCase): | |||
| 319 | self.assertGreaterEqual(sqnr, SQNR_THRESHOLD) | 321 | self.assertGreaterEqual(sqnr, SQNR_THRESHOLD) |
| 320 | 322 | ||
| 321 | def test_mx_training_simulation(self): | 323 | def test_mx_training_simulation(self): |
| 322 | - """上游 ``test_mx_training_simulation`` 整改迁移:设备 NPU + | 324 | + """Upstream ``test_mx_training_simulation``: device NPU + kernel_preference=NPU; asserts SGD updates weights.""" |
| 323 | - kernel_preference=NPU;验证 SGD 训练步进后权重真实更新。""" | ||
| 324 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear | 325 | from torchao.prototype.qat import MXFakeQuantizeConfig, MXFakeQuantizedLinear |
| 325 | 326 | ||
| 326 | M, K, N = 128, 256, 128 | 327 | M, K, N = 128, 256, 128 |
| @@ -372,8 +373,8 @@ class TestQATUpstreamAdapted(TestCase): | |||
| 372 | [torch.float4_e2m1fn_x2, torch.float8_e4m3fn], | 373 | [torch.float4_e2m1fn_x2, torch.float8_e4m3fn], |
| 373 | ) | 374 | ) |
| 374 | def test_quantize_api_mx(self, dtype): | 375 | def test_quantize_api_mx(self, dtype): |
| 375 | - """上游 ``test_quantize_api_mx`` 整改迁移:设备 NPU + kernel_preference=NPU; | 376 | + """Upstream ``test_quantize_api_mx``: device NPU, kernel_preference=NPU |
| 376 | - 依赖 torchao_ascend 的 MX 分发。prepare/convert SQNR 目标与上游一致(inf)。""" | 377 | + (torchao_ascend MX dispatch); SQNR targets inf.""" |
| 377 | from torchao.prototype.mx_formats import MXDynamicActivationMXWeightConfig | 378 | from torchao.prototype.mx_formats import MXDynamicActivationMXWeightConfig |
| 378 | 379 | ||
| 379 | self._test_quantize_api_against_ptq( | 380 | self._test_quantize_api_against_ptq( |
| @@ -386,6 +387,49 @@ class TestQATUpstreamAdapted(TestCase): | |||
| 386 | target_convert_sqnr=float("inf"), | 387 | target_convert_sqnr=float("inf"), |
| 387 | ) | 388 | ) |
| 388 | 389 | ||
| 390 | + @parametrize("granularity", [PerTensor(), PerRow()]) | ||
| 391 | + def test_float8_fake_quantize(self, granularity: Granularity): | ||
| 392 | + """Upstream ``test_float8_fake_quantize``: input on NPU (bf16); values vs Float8Tensor dequantize (SQNR>16).""" | ||
| 393 | + dtype = torch.float8_e4m3fn | ||
| 394 | + fq_config = Float8FakeQuantizeConfig(dtype, granularity) | ||
| 395 | + fake_quantizer = Float8FakeQuantizer(fq_config) | ||
| 396 | + torch.manual_seed(self.SEED) | ||
| 397 | + x = torch.randn(32, 64, dtype=torch.bfloat16, device=self.device) | ||
| 398 | + out = fake_quantizer(x) | ||
| 399 | + out_expected = Float8Tensor.from_hp(x, dtype, granularity).dequantize() | ||
| 400 | + sqnr = compute_error(out, out_expected) | ||
| 401 | + self.assertGreater(sqnr, 16) | ||
| 402 | + | ||
| 403 | + def test_fake_quantizer_enabled_attribute(self): | ||
| 404 | + """Upstream ``test_fake_quantizer_enabled_attribute``: Float8 input on NPU (bf16); | ||
| 405 | + Int4 path stays CPU (ATen only, device-agnostic). enabled gating for Int4/Float8.""" | ||
| 406 | + # Int4WeightFakeQuantizer: enabled gating through the bf16 activation path, ATen ops only | ||
| 407 | + int4_config = Int4WeightFakeQuantizeConfig( | ||
| 408 | + group_size=32, | ||
| 409 | + activation_dtype=torch.bfloat16, | ||
| 410 | + ) | ||
| 411 | + int4_fake_quantizer = Int4WeightFakeQuantizer(int4_config) | ||
| 412 | + self.assertTrue(int4_fake_quantizer.enabled) | ||
| 413 | + | ||
| 414 | + torch.manual_seed(self.SEED) | ||
| 415 | + w = torch.randn(64, 64, dtype=torch.bfloat16) | ||
| 416 | + | ||
| 417 | + int4_fake_quantizer.enabled = False | ||
| 418 | + torch.testing.assert_close(int4_fake_quantizer(w), w, atol=0, rtol=0) | ||
| 419 | + | ||
| 420 | + int4_fake_quantizer.enabled = True | ||
| 421 | + self.assertFalse(torch.equal(int4_fake_quantizer(w), w)) | ||
| 422 | + | ||
| 423 | + # Float8FakeQuantizer: disabled passthrough only; the enabled path | ||
| 424 | + # is covered by test_float8_fake_quantize | ||
| 425 | + float8_config = Float8FakeQuantizeConfig(torch.float8_e4m3fn, PerRow()) | ||
| 426 | + float8_fake_quantizer = Float8FakeQuantizer(float8_config) | ||
| 427 | + self.assertTrue(float8_fake_quantizer.enabled) | ||
| 428 | + | ||
| 429 | + x = torch.randn(32, 64, dtype=torch.bfloat16, device=self.device) | ||
| 430 | + float8_fake_quantizer.enabled = False | ||
| 431 | + torch.testing.assert_close(float8_fake_quantizer(x), x, atol=0, rtol=0) | ||
| 432 | + | ||
| 389 | 433 | ||
| 390 | instantiate_parametrized_tests(TestQATUpstreamAdapted) | 434 | instantiate_parametrized_tests(TestQATUpstreamAdapted) |
| 391 | 435 | ||