Merged
add mx_fake_quantize #835
caoshuyangAdd on Sep 17
add mx_fake_quantize #835
Merged
Total: 2 files changed+143-0
| @@ -317,3 +317,82 @@ def test_mx_quantize_dual_axis_quant_matmul_matches_raw_op(elem_dtype, case_a, c | |||
| 317 | 317 | ||
| 318 | assert y.shape == y_ref.shape | 318 | assert y.shape == y_ref.shape |
| 319 | assert torch.equal(y, y_ref), "npu_quant_matmul result differs between mx_quantize_dual_axis and raw op" | 319 | assert torch.equal(y, y_ref), "npu_quant_matmul result differs between mx_quantize_dual_axis and raw op" |
| 320 | + | ||
| 321 | + | ||
| 322 | +# ========================================================================= | ||
| 323 | +# Tests for mx_fake_quantize (quantize then dequantize round trip) | ||
| 324 | +# ========================================================================= | ||
| 325 | + | ||
| 326 | + | ||
| 327 | +@pytest.mark.parametrize( | ||
| 328 | + "tensor, axis", | ||
| 329 | + [ | ||
| 330 | + # 1. Dense (is_contiguous() True) -> if branch, the ops see the tensor as-is. | ||
| 331 | + (torch.randn(256, 128, device="npu", dtype=torch.bfloat16), -1), | ||
| 332 | + # 2. Quant axis strided (stride(axis) != 1): a transposed 2D tensor, which | ||
| 333 | + # no view can undo, so the ops see the tensor as-is. | ||
| 334 | + (torch.randn(128, 256, device="npu", dtype=torch.bfloat16).transpose(0, 1), 1), | ||
| 335 | + # 3. Pure perm view with innermost-contiguous quant axis (like wo_a): the | ||
| 336 | + # permuting branch, where FP4 packs a different dim than the raw ops' call. | ||
| 337 | + (torch.randn(4, 128, 256, device="npu", dtype=torch.bfloat16).transpose(1, 2), 1), | ||
| 338 | + # 4. Non-pure strided view, stride(axis) == 1 but no permutation makes it | ||
| 339 | + # dense, so the permuting branch's permutation is the identity and the | ||
| 340 | + # op copies internally. The quant dim is a whole number of blocks, which | ||
| 341 | + # the dequantize helper the reference uses requires. | ||
| 342 | + (torch.as_strided(torch.randn(2, 65, device="npu", dtype=torch.bfloat16), (2, 64), (65, 1)), 1), | ||
| 343 | + ], | ||
| 344 | + ids=["dense", "strided_axis", "perm_view", "non_pure"], | ||
| 345 | +) | ||
| 346 | +@pytest.mark.parametrize("elem_dtype", [torch.float8_e4m3fn, torch.float8_e5m2, torch.float4_e2m1fn_x2]) | ||
| 347 | +def test_mx_fake_quantize_matches_quantize_then_dequantize_for_all_layouts(tensor, axis, elem_dtype): | ||
| 348 | + """mx_fake_quantize reproduces quantize-then-dequantize on all four layouts. | ||
| 349 | + | ||
| 350 | + The reference quantizes with the raw ``npu_dynamic_mx_quant`` and dequantizes | ||
| 351 | + with ``mxfp8_dequantize``/``mxfp4_dequantize``, the helpers training's fake | ||
| 352 | + quantization has used so far (``MXFP4FakeQuantize.forward``). The raw | ||
| 353 | + ``npu_anti_mx_quant`` cannot serve as the reference: it only consumes quantized | ||
| 354 | + data whose quant axis is trailing, which the ``perm_view`` layout breaks. | ||
| 355 | + | ||
| 356 | + These are value-equivalence checks: they verify correctness, not that a real | ||
| 357 | + transpose was avoided (that would require profiling). The point is each of the | ||
| 358 | + four branch inputs must dequantize to what the raw ops produce for the original | ||
| 359 | + tensor. Values are compared rather than quantized bytes: for FP4 the two calls | ||
| 360 | + may pack different dims (two values per byte), which does not change what each | ||
| 361 | + value dequantizes to. | ||
| 362 | + | ||
| 363 | + The result is then fake quantized a second time: the dequantized tensor's layout | ||
| 364 | + need not match the original's (``non_pure`` comes back dense), so the second call | ||
| 365 | + may take the other branch, and it must still reproduce the values exactly. | ||
| 366 | + """ | ||
| 367 | + from torchao_npu.ops.mx_ops import mxfp4_dequantize, mxfp8_dequantize | ||
| 368 | + from torchao_npu.quantization.quant_primitives.mx import mx_fake_quantize | ||
| 369 | + | ||
| 370 | + config = MXQuantizeConfig(elem_dtype=elem_dtype) | ||
| 371 | + | ||
| 372 | + y = mx_fake_quantize(tensor, axis, config) | ||
| 373 | + y_q, scale = torch_npu.npu_dynamic_mx_quant( | ||
| 374 | + tensor, | ||
| 375 | + axis=axis, | ||
| 376 | + dst_type=config.npu_elem_dtype, | ||
| 377 | + block_size=config.block_size, | ||
| 378 | + round_mode=config.round_mode, | ||
| 379 | + scale_alg=config.scale_alg, | ||
| 380 | + dst_type_max=config.dst_type_max, | ||
| 381 | + ) | ||
| 382 | + dequantize = mxfp4_dequantize if elem_dtype is torch.float4_e2m1fn_x2 else mxfp8_dequantize | ||
| 383 | + y_ref = dequantize( | ||
| 384 | + y_q, | ||
| 385 | + scale, | ||
| 386 | + axis=axis, | ||
| 387 | + block_size=config.block_size, | ||
| 388 | + output_shape=tensor.shape, | ||
| 389 | + output_dtype=tensor.dtype, | ||
| 390 | + ) | ||
| 391 | + | ||
| 392 | + assert y.shape == tensor.shape, f"shape mismatch: {y.shape} vs {tensor.shape}" | ||
| 393 | + assert y.dtype == tensor.dtype, f"dtype mismatch: {y.dtype} vs {tensor.dtype}" | ||
| 394 | + assert torch.equal(y, y_ref), "fake quantized values differ from the reference dequantize" | ||
| 395 | + | ||
| 396 | + # Idempotency: quantize -> dequantize -> quantize -> dequantize is a no-op. | ||
| 397 | + y2 = mx_fake_quantize(y, axis, config) | ||
| 398 | + assert torch.equal(y, y2), "fake quantization is not idempotent" | ||
| @@ -129,6 +129,70 @@ def mx_quantize( | |||
| 129 | return y, scale | 129 | return y, scale |
| 130 | 130 | ||
| 131 | 131 | ||
| 132 | +def mx_fake_quantize( | ||
| 133 | + tensor: torch.Tensor, | ||
| 134 | + axis: int, | ||
| 135 | + config: MXQuantizeConfig, | ||
| 136 | +) -> torch.Tensor: | ||
| 137 | + """MX fake-quantize ``tensor`` along ``axis``. | ||
| 138 | + | ||
| 139 | + Quantizes with ``npu_dynamic_mx_quant`` and immediately dequantizes the result | ||
| 140 | + with ``npu_anti_mx_quant``, so the values are those of a real MX | ||
| 141 | + quantization/dequantization round trip while the returned tensor keeps | ||
| 142 | + ``tensor.dtype``. | ||
| 143 | + | ||
| 144 | + Unlike :func:`mx_quantize`, the quant axis is always permuted to -1 first, | ||
| 145 | + because ``npu_anti_mx_quant`` only consumes quantized data whose quant axis is | ||
| 146 | + trailing. The permutation is a view, so it introduces no copy of its own: for a | ||
| 147 | + tensor whose quant axis is already trailing it is the identity, and otherwise | ||
| 148 | + the quant op copies internally when it cannot consume the permuted layout as-is. | ||
| 149 | + | ||
| 150 | + Args: | ||
| 151 | + tensor: Tensor to quantize, shape ``(..., K, ...)``. | ||
| 152 | + axis: Dimension to quantize along. | ||
| 153 | + config: MX quantization parameters. | ||
| 154 | + | ||
| 155 | + Returns: | ||
| 156 | + The fake-quantized tensor, with the same shape and dtype as ``tensor``. | ||
| 157 | + """ | ||
| 158 | + | ||
| 159 | + axis = normalize_dim(axis, tensor.ndim) | ||
| 160 | + | ||
| 161 | + perm_indices = sorted( | ||
| 162 | + (d for d in range(tensor.ndim) if d != axis), | ||
| 163 | + key=lambda d: tensor.stride(d), | ||
| 164 | + reverse=True, | ||
| 165 | + ) | ||
| 166 | + perm_indices.append(axis) | ||
| 167 | + tensor_p = tensor.permute(perm_indices) | ||
| 168 | + | ||
| 169 | + y_p, scale_p = torch_npu.npu_dynamic_mx_quant( | ||
| 170 | + tensor_p, | ||
| 171 | + axis=-1, | ||
| 172 | + dst_type=config.npu_elem_dtype, | ||
| 173 | + block_size=config.block_size, | ||
| 174 | + round_mode=config.round_mode, | ||
| 175 | + scale_alg=config.scale_alg, | ||
| 176 | + dst_type_max=config.dst_type_max, | ||
| 177 | + ) | ||
| 178 | + | ||
| 179 | + y_fake_p = torch_npu.npu_anti_mx_quant( | ||
| 180 | + y_p, | ||
| 181 | + scale_p, | ||
| 182 | + axis=-1, | ||
| 183 | + dst_type=tensor_p.dtype, | ||
| 184 | + src_type=config.npu_elem_dtype, | ||
| 185 | + ) | ||
| 186 | + | ||
| 187 | + # Inverse permutation: y_p dim j corresponds to tensor dim perm_indices[j]. | ||
| 188 | + perm_back_indices = [0] * tensor.ndim | ||
| 189 | + for j, p in enumerate(perm_indices): | ||
| 190 | + perm_back_indices[p] = j | ||
| 191 | + y_fake = y_fake_p.permute(perm_back_indices) | ||
| 192 | + | ||
| 193 | + return y_fake | ||
| 194 | + | ||
| 195 | + | ||
| 132 | def mx_quantize_dual_axis( | 196 | def mx_quantize_dual_axis( |
| 133 | tensor: torch.Tensor, | 197 | tensor: torch.Tensor, |
| 134 | config: MXQuantizeConfig, | 198 | config: MXQuantizeConfig, |