Compare commits

..
22 Commits
Author SHA1 Message Date
i-robot ce67fc0403 !77 update image in Installation Guide
Merge pull request !77 from yinzijun/2.0.3.tr5
2021-10-15 10:32:48 +00:00
weili10 25a75f9138 update README.zh.md. 2021-10-15 10:05:03 +00:00
ZijunYin 46be05d4a2 update image in docs/en/PyTorch Installation Guide 2021-10-15 17:51:00 +08:00
i-robot 10a621ac7e !75 update English docs
Merge pull request !75 from yinzijun/2.0.3.tr5
2021-10-15 09:36:48 +00:00
ZijunYin 0d912b623e Merge branch '2.0.3.tr5' of https://gitee.com/yinzijun/pytorch into 2.0.3.tr5 2021-10-15 17:21:02 +08:00
ZijunYin d65305484e update English docs. 2021-10-15 17:20:53 +08:00
i-robot bc2de075f5 !73 更新readme:增加文档链接
Merge pull request !73 from shibo/2.0.3.tr5
2021-10-13 09:30:49 +00:00
shibo19 b9b85d8bb7 update readme 2021-10-13 16:16:16 +08:00
i-robot af55dd59af !71 update RELEASENOTE with 2.0.2
Merge pull request !71 from yinzijun/2.0.3.tr5
2021-10-09 10:11:51 +00:00
ZijunYin 2e1a17d4b1 Merge branch '2.0.3.tr5' of https://gitee.com/yinzijun/pytorch into 2.0.3.tr5 2021-10-09 17:55:00 +08:00
ZijunYin ab5f233823 update RELEASENOTE.md 2021-10-09 17:54:49 +08:00
yinzijun 4146762193 !68 update docs/zh/RELEASENOTE/RELEASENOTE.md.
Merge pull request !68 from liuquan/N/A
2021-10-09 08:42:49 +00:00
刘全 c24a2a26f2 update docs/zh/RELEASENOTE/RELEASENOTE.md. 2021-10-09 07:10:10 +00:00
yinzijun 99baa47bac !66 add releasenote
Merge pull request !66 from yinzijun/2.0.3.tr5
2021-10-09 07:03:02 +00:00
ZijunYin 3aad7226de add RELEASENOTE.md 2021-10-09 09:54:56 +08:00
weili10 2c1766a041 update README.zh.md. 2021-10-08 02:46:19 +00:00
yinzijun 58402d67d2 !64 update docs 2.0.3.B090
Merge pull request !64 from yinzijun/2.0.3.tr5
2021-09-30 07:26:33 +00:00
ZijunYin 22a5bf8eba update docs 2.0.3.B090 2021-09-30 15:14:19 +08:00
AtlasAccount 7ec3a5a42a 同步1.5.0 2c2f79aaccfa455fb24553f77cca62d838b75bdf
!2559 【BugFix】修复输入shape不一致,算子侧未broadcast,导致不支持
    Merge pull request !2559 from 姚斌/2.0.3.tr5
--
    !2558 modify:del test_cases of 1 dim and NZ format in UT files
    Merge pull request !2558 from 郭夏/2.0.3.tr5
--
    !2556 修复IOU输出数据类型转换
    Merge pull request !2556 from 李攀/2.0.3.tr5
同步1.8.1 7afd57f35ebc3b81dd4c3f642e3f8ba81c1f07f0
2021-09-28 22:05:02 +08:00
AtlasAccount 8611e0e3d5 同步1.5.0 a3c3eef54ba99da98fcfb1f47315ab0aaecb6f54
!2553 修复load模式时conv2d反向dump结果ir_name被覆盖的问题,合入商发
    Merge pull request !2553 from gaokai21/2.0.3.tr5
同步1.8.1 7afd57f35ebc3b81dd4c3f642e3f8ba81c1f07f0
2021-09-27 21:00:32 +08:00
AtlasAccount a2ed4eb074 同步1.5.0 55e1c5be4b9ce8cf007fdf7848d3e933c7dba800
!2548 [contrib/npu/optimized_lib/] merge master to 2.0.3.tr5
    Merge pull request !2548 from 王姜奔/2.0.3.tr5
同步1.8.1 7afd57f35ebc3b81dd4c3f642e3f8ba81c1f07f0
2021-09-27 14:33:37 +08:00
AtlasAccount c6d5d99656 同步1.5.0 210593a373ef600735b60946c7edeccefa97e5eb
!2546 修复maxunpool2dbackward执行报错
    Merge pull request !2546 from 李攀/bugfix
同步1.8.1 7afd57f35ebc3b81dd4c3f642e3f8ba81c1f07f0
2021-09-27 11:01:57 +08:00
1620 changed files with 236210 additions and 51948 deletions
-24
View File
@@ -1,24 +0,0 @@
<!-- Thanks for sending a pull request!
-->
**What type of PR is this?**
> Uncomment only one ` /kind <>` line, hit enter to put that in a new line, and remove leading whitespaces from that line:
>
> /kind bug
> /kind task
> /kind feature
**What does this PR do / why do we need it**:
**Which issue(s) this PR fixes**:
<!--
*Automatically closes linked issue when PR is merged.
Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
-->
Fixes #
**Special notes for your reviewers**:
+6 -6
View File
@@ -18,7 +18,6 @@
- 在[Gitee](https://gitee.com/ascend/pytorch)上Fork存储库。
- 阅读[README.md](#https://gitee.com/ascend/pytorch/blob/master/README.zh.md)以获取项目信息和构建说明。
- 行为准则 [coc](https://gitee.com/ascend/community/blob/master/code-of-conduct_zh_cn.md)。
<h2 id="开发指导.md">开发指导</h2>
@@ -99,7 +98,7 @@
2. 设置环境变量。
进入"pytorch/src"路径,并执行env.sh脚本。
进入“pytorh/src“路径,并执行env.sh脚本。
```
bash env.sh
@@ -120,11 +119,11 @@
- 编码指南
请在PyTorch社区使用规统一的编码分格,python建议的编码风格是[PEP 8编码样式](https://pep8.org/),C++编码所建议的风格是 [Google C++编码指南](http://google.github.io/styleguide/cppguide.html) 。可以使用[CppLint](https://github.com/cpplint/cpplint),[CppCheck](http://cppcheck.sourceforge.net/),[CMakeLint](https://github.com/cmake-lint/cmake-lint),[CodeSpell](https://github.com/codespell-project/codespell), [Lizard](http://www.lizard.ws/),[ShellCheck](https://github.com/koalaman/shellcheck)和[pylint](https://pylint.org/)检查代码的格式,建议在您的IDE中安装这些插件。
请在PyTorch社区使用规统一的编码分格,_Python__中_建议的编码风格是[PEP 8编码样式](https://pep8.org/),_C++_编码所建议的风格是 [Google C++编码指南](http://google.github.io/styleguide/cppguide.html) 。可以使用[CppLint](https://github.com/cpplint/cpplint),[CppCheck](http://cppcheck.sourceforge.net/),[CMakeLint](https://github.com/cmake-lint/cmake-lint),[CodeSpell](https://github.com/codespell-project/codespell), [Lizard](http://www.lizard.ws/),[ShellCheck](https://github.com/koalaman/shellcheck)和[pylint](https://pylint.org/)检查代码的格式,建议在您的IDE中安装这些插件。
- 单元测试指南
请在PyTorch社区使用统一的单元测试风格, Python中建议的单元测试风格是[pytest](http://www.pytest.org/en/latest/),C++单元测试所建议的风格是 [Googletest Primer](#https://github.com/google/googletest/blob/master/docs/primer.md) 。测试用例的设计意图应该通过它的注释名称来反映。
请在PyTorch社区使用统一的单元测试风格, _Python_中建议的单元测试风格是[pytest](http://www.pytest.org/en/latest/),_C++_单元测试所建议的风格是 [Googletest Primer](#https://github.com/google/googletest/blob/master/docs/primer.md) 。测试用例的设计意图应该通过它的注释名称来反映。
- 重构指南
@@ -166,7 +165,7 @@
3. 本地开发代码。
为了避免多个分支之间的不一致,建议创建新的分支进行开发:
为了避免多个分支之间的不一致,建议签出到一个新的分支:
```
git checkout -b {new_branch_name} origin/master
@@ -186,7 +185,7 @@
git push origin {new_branch_name}
```
5. 向 PyTorch存储库拉取请求。
5. 向 PyTorh存储库拉取请求。
在最后一步中,您需要在新分支和“PyTorch master“分支之间拉取比较请求。完成拉取请求后,“Jenkins CI“将自动设置为构建测试。您的pull request应该尽快合并到上游 master 分支,以降低合并的风险。
@@ -225,3 +224,4 @@
- 确保你的提交历史被排序。
- 始终将您的分支与主分支保持一致。
- 对于错误修复 PR,请确保链接所有相关问题。
+6 -18
View File
@@ -1,9 +1,8 @@
approvers:
- blian
- nalinaly
- weili10
- you-ansheng
reviewers:
- zhou_sinan
- shibo19
- Ronnie_zheng
- xiaxia3
@@ -11,21 +10,10 @@ reviewers:
- petissue
- td__lihan
- ascendzyj
- wudingyuan
- wangyu0516
- yskhhh
- matrixplayer
- li_jing_hw
- wangjiangben_hw
- qingfenxiaochong
- goodjobwubai
- fairwarning
- you-ansheng
- yinzijun
- lvpeiyuan
- xchu42
- weili10
- shaoyf
- yanpengquan07
- xiong05
- liu-jiaweikf
- xiepeng20
- brightlyking
- chenhao_1209
- goodjobwubai
- fairwarning
-500
View File
@@ -1,500 +0,0 @@
# AscendPyTorch
<h1 id="introductionmd">Introduction</h1>
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 environment for model development and running under PyTorch, you can manually build and install modules adapted to the PyTorch framework on a server.
<h3 id="prerequisitesmd">Prerequisites</h3>
- The development or operating environment of CANN has been installed. For details, see the *CANN Software Installation Guide*.
- Python version: 3.7.5 or 3.8
# System Dependencies
## CentOS & EulerOS
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 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 |
# Installation Methods
## Installing the PyTorch Environment Dependencies
Obtain the PyTorch source code (from the current repository) that adapts to Ascend AI Processors.
```
git clone -b v1.5.0-3.0.rc2 https://gitee.com/ascend/pytorch.git
```
## Obtaining the Native PyTorch Source Code and Third-Party Code
Obtain the native PyTorch 1.5.0 source code from the root directory **/pytorch** of the current repository. Check whether there are fixed security-related issues in the Security and Issues categories in the PyTorch native repository. Update the native PyTorch code if there are any fixes.
```sh
cd pytorch
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
```
Go to the **pytorch/pytorch/** directory and obtain the passive dependency code of PyTorch. It takes a long time to obtain the code.
```sh
cd pytorch
git submodule sync
git submodule update --init --recursive
```
If no error is reported, the PyTorch and third-party code on which PyTorch depends is generated.
## Generating Full PyTorch Code That Adapts to Ascend AI Processors
Go to the **pytorch/scripts** directory and run the script of the selected version. (Note: The downloaded native PyTorch source code must match the following version. Otherwise, an error may occur.)
```sh
cd ../scripts/
bash gen.sh
```
The full code adapted to the NPU is generated in the **pytorch/pytorch/** directory.
## Installing the Python Dependency Library
Go to the **pytorch/pytorch/** directory and install the Python dependency library.
```python3
cd ../pytorch
pip3 install -r requirements.txt
```
## Compiling Torch Binary Package
In the **pytorch/pytorch/** directory, run the following command:
```sh
# Python 3.7
bash build.sh
or
bash build.sh --python=3.7 (recommended)
# Python 3.8
bash build.sh --python=3.8
```
The generated binary package is in the **pytorch/pytorch/dist/** directory.
## Installing PyTorch
**x86_64:**
**torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl** (The actual name may contain the minor version number, for example, **torch-1.5.0.post2+ascend-cp37-cp37m-linux_x86_64.whl**.)
```shell
cd dist
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl
```
**arm:**
**torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl** (The actual name may contain the minor version number, for example, **torch-1.5.0.post2+ascend-cp37-cp37m-linux_aarch64.whl**.)
```shell
cd dist
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl
```
# Running
## Executing Environment Variables
Run the script for setting environment variables in the **pytorch/pytorch/** directory.
```
cd ../
source env.sh
```
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**.
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**.
```
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
```
**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.</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>
<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>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_p0711356152317"><a name="zh-cn_topic_0000001152616261_p0711356152317"></a><a name="zh-cn_topic_0000001152616261_p0711356152317"></a>(Optional) Use asynchronous task delivery to asynchronously invoke the ACL interface. To enable this function, set it to **1** (recommended default setting).</p>
</td>
</tbody>
</table>
## Running the Unit Test Script
Verify the running. The output is **OK**.
```shell
// Select a test script that matches the preceding version. The following uses the 1.5.0 version as an example.
cd ../
python3 pytorch1.5.0/test/test_npu/test_network_ops/test_div.py
```
# (Optional) Installing the Mixed Precision Module
Select the APEX module based on the following functions. For details about how to build and install the APEX module, see the [README.en](https://gitee.com/ascend/apex/tree/v1.5.0-3.0.rc2).
- 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).
# Suggestions and Communication
We sincerely welcome you to join discussions in the community and contribute your suggestions. We will reply to you as soon as possible.
# Branch Maintenance Policies
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. |
# 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 | |
| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained <br> 2023-07-15 estimated | |
# FAQ
## 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 **libhccl.so** cannot be found by **import torch**.
Environment variables are not configured. You need to configure them using the **env.sh** script.
```
source pytorch/pytorch1.5.0/src/env.sh
```
## 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} indicates 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} indicates 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 commands:
```
./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
```
> ![img](figures/icon-notice.gif) **NOTE:**
>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++
```
5. Configure environment variables.
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}
```
**${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/**.
>![](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.
CentOS and EulerOS
```sh
yum -y install openblas
```
Ubuntu
```sh
apt install libopenblas-dev
```
## torchvision fails to be installed using pip in the Arm environment.
The source code can be used for installation. (You need to install the AscendPyTorch first and configure environment variables using **env.sh**.)
```
git clone -b v0.6.0 https://github.com/pytorch/vision.git
cd vision
python setup.py install
```
Verify that the torchvision is successfully installed.
```
python -c "import torchvision"
```
If no error is reported, the installation is successful.
# Release Notes
For details, see [Release Notes](docs/en/RELEASENOTE).
+60 -340
View File
@@ -1,90 +1,67 @@
# AscendPyTorch
<h1 id="简介md">简介</h1>
本项目开发了PyTorch Adapter插件,用于昇腾适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。用户在准备相关环境进行基于PyTorch框架模型的开发、运行时,可以选择在服务器中手动编译安装PyTorch框架相关模块。
# 项目简介
本项目开发了PyTorch Adapter插件,用于昇腾适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。
<h3 id="前提条件md">前提条件</h3>
# 编译/执行约束
gcc版本: 7.3.0(只在编译场景要求)
cmake版本:3.12.0以上版本(只在编译场景要求)
python版本:3.7.5 和 3.8.x(编译方法有差别,详见脚本编译章节)
- 需完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
- Python支持版本:3.7.5、3.8。
# 系统依赖库
## CentOS & EulerOS
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
yum install -y cmake zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas
## 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 -y gcc==7.3.0 cmake==3.12.0
>![](figures/icon-note.gif) **说明:**
>若安装gcc与cmake依赖命令报错,请参考FAQ使用源码安装。
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
# 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 |
| 3.0.rc3 | CANN 6.0.RC1 | 1.5.0.post7 | v1.5.0-3.0.rc3 |
| 3.0.rc3 | CANN 6.0.RC1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 |
| 3.0.rc3 | CANN 6.0.RC1 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 | \ |
| 3.0.0 | CANN 6.0.1 | 1.5.0.post8 | v1.5.0-3.0.0 | \ |
| 3.0.0 | CANN 6.0.1 | 1.8.1 | v1.8.1-3.0.0 | \ |
| 3.0.0 | CANN 6.0.1 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 | \ |
| AscendPyTorch版本 | CANN版本 |
| :------------ | :----------- |
| 2.0.2 | CANN 5.0.2 |
| 2.0.3 | CANN 5.0.3 |
# 安装方式
## 安装PyTorch依赖环境
获取适配昇腾AI处理器的PyTorch源代码(即当前仓库代码)。
```
git clone -b v1.5.0 https://gitee.com/ascend/pytorch.git
```
# 使用方式 --生成全量代码并编译
## 获取原生PyTorch源代码和third_party代码
在当前仓库根目录pytorch/下获取原生PyTorch1.5.0的源代码。请关注PyTorch原生社区的安全板块与Issue板块是否有安全相关问题修复,并根据社区修复及时更新原生PyTorch代码。
当前支持pytorch 1.5.0和1.8.1的版本。根据需求,在当前仓库根目录pytorch/下获取原生PyTorch的源代码
```sh
cd pytorch
// 1.5.0 版本
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
// 1.8.1 版本
git clone -b v1.8.1 --depth=1 https://github.com/pytorch/pytorch.git
```
进入到pytorch/pytorch/目录下, 获取PyTorch被动依赖代码(获取时间较长,请耐心等待)。
```sh
cd pytorch
git submodule sync
git submodule update --init --recursive
```
完成且没有报错之后就生成了PyTorch及其依赖的三方代码
## 生成适配昇腾AI处理器的PyTorch全量代码。
## 生成适配昇腾AI处理器的PyTorch代码。
进入到pytorch/scripts目录,根据选择的版本执行,执行脚本(注意:下载原生PyTorch源代码和下面版本要对应,否则可能出错)
进入到pytorch/scripts目录,根据选择的版本执行,执行脚本(注意:下载原生Pytorch源代码和下面版本要对应,否则可能出错)
```sh
cd ../scripts/
// 默认为1.5.0版本
bash gen.sh
// 对于1.8.1版本,则通过-v 参数指定
bash gen.sh -v 1.8.1
```
会在pytorch/pytorch/目录中生成npu适配全量代码
@@ -95,14 +72,13 @@ bash gen.sh
进入到pytorch/pytorch/目录,依赖库安装:
```python3
cd ../pytorch
pip3 install -r requirements.txt
```
## 编译torch的二进制包
在pytorch/pytorch/目录,执行
进入到pytorch/pytorch/目录,执行
```sh
# python3.7版本
@@ -116,14 +92,15 @@ bash build.sh --python=3.8
生成的二进制包在pytorch/pytorch/dist/目录下
## 安装pytorch
# 安装
### (以1.5.0版本为例,1.8.1版本同理)
**x86_64:**
torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl (实际可能附带小版本号例如torch-1.5.0.post2+ascend-cp37-cp37m-linux_x86_64.whl)
```shell
cd dist
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl
```
@@ -134,7 +111,6 @@ pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl
torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl (实际可能附带小版本号例如torch-1.5.0.post2+ascend-cp37-cp37m-linux_aarch64.whl)
```shell
cd dist
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl
```
@@ -144,75 +120,43 @@ pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl
## 运行环境变量
在pytorch/pytorch/中执行设置环境变量脚本
在当前仓库根目录中执行设置环境变量脚本
```
cd ../
source env.sh
source pytorch/env.sh
```
## 自定义环境变量
以下环境变量为NPU场景下使用的功能类或可以提升性能的环境变量:
```
export TASK_QUEUE_ENABLE=1 # 使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1
export PTCOPY_ENABLE=1 # 使用PTCopy算子模式,加速转连续及copy等过程,建议默认开启,开启设置为1
```
可选的环境变量可能会对运行的模型产生影响:
```
export COMBINED_ENABLE=1 # 非连续转连续二级推导优化,可选,开启设置为1。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升
export DYNAMIC_COMPILE_ENABLE=1 # 动态shape特性功能,针对shape变化场景,可选,开启设置为1
export COMBINED_ENABLE=1 # 非连续两个算子组合类场景优化,可选,开启设置为1
export TRI_COMBINED_ENABLE=1 # 非连续三个算子组合类场景优化,可选,开启设置为1
export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
export TASK_QUEUE_ENABLE=1 # 使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1
export DYNAMIC_OP="ADD#MUL" # 算子实现,ADD和MUL算子在不同场景下有不同的性能表现。可选
```
当系统为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>
</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。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升。</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>(可选)算子数据dump功能,调试时使用,开启设置为1。</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>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_p0711356152317"><a name="zh-cn_topic_0000001152616261_p0711356152317"></a><a name="zh-cn_topic_0000001152616261_p0711356152317"></a>(可选)使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1。 </p>
</td>
</tbody>
</table>
## 执行单元测试脚本
验证运行, 输出结果OK
```shell
// 根据前述版本,选择对应的测试脚本,以下为1.5.0版本
cd ../
python3 pytorch1.5.0/test/test_npu/test_network_ops/test_div.py
python3 pytorch1.5.0/test/test_npu/test_div.py
// 以下为1.8.1版本
python3 pytorch1.8.1/test/test_npu/test_div.py
```
# 安装混合精度模块(可选)
请用户根据以下功能需要选择使用,若需要安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex/tree/v1.5.0)进行编译安装Apex模块。
- APEX
- O1配置模式:Conv,Matmul等使用float16精度计算,其他如softmax、BN使用float32精度。
- O2配置模式:除BN使用float32精度外,其他部分使用float16精度。
- 静态loss scale:静态设置参数确保混合精度训练收敛。
- 动态loss scale:动态计算loss scale的值并判断是否溢出。
# 文档
@@ -238,261 +182,59 @@ Ascend PyTorch的版本分支有以下几种维护阶段:
| **分支名** | **当前状态** | **上线时间** | **后续状态** | **EOL 日期**|
|------------|--------------|----------------------|----------------------------------------|------------|
| **v2.0.2** | EOL | 2021-07-29 | N/A | |
| **v2.0.3** | EOL | 2021-10-15 | N/A | |
| **v2.0.4** | Unmaintained | 2022-01-15 | EOL <br> 2023-04-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 | |
| **v3.0.rc3** | Maintained | 2022-10-20 | Unmaintained <br> 2023-10-20 estimated | |
| **v3.0.0** | Maintained | 2023-1-20 | Unmaintained <br> 2024-1-20 estimated | |
| **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 | |
# FAQ
## 在PIP设置为华为源时,安装requirments.txt中的typing依赖后,会导致python环境错误。
在PIP设置为华为源时,需打开requirments.txt文件,删除typing依赖,再执行命令。
```
pip3 install -r requirments.txt
```
## import torch 报找不到libhccl.so错误
未配置环境变量,需通过env.sh脚本配置
```
source pytorch/pytorch1.5.0/src/env.sh
```
## 编译过程执行bash build.sh报错FAILED:confu-deps/XNNPACK/CMakefiles/XNNPACK.dir/src/f32-gemm/gen-inc/4x8inc-minmax-{arch}-neonfma-cortex-a{xx}.S.o
编译前,环境变量默认USE_XNNPACK=1,编译时会报错,需设置重设该环境变量,再次编译。
1. 重设环境变量
```
export USE_XNNPACK=0
```
2. 清除编译缓存
```
make clean
```
3. 重新编译
```
bash build.sh --python={python_version}
```
## 编译过程执行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-toolkit/latest/fwkacllib/lib64
用户态:
```
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 #{arch}为架构名称
cd /urs/local/nnae/latest/fwkacllib/lib64
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。(参考cmake官网)
cmake官网下载linux版本安装(当前3.18.0)
​ X86_64环境脚本安装:cmake-3.12.0-Linux-x86_64.sh
1. 使用yum命令安装: yum install -y cmake==3.18.0
​ aarch64环境脚本安装:cmake-3.12.0-Linux-aarch64.sh
2. 下载cmake sh脚本安装:(参考cmake官网)
1. 执行命令。
X86_64环境推荐脚本安装: cmake-3.18.2-Linux-x86_64.sh
```
./cmake-3.12.0-Linux-{arch}.sh #{arch}为架构名称
```
2. 设置软连接。
## GCC版本问题切换问题
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
目前存在测试环境从GCC4.8.5 切换到 GCC7.3.0。这个过程容易出现错误导致pytorch编译不过,以下是需要软连接的库
3. 执行如下命令验证是否安装成功。
```
cmake --version
```
如显示“cmake version 3.12.0”则表示安装成功。
方法二:使用源码编译安装。
1. 获取Cmake软件包。
```
wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
```
2. 解压并进入软件包目录。
```
tar -xf cmake-3.12.0.tar.gz
cd cmake-3.12.0/
```
3. 执行配置、编译和安装命令。
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. 设置软连接。
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. 执行如下命令验证是否安装成功。
```
cmake --version
```
如显示“cmake version 3.12.0”则表示安装成功。
## 命令行安装gcc依赖时提示找不到包、编译时gcc报错问题
部分源下载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目录:
```
sudo rm -rf /tmp/*
```
3. 安装依赖(以CentOS和Ubuntu系统为例)。
- CentOS执行如下命令安装。
```
yum install bzip2
```
- Ubuntu执行如下命令安装。
```
apt-get install bzip2
```
4. 编译安装gcc。
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
```
tar -zxvf gcc-7.3.0.tar.gz
```
2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
```
cd gcc-7.3.0
./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
```
下载好上述依赖包后,重新执行以下命令:
```
./contrib/download_prerequisites
```
如果命令校验失败,需要确认上述依赖包在文件夹中的唯一性,无重复下载,若存在重复的依赖包,需删除。
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
```
> ![img](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}/gcc-7.3.0/bin/gcc /usr/bin/gcc
ln -s ${install_path}/gcc-7.3.0/bin/g++ /usr/bin/g++
ln -s ${install_path}/gcc-7.3.0/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/gcc7.3.0/“。
>![](figures/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
若存在pytorch编译不过,请检查软连接的库是否正确。
gcc, g++,c++(--version 必须是7.3.0)
libstdc++->libstdc++.so.6.0.24(7.3.0)
## 找不到libblas.so问题
环境缺少openblas库,需要安装openblas库
@@ -509,28 +251,6 @@ Ubuntu环境
apt install libopenblas-dev
```
## ARM环境pip安装torchvision失败
可采用源码安装(需先安装昇腾pytorch并通过env.sh配置环境变量)
```
git clone -b v0.6.0 https://github.com/pytorch/vision.git
cd vision
python setup.py install
```
验证torchvision是否安装成功
```
python -c "import torchvision"
```
若不报错,则说明安装成功
# 版本说明
版本说明请参阅[ReleseNote](docs/zh/RELEASENOTE)
@@ -1,900 +0,0 @@
# Overview
Users can obtain PyTorch training models from Ascend ModelZoo, but the models do not support multi-server multi-device training. You need to modify the models based on the actual model code. This document describes how to quickly train a PyTorch model in Distributed Data Parallel (DDP) mode in multi-server multi-device scenario.
# Training Workflow
The process of training a PyTorch model in multi-server multi-device scenario includes environment preparation, model preparation, model modification, and training startup.
1. Environment Preparation
Prepare the software, hardware, and network environment for multi-server multi-device training, including setting up the development and operating environment, connecting the cluster network, setting the processor IP address, and setting the firewall.
2. Model Preparation
Prepare a PyTorch model, data loader, and optimizer for training. You can download them from the open source community (https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch) or prepare them by yourself.
3. Model Modification
Modify the basic model and add the code and environment variables required by DDP to enable the multi-server multi-device training.
4. Training Startup
Start model training in the multi-server multi-device scenario and view training logs.
# Quick Start
## Overview
The example presented in this document helps you quickly understand how a PyTorch model is trained in multi-server multi-device scenario. The example uses a custom model for training in two-computer eight-device scenario. The two computers are named AI Server0 and AI Server1. The eight Ascend 910 Processors on each computer are named device0 to device7.
## Preparing the Environment
At least two computers with Ascend 910 Processors installed are required, and the NPU firmware and driver are correctly installed on each computer.
1. Prepare the development and operating environment on each computer.
- Install the CANN development and operating environment. For details, see the *CANN Software Installation Guide*. Use CANN later than 5.0.3.
- Install the PyTorch that adapts to NPU. For details, see the *PyTorch Installation Guide*.
2. Prepare the network.
Set up the network by directly connecting switches or optical ports. For details, see the *Ascend Data Center Solution Networking Guide* at https://support.huawei.com/enterprise/en/doc/EDOC1100221995/229cc0e4.
In this example, two computers with eight devices are used for training, so optical ports are used for network connection.
3. Configure the device IP address.
Configure the device IP address on AI Server0.
```shell
hccn_tool -i 0 -ip -s address 192.168.100.101 netmask 255.255.255.0
hccn_tool -i 1 -ip -s address 192.168.101.101 netmask 255.255.255.0
hccn_tool -i 2 -ip -s address 192.168.102.101 netmask 255.255.255.0
hccn_tool -i 3 -ip -s address 192.168.103.101 netmask 255.255.255.0
hccn_tool -i 4 -ip -s address 192.168.100.100 netmask 255.255.255.0
hccn_tool -i 5 -ip -s address 192.168.101.100 netmask 255.255.255.0
hccn_tool -i 6 -ip -s address 192.168.102.100 netmask 255.255.255.0
hccn_tool -i 7 -ip -s address 192.168.103.100 netmask 255.255.255.0
```
Configure the device IP address on AI Server1.
```shell
hccn_tool -i 0 -ip -s address 192.168.100.111 netmask 255.255.255.0
hccn_tool -i 1 -ip -s address 192.168.101.111 netmask 255.255.255.0
hccn_tool -i 2 -ip -s address 192.168.102.111 netmask 255.255.255.0
hccn_tool -i 3 -ip -s address 192.168.103.111 netmask 255.255.255.0
hccn_tool -i 4 -ip -s address 192.168.100.110 netmask 255.255.255.0
hccn_tool -i 5 -ip -s address 192.168.101.110 netmask 255.255.255.0
hccn_tool -i 6 -ip -s address 192.168.102.110 netmask 255.255.255.0
hccn_tool -i 7 -ip -s address 192.168.103.110 netmask 255.255.255.0
```
4. Configure the firewall.
- Command for disabling the firewall on Ubuntu:
```shell
ufw disable
```
```
- Command for disabling the firewall on Red Hat or CentOS 7:
```shell
systemctl stop firewalld
```
## Preparing a Model
This example creates a simple model for you to quickly understand multi-server multi-device training. You can also obtain the Ascend NPU-based PyTorch training model from the open source community (https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch).
1. Prepare a DDP model.
The following is an example of main.py for multi-server multi-device training.
```python
import argparse
import os
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
### 1. Perform basic operations. ###
# Build a model.
class ToyModel(nn.Module):
def __init__(self):
super(ToyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Obtain a dataset.
def get_dataset():
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
train_sampler = torch.utils.data.distributed.DistributedSampler(my_trainset)
trainloader = torch.utils.data.DataLoader(my_trainset,
batch_size=16, num_workers=2, sampler=train_sampler)
return trainloader
### 2. Initialize the parameters, data, model, loss function, and optimizer. ####
# Obtain local_rank and addr.
parser = argparse.ArgumentParser()
parser.add_argument("--local_rank", default=-1, type=int)
parser.add_argument("--addr", default='127.0.0.1', type=str, help='master addr')
FLAGS = parser.parse_args()
local_rank = FLAGS.local_rank
addr = FLAGS.addr
# Set the IP address and port of the master node.
os.environ['MASTER_ADDR'] = addr
os.environ['MASTER_PORT'] = '29501'
# Initialize the DDP backend.
loc = 'npu:{}'.format(local_rank)
torch.npu.set_device(loc)
dist.init_process_group(backend='hccl') # HCCL is the backend of the NPU device.
# Prepare data after DDP initialization.
trainloader = get_dataset()
# Instantiate the model.
model = ToyModel().to(loc)
# Load the model weight. The weight needs to be loaded only on the master node before the DDP model is built.
ckpt_path = None
if dist.get_rank() == 0 and ckpt_path is not None:
model.load_state_dict(torch.load(ckpt_path))
# Build the DDP model.
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
# Initialize the optimizer. After the DDP model is built, use the model to initialize the optimizer.
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# Initialize the loss function.
loss_func = nn.CrossEntropyLoss().to(loc)
### 3. Train the network.
model.train()
iterator = range(100)
for epoch in iterator:
trainloader.sampler.set_epoch(epoch)
for data, label in trainloader:
data, label = data.to(local_rank), label.to(local_rank)
optimizer.zero_grad()
prediction = model(data)
loss = loss_func(prediction, label)
loss.backward()
print("loss = %0.3f \n" % loss)
optimizer.step()
# 1. Similar to the DP mode, when you save a model, note that model.module instead of model is saved.
# That is because the model actually refers to a DDP model, and the parameters are packaged by `model=DDP(model)`.
# 2. You only need to save the model on process 0 once to avoid repeated saving.
if dist.get_rank() == 0:
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
```
2. Ensure that the model is correct for training in the single-server multi-device scenario.
1. The Python third-party library is required if you install the model script yourself.
2. Configure NPU environment variables. For information about the **env_npu.sh** script, see the appendix.
```shell
source env_npu.sh
```
3. Execute **torch.distributed.launch** to run the following main.py command to train a model in single-server multi-device scenario.
```shell
python -m torch.distributed.launch --nproc_per_node 8 main.py
```
`--nproc_per_node` indicates the number of training cards.
After the command is run successfully, the model is trained on the eight NPUs of the device.
## Modifying the Model
The example provided in "Quick Start" is adapted to the multi-server multi-device training. You do not need to modify the script. For details about how to modify other models, see section "Multi-server Multi-device Training".
## Starting the Training
1. Upload main.py model script to any directory on AI Server0 and AI Server1.
2. Query the host IP addresses of the servers.
```shell
hostname -I
```
All IP addresses are displayed, and the first IP address is the host IP address of the current server.
For example, the host IP address of AI Server0 is **192.168.*xx*.22**, and that of AI Server1 is **192.168.*xx*.23**.
3. Use AI Server0 as the master node, and start the 2 x 8 cluster.
Startup commands for AI Server0:
```shell
# Set environment variables. Obtain the env_npu.sh script content from the appendix.
source env_npu.sh
# Disable the trustlist of HCCL channel.
export HCCL_WHITELIST_DISABLE=1
# Initialize the IP address of the HCCL communication NIC, and set the IP address to the host IP address of the current server.
export HCCL_IF_IP=192.168.xx.22
#
python3.7 -m torch.distributed.launch --nnodes=2 --node_rank=0 --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
```
Startup commands for AI Server1:
```shell
# Set environment variables. Obtain the env_npu.sh script content from the appendix.
source env_npu.sh
# Disable the trustlist of HCCL channel.
export HCCL_WHITELIST_DISABLE=1
# Initialize the IP address of the HCCL communication NIC, and set the IP address to the host IP address of the current server.
export HCCL_IF_IP=192.168.xx.23
python3.7 -m torch.distributed.launch --nnodes=2 --node_rank=1 --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
```
Parameter description:
--nnode: specifies the number of nodes used for distributed training scripts.
--node_rank: specifies the rank of the current node during multi-node distributed training.
--nproc_per_node: specifies the number of GPU-based training processes on the current node.
--master_addr: address of the master node (rank is 0). The value can be the IP address or the host name of node 0.
--master_port: specifies the port number used by the master node during distributed training.
--addr: input parameter of the main.py script, specifying the host IP address of the master node.
3. View the host logs.
Host logs are stored in the `~/ascend/log` directory. You can go to this directory to view the device logs of each host.
# Multi-server Multi-device Training
## Common Concepts and Parameters
Basic concepts for PyTorch distributed training
| Basic Concept | Description |
| :-----------: | ------------------------------------------------------------ |
| AI Server | Computer with an Ascend 910 Processors. Multiple computers are identified as AI Server +serial number, for example, AI Server0 and AI Server1. |
| device | Ascend 910 Processors on the AI server. Multiple processors are represented as device 0, device 1, ..., and device 7. |
| host | AI server host. |
| master | Select one of multiple AI servers as the master node for data communication. |
| group | Process group. By default, there is only one group. Use the default value. |
| world size | Number of global parallel processes, which can be obtained by running **torch.distributed.get_world_size()**. The value is the same for different processes. |
| rank | Sequence number of the current process, which is used for communication between processes. For example, for a 2 x 8 cluster, the **world size** is 16, and the rank in each process is [0, 1, 2, ..., 15]. |
| local_rank | Sequence number of processes on each host, for example, there are processes 0-7 on each host. Generally, **local_rank** is used to set the GPU/NPU on which the current model runs. |
Parameters for executing **torch.distributed.launch** to start multi-device training
| Parameter | Description |
| ------------------ | ------------------------------------------------------------ |
| **nnodes** | Specifies the number of nodes used for distributed training scripts. |
| **node_rank** | Specifies the rank of the current node during multi-node distributed training. |
| **nproc_per_node** | Specifies the number of GPU-based training processes on the current node. You are advised to set this parameter to the number of GPUs on the current node. In this way, each process can independently control a GPU to achieve the highest efficiency. |
| **master_addr** | Address of the master node (rank is 0). The value can be the IP address or the host name of node 0. For single-node multi-process training, set this parameter to **127.0.0.1**. |
| **master_port**: | Specifies the port number used by the master node during distributed training. The port number must be different from the port numbers of other applications. |
## Multi-server Multi-device Training Process
### Preparing the Environment
At least two computers with Ascend 910 Processors installed are required, and the NPU firmware and driver are correctly installed on each server.
1. Prepare the development and operating environment on each computer.
- Install the CANN development and operating environment. For details, see the *CANN Software Installation Guide*. Use CANN later than 5.0.3.
- Install the PyTorch that adapts to NPU. For details, see the *PyTorch Installation Guide.*
2. Prepare the network.
Cluster training is completed by multiple computers (a maximum of 128) with Ascend 910 Processors installed. The computers need to work with switches to form a fully-connected active/standby network on the data plane. The 8 x *n*-device training is supported. Two computers can be directly connected through optical ports. For details, see the *Ascend Data Center Solution Networking Guide * at https://support.huawei.com/enterprise/en/doc/EDOC1100221995/229cc0e4.
3. Configure the device IP address.
Use hccn_tool to configure the device IP address. hccn_tool is provided by CANN.
```shell
hccn_tool -i 0 -ip -s address 192.168.100.111 netmask 255.255.255.0
```
Observe the following rules when configuring the device IP address:
1. On the AI servers, devices 0/4, 1/5, 2/6, and 3/7 must be in the same network segment. But devices 0, 1, 2, and 3 must be in different network segments, and devices 4, 5, 6, and 7 must be in different network segments.
2. In the cluster scenario, the devices corresponding to each AI server must be in the same network segment. NICs 0 and 1 of AI Server0 and AI Server1 must be in the same network segment.
3. Each IP address must be unique. IP addresses in the same network segment must be distinguished by the last eight bits.
Use hccn_tool to check whether the device IP address is correct.
- Query the IP address of each device.
```shell
hccn_tool -i 0 -ip –g
```
The IP addresses are displayed:
> ipaddr:192.168.100.101
>
> netmask:255.255.255.0
- Use hccn_tool to ensure that the devices of the two hosts are correctly connected by performing the test for eight times from device0 to devcie7.
```shell
hccn_tool -i 0 -netdetect -s address xx.xx.xx.xx
hccn_tool -i 0 -net_health –g
```
**-i**: device ID.
**-s address**: ***xx.xx.xx.xx*** is the IP address of device *i* on the other host.
If `success` is returned, the connection is successful.
4. Configure the firewall.
During HCCL communication, the firewall may intercept the communication port, causing communication timeout. Therefore, you need to disable the firewall on the server for PyTorch cluster training.
- Command for disabling the firewall on Ubuntu:
```shell
ufw disable
```
- Command for disabling the firewall on Red Hat or CentOS 7:
```shell
systemctl stop firewalld
```
### Preparing a Model
There are two methods for preparing a model.
- Download a PyTorch training model from the open source community (https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch).
The model obtained from the open source community supports single-server multi-device training. Modify the model based on the related parameters described in section "Modifying the Model".
- Manually build a PyTorch training model.
1. Prepare a PyTorch training model and data loader.
Prepare a PyTorch model:
```python
class ToyModel(nn.Module):
def __init__(self):
...
def forward(self,x):
...
```
Prepare data:
```python
def get_dataset():
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(my_trainset,batch_size=16,)
return trainloader
trainloader=get_dataset()
```
2. Instantiate the model.
```python
# Instantiate the model.
model = ToyModel().to(loc)
# Load the model weight
if ckpt_path is not None:
model.load_state_dict(torch.load(ckpt_path))
```
3. Prepare the loss function and optimizer.
```python
# Initialize the optimizer. After the DDP model is built, use the model to initialize the optimizer.
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# Initialize the loss function.
loss_func = nn.CrossEntropyLoss().to(loc)
```
4. Train the model.
```python
### 3. Train the network.
model.train()
iterator = range(100)
for epoch in iterator:
for data, label in trainloader:
data, label = data.to(local_rank), label.to(local_rank)
optimizer.zero_grad()
prediction = model(data)
loss = loss_func(prediction, label)
loss.backward()
print("loss = %0.3f \n" % loss)
optimizer.step()
torch.save(model.state_dict(), "%d.ckpt" % epoch)
```
### Modifying the Model
Modify the IP address and port of the master node, initialize the **distributed ** function, model DDP, data DDP, and optimizer, and modify the DDP model training method based on the initial model code.
1. Set the IP address and port for the master node. In the NPU distributed training, HCCL is used for communication, while in PyTorch, the HCCL communication mechanism that is detected by automatic topology is used. That is, **RANK_TABLE_FLIE** is not required, but the communication depends on the NIC on the host side. Therefore, you need to set environment variables in the code to set the communication NIC.
```python
os.environ['MASTER_ADDR'] = xxx.xxx.xxx.xxx
os.environ['MASTER_PORT'] = 'xxx'
```
**MASTER_ADDR**: Set this parameter to the IP address of the master node in the cluster. (Select any host as the master node.)
**MASTER_PORT**: Set this parameter to the idle port of the master node.
In the model code, the IP address and port number of the master node are generally presented as transferred parameters. In some open-source code, the IP address and port number may be presented as **127.0.0.1**. In this case, you need to modify them.
The preceding variables must be declared before **torch.distributed.init_process_group()** is invoked.
2. Initialize **distributed**.
In PyTorch, `dist.init_process_group(backend='hccl', world_size=world_size, rank=rank)` is used to initialize thread groups. The parameters are described as follows:
`backend`: communication protocol used for distributed training. Only hccl can be used on the NPU.
`world_size`: total number of devices used for training.
`rank`: rank ID of the currently initialized device, that is, the global logical ID.
There are two methods to start multi-device training:
- **torch.distributed.launch**:
```python
import torch.distributed as dist
dist.init_process_group(backend='hccl') # HCCL is the backend of the NPU device.
```
- **mp.spawn**:
```python
import torch.distributed as dist
def main_worker(pid_idx, device_nums_per_node, args):
args.distributed_rank = args.rank * device_nums_per_node + pid_idx
dist.init_process_group(backend=args.dist_backend, world_size=args.distributed_world_size, rank=args.distributed_rank)
```
In the preceding commands:
`pid_idx`: device ID.
`device_nums_per_node`: number of devices on each AI server.
3. Initialize the model DDP.
```python
# Instantiate the model.
model = ToyModel().to(loc)
# Load the model weight. It needs to be loaded only on the master node before the DDP model is built.
if dist.get_rank() == 0 and ckpt_path is not None:
model.load_state_dict(torch.load(ckpt_path))
# Build the DDP model.
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
```
4. Initialize the data DDP.
```python
def get_dataset():
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
train_sampler = torch.utils.data.distributed.DistributedSampler(my_trainset)
trainloader = torch.utils.data.DataLoader(my_trainset,
batch_size=16, num_workers=2, sampler=train_sampler)
return trainloader
trainloader = get_dataset()
```
5. Initialize the loss function and optimizer.
```python
# Initialize the optimizer. After the DDP model is built, use the model to initialize the optimizer.
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# Initialize the loss function.
loss_func = nn.CrossEntropyLoss().to(loc)
```
6. Train the DDP model.
```python
model.train()
iterator = range(100)
for epoch in iterator:
# Set epoch.
trainloader.sampler.set_epoch(epoch)
for data, label in trainloader:
data, label = data.to(local_rank), label.to(local_rank)
optimizer.zero_grad()
prediction = model(data)
loss = loss_func(prediction, label)
loss.backward()
print("loss = %0.3f \n" % loss)
optimizer.step()
# 1. Similar to the DP mode, when you save a model, note that model.module instead of model is saved.
# That is because the model actually refers to a DDP model, and the parameters are packaged by `model=DDP(model)`.
# 2. You only need to save the model on process 0 once to avoid repeated saving.
if dist.get_rank() == 0:
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
```
### Start the Training
The training can be started manually or using the shell script.
- Start the training manually using **torch.distributed.launch**.
1. Configure NPU environment variables. For details, see the **env_npu.sh** script in the appendix.
2. Add environment variables. For multi-server training, add the `HCCL_WHITELIST_DISABLE` and `HCCL_IF_IP` environment variables.
- **HCCL_WHITELIST_DISABLE**: HCCL channel trustlist. The value **1** indicates that the trustlist is disabled.
- **HCCL_IF_IP**: initialized IP address of the HCCL communication NIC. Set it to the IP address of the host NIC IP of the current server.
3. Upload the modified model script to each AI server.
4. Install the required Python library on each AI server.
5. Select an AI server as the master node and query the IP address of each AI server.
6. Run the following commands on each AI server:
```
python3 -m torch.distributed.launch --nnodes=${nnodes} --node_rank=i --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
```
In the preceding commands:
**--nnodes**: number of AI servers used for distributed training scripts.
**--node_rank**: AI server ID.
**--nproc_per_node**: number of devices of each AI server.
**--master_addr**: IP address of the AI server that functions as the master node.
**--master_port**: port number of the AI server that functions as the master node.
**main.py**: Change it to the name of the startup script.
**--addr**: indicates the IP address of the master node, which is a parameter transferred to the startup script.
- Start the training using Open MPI.
1. Install the PI open-source library.
In the multi-server multi-device scenario, distributed training deployment depends on the Open MPI open-source library, which must be installed on each server that participates in model training. Currently, Open MPI 4.0.1, 4.0.2, or 4.0.3 is required.
Run the **mpirun --version** command to check whether Open MPI has been installed. If `mpirun (Open MPI) 4.0.2 Report bugs to http://www.open-mpi.org/community/help/` is returned, Open MPI has been installed. If it has been installed and its version is 4.0.1, 4.0.2, or 4.0.3, you do not need to install it again.
Otherwise, perform the following steps to install it
1. Visit the following link to download the Open MPI software package, for example, openmpi-4.0.2.tar.bz2.
https://www.open-mpi.org/software/ompi/v4.0/
2. Log in to the installation environment as the root user.
3. Upload the downloaded Open MPI software package to a directory in the installation environment.
4. Go to the directory and run the following command to decompress the software package:
```shell
tar -jxvf openmpi-4.0.2.tar.bz2
```
5. Go to the directory generated after the decompression, and run the following commands to configure, compile, and install Open MPI:
```shell
./configure --prefix=/usr/local/mpirun4.0.2
make
make install
```
The **--prefix** parameter specifies the Open MPI installation path. Change it based on the site requirements.
6. Run the **vi ~/.bashrc** command to open the **.bashrc** file, and add the following environment variables to the end of the file:
```shell
export OPENMPI=/usr/local/mpirun4.0.2
export LD_LIBRARY_PATH=$OPENMPI/lib
export PATH=$OPENMPI/bin:$PATH
```
In the environment variables, **/usr/local/mpirun4.0.2** indicates the Open MPI installation path. Change it based on the site requirements.
Run the **:wq!** command to save the file and exit.
7. Make the configuration take effect.
```
source ~/.bashrc
```
8. After the installation is complete, run the following command to check the installation version. If the required version information is displayed, the installation is successful.
```
mpirun --version
```
2. Configure SSH password-free login for the AI servers.
If Open MPI is used for distributed training deployment in the multi-server multi-device scenario, you need to configure SSH password-free login between every two servers to ensure that the servers can communicate with each other. The procedure is as follows:
1. Log in to each server as the root user.
2. Configure the reliability among hosts in the cluster.
Open the **/etc/ssh/ssh_config** file and add the following fields to the end of the file:
```
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
```
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:
```
xxx.xxx.xxx.111 ubuntu
```
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 **xxx.xxx.xxx.111**.):
```
cd ~/.ssh/ # If the directory does not exist, run the ssh localhost command first.
ssh-keygen -t rsa # After the key is generated, a message is displayed. Press Enter for three consecutive times.
mv id_rsa.pub authorized_keys # Renames the generated key id_rsa.pub to authorized_keys.
```
5. Generate a key on each of the other servers, and copy the keys to the **authorized_keys** file on the first server.
1. Run the following commands on each of the other servers to generate a key:
cd ~/.ssh/
ssh-keygen -t rsa
2. Download the key file **id_rsa.pub** generated on each server to the local host and copy the key in the file.
3. On the first server, run the following command to open the authorized_keys file and copy the keys of each of other servers to the end of the public key of the first server.
```
vi ~/.ssh/authorized_keys
```
Run the **:wq!** command to save the file.
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@xxx.xxx.xxx.111:~/.ssh/authorized_keys ./
7. Run the following command on each server to test password-free login:
```
ssh User name@IP address
```
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.
```
Linux ubuntu 4.19.28 #1 SMP Tue Jun 23 19:05:23 EDT 2020 x86_64
The programs included with the ubuntu GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
ubuntu GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Tue Sep 15 14:37:21 2020 from 10.254.88.75
```
You can run the **exit** command to log out of the server. If information similar to the following is displayed, the logout is successful.
```
logout
Connection to xxx.xxx.xxx.222 closed.
```
3. Use Open MPI to start model training.
1. Compile a startup script for each AI server, for example, train.sh, and move the startup script to the same path of the corresponding AI server.
```
# Configure NPU environment variables. For information about the env_npu.sh script, see the appendix.
source env_npu.sh
#Disable the trustlist of HCCL channel.
export HCCL_WHITELIST_DISABLE=1
# Initialize the IP address of the HCCL communication NIC , and set the IP address to the host IP address of the current server.
export HCCL_IF_IP=xxx.xxx.xx.xxx
python3 -m torch.distributed.launch --nnodes=${nnodes} --node_rank=i --nproc_per_node 8 --master_addr xxx.xxx.xx.xxx --master_port 29501 main.py --addr xxx.xxx.xx.xxx
```
For details about the script parameters, see section "Start the training manually using **torch.distributed.launch**".
2. Compile the startup script.
```
# Configuring the mpirun environment variables.
export PATH=$PATH:/usr/local/mpirun4.0.2/bin
# Run the mpirun tool.
mpirun -H xxx.xxx.xxx.xxx:1,xxx.xxx.xxx.xxx:1 \
--bind-to none -map-by slot \
--mca btl_tcp_if_exclude lo,docker0,endvnic\
--allow-run-as-root \
--prefix /usr/local/mpirun4.0.2/ \
./train.sh
```
In the preceding command:
**-H**: IP address of each AI server and the number of started processes.
**--bind-to**: process-binding policy.
**--mca**: MCA parameter in a specific context. **arg0** is the parameter name, and **arg1** is the parameter value.
**--allow-run-as-root**: The root user is allowed to run this script.
**--prefix**: path of mpirun4.0.2.
**./train.sh**: path of the startup script of each AI server.
4. View the log information after the training succeeds.
Host logs are stored in the `~/ascend/log` directory. You can go to this directory to view the device logs of each host.
# Appendix
The following shows the NPU environment variable configuration script **env_npu.sh**, which can be used to configure the operating and development environment variables.
```shell
#!/bin/bash
export install_path=/usr/local/Ascend
if [ -d ${install_path}/toolkit ]; then
export LD_LIBRARY_PATH=/usr/include/hdf5/lib/:/usr/local/:/usr/local/lib/:/usr/lib/:${install_path}/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons:${path_lib}:${LD_LIBRARY_PATH}
export PATH=${install_path}/fwkacllib/ccec_compiler/bin:${install_path}/fwkacllib/bin:$PATH
export PYTHONPATH=${install_path}/fwkacllib/python/site-packages:${install_path}/tfplugin/python/site-packages:${install_path}/toolkit/python/site-packages:$PYTHONPATH
export PYTHONPATH=/usr/local/python3.7.5/lib/python3.7/site-packages:$PYTHONPATH
export ASCEND_OPP_PATH=${install_path}/opp
else
if [ -d ${install_path}/nnae/latest ];then
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
export PYTHONPATH=${install_path}/nnae/latest/fwkacllib/python/site-packages/:${install_path}/nnae/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:${install_path}/nnae/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
export ASCEND_AICPU_PATH=${install_path}/nnae/latest
else
export LD_LIBRARY_PATH=/usr/local/:/usr/local/lib/:/usr/lib64/:/usr/lib/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64-linux-gnu:$LD_LIBRARY_PATH
export PATH=$PATH:${install_path}/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin/:${install_path}/ascend-toolkit/latest/toolkit/tools/ide_daemon/bin/
export ASCEND_OPP_PATH=${install_path}/ascend-toolkit/latest/opp/
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
export PYTHONPATH=${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/:${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
export ASCEND_AICPU_PATH=${install_path}/ascend-toolkit/latest
fi
fi
#Output host logs to the serial port. 0: disable; 1: enable.
export ASCEND_SLOG_PRINT_TO_STDOUT=0
#Set the default log level. 0: debug; 1: info; 2: warning; 3: error.
export ASCEND_GLOBAL_LOG_LEVEL=3
#Enable or disable the event log. 0: disable; 1: enable.
export ASCEND_GLOBAL_EVENT_ENABLE=0
#Enable or disable taskque. 0: disable; 1: enable.
export TASK_QUEUE_ENABLE=1
#Enable or disable the HCCL trustlist. 1: disable; 0: enable.
export HCCL_WHITELIST_DISABLE=1
#Set the device-side log to error.
${install_path}/driver/tools/msnpureport -g error -d 0
${install_path}/driver/tools/msnpureport -g error -d 1
${install_path}/driver/tools/msnpureport -g error -d 2
${install_path}/driver/tools/msnpureport -g error -d 3
${install_path}/driver/tools/msnpureport -g error -d 4
${install_path}/driver/tools/msnpureport -g error -d 5
${install_path}/driver/tools/msnpureport -g error -d 6
${install_path}/driver/tools/msnpureport -g error -d 7
#Disable the event log on the device side.
${install_path}/driver/tools/msnpureport -e disable
path_lib=$(python3.7 -c """
import sys
import re
result=''
for index in range(len(sys.path)):
match_sit = re.search('-packages', sys.path[index])
if match_sit is not None:
match_lib = re.search('lib', sys.path[index])
if match_lib is not None:
end=match_lib.span()[1]
result += sys.path[index][0:end] + ':'
result+=sys.path[index] + '/torch/lib:'
print(result)"""
)
echo ${path_lib}
export LD_LIBRARY_PATH=/usr/local/python3.7.5/lib/:${path_lib}:$LD_LIBRARY_PATH
```
File diff suppressed because it is too large Load Diff

Before

Width:  |  Height:  |  Size: 580 B

After

Width:  |  Height:  |  Size: 580 B

Before

Width:  |  Height:  |  Size: 580 B

After

Width:  |  Height:  |  Size: 580 B

Before

Width:  |  Height:  |  Size: 394 B

After

Width:  |  Height:  |  Size: 394 B

Before

Width:  |  Height:  |  Size: 406 B

After

Width:  |  Height:  |  Size: 406 B

Before

Width:  |  Height:  |  Size: 253 B

After

Width:  |  Height:  |  Size: 253 B

Before

Width:  |  Height:  |  Size: 580 B

After

Width:  |  Height:  |  Size: 580 B

File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
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

@@ -1,486 +1,555 @@
# PyTorch Installation Guide
- [Overview](#overview)
- [Overview](#overview.md)
- [Manual Build and Installation](#manual-build-and-installation.md)
- [Prerequisites](#prerequisites.md)
- [Installing the PyTorch Framework](#installing-the-pytorch-framework.md)
- [Configuring Environment Variables](#configuring-environment-variables.md)
- [Installing the Mixed Precision Module](#installing-the-mixed-precision-module.md)
- [References](#references.md)
- [Installing CMake](#installing-cmake.md)
- [How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-7-3-0.md)
- [What Do I Do If "torch 1.5.0xxxx" and "torchvision" Do Not Match When torch-\*.whl Is Installed?](#what-do-i-do-if-torch-1-5-0xxxx-and-torchvision-do-not-match-when-torch--whl-is-installed.md)
<h2 id="overview.md">Overview</h2>
- [System Dependencies](#system-dependencies)
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.
- [Ascend Auxiliary Software](#ascend-auxiliary-software)
**Figure 1** Environment setup process<a name="en-us_topic_0000001119176876_fig1938918396117"></a>
- [Installation Methods](#installation-methods)
- [Running] (#running)
![](figures/210926103326800.png)
- [(Optional) Installing the Mixed Precision Module](#optional-installing-the-mixed-precision-module)
<h2 id="manual-build-and-installation.md">Manual Build and Installation</h2>
- [FAQ](#faq)
- **[Prerequisites](#prerequisites.md)**
- [Release Notes](#release-notes)
- **[Installing the PyTorch Framework](#installing-the-pytorch-framework.md)**
- **[Configuring Environment Variables](#configuring-environment-variables.md)**
# Overview<a name="Overview"></a>
- **[Installing the Mixed Precision Module](#installing-the-mixed-precision-module.md)**
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 environment for model development and running under PyTorch, you can manually build and install modules adapted to the PyTorch framework on a server.
## Prerequisites
<h2 id="prerequisites.md">Prerequisites</h2>
- The development or operating environment of CANN has been installed. For details, see the *CANN Software Installation Guide*.
- Python version: 3.7.5 or 3.8
## Prerequisites<a name="en-us_topic_0000001105856382_en-us_topic_0275872734_section108914373254"></a>
# System Dependencies<a name="System Dependencies"></a>
- The development or operating environment of CANN has been installed. For details, see the _CANN Software Installation Guide_.
- CMake 3.12.0 or later has been installed. For details about how to install CMake, see [Installing CMake](#installing-cmake.md).
- 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-7-3-0.md).
- Python 3.7.5 or 3.8 has been installed.
- The Patch and Git tools have been installed in the environment. To install the tools for Ubuntu and CentOS, run the following commands:
- Ubuntu
## CentOS & EulerOS
```
apt-get install patch
apt-get install git
```
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
- CentOS
yum install -y gcc==7.3.0 cmake==3.12.0
```
yum install patch
yum install git
```
## 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 -y gcc==7.3.0 cmake==3.12.0
<h2 id="installing-the-pytorch-framework.md">Installing the PyTorch Framework</h2>
## Installation Process<a name="en-us_topic_0000001152776301_section1611810384557"></a>
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.
>![](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.
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
```
# Ascend Auxiliary Software<a name="Ascend Auxiliary Software"></a>
3. Obtain the PyTorch source code.
| 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 |
1. Run the following command to obtain the PyTorch source code adapted to Ascend AI Processors:
# Installation Methods<a name="Installation Methods"></a>
```
git clone https://gitee.com/ascend/pytorch.git
```
## Installing the PyTorch Environment Dependencies
The directory structure of the downloaded source code is as follows:
```
├── patch # Directory of the patch adapted to Ascend AI Processors
│ ├── pytorch1.5.0_npu.patch # Patch for PyTorch 1.5.0
│ └── pytorch1.8.1_npu.patch # Patch for PyTorch 1.8.1
├── pytorch1.5.0 # Source code and test directory for PyTorch 1.5.0
│ ├── access_control_test.py
│ ├── src # Source code directory
│ └── test # Directory for storing test cases
├── pytorch1.8.1 # Source code and test directory for PyTorch 1.8.1
│ ├── access_control_test.py
│ ├── src # Source code directory
│ └── test # Directory for storing test cases
└── scripts # Build and create a directory.
```
Obtain the PyTorch source code (from the current repository) that adapts to Ascend AI Processors.
2. Obtain the native PyTorch source code from the root directory **/pytorch** of the current repository.
- If PyTorch 1.5.0 is installed, run the following command:
```
git clone -b v1.5.0-3.0.rc2 https://gitee.com/ascend/pytorch.git
```
```
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
```
## Obtaining the Native PyTorch Source Code and Third-Party Code
- If PyTorch 1.8.1 is installed, run the following command:
Obtain the native PyTorch 1.5.0 source code from the root directory **/pytorch** of the current repository. Check whether there are fixed security-related issues in the Security and Issues categories in the PyTorch native repository. Update the native PyTorch code if there are any fixes.
```
git clone -b v1.8.1 --depth=1 https://github.com/pytorch/pytorch.git
```
```sh
cd pytorch
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
```
3. Run the following commands to go to the native PyTorch code directory **pytorch** and obtain the PyTorch passive dependency code:
Go to the **pytorch/pytorch/** directory and obtain the passive dependency code of PyTorch. It takes a long time to obtain the code.
```
cd pytorch
git submodule sync
git submodule update --init --recursive
```
```sh
cd pytorch
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.
If no error is reported, the PyTorch and third-party code on which PyTorch depends is generated.
4. Generate the PyTorch installation package adapted to Ascend AI Processors.
1. Go to the **pytorch/scripts** directory and run the conversion script to generate full code adapted to Ascend AI Processors.
## Generating Full PyTorch Code That Adapts to Ascend AI Processors
```
cd ../scripts
# If PyTorch 1.5.0 is installed:
bash gen.sh
# If PyTorch 1.8.1 is installed:
bash gen.sh -v 1.8.1
```
Go to the **pytorch/scripts** directory and run the script of the selected version. (Note: The downloaded native PyTorch source code must match the following version. Otherwise, an error may occur.)
The full code adapted to Ascend AI Processors is generated in the **pytorch/pytorch** directory.
```sh
cd ../scripts/
bash gen.sh
```
2. Go to the **pytorch/pytorch/** directory and install the dependency library.
The full code adapted to the NPU is generated in the **pytorch/pytorch/** directory.
```
cd ../pytorch
pip3 install -r requirements.txt
```
3. Build and generate the binary installation package of PyTorch.
## Installing the Python Dependency Library
```
bash build.sh --python=3.7
or
bash build.sh --python=3.8
```
Go to the **pytorch/pytorch/** directory and install the Python dependency library.
Specify the Python version in the environment for build. The generated binary package is stored in the current dist directory **pytorch/pytorch/dist**.
```python3
cd ../pytorch
pip3 install -r requirements.txt
```
5. <a name="en-us_topic_0000001152776301_li49671667141"></a>Install PyTorch.
Go to the **pytorch/pytorch/dist** directory and run the following command to install PyTorch:
## Compiling Torch Binary Package
```
pip3 install --upgrade torch-1.5.0+ascend.post3-cp37-cp37m-linux_{arch}.whl
```
In the **pytorch/pytorch/** directory, run the following command:
_\{**arch\}**_ indicates the architecture information. The value can be **aarch64** or **x86\_64**.
```sh
# Python 3.7
bash build.sh
or
bash build.sh --python=3.7 (recommended)
>![](public_sys-resources/icon-note.gif) **NOTE:**
>To upgrade PyTorch in the environment, uninstall the PyTorch software package installed in the environment and then perform [Step 5 Install PyTorch](#en-us_topic_0000001152776301_li49671667141). Run the following command to check whether PyTorch has been installed:
>**pip3 list | grep torch**
# Python 3.8
bash build.sh --python=3.8
```
The generated binary package is in the **pytorch/pytorch/dist/** directory.
<h2 id="configuring-environment-variables.md">Configuring Environment Variables</h2>
## Installing PyTorch
After the software packages are installed, configure environment variables to use Ascend PyTorch. For details about the environment variables, see [Table 1](#en-us_topic_0000001152616261_table42017516135).
**x86_64:**
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:
**torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl** (The actual name may contain the minor version number, for example, **torch-1.5.0.post2+ascend-cp37-cp37m-linux_x86_64.whl**.)
```
source pytorch/env.sh
```
```shell
cd dist
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl
```
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" # 1.1.1.1 is the NIC IP address of the host. Change it based on the site requirements. Ensure that the NIC IP addresses in use can communicate with each other in the cluster.
```
**arm:**
3. \(Optional\) Configure function or performance environment variables in the NPU scenario. The variables are disabled by default.
**torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl** (The actual name may contain the minor version number, for example, **torch-1.5.0.post2+ascend-cp37-cp37m-linux_aarch64.whl**.)
```
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 TRI_COMBINED_ENABLE=1 # (Optional) Optimizes the scenario where three 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" # (Optional) Operator implementation. The performance of the ADD and MUL operators varies depending on the scenarios.
```
```shell
cd dist
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl
```
# Running<a name="Running"></a>
## Executing Environment Variables
Run the script for setting environment variables in the **pytorch/pytorch/** directory.
```
cd ../
source env.sh
```
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**.
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**.
```
If the system is openEuler or its inherited OS, such as UOS, run the following command to cancel CPU core binding.
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
```
**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>
**Table 1** Description of environment variables
<a name="en-us_topic_0000001152616261_table42017516135"></a>
<table><thead align="left"><tr id="en-us_topic_0000001152616261_row16198951191317"><th class="cellrowborder" valign="top" width="55.48%" id="mcps1.2.3.1.1"><p id="en-us_topic_0000001152616261_p51981251161315"><a name="en-us_topic_0000001152616261_p51981251161315"></a><a name="en-us_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 class="cellrowborder" valign="top" width="44.519999999999996%" id="mcps1.2.3.1.2"><p id="en-us_topic_0000001152616261_p9198135114133"><a name="en-us_topic_0000001152616261_p9198135114133"></a><a name="en-us_topic_0000001152616261_p9198135114133"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="en-us_topic_0000001152616261_row6882121917329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p688241953218"><a name="en-us_topic_0000001152616261_p688241953218"></a><a name="en-us_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="en-us_topic_0000001152616261_p1888291915322"><a name="en-us_topic_0000001152616261_p1888291915322"></a><a name="en-us_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-0.md#en-us_topic_0000001135347812_en-us_topic_0000001173199577_en-us_topic_0000001172534867_en-us_topic_0276688294_li9745165315131">5</a>.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row16194175523010"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p16195185523019"><a name="en-us_topic_0000001152616261_p16195185523019"></a><a name="en-us_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="en-us_topic_0000001152616261_row2954102119329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p195452113218"><a name="en-us_topic_0000001152616261_p195452113218"></a><a name="en-us_topic_0000001152616261_p195452113218"></a>PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p964914893211"><a name="en-us_topic_0000001152616261_p964914893211"></a><a name="en-us_topic_0000001152616261_p964914893211"></a>Executable program search path. Set this variable based on the preceding example.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row58592816294"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p1886016892913"><a name="en-us_topic_0000001152616261_p1886016892913"></a><a name="en-us_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="en-us_topic_0000001152616261_p28608892915"><a name="en-us_topic_0000001152616261_p28608892915"></a><a name="en-us_topic_0000001152616261_p28608892915"></a>Operator package (OPP) root directory. Set this variable based on the preceding example.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row144592037903"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p104601373014"><a name="en-us_topic_0000001152616261_p104601373014"></a><a name="en-us_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="en-us_topic_0000001152616261_p1046013716017"><a name="en-us_topic_0000001152616261_p1046013716017"></a><a name="en-us_topic_0000001152616261_p1046013716017"></a>Path of the operator information library.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row16184379493"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p131851873492"><a name="en-us_topic_0000001152616261_p131851873492"></a><a name="en-us_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="en-us_topic_0000001152616261_p181851575497"><a name="en-us_topic_0000001152616261_p181851575497"></a><a name="en-us_topic_0000001152616261_p181851575497"></a>Path of the AI CPU operator package.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row234714854615"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p2034724894619"><a name="en-us_topic_0000001152616261_p2034724894619"></a><a name="en-us_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="en-us_topic_0000001152616261_row1680820246202"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p4809112415207"><a name="en-us_topic_0000001152616261_p4809112415207"></a><a name="en-us_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="en-us_topic_0000001152616261_row0671137162115"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p4671203792114"><a name="en-us_topic_0000001152616261_p4671203792114"></a><a name="en-us_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="en-us_topic_0000001152616261_row1371356152313"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p15106173103120"><a name="p15106173103120"></a><a name="p15106173103120"></a>PTCOPY_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p71055317311"><a name="p71055317311"></a><a name="p71055317311"></a>Use the PTCopy operator mode to accelerate the operation of converting non-contiguous tensors to contiguous tensors and copy process. You are advised to set the value to <strong id="b114621515513"><a name="b114621515513"></a><a name="b114621515513"></a>1</strong> to enable this function. </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) 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.</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) 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>
</tr>
<tr id="row17630155212342"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p66309527341"><a name="p66309527341"></a><a name="p66309527341"></a>RI_COMBINED_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p19630185220345"><a name="p19630185220345"></a><a name="p19630185220345"></a>(Optional) Optimizes the scenario where three inconsecutive operators are combined. To enable this function, set the value to <strong id="b10522121418612"><a name="b10522121418612"></a><a name="b10522121418612"></a>1</strong>.</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 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="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>TASK_QUEUE_ENABLE</p>
<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="zh-cn_topic_0000001152616261_p0711356152317"><a name="zh-cn_topic_0000001152616261_p0711356152317"></a><a name="zh-cn_topic_0000001152616261_p0711356152317"></a>(Optional) Use asynchronous task delivery to asynchronously invoke the ACL interface. To enable this function, set it to **1** (recommended default setting). </p>
<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="en-us_topic_0000001152616261_p16711563237"><a name="en-us_topic_0000001152616261_p16711563237"></a><a name="en-us_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>
</tr>
</tbody>
</table>
## Running the Unit Test Script
<h2 id="installing-the-mixed-precision-module.md">Installing the Mixed Precision Module</h2>
Verify the running. The output is **OK**.
## Prerequisites<a name="en-us_topic_0000001106176190_section3225481020"></a>
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.md).
```shell
// Select a test script that matches the preceding version. The following uses the 1.5.0 version as an example.
cd ../
python3 pytorch1.5.0/test/test_npu/test_network_ops/test_div.py
```
# (Optional) Installing the Mixed Precision Module<a name="(Optional) Installing the Mixed Precision Module"></a>
## Installation Process<a name="en-us_topic_0000001106176190_section11880164819567"></a>
Select the APEX module based on the following functions. For details about how to build and install the APEX module, see the [README.en](https://gitee.com/ascend/apex/tree/v1.5.0-3.0.rc2/).
1. Log in to the server as the **root** user or a non-root user.
2. Obtain the Apex source code.
- 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.
1. Run the following command to obtain the Apex source code adapted to Ascend AI Processors:
# FAQ
```
git clone 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
```
## When PIP is set to the Huawei source, a Python environment error occurs after the typing dependency in the **requirements.txt** file is installed.
2. Run the following commands to go to the **apex** directory and obtain the native Apex source code:
When PIP is set to the Huawei source, open the **requirements.txt** file, delete the typing dependency, and then run the following command:
```
cd apex
git clone https://github.com/NVIDIA/apex.git
```
```
pip3 install -r requirments.txt
```
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.
## The **libhccl.so** cannot be found by **import torch**.
```
cd apex
git checkout 4ef930c1c884fdca5f472ab2ce7cb9b505d26c1a
```
Environment variables are not configured. You need to configure them using the **env.sh** script.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Due to network fluctuation, it may take a long time to obtain the source code.
```
source pytorch/pytorch1.5.0/src/env.sh
```
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.
## The error message "no module named yaml/typing_extensions." is displayed when **bash build.sh** is run during compilation.
2. Go to the full code directory **apex/apex**, and compile and generate the binary installation package of Apex.
PyTorch compilation depends on the YAML and typing_extensions libraries, which need to be manually installed.
```
cd ../apex
python3 setup.py --cpp_ext --npu_float_status bdist_wheel
```
```
pip3 install pyyaml
pip3 install typing_extensions
```
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**.
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.
4. <a name="en-us_topic_0000001106176190_li425495374416"></a>Install Apex.
Go to the **apex/apex/dist** directory and run the following command to install Apex:
```
pip3 install --upgrade apex-0.1+ascend-cp37-cp37m-linux_{arch}.whl
```
## TE cannot be found during running.
_\{**arch\}**_ indicates the architecture information. The value can be **aarch64** or **x86\_64**.
Development state:
>![](public_sys-resources/icon-note.gif) **NOTE:**
>To upgrade PyTorch in the environment, uninstall the PyTorch software package installed in the environment and then perform [Step 4 Install Apex](#en-us_topic_0000001106176190_li425495374416). Run the following command to check whether PyTorch has been installed:
>**pip3 list | grep apex**
```
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
<h2 id="references.md">References</h2>
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
- **[Installing CMake](#installing-cmake.md)**
User state:
- **[How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-7-3-0.md)**
```
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 # {arch} is the architecture name.
- **[What Do I Do If "torch 1.5.0xxxx" and "torchvision" Do Not Match When torch-\*.whl Is Installed?](#what-do-i-do-if-torch-1-5-0xxxx-and-torchvision-do-not-match-when-torch--whl-is-installed.md)**
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
<h2 id="installing-cmake.md">Installing CMake</h2>
Procedure for upgrading CMake to 3.12.1
1. Obtain the CMake software package.
## 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.
```
wget https://cmake.org/files/v3.12/cmake-3.12.1.tar.gz --no-check-certificate
```
Method 1: Download the installation script and install CMake. (For details, see the CMake official website.)
2. Decompress the package and go to the software package directory.
​ x86_64 environment: cmake-3.12.0-Linux-x86_64.sh
```
tar -xf cmake-3.12.1.tar.gz
cd cmake-3.12.1/
```
​ AArch64 environment: cmake-3.12.0-Linux-aarch64.sh
3. Run the configuration, build, and installation commands.
1. Run the following command:
```
./configure --prefix=/usr/local/cmake
make && make install
```
```
./cmake-3.12.0-Linux-{arch}.sh #{arch} indicates the architecture name.
```
4. Set the soft link.
2. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. Run the following command to check whether CMake has been installed:
3. Run the following command to check whether CMake has been installed:
```
cmake --version
```
```
cmake --version
```
If the message "cmake version 3.12.1" is displayed, the installation is successful.
If the message "cmake version 3.12.0" is displayed, the installation is successful.
<h2 id="how-do-i-install-gcc-7-3-0.md">How Do I Install GCC 7.3.0?</h2>
Method 2: Use the source code to compile and install.
Perform the following steps as the **root** user.
1. Obtain the CMake software package.
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:
```
wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
```
```
sudo rm -rf /tmp/*
```
2. Decompress the package and go to the software package directory.
3. Install the dependency package. \(CentOS and Ubuntu are used as examples.\)
- For CentOS, run the following command:
```
tar -xf cmake-3.12.0.tar.gz
cd cmake-3.12.0/
```
```
yum install bzip2
```
3. Run the configuration, compilation, and installation commands.
- For Ubuntu, run the following command:
```
./configure --prefix=/usr/local/cmake
make && make install
```
```
apt-get install bzip2
```
4. Set the soft link.
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:
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
```
tar -zxvf gcc-7.3.0.tar.gz
```
5. Run the following command to check whether CMake has been installed:
2. Go to the extracted directory and run the following command to download the GCC dependency packages:
```
cmake --version
```
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
If the message "cmake version 3.12.0" is displayed, the installation is successful.
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:
## During GCC installation through the CLI, an error is reported indicating that the package cannot be found. During GCC compilation, another error is reported.
```
./contrib/download_prerequisites
```
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.
If the validation fails, check whether the dependency packages are repeatedly downloaded. The packages should be downloaded at a time.
Perform the following steps as the **root** user.
3. <a name="en-us_topic_0000001135347812_en-us_topic_0000001173199577_en-us_topic_0000001172534867_en-us_topic_0276688294_li1649343041310"></a>Run the configuration, build, and installation commands.
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).
```
./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
```
2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
>![](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**.
```
sudo rm -rf /tmp/*
```
3. Install the dependency package. (CentOS and Ubuntu are used as examples.)
5. Set the environment variable.
- For CentOS, run the following command:
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:
```
yum install bzip2
```
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
- For Ubuntu, run the following command:
**$\{install\_path\}** indicates the GCC 7.3.0 installation path configured in [3](#en-us_topic_0000001135347812_en-us_topic_0000001173199577_en-us_topic_0000001172534867_en-us_topic_0276688294_li1649343041310). In this example, the GCC 7.3.0 installation path is **/usr/local/gcc7.3.0/**.
```
apt-get install bzip2
```
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Skip this step if you do not need to use the compilation environment with GCC upgraded.
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:
<h2 id="what-do-i-do-if-torch-1-5-0xxxx-and-torchvision-do-not-match-when-torch--whl-is-installed.md">What Do I Do If "torch 1.5.0xxxx" and "torchvision" Do Not Match When torch-\*.whl Is Installed?</h2>
```
tar -zxvf gcc-7.3.0.tar.gz
```
## Symptom<a name="en-us_topic_0000001105856364_en-us_topic_0175549220_section197270431505"></a>
2. Go to the extracted directory and download the GCC dependency packages:
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.
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
![](figures/en-us_image_0000001190081735.png)
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:
## Possible Causes<a name="en-us_topic_0000001105856364_en-us_topic_0175549220_section169499490501"></a>
```
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
```
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.
After the preceding dependencies are downloaded, run the following command again:
## Solution<a name="en-us_topic_0000001105856364_section108142031907"></a>
```
./contrib/download_prerequisites
```
This problem has no impact on the actual result, and no action is required.
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
```
> ![img](public_sys-resources/icon-notice.gif) **NOTE: **
>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++
```
5. Configure environment variables.
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}
```
**${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/**.
>![](public_sys-resources/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.
CentOS and EulerOS
```sh
yum -y install openblas
```
Ubuntu
```sh
apt install libopenblas-dev
```
## torchvision fails to be installed using pip in the Arm environment.
The source code can be used for installation. (You need to install the AscendPyTorch first and configure environment variables using **env.sh**.)
```
git clone -b v0.6.0 https://github.com/pytorch/vision.git
cd vision
python setup.py install
```
Verify that the torchvision is successfully installed.
```
python -c "import torchvision"
```
If no error is reported, the installation is successful.
For details about releases, see [Release Notes](https://gitee.com/ascend/pytorch/blob/v1.5.0-3.0.rc2/docs/zh/RELEASENOTE/RELEASENOTE.md).
@@ -1,48 +1,48 @@
# PyTorch Online Inference Guide
- [Application Scenario](#application-scenariomd)
- [Basic Workflow](#basic-workflowmd)
- [Prerequisites](#prerequisitesmd)
- [Online Inference Process](#online-inference-processmd)
- [Environment Variable Configuration](#environment-variable-configurationmd)
- [Sample Reference](#sample-referencemd)
- [Special Topics](#special-topicsmd)
- [Mixed Precision](#mixed-precisionmd)
- [How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-7-3-0md)
<h2 id="application-scenariomd">Application Scenario</h2>
- [Application Scenario](#application-scenario.md)
- [Basic Workflow](#basic-workflow.md)
- [Prerequisites](#prerequisites.md)
- [Online Inference Process](#online-inference-process.md)
- [Environment Variable Configuration](#environment-variable-configuration.md)
- [Sample Reference](#sample-reference.md)
- [Special Topics](#special-topics.md)
- [Mixed Precision](#mixed-precision.md)
- [How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-7-3-0.md)
<h2 id="application-scenario.md">Application Scenario</h2>
Online inference, unlike offline inference, allows developers to perform inference directly with PyTorch models using the **model.eval\(\)** method.
In this way, PyTorch-based inference apps can be directly ported to the Ascend AI Processor, which is especially useful in the data center inference scenarios.
### Supported Processors<a name="section15598658104219"></a>
## Supported Processors<a name="section15598658104219"></a>
Ascend 910 AI Processor
Ascend 310P AI Processor
Ascend 710 AI Processor
<h2 id="basic-workflowmd">Basic Workflow</h2>
<h2 id="basic-workflow.md">Basic Workflow</h2>
- **[Prerequisites](#prerequisitesmd)**
- **[Prerequisites](#prerequisites.md)**
- **[Online Inference Process](#online-inference-processmd)**
- **[Online Inference Process](#online-inference-process.md)**
- **[Environment Variable Configuration](#environment-variable-configurationmd)**
- **[Environment Variable Configuration](#environment-variable-configuration.md)**
- **[Sample Reference](#sample-referencemd)**
- **[Sample Reference](#sample-reference.md)**
<h3 id="prerequisitesmd">Prerequisites</h3>
<h2 id="prerequisites.md">Prerequisites</h2>
The PyTorch framework and mixed precision module have been installed. For details, see the _PyTorch Installation Guide_.
<h3 id="online-inference-processmd">Online Inference Process</h3>
<h2 id="online-inference-process.md">Online Inference Process</h2>
[Figure 1](#fig13802941161818) shows the online inference process.
**Figure 1** Online inference process<a name="fig13802941161818"></a>
![](figures/online-inference-process.png "online-inference-process")
<h3 id="environment-variable-configurationmd">Environment Variable Configuration</h3>
<h2 id="environment-variable-configuration.md">Environment Variable Configuration</h2>
The following are the environment variables required for starting the inference process on PyTorch:
@@ -57,10 +57,10 @@ The following are the environment variables required for starting the inference
export PATH=/usr/local/python3.7.5/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/python3.7.5/lib:$LD_LIBRARY_PATH
# Set the logical ID of a processor.
# Sets the logical ID of a processor.
export ASCEND_DEVICE_ID=0
# Output log information. Replace it as required.
# Outputs log information. Replace it as required.
export ASCEND_SLOG_PRINT_TO_STDOUT=1
export ASCEND_GLOBAL_LOG_LEVEL=0
@@ -82,7 +82,7 @@ export TASK_QUEUE_ENABLE=0
<tbody><tr id="row2732273481"><td class="cellrowborder" valign="top" width="46.75467546754676%" headers="mcps1.2.4.1.1 "><p id="p57382719481"><a name="p57382719481"></a><a name="p57382719481"></a>LD_LIBRARY_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="43.18431843184319%" headers="mcps1.2.4.1.2 "><p id="p07319271480"><a name="p07319271480"></a><a name="p07319271480"></a>Dynamic library search path. Set this variable based on the preceding example.</p>
<div class="note" id="note119943144912"><a name="note119943144912"></a><a name="note119943144912"></a><span class="notetitle"> NOTE: </span><div class="notebody"><p id="p49933104915"><a name="p49933104915"></a><a name="p49933104915"></a>If GCC 7.3.0 is installed in OSs such as CentOS 7.6, Debian, and BC-Linux, configure the related environment variables. For details, see <a href="#how-do-i-install-gcc-7-3-0md#en-us_topic_0000001146754749_en-us_topic_0000001072593337_l5e5c9395407d46439788b12f0e6342bc">5</a>.</p>
<div class="note" id="note119943144912"><a name="note119943144912"></a><a name="note119943144912"></a><span class="notetitle"> NOTE: </span><div class="notebody"><p id="p49933104915"><a name="p49933104915"></a><a name="p49933104915"></a>If GCC 7.3.0 is installed in OSs such as CentOS 7.6, Debian, and BC-Linux, configure the related environment variables. For details, see <a href="#how-do-i-install-gcc-7-3-0.md#en-us_topic_0000001146754749_en-us_topic_0000001072593337_l5e5c9395407d46439788b12f0e6342bc">5</a>.</p>
</div></div>
</td>
<td class="cellrowborder" valign="top" width="10.061006100610062%" headers="mcps1.2.4.1.3 "><p id="p187352744817"><a name="p187352744817"></a><a name="p187352744817"></a>Required</p>
@@ -133,9 +133,9 @@ export TASK_QUEUE_ENABLE=0
>![](public_sys-resources/icon-note.gif) **NOTE:**
>For more log information, see the _CANN Log Reference_.
<h3 id="sample-referencemd">Sample Reference</h3>
<h2 id="sample-reference.md">Sample Reference</h2>
#### Sample Code<a name="section2017032418274"></a>
## Sample Code<a name="section2017032418274"></a>
Try to minimize the initialization frequency across the app lifetime during inference. The inference mode is set using the **model.eval\(\)** method, and the inference process must run under the code branch **with torch.no\_grad\(\):**.
@@ -406,7 +406,7 @@ if __name__ == '__main__':
main()
```
#### Sample Running<a name="section340764716270"></a>
## Sample Running<a name="section340764716270"></a>
The following uses the ResNet-50 model as an example to describe how to perform online inference.
@@ -416,11 +416,11 @@ The following uses the ResNet-50 model as an example to describe how to perform
2. Edit the inference script.
Create a model script file **resnet50\_infer\_for\_pytorch.py** and write code. For how to write the code, see [Sample Code]().
Create a model script file **resnet50\_infer\_for\_pytorch.py** and write code by referring to [Sample Code]().
3. Run inference.
Set environment variables (for how to set them, see [Environment Variable Configuration](#environment-variable-configurationmd)) and then run the following command:
Set environment variables by referring to [Environment Variable Configuration](#environment-variable-configuration.md) and then run the following command:
```
python3 pytorch-resnet50-apex.py --data /data/imagenet \
@@ -433,14 +433,14 @@ The following uses the ResNet-50 model as an example to describe how to perform
>The preceding command is an example only. Modify the arguments as needed.
<h2 id="special-topicsmd">Special Topics</h2>
<h2 id="special-topics.md">Special Topics</h2>
- **[Mixed Precision](#mixed-precisionmd)**
- **[Mixed Precision](#mixed-precision.md)**
<h3 id="mixed-precisionmd">Mixed Precision</h3>
<h2 id="mixed-precision.md">Mixed Precision</h2>
#### Overview<a name="section14734122962615"></a>
## Overview<a name="section14734122962615"></a>
Based on the architecture features of the NPU, mixed precision is involved in the model computing, that is, the scenario where the float16 and float32 data types are used together. Replacing float32 with float16 has the following advantages:
@@ -450,7 +450,7 @@ Based on the architecture features of the NPU, mixed precision is involved in th
However, the mixed precision training is limited by the precision range expressed by float16. If float32 is converted into float16, the training convergence is affected. To use float16 for acceleration in some computations and ensure training convergence, the mixed precision module Apex is used. The mixed precision module Apex is a comprehensive optimization library that features high optimization performance and precision.
#### Supported Features<a name="section175201458521"></a>
## Supported Features<a name="section175201458521"></a>
[Table 1](#en-us_topic_0278765773_table10717173813332) describes the functions and optimization of the mixed precision module.
@@ -489,34 +489,34 @@ However, the mixed precision training is limited by the precision range expresse
>![](public_sys-resources/icon-note.gif) **NOTE:**
>In the current version, Apex is implemented using Python and does not support AscendCL or CUDA optimization.
#### Initializing the Mixed Precision Model<a name="section18178125518268"></a>
## Initializing the Mixed Precision Model<a name="section18178125518268"></a>
1. To use the mixed precision module Apex, import the amp module from the Apex library.
1. To use the mixed precision module Apex, you need to import the amp module from the Apex library as follows:
```
from apex import amp
```
2. Initialize the amp module so that it can modify the model, optimizer, and PyTorch internal functions.
2. After the amp module is imported, you need to initialize it so that it can modify the model, optimizer, and PyTorch internal functions. The initialization code is as follows:
```
model, optimizer = amp.initialize(model, optimizer)
```
For details, see "Initialize the mixed precision model."# in [Sample Code](#sample-referencemd).
For details, see "Initialize the mixed precision model."# in [Sample Code](#sample-reference.md).
```
model, optimizer = amp.initialize(model, optimizer, opt_level="O2", loss_scale=1024, verbosity=1)
```
#### Mixed Precision Inference<a name="section818071513288"></a>
## Mixed Precision Inference<a name="section818071513288"></a>
After the mixed precision model is initialized, perform model forward propagation.
Sample code: For details, see the implementation of **validate\(val\_loader, model, args\)** in [Sample Code](#sample-referencemd).
Sample code: For details, see the implementation of **validate\(val\_loader, model, args\)** in [Sample Code](#sample-reference.md).
<h2 id="how-do-i-install-gcc-7-3-0md">How Do I Install GCC 7.3.0?</h2>
<h2 id="how-do-i-install-gcc-7-3-0.md">How Do I Install GCC 7.3.0?</h2>
Perform the following steps as the **root** user.
@@ -585,7 +585,7 @@ Perform the following steps as the **root** user.
5. Set the environment variable.
Training must be performed in the compilation environment with GCC upgraded. Therefore, configure the following environment variable in the training script:
The build environment after GCC upgrade is required for training. Therefore, you need to configure the following environment variable in the training script:
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
@@ -594,5 +594,6 @@ Perform the following steps as the **root** user.
**$\{install\_path\}** indicates the GCC 7.3.0 installation path configured in [3.](#en-us_topic_0000001146754749_en-us_topic_0000001072593337_l75d31a2874534a2092e80a5f865b46f0). In this example, the GCC 7.3.0 installation path is **/usr/local/linux\_gcc7.3.0/**.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Skip this step if you do not the compilation environment with GCC upgraded.
>The environment variable needs to be configured only when you need to use the build environment after the GCC upgrade.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
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

+62 -413
View File
@@ -1,406 +1,42 @@
# FrameworkPTAdapter 3.0.RC2 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 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.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.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 2.0.3 Release Notes
- [FrameworkPTAdapter 2.0.3](#frameworkptadapter-2-0-3.md)
- [Before You Start](#before-you-start.md)
- [New Features](#new-features.md)
- [Modified Features](#modified-features.md)
- [Resolved Issues](#resolved-issues.md)
- [Known Issues](#known-issues.md)
- [Compatibility](#compatibility.md)
- [FrameworkPTAdapter 2.0.2](#frameworkptadapter-2-0-2.md)
- [Before You Start](#before-you-start-0.md)
- [New Features](#new-features-1.md)
- [Modified Features](#modified-features-2.md)
- [Resolved Issues](#resolved-issues-3.md)
- [Known Issues](#known-issues-4.md)
- [Compatibility](#compatibility-5.md)
<h2 id="frameworkptadapter-2-0-3.md">FrameworkPTAdapter 2.0.3</h2>
<h2 id="frameworkptadapter-30rc2">FrameworkPTAdapter 3.0.RC2</h2>
- **[Before You Start](#before-you-start.md)**
- **[New Features](#new-features.md)**
<h3 id="Before You Start">Before You Start</h3>
- **[Modified Features](#modified-features.md)**
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.
- **[Resolved Issues](#resolved-issues.md)**
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.
- **[Known Issues](#known-issues.md)**
<h3 id="New Features">New Features</h3>
- **[Compatibility](#compatibility.md)**
**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>
<h3 id="Modified Features">Modified Features</h3>
N/A
<h3 id="Resolved Issues">Resolved Issues</h3>
N/A
<h3 id="Known Issues">Known Issues</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>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>
<h3 id="Compatibility">Compatibility</h3>
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
<h2 id="frameworkptadapter-30rc1">FrameworkPTAdapter 3.0.RC1</h2>
<h3 id="Before You Start 1">Before You Start</h3>
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 adopts the plugin adaptation mode and inherits the features of PyTorch 1.5.0. Their functions are basically the same, but PyTorch 1.8.1 provides better development experience for backend operator adaptation.
AOE-based tuning is supported.
<h3 id="New Features 1">New Features</h3>
**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>
The <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>AOE-based tuning supported</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>Supports AOE-based tuning to improve model performance.</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></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> Added the function of adapted operator development. For details, see the operator list.</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="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Port the NPU adapted code to the torch_npu plugin to decouple the Ascend adapted code from the native PyTorch code.</p>
</td>
<tr>
The <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>AOE-based tuning supported</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>Supports AOE-based tuning to improve model performance.</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>Framework API satisfaction</p>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Supports APIs adapted to PyTorch 1.5.0. For details, see the API list.</p>
</td>
</tr>
</tbody>
</table>
<h3 id="Modified Features 1">Modified Features</h3>
N/A
<h3 id="Resolved Issues 1">Resolved Issues</h3>
N/A
<h3 id="Known Issues 1">Known Issues</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>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>
<h3 id="Compatibility 1">Compatibility</h3>
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
<h2 id="FrameworkPTAdapter-204">FrameworkPTAdapter 2.0.4</h2>
<h3 id="Before You Start 2">Before You Start</h3>
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 inherits the features of PyTorch 1.5.0. Their functions are basically the same, but PyTorch 1.8.1 provides better development experience for backend operator adaptation. Currently, PyTorch 1.8.1 supports only the ResNet-50 network model.
<h3 id="New Features 2">New Features</h3>
**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="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.5.0 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>Optimization of model accuracy analyzer</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>Supports mapping between IR and TBE operators and enabled the NPU dump data to be loaded to the GPU side for comparison.</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>E2E prof supported</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Integrated the profile data obtained by the native PyTorch Profiling tool and CANN prof tool to implement end-to-end model and operator performance analysis.</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></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> Added the function of adapted operator development. For details, see the operator list.</p>
</td>
</tr>
<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.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>AMP supported</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>Supports the native training of automatic mixed precision (AMP) of PyTorch.</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>Profiling supported</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Supports the native profiling function of PyTorch.</p>
</td>
</tr>
<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>OS compatibility</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>OS compatibility</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>Supports Ubuntu 20.04 (x86 and Arm) and EulerOS 2.10 (Arm)</p>
</td>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Python version compatibility</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>Supports compilation and use of Python 3.9 (only for PyTorch 1.8.1).</p>
</td>
</tr>
</tbody>
</table>
<h3 id="Modified Features 2">Modified Features</h3>
N/A
<h3 id="Resolved Issues 2">Resolved Issues</h3>
N/A
<h3 id="Known Issues 2">Known Issues</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>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>
<h3 id="Compatibility 2">Compatibility</h3>
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
<h2 id="frameworkptadapter-203">FrameworkPTAdapter 2.0.3</h2>
<h3 id="Before You Start 3">Before You Start</h3>
<h2 id="before-you-start.md">Before You Start</h2>
This framework is modified based on the open-source PyTorch 1.5.0 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 is supported by this version and later, and this version inherits the features of PyTorch 1.5.0 and provides the same functions, except for the Profiling tool. In addition, it optimizes the backend operator adaptation. Currently, PyTorch 1.8.1 supports only the ResNet-50 network model.
PyTorch 1.8.1 is supported by this version and later, and this version inherits the features of PyTorch 1.5.0 and provides the same functions, except for the profiling tool. In addition, it optimizes the backend operator adaptation. Currently, PyTorch 1.8.1 supports only the ResNet-50 network model.
<h3 id="New Features 3">New Features</h3>
<h2 id="new-features.md">New Features</h2>
**Table 1** Features supported by PyTorch
**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>
@@ -425,7 +61,7 @@ PyTorch 1.8.1 is supported by this version and later, and this version inherits
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Operator overflow/underflow detection tool</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>Supported IR-level operator overflow/underflow detection in the PyTorch framework. When an AI Core operator overflow/underflow occurs, the IR information is displayed.</p>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>Supported IR-level operator overflow/underflow detection in the PyTorch framework. When AI Core operator overflow/underflow occurs, the IR information is displayed.</p>
</td>
</tr>
<tr id="row185381431133610"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p953883153611"><a name="p953883153611"></a><a name="p953883153611"></a>OS compatibility</p>
@@ -573,15 +209,15 @@ PyTorch 1.8.1 is supported by this version and later, and this version inherits
</tbody>
</table>
<h3 id="Modified Features 3">Modified Features</h3>
<h2 id="modified-features.md">Modified Features</h2>
N/A
<h3 id="Resolved Issues 3">Resolved Issues</h3>
<h2 id="resolved-issues.md">Resolved Issues</h2>
N/A
<h3 id="Known Issues 3">Known Issues</h3>
<h2 id="known-issues.md">Known Issues</h2>
<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>
@@ -590,9 +226,9 @@ N/A
</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>
<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</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 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 does 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>
@@ -620,22 +256,34 @@ N/A
</tbody>
</table>
<h3 id="Compatibility 3">Compatibility</h3>
<h2 id="compatibility.md">Compatibility</h2>
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04, BC-Linux 7.6, Debian 9.9, Debian 10, and openEuler 20.03 LTS.
Atlas 800 \(model 9010\): CentOS 7.6, Ubuntu 18.04, BC-Linux 7.6, Debian 9.9, Debian 10, and openEuler 20.03 LTS.
Atlas 800 (model 9000): CentOS 7.6, Euler 2.8, Kylin V10, BC-Linux 7.6, openEuler 20.03 LTS, and UOS 20 1020e.
Atlas 800 \(model 9000\): CentOS 7.6, Euler 2.8, Kylin v10, BC-Linux 7.6, OpenEuler 20.03 LTS, and UOS 20 1020e.
<h2 id="frameworkptadapter-202">FrameworkPTAdapter 2.0.2</h2>
<h2 id="frameworkptadapter-2-0-2.md">FrameworkPTAdapter 2.0.2</h2>
- **[Before You Start](#before-you-start-0.md)**
- **[New Features](#new-features-1.md)**
- **[Modified Features](#modified-features-2.md)**
- **[Resolved Issues](#resolved-issues-3.md)**
- **[Known Issues](#known-issues-4.md)**
- **[Compatibility](#compatibility-5.md)**
<h3 id="Before You Start 4">Before You Start</h3>
<h2 id="before-you-start-0.md">Before You Start</h2>
This framework is modified based on the open-source PyTorch 1.5.0 primarily 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.
<h3 id="New Features-1md">New Features</h3>
<h2 id="new-features-1.md">New Features</h2>
**Table 1** Features supported by PyTorch
**Table 1** Features supported by PyTorch
<a name="t76c34275cbb74753970f7c5a9eb594fa"></a>
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.489999999999998%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
@@ -692,7 +340,7 @@ This framework is modified based on the open-source PyTorch 1.5.0 primarily deve
</tr>
<tr id="row7627155917380"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1561525916383"><a name="p1561525916383"></a><a name="p1561525916383"></a>Model Accuracy Analyzer</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p19616115953816"><a name="p19616115953816"></a><a name="p19616115953816"></a>Added the Model Accuracy Analyzer and supported training accuracy demarcation.</p>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p19616115953816"><a name="p19616115953816"></a><a name="p19616115953816"></a>Added model accuracy analyzers and supported training accuracy demarcation.</p>
</td>
</tr>
<tr id="row46269593383"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p0616559163819"><a name="p0616559163819"></a><a name="p0616559163819"></a>Ascend 710 AI Processor</p>
@@ -708,15 +356,15 @@ This framework is modified based on the open-source PyTorch 1.5.0 primarily deve
</tbody>
</table>
<h3 id="Modified Features 4">Modified Features</h3>
<h2 id="modified-features-2.md">Modified Features</h2>
N/A
<h3 id="Resolved Issues 4">Resolved Issues</h3>
<h2 id="resolved-issues-3.md">Resolved Issues</h2>
N/A
<h3 id="Known Issues 4">Known Issues</h3>
<h2 id="known-issues-4.md">Known Issues</h2>
<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>
@@ -725,9 +373,9 @@ N/A
</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>
<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</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 class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p13699152010301"><a name="p13699152010301"></a><a name="p13699152010301"></a>The NPU does 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>
@@ -749,14 +397,15 @@ N/A
</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 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 CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
<h3 id="Compatibility 4">Compatibility</h3>
<h2 id="compatibility-5.md">Compatibility</h2>
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04, BC-Linux 7.6, Debian 9.9, Debian 10, and openEuler 20.03 LTS.
Atlas 800 \(model 9010\): CentOS 7.6/Ubuntu 18.04/BC-Linux 7.6/Debian 9.9/Debian 10/openEuler 20.03 LTS
Atlas 800 \(model 9000\): CentOS 7.6/EulerOS 2.8/Kylin v10/BC-Linux 7.6/openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6/EulerOS 2.8/Kylin v10/BC-Linux 7.6/openEuler 20.03 LTS
File diff suppressed because it is too large Load Diff
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

File diff suppressed because it is too large Load Diff
@@ -18,7 +18,7 @@
昇腾910 AI处理器
昇腾310P AI处理器
昇腾710 AI处理器
<h2 id="基本使用流程md">基本使用流程</h2>
@@ -596,3 +596,4 @@ if __name__ == '__main__':
>![](public_sys-resources/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
+455 -386
View File
@@ -1,192 +1,299 @@
# 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框架相关模块。
- [Ascend配套软件](#Ascend配套软件)
**图 1** 环境准备流程图<a name="zh-cn_topic_0000001119176876_fig1938918396117"></a>
- [安装方式](#安装方式)
- [运行](#运行)
![](figures/210926103326800.png)
- [安装混合精度模块(可选)](#安装混合精度模块(可选))
<h2 id="手动编译安装md">手动编译安装</h2>
- [FAQ](#FAQ)
- **[前提条件](#前提条件md)**
- [版本说明](#版本说明)
- **[安装PyTorch框架](#安装PyTorch框架md)**
- **[配置环境变量](#配置环境变量md)**
# 简介<a name="简介"></a>
- **[安装混合精度模块](#安装混合精度模块md)**
本项目开发了PyTorch Adapter插件,用于昇腾适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。用户在准备相关环境进行基于PyTorch框架模型的开发、运行时,可以选择在服务器中手动编译安装PyTorch框架相关模块。
<h3 id="前提条件md">前提条件</h3>
- 需完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
- Python支持版本为3.7.5、3.8。
#### 前提条件<a name="zh-cn_topic_0000001105856382_zh-cn_topic_0275872734_section108914373254"></a>
# 系统依赖库<a name="系统依赖库"></a>
- 需完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
- 需安装3.12.0以上版本的CMake,安装方法请参考[CMake安装方法](#CMake安装方法md)。
- 需确保已安装7.3.0以上版本的gcc,7.3.0版本gcc具体安装及使用方式请参考[安装7.3.0版本gcc](#安装7-3-0版本gccmd)。
- 需安装python版本为3.7.5或3.8。
- 需确保环境中已安装patch、git工具,以Ubuntu和CentOS系统为例,命令如下:
- Ubuntu系统
## CentOS & EulerOS
```
apt-get install patch
apt-get install git
```
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
- CentOS系统
yum install -y gcc==7.3.0 cmake==3.12.0
## 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 -y gcc==7.3.0 cmake==3.12.0
```
yum install patch
yum install git
```
>![](public_sys-resources/icon-note.gif) **说明:**
>若安装gcc与cmake依赖命令报错,请参考FAQ使用源码安装。
<h3 id="安装PyTorch框架md">安装PyTorch框架</h3>
#### 安装流程<a name="zh-cn_topic_0000001152776301_section1611810384557"></a>
1. 以root或非root用户登录服务器。
2. 依次执行如下命令安装PyTorch依赖环境。
如果使用非root用户安装Python及其依赖,用户需要在本步骤中的每句命令结尾加上**--user**,命令示例为:**pip3.7 install pyyaml --user**
```
pip3 install pyyaml
pip3 install wheel
```
3. 获取PyTorch源代码。
1. 运行如下命令,获取适配昇腾AI处理器的PyTorch源代码。
```
git clone https://gitee.com/ascend/pytorch.git
```
下载的源码主要目录结构如下所示:
```
├── patch # 昇腾AI处理器适配补丁目录
│ ├── pytorch1.5.0_npu.patch # pytorch1.5.0版本补丁
│ └── pytorch1.8.1_npu.patch # pytorch1.8.1版本补丁
├── pytorch1.5.0 # pytorch1.5.0源码及测试目录
│ ├── access_control_test.py
│ ├── src # 源码目录
│ └── test # 测试用例存放目录
├── pytorch1.8.1 # pytorch1.8.1源码及测试目录
│ ├── access_control_test.py
│ ├── src # 源码目录
│ └── test # 测试用例存放目录
└── scripts # 编译构建目录
```
2. 在当前仓根目录“/pytorch“下获取原生PyTorch源代码。
- 若安装pytorch1.5.0版本,执行如下命令。
```
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
```
- 若安装pytorch1.8.1版本,执行如下命令。
```
git clone -b v1.8.1 --depth=1 https://github.com/pytorch/pytorch.git
```
3. 运行如下命令,进入原生pytorch代码目录“pytorch“,并获取PyTorch被动依赖代码。
```
cd pytorch
git submodule sync
git submodule update --init --recursive
```
>![](public_sys-resources/icon-note.gif) **说明:**
>受网络波动影响,源码获取时间可能较长,下载过程中请耐心等待。 下载完成之后若没有报错,即生成了PyTorch及其依赖的第三方代码。
4. 编译生成适配昇腾AI处理器的PyTorch安装包。
1. 进入“pytorch/scripts“文件夹,执行转换脚本,生成适配昇腾AI处理器的全量代码。
```
cd ../scripts
# 若安装1.5.0版本
bash gen.sh
# 若安装1.8.1版本
bash gen.sh -v 1.8.1
```
将在"pytorch/pytorch"目录中生成适配昇腾AI处理器的全量代码。
2. 进入到“pytorch/pytorch/“目录,依赖库安装。
```
cd ../pytorch
pip3 install -r requirements.txt
```
3. 编译生成pytorch的二进制安装包。
```
bash build.sh --python=3.7
或
bash build.sh --python=3.8
```
请指定环境中python版本进行编译。生成的二进制包在当前的dist目录下,即“pytorch/pytorch/dist”文件夹目录下。
5. <a name="zh-cn_topic_0000001152776301_li49671667141"></a>安装PyTorch。
进入“pytorch/pytorch/dist“文件夹目录,执行如下命令安装。
```
pip3 install --upgrade torch-1.5.0+ascend.post3-cp37-cp37m-linux_{arch}.whl
```
**\{arch\}**表示架构信息,为aarch64或x86\_64。
>![](public_sys-resources/icon-note.gif) **说明:**
>若对环境中的PyTorch进行升级时,需要先卸载环境中已安装的PyTorch软件包再执行[5. 安装PyTorch。](#zh-cn_topic_0000001152776301_li49671667141)可以通过执行如下命令查询环境上是否已安装PyTorch。
>**pip3 list | grep torch**
# Ascend配套软件<a name="Ascend配套软件"></a>
<h3 id="配置环境变量md">配置环境变量</h3>
| 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 |
安装完软件包后,需要配置环境变量才能正常使用昇腾PyTorch。相关环境变量介绍参见[表1](#zh-cn_topic_0000001152616261_table42017516135)。
# 安装方式<a name="安装方式"></a>
1. 配置运行环境变量,在适配昇腾AI处理器的PyTorch源代码根目录中运行如下命令。
## 安装PyTorch依赖环境
```
source pytorch/env.sh
```
2. 请依据实际场景,选择合适的HCCL初始化方式,并配置相应环境变量。
获取适配昇腾AI处理器的PyTorch源代码(即当前仓库代码)。
```
# 场景一:单机场景
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在集群内是互通的。
```
```
git clone -b v1.5.0 https://gitee.com/ascend/pytorch.git
```
3. (可选)NPU场景下配置功能或性能环境变量。默认为不开启。
## 获取原生PyTorch源代码和third_party代码
```
export DYNAMIC_COMPILE_ENABLE=1 # 动态shape特性功能,针对shape变化场景,可选,开启设置为1(PyTorch1.8.1不支持该环境变量)
export COMBINED_ENABLE=1 # 非连续两个算子组合类场景优化,可选,开启设置为1
export TRI_COMBINED_ENABLE=1 # 非连续三个算子组合类场景优化,可选,开启设置为1
export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
export DYNAMIC_OP="ADD#MUL" # 算子实现,ADD和MUL算子在不同场景下有不同的性能表现。可选
```
在当前仓库根目录pytorch/下获取原生PyTorch1.5.0的源代码。请关注PyTorch原生社区的安全板块与Issue板块是否有安全相关问题修复,并根据社区修复及时更新原生PyTorch代码。
```sh
cd pytorch
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
```
进入到pytorch/pytorch/目录下, 获取PyTorch被动依赖代码(获取时间较长,请耐心等待)。
```sh
cd pytorch
git submodule sync
git submodule update --init --recursive
```
完成且没有报错之后就生成了PyTorch及其依赖的三方代码
## 生成适配昇腾AI处理器的PyTorch全量代码。
进入到pytorch/scripts目录,根据选择的版本执行,执行脚本(注意:下载原生Pytorch源代码和下面版本要对应,否则可能出错)
```sh
cd ../scripts/
bash gen.sh
```
会在pytorch/pytorch/目录中生成npu适配全量代码
## python依赖库
进入到pytorch/pytorch/目录,依赖库安装:
```python3
cd ../pytorch
pip3 install -r requirements.txt
```
## 编译torch的二进制包
在pytorch/pytorch/目录,执行
```sh
# python3.7版本
bash build.sh
或者
bash build.sh --python=3.7(推荐)
# python3.8版本
bash build.sh --python=3.8
```
生成的二进制包在pytorch/pytorch/dist/目录下
## 安装pytorch
**x86_64:**
torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl (实际可能附带小版本号例如torch-1.5.0.post2+ascend-cp37-cp37m-linux_x86_64.whl)
```shell
cd dist
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl
```
**arm:**
torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl (实际可能附带小版本号例如torch-1.5.0.post2+ascend-cp37-cp37m-linux_aarch64.whl)
```shell
cd dist
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl
```
# 运行<a name="运行"></a>
## 运行环境变量
在pytorch/pytorch/中执行设置环境变量脚本
```
cd ../
source env.sh
```
可选的环境变量可能会对运行的模型产生影响:
```
export COMBINED_ENABLE=1 # 非连续转连续二级推导优化,可选,开启设置为1。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升
export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
export TASK_QUEUE_ENABLE=1 # 使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1
```
当系统为openEuler及其继承操作系统时,如UOS,需设置此命令,取消CPU绑核。
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="zh-cn_topic_0000001152616261_row1371356152313"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p15106173103120"><a name="p15106173103120"></a><a name="p15106173103120"></a>PTCOPY_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p71055317311"><a name="p71055317311"></a><a name="p71055317311"></a>使用PTCopy算子模式,加速转连续及copy等过程,建议开启,开启设置为1</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。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升。</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。</p>
</td>
</tr>
<tr id="row17630155212342"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p66309527341"><a name="p66309527341"></a><a name="p66309527341"></a>RI_COMBINED_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p19630185220345"><a name="p19630185220345"></a><a name="p19630185220345"></a>(可选)非连续三个算子组合类场景优化,开启设置为1。</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>
@@ -194,293 +301,255 @@ export TASK_QUEUE_ENABLE=1 # 使用异步任务下发,异步调用acl接口,
<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="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>TASK_QUEUE_ENABLE</p>
<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="zh-cn_topic_0000001152616261_p0711356152317"><a name="zh-cn_topic_0000001152616261_p0711356152317"></a><a name="zh-cn_topic_0000001152616261_p0711356152317"></a>(可选)使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1。 </p>
<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>
验证运行, 输出结果OK
#### 前提条件<a name="zh-cn_topic_0000001106176190_section3225481020"></a>
1. 请确保运行环境中适配昇腾AI处理器的PyTorch框架能正常使用。
2. 编译安装Apex前,需参见[配置环境变量](#配置环境变量md)配置好编译过程依赖的环境变量。
#### 安装流程<a name="zh-cn_topic_0000001106176190_section11880164819567"></a>
1. 以root或非root用户登录服务器。
2. 获取apex源代码。
1. 运行如下命令,获取适配昇腾AI处理器的apex源代码。
```
git clone https://gitee.com/ascend/apex.git
```
下载的源码主要目录结构如下所示:
```
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“文件夹目录,执行如下命令安装。
```
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**
```shell
// 根据前述版本,选择对应的测试脚本,以下为1.5.0版本
cd ../
python3 pytorch1.5.0/test/test_npu/test_network_ops/test_div.py
```
# 安装混合精度模块(可选)<a name="安装混合精度模块(可选)"></a>
<h2 id="参考信息md">参考信息</h2>
请用户根据以下功能需要选择使用,若需要安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex/tree/v1.5.0/)进行编译安装Apex模块。
- **[CMake安装方法](#CMake安装方法md)**
- APEX
- O1配置模式:Conv,Matmul等使用float16精度计算,其他如softmax、BN使用float32精度。
- O2配置模式:除BN使用float32精度外,其他部分使用float16精度。
- 静态loss scale:静态设置参数确保混合精度训练收敛。
- 动态loss scale:动态计算loss scale的值并判断是否溢出。
- **[安装7.3.0版本gcc](#安装7-3-0版本gccmd)**
# FAQ
- **[安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配md)**
<h3 id="CMake安装方法md">CMake安装方法</h3>
## 在PIP设置为华为源时,安装requirments.txt中的typing依赖后,会导致python环境错误。
CMake版本升级为3.12.1的方法
在PIP设置为华为源时,需打开requirments.txt文件,删除typing依赖,再执行命令。
1. 获取Cmake软件包。
```
pip3 install -r requirments.txt
```
```
wget https://cmake.org/files/v3.12/cmake-3.12.1.tar.gz --no-check-certificate
```
2. 解压并进入软件包目录。
```
tar -xf cmake-3.12.1.tar.gz
cd cmake-3.12.1/
```
3. 执行配置、编译和安装命令。
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. 设置软连接。
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. 执行如下命令验证是否安装成功。
```
cmake --version
```
如显示“cmake version 3.12.1”则表示安装成功。
## import torch 报找不到libhccl.so错误
未配置环境变量,需通过env.sh脚本配置
```
source pytorch/pytorch1.5.0/src/env.sh
```
## 编译过程执行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”则表示安装成功。
方法二:使用源码编译安装。
1. 获取Cmake软件包。
```
wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
```
2. 解压并进入软件包目录。
```
tar -xf cmake-3.12.0.tar.gz
cd cmake-3.12.0/
```
3. 执行配置、编译和安装命令。
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. 设置软连接。
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. 执行如下命令验证是否安装成功。
```
cmake --version
```
如显示“cmake version 3.12.0”则表示安装成功。
## 命令行安装gcc依赖时提示找不到包、编译时gcc报错问题
部分源下载gcc时会提示无法找到包,需要使用源码编译安装。
<h3 id="安装7-3-0版本gccmd">安装7.3.0版本gcc</h3>
以下步骤请在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)。
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目录:
2. 安装gcc时候会占用大量临时空间,所以先执行下面的命令清空/tmp目录:
```
sudo rm -rf /tmp/*
```
```
sudo rm -rf /tmp/*
```
3. 安装依赖(以CentOS和Ubuntu系统为例)。
- CentOS执行如下命令安装。
3. 安装依赖(以CentOS和Ubuntu系统为例)。
```
yum install bzip2
```
- CentOS执行如下命令安装。
- Ubuntu执行如下命令安装。
```
yum install bzip2
```
```
apt-get install bzip2
```
- Ubuntu执行如下命令安装。
4. 编译安装gcc。
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
```
apt-get install bzip2
```
```
tar -zxvf gcc-7.3.0.tar.gz
```
4. 编译安装gcc。
2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
```
tar -zxvf gcc-7.3.0.tar.gz
```
如果执行上述命令报错,需要执行如下命令在“gcc-7.3.0/“文件夹下下载依赖包:
2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
```
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
```
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
下载好上述依赖包后,重新执行以下命令:
如果执行上述命令报错,需要执行如下命令在“gcc-7.3.0/“文件夹下下载依赖包:
```
./contrib/download_prerequisites
```
```
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>执行配置、编译和安装命令:
```
./contrib/download_prerequisites
```
```
./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
```
如果命令校验失败,需要确认上述依赖包在文件夹中的唯一性,无重复下载,若存在重复的依赖包,需删除。
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
```
> ![img](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}/gcc-7.3.0/bin/gcc /usr/bin/gcc
ln -s ${install_path}/gcc-7.3.0/bin/g++ /usr/bin/g++
ln -s ${install_path}/gcc-7.3.0/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/gcc7.3.0/“。
>![](public_sys-resources/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
若存在pytorch编译不过,请检查软连接的库是否正确。
libstdc++->libstdc++.so.6.0.24(7.3.0)
## 找不到libblas.so问题
环境缺少openblas库,需要安装openblas库
Centos,EulerOS环境
```sh
yum -y install openblas
```
Ubuntu环境
```sh
apt install libopenblas-dev
```
>![](public_sys-resources/icon-notice.gif) **须知:**
>其中“--prefix“参数用于指定linux\_gcc7.3.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.3.0“。
5. 配置环境变量。
## ARM环境pip安装torchvision失败
当用户执行训练时,需要用到gcc升级后的编译环境,因此要在训练脚本中配置环境变量,通过如下命令配置。
可采用源码安装(需先安装昇腾pytorch并通过env.sh配置环境变量)
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
```
git clone -b v0.6.0 https://github.com/pytorch/vision.git
cd vision
python setup.py install
```
其中$\{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/“。
验证torchvision是否安装成功
>![](public_sys-resources/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
```
python -c "import torchvision"
```
若不报错,则说明安装成功
<h3 id="安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配md">安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配</h3>
# 版本说明<a name='版本说明'></a>
#### 现象描述<a name="zh-cn_topic_0000001105856364_zh-cn_topic_0175549220_section197270431505"></a>
安装“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>
对实际结果无影响,无需处理。
版本说明请参阅[ReleseNote](https://gitee.com/ascend/pytorch/blob/v1.5.0/docs/zh/RELEASENOTE/RELEASENOTE.md)
@@ -1,923 +0,0 @@
# 概述
用户可以从Ascend ModelZoo获得PyTorch训练模型,但不支持多机多卡训练,需要根据模型的实际代码进行修改。本文帮助用户快速实现Pytorch模型在多机多卡上使用DDP(Distributed Data Parallel)模式训练。
# 训练流程
PyTorch模型多机多卡训练流程一般包括准备环境、准备模型、修改模型、启动训练四个部分。
1. 准备环境。
准备多机多卡训练的软件、硬件、网络环境,包括开发和运行环境搭建、集群组网链接、芯片IP设置、防火墙设置等。
2. 准备模型。
准备PyTorch模型、数据加载器、优化器等训练需要的模块,从[开源社区](https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch)获取,也可以自行实现。
3. 修改模型。
在基础模型上进行修改,添加DDP需要的代码和环境变量,使模型支持在多机多卡训练。
4. 启动训练。
实现在多机多卡环境启动模型训练并查看训练日志。
# 快速上手
## 概述
通过示例帮助用户快速了解PyTorch模型是如何在多机多卡上训练的。该示例使用自定义模型实现两台计算机8卡训练。两台计算机分别命名为AI Server0、AI Server1,每台计算机上的8个Ascend 910处理器命名为device 0~7。
## 准备环境
首先您需要具有至少两台装有Ascend 910处理器的计算机,并保证每台计算机都正确的安装NPU固件和驱动。
1. 准备开发和运行环境。
在每台计算机上分别完成开发和运行环境准备。
- 完成CANN开发和运行环境的安装,请参见《CANN 软件安装指南》,支持5.0.3以后版本。
- 安装适配NPU的PyTorch,安装方法请参见《PyTorch安装指南》。
2. 准备组网。
通过交换机或光口直连的方式完成计算设备组网搭建,搭建方法请参见《[数据中心训练场景组网](https://support.huawei.com/enterprise/zh/doc/EDOC1100221993/229cc0e4)》。
该示例中采用两台计算机8卡进行训练,故可以采用光口直连的方式准备组网。
3. 配置device IP
在AI Server0上配置device IP。
```shell
hccn_tool -i 0 -ip -s address 192.168.100.101 netmask 255.255.255.0
hccn_tool -i 1 -ip -s address 192.168.101.101 netmask 255.255.255.0
hccn_tool -i 2 -ip -s address 192.168.102.101 netmask 255.255.255.0
hccn_tool -i 3 -ip -s address 192.168.103.101 netmask 255.255.255.0
hccn_tool -i 4 -ip -s address 192.168.100.100 netmask 255.255.255.0
hccn_tool -i 5 -ip -s address 192.168.101.100 netmask 255.255.255.0
hccn_tool -i 6 -ip -s address 192.168.102.100 netmask 255.255.255.0
hccn_tool -i 7 -ip -s address 192.168.103.100 netmask 255.255.255.0
```
在AI Server1上配置device IP。
```shell
hccn_tool -i 0 -ip -s address 192.168.100.111 netmask 255.255.255.0
hccn_tool -i 1 -ip -s address 192.168.101.111 netmask 255.255.255.0
hccn_tool -i 2 -ip -s address 192.168.102.111 netmask 255.255.255.0
hccn_tool -i 3 -ip -s address 192.168.103.111 netmask 255.255.255.0
hccn_tool -i 4 -ip -s address 192.168.100.110 netmask 255.255.255.0
hccn_tool -i 5 -ip -s address 192.168.101.110 netmask 255.255.255.0
hccn_tool -i 6 -ip -s address 192.168.102.110 netmask 255.255.255.0
hccn_tool -i 7 -ip -s address 192.168.103.110 netmask 255.255.255.0
```
4. 配置防火墙
- Ubuntu系统防火墙关闭命令
```shell
ufw disable
- Redhat或CentOS 7系统防火墙关闭命令
```shell
systemctl stop firewalld
## 准备模型
该示例创建一个简单的模型,供用户快速了解多机多卡训练。用户也可以从[开源社区](https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch)获取基于Ascned NPU的PyTorch训练模型。
1. DDP模型。
实现一个简单的样例main.py用于多机多卡训练。
```python
import argparse
import os
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
### 1.基础模块 ###
# 搭建模型
class ToyModel(nn.Module):
def __init__(self):
super(ToyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# 获取数据集方法
def get_dataset():
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
train_sampler = torch.utils.data.distributed.DistributedSampler(my_trainset)
trainloader = torch.utils.data.DataLoader(my_trainset,
batch_size=16, num_workers=2, sampler=train_sampler)
return trainloader
### 2. 初始化参数、数据、模型、损失函数、优化器 ####
# 获取local_rank和addr参数
parser = argparse.ArgumentParser()
parser.add_argument("--local_rank", default=-1, type=int)
parser.add_argument("--addr", default='127.0.0.1', type=str, help='master addr')
FLAGS = parser.parse_args()
local_rank = FLAGS.local_rank
addr = FLAGS.addr
# 设置系统的Master地址和端口
os.environ['MASTER_ADDR'] = addr
os.environ['MASTER_PORT'] = '29501'
# DDP backend初始化
loc = 'npu:{}'.format(local_rank)
torch.npu.set_device(loc)
dist.init_process_group(backend='hccl') # hccl是NPU设备上的后端
# 准备数据,要在DDP初始化之后进行
trainloader = get_dataset()
# 实例化模型
model = ToyModel().to(loc)
# 加载模型权重,在构造DDP模型之前,且只需要在master上加载就行了。
ckpt_path = None
if dist.get_rank() == 0 and ckpt_path is not None:
model.load_state_dict(torch.load(ckpt_path))
# 构造DDP model
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
# 初始化优化器,在构造DDP model之后,用model初始化optimizer。
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# 初始化损失函数
loss_func = nn.CrossEntropyLoss().to(loc)
### 3. 网络训练 ###
model.train()
iterator = range(100)
for epoch in iterator:
trainloader.sampler.set_epoch(epoch)
for data, label in trainloader:
data, label = data.to(local_rank), label.to(local_rank)
optimizer.zero_grad()
prediction = model(data)
loss = loss_func(prediction, label)
loss.backward()
print("loss = %0.3f \n" % loss)
optimizer.step()
# 1. save模型的时候,和DP模式一样,有一个需要注意的点:保存的是model.module而不是model。
# 因为model其实是DDP model,参数是被`model=DDP(model)`包起来的。
# 2. 只需要在进程0上保存一次就行了,避免多次保存重复的东西。
if dist.get_rank() == 0:
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
```
2. 在单机多卡上运行训练,确保模型正确。
1. 用户自行安装模型脚本需要的Python第三方库。
2. 配置NPU环境变量,env_npu.sh脚本请参见附录。
```shell
source env_npu.sh
```
3. 使用torch.distributed.launch执行main.py如下命令在单机多卡上训练模型。
```shell
python -m torch.distributed.launch --nproc_per_node 8 main.py
```
`--nproc_per_node` 为训练卡的数量。
运行成功后,模型在该设备的8张NPU上进行训练。
## 修改模型
该快速上手提供的示例,已经对多机多卡训练进行了适配,不需要对脚本进行修改。其他模型的多机多卡适配修改,请参考”多机多卡训练“章节。
## 启动训练
1. 将main.py模型脚本上传至AI Server0和AI Server1任意路径下。
2. 查询服务器的host IP:
```shell
hostname -I
```
打印出所有IP,第一个为IP当前服务器的host IP。
比如:AI Server0服务器的host IP为:192.168.xx.22, AI Server1服务器的host IP为:192.168.xx.23。
3. 使用AI Server0为master节点,我们现在拉起2 x 8的集群。
在AI server0服务器上启动命令:
```shell
# 设置环境变量,env_npu.sh脚本内容从附录获取
source env_npu.sh
# 关闭HCCL通道白名单
export HCCL_WHITELIST_DISABLE=1
# HCCL初始化通信网卡IP,设置为当前服务器的host IP
export HCCL_IF_IP=192.168.xx.22
#
python3.7 -m torch.distributed.launch --nnodes=2 --node_rank=0 --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
```
在AI server1服务器上启动命令:
```shell
# 设置环境变量,env_npu.sh脚本内容从附录获取
source env_npu.sh
# 关闭HCCL通道白名单
export HCCL_WHITELIST_DISABLE=1
# HCCL初始化通信网卡IP,设置为当前服务器的host IP
export HCCL_IF_IP=192.168.xx.23
python3.7 -m torch.distributed.launch --nnodes=2 --node_rank=1 --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
```
参数说明。
--nnode:指定用来分布式训练脚本的节点数。
--node_rank:多节点分布式训练时,指定当前节点的 rank。
--nproc_per_node:指定当前节点上,使用GPU训练的进程数。
--master_addr:master节点(rank为0)的地址,应该为ip地址或者node 0 的 hostname。
--master_port:指定分布式训练中,master 节点使用的端口号。
--addr:main.py 脚本的入参,输入master节点的host IP。
3. host日志查看
host日志保存在`~/ascend/log`路径下,用户可以到该路径下查看每个host的device日志。
通过该简单的示例您已经完成了多机多卡模型的训练。
# 多机多卡训练
## 常用概念及参数介绍
pytorch分布式训练基本概念
| 基本概念 | 说明 |
| ---------- | ------------------------------------------------------------ |
| AI Server | 带有Ascend 910处理器的计算机,多台计算机用AI Server0+序号表示,如AI Server0、AI Server1。 |
| device | AI Server上Ascend 910卡,多卡用device 0、device 1……device 7表示。 |
| host | AI Server主机。 |
| master | 在多台AI Server选取一台作为master,作为数据通信的主机。 |
| group | 即进程组。默认情况下,只有一个组,采用用默认的就行。 |
| world size | 表示全局的进程并行数,可通过torch.distributed.get_world_size()获取, 在不同进程里,该值是一样的。 |
| rank | 表示当前进的序号, 用于进程间通讯。比如是2x8的集群,world size 就是16,rank在每个进程里依次是0,1,2,…,15。 |
| local_rank | 每台机子上的进程的序号。机器一上有0,1,2,3,4,5,6,7,机器二上也有0,1,2,3,4,5,6,7。一般情况下,你需要用这个local_rank来设置当前模型是跑在当前机器的哪块GPU/NPU上面的。 |
使用torch.distributed.launch启动多卡训练时的参数
| 参数名称 | 说明 |
| ------------------ | ------------------------------------------------------------ |
| **nnodes** | 指定用来分布式训练脚本的节点数 |
| **node_rank** | 多节点分布式训练时,指定当前节点的 rank |
| **nproc_per_node** | 指定当前节点上,使用GPU训练的进程数。建议将该参数设置为当前节点的GPU数量,这样每个进程都能单独控制一个GPU,效率最高。 |
| **master_addr** | master节点(rank为0)的地址,应该为ip地址或者node 0 的 hostname。对于单节点多进程训练的情况,该参数可以设置为 127.0.0.1。 |
| **master_port**: | 指定分布式训练中,master 节点使用的端口号,必须与其他应用的端口号不冲突。 |
## 多机多卡训练流程
### 准备环境
首先您需要具有至少两台AI Server(装有Ascend 910处理器的计算机),并保证每台计算机已安装正确版本的NPU固件和驱动。
1. 准备开发和运行环境。
在每台计算机上分别完成开发和运行环境准备。
- 完成CANN开发和运行环境的安装,请参见《CANN 软件安装指南》,支持5.0.3以后版本。
- 安装适配NPU的PyTorch,安装方法请参见《PyTorch安装指南》。
2. 准备组网。
集群训练由多台装有Ascend 910处理器的计算机完成(最多128台),需要配合交换机组成数据面全连接主备网络,支持8 x n卡训练场景,2台机器可以采用光口直连的方式。搭建方法请参见《[数据中心训练场景组网](https://support.huawei.com/enterprise/zh/doc/EDOC1100221993/229cc0e4)》。
3. 配置device IP
使用hccn_tool工具配置device IP,hccn_tool工具CANN软件以提供。
```shell
hccn_tool -i 0 -ip -s address 192.168.100.111 netmask 255.255.255.0
```
配置device IP需遵守以下规则:
1. AI Server中的第0/4,1/5,2/6,3/7号device需处于同一网段,第0/1/2/3号device在不同网段,第4/5/6/7号device在不同网段。
2. 对于集群场景,各AI Server对应的位置的device需处于同一网段,AI Server0和AI Server1的0号网卡需处于同一网段、1号网卡需要在同一网段
3. 每个IP都不能冲突,相同网段下的IP需在最后8位做区分
使用hccn_tool工具验证device IP是否配置正确。
- 查询每个device的ip。
```shell
hccn_tool -i 0 -ip –g
```
打印查询结果:
> ipaddr:192.168.100.101
>
> netmask:255.255.255.0
- 使用hccn_tool 确保2机器的卡间连通性,从device0 - devcie7 测试8次,确保所有两机间所有卡都连通。
```shell
hccn_tool -i 0 -netdetect -s address xx.xx.xx.xx
hccn_tool -i 0 -net_health –g
```
-i:device序号
-s address:xx.xx.xx.xx是另外一台机器的device i的IP
如果返回`success`则表示已经连通。
4. 配置防火墙
在进行HCCL通信的时候可能出现防火墙拦截通信端口导致通信超时,因此在运行pytorch的集群训练的时候需要注意将服务器上的防火墙关闭。
- Ubuntu系统防火墙关闭命令
```shell
ufw disable
```
- Redhat或CentOS 7系统防火墙关闭命令
```shell
systemctl stop firewalld
```
### 准备模型
准备模型阶段主要有两种方式。
- 从[开源社区](https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch)下载PyTorch训练模型
从开源社区获取的模型已经支持单机多卡训练,请用户参照“修改模型”小节需要修改的项目,根据具体模型完成相应修改。
- 手动搭建PyTorch训练模型
1. 准备PyTorch训练模型、数据加载器
准备PyTorch模型。
```python
class ToyModel(nn.Module):
def __init__(self):
...
def forward(self,x):
...
```
准备数据获取方法。
```python
def get_dataset():
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(my_trainset,batch_size=16,)
return trainloader
trainloader=get_dataset()
```
2. 实例化模型
```python
# 实例化模型
model = ToyModel().to(loc)
# 加载模型权重
if ckpt_path is not None:
model.load_state_dict(torch.load(ckpt_path))
```
3. 准备损失函数和优化器。
```python
# 初始化优化器,在构造DDP model之后,用model初始化optimizer。
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# 初始化损失函数
loss_func = nn.CrossEntropyLoss().to(loc)
```
4. 训练模型
```python
### 3. 网络训练 ###
model.train()
iterator = range(100)
for epoch in iterator:
for data, label in trainloader:
data, label = data.to(local_rank), label.to(local_rank)
optimizer.zero_grad()
prediction = model(data)
loss = loss_func(prediction, label)
loss.backward()
print("loss = %0.3f \n" % loss)
optimizer.step()
torch.save(model.state_dict(), "%d.ckpt" % epoch)
```
### 修改模型
模型修改主要涉及以下6项,包括master ip地址和端口的设置,distributed初始化,模型DDP初始化,数据DDP初始化,优化器初始化,DDP模型训练方法修改。请用户结合初始模型代码,灵活修改。
1. 设置master ip地址和端口,在NPU进行分布式训练使用HCCL进行通信,在PyTorch中使用的是自动拓扑探测的HCCL通信机制,即不需要使用RANK_TABLE_FLIE,但是其依赖于host侧的网卡进行通信,因此需要在代码中设置环境变量来设置通信网卡。
```python
os.environ['MASTER_ADDR'] = xxx.xxx.xxx.xxx
os.environ['MASTER_PORT'] = 'xxx'
```
MASTER_ADDR:设置为集群中master的IP(任意挑选一台作为master即可)
MASTER_PORT:设置为master的一个空闲端口
master ip地址和端口在模型代码中一般会设置为传参的形式,也有可能某些开源代码中设置为"127.0.0.1",需要进行修改。
上述变量需在调用torch.distributed.init_process_group()之前声明。
2. distributed初始化
PyTorch中使用`dist.init_process_group(backend='hccl', world_size=world_size, rank=rank)`来初始化线程组其中参数含义如下。
`backend`:进行分布式训练的使用的通信协议,在NPU上只能使用"hccl"
`world_size`:进行训练时使用的device的总数
`rank`: 当前初始化的device的rank_id,也就是全局的逻辑ID
有两种方法启动多卡训练,分别初始化的方法如下。
- 使用torch.distributed.launch启动多卡训练。
```python
import torch.distributed as dist
dist.init_process_group(backend='hccl') # hccl是NPU设备上的后端
```
- 使用mp.spawn启动多卡训练。
```python
import torch.distributed as dist
def main_worker(pid_idx, device_nums_per_node, args):
args.distributed_rank = args.rank * device_nums_per_node + pid_idx
dist.init_process_group(backend=args.dist_backend, world_size=args.distributed_world_size, rank=args.distributed_rank)
```
其中:
`pid_idx`:device序号。
`device_nums_per_node`:每个AI Server的device数量。
3. 模型DDP初始化
```python
# 实例化模型
model = ToyModel().to(loc)
# 加载模型权重,在构造DDP模型之前,且只需要在master上加载。
if dist.get_rank() == 0 and ckpt_path is not None:
model.load_state_dict(torch.load(ckpt_path))
# 构造DDP model
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
```
4. 数据DDP初始化
```python
def get_dataset():
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
train_sampler = torch.utils.data.distributed.DistributedSampler(my_trainset)
trainloader = torch.utils.data.DataLoader(my_trainset,
batch_size=16, num_workers=2, sampler=train_sampler)
return trainloader
trainloader = get_dataset()
```
5. 损失方法、优化器。
```python
# 初始化优化器,在构造DDP model之后,用model初始化optimizer。
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# 初始化损失函数
loss_func = nn.CrossEntropyLoss().to(loc)
```
6. DDP模型训练
```python
model.train()
iterator = range(100)
for epoch in iterator:
# 设置epoch
trainloader.sampler.set_epoch(epoch)
for data, label in trainloader:
data, label = data.to(local_rank), label.to(local_rank)
optimizer.zero_grad()
prediction = model(data)
loss = loss_func(prediction, label)
loss.backward()
print("loss = %0.3f \n" % loss)
optimizer.step()
# 1. save模型的时候,和DP模式一样,有一个需要注意的点:保存的是model.module而不是model。
# 因为model其实是DDP model,参数是被`model=DDP(model)`包起来的。
# 2. 只需要在进程0上保存一次就行了,避免多次保存重复的东西。
if dist.get_rank() == 0:
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
```
### 启动训练
启动训练提供两种方式,手动启动和shell脚本启动
- 手动启动(使用torch.distributed.launch方式启动)
1. 配置NPU 环境变量,请参考附录提供的env_npu.sh脚本
2. 添加环境变量,多机训练需要增加`HCCL_WHITELIST_DISABLE`和`HCCL_IF_IP`环境变量。
- HCCL_WHITELIST_DISABLE:HCCL通道白名单,一般性设置为1表示关闭白名单。
- HCCL_IF_IP:HCCL初始化通信网卡IP,设置为当前服务器的host网卡IP。
3. 将修改的模型脚本上传至每个AI Server
4. 在每个AI Server上安装必要Python库
5. 任选一个AI Server作为masker节点,并查询每个AI Server的IP。
6. 在每个AI server服务器上启动命令
```
python3 -m torch.distributed.launch --nnodes=${nnodes} --node_rank=i --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
```
其中:
--nnodes:用来分布式训练脚本的AI server数。
--node_rank:AI server的序号,每个AI server有对应的序号。
--nproc_per_node:每个AI server的device数量。
--master_addr:作为maskter节点的AI server IP地址。
--master_port: 作为maskter节点的AI server 端口号。
main.py:请修改为启动脚本名称。
--addr :传入启动脚本的参数,master IP地址。
- 使用OpenMPI启动
1. 安装 OpenMPI开源库
多机多卡环境下分布式训练部署依赖于OpenMPI开源库,参与模型训练的每台服务器都需要安装OpenMPI开源库。目前OpenMPI开源库的版本要求为4.0.1、4.0.2或4.0.3。
执行`mpirun --version`命令检查是否已安装OpenMPI。如果返回`mpirun (Open MPI) 4.0.2 Report bugs to http://www.open-mpi.org/community/help/` ,说明已经安装。如果已安装,且版本为4.0.1、4.0.2或4.0.3其中一个,则无需再安装。
否则请按照如下步骤安装OpenMPI:
1. 访问如下链接下载OpenMPI软件包。例如openmpi-4.0.2.tar.bz2。
https://www.open-mpi.org/software/ompi/v4.0/
2. 以root用户登录安装环境。
3. 将下载的OpenMPI软件包上传到安装环境的某一目录下。
4. 进入软件包所在目录,执行如下命令解压软件包。
```shell
tar -jxvf openmpi-4.0.2.tar.bz2
```
5. 进入解压后的目录,执行如下命令配置、编译和安装。
```shell
./configure --prefix=/usr/local/mpirun4.0.2
make
make install
```
其中“--prefix”参数用于指定OpenMPI安装路径,用户根据实际情况进行修改。
6. 执行vi ~/.bashrc命令,打开.bashrc文件,在文件的最后添加如下环境变量。
```shell
export OPENMPI=/usr/local/mpirun4.0.2
export LD_LIBRARY_PATH=$OPENMPI/lib
export PATH=$OPENMPI/bin:$PATH
```
其中“/usr/local/mpirun4.0.2”为OpenMPI安装路径,用户需要根据实际进行修改。
执行:wq!命令保存文件并退出。
7. 执行如下命令使环境变量生效。
```
source ~/.bashrc
```
8. 安装完成之后,执行如下命令查看安装版本,如果返回正确的版本信息,则说明安装成功。
```
mpirun --version
```
2. 配置AI Server SSH免密登录
如果使用OpenMPI在多机多卡环境下分布式训练部署,需要在每两台服务器之间配置SSH免密登录,确保服务器之间可以互通。具体操作步骤如下:
1. 以root用户登录每台服务器。
2. 配置集群中主机间的可信度。
打开并编辑**/etc/ssh/ssh_config**文件,在文件最后增加如下字段:
```
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
```
3. 在每台服务器上分别打开**/etc/hosts**文件,在该文件中添加本服务器对应的IP地址和主机名,且需要添加到该文件的首行。如果文件中已添加,则跳过此步骤。添加内容示例如下:
```
xxx.xxx.xxx.111 ubuntu
```
其中xxx.xxx.xxx.111为该服务器的IP地址,ubuntu为主机名。
4. 在第一台服务器执行如下命令生成公钥(例如第一台服务器IP为xxx.xxx.xxx.111)。
```
cd ~/.ssh/ # 若没有该目录,请先执行一次ssh localhost
ssh-keygen -t rsa # 生成秘钥,会出现提示,连续点击3次"Enter"即可
mv id_rsa.pub authorized_keys # 将生成的秘钥id_rsa.pub重命名为公钥authorized_keys
```
5. 在其他每台服务器上都生成秘钥,并复制到第一台服务器的authorized_keys文件中。
1. 在其他每台服务器上执行如下命令生成秘钥。
cd ~/.ssh/
ssh-keygen -t rsa
2. 将其他每台服务器上生成的秘钥文件id_rsa.pub下载到本地,并复制该文件中的秘钥。
3. 在第一台服务器内执行如下命令打开公钥文件authorized_keys,将[5.b](#li361025101116 "link to:#li361025101116
ctrl +click to jump")复制的其他每台服务器的秘钥粘贴到第一台服务器的公钥后面。
```
vi ~/.ssh/authorized_keys
```
执行**:wq!**保存该文件。
6. 在其他每台服务器上执行如下命令将第一台服务器制作好的公钥复制到其他每台服务器内。
cd ~/.ssh/
scp root@xxx.xxx.xxx.111:~/.ssh/authorized_keys ./
7. 在每台服务器执行如下命令测试免密登录。
```
ssh 用户名@IP地址
```
例如:在第一台服务器xxx.xxx.xxx.111免密登录服务器xxx.xxx.xxx.222,执行**ssh root@xxx.xxx.xxx.222**命令。
若显示类似如下信息,说明已免密登录服务器xxx.xxx.xxx.222。
```
Linux ubuntu 4.19.28 #1 SMP Tue Jun 23 19:05:23 EDT 2020 x86_64
The programs included with the ubuntu GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
ubuntu GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Tue Sep 15 14:37:21 2020 from 10.254.88.75
```
执行**exit**命令可以退出登录,若显示类似如下信息,说明已退出登录。
```
logout
Connection to xxx.xxx.xxx.222 closed.
```
3. 使用OpenMPI拉起模型训练。
1. 分别为每一个AI server编写启动脚本,如train.sh,并将启动脚本分别移到相应AI server的同一路径下。
```
# 配置NPU环境变量,env_npu.sh脚本参见附录
source env_npu.sh
#关闭HCCL通道白名单
export HCCL_WHITELIST_DISABLE=1
# HCCL初始化通信网卡IP,设置为当前服务器的host IP
export HCCL_IF_IP=xxx.xxx.xx.xxx
python3 -m torch.distributed.launch --nnodes=${nnodes} --node_rank=i --nproc_per_node 8 --master_addr xxx.xxx.xx.xxx --master_port 29501 main.py --addr xxx.xxx.xx.xxx
```
脚本参数请参见手动启动。
2. 编写启动脚本
```
# 配置mpirun环境变量
export PATH=$PATH:/usr/local/mpirun4.0.2/bin
# 执行mpirun工具
mpirun -H xxx.xxx.xxx.xxx:1,xxx.xxx.xxx.xxx:1 \
--bind-to none -map-by slot \
--mca btl_tcp_if_exclude lo,docker0,endvnic\
--allow-run-as-root \
--prefix /usr/local/mpirun4.0.2/ \
./train.sh
```
其中
-H:每个AI server的IP:启动进程数。
--bind-to:绑定进程的策略。
--mca:特定上下文的MCA参数,arg0为参数名,arg1为参数值。
--allow-run-as-root:允许使用root用户运行。
--prefix:mpirun4.0.2路径。
./train.sh:各个AI server的启动脚本路径。
4.
训练成功后可以查看日志信息。
host日志保存在`~/ascend/log`路径下,用户可以到该路径下查看每个host的device日志。
# 附录
NPU环境变量配置脚本env_npu.sh,可使用该脚本进行运行和开发环境变量的配置。
```shell
#!/bin/bash
export install_path=/usr/local/Ascend
if [ -d ${install_path}/toolkit ]; then
export LD_LIBRARY_PATH=/usr/include/hdf5/lib/:/usr/local/:/usr/local/lib/:/usr/lib/:${install_path}/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons:${path_lib}:${LD_LIBRARY_PATH}
export PATH=${install_path}/fwkacllib/ccec_compiler/bin:${install_path}/fwkacllib/bin:$PATH
export PYTHONPATH=${install_path}/fwkacllib/python/site-packages:${install_path}/tfplugin/python/site-packages:${install_path}/toolkit/python/site-packages:$PYTHONPATH
export PYTHONPATH=/usr/local/python3.7.5/lib/python3.7/site-packages:$PYTHONPATH
export ASCEND_OPP_PATH=${install_path}/opp
else
if [ -d ${install_path}/nnae/latest ];then
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
export PYTHONPATH=${install_path}/nnae/latest/fwkacllib/python/site-packages/:${install_path}/nnae/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:${install_path}/nnae/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
export ASCEND_AICPU_PATH=${install_path}/nnae/latest
else
export LD_LIBRARY_PATH=/usr/local/:/usr/local/lib/:/usr/lib64/:/usr/lib/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64-linux-gnu:$LD_LIBRARY_PATH
export PATH=$PATH:${install_path}/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin/:${install_path}/ascend-toolkit/latest/toolkit/tools/ide_daemon/bin/
export ASCEND_OPP_PATH=${install_path}/ascend-toolkit/latest/opp/
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
export PYTHONPATH=${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/:${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
export ASCEND_AICPU_PATH=${install_path}/ascend-toolkit/latest
fi
fi
#将Host日志输出到串口,0-关闭/1-开启
export ASCEND_SLOG_PRINT_TO_STDOUT=0
#设置默认日志级别,0-debug/1-info/2-warning/3-error
export ASCEND_GLOBAL_LOG_LEVEL=3
#设置Event日志开启标志,0-关闭/1-开启
export ASCEND_GLOBAL_EVENT_ENABLE=0
#设置是否开启taskque,0-关闭/1-开启
export TASK_QUEUE_ENABLE=1
#HCCL白名单开关,1-关闭/0-开启
export HCCL_WHITELIST_DISABLE=1
#设置device侧日志登记为error
${install_path}/driver/tools/msnpureport -g error -d 0
${install_path}/driver/tools/msnpureport -g error -d 1
${install_path}/driver/tools/msnpureport -g error -d 2
${install_path}/driver/tools/msnpureport -g error -d 3
${install_path}/driver/tools/msnpureport -g error -d 4
${install_path}/driver/tools/msnpureport -g error -d 5
${install_path}/driver/tools/msnpureport -g error -d 6
${install_path}/driver/tools/msnpureport -g error -d 7
#关闭Device侧Event日志
${install_path}/driver/tools/msnpureport -e disable
path_lib=$(python3.7 -c """
import sys
import re
result=''
for index in range(len(sys.path)):
match_sit = re.search('-packages', sys.path[index])
if match_sit is not None:
match_lib = re.search('lib', sys.path[index])
if match_lib is not None:
end=match_lib.span()[1]
result += sys.path[index][0:end] + ':'
result+=sys.path[index] + '/torch/lib:'
print(result)"""
)
echo ${path_lib}
export LD_LIBRARY_PATH=/usr/local/python3.7.5/lib/:${path_lib}:$LD_LIBRARY_PATH
```
@@ -10,6 +10,7 @@
- [注册算子开发](#注册算子开发md)
- [概述](#概述md)
- [PyTorch1.5.0 注册算子开发](#PyTorch1-5-0-注册算子开发md)
- [PyTorch1.8.1 注册算子开发](#PyTorch1-8-1-注册算子开发md)
- [算子适配插件开发](#算子适配插件开发md)
- [编译和安装PyTorch框架](#编译和安装PyTorch框架md)
- [算子功能验证](#算子功能验证md)
@@ -135,7 +136,7 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
- 需安装3.12.0及以上版本的CMake,安装方法请参考[CMake安装方法](#CMake安装方法md)。
- 需确保已安装7.3.0以上版本的gcc,7.3.0版本gcc具体安装及使用方式请参见《CANN 软件安装指南》中的“安装7.3.0版本gcc”章节。
- 需确保环境中已安装git工具,以Ubuntu和CentOS系统为例,命令如下:
- Ubuntu、EulerOS系统
- Ubuntu系统
```
apt-get install patch
@@ -164,7 +165,8 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
- 当前昇腾AI处理器中支持的算子以及对应的算子约束可以通过以下两种方式查询。
- 命令行开发方式下,您可以参见《CANN 算子清单 \(Ascend 910\)》进行离线查询。
- MindStudio开发方式下,您可以通过MindStudio进行在线查询,详细查看方法可参见《MindStudio 用户指南》中的“算子&模型速查”章节。
- 当前PyTorch适配的算子列表可以参见[《PyTorch API支持清单_1.5.0》](https://gitee.com/ascend/pytorch/blob/v1.5.0/docs/zh/PyTorch%20API%E6%94%AF%E6%8C%81%E6%B8%85%E5%8D%95_1.5.0.md) 。
- 当前PyTorch适配的算子列表可以参见《PyTorch适配算子清单》。
<h2 id="算子适配开发md">算子适配开发</h2>
@@ -186,19 +188,20 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
<h3 id="获取PyTorch源码md">获取PyTorch源码</h3>
目前只支持PyTorch1.5.0和1.8.1版本,PyTorch源码获取请参见[《PyTorch安装指南》](https://gitee.com/ascend/pytorch/blob/v1.5.0/docs/zh/PyTorch%E5%AE%89%E8%A3%85%E6%8C%87%E5%8D%97/PyTorch%E5%AE%89%E8%A3%85%E6%8C%87%E5%8D%97.md) 中“安装PyTorch框架”章节,完成在"pytorch/pytorch"目录生成适配昇腾AI处理器的全量代码步骤。将在pytorch/pytorch目录中进行PyTorch 算子适配开发。
目前只支持PyTorch1.5.0和1.8.1版本,PyTorch源码获取请参见《PyTorch安装指南》中“安装PyTorch框架”章节,完成在"pytorch/pytorch"目录生成适配昇腾AI处理器的全量代码步骤。将在pytorch/pytorch目录中进行PyTorch 算子适配开发。
<h3 id="注册算子开发md">注册算子开发</h3>
- **[概述](#概述md)**
- **[PyTorch1.5.0 注册算子开发](#PyTorch1-5-0-注册算子开发md)**
- **[PyTorch1.5.0 注册算子开发](#PyTorch1-5-0-注册算子开发md)**
- **[PyTorch1.8.1 注册算子开发](#PyTorch1-8-1-注册算子开发md)**
<h4 id="概述md">概述</h4>
当前制定的NPU适配派发原则是NPU算子的派发不经过框架公共函数,直接派发成NPU适配的函数,即算子执行调用栈中只包含NPU适配的函数调用,不包含框架公共函数。PyTorch框架在编译时,会根据 native\_functions.yaml 的定义,按框架中定义的类型和设备分发原则,生成相应的新算子的中间层的调用说明。对于NPU,会生成在 pytorch/pytorch/build/aten/src/ATen/NPUType.cpp。
当前制定的NPU适配派发原则是NPU算子的派发不经过框架公共函数,直接派发成NPU适配的函数,即算子执行调用栈中只包含NPU适配的函数调用,不包含框架公共函数。PyTorch框架在编译时,会根据 native\_functions.yaml 的定义,按框架中定义的类型和设备分发原则,生成相应的新算子的中间层的调用说明。对于NPU,会生成在 build/aten/src/ATen/NPUType.cpp。
<h4 id="PyTorch1-5-0-注册算子开发md">PyTorch1.5.0 注册算子开发</h4>
@@ -330,6 +333,96 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
supports_named_tensor: True
```
<h4 id="PyTorch1-8-1-注册算子开发md">PyTorch1.8.1 注册算子开发</h4>
##### 注册算子开发方法<a name="section575212111125"></a>
1. 打开native\_functions.yaml文件。
native\_functions.yaml 文件中,定义了所有算子函数原型,包括函数名称和参数等信息,每个算子函数支持不同硬件平台的派发信息。该文件所在路径为pytorch/aten/src/ATen/native/native\_functions.yaml。
2. 确定需要派发函数。
- yaml 中已存在的算子
将所有与待适配算子相关的函数进行派发。
- yaml中未存在的自定义算子
由于yaml中没有相关算子的信息,需要手动添加相关函数,包括函数名,参数信息,返回类型信息。添加规则及方法请参见“pytorch/aten/src/ATen/native/README.md“。
```
- func:适配算子名称(输入参数信息) -> 返回类型
```
##### 示例<a name="section434031421219"></a>
以torch.add\(\)算子为例介绍注册算子开发过程。
1. 打开native\_functions.yaml文件。
2. 搜索相关函数。
在yaml中搜索add,找到与add算子相关的函数描述func。由于add是PyTorch内置算子,不需要手动添加func。若是自定义算子,需要手动添加func。
3. 确定算子相关函数名称及其类型的func描述。
- add.Tensor 的函数分发描述。
```
- func: add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor
structured_delegate: add.out
variants: function, method
dispatch:
SparseCPU, SparseCUDA: add_sparse
MkldnnCPU: mkldnn_add
```
- add.Scalar 的函数分发描述。
```
- func: add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor
variants: function, method
dispatch:
DefaultBackend: add
```
- add\_.Tensor 的函数分发描述。
```
- func: add_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
variants: method
structured_delegate: add.out
dispatch:
SparseCPU, SparseCUDA: add_sparse_
MkldnnCPU: mkldnn_add_
```
- add\_.Scalar 的函数分发描述。
```
- func: add_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)
variants: method
dispatch:
DefaultBackend: add_
```
- add.out 的函数分发描述。
```
- func: add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
structured: True
structured_inherits: TensorIteratorBase
dispatch:
CPU, CUDA: add_out
SparseCPU: add_out_sparse_cpu
SparseCUDA: add_out_sparse_cuda
MkldnnCPU: mkldnn_add_out
```
<h3 id="算子适配插件开发md">算子适配插件开发</h3>
#### 简介<a name="zh-cn_topic_0000001125315877_section16410139174517"></a>
@@ -340,7 +433,7 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
1. 创建适配插件文件。
NPU TBE算子适配文件保存在pytorch/pytorch/aten/src/ATen/native/npu目录下,命名风格采用大驼峰,命名格式:<算子名\> + <KernelNpu\>.cpp,如:AddKernelNpu.cpp。
NPU TBE算子适配文件保存在pytorch/aten/src/ATen/native/npu目录下,命名风格采用大驼峰,命名格式:<算子名\> + <KernelNpu\>.cpp,如:AddKernelNpu.cpp。
2. 引入依赖头文件。
@@ -353,10 +446,24 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
根据注册算子开发中的分发函数确定自定义算子适配主体函数。
4. 分别实现适配主体函数。
4. 分别实现适配主体函数。
实现算子适配主题函数,根据TBE算子原型构造得到对应的input、output、attr。
实现算子适配主题函数,根据TBE算子原型构造得到对应的input、output、attr。
5. (仅1.8.1版本需要操作该步骤)使用TORCH\_LIBRARY\_IMPL宏关联注册算子开发中native\_functions.yaml文件的算子描述func。
TORCH\_LIBRARY\_IMPL是PyTorch提供的用于注册算子分发的宏,使用方法如下。
```
Torch_LIBRARY_IMPL(aten, PrivateUse1, m){
m.impl("yaml中算子func方法名1", TORCH_FN("对应的适配主体函数名1"))
m.impl("yaml中算子func方法名2", TORCH_FN("对应的适配主体函数名2"))
}
```
- aten为命名空间,可以根据实现文件命名空间自行定义。
- PrivateUse1为dispatchKey, 固定设置NPU。
- m为固定字段。
#### 示例<a name="zh-cn_topic_0000001125315877_section18021337113012"></a>
@@ -511,6 +618,14 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
}
```
5. (仅1.8.1版本需要操作该步骤)使用TORCH\_LIBRARY\_IMPL宏关联注册算子。
```
TORCH_LIBRARY_IMPL(aten, NPU, m) {
m.impl("add.Tensor", TORCH_FN(add_npu));
m.impl("add_.Tensor", TORCH_FN(add_npu_));
m.impl("add.out", TORCH_FN(add_out_npu));}
```
>![](public_sys-resources/icon-note.gif) **说明:**
@@ -535,7 +650,7 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
bash build.sh --python=3.8
```
请指定环境中python版本进行编译。编译成功后,会在pytorch/pytorch/dist”文件夹目录下生成二进制包 torch-\*.whl ,例如:torch-1.5.0+ascend.post3-cp37-cp37m-linux\_x86.whl。
请指定环境中python版本进行编译。编译成功后,会在pytorch/pytorch/dist”文件夹目录下生成二进制包 torch-\*.whl ,例如:torch-1.5.0+ascend.post3-cp37-cp37m-linux\_x86.whl或者torch-1.8.1+ascend-cp37-cp37m-linux\_x86.whl。
#### 安装PyTorch框架<a name="zh-cn_topic_0000001125736777_section119821419153412"></a>
@@ -549,9 +664,7 @@ pip3 install --upgrade torch-1.5.0+ascend.post3-cp37-cp37m-linux_{arch}.whl
**\{arch\}**表示架构信息,为aarch64或x86\_64。
>![](public_sys-resources/icon-note.gif) **说明:**
>--upgrade:卸载环境中已安装的PyTorch插件软件包再执行更新安装。
>
>可以通过执行如下命令查询环境上是否已安装PyTorch。
>若环境中已安装PyTorch时,需要先卸载环境中已安装的PyTorch软件包再执行,可以通过执行如下命令查询环境上是否已安装PyTorch。
>**pip3 list | grep torch**
修改代码之后,需要重新执行“编译”和“安装”PyTorch过程。
@@ -575,7 +688,7 @@ pip3 install --upgrade torch-1.5.0+ascend.post3-cp37-cp37m-linux_{arch}.whl
进行自定义算子功能验证,通过PyTorch前端构造自定义算子的函数并运行验证。
在https://gitee.com/ascend/pytorch 中 "pytorch/pytorch1.5..0/test/test\_npu"目录下提供了测试用例及测试工具,供用户参考。
在https://gitee.com/ascend/pytorch中 "pytorch/test/test\_npu"目录下提供了测试用例及测试工具,供用户参考。
<h3 id="实现过程md">实现过程</h3>
@@ -585,14 +698,12 @@ pip3 install --upgrade torch-1.5.0+ascend.post3-cp37-cp37m-linux_{arch}.whl
#### 操作步骤<a name="zh-cn_topic_0000001164276377_section02504494109"></a>
1. 设置环境变量。
1. 设置环境变量。
```
# 进行环境变量设置。具体如下(以root用户安装,安装路径为默认路径为例):
usr/local/Ascend/ascend-toolkit/set_env.sh
# 进行环境变量设置。具体如下(以非root用户安装,安装路径为默认路径为例):
${HOME}/Ascend/ascend-toolkit/set_env.sh
```
```
# 进行环境变量设置。具体如下(以HwHiAiUser用户安装,安装路径为默认路径为例):
. /home/HwHiAiUser/Ascend/ascend-toolkit/set_env.sh
```
2. 编写测试脚本。以add算子为例,在“pytorch/test/test\_npu/test\_network\_ops“路径下编写测试脚本文件: test\_add.py。
@@ -691,9 +802,7 @@ pillow==5.3.0安装失败。
执行以下命令安装所需依赖。
```
apt-get install libjpeg python-devel zlib-devel libjpeg-turbo-devel #Ubuntu、EulerOS
yum install libjpeg python-devel zlib-devel libjpeg-turbo-devel #CentOS
apt-get install libjpeg python-devel zlib-devel libjpeg-turbo-devel
```
<h3 id="pip3-7-install-torchvision安装失败md">pip3.7 install torchvision安装失败</h3>
@@ -738,15 +847,13 @@ pip3.7 install torchvision --no-deps
设置日志输出到屏幕,重定向到指定文本文件
1. 设置环境变量,将当前用户的日志到屏幕。
1. 设置环境变量,将当前用户的日志到屏幕。
```
export SLOG_PRINT_TO_STDOUT=1
export ASCEND_GLOBAL_LOG_LEVEL=1
#0:debug等级;1:info;2:warning;3:error
```
```
export SLOG_PRINT_TO_STDOUT=1
```
设置完成后,直接运行测试用例,就可以将相关的日志输出到屏幕,为了方便查看和回溯,建议根据需要使用[2](#zh-cn_topic_0000001125315889_li168732325719)运行。
设置完成后,直接运行测试用例,就可以将相关的日志输出到屏幕,为了方便查看和回溯,建议根据需要使用[2](#zh-cn_topic_0000001125315889_li168732325719)运行。
2. <a name="zh-cn_topic_0000001125315889_li168732325719"></a>运行测试用例时,将日志重定向到指定文件。
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

File diff suppressed because it is too large Load Diff
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

+1 -377
View File
@@ -1,25 +1,4 @@
# 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)
- [特性修改](#特性修改md)
- [已修复问题](#已修复问题md)
- [已知问题](#已知问题md)
- [兼容性](#兼容性md)
- [FrameworkPTAdapter 2.0.4](#FrameworkPTAdapter-2-0-4md)
- [用户须知](#用户须知md)
- [新增特性](#新增特性md)
- [特性修改](#特性修改md)
- [已修复问题](#已修复问题md)
- [已知问题](#已知问题md)
- [兼容性](#兼容性md)
# FrameworkPTAdapter 2.0.3 版本说明书
- [FrameworkPTAdapter 2.0.3](#FrameworkPTAdapter-2-0-3md)
- [用户须知](#用户须知md)
- [新增特性](#新增特性md)
@@ -34,361 +13,6 @@
- [已修复问题](#已修复问题-3md)
- [已知问题](#已知问题-4md)
- [兼容性](#兼容性-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>
<h3 id="用户须知md">用户须知</h3>
本框架基于Facebook主导的开源PyTorch1.5.0和1.8.1版本进行修改,延续原生的PyTorch特性,使用NPU进行动态图训练;以算子粒度进行模型适配,代码重用性好,支持现有的网络只修改设备类型或数据类型,即可迁移到NPU上使用。
PyTorch1.8.1版本采用插件化适配方式,延续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>
<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>支持AOE调优工具</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>支持AOE自动调优工具,提升模型性能。</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></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> 新增适配算子开发(详见API清单)。</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="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>将NPU适配代码解耦迁移至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>支持AOE调优工具</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>支持AOE自动调优工具,提升模型性能。</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>框架API满足度提升</p>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>支持昇腾PyTorch1.5.0版本已适配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-2-0-4md">FrameworkPTAdapter 2.0.4</h2>
<h3 id="用户须知md">用户须知</h3>
本框架基于Facebook主导的开源PyTorch1.5.0和1.8.1版本进行修改,延续原生的PyTorch特性,使用NPU进行动态图训练;以算子粒度进行模型适配,代码重用性好,支持现有的网络只修改设备类型或数据类型,即可迁移到NPU上使用。
PyTorch1.8.1版本延续PyTorch1.5.0特性,功能基本保持一致,对后端算子适配提供较好开发体验。当期1.8.1版本仅支持Resent50网络模型。
<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="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.5.0特性</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="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>支持IR与对应TBE算子映射,支持在GPU侧加载NPU侧dump数据对比。</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>支持E2E prof工具</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>将PyTorch原生profiling工具和cann prof工具获取到的性能数据统一集成,实现端到端的模型和算子性能分析。</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></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> 新增适配算子开发(详见算子清单)。</p>
</td>
</tr>
<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.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>支持AMP</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>支持PyTorch原生自动混合精度。</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>支持Profiling</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>支持PyTorch原生Profiling功能。</p>
</td>
</tr>
<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>OS兼容性</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>OS兼容性</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>新增支持Ubuntu20.04 x86+arm,Euler 2.10 arm系统。</p>
</td>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Python版本兼容性</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>支持python3.9环境编译及使用(仅PyTorch1.8.1)。</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-2-0-3md">FrameworkPTAdapter 2.0.3</h2>
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

File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

+584 -2550
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+9 -16
View File
@@ -20,7 +20,7 @@ import sys
import subprocess
from abc import ABCMeta, abstractmethod
DEFAULT_UT_FILE = 'test/test_npu/pytorch_resnet.py'
DEFAULT_UT_FILE = 'test/test_npu/test_add.py'
class AccurateTest(metaclass=ABCMeta):
@abstractmethod
@@ -30,10 +30,9 @@ class AccurateTest(metaclass=ABCMeta):
"""
raise Exception("abstract method.")
@staticmethod
def find_ut_by_regex(regex, mindepth=2):
def find_ut_by_regex(self, regex):
ut_files = []
cmd = "find {} -mindepth {} -name {}".format('test/test_npu', mindepth, regex)
cmd = "find {} -name {}".format('test/test_npu', regex)
status, output = subprocess.getstatusoutput(cmd)
if status:
pass # 对于找不到的暂时不作处理
@@ -112,11 +111,9 @@ class TestMgr():
if os.path.exists(changed_file):
exist_ut_file.append(changed_file)
self.ut_files = exist_ut_file
for ut in self.ut_files:
if ut.split('/')[-1] == 'run_tests.py':
self.ut_files.remove(ut)
self.ut_files.append(DEFAULT_UT_FILE)
if len(self.ut_files) == 0:
self.ut_files.append(DEFAULT_UT_FILE)
def get_ut_files(self):
return self.ut_files
@@ -128,7 +125,7 @@ class TestMgr():
def print_ut_files(self):
print("ut files:")
for ut_file in self.ut_files:
for ut_file in ut_files:
print(ut_file)
@@ -178,7 +175,7 @@ def exec_ut(ut_files):
return ret_status
def main():
if __name__ == "__main__":
cur_dir = os.path.abspath(os.path.dirname(__file__))
modify_files = os.path.join(cur_dir, 'modify_files.txt')
test_mgr = TestMgr()
@@ -190,8 +187,4 @@ def main():
test_mgr.print_ut_files()
ret = exec_ut(ut_files)
sys.exit(ret)
if __name__ == "__main__":
main()
sys.exit(ret)
@@ -59,10 +59,6 @@ struct CAFFE2_API NPUHooksInterface {
TORCH_CHECK(false, "Cannot initialize NPU without building library with options USE_NPU = 1.", NPU_HELP);
}
virtual bool isPinnedPtr(void* data) const {
return false;
}
virtual Generator* getDefaultNPUGenerator(DeviceIndex device_index = -1) const {
TORCH_CHECK(false, "Cannot get default NPU generator without ATen_cuda library. ", NPU_HELP);
}
@@ -669,8 +669,6 @@
dispatch:
CPU: _bincount_cpu
CUDA: _bincount_cuda
npu_dispatch:
NPU: bincount_npu
- func: bitwise_not(Tensor self) -> Tensor
use_c10_dispatcher: full
@@ -1416,8 +1414,6 @@
NPU: _embedding_bag_npu
- func: _embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, int num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights) -> Tensor
npu_dispatch:
NPU: _embedding_bag_backward_npu
- func: _embedding_bag_sparse_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, int num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights) -> Tensor
@@ -1769,21 +1765,19 @@
# `align_corners = True`.
- func: grid_sampler(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
use_c10_dispatcher: full
npu_dispatch:
NPU: grid_sampler_npu
- func: grid_sampler_2d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
use_c10_dispatcher: full
dispatch:
CPU: grid_sampler_2d_cpu
CUDA: grid_sampler_2d_cuda
npu_dispatch:
NPU: grid_sampler_2d_npu
- func: grid_sampler_2d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> (Tensor, Tensor)
dispatch:
CPU: grid_sampler_2d_backward_cpu
CUDA: grid_sampler_2d_backward_cuda
npu_dispatch:
NPU: grid_sampler_2d_backward_npu
- func: grid_sampler_3d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
use_c10_dispatcher: full
@@ -2672,8 +2666,6 @@
- func: batch_norm_gather_stats_with_counts(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, int[] counts) -> (Tensor, Tensor)
dispatch:
CUDA: batch_norm_gather_stats_with_counts_cuda
npu_dispatch:
NPU: batch_norm_gather_stats_with_counts_npu
- func: native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
dispatch:
@@ -2691,8 +2683,6 @@
- func: batch_norm_backward_elemt(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, Tensor mean_dy, Tensor mean_dy_xmu) -> Tensor
dispatch:
CUDA: batch_norm_backward_elemt_cuda
npu_dispatch:
NPU: batch_norm_backward_elemt_npu
- func: batch_norm_update_stats(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum) -> (Tensor, Tensor)
dispatch:
@@ -3732,8 +3722,6 @@
dispatch:
CPU: unique_consecutive_cpu
CUDA: unique_consecutive_cuda
npu_dispatch:
NPU: unique_consecutive_npu
- func: unique_dim_consecutive(Tensor self, int dim, bool return_inverse=False, bool return_counts=False) -> (Tensor, Tensor, Tensor)
variants: function
@@ -4691,9 +4679,7 @@
- func: rnn_relu.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor)
- func: lstm_cell(Tensor input, Tensor[] hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> (Tensor, Tensor)
npu_dispatch:
NPU: lstm_cell_npu
- func: gru_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor
- func: rnn_tanh_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor
@@ -5192,7 +5178,7 @@
dispatch:
CPU: __lshift__
CUDA: __lshift__
npu_dispatch:
npu_dispatch:
NPU: __lshift___npu
- func: __lshift__.Tensor(Tensor self, Tensor other) -> Tensor
@@ -5201,7 +5187,7 @@
dispatch:
CPU: __lshift__
CUDA: __lshift__
npu_dispatch:
npu_dispatch:
NPU: __lshift___npu
- func: __ilshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
@@ -6592,7 +6578,7 @@
CUDA: legacy::cuda::_th_index_copy_
npu_dispatch:
NPU: index_copy_npu_
- func: _cumsum(Tensor self, int dim) -> Tensor
use_c10_dispatcher: full
dispatch:
@@ -7648,16 +7634,12 @@
dispatch:
CPU: reflection_pad1d_out_cpu
CUDA: reflection_pad1d_out_cuda
npu_dispatch:
NPU: reflection_pad1d_out_npu
- func: reflection_pad1d(Tensor self, int[2] padding) -> Tensor
python_module: nn
dispatch:
CPU: reflection_pad1d_cpu
CUDA: reflection_pad1d_cuda
npu_dispatch:
NPU: reflection_pad1d_npu
- func: reflection_pad1d_backward.grad_input(Tensor grad_output, Tensor self, int[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
python_module: nn
@@ -7708,32 +7690,24 @@
dispatch:
CPU: replication_pad1d_out_cpu
CUDA: replication_pad1d_out_cuda
npu_dispatch:
NPU: replication_pad1d_out_npu
- func: replication_pad1d(Tensor self, int[2] padding) -> Tensor
python_module: nn
dispatch:
CPU: replication_pad1d_cpu
CUDA: replication_pad1d_cuda
npu_dispatch:
NPU: replication_pad1d_npu
- func: replication_pad1d_backward.grad_input(Tensor grad_output, Tensor self, int[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!)
python_module: nn
dispatch:
CPU: replication_pad1d_backward_out_cpu
CUDA: replication_pad1d_backward_out_cuda
npu_dispatch:
NPU: replication_pad1d_backward_out_npu
- func: replication_pad1d_backward(Tensor grad_output, Tensor self, int[2] padding) -> Tensor
python_module: nn
dispatch:
CPU: replication_pad1d_backward_cpu
CUDA: replication_pad1d_backward_cuda
npu_dispatch:
NPU: replication_pad1d_backward_npu
- func: replication_pad2d.out(Tensor self, int[4] padding, *, Tensor(a!) out) -> Tensor(a!)
python_module: nn
@@ -8336,21 +8310,11 @@
device_guard: False
supports_named_tensor: True
- func: get_npu_format(Tensor self) -> int
variants: function, method
npu_dispatch_only:
NPU: get_npu_format
- func: npu_format_cast(Tensor self, int acl_format) -> Tensor
variants: function, method
npu_dispatch_only:
NPU: format_cast_npu
- func: npu_format_cast.Tensor(Tensor self, Tensor dst) -> Tensor
variants: function, method
npu_dispatch_only:
NPU: format_cast_npu
- func: npu_format_cast_.acl_format(Tensor(a!) self, int acl_format) -> Tensor(a!)
variants: method
npu_dispatch_only:
@@ -8361,6 +8325,11 @@
npu_dispatch_only:
NPU: format_cast_npu_
- func: npu_transpose_to_contiguous(Tensor self) -> Tensor
variants: function, method
npu_dispatch_only:
NPU: transpose_to_contiguous_npu
- func: npu_transpose(Tensor self, int[] perm) -> Tensor
variants: function, method
npu_dispatch_only:
@@ -8448,11 +8417,6 @@
variants: function, method
npu_dispatch_only:
NPU: nms_v4_npu
- func: npu_nms_rotated(Tensor self, Tensor scores, float iou_threshold, float scores_threshold=0, int max_output_size=-1, int mode=0) -> (Tensor, Tensor)
variants: function, method
npu_dispatch_only:
NPU: nms_rotated_npu
- func: npu_lstm(Tensor input, Tensor weight, Tensor bias, Tensor seqMask, Tensor h, Tensor c, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, bool flagSeq, bool direction) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
variants: function
@@ -8561,14 +8525,6 @@
npu_dispatch_only:
NPU: max_v1_npu
- func: npu_min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices)
npu_dispatch_only:
NPU: min_v1_npu
- func: npu_min.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices)
npu_dispatch_only:
NPU: min_v1_npu
- func: npu_scatter(Tensor self, Tensor indices, Tensor updates, int dim) -> Tensor
variants: function, method
npu_dispatch_only:
@@ -8578,22 +8534,10 @@
npu_dispatch_only:
NPU: max_backward_npu
- func: npu_min_backward(Tensor grad, int dim, Tensor indices, int[] sizes, bool keepdim=False) -> Tensor
npu_dispatch_only:
NPU: min_backward_npu
- func: npu_apply_adam.old(Tensor(a!) var, Tensor(b!) m, Tensor(c!) v, Scalar beta1_power, Scalar beta2_power, Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, bool? use_locking, bool? use_nesterov) -> (Tensor(a!), Tensor(b!), Tensor(c!))
- func: npu_apply_adam(Tensor(a!) var, Tensor(b!) m, Tensor(c!) v, Scalar beta1_power, Scalar beta2_power, Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, bool? use_locking, bool? use_nesterov) -> (Tensor(a!), Tensor(b!), Tensor(c!))
npu_dispatch_only:
NPU: apply_adam_npu
- func: npu_apply_adam(Scalar beta1_power, Scalar beta2_power, Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, bool? use_locking, bool? use_nesterov) -> (Tensor var, Tensor m, Tensor v)
npu_dispatch_only:
NPU: npu_apply_adam
- func: npu_apply_adam.out(Scalar beta1_power, Scalar beta2_power, Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, bool? use_locking, bool? use_nesterov, *, Tensor(a!) var, Tensor(b!) m, Tensor(c!) v) -> (Tensor(a!), Tensor(b!), Tensor(c!))
npu_dispatch_only:
NPU: apply_adam_out_npu
- func: npu_layer_norm_eval(Tensor input, int[] normalized_shape, Tensor? weight=None, Tensor? bias=None, float eps=1e-05) -> Tensor
npu_dispatch_only:
NPU: layer_norm_eval_npu
@@ -8664,16 +8608,6 @@
variants: function, method
npu_dispatch_only:
NPU: yolo_boxes_encode_npu
- func: npu_rotated_box_encode(Tensor self, Tensor gt_bboxes, Tensor weight) -> Tensor
variants: function
npu_dispatch_only:
NPU: rotated_box_encode_npu
- func: npu_rotated_box_decode(Tensor self, Tensor deltas, Tensor weight) -> Tensor
variants: function
npu_dispatch_only:
NPU: rotated_box_decode_npu
- func: npu_grid_assign_positive(Tensor self, Tensor overlaps, Tensor box_responsible_flags, Tensor max_overlaps, Tensor argmax_overlaps, Tensor gt_max_overlaps, Tensor gt_argmax_overlaps, int num_gts, float pos_iou_thr, float min_pos_iou, bool gt_max_assign_all) -> Tensor
variants: function, method
@@ -8702,120 +8636,14 @@
npu_dispatch_only:
NPU: linear_backward_npu
- func: npu_bert_apply_adam.old(Tensor(a!) var, Tensor(b!) m, Tensor(c!) v, Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, Scalar max_grad_norm, Scalar global_grad_norm, Scalar weight_decay, Scalar? step_size=None, int adam_mode=0) -> (Tensor(a!), Tensor(b!), Tensor(c!))
- func: npu_bert_apply_adam(Tensor(a!) var, Tensor(b!) m, Tensor(c!) v, Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, Scalar max_grad_norm, Scalar global_grad_norm, Scalar weight_decay) -> (Tensor(a!), Tensor(b!), Tensor(c!))
npu_dispatch_only:
NPU: bert_apply_adam_npu
- func: npu_bert_apply_adam(Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, Scalar max_grad_norm, Scalar global_grad_norm, Scalar weight_decay, Scalar? step_size=None, int adam_mode=0) -> (Tensor var, Tensor m, Tensor v)
npu_dispatch_only:
NPU: npu_bert_apply_adam
- func: npu_bert_apply_adam.out(Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, Scalar max_grad_norm, Scalar global_grad_norm, Scalar weight_decay, Scalar? step_size=None, int adam_mode=0, *, Tensor(a!) var, Tensor(b!) m, Tensor(c!) v) -> (Tensor(a!), Tensor(b!), Tensor(c!))
npu_dispatch_only:
NPU: bert_apply_adam_out_npu
- func: npu_giou(Tensor self, Tensor gtboxes, bool trans=False, bool is_cross=False, int mode=0) -> Tensor
npu_dispatch_only:
NPU: giou_npu
- func: npu_giou_backward(Tensor grad, Tensor bboxes, Tensor gtboxes, bool trans=False, bool is_cross=False, int mode=0) -> (Tensor, Tensor)
npu_dispatch_only:
NPU: giou_backward_npu
- func: npu_silu(Tensor self) -> Tensor
npu_dispatch_only:
NPU: silu_npu
- func: npu_silu_(Tensor(a!) self) -> Tensor(a!)
npu_dispatch_only:
NPU: silu_npu_
- func: npu_silu_backward(Tensor grad_output, Tensor x0, Tensor x1) -> Tensor
npu_dispatch_only:
NPU: silu_backward_npu
- func: npu_reshape(Tensor self, int[] shape, bool can_refresh=False) -> Tensor
variants: function, method
npu_dispatch_only:
NPU: reshape_npu
- func: npu_reshape.out(Tensor self, int[] shape, bool can_refresh=False, *, Tensor(a!) out) -> Tensor(a!)
npu_dispatch_only:
NPU: reshape_out_npu
- func: npu_rotated_overlaps(Tensor self, Tensor query_boxes, bool trans=False) -> Tensor
npu_dispatch_only:
NPU: rotated_overlaps_npu
- func: npu_rotated_iou(Tensor self, Tensor query_boxes, bool trans=False, int mode=0, bool is_cross=True, float v_threshold=0.0, float e_threshold=0.0) -> Tensor
npu_dispatch_only:
NPU: rotated_iou_npu
- func: npu_hcom_allreduce.out(Tensor self, str reduction, str group, int fusion, int fusion_id, float alpha, float beta, Tensor(a!) out, int? hccl_comm) -> Tensor(a!)
npu_dispatch_only:
NPU: hcom_allreduce_npu
- func: npu_stride_copy(Tensor self, int[] shape, int[] stride, Scalar storage_offset) -> Tensor
variants: function, method
npu_dispatch_only:
NPU: stride_copy_npu
- func: npu_stride_copy.out(Tensor self, int[] shape, int[] stride, Scalar storage_offset, *, Tensor(a!) out) -> Tensor(a!)
npu_dispatch_only:
NPU: stride_copy_out_npu
- func: dropout_with_byte_mask(Tensor self, float p, bool train) -> Tensor
- func: dropout_with_byte_mask_(Tensor(a!) self, float p, bool train) -> Tensor(a!)
- func: _dropout_with_byte_mask(Tensor self, float p) -> (Tensor, Tensor)
npu_dispatch_only:
NPU: _dropout_with_byte_mask_npu
- func: _dropout_with_byte_mask_inplace(Tensor(a!) result, float p) -> (Tensor(a!), Tensor)
npu_dispatch_only:
NPU: _dropout_with_byte_mask_npu_inplace
- func: _dropout_with_byte_mask_backward(Tensor grad_output, Tensor mask, float p) -> Tensor
npu_dispatch_only:
NPU: dropout_with_byte_mask_backward_npu
- func: npu_dropout_with_add_softmax(Tensor self, Tensor x1, Scalar alpha, float prob, int dim) -> (Tensor, Tensor, Tensor)
variants: function, method
npu_dispatch_only:
NPU: dropout_with_add_softmax_npu
- func: npu_dropout_with_add_softmax_backward(Tensor grad, Tensor mask, Tensor softmax_out, Scalar alpha, float prob, int dim) -> (Tensor, Tensor)
variants: function, method
npu_dispatch_only:
NPU: dropout_with_add_softmax_backward_npu
- func: npu_multi_head_attention(Tensor query, Tensor key, Tensor value, Tensor query_weight, Tensor key_weight, Tensor value_weight, Tensor attn_mask, Tensor out_proj_weight, Tensor? query_bias, Tensor? key_bias, Tensor? value_bias, Tensor? out_proj_bias, Tensor? dropout_mask, int attn_head_num, int attn_dim_per_head, int src_len, int tgt_len, float dropout_prob, bool softmax_use_float) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
npu_dispatch_only:
NPU: multi_head_attention_npu
- func: npu_multi_head_attention_backward(Tensor query, Tensor key, Tensor value, Tensor query_weight, Tensor key_weight, Tensor value_weight, Tensor out_proj_weight, Tensor? query_bias, Tensor? key_bias, Tensor? value_bias, Tensor? out_proj_bias, Tensor query_res, Tensor key_res, Tensor value_res, Tensor attn_scores, Tensor attn_res, Tensor context, Tensor y_grad, Tensor dropout_mask, int attn_head_num, int attn_dim_per_head, int src_len, int tgt_len, float dropout_prob, bool softmax_use_float) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
npu_dispatch_only:
NPU: multi_head_attention_backward_npu
- func: npu_dropout_gen_mask(int[] size, float p, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
npu_dispatch_only:
NPU: dropout_gen_mask_impl
- func: npu_dropout_do_mask(Tensor self, Tensor mask, float p) -> (Tensor, Tensor)
npu_dispatch_only:
NPU: dropout_do_mask_impl
- func: npu_enque_tensor(Tensor[] tensors, str format_string) -> ()
npu_dispatch_only:
NPU: enque_tensor_npu
- func: npu_lstm_cell(Tensor input, Tensor w_ih, Tensor w_hh, Tensor h, Tensor c, Tensor? bias=None) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
variants: function
npu_dispatch_only:
NPU: lstm_cell_npu
- func: npu_lstm_cell_backward(Tensor? grady, Tensor? gradh, Tensor? gradc, Tensor input, Tensor w_ih, Tensor w_hh, Tensor h, Tensor c, Tensor y_output, Tensor h_output, Tensor c_output, Tensor i, Tensor j, Tensor f, Tensor o, Tensor tanhc) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)
variants: function
npu_dispatch_only:
NPU: lstm_cell_backward_npu
NPU: giou_backward_npu
@@ -1,5 +1,5 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
@@ -59,8 +59,8 @@ Tensor& adds_out_npu_nocheck(
}
cmd.Name("Add")
.Input(self)
.Input(Scalar(value), self.scalar_type())
.Output(result, "", nullopt, real_type)
.Input(value, self.scalar_type())
.Output(result, real_type)
.Run();
return result;
@@ -97,15 +97,24 @@ Tensor& add_out_npu_nocheck(
cmd.Name("Add")
.Input(self)
.Input(other)
.Output(result, "", nullopt, real_type)
.Output(result, real_type)
.Run();
} else {
cmd.Name("AxpyV2")
.Input(self)
.Input(other)
.Input(alpha, self.scalar_type())
.Output(result)
.Run();
if (c10::npu::OptionsManager::CheckDynamicOptimizer("ADD")) {
cmd.Name("AxpyV2")
.Input(self)
.Input(other)
.Input(alpha, self.scalar_type())
.Output(result)
.Run();
} else {
cmd.Name("Axpy")
.Input(self)
.Input(other)
.Attr("alpha", alpha)
.Output(result)
.Run();
}
}
}
@@ -28,7 +28,7 @@ Tensor& addbmm_out_npu(
Tensor bmmResult = at::bmm(MulResult,batch2);
int64_t dim[2] = {batch1.size(1), batch2.size(2)};
Tensor sumResult = at::sum_to(bmmResult, dim);
// sumResult + self*beta
//sumResult + self*beta
at::add_out(result, sumResult, self, beta);
return result;
}
@@ -1,5 +1,5 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
@@ -15,51 +15,26 @@
// limitations under the License.
#include "ATen/native/npu/utils/OpAdapter.h"
#include "ATen/native/npu/utils/CalcuOpUtil.h"
namespace at {
namespace native {
using namespace at::native::npu;
Tensor& addcdiv_npu_nocheck(
Tensor& result,
const Tensor& self,
const Tensor& tensor1,
const Tensor& tensor2,
Scalar value) {
bool isFp32 = self.scalar_type() == at::kFloat && tensor1.scalar_type() == at::kFloat && tensor2.scalar_type() == at::kFloat;
Tensor selfCp = isFp32 ? self : self.npu_dtype_cast(at::kFloat);
Tensor tensor1Cp = isFp32 ? tensor1 : tensor1.npu_dtype_cast(at::kFloat);
Tensor tensor2Cp = isFp32 ? tensor2 : tensor2.npu_dtype_cast(at::kFloat);
OpCommand cmd;
cmd.Name("Addcdiv")
.Input(selfCp)
.Input(tensor1Cp)
.Input(tensor2Cp)
.Input(value, selfCp.scalar_type())
.Output(result)
.Run();
return result;
}
Tensor& addcdiv_out_npu(
Tensor& result,
const Tensor& self,
const Tensor& tensor1,
const Tensor& tensor2,
Scalar value) {
auto divOutputSize = broadcast_ops_npu_output_size(tensor1, tensor2);
auto outputSize = broadcast_ops_npu_output_size(self.sizes(), divOutputSize);
bool isFp32 = self.scalar_type() == at::kFloat && tensor1.scalar_type() == at::kFloat && tensor2.scalar_type() == at::kFloat;
Tensor temp = isFp32 ? OpPreparation::ApplyTensor(self, outputSize)
: OpPreparation::ApplyTensor(outputSize, self.options().dtype(at::kFloat), self);
addcdiv_npu_nocheck(temp, self, tensor1, tensor2, value);
temp = isFp32 ? temp : temp.npu_dtype_cast(self.scalar_type());
OpPreparation::CheckOut(
{temp},
result,
temp);
result.copy_(temp);
OpCommand cmd;
cmd.Name("Addcdiv")
.Input(self)
.Input(tensor1)
.Input(tensor2)
.Input(value, self.scalar_type())
.Output(result)
.Run();
return result;
}
@@ -68,14 +43,11 @@ Tensor addcdiv_npu(
const Tensor& tensor1,
const Tensor& tensor2,
Scalar value) {
auto divOutputSize = broadcast_ops_npu_output_size(tensor1, tensor2);
auto outputSize = broadcast_ops_npu_output_size(self.sizes(), divOutputSize);
bool isFp32 = self.scalar_type() == at::kFloat && tensor1.scalar_type() == at::kFloat && tensor2.scalar_type() == at::kFloat;
Tensor result = isFp32 ? OpPreparation::ApplyTensor(self, outputSize)
: OpPreparation::ApplyTensor(outputSize, self.options().dtype(at::kFloat), self);
addcdiv_npu_nocheck(result, self, tensor1, tensor2, value);
result = isFp32 ? result : result.npu_dtype_cast(self.scalar_type());
Tensor result = OpPreparation::ApplyTensor(self, outputSize);
addcdiv_out_npu(result, self, tensor1, tensor2, value);
return result;
}
@@ -84,7 +56,14 @@ Tensor& addcdiv_npu_(
const Tensor& tensor1,
const Tensor& tensor2,
Scalar value) {
addcdiv_out_npu(self, self, tensor1, tensor2, value);
OpPreparation::CheckMemory({self, tensor1, tensor2}, {self});
if (!NpuUtils::check_match(&self)) {
Tensor contiguousSelf = NpuUtils::format_contiguous(self);
Tensor result = addcdiv_out_npu(contiguousSelf, contiguousSelf, tensor1, tensor2, value);
NpuUtils::format_fresh_view(self, result);
} else {
addcdiv_out_npu(self, self, tensor1, tensor2, value);
}
return self;
}
@@ -28,12 +28,12 @@ Tensor& addcmul_out_npu_nocheck(
const Scalar value) {
OpCommand cmd;
cmd.Name("Addcmul")
.Input(self)
.Input(tensor1)
.Input(tensor2)
.Input(value, self.scalar_type())
.Output(result)
.Run();
.Input(self)
.Input(tensor1)
.Input(tensor2)
.Input(value, self.scalar_type())
.Output(result)
.Run();
return result;
}
@@ -48,7 +48,6 @@ Tensor addmm_npu(
const Tensor& mat2,
Scalar beta,
Scalar alpha) {
TORCH_CHECK(self.scalar_type() == mat1.scalar_type(), "The input 0 and input 1 must have the same dtype.");
// calculate the output size
auto outputSize = addmm_npu_output_size(self, mat1, mat2, beta, alpha);
@@ -70,7 +69,6 @@ Tensor& addmm_npu_(
const Tensor& mat2,
Scalar beta,
Scalar alpha) {
TORCH_CHECK(self.scalar_type() == mat1.scalar_type(), "The input 0 and input 1 must have the same dtype.");
SmallVector<Tensor, N> inputs = {self, mat1, mat2};
SmallVector<Tensor, N> outputs = {self};
CalcuOpUtil::check_memory_over_laps(inputs, outputs);
@@ -56,7 +56,7 @@ Tensor& affine_grid_generator_backward_nocheck(
return result;
}
} // namespace
}//namespace
Tensor affine_grid_generator_backward_npu(
const Tensor& grad,
@@ -1,5 +1,5 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
@@ -28,10 +28,18 @@ Tensor& affine_grid_generator_npu_nocheck(
const Tensor& theta,
IntArrayRef size,
bool align_corners) {
int value = size.size();
vector<int> tmp_vector = {};
for (int i = 0; i < value; i++) {
tmp_vector.emplace_back(size[i]);
}
Tensor sizeTensor_cpu = from_blob((void*)tmp_vector.data(), {value}, at::kInt);
Tensor sizeTensor_npu = CalcuOpUtil::copy_tensor_host_to_device(sizeTensor_cpu);
OpCommand cmd;
cmd.Name("AffineGrid")
.Input(theta)
.Input(size, at::kInt)
.InputPair(sizeTensor_npu, sizeTensor_cpu)
.Output(result)
.Attr("align_corners", align_corners)
.Run();
@@ -43,7 +51,7 @@ Tensor affine_grid_generator_npu(
const Tensor& theta,
IntArrayRef size,
bool align_corners) {
TORCH_CHECK(size.size() == 4 || size.size() == 5,
TORCH_CHECK(size.size() == 4 || size.size() == 5,
"AffineGridGenerator needs 4d or 5d size(input).");
// calculate the output size
SmallVector<int64_t, SIZE> outputSize = { };
@@ -57,8 +65,8 @@ Tensor affine_grid_generator_npu(
Tensor result = OpPreparation::ApplyTensor(theta, outputSize);
// calculate the output result of the NPU
affine_grid_generator_npu_nocheck(
result,
theta,
result,
theta,
size,
align_corners);
@@ -27,14 +27,32 @@ inline Tensor all_out_npu_nocheck(
const Tensor& self,
SmallVector<int64_t, N> dimList,
bool keepdim) {
if (!c10::npu::OptionsManager::CheckDynamicEnable()){
OpCommand cmd;
cmd.Name("ReduceAll")
.Input(self)
.Input(dimList, at::kLong)
.Output(result)
.Attr("keep_dims", keepdim)
.Run();
} else {
OpDynamicCommand cmd;
cmd.Name("ReduceAllD")
.Input(self)
.Output(result)
.Attr("axes", dimList)
.Attr("keep_dims", keepdim);
// DYNAMIC
Tensor dimTensor_cpu = from_blob((void*)dimList.data(), {dimList.size()}, at::kLong).to(at::kInt);
Tensor dimTensor_npu = CalcuOpUtil::copy_tensor_host_to_device(dimTensor_cpu);
cmd.DynamicName("ReduceAll")
.DynamicInput(self)
.DynamicInput(dimTensor_npu)
.DynamicOutput(result, "", FIXED_NONE, false)
.DynamicAttr("keep_dims", keepdim)
.DynamicOpRun();
OpCommand cmd;
cmd.Name("ReduceAll")
.Input(self)
.Input(dimList, at::kLong)
.Output(result)
.Attr("keep_dims", keepdim)
.Run();
}
return result;
}
@@ -63,78 +81,52 @@ Tensor& all_out_npu(
Tensor all_npu(const Tensor& self, int64_t dim, bool keepdim) {
TORCH_CHECK(self.scalar_type() == ScalarType::Bool || self.scalar_type() == ScalarType::Byte,
"all only supports torch.uint8 and torch.bool dtypes");
TORCH_CHECK(dim >= -(self.dim()) && dim < self.dim(),
"The value of dim must be greater than or equal to -self.dim() and less than self.dim()");
Tensor selfCopy = self;
if(selfCopy.scalar_type() == ScalarType::Byte){
selfCopy = selfCopy.npu_dtype_cast(ScalarType::Bool);
}
"all only supports torch.uint8 and torch.bool dtypes");
if (self.numel() == 0) {
SmallVector<int64_t, N> outputSize;
for(int64_t i = 0; i < self.dim(); i++){
if(dim != i){
outputSize.emplace_back(self.size(i));
}
}
Tensor res = OpPreparation::ApplyTensorWithFormat(
outputSize,
self.options().dtype(kInt),
CalcuOpUtil::get_tensor_npu_format(self)).fill_(1).npu_dtype_cast(self.scalar_type());
Tensor res = at::empty_with_format({}, self.options().dtype(kInt), CalcuOpUtil::get_tensor_npu_format(self)).fill_(1).to(ScalarType::Bool);
return res;
}
// calculate the output size
IntArrayRef dims(dim);
auto outputSize = reduce_ops_npu_output_size(selfCopy, dims, keepdim);
auto outputSize = reduce_ops_npu_output_size(self, dims, keepdim);
// construct the output tensor of the NPU
Tensor result = OpPreparation::ApplyTensorWithFormat(
outputSize, selfCopy.options(), CalcuOpUtil::get_tensor_npu_format(selfCopy));
Tensor result = at::empty_with_format(
outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
// calculate the output result of the NPU
all_out_npu_nocheck(result, selfCopy, {dim}, keepdim);
if(self.scalar_type() == ScalarType::Byte){
result = result.npu_dtype_cast(ScalarType::Byte);
}
all_out_npu_nocheck(result, self, {dim}, keepdim);
return result;
}
Tensor all_npu(const Tensor& self) {
TORCH_CHECK(self.scalar_type() == ScalarType::Bool || self.scalar_type() == ScalarType::Byte,
"all only supports torch.uint8 and torch.bool dtypes");
Tensor selfCopy = self;
if(selfCopy.scalar_type() == ScalarType::Byte){
selfCopy = selfCopy.npu_dtype_cast(ScalarType::Bool);
}
"all only supports torch.uint8 and torch.bool dtypes");
if (self.numel() == 0) {
Tensor res = OpPreparation::ApplyTensorWithFormat(
{},
self.options().dtype(kInt),
CalcuOpUtil::get_tensor_npu_format(self)).fill_(1).npu_dtype_cast(self.scalar_type());
Tensor res = at::empty_with_format(
{},
self.options().dtype(kInt),
CalcuOpUtil::get_tensor_npu_format(self)).fill_(1).to(ScalarType::Bool);
return res;
}
// calculate the output size
IntArrayRef dims;
auto outputSize = reduce_ops_npu_output_size(selfCopy, dims, false);
auto outputSize = reduce_ops_npu_output_size(self, dims, false);
// construct the output tensor of the NPU
Tensor result = OpPreparation::ApplyTensorWithFormat(
outputSize, selfCopy.options(), CalcuOpUtil::get_tensor_npu_format(selfCopy));
Tensor result = at::empty_with_format(
outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
// calculate the output result of the NPU
all_out_npu_nocheck(
result,
selfCopy,
CalcuOpUtil::get_dimlist_for_tensor(selfCopy),
self,
CalcuOpUtil::get_dimlist_for_tensor(self),
false);
if(self.scalar_type() == ScalarType::Byte){
result = result.npu_dtype_cast(ScalarType::Byte);
}
return result;
}
@@ -26,14 +26,31 @@ inline Tensor& any_out_npu_nocheck(
const Tensor& self,
SmallVector<int64_t, N> dimList,
bool keepdim) {
OpCommand cmd;
cmd.Name("ReduceAny")
.Input(self)
.Input(dimList)
.Output(result)
.Attr("keep_dims", keepdim)
.Run();
if (!c10::npu::OptionsManager::CheckDynamicEnable()){
OpCommand cmd;
cmd.Name("ReduceAny")
.Input(self)
.Input(dimList)
.Output(result)
.Attr("keep_dims", keepdim)
.Run();
} else {
OpDynamicCommand cmd;
cmd.Name("ReduceAnyD")
.Input(self)
.Output(result)
.Attr("axes", dimList)
.Attr("keep_dims", keepdim);
// DYNAMIC
Tensor dimTensor_cpu = from_blob((void*)dimList.data(), {dimList.size()}, at::kLong).to(at::kInt);
Tensor dimTensor_npu = CalcuOpUtil::copy_tensor_host_to_device(dimTensor_cpu);
cmd.DynamicName("ReduceAny")
.DynamicInput(self)
.DynamicInput(dimTensor_npu, "axes")
.DynamicOutput(result, "", FIXED_NONE, false)
.DynamicAttr("keep_dims", keepdim)
.DynamicOpRun();
}
return result;
}
@@ -94,7 +111,7 @@ Tensor any_npu(const Tensor& self) {
self.options().dtype(ScalarType::Float),
CalcuOpUtil::get_tensor_npu_format(self))
.fill_(self.item())
.npu_dtype_cast(ScalarType::Bool);
.to(ScalarType::Bool);
return any_npu(self_tmp, 0, false);
}
@@ -20,7 +20,7 @@
namespace at {
namespace native {
using namespace at::native::npu;
std::tuple<Tensor, Tensor, Tensor> apply_adam_out_npu_nocheck(
std::tuple<Tensor, Tensor, Tensor> apply_adam_out_npu(
Tensor& var_out,
Tensor& m_out,
Tensor& v_out,
@@ -34,7 +34,7 @@ std::tuple<Tensor, Tensor, Tensor> apply_adam_out_npu_nocheck(
c10::optional<bool> use_locking,
c10::optional<bool> use_nesterov) {
OpCommand cmd;
cmd.Name("ApplyAdamD")
cmd.Name("ApplyAdam")
.Input(var_out)
.Input(m_out)
.Input(v_out)
@@ -45,9 +45,7 @@ std::tuple<Tensor, Tensor, Tensor> apply_adam_out_npu_nocheck(
.Input(beta2, var_out.scalar_type())
.Input(epsilon, var_out.scalar_type())
.Input(grad)
.Output(var_out)
.Output(m_out)
.Output(v_out);
.Output(var_out);
if (use_locking != c10::nullopt) {
cmd.Attr("use_locking", bool(use_locking));
}
@@ -59,49 +57,6 @@ std::tuple<Tensor, Tensor, Tensor> apply_adam_out_npu_nocheck(
return std::tie(var_out, m_out, v_out);
}
std::tuple<Tensor, Tensor, Tensor> npu_apply_adam(
Scalar beta1_power,
Scalar beta2_power,
Scalar lr,
Scalar beta1,
Scalar beta2,
Scalar epsilon,
const Tensor& grad,
c10::optional<bool> use_locking,
c10::optional<bool> use_nesterov) {
AT_ERROR("npu_apply_adam is not implemented for Tensor");
}
std::tuple<Tensor&, Tensor&, Tensor&> apply_adam_out_npu(
Tensor& var,
Tensor& m,
Tensor& v,
Scalar beta1_power,
Scalar beta2_power,
Scalar lr,
Scalar beta1,
Scalar beta2,
Scalar epsilon,
const Tensor& grad,
c10::optional<bool> use_locking,
c10::optional<bool> use_nesterov) {
apply_adam_npu(
var,
m,
v,
beta1_power,
beta2_power,
lr,
beta1,
beta2,
epsilon,
grad,
use_locking,
use_nesterov);
return std::tie(var, m, v);
}
std::tuple<Tensor, Tensor, Tensor> apply_adam_npu(
Tensor& var,
Tensor& m,
@@ -122,7 +77,7 @@ std::tuple<Tensor, Tensor, Tensor> apply_adam_npu(
Tensor contiguous_var = var_match ? var : NpuUtils::format_contiguous(var);
Tensor contiguous_m = m_match ? m : NpuUtils::format_contiguous(m);
Tensor contiguous_v = v_match ? v : NpuUtils::format_contiguous(v);
apply_adam_out_npu_nocheck(
apply_adam_out_npu(
contiguous_var,
contiguous_m,
contiguous_v,
@@ -145,7 +100,7 @@ std::tuple<Tensor, Tensor, Tensor> apply_adam_npu(
NpuUtils::format_fresh_view(v, contiguous_v);
}
} else {
apply_adam_out_npu_nocheck(
apply_adam_out_npu(
var,
m,
v,
@@ -162,4 +117,4 @@ std::tuple<Tensor, Tensor, Tensor> apply_adam_npu(
return std::tie(var, m, v);
}
} // namespace native
} // namespace at
} // namespace at
@@ -40,9 +40,9 @@ Tensor& arange_out_npu_nocheck(
Scalar step) {
OpCommand cmd;
cmd.Name("Range")
.Input(start, result.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT)
.Input(end, result.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT)
.Input(step, result.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT)
.Input(start, result.scalar_type()) //start
.Input(end, result.scalar_type()) //limit
.Input(step, result.scalar_type()) //delta
.Output(result)
.Run();
@@ -50,11 +50,11 @@ Tensor& arange_out_npu_nocheck(
}
Tensor arange_npu(Scalar end, const TensorOptions& options) {
return arange_npu(0, end, options); // start = 0
return arange_npu(/*start=*/0, end, options);
}
Tensor arange_npu(Scalar start, Scalar end, const TensorOptions& options) {
return arange_npu(start, end, 1, options);
return arange_npu(start, end, /*step=*/1, options);
}
Tensor arange_npu(
@@ -66,7 +66,7 @@ Tensor arange_npu(
float end_value = CalcuOpUtil::get_scalar_float_value(end);
float step_value = CalcuOpUtil::get_scalar_float_value(step);
// Check step start end
//Check step start end
TORCH_CHECK(step_value > 0 || step_value < 0, "step must be nonzero");
TORCH_CHECK(((step_value > 0) && (end_value >= start_value)) || ((step_value < 0) && (end_value <= start_value)),
"upper bound and larger bound inconsistent with step sign");
@@ -74,9 +74,10 @@ Tensor arange_npu(
bool set_to_integral_dtype =
!options.has_dtype() && allIntegral({start, end, step});
// check start == end
//check start == end
Tensor result_check = set_to_integral_dtype
? at::empty_with_format({0}, options.dtype(at::ScalarType::Long), ACL_FORMAT_ND)
? at::empty_with_format(
{0}, options.dtype(at::ScalarType::Int), ACL_FORMAT_ND)
: at::empty_with_format({0}, options, ACL_FORMAT_ND);
if (start_value == end_value) {
return result_check;
@@ -89,28 +90,29 @@ Tensor arange_npu(
SmallVector<int64_t, SIZE> outputSize = {size_value};
Tensor result = set_to_integral_dtype
? at::empty_with_format(outputSize, options.dtype(at::ScalarType::Long), ACL_FORMAT_ND)
? at::empty_with_format(
outputSize, options.dtype(at::ScalarType::Int), ACL_FORMAT_ND)
: at::empty_with_format(outputSize, options, ACL_FORMAT_ND);
if(options.dtype() == at::kHalf) {
result = result.npu_dtype_cast(at::kFloat);
result = result.to(at::kFloat);
}
arange_out_npu_nocheck(result, start, end, step);
if(options.dtype() == at::kHalf) {
result = result.npu_dtype_cast(at::kHalf);
result = result.to(at::kHalf);
}
return result;
}
Tensor& arange_out_npu(Tensor& result, Scalar end) {
return arange_out_npu(result, 0, end);
return arange_out_npu(result, /*start=*/0, end);
}
Tensor& arange_out_npu(Tensor& result, Scalar start, Scalar end) {
return arange_out_npu(result, start, end, 1);
return arange_out_npu(result, start, end, /*step=*/1);
}
Tensor& arange_out_npu(
@@ -122,7 +124,7 @@ Tensor& arange_out_npu(
float end_value = CalcuOpUtil::get_scalar_float_value(end);
float step_value = CalcuOpUtil::get_scalar_float_value(step);
// Check step start end
//Check step start end
TORCH_CHECK(step_value > 0 || step_value < 0, "step must be nonzero");
TORCH_CHECK(((step_value > 0) && (end_value >= start_value)) || ((step_value < 0) && (end_value <= start_value)),
"upper bound and larger bound inconsistent with step sign");
@@ -42,7 +42,7 @@ Tensor argmax_npu(const Tensor& self, optional<int64_t> dim, bool keepdim) {
.Attr("keep_dims", realKeepDim)
.Run();
result = result.npu_dtype_cast(ScalarType::Long);
result = result.to(ScalarType::Long);
return result;
}
} // namespace native
@@ -68,7 +68,7 @@ Tensor& argsort_out_npu_nocheck(
at::npu_transpose_out(indices, transposeIndices, perm);
// indices dtype transform to Int64
//indices dtype transform to Int64
indices = indices.to(at::kLong);
return indices;
@@ -1,87 +0,0 @@
// Copyright (c) 2020, Huawei Technologies.All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ATen/native/npu/utils/OpAdapter.h"
#include <torch/csrc/autograd/record_function.h>
#include "ATen/native/npu/common/InnerNpuNativeFunction.h"
#include "ATen/native/npu/frame/StorageDescHelper.h"
#include "ATen/native/npu/utils/NpuStorageOffsetGuard.h"
namespace at {
namespace native {
using namespace at::native::npu;
Tensor& stride_copy_out_npu_nocheck(
Tensor& result,
const Tensor& self,
IntArrayRef shape,
IntArrayRef stride,
Scalar storage_offset) {
if ((result.nbytes() < 32) && (!StorageDescHelper::MetaDataAreMatch(&result))) {
// [算子限制] 对于1. 小于一个block的数据搬运 2.result不match,Astrided暂不支持。
copy_kernel_npu(result, self, false);
return result;
}
RECORD_HOST_FUNCTION("npuAsStrided", std::vector<c10::IValue>({self}));
E2E_RECORD_FUNCTION("npuAsStrided");
// Set the offset of input discontiguous tensor to be 0.
// The accurate offset would be provided as a attr to op.
OpCommand cmd;
if (c10::npu::NpuRunMode::IsGraphMode()) {
NpuStorageOffsetGuard guard_input(const_cast<Tensor &>(self));
cmd.Name("AsStrided")
.InputWithoutContiguous(self)
.Input(shape)
.Input(stride)
.Input(storage_offset, at::kLong, CompileType::MEMORY_HOST_COMPILE_DEPENDENT)
.Output(result)
.Run();
return result;
}
// (Ascend) Fix multi-compiling of asstrided op by wrapping attr storage_offset as a NPU Tensor instead of GE Const node.
// If GE Data node can pass vaule of storage_offset to op, we can switch storage_offset to Data node finally.
cmd.Name("AsStrided")
.InputWithoutContiguous(self)
.Input(shape)
.Input(stride)
.InputScalarToNPUTensor(at::Scalar(0), at::kLong)
.Output(result)
.Run();
return result;
}
Tensor& stride_copy_out_npu(
Tensor& result,
const Tensor& self,
IntArrayRef shape,
IntArrayRef stride,
Scalar storage_offset) {
stride_copy_out_npu_nocheck(result, self, shape, stride, storage_offset);
return result;
}
Tensor stride_copy_npu(
const Tensor& self,
IntArrayRef shape,
IntArrayRef stride,
Scalar storage_offset) {
// AsStrided OP only supports ND input
Tensor result = OpPreparation::ApplyTensorWithFormat(
shape, self.options(), ACL_FORMAT_ND);
stride_copy_out_npu_nocheck(result, self, shape, stride, storage_offset);
return result;
}
} // namespace native
} // namespace at
@@ -32,7 +32,7 @@ Tensor& atan_out_npu(Tensor& result, const Tensor& self) {
Tensor atan_npu(const Tensor& self) {
Tensor result = OpPreparation::ApplyTensor(self);
// calculate the output result of the NPU
//calculate the output result of the NPU
atan_out_npu(result, self);
return result;
}
@@ -14,37 +14,31 @@
#include "ATen/native/npu/utils/CalcuOpUtil.h"
#include "ATen/native/npu/utils/OpAdapter.h"
#include "ATen/native/npu/utils/KernelNpuOutputSize.h"
namespace at {
namespace native {
using namespace at::native::npu;
Tensor& baddbmm_nocheck(
const Tensor& self,
const Tensor& tensor1,
const Tensor& tensor2,
Scalar beta,
Scalar alpha,
Tensor& result) {
auto outputSize = baddbmm_npu_output_size(tensor1, tensor2);
Tensor BatchMatMulTensor = OpPreparation::ApplyTensor(self, outputSize);
bool isSelfT = CalcuOpUtil::is_transpose_last_two_dims(tensor1);
bool isMat2T = CalcuOpUtil::is_transpose_last_two_dims(tensor2);
SmallVector<NPUTensorDesc, N> baddbmm_npu_input(
const Tensor& self,
const Tensor& other) {
return CalcuOpUtil::create_npu_input_tensor_desc({self, other});
}
OpCommand cmd;
cmd.Name("BatchMatMul")
.Input(tensor1)
.Input(tensor2)
.Output(BatchMatMulTensor)
.Attr("adj_x1", isSelfT)
.Attr("adj_x2", isMat2T)
.Run();
SmallVector<NPUTensorDesc, N> baddbmm_npu_output(
const Tensor& result) {
return CalcuOpUtil::create_npu_output_tensor_desc({result});
}
Tensor alphaMulTensor = at::mul(BatchMatMulTensor, alpha);
Tensor betaMulTensor = at::mul(self, beta);
at::add_out(result, alphaMulTensor, betaMulTensor, 1);
return result;
SmallVector<NPUAttrDesc, N> baddbmm_npu_attr(
const Tensor& self,
const Tensor& mat2) {
bool isSelfT = CalcuOpUtil::is_transpose_last_two_dims(self);
bool isMat2T = CalcuOpUtil::is_transpose_last_two_dims(mat2);
NPUAttrDesc npuAttrSelfTranspose = NPUAttrDesc("adj_x1", isSelfT);
NPUAttrDesc npuAttrMat2Transpose = NPUAttrDesc("adj_x2", isMat2T);
SmallVector<NPUAttrDesc, N> attrs = {npuAttrSelfTranspose, npuAttrMat2Transpose};
return attrs;
}
Tensor& baddbmm_out_npu(
@@ -53,13 +47,21 @@ Tensor& baddbmm_out_npu(
const Tensor& tensor1,
const Tensor& tensor2,
Scalar beta,
Scalar alpha){
OpPreparation::CheckOut(
{self, tensor1, tensor2},
result,
self);
baddbmm_nocheck(self, tensor1, tensor2, beta, alpha, result);
Scalar alpha) {
auto outputSize = baddbmm_npu_output_size(tensor1, tensor2);
Tensor BatchMatMulTensor = OpPreparation::ApplyTensor(self, outputSize);
auto inputs = baddbmm_npu_input(tensor1, tensor2);
auto outputs = baddbmm_npu_output({BatchMatMulTensor});
auto attrs = baddbmm_npu_attr(tensor1, tensor2);
CalcuOpUtil::execute_npu_operate("BatchMatMul", inputs, outputs, attrs);
Tensor alphaMulTensor = at::mul(BatchMatMulTensor, alpha);
Tensor betaMulTensor = at::mul(self, beta);
at::add_out(result, alphaMulTensor, betaMulTensor);
return result;
}
@@ -71,9 +73,10 @@ Tensor baddbmm_npu(
Scalar alpha) {
Tensor outputTensor = self;
auto outputSize = baddbmm_npu_output_size(tensor1, tensor2);
Tensor result = OpPreparation::ApplyTensor(
outputTensor,
outputSize);
Tensor result = at::empty_with_format(
outputSize,
outputTensor.options(),
CalcuOpUtil::get_tensor_npu_format(outputTensor));
baddbmm_out_npu(result, self, tensor1, tensor2, beta, alpha);
return result;
}
@@ -30,16 +30,16 @@ std::tuple<Tensor, Tensor, Tensor, Tensor> batch_nms_npu(
// construct the output tensor of the NPU
Tensor nmsed_boxes = OpPreparation::ApplyTensor(
{self.size(0), max_total_size, 4},
self.options(),
self.options().dtype(at::kHalf),
self);
Tensor nmsed_scores = OpPreparation::ApplyTensor(
{self.size(0), max_total_size},
self.options(),
self.options().dtype(at::kHalf),
self);
Tensor nmsed_classes = OpPreparation::ApplyTensor(
{self.size(0), max_total_size},
self.options(),
self.options().dtype(at::kHalf),
self);
Tensor nmsed_num = OpPreparation::ApplyTensor(
@@ -15,77 +15,87 @@
// limitations under the License.
#include "ATen/native/npu/utils/OpAdapter.h"
#include "c10/npu/NPUCachingAllocator.h"
#include "ATen/npu/NPUGenerator.h"
#include "ATen/Utils.h"
namespace at {
namespace native {
using namespace at::native::npu;
Tensor& bernoulli_npu_nocheck(Tensor& y, double prob, int64_t seed, int64_t offset) {
Tensor& bernoulli_out_npu(Tensor& result, const Tensor& self, double p) {
OpCommand cmd;
cmd.Name("StatelessBernoulli")
.Input(y.sizes(), at::kLong, CompileType::MEMORY_HOST_COMPILE_INDEPENDENT)
.Input(Scalar(prob), ScalarType::Float)
.Input(Scalar(seed), ScalarType::Long)
.Input(Scalar(offset), ScalarType::Long)
.Output(y)
.Attr("dtype", y.scalar_type())
.Run();
return y;
cmd.Name("Bernoulli")
.Input(self)
.Input(p, ScalarType::Float)
.Output(result)
.Run();
return result;
}
Tensor& bernoulli_npu_nocheck(Tensor& y, const Tensor& prob, int64_t seed, int64_t offset) {
Tensor& bernoulli_out_npu(Tensor& result, const Tensor& self, const Tensor& p) {
OpCommand cmd;
cmd.Name("StatelessBernoulli")
.Input(y.sizes(), at::kLong, CompileType::MEMORY_HOST_COMPILE_INDEPENDENT)
.Input(prob)
.Input(Scalar(seed), ScalarType::Long)
.Input(Scalar(offset), ScalarType::Long)
.Output(y)
.Attr("dtype", y.scalar_type())
.Run();
return y;
cmd.Name("Bernoulli")
.Input(self)
.Input(p)
.Output(result)
.Run();
return result;
}
Tensor& bernoulli_npu_(Tensor& self, double p, Generator* gen) {
auto gen_ = get_generator_or_default<NPUGenerator>(gen, at::npu::detail::getDefaultNPUGenerator());
auto pair = gen_->philox_engine_inputs(10);
const int64_t seed = pair.first;
const int64_t offset = pair.second;
OpPreparation::CheckMemory({self}, {self});
ScalarType selfType = self.scalar_type();
Tensor selfFp32 = self;
if (self.scalar_type() == ScalarType::Half) {
selfFp32 = self.to(ScalarType::Float);
}
if (!NpuUtils::check_match(&self)) {
Tensor contiguousSelf = NpuUtils::format_contiguous(self);
bernoulli_npu_nocheck(contiguousSelf, p, seed, offset);
NpuUtils::format_fresh_view(self, contiguousSelf);
Tensor contiguousSelf = NpuUtils::format_contiguous(selfFp32);
Tensor result = bernoulli_out_npu(contiguousSelf, contiguousSelf, p);
NpuUtils::format_fresh_view(self, result);
} else {
bernoulli_npu_nocheck(self, p, seed, offset);
bernoulli_out_npu(selfFp32, selfFp32, p);
self.copy_(selfFp32);
}
if(self.scalar_type() != selfType){
self = self.to(ScalarType::Half);
}
return self;
}
Tensor& bernoulli_npu_(Tensor& self, const Tensor& p, Generator* gen) {
auto gen_ = get_generator_or_default<NPUGenerator>(gen, at::npu::detail::getDefaultNPUGenerator());
auto pair = gen_->philox_engine_inputs(10);
const int64_t seed = pair.first;
const int64_t offset = pair.second;
OpPreparation::CheckMemory({self}, {self});
ScalarType selfType = self.scalar_type();
Tensor selfFp32 = self;
Tensor pFp32 = OpPreparation::CastBackToOriFormat(p);;
if (self.scalar_type() == ScalarType::Half) {
selfFp32 = self.to(ScalarType::Float);
pFp32 = p.to(ScalarType::Float);
}
Tensor pOriFormat = OpPreparation::CastBackToOriFormat(p);
if (!NpuUtils::check_match(&self)) {
Tensor contiguousSelf = NpuUtils::format_contiguous(self);
bernoulli_npu_nocheck(contiguousSelf, pOriFormat, seed, offset);
NpuUtils::format_fresh_view(self, contiguousSelf);
Tensor contiguousSelf = NpuUtils::format_contiguous(selfFp32);
Tensor result = bernoulli_out_npu(contiguousSelf, contiguousSelf, pFp32);
NpuUtils::format_fresh_view(self, result);
} else {
bernoulli_npu_nocheck(self, pOriFormat, seed, offset);
bernoulli_out_npu(selfFp32, selfFp32, pFp32);
self.copy_(selfFp32);
}
if(self.scalar_type() != selfType){
self = self.to(ScalarType::Half);
}
return self;
}
Tensor bernoulli_npu(const Tensor& self, Generator* gen) {
Tensor selfCopy = OpPreparation::ApplyTensorWithFormat(self.sizes(), self.options(), ACL_FORMAT_ND);
const Tensor p = self;
Tensor selfCopy = at::empty_with_format(
self.sizes(), self.options(), ACL_FORMAT_ND);
selfCopy.copy_(self);
return bernoulli_npu_(selfCopy, self, gen);
return bernoulli_npu_(selfCopy, p, gen);
}
} // namespace native
} // namespace at
@@ -1,5 +1,5 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
@@ -34,10 +34,7 @@ tuple<Tensor, Tensor, Tensor> bert_apply_adam_out_npu_nocheck(
const Tensor& grad,
Scalar max_grad_norm,
Scalar global_grad_norm,
Scalar weight_decay,
optional<Scalar> step_size,
int64_t adam_mode) {
std::string adamMode = adam_mode == 0 ? "adam" : "mbart_adam";
Scalar weight_decay) {
OpCommand cmd;
cmd.Name("ApplyAdamV2")
.Input(var)
@@ -50,19 +47,21 @@ tuple<Tensor, Tensor, Tensor> bert_apply_adam_out_npu_nocheck(
.Input(grad)
.Input(max_grad_norm, var.scalar_type())
.Input(global_grad_norm, var.scalar_type())
.Input(weight_decay, var.scalar_type());
if (step_size.has_value()) {
cmd.Input(step_size.value(), var.scalar_type());
}
cmd.Output(var_out)
.Input(weight_decay, var.scalar_type())
.Output(var_out)
.Output(m_out)
.Output(v_out)
.Attr("adam_mode", adamMode)
.Run();
return std::tie(var_out, m_out, v_out);
}
std::tuple<Tensor, Tensor, Tensor> npu_bert_apply_adam(
tuple<Tensor, Tensor, Tensor> bert_apply_adam_out_npu(
Tensor& var_out,
Tensor& m_out,
Tensor& v_out,
const Tensor& var,
const Tensor& m,
const Tensor& v,
Scalar lr,
Scalar beta1,
Scalar beta2,
@@ -70,30 +69,21 @@ std::tuple<Tensor, Tensor, Tensor> npu_bert_apply_adam(
const Tensor& grad,
Scalar max_grad_norm,
Scalar global_grad_norm,
Scalar weight_decay,
optional<Scalar> step_size,
int64_t adam_mode) {
AT_ERROR("npu_bert_apply_adam is not implemented for Tensor");
}
Scalar weight_decay) {
OpPipeWithDefinedOut check;
check.CheckMemory({var, m, v, grad}, {var_out, m_out, v_out});
tuple<Tensor&, Tensor&, Tensor&> bert_apply_adam_out_npu(
Tensor& var,
Tensor& m,
Tensor& v,
Scalar lr,
Scalar beta1,
Scalar beta2,
Scalar epsilon,
const Tensor& grad,
Scalar max_grad_norm,
Scalar global_grad_norm,
Scalar weight_decay,
optional<Scalar> step_size,
int64_t adam_mode) {
bert_apply_adam_npu(
var, m, v,
lr, beta1, beta2, epsilon, grad, max_grad_norm, global_grad_norm, weight_decay, step_size, adam_mode);
return std::tie(var, m, v);
auto func = [&var, &m, &v, &lr, &beta1, &beta2, &epsilon, &grad, &max_grad_norm, &global_grad_norm, &weight_decay] (
Tensor& var_out,
Tensor& m_out,
Tensor& v_out) {
bert_apply_adam_out_npu_nocheck(var_out, m_out, v_out, var, m, v,
lr, beta1, beta2, epsilon, grad, max_grad_norm, global_grad_norm, weight_decay);
};
OpPipeWithMultiOut<Tensor&, Tensor&, Tensor&> pipe(var_out, m_out, v_out);
return pipe.Call(func)
.ReturnRef<Tensor&, Tensor&, Tensor&>();
}
tuple<Tensor, Tensor, Tensor> bert_apply_adam_npu(
@@ -107,13 +97,12 @@ tuple<Tensor, Tensor, Tensor> bert_apply_adam_npu(
const Tensor& grad,
Scalar max_grad_norm,
Scalar global_grad_norm,
Scalar weight_decay,
optional<Scalar> step_size,
int64_t adam_mode) {
bert_apply_adam_out_npu_nocheck(
Scalar weight_decay) {
bert_apply_adam_out_npu(
var, m, v, var, m, v,
lr, beta1, beta2, epsilon, grad, max_grad_norm, global_grad_norm, weight_decay, step_size, adam_mode);
lr, beta1, beta2, epsilon, grad, max_grad_norm, global_grad_norm, weight_decay);
return std::tie(var, m, v);
}
} // namespace native
} // namespace at
@@ -15,7 +15,6 @@
// limitations under the License.
#include "ATen/native/npu/utils/OpAdapter.h"
#include "ATen/native/npu/utils/NpuUtils.h"
namespace at {
namespace native {
@@ -31,7 +30,15 @@ Tensor& binary_cross_entropy_backward_out_npu(
Tensor weightTensor = weight.defined() ? weight :
at::ones(self.sizes(), self.options());
std::string reductionStr = NpuUtils::get_reduction_str(reduction);
string reductionStr;
if (reduction == Reduction::None) {
reductionStr = "none";
} else if (reduction == Reduction::Mean) {
reductionStr = "mean";
} else if (reduction == Reduction::Sum) {
reductionStr = "sum";
}
OpCommand cmd;
cmd.Name("BinaryCrossEntropyGrad")
.Input(self)
@@ -15,7 +15,6 @@
// limitations under the License.
#include "ATen/native/npu/utils/OpAdapter.h"
#include "ATen/native/npu/utils/NpuUtils.h"
namespace at {
namespace native {
@@ -33,7 +32,12 @@ Tensor& binary_cross_entropy_out_npu(
}
// constructs the attr of the NPUAttrDesc
std::string reductionStr = NpuUtils::get_reduction_str(reduction);
string reductionStr = "mean";
if (reduction == Reduction::None) {
reductionStr = "none";
} else if (reduction == Reduction::Sum) {
reductionStr = "sum";
}
// executing the NPU operator
OpCommand cmd;
@@ -66,7 +70,7 @@ Tensor binary_cross_entropy_npu(
Tensor result = OpPreparation::ApplyTensor(self, outputSize);
if (self.numel() == 0) {
// In this scenario, needs to return nan. And the nan of the NPU can only be fp32.
result = result.npu_dtype_cast(at::kFloat).fill_(0);
result = result.to(at::kFloat).fill_(0);
result = result / 0;
return result;
}
@@ -15,7 +15,6 @@
// limitations under the License.
#include "ATen/native/npu/utils/OpAdapter.h"
#include "ATen/native/npu/utils/NpuUtils.h"
namespace at {
namespace native {
@@ -47,7 +46,14 @@ Tensor binary_cross_entropy_with_logits_backward_npu(
Tensor doutTensor = broadcast_npu(grad_output, self.sizes());
std::string reductionStr = NpuUtils::get_reduction_str(reduction);
string reductionStr;
if (reduction == Reduction::None) {
reductionStr = "none";
} else if (reduction == Reduction::Mean) {
reductionStr = "mean";
} else if (reduction == Reduction::Sum) {
reductionStr = "sum";
}
OpCommand cmd;
cmd.Name("SigmoidCrossEntropyWithLogitsGradV2")
@@ -16,7 +16,6 @@
#include "ATen/native/npu/utils/OpAdapter.h"
#include "ATen/native/npu/utils/CalcuOpUtil.h"
#include "ATen/native/npu/utils/NpuUtils.h"
namespace at {
namespace native {
@@ -61,7 +60,14 @@ Tensor binary_cross_entropy_with_logits_npu(
}
// constructs the attr of the NPUAttrDesc
std::string reductionStr = NpuUtils::get_reduction_str(reduction);
string reductionStr;
if (reduction == Reduction::None) {
reductionStr = "none";
} else if (reduction == Reduction::Mean) {
reductionStr = "mean";
} else if (reduction == Reduction::Sum) {
reductionStr = "sum";
}
// executing the NPU operator
OpCommand cmd;
@@ -1,76 +0,0 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ATen/native/npu/utils/OpAdapter.h"
#include "ATen/native/npu/utils/CalcuOpUtil.h"
namespace at {
namespace native {
using namespace at::native::npu;
Tensor& bincount_npu_nocheck(
const Tensor& self,
const Tensor& weights,
int64_t sizes,
Tensor& result) {
OpCommand cmd;
cmd.Name("Bincount")
.Input(self)
.Input(Scalar(sizes), ScalarType::Int)
.Input(weights)
.Output(result)
.Run();
return result;
}
Tensor bincount_npu(
const Tensor& self,
const Tensor& weights,
int64_t minlength) {
if (self.sizes()[0] == 0) {
auto result = OpPreparation::ApplyTensorWithSizes(
{0},
self.options().dtype(at::ScalarType::Long));
return result;
}
// calculate output size
auto sizes = static_cast<int64_t>(
CalcuOpUtil::get_scalar_float_value(max_npu(self).item()));
sizes = (sizes < minlength) ? minlength : (sizes + 1);
// input convert to int32
if (self.dtype() == at::ScalarType::Long) {
TORCH_WARN_ONCE("CANN: Bincount cann't support dtype int64.");
}
auto input = self.npu_dtype_cast(at::ScalarType::Int);
// weight convert dtype as same as output defined by torch
auto weight = weights;
if (!weights.defined()) {
TensorOptions options = input.options();
weight = ones_npu(input.sizes(), options.dtype(at::ScalarType::Long));
} else if (!(weights.dtype() == at::ScalarType::Float)) {
weight = weights.npu_dtype_cast(at::ScalarType::Double);
}
auto result = OpPreparation::ApplyTensor(weight, {sizes});
bincount_npu_nocheck(input, weight, sizes, result);
return result;
}
} // namespace native
} // namespace at

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