### 安装 run 包 Source: https://github.com/ascend/msprof/blob/master/docs/zh/install_guide/msprof_install_guide.md 执行安装命令,支持 --install-path 等参数。安装成功后显示 'mindstudio-profiler package install success.'。 ```shell ./mindstudio-profiler__{arch}.run --install ``` -------------------------------- ### 编译 run 包(--mode=all) Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 编译包含采集和解析功能的完整软件包,版本号由 --version 指定。 ```bash bash build/build.sh --mode=all --version= ``` -------------------------------- ### Set TMPDIR to resolve Not enough space left in /root during installation Source: https://github.com/ascend/msprof/blob/master/docs/zh/support/faq.md When installing mindstudio-profiler_26.0.0_aarch64.run fails with 'Not enough space left in /root', the installer uses /root as a temporary directory during extraction. Create a temporary directory with more space, set TMPDIR to it, then run the installer. ```bash mkdir -p /path/to/tmpdir export TMPDIR=/path/to/tmpdir ./mindstudio-profiler_26.0.0_aarch64.run --install ``` -------------------------------- ### 编译 run 包(--mode=analysis) Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 编译仅包含解析功能的软件包,版本号由 --version 指定。 ```bash bash build/build.sh --mode=analysis --version= ``` -------------------------------- ### Set msprof_analysis library prefix and install path Source: https://github.com/ascend/msprof/blob/master/analysis/csrc/CMakeLists.txt Configures the msprof_analysis target to remove the 'lib' prefix from the built library and installs it to the parent directory's lib64 folder. The install command uses OPTIONAL to avoid failure if the target is not built. ```CMake # 去掉lib前缀 set_target_properties(msprof_analysis PROPERTIES PREFIX "") # 指定安装路径 install(TARGETS msprof_analysis OPTIONAL LIBRARY DESTINATION ${CMAKE_SOURCE_DIR}/../lib64 ) ``` -------------------------------- ### 最小化采集验证命令 msprof --application Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 功能开发完成后建议先执行的最小化采集验证命令,指定应用和输出目录。若功能正常,通常会在输出目录下生成 PROF_XXX 目录结构。 ```bash msprof --application="python train.py" --output=/home/prof_output ``` -------------------------------- ### aclrtsStreamGetAttribute Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/MindStudio Profiler性能调优特性分析与设计说明书.md Retrieves a stream attribute for profiling control in aclGraph scenarios. This function gets the value of a previously set attribute from a stream. ```APIDOC ## [GET] aclrtsStreamGetAttribute ### Description Retrieves a stream attribute for profiling control in aclGraph scenarios. This function gets the value of a previously set attribute from a stream. ### Method GET ### Endpoint aclrtsStreamGetAttribute ### Parameters #### Parameters - **stm** (rtStream_t) - Required - The stream object. - **stmAttrId** (rtStreamAttr) - Required - The attribute ID (key) to retrieve. - **attrValue** (rtStreamAttrValue_t*) - Required - Pointer to store the retrieved attribute value. ### Response #### Success Response (0) - **error code** (rtError_t) - Returns an error code indicating success or failure. #### Response Example ``` 0 ``` ``` -------------------------------- ### 重载并重启 Docker 服务 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 保存代理配置后执行,使配置生效。 ```bash sudo systemctl daemon-reload sudo systemctl restart docker ``` -------------------------------- ### 解析验证命令 msprof.py import Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 将 PROF_XXX 目录导入到 msprof 数据库的命令,用于验证导入链路。 ```bash python3 msprof.py import -dir /home/profiler_data/PROF_XXX ``` -------------------------------- ### gil_trace_record_start(pid_list=None, duration=-1) Source: https://github.com/ascend/msprof/blob/master/misc/gil_tracer/README.md API to start GIL data collection programmatically. Allows embedding collection into application logic with dynamic control. ```APIDOC ## [API] gil_trace_record_start ### Description Starts GIL data collection for specified processes or all NPU Python processes. ### Method Python Function ### Endpoint `gil_trace_record_start(pid_list=None, duration=-1)` ### Parameters #### Optional Arguments - **pid_list** (list of int) - Optional - List of process IDs to collect GIL data from. Default: None (all NPU Python processes). - **duration** (integer) - Optional - Collection duration in seconds. Default: -1 (continuous until `gil_trace_record_stop()` is called). ### Request Example ```python from gil_trace_record import gil_trace_record_start gil_trace_record_start(pid_list=[os.getpid()], duration=10) ``` ### Response #### Success Response Starts collection; data files generated in sysTrace data directory (default `/home/sysTrace/GIL`) with filename format `GIL__rank_.json`. ``` -------------------------------- ### 使用 msprof 采集所有打点数据 Source: https://github.com/ascend/msprof/blob/master/samples/README.md 正常执行 sample_run.sh 脚本时,使用 msprof 配置 --msproftx=on 采集所有打点数据,包括默认 domain 和用户自定义 domain 范围内的数据。 ```bash msprof --msproftx=on bash sample_run.sh ``` -------------------------------- ### Use FunctionMonitorContext in PyTorch script Source: https://github.com/ascend/msprof/blob/master/misc/function_monitor/README.md Wrap the code block to monitor with FunctionMonitorContext. The func_name and threshold_ms parameters are required; process_name is optional. The example runs a model function 10 times. ```python import os import torch from function_monitor import FunctionMonitorContext def model_run(): size = 1024 A = torch.rand(size, size, dtype=torch.float32, requires_grad=False).npu() B = torch.rand(size, size, dtype=torch.float32, requires_grad=False).npu() with FunctionMonitorContext(func_name='torch_operator_run', threshold_ms=1): for i in range(10): C = torch.matmul(A, B) D = torch.nn.functional.relu(C) E = torch.nn.functional.layer_norm(D, D.size()[1:]) if __name__ == '__main__': for i in range(10): model_run() ``` -------------------------------- ### 获取设备信息命令格式 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/extended_functions.md 使用get_msprof_info.py脚本获取设备信息。命令格式为:python3 get_msprof_info.py -dir [--help]。-dir或--collection-dir为必选参数,指定收集到的Profiling数据目录;-h或--help为可选参数,显示帮助信息。 ```bash python3 get_msprof_info.py -dir [--help] ``` -------------------------------- ### msprof.py query 命令格式 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/extended_functions.md 查询性能数据文件信息的命令格式,需先执行 import 命令解析数据,否则查询结果无意义。 ```bash python3 msprof.py query -dir ``` -------------------------------- ### 下载三方依赖(download_thirdparty.sh) Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 运行脚本下载构建所需的三方依赖。 ```bash bash scripts/download_thirdparty.sh ``` -------------------------------- ### 非集群场景获取设备信息示例 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/extended_functions.md 在非集群场景下,使用get_msprof_info.py脚本获取设备信息。命令示例指定了PROF_XXX目录下的device_0目录作为-dir参数。 ```bash python3 get_msprof_info.py -dir /home/1/PROF_000001_20220129014731273_KEDKPORHMAGPGD/device_0 ``` -------------------------------- ### 将当前用户加入 Docker 用户组 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 解决 Docker 命令 permission denied 错误,需以 root 权限执行,替换 <当前用户名> 为实际用户名。执行后需重新登录或运行 newgrp docker 使变更生效。 ```bash sudo usermod -aG docker <当前用户名> ``` -------------------------------- ### 多采集进程性能数据目录结构 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/msprof_parsing_instruct.md 多 Device 场景下,若启动多采集进程则生成多个 PROF_XXX 目录,每个目录下包含 device 目录、host 目录、msprof_*.db 文件和 mindstudio_profiler_output 目录。device 目录在 PROF_XXX 目录下生成,每个 PROF_XXX 目录下生成多少个 device 目录与用户实际操作有关,不影响性能数据分析。 ```ColdFusion └── PROF_XXX1 ├── device_0 │ └── data ├── host │ └── data ├── msprof_*.db └── mindstudio_profiler_output ├── msprof_*.json ├── step_trace_*.json ├── xx_*.csv ... └── README.txt └── PROF_XXX2 ├── device_1 │ └── data ├── host │ └── data ├── msprof_*.db └── mindstudio_profiler_output ├── msprof_*.json ├── step_trace_*.json ├── xx_*.csv ... └── README.txt ``` -------------------------------- ### 单采集进程目录结构 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/extended_functions.md 单采集进程下生成的Profiling数据目录结构。 ```ColdFusion └── PROF_XXX ├── device_0 │ └── data ├── device_1 │ └── data ├── host │ └── data ├── msprof_*.db └── mindstudio_profiler_output ├── msprof_{timestamp}.json ├── step_trace_{timestamp}.json ├── xx_*.csv ... └── README.txt ``` -------------------------------- ### 导出summary数据和db文件 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/extended_functions.md 导出summary数据和db文件。需要先完成解析性能数据。 ```bash python3 msprof.py export summary -dir [--model-id ] [--iteration-id ] [--iteration-count ] [--format ] [--clear] ``` -------------------------------- ### 绑核命令格式 Source: https://github.com/ascend/msprof/blob/master/misc/host_analyzer/README.md 自定义绑核功能的命令行入口,支持可选日志等级和配置文件参数。 ```bash python3 entrance.py bind [-l] [-c ] ``` -------------------------------- ### 获取 msprof 代码(git clone) Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 在编译容器中执行,克隆 msprof 仓库并进入目录。 ```bash git clone https://gitcode.com/Ascend/msprof.git cd msprof ``` -------------------------------- ### 解析验证命令 msprof --export=on Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 对解析链路改动时建议验证的导出命令,开启导出功能并指定 PROF_XXX 目录。 ```bash msprof --export=on --output=/home/profiler_data/PROF_XXX ``` -------------------------------- ### 容器内安装 Python 依赖 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在容器内执行,安装 networkx、pillow、PyTorch CPU 版、torchvision 和 torch_npu。若企业内网安装失败,需参考离线安装方案。 ```bash pip3 install networkx==3.6.1 pillow==12.2.0 pip3 install https://inst.obs.cn-north-4.myhuaweicloud.com/env/mirror/$(arch)/download.pytorch.org/whl/cpu/torch-2.7.1%2Bcpu-cp311-cp311-manylinux_2_28_$(arch).whl pip3 install torchvision==0.22.1 --index-url https://download.pytorch.org/whl/cpu pip3 install https://gitcode.com/Ascend/pytorch/releases/download/v26.0.0-pytorch2.7.1/torch_npu-2.7.1.post4-cp311-cp311-manylinux_2_28_$(arch).whl ``` -------------------------------- ### 解析验证命令 msprof.py export summary 和 db Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 必要时继续验证的导出命令,分别导出 summary 和 db 数据。 ```bash python3 msprof.py export summary -dir /home/profiler_data/PROF_XXX python3 msprof.py export db -dir /home/profiler_data/PROF_XXX ``` -------------------------------- ### 执行卸载 Source: https://github.com/ascend/msprof/blob/master/docs/zh/install_guide/msprof_install_guide.md 执行卸载命令,{tools_name} 配置为需卸载的工具名称,可通过 python ms_install.py help 查询。卸载成功打印 'Successfully uninstalled 1 tool ({tools_name})'。 ```bash python ms_install.py uninstall {tools_name} ``` -------------------------------- ### 查看最新 PROF_XXX 结果目录 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在采集命令执行完成后运行,定位最新生成的 PROF_XXX 目录并查看其结构。输出目录同时包含原始数据和解析导出结果,实际文件取决于采集内容和导出类型。 ```bash PROF_DIR=$(ls -dt "${HOME}"/prof_output/PROF_* | head -n 1) echo "${PROF_DIR}" tree -L 1 "${PROF_DIR}" tree -L 1 "${PROF_DIR}/mindstudio_profiler_output" ``` -------------------------------- ### 使用 docker cp 拷贝 Profiling 数据到本地 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在宿主机终端执行,将容器内的 PROF_XXX 目录拷贝到当前目录,以便在 MindStudio Insight 中导入。 ```bash docker cp "${CONTAINER_ID}:${PROF_DIR}" ./ ``` -------------------------------- ### msprof 带 reports 参数的业务应用执行命令(测试用例) Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/Mindstudio 26.1.0性能调优技术方案设计.md 测试用例中用于验证 msprof 命令行支持 reports 参数的执行命令,通过 --reports 指定配置文件。 ```bash msprof --output=* ./main [args] --reports="reports_sample_config.json" ``` -------------------------------- ### msprof 业务应用执行命令(测试用例) Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/Mindstudio 26.1.0性能调优技术方案设计.md 测试用例中用于执行业务应用的 msprof 命令,通过 --output 指定输出目录,用于采集性能数据。 ```bash msprof --output=* ./main [args] ``` -------------------------------- ### 采集输出目录结构 PROF_XXX Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 采集成功后输出目录下生成的典型目录结构,包含 host/data、device_{id}/data、msprof_{timestamp}.db 和 mindstudio_profiler_output 等。 ```text PROF_XXX ├── host │ └── data ├── device_{id} │ └── data ├── msprof_{timestamp}.db └── mindstudio_profiler_output ├── msprof_{timestamp}.json ├── op_summary_{timestamp}.csv └── ... ``` -------------------------------- ### 解析验证命令 msprof.py query Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 查询 PROF_XXX 目录中数据的命令,用于验证查询链路。 ```bash python3 msprof.py query -dir /home/profiler_data/PROF_XXX ``` -------------------------------- ### 集群场景获取设备信息示例 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/extended_functions.md 在集群场景下,使用get_msprof_info.py脚本获取设备信息。命令示例指定PROF_XXX目录的父目录作为-dir参数。 ```bash python3 get_msprof_info.py -dir /home/1/ ``` -------------------------------- ### 下载 Python 依赖包 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在具备公网访问能力、与内网 NPU 服务器 CPU 架构相同且使用相同 Python 版本的中转环境中执行,将 xxx 替换为实际包名。 ```bash mkdir -p offline_wheels python3 -m pip download xxx --dest offline_wheels ``` -------------------------------- ### 开启碎片缓解环境变量(GE_USE_STATIC_MEMORY 和 PYTORCH_NPU_ALLOC_CONF) Source: https://github.com/ascend/msprof/blob/master/docs/zh/best_practices/memory_fragmentation.md 用于验证内存碎片问题,分别针对 GE 侧和框架侧开启碎片缓解。设置后短序列场景下 reserved 增长明显缓解,涨幅从约 600MB 降至约 75MB。 ```bash export GE_USE_STATIC_MEMORY=3 export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True ``` -------------------------------- ### 克隆msprof仓库 Source: https://github.com/ascend/msprof/blob/master/docs/zh/contributing/contributing_guide.md 克隆Fork后的msprof仓库到本地进行代码开发。 ```bash git clone https://gitcode.com//msprof.git cd msprof ``` -------------------------------- ### 单采集进程性能数据目录结构 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/msprof_parsing_instruct.md 执行 msprof --export 命令后,会在 PROF_XXX 目录下生成 mindstudio_profiler_output 目录。单采集进程场景下,仅生成一个 PROF_XXX 目录,其中包含 device_0、device_1、host 等子目录,以及 msprof_*.db 文件和 mindstudio_profiler_output 目录。 ```ColdFusion └── PROF_XXX ├── device_0 │ └── data ├── device_1 │ └── data ├── host │ └── data ├── msprof_*.db └── mindstudio_profiler_output ├── msprof_*.json ├── step_trace_*.json ├── xx_*.csv ... └── README.txt ``` -------------------------------- ### reports_sample_config.json 配置示例 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/msprof_parsing_instruct.md reports_sample_config.json 文件默认保存在 ${INSTALL_DIR}/tools/profiler/profiler_tool/analysis/msconfig/ 目录下,也可在任意有读写权限的目录下自行创建。该文件控制相应性能数据的开关,可配置开启(true)或关闭(false 或删除字段),控制的性能数据包括 msprof_*.json 文件的 timeline 数据层级(如 CANN、Ascend Hardware、AI Core Freq、片上内存、Communication、Overlap Analysis、NPU_MEM 层级等)。需确保文件格式正确,否则可能导致 --reports 参数不生效或文件读取失败。 ```json { "json_process": { "ascend": true, "acc_pmu": true, "cann": true, "ddr": true, "stars_chip_trans": true, "hbm": true, "communication": true, "hccs": true, "os_runtime_api": true, "network_usage": true, "disk_usage": true, "memory_usage": true, "cpu_usage": true, "msproftx": true, "npu_mem": true, "overlap_analyse": true, "pcie": true, "sio": true, "stars_soc": true, "step_trace": true, "freq": true, "llc": true, "nic": true, "roce": true, "qos": true, "device_tx": true, "ccu": true, "biu_perf": true, "ub": true, "block_detail": true } } ``` -------------------------------- ### 导出summary数据和db文件(使用示例) Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/extended_functions.md 使用示例:导出summary数据和db文件。 ```bash python3 msprof.py export summary -dir /home/HwHiAiUser/profiler_data/PROF_XXX ``` -------------------------------- ### 离线导入 CANN 镜像(内网服务器加载) Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 将 cann.tar 传输至内网服务器后执行,加载完成后继续第 3.2 节并返回第 2.1.5 节启动容器。 ```bash docker load -i cann.tar docker images | grep cann ``` -------------------------------- ### msprof_slice.json 配置文件示例 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/extended_functions.md 用于配置性能数据文件分片属性。默认关闭分片,slice_file_size 为 0,strategy 为 0。配置文件保存于 ${INSTALL_DIR}/tools/profiler/profiler_tool/analysis/msconfig。 ```json { "slice_switch": "off", "slice_file_size(MB)": 0, "strategy": 0 } ``` -------------------------------- ### PyTorch Profiler 采集 Host 侧系统调用配置 Source: https://github.com/ascend/msprof/blob/master/docs/zh/best_practices/syscall_high_latency.md 用于采集 Host 侧系统调用信息,与 CANN 层 Profiling 数据联合分析。需设置 host_sys=[torch_npu.profiler.HostSystem.OSRT] 以采集进程级别的系统调用,并配合 schedule 与 prof.step() 使用。 ```python import torch_npu experimental_config = torch_npu.profiler._ExperimentalConfig( profiler_level=torch_npu.profiler.ProfilerLevel.Level0, aic_metrics=torch_npu.profiler.AiCMetrics.AiCoreNone, data_simplification=False, host_sys=[torch_npu.profiler.HostSystem.OSRT], # 采集进程级别的系统调用 ) # 添加Profiling采集基础配置参数,详细参数介绍可参考下文的参数说明 with torch_npu.profiler.profile( activities=[ torch_npu.profiler.ProfilerActivity.CPU, torch_npu.profiler.ProfilerActivity.NPU ], schedule=torch_npu.profiler.schedule(wait=0, warmup=0, active=1, repeat=1, skip_first=0), # 与prof.step()配套使用 on_trace_ready=torch_npu.profiler.tensorboard_trace_handler("./result"), experimental_config=experimental_config) as prof: # 启动性能数据采集 for step in range(steps): # 训练迭代 train_one_step() # 训练函数 prof.step() # 与schedule配套使用 ``` -------------------------------- ### 配置 Docker 代理(http-proxy.conf) Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 适用于 Docker 版本 ≥ 18.0 的 Linux 环境。编辑 /etc/systemd/system/docker.service.d/http-proxy.conf,根据实际环境替换用户名、密码、代理地址及端口。 ```text [Service] Environment="HTTP_PROXY=http://username:password@proxy.example.com:8080" Environment="HTTPS_PROXY=http://username:password@proxy.example.com:8080" Environment="NO_PROXY=localhost,127.0.0.1,.example.com" ``` -------------------------------- ### 下载容器启动脚本 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在宿主机执行,下载 ctr_in.py 脚本并赋予执行权限。若网络受限无法下载,需参考离线传输方案。 ```bash cd ~ && curl -fLO --retry 3 https://inst.obs.cn-north-4.myhuaweicloud.com/env/ctr_in.py && chmod +x ctr_in.py ``` -------------------------------- ### 采集性能数据:torch_npu.profiler 配置 Source: https://github.com/ascend/msprof/blob/master/docs/zh/best_practices/communication_address_misalignment.md 用于采集完整训练 step 的 profiling 数据,确认通信耗时占比及具体算子。需设置 profile_level 为 ProfilerLevel.Level1 才能采集到 HCCL 通信算子的完整数据,with_stack=True 记录调用栈,schedule 需保证 active 覆盖足够的 step。 ```python with torch_npu.profiler.profile( activities=[torch_npu.profiler.ProfilerActivity.CPU, torch_npu.profiler.ProfilerActivity.NPU], schedule=torch_npu.profiler.schedule(wait=1, warmup=1, active=5, repeat=1), on_trace_ready=torch_npu.profiler.tensorboard_trace_handler(output_dir), profile_level=torch_npu.profiler.ProfilerLevel.Level1, with_stack=True, ): ... ``` -------------------------------- ### 解析验证命令 msprof.py export timeline Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 导出时间线数据的命令,用于验证 timeline 导出功能。 ```bash python3 msprof.py export timeline -dir /home/profiler_data/PROF_XXX ``` -------------------------------- ### 获取容器 ID 和 PROF_DIR 变量赋值语句 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在容器内执行,输出 CONTAINER_ID 和 PROF_DIR 的变量赋值语句,用于后续在宿主机上通过 docker cp 拷贝 Profiling 数据。 ```bash echo "CONTAINER_ID=${HOSTNAME:-$(cat /etc/hostname)}; PROF_DIR=${PROF_DIR}" ``` -------------------------------- ### msprof --parse=on --output= [--python-path=] Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/msprof_parsing_instruct.md 解析原始性能数据文件,生成sqlite目录及db文件。该命令仅进行性能数据解析,不导出性能数据文件,适用于解析失败后重新解析或配合指定迭代导出等场景。 ```APIDOC ## [CLI] msprof --parse=on --output= [--python-path=] ### Description 解析原始性能数据文件,生成sqlite目录及db文件。该命令仅进行性能数据解析,不导出性能数据文件,适用于解析失败后重新解析或配合指定迭代导出等场景。 ### Method CLI ### Endpoint msprof --parse=on --output= [--python-path=] ### Parameters #### Required Parameters - **--parse** (string) - 必选 - 解析原始性能数据文件。可选on或off,默认值为off。on表示开启,off表示关闭。 - **--output** (string) - 必选 - 原始性能数据文件目录。须指定为PROF_XXX目录或PROF_XXX目录的父目录,例如:/home/profiler_data/PROF_XXX。 #### Optional Parameters - **--python-path** (string) - 可选 - 指定解析使用的Python解释器路径,支持 Python 3.7.5 及以上版本。 ### Request Example ```bash msprof --parse=on --output=/home/profiler_data/PROF_XXX ``` ### Response #### Success Response 执行完上述命令,会在PROF_XXX的device_{id}和host目录下生成sqlite目录,sqlite目录下会有db文件生成。需要继续执行解析并导出性能数据,导出最终结果的timeline数据或db文件。 ``` -------------------------------- ### 使用示例2:默认策略绑核 Source: https://github.com/ascend/msprof/blob/master/misc/host_analyzer/README.md 不指定配置文件时,按默认策略为每张NPU卡分配CPU区间并绑定关键线程和中断。 ```python python3 entrance.py bind ``` -------------------------------- ### 设置Python环境变量(以python3.7.5为例) Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/msprof_parsing_instruct.md 配置Python路径和库文件路径,用于msProf工具运行。需根据实际Python版本修改路径。 ```bash export PATH=/usr/local/python3.7.5/bin:$PATH #设置python3.7.5库文件路径 export LD_LIBRARY_PATH=/usr/local/python3.7.5/lib:$LD_LIBRARY_PATH ``` -------------------------------- ### 重新进入容器的原生命令 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在宿主机执行,替换 为实际容器名称。 ```bash docker exec -it bash ``` -------------------------------- ### 导出db文件(使用示例) Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/extended_functions.md 使用示例:导出db文件,生成汇总所有性能数据的.db格式文件(msprof_时间戳.db)。 ```bash python3 msprof.py export db -dir /home/HwHiAiUser/profiler_data/PROF_XXX ``` -------------------------------- ### 使用示例1:指定配置文件绑核 Source: https://github.com/ascend/msprof/blob/master/misc/host_analyzer/README.md 使用自定义配置文件执行绑核,示例中假设仅NPU4,5,6,7在运行,按配置绑定进程、线程、PID和中断。 ```bash python3 entrance.py bind -c ./bind_design.json ``` -------------------------------- ### CMakeLists.txt for device_init_utest Source: https://github.com/ascend/msprof/blob/master/test/msprof_cpp/analysis_ut/domain/init/CMakeLists.txt Builds the device_init_utest executable by collecting source files from analysis and test directories, adding device_context source files, and running the test via run_test(). ```cmake aux_source_directory(${TOP_DIR}/analysis/csrc/infrastructure/data_inventory DEVICE_TASK_SOURCE) aux_source_directory(${TOP_DIR}/analysis/csrc/domain/entities/hal DEVICE_TASK_SOURCE) aux_source_directory(${TOP_DIR}/analysis/csrc/domain/services/init DEVICE_TASK_SOURCE) aux_source_directory(${TOP_DIR}/analysis/csrc/infrastructure/process DEVICE_TASK_SOURCE) aux_source_directory(${TOP_DIR}/analysis/csrc/infrastructure/utils DEVICE_TASK_SOURCE) aux_source_directory(${TOP_DIR}/test/msprof_cpp/analysis_ut/domain/init/test DEVICE_TASK_SOURCE) aux_source_directory(${TOP_DIR}/test/msprof_cpp/analysis_ut/stubs/dfx DEVICE_TASK_SOURCE) add_executable(device_init_utest ${DEVICE_TASK_SOURCE} ${TOP_DIR}/analysis/csrc/domain/services/device_context/cpu_info.cpp ${TOP_DIR}/analysis/csrc/domain/services/device_context/device_context.cpp ${TOP_DIR}/analysis/csrc/domain/services/device_context/device_info.cpp ${TOP_DIR}/analysis/csrc/domain/services/device_context/load_start_log.cpp ${TOP_DIR}/analysis/csrc/domain/services/device_context/sample_info.cpp ${TOP_DIR}/analysis/csrc/domain/services/device_context/start_info.cpp ) run_test(device_init_utest) ``` -------------------------------- ### 确认 ctr_in.py 权限 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在内网服务器宿主机上执行,确认 ctr_in.py 存在且具有执行权限后返回第 2.1.5 节启动容器。 ```bash cd ~ chmod +x ctr_in.py ls -l ctr_in.py ``` -------------------------------- ### 离线导入 CANN 镜像(中转机拉取并保存) Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在具备公网访问能力且 CPU 架构相同的中转机上执行。将第一行的值替换为第 2.1.2 节记录的 MY_STUDY_VAR_CANN_IMAGE 完整值。 ```bash CANN_IMAGE='完整镜像地址' docker pull "${CANN_IMAGE}" docker save -o cann.tar "${CANN_IMAGE}" ``` -------------------------------- ### 提交更改 git add 和 git commit Source: https://github.com/ascend/msprof/blob/master/docs/zh/contributing/contributing_guide.md 将更改添加到暂存区并提交,提交信息需遵循规范,例如 feat: 。 ```bash git add . git commit -m "feat: " ``` -------------------------------- ### msprof --parse 命令格式 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/msprof_parsing_instruct.md 解析性能数据功能的命令格式。--parse 为必选参数,可选 on 或 off,默认值为 off;--output 为必选参数,指定原始性能数据文件目录(PROF_XXX 目录或其父目录);--python-path 为可选参数,指定 Python 解释器路径,支持 Python 3.7.5 及以上版本。 ```bash msprof --parse=on --output= [--python-path=] ``` -------------------------------- ### 下载 ctr_in.py 脚本 Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在可访问当前网页的浏览器中输入该链接,下载 ctr_in.py 并手动拷贝至内网服务器的 ~/ 目录。 ```text https://inst.obs.cn-north-4.myhuaweicloud.com/env/ctr_in.py ``` -------------------------------- ### 安装 run 包 Source: https://github.com/ascend/msprof/blob/master/docs/zh/development_guide/development_guide.md 进入 output 目录,赋予执行权限并安装生成的 run 包。 ```bash cd output chmod +x mindstudio-profiler__.run ./mindstudio-profiler__.run --install ``` -------------------------------- ### 添加 sysTrace 二进制到 PATH 环境变量 Source: https://github.com/ascend/msprof/blob/master/misc/gil_tracer/README.md 将 sysTrace 二进制工具添加到 PATH 环境变量中,以便后续命令行调用。 ```bash export PATH=$PATH:/systrace/build ``` -------------------------------- ### msprof --export 使用 --reports 参数导出 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/msprof_parsing_instruct.md 传入用户自定义的 reports_sample_config.json 配置文件,根据配置文件中指定的范围导出相应的性能数据。 ```bash msprof --export=on --output=/home/profiler_data/PROF_XXX --reports=/path/to/reports_sample_config.json ``` -------------------------------- ### 为 run 包添加可执行权限 Source: https://github.com/ascend/msprof/blob/master/docs/zh/install_guide/msprof_install_guide.md 在 artifacts 目录下执行,为 run 包添加可执行权限。 ```shell cd ~/msprof/artifacts chmod +x mindstudio-profiler__{arch}.run ``` -------------------------------- ### msprof --query 命令格式 Source: https://github.com/ascend/msprof/blob/master/docs/zh/user_guide/msprof_parsing_instruct.md 查询性能数据文件信息的基本命令格式。--query 为必选参数,可选 on 或 off,默认值为 off;--output 为必选参数,须指定为 PROF_XXX 目录或其父目录。 ```bash msprof --query=on --output= ``` -------------------------------- ### 写入示例训练代码 train.py Source: https://github.com/ascend/msprof/blob/master/docs/zh/quick_start/msprof_quick_start.md 在容器内执行此命令,将示例训练代码写入 ~/train.py。该脚本使用随机数据训练 2 个 epoch,自动查找空闲 NPU 并执行训练,仅用于生成性能数据。注意:导入语句为单行合并(非规范写法);如需指定 NPU,请将最后一行中的 find_idle_npu() 替换为实际设备编号(如 0)。 ```bash cat > ~/train.py << 'EOF' import sys, re, subprocess, torch, torch.nn as nn, torch.optim as optim, torchvision.models as models # 为精简篇幅,导入语句合并为单行(非规范写法) class ResNet50: def __init__(self, num_classes=1000, device=0): self.device = f"npu:{device}" torch.npu.set_device(self.device) print(f"[INFO] Using device: {self.device}") self.model = models.resnet50(weights=None, num_classes=num_classes).to(self.device) def train(self, data_loader, epochs=1, lr=1e-4, freeze_backbone=False): for p in self.model.parameters(): p.requires_grad = not freeze_backbone for p in self.model.fc.parameters(): p.requires_grad = True optimizer = optim.Adam([p for p in self.model.parameters() if p.requires_grad], lr=lr) criterion = nn.CrossEntropyLoss().to(self.device) self.model.train() for epoch in range(epochs): total_loss = 0.0 for inputs, labels in data_loader: inputs, labels = inputs.to(self.device), labels.to(self.device) optimizer.zero_grad() loss = criterion(self.model(inputs), labels) loss.backward() optimizer.step() total_loss += loss.item() print(f"[Epoch {epoch + 1}/{epochs}] Average Loss: {total_loss / len(data_loader):.4f}") def find_idle_npu(): res = subprocess.run(["npu-smi", "info"], capture_output=True, text=True) if res.returncode != 0: sys.exit(f"ERROR: npu-smi info failed: {res.stderr.strip()}") idle = [int(x) for x in re.findall(r'No running processes found in NPU\s+(\d+)', res.stdout)] print(f"[INFO] Available (idle) NPU IDs: {idle}") if not idle: sys.exit("[WARNING] No idle NPU, please free resources or retry later.") return int(idle[0]) if __name__ == "__main__": dataset = torch.utils.data.TensorDataset(torch.randn(80, 3, 224, 224), torch.randint(0, 10, (80,))) ResNet50(num_classes=10, device=find_idle_npu()).train(torch.utils.data.DataLoader(dataset, batch_size=8, shuffle=True), epochs=2, lr=1e-3, freeze_backbone=True) EOF ``` -------------------------------- ### 提交信息规范模板 Source: https://github.com/ascend/msprof/blob/master/docs/zh/contributing/contributing_guide.md 提交信息应包含类型、主题、正文和页脚,类型包括 feat、fix、docs、style、refactor、test、chore。 ```bash :