Open
【11月贡献大赛-缺陷修复】fix(ops-precision-standard): [Bug] fix empty batch crash, fp16/uint8 diff overflow, shape broadcast, and NaN/Inf handling in mare_mere_threshold.py #7335
liuhongweiAdd on 7 hours ago
【11月贡献大赛-缺陷修复】fix(ops-precision-standard): [Bug] fix empty batch crash, fp16/uint8 diff overflow, shape broadcast, and NaN/Inf handling in mare_mere_threshold.py #7335
Open
Total: 2 files changed+120-43
| @@ -15,13 +15,30 @@ | |||
| 15 | import numpy as np | 15 | import numpy as np |
| 16 | 16 | ||
| 17 | 17 | ||
| 18 | +def _prepare_pair(actual, golden): | ||
| 19 | + """校验输入形状与非空并转为 float64,避免 fp16 溢出及无符号整型回绕。""" | ||
| 20 | + actual_arr = np.asarray(actual) | ||
| 21 | + golden_arr = np.asarray(golden) | ||
| 22 | + if actual_arr.shape != golden_arr.shape: | ||
| 23 | + raise ValueError( | ||
| 24 | + f"Shape mismatch: actual {actual_arr.shape} vs golden {golden_arr.shape}" | ||
| 25 | + ) | ||
| 26 | + if actual_arr.size == 0: | ||
| 27 | + raise ValueError("Input tensors must be non-empty") | ||
| 28 | + return actual_arr.astype(np.float64), golden_arr.astype(np.float64) | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def _relative_errors(actual, golden): | ||
| 32 | + actual_f, golden_f = _prepare_pair(actual, golden) | ||
| 33 | + return np.abs(actual_f - golden_f) / (np.abs(golden_f) + 1e-7) | ||
| 34 | + | ||
| 35 | + | ||
| 18 | def calculate_mare(actual, golden): | 36 | def calculate_mare(actual, golden): |
| 19 | """ | 37 | """ |
| 20 | 计算最大相对误差(MARE) | 38 | 计算最大相对误差(MARE) |
| 21 | MARE = max(|actual - golden| / (|golden| + 1e-7)) | 39 | MARE = max(|actual - golden| / (|golden| + 1e-7)) |
| 22 | """ | 40 | """ |
| 23 | - relative_errors = np.abs(actual - golden) / (np.abs(golden) + 1e-7) | 41 | + return float(np.max(_relative_errors(actual, golden))) |
| 24 | - return np.max(relative_errors) | ||
| 25 | 42 | ||
| 26 | 43 | ||
| 27 | def calculate_mere(actual, golden): | 44 | def calculate_mere(actual, golden): |
| @@ -29,8 +46,7 @@ def calculate_mere(actual, golden): | |||
| 29 | 计算平均相对误差(MERE) | 46 | 计算平均相对误差(MERE) |
| 30 | MERE = avg(|actual - golden| / (|golden| + 1e-7)) | 47 | MERE = avg(|actual - golden| / (|golden| + 1e-7)) |
| 31 | """ | 48 | """ |
| 32 | - relative_errors = np.abs(actual - golden) / (np.abs(golden) + 1e-7) | 49 | + return float(np.mean(_relative_errors(actual, golden))) |
| 33 | - return np.mean(relative_errors) | ||
| 34 | 50 | ||
| 35 | 51 | ||
| 36 | def get_threshold_by_dtype(dtype): | 52 | def get_threshold_by_dtype(dtype): |
| @@ -73,20 +89,25 @@ def check_precision_threshold(npu_output, golden_output): | |||
| 73 | Returns: | 89 | Returns: |
| 74 | dict: 包含is_pass和各种误差指标的字典 | 90 | dict: 包含is_pass和各种误差指标的字典 |
| 75 | """ | 91 | """ |
| 92 | + npu_arr = np.asarray(npu_output) | ||
| 93 | + golden_arr = np.asarray(golden_output) | ||
| 94 | + npu_f, golden_f = _prepare_pair(npu_arr, golden_arr) | ||
| 95 | + has_non_finite = not (np.all(np.isfinite(npu_f)) and np.all(np.isfinite(golden_f))) | ||
| 96 | + | ||
| 76 | # 计算误差指标 | 97 | # 计算误差指标 |
| 77 | - mare = calculate_mare(npu_output, golden_output) | 98 | + mare = calculate_mare(npu_f, golden_f) |
| 78 | - mere = calculate_mere(npu_output, golden_output) | 99 | + mere = calculate_mere(npu_f, golden_f) |
| 79 | - | 100 | + |
| 80 | # 获取阈值 | 101 | # 获取阈值 |
| 81 | - threshold = get_threshold_by_dtype(npu_output.dtype) | 102 | + threshold = float(get_threshold_by_dtype(npu_arr.dtype)) |
| 82 | - mare_threshold = 10 * threshold | 103 | + mare_threshold = float(10 * threshold) |
| 83 | - | 104 | + |
| 84 | # 判定是否通过 | 105 | # 判定是否通过 |
| 85 | - mere_pass = mere < threshold | 106 | + mere_pass = bool(not has_non_finite and mere < threshold) |
| 86 | - mare_pass = mare < mare_threshold | 107 | + mare_pass = bool(not has_non_finite and mare < mare_threshold) |
| 87 | - | 108 | + |
| 88 | - is_pass = mere_pass and mare_pass | 109 | + is_pass = bool(mere_pass and mare_pass) |
| 89 | - | 110 | + |
| 90 | result = { | 111 | result = { |
| 91 | 'is_pass': is_pass, | 112 | 'is_pass': is_pass, |
| 92 | 'mare': mare, | 113 | 'mare': mare, |
| @@ -95,18 +116,20 @@ def check_precision_threshold(npu_output, golden_output): | |||
| 95 | 'mare_threshold': mare_threshold, | 116 | 'mare_threshold': mare_threshold, |
| 96 | 'mere_pass': mere_pass, | 117 | 'mere_pass': mere_pass, |
| 97 | 'mare_pass': mare_pass, | 118 | 'mare_pass': mare_pass, |
| 98 | - 'npu_dtype': str(npu_output.dtype), | 119 | + 'npu_dtype': str(npu_arr.dtype), |
| 99 | - 'golden_dtype': str(golden_output.dtype), | 120 | + 'golden_dtype': str(golden_arr.dtype), |
| 100 | - 'shape': npu_output.shape | 121 | + 'shape': npu_arr.shape |
| 101 | } | 122 | } |
| 102 | - | 123 | + |
| 103 | if not is_pass: | 124 | if not is_pass: |
| 104 | result['failure_reasons'] = [] | 125 | result['failure_reasons'] = [] |
| 105 | - if not mere_pass: | 126 | + if has_non_finite: |
| 127 | + result['failure_reasons'].append('Input contains NaN or Inf values') | ||
| 128 | + if not mere_pass and (not np.isfinite(mere) or mere >= threshold): | ||
| 106 | result['failure_reasons'].append(f'MERE {mere:.6f} >= threshold {threshold:.6f}') | 129 | result['failure_reasons'].append(f'MERE {mere:.6f} >= threshold {threshold:.6f}') |
| 107 | - if not mare_pass: | 130 | + if not mare_pass and (not np.isfinite(mare) or mare >= mare_threshold): |
| 108 | result['failure_reasons'].append(f'MARE {mare:.6f} >= mare_threshold {mare_threshold:.6f}') | 131 | result['failure_reasons'].append(f'MARE {mare:.6f} >= mare_threshold {mare_threshold:.6f}') |
| 109 | - | 132 | + |
| 110 | return result | 133 | return result |
| 111 | 134 | ||
| 112 | 135 | ||
| @@ -122,74 +145,74 @@ def check_precision_threshold_batch(outputs_list): | |||
| 122 | """ | 145 | """ |
| 123 | results = [] | 146 | results = [] |
| 124 | pass_count = 0 | 147 | pass_count = 0 |
| 125 | - | 148 | + |
| 126 | mare_values = [] | 149 | mare_values = [] |
| 127 | mere_values = [] | 150 | mere_values = [] |
| 128 | - | 151 | + |
| 129 | for npu_out, golden_out in outputs_list: | 152 | for npu_out, golden_out in outputs_list: |
| 130 | result = check_precision_threshold(npu_out, golden_out) | 153 | result = check_precision_threshold(npu_out, golden_out) |
| 131 | results.append(result) | 154 | results.append(result) |
| 132 | - | 155 | + |
| 133 | if result['is_pass']: | 156 | if result['is_pass']: |
| 134 | pass_count += 1 | 157 | pass_count += 1 |
| 135 | - | 158 | + |
| 136 | mare_values.append(result['mare']) | 159 | mare_values.append(result['mare']) |
| 137 | mere_values.append(result['mere']) | 160 | mere_values.append(result['mere']) |
| 138 | - | 161 | + |
| 139 | total = len(outputs_list) | 162 | total = len(outputs_list) |
| 140 | summary = { | 163 | summary = { |
| 141 | 'total_cases': total, | 164 | 'total_cases': total, |
| 142 | 'pass_count': pass_count, | 165 | 'pass_count': pass_count, |
| 143 | 'fail_count': total - pass_count, | 166 | 'fail_count': total - pass_count, |
| 144 | - 'pass_rate': pass_count / total if total > 0 else 0, | 167 | + 'pass_rate': float(pass_count / total) if total > 0 else 0.0, |
| 145 | - 'mare_mean': np.mean(mare_values), | 168 | + 'mare_mean': float(np.mean(mare_values)) if total > 0 else 0.0, |
| 146 | - 'mare_max': np.max(mare_values), | 169 | + 'mare_max': float(np.max(mare_values)) if total > 0 else 0.0, |
| 147 | - 'mere_mean': np.mean(mere_values), | 170 | + 'mere_mean': float(np.mean(mere_values)) if total > 0 else 0.0, |
| 148 | - 'mere_max': np.max(mere_values), | 171 | + 'mere_max': float(np.max(mere_values)) if total > 0 else 0.0, |
| 149 | 'detail_results': results | 172 | 'detail_results': results |
| 150 | } | 173 | } |
| 151 | - | 174 | + |
| 152 | return summary | 175 | return summary |
| 153 | 176 | ||
| 154 | 177 | ||
| 155 | if __name__ == '__main__': | 178 | if __name__ == '__main__': |
| 156 | # 示例用法 | 179 | # 示例用法 |
| 157 | np.random.seed(42) | 180 | np.random.seed(42) |
| 158 | - | 181 | + |
| 159 | # 测试1: FP16通过 | 182 | # 测试1: FP16通过 |
| 160 | golden1 = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16) | 183 | golden1 = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float16) |
| 161 | npu1 = np.array([1.0001, 2.0001, 3.0001, 4.0001], dtype=np.float16) | 184 | npu1 = np.array([1.0001, 2.0001, 3.0001, 4.0001], dtype=np.float16) |
| 162 | - | 185 | + |
| 163 | result1 = check_precision_threshold(npu1, golden1) | 186 | result1 = check_precision_threshold(npu1, golden1) |
| 164 | print(f"测试1 - FP16通过: {result1['is_pass']}") | 187 | print(f"测试1 - FP16通过: {result1['is_pass']}") |
| 165 | print(f" MERE: {result1['mere']:.6f}, threshold: {result1['threshold']:.6f}") | 188 | print(f" MERE: {result1['mere']:.6f}, threshold: {result1['threshold']:.6f}") |
| 166 | print(f" MARE: {result1['mare']:.6f}, mare_threshold: {result1['mare_threshold']:.6f}") | 189 | print(f" MARE: {result1['mare']:.6f}, mare_threshold: {result1['mare_threshold']:.6f}") |
| 167 | - | 190 | + |
| 168 | # 测试2: FP32通过 | 191 | # 测试2: FP32通过 |
| 169 | golden2 = np.array([10.0, 20.0, 30.0], dtype=np.float32) | 192 | golden2 = np.array([10.0, 20.0, 30.0], dtype=np.float32) |
| 170 | npu2 = np.array([10.00001, 20.00001, 30.00001], dtype=np.float32) | 193 | npu2 = np.array([10.00001, 20.00001, 30.00001], dtype=np.float32) |
| 171 | - | 194 | + |
| 172 | result2 = check_precision_threshold(npu2, golden2) | 195 | result2 = check_precision_threshold(npu2, golden2) |
| 173 | print(f"测试2 - FP32通过: {result2['is_pass']}") | 196 | print(f"测试2 - FP32通过: {result2['is_pass']}") |
| 174 | print(f" MERE: {result2['mere']:.6f}, threshold: {result2['threshold']:.6f}") | 197 | print(f" MERE: {result2['mere']:.6f}, threshold: {result2['threshold']:.6f}") |
| 175 | - | 198 | + |
| 176 | # 测试3: BF16不通过 | 199 | # 测试3: BF16不通过 |
| 177 | golden3 = np.array([1.0, 2.0, 3.0], dtype=np.float32) # 模拟BF16精度 | 200 | golden3 = np.array([1.0, 2.0, 3.0], dtype=np.float32) # 模拟BF16精度 |
| 178 | npu3 = np.array([1.01, 2.01, 3.01], dtype=np.float32) | 201 | npu3 = np.array([1.01, 2.01, 3.01], dtype=np.float32) |
| 179 | - | 202 | + |
| 180 | # 手动设置BF16阈值测试 | 203 | # 手动设置BF16阈值测试 |
| 181 | threshold_bf16 = 2 ** (-7) | 204 | threshold_bf16 = 2 ** (-7) |
| 182 | mare3 = calculate_mare(npu3, golden3) | 205 | mare3 = calculate_mare(npu3, golden3) |
| 183 | mere3 = calculate_mere(npu3, golden3) | 206 | mere3 = calculate_mere(npu3, golden3) |
| 184 | - | 207 | + |
| 185 | print(f"测试3 - BF16阈值测试: mere={mere3:.6f}, threshold={threshold_bf16:.6f}") | 208 | print(f"测试3 - BF16阈值测试: mere={mere3:.6f}, threshold={threshold_bf16:.6f}") |
| 186 | print(f" 是否通过: mere < threshold? {mere3 < threshold_bf16}") | 209 | print(f" 是否通过: mere < threshold? {mere3 < threshold_bf16}") |
| 187 | - | 210 | + |
| 188 | # 测试4: 批量检查 | 211 | # 测试4: 批量检查 |
| 189 | outputs_list = [ | 212 | outputs_list = [ |
| 190 | (np.array([1.0, 2.0], dtype=np.float16), np.array([1.0, 2.0], dtype=np.float16)), | 213 | (np.array([1.0, 2.0], dtype=np.float16), np.array([1.0, 2.0], dtype=np.float16)), |
| 191 | (np.array([3.0, 4.0], dtype=np.float16), np.array([3.0, 4.0], dtype=np.float16)) | 214 | (np.array([3.0, 4.0], dtype=np.float16), np.array([3.0, 4.0], dtype=np.float16)) |
| 192 | ] | 215 | ] |
| 193 | - | 216 | + |
| 194 | summary = check_precision_threshold_batch(outputs_list) | 217 | summary = check_precision_threshold_batch(outputs_list) |
| 195 | - print(f"测试4 - 批量: 通过率 {summary['pass_rate']:.2%}") | 218 | + print(f"测试4 - 批量: 通过率 {summary['pass_rate']:.2%}") |
| @@ -0,0 +1,54 @@ | |||
| 1 | +import sys | ||
| 2 | +from pathlib import Path | ||
| 3 | + | ||
| 4 | +import numpy as np | ||
| 5 | +import pytest | ||
| 6 | + | ||
| 7 | +SCRIPT_DIR = Path(__file__).resolve().parents[1] / "scripts" | ||
| 8 | +sys.path.insert(0, str(SCRIPT_DIR)) | ||
| 9 | + | ||
| 10 | +import mare_mere_threshold as mmt # noqa: E402 | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +def test_empty_batch_returns_zero_summary(): | ||
| 14 | + summary = mmt.check_precision_threshold_batch([]) | ||
| 15 | + assert summary["total_cases"] == 0 | ||
| 16 | + assert summary["pass_rate"] == 0.0 | ||
| 17 | + assert summary["mare_max"] == 0.0 | ||
| 18 | + assert summary["mere_max"] == 0.0 | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +def test_fp16_overflow_and_uint8_underflow_avoided(): | ||
| 22 | + a16 = np.array([40000.0], dtype=np.float16) | ||
| 23 | + b16 = np.array([-40000.0], dtype=np.float16) | ||
| 24 | + mare16 = mmt.calculate_mare(a16, b16) | ||
| 25 | + assert np.isfinite(mare16) | ||
| 26 | + assert mare16 == pytest.approx(2.0, rel=1e-3) | ||
| 27 | + | ||
| 28 | + a8 = np.array([1], dtype=np.uint8) | ||
| 29 | + b8 = np.array([2], dtype=np.uint8) | ||
| 30 | + assert mmt.calculate_mare(a8, b8) == pytest.approx(0.5, rel=1e-6) | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def test_shape_mismatch_and_empty_array_raise(): | ||
| 34 | + with pytest.raises(ValueError): | ||
| 35 | + mmt.check_precision_threshold(np.array([1.0]), np.array([1.0, 2.0])) | ||
| 36 | + with pytest.raises(ValueError): | ||
| 37 | + mmt.check_precision_threshold(np.array([], dtype=np.float32), np.array([], dtype=np.float32)) | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def test_nan_inf_fails_and_returns_native_types(): | ||
| 41 | + res = mmt.check_precision_threshold( | ||
| 42 | + np.array([1.0, np.nan], dtype=np.float32), | ||
| 43 | + np.array([1.0, 2.0], dtype=np.float32), | ||
| 44 | + ) | ||
| 45 | + assert res["is_pass"] is False | ||
| 46 | + assert isinstance(res["is_pass"], bool) | ||
| 47 | + assert isinstance(res["mare"], float) | ||
| 48 | + assert any("NaN" in reason for reason in res["failure_reasons"]) | ||
| 49 | + | ||
| 50 | + res_inf = mmt.check_precision_threshold( | ||
| 51 | + np.array([np.inf], dtype=np.float32), | ||
| 52 | + np.array([1.0], dtype=np.float32), | ||
| 53 | + ) | ||
| 54 | + assert res_inf["is_pass"] is False | ||