Merged
fix(examples): reject non-finite FlatQuant references #492
tianjunAdd on Oct 12
fix(examples): reject non-finite FlatQuant references #492
Merged
Total: 2 files changed+169-3
| @@ -3,11 +3,11 @@ | |||
| 3 | 3 | ||
| 4 | # ---------------------------------------------------------------------------------------------------------- | 4 | # ---------------------------------------------------------------------------------------------------------- |
| 5 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. | 5 | # Copyright (c) 2026 Huawei Technologies Co., Ltd. |
| 6 | -# This program is free software; you can redistribute it and/or modify it under the terms and conditions of | 6 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of |
| 7 | -# the CANN Open Software License Agreement Version 2.0 (the "License). | 7 | +# CANN Open Software License Agreement Version 2.0 (the "License"). |
| 8 | # Please refer to the License for details. You may not use this file except in compliance with the License. | 8 | # Please refer to the License for details. You may not use this file except in compliance with the License. |
| 9 | # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | 9 | # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, |
| 10 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. | 10 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 11 | # See LICENSE in the root of the software repository for the full text of the License. | 11 | # See LICENSE in the root of the software repository for the full text of the License. |
| 12 | # ---------------------------------------------------------------------------------------------------------- | 12 | # ---------------------------------------------------------------------------------------------------------- |
| 13 | 13 | ||
| @@ -20,6 +20,7 @@ Outputs of the kernel per batch b (row-major MxN matrix, flattened to mn element | |||
| 20 | b * ceil(mn / 64) * 2 (== b * mn / 32 when mn % 64 == 0). | 20 | b * ceil(mn / 64) * 2 (== b * mn / 32 when mn % 64 == 0). |
| 21 | 21 | ||
| 22 | Checks: | 22 | Checks: |
| 23 | + - golden: all float32 reference values must be finite before comparison. | ||
| 23 | - scale: the NPU scale byte must match the golden DYN_DTYPE_RANGE exponent derived | 24 | - scale: the NPU scale byte must match the golden DYN_DTYPE_RANGE exponent derived |
| 24 | from the BF16-rounded golden reference within +/-1 (a 1-ulp BF16 difference of the | 25 | from the BF16-rounded golden reference within +/-1 (a 1-ulp BF16 difference of the |
| 25 | group amax may flip the rounded exponent by one). | 26 | group amax may flip the rounded exponent by one). |
| @@ -65,6 +66,8 @@ def verify(golden_dir, actual_dir, k, m, n): | |||
| 65 | golden = np.fromfile( | 66 | golden = np.fromfile( |
| 66 | os.path.join(golden_dir, "golden_ref.bin"), dtype=np.float32 | 67 | os.path.join(golden_dir, "golden_ref.bin"), dtype=np.float32 |
| 67 | ).reshape(k, m, n) | 68 | ).reshape(k, m, n) |
| 69 | + if not np.all(np.isfinite(golden)): | ||
| 70 | + raise ValueError("Golden reference contains non-finite values") | ||
| 68 | npu_y = np.fromfile(os.path.join(actual_dir, "npu_y.bin"), dtype=np.uint8) | 71 | npu_y = np.fromfile(os.path.join(actual_dir, "npu_y.bin"), dtype=np.uint8) |
| 69 | npu_scale = np.fromfile(os.path.join(actual_dir, "npu_scale.bin"), dtype=np.uint8) | 72 | npu_scale = np.fromfile(os.path.join(actual_dir, "npu_scale.bin"), dtype=np.uint8) |
| 70 | 73 | ||
| @@ -0,0 +1,163 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +"""Host-only CLI regressions using synthetic FlatQuant binary fixtures.""" | ||
| 10 | + | ||
| 11 | +import json | ||
| 12 | +from pathlib import Path | ||
| 13 | +import subprocess | ||
| 14 | +import sys | ||
| 15 | +import tempfile | ||
| 16 | +import unittest | ||
| 17 | + | ||
| 18 | +import numpy as np | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +MATRIX_ROWS = 16 | ||
| 22 | +MATRIX_COLUMNS = 16 | ||
| 23 | +MATRIX_ELEMENTS = MATRIX_ROWS * MATRIX_COLUMNS | ||
| 24 | +GROUP_SIZE = 32 | ||
| 25 | +NONFINITE_SCALE = 253 | ||
| 26 | +HALF_SCALE = 124 | ||
| 27 | +VERIFIER = Path(__file__).resolve().parents[1] / "scripts" / "verify_result.py" | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +class FlatQuantResultVerifierTest(unittest.TestCase): | ||
| 31 | + @staticmethod | ||
| 32 | + def _run_cli(reference, packed=None, scales=None): | ||
| 33 | + batches = reference.shape[0] | ||
| 34 | + if packed is None: | ||
| 35 | + packed = np.zeros(batches * MATRIX_ELEMENTS // 2, dtype=np.uint8) | ||
| 36 | + if scales is None: | ||
| 37 | + scales = np.zeros(batches * MATRIX_ELEMENTS // GROUP_SIZE, dtype=np.uint8) | ||
| 38 | + with tempfile.TemporaryDirectory() as folder: | ||
| 39 | + golden_dir = Path(folder) / "golden" | ||
| 40 | + actual_dir = Path(folder) / "actual" | ||
| 41 | + golden_dir.mkdir() | ||
| 42 | + actual_dir.mkdir() | ||
| 43 | + reference.tofile(golden_dir / "golden_ref.bin") | ||
| 44 | + packed.tofile(actual_dir / "npu_y.bin") | ||
| 45 | + scales.tofile(actual_dir / "npu_scale.bin") | ||
| 46 | + command = [ | ||
| 47 | + sys.executable, | ||
| 48 | + str(VERIFIER), | ||
| 49 | + "--golden-dir", | ||
| 50 | + str(golden_dir), | ||
| 51 | + "--actual-dir", | ||
| 52 | + str(actual_dir), | ||
| 53 | + "--k", | ||
| 54 | + str(batches), | ||
| 55 | + "--m", | ||
| 56 | + str(MATRIX_ROWS), | ||
| 57 | + "--n", | ||
| 58 | + str(MATRIX_COLUMNS), | ||
| 59 | + "--iter-batch", | ||
| 60 | + "1", | ||
| 61 | + "--has-p2", | ||
| 62 | + "false", | ||
| 63 | + ] | ||
| 64 | + result = subprocess.run( | ||
| 65 | + command, capture_output=True, text=True, check=False | ||
| 66 | + ) | ||
| 67 | + metrics_file = actual_dir / "verify_metrics.json" | ||
| 68 | + metrics = ( | ||
| 69 | + json.loads(metrics_file.read_text()) if metrics_file.exists() else None | ||
| 70 | + ) | ||
| 71 | + return result, metrics | ||
| 72 | + | ||
| 73 | + def _assert_nonfinite_rejected(self, reference, packed=None, scales=None): | ||
| 74 | + result, metrics = self._run_cli(reference, packed, scales) | ||
| 75 | + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) | ||
| 76 | + self.assertIn("Golden reference contains non-finite values", result.stderr) | ||
| 77 | + self.assertNotIn("[PASS]", result.stdout) | ||
| 78 | + self.assertIsNone(metrics) | ||
| 79 | + | ||
| 80 | + def test_single_nan_reference_is_rejected(self): | ||
| 81 | + reference = np.zeros((1, MATRIX_ROWS, MATRIX_COLUMNS), dtype=np.float32) | ||
| 82 | + reference.flat[0] = np.nan | ||
| 83 | + scales = np.zeros(MATRIX_ELEMENTS // GROUP_SIZE, dtype=np.uint8) | ||
| 84 | + scales[0] = NONFINITE_SCALE | ||
| 85 | + self._assert_nonfinite_rejected(reference, scales=scales) | ||
| 86 | + | ||
| 87 | + def test_nan_in_later_batch_is_rejected(self): | ||
| 88 | + reference = np.zeros((2, MATRIX_ROWS, MATRIX_COLUMNS), dtype=np.float32) | ||
| 89 | + reference.flat[-1] = np.nan | ||
| 90 | + scales = np.zeros(2 * MATRIX_ELEMENTS // GROUP_SIZE, dtype=np.uint8) | ||
| 91 | + scales[-1] = NONFINITE_SCALE | ||
| 92 | + self._assert_nonfinite_rejected(reference, scales=scales) | ||
| 93 | + | ||
| 94 | + def test_all_nan_reference_is_rejected(self): | ||
| 95 | + reference = np.full((1, MATRIX_ROWS, MATRIX_COLUMNS), np.nan, dtype=np.float32) | ||
| 96 | + scales = np.full(MATRIX_ELEMENTS // GROUP_SIZE, NONFINITE_SCALE, dtype=np.uint8) | ||
| 97 | + self._assert_nonfinite_rejected(reference, scales=scales) | ||
| 98 | + | ||
| 99 | + def test_infinite_reference_groups_are_rejected(self): | ||
| 100 | + for value, packed_byte in ((np.inf, 0x77), (-np.inf, 0xFF)): | ||
| 101 | + with self.subTest(value=value): | ||
| 102 | + reference = np.zeros((1, MATRIX_ROWS, MATRIX_COLUMNS), dtype=np.float32) | ||
| 103 | + reference.reshape(-1)[:GROUP_SIZE] = value | ||
| 104 | + packed = np.zeros(MATRIX_ELEMENTS // 2, dtype=np.uint8) | ||
| 105 | + # E2M1 nibbles 7/15 are +/-6; +/-6 * 2**126 overflows float32. | ||
| 106 | + packed[: GROUP_SIZE // 2] = packed_byte | ||
| 107 | + scales = np.zeros(MATRIX_ELEMENTS // GROUP_SIZE, dtype=np.uint8) | ||
| 108 | + scales[0] = NONFINITE_SCALE | ||
| 109 | + self._assert_nonfinite_rejected(reference, packed, scales) | ||
| 110 | + | ||
| 111 | + def test_zero_reference_passes_multiple_batches(self): | ||
| 112 | + reference = np.zeros((2, MATRIX_ROWS, MATRIX_COLUMNS), dtype=np.float32) | ||
| 113 | + result, metrics = self._run_cli(reference) | ||
| 114 | + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | ||
| 115 | + self.assertEqual(metrics["overall_status"], "pass") | ||
| 116 | + self.assertTrue( | ||
| 117 | + all(output["status"] == "pass" for output in metrics["outputs"]) | ||
| 118 | + ) | ||
| 119 | + | ||
| 120 | + def test_exact_finite_positive_and_negative_reference_pass(self): | ||
| 121 | + # E2M1 +/-4 (nibbles 6/14), with scale byte 124, represents +/-0.5. | ||
| 122 | + for value, packed_byte in ((0.5, 0x66), (-0.5, 0xEE)): | ||
| 123 | + with self.subTest(value=value): | ||
| 124 | + reference = np.full( | ||
| 125 | + (1, MATRIX_ROWS, MATRIX_COLUMNS), value, dtype=np.float32 | ||
| 126 | + ) | ||
| 127 | + packed = np.full(MATRIX_ELEMENTS // 2, packed_byte, dtype=np.uint8) | ||
| 128 | + scales = np.full( | ||
| 129 | + MATRIX_ELEMENTS // GROUP_SIZE, HALF_SCALE, dtype=np.uint8 | ||
| 130 | + ) | ||
| 131 | + result, metrics = self._run_cli(reference, packed, scales) | ||
| 132 | + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) | ||
| 133 | + self.assertEqual(metrics["overall_status"], "pass") | ||
| 134 | + | ||
| 135 | + def test_mismatched_finite_output_still_fails(self): | ||
| 136 | + reference = np.full((1, MATRIX_ROWS, MATRIX_COLUMNS), 0.5, dtype=np.float32) | ||
| 137 | + scales = np.full(MATRIX_ELEMENTS // GROUP_SIZE, HALF_SCALE, dtype=np.uint8) | ||
| 138 | + result, metrics = self._run_cli(reference, scales=scales) | ||
| 139 | + self.assertEqual(result.returncode, 1, result.stdout + result.stderr) | ||
| 140 | + self.assertEqual(metrics["overall_status"], "fail") | ||
| 141 | + self.assertEqual(metrics["outputs"][0]["error_ratio"], 1.0) | ||
| 142 | + self.assertEqual(metrics["outputs"][1]["error_ratio"], 0.0) | ||
| 143 | + | ||
| 144 | + def test_wrong_output_lengths_still_fail(self): | ||
| 145 | + reference = np.zeros((1, MATRIX_ROWS, MATRIX_COLUMNS), dtype=np.float32) | ||
| 146 | + cases = ( | ||
| 147 | + (np.zeros(MATRIX_ELEMENTS // 2 - 1, dtype=np.uint8), None, "NPU y size"), | ||
| 148 | + ( | ||
| 149 | + None, | ||
| 150 | + np.zeros(MATRIX_ELEMENTS // GROUP_SIZE - 1, dtype=np.uint8), | ||
| 151 | + "NPU scale size", | ||
| 152 | + ), | ||
| 153 | + ) | ||
| 154 | + for packed, scales, message in cases: | ||
| 155 | + with self.subTest(message=message): | ||
| 156 | + result, metrics = self._run_cli(reference, packed, scales) | ||
| 157 | + self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) | ||
| 158 | + self.assertIn(message, result.stderr) | ||
| 159 | + self.assertIsNone(metrics) | ||
| 160 | + | ||
| 161 | + | ||
| 162 | +if __name__ == "__main__": | ||
| 163 | + unittest.main() | ||