Open
【11月贡献大赛-缺陷修复】fix(pypto-precision-compare): [Bug] prevent cross-checkpoint parse bleed, guard None tolerance crash, and handle empty/UTF-8 logs in plot_accuracy.py #7336
liuhongweiAdd on 10 hours ago
【11月贡献大赛-缺陷修复】fix(pypto-precision-compare): [Bug] prevent cross-checkpoint parse bleed, guard None tolerance crash, and handle empty/UTF-8 logs in plot_accuracy.py #7336
Open
Total: 2 files changed+101-10
| @@ -17,6 +17,8 @@ import re | |||
| 17 | import sys | 17 | import sys |
| 18 | import os | 18 | import os |
| 19 | import logging | 19 | import logging |
| 20 | +import matplotlib | ||
| 21 | +matplotlib.use('Agg') | ||
| 20 | import matplotlib.pyplot as plt | 22 | import matplotlib.pyplot as plt |
| 21 | import numpy as np | 23 | import numpy as np |
| 22 | 24 | ||
| @@ -58,7 +60,11 @@ def parse_checkpoints(lines): | |||
| 58 | actual_rtol = None | 60 | actual_rtol = None |
| 59 | actual_atol = None | 61 | actual_atol = None |
| 60 | 62 | ||
| 61 | - for j in range(start_line, min(start_line + 20, len(lines))): | 63 | + end_line = min( |
| 64 | + start_line + 20, | ||
| 65 | + checkpoint_line_indices[i + 1] if i + 1 < len(checkpoints) else len(lines), | ||
| 66 | + ) | ||
| 67 | + for j in range(start_line, end_line): | ||
| 62 | if 'Tolerance: rtol=' in lines[j]: | 68 | if 'Tolerance: rtol=' in lines[j]: |
| 63 | num_pattern = r'([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)' | 69 | num_pattern = r'([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)' |
| 64 | tolerance_pattern = f'Tolerance: rtol={num_pattern}, atol={num_pattern}' | 70 | tolerance_pattern = f'Tolerance: rtol={num_pattern}, atol={num_pattern}' |
| @@ -81,11 +87,15 @@ def parse_checkpoints(lines): | |||
| 81 | return results | 87 | return results |
| 82 | 88 | ||
| 83 | 89 | ||
| 90 | +def _fmt_val(val): | ||
| 91 | + return f'{val:.6f}' if val is not None else 'N/A' | ||
| 92 | + | ||
| 93 | + | ||
| 84 | def plot_accuracy(results, output_path): | 94 | def plot_accuracy(results, output_path): |
| 85 | """绘制精度变化折线图""" | 95 | """绘制精度变化折线图""" |
| 86 | checkpoints_list = [r[0] for r in results] | 96 | checkpoints_list = [r[0] for r in results] |
| 87 | - tol_rtol_values = [r[1] for r in results] | 97 | + tol_rtol_values = [r[1] if r[1] is not None else np.nan for r in results] |
| 88 | - tol_atol_values = [r[2] for r in results] | 98 | + tol_atol_values = [r[2] if r[2] is not None else np.nan for r in results] |
| 89 | act_rtol_values = [r[3] for r in results] | 99 | act_rtol_values = [r[3] for r in results] |
| 90 | act_atol_values = [r[4] for r in results] | 100 | act_atol_values = [r[4] for r in results] |
| 91 | 101 | ||
| @@ -127,6 +137,7 @@ def plot_accuracy(results, output_path): | |||
| 127 | 137 | ||
| 128 | plt.tight_layout() | 138 | plt.tight_layout() |
| 129 | plt.savefig(output_path, dpi=300, bbox_inches='tight') | 139 | plt.savefig(output_path, dpi=300, bbox_inches='tight') |
| 140 | + plt.close(fig) | ||
| 130 | return output_path | 141 | return output_path |
| 131 | 142 | ||
| 132 | 143 | ||
| @@ -137,9 +148,14 @@ def print_summary(results): | |||
| 137 | logger.info(f"{'Checkpoint':<30} {'Tolerance':<25} {'Actual':<25} {'Status':<10}") | 148 | logger.info(f"{'Checkpoint':<30} {'Tolerance':<25} {'Actual':<25} {'Status':<10}") |
| 138 | logger.info("-" * 100) | 149 | logger.info("-" * 100) |
| 139 | for ckpt, tol_rtol, tol_atol, act_rtol, act_atol in results: | 150 | for ckpt, tol_rtol, tol_atol, act_rtol, act_atol in results: |
| 140 | - status = "FAIL" if (act_rtol > tol_rtol or act_atol > tol_atol) else "PASS" | 151 | + if tol_rtol is None or tol_atol is None: |
| 141 | - tol_str = f"rt={tol_rtol:.6f}, at={tol_atol:.6f}" | 152 | + status = "UNKNOWN" |
| 142 | - act_str = f"rt={act_rtol:.6f}, at={act_atol:.6f}" | 153 | + elif act_rtol > tol_rtol or act_atol > tol_atol: |
| 154 | + status = "FAIL" | ||
| 155 | + else: | ||
| 156 | + status = "PASS" | ||
| 157 | + tol_str = f"rt={_fmt_val(tol_rtol)}, at={_fmt_val(tol_atol)}" | ||
| 158 | + act_str = f"rt={_fmt_val(act_rtol)}, at={_fmt_val(act_atol)}" | ||
| 143 | logger.info(f"{ckpt:<30} {tol_str:<25} {act_str:<25} {status:<10}") | 159 | logger.info(f"{ckpt:<30} {tol_str:<25} {act_str:<25} {status:<10}") |
| 144 | logger.info("-" * 100) | 160 | logger.info("-" * 100) |
| 145 | 161 | ||
| @@ -157,15 +173,22 @@ def main(): | |||
| 157 | 173 | ||
| 158 | operator_name = extract_operator_name(log_file_path) | 174 | operator_name = extract_operator_name(log_file_path) |
| 159 | 175 | ||
| 160 | - with open(log_file, 'r') as f: | 176 | + try: |
| 161 | - lines = f.readlines() | 177 | + with open(log_file, 'r', encoding='utf-8', errors='replace') as f: |
| 178 | + lines = f.readlines() | ||
| 179 | + except OSError as exc: | ||
| 180 | + logger.error(f"错误: 无法读取日志文件 {log_file}: {exc}") | ||
| 181 | + sys.exit(1) | ||
| 162 | 182 | ||
| 163 | results = parse_checkpoints(lines) | 183 | results = parse_checkpoints(lines) |
| 184 | + if not results: | ||
| 185 | + logger.error(f"错误: 未从日志中提取到有效检查点精度数据: {log_file}") | ||
| 186 | + sys.exit(1) | ||
| 164 | 187 | ||
| 165 | logger.info(f'提取到 {len(results)} 个检查点的精度数据') | 188 | logger.info(f'提取到 {len(results)} 个检查点的精度数据') |
| 166 | for i, (ckpt, tol_rtol, tol_atol, act_rtol, act_atol) in enumerate(results): | 189 | for i, (ckpt, tol_rtol, tol_atol, act_rtol, act_atol) in enumerate(results): |
| 167 | - tol_str = f'Tolerance(rt={tol_rtol:.6f}, at={tol_atol:.6f})' | 190 | + tol_str = f'Tolerance(rt={_fmt_val(tol_rtol)}, at={_fmt_val(tol_atol)})' |
| 168 | - act_str = f'Actual(rt={act_rtol:.6f}, at={act_atol:.6f})' | 191 | + act_str = f'Actual(rt={_fmt_val(act_rtol)}, at={_fmt_val(act_atol)})' |
| 169 | logger.info(f'{i+1}. {ckpt}: {tol_str} | {act_str}') | 192 | logger.info(f'{i+1}. {ckpt}: {tol_str} | {act_str}') |
| 170 | 193 | ||
| 171 | output_image = os.path.join(log_file_dir, f'{operator_name}_accuracy_change.png') | 194 | output_image = os.path.join(log_file_dir, f'{operator_name}_accuracy_change.png') |
| @@ -0,0 +1,68 @@ | |||
| 1 | +import subprocess | ||
| 2 | +import sys | ||
| 3 | +from pathlib import Path | ||
| 4 | + | ||
| 5 | +SCRIPT_DIR = Path(__file__).resolve().parents[1] / "scripts" | ||
| 6 | +sys.path.insert(0, str(SCRIPT_DIR)) | ||
| 7 | + | ||
| 8 | +import plot_accuracy as pa # noqa: E402 | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +def test_cross_checkpoint_bleed_prevented(): | ||
| 12 | + lines = [ | ||
| 13 | + "01_first:\n", | ||
| 14 | + " Tolerance: rtol=1e-3, atol=1e-4\n", | ||
| 15 | + "02_second:\n", | ||
| 16 | + " Tolerance: rtol=2e-3, atol=2e-4\n", | ||
| 17 | + " Actual: rtol=5e-4, atol=1e-5\n", | ||
| 18 | + ] | ||
| 19 | + results = pa.parse_checkpoints(lines) | ||
| 20 | + assert len(results) == 1 | ||
| 21 | + assert results[0][0] == "02_second" | ||
| 22 | + assert results[0][1] == 2e-3 | ||
| 23 | + assert results[0][3] == 5e-4 | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def test_missing_tolerance_plots_and_prints_without_crash(tmp_path: Path): | ||
| 27 | + results = [ | ||
| 28 | + ("01_no_tol", None, None, 1e-4, 2e-5), | ||
| 29 | + ("02_with_tol", 1e-3, 1e-4, 5e-4, 5e-5), | ||
| 30 | + ] | ||
| 31 | + out_png = tmp_path / "out.png" | ||
| 32 | + pa.plot_accuracy(results, str(out_png)) | ||
| 33 | + assert out_png.is_file() | ||
| 34 | + assert out_png.stat().st_size > 1000 | ||
| 35 | + pa.print_summary(results) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def test_cli_utf8_and_error_exit_codes(tmp_path: Path): | ||
| 39 | + script = SCRIPT_DIR / "plot_accuracy.py" | ||
| 40 | + | ||
| 41 | + missing = subprocess.run( | ||
| 42 | + [sys.executable, str(script), str(tmp_path / "nonexistent.log")], | ||
| 43 | + capture_output=True, | ||
| 44 | + text=True, | ||
| 45 | + ) | ||
| 46 | + assert missing.returncode == 1 | ||
| 47 | + | ||
| 48 | + empty_log = tmp_path / "empty_verify_result.log" | ||
| 49 | + empty_log.write_text("# 无任何检查点\n", encoding="utf-8") | ||
| 50 | + empty_run = subprocess.run( | ||
| 51 | + [sys.executable, str(script), str(empty_log)], | ||
| 52 | + capture_output=True, | ||
| 53 | + text=True, | ||
| 54 | + ) | ||
| 55 | + assert empty_run.returncode == 1 | ||
| 56 | + | ||
| 57 | + ok_log = tmp_path / "matmul_verify_result.log" | ||
| 58 | + ok_log.write_text( | ||
| 59 | + "# 中文说明\n01_stage:\n Actual: rtol=1e-4, atol=1e-5\n", | ||
| 60 | + encoding="utf-8", | ||
| 61 | + ) | ||
| 62 | + ok_run = subprocess.run( | ||
| 63 | + [sys.executable, str(script), str(ok_log)], | ||
| 64 | + capture_output=True, | ||
| 65 | + text=True, | ||
| 66 | + ) | ||
| 67 | + assert ok_run.returncode == 0 | ||
| 68 | + assert (tmp_path / "matmul_accuracy_change.png").is_file() | ||