Compare commits

...
79 Commits
Author SHA1 Message Date
weili10 aad811397a !2127 Unified version number format.
Merge pull request !2127 from 闫鹏全/v1.8.1-3.0.rc2
2023-01-16 03:00:28 +00:00
闫鹏全 86351e5adb Unified version number format. 2023-01-14 15:14:15 +08:00
i-robot 7ef6dbbfca !1542 API修正
Merge pull request !1542 from 彭子荣/v1.8.1-3.0.rc2
2022-11-08 03:41:01 +00:00
pengzirong fd2aead757 API修正 2022-11-08 11:15:38 +08:00
i-robot db333b4be2 !1517 API清单更新
Merge pull request !1517 from 彭子荣/v1.8.1-3.0.rc2
2022-11-03 13:30:13 +00:00
pengzirong 76592954a2 API清单更新 2022-11-03 17:57:57 +08:00
i-robot b6a78d5140 !1458 修正API清单
Merge pull request !1458 from 彭子荣/v1.8.1-3.0.rc2
2022-11-03 03:06:02 +00:00
pengzirong 1a56c90d1f 修正API参考 2022-11-01 15:23:49 +08:00
i-robot e12e1d8e4d !1454 删除非版本特性
Merge pull request !1454 from 彭子荣/v1.8.1-3.0.rc2
2022-10-25 06:15:21 +00:00
pengzirong 6d03bc7f25 删除自动迁移工具 2022-10-25 11:45:45 +08:00
i-robot 761ca4b3a4 !1452 删除错误内容
Merge pull request !1452 from 彭子荣/v1.8.1-3.0.rc2
2022-10-24 09:59:37 +00:00
pengzirong 37be703f99 删除精度比对 2022-10-24 17:27:50 +08:00
i-robot d3a83db24a !1400 新增训练调优&工具使用指南
Merge pull request !1400 from 彭子荣/v1.8.1-3.0.rc2
2022-10-14 13:18:11 +00:00
pengzirong 66b5c0b42c 新增训练调优&工具使用指南 2022-10-14 21:02:33 +08:00
尤安升 d27de79844 update torch_npu/utils/module.py. 2022-09-13 02:51:30 +00:00
i-robot 04199d2884 !1226 网络模型移植与训练指南修改
Merge pull request !1226 from 彭子荣/v1.8.1-3.0.rc2
2022-09-09 03:28:14 +00:00
pengzirong fcb3b04d51 修改精度调测章节调优方法&检查全文跳转链接
1
2022-09-08 18:20:32 +08:00
i-robot 8b4f2c3573 !1157 网络模型移植与训练指南&多机多卡训练适配指南资料修改
Merge pull request !1157 from 彭子荣/v1.8.1-3.0.rc2
2022-08-31 02:28:46 +00:00
pengzirong 50ee12dca1 网络模型移植与训练指南全文问题检查
1
2022-08-31 10:17:29 +08:00
i-robot 3a89035ad1 !1179 Fix serialization.
Merge pull request !1179 from 尤安升/v1.8.1-3.0.rc2
2022-08-25 08:12:48 +00:00
尤安升 29a991ee82 update torch_npu/utils/serialization.py.
Signed-off-by: 尤安升 <youansheng@huawei.com>
2022-08-25 06:13:14 +00:00
i-robot 652c089d4b !1112 Pytorch API支持清单合入
Merge pull request !1112 from 彭子荣/v1.8.1-3.0.rc2
2022-08-08 07:09:58 +00:00
pengzirong a64b9864b7 API支持度修改
1
2022-08-02 15:27:28 +08:00
i-robot 528008258c !1098 网络模型移植与训练指南修改
Merge pull request !1098 from 彭子荣/v1.8.1-3.0.rc2
2022-07-29 10:55:15 +00:00
pengzirong 6cf5bb349c 修改跳转链接 2022-07-27 15:24:48 +08:00
i-robot 9e8a59050b !1077 Updated the README.en, Installation Guide, API Support, and Release Notes.
Merge pull request !1077 from yanhuiling/v1.8.1-3.0.rc2
2022-07-22 03:18:48 +00:00
yanhuiling 364f11e281 Updated English documents. 2022-07-21 17:31:42 +08:00
i-robot 91de053dd4 !1067 bugfix:修复npu_transpose 传递ACL信息错误问题
Merge pull request !1067 from 李超/v1.8.1-3.0.rc2
2022-07-18 09:17:23 +00:00
李超 d29d8ee92b fix oom when calling npu_transpose 2022-07-18 10:24:39 +08:00
尤安升 a88db63f80 update Third_Party_Open_Source_Software_Notice. 2022-07-15 17:08:40 +08:00
尤安升 481d893a08 add Third_Party_Open_Source_Software_Notice. 2022-07-15 08:00:47 +00:00
weili10 f4d3295071 update maintenance status for 3.0.rc2 2022-07-15 03:28:17 +00:00
i-robot 14c3832ee5 !1061 Support to_cpu for the attr items of Module && 撤销_rebuild_tensor_v2的修改
Merge pull request !1061 from 王夏夏/v1.8.1-3.0.rc2
2022-07-14 07:18:14 +00:00
i-robot 4d7a2fbc5c !1060 Pytorch API支持清单合入
Merge pull request !1060 from 彭子荣/v1.8.1-3.0.rc2
2022-07-14 07:16:13 +00:00
xiaxia3 2d5891833d Support to_cpu for the attr items of Module && 撤销_rebuild_tensor_v2的修改 2022-07-14 14:22:51 +08:00
pengzirong 529bc056eb 新增可支持非算子API
1

RELEASENOTE 更新3.0.RC2内容

1
2022-07-14 11:08:29 +08:00
i-robot 8c3386dc78 !1051 Pytorch API支持清单修改
Merge pull request !1051 from 彭子荣/v1.8.1-3.0.rc2
2022-07-12 13:18:54 +00:00
i-robot 2c7290d438 !1054 回退sort修改
Merge pull request !1054 from 王夏夏/v1.8.1-3.0.rc2
2022-07-12 13:06:53 +00:00
xiaxia3 72bc8801e7 回退sort修改1 2022-07-12 19:51:30 +08:00
pengzirong e2b4c7c77b 更新API文档,README与安装指南
1
2022-07-12 18:10:08 +08:00
i-robot 411612a5a4 !1050 安装指南资料修改
Merge pull request !1050 from 彭子荣/v1.8.1-3.0.rc2
2022-07-12 06:30:54 +00:00
pengzirong 5474a8f6bb 环境变量表格位置错误
1

1
2022-07-12 10:35:56 +08:00
i-robot 7bfca6b37c !1046 [contrib/npu/optimized_lib/] fusedcolorjitter remove the torchvision dependency
Merge pull request !1046 from 王姜奔/v1.8.1-3.0.rc2
2022-07-11 12:03:30 +00:00
王姜奔 959aa11d48 Remove the torchvision dependency 2022-07-11 17:40:37 +08:00
i-robot c81f222643 !1045 多级多卡训练适配指南 英文资料更新
Merge pull request !1045 from 彭子荣/v1.8.1-3.0.rc2
2022-07-11 09:39:38 +00:00
pengzirong 3f3f3ec8a3 update ip to the sample ip 2022-07-11 17:00:28 +08:00
i-robot 9922579b82 !1036 网络模型移植与训练指南修改
Merge pull request !1036 from 彭子荣/v1.8.1-3.0.rc2
2022-07-11 08:35:31 +00:00
i-robot 2c01646dfd !1041 Updated the PyTorch Installation Guide, PyTorch Network Model Porting and Training Guide, and README.en
Merge pull request !1041 from yanhuiling/v1.8.1-3.0.rc2
2022-07-11 08:33:33 +00:00
yanhuiling 02552fd5d6 修改英文版安装指南、网络移植指南与README.en 2022-07-11 15:40:54 +08:00
pengzirong 9ad398b9a6 网络模型移植与训练指南新增硬件支持说明 2022-07-11 14:50:37 +08:00
i-robot 37a1bc9a5e !1027 V1.8.1-3.0.RC2资料更新
Merge pull request !1027 from 彭子荣/v1.8.1-3.0.rc2
2022-07-11 03:33:36 +00:00
pengzirong 7289ccc104 1.8.1-3.0.rc2README与安装指南修改
修改APEX README 跳转链接
2022-07-11 10:57:45 +08:00
i-robot f8f565688b !1022 回退 bugfix: torch.device('npu').index=None
Merge pull request !1022 from 李超/v1.8.1-3.0.rc2
2022-07-08 02:32:57 +00:00
李超 a30f40dbf4 roll back torch.device.index fixing 2022-07-07 18:59:11 +08:00
i-robot a4e680d830 !1018 资料更新
Merge pull request !1018 from 彭子荣/v1.8.1-3.0.rc2
2022-07-07 09:54:07 +00:00
i-robot 7f4cc7aaa6 !1015 强制sort走fp32
Merge pull request !1015 from 王夏夏/v1.8.1-3.0.rc2
2022-07-07 09:40:13 +00:00
i-robot 00f1a47776 !1010 bugfix: torch.device('npu').index=None
Merge pull request !1010 from 李超/v1.8.1-3.0.rc2
2022-07-07 08:56:15 +00:00
i-robot 9c39c0e07d !1020 bugfix:修复device变动导致的cast weight未生效问题
Merge pull request !1020 from 李超/v1.8.1-3.0.rc2-1
2022-07-07 08:54:16 +00:00
李超 e86c20210d fix cast weight for tensors with different devices 2022-07-07 16:32:43 +08:00
pengzirong 29ffacaa0c 更新依赖下载
1
2022-07-07 15:35:32 +08:00
xiaxia3 afcdfdb4ad 强制sort走fp32 2022-07-07 15:10:07 +08:00
i-robot 65493f8713 !1013 EADME与安装指南差异修改
Merge pull request !1013 from 彭子荣/v1.8.1-3.0.rc2
2022-07-07 06:58:12 +00:00
pengzirong 74f1c7f2a5 更新README与安装指南误差与问题
1
2022-07-07 14:09:00 +08:00
李超 b57324fa06 fix torch.device('npu').index=None 2022-07-06 17:05:58 +08:00
i-robot 00f85d334c !1005 index_put fix bug(商分)
Merge pull request !1005 from 王晓/index_put_rc2
2022-07-05 14:01:31 +00:00
wangxiao 9985404398 fixbug indexput 2022-07-05 20:42:07 +08:00
i-robot 5f334f0889 !1001 bugfix: 解决torch._as_tensor 无法创建NPU Tensor问题
Merge pull request !1001 from 李超/v1.8.1-3.0.rc2
2022-07-05 09:17:32 +00:00
李超 68d1c05dd5 bugfix: support creating npu tensor using torch.as_tensor 2022-07-05 17:00:47 +08:00
i-robot dbf95ced96 !1000 [Bugfix] Fix new empty error.
Merge pull request !1000 from 尤安升/cleancode
2022-07-05 07:51:24 +00:00
i-robot 2c17820b58 !993 【FixBug】修改index_put适配于1.5保持一致(商分)
Merge pull request !993 from 王晓/index_put_rc2
2022-07-04 09:35:24 +00:00
wangxiao 4b778a0374 rc2 fix index_put 2022-07-02 16:52:01 +08:00
i-robot 82371fae53 !987 _has_compatible_shallow_copy_type重复注册warning增加readme说明
Merge pull request !987 from 李超/v1.8.1-3.0.rc2
2022-07-02 03:14:50 +00:00
i-robot aaf07da7bc !990 Revert to deepcopy.
Merge pull request !990 from 尤安升/cleancode
2022-07-02 02:54:50 +00:00
李超 2369084dc5 discription of duplicate registration warning 2022-07-02 10:42:59 +08:00
i-robot 90bdaeeb6b !983 master内容同步
Merge pull request !983 from 彭子荣/v1.8.1-3.0.rc2
2022-07-01 06:46:10 +00:00
pengzirong d272cac299 修改下载对应分支命令;删除部分环境变量 2022-07-01 09:51:02 +08:00
i-robot 28d15047b5 !970 网络模型移植与训练指南&多机多卡训练适配指南资料修改
Merge pull request !970 from 彭子荣/master
2022-06-30 08:57:26 +00:00
pengzirong 852c69c6b7 算子开发指南;网络模型移植与训练指南;README资料修改 2022-06-30 16:41:56 +08:00
i-robot c72021db81 !975 Clean code for wrong import order.
Merge pull request !975 from 尤安升/cleancode
2022-06-30 06:55:05 +00:00
110 changed files with 8096 additions and 5494 deletions
+372 -121
View File
@@ -1,105 +1,85 @@
# AscendPyTorch
## Overview
This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch framework so that developers who use the PyTorch framework can obtain powerful compute capabilities of Ascend AI Processors. When setting up the environments for PyTorch model development and operating, developers can manually compile related modules on servers.
# Project Introduction
## Prerequisites
This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch framework so that developers who use the PyTorch framework can obtain powerful compute capabilities of Ascend AI Processors.
# Compilation/Execution Constraints
GCC version: 7.3.0 (required only in compilation scenarios)
CMake version: 3.12.0 or later (required only in compilation scenarios)
Python version: 3.7.5, 3.8.x, or 3.9.x (PyTorch1.5 does not support Python 3.9.x.)
- The development or operating environment of CANN has been installed. For details, see the *CANN Software Installation Guide*.
- Python 3.7.5, 3.8, and 3.9 are supported.
# System Dependencies
## CentOS & EulerOS
yum install -y cmake zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
yum install -y gcc==7.3.0 cmake==3.12.0
## Ubuntu
apt-get install -y gcc g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 cmake dos2unix libopenblas-dev
apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
apt-get install -y gcc==7.3.0 cmake==3.12.0
>![](figures/icon-note.gif) **NOTE:**
>If an error occurs during the installation of the GCC and CMake dependency commands, use the source code for installation. For details, see the FAQ.
# Ascend Auxiliary Software
| AscendPyTorch Version| CANN Version| Supported PyTorch Version| Gitee Branch|
| :------------ | :----------- | :----------- | ------------- |
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
| AscendPyTorch Version | CANN Version | Supported PyTorch Version | Gitee Branch |
| :-------------------- | :----------- | :------------------------ | -------------- |
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.2.tr5 |
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.2.tr5 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
# Installation Methods
# Installation Method
## Install the PyTorch environment dependencies.
If you install dependencies as a non-root user, add **--user** at the end of each command in this step, for example, **pip3 install pyyaml --user**.
```sh
pip3 install pyyaml
pip3 install wheel
```
## Compile and install the PyTorch and Ascend plugin.
Download the plugin code.
Install the official torch package, and then compile and install the plugin.
```sh
git clone -b v1.8.1-3.0.rc1 https://gitee.com/ascend/pytorch.git
#x86_64
pip3 install torch==1.8.1+cpu # If an error is reported when you run the pip command to install PyTorch of the CPU version, manually download the .whl package from https://download.pytorch.org/whl/torch.
#AArch64
#The community does not provide the CPU installation package of the ARM architecture. For details, see the first FAQ to compile and install PyTorch using the source code.
```
Code in the current repository is PyTorch 1.8.1. Obtain the native Pytorch source code from the root directory **/pytorch** of the current repository and rename it to **pytorch_v1.8.1**.
```sh
// Version 1.8.1
cd pytorch # Root directory of the plugin
git clone -b v1.8.1 --depth=1 https://github.com/pytorch/pytorch.git pytorch_v1.8.1
Compile and generate the binary installation package of the PyTorch plugin.
Download code of the corresponding branch and go to the root directory of the plugin.
```
#
git clone -b v1.8.1-3.0.rc2 https://gitee.com/ascend/pytorch.git
cd pytorch
# Specify the Python version packaging mode:
bash ci/build.sh --python=3.7
# or
bash ci/build.sh --python=3.8
# or
bash ci/build.sh --python=3.9
```
Run the following commands to go to the native PyTorch source code directory **pytorch_v1.8.1** and obtain the PyTorch passive dependency code:
Install the **torch_npu** package generated in the **pytorch/dist** directory. *{arch}* indicates the architecture name.
```
cd pytorch_v1.8.1
git submodule sync
git submodule update --init --recursive
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
```
After the preceding operations are complete and no error is reported, the PyTorch and the third-party code on which the PyTorch depends are generated. Then, the patch is added to the PyTorch source code and compiled.
```sh
cd ../patch
bash apply_patch.sh ../pytorch_v1.8.1
cd ../pytorch_v1.8.1
Specify the Python version packaging mode:
bash build.sh --python=3.7
or
bash build.sh --python=3.8
or
bash build.sh --python=3.9
Download TorchVision.
```
Install the torch package generated in the **pytorch/pytorch_v1.8.1/dist** directory, and then compile and install the plugin.
```
cd dist
pip3 install --upgrade torch-1.8.1+ascend.rc1-cp37-cp37m-linux_{arch}.whl
```
Build and generate the binary installation package of the PyTorch plugin.
```
cd ../../ci # Access the root directory of the plugin.
Specify the Python version packaging mode:
bash build.sh --python=3.7
or
bash build.sh --python=3.8
or
bash build.sh --python=3.9
```
Install the torch_npu package generated in the **pytorch/dist** directory.
```
cd ../dist
pip3 install --upgrade torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
pip3 install torchvision==0.9.1
```
@@ -110,39 +90,70 @@ pip3 install --upgrade torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
Run the script for setting environment variables in the root directory of the current repository.
```
cd ../
source env.sh
```
## Customize environment variables.
The following environment variables are function classes used in NPU scenarios or environment variables that can improve performance:
```
export TASK_QUEUE_ENABLE=1 # Delivered by an asynchronous task to asynchronously call the ACL interface. You are advised to enable this environment variable and set its value to **1**.
```
The following are optional environment variables that may affect running models:
```
export DYNAMIC_COMPILE_ENABLE=1 # Dynamic shape feature. This environment variable is optional for shape change scenarios. To enable it, set its value to **1**.
export COMBINED_ENABLE=1 # (Optional) Optimizes the scenario where two inconsecutive operators are combined. To enable this function, set the value to **1**.
export ACL_DUMP_DATA=1 # (Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to **1**.
export DYNAMIC_OP="ADD#MUL" # Operator implementation. The ADD and MUL operators have different performance in different scenarios. Optional
export COMBINED_ENABLE=1 # (Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency.
export ACL_DUMP_DATA=1 # (Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.
```
**Table 1** Description of environment variables
<a name="zh-cn_topic_0000001152616261_table42017516135"></a>
<table><thead align="left"><tr id="zh-cn_topic_0000001152616261_row16198951191317"><th class="cellrowborder" valign="top" width="55.48%" id="mcps1.2.3.1.1"><p id="zh-cn_topic_0000001152616261_p51981251161315"><a name="zh-cn_topic_0000001152616261_p51981251161315"></a><a name="zh-cn_topic_0000001152616261_p51981251161315"></a>Environment Variable</p>
</th>
<th class="cellrowborder" valign="top" width="44.519999999999996%" id="mcps1.2.3.1.2"><p id="zh-cn_topic_0000001152616261_p9198135114133"><a name="zh-cn_topic_0000001152616261_p9198135114133"></a><a name="zh-cn_topic_0000001152616261_p9198135114133"></a>Description</p>
</td>
</tr>
<tr id="row78312162301"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1832171673019"><a name="p1832171673019"></a><a name="p1832171673019"></a>COMBINED_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency. However, the host delivery performance may deteriorate.</p>
</td>
</tr>
<tr id="row183041355123411"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p730435533415"><a name="p730435533415"></a><a name="p730435533415"></a>ACL_DUMP_DATA</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p16304105533412"><a name="p16304105533412"></a><a name="p16304105533412"></a>(Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.</p>
</td>
</tr>
</tbody>
</table>
## Run the unit test script.
Verify the execution. The output result is OK.
Verify the running. The output is **OK**.
```shell
cd test/test_network_ops/
python3 test_div.py
```
# Documentation
# (Optional) Installing the Mixed Precision Module
AscendPyTorch 1.8.1 integrates the AMP module and can be used for training with mixed precision. The differences between the AMP module and the Apex module are as follows. You can select a desired module. For details about how to compile and install the Apex module, see the related [**README.en**](https://gitee.com/ascend/apex) file.
- AMP
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
- Tensor fusion is not supported.
- Apex
- O1 configuration mode: Conv and Matmul use the float16 precision for computing, and Softmax and BN use float32.
- O2 configuration mode: BN uses the float32 precision for computing, and others use float16.
- Static loss scale: Parameters are statically set to ensure the convergence of training with mixed precision.
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
# Documents
For more details about the installation guide, model porting and training/inference tutorials, and API list, see [User Documents](https://gitee.com/ascend/pytorch/tree/master/docs/en).
@@ -154,32 +165,64 @@ We sincerely welcome you to join discussions in the community and contribute you
The version branches of AscendPyTorch have the following maintenance phases:
| **Status** | **Duration** | **Description** |
| ----------------- | ------------- | ------------------------------------------------------------ |
| Planning | 1 - 3 months | Plan features. |
| Development | 3 months | Develop features. |
| Maintained | 6 - 12 months | Allow the incorporation of all resolved issues and release the version. |
| Unmaintained | 0 - 3 months | Allow the incorporation of all resolved issues. No dedicated maintenance personnel are available. No version will be released. |
| End Of Life (EOL) | N/A | Do not accept any modification to a branch. |
| **Status** | **Duration** | **Description** |
|-------------|---------------|--------------------------------------------------|
| Planning | 1-3 months | Plan features. |
| Development | 3 months | Develop features. |
| Maintained | 6-12 months | Allow the incorporation of all resolved issues and release the version.|
| Unmaintained| 0-3 months | Allow the incorporation of all resolved issues. No dedicated maintenance personnel are available. No version will be released. |
| End Of Life (EOL) | N/A | Do not accept any modification to a branch. |
# Maintenance Status of Existing Branches
| **Branch Name** | **Status** | **Launch Date** | **Subsequent Status** | **EOL Date** |
| --------------- | ---------- | --------------- | -------------------------------------- | ------------ |
| **v2.0.2** | Maintained | 2021-07-29 | Unmaintained <br> 2022-07-29 estimated | |
| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained <br> 2022-10-15 estimated | |
| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained <br> 2023-01-15 estimated | |
| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained <br> 2023-04-10 estimated | |
| **Branch Name**| **Status** | **Launch Date** | **Subsequent Status** | **EOL Date**|
|------------|--------------|----------------------|----------------------------------------|------------|
| **v2.0.2** | Maintained | 2021-07-29 | Unmaintained <br> 2022-07-29 estimated | |
| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained <br> 2022-10-15 estimated | |
| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained <br> 2023-01-15 estimated | |
| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained <br> 2023-04-10 estimated | |
| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained <br> 2023-07-15 estimated |
# FAQs
## When the CPU architecture is ARM, PyTorch 1.8.1 cannot be installed using the PIP3 command because the community does not provide the torch package for the ARM CPU architecture. In this case, use the source code to compile and install PyTorch 1.8.1.
# FAQ
Download the PyTorch 1.8.1 source package.
```
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
```
Access the source package to obtain the passive dependency code.
```
cd pytorch_v1.8.1
git submodule sync
git submodule update --init --recursive
```
Compile and install PyTorch 1.8.1.
```
python3 setup.py install
```
## When PIP is set to the Huawei source, a Python environment error occurs after the typing dependency in the **requirements.txt** file is installed.
When PIP is set to the Huawei source, open the **requirements.txt** file, delete the typing dependency, and then run the following command:
```
pip3 install -r requirments.txt
```
## The error message "no module named yaml/typing_extensions." is displayed when **bash build.sh** is run during compilation.
PyTorch compilation depends on the YAML and typing_extensions libraries, which need to be manually installed.
```
pip3 install pyyaml
pip3 install typing_extensions
```
After the installation is successful, run **make clean** and then **bash build.sh** to perform compilation. Otherwise, an unknown compilation error may occur due to the cache.
@@ -187,40 +230,183 @@ After the installation is successful, run **make clean** and then **bash build.s
Development state:
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64
User state:
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64
```
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 # {arch} is the architecture name.
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
User state:
```
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 # {arch} is the architecture name.
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
## During CMake installation through the CLI, an error is reported indicating that the package cannot be found. During CMake compilation, another error is reported indicating that the version is too early. In this cause, you can use the installation script or source code to compile and install CMake.
Method 1: Download the installation script and install CMake. (For details, see the CMake official website.)
​ x86_64 environment: cmake-3.12.0-Linux-x86_64.sh
​ AArch64 environment: cmake-3.12.0-Linux-aarch64.sh
1. Run the following command:
```
./cmake-3.12.0-Linux-{arch}.sh # {arch} indicates the architecture name.
```
2. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
3. Run the following command to check whether CMake has been installed:
```
cmake --version
```
If the message "cmake version 3.12.0" is displayed, the installation is successful.
Method 2: Use the source code to compile and install.
1. Obtain the CMake software package.
```
wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
```
2. Decompress the package and go to the software package directory.
```
tar -xf cmake-3.12.0.tar.gz
cd cmake-3.12.0/
```
3. Run the configuration, compilation, and installation commands.
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. Run the following command to check whether CMake has been installed:
```
cmake --version
```
If the message "cmake version 3.12.0" is displayed, the installation is successful.
## During GCC installation through the CLI, an error is reported indicating that the package cannot be found. During GCC compilation, another error is reported.
When downloading GCC from some sources, you may be prompted by an error message indicating that the package cannot be found. In this case, use the source code to compile and install GCC.
Perform the following steps as the **root** user.
1. Download **gcc-7.3.0.tar.gz** from [https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz).
2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
```
sudo rm -rf /tmp/*
```
3. Install the dependency package. (CentOS and Ubuntu are used as examples.)
- For CentOS, run the following command:
```
yum install bzip2
```
- For Ubuntu, run the following command:
```
apt-get install bzip2
```
4. Compile and install GCC.
1. Go to the directory where the source package **gcc-7.3.0.tar.gz** is located and run the following command to decompress it:
```
tar -zxvf gcc-7.3.0.tar.gz
```
2. Go to the extracted directory and download the GCC dependency packages:
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
If an error is reported during the command execution, run the following commands in the **gcc-7.3.0/** directory to download the dependency packages:
```
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
```
After the preceding dependencies are downloaded, run the following command again:
```
./contrib/download_prerequisites
```
If the verification fails, check whether there are duplicate dependency packages in the folder. If yes, delete duplicate ones.
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>Run the configuration, compilation, and installation commands.
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
make -j15 # Check the number of CPUs by running **grep -w processor /proc/cpuinfo|wc -l**. In this example, the number is 15. You can set the parameters as required.
make install
```
>![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/docs/en/PyTorch%20Network%20Model%20Porting%20and%20Training%20Guide/public_sys-resources/icon-notice.gif) **NOTICE:**
>The **--prefix** option is used to specify the **linux\_gcc7.3.0** installation path, which is configurable. Do not set it to **/usr/local** or **/usr,** which is the default installation path for the GCC installed by using the software source. Otherwise, a conflict occurs and the original GCC compilation environment of the system is damaged. In this example, the installation path is set to **/usr/local/linux\_gcc7.3.0**.
4. Change the soft links.
```
ln -s ${install_path}/bin/gcc /usr/bin/gcc
ln -s ${install_path}/bin/g++ /usr/bin/g++
ln -s ${install_path}/bin/c++ /usr/bin/c++
```
## An error message is reported during CMake compilation, indicating that the version is too early.
Download the Linux version from the CMake official website and install it. (The current version is 3.18.0.)
1. Run the **yum install -y cmake==3.18.0** command to install it.
2. Download the **cmake sh** script and install it. (For details, see the CMake official website.)
Recommended script in the x86_64 environment: **cmake-3.18.2-Linux-x86_64.sh**
5. Configure the environment variable.
Training must be performed in the compilation environment with GCC upgraded. If you want to run training, configure the following environment variable in your training script:
## GCC version switch errors occur.
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
When the test environment is switched from GCC 4.8.5 to GCC 7.3.0, errors may occur and the PyTorch compilation fails. The following lists the libraries that require soft connections:
**${install_path}** indicates the GCC 7.3.0 installation path configured in [3](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310). In this example, the GCC 7.3.0 installation path is **/usr/local/gcc7.3.0/**.
gcc, g++, c++ (The version must be 7.3.0.)
>![](figures/icon-note.gif) **NOTE:**
>Skip this step if you do not need to use the compilation environment with GCC upgraded.
If the PyTorch compilation fails, check whether the soft link library is correct.
libstdc++->libstdc++.so.6.0.24(7.3.0)
## libblas.so cannot be found.
The OpenBLAS library is missing in the environment. You need to install it.
@@ -237,6 +423,71 @@ Ubuntu
apt install libopenblas-dev
```
# Release Notes
## No device is mounted to the container.
For details, see [Release Notes](https://gitee.com/ascend/pytorch/tree/master/docs/en/RELEASENOTE).
An NPU-related error is reported when a script is run in the container. The **device** parameter is not set before container instance startup. As a result, the instance cannot be started.
![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/figures/FAQ.png)
Run the following command to restart the container:
```sh
docker run -it --ipc=host \
--device=/dev/davinciX \
--device=/dev/davinci_manager \
--device=/dev/devmm_svm \
--device=/dev/hisi_hdc \
-v /usr/local/Ascend/driver \
-v /usr/local/dcmi \
-v /usr/local/bin/npu-smi \
${image name}:{tag} \
/bin/bash
```
Parameter description:
**/dev/davinci*X***: NPU device. *X* is the physical ID of the chip, for example, **davinci0**.
**/dev/davinci_manager**: management device
**/dev/devmm_svm**: management device
**/dev/hisi_hdc**: management device
**/usr/local/Ascend/driver**: driver directory
**/usr/local/dcmi**: DCMI directory
**/usr/local/bin/npu-smi**: npu-smi tool
**$*{image name}:{tag}***: image name and version
## An error is reported during installation of -torch--whl-, indicating that -torch-1-5-0xxxx- and -torchvision- versions do not match.
During installation of **torch-\*.whl**, the message "ERROR: torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible" is displayed.
![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/figures/zh-cn_image_0000001190081735.png)
When the PyTorch is installed, the version check is automatically triggered. The version of the torchvision installed in the environment is 0.6.0. During the check, it is found that the version of the **torch-\*.whl** is inconsistent with the required version 1.5.0. As a result, an error message is displayed, but the installation is successful.
This problem does not affect the actual result, and no action is required.
## When you run **import torch_npu**, if "_has_compatible_shallow_copy_type" is output, a warning about a repeated registration error is displayed.
The warning is triggered by the shallow copy operation of **Tensor.set_data**, as shown in the following figure. The main cause is that after the PyTorch plugin is decoupled, `_has_compatible_shallow_copy_type` cannot detect shallow copy of NPU tensors. You need to register `_has_compatible_shallow_copy_type` again.
This error can be ignored because it does not affect the model accuracy and performance.
It will be resolved after the NPU's device ID is incorporated into the community or the `_has_compatible_shallow_copy_type` registration mode is changed in a later PyTorch version.
![Input Image Description](https://images.gitee.com/uploads/images/2022/0701/153621_2b5080c4_7902902.png)
## An error is reported when torch_npu is referenced with Python commands in the compilation directory.
To verify the torch_npu reference, switch to another directory. If you perform the verification in the compilation directory, the following error message is displayed:
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
# Version Description
For details, see [Release Notes](https://gitee.com/ascend/pytorch/tree/master/docs/en/RELEASENOTE).
+98 -119
View File
@@ -6,17 +6,26 @@
<h2 id="md">前提条件</h2>
- 需完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
- 需安装python版本为3.7.5、3.8、3.9。
- Python支持版本为3.7.5、3.8、3.9。
# 系统依赖库
## CentOS & EulerOS
yum install -y cmake==3.12.0 zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git gcc==7.3.0
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
yum install -y gcc==7.3.0 cmake==3.12.0
## Ubuntu
apt-get install -y gcc==7.3.0 g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 cmake==3.12.0 dos2unix libopenblas-dev git
apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
apt-get install -y gcc==7.3.0 cmake==3.12.0
>![](figures/icon-note.gif) **说明:**
>若安装gcc与cmake依赖命令报错,请参考FAQ使用源码安装。
# Ascend配套软件
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 | Gitee分支名称 |
@@ -26,6 +35,8 @@ apt-get install -y gcc==7.3.0 g++ make build-essential libssl-dev zlib1g-dev lib
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
# 安装方式
@@ -40,16 +51,22 @@ pip3 install wheel
## 编译安装PyTorch和昇腾插件
首先安装官方torch包,然后编译安装插件。(ARM架构CPU安装,请参见第一条FAQ)
首先安装官方torch包,然后编译安装插件。
```sh
pip3 install torch==1.8.1+cpu
#x86_64
pip3 install torch==1.8.1+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
#aarch64
#社区未提供arm架构cpu安装包,请参见FAQ第一条,使用源码编译安装pytorch
```
编译生成pytorch插件的二进制安装包。
```
git clone -b master https://gitee.com/ascend/pytorch.git & cd pytorch # 下载master分支代码,进入插件根目录
# 下载对应分支代码,进入插件根目录
git clone -b v1.8.1-3.0.rc2 https://gitee.com/ascend/pytorch.git
cd pytorch
# 指定python版本编包方式:
bash ci/build.sh --python=3.7
# 或
@@ -58,13 +75,15 @@ bash ci/build.sh --python=3.8
bash ci/build.sh --python=3.9
```
然后安装pytorch/dist下生成的插件torch_npu包
然后安装pytorch/dist下生成的插件torch_npu包,{arch}为架构名称。
```
pip3 install --upgrade dist/torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
```
下载torchvision。
```
pip3 install torchvision==0.9.1
```
# 运行
## 运行环境变量
@@ -78,105 +97,24 @@ source env.sh
## 自定义环境变量
以下环境变量为NPU场景下使用的功能类或可以提升性能的环境变量:
```
export TASK_QUEUE_ENABLE=1 # 使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1
```
可选的环境变量可能会对运行的模型产生影响:
```
export DYNAMIC_COMPILE_ENABLE=1 # 动态shape特性功能,针对shape变化场景,可选,开启设置为1
export COMBINED_ENABLE=1 # 非连续两个算子组合类场景优化,可选,开启设置为1
export COMBINED_ENABLE=1 # 非连续转连续二级推导优化,可选,开启设置为1。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升。
export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
export DYNAMIC_OP="ADD#MUL" # 算子实现,ADD和MUL算子在不同场景下有不同的性能表现。可选
```
**表 1** 环境变量说明
<a name="zh-cn_topic_0000001152616261_table42017516135"></a>
<table><thead align="left"><tr id="zh-cn_topic_0000001152616261_row16198951191317"><th class="cellrowborder" valign="top" width="55.48%" id="mcps1.2.3.1.1"><p id="zh-cn_topic_0000001152616261_p51981251161315"><a name="zh-cn_topic_0000001152616261_p51981251161315"></a><a name="zh-cn_topic_0000001152616261_p51981251161315"></a>配置项</p>
</th>
<th class="cellrowborder" valign="top" width="44.519999999999996%" id="mcps1.2.3.1.2"><p id="zh-cn_topic_0000001152616261_p9198135114133"><a name="zh-cn_topic_0000001152616261_p9198135114133"></a><a name="zh-cn_topic_0000001152616261_p9198135114133"></a>说明</p>
</th>
</tr>
</thead>
<tbody><tr id="zh-cn_topic_0000001152616261_row6882121917329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p688241953218"><a name="zh-cn_topic_0000001152616261_p688241953218"></a><a name="zh-cn_topic_0000001152616261_p688241953218"></a>LD_LIBRARY_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1888291915322"><a name="zh-cn_topic_0000001152616261_p1888291915322"></a><a name="zh-cn_topic_0000001152616261_p1888291915322"></a>动态库的查找路径,参考上述举例配置。</p>
<p id="p1292181892120"><a name="p1292181892120"></a><a name="p1292181892120"></a>若训练所在系统环境需要升级gcc(例如CentOS、Debian和BClinux系统),则<span class="parmname" id="parmname795020446318"><a name="parmname795020446318"></a><a name="parmname795020446318"></a>“LD_LIBRARY_PATH”</span>配置项处动态库查找路径需要添加<span class="filepath" id="zh-cn_topic_0256062644_filepath115819811512"><a name="zh-cn_topic_0256062644_filepath115819811512"></a><a name="zh-cn_topic_0256062644_filepath115819811512"></a>“${install_path}/lib64”</span>,其中<span class="filepath" id="zh-cn_topic_0256062644_filepath195951574421"><a name="zh-cn_topic_0256062644_filepath195951574421"></a><a name="zh-cn_topic_0256062644_filepath195951574421"></a>“{install_path}”</span>为gcc升级安装路径。请参见<a href="#安装7-3-0版本gccmd#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li9745165315131">5</a>。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row16194175523010"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p16195185523019"><a name="zh-cn_topic_0000001152616261_p16195185523019"></a><a name="zh-cn_topic_0000001152616261_p16195185523019"></a>PYTHONPATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p19637083322"><a name="zh-cn_topic_0000001152616261_p19637083322"></a><a name="zh-cn_topic_0000001152616261_p19637083322"></a>Python搜索路径,参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row2954102119329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p195452113218"><a name="zh-cn_topic_0000001152616261_p195452113218"></a><a name="zh-cn_topic_0000001152616261_p195452113218"></a>PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p964914893211"><a name="zh-cn_topic_0000001152616261_p964914893211"></a><a name="zh-cn_topic_0000001152616261_p964914893211"></a>可执行程序的查找路径,参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row58592816294"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p1886016892913"><a name="zh-cn_topic_0000001152616261_p1886016892913"></a><a name="zh-cn_topic_0000001152616261_p1886016892913"></a>ASCEND_OPP_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p28608892915"><a name="zh-cn_topic_0000001152616261_p28608892915"></a><a name="zh-cn_topic_0000001152616261_p28608892915"></a>算子根目录,参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row144592037903"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p104601373014"><a name="zh-cn_topic_0000001152616261_p104601373014"></a><a name="zh-cn_topic_0000001152616261_p104601373014"></a>OPTION_EXEC_EXTERN_PLUGIN_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1046013716017"><a name="zh-cn_topic_0000001152616261_p1046013716017"></a><a name="zh-cn_topic_0000001152616261_p1046013716017"></a>算子信息库路径。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row16184379493"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p131851873492"><a name="zh-cn_topic_0000001152616261_p131851873492"></a><a name="zh-cn_topic_0000001152616261_p131851873492"></a>ASCEND_AICPU_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p181851575497"><a name="zh-cn_topic_0000001152616261_p181851575497"></a><a name="zh-cn_topic_0000001152616261_p181851575497"></a>aicpu算子包路径。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row234714854615"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p2034724894619"><a name="zh-cn_topic_0000001152616261_p2034724894619"></a><a name="zh-cn_topic_0000001152616261_p2034724894619"></a>TASK_QUEUE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p53477489462"><a name="zh-cn_topic_0000001152616261_p53477489462"></a><a name="zh-cn_topic_0000001152616261_p53477489462"></a>使用异步任务下发,异步调用acl接口。建议开启,开启设置为1。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row1680820246202"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p4809112415207"><a name="zh-cn_topic_0000001152616261_p4809112415207"></a><a name="zh-cn_topic_0000001152616261_p4809112415207"></a>HCCL_WHITELIST_DISABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p952814428206"><a name="zh-cn_topic_0000001152616261_p952814428206"></a><a name="zh-cn_topic_0000001152616261_p952814428206"></a>配置在使用HCCL时是否开启通信白名单。</p>
<a name="ul928845132310"></a><a name="ul928845132310"></a><ul id="ul928845132310"><li>0:开启白名单,无需校验HCCL通信白名单。</li><li>1:关闭白名单,需校验HCCL通信白名单。</li></ul>
<p id="zh-cn_topic_0000001152616261_p5809162416201"><a name="zh-cn_topic_0000001152616261_p5809162416201"></a><a name="zh-cn_topic_0000001152616261_p5809162416201"></a>缺省值为0,默认开启白名单。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row0671137162115"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p4671203792114"><a name="zh-cn_topic_0000001152616261_p4671203792114"></a><a name="zh-cn_topic_0000001152616261_p4671203792114"></a>HCCL_IF_IP</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1822165982114"><a name="zh-cn_topic_0000001152616261_p1822165982114"></a><a name="zh-cn_topic_0000001152616261_p1822165982114"></a>配置HCCL的初始化通信网卡IP。</p>
<a name="ul2676102292415"></a><a name="ul2676102292415"></a><ul id="ul2676102292415"><li>ip格式为点分十进制。</li><li>暂只支持host网卡。</li></ul>
<p id="zh-cn_topic_0000001152616261_p1167163719217"><a name="zh-cn_topic_0000001152616261_p1167163719217"></a><a name="zh-cn_topic_0000001152616261_p1167163719217"></a>缺省时,按照以下优先级选定host通信网卡名:docker/local以外网卡(网卡名字字典序升序排列)&gt;docker 网卡 &gt; local网卡</p>
</td>
</tr>
<tr id="row743212132309"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p17433111312307"><a name="p17433111312307"></a><a name="p17433111312307"></a>ASCEND_SLOG_PRINT_TO_STDOUT</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p6433151393018"><a name="p6433151393018"></a><a name="p6433151393018"></a>(可选)设置是否开启日志打屏。</p>
<a name="ul760201917473"></a><a name="ul760201917473"></a><ul id="ul760201917473"><li>0:表示采用日志的默认输出方式。</li><li>1:表示日志打屏显示。</li><li>其他值为非法值。</li></ul>
</td>
</tr>
<tr id="row19237171814300"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p14238161893019"><a name="p14238161893019"></a><a name="p14238161893019"></a>ASCEND_GLOBAL_LOG_LEVEL</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p223841810303"><a name="p223841810303"></a><a name="p223841810303"></a>设置应用类日志的全局日志级别。</p>
<a name="ul175714586453"></a><a name="ul175714586453"></a><ul id="ul175714586453"><li>0:对应DEBUG级别。</li><li>1:对应INFO级别。</li><li>2:对应WARNING级别。</li><li>3:对应ERROR级别。</li><li>4:对应NULL级别,不输出日志。</li><li>其他值为非法值。</li></ul>
</td>
</tr>
<tr id="row1348192313303"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1734815235305"><a name="p1734815235305"></a><a name="p1734815235305"></a>ASCEND_GLOBAL_EVENT_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p12348202373018"><a name="p12348202373018"></a><a name="p12348202373018"></a>设置应用类日志是否开启Event日志。</p>
<a name="ul416352114610"></a><a name="ul416352114610"></a><ul id="ul416352114610"><li>0:不开启Event日志。</li><li>1:开启Event日志。</li><li>其他值为非法值。</li></ul>
</td>
</tr>
<tr id="row17878184693015"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1878194683016"><a name="p1878194683016"></a><a name="p1878194683016"></a>DYNAMIC_COMPILE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p1887894620304"><a name="p1887894620304"></a><a name="p1887894620304"></a>(可选)动态shape特性功能,针对shape变化场景,开启设置为1(PyTorch1.8.1不支持该环境变量)。</p>
</td>
</tr>
<tr id="row78312162301"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1832171673019"><a name="p1832171673019"></a><a name="p1832171673019"></a>COMBINED_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(可选)非连续两个算子组合类场景优化,开启设置为1。</p>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(可选)非连续转连续二级推导优化,开启设置为1。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升。但是Host下发性能存在下降风险。</p>
</td>
</tr>
<tr id="row183041355123411"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p730435533415"><a name="p730435533415"></a><a name="p730435533415"></a>ACL_DUMP_DATA</p>
@@ -184,19 +122,11 @@ export DYNAMIC_OP="ADD#MUL" # 算子实现,ADD和MUL算子在不同场景下
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p16304105533412"><a name="p16304105533412"></a><a name="p16304105533412"></a>(可选)算子数据dump功能,调试时使用,开启设置为1。</p>
</td>
</tr>
<tr id="row27481914203518"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p674813144357"><a name="p674813144357"></a><a name="p674813144357"></a>DYNAMIC_OP</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p974891414353"><a name="p974891414353"></a><a name="p974891414353"></a>(可选)算子实现,ADD和MUL算子在不同场景下有不同的性能表现。默认不设置。</p>
</td>
</tr>
<tr id="row19173161510309"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p16711563237"><a name="zh-cn_topic_0000001152616261_p16711563237"></a><a name="zh-cn_topic_0000001152616261_p16711563237"></a>unset GOMP_CPU_AFFINITY</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p0711356152317"><a name="zh-cn_topic_0000001152616261_p0711356152317"></a><a name="zh-cn_topic_0000001152616261_p0711356152317"></a>(可选)当系统为openEuler及其继承操作系统时,如UOS,需设置此命令,取消CPU绑核。</p>
</td>
</tr>
</tbody>
</table>
## 执行单元测试脚本
验证运行, 输出结果OK
@@ -208,7 +138,7 @@ python3 test_div.py
# 安装混合精度模块(可选)
AscendPyTorch1.8.1集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
AscendPyTorch1.8.1集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex/tree/v1.8.1-3.0.rc2/)进行编译安装Apex模块。
- AMP
- 动态loss scale:动态计算loss scale的值并判断是否溢出。
@@ -252,6 +182,7 @@ Ascend PyTorch的版本分支有以下几种维护阶段:
| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained <br> 2022-10-15 estimated | |
| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained <br> 2023-01-15 estimated | |
| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained <br> 2023-04-10 estimated | |
| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained <br> 2023-07-15 estimated | |
# FAQ
@@ -302,13 +233,17 @@ pip3 install typing_extensions
开发态:
```
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 #{arch}为架构名称。
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
用户态:
```
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 #{arch}为架构名称。
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
@@ -317,14 +252,35 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
## 命令行安装cmake依赖时提示找不到包、编译cmake报错版本过低,可使用安装脚本或源码编译安装。
下载安装脚本安装cmake。(参考cmake官网)
方法一:下载安装脚本安装cmake。(参考cmake官网)
​ X86_64环境推荐脚本安装:cmake-3.12.0-Linux-x86_64.sh
​ X86_64环境脚本安装:cmake-3.12.0-Linux-x86_64.sh
​ aarch64环境脚本安装:cmake-3.12.0-Linux-aarch64.sh
1. 执行命令。
```
./cmake-3.12.0-Linux-{arch}.sh #{arch}为架构名称
```
2. 设置软连接。
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
3. 执行如下命令验证是否安装成功。
```
cmake --version
```
如显示“cmake version 3.12.0”则表示安装成功。
部分源下载cmake时会提示无法找到包,需要使用源码编译安装。
方法二:使用源码编译安装。
1. 获取Cmake软件包。
1. 获取cmake软件包。
```
wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
@@ -416,7 +372,7 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
./contrib/download_prerequisites
```
如果上述命令校验失败,需要确保依赖包为一次性下载成功,无重复下载现象。
如果命令校验失败,需要确认上述依赖包在文件夹中的唯一性,无重复下载,若存在重复的依赖包,需删除。
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>执行配置、编译和安装命令:
@@ -426,9 +382,16 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
make install
```
>![](D:\projects\pzrpytorch\pytorch\docs\zh\PyTorch安装指南\public_sys-resources\icon-notice.gif) **须知:**
>![](figures/icon-notice.gif) **须知:**
>其中“--prefix“参数用于指定linux\_gcc7.3.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.3.0“。
4. 修改软连接。
```
ln -s ${install_path}/bin/gcc /usr/bin/gcc
ln -s ${install_path}/bin/g++ /usr/bin/g++
ln -s ${install_path}/bin/c++ /usr/bin/c++
```
5. 配置环境变量。
@@ -438,14 +401,13 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.3.0安装路径,本示例为“/usr/local/gcc7.3.0/“。
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.3.0安装路径,本示例为“/usr/local/linux_gcc7.3.0/“。
>![](D:\projects\pzrpytorch\pytorch\docs\zh\PyTorch安装指南\public_sys-resources\icon-note.gif) **说明:**
>![](figures/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
目前存在测试环境从GCC4.8.5 切换到 GCC7.3.0。这个过程容易出现错误导致pytorch编译不过,以下是需要软连接的库
若存在pytorch编译不过,请检查软连接的库是否正确。
gcc, g++,c++(--version 必须是7.3.0)
libstdc++->libstdc++.so.6.0.24(7.3.0)
@@ -514,7 +476,24 @@ ${镜像名称}:{tag}:镜像名称与版本号。
对实际结果无影响,无需处理。
## import torch_npu 显示_has_compatible_shallow_copy_type重复注册warning问题
# 版本说明
warning如下图所示,由Tensor.set_data浅拷贝操作触发。主要原因是PyTorch插件化解耦后,`_has_compatible_shallow_copy_type`缺乏对NPU Tensor的浅拷贝判断支持,因此需要重新注册`_has_compatible_shallow_copy_type`。
版本说明请参阅[ReleseNote](docs/zh/RELEASENOTE)
该warning不影响模型的精度和性能,可以忽略。
待NPU 设备号合入社区或者后续Pytorch版本`_has_compatible_shallow_copy_type`注册方式发生变动,该warning会被解决。
![输入图片说明](https://images.gitee.com/uploads/images/2022/0701/153621_2b5080c4_7902902.png)
## 在编译torch_npu的目录进入python引用torch_npu报错问题
验证torch_npu的引入,请切换至其他目录进行,在编译目录执行会提示如下错误。
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
# 版本说明<a name='版本说明'></a>
版本说明请参阅[ReleseNote](docs/zh/RELEASENOTE)
File diff suppressed because one or more lines are too long
@@ -727,12 +727,12 @@ The training can be started manually or using the shell script.
3. Open the **/etc/hosts** file on each server and add the corresponding IP address and host name of the server to the first line of the file. If the file already contains the IP address and host name, skip this step. The following is an example of the content to be added:
```
10.90.140.199 ubuntu
xxx.xxx.xxx.111 ubuntu
```
In the preceding content, **10.90.140.199** is the IP address of the server, and **ubuntu** is the host name.
In the preceding content, **xxx.xxx.xxx.111** is the IP address of the server, and **ubuntu** is the host name.
4. Run the following commands on the first server to generate a public key (Assume that the IP address of the first server is **10.90.140.199**.):
4. Run the following commands on the first server to generate a public key (Assume that the IP address of the first server is **xxx.xxx.xxx.111**.):
```
cd ~/.ssh/ # If the directory does not exist, run the ssh localhost command first.
@@ -760,7 +760,7 @@ The training can be started manually or using the shell script.
6. Run the following commands on each of the other servers to copy the public key of the first server to each of the other servers:
cd ~/.ssh/
scp root@10.90.140.199:~/.ssh/authorized_keys ./
scp root@xxx.xxx.xxx.111:~/.ssh/authorized_keys ./
7. Run the following command on each server to test password-free login:
@@ -768,7 +768,7 @@ The training can be started manually or using the shell script.
ssh User name@IP address
```
For example, run the **ssh root@10.90.140.231** command to log in to the server whose IP address is 10.90.140.231 from the first server whose IP address is 10.90.140.199 without a password.
For example, run the **ssh root@xxx.xxx.xxx.222** command to log in to the server whose IP address is xxx.xxx.xxx.222 from the first server whose IP address is xxx.xxx.xxx.111 without a password.
If information similar to the following is displayed, the login without a password is successful.
@@ -788,7 +788,7 @@ The training can be started manually or using the shell script.
```
logout
Connection to 10.90.140.231 closed.
Connection to xxx.xxx.xxx.222 closed.
```
3. Use Open MPI to start model training.
@@ -856,7 +856,7 @@ if [ -d ${install_path}/toolkit ]; then
export ASCEND_OPP_PATH=${install_path}/opp
else
if [ -d ${install_path}/nnae/latest ];then
exportLD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
export PATH=$PATH:${install_path}/nnae/latest/fwkacllib/ccec_compiler/bin/:${install_path}/nnae/latest/toolkit/tools/ide_daemon/bin/
export ASCEND_OPP_PATH=${install_path}/nnae/latest/opp/
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
File diff suppressed because it is too large Load Diff
@@ -1,296 +1,140 @@
# PyTorch Installation Guide
- [PyTorch Installation Guide](#pytorch-installation-guide)
- [Overview](#overview)
- [Manual Build and Installation](#manual-build-and-installation)
- [Prerequisites](#prerequisites)
- [Installing the PyTorch Framework](#installing-the-pytorch-framework)
- [Configuring Environment Variables](#configuring-environment-variables)
- [Installing the Mixed Precision Module](#installing-the-mixed-precision-module)
- [References](#references)
- [Installing CMake](#installing-cmake)
- [How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-730)
- [What to Do If "-torch-1-5-0xxxx-" and "-torchvision-" Do Not Match When-torch--whl- Is Installed?](#what-to-do-if-torch-1-5-0xxxx-and-torchvision-do-not-match-when-torch-whl-is-installed)
## Overview
- [Overview](#overviewa-nameoverviewa)
When setting up the environment for PyTorch model development and running, you can manually build and install the modules adapted to the PyTorch framework on a server.
- [System Dependencies](#system-dependenciesa-namesystem-dependenciesa)
**Figure 1** Environment setup process<a name="zh-cn_topic_0000001119176876_fig1938918396117"></a>
- [Ascend Auxiliary Software](#ascend-auxiliary-softwarea-nameascend-auxiliary-softwarea)
- [Installation Methods](#installation-methodsa-nameinstallation-methodsa)
![](figures/210926103326800.png)
- [Running](#runninga-namerunninga)
- [(Optional) Installing the Mixed Precision Module](#optional-installing-the-mixed-precision-modulea-nameoptional-installing-the-mixed-precision-modulea)
- [FAQs](#faqsa-namefaqsa)
- [Version Descriptio](#version-descriptiona-nameversion-descriptiona)
## Manual Build and Installation
### Prerequisites
#### Prerequisites
# Overview<a name="Overview"></a>
This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch framework so that developers who use the PyTorch framework can obtain powerful compute capabilities of Ascend AI Processors. When setting up the environments for PyTorch model development and operating, developers can manually compile related modules on servers.
## Prerequisites
- The development or operating environment of CANN has been installed. For details, see the *CANN Software Installation Guide*.
- Python 3.7.5, 3.8, and 3.9 are supported.
| AscendPyTorch Version | CANN Version | Supported PyTorch Version |
| :------------ | :----------- | :----------- |
| 3.0.2 | CANN 5.0.2 | 1.5.0.post2 |
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 |
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5, 1.8.1.rc1 |
# System Dependencies<a name="System-Dependencies"></a>
- CMake 3.12.0 or later has been installed. For details about how to install CMake, see [Installing CMake](#installing-cmake).
## CentOS & EulerOS
- GCC 7.3.0 or later has been installed. For details about how to install and use GCC 7.3.0, see [How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-730).
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
- Python 3.7.5, 3.8, or 3.9 has been installed.
yum install -y gcc==7.3.0 cmake==3.12.0
- Note that PyTorch 1.5 does not support Python 3.9 build and installation. Only Torch 1.8.1 supports Python 3.9 build and installation.
## Ubuntu
- The Patch and Git tools have been installed in the environment. To install the tools for Ubuntu and CentOS, run the following commands:
- Ubuntu
apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
```
apt-get install patch
apt-get install git
```
apt-get install -y gcc==7.3.0 cmake==3.12.0
- CentOS:
>![](public_sys-resources/icon-note.gif) **NOTE:**
>If an error occurs during the installation of the GCC and CMake dependency commands, use the source code for installation. For details, see the FAQ.
```
yum install patch
yum install git
```
# Ascend Auxiliary Software<a name="Ascend-Auxiliary-Software"></a>
| AscendPyTorch Version| CANN Version| Supported PyTorch Version| Gitee Branch|
| :------------ | :----------- | :----------- | ------------- |
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
# Installation Methods<a name="Installation-Methods"></a>
## Install the PyTorch environment dependencies.
If you install dependencies as a non-root user, add **--user** at the end of each command in this step, for example, **pip3 install pyyaml --user**.
```sh
pip3 install pyyaml
pip3 install wheel
```
## Compile and install the PyTorch and Ascend plugin.
Install the official torch package, and then compile and install the plugin.
```sh
#x86_64
pip3 install torch==1.8.1+cpu # If an error is reported when you run the pip command to install PyTorch of the CPU version, manually download the .whl package from https://download.pytorch.org/whl/torch.
#AArch64
#The community does not provide the CPU installation package of the ARM architecture. For details, see the first FAQ to compile and install PyTorch using the source code.
```
Compile and generate the binary installation package of the PyTorch plugin.
```
# Download code of the corresponding branch and go to the root directory of the plugin.
git clone -b v1.8.1-3.0.rc2 https://gitee.com/ascend/pytorch.git
cd pytorch
# Specify the Python version packaging mode:
bash ci/build.sh --python=3.7
# or
bash ci/build.sh --python=3.8
#or
bash ci/build.sh --python=3.9
```
### Installing the PyTorch Framework
Install the **torch_npu** package generated in the **pytorch/dist** directory. *{arch}* indicates the architecture name.
#### Installation Process
1. Log in to the server as the **root** user or a non-root user.
2. Run the following commands in sequence to install the PyTorch dependencies.
If you install Python and its dependencies as a non-root user, add **--user** at the end of each command in this step. Example command: **pip3.7 install pyyaml --user**.
```
pip3 install pyyaml
pip3 install wheel
```
3. Obtain the PyTorch source code.
1. Run the following commands to obtain the PyTorch source code adapted to Ascend AI Processors and switch to the required branch:
```
git clone https://gitee.com/ascend/pytorch.git
# By default, the master branch (PyTorch 1.8.1) is used. If another branch is required, run the git checkout command to switch to that branch.
cd pytorch
git checkout -b v1.8.1-3.0.rc1 remotes/origin/v1.8.1-3.0.rc1
```
3. Obtain the native PyTorch source code from the root directory **/pytorch** of the current repository and rename it **pytorch_v1.8.1**.
```
// Version 1.8.1
cd pytorch # Root directory of the plugin
git clone -b v1.8.1 --depth=1 https://github.com/pytorch/pytorch.git pytorch_v1.8.1
```
3. Run the following commands to go to the native PyTorch source code directory **pytorch_v1.8.1** and obtain the PyTorch passive dependency code:
```
cd pytorch_v1.8.1
git submodule sync
git submodule update --init --recursive
```
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Due to network fluctuation, it may take a long time to obtain the source code. If no error is reported after the download is complete, the PyTorch and third-party code on which PyTorch depends are generated.
4. Generate the PyTorch installation package adapted to Ascend AI Processors.
1. Add the patch to the PyTorch source code and build it.
```
cd ../patch
bash apply_patch.sh ../pytorch_v1.8.1
cd ../pytorch_v1.8.1
Specify the Python version packaging mode:
bash build.sh --python=3.7
Or
bash build.sh --python=3.8
Or
bash build.sh --python=3.9
```
Install the **torch** package generated in the dist directory (**pytorch/pytorch_v1.8.1/dist**).
```
cd dist
pip3 install --upgrade torch-1.8.1+ascend.rc1-cp37-cp37m-linux_{arch}.whl #**\{arch\}** indicates the architecture, which can be **aarch64** or **x86\_64**.
```
3. Build and generate the binary installation package of the PyTorch plugin.
```
cd ../../ci # Access the root directory of the plugin.
Specify the Python version packaging mode:
bash build.sh --python=3.7
Or
bash build.sh --python=3.8
Or
bash build.sh --python=3.9
```
Specify the Python version in the environment for build. The generated binary package is stored in the current dist directory **pytorch/dist**.
5. Install the PyTorch plugin.
Go to the **pytorch/dist** directory and run the following command to install the **torch_npu** package:
```
cd ../dist
pip3 install --upgrade torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
```
>![](public_sys-resources/icon-note.gif) **NOTE:**
>To upgrade the PyTorch plugin in the environment, uninstall the PyTorch plugin software package installed in the environment and then perform [5. Install the PyTorch plugin.](#zh-cn_topic_0000001152776301_li49671667141) Run the following command to check whether the PyTorch plugin has been installed:
>**pip3 list | grep torch-npu**
```
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
```
Download TorchVision.
```
pip3 install torchvision==0.9.1
```
### Configuring Environment Variables
# Running<a name="Running"></a>
After the software packages are installed, configure environment variables to use Ascend PyTorch. For details about the environment variables, see [Table 1](#zh-cn_topic_0000001152616261_table42017516135).
## Execute environment variables.
1. Configure the operating environment variables by running the following command in the **root** directory of the PyTorch source code adapted to Ascend AI Processors:
Run the script for setting environment variables in the root directory of the current repository.
```
cd ../
source env.sh
```
2. Select a proper HCCL initialization mode based on the actual scenario and configure the corresponding environment variables.
```
# Scenario 1: Single-node scenario
export HCCL_WHITELIST_DISABLE=1 # Disable the HCCL trustlist.
# Scenario 2: Multi-node scenario
export HCCL_WHITELIST_DISABLE=1 # Disable the HCCL trustlist.
export HCCL_IF_IP="1.1.1.1" # Replace 1.1.1.1 with the actual NIC IP address of the host. Ensure that the NIC IP addresses in use can communicate with each other in the cluster.
```
3. (Optional) Configure function or performance environment variables in the NPU scenario. The variables are disabled by default.
```
export DYNAMIC_COMPILE_ENABLE=1 # (Optional) Dynamic shape feature, which is used when the shape changes. To enable this function, set the value to **1**. (PyTorch 1.8.1 does not support this environment variable.)
export COMBINED_ENABLE=1 # (Optional) Optimizes the scenario where two inconsecutive operators are combined. To enable this function, set the value to **1**.
export ACL_DUMP_DATA=1 # Operator data dump function, which is used for debugging. This environment variable is optional. To enable it, set its value to **1**.
export DYNAMIC_OP="ADD#MUL" # Operator implementation. The ADD and MUL operators have different performance in different scenarios. This parameter is optional.
```
4. (Optional) If the system is openEuler or its inherited OS, such as UOS, run the following command to cancel CPU core binding.
```
# unset GOMP_CPU_AFFINITY
```
```
source env.sh
```
## Customize environment variables.
The following are optional environment variables that may affect running models:
```
export COMBINED_ENABLE=1 # (Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency.
export ACL_DUMP_DATA=1 # (Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.
```
**Table 1** Description of environment variables
<a name="zh-cn_topic_0000001152616261_table42017516135"></a>
<table><thead align="left"><tr id="zh-cn_topic_0000001152616261_row16198951191317"><th class="cellrowborder" valign="top" width="55.48%" id="mcps1.2.3.1.1"><p id="zh-cn_topic_0000001152616261_p51981251161315"><a name="zh-cn_topic_0000001152616261_p51981251161315"></a><a name="zh-cn_topic_0000001152616261_p51981251161315"></a>Environment Variable</p>
</th>
<th class="cellrowborder" valign="top" width="44.519999999999996%" id="mcps1.2.3.1.2"><p id="zh-cn_topic_0000001152616261_p9198135114133"><a name="zh-cn_topic_0000001152616261_p9198135114133"></a><a name="zh-cn_topic_0000001152616261_p9198135114133"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="zh-cn_topic_0000001152616261_row6882121917329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p688241953218"><a name="zh-cn_topic_0000001152616261_p688241953218"></a><a name="zh-cn_topic_0000001152616261_p688241953218"></a>LD_LIBRARY_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1888291915322"><a name="zh-cn_topic_0000001152616261_p1888291915322"></a><a name="zh-cn_topic_0000001152616261_p1888291915322"></a>Dynamic library search path. Set this variable based on the preceding example.</p>
<p id="p1292181892120"><a name="p1292181892120"></a><a name="p1292181892120"></a>If you need to upgrade GCC in OSs such as CentOS, Debian, and BC-Linux, add <strong id="b6163826603"><a name="b6163826603"></a><a name="b6163826603"></a><em id="i161631926505"><a name="i161631926505"></a><a name="i161631926505"></a>${install_path}</em>/lib64</strong> to the <span class="parmname" id="parmname161637265015"><a name="parmname161637265015"></a><a name="parmname161637265015"></a><b>LD_LIBRARY_PATH</b></span> variable of the dynamic library search path. Replace <em id="i01649261704"><a name="i01649261704"></a><a name="i01649261704"></a><strong id="b1216317261109"><a name="b1216317261109"></a><a name="b1216317261109"></a>{install_path}</strong></em> with the GCC installation path. For details, see <a href="#how-do-i-install-gcc-7-3-0md#en-us_topic_0000001135347812_en-us_topic_0000001173199577_en-us_topic_0000001172534867_en-us_topic_0276688294_li9745165315131"> step 5</a>.</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row16194175523010"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p16195185523019"><a name="zh-cn_topic_0000001152616261_p16195185523019"></a><a name="zh-cn_topic_0000001152616261_p16195185523019"></a>PYTHONPATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p19637083322"><a name="en-us_topic_0000001152616261_p19637083322"></a><a name="en-us_topic_0000001152616261_p19637083322"></a>Python search path. Set this variable based on the preceding example.</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row2954102119329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p195452113218"><a name="zh-cn_topic_0000001152616261_p195452113218"></a><a name="zh-cn_topic_0000001152616261_p195452113218"></a>PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p964914893211"><a name="zh-cn_topic_0000001152616261_p964914893211"></a><a name="zh-cn_topic_0000001152616261_p964914893211"></a>Executable program search path. Set this variable based on the preceding example.</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row58592816294"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p1886016892913"><a name="zh-cn_topic_0000001152616261_p1886016892913"></a><a name="zh-cn_topic_0000001152616261_p1886016892913"></a>ASCEND_OPP_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p28608892915"><a name="zh-cn_topic_0000001152616261_p28608892915"></a><a name="zh-cn_topic_0000001152616261_p28608892915"></a>Operator root directory. Set this variable based on the preceding example.</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row144592037903"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p104601373014"><a name="zh-cn_topic_0000001152616261_p104601373014"></a><a name="zh-cn_topic_0000001152616261_p104601373014"></a>OPTION_EXEC_EXTERN_PLUGIN_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1046013716017"><a name="zh-cn_topic_0000001152616261_p1046013716017"></a><a name="zh-cn_topic_0000001152616261_p1046013716017"></a>Path of the operator information library.</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row16184379493"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p131851873492"><a name="zh-cn_topic_0000001152616261_p131851873492"></a><a name="zh-cn_topic_0000001152616261_p131851873492"></a>ASCEND_AICPU_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p181851575497"><a name="zh-cn_topic_0000001152616261_p181851575497"></a><a name="zh-cn_topic_0000001152616261_p181851575497"></a>Path of the AI CPU OPP.</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row234714854615"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p2034724894619"><a name="zh-cn_topic_0000001152616261_p2034724894619"></a><a name="zh-cn_topic_0000001152616261_p2034724894619"></a>TASK_QUEUE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p53477489462"><a name="en-us_topic_0000001152616261_p53477489462"></a><a name="en-us_topic_0000001152616261_p53477489462"></a>Whether to asynchronously deliver tasks and call the ACL APIs. You are advised to set this parameter to <strong id="en-us_topic_0000001152616261_b186701714141819"><a name="en-us_topic_0000001152616261_b186701714141819"></a><a name="en-us_topic_0000001152616261_b186701714141819"></a>1</strong> to enable this function.</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row1680820246202"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p4809112415207"><a name="zh-cn_topic_0000001152616261_p4809112415207"></a><a name="zh-cn_topic_0000001152616261_p4809112415207"></a>HCCL_WHITELIST_DISABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p952814428206"><a name="en-us_topic_0000001152616261_p952814428206"></a><a name="en-us_topic_0000001152616261_p952814428206"></a>Whether to enable the communication trustlist when the HCCL is used.</p>
<a name="ul928845132310"></a><a name="ul928845132310"></a><ul id="ul928845132310"><li><strong id="b12793231525"><a name="b12793231525"></a><a name="b12793231525"></a>0</strong>: enable the trustlist. The HCCL communication trustlist does not need to be verified.</li><li><strong id="b1146142619212"><a name="b1146142619212"></a><a name="b1146142619212"></a>1</strong>: disable the trustlist. The HCCL communication trustlist needs to be verified.</li></ul>
<p id="en-us_topic_0000001152616261_p5809162416201"><a name="en-us_topic_0000001152616261_p5809162416201"></a><a name="en-us_topic_0000001152616261_p5809162416201"></a>The default value is <strong id="en-us_topic_0000001152616261_b1270332516435"><a name="en-us_topic_0000001152616261_b1270332516435"></a><a name="en-us_topic_0000001152616261_b1270332516435"></a>0</strong>, indicating that the trustlist is enabled by default.</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row0671137162115"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p4671203792114"><a name="zh-cn_topic_0000001152616261_p4671203792114"></a><a name="zh-cn_topic_0000001152616261_p4671203792114"></a>HCCL_IF_IP</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p1822165982114"><a name="en-us_topic_0000001152616261_p1822165982114"></a><a name="en-us_topic_0000001152616261_p1822165982114"></a>IP address of the NIC for initializing communication in the HCCL.</p>
<a name="ul2676102292415"></a><a name="ul2676102292415"></a><ul id="ul2676102292415"><li>The IP address is in dotted decimal notation.</li><li>Currently, only the host NIC is supported.</li></ul>
<p id="en-us_topic_0000001152616261_p1167163719217"><a name="en-us_topic_0000001152616261_p1167163719217"></a><a name="en-us_topic_0000001152616261_p1167163719217"></a>By default, the host communication NICs are selected in the following sequence: NICs other than Docker/local NICs (in ascending alphabetical order of NIC names) &gt; Docker NICs &gt; local NICs.</p>
</td>
</tr>
<tr id="row743212132309"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p17433111312307"><a name="p17433111312307"></a><a name="p17433111312307"></a>ASCEND_SLOG_PRINT_TO_STDOUT</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p6433151393018"><a name="p6433151393018"></a><a name="p6433151393018"></a>(Optional) Whether to enable the log printing function.</p>
<a name="ul760201917473"></a><a name="ul760201917473"></a><ul id="ul760201917473"><li><strong id="b1955232216215"><a name="b1955232216215"></a><a name="b1955232216215"></a>0</strong>: uses the default log output mode.</li><li><strong id="b22913272211"><a name="b22913272211"></a><a name="b22913272211"></a>1</strong>: prints the logs to the screen.</li><li>Other values: invalid</li></ul>
</td>
</tr>
<tr id="row19237171814300"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p14238161893019"><a name="p14238161893019"></a><a name="p14238161893019"></a>ASCEND_GLOBAL_LOG_LEVEL</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p223841810303"><a name="p223841810303"></a><a name="p223841810303"></a>Sets the global log level of app logs.</p>
<a name="ul175714586453"></a><a name="ul175714586453"></a><ul id="ul175714586453"><li><strong id="b94698561835"><a name="b94698561835"></a><a name="b94698561835"></a>0</strong>: DEBUG</li><li><strong id="b1612516597314"><a name="b1612516597314"></a><a name="b1612516597314"></a>1</strong>: INFO</li><li><strong id="b82051911547"><a name="b82051911547"></a><a name="b82051911547"></a>2</strong>: WARNING</li><li><strong id="b04351021945"><a name="b04351021945"></a><a name="b04351021945"></a>3</strong>: ERROR</li><li><strong id="b116153316418"><a name="b116153316418"></a><a name="b116153316418"></a>4</strong>: NULL (no log output)</li><li>Other values: invalid</li></ul>
</td>
</tr>
<tr id="row1348192313303"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1734815235305"><a name="p1734815235305"></a><a name="p1734815235305"></a>ASCEND_GLOBAL_EVENT_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p12348202373018"><a name="p12348202373018"></a><a name="p12348202373018"></a>Whether to enable event logging for apps.</p>
<a name="ul416352114610"></a><a name="ul416352114610"></a><ul id="ul416352114610"><li><strong id="b425610311940"><a name="b425610311940"></a><a name="b425610311940"></a>0</strong>: disabled</li><li><strong id="b198984321741"><a name="b198984321741"></a><a name="b198984321741"></a>1</strong>: enabled</li><li>Other values: invalid</li></ul>
</td>
</tr>
<tr id="row17878184693015"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1878194683016"><a name="p1878194683016"></a><a name="p1878194683016"></a>DYNAMIC_COMPILE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p1887894620304"><a name="p1887894620304"></a><a name="p1887894620304"></a>(Optional) Dynamic shape feature, which is used when the shape changes. To enable this function, set the value to <strong id="b11281447194117"><a name="b11281447194117"></a><a name="b11281447194117"></a>1</strong>. (PyTorch 1.8.1 does not support this environment variable.)</p>
</td>
</tr>
<tr id="row78312162301"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1832171673019"><a name="p1832171673019"></a><a name="p1832171673019"></a>COMBINED_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(Optional) Optimizes the scenario where two inconsecutive operators are combined. To enable this function, set the value to <strong id="b19824817612"><a name="b19824817612"></a><a name="b19824817612"></a>1</strong>.</p>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency. However, the host delivery performance may deteriorate.</p>
</td>
</tr>
<tr id="row183041355123411"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p730435533415"><a name="p730435533415"></a><a name="p730435533415"></a>ACL_DUMP_DATA</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p16304105533412"><a name="p16304105533412"></a><a name="p16304105533412"></a>(Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to <strong id="b1861154419918"><a name="b1861154419918"></a><a name="b1861154419918"></a>1</strong>.</p>
</td>
</tr>
<tr id="row27481914203518"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p674813144357"><a name="p674813144357"></a><a name="p674813144357"></a>DYNAMIC_OP</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p974891414353"><a name="p974891414353"></a><a name="p974891414353"></a>(Optional) Operator implementation. The performance of the ADD and MUL operators varies depending on the scenarios. This parameter is not set by default.</p>
</td>
</tr>
<tr id="row19173161510309"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p16711563237"><a name="zh-cn_topic_0000001152616261_p16711563237"></a><a name="zh-cn_topic_0000001152616261_p16711563237"></a>unset GOMP_CPU_AFFINITY</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p0711356152317"><a name="en-us_topic_0000001152616261_p0711356152317"></a><a name="en-us_topic_0000001152616261_p0711356152317"></a>(Optional) If the system is openEuler or its inherited OS, such as UOS, run this command to cancel CPU core binding.</p>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p16304105533412"><a name="p16304105533412"></a><a name="p16304105533412"></a>(Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.</p>
</td>
</tr>
</tbody>
@@ -298,234 +142,334 @@ After the software packages are installed, configure environment variables to us
### Installing the Mixed Precision Module
## Run the unit test script.
#### Prerequisites
Verify the running. The output is **OK**.
1. Ensure that the PyTorch framework adapted to Ascend AI Processors in the operating environment can be used properly.
2. Before building and installing Apex, you have configured the environment variables on which the build depends. See [Configuring Environment Variables](#configuring-environment-variables).
```shell
cd test/test_network_ops/
python3 test_div.py
```
#### Installation Process
# (Optional) Installing the Mixed Precision Module<a name="(Optional) Installing the Mixed Precision Module"></a>
1. Log in to the server as the **root** user or a non-root user.
2. Obtain the Apex source code.
AscendPyTorch 1.8.1 integrates the AMP module and can be used for training with mixed precision. The differences between the AMP module and the Apex module are as follows. You can select a desired module. For details about how to compile and install the Apex module, see the related [**README.en**](https://gitee.com/ascend/apex) file.
(1) Run the following command to obtain the Apex source code adapted to Ascend AI Processors:
- AMP
```
git clone -b master https://gitee.com/ascend/apex.git
```
The directory structure of the downloaded source code is as follows:
```
apex
│ ├─patch # Directory of the patch adapted to Ascend AI Processors
│ ├─npu.patch
│ ├─scripts # Build and create a directory.
│ ├─gen.sh
│ ├─src # Source code directory
│ ├─tests # Directory for storing test cases
```
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
- Tensor fusion is not supported.
(2) Run the following commands to go to the **apex** directory and obtain the native Apex source code:
- Apex
```
cd apex
git clone https://github.com/NVIDIA/apex.git
```
After the native Apex source code is downloaded, the main directory structure of the code is as follows:
```
apex
│ ├─apex # Directory for storing the native Apex code
│ ├─patch # Directory of the patch adapted to Ascend AI Processors
│ ├─npu.patch
│ ├─scripts # Build and create a directory.
│ ├─gen.sh
│ ├─src # Source code directory
│ ├─tests # Directory for storing test cases
```
(3) Go to the native Apex code directory, that is, **apex/apex**. Switch to the code branch whose commit ID is 4ef930c1c884fdca5f472ab2ce7cb9b505d26c1a.
```
cd apex
git checkout 4ef930c1c884fdca5f472ab2ce7cb9b505d26c1a
```
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Due to network fluctuation, it may take a long time to obtain the source code.
3. Generate the Apex installation package adapted to Ascend AI Processors.
(1) Go to the **apex/scripts** directory and run the conversion script to generate full code adapted to Ascend AI Processors.
```
cd ../scripts
bash gen.sh
```
The full code adapted to Ascend AI Processors is generated in the **apex/apex** directory.
(2) Go to the full code directory **apex/apex**, and compile and generate the binary installation package of Apex.
```
cd ../apex
python3 setup.py --cpp_ext --npu_float_status bdist_wheel
```
The Python version must be the same as that used by PyTorch. The generated binary package is stored in the current **dist** directory, that is, **apex/apex/dist**.
4. Install Apex.
Go to the **apex/apex/dist** directory and run the following command to install Apex:
```
cd dist
pip3 install --upgrade apex-0.1+ascend-cp37-cp37m-linux_{arch}.whl
```
*\{arch\}* indicates the architecture information, which can be **aarch64** or **x86\_64**.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>To upgrade the Apex in the environment, uninstall the PyTorch software package installed in the environment and then perform [4. Install Apex.](#zh-cn_topic_0000001106176190_li425495374416) Run the following command to check whether PyTorch has been installed:
>**pip3 list | grep apex**
## References
### Installing CMake
Procedure for upgrading CMake to 3.12.1
1. Obtain the CMake software package.
```
wget https://cmake.org/files/v3.12/cmake-3.12.1.tar.gz --no-check-certificate
```
2. Decompress the package and go to the software package directory.
```
tar -xf cmake-3.12.1.tar.gz
cd cmake-3.12.1/
```
3. Run the configuration, compilation, and installation commands.
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. Run the following command to check whether CMake has been installed:
```
cmake --version
```
If the message "cmake version 3.12.1" is displayed, the installation is successful.
- O1 configuration mode: Conv and Matmul use the float16 precision for computing, and Softmax and BN use float32.
- O2 configuration mode: BN uses the float32 precision for computing, and others use float16.
- Static loss scale: Parameters are statically set to ensure the convergence of training with mixed precision.
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
### How Do I Install GCC 7.3.0?
# FAQs<a name="FAQs"></a>
## When the CPU architecture is ARM, PyTorch 1.8.1 cannot be installed using the PIP3 command because the community does not provide the torch package for the ARM CPU architecture. In this case, use the source code to compile and install PyTorch 1.8.1.
Download the PyTorch 1.8.1 source package.
```
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
```
Access the source package to obtain the passive dependency code.
```
cd pytorch_v1.8.1
git submodule sync
git submodule update --init --recursive
```
Compile and install PyTorch 1.8.1.
```
python3 setup.py install
```
## When PIP is set to the Huawei source, a Python environment error occurs after the typing dependency in the **requirements.txt** file is installed.
When PIP is set to the Huawei source, open the **requirements.txt** file, delete the typing dependency, and then run the following command:
```
pip3 install -r requirments.txt
```
## The error message "no module named yaml/typing_extensions." is displayed when **bash build.sh** is run during compilation.
PyTorch compilation depends on the YAML and typing_extensions libraries, which need to be manually installed.
```
pip3 install pyyaml
pip3 install typing_extensions
```
After the installation is successful, run **make clean** and then **bash build.sh** to perform compilation. Otherwise, an unknown compilation error may occur due to the cache.
## TE cannot be found during running.
Development state:
```
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 # {arch} is the architecture name.
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
User state:
```
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 # {arch} is the architecture name.
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
## During CMake installation through the CLI, an error is reported indicating that the package cannot be found. During CMake compilation, another error is reported indicating that the version is too early. In this cause, you can use the installation script or source code to compile and install CMake.
Method 1: Download the installation script and install CMake. (For details, see the CMake official website.)
​ x86_64 environment: cmake-3.12.0-Linux-x86_64.sh
​ AArch64 environment: cmake-3.12.0-Linux-aarch64.sh
1. Run the following command:
```
./cmake-3.12.0-Linux-{arch}.sh # {arch} indicates the architecture name.
```
2. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
3. Run the following command to check whether CMake has been installed:
```
cmake --version
```
If the message "cmake version 3.12.0" is displayed, the installation is successful.
Method 2: Use the source code to compile and install.
1. Obtain the CMake software package.
```
wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
```
2. Decompress the package and go to the software package directory.
```
tar -xf cmake-3.12.0.tar.gz
cd cmake-3.12.0/
```
3. Run the configuration, compilation, and installation commands.
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. Run the following command to check whether CMake has been installed:
```
cmake --version
```
If the message "cmake version 3.12.0" is displayed, the installation is successful.
## During GCC installation through the CLI, an error is reported indicating that the package cannot be found. During GCC compilation, another error is reported.
When downloading GCC from some sources, you may be prompted by an error message indicating that the package cannot be found. In this case, use the source code to compile and install GCC.
Perform the following steps as the **root** user.
1. Download **gcc-7.3.0.tar.gz** from [https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz).
2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
1. Download **gcc-7.3.0.tar.gz** from [https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz).
```
sudo rm -rf /tmp/*
```
2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
3. Install the dependency package. (CentOS and Ubuntu are used as examples.)
- For CentOS, run the following command:
```
sudo rm -rf /tmp/*
```
```
yum install bzip2
```
3. Install the dependency package. (CentOS and Ubuntu are used as examples.)
- For Ubuntu, run the following command:
- For CentOS, run the following command:
```
apt-get install bzip2
```
```
yum install bzip2
```
4. Build and install GCC.
1. Go to the directory where the source package **gcc-7.3.0.tar.gz** is located and run the following command to decompress it:
- For Ubuntu, run the following command:
```
tar -zxvf gcc-7.3.0.tar.gz
```
```
apt-get install bzip2
```
2. Go to the extracted directory and run the following command to download the GCC dependency packages:
4. Compile and install GCC.
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
1. Go to the directory where the source package **gcc-7.3.0.tar.gz** is located and run the following command to decompress it:
If an error is reported during the command execution, run the following commands in the **gcc-7.3.0/** directory to download the dependency packages:
```
tar -zxvf gcc-7.3.0.tar.gz
```
```
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
```
2. Go to the extracted directory and download the GCC dependency packages:
After the preceding dependencies are downloaded, run the following command again:
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
```
./contrib/download_prerequisites
```
If an error is reported during the command execution, run the following commands in the **gcc-7.3.0/** directory to download the dependency packages:
If the validation fails, check whether the dependency packages are downloaded more than once.
```
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
```
3. Run the configuration, build, and installation commands.
After the preceding dependencies are downloaded, run the following command again:
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
make -j15 # Check the number of CPUs by running **grep -w processor /proc/cpuinfo|wc -l**. In this example, the number is 15.
make install
```
```
./contrib/download_prerequisites
```
>![](public_sys-resources/icon-notice.gif) **NOTICE:**
>The **--prefix** option is used to specify the **linux\_gcc7.3.0** installation path, which is configurable. Do not set it to **/usr/local** or **/usr**, which is the default installation path for the GCC installed by using the software source. Otherwise, a conflict occurs and the original GCC compilation environment of the system is damaged. In this example, the installation path is set to **/usr/local/linux\_gcc7.3.0**.
If the verification fails, check whether there are duplicate dependency packages in the folder. If yes, delete duplicate ones.
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>Run the configuration, compilation, and installation commands.
5. Set the environment variable.
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
make -j15 # Check the number of CPUs by running **grep -w processor /proc/cpuinfo|wc -l**. In this example, the number is 15. You can set the parameters as required.
make install
```
Training must be performed in the compilation environment with GCC upgraded. If you want to run training, configure the following environment variable in your training script:
>![](public_sys-resources/icon-notice.gif) **NOTICE:**
>The **--prefix** option is used to specify the **linux\_gcc7.3.0** installation path, which is configurable. Do not set it to **/usr/local** or **/usr,** which is the default installation path for the GCC installed by using the software source. Otherwise, a conflict occurs and the original GCC compilation environment of the system is damaged. In this example, the installation path is set to **/usr/local/linux\_gcc7.3.0**.
4. Change the soft links.
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
```
ln -s ${install_path}/bin/gcc /usr/bin/gcc
ln -s ${install_path}/bin/g++ /usr/bin/g++
ln -s ${install_path}/bin/c++ /usr/bin/c++
```
**${install_path}** indicates the GCC 7.3.0 installation path configured in [3](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310). In this example, the GCC 7.3.0 installation path is **/usr/local/gcc7.3.0/**.
5. Configure environment variables.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Skip this step if you do not need to use the compilation environment with GCC upgraded.
Training must be performed in the compilation environment with GCC upgraded. If you want to run training, configure the following environment variable in your training script:
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
### What to Do If "-torch-1-5-0xxxx-" and "-torchvision-" Do Not Match When-torch--whl- Is Installed?
**${install_path}** indicates the GCC 7.3.0 installation path configured in [3](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310). In this example, the GCC 7.3.0 installation path is **/usr/local/linux_gcc7.3.0/**.
#### Symptom
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Skip this step if you do not need to use the compilation environment with GCC upgraded.
During the installation of **torch-\*.whl**, the message "ERROR: torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible" is displayed.
If the PyTorch compilation fails, check whether the soft link library is correct.
![](figures/zh-cn_image_0000001190081735.png)
libstdc++->libstdc++.so.6.0.24(7.3.0)
#### Possible Causes
## libblas.so cannot be found.
The OpenBLAS library is missing in the environment. You need to install it.
CentOS and EulerOS
```sh
yum -y install openblas
```
Ubuntu
```sh
apt install libopenblas-dev
```
## No device is mounted to the container.
An NPU-related error is reported when a script is run in the container. The **device** parameter is not set before container instance startup. As a result, the instance cannot be started.
![](figures/FAQ.png)
Run the following command to restart the container:
```sh
docker run -it --ipc=host \
--device=/dev/davinciX \
--device=/dev/davinci_manager \
--device=/dev/devmm_svm \
--device=/dev/hisi_hdc \
-v /usr/local/Ascend/driver \
-v /usr/local/dcmi \
-v /usr/local/bin/npu-smi \
${image name}:{tag} \
/bin/bash
```
Parameter description:
**/dev/davinci*X***: NPU device. *X* is the physical ID of the chip, for example, **davinci0**.
**/dev/davinci_manager**: management device
**/dev/devmm_svm**: management device
**/dev/hisi_hdc**: management device
**/usr/local/Ascend/driver**: driver directory
**/usr/local/dcmi**: DCMI directory
**/usr/local/bin/npu-smi**: npu-smi tool
**$*{image name}:{tag}***: image name and version
## An error is displayed during installation of -torch--whl-, indicating that -torch-1-5-0xxxx- and -torchvision- versions do not match.
During installation of **torch-\*.whl**, the message "ERROR: torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible" is displayed.
![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/figures/zh-cn_image_0000001190081735.png)
When the PyTorch is installed, the version check is automatically triggered. The version of the torchvision installed in the environment is 0.6.0. During the check, it is found that the version of the **torch-\*.whl** is inconsistent with the required version 1.5.0. As a result, an error message is displayed, but the installation is successful.
#### Solution
This problem does not affect the actual result, and no action is required.
This problem has no impact on the actual result, and no action is required.
## When you run **import torch_npu**, if "_has_compatible_shallow_copy_type" is output, a warning about a repeated registration error is displayed.
The warning is triggered by the shallow copy operation of **Tensor.set_data**, as shown in the following figure. The main cause is that after the PyTorch plugin is decoupled, `_has_compatible_shallow_copy_type` cannot detect shallow copy of NPU tensors. You need to register `_has_compatible_shallow_copy_type` again.
This error can be ignored because it does not affect the model accuracy and performance.
It will be resolved after the NPU's device ID is incorporated into the community or the `_has_compatible_shallow_copy_type` registration mode is changed in a later PyTorch version.
![Input Image Description](https://images.gitee.com/uploads/images/2022/0701/153621_2b5080c4_7902902.png)
## An error is reported when torch_npu is referenced with Python commands in the compilation directory.
To verify the torch_npu reference, switch to another directory. If you perform the verification in the compilation directory, the following error message is displayed:
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
# Version Description<a name='Version Description'></a>
For details, see [Release Notes](https://gitee.com/ascend/pytorch/tree/master/docs/en/RELEASENOTE).
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

@@ -1,137 +1,34 @@
# PyTorch Network Model Porting and Training Guide
- [PyTorch Network Model Porting and Training Guide](#pytorch-network-model-porting-and-training-guide)
- [Overview](#overview)
- [Solution Features and Advantages](#solution-features-and-advantages)
- [Restrictions and Limitations](#restrictions-and-limitations)
- [Porting Process](#porting-process)
- [Quick Start](#quick-start)
- [Introduction](#introduction)
- [Model Selection](#model-selection)
- [Model Porting Evaluation](#model-porting-evaluation)
- [Environment Setup](#environment-setup)
- [Model Porting](#model-porting)
- [Single-Device Training Porting](#single-device-training-porting)
- [Single-Server Multi-Device Training Modification](#single-server-multi-device-training-modification)
- [Model Training](#model-training)
- [Model Porting Evaluation](#model-porting-evaluation-1)
- [Environment Setup](#environment-setup-1)
- [Model Porting](#model-porting-1)
- [Tool-Facilitated](#tool-facilitated)
- [Introduction](#introduction-1)
- [Overview](#overview-1)
- [Model Support](#model-support)
- [System Requirement](#system-requirement)
- [Environment Setup](#environment-setup-2)
- [Instructions](#instructions)
- [Command-line Options](#command-line-options)
- [Customizing a Rule File](#customizing-a-rule-file)
- [Performing Conversion](#performing-conversion)
- [Result Analysis](#result-analysis)
- [Manual](#manual)
- [Single-Device Training Model Porting](#single-device-training-model-porting)
- [Multi-Device Training Model Porting](#multi-device-training-model-porting)
- [PyTorch-related API Replacement](#pytorch-related-api-replacement)
- [Mixed Precision](#mixed-precision)
- [Overview](#overview-2)
- [Supported Features](#supported-features)
- [Integrating Mixed Precision Module Into the PyTorch Model](#integrating-mixed-precision-module-into-the-pytorch-model)
- [Usage of PyTorch 1.8.1 AMP on NPUs](#usage-of-pytorch-181-amp-on-npus)
- [Overview](#overview-3)
- [AMP Application Scenarios](#amp-application-scenarios)
- [Usage of AMP on NPUs](#usage-of-amp-on-npus)
- [Precautions](#precautions)
- [Model Training](#model-training-1)
- [Performance Analysis and Optimization](#performance-analysis-and-optimization)
- [Prerequisites](#prerequisites)
- [Commissioning Process](#commissioning-process)
- [Overall Guideline](#overall-guideline)
- [Training Data Collection](#training-data-collection)
- [Profile Data Collection](#profile-data-collection)
- [Obtaining Operator Information (OP_INFO)](#obtaining-operator-information-op_info)
- [Host-side Performance Optimization](#host-side-performance-optimization)
- [Overview](#overview-4)
- [Changing the CPU Performance Mode (x86 Server)](#changing-the-cpu-performance-mode-x86-server)
- [Setting the Power Policy to High Performance](#setting-the-power-policy-to-high-performance)
- [Setting the CPU Mode to Performance](#setting-the-cpu-mode-to-performance)
- [Changing the CPU Performance Mode (ARM Server)](#changing-the-cpu-performance-mode-arm-server)
- [Setting the Power Policy to High Performance](#setting-the-power-policy-to-high-performance-1)
- [Installing the High-Performance Pillow Library (x86 Server)](#installing-the-high-performance-pillow-library-x86-server)
- [(Optional) Installing the OpenCV Library of the Specified Version](#optional-installing-the-opencv-library-of-the-specified-version)
- [Training Performance Optimization](#training-performance-optimization)
- [Operator Bottleneck Optimization](#operator-bottleneck-optimization)
- [Copy Bottleneck Optimization](#copy-bottleneck-optimization)
- [Framework Bottleneck Optimization](#framework-bottleneck-optimization)
- [Compilation Bottleneck Optimization](#compilation-bottleneck-optimization)
- [E2E Performance Tool (E2E prof) Instructions](#e2e-performance-tool-e2e-prof-instructions)
- [Introduction](#introduction-2)
- [Usage Tutorial](#usage-tutorial)
- [Result Parsing](#result-parsing)
- [Advanced Settings](#advanced-settings)
- [Affinity Library](#affinity-library)
- [Source](#source)
- [Functions](#functions)
- [AOE Instructions](#aoe-instructions)
- [Introduction to AOE](#introduction-to-aoe)
- [AOE Usage](#aoe-usage)
- [Precautions](#precautions-1)
- [Performance Verification](#performance-verification)
- [Precision Commissioning](#precision-commissioning)
- [Prerequisites](#prerequisites-1)
- [Commissioning Process](#commissioning-process-1)
- [Overall Guideline](#overall-guideline-1)
- [Precision Tuning Methods](#precision-tuning-methods)
- [**Environment Setup**](#environment-setup-3)
- [Model Operator Precision Comparison](#model-operator-precision-comparison)
- [Single-Operator Overflow/Underflow Detection](#single-operator-overflowunderflow-detection)
- [Mapping Between IR and TBE Operators](#mapping-between-ir-and-tbe-operators)
- [Mapping Between NPU and GPU Operators.](#mapping-between-npu-and-gpu-operators)
- [Model Saving and Conversion](#model-saving-and-conversion)
- [Introduction](#introduction-3)
- [Saving a Model](#saving-a-model)
- [Exporting an ONNX Model](#exporting-an-onnx-model)
- [Introduction](#introduction-4)
- [Using the .pth or .pt File to Export the ONNX Model](#using-the-pth-or-pt-file-to-export-the-onnx-model)
- [Using the .pth.tar File to Export the ONNX Model](#using-the-pthtar-file-to-export-the-onnx-model)
- [Samples](#samples)
- [ShuffleNet Model Optimization](#shufflenet-model-optimization)
- [Obtaining Samples](#obtaining-samples)
- [How to Obtain](#how-to-obtain)
- [Directory Structure](#directory-structure)
- [Model Evaluation](#model-evaluation)
- [Porting the Network](#porting-the-network)
- [Commissioning the Network](#commissioning-the-network)
- [Forward check](#forward-check)
- [Entire Network Check](#entire-network-check)
- [Python Optimization Details](#python-optimization-details)
- [References](#references)
- [Single-Operator Sample Building](#single-operator-sample-building)
- [Single-Operator Dump Method](#single-operator-dump-method)
- [Collecting Dump Data](#collecting-dump-data)
- [Viewing Overflowed Data](#viewing-overflowed-data)
- [Parse the dump file of an overflow operator.](#parse-the-dump-file-of-an-overflow-operator)
- [Common Environment Variables](#common-environment-variables)
- [dump op Method](#dump-op-method)
- [Compile Option Settings](#compile-option-settings)
- [How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-730)
- [HDF5 Compilation and Installation](#hdf5-compilation-and-installation)
- [FAQs](#faqs)
- [FAQs About Software Installation](#faqs-about-software-installation)
- [FAQs About Model and Operator Running](#faqs-about-model-and-operator-running)
- [FAQs About Model Commissioning](#faqs-about-model-commissioning)
- [FAQs About Other Operations](#faqs-about-other-operations)
- [FAQs About Distributed Model Training](#faqs-about-distributed-model-training)
- [Overview](#Overviewmd)
- [Restrictions and Limitations](#Restrictions-and-Limitationsmd)
- [Porting Process](#Porting-Processmd)
- [Quick Start](#Quick-Startmd)
- [Model Porting Evaluation](#Model-Porting-Evaluationmd)
- <a href="#Environment Setupmd">Environment Setup</a>
- <a href="#Model Portingmd">Model Porting</a>
- <a href="#Model Trainingmd">Model Training</a>
- <a href="#Performance Optimization and Analysismd">Performance Optimization and Analysis</a>
- <a href="#Precision Commissioningmd">Precision Commissioning</a>
- <a href="#Model Saving and Conversionmd">Model Saving and Conversion</a>
- [ShuffleNet Model Optimization](#ShuffleNet-Model-Optimizationmd)
- [References](#Referencesmd)
- <a href="#FAQsmd">FAQs</a>
- [FAQs About Software Installation](#faqs-about-software-installationmd)
- [FAQs About Model and Operator Running](#faqs-about-model-and-operator-runningmd)
- [FAQs About Model Commissioning](#faqs-about-model-commissioningmd)
- [FAQs About Other Operations](#faqs-about-other-operationsmd)
- [FAQs About Distributed Model Training](#faqs-about-distributed-model-trainingmd)
## Overview
## <h2 id="Overviewmd">Overview</h2>
Currently, the solution of adapting to the Ascend AI Processor is an online solution.
### Solution Features and Advantages
The acceleration of the Ascend AI Processor is implemented by calling various operators (OP-based). That is, the AscendCL is used to call one or more D affinity operators to replace the original GPU-based implementation. [Figure 1](#fig2267112413239) shows the logical model of the implementation.
The acceleration of the Ascend AI Processor is implemented by calling various operators (OP-based). That is, the AscendCL is used to call one or more D affinity operators to replace the original GPU-based implementation. [Figure 1](#123) shows the logical model of the implementation.
**Figure 1** Logical model
**Figure 1** Logical model<a name="123"></a>
![](figures/pytorch适配逻辑结构图-优化.png)
@@ -144,7 +41,7 @@ Currently, the main reasons for selecting the online adaptation solution are as
4. It has good scalability. During the streamlining process, only the development and implementation of related compute operators are involved for new network types or structures. Framework operators, reverse graph building, and implementation mechanisms can be reused.
5. The usage and style are the same as those of the GPU-based implementation. During online adaptation, you only need to specify the device as the Ascend AI Processor in Python and device operations to develop, train, and debug the network in PyTorch using the Ascend AI Processor. You do not need to pay attention to the underlying details of the Ascend AI Processor. In this way, you can minimize the modification and complete porting with low costs.
## Restrictions and Limitations
## <h2 id="Restrictions-and-Limitationsmd">Restrictions and Limitations</h2>
- In the **infershape** phase, operators do not support unknown shape inference.
- Only the float16 operator can be used for cube computing.
@@ -157,11 +54,11 @@ Currently, the main reasons for selecting the online adaptation solution are as
- Allocation at only 1, 2, 4, or 8 processors is supported.
- Only the int8, int32, float16, and float32 data types are supported.
## Porting Process
## <h2 id="Porting-Processmd">Porting Process</h2>
Model porting refers to moving models that have been implemented in the open-source community to an Ascend AI Processor. [Figure 2](#fig759451810422) shows the model porting process.
**Figure 2** Porting process
**Figure 2** Porting process<a name="fig759451810422"></a>
![](figures/porting-process.png "porting-process")
**Table 1** Porting process
@@ -179,7 +76,7 @@ Model porting refers to moving models that have been implemented in the open-sou
</tr>
<tr id="row53492016112717"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p133501716132719"><a name="p133501716132719"></a><a name="p133501716132719"></a>Model porting evaluation</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p113504168278"><a name="p113504168278"></a><a name="p113504168278"></a>For details, see <a href="#model-porting-evaluationmd">Model Porting Evaluation</a>.</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p113504168278"><a name="p113504168278"></a><a name="p113504168278"></a>For details, see <a href="#Model-Porting-Evaluationmd">Model Porting Evaluation</a>.</p>
</td>
</tr>
<tr id="row9883113014287"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p8883203017280"><a name="p8883203017280"></a><a name="p8883203017280"></a>Operator development</p>
@@ -189,17 +86,17 @@ Model porting refers to moving models that have been implemented in the open-sou
</tr>
<tr id="row2056653212812"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p1656743213814"><a name="p1656743213814"></a><a name="p1656743213814"></a>Environment setup</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p1156712323811"><a name="p1156712323811"></a><a name="p1156712323811"></a>For details, see <a href="#environment-setupmd">Environment Setup</a>.</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p1156712323811"><a name="p1156712323811"></a><a name="p1156712323811"></a>For details, see <a href="#Environment Setupmd">Environment Setup</a>.</p>
</td>
</tr>
<tr id="row43031317489"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p14304131711817"><a name="p14304131711817"></a><a name="p14304131711817"></a>Model porting</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p53043171687"><a name="p53043171687"></a><a name="p53043171687"></a>For details, see <a href="#model-portingmd">Model Porting</a>.</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p53043171687"><a name="p53043171687"></a><a name="p53043171687"></a>For details, see <a href="#Model Portingmd">Model Porting</a>.</p>
</td>
</tr>
<tr id="row10695931399"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p186956311094"><a name="p186956311094"></a><a name="p186956311094"></a>Model training</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p10696123117914"><a name="p10696123117914"></a><a name="p10696123117914"></a>For details, see <a href="#model-trainingmd">Model Training</a>.</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p10696123117914"><a name="p10696123117914"></a><a name="p10696123117914"></a>For details, see <a href="#Model Trainingmd">Model Training</a>.</p>
</td>
</tr>
<tr id="row1658912015291"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p195901920192910"><a name="p195901920192910"></a><a name="p195901920192910"></a>Error analysis</p>
@@ -209,17 +106,17 @@ Model porting refers to moving models that have been implemented in the open-sou
</tr>
<tr id="row13191151664310"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p219216162433"><a name="p219216162433"></a><a name="p219216162433"></a>Performance analysis and optimization</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p11192181615434"><a name="p11192181615434"></a><a name="p11192181615434"></a>For details, see <a href="#performance-analysis-and-optimizationmd">Performance Optimization and Analysis</a>.</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p11192181615434"><a name="p11192181615434"></a><a name="p11192181615434"></a>For details, see <a href="#Performance Optimization and Analysismd">Performance Optimization and Analysis</a>.</p>
</td>
</tr>
<tr id="row94308194435"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p74301019144319"><a name="p74301019144319"></a><a name="p74301019144319"></a>Precision commissioning</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p24301119174313"><a name="p24301119174313"></a><a name="p24301119174313"></a>For details, see <a href="#precision-commissioningmd">Precision Commissioning</a>.</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p24301119174313"><a name="p24301119174313"></a><a name="p24301119174313"></a>For details, see <a href="#Precision Commissioningmd">Precision Commissioning</a>.</p>
</td>
</tr>
<tr id="row7630202112430"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p1263012210438"><a name="p1263012210438"></a><a name="p1263012210438"></a>Model saving and conversion</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p12631521104319"><a name="p12631521104319"></a><a name="p12631521104319"></a>For details, see <a href="#model-saving-and-conversionmd">Model Saving and Conversion</a> and "ATC Tool Instructions" in the <span id="ph98735134233"><a name="ph98735134233"></a><a name="ph98735134233"></a><em id="en-us_topic_0000001135865460_i17706223113013_1"><a name="en-us_topic_0000001135865460_i17706223113013_1"></a><a name="en-us_topic_0000001135865460_i17706223113013_1"></a>CANN Auxiliary Development Tool User Guide </em></span>.</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p12631521104319"><a name="p12631521104319"></a><a name="p12631521104319"></a>For details, see <a href="#Model Saving and Conversionmd">Model Saving and Conversion</a> and "ATC Tool Instructions" in the <span id="ph98735134233"><a name="ph98735134233"></a><a name="ph98735134233"></a><em id="en-us_topic_0000001135865460_i17706223113013_1"><a name="en-us_topic_0000001135865460_i17706223113013_1"></a><a name="en-us_topic_0000001135865460_i17706223113013_1"></a>CANN Auxiliary Development Tool User Guide </em></span>.</p>
</td>
</tr>
<tr id="row196272410438"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p176218241431"><a name="p176218241431"></a><a name="p176218241431"></a>Application software development</p>
@@ -229,13 +126,13 @@ Model porting refers to moving models that have been implemented in the open-sou
</tr>
<tr id="row17586759102515"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p6586155952510"><a name="p6586155952510"></a><a name="p6586155952510"></a>FAQs</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p105871359192515"><a name="p105871359192515"></a><a name="p105871359192515"></a>Describes how to prepare the environment, port models, commission models, and resolve other common problems. For details, see <a href="#faqsmd">FAQs</a>.</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p105871359192515"><a name="p105871359192515"></a><a name="p105871359192515"></a>Describes how to prepare the environment, port models, commission models, and resolve other common problems. For details, see <a href="#FAQsmd">FAQs</a>.</p>
</td>
</tr>
</tbody>
</table>
## Quick Start
## <h2 id="Quick-Startmd">Quick Start</h2>
### Introduction
@@ -806,7 +703,7 @@ python3 main.py /home/data/resnet50/imagenet --addr='1.1.1.1' \ #
>![](public_sys-resources/icon-note.gif) **NOTE:** **dist-backend** must be set to **hccl** to support distributed training on Ascend AI devices.
## Model Porting Evaluation
## <h2 id="Model-Porting-Evaluationmd">Model Porting Evaluation</h2>
1. When selecting models, select authoritative PyTorch models as benchmarks, including but not limited to PyTorch ([example](https://github.com/pytorch/examples/tree/master/imagenet)/[vision](https://github.com/pytorch/vision)), facebookresearch ([Detectron](https://github.com/facebookresearch/Detectron)/[detectron2](https://github.com/facebookresearch/detectron2)), and open-mmlab ([mmdetection](https://github.com/open-mmlab/mmdetection)/[mmpose](https://github.com/open-mmlab/mmpose)).
@@ -815,11 +712,11 @@ python3 main.py /home/data/resnet50/imagenet --addr='1.1.1.1' \ #
>![](public_sys-resources/icon-note.gif) **NOTE:**
>You can also port the model and training script to the Ascend AI Processor for training to view the error information. For details about how to port the model and training script, see the following sections. Generally, a message is displayed, indicating that an operator (the first operator that is not supported) cannot run in the backend of the Ascend AI Processor. Environment Setup
## Environment Setup
## <h2 id="Environment Setupmd">Environment Setup</h2>
Refer to the *[PyTorch Installation Guide](https://gitee.com/ascend/pytorch/blob/master/docs/en/PyTorch%20Installation%20Guide/PyTorch%20Installation%20Guide.md)* to install PyTorch and the mixed precision module, and configure required environment variables.
## Model Porting
## <h2 id="Model Portingmd">Model Porting</h2>
### Tool-Facilitated
@@ -832,9 +729,9 @@ The Ascend platform provides a script conversion tool to enable you to port trai
Ascend NPU is an up-and-comer in the AI computing field, but most training and online inference scripts are based on GPUs. Due to the architecture differences between NPUs and GPUs, GPU-based training and online inference scripts cannot be directly used on NPUs. The script conversion tool provides an automated method for converting GPU-based scripts into NPU-based scripts, reducing the learning cost and workload of manual script migration, thereby improving the migration efficiency.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>- msFmkTransplt provides suggestions and converts scripts by the adaptation rules, significantly accelerating script migration and reducing development workload. The scripts in [Table 3](#en-us_topic_0000001133095885_table4705239194613) can be directly executed after being converted. The conversion results of other scripts are for reference only. You need to perform adaptation based on the site requirements.
>- The original scripts in [Table 3](#en-us_topic_0000001133095885_table4705239194613) must be executed in the GPU environment and based on Python 3.
>- For scripts in [Table 3](#en-us_topic_0000001133095885_table4705239194613), the execution logic after conversion is the same as that before conversion.
>- msFmkTransplt provides suggestions and converts scripts by the adaptation rules, significantly accelerating script migration and reducing development workload. The scripts in [Table 2](#en-us_topic_0000001133095885_table4705239194613) can be directly executed after being converted. The conversion results of other scripts are for reference only. You need to perform adaptation based on the site requirements.
>- The original scripts in [Table 2](#en-us_topic_0000001133095885_table4705239194613) must be executed in the GPU environment and based on Python 3.
>- For scripts in [Table 2](#en-us_topic_0000001133095885_table4705239194613), the execution logic after conversion is the same as that before conversion.
>- This script conversion tool only supports the conversion of PyTorch training scripts.
##### Model Support
@@ -853,7 +750,7 @@ Set up the development environment by referring to the *[CANN Software Installat
##### Command-line Options
**Table 3** Command-line options
**Table 2** Command-line options<a name="en-us_topic_0000001133095885_table4705239194613"></a>
<table><thead align="left"><tr id="en-us_topic_0000001086713630_row175811919124014"><th class="cellrowborder" valign="top" width="22.35%" id="mcps1.2.4.1.1"><p id="en-us_topic_0000001086713630_p155823194404"><a name="en-us_topic_0000001086713630_p155823194404"></a><a name="en-us_topic_0000001086713630_p155823194404"></a>Option</p>
</th>
@@ -934,7 +831,7 @@ An example of a custom conversion rule is as follows:
}
```
**Table 4** Options
**Table 3** Options
<table><thead align="left"><tr id="en-us_topic_0000001086713630_row20236153212276"><th class="cellrowborder" valign="top" width="30%" id="mcps1.2.3.1.1"><p id="en-us_topic_0000001086713630_p13236113220275"><a name="en-us_topic_0000001086713630_p13236113220275"></a><a name="en-us_topic_0000001086713630_p13236113220275"></a>Option</p>
</th>
@@ -1080,9 +977,9 @@ For details, see [Single-Server Multi-Device Training Modification](#single-serv
#### PyTorch-related API Replacement
1. To enable the Ascend AI Processor to use the capabilities of the PyTorch framework, the native PyTorch framework needs to be adapted at the device layer. The APIs related to the CPU and CUDA need to be replaced for external presentation. During network porting, some device-related APIs need to be replaced with the APIs related to the Ascend AI Processor. [Table 5](#table1922064517344) lists the supported device-related APIs.
1. To enable the Ascend AI Processor to use the capabilities of the PyTorch framework, the native PyTorch framework needs to be adapted at the device layer. The APIs related to the CPU and CUDA need to be replaced for external presentation. During network porting, some device-related APIs need to be replaced with the APIs related to the Ascend AI Processor. [Table 4](#table1922064517344) lists the supported device-related APIs.
**Table 5** Device-related APIs
**Table 4** Device-related APIs<a name="table1922064517344"></a>
<table><thead align="left"><tr id="row1222164553413"><th class="cellrowborder" valign="top" width="43.43434343434344%" id="mcps1.2.4.1.1"><p id="p15221445163419"><a name="p15221445163419"></a><a name="p15221445163419"></a>Original PyTorch API</p>
</th>
@@ -1211,7 +1108,7 @@ For details, see [Single-Server Multi-Device Training Modification](#single-serv
2. When building or porting a network, you need to create tensors of specified data types. The following table lists the tensors created on the Ascend AI Processor.
**Table 6** Tensor-related APIs
**Table 5** Tensor-related APIs
<table><thead align="left"><tr id="row1926554133710"><th class="cellrowborder" valign="top" width="50.349999999999994%" id="mcps1.2.3.1.1"><p id="p797211564811"><a name="p797211564811"></a><a name="p797211564811"></a>GPU tensor</p>
</th>
@@ -1289,15 +1186,15 @@ However, the mixed precision training is limited by the precision range expresse
In addition to the preceding advantages, the mixed precision module Apex adapted to Ascend AI Processors can improve computing performance. Details are described as follows:
- During mixed precision calculation, Apex calculates the grad of the model. You can enable combine\_grad to accelerate these operations. Set the **combine\_grad** parameter of the amp.initialize\(\) interface to **True**.
- After the adaptation, Apex optimizes optimizers, such as adadelta, adam, sgd, and lamb to adapt them to Ascend AI Processors. As a result, the obtained NPU-based fusion optimizers are consistent with the native algorithms, but the calculation speed is faster. You only need to replace the original optimizer with **apex.optimizers.*** (* indicates the optimizer name, for example, **NpuFusedSGD**).
- The adapted apex optimizes the affinity of the Ascend AI processor for data parallel training, supports the use of fused grad for acceleration, while maintaining the consistency of computational logic. This function can be turned on by turning on the **combine_ddp** switch, that is, setting the amp.initialize interface parameter **combine_ddp** to **True** and turning off DistributedDataParallel.
- During mixed precision calculation, Apex calculates the grad of the model. You can enable **combine_grad** to accelerate the calculation. Specifically, set the combine_grad parameter of the **amp.initialize()** interface to **True**.
- After the adaptation, Apex optimizes optimizers, such as adadelta, adam, sgd, and lamb to adapt them to Ascend AI Processors. As a result, the obtained NPU-based fusion optimizers are consistent with the native algorithms, but the calculation speed is faster. You only need to replace the original optimizer with **apex.optimizers.*** (* indicates the optimizer name, for example, **NpuFusedSGD**).
- After the adaptation, Apex is optimized to adapt to Ascend AI Processors in the parallel data processing scenario. It supports acceleration with combined grad and maintains the compute logic consistency. To enable this function, set **combine_ddp** in the **amp.initialize()** interface to True and disable **DistributedDataParallel**.
#### Supported Features
[Table 7](#table10717173813332) describes the functions and optimization of the mixed precision module.
[Table 6](#table10717173813332) describes the functions and optimization of the mixed precision module.
**Table 7** Functions of the mixed precision module
**Table 6** Functions of the mixed precision module<a name="table10717173813332"></a>
<table><thead align="left"><tr id="row371716385333"><th class="cellrowborder" valign="top" width="32.269999999999996%" id="mcps1.2.3.1.1"><p id="p13717163815333"><a name="p13717163815333"></a><a name="p13717163815333"></a>Function</p>
</th>
@@ -1393,19 +1290,21 @@ The PyTorch 1.8.1 framework supports only the preceding four scenarios. For deta
1. In PyTorch 1.8.1, AMP is implemented by using decorators. During training and test, **with Autocast()** needs to be added to convert the arguments of the model into FP16. If **with Autocast()** is not added, the arguments are still FP32. In the case of an extreme batch size, the memory is insufficient.
2. PyTorch 1.8.1 AMP does not support tensor fusion.
## Model Training
## <h2 id="Model Trainingmd">Model Training</h2>
After the training scripts are ported, set environment variables by following the instructions in [Environment Variable Configuration](#en-us_topic_0000001144082004md) and run the **python3** _xxx_ command to train a model. For details, see [Script Execution](#script-executionmd).
>![](public_sys-resources/icon-note.gif) **NOTE:**
>When running the **python3** _xxx_ command, create a soft link between Python 3 and the installation path of Python that matches the current PyTorch version.
## Performance Analysis and Optimization
## <h2 id="Performance Optimization and Analysismd">Performance Optimization and Analysis</h2>
### Prerequisites
1. Modify the open-source code to ensure that the model can run properly, including data preprocessing, forward propagation, loss calculation, mixed precision, back propagation, and parameter update. For details, see [Samples](#samples).
2. During model porting, check whether the model can run properly and whether the existing operators can meet the requirements. If no operator meets the requirements, develop an adapted operator. For details, see the _PyTorch Operator Development Guide_.
2. During model porting, check whether the model can run properly and whether the existing operators can meet the requirements. If an operator does not meet the requirements, develop an adapted operator. For details, see the _PyTorch Operator Development Guide_.
3. Prioritize the single-device function, and then enable the multi-device function.
### Commissioning Process
@@ -1413,28 +1312,33 @@ After the training scripts are ported, set environment variables by following th
#### Overall Guideline
1. Check whether the throughput meets the expected requirements based on the training execution result.
2. If the throughput does not meet requirements, you need to find out the causes of the performance bottleneck. Possible causes are as follows:
- Operator bottleneck: The execution of an operator is too slow.
- Copy bottleneck: The bottleneck is caused by the copy operation during converting non-contiguous tensors to contiguous tensors.
- Framework bottleneck: Additional operations are required due to operator format conversion.
- Compilation bottleneck: Repeated compilation is caused by the changes of shape or attributes.
2. If the performance does not meet requirements, find out the causes of the performance bottlenecks. Possible causes are as follows:
- Operator bottleneck: Some operators in the model are executed slowly because of copy, format conversion, and many other operations.
- Compilation bottleneck: Repeated compilation is caused by constant changes of shapes or attributes.
- Performance bottleneck caused by dataset loading or preprocessing in model training.
3. Analyze the preceding causes of performance bottlenecks and optimize the performance.
#### Training Data Collection
3. Analyze the preceding causes of performance bottlenecks and optimize the performance.
##### Profile Data Collection
To eliminate the performance bottleneck caused by dataset loading or preprocessing, you can modify the server configuration. If the dataset contains only videos or images, you can install the high-performance Pillow and OpenCV libraries for optimization. For details, see [Host-side Performance Optimization](#host-side-performance-optimizationa-namehost-side-performance-optimizationa). To eliminate bottlenecks caused by operators and compilation, follow instructions in [Profile Data Collection](#profile-data-collectiona-nameprofile-data-collectiona). In addition, you can collect operator **OP_INFO** to view information about all called operators in the model. With the call sequence and relationship, you can determine whether the performance bottleneck is caused by the insertion of redundant TransData due to format conversion. (TransData is mainly used for data type and format conversion.)
During model training, if the throughput does not meet requirements, you can collect profile data generated during the training process to analyze which step and which operator cause the performance consumption. The profile data is collected at the PyTorch layer (PyTorch API data) and CANN layer (TBE operator data).
##### Profile Data Collection<a name="Profile Data Collection"></a>
During model training, if the throughput does not meet requirements, you can collect profile data generated during the training process to analyze which step and which operator cause the performance consumption. In model training on NPU-based PyTorch, the typical operator execution procedure is as follows: 1. PyTorch distributes an operator for multiple times. 2. The operator calls the ACL API. 3. CANN compiles the operator and GE/FE processes the operator. 4. The NPU computes and executes the operator. The entire procedure and call stack are deep. Before the ACL API call, the call stack and processes are in the PyTorch framework. After the call, all processes are in CANN. (The basic software package of CANN is called by calling the SO library). Therefore, three Profiling modes are provided to record profile data at different layers: PyTorch Profiling, CANN Profiling, and E2E Profiling. The PyTorch Profiling function is inherited from the native PyTorch. It records the time consumption of the call stack during multiple distributions of operators at the PyTorch framework layer. The processes of the operators in CANN can only be displayed as an entire block without any internal details. CANN Profiling records only performance information about operator execution at the CANN layer. It analyzes the operator execution performance on the NPU device and clearly shows the time consumption of each operator in different shapes and formats. E2E Profiling combines the profile data at the PyTorch and CANN layers to analyze performance bottlenecks in an end-to-end manner. It displays the profile data by module. The data at the PyTorch layer is basically the same as that in PyTorch Profiling, and the data at the CANN layer is divided into multiple modules, such as GE, ACL, Runtime, AI CPU, and Device, which can be used to analyze the overall model performance bottlenecks. The following figure shows the relationship between the three Profiling modes. Note that E2E Profiling is not really the combination of PyTorch Profiling and CANN Profiling. The **OP_INFO** is collected by logs. It is used to obtain information about all operators called in the model to check whether unnecessary TransData (mainly used for data type and format conversion) is inserted into the model.
![](https://gitee.com/yanhuiling/pytorch/raw/v1.8.1-3.0.rc2/docs/en/PyTorch%20Network%20Model%20Porting%20and%20Training%20Guide/figures/profile-data-collection.PNG)
The following describes how to collect **OP_INFO** and data in the three Profiling modes.
Select a collection mode based on the site requirements and perform the following steps to collect the profile data.
- Profile data collection at the PyTorch layer
1. Obtain the **chrome\_trace** file.
Data Collection in PyTorch Profiling
Use the profile API to reconstruct the loss calculation and optimization process of the original code.
1. Obtain the **chrome\_trace** file.
Use the profile API to reconstruct the loss calculation and optimization process of the original code.
```
# Use the profile API adapted to Ascend-PyTorch. You are advised to run only one step.
with torch.autograd.profiler.profile(use_npu=True) as prof:
out = model(input_tensor)
@@ -1447,24 +1351,24 @@ Select a collection mode based on the site requirements and perform the followin
# Export the chrome_trace file to a specified path.
output_path = '/home/HwHiAiUser/profile_data.json'
prof.export_chrome_trace(output_path)
```
2. After the execution is successful, print the profiling result.
2. After the execution is successful, print the profiling result.
The printed result includes the CPU and NPU time consumption. For details, see Table 8.
The printed result includes the CPU and NPU time consumption. For details, see [Table 7](#234).
<a name='Table 8 Profiling result field'>**Table 8** Profiling result fields</a>
Table 7 Profiling result fields<a name="234"></a>
| Name | Self CPU % | Self CPU | CPU total % | CPU total | CPU time avg | Self NPU % | Self NPU | NPU total | NPU time avg | # of Calls |
| ---- | ---------- | -------- | ----------- | --------- | ------------ | ---------- | -------- | --------- | ------------ | :--------: |
| Name | Self CPU % | Self CPU | CPU total % | CPU total | CPU time avg | Self NPU % | Self NPU | NPU total | NPU time avg | # of Calls |
| ---- | ---------- | -------- | ----------- | --------- | ------------ | ---------- | -------- | --------- | ------------ | :--------: |
3. View the **chrome_trace** file.
3. View the **chrome_trace** file.
To view the **chrome_trace** file, access **chrome://tracing** in the Chrome browser, drag the file in the blank space. You can press **W**, **A**, **S**, or **D** to zoom in, zoom out, or move the profiling result.
To view the **chrome_trace** file, access **chrome://tracing** in the Chrome browser, drag the file in the blank space. You can press **W**, **A**, **S**, or **D** to zoom in, zoom out, or move the profiling result.
4. Other profiling functions are as follows.
4. Other profiling functions are as follows.
- Obtain the shape information of the input tensor of an operator.
- Obtain the shape information of the input tensor of an operator.
```python
# Add the record_shapes parameter to obtain the shape information of the input tensor.
@@ -1473,9 +1377,9 @@ Select a collection mode based on the site requirements and perform the followin
print(prof)
```
The `Input Shape` information of each operator is added to the printed result.
The `Input Shape` information of each operator is added to the printed result.
- Obtain the memory information of the NPU in use.
- Obtain the memory information of the NPU in use.
```python
# Add the profile parameter to obtain the memory usage of the operators.
@@ -1484,32 +1388,30 @@ Select a collection mode based on the site requirements and perform the followin
print(prof)
```
The `CPU Mem`, `Self CPU Mem`, `NPU Mem`, and `Self NPU Mem` information of each operator is added to the printed result.
The `CPU Mem`, `Self CPU Mem`, `NPU Mem`, and `Self NPU Mem` information of each operator is added to the printed result.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>
>This function is supported only by PyTorch 1.8 or later.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>
>This function is supported only by PyTorch 1.8 or later.
- Obtain a simplified operator performance report.
- Obtain a simplified operator performance report.
This function prints only the operator information at the bottom layer of each operator stack, simplifying the analysis result.
```python
This function prints only the operator information at the bottom layer of each operator stack, simplifying the analysis result.
# Add the use_npu_simple parameter to obtain the simplified operator performance report.
with torch.autograd.profiler.profile(use_npu=True, use_npu_simple=True) as prof:
# Add the model calculation process.
# Export the chrome_trace file to a specified path.
output_path = '/home/HwHiAiUser/profile_data.json'
prof.export_chrome_trace(output_path)
```
Open the **chrome_trace** result file in the Chrome browser to view the simplified operator performance report.
Open the **chrome_trace** result file in the Chrome browser to view the simplified operator performance report.
Data Collection in CANN Profiling
1. Obtain the profile data file.
- Profile data collection at the CANN layer
1. Obtain the profile data file.
```
profiler_result_path = "/home/profiling_data" # folder for storing the profile data. Specify it based on the site requirements.
with torch_npu.npu.profile(profiler_result_path, config): Generally, only one step needs to be performed. You can retain the default config.
out = model(input_tensor)
@@ -1517,17 +1419,19 @@ Select a collection mode based on the site requirements and perform the followin
loss.backward()
optimizer.zero_grad()
optimizer.step()
```
>![](public_sys-resources/icon-note.gif) **NOTE:**
>The **config** parameter is used to configure the types of CANN profile data that need to be obtained. For details about the setting method, see the **config** description in [Advanced Settings](#advanced-settings).
When obtaining the profile data file, deliver **model**, **input\_tensor**, and **target** to the NPU.
The **config** parameter is used to configure the types of the CANN profile data to be obtained. For details, see the description of the parameter in the [E2E Profiling Advanced Settings](#Advanced-Settings).
2. Parse the profile data file.
>![](public_sys-resources/icon-note.gif) **NOTE:**
When obtaining the profile data file, deliver **model**, **input\_tensor**, and **target** to the NPU.
For details, see "Profiling Instructions > Advanced Features (All Profiling Modes and Items) > Data Parsing and Export" in the *CANN Auxiliary Development Tool User Guide*.
3. Refer to the advanced usage.
2. Parse the profile data file.
For details, see "Profiling Instructions > Advanced Features (All Profiling Modes and Items) > Data Parsing and Export" in the *CANN Auxiliary Development Tool User Guide*.
3. Refer to the advanced usage.
The PyTorch framework runs in single-operator mode and cannot distinguish step information. If multiple steps are executed in the WITH statement, the data obtained through Profiling is multiple steps connected. The data of one step cannot be distinguished from the prof diagram. Therefore, to distinguish step information, advanced APIs are provided. See the following example:
```
for i in range(steps):
@@ -1542,8 +1446,100 @@ Select a collection mode based on the site requirements and perform the followin
torch_npu.npu.prof_stop()
torch_npu.npu.prof_finalize()
```
Data Collection in E2E Profiling
##### Obtaining Operator Information (OP_INFO)
1. Obtain the profile data file.
Add the **with** statement to enable the E2E Profiling function.
```
with torch_npu.npu.profile(profiler_result_path="./result",use_e2e_profiler=True):
model_train()
```
- **profiler_result_path** indicates the path for storing the Profiling results. If no path is specified, the current path is used by default.
- **use_e2e_profiler** indicates whether to enable the E2E Profiling function. The default value is False, indicating that only the CANN Profiling function is enabled.
(NPU operators can be executed only after compilation. To ensure data accuracy, you are advised to perform 10 steps first, and then start the E2E Profiling operation after the tenth step. Generally, only one or two steps are required for Profiling.)
2. Parse the profile data.
The data obtained by the E2E Profiling tool is raw data, which can be viewed only after being parsed.
a. Use the path in the tutorial as an example. The tool creates a folder in the **profiler_result_path** directory to save the raw data.
![](figures/1.png)
b. Switch to the **./result/PROF_XXX** directory in the preceding figure and run the script.
```
/usr/local/Ascend/ascend-toolkit/latest/toolkit/tools/profiler/bin/msprof --export=on --output=./
### Change the path according to the actual installation path and set the environment variables.
```
- **output** indicates the path of the raw data.
c. After the running is complete, find the **timeline** directory generated in the raw data path. See the following figure.
![](figures/2.png)
d. In **chrome://tracing/**, open the parsed profile data file in the **timeline** path.
Open a browser and enter **chrome://tracing/** in the address box.
Click **Load** to upload the file.
<img src="figures/chrometracing.png" style="zoom:80%;" />
An example is provided as follows:
<img src="figures/3.png" style="zoom:80%;" />
The window shown in the preceding figure is divided into four layers in a top-down order. The first layer (MsprofTx) contains the PyTorch framework data, the second layer (AscendCL) contains the ACL data, the third layer (Task Scheduler) contains the device data, and the fourth layer (AI CPU) contains the AI CPU data.
3. The E2E Profiling tool obtains data at all of the preceding layers by default. The process of obtaining data also affects the performance. If a large amount of profile data is obtained, it may not be used as a reference. Therefore, the E2E Profiling tool provides configurable options for fine-grained control of obtaining only some data at the layers.<a name="Advanced-Settings"></a>
```
with torch_npu.npu.profile(profiler_result_path="./results", use_e2e_profiler=True, \
config=torch_npu.npu.profileConfig(ACL_PROF_ACL_API=True, \
ACL_PROF_TASK_TIME=True, ACL_PROF_AICORE_METRICS=True, \
ACL_PROF_AICPU=True, ACL_PROF_L2CACHE=False, \
ACL_PROF_HCCL_TRACE=True, ACL_PROF_TRAINING_TRACE=False, \
aiCoreMetricsType=0)):
# ACL_PROF_ACL_API: collects profile data of AscendCL APIs. The default value is True.
# ACL_PROF_TASK_TIME: collects the execution time of AI Core operators. The default value is True.
# ACL_PROF_AICORE_METRICS: collects AI Core performance metrics. Only the metrics configured in aicore_metrics are valid. The default value is True.
# ACL_PROF_AICPU: 0x0008, collects traces of AI CPU tasks, including the start and end of each task. The default value is True.
# ACL_PROF_L2CACHE: collects L2 Cache data. The data causes Profiling result expansion. The default value is False.
# ACL_PROF_HCCL_TRACE: collects HCCL data. The default value is True.
# ACL_PROF_TRAINING_TRACE: collects iteration trace data, which records the forward and backward propagation steps of a model. The default value is False.
The values of aiCoreMetricsType are defined as follows. The default value is 0.
# ACL_AICORE_ARITHMETIC_UTILIZATION = 0: percentages of arithmetic throughput, including metrics mac_fp16_ratio, mac_int8_ratio, vec_fp32_ratio, vec_fp16_ratio, vec_int32_ratio, and vec_misc_ratio
# ACL_AICORE_PIPE_UTILIZATION = 1: percentages of time taken by the compute units and MTEs, including metrics vec_ratio, mac_ratio, scalar_ratio, mte1_ratio, mte2_ratio, mte3_ratio, and icache_miss_rate
# ACL_AICORE_MEMORY_BANDWIDTH = 2: percentages of external memory read/write instructions, including metrics ub_read_bw, ub_write_bw, l1_read_bw, l1_write_bw, l2_read_bw, l2_write_bw, main_mem_read_bw, and main_mem_write_bw
# ACL_AICORE_L0B_AND_WIDTH: percentages of internal memory read/write instructions, including scalar_ld_ratio, scalar_st_ratio, l0a_read_bw, l0a_write_bw, l0b_read_bw, l0b_write_bw, l0c_read_bw, and l0c_write_bw.
# ACL_AICORE_RESOURCE_CONFLICT_RATIO: percentages of pipeline queue instructions, including vec_bankgroup_cflt_ratio, vec_bank_cflt_ratio, vec_resc_cflt_ratio, mte1_iq_full_ratio, mte2_iq_full_ratio, mte3_iq_full_ratio, cube_iq_full_ratio, vec_iq_full_ratio, and iq_full_ratio.
# ACL_AICORE_NONE = 0xFF: Profiling disabled
```
##### Obtaining Operator Information (**OP_INFO**)
The network model is executed as an operator (OP). The OPInfo log can be used to obtain the operator and its attributes during the actual execution. Obtain the information by running the **get_ascend_op_info.py** script.
@@ -1610,7 +1606,7 @@ The network model is executed as an operator (OP). The OPInfo log can be used to
6. Analyze the extra tasks in TaskInfo, especially transdata.
#### Host-side Performance Optimization
#### Host-side Performance Optimization<a name="Host-side Performance Optimization"></a>
##### Overview
@@ -1628,26 +1624,26 @@ To improve network performance, you need to set the power policy to high perform
1. Log in to the iBMC WebUI, start the virtual console, and select **HTML5 Integrated Remote Console**, as shown in [Figure 3](#fig15869135420288).
**Figure 3** Remote console
**Figure 3** Remote console<a name="fig15869135420288"></a>
![](figures/remote-console.png "remote-console")
2. On the virtual toolbar, click the startup item tool ![](figures/en-us_image_0000001144241932.png). The startup item drop-down list is displayed, as shown in [Figure 4](#fig744814574243).
**Figure 4** Startup item tool
**Figure 4** Startup item tool<a name="fig744814574243"></a>
![](figures/startup-item-tool.png "startup-item-tool")
3. In the drop-down list, choose, select **BIOS Setup**, and click ![](figures/en-us_image_0000001190201999.png) on the toolbar to restart the server.
4. After the system restarts, the BIOS configuration screen is displayed. Choose **Advanced** \> **Socket Configuration**. See [Figure 5](#fig4546303814).
**Figure 5** Socket Configuration
**Figure 5** Socket Configuration<a name="fig4546303814"></a>
![](figures/socket-configuration.png "socket-configuration")
5. On the **Advanced Power Mgmt. Configuration** page displayed, set **Power Policy** to **Performance**, See [Figure 6](#fig15501111014442).
**Figure 6** Setting the power policy
**Figure 6** Setting the power policy<a name="fig15501111014442"></a>
![](figures/setting-the-power-policy.png "setting-the-power-policy")
@@ -1657,15 +1653,15 @@ To improve network performance, you need to set the power policy to high perform
Perform the following steps as the **root** user:
1. Run the following command to check the current CPU mode:
1. Run the following command to check the current CPU mode:<a name="li158435131344"></a>
```
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
```
After the preceding command is run, the current CPU mode is displayed. For details, see [Table 1](#table354392019384). If the current CPU mode is not performance, perform the following operations to set the CPU mode to performance: Otherwise, skip this step.
After the preceding command is run, the current CPU mode is displayed. For details, see [Table 8](#table354392019384). If the current CPU mode is not performance, perform the following operations to set the CPU mode to performance: Otherwise, skip this step.
**Table 1** CPU mode
**Table 8** CPU mode<a name="table354392019384"></a>
<table><thead align="left"><tr id="row16543172093819"><th class="cellrowborder" valign="top" width="30.819999999999997%" id="mcps1.2.3.1.1"><p id="p2526552113912"><a name="p2526552113912"></a><a name="p2526552113912"></a>Governor</p>
</th>
@@ -1738,26 +1734,26 @@ Some models that have demanding requirements on the CPUs on the host, for exampl
1. Log in to the iBMC WebUI, start the virtual console, and select **HTML5 Integrated Remote Console**, as shown in [Figure 7](#fig15869135420288).
**Figure 7** Remote console
**Figure 7** Remote console<a name="fig15869135420288"></a>
![](figures/remote-console-0.png "remote-console-0")
2. On the virtual toolbar, click the startup item tool ![](figures/en-us_image_0000001190202013.png). The startup item drop-down list is displayed, as shown in [Figure 8](#fig744814574243).
**Figure 8** Startup item tool
**Figure 8** Startup item tool<a name="fig744814574243"></a>
![](figures/startup-item-tool-1.png "startup-item-tool-1")
3. In the drop-down list, select **BIOS Setup**, and click ![](figures/en-us_image_0000001190081877.png) on the toolbar to restart the server.
4. After the system restarts, the BIOS configuration screen is displayed. Choose **Advanced** \> **Performance Config**. See [Figure 9](#fig4546303814).
**Figure 9** Performance Config
**Figure 9** Performance Config<a name="fig4546303814"></a>
![](figures/performance-config.png "performance-config")
5. On the **Performance Config** page, set **Power Policy** to **Performance**. See [Figure 10](#fig15501111014442).
**Figure 10** Setting the power policy
**Figure 10** Setting the power policy <a name="fig15501111014442"></a>
![](figures/setting-the-power-policy-2.png "setting-the-power-policy-2")
@@ -1824,7 +1820,7 @@ If the model depends on OpenCV, you are advised to install OpenCV 3.4.10 to ensu
##### Operator Bottleneck Optimization
1. Obtain the profile data during training. For details, see [Profile Data Collection](#profile-data-collection).
1. Obtain the profile data during training. For details, see [Profile Data Collection](#profile-data-collectiona-nameprofile-data-collectiona).
2. Analyze the profile data to obtain the time-consuming operator.
3. See [Single-Operator Sample Building](#single-operator-sample-building) to build the single-operator sample of the time-consuming operator, and compare the execution time of a single-operator sample on the CPU and GPU. If the performance is insufficient, use either of the following methods to solve the problem:
- Workaround: Use other efficient operators with the same semantics.
@@ -1833,8 +1829,8 @@ If the model depends on OpenCV, you are advised to install OpenCV 3.4.10 to ensu
##### Copy Bottleneck Optimization
1. Obtain the profile data during training. For details, see [Profile Data Collection](#profile-data-collection).
2. Analyze the Profile data to obtain the execution time of **format\_contiguous**, **AsStrided**, or **PTCopy** in the entire network.
1. Obtain the profile data during training. For details, see [Profile Data Collection](#profile-data-collectiona-nameprofile-data-collectiona).
2. Analyze the Profile data to obtain the execution time of **format_contiguous**, **AsStrided**, or **PTCopy** in the entire network.
3. If the execution takes a long time, use either of the following methods to solve the problem:
- Method 1 \(workaround\): Replace view operators with compute operators. In PyTorch, view operators cause conversion from non-contiguous tensors to contiguous tensors. The optimization idea is to replace view operators with compute operators. Common view operators include view, permute, and transpose operators. For more view operators, go to [https://pytorch.org/docs/stable/tensor\_view.html](https://pytorch.org/docs/stable/tensor_view.html).
- Method 2 \(solution\): Accelerate the operation of converting non-contiguous tensors to contiguous tensors.
@@ -1842,7 +1838,7 @@ If the model depends on OpenCV, you are advised to install OpenCV 3.4.10 to ensu
##### Framework Bottleneck Optimization
1. Obtain the operator information (OP_INFO) during the training. For details, see [Obtaining Operator Information (OP_INFO)](#obtaining-operator-information-op_info).
1. Obtain the operator information (OP_INFO) during the training. For details, see [Obtaining Operator Information (OP_INFO)](#obtaining-operator-information-opinfo).
2. Analyze the specifications and calling relationship of operators in OP\_INFO to check whether redundant operators are inserted. Pay special attention to check whether transdata is proper.
3. Solution: Specify the initialization format of some operators to eliminate cast operators.
4. In **pytorch/torch_npu/utils/module.py**, specify the operator initialization format in **cast\_weight**, as shown in the following figure.
@@ -1863,89 +1859,6 @@ The format setting principle is as follows:
- Solution: Reduce compilation or do not compile the operator.
- For details about how to optimize the operator compilation configuration, see [Compile Option Settings](#compile-option-settings).
### E2E Performance Tool (E2E prof) Instructions
#### Introduction
The E2E prof tool integrates the framework-layer data obtained by the Profiling tool of PyTorch and the operator profile data obtained by the CANN prof tool to implement end-to-end model and operator performance analysis.
#### Usage Tutorial
Add the following with statement to enable the E2E prof function.
```
with torch_npu.npu.profile(profiler_result_path="./result",use_e2e_profiler=True):
model_train()
```
- **profiler_result_path** indicates the path for storing the prof results. If no path is specified, the current path is used by default.
- **use_e2e_profiler** indicates whether to enable the E2E prof function. The default value is **False**, indicating that only the CANN prof function is enabled.
(The NUP operator can be executed only after compilation. To ensure data accuracy, you are advised to run it for 10 steps first, and then perform the E2E prof operation. Generally, only one or two steps are required for profiling.)
#### Result Parsing
The results obtained by using the E2E prof tool are raw data, which can be viewed only after being parsed.
1. Use the path in the tutorial as an example. The tool creates a folder in the *profiler_result_path* directory to save the raw data.
![](https://gitee.com/ascend/pytorch/raw/master/docs/zh/PyTorch%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%9E%8B%E7%A7%BB%E6%A4%8D&%E8%AE%AD%E7%BB%83%E6%8C%87%E5%8D%97/figures/1.png)
2. Switch to the **./result** directory in the preceding figure and run the following script:
```
/usr/local/Ascend/ascend-toolkit/latest/toolkit/tools/profiler/bin/msprof --export=on --output=./
```
- **output**: indicates the path of the raw data.
3. After the running is complete, find the **timeline** directory in the raw data path. See the following figure.
![](https://gitee.com/ascend/pytorch/raw/master/docs/zh/PyTorch%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%9E%8B%E7%A7%BB%E6%A4%8D&%E8%AE%AD%E7%BB%83%E6%8C%87%E5%8D%97/figures/2.png)
4. The **timeline** directory stores the parsed profile data, which can be opened in **chrome://tracing/**.
1. Open a browser and enter **chrome://tracing/** in the address box.
2. Click **Load** to upload the file.
![](https://gitee.com/ascend/pytorch/raw/master/docs/zh/PyTorch%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%9E%8B%E7%A7%BB%E6%A4%8D&%E8%AE%AD%E7%BB%83%E6%8C%87%E5%8D%97/figures/chrometracing.png)
An example is provided as follows:
![](https://gitee.com/ascend/pytorch/raw/master/docs/zh/PyTorch%E7%BD%91%E7%BB%9C%E6%A8%A1%E5%9E%8B%E7%A7%BB%E6%A4%8D&%E8%AE%AD%E7%BB%83%E6%8C%87%E5%8D%97/figures/3.png)
This example contains four layers from top to bottom. The first layer (MsprofTx) contains the PyTorch framework data, the second layer (AscendCL) contains the AscendCL data, the third layer (Task Scheduler) contains the device data, and the fourth layer (AI CPU) contains the AI CPU data.
#### Advanced Settings
By default, the E2E prof tool can obtain all of the preceding data. However, the process of obtaining data affects the performance. If a large amount of data is obtained, the profile data cannot be used as a reference. Therefore, the E2E prof tool provides configurable options for fine-grained control over obtaining data of specified layers.
```
with torch_npu.npu.profile(profiler_result_path="./results", use_e2e_profiler=True, \
config=torch_npu.npu.profileConfig(ACL_PROF_ACL_API=True, \
ACL_PROF_TASK_TIME=True, ACL_PROF_AICORE_METRICS=True, \
ACL_PROF_AICPU=True, ACL_PROF_L2CACHE=False, \
ACL_PROF_HCCL_TRACE=True, ACL_PROF_TRAINING_TRACE=False, \
aiCoreMetricsType=0)):
```
- **ACL_PROF_ACL_API**: collects profile data of AscendCL APIs. The default value is **True**.
- **ACL_PROF_TASK_TIME**: collects the execution time of AI Core operators. The default value is **True**.
- **ACL_PROF_AICORE_METRICS**: collects the AI Core performance metrics. Only those configured in **aicore_metrics** are valid. The default value is **True**.
- **ACL_PROF_AICPU**: 0x0008, collects traces of AI CPU tasks, including the start and end of each task. The default value is **True**.
- **ACL_PROF_L2CACHE**: collects L2 cache data. The default value is **True**.
- **ACL_PROF_HCCL_TRACE**: collects HCCL data. The default value is **True**.
- **ACL_PROF_TRAINING_TRACE**: collects iteration traces, which record the forward and backward propagation steps of a model. The default value is **False**.
The values of **aiCoreMetricsType** are defined as follows. The default value is **0**.
- **ACL_AICORE_ARITHMETIC_UTILIZATION = 0**: percentages of arithmetic throughput, including metrics **mac_fp16_ratio**, **mac_int8_ratio**, **vec_fp32_ratio**, **vec_fp16_ratio**, **vec_int32_ratio**, and **vec_misc_ratio**
- **ACL_AICORE_PIPE_UTILIZATION = 1**: percentages of time taken by the compute units and MTEs, including metrics **vec_ratio**, **mac_ratio**, **scalar_ratio**, **mte1_ratio**, **mte2_ratio**, **mte3_ratio**, and **icache_miss_rate**
- **ACL_AICORE_MEMORY_BANDWIDTH = 2**: percentages of external memory read/write instructions, including metrics **ub_read_bw**, **ub_write_bw**, **l1_read_bw**, **l1_write_bw**, **l2_read_bw**, **l2_write_bw**, **main_mem_read_bw**, and **main_mem_write_bw**
- **ACL_AICORE_L0B_AND_WIDTH**: percentages of internal memory read/write instructions, including **scalar_ld_ratio**, **scalar_st_ratio**, **l0a_read_bw**, **l0a_write_bw**, **l0b_read_bw**, **l0b_write_bw**, **l0c_read_bw**, and **l0c_write_bw**.
- **ACL_AICORE_RESOURCE_CONFLICT_RATIO**: percentages of pipeline stall instructions, including **vec_bankgroup_cflt_ratio**, **vec_bank_cflt_ratio**, **vec_resc_cflt_ratio**, **mte1_iq_full_ratio**, **mte2_iq_full_ratio**, **mte3_iq_full_ratio**, **cube_iq_full_ratio**, **vec_iq_full_ratio**, and **iq_full_ratio**.
- **ACL_AICORE_NONE = 0xFF**: Profiling disabled
### Affinity Library
@@ -2069,7 +1982,7 @@ For an NPU device, the input parameters (such as the shape and format) of each o
After the tuning is complete, restore the code, run the model, and check whether the model/operator performance is improved.
## Precision Commissioning
## <h2 id="Precision Commissioningmd">Precision Commissioning</h2>
### Prerequisites
Currently, PyTorch 1.8.1 does not support this function.
@@ -2392,7 +2305,7 @@ You can also commission the network model precision by analyzing the entire netw
print("[grad]: "+name, module.grad)
```
## Model Saving and Conversion
## <h2 id="Model Saving and Conversionmd">Model Saving and Conversion</h2>
### Introduction
@@ -2568,7 +2481,7 @@ if __name__ == "__main__":
## Samples
### ShuffleNet Model Optimization
### <h3 id="ShuffleNet-Model-Optimizationmd">ShuffleNet Model Optimization</h3>
#### Obtaining Samples
@@ -2609,7 +2522,7 @@ For details about how to commission the network, see [Commissioning Process](#co
The forward check record table is as follows:
**Table 1** Forward check
**Table 9** Forward check
<table><thead align="left"><tr id="row5326170182016"><th class="cellrowborder" valign="top" width="6.419999999999999%" id="mcps1.2.5.1.1"><p id="p113266011202"><a name="p113266011202"></a><a name="p113266011202"></a>No.</p>
</th>
@@ -2681,7 +2594,7 @@ The details are as follows:
The record table of the entire network check is as follows:
**Table 2** Entire network check
**Table 10** Entire network check
<table><thead align="left"><tr id="row487985710248"><th class="cellrowborder" valign="top" width="6.419999999999999%" id="mcps1.2.5.1.1"><p id="p10879125714244"><a name="p10879125714244"></a><a name="p10879125714244"></a>No.</p>
</th>
@@ -3097,7 +3010,7 @@ for group in [2, 4, 8]:
return out
```
## References
## <h2 id="Referencesmd">References</h2>
### Single-Operator Sample Building
@@ -3520,7 +3433,7 @@ Perform the following steps as the **root** user.
```
## FAQs
## <h2 id="FAQsmd">FAQs</h2>
- **[FAQs About Software Installation](#faqs-about-software-installationmd)**
@@ -3534,7 +3447,7 @@ Perform the following steps as the **root** user.
- **[FAQs About Distributed Model Training](#faqs-about-distributed-model-trainingmd)**
### FAQs About Software Installation
### <h3 id="faqs-about-software-installationmd">FAQs About Software Installation</h3>
- **[pip3.7 install Pillow==5.3.0 Installation Failed](#pip3-7-install-pillow-5-3-0-installation-failedmd)**
@@ -3563,7 +3476,7 @@ Run the following commands to install the dependencies:
**apt-get install libjpeg python-devel zlib-devel libjpeg-turbo-devel**
### FAQs About Model and Operator Running
### <h3 id="faqs-about-model-and-operator-runningmd">FAQs About Model and Operator Running</h3>
- **[What Do I Do If the Error Message "RuntimeError: ExchangeDevice:" Is Displayed During Model or Operator Running?](#what-do-i-do-if-the-error-message-runtimeerror-exchangedevice-is-displayed-during-model-or-operatormd)**
@@ -3922,7 +3835,7 @@ A public API is called.
The error information does not affect the training function and performance and can be ignored.
### FAQs About Model Commissioning
### <h3 id="faqs-about-model-commissioningmd">FAQs About Model Commissioning</h3>
- **[What Do I Do If the Error Message "RuntimeError: malloc:/..../pytorch/c10/npu/NPUCachingAllocator.cpp:293 NPU error, error code is 500000." Is Displayed During Model Commissioning?](#what-do-i-do-if-the-error-message-runtimeerror-malloc-pytorch-c10-npu-npucachingallocator-cpp-293-npmd)**
@@ -4004,7 +3917,7 @@ In the preceding figure, the error path is **.../code/pytorch/torch/\_\_init\_\
Switch to another directory to run the script.
### FAQs About Other Operations
### <h3 id="faqs-about-other-operationsmd">FAQs About Other Operations</h3>
- **[What Do I Do If an Error Is Reported During CUDA Stream Synchronization?](#what-do-i-do-if-an-error-is-reported-during-cuda-stream-synchronizationmd)**
@@ -4193,12 +4106,14 @@ The script is as follows:
model.load_state_dict(state_dict)
```
### FAQs About Distributed Model Training
### <h3 id="faqs-about-distributed-model-trainingmd">FAQs About Distributed Model Training</h3>
- **[What Do I Do If the Error Message "host not found." Is Displayed During Distributed Model Training?](#what-do-i-do-if-the-error-message-host-not-found-is-displayed-during-distributed-model-trainingmd)**
- **[What Do I Do If the Error Message "RuntimeError: connect\(\) timed out." Is Displayed During Distributed Model Training?](#what-do-i-do-if-the-error-message-runtimeerror-connect-timed-out-is-displayed-during-distributed-mmd)**
- **[What Do I Do If The Error Message "RuntimeError: HCCL\(\) error" Is Displayed During Distributed Model Training?](#what-do-i-do-if-the-error-message-runtimeerror-connect()-timed-out-is-displayed-during-distributed-mmd)**
<h4 id="what-do-i-do-if-the-error-message-host-not-found-is-displayed-during-distributed-model-trainingmd">What Do I Do If the Error Message "host not found." Is Displayed During Distributed Model Training?</h4>
@@ -4228,3 +4143,20 @@ During distributed model training, the system firewall may block the communicati
Query the HCCL port that is blocked by the system firewall and enable the port.
<h4 id="What-Do-I-Do-If-The-Error-Message-RuntimeError-CCL\(\)-error-Is-Displayed-During Distributed-Model-Training?">What Do I Do If The Error Message "RuntimeError: HCCL\(\) error" Is Displayed During Distributed Model Training?"</h4>
##### Symptom
![](figures/HCCL.jpg)
##### Possible Causes
During distributed model training, different device processes may be executed asynchronously due to specific factors before HCCL is initialized. You can set the link setup waiting time based on the actual device performance.
##### Solution
export HCCL_CONNECT_TIMEOUT=time
The default value of **time** is **120**, in seconds.The value range is [120, 7200].
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

+121 -6
View File
@@ -1,34 +1,149 @@
# FrameworkPTAdapter 3.0.RC1 Release Notes
# FrameworkPTAdapter 3.0.RC2 Release Notes
- [FrameworkPTAdapter 3.0.RC1 Release Notes](#frameworkptadapter-30rc1-release-notes)
- [FrameworkPTAdapter 3.0.RC1](#frameworkptadapter-30rc1)
- [FrameworkPTAdapter 3.0.RC2 Release Notes](#frameworkptadapter-30rc2-release-notes)
- [FrameworkPTAdapter 3.0.RC2](#frameworkptadapter-30rc2)
- [Before You Start](#before-you-start)
- [New Features](#new-features)
- [Modified Features](#modified-features)
- [Resolved Issues](#resolved-issues)
- [Known Issues](#known-issues)
- [Compatibility](#compatibility)
- [FrameworkPTAdapter 2.0.4](#frameworkptadapter-204)
- [FrameworkPTAdapter 3.0.RC1](#frameworkptadapter-30rc1)
- [Before You Start](#before-you-start-1)
- [New Features](#new-features-1)
- [Modified Features](#modified-features-1)
- [Resolved Issues](#resolved-issues-1)
- [Known Issues](#known-issues-1)
- [Compatibility](#compatibility-1)
- [FrameworkPTAdapter 2.0.3](#frameworkptadapter-203)
- [FrameworkPTAdapter 2.0.4](#frameworkptadapter-204)
- [Before You Start](#before-you-start-2)
- [New Features](#new-features-2)
- [Modified Features](#modified-features-2)
- [Resolved Issues](#resolved-issues-2)
- [Known Issues](#known-issues-2)
- [Compatibility](#compatibility-2)
- [FrameworkPTAdapter 2.0.2](#frameworkptadapter-202)
- [FrameworkPTAdapter 2.0.3](#frameworkptadapter-203)
- [Before You Start](#before-you-start-3)
- [New Features](#new-features-3)
- [Modified Features](#modified-features-3)
- [Resolved Issues](#resolved-issues-3)
- [Known Issues](#known-issues-3)
- [Compatibility](#compatibility-3)
- [FrameworkPTAdapter 2.0.2](#frameworkptadapter-202)
- [Before You Start](#before-you-start-4)
- [New Features](#new-features-4)
- [Modified Features](#modified-features-4)
- [Resolved Issues](#resolved-issues-4)
- [Known Issues](#known-issues-4)
- [Compatibility](#compatibility-4)
## FrameworkPTAdapter 3.0.RC2
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 and 1.8.1 developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
PyTorch 1.8.1 uses plug-in adaptation and is completely decoupled from the native PyTorch framework. The current functions and performance of PyTorch 1.8.1 are basically the same as those of PyTorch 1.5.0, providing good development experience for backend operator adaptation.
AOE-based tuning is supported.
### New Features
**Table 1** Features supported by PyTorch
<a name="t76c34275cbb74753970f7c5a9eb594fa"></a>
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.5.0 features adapted to NPUs</p>
</td>
</tr>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> Fixed a few bugs.</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="3" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.8.1 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Decoupled as plugins</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Decoupled the torch_npu plugin from the native PyTorch framework completely.</p>
</td>
<tr>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Performance optimization</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Optimized the single-operator delivery and collective communication functions.</p>
</td>
</tr>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>API satisfaction</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Added more APIs. (For details, see the API list.)</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<a name="table1969972073016"></a>
<table><thead align="left"><tr id="row3699162017307"><th class="cellrowborder" valign="top" width="18.22%" id="mcps1.1.3.1.1"><p id="p16992020153010"><a name="p16992020153010"></a><a name="p16992020153010"></a>Known Issue</p>
</th>
<th class="cellrowborder" valign="top" width="81.78%" id="mcps1.1.3.1.2"><p id="p269919203308"><a name="p269919203308"></a><a name="p269919203308"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row9699142003011"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p1769932017300"><a name="p1769932017300"></a><a name="p1769932017300"></a>Data type support</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p13699152010301"><a name="p13699152010301"></a><a name="p13699152010301"></a>NPUs do not support the input or output of the inf/nan data of the float16 type</p>
</td>
</tr>
<tr id="row146991520153016"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p156997200308"><a name="p156997200308"></a><a name="p156997200308"></a>Data format</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p10699182020308"><a name="p10699182020308"></a><a name="p10699182020308"></a>Dimensions cannot be reduced when the format larger than 4D is used.</p>
</td>
</tr>
<tr id="row11121205610549"><td class="cellrowborder" rowspan="3" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p1647216219558"><a name="p1647216219558"></a><a name="p1647216219558"></a>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></a></p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p3116115695415"><a name="p3116115695415"></a><a name="p3116115695415"></a>The graphs executed on different devices in a training job must be the same.</p>
</td>
</tr>
<tr id="row51211656105411"><td class="cellrowborder" valign="top" headers="mcps1.1.3.1.1 "><p id="p1311616560541"><a name="p1311616560541"></a><a name="p1311616560541"></a>Allocation at only 1, 2, 4, or 8 processors is supported.</p>
</td>
</tr>
<tr id="row8647195765419"><td class="cellrowborder" valign="top" headers="mcps1.1.3.1.1 "><p id="p2064225716544"><a name="p2064225716544"></a><a name="p2064225716544"></a>Only the int8, int32, float16, and float32 data types are supported.</p>
</td>
</tr>
<tr id="row4646195719548"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p4642195718541"><a name="p4642195718541"></a><a name="p4642195718541"></a>Apex function</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p864205725412"><a name="p864205725412"></a><a name="p864205725412"></a>In the current version, Apex is implemented mainly using Python, and the customized optimization of CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04/2.04, BC-Linux 7.6, Debian 9.9, Debian 10, openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6, Ubuntu 18.04/2.04, EulerOS 2.8/2.10, Kylin V10, BC-Linux 7.6, openEuler 20.03 LTS, UOS 20 1020e
## FrameworkPTAdapter 3.0.RC1
### Before You Start
File diff suppressed because it is too large Load Diff
+354 -427
View File
@@ -1,294 +1,133 @@
# PyTorch安装指南
- [简介](#简介md)
- [手动编译安装](#手动编译安装md)
- [前提条件](#前提条件md)
- [安装PyTorch框架](#安装PyTorch框架md)
- [配置环境变量](#配置环境变量md)
- [安装混合精度模块](#安装混合精度模块md)
- [参考信息](#参考信息md)
- [CMake安装方法](#CMake安装方法md)
- [安装7.3.0版本gcc](#安装7-3-0版本gccmd)
- [安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配md)
<h2 id="简介md">简介</h2>
用户在准备相关环境进行基于PyTorch框架模型的开发、运行时,可以选择在服务器中手动编译安装PyTorch框架相关模块。
- [简介](#简介)
**图 1** 环境准备流程图<a name="zh-cn_topic_0000001119176876_fig1938918396117"></a>
- [系统依赖库](#系统依赖库)
- [Ascend配套软件](#Ascend配套软件)
![](figures/210926103326800.png)
- [安装方式](#安装方式)
<h2 id="手动编译安装md">手动编译安装</h2>
- [运行](#运行)
- [安装混合精度模块(可选)](#安装混合精度模块(可选))
- [FAQ](#FAQ)
- [版本说明](#版本说明)
- **[前提条件](#前提条件md)**
# 简介<a name="简介"></a>
- **[安装PyTorch框架](#安装PyTorch框架md)**
本项目开发了PyTorch Adapter插件,用于昇腾适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。用户在准备相关环境进行基于PyTorch框架模型的开发、运行时,可以选择在服务器中手动编译相关模块。
- **[配置环境变量](#配置环境变量md)**
- **[安装混合精度模块](#安装混合精度模块md)**
<h3 id="前提条件md">前提条件</h3>
#### 前提条件<a name="zh-cn_topic_0000001105856382_zh-cn_topic_0275872734_section108914373254"></a>
<h2 id="md">前提条件</h2>
- 需完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
- Python支持版本为3.7.5、3.8、3.9。
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 |
| :------------ | :----------- | :----------- |
| 3.0.2 | CANN 5.0.2 | 1.5.0.post2 |
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 |
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5, 1.8.1.rc1 |
# 系统依赖库<a name="系统依赖库"></a>
- 需安装3.12.0以上版本的CMake,安装方法请参考[CMake安装方法](#CMake安装方法md)。
## CentOS & EulerOS
- 需确保已安装7.3.0以上版本的gcc,7.3.0版本gcc具体安装及使用方式请参考[安装7.3.0版本gcc](#安装7-3-0版本gccmd)。
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
- 需安装python版本为3.7.5、3.8、3.9。
yum install -y gcc==7.3.0 cmake==3.12.0
- 需注意torch1.5版本不支持python3.9编译安装(与官方保持一致),仅torch1.8.1版本支持python版本3.9进行编译安装。
## Ubuntu
- 需确保环境中已安装patch、git工具,以Ubuntu和CentOS系统为例,命令如下:
- Ubuntu系统
apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
```
apt-get install patch
apt-get install git
```
- CentOS系统
```
yum install patch
yum install git
```
apt-get install -y gcc==7.3.0 cmake==3.12.0
<h3 id="安装PyTorch框架md">安装PyTorch框架</h3>
>![](public_sys-resources/icon-note.gif) **说明:**
>若安装gcc与cmake依赖命令报错,请参考FAQ使用源码安装。
#### 安装流程<a name="zh-cn_topic_0000001152776301_section1611810384557"></a>
# Ascend配套软件
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 | Gitee分支名称 |
| :------------ | :----------- | :----------- | ------------- |
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
1. 以root或非root用户登录服务器。
# 安装方式<a name="安装方式"></a>
2. 依次执行如下命令安装PyTorch依赖环境。
## 安装Pytorch依赖环境
如果使用非root用户安装Python及其依赖,用户需要在本步骤中的每句命令结尾加上**--user**,命令示例为:**pip3.7 install pyyaml --user**
如果使用非root用户安装,用户需要在本步骤的每句命令后加**--user**,示例如:pip3 install pyyaml --user。
```
pip3 install pyyaml
pip3 install wheel
```
```sh
pip3 install pyyaml
pip3 install wheel
```
3. 获取PyTorch源代码。
## 编译安装PyTorch和昇腾插件
1. 运行如下命令,获取适配昇腾AI处理器的PyTorch源代码,并切换到所需的分支。
首先安装官方torch包,然后编译安装插件。
```
git clone https://gitee.com/ascend/pytorch.git
# 默认是master分支,master分支时pytorch1.8.1版本,若需要其他分支请使用git checkout 命令切换
cd pytorch
git checkout -b v1.8.1-3.0.rc1 remotes/origin/v1.8.1-3.0.rc1
```
```sh
#x86_64
pip3 install torch==1.8.1+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
2. 在当前仓根目录“/pytorch”下获得原生PyTorch 1.8.1源代码并重命名为pytorch_v1.8.1。
#aarch64
#社区未提供arm架构cpu安装包,请参见FAQ第一条,使用源码编译安装pytorch
```
```
//1.8.1版本
cd pytorch #插件根目录
git clone -b v1.8.1 --depth=1 https://github.com/pytorch/pytorch.git pytorch_v1.8.1
```
编译生成pytorch插件的二进制安装包。
>![](public_sys-resources/icon-note.gif) **说明:**
>请关注PyTorch原生社区的安全板块与Issue板块是否有安全相关问题修复,并根据社区修复及时更新原生PyTorch代码。
```
# 下载对应分支代码,进入插件根目录
git clone -b v1.8.1-3.0.rc2 https://gitee.com/ascend/pytorch.git
cd pytorch
# 指定python版本编包方式:
bash ci/build.sh --python=3.7
# 或
bash ci/build.sh --python=3.8
# 或
bash ci/build.sh --python=3.9
```
3. 运行如下命令,进入原生pytorch代码目录“pytorch_v1.8.1“,并获取PyTorch被动依赖代码。
然后安装pytorch/dist下生成的插件torch_npu包,{arch}为架构名称。
```
cd pytorch_v1.8.1
git submodule sync
git submodule update --init --recursive
```
```
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
```
下载torchvision。
```
pip3 install torchvision==0.9.1
```
# 运行<a name="运行"></a>
>![](public_sys-resources/icon-note.gif) **说明:**
>受网络波动影响,源码获取时间可能较长,下载过程中请耐心等待。 下载完成之后若没有报错,即生成了PyTorch及其依赖的第三方代码。
## 运行环境变量
4. 编译生成适配昇腾AI处理器的PyTorch安装包。
1. 将patch打入Pytorch源码并编译。
在当前仓库根目录中执行设置环境变量脚本
```
cd ../patch
bash apply_patch.sh ../pytorch_v1.8.1
cd ../pytorch_v1.8.1
指定python版本编包方式:
bash build.sh --python=3.7
或
bash build.sh --python=3.8
或
bash build.sh --python=3.9
```
安装当前dist目录(pytorch/pytorch_v1.8.1/dist)下生成的torch包。
```
cd dist
pip3 install --upgrade torch-1.8.1+ascend.rc1-cp37-cp37m-linux_{arch}.whl #**\{arch\}**表示架构信息,为aarch64或x86\_64。
```
3. 编译生成pytorch插件的二进制安装包。
```
cd ../../ci #进入插件根目录
指定python版本编包方式:
bash build.sh --python=3.7
或
bash build.sh --python=3.8
或
bash build.sh --python=3.9
```
请指定环境中python版本进行编译。生成的二进制包在当前的dist目录下,即“pytorch/dist”文件夹目录下。
5. <a name="zh-cn_topic_0000001152776301_li49671667141"></a>安装PyTorch插件。
进入“pytorch/dist“文件夹目录,执行如下命令安装torch_npu包。
```
cd ../dist
pip3 install --upgrade torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
```
>![](public_sys-resources/icon-note.gif) **说明:**
>若对环境中的PyTorch插件进行升级时,需要先卸载环境中已安装的PyTorch插件软件包再执行[5. 安装PyTorch插件。](#zh-cn_topic_0000001152776301_li49671667141)可以通过执行如下命令查询环境上是否已安装PyTorch插件。
>**pip3 list | grep torch-npu**
```
source env.sh
```
<h3 id="配置环境变量md">配置环境变量</h3>
## 自定义环境变量
安装完软件包后,需要配置环境变量才能正常使用昇腾PyTorch。相关环境变量介绍参见[表1](#zh-cn_topic_0000001152616261_table42017516135)。
可选的环境变量可能会对运行的模型产生影响:
1. 配置运行环境变量,在适配昇腾AI处理器的PyTorch源代码根目录中运行如下命令。
```
export COMBINED_ENABLE=1 # 非连续转连续二级推导优化,可选,开启设置为1。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升。
export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
```
```
cd ../
source env.sh
```
**表 1** 环境变量说明<a name="zh-cn_topic_0000001152616261_table42017516135"></a>
2. 请依据实际场景,选择合适的HCCL初始化方式,并配置相应环境变量。
```
# 场景一:单机场景
export HCCL_WHITELIST_DISABLE=1 # 关闭HCCL通信白名单
# 场景二:多机场景。
export HCCL_WHITELIST_DISABLE=1 # 关闭HCCL通信白名单
export HCCL_IF_IP="1.1.1.1" # “1.1.1.1”为示例使用的host网卡IP,请根据实际修改。需要保证使用的网卡IP在集群内是互通的。
```
3. (可选)NPU场景下配置功能或性能环境变量。默认为不开启。
```
export DYNAMIC_COMPILE_ENABLE=1 # 动态shape特性功能,针对shape变化场景,可选,开启设置为1(PyTorch1.8.1不支持该环境变量)
export COMBINED_ENABLE=1 # 非连续两个算子组合类场景优化,可选,开启设置为1
export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
export DYNAMIC_OP="ADD#MUL" # 算子实现,ADD和MUL算子在不同场景下有不同的性能表现。可选
```
4. (可选)当系统为openEuler及其继承操作系统时,如UOS,需设置此命令,取消CPU绑核。
```
# unset GOMP_CPU_AFFINITY
```
**表 1** 环境变量说明
<a name="zh-cn_topic_0000001152616261_table42017516135"></a>
<table><thead align="left"><tr id="zh-cn_topic_0000001152616261_row16198951191317"><th class="cellrowborder" valign="top" width="55.48%" id="mcps1.2.3.1.1"><p id="zh-cn_topic_0000001152616261_p51981251161315"><a name="zh-cn_topic_0000001152616261_p51981251161315"></a><a name="zh-cn_topic_0000001152616261_p51981251161315"></a>配置项</p>
</th>
<th class="cellrowborder" valign="top" width="44.519999999999996%" id="mcps1.2.3.1.2"><p id="zh-cn_topic_0000001152616261_p9198135114133"><a name="zh-cn_topic_0000001152616261_p9198135114133"></a><a name="zh-cn_topic_0000001152616261_p9198135114133"></a>说明</p>
</th>
</tr>
</thead>
<tbody><tr id="zh-cn_topic_0000001152616261_row6882121917329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p688241953218"><a name="zh-cn_topic_0000001152616261_p688241953218"></a><a name="zh-cn_topic_0000001152616261_p688241953218"></a>LD_LIBRARY_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1888291915322"><a name="zh-cn_topic_0000001152616261_p1888291915322"></a><a name="zh-cn_topic_0000001152616261_p1888291915322"></a>动态库的查找路径,参考上述举例配置。</p>
<p id="p1292181892120"><a name="p1292181892120"></a><a name="p1292181892120"></a>若训练所在系统环境需要升级gcc(例如CentOS、Debian和BClinux系统),则<span class="parmname" id="parmname795020446318"><a name="parmname795020446318"></a><a name="parmname795020446318"></a>“LD_LIBRARY_PATH”</span>配置项处动态库查找路径需要添加<span class="filepath" id="zh-cn_topic_0256062644_filepath115819811512"><a name="zh-cn_topic_0256062644_filepath115819811512"></a><a name="zh-cn_topic_0256062644_filepath115819811512"></a>“${install_path}/lib64”</span>,其中<span class="filepath" id="zh-cn_topic_0256062644_filepath195951574421"><a name="zh-cn_topic_0256062644_filepath195951574421"></a><a name="zh-cn_topic_0256062644_filepath195951574421"></a>“{install_path}”</span>为gcc升级安装路径。请参见<a href="#安装7-3-0版本gccmd#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li9745165315131">5</a>。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row16194175523010"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p16195185523019"><a name="zh-cn_topic_0000001152616261_p16195185523019"></a><a name="zh-cn_topic_0000001152616261_p16195185523019"></a>PYTHONPATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p19637083322"><a name="zh-cn_topic_0000001152616261_p19637083322"></a><a name="zh-cn_topic_0000001152616261_p19637083322"></a>Python搜索路径,参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row2954102119329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p195452113218"><a name="zh-cn_topic_0000001152616261_p195452113218"></a><a name="zh-cn_topic_0000001152616261_p195452113218"></a>PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p964914893211"><a name="zh-cn_topic_0000001152616261_p964914893211"></a><a name="zh-cn_topic_0000001152616261_p964914893211"></a>可执行程序的查找路径,参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row58592816294"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p1886016892913"><a name="zh-cn_topic_0000001152616261_p1886016892913"></a><a name="zh-cn_topic_0000001152616261_p1886016892913"></a>ASCEND_OPP_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p28608892915"><a name="zh-cn_topic_0000001152616261_p28608892915"></a><a name="zh-cn_topic_0000001152616261_p28608892915"></a>算子根目录,参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row144592037903"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p104601373014"><a name="zh-cn_topic_0000001152616261_p104601373014"></a><a name="zh-cn_topic_0000001152616261_p104601373014"></a>OPTION_EXEC_EXTERN_PLUGIN_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1046013716017"><a name="zh-cn_topic_0000001152616261_p1046013716017"></a><a name="zh-cn_topic_0000001152616261_p1046013716017"></a>算子信息库路径。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row16184379493"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p131851873492"><a name="zh-cn_topic_0000001152616261_p131851873492"></a><a name="zh-cn_topic_0000001152616261_p131851873492"></a>ASCEND_AICPU_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p181851575497"><a name="zh-cn_topic_0000001152616261_p181851575497"></a><a name="zh-cn_topic_0000001152616261_p181851575497"></a>aicpu算子包路径。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row234714854615"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p2034724894619"><a name="zh-cn_topic_0000001152616261_p2034724894619"></a><a name="zh-cn_topic_0000001152616261_p2034724894619"></a>TASK_QUEUE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p53477489462"><a name="zh-cn_topic_0000001152616261_p53477489462"></a><a name="zh-cn_topic_0000001152616261_p53477489462"></a>使用异步任务下发,异步调用acl接口。建议开启,开启设置为1。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row1680820246202"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p4809112415207"><a name="zh-cn_topic_0000001152616261_p4809112415207"></a><a name="zh-cn_topic_0000001152616261_p4809112415207"></a>HCCL_WHITELIST_DISABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p952814428206"><a name="zh-cn_topic_0000001152616261_p952814428206"></a><a name="zh-cn_topic_0000001152616261_p952814428206"></a>配置在使用HCCL时是否开启通信白名单。</p>
<a name="ul928845132310"></a><a name="ul928845132310"></a><ul id="ul928845132310"><li>0:开启白名单,无需校验HCCL通信白名单。</li><li>1:关闭白名单,需校验HCCL通信白名单。</li></ul>
<p id="zh-cn_topic_0000001152616261_p5809162416201"><a name="zh-cn_topic_0000001152616261_p5809162416201"></a><a name="zh-cn_topic_0000001152616261_p5809162416201"></a>缺省值为0,默认开启白名单。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row0671137162115"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p4671203792114"><a name="zh-cn_topic_0000001152616261_p4671203792114"></a><a name="zh-cn_topic_0000001152616261_p4671203792114"></a>HCCL_IF_IP</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1822165982114"><a name="zh-cn_topic_0000001152616261_p1822165982114"></a><a name="zh-cn_topic_0000001152616261_p1822165982114"></a>配置HCCL的初始化通信网卡IP。</p>
<a name="ul2676102292415"></a><a name="ul2676102292415"></a><ul id="ul2676102292415"><li>ip格式为点分十进制。</li><li>暂只支持host网卡。</li></ul>
<p id="zh-cn_topic_0000001152616261_p1167163719217"><a name="zh-cn_topic_0000001152616261_p1167163719217"></a><a name="zh-cn_topic_0000001152616261_p1167163719217"></a>缺省时,按照以下优先级选定host通信网卡名:docker/local以外网卡(网卡名字字典序升序排列)&gt;docker 网卡 &gt; local网卡</p>
</td>
</tr>
<tr id="row743212132309"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p17433111312307"><a name="p17433111312307"></a><a name="p17433111312307"></a>ASCEND_SLOG_PRINT_TO_STDOUT</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p6433151393018"><a name="p6433151393018"></a><a name="p6433151393018"></a>(可选)设置是否开启日志打屏。</p>
<a name="ul760201917473"></a><a name="ul760201917473"></a><ul id="ul760201917473"><li>0:表示采用日志的默认输出方式。</li><li>1:表示日志打屏显示。</li><li>其他值为非法值。</li></ul>
</td>
</tr>
<tr id="row19237171814300"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p14238161893019"><a name="p14238161893019"></a><a name="p14238161893019"></a>ASCEND_GLOBAL_LOG_LEVEL</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p223841810303"><a name="p223841810303"></a><a name="p223841810303"></a>设置应用类日志的全局日志级别。</p>
<a name="ul175714586453"></a><a name="ul175714586453"></a><ul id="ul175714586453"><li>0:对应DEBUG级别。</li><li>1:对应INFO级别。</li><li>2:对应WARNING级别。</li><li>3:对应ERROR级别。</li><li>4:对应NULL级别,不输出日志。</li><li>其他值为非法值。</li></ul>
</td>
</tr>
<tr id="row1348192313303"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1734815235305"><a name="p1734815235305"></a><a name="p1734815235305"></a>ASCEND_GLOBAL_EVENT_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p12348202373018"><a name="p12348202373018"></a><a name="p12348202373018"></a>设置应用类日志是否开启Event日志。</p>
<a name="ul416352114610"></a><a name="ul416352114610"></a><ul id="ul416352114610"><li>0:不开启Event日志。</li><li>1:开启Event日志。</li><li>其他值为非法值。</li></ul>
</td>
</tr>
<tr id="row17878184693015"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1878194683016"><a name="p1878194683016"></a><a name="p1878194683016"></a>DYNAMIC_COMPILE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p1887894620304"><a name="p1887894620304"></a><a name="p1887894620304"></a>(可选)动态shape特性功能,针对shape变化场景,开启设置为1(PyTorch1.8.1不支持该环境变量)。</p>
</td>
</tr>
<tr id="row78312162301"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1832171673019"><a name="p1832171673019"></a><a name="p1832171673019"></a>COMBINED_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(可选)非连续两个算子组合类场景优化,开启设置为1。</p>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(可选)非连续转连续二级推导优化,开启设置为1。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升。但是Host下发性能存在下降风险。</p>
</td>
</tr>
<tr id="row183041355123411"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p730435533415"><a name="p730435533415"></a><a name="p730435533415"></a>ACL_DUMP_DATA</p>
@@ -296,258 +135,346 @@
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p16304105533412"><a name="p16304105533412"></a><a name="p16304105533412"></a>(可选)算子数据dump功能,调试时使用,开启设置为1。</p>
</td>
</tr>
<tr id="row27481914203518"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p674813144357"><a name="p674813144357"></a><a name="p674813144357"></a>DYNAMIC_OP</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p974891414353"><a name="p974891414353"></a><a name="p974891414353"></a>(可选)算子实现,ADD和MUL算子在不同场景下有不同的性能表现。默认不设置。</p>
</td>
</tr>
<tr id="row19173161510309"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p16711563237"><a name="zh-cn_topic_0000001152616261_p16711563237"></a><a name="zh-cn_topic_0000001152616261_p16711563237"></a>unset GOMP_CPU_AFFINITY</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p0711356152317"><a name="zh-cn_topic_0000001152616261_p0711356152317"></a><a name="zh-cn_topic_0000001152616261_p0711356152317"></a>(可选)当系统为openEuler及其继承操作系统时,如UOS,需设置此命令,取消CPU绑核。</p>
</td>
</tr>
</tbody>
</table>
<h3 id="安装混合精度模块md">安装混合精度模块</h3>
## 执行单元测试脚本
#### 前提条件<a name="zh-cn_topic_0000001106176190_section3225481020"></a>
验证运行, 输出结果OK
1. 请确保运行环境中适配昇腾AI处理器的PyTorch框架能正常使用。
2. 编译安装Apex前,需参见[配置环境变量](#配置环境变量md)配置好编译过程依赖的环境变量。
```shell
cd test/test_network_ops/
python3 test_div.py
```
#### 安装流程<a name="zh-cn_topic_0000001106176190_section11880164819567"></a>
# 安装混合精度模块(可选)<a name="安装混合精度模块(可选)"></a>
1. 以root或非root用户登录服务器。
2. 获取apex源代码。
AscendPyTorch1.8.1集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex/tree/v1.8.1-3.0.rc2/)进行编译安装Apex模块。
1. 运行如下命令,获取适配昇腾AI处理器的apex源代码。
- AMP
```
git clone -b master https://gitee.com/ascend/apex.git
```
- 动态loss scale:动态计算loss scale的值并判断是否溢出。
- 不支持tensor融合功能。
下载的源码主要目录结构如下所示:
- APEX
```
apex
│ ├─patch # 昇腾AI处理器适配补丁目录
│ ├─npu.patch
│ ├─scripts # 编译构建目录
│ ├─gen.sh
│ ├─src # 源码目录
│ ├─tests # 测试用例存放目录
```
2. 运行如下命令,进入“apex“目录,并获取原生apex源代码。
```
cd apex
git clone https://github.com/NVIDIA/apex.git
```
下载原生apex源码后,代码主要目录结构如下所示:
```
apex
│ ├─apex # 原生apex代码目录
│ ├─patch # 昇腾AI处理器适配补丁目录
│ ├─npu.patch
│ ├─scripts # 编译构建目录
│ ├─gen.sh
│ ├─src # 源码目录
│ ├─tests # 测试用例存放目录
```
3. 进入原生apex代码目录,即“apex/apex“目录。切换至commitid为4ef930c1c884fdca5f472ab2ce7cb9b505d26c1a的代码分支。
```
cd apex
git checkout 4ef930c1c884fdca5f472ab2ce7cb9b505d26c1a
```
>![](public_sys-resources/icon-note.gif) **说明:**
>受网络波动影响,源码获取时间可能较长,下载过程中请耐心等待。
3. 编译生成适配昇腾AI处理器的apex安装包。
1. 进入“apex/scripts“文件夹,执行转换脚本,生成适配昇腾AI处理器的全量代码。
```
cd ../scripts
bash gen.sh
```
将在"apex/apex"目录中生成适配昇腾AI处理器的全量代码。
2. 进入适配后的全量代码目录,即“apex/apex“目录,编译生成apex的二进制安装包。
```
cd ../apex
python3 setup.py --cpp_ext --npu_float_status bdist_wheel
```
Python版本需与PyTorch使用的Python一致,生成的二进制包在当前的dist目录下,即“apex/apex/dist”文件夹目录下。
4. <a name="zh-cn_topic_0000001106176190_li425495374416"></a>安装apex。
进入“apex/apex/dist“文件夹目录,执行如下命令安装。
```
cd dist
pip3 install --upgrade apex-0.1+ascend-cp37-cp37m-linux_{arch}.whl
```
**\{arch\}**表示架构信息,为aarch64或x86\_64。
>![](public_sys-resources/icon-note.gif) **说明:**
>若对环境中的Apex进行升级时,需要先卸载环境中已安装的PyTorch软件包再执行[4. 安装apex。](#zh-cn_topic_0000001106176190_li425495374416)可以通过执行如下命令查询环境上是否已安装PyTorch。
>**pip3 list | grep apex**
- O1配置模式:Conv,Matmul等使用float16精度计算,其他如softmax、BN使用float32精度。
- O2配置模式:除BN使用float32精度外,其他部分使用float16精度。
- 静态loss scale:静态设置参数确保混合精度训练收敛。
- 动态loss scale:动态计算loss scale的值并判断是否溢出。
<h2 id="参考信息md">参考信息</h2>
# FAQ<a name="FAQ"></a>
- **[CMake安装方法](#CMake安装方法md)**
## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch1.8.1,需要使用源码编译安装。
- **[安装7.3.0版本gcc](#安装7-3-0版本gccmd)**
下载PyTorch v1.8.1源码包。
- **[安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配md)**
```
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
```
进入源码包获取被动依赖代码。
```
cd pytorch_v1.8.1
git submodule sync
git submodule update --init --recursive
```
执行编译安装。
```
python3 setup.py install
```
## 在PIP设置为华为源时,安装requirments.txt中的typing依赖后,会导致python环境错误。
在PIP设置为华为源时,需打开requirments.txt文件,删除typing依赖,再执行命令。
```
pip3 install -r requirments.txt
```
## 编译过程执行bash build.sh报错no module named yaml/typing_extensions.
pytorch编译依赖 yaml库和typing_extensions库,需要手动安装。
```
pip3 install pyyaml
pip3 install typing_extensions
```
安装成功后,注意需要执行make clean在执行bash build.sh进行编译,否则可能因缓存出现未知编译错误。
## 运行遇到找不到te问题
开发态:
```
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 #{arch}为架构名称。
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
用户态:
```
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 #{arch}为架构名称。
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
## 命令行安装cmake依赖时提示找不到包、编译cmake报错版本过低,可使用安装脚本或源码编译安装。
方法一:下载安装脚本安装cmake。(参考cmake官网)
​ X86_64环境脚本安装:cmake-3.12.0-Linux-x86_64.sh
​ aarch64环境脚本安装:cmake-3.12.0-Linux-aarch64.sh
1. 执行命令。
```
./cmake-3.12.0-Linux-{arch}.sh #{arch}为架构名称
```
2. 设置软连接。
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
3. 执行如下命令验证是否安装成功。
```
cmake --version
```
如显示“cmake version 3.12.0”则表示安装成功。
<h3 id="CMake安装方法md">CMake安装方法</h3>
方法二:使用源码编译安装。
CMake版本升级为3.12.1的方法
1. 获取cmake软件包。
1. 获取Cmake软件包。
```
wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
```
```
wget https://cmake.org/files/v3.12/cmake-3.12.1.tar.gz --no-check-certificate
```
2. 解压并进入软件包目录。
2. 解压并进入软件包目录。
```
tar -xf cmake-3.12.0.tar.gz
cd cmake-3.12.0/
```
```
tar -xf cmake-3.12.1.tar.gz
cd cmake-3.12.1/
```
3. 执行配置、编译和安装命令。
3. 执行配置、编译和安装命令。
```
./configure --prefix=/usr/local/cmake
make && make install
```
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. 设置软连接。
4. 设置软连接。
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. 执行如下命令验证是否安装成功。
5. 执行如下命令验证是否安装成功。
```
cmake --version
```
```
cmake --version
```
如显示“cmake version 3.12.0”则表示安装成功。
如显示“cmake version 3.12.1”则表示安装成功。
## 命令行安装gcc依赖时提示找不到包、编译时gcc报错问题
<h3 id="安装7-3-0版本gccmd">安装7.3.0版本gcc</h3>
部分源下载gcc时会提示无法找到包,需要使用源码编译安装。
以下步骤请在root用户下执行。
1. 下载gcc-7.3.0.tar.gz,下载地址为[https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz)。
2. 安装gcc时候会占用大量临时空间,所以先执行下面的命令清空/tmp目录:
1. 下载gcc-7.3.0.tar.gz,下载地址为[https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz)。
```
sudo rm -rf /tmp/*
```
2. 安装gcc时候会占用大量临时空间,所以先执行下面的命令清空/tmp目录:
3. 安装依赖(以CentOS和Ubuntu系统为例)。
- CentOS执行如下命令安装。
```
sudo rm -rf /tmp/*
```
```
yum install bzip2
```
3. 安装依赖(以CentOS和Ubuntu系统为例)。
- Ubuntu执行如下命令安装。
- CentOS执行如下命令安装。
```
apt-get install bzip2
```
```
yum install bzip2
```
4. 编译安装gcc。
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
- Ubuntu执行如下命令安装。
```
tar -zxvf gcc-7.3.0.tar.gz
```
```
apt-get install bzip2
```
2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
4. 编译安装gcc。
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
如果执行上述命令报错,需要执行如下命令在“gcc-7.3.0/“文件夹下下载依赖包:
```
tar -zxvf gcc-7.3.0.tar.gz
```
```
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
```
2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
下载好上述依赖包后,重新执行以下命令:
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
```
./contrib/download_prerequisites
```
如果执行上述命令报错,需要执行如下命令在“gcc-7.3.0/“文件夹下下载依赖包:
如果上述命令校验失败,需要确保依赖包为一次性下载成功,无重复下载现象。
```
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
```
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>执行配置、编译和安装命令:
下载好上述依赖包后,重新执行以下命令:
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
make -j15 # 通过grep -w processor /proc/cpuinfo|wc -l查看cpu数,示例为15,用户可自行设置相应参数。
make install
```
```
./contrib/download_prerequisites
```
>![](public_sys-resources/icon-notice.gif) **须知:**
>其中“--prefix“参数用于指定linux\_gcc7.3.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.3.0“。
如果命令校验失败,需要确认上述依赖包在文件夹中的唯一性,无重复下载,若存在重复的依赖包,需删除。
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>执行配置、编译和安装命令:
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
make -j15 # 通过grep -w processor /proc/cpuinfo|wc -l查看cpu数,示例为15,用户可自行设置相应参数。
make install
```
>![](public_sys-resources/icon-notice.gif) **须知:**
>其中“--prefix“参数用于指定linux\_gcc7.3.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.3.0“。
4. 修改软连接。
```
ln -s ${install_path}/bin/gcc /usr/bin/gcc
ln -s ${install_path}/bin/g++ /usr/bin/g++
ln -s ${install_path}/bin/c++ /usr/bin/c++
```
5. 配置环境变量。
当用户执行训练时,需要用到gcc升级后的编译环境,因此要在训练脚本中配置环境变量,通过如下命令配置。
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.3.0安装路径,本示例为“/usr/local/linux_gcc7.3.0/“。
>![](public_sys-resources/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
若存在pytorch编译不过,请检查软连接的库是否正确。
5. 配置环境变量。
libstdc++->libstdc++.so.6.0.24(7.3.0)
当用户执行训练时,需要用到gcc升级后的编译环境,因此要在训练脚本中配置环境变量,通过如下命令配置。
## 找不到libblas.so问题
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
环境缺少openblas库,需要安装openblas库
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.3.0安装路径,本示例为“/usr/local/gcc7.3.0/“。
Centos,EulerOS环境
>![](public_sys-resources/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
```sh
yum -y install openblas
```
Ubuntu环境
<h3 id="安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配md">安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配</h3>
```sh
apt install libopenblas-dev
```
#### 现象描述<a name="zh-cn_topic_0000001105856364_zh-cn_topic_0175549220_section197270431505"></a>
## 容器中未挂载device问题
在容器中运行脚本出现NPU相关ERROR。由于启动容器实例时,未挂载device参数,导致无法正常启动实例。
![](figures/FAQ.png)
请用户参考以下命令,重启容器。
```sh
docker run -it --ipc=host \
--device=/dev/davinciX \
--device=/dev/davinci_manager \
--device=/dev/devmm_svm \
--device=/dev/hisi_hdc \
-v /usr/local/Ascend/driver \
-v /usr/local/dcmi \
-v /usr/local/bin/npu-smi \
${镜像名称}:{tag} \
/bin/bash
```
参数说明:
/dev/davinciX:NPU设配,X是芯片物理ID号例如davinci0。
/dev/davinci_manager:管理设备。
/dev/devmm_svm:管理设备。
/dev/hisi_hdc:管理设备。
/usr/local/Ascend/driver:驱动目录。
/usr/local/dcmi:DCMI目录。
/usr/local/bin/npu-smi:npu-smi工具。
${镜像名称}:{tag}:镜像名称与版本号。
## 安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配
安装“torch-\*.whl”时,提示"ERROR:torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible"。
![](figures/zh-cn_image_0000001190081735.png)
#### 可能原因<a name="zh-cn_topic_0000001105856364_zh-cn_topic_0175549220_section169499490501"></a>
安装torch时,会自动触发torchvision进行依赖版本检查,环境中安装的torchvision版本为0.6.0,检查时发现我们安装的torch-\*.whl的版本号与要求的1.5.0不一致,所以提示报错,但实际安装成功 。
#### 处理方法<a name="zh-cn_topic_0000001105856364_section108142031907"></a>
对实际结果无影响,无需处理。
## import torch_npu 显示_has_compatible_shallow_copy_type重复注册warning问题
warning如下图所示,由Tensor.set_data浅拷贝操作触发。主要原因是PyTorch插件化解耦后,`_has_compatible_shallow_copy_type`缺乏对NPU Tensor的浅拷贝判断支持,因此需要重新注册`_has_compatible_shallow_copy_type`。
该warning不影响模型的精度和性能,可以忽略。
待NPU 设备号合入社区或者后续Pytorch版本`_has_compatible_shallow_copy_type`注册方式发生变动,该warning会被解决。
![输入图片说明](https://images.gitee.com/uploads/images/2022/0701/153621_2b5080c4_7902902.png)
## 在编译torch_npu的目录进入python引用torch_npu报错问题
验证torch_npu的引入,请切换至其他目录进行,在编译目录执行会提示如下错误。
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
# 版本说明<a name='版本说明'></a>
版本说明请参阅[ReleseNote](https://gitee.com/ascend/pytorch/blob/v1.8.1-3.0.rc2/docs/zh/RELEASENOTE/RELEASENOTE.md)
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

@@ -715,12 +715,12 @@ pytorch分布式训练基本概念
3. 在每台服务器上分别打开**/etc/hosts**文件,在该文件中添加本服务器对应的IP地址和主机名,且需要添加到该文件的首行。如果文件中已添加,则跳过此步骤。添加内容示例如下:
```
10.90.140.199 ubuntu
xxx.xxx.xxx.111 ubuntu
```
其中10.90.140.199为该服务器的IP地址,ubuntu为主机名。
其中xxx.xxx.xxx.111为该服务器的IP地址,ubuntu为主机名。
4. 在第一台服务器执行如下命令生成公钥(例如第一台服务器IP为10.90.140.199)。
4. 在第一台服务器执行如下命令生成公钥(例如第一台服务器IP为xxx.xxx.xxx.111)。
```
cd ~/.ssh/ # 若没有该目录,请先执行一次ssh localhost
@@ -749,7 +749,7 @@ pytorch分布式训练基本概念
6. 在其他每台服务器上执行如下命令将第一台服务器制作好的公钥复制到其他每台服务器内。
cd ~/.ssh/
scp root@10.90.140.199:~/.ssh/authorized_keys ./
scp root@xxx.xxx.xxx.111:~/.ssh/authorized_keys ./
7. 在每台服务器执行如下命令测试免密登录。
@@ -757,9 +757,9 @@ pytorch分布式训练基本概念
ssh 用户名@IP地址
```
例如:在第一台服务器10.90.140.199免密登录服务器10.90.140.231,执行**ssh root@10.90.140.231**命令。
例如:在第一台服务器xxx.xxx.xxx.111免密登录服务器xxx.xxx.xxx.222,执行**ssh root@xxx.xxx.xxx.222**命令。
若显示类似如下信息,说明已免密登录服务器10.90.140.231。
若显示类似如下信息,说明已免密登录服务器xxx.xxx.xxx.222。
```
Linux ubuntu 4.19.28 #1 SMP Tue Jun 23 19:05:23 EDT 2020 x86_64
@@ -777,7 +777,7 @@ pytorch分布式训练基本概念
```
logout
Connection to 10.90.140.231 closed.
Connection to xxx.xxx.xxx.222 closed.
```
3. 使用OpenMPI拉起模型训练。
@@ -846,7 +846,7 @@ if [ -d ${install_path}/toolkit ]; then
export ASCEND_OPP_PATH=${install_path}/opp
else
if [ -d ${install_path}/nnae/latest ];then
exportLD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
export PATH=$PATH:${install_path}/nnae/latest/fwkacllib/ccec_compiler/bin/:${install_path}/nnae/latest/toolkit/tools/ide_daemon/bin/
export ASCEND_OPP_PATH=${install_path}/nnae/latest/opp/
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 607 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 99 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Before

Width:  |  Height:  |  Size: 121 KiB

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 140 KiB

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 580 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 580 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 394 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 406 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 253 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 580 B

+122 -2
View File
@@ -1,4 +1,11 @@
# FrameworkPTAdapter 3.0.RC1 版本说明书
# FrameworkPTAdapter 3.0.RC2 版本说明书
- [FrameworkPTAdapter 3.0.RC2](#FrameworkPTAdapter-3-0-RC2md)
- [用户须知](#用户须知md)
- [新增特性](#新增特性md)
- [特性修改](#特性修改md)
- [已修复问题](#已修复问题md)
- [已知问题](#已知问题md)
- [兼容性](#兼容性md)
- [FrameworkPTAdapter 3.0.RC1](#FrameworkPTAdapter-3-0-RC1md)
- [用户须知](#用户须知md)
- [新增特性](#新增特性md)
@@ -28,7 +35,120 @@
- [已知问题](#已知问题-4md)
- [兼容性](#兼容性-5md)
- - ](#兼容性-5md)
<h2 id="FrameworkPTAdapter-3-0-RC2md">FrameworkPTAdapter 3.0.RC2</h2>
<h3 id="用户须知md">用户须知</h3>
本框架基于Facebook主导的开源PyTorch1.5.0和1.8.1版本进行修改,延续原生的PyTorch特性,使用NPU进行动态图训练;以算子粒度进行模型适配,代码重用性好,支持现有的网络只修改设备类型或数据类型,即可迁移到NPU上使用。
PyTorch1.8.1版本采用插件化适配方式,与原生PyTorch框架实现彻底解耦,当前功能、性能与PyTorch1.5.0基本保持一致,对后端算子适配提供较好开发体验。
支持AOE调优工具。
<h3 id="新增特性md">新增特性</h3>
**表 1** PyTorch支持的版本特性列表
<a name="t76c34275cbb74753970f7c5a9eb594fa"></a>
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>一级特性</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>二级特性</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>说明</p>
</th>
</tr>
</thead>
<tbody>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>适配NPU的PyTorch1.5.0特性</p>
</td>
</tr>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> 框架基础功能。</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> 少量BUG修复。</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="3" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>适配NPU的PyTorch1.8.1特性</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>插件化解耦</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>torch_npu插件与原生PyTorch框架实现彻底解耦。</p>
</td>
<tr>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>性能优化</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>优化单算子下发以及集合通讯功能</p>
</td>
</tr>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>API满足度提升。</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>新增部分API适配(详情见API清单)。</p>
</td>
</tr>
</tbody>
</table>
<h3 id="特性修改md">特性修改</h3>
不涉及
<h3 id="已修复问题md">已修复问题</h3>
不涉及
<h3 id="已知问题md">已知问题</h3>
<a name="table1969972073016"></a>
<table><thead align="left"><tr id="row3699162017307"><th class="cellrowborder" valign="top" width="18.22%" id="mcps1.1.3.1.1"><p id="p16992020153010"><a name="p16992020153010"></a><a name="p16992020153010"></a>已知问题</p>
</th>
<th class="cellrowborder" valign="top" width="81.78%" id="mcps1.1.3.1.2"><p id="p269919203308"><a name="p269919203308"></a><a name="p269919203308"></a>问题描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row9699142003011"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p1769932017300"><a name="p1769932017300"></a><a name="p1769932017300"></a>数据类型支持</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p13699152010301"><a name="p13699152010301"></a><a name="p13699152010301"></a>NPU不支持float16类型的inf/nan数据输入输出。</p>
</td>
</tr>
<tr id="row146991520153016"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p156997200308"><a name="p156997200308"></a><a name="p156997200308"></a>数据Format</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p10699182020308"><a name="p10699182020308"></a><a name="p10699182020308"></a>出现4D以上的format时不能降维。</p>
</td>
</tr>
<tr id="row11121205610549"><td class="cellrowborder" rowspan="3" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p1647216219558"><a name="p1647216219558"></a><a name="p1647216219558"></a>集合通信约束</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></a></p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p3116115695415"><a name="p3116115695415"></a><a name="p3116115695415"></a>要求一次训练任务中不同device上执行的图相同。</p>
</td>
</tr>
<tr id="row51211656105411"><td class="cellrowborder" valign="top" headers="mcps1.1.3.1.1 "><p id="p1311616560541"><a name="p1311616560541"></a><a name="p1311616560541"></a>当前只支持1/2/4/8P粒度的分配。</p>
</td>
</tr>
<tr id="row8647195765419"><td class="cellrowborder" valign="top" headers="mcps1.1.3.1.1 "><p id="p2064225716544"><a name="p2064225716544"></a><a name="p2064225716544"></a>只支持int8,int32,float16和float32数据类型。</p>
</td>
</tr>
<tr id="row4646195719548"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p4642195718541"><a name="p4642195718541"></a><a name="p4642195718541"></a>Apex功能支持</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p864205725412"><a name="p864205725412"></a><a name="p864205725412"></a>Apex当前版本的实现方式主要为python实现,不支持APEX中的自定义优化CUDA Kernel。</p>
</td>
</tr>
</tbody>
</table>
<h3 id="兼容性md">兼容性</h3>
A800-9010:CentOS 7.6/Ubuntu 18.04, 2.04/BC-Linux 7.6/Debian 9.9/Debian 10/OpenEuler 20.03 LTS
A800-9000:CentOS 7.6/Ubuntu 18.04, 2.04/Euler 2.8, 2.10/Kylin v10/BC-Linux 7.6/OpenEuler 20.03 LTS/UOS 20 1020e
<h2 id="FrameworkPTAdapter-3-0-RC1md">FrameworkPTAdapter 3.0.RC1</h2>
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+12
View File
@@ -13,6 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy
import torch
import torch_npu
from torch_npu.utils.device_guard import torch_device_guard, device
@@ -65,6 +66,16 @@ def jit_script(obj, optimize=None, _frames_up=0, _rcb=None):
# (Ascend) Disable extension of torch.jit.script
return obj
def _as_tensor(*args, **kwargs):
if kwargs and "device" in kwargs:
dst_device = kwargs.get("device")
if "npu" in str(dst_device):
if isinstance(args[0], numpy.ndarray):
return torch.from_numpy(args[0]).to(dst_device)
else:
return args[0].to(dst_device)
return torch._C._VariableFunctions.as_tensor(*args, **kwargs)
${device_methods_def_py_dispatch}
@@ -78,5 +89,6 @@ def add_torch_funcs():
torch.empty_with_format = _empty_with_format
torch.npu_dropout_gen_mask = _npu_dropout_gen_mask
torch.jit.script = jit_script
torch.as_tensor = _as_tensor
${device_methods_def_py}
+1 -1
View File
@@ -36,7 +36,7 @@ from setuptools.command.build_clib import build_clib
from setuptools.command.egg_info import egg_info
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
VERSION = '1.8.1rc2'
VERSION = '1.8.1.rc2'
def which(thefile):
+23 -2
View File
@@ -151,10 +151,31 @@ class TestCreationOps(TestCase):
self.assertRtolEqual(cpu_output3.numpy(), npu_output3.cpu().numpy())
def test_as_tensor(self):
# numpy ndarray to cpu/npu tensor
a = np.array([1, 2, 3])
cpu_output = torch.as_tensor(a, device=torch.device('cpu'))
npu_output = torch.as_tensor(a, device=device)
self.assertRtolEqual(cpu_output.numpy(), npu_output.cpu().numpy())
npu_output1 = torch.as_tensor(a, device="npu:0")
npu_output2 = torch.as_tensor(a, device="npu")
npu_output3 = torch.as_tensor(a, device=torch.device("npu"))
self.assertRtolEqual(cpu_output.numpy(), npu_output1.cpu().numpy())
self.assertRtolEqual(cpu_output.numpy(), npu_output2.cpu().numpy())
self.assertRtolEqual(cpu_output.numpy(), npu_output3.cpu().numpy())
# cpu tesor to npu tensor
a = np.array([1, 2, 3])
cpu_input = torch.as_tensor(a, device=torch.device('cpu'))
npu_output1 = torch.as_tensor(cpu_input, device="npu:0")
npu_output2 = torch.as_tensor(cpu_input, device="npu")
npu_output3 = torch.as_tensor(cpu_input, device=torch.device("npu"))
self.assertRtolEqual(cpu_input.numpy(), npu_output1.cpu().numpy())
self.assertRtolEqual(cpu_input.numpy(), npu_output2.cpu().numpy())
self.assertRtolEqual(cpu_input.numpy(), npu_output3.cpu().numpy())
# npu tesor to cpu tensor
a = np.array([1, 2, 3])
npu_input = torch.as_tensor(a, device=torch.device('npu'))
cpu_output = torch.as_tensor(npu_input, device="cpu")
self.assertRtolEqual(cpu_output.numpy(), npu_input.cpu().numpy())
def test_as_strided(self):
x = torch.randn(3, 3, device='npu:0')
-1
View File
@@ -87,7 +87,6 @@ class TestSort(TestCase):
cpu_output, cpu_indices = self.cpu_default_op_exec(cpu_input1.to(torch.float32))
npu_output, npu_indices = self.npu_default_op_exec(npu_input1)
self.assertRtolEqual(cpu_output.astype(np.float16), npu_output)
self.assertRtolEqual(cpu_indices, npu_indices)
if __name__ == "__main__":
run_tests()
+3 -3
View File
@@ -515,9 +515,9 @@ class TestNpu(TestCase):
device1 = torch.device("npu:1")
device2 = torch.device("npu")
device3 = torch.device("npu", 2)
self.assertEqual(str(device1), f"{torch_npu.npu.native_device}:1")
self.assertEqual(str(device2), torch_npu.npu.native_device)
self.assertEqual(str(device3), f"{torch_npu.npu.native_device}:2")
self.assertEqual(str(device1), f"device(type='{torch_npu.npu.npu_device}', index=1)")
self.assertEqual(str(device2), f"device(type='{torch_npu.npu.npu_device}', index=None)")
self.assertEqual(str(device3), f"device(type='{torch_npu.npu.npu_device}', index=2)")
def test_function_tensor_data_npu(self):
x = torch.ones(())
+54 -5
View File
@@ -15,9 +15,10 @@
import random
from math import sin, cos, pi
import numbers
import numpy as np
from PIL import Image
from torchvision.transforms import ColorJitter
import torch
class FusedColorJitterApply(object):
@@ -72,6 +73,14 @@ class FusedColorJitterApply(object):
def apply_image_transform(self, img, transform_matrix, transform_offset):
H, W, C = img.shape
if C != 3:
if C == 4:
img = img[:, :, :3]
elif C == 1:
img = img.repeat(3, axis=-1)
else:
raise ('Unknow format using.. Currnet shape is {}'.format(img.shape))
H, W, C = img.shape
img = np.matmul(img.reshape(-1, 3), transform_matrix) + transform_offset
return img.reshape(H, W, C)
@@ -97,7 +106,7 @@ class FusedColorJitterApply(object):
return img
class FusedColorJitter(ColorJitter):
class FusedColorJitter(torch.nn.Module):
"""Randomly change the brightness, contrast, saturation and hue of an image.
Unlike the native torchvision.transforms.ColorJitter,
@@ -125,9 +134,49 @@ class FusedColorJitter(ColorJitter):
"""
def __init__(self, brightness=0., contrast=0., saturation=0., hue=0.):
super().__init__(brightness, contrast, saturation, hue)
def __init__(self, brightness=0, contrast=0, saturation=0, hue=0):
super().__init__()
self.brightness = self._check_input(brightness, 'brightness')
self.contrast = self._check_input(contrast, 'contrast')
self.saturation = self._check_input(saturation, 'saturation')
self.hue = self._check_input(hue, 'hue', center=0, bound=(-0.5, 0.5),
clip_first_on_zero=False)
self.transformer = FusedColorJitterApply(brightness, contrast, saturation, hue)
def __call__(self, img):
@torch.jit.unused
def _check_input(self, value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True):
if isinstance(value, numbers.Number):
if value < 0:
raise ValueError("If {} is a single number, it must be non negative.".format(name))
value = [center - float(value), center + float(value)]
if clip_first_on_zero:
value[0] = max(value[0], 0.0)
elif isinstance(value, (tuple, list)) and len(value) == 2:
if not bound[0] <= value[0] <= value[1] <= bound[1]:
raise ValueError("{} values should be between {}".format(name, bound))
else:
raise TypeError("{} should be a single number or a list/tuple with length 2.".format(name))
# if value is 0 or (1., 1.) for brightness/contrast/saturation
# or (0., 0.) for hue, do nothing
if value[0] == value[1] == center:
value = None
return value
def forward(self, img):
return self.transformer(img)
def __repr__(self):
format_string = self.__class__.__name__ + '('
format_string += 'brightness={0}'.format(self.brightness)
format_string += ', contrast={0}'.format(self.contrast)
format_string += ', saturation={0}'.format(self.saturation)
format_string += ', hue={0})'.format(self.hue)
return format_string
if __name__ == '__main__':
image = Image.fromarray(torch.randint(0, 256, size=(224, 224, 3)).numpy().astype(np.uint8))
fcj = FusedColorJitter(0.1, 0.1, 0.1, 0.1)
image = fcj(image)
@@ -1862,11 +1862,9 @@ autograd:
- elu_
custom:
- func: npu_transpose_to_contiguous(Tensor self) -> Tensor
- func: npu_transpose(Tensor self, int[] perm, bool require_contiguous=True) -> Tensor
variants: function, method
- func: npu_transpose(Tensor self, int[] perm) -> Tensor
variants: function, method
- func: npu_transpose.out(Tensor self, int[] perm, *, Tensor(a!) out) -> Tensor(a!)
- func: npu_transpose.out(Tensor self, int[] perm, bool require_contiguous=True, *, Tensor(a!) out) -> Tensor(a!)
- func: npu_broadcast(Tensor self, int[] size) -> Tensor
variants: function, method
- func: npu_broadcast.out(Tensor self, int[] size, *, Tensor(a!) out) -> Tensor(a!)
+2 -2
View File
@@ -53,7 +53,7 @@ at::Tensor& argsort_out_npu_nocheck(
}
std::swap(perm[dim], perm[lastDim]);
at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm);
at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm, true);
auto outputSize = transpose_npu_output_size(values, perm);
at::Tensor transposeValues = OpPreparation::ApplyTensor(
values,
@@ -65,7 +65,7 @@ at::Tensor& argsort_out_npu_nocheck(
argsort_out_npu_no_transpose(
transposeValues, transposeIndices, transposeSelf, lastDim, descending);
NPUNativeFunctions::npu_transpose_out(transposeIndices, perm, indices);
NPUNativeFunctions::npu_transpose_out(transposeIndices, perm, true, indices);
// indices dtype transform to Int64
indices = NPUNativeFunctions::npu_dtype_cast(indices, at::kLong);
+3 -3
View File
@@ -52,7 +52,7 @@ void NPUNativeFunctions::_cummin_helper(const at::Tensor& self, at::Tensor& valu
}
std::swap(perm[dim], perm[firstDim]);
at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm);
at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm, true);
auto outputSize = transpose_npu_output_size(values, perm);
at::Tensor transposeValue = OpPreparation::ApplyTensor(self, outputSize);
at::Tensor transposeIndices = OpPreparation::ApplyTensor(outputSize, self.options().dtype(at::kInt), self);
@@ -60,8 +60,8 @@ void NPUNativeFunctions::_cummin_helper(const at::Tensor& self, at::Tensor& valu
cummin_out_npu_nocheck(transposeValue, transposeIndices, transposeSelf, firstDim);
// Indices must to be long
transposeIndices = transposeIndices.to(at::kLong);
NPUNativeFunctions::npu_transpose_out(transposeValue, perm, values);
NPUNativeFunctions::npu_transpose_out(transposeIndices, perm, indices);
NPUNativeFunctions::npu_transpose_out(transposeValue, perm, true, values);
NPUNativeFunctions::npu_transpose_out(transposeIndices, perm, true, indices);
} else {
at::Tensor valuesTemp = OpPreparation::ApplyTensor(self);
at::Tensor indicesTemp = OpPreparation::ApplyTensor(self, self.options().dtype(at::kInt));
+19 -15
View File
@@ -25,23 +25,13 @@ namespace native {
at::Tensor& index_put_nocheck(
at::Tensor& result,
const at::Tensor& self,
const at::TensorList& indices,
std::vector<at::Tensor> allDefinedIndices,
at::SmallVector<int64_t, N> masks,
const at::Tensor& value,
bool accumulate) {
if (value.numel() == 0) {
return result;
}
at::SmallVector<int64_t, N> masks;
std::vector<at::Tensor> allDefinedIndices;
for (int64_t i = 0; i < indices.size(); i++) {
if (indices[i].defined()) {
masks.emplace_back(1);
allDefinedIndices.emplace_back(indices[i]);
} else {
masks.emplace_back(0);
}
}
auto masksTensor = CalcuOpUtil::copy_tensor_host_to_device(
at::from_blob(masks.data(), {masks.size()}, dtype(at::ScalarType::Long)));
@@ -95,7 +85,21 @@ at::Tensor& NPUNativeFunctions::_index_put_impl_(
const bool accumulate,
const bool unsafe) {
at::native::checkIndexTensorTypes(indices);
auto indices_cast = at::native::expandTensors(self, indices);
at::SmallVector<int64_t, N> masks;
std::vector<at::Tensor> allDefinedIndices;
for (c10::optional<at::Tensor> index_opt : indices) {
if (index_opt.has_value()) {
at::Tensor index = std::move(*index_opt);
if (index.defined()) {
allDefinedIndices.emplace_back(index);
masks.emplace_back(1);
} else {
masks.emplace_back(0);
}
} else {
masks.emplace_back(0);
}
}
OpPreparation::CastBackToOriFormat(self);
at::Tensor valueCopy = value;
@@ -105,10 +109,10 @@ at::Tensor& NPUNativeFunctions::_index_put_impl_(
if (!NpuUtils::check_match(&self)) {
at::Tensor contiguousSelf = NpuUtils::format_contiguous(selfCopy);
at::Tensor result = index_put_nocheck(
contiguousSelf, contiguousSelf, indices_cast, valueCopy, accumulate);
contiguousSelf, contiguousSelf, allDefinedIndices, masks, valueCopy, accumulate);
self.copy_(result);
} else {
index_put_nocheck(selfCopy, selfCopy, indices_cast, valueCopy, accumulate);
index_put_nocheck(selfCopy, selfCopy, allDefinedIndices, masks, valueCopy, accumulate);
self.copy_(selfCopy);
}
return self;
@@ -55,7 +55,7 @@ std::tuple<at::Tensor, at::Tensor> NPUNativeFunctions::_pad_packed_sequence(
prevBatchSize = batchSize;
}
if (batchFirst) {
output = NPUNativeFunctions::npu_transpose(data, {0, 1});
output = NPUNativeFunctions::npu_transpose(data, {0, 1}, true);
}
return std::tie(output, lengthsT);
}

Some files were not shown because too many files have changed in this diff Show More