性能采集设计文档【免费下载链接】cann-bench评测AI在处理CANN领域代码任务的能力涵盖算子生成、算子优化等领域支撑模型选型、训练效果评估统一量化评估标准识别Agent能力短板构建CANN领域评测平台推动AI能力在CANN领域的持续演进。项目地址: https://gitcode.com/cann/cann-bench文档版本V0.2.0本文档详细描述评测工程的性能采集机制设计包括 NPU Profiler 采集、kernel_details.csv 解析、升频清 Cache、Warmup Kernel 精确过滤等核心机制。V0.2.0 更新说明2026-04-30Profiling 升级为 Level1默认/ Level2可选删除 Level0 支持数据源改为 kernel_details.csv47列支持 Input Shapes 精确形状匹配过滤 warmup删除_suppress_cann_profiler_errors()Level1/Level2 有完整数据无需抑制统计量改为中位数1. 设计目标性能采集模块的目标是获取NPU kernel-only 执行时间用于计算生成算子与基准性能的加速比。设计原则目标说明精准性只测量 NPU 内核执行时间排除 API 调用、Host 端开销一致性通过升频清 Cache 保证多次测量结果稳定防作弊InputPool 防止按 data_ptr 缓存输出的攻击容错性Trace 解析失败时降级到简单计时2. 核心架构┌─────────────────────────────────────────────────────────────────┐ │ OpRunner.run() │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ 1. to_device_batch(input_tensors) → NPU tensors │ │ │ │ 2. _update_params(params, device_tensors) │ │ │ └──────────────────────────────────────────────────────────┘ │ │ │ │ │ ┌───────────────▼───────────────┐ │ │ │ PerfEvaluator.run_profiled │ │ │ │ ┌────────────────────────┐ │ │ │ │ │ _prepare_warmup_tensors│ │ ← 10240×10240 fp16 │ │ │ │ MatMul ReduceMax │ │ 升频清 Cache │ │ │ └────────────────────────┘ │ │ │ │ │ │ │ │ │ ┌─────────▼─────────────┐ │ │ │ │ │ torch_npu.profiler │ │ ← Level1/Level2 │ │ │ │ schedule(warmup,repeat│ │ │ │ │ │ freq_boost per step│ │ │ │ │ └─────────┬─────────────┘ │ │ │ │ │ │ │ │ │ ┌─────────▼─────────────┐ │ │ │ │ │ kernel_details.csv │ │ ← 47列详细数据 │ │ │ │ (Input Shapes) │ │ │ │ │ └─────────┬─────────────┘ │ │ │ │ │ │ │ │ │ ┌─────────▼─────────────┐ │ │ │ │ │ _parse_kernel_details │ │ ← 精确形状匹配 │ │ │ │ _is_warmup_kernel │ │ 过滤 warmup │ │ │ └─────────┬─────────────┘ │ │ │ │ │ │ │ │ │ PerfResult │ │ │ └──────────────┴────────────────┘ │ └─────────────────────────────────────────────────────────────────┘3. 采集流程3.1 主流程def run_profiled(case_id, func, *args, warmup3, repeat5): # 1. 准备升频清 Cache tensors if freq_boost: _prepare_warmup_tensors() # MatMul ReduceMax tensors # 2. 创建 profiling 目录 prof_dir freports/prof_data/{level}/{op_name}/{caseid}/ # 3. 执行 warmup repeat 周期Level1/Level2 with torch_npu.profiler.profile( scheduleschedule(wait0, warmupwarmup, activerepeat), on_trace_readytensorboard_trace_handler(prof_dir), experimental_config_ExperimentalConfig( profiler_levelProfilerLevel.Level1, # 默认 Level1 ), ): for _ in range(warmup repeat): _boost_freq_and_clear_cache() # 每次调用前升频 func(*args) prof.step() # 4. 定位并解析 kernel_details.csv47列 csv_file locate_kernel_details_csv(prof_dir) op_times, total_us _parse_kernel_details_csv(csv_file) # 5. 按 repeat 次数归一化使用中位数 elapsed_us median(op_times.values()) return outputs, PerfResult(elapsed_us, op_times)3.2 时序图时间 ─────────────────────────────────────────────────────────────▶ ┌─────────────────────────────────────────────────────────────┐ │ torch_npu.profiler.profile() 上下文 │ └─────────────────────────────────────────────────────────────┘ │ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │ Warmup 1 │ │ Warmup 2 │ │ Warmup 3 │ │ │────────────│ │────────────│ │────────────│ │ │ boost_freq │ │ boost_freq │ │ boost_freq │ │ │ func() │ │ func() │ │ func() │ │ │ prof.step()│ │ prof.step()│ │ prof.step()│ │ └────────────┘ └────────────┘ └────────────┘ │ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │ Active 1 │ │ Active 2 │ │ Active 3 │ │ Active 4 │ │ Active 5 │ │ │────────────│ │────────────│ │────────────│ │────────────│ │────────────│ │ │ boost_freq │ │ boost_freq │ │ boost_freq │ │ boost_freq │ │ boost_freq │ │ │ func() │ │ func() │ │ func() │ │ func() │ │ func() │ │ │ prof.step()│ │ prof.step()│ │ prof.step()│ │ prof.step()│ │ prof.step()│ │ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ on_trace_handler → trace_view.json │ └─────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────┐ │ _parse_trace_file() → PerfResult │ └─────────────────────────────────────────────────────────────┘4. 核心组件4.1 PerfEvaluator职责NPU 性能采集与 Trace 解析。关键参数参数类型默认值说明enabledboolFalse是否启用 Profilerwarmupint3预热次数repeatint5采集次数archive_profboolTrue是否归档 profiling 数据freq_boostboolTrue是否启用升频清 Cache核心方法方法职责run_profiled()主入口执行 profiling 并返回结果_prepare_warmup_tensors()创建升频清 Cache 的 MatMul ReduceMax tensors_boost_freq_and_clear_cache()执行 MatMul ReduceMax 升频清 L2 Cache_profile()执行 torch_npu.profiler.profile() 上下文_parse_trace_file()解析 Chrome Trace JSON_normalize_result()按 repeat 次数归一化结果4.2 OpRunner职责算子执行与性能采集协调。核心方法方法职责run()执行算子自动选择 Profiler 或简单计时run_ai_op()执行 AI 算子支持 enable_perf 参数_run_simple()简单计时执行Profiler 禁用时_update_params()将设备张量替换参数中的 CPU 张量引用4.3 InputPool职责防止 data_ptr 缓存攻击。原理攻击者可能按 tensor.data_ptr() 缓存输出相同输入地址返回预计算结果。InputPool 预分配多个 clone 输入轮换使用保证每次调用的 data_ptr 都不同。关键参数参数默认值说明max_pool_size8最大池大小max_memory_mb512最大内存占用MB使用方式pool InputPool(inputs, pool_sizewarmup repeat) for _ in range(warmup repeat): inputs pool.get_next() # 每次 data_ptr 不同 output func(*inputs)5. Profiler 配置5.1 torch_npu.profiler 参数# Level1默认或 Level2 配置 profiler_level torch_npu.profiler.ProfilerLevel.Level1 # 默认 if config.profiler_level Level2: profiler_level torch_npu.profiler.ProfilerLevel.Level2 experimental_config torch_npu.profiler._ExperimentalConfig( export_type[torch_npu.profiler.ExportType.Text], profiler_levelprofiler_level, aic_metricstorch_npu.profiler.AiCMetrics.AicPipeUtilization, ) with torch_npu.profiler.profile( activities[ torch_npu.profiler.ProfilerActivity.CPU, torch_npu.profiler.ProfilerActivity.NPU, ], scheduletorch_npu.profiler.schedule( wait0, warmupwarmup, activerepeat, repeat1 ), on_trace_readytorch_npu.profiler.tensorboard_trace_handler(prof_dir), record_shapesFalse, profile_memoryFalse, with_stackFalse, experimental_configexperimental_config, ) as prof: for _ in range(warmup repeat): _boost_freq_and_clear_cache() func(*args) prof.step()5.2 Profiler Level 选择Level数据量CSV 列数适用场景Level1中等47默认级别包含 Input Shapes 用于精确 warmup 过滤Level2详细47全量采集更详细的 AICPU 指标选择 Level1 的原因实验验证Level1/Level2 与 Level0 耗时无差异提供 Input Shapes 列支持精确形状匹配过滤 warmup kernel47 列数据维度丰富包含 AICPU 等不会产生 CANN parser ERROR数据完整6. CSV 解析6.1 kernel_details.csv 结构Level1/Level2 profiling 自动产出kernel_details.csv包含 47 列详细数据关键列列名说明用途OP Type算子类型如 MatMul, ReduceMaxwarmup 过滤Input Shapes输入形状如10240,10240;10240,10240精确 warmup 过滤Task Duration (us)NPU kernel 执行时间核心测量对象OP Name具体算子名如 aclnnExp结果记录6.2 Warmup Kernel 精确过滤使用 OP Type Input Shapes 精确匹配过滤 warmup kernels# Warmup kernel 形状特征 WARMUP_MATMUL_SHAPE 10240,10240;10240,10240 WARMUP_REDUCE_SHAPE 96,1024,1024;3 def _is_warmup_kernel(op_type: str, input_shapes: str) - bool: 精确形状匹配判断 warmup kernel if op_type MatMul and input_shapes WARMUP_MATMUL_SHAPE: return True if op_type ReduceMax and input_shapes WARMUP_REDUCE_SHAPE: return True return False优势精确匹配不会误过滤同名算子如测试名为 Max 的算子基于 Input Shapes 列数据可靠替代了脆弱的名称子串匹配6.3 解析逻辑def _parse_kernel_details_csv(csv_file): import pandas as pd df pd.read_csv(csv_file) device_kernels {} durations [] for row in df.itertuples(): op_type getattr(row, OP Type, ) input_shapes getattr(row, Input Shapes, ) duration getattr(row, Task Duration (us), 0) # 精确形状匹配过滤 warmup if _is_warmup_kernel(op_type, input_shapes): continue op_name getattr(row, OP Name, op_type) device_kernels[op_name] device_kernels.get(op_name, 0) duration durations.append(duration) # 中位数统计更稳定 elapsed_us median(durations) if durations else 0 return device_kernels, elapsed_us7. 升频清 Cache7.1 目的每次测量前执行 MatMul ReduceMax升频将 NPU 频率提升到稳定状态清 Cache清空 L2 Cache保证测量一致性7.2 实现细节def _prepare_warmup_tensors(): device self.device_manager.get_device() # MatMul tensors: 10240×10240 fp16 mm1 torch.rand((10240, 10240), dtypetorch.float16).to(device) mm2 torch.rand((10240, 10240), dtypetorch.float16).to(device) # Reduce tensor: 96×1024×1024 fp16 reduce_input torch.rand((96, 1024, 1024), dtypetorch.float16).to(device) self._warmup_tensors (mm1, mm2, reduce_input) def _boost_freq_and_clear_cache(): mm1, mm2, reduce_input self._warmup_tensors torch.matmul(mm1, mm2) torch.npu.synchronize(mm1.device) # 同步目标设备而非默认设备 torch.max(reduce_input) torch.npu.synchronize(mm1.device)7.3 设备同步设计要点同步目标设备mm1.device而非默认设备。torch.npu.synchronize(mm1.device) # 正确同步 warmup tensor 所在设备 torch.npu.synchronize() # 错误同步当前设备可能与 warmup tensor 不同原因.npu()无参数时迁移到当前设备默认 0可能导致 warmup tensor 与测试 tensor 在不同设备上。8. CPU Fallback当 Profiler 禁用或 NPU 不可用时使用简单计时def _measure_simple(func, warmup, repeat): # Warmup for _ in range(warmup): func(*args) # Measure times [] for _ in range(repeat): torch.npu.synchronize() if npu_available t0 time.perf_counter() func(*args) torch.npu.synchronize() if npu_available times.append((time.perf_counter() - t0) * 1_000_000) elapsed_us sum(times) / len(times) return PerfResult(elapsed_uselapsed_us)差异对比方式测量内容精度ProfilerNPU kernel-only高排除 API 开销SimpleWall-clock含 API低作为兜底10. 数据归档10.1 目录结构reports/prof_data/ ├── level1/ │ ├── Exp/ │ │ ├── 1/ │ │ │ └── trace_view.json │ │ ├── 2/ │ │ │ └── trace_view.json │ │ └── ... │ ├── Add/ │ └── ... ├── level2/ │ └── ... └── level3/ └── ...10.2 case_id 解析def _parse_case_id(case_id): # L2_Gcd_5 → (level2, Gcd, 5) m re.match(r^L(?Plevel\d)_(?Pop.)_(?Pcase\d)$, case_id) if not m: return level_unknown, case_id, 0 return flevel{m[level]}, m[op], m[case]11. 配置参数参数配置来源默认值说明enable_profilerConfig / CLI--no-perfTrue是否启用 ProfilerwarmupConfig / CLI--warmup3预热次数repeatConfig / CLI--repeat5采集次数freq_boostPerfEvaluator 初始化True是否升频清 Cachearchive_profPerfEvaluator 初始化True是否归档 Trace 数据use_input_poolrun_profiled 参数False是否启用 InputPoolprofiler_levelConfig / CLI--profiler-levellevel1Profiler 级别level0/level111. 设计问题与改进方向11.1 Warmup Kernel 过滤已解决历史问题使用名称子串匹配过滤 warmup kernels可能误过滤同名算子。已实施改进升级到 Level1 profiling使用kernel_details.csv的 Input Shapes 列精确形状匹配WARMUP_MATMUL_SHAPE 10240,10240;10240,10240 WARMUP_REDUCE_SHAPE 96,1024,1024;3 def _is_warmup_kernel(op_type: str, input_shapes: str) - bool: if op_type MatMul and input_shapes WARMUP_MATMUL_SHAPE: return True if op_type ReduceMax and input_shapes WARMUP_REDUCE_SHAPE: return True return False效果不再误过滤测试名为 Max 或 Matmul 的算子。11.2 统计量改为中位数现状已从平均值改为中位数统计。原因中位数对异常值更稳定与 inner/perf_engine.py 保持一致。12. Level1 Profiling 升级已完成12.1 升级内容已完成升级2026-04-30变更项原方案新方案Profiler LevelLevel0Level1默认/ Level2可选数据源trace_view.jsonkernel_details.csv47列Warmup 过滤名称子串匹配Input Shapes 精确形状匹配统计量平均值中位数ERROR 抑制_suppress_cann_profiler_errors()已删除Level1/Level2 无 ERROR12.2 实验验证结论指标Level0Level1Level2耗时5.69s5.67s5.69sCSV 列数94747Input Shapes❌ 无✓ 有✓ 有结论Level1/Level2 耗时无增加提供丰富数据用于精确 warmup 过滤。12.3 配置参数参数配置来源默认值说明profiler_levelConfigLevel1Profiler 级别--profiler-levelCLILevel1可选值: Level1, Level2--task-dir| CLI | kernel_bench | 评测目录替代 --level |--device-id| CLI | None | NPU 设备 ID未指定则多卡并行 | |--processes-per-card| CLI | 2 | 多卡并行时每卡进程数 | |--timeout-per-process| CLI | 300 | 多卡并行时单进程超时秒 | |--no-perf| CLI | False | 关闭性能采集仅精度验证 | |--warmup| CLI | 3 | 预热次数 | |--repeat| CLI | 5 | 采集次数 |13. CLI 入口统一13.1 职责划分评测入口统一后各脚本职责明确脚本职责独特能力src/kernel_eval/cli.py核心评测入口所有评测能力--dir、多卡并行、--no-perf、--source-dirtests/run_simple.pyGolden 特化Golden 伪装NPU 模式、CPU 模式验证scripts/run_evaluation.shCLI 封装无纯参数转发scripts/run_test.shrun_simple.py 封装无纯参数转发13.2 CLI 核心能力python -m kernel_eval.cli eval支持以下参数目录与筛选--dir path评测目录kernel_bench/level1/exp 等--operator name按算子名称筛选--case-id id按用例编号筛选设备配置--device cpu|npu设备类型--device-id id单卡模式不指定则多卡并行--processes-per-card n多卡并行时每卡进程数--timeout-per-process n多卡并行时单进程超时性能配置--warmup n预热次数--repeat n采集次数--no-perf关闭性能采集--profiler-level Level1|Level2Profiler 级别源码评测--source-dir dirAI 生成算子源码目录自动编译安装13.3 多卡并行模式CLI 自动判断多卡并行模式# 多卡并行条件NPU 未指定 device_id 无 source_dirGolden 模式 use_multi_card ( args.device npu and args.device_id is None and not args.source_dir )多卡并行使用ProcessPoolCoordinator每张 NPU 卡运行processes_per_card个进程进程间无通信通过文件传递结果每进程独立初始化torch_npu.profiler13.4 run_simple.py 保留能力tests/run_simple.py仅保留两个特化能力Golden 伪装将 golden 函数伪装成 AI 算子用于 NPU 模式验证CPU 模式纯 CPU 验证 golden 可执行不采集性能# CPU 模式run_simple.py 特化 python tests/run_simple.py --cpu --operator Exp # NPU 模式 Golden 伪装run_simple.py 特化 python tests/run_simple.py --npu --operator Exp # NPU 多卡并行应使用 CLI python -m kernel_eval.cli eval --operator Exp14. 相关文件文件职责src/kernel_eval/eval/perf_eval.py性能采集核心实现src/kernel_eval/eval/op_runner.py算子执行与性能协调src/kernel_eval/eval/input_pool.pyInputPool 防缓存攻击src/kernel_eval/utils/device_manager.py设备管理与同步src/kernel_eval/config.py全局配置warmup/repeat 等【免费下载链接】cann-bench评测AI在处理CANN领域代码任务的能力涵盖算子生成、算子优化等领域支撑模型选型、训练效果评估统一量化评估标准识别Agent能力短板构建CANN领域评测平台推动AI能力在CANN领域的持续演进。项目地址: https://gitcode.com/cann/cann-bench创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考