针对用户程序调用CANN软件栈接口可能出现的内存异常操作场景,msSanitizer检测工具提供了Device相关接口和AscendCL相关接口的内存检测能力,方便用户对程序内存异常操作位置的排查和定位。
当npu-smi info命令查询到的设备内存不断增大时,可使用本工具进行内存泄漏定位定界,若AscendCL系列接口泄漏可支持定位到代码行。
内存泄漏定位可分为以下步骤:
mssanitizer --check-device-heap=yes --leak-check=yes ./add_npu
待检测程序(以add_custom_npu为例)所在路径可配置为绝对路径或相对路径,请根据实际环境配置。
mssanitizer --check-cann-heap=yes --leak-check=yes ./add_npu
定位发生泄漏的代码文件和代码行时,需要将用户代码中原有的“acl/acl.h”头文件替换为工具中提供的msSanitizer API头文件“acl.h”,并将动态库libascend_acl_hook.so文件链接至用户的应用工程中,并重新编译应用工程,具体操作步骤请参见导入API头文件和链接动态库。
mssanitizer --check-cann-heap=yes --leak-check=yes ./add_npu
以下输出结果表明在调用应用程序main.cpp的第55行存在一次内存分配但未释放,至此可定位到内存泄漏的原因。
1 2 3 4 5 6 | ====== ERROR: LeakCheck: detected memory leaks ====== Direct leak of 32768 byte(s) ====== at 0x124080024000 on GM allocated in main.cpp:55 (serialNo:0) ====== SUMMARY: 32768 byte(s) leaked in 1 allocation(s) |
本示例以
git clone https://gitee.com/ascend/samples.git -b v1.0-8.1.RC1.alpha001
#include "data_utils.h" #ifndef ASCENDC_CPU_DEBUG // #include "acl/acl.h" // acl/acl.h 替换为 acl.h #include "acl.h" extern void add_custom_do(uint32_t blockDim, void *stream, uint8_t *x, uint8_t *y, uint8_t *z); #else
add_executable(ascendc_kernels_bbit ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp) target_compile_options(ascendc_kernels_bbit PRIVATE $<BUILD_INTERFACE:$<$<STREQUAL:${RUN_MODE},cpu>:-g>> -O2 -std=c++17 -D_GLIBCXX_USE_CXX11_ABI=0 -Wall -Werror ) # 算子可执行文件编译时,引入API头文件路径 target_include_directories(ascendc_kernels_bbit PUBLIC $ENV{ASCEND_HOME_PATH}/tools/mssanitizer/include/acl) # 算子可执行文件链接时,引入libascend_acl_hook.so动态库路径 target_link_directories(ascendc_kernels_bbit PRIVATE $ENV{ASCEND_HOME_PATH}/tools/mssanitizer/lib64) target_link_libraries(ascendc_kernels_bbit PRIVATE $<BUILD_INTERFACE:$<$<OR:$<STREQUAL:${RUN_MODE},npu>,$<STREQUAL:${RUN_MODE},sim>>:host_intf_pub>> $<BUILD_INTERFACE:$<$<STREQUAL:${RUN_MODE},cpu>:ascendcl>> ascendc_kernels_${RUN_MODE} # 将算子可执行文件链接至libascend_acl_hook.so动态库 ascend_acl_hook )
在安装昇腾AI处理器的服务器执行npu-smi info命令进行查询,获取Chip Name信息。实际配置值为AscendChip Name,例如Chip Name取值为xxxyy,实际配置值为Ascendxxxyy。
export LD_LIBRARY_PATH=${ASCEND_HOME_PATH}/tools/mssanitizer/lib64:$LD_LIBRARY_PATH mssanitizer --check-cann-heap=yes --leak-check=yes -- bash run.sh -r npu -v Ascendxxxyy