Compare commits

..
29 Commits
Author SHA1 Message Date
i-robot 7c3acf31cf !33 同步 3cd6fe790d2af7fc618bde1f17ae347c42438c83
Merge pull request !33 from weili10/2.0.2.tr5
2021-07-29 09:33:05 +00:00
i-robot 7d7070c344 !27 文档修改命名格式归档
Merge pull request !27 from yinzijun/2.0.2.tr5
2021-07-29 09:17:03 +00:00
张昱杰 18396d4937 update scripts/mkdirs.sh. 2021-07-29 09:12:39 +00:00
weili10 7a563bcc03 同步3cd6fe790d2af7fc618bde1f17ae347c42438c83 2021-07-29 17:01:23 +08:00
ZijunYin ac4e725c80 add RELEASENOTE 2021-07-29 16:51:58 +08:00
ZijunYin 68eac297da change name of releasenote 2021-07-29 16:49:07 +08:00
i-robot 49347eadd2 !32 增加版权声明
Merge pull request !32 from weili10/2.0.2.tr5
2021-07-29 08:01:07 +00:00
weili10 36bc73fc7c 增加版权声明 2021-07-29 15:51:35 +08:00
weili10 def54c93b6 update README.zh.md. 2021-07-29 06:46:26 +00:00
i-robot 2ef2eed751 !31 解决原生pytorch中dos编码文件打patch报错问题
Merge pull request !31 from weili10/2.0.2.tr5
2021-07-29 03:27:04 +00:00
weili10 c757565613 解决原生pytorch中dos编码文件打patch报错问题 2021-07-29 10:53:20 +08:00
i-robot a933722394 !28 增加开源软件使用说明
Merge pull request !28 from weili10/2.0.2.tr5
2021-07-29 01:15:03 +00:00
weili10 a584a4e5f2 增加开源软件使用说明 2021-07-28 21:50:56 +08:00
ZijunYin 2f58ad99a0 update docs, add releasenote 2021-07-28 20:45:59 +08:00
ZijunYin 3323c4eecb update docs with new file name and icons 2021-07-27 17:03:50 +08:00
weili10 92f2f166e4 update README.zh.md. 2021-07-27 06:53:49 +00:00
weili10 98ffda59bb update README.zh.md. 2021-07-27 06:50:50 +00:00
weili10 c0989a8a1f update README.zh.md. 2021-07-27 06:50:08 +00:00
weili10 2141b0eb57 !20 同步062fd2fe1728234949b75ce9d1b07267074a8243
Merge pull request !20 from weili10/2.0.2.tr5
2021-07-17 11:46:01 +00:00
weili10 34b3fd413d 同步062fd2fe1728234949b75ce9d1b07267074a8243 2021-07-17 19:42:55 +08:00
weili10 424e4d3c91 update LICENSE. 2021-07-16 13:43:16 +00:00
weili10 982bf7a05b !18 同步c59af4f05ca3150b272cfc2bfa956cf37b7f6291
Merge pull request !18 from weili10/2.0.2.tr5
2021-07-16 13:42:18 +00:00
weili10 54606dd727 同步c59af4f05ca3150b272cfc2bfa956cf37b7f6291 2021-07-16 18:43:32 +08:00
weili10 1a0abe14d7 !15 [Task]新版本文档归档
Merge pull request !15 from fenghaolin/2.02tr5
2021-07-14 13:52:03 +00:00
fenghaolin 1f2e7c6d71 新版本资料归档 2021-07-14 21:40:06 +08:00
weili10 2f43a92d76 !12 同步 16c245707319972d9ae24d6c4e0863abdeaca6b6
Merge pull request !12 from weili10/2.0.2.tr5
2021-07-14 06:18:00 +00:00
weili10 7f158abe29 同步 16c245707319972d9ae24d6c4e0863abdeaca6b6 2021-07-14 14:13:54 +08:00
weili10 1f2771b747 update LICENSE. 2021-07-14 05:52:26 +00:00
weili10 bbdfd6c0ea update LICENSE. 2021-07-14 03:54:54 +00:00
276 changed files with 4288 additions and 18794 deletions
+1 -4
View File
@@ -13,7 +13,4 @@ reviewers:
- wangyu0516
- yskhhh
- lvpeiyuan
- xchu42
- weili10
- goodjobwubai
- fairwarning
- xchu42
+7 -14
View File
@@ -24,11 +24,14 @@ yum install -y cmake zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel g
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配套软件
# python依赖库
| AscendPyTorch版本 | CANN版本 |
| :------------ | :----------- |
| 2.0.2 | CANN 5.0.2 |
依赖库安装:
```python3
pip3 install -r requirements.txt
```
# 使用方式 --生成全量代码并编译
@@ -60,16 +63,6 @@ bash gen.sh
会在pytorch/pytorch/目录中生成npu适配全量代码
## python依赖库
进入到pytorch/pytorch/目录,依赖库安装:
```python3
pip3 install -r requirements.txt
```
## 编译torch的二进制包
进入到pytorch/pytorch/目录,执行
+3 -3
View File
@@ -1,5 +1,6 @@
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# All rights reserved.
# -*- coding: UTF-8 -*-
# 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.
@@ -12,7 +13,6 @@
# 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.
# -*- coding: UTF-8 -*-
import os
import re
@@ -445,7 +445,7 @@ if __name__ == '__main__':
基于NPU芯片的架构特性,模型运算会涉及到混合精度,即混合使用float16和float32数据类型的应用场景。使用float16代替float32有如下好处:
- 对于中间变量的内存占用更少,节省内存的使用。
- 因内存使用会减少,所以数据传出的时间也会相应减少。
- 因内存使用会减少,所以数据传出的时间也会减少。
- float16的计算单元可以提供更快的计算性能。
但是,混合精度训练受限于float16表达的精度范围,单纯将float32转换成float16会影响训练收敛情况,为了保证部分计算使用float16来进行加速的同时能保证训练收敛,这里采用混合精度模块Apex来达到以上效果。混合精度模块Apex是一个集优化性能、精度收敛于一身的综合优化库。
@@ -465,12 +465,12 @@ if __name__ == '__main__':
</thead>
<tbody><tr id="zh-cn_topic_0278765773_row1571763813334"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0278765773_p4502732153412"><a name="zh-cn_topic_0278765773_p4502732153412"></a><a name="zh-cn_topic_0278765773_p4502732153412"></a>O1配置模式</p>
</td>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0278765773_p640053920348"><a name="zh-cn_topic_0278765773_p640053920348"></a><a name="zh-cn_topic_0278765773_p640053920348"></a>Conv, Matmul等使用float16计算,其他如Softmax、BN使用float32。</p>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0278765773_p640053920348"><a name="zh-cn_topic_0278765773_p640053920348"></a><a name="zh-cn_topic_0278765773_p640053920348"></a>Conv, Matmul等使用<span>float16</span>计算,其他如Softmax、BN使用<span>float32</span>。</p>
</td>
</tr>
<tr id="zh-cn_topic_0278765773_row3717173817336"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0278765773_p11503103210344"><a name="zh-cn_topic_0278765773_p11503103210344"></a><a name="zh-cn_topic_0278765773_p11503103210344"></a>O2配置模式</p>
</td>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0278765773_p164001639143419"><a name="zh-cn_topic_0278765773_p164001639143419"></a><a name="zh-cn_topic_0278765773_p164001639143419"></a>BN使用float32,其他绝大部分使用float16。</p>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0278765773_p164001639143419"><a name="zh-cn_topic_0278765773_p164001639143419"></a><a name="zh-cn_topic_0278765773_p164001639143419"></a>BN使用<span>float32</span>,其他绝大部分使用<span>float16</span>。</p>
</td>
</tr>
<tr id="zh-cn_topic_0278765773_row14717193815334"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0278765773_p1950318328349"><a name="zh-cn_topic_0278765773_p1950318328349"></a><a name="zh-cn_topic_0278765773_p1950318328349"></a>静态Loss Scale功能</p>
@@ -540,6 +540,7 @@ if __name__ == '__main__':
apt-get install bzip2
```
4. 编译安装gcc。
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

@@ -14,7 +14,7 @@
- [安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配.md)
<h2 id="简介.md">简介</h2>
用户在准备相关环境进行基于PyTorch框架模型的开发、运行时,可以选择在服务器中手动编译安装PyTorch框架相关模块,或直接获取Ascend Hub镜像中心提供的基础镜像(镜像中已安装PyTorch模块和混合精度模块),进行模型的开发、运行。
用户在准备相关环境进行PyTorch模型的移植及训练时,可以选择在训练服务器中手动编译安装PyTorch框架相关模块,或直接获取Ascend Hub镜像中心提供的基础镜像(镜像中已安装PyTorch模块和混合精度模块),进行模型的移植与训练。
**图 1** 环境准备流程图<a name="zh-cn_topic_0000001119176876_fig1938918396117"></a>
![](figures/环境准备流程图.png "环境准备流程图")
@@ -118,6 +118,7 @@
git submodule update --init --recursive
```
>![](public_sys-resources/icon-note.gif) **说明:**
>受网络波动影响,源码获取时间可能较长,下载过程中请耐心等待。 下载完成之后若没有报错,即生成了PyTorch及其依赖的第三方代码。
@@ -140,6 +141,7 @@
生成的二进制包在当前的dist目录下,即“pytorch/pytorch/dist”文件夹目录下。
5. <a name="zh-cn_topic_0000001152776301_li49671667141"></a>安装PyTorch。
进入“pytorch/pytorch/dist“文件夹目录,执行如下命令安装。
@@ -157,7 +159,7 @@
<h2 id="配置环境变量.md">配置环境变量</h2>
安装完软件包后,需要配置环境变量才能正常使用昇腾PyTorch。建议构建启动脚本,例如构建set\_env.sh脚本,使用source set\_env.sh配置当前窗口的环境变量。set\_env.sh脚本内容如下(以root用户安装,,安装路径为默认路径,python版本为3.7.5为例,用户可根据软件包实际安装路径修改配置项。)。
安装完软件包后,需要配置环境变量才能正常使用昇腾PyTorch。建议构建启动脚本,例如构建set\_env.sh脚本,使用source set\_env.sh配置当前窗口的环境变量。set\_env.sh脚本内容如下(以root用户安装,安装路径为默认路径为例)。
```
cpu_type=$(echo $HOSTTYPE)
@@ -339,6 +341,7 @@ export HCCL_IF_IP="1.1.1.1" # “1.1.1.1”为示例使用的host网卡IP,请
cd ..
```
>![](public_sys-resources/icon-note.gif) **说明:**
>受网络波动影响,源码获取时间可能较长,下载过程中请耐心等待。
@@ -361,6 +364,7 @@ export HCCL_IF_IP="1.1.1.1" # “1.1.1.1”为示例使用的host网卡IP,请
生成的二进制包在当前的dist目录下,即“apex/apex/dist”文件夹目录下。
4. <a name="zh-cn_topic_0000001106176190_li425495374416"></a>安装apex。
进入“apex/apex/dist“文件夹目录,执行如下命令安装。
@@ -387,7 +391,7 @@ export HCCL_IF_IP="1.1.1.1" # “1.1.1.1”为示例使用的host网卡IP,请
## 前提条件<a name="zh-cn_topic_0000001118701830_zh-cn_topic_0275872734_section108914373254"></a>
- 已准备好相应硬件环境驱动和固件的安装,请参见各硬件产品[“驱动和固件安装升级指南”](https://support.huawei.com/enterprise/zh/category/ai-computing-platform-pid-1557196528909)。需要在硬件设备上安装与CANN版本配套的固件与驱动。
- 已完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
- 宿主机上已安装Docker。
## 获取并使用镜像<a name="zh-cn_topic_0000001118701830_section108941734162613"></a>
@@ -493,6 +497,7 @@ CMake版本升级为3.12.1的方法
apt-get install bzip2
```
4. 编译安装gcc。
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
@@ -556,7 +561,7 @@ CMake版本升级为3.12.1的方法
安装“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)
![](figures/zh-cn_image_0000001180656411.png)
## 可能原因<a name="zh-cn_topic_0000001105856364_zh-cn_topic_0175549220_section169499490501"></a>

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

@@ -8,36 +8,36 @@
- [前提条件](#前提条件.md)
- [获取PyTorch源码](#获取PyTorch源码.md)
- [注册算子开发](#注册算子开发.md)
- [算子适配插件开发](#算子适配插件开发.md)
- [编译和安装PyTorch框架](#编译和安装PyTorch框架.md)
- [算子适配开发](#算子适配开发-0.md)
- [编译安装PyTorch框架](#编译安装PyTorch框架.md)
- [算子功能验证](#算子功能验证.md)
- [概述](#概述.md)
- [实现过程](#实现过程.md)
- [FAQ](#FAQ.md)
- [Pillow==5.3.0安装失败](#Pillow-5-3-0安装失败.md)
- [pip3.7 install torchvision安装失败](#pip3-7-install-torchvision安装失败.md)
- [安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配.md)
- [Pillow==5.3.0安装失败](#Pillow==5.3.0安装失败.md)
- [pip3.7 install torchvision安装失败](#pip3.7 install torchvision安装失败.md)
- [安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装torch-\*.whl提示torch 1.5.0xxxx与torchvision所依赖的版本不匹配.md)
- [执行算子功能验证用例,结果成功,但会报一个错误“THPModule\_npu\_shutdown failed.”](#执行算子功能验证用例,结果成功,但会报一个错误THPModule\_npu\_shutdown failed.md)
- [如何查看测试的运行日志](#如何查看测试的运行日志.md)
- [为什么我实现的“自定义TBE算子”无法调用到?](#为什么我实现的-自定义TBE算子-无法调用到.md)
- [如何确定“TBE算子”是否被“PyTorch适配”正确调用](#如何确定-TBE算子-是否被-PyTorch适配-正确调用.md)
- [PyTorch编译失败,提示“error: ld returned 1 exit status”](#PyTorch编译失败-提示-error-ld-returned-1-exit-status.md)
- [PyTorch编译失败,提示“error: call of overload ....”](#PyTorch编译失败-提示-error-call-of-overload.md)
- [测试运行输出的NPU错误码是什么意思,有无对应的含义解释?](#测试运行输出的NPU错误码是什么意思,有无对应的含义解释?.md)
- [为什么我实现的“自定义TBE算子”无法调用到?](#为什么我实现的自定义TBE算子无法调用到?.md)
- [如何确定“TBE算子”是否被“PyTorch适配”正确调用?](#如何确定TBE算子是否被PyTorch适配正确调用?.md)
- [PyTorch编译失败,提示“error: ld returned 1 exit status”](#PyTorch编译失败,提示error: ld returned 1 exit status.md)
- [PyTorch编译失败,提示“error: call of overload ....”](#PyTorch编译失败,提示error: call of overload.md)
- [附录](#附录.md)
- [CMake安装方法](#CMake安装方法.md)
- [自定义算子导出方法](#自定义算子导出方法.md)
<h2 id="简介.md">简介</h2>
## 简介<a name="简介.md"></a>
## 概述<a name="zh-cn_topic_0000001125558589_section7405182695312"></a>
用户通过完成TBE自定义算子适配PyTorch框架,实现PyTorch框架中算子在昇腾AI处理器上运行。
为了实现PyTorch深度学习框架在昇腾AI处理器上运行,需要将框架算子用TBE自定义开发。
<h2 id="算子开发流程.md">算子开发流程</h2>
## 算子开发流程<a name="算子开发流程.md"></a>
Pytorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
1. TBE算子开发:昇腾AI软件栈中不包含相应的算子,需要先完成TBE算子的开发,再进行PyTorch框架下的算子适配。
TBE算子开发流程及方法请参见《CANN TBE自定义算子开发指南》。
TBE算子开发流程及方法请参见《[CANN TBE自定义算子开发指南](https://support.huawei.com/enterprise/zh/doc/EDOC1100191916)》。
2. PyTorch框架下的算子适配:昇腾AI软件栈中已实现了相应的TBE算子,可直接进行PyTorch框架适配。
@@ -46,111 +46,45 @@ Pytorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
**图 1** PyTorch框架下的算子适配流程<a name="zh-cn_topic_0000001105032530_fig1981905141719"></a>
![](figures/PyTorch框架下的算子适配流程.png "PyTorch框架下的算子适配流程")
**表 1** 算子开发步骤详解
<a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_table131083578318"></a>
<table><thead align="left"><tr id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_row210905703113"><th class="cellrowborder" valign="top" width="6.811326262527976%" id="mcps1.2.5.1.1"><p id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p41091857143113"><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p41091857143113"></a><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p41091857143113"></a>序号</p>
</th>
<th class="cellrowborder" valign="top" width="17.865135740001946%" id="mcps1.2.5.1.2"><p id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p1710955713112"><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p1710955713112"></a><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p1710955713112"></a>步骤</p>
</th>
<th class="cellrowborder" valign="top" width="55.55123090396029%" id="mcps1.2.5.1.3"><p id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p26391719183320"><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p26391719183320"></a><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p26391719183320"></a>描述</p>
</th>
<th class="cellrowborder" valign="top" width="19.772307093509777%" id="mcps1.2.5.1.4"><p id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p13109155719317"><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p13109155719317"></a><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p13109155719317"></a>参考</p>
</th>
</tr>
</thead>
<tbody><tr id="zh-cn_topic_0000001105032530_row1381016124918"><td class="cellrowborder" valign="top" width="6.811326262527976%" headers="mcps1.2.5.1.1 "><p id="zh-cn_topic_0000001105032530_p1181015128915"><a name="zh-cn_topic_0000001105032530_p1181015128915"></a><a name="zh-cn_topic_0000001105032530_p1181015128915"></a>1</p>
</td>
<td class="cellrowborder" valign="top" width="17.865135740001946%" headers="mcps1.2.5.1.2 "><p id="zh-cn_topic_0000001105032530_p1881012121799"><a name="zh-cn_topic_0000001105032530_p1881012121799"></a><a name="zh-cn_topic_0000001105032530_p1881012121799"></a>环境准备</p>
</td>
<td class="cellrowborder" valign="top" width="55.55123090396029%" headers="mcps1.2.5.1.3 "><p id="zh-cn_topic_0000001105032530_p1381018121891"><a name="zh-cn_topic_0000001105032530_p1381018121891"></a><a name="zh-cn_topic_0000001105032530_p1381018121891"></a>准备算子开发及运行验证所依赖的开发环境与运行环境。</p>
</td>
<td class="cellrowborder" rowspan="2" valign="top" width="19.772307093509777%" headers="mcps1.2.5.1.4 "><p id="zh-cn_topic_0000001105032530_p1498205181013"><a name="zh-cn_topic_0000001105032530_p1498205181013"></a><a name="zh-cn_topic_0000001105032530_p1498205181013"></a><a href="#算子开发准备.md">算子开发准备</a></p>
</td>
</tr>
<tr id="zh-cn_topic_0000001105032530_row194671091290"><td class="cellrowborder" valign="top" headers="mcps1.2.5.1.1 "><p id="zh-cn_topic_0000001105032530_p3467169594"><a name="zh-cn_topic_0000001105032530_p3467169594"></a><a name="zh-cn_topic_0000001105032530_p3467169594"></a>2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.5.1.2 "><p id="zh-cn_topic_0000001105032530_p1346749990"><a name="zh-cn_topic_0000001105032530_p1346749990"></a><a name="zh-cn_topic_0000001105032530_p1346749990"></a>算子速查</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.5.1.3 "><p id="zh-cn_topic_0000001105032530_p1767111499129"><a name="zh-cn_topic_0000001105032530_p1767111499129"></a><a name="zh-cn_topic_0000001105032530_p1767111499129"></a>查看TBE算子支持列表和PyTorch算子适配列表。</p>
<a name="zh-cn_topic_0000001105032530_ul03431749101318"></a><a name="zh-cn_topic_0000001105032530_ul03431749101318"></a><ul id="zh-cn_topic_0000001105032530_ul03431749101318"><li>当前<span id="zh-cn_topic_0000001105032530_ph1748571571010"><a name="zh-cn_topic_0000001105032530_ph1748571571010"></a><a name="zh-cn_topic_0000001105032530_ph1748571571010"></a>昇腾AI处理器</span>支持的算子列表及支持的算子的详细规格约束。</li><li>当前PyTorch适配的算子列表。</li></ul>
</td>
</tr>
<tr id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_row411025743119"><td class="cellrowborder" valign="top" width="6.811326262527976%" headers="mcps1.2.5.1.1 "><p id="zh-cn_topic_0000001105032530_p156991054952"><a name="zh-cn_topic_0000001105032530_p156991054952"></a><a name="zh-cn_topic_0000001105032530_p156991054952"></a>3</p>
</td>
<td class="cellrowborder" valign="top" width="17.865135740001946%" headers="mcps1.2.5.1.2 "><p id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p3110657203110"><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p3110657203110"></a><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p3110657203110"></a>获取PyTorch源码</p>
</td>
<td class="cellrowborder" valign="top" width="55.55123090396029%" headers="mcps1.2.5.1.3 "><p id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p381282212"><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p381282212"></a><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p381282212"></a>获取昇腾社区PyTorch源码。</p>
</td>
<td class="cellrowborder" rowspan="4" valign="top" width="19.772307093509777%" headers="mcps1.2.5.1.4 "><p id="zh-cn_topic_0000001105032530_p10679152717175"><a name="zh-cn_topic_0000001105032530_p10679152717175"></a><a name="zh-cn_topic_0000001105032530_p10679152717175"></a><a href="#算子开发准备.md">算子适配开发</a></p>
</td>
</tr>
<tr id="zh-cn_topic_0000001105032530_row1184984391512"><td class="cellrowborder" valign="top" headers="mcps1.2.5.1.1 "><p id="zh-cn_topic_0000001105032530_p1054075616153"><a name="zh-cn_topic_0000001105032530_p1054075616153"></a><a name="zh-cn_topic_0000001105032530_p1054075616153"></a>4</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.5.1.2 "><p id="zh-cn_topic_0000001105032530_p1463045415151"><a name="zh-cn_topic_0000001105032530_p1463045415151"></a><a name="zh-cn_topic_0000001105032530_p1463045415151"></a>注册算子开发</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.5.1.3 "><p id="zh-cn_topic_0000001105032530_p1634748161614"><a name="zh-cn_topic_0000001105032530_p1634748161614"></a><a name="zh-cn_topic_0000001105032530_p1634748161614"></a>将算子分发到昇腾AI处理器。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_row252634054913"><td class="cellrowborder" valign="top" headers="mcps1.2.5.1.1 "><p id="zh-cn_topic_0000001105032530_p55407561152"><a name="zh-cn_topic_0000001105032530_p55407561152"></a><a name="zh-cn_topic_0000001105032530_p55407561152"></a>5</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.5.1.2 "><p id="zh-cn_topic_0000001105032530_p116302054131518"><a name="zh-cn_topic_0000001105032530_p116302054131518"></a><a name="zh-cn_topic_0000001105032530_p116302054131518"></a>算子适配层开发</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.5.1.3 "><p id="zh-cn_topic_0000001105032530_p8583195119173"><a name="zh-cn_topic_0000001105032530_p8583195119173"></a><a name="zh-cn_topic_0000001105032530_p8583195119173"></a>算子适配层开发,将基于第三方框架的算子属性映射成适配昇腾AI处理器的算子属性。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_row17721543154917"><td class="cellrowborder" valign="top" headers="mcps1.2.5.1.1 "><p id="zh-cn_topic_0000001105032530_p125402056121515"><a name="zh-cn_topic_0000001105032530_p125402056121515"></a><a name="zh-cn_topic_0000001105032530_p125402056121515"></a>6</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.5.1.2 "><p id="zh-cn_topic_0000001105032530_p963085451515"><a name="zh-cn_topic_0000001105032530_p963085451515"></a><a name="zh-cn_topic_0000001105032530_p963085451515"></a>编译安装PyTorch框架</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.5.1.3 "><p id="zh-cn_topic_0000001105032530_p1463431151811"><a name="zh-cn_topic_0000001105032530_p1463431151811"></a><a name="zh-cn_topic_0000001105032530_p1463431151811"></a>编译适配开发后的PyTorch源码,并安装编译的源码包。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_row162484372491"><td class="cellrowborder" valign="top" width="6.811326262527976%" headers="mcps1.2.5.1.1 "><p id="zh-cn_topic_0000001105032530_p454075611155"><a name="zh-cn_topic_0000001105032530_p454075611155"></a><a name="zh-cn_topic_0000001105032530_p454075611155"></a>7</p>
</td>
<td class="cellrowborder" valign="top" width="17.865135740001946%" headers="mcps1.2.5.1.2 "><p id="zh-cn_topic_0000001105032530_p11630135413155"><a name="zh-cn_topic_0000001105032530_p11630135413155"></a><a name="zh-cn_topic_0000001105032530_p11630135413155"></a>算子功能验证</p>
</td>
<td class="cellrowborder" valign="top" width="55.55123090396029%" headers="mcps1.2.5.1.3 "><p id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p4952132615216"><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p4952132615216"></a><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p4952132615216"></a>在真实的硬件环境中验证算子功能。</p>
</td>
<td class="cellrowborder" valign="top" width="19.772307093509777%" headers="mcps1.2.5.1.4 "><p id="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p20908934557"><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p20908934557"></a><a name="zh-cn_topic_0000001105032530_zh-cn_topic_0228422310_p20908934557"></a><a href="#算子功能验证.md">算子功能验证</a></p>
</td>
</tr>
</tbody>
</table>
| 序号 | 步骤 | 描述 | 参考 |
| ---- | ------------------- | ------------------------------------------------------------ | -------------------------------- |
| 1 | 环境准备 | 准备算子开发及运行验证所依赖的开发环境与运行环境。 | [算子开发准备](#算子开发准备.md) |
| 2 | 算子速查 | 查看TBE算子支持列表和PyTorch算子适配列表。当前昇腾AI处理器支持的算子列表及支持的算子的详细规格约束;当前PyTorch适配的算子列表。 | [算子开发准备](#算子开发准备.md) |
| 3 | 获取PyTorch源码 | 获取昇腾社区PyTorch源码。 | [算子适配开发](#算子适配开发.md) |
| 4 | 注册算子开发 | 将算子分发到昇腾AI处理器。 | [算子适配开发](#算子适配开发.md) |
| 5 | 算子适配层开发 | 算子适配层开发,将基于第三方框架的算子属性映射成适配昇腾AI处理器的算子属性。 | [算子适配开发](#算子适配开发.md) |
| 6 | 编译安装PyTorch框架 | 编译适配开发后的Pytorch源码,并安装编译的源码包。 | [算子适配开发](#算子适配开发.md) |
| 7 | 算子验证 | 在真实的硬件环境中验证算子功能。 | [算子功能验证](#算子功能验证.md) |
<h2 id="算子开发准备.md">算子开发准备</h2>
## 算子开发准备<a name="算子开发准备.md"></a>
- **[环境准备](#环境准备.md)**
- **[算子速查](#算子速查.md)**
### 环境准备<a name="环境准备.md"></a>
<h2 id="环境准备.md">环境准备</h2>
**前提条件**
## 前提条件<a name="zh-cn_topic_0000001125736787_section12464163765320"></a>
- 需完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
- 需安装3.12.0及以上版本的CMake,安装方法请参考[CMake安装方法](#CMake安装方法.md)。
- 需确保已安装7.3.0以上版本的gcc,7.3.0版本gcc具体安装及使用方式请参见《CANN 软件安装指南》中的“安装7.3.0版本gcc”章节。
- 已完成CANN开发或运行环境的安装,具体操作请参考《[CANN 软件安装指南](https://support.huawei.com/enterprise/zh/ascend-computing/cann-pid-251168373)》。
- 需安装3.12.0以上版本的CMake,安装方法请参考[CMake安装方法](#CMake安装方法.md)。
- 需确保已安装7.3.0以上版本的gcc,7.3.0版本gcc具体安装及使用方式请参见《[CANN 软件安装指南](https://support.huawei.com/enterprise/zh/ascend-computing/cann-pid-251168373)》中的“安装7.3.0版本gcc”章节。
- 需确保环境中已安装git工具,以Ubuntu和CentOS系统为例,命令如下:
- Ubuntu系统
```
apt-get install git
```
**apt-get install git**
- CentOS系统
```
yum install git
```
**yum install git**
## 安装PyTorch依赖环境<a name="zh-cn_topic_0000001125736787_section18699192116550"></a>
**安装PyTorch依赖环境**
如果使用非root用户安装Python及其依赖,用户需要在每句命令末尾加上**--user**,保证安装的正常进行。命令示例为:**pip3.7 install pyyaml --user**
如果使用非root用户安装Python及其依赖,用户需要在每句命令结尾加上**--user**,保证安装的正常进行。命令示例为:**pip3.7 install pyyaml --user**
```
pip3.7 install pyyaml
@@ -161,46 +95,38 @@ pip3.7 install Pillow==5.3.0
>![](public_sys-resources/icon-note.gif) **说明:**
>若以上过程出错,请参考[FAQ](#FAQ.md)尝试解决问题。
<h2 id="算子速查.md">算子速查</h2>
### 算子速查<a name="算子速查.md"></a>
进行算子开发时,您可以查询当前昇腾AI处理器中支持的算子列表和当前PyTorch适配的算子列表。根据查询结果进行算子开发或PyTorch算子适配。
- 若昇腾AI处理器不支持算子,则需要进行TBE算子开发和PyTorch框架算子适配。
- 若昇腾AI处理器支持算子但PyTorch框架没有算子适配,仅需要进行PyTorch框架下算子适配。
- 若PyTorch框架已经适配算子,直接使用算子即可,不需要开发和适配。
昇腾AI处理器和PyTorch适配的算子查询方式如下。
- 当前昇腾AI处理器中支持的算子以及对应的算子约束可以通过以下两种方式查询。
- 命令行开发方式下,您可以参见《CANN 算子清单 \(Ascend 910\)》进行离线查询。
- MindStudio开发方式下,您可以通过MindStudio进行在线查询,详细查看方法可参见《MindStudio 用户指南》中的“算子&模型速查”章节。
- 命令行开发方式下,您可以参见《[CANN 算子清单 \(Ascend 910\)](https://support.huawei.com/enterprise/zh/doc/EDOC1100191920)》进行离线查询。
- MindStudio开发方式下,您可以通过MindStudio进行在线查询,详细查看方法可参见《[MindStudio 用户指南](https://support.huaweicloud.com/mindstudio301/index.html)》中的“算子&模型速查”章节。
- 当前PyTorch适配的算子列表可以参见《[PyTorch适配算子清单](https://support.huawei.com/enterprise/zh/doc/EDOC1100191773)》
- 当前PyTorch适配的算子列表可以参见《PyTorch适配算子清单》。
## 算子适配开发<a name="算子适配开发.md"></a>
<h2 id="算子适配开发.md">算子适配开发</h2>
- **[前提条件](#前提条件.md)**
- **[前提条件](#前提条件.md)**
- **[获取PyTorch源码](#获取PyTorch源码.md)**
- **[获取PyTorch源码](#获取PyTorch源码.md)**
- **[注册算子开发](#注册算子开发.md)**
- **[注册算子开发](#注册算子开发.md)**
- **[算子适配开发](#算子适配开发-0.md)**
- **[算子适配插件开发](#算子适配插件开发.md)**
- **[编译安装PyTorch框架](#编译安装PyTorch框架.md)**
- **[编译和安装PyTorch框架](#编译和安装PyTorch框架.md)**
### 前提条件<a name="前提条件.md"></a>
1. 完成开发及运行环境准备及相关依赖的安装,详情请参见[环境准备](#环境准备.md)。
2. 完成相关的TBE算子开发及部署,详情请参见《[CANN TBE自定义算子开发指南](https://support.huawei.com/enterprise/zh/doc/EDOC1100191916)》。
<h2 id="前提条件.md">前提条件</h2>
### 获取PyTorch源码<a name="获取PyTorch源码.md"></a>
- 完成开发及运行环境准备及相关依赖的安装,详情请参见[环境准备](#环境准备.md)。
- 完成相关的TBE算子开发及部署,详情请参见《CANN TBE自定义算子开发指南》。
<h2 id="获取PyTorch源码.md">获取PyTorch源码</h2>
从gitee上获取适配昇腾AI处理器的PyTorch源代码,获取地址为: [https://gitee.com/ascend/pytorch-develop](https://gitee.com/ascend/pytorch-develop) 。用户可以通过执行下面git命令行下载源代码。
从gitee上获取适配昇腾AI处理器的PyTorch源代码,获取地址为:[https://gitee.com/ascend/pytorch](https://gitee.com/ascend/pytorch) 。用户可以通过执行下面git命令行下载源代码。
```
git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
git clone https://gitee.com/ascend/pytorch.git --deepth=1
```
下载成功后,得到pytorch文件目录。
@@ -208,13 +134,13 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
>![](public_sys-resources/icon-note.gif) **说明:**
>如无权限获取代码,请联系华为技术支持申请加入“Ascend”组织。
<h2 id="注册算子开发.md">注册算子开发</h2>
### 注册算子开发<a name="注册算子开发.md"></a>
## 概述<a name="zh-cn_topic_0000001125315887_section693616257599"></a>
#### 概述
当前制定的NPU适配派发原则是NPU算子的派发不经过框架公共函数,直接派发成NPU适配的函数,即算子执行调用栈中只包含NPU适配的函数调用,不包含框架公共函数。PyTorch框架在编译时,会根据 native\_functions.yaml 的定义,按框架中定义的类型和设备分发原则,生成相应的新算子的中间层的调用说明。对于NPU,会生成在 build/aten/src/ATen/NPUType.cpp。
## 注册算子开发方法<a name="zh-cn_topic_0000001125315887_section16610942811"></a>
#### 注册算子开发方法
1. 打开native\_functions.yaml文件。
@@ -233,6 +159,7 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
- func:适配算子名称(输入参数信息) -> 返回类型
```
3. 修改native\_functions.yaml文件,添加实现该算子相关函数的分发描述。
yaml 文件编写规范:
@@ -251,6 +178,7 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
NPU: NPU_Adapt_Fun_Name
```
>![](public_sys-resources/icon-note.gif) **说明:**
>NPU\_Adapt\_Fun\_Name的格式为 :
>- 如果原Fun\_Name无"\_"后缀,则格式:Fun\_Name + "\_" + "npu",如:add --\> add\_npu。
@@ -258,12 +186,12 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
>该格式供参考,算子适配开发过程中的函数名需与NPU\_Adapt\_Fun\_Name保持一致。
## 示例<a name="zh-cn_topic_0000001125315887_section3651235962"></a>
#### 示例
以torch.add\(\)算子为例介绍注册算子开发过程。
1. 打开native\_functions.yaml文件。
2. 确定相关函数。
2. 确定相关函数
在yaml中搜索add,找到与add算子相关的函数。
@@ -342,21 +270,19 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
supports_named_tensor: True
```
### 算子适配开发<a name="算子适配开发-0.md"></a>
<h2 id="算子适配插件开发.md">算子适配插件开发</h2>
## 简介<a name="zh-cn_topic_0000001125315877_section16410139174517"></a>
#### 简介
用户通过开发算子适配插件,实现PyTorch原生算子的输入参数、输出参数和属性的格式转换,使转换后的格式与TBE算子的输入参数、输出参数和属性的格式相同。适配昇腾AI处理器的PyTorch源代码中提供了适配关联、类型转换和判别、处理动态shape等相关的方法供用户使用。
## 适配插件实现<a name="zh-cn_topic_0000001125315877_section1174074518456"></a>
#### 适配插件实现
1. 创建适配插件文件。
1. 创建适配插件文件
NPU TBE算子适配文件保存在pytorch/aten/src/ATen/native/npu目录下,命名风格采用大驼峰,命名格式:<算子名\> + <KernelNpu\>.cpp,如:AddKernelNpu.cpp。
2. 引入依赖头文件。
2. 引入依赖头文件
适配昇腾AI处理器的PyTorch源代码在ATen/native/npu/utils中提供适配常用的工具供用户使用。
@@ -365,22 +291,22 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
3. 定义算子适配主体函数。
根据注册算子开发中的分发函数确定自定义算子适配主体函数。
根据注册算子开发中的分发函数确定自定义算子适配主题函数。
4. 分别实现适配主体函数。
实现算子适配主题函数,根据TBE算子原型构造得到对应的input、output、attr。
## 示例<a name="zh-cn_topic_0000001125315877_section18021337113012"></a>
#### 示例
以torch.add\(\)算子为例介绍算子适配开发过程。
1. 创建适配插件文件。
1. 创建适配插件文件
在pytorch/aten/src/ATen/native/npu目录下创建AddKernelNpu.cpp适配文件。
在pytorch/aten/src/ATen/native/npu目录下创建AddKernelNpu.cpp适配文件
2. 引入依赖头文件。
2. 引入依赖头文件
```
#include <c10/npu/OptionsManager.h>
@@ -389,6 +315,7 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
```
>![](public_sys-resources/icon-note.gif) **说明:**
>" OptionsManager.h"中主要包含类型动态shape相关的函数。
>" CalcuOpUtil.h "中主要包含类型转换和判别的函数。
>" OpAdapter.h"文件中主要包含适配关联的头文件。
@@ -529,9 +456,9 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
>![](public_sys-resources/icon-note.gif) **说明:**
>AddKernelNpu.cpp的详细实现代码请参见pytorch/aten/src/ATen/native/npu/AddKernelNpu.cpp文档。
<h2 id="编译和安装PyTorch框架.md">编译和安装PyTorch框架</h2>
### 编译安装PyTorch框架<a name="编译安装PyTorch框架.md"></a>
## 编译PyTorch框架<a name="zh-cn_topic_0000001125736777_section470105143317"></a>
#### 编译PyTorch框架
1. 进入PyTorch工作目录 :“pytorch“。
2. 给脚本文件赋权限:
@@ -542,72 +469,75 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
**./build.sh**
>![](public_sys-resources/icon-note.gif) **说明:**
>首次编译持续的时间较长,可能超过30分钟,建议:若无必要,无需执行"make clean"。
4. 编译成功后,会在“**pytorch/dist**” 下会生成 torch-\*.whl 包,例如:torch-1.5.0a0-cp37-cp37m-linux\_x86.whl
4. 编译成功后,会在“**pytorch/dist**” 下生成 torch-\*.whl 包,例如:torch-1.5.0a0-cp37-cp37m-linux\_x86.whl。
>![](public_sys-resources/icon-note.gif) **说明:**
>首次编译持续的时间较长,可能超过30分钟,建议:若无必要,无需执行"make clean"。
## 安装PyTorch框架<a name="zh-cn_topic_0000001125736777_section119821419153412"></a>
#### 安装PyTorch框架
1. 将[编译和安装PyTorch框架](#编译和安装PyTorch框架.md)生成的torch-\*.whl包上传到服务器任一路径。
1. 将[编译安装PyTorch框架](#编译安装PyTorch框架.md)生成的torch-\*.whl包上传到服务器任一路径。
2. 进入torch-\*.whl 所在的目录,使用pip命令完成torch安装。
当前登录用户为root用户时,执行:
```
pip3.7 install torch-*.whl
pip3.7.5 install torch-*.whl
```
当前登录用户为非root用户时,执行:
```
pip3.7 install torch-*.whl --user
pip3.7.5 install torch-*.whl --user
```
>![](public_sys-resources/icon-note.gif) **说明:**
>- 修改代码之后,需要重新执行“编译”和“安装”PyTorch过程。
>- 安装过程中,可能会出现错误提示"torchvision 0.6.0" 版本不匹配,此问题无影响,忽略即可。
>1. 修改代码之后,需要重新执行“编译”和“安装”PyTorch过程。
>2. 安装过程中,可能会出现错误提示"torchvision 0.6.0" 版本不匹配,此问题无影响,忽略即可。
<h2 id="算子功能验证.md">算子功能验证</h2>
## 算子功能验证<a name="算子功能验证.md"></a>
- **[概述](#概述.md)**
- **[实现过程](#实现过程.md)**
### 概述<a name="概述.md"></a>
<h2 id="概述.md">概述</h2>
## 简介<a name="zh-cn_topic_0000001117556616_section29881459155718"></a>
#### 简介
完成算子适配开发后,可通过运行适配昇腾处理器的PyTorch算子,验证算子运行结果是否正确。
算子功能验证会覆盖算子开发的所有交付件,包含实现文件,算子原型定义、算子信息库以及算子适配插件。本节仅对验证的方法做介绍。
## 测试用例及测试工具<a name="zh-cn_topic_0000001117556616_section158972351160"></a>
#### 测试用例及测试工具
进行自定义算子功能验证,通过PyTorch前端构造自定义算子的函数并运行验证。
在https://gitee.com/ascend/pytorch-develop中 "pytorch/test/test\_npu/test\_network\_ops"目录下提供了测试用例及测试工具,供用户参考。
在https://gitee.com/ascend/pytorch中 "pytorch/test/test\_npu/test\_network\_ops"目录下提供了测试用例及测试工具,供用户参考。
<h2 id="实现过程.md">实现过程</h2>
### 实现过程<a name="实现过程.md"></a>
## 简介<a name="zh-cn_topic_0000001164276377_section29881459155718"></a>
#### 简介
本章通过具体例子,完成PyTorch算子的功能测试步骤。
## 操作步骤<a name="zh-cn_topic_0000001164276377_section02504494109"></a>
#### 操作步骤
1. 设置环境变量。
```
# 进行环境变量设置。具体如下(以HwHiAiUser用户安装,安装路径为默认路径为例):
. /home/HwHiAiUser/Ascend/ascend-toolkit/set_env.sh
export install_path=/home/HwHiAiUser/Ascend/ascend-toolkit/latest
export PATH={install_path}/fwkacllib/ccec_compiler/bin:{install_path}/fwkacllib/bin:{install_path}/toolkit/bin:$PATH
export LD_LIBRARY_PATH={install_path}/fwkacllib/lib64:$LD_LIBRARY_PATH
export PYTHONPATH={install_path}/fwkacllib/python/site-packages:{install_path}/toolkit/python/site-packages:$PYTHONPATH
export ASCEND_OPP_PATH={install_path}/opp/
export ASCEND_AICPU_PATH={install_path}/x86_64-linux/
```
install\_path请修改为Toolkit的实际安装路径。
2. 编写测试脚本。以add算子为例,在“pytorch/test/test\_npu/test\_network\_ops“路径下编写测试脚本文件: test\_add.py。
2. 编写测试脚本。以add算子为例,在“pytorch/test/test\_npu/test\_network\_ops“路径下编写测试脚本文件: testcase\_add.py。
以下示例仅为一个简单的用例实现供用户参考,具体测试用例的实现,需要根据算子定义进行完整的覆盖才能保证功能的基本正确。
@@ -653,7 +583,7 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
format_list = [0, 3, 29]
shape_format = [
[np.float32, i, [5, 256]] for i in format_list
]
]
self.add_result(shape_format)
instantiate_device_type_tests(TestAdd, globals(), except_for="cpu")
@@ -666,91 +596,113 @@ git clone https://gitee.com/ascend/pytorch-develop.git --deepth=1
3. 执行测试用例脚本
进入test\_add.py所在的目录,执行:
进入add\_testcase.py所在的目录,执行:
```
python3.7 test_add.py
python3.7.5 testcase_add.py
```
## FAQ<a name="FAQ.md"></a>
<h2 id="FAQ.md">FAQ</h2>
- **[Pillow==5.3.0安装失败](#Pillow==5.3.0安装失败.md)**
- **[Pillow==5.3.0安装失败](#Pillow-5-3-0安装失败.md)**
- **[pip3.7 install torchvision安装失败](#pip3.7 install torchvision安装失败.md)**
- **[pip3.7 install torchvision安装失败](#pip3-7-install-torchvision安装失败.md)**
- **[安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装torch-\*.whl提示torch 1.5.0xxxx与torchvision所依赖的版本不匹配.md)**
- **[安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配.md)**
- **[执行算子功能验证用例,结果成功,但会报一个错误“THPModule\_npu\_shutdown failed.”](#执行算子功能验证用例,结果成功,但会报一个错误THPModule\_npu\_shutdown failed.md)**
- **[如何查看测试的运行日志](#如何查看测试的运行日志.md)**
- **[为什么我实现的“自定义TBE算子”无法调用到?](#为什么我实现的-自定义TBE算子-无法调用到.md)**
- **[测试运行输出的NPU错误码是什么意思,有无对应的含义解释?](#测试运行输出的NPU错误码是什么意思,有无对应的含义解释?.md)**
- **[如何确定“TBE算子”是否被“PyTorch适配”正确调用](#如何确定-TBE算子-是否被-PyTorch适配-正确调用.md)**
- **[为什么我实现的“自定义TBE算子”无法调用到?](#为什么我实现的自定义TBE算子无法调用到?.md)**
- **[PyTorch编译失败,提示“error: ld returned 1 exit status”](#PyTorch编译失败-提示-error-ld-returned-1-exit-status.md)**
- **[如何确定“TBE算子”是否被“PyTorch适配”正确调用?](#如何确定TBE算子是否被PyTorch适配正确调用?.md)**
- **[PyTorch编译失败,提示“error: call of overload ....”](#PyTorch编译失败-提示-error-call-of-overload.md)**
- **[PyTorch编译失败,提示“error: ld returned 1 exit status”](#PyTorch编译失败,提示error: ld returned 1 exit status.md)**
- **[PyTorch编译失败,提示“error: call of overload ....”](#PyTorch编译失败,提示error: call of overload.md)**
<h2 id="Pillow-5-3-0安装失败.md">Pillow==5.3.0安装失败</h2>
### Pillow==5.3.0安装失败<a name="Pillow==5.3.0安装失败.md"></a>
## 现象描述<a name="zh-cn_topic_0000001125315879_zh-cn_topic_0175549220_section197270431505"></a>
**现象描述**
pillow==5.3.0安装失败。
## 可能原因<a name="zh-cn_topic_0000001125315879_zh-cn_topic_0175549220_section169499490501"></a>
**可能原因**
缺少必要的依赖,如:libjpeg、python-devel、 zlib-devel 、libjpeg-turbo-devel等等。
## 处理方法<a name="zh-cn_topic_0000001125315879_section108142031907"></a>
**处理方法**
执行以下命令安装所需依赖。
apt-get install libjpeg python-devel zlib-devel libjpeg-turbo-devel。
```
apt-get install libjpeg python-devel zlib-devel libjpeg-turbo-devel
```
### pip3.7 install torchvision安装失败<a name="pip3.7 install torchvision安装失败.md"></a>
<h2 id="pip3-7-install-torchvision安装失败.md">pip3.7 install torchvision安装失败</h2>
## 现象描述<a name="zh-cn_topic_0000001125641109_zh-cn_topic_0175549220_section197270431505"></a>
**现象描述**
pip3.7 install torchvision安装失败。
## 可能原因<a name="zh-cn_topic_0000001125641109_zh-cn_topic_0175549220_section169499490501"></a>
**可能原因**
torch与torchvision版本不匹配。
## 处理方法<a name="zh-cn_topic_0000001125641109_section108142031907"></a>
**处理方法**
执行以下命令。
```
pip3.7 install torchvision --no-deps
```
<h2 id="安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配.md">安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配</h2>
### 安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配<a name="安装torch-\*.whl提示torch 1.5.0xxxx与torchvision所依赖的版本不匹配.md"></a>
## 现象描述<a name="zh-cn_topic_0000001125315883_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_0000001144082048.png)
![](figures/zh-cn_image_0000001172886189.png)
但实际安装成功
但实际安装成功。
## 可能原因<a name="zh-cn_topic_0000001125315883_zh-cn_topic_0175549220_section169499490501"></a>
**可能原因**
安装torch时,会自动触发torchvision进行依赖版本检查,环境中安装的torchvision版本为0.6.0,检查时发现我们安装的torch-\*.whl的版本号与要求的1.5.0不一致,所以提示了一条错误 。
## 处理方法<a name="zh-cn_topic_0000001125315883_section108142031907"></a>
**处理方法**
对实际结果无影响,无需处理。
<h2 id="如何查看测试的运行日志.md">如何查看测试的运行日志</h2>
### 执行算子功能验证用例,结果成功,但会报一个错误“THPModule\_npu\_shutdown failed.”<a name="执行算子功能验证用例,结果成功,但会报一个错误THPModule\_npu\_shutdown failed.md"></a>
**现象描述**
执行算子功能验证用例,结果成功,但会报一个错误“THPModule\_npu\_shutdown failed.”。
![](figures/zh-cn_image_0000001173046107.png)
**可能原因**
可能是框架影响,待进一步定位 。
**处理方法**
对实际结果无影响,无需处理,忽略此问题。
### 如何查看测试的运行日志<a name="如何查看测试的运行日志.md"></a>
测试运行过程提示错误,但直接可参考的信息太少,如何才能看到更详细的运行日志?
设置日志输出到屏幕,重定向到指定文本文件
方式一:直接查看运行日志
1. 进入 "/var/log/npu"目录
在此目录下,对于算子功能测试运行,主要的涉及日志路径为“oplog”和“slog”,建议优先查看“oplog”中的日志,这里记录了算子运行过程中的关键信息;slog下的日志记录系统的运行过程及异常信息,具体日志信息内容,参考[日志文件](https://support.huaweicloud.com/lr-A800_9000_9010/atlaslog_24_0003.html)描述。
2. 进入对应的日志目录,使用vi等工具打开最新的日志文件,进行日志查看。
>![](public_sys-resources/icon-note.gif) **说明:**
>以“/var/log/npu/oplog”为例,"vi oplog.log",可以查看到很多日志信息。但由于可能存在很多开发者同时操作设备进行测试,所有会包含其他开发者的运行日志信息,需要开发者通过“时间”等信息,识别出相关的日志。建议使用“方式二”
方式二:设置日志输出到屏幕,重定向到指定文本文件
1. 设置环境变量,将当前用户的日志到屏幕。
@@ -760,68 +712,76 @@ pip3.7 install torchvision --no-deps
设置完成后,直接运行测试用例,就可以将相关的日志输出到屏幕,为了方便查看和回溯,建议根据需要使用[2](#zh-cn_topic_0000001125315889_li168732325719)运行。
2. <a name="zh-cn_topic_0000001125315889_li168732325719"></a>运行测试用例时,将日志重定向到指定文件。
2. 运行测试用例时,将日志重定向到指定文件。
```
python3.7 test_add.py > test_log.txt
python3.7.5 add_testcase.py > test_log.txt
```
### 测试运行输出的NPU错误码是什么意思,有无对应的含义解释?<a name="测试运行输出的NPU错误码是什么意思,有无对应的含义解释?.md"></a>
<h2 id="为什么我实现的-自定义TBE算子-无法调用到.md">为什么我实现的“自定义TBE算子”无法调用到?</h2>
参考“[错误码定义](https://support.huaweicloud.com/adevg-A300_3000_3010/atlasdevelopment_01_0256.html)”。
## 现象描述<a name="zh-cn_topic_0000001125736795_zh-cn_topic_0175549220_section197270431505"></a>
### 为什么我实现的“自定义TBE算子”无法调用到?<a name="为什么我实现的自定义TBE算子无法调用到?.md"></a>
**现象描述**
完成“自定义TBE算子”开发,和“PyTorch”适配开发,但执行测试用例,发现无法调用到新开发的算子。
## 可能原因<a name="zh-cn_topic_0000001125736795_zh-cn_topic_0175549220_section169499490501"></a>
**可能原因**
- 环境变量没有正确设置。
- yaml存在错误,导致没有正确分发。
- 自定义TBE算子实现存在问题,导致无法调用到。
1. 环境变量没有正确设置;
2. yaml存在错误,导致没有正确分发;
3. 自定义TBE算子实现存在问题,导致无法调用到。
## 处理方法<a name="zh-cn_topic_0000001125736795_section108142031907"></a>
**处理方法**
1. 参考“[算子功能验证](#算子功能验证.md)”章节,完成运行环境设置,特别注意:
```
. /home/HwHiAiUser/Ascend/ascend-toolkit/set_env.sh
export ASCEND_OPP_PATH=~/.local/Ascend/opp
export CUSTOM_OP_LIB_PATH=~/.local/Ascend/opp/framework/custom/tensorflow
```
2. 检查yaml文件中对应算子的分发配置,是否正确的完整分发;
3. 分析排查代码实现,建议手段:
1. 修改"pytorch"中的算子适配实现,让“test\_add.py”可以调用到“自定义算子包”中的TBE算子;
1. 修改"pytorch"中的算子适配实现,让"add\_testcase.py"可以调用到“自定义算子包”中的TBE算子;
"pytorch/aten/src/ATen/native/npu/AddKernelNpu.cpp"
![](figures/zh-cn_image_0000001144082088.png)
![](figures/zh-cn_image_0000001126846510.png)
2. 完成上两步的编译、安装,调用“python3.7 test\_add.py”进行测试。
2. 修改"cann"中的"add"算子实现\(建议此时不要包含新开发的“自定义TBE算子”,方便对比\),在算子入口增加日志打印,作为运行标识;
"cann/ops/contrib/ops/custom/tbe/impl/add.py"
3. 完成上两步的编译、安装,调用"python3.7.5 add\_testcase.py"进行测试;
```
cd 至"test_add.py" 所在路径,调用
test_add.py
cd 至"add_testcase.py" 所在路径,调用
add_testcase.py
进行测试
```
至此步骤,不应该有错误,屏幕应该输出 "add" 中增加的日志打印。若出错,请完成代码清理排查,保证无新开发的代码影响测试。
3. 将新开发的“自定义TBE算子”合并到"cann"中,在对应的在算子入口增加日志打印,作为运行标识。
4. 完成上面的"cann"编译、安装,调用“python3.7.5 test\_add.py”进行测试。
4. 将新开发的“自定义TBE算子”合并到"cann"中,在对应的在算子入口增加日志打印,作为运行标识;
5. 完成上面的"cann"编译、安装,调用"python3.7.5 add\_testcase.py"进行测试;
>![](public_sys-resources/icon-note.gif) **说明:**
>根据Ascend的设计逻辑,用户开发安装的“custom”算子包优先级高于“built-in”的内置算子包,在运行加载时,会优先加载调度“custom”包中的算子。过程中,若解析“custom”中的算子信息文件失败,则会跳过“custom”算子包,不加载调度任何“custom”算子包中的任何算子。
>- 若此步骤出错,或屏幕未输出 "add" 中增加的日志打印,则说明新开发的“自定义TBE算子”有错误,影响了“自定义算子包”的加载,建议**优先排查新开发的“自定义TBE算子”中的“算子信息定义”是否正确**。
>- 若此步骤正确,至少说明 **新开发的“自定义TBE算子”中的“算子信息定义”不影响运行**。
>1、背景知识:根据Ascend的设计逻辑,用户开发安装的“custom”算子包优先级高于“built-in”的内置算子包,在运行加载时,会优先加载调度“custom”包中的算子。过程中,若解析“custom”中的算子信息文件失败,则会跳过“custom”算子包,不加载调度任何“custom”算子包中的任何算子。
>2、若此步骤出错,或屏幕未输出 "add" 中增加的日志打印,则说明新开发的“自定义TBE算子”有错误,影响了“自定义算子包”的加载,建议**优先排查新开发的“自定义TBE算子”中的“算子信息定义”是否正确**。
>3、若此步骤正确,至少说明 **新开发的“自定义TBE算子”中的“算子信息定义”不影响运行**。
5. 调用“python3.7.5 xxx\_testcase.py”进行测试;
6. 调用"python3.7.5 xxx\_testcase.py"进行测试;
>![](public_sys-resources/icon-note.gif) **说明:**
>- 若屏幕正常输出新开发的“自定义TBE算子”中增加的日志打印,则至少说明调度到了新开发的算子。
>- 若屏幕未输出新开发的“自定义TBE算子”中增加的日志打印,则问题可能出现在“PyTorch适配”中,需要排查这一部分的实现代码,较多的可能会出现在“XxxxKernelNpu.cpp”中的输入、输出未能正确适配。
>1、若屏幕正常输出新开发的“自定义TBE算子”中增加的日志打印,则至少说明调度到了新开发的算子。
>2、若屏幕未输出新开发的“自定义TBE算子”中增加的日志打印,则问题可能出现在"PyTorch适配"中,需要排查这一部分的实现代码,较多的可能会出现在“XxxxKernelNpu.cpp”中的输入、输出未能正确适配。
<h2 id="如何确定-TBE算子-是否被-PyTorch适配-正确调用.md">如何确定“TBE算子”是否被“PyTorch适配”正确调用</h2>
### 如何确定“TBE算子”是否被“PyTorch适配”正确调用?<a name="如何确定TBE算子是否被PyTorch适配正确调用?.md"></a>
不管是“custom”算子,还是“built-in”算子,在安装后,都是以\*.py源码的方式存放在安装目录下,所以我们可以通过编辑源码,在API入口增加日志的方式,打印输出入参,确定输入的参数是否正确。
@@ -830,7 +790,7 @@ pip3.7 install torchvision --no-deps
下面以"built-in"算子中的"zn\_2\_nchw"算子为例:
1. 打开安装在用户目录下的算子包安装目录。
1. 打开安装在用户目录下的算子包安装目录
```
cd ~/.local/Ascend/opp/op_impl/built-in/ai_core/tbe/impl
@@ -839,7 +799,7 @@ pip3.7 install torchvision --no-deps
可以看到相应的算子\*.py源码文件均为“只读”,即此时不可编辑。
![](figures/zh-cn_image_0000001190081791.png)
![](figures/zh-cn_image_0000001127006336.png)
2. 修改算子\*.py源码文件属性,增加“可写”权限。
@@ -848,7 +808,7 @@ pip3.7 install torchvision --no-deps
ll
```
![](figures/zh-cn_image_0000001190081803.png)
![](figures/zh-cn_image_0000001172886191.png)
3. 打开算子\*.py源码文件,增加日志,保存退出。
@@ -856,7 +816,7 @@ pip3.7 install torchvision --no-deps
vi zn_2_nchw.py
```
![](figures/zh-cn_image_0000001190201951.png)
![](figures/zh-cn_image_0000001173046109.png)
上面例子只加了个标识,实际调测时,可以增加打印输入参数信息。
@@ -868,63 +828,62 @@ pip3.7 install torchvision --no-deps
sudo chmod -w zn_2_nchw.py
```
![](figures/zh-cn_image_0000001144082072.png)
![](figures/zh-cn_image_0000001126846512.png)
### PyTorch编译失败,提示“error: ld returned 1 exit status”<a name="PyTorch编译失败,提示error: ld returned 1 exit status.md"></a>
<h2 id="PyTorch编译失败-提示-error-ld-returned-1-exit-status.md">PyTorch编译失败,提示“error: ld returned 1 exit status”</h2>
## 现象描述<a name="zh-cn_topic_0000001125315885_zh-cn_topic_0175549220_section197270431505"></a>
**现象描述**
PyTorch编译失败,提示“ error: ld returned 1 exit status”。
![](figures/zh-cn_image_0000001190201973.png)
![](figures/zh-cn_image_0000001127006338.png)
## 可能原因<a name="zh-cn_topic_0000001125315885_zh-cn_topic_0175549220_section169499490501"></a>
**可能原因**
通过日志分析,大概原因为XxxxKernelNpu.cpp中实现的适配函数,与PyTorch框架算子要求的分发实现接口参数不匹配。在上面的例子中,是“binary\_cross\_entropy\_npu”,打开对应的XxxxKernelNpu.cpp文件,找到相应的适配函数。
![](figures/zh-cn_image_0000001144241896.png)
![](figures/zh-cn_image_0000001172886193.png)
可以看出实现中,最后一个参数是"int" ,与要求的“long”不匹配。
## 处理方法<a name="zh-cn_topic_0000001125315885_section108142031907"></a>
**处理方法**
修改XxxxKernelNpu.cpp中实现的适配函数,在上面的例子中,修改“binary\_cross\_entropy\_npu”方法最后一个参数类型为“int64\_t”\(cpp中“long”的类型使用"int64\_t"\)。
<h2 id="PyTorch编译失败-提示-error-call-of-overload.md">PyTorch编译失败,提示“error: call of overload ....”</h2>
### PyTorch编译失败,提示“error: call of overload ....”<a name="PyTorch编译失败,提示error: call of overload.md"></a>
## 现象描述<a name="zh-cn_topic_0000001125641113_zh-cn_topic_0175549220_section197270431505"></a>
**现象描述**
PyTorch编译失败,提示“error: call of overload ....”。
PyTorch编译失败,提示“error: call of overload ....”
![](figures/zh-cn_image_0000001144082056.png)
![](figures/zh-cn_image_0000001173046111.png)
![](figures/zh-cn_image_0000001190201935.png)
![](figures/zh-cn_image_0000001126846514.png)
## 可能原因<a name="zh-cn_topic_0000001125641113_zh-cn_topic_0175549220_section169499490501"></a>
**可能原因**
通过日志分析,错误出在XxxxKernelNpu.cpp中30行位置,NPUAttrDesc的参数不合法。在上面的例子中,是“binary\_cross\_entropy\_attr”,打开对应的XxxxKernelNpu.cpp文件,找到相应的适配函数。
![](figures/zh-cn_image_0000001144082064.png)
![](figures/zh-cn_image_0000001127006340.png)
可以看出实现中,NPUAttrDesc的入参,第二个参数是"int" ,与NPUAttrDesc定义不匹配。
## 处理方法<a name="zh-cn_topic_0000001125641113_section108142031907"></a>
**处理方法**
1、将binary\_cross\_entropy\_attr\(\)中错误的行代码替换为上面的注释中的代码
1. 将binary\_cross\_entropy\_attr\(\)中错误的行代码替换为上面的注释中的代码。
2、binary\_cross\_entropy\_attr\(\)入参类型修改为 int64\_t。
<h2 id="附录.md">附录</h2>
- **[CMake安装方法](#CMake安装方法.md)**
- **[自定义算子导出方法](#自定义算子导出方法.md)**
2. binary\_cross\_entropy\_attr\(\)入参类型修改为 int64\_t。
<h2 id="CMake安装方法.md">CMake安装方法</h2>
## 附录<a name="附录.md"></a>
以CMake版本升级为3.12.1为例说明。
- **[CMake安装方法](#CMake安装方法.md)**
- **[自定义算子导出方法](#自定义算子导出方法.md)**
### CMake安装方法<a name="CMake安装方法.md"></a>
CMake版本升级为3.12.1的方法
1. 获取Cmake软件包。
@@ -958,24 +917,23 @@ PyTorch编译失败,提示“error: call of overload ....”。
cmake --version
```
显示“cmake version 3.12.1”则表示安装成功。
如显示“cmake version 3.12.1”则表示安装成功。
### 自定义算子导出方法<a name="自定义算子导出方法.md"></a>
<h2 id="自定义算子导出方法.md">自定义算子导出方法</h2>
## 简介<a name="zh-cn_topic_0000001136292799_section13121145561615"></a>
#### 简介
PyTorch训练模型中包含自定义算子,将自定义算子导出成onnx单算子模型,方便转移到其他AI框架中使用。自定义算子导出有三种形式,适配NPU的TBE算子导出、C++算子导出、纯Python算子导出。
## 前提条件<a name="zh-cn_topic_0000001136292799_section6744175713010"></a>
#### 前提条件
安装PyTorch框架。
## TBE算子导出<a name="zh-cn_topic_0000001136292799_section17568113818325"></a>
#### TBE算子导出
TBE算子导出有两种方式。
方式一:
第一种方式。
1. 定义和注册算子
@@ -1042,7 +1000,7 @@ TBE算子导出有两种方式。
```
方式二:
第二种方式。
1. 定义方法类
@@ -1126,7 +1084,7 @@ TBE算子导出有两种方式。
>![](public_sys-resources/icon-note.gif) **说明:**
>详细实现代码请参见[test\_custom\_ops\_npu\_demo.py](https://gitee.com/ascend/pytorch/blob/master/test/test_npu/test_onnx/torch.onnx/custom_ops_demo/test_custom_ops_npu_demo.py),如无权限获取代码,请联系华为技术支持申请加入“Ascend”组织。
## C++算子导出<a name="zh-cn_topic_0000001136292799_section1465619203319"></a>
#### C++算子导出
1. 自定义算子
@@ -1192,7 +1150,7 @@ TBE算子导出有两种方式。
>![](public_sys-resources/icon-note.gif) **说明:**
>详细实现代码请参见[test\_custom\_ops\_demo.py](https://gitee.com/ascend/pytorch/blob/master/test/test_npu/test_onnx/torch.onnx/custom_ops_demo/test_custom_ops_demo.py),如无权限获取代码,请联系华为技术支持申请加入“Ascend”组织。
## 纯Python算子导出<a name="zh-cn_topic_0000001136292799_section98044317326"></a>
#### 纯Python算子导出
1. 自定义算子

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 43 KiB

Before

Width:  |  Height:  |  Size: 7.6 KiB

After

Width:  |  Height:  |  Size: 7.6 KiB

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Before

Width:  |  Height:  |  Size: 78 KiB

After

Width:  |  Height:  |  Size: 78 KiB

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

@@ -37,8 +37,6 @@
- [调测过程](#调测过程-4.md)
- [总体思路](#总体思路-5.md)
- [精度调优方法](#精度调优方法.md)
- [单算子溢出检测](#单算子溢出检测.md)
- [整网调测](#整网调测.md)
- [模型保存与转换](#模型保存与转换.md)
- [简介](#简介.md)
- [模型保存](#模型保存.md)
@@ -61,7 +59,6 @@
- [常用环境变量说明](#常用环境变量说明.md)
- [dump op方法](#dump-op方法.md)
- [安装7.3.0版本gcc](#安装7-3-0版本gcc.md)
- [编译安装hdf5](#编译安装hdf5.md)
- [FAQ](#FAQ.md)
- [软件安装常见问题](#软件安装常见问题.md)
- [pip3.7 install Pillow==5.3.0安装失败](#pip3-7-install-Pillow-5-3-0安装失败.md)
@@ -73,7 +70,7 @@
- [在模型运行时遇到报错“RuntimeError: Initialize.”](#在模型运行时遇到报错-RuntimeError-Initialize.md)
- [在模型运行时遇到报错“TVM/te/cce error.”](#在模型运行时遇到报错-TVM-te-cce-error.md)
- [在模型运行时遇到报错“MemCopySync:drvMemcpy failed.”](#在模型运行时遇到报错-MemCopySync-drvMemcpy-failed.md)
- [在模型运行时遇到报错“MemCopySync:drvMemcpy failed.”](#在模型运行时遇到报错-MemCopySync-drvMemcpy-failed-7.md)
- [在模型运行时遇到报错“MemCopySync:drvMemcpy failed.”1](#在模型运行时遇到报错-MemCopySync-drvMemcpy-failed-1.md)
- [在模型运行时将多任务下发关闭\(export TASK\_QUEUE\_ENABLE=0\)后仍然遇到报错“HelpACLExecute.”](#在模型运行时将多任务下发关闭&#40;export-TASK_QUEUE_ENABLE-0&#41;后仍然遇到报错-HelpACLExecute.md)
- [在模型运行时遇到报错“55056 GetInputConstDataOut: ErrorNo: -1\(failed\)”](#在模型运行时遇到报错-55056-GetInputConstDataOut-ErrorNo--1&#40;failed&#41;.md)
- [模型调测常见问题](#模型调测常见问题.md)
@@ -155,7 +152,7 @@
</tr>
<tr id="row9883113014287"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p8883203017280"><a name="p8883203017280"></a><a name="p8883203017280"></a>算子开发</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p158831830192814"><a name="p158831830192814"></a><a name="p158831830192814"></a>详情请参见<span id="ph144957513112"><a name="ph144957513112"></a><a name="ph144957513112"></a><span id="ph45906272222"><a name="ph45906272222"></a><a name="ph45906272222"></a>《PyTorch算子开发指南》</span></span>。</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p158831830192814"><a name="p158831830192814"></a><a name="p158831830192814"></a>详情请参见<span id="ph144957513112"><a name="ph144957513112"></a><a name="ph144957513112"></a><span id="ph07771712101117"><a name="ph07771712101117"></a><a name="ph07771712101117"></a>《PyTorch算子开发指南》</span></span>。</p>
</td>
</tr>
<tr id="row2056653212812"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p1656743213814"><a name="p1656743213814"></a><a name="p1656743213814"></a>环境准备</p>
@@ -175,7 +172,7 @@
</tr>
<tr id="row1658912015291"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p195901920192910"><a name="p195901920192910"></a><a name="p195901920192910"></a>错误分析</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p95904208295"><a name="p95904208295"></a><a name="p95904208295"></a>详情请参见<span id="ph7924185091616"><a name="ph7924185091616"></a><a name="ph7924185091616"></a>《CANN 日志参考》</span>和<span id="ph1572317171516"><a name="ph1572317171516"></a><a name="ph1572317171516"></a>《CANN 开发辅助工具指南》</span>中“AI Core Error分析工具使用指南”章节。</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p95904208295"><a name="p95904208295"></a><a name="p95904208295"></a>详情请参见<span id="ph92061657112415"><a name="ph92061657112415"></a><a name="ph92061657112415"></a>《CANN 日志参考》</span>和<span id="ph4109111816191"><a name="ph4109111816191"></a><a name="ph4109111816191"></a>《CANN 开发辅助工具指南》</span>中“AI Core Error分析工具使用指南”章节。</p>
</td>
</tr>
<tr id="row13191151664310"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p219216162433"><a name="p219216162433"></a><a name="p219216162433"></a>性能调优和分析</p>
@@ -190,12 +187,12 @@
</tr>
<tr id="row7630202112430"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p1263012210438"><a name="p1263012210438"></a><a name="p1263012210438"></a>模型保存与转换</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p12631521104319"><a name="p12631521104319"></a><a name="p12631521104319"></a>详情请参见<a href="#模型保存与转换.md">模型保存与转换</a>和<span id="ph98735134233"><a name="ph98735134233"></a><a name="ph98735134233"></a>《CANN 开发辅助工具指南》</span>中“ATC工具使用指南”章节。</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p12631521104319"><a name="p12631521104319"></a><a name="p12631521104319"></a>详情请参见<a href="#模型保存与转换.md">模型保存与转换</a>和<span id="ph1834334902411"><a name="ph1834334902411"></a><a name="ph1834334902411"></a><span id="ph13354922101910"><a name="ph13354922101910"></a><a name="ph13354922101910"></a>《CANN 开发辅助工具指南》</span></span>中“ATC工具使用指南”章节。</p>
</td>
</tr>
<tr id="row196272410438"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p176218241431"><a name="p176218241431"></a><a name="p176218241431"></a>应用软件开发</p>
</td>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p1962142434317"><a name="p1962142434317"></a><a name="p1962142434317"></a>详情请参见<span id="ph1062525151815"><a name="ph1062525151815"></a><a name="ph1062525151815"></a>《CANN 应用软件开发指南(C&amp;C++, 推理)》</span>。</p>
<td class="cellrowborder" valign="top" width="71.82%" headers="mcps1.2.3.1.2 "><p id="p1962142434317"><a name="p1962142434317"></a><a name="p1962142434317"></a>详情请参见<span id="ph10403111142311"><a name="ph10403111142311"></a><a name="ph10403111142311"></a><span id="ph16725185971512"><a name="ph16725185971512"></a><a name="ph16725185971512"></a>《CANN 应用软件开发指南(C&amp;C++, 推理)》</span></span>。</p>
</td>
</tr>
<tr id="row17586759102515"><td class="cellrowborder" valign="top" width="28.18%" headers="mcps1.2.3.1.1 "><p id="p6586155952510"><a name="p6586155952510"></a><a name="p6586155952510"></a>FAQ</p>
@@ -228,7 +225,7 @@
<h2 id="配置环境变量.md">配置环境变量</h2>
安装完软件包后,需要配置环境变量才能正常使用昇腾PyTorch。建议构建启动脚本,例如构建set\_env.sh脚本,使用source set\_env.sh配置当前窗口的环境变量。set\_env.sh脚本内容如下(以root用户安装,安装路径为默认路径,python版本为3.7.5为例,用户可根据软件包实际安装路径修改配置项。)。
安装完软件包后,需要配置环境变量才能正常使用昇腾PyTorch。建议构建启动脚本,例如构建set\_env.sh脚本,使用source set\_env.sh配置当前窗口的环境变量。set\_env.sh脚本内容如下(以root用户安装,安装路径为默认路径为例)。
```
cpu_type=$(echo $HOSTTYPE)
@@ -294,18 +291,18 @@ export HCCL_IF_IP="1.1.1.1" # “1.1.1.1”为示例使用的host网卡IP,请
</thead>
<tbody><tr id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_row6882121917329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p688241953218"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p688241953218"></a><a name="zh-cn_topic_0000001134654416_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_0000001134654416_zh-cn_topic_0000001152616261_p1888291915322"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p1888291915322"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p1888291915322"></a>动态库的查找路径,参考上述举例配置。</p>
<p id="zh-cn_topic_0000001134654416_p1292181892120"><a name="zh-cn_topic_0000001134654416_p1292181892120"></a><a name="zh-cn_topic_0000001134654416_p1292181892120"></a>若训练所在系统环境需要升级gcc(例如CentOS、Debian和BClinux系统),则<span class="parmname" id="zh-cn_topic_0000001134654416_parmname795020446318"><a name="zh-cn_topic_0000001134654416_parmname795020446318"></a><a name="zh-cn_topic_0000001134654416_parmname795020446318"></a>“LD_LIBRARY_PATH”</span>配置项处动态库查找路径需要添加<span class="filepath" id="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath115819811512"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath115819811512"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath115819811512"></a>“${install_path}/lib64”</span>,其中<span class="filepath" id="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath195951574421"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath195951574421"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath195951574421"></a>“{install_path}”</span>为gcc升级安装路径。请参见<a href="#安装7-3-0版本gcc.md#zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li9745165315131">5</a>。</p>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p1888291915322"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p1888291915322"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p1888291915322"></a><span>动态库的查找路径,</span>参考上述举例配置。</p>
<p id="zh-cn_topic_0000001134654416_p1292181892120"><a name="zh-cn_topic_0000001134654416_p1292181892120"></a><a name="zh-cn_topic_0000001134654416_p1292181892120"></a>若训练所在系统环境需要升级gcc(例如CentOS、Debian和BClinux系统),则<span class="parmname" id="zh-cn_topic_0000001134654416_parmname795020446318"><a name="zh-cn_topic_0000001134654416_parmname795020446318"></a><a name="zh-cn_topic_0000001134654416_parmname795020446318"></a>“LD_LIBRARY_PATH”</span>配置项处动态库查找路径需要添加<span class="filepath" id="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath115819811512"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath115819811512"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath115819811512"></a>“${install_path}/lib64”</span>,其中<span class="filepath" id="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath195951574421"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath195951574421"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0256062644_filepath195951574421"></a>“{install_path}”</span>为gcc升级安装路径。请参见<a href="#zh-cn_topic_0000001181522175.md#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_0000001134654416_zh-cn_topic_0000001152616261_row16194175523010"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p16195185523019"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p16195185523019"></a><a name="zh-cn_topic_0000001134654416_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_0000001134654416_zh-cn_topic_0000001152616261_p19637083322"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p19637083322"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p19637083322"></a>Python搜索路径,参考上述举例配置。</p>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p19637083322"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p19637083322"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p19637083322"></a><span>Python搜索路径,</span>参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_row2954102119329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p195452113218"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p195452113218"></a><a name="zh-cn_topic_0000001134654416_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_0000001134654416_zh-cn_topic_0000001152616261_p964914893211"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p964914893211"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p964914893211"></a>可执行程序的查找路径,参考上述举例配置。</p>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p964914893211"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p964914893211"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p964914893211"></a><span>可执行程序的查找路径,</span>参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_row58592816294"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p1886016892913"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p1886016892913"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p1886016892913"></a>ASCEND_OPP_PATH</p>
@@ -331,7 +328,7 @@ export HCCL_IF_IP="1.1.1.1" # “1.1.1.1”为示例使用的host网卡IP,请
<tr id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_row1680820246202"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p4809112415207"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p4809112415207"></a><a name="zh-cn_topic_0000001134654416_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_0000001134654416_zh-cn_topic_0000001152616261_p952814428206"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p952814428206"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p952814428206"></a>配置在使用HCCL时是否开启通信白名单。</p>
<a name="zh-cn_topic_0000001134654416_ul928845132310"></a><a name="zh-cn_topic_0000001134654416_ul928845132310"></a><ul id="zh-cn_topic_0000001134654416_ul928845132310"><li>0:开启白名单</li><li>1:关闭白名单</li></ul>
<a name="zh-cn_topic_0000001134654416_ul928845132310"></a><a name="zh-cn_topic_0000001134654416_ul928845132310"></a><ul id="zh-cn_topic_0000001134654416_ul928845132310"><li>0:开启白名单,无需校验HCCL通信白名单。</li><li>1:关闭白名单,需校验HCCL通信白名单。</li></ul>
<p id="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p5809162416201"><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p5809162416201"></a><a name="zh-cn_topic_0000001134654416_zh-cn_topic_0000001152616261_p5809162416201"></a>缺省值为0,默认开启白名单。</p>
</td>
</tr>
@@ -718,30 +715,6 @@ Ascend平台提供了脚本转换工具使用户能通过命令行方式将训
<td class="cellrowborder" valign="top" width="22.900000000000002%" headers="mcps1.2.4.1.3 "><p id="zh-cn_topic_0000001086713630_p6273113412368"><a name="zh-cn_topic_0000001086713630_p6273113412368"></a><a name="zh-cn_topic_0000001086713630_p6273113412368"></a>/home/username/fmktransplt_rule.json</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001086713630_row1355087145112"><td class="cellrowborder" valign="top" width="22.35%" headers="mcps1.2.4.1.1 "><p id="zh-cn_topic_0000001086713630_p1801752706"><a name="zh-cn_topic_0000001086713630_p1801752706"></a><a name="zh-cn_topic_0000001086713630_p1801752706"></a>-s</p>
<p id="zh-cn_topic_0000001086713630_p011914159516"><a name="zh-cn_topic_0000001086713630_p011914159516"></a><a name="zh-cn_topic_0000001086713630_p011914159516"></a>--specify-device</p>
</td>
<td class="cellrowborder" valign="top" width="54.75%" headers="mcps1.2.4.1.2 "><a name="zh-cn_topic_0000001086713630_ul186822151820"></a><a name="zh-cn_topic_0000001086713630_ul186822151820"></a><ul id="zh-cn_topic_0000001086713630_ul186822151820"><li>可以通过环境变量设置指定device作为高级特性,但有可能导致原本脚本中分布式功能失效。</li><li>可选。</li></ul>
</td>
<td class="cellrowborder" valign="top" width="22.900000000000002%" headers="mcps1.2.4.1.3 "><p id="zh-cn_topic_0000001086713630_p185502785114"><a name="zh-cn_topic_0000001086713630_p185502785114"></a><a name="zh-cn_topic_0000001086713630_p185502785114"></a>-</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001086713630_row1914883514326"><td class="cellrowborder" valign="top" width="22.35%" headers="mcps1.2.4.1.1 "><p id="zh-cn_topic_0000001086713630_p51490353324"><a name="zh-cn_topic_0000001086713630_p51490353324"></a><a name="zh-cn_topic_0000001086713630_p51490353324"></a>-sim</p>
<p id="zh-cn_topic_0000001086713630_p5549113123714"><a name="zh-cn_topic_0000001086713630_p5549113123714"></a><a name="zh-cn_topic_0000001086713630_p5549113123714"></a>--similar</p>
</td>
<td class="cellrowborder" valign="top" width="54.75%" headers="mcps1.2.4.1.2 "><a name="zh-cn_topic_0000001086713630_ul856518554400"></a><a name="zh-cn_topic_0000001086713630_ul856518554400"></a><ul id="zh-cn_topic_0000001086713630_ul856518554400"><li>用功能相似的API替换某些不支持的API,但有可能导致准确性和性能下降。</li><li>可选。</li></ul>
</td>
<td class="cellrowborder" valign="top" width="22.900000000000002%" headers="mcps1.2.4.1.3 "><p id="zh-cn_topic_0000001086713630_p13149193573212"><a name="zh-cn_topic_0000001086713630_p13149193573212"></a><a name="zh-cn_topic_0000001086713630_p13149193573212"></a>-</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001086713630_row311811519515"><td class="cellrowborder" valign="top" width="22.35%" headers="mcps1.2.4.1.1 "><p id="zh-cn_topic_0000001086713630_p1755018717511"><a name="zh-cn_topic_0000001086713630_p1755018717511"></a><a name="zh-cn_topic_0000001086713630_p1755018717511"></a>distributed</p>
</td>
<td class="cellrowborder" valign="top" width="54.75%" headers="mcps1.2.4.1.2 "><p id="zh-cn_topic_0000001086713630_p27033264208"><a name="zh-cn_topic_0000001086713630_p27033264208"></a><a name="zh-cn_topic_0000001086713630_p27033264208"></a>将GPU单卡脚本转换为NPU多卡脚本,仅支持使用torch.utils.data.DataLoader方式加载数据的场景,指定此参数时,才可以指定以下两个参数。</p>
<a name="zh-cn_topic_0000001086713630_ul94321522131015"></a><a name="zh-cn_topic_0000001086713630_ul94321522131015"></a><ul id="zh-cn_topic_0000001086713630_ul94321522131015"><li>-m,--main:训练脚本的入口python文件,必选。</li><li>-t,--target model:目标模型变量名,默认为'model',可选。</li></ul>
</td>
<td class="cellrowborder" valign="top" width="22.900000000000002%" headers="mcps1.2.4.1.3 "><p id="zh-cn_topic_0000001086713630_p011961519515"><a name="zh-cn_topic_0000001086713630_p011961519515"></a><a name="zh-cn_topic_0000001086713630_p011961519515"></a>-</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001086713630_row1736213644115"><td class="cellrowborder" valign="top" width="22.35%" headers="mcps1.2.4.1.1 "><p id="zh-cn_topic_0000001086713630_p1036312363411"><a name="zh-cn_topic_0000001086713630_p1036312363411"></a><a name="zh-cn_topic_0000001086713630_p1036312363411"></a>-h</p>
<p id="zh-cn_topic_0000001086713630_p176714017418"><a name="zh-cn_topic_0000001086713630_p176714017418"></a><a name="zh-cn_topic_0000001086713630_p176714017418"></a>--help</p>
</td>
@@ -753,7 +726,6 @@ Ascend平台提供了脚本转换工具使用户能通过命令行方式将训
</tbody>
</table>
## 自定义规则文件<a name="zh-cn_topic_0000001086713630_section1879318256392"></a>
自定义转换规则样例如下:
@@ -841,8 +813,7 @@ Ascend平台提供了脚本转换工具使用户能通过命令行方式将训
</tr>
<tr id="zh-cn_topic_0000001086713630_row4677165715235"><td class="cellrowborder" valign="top" width="30%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001086713630_p2434071544"><a name="zh-cn_topic_0000001086713630_p2434071544"></a><a name="zh-cn_topic_0000001086713630_p2434071544"></a>parent_module</p>
</td>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001086713630_p571992311016"><a name="zh-cn_topic_0000001086713630_p571992311016"></a><a name="zh-cn_topic_0000001086713630_p571992311016"></a>父级模块全名</p>
<p id="zh-cn_topic_0000001086713630_p1065614314599"><a name="zh-cn_topic_0000001086713630_p1065614314599"></a><a name="zh-cn_topic_0000001086713630_p1065614314599"></a>例如torch.cuda.amp,amp的父级模块全名为torch.cuda。</p>
<td class="cellrowborder" valign="top" width="70%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001086713630_p443419713418"><a name="zh-cn_topic_0000001086713630_p443419713418"></a><a name="zh-cn_topic_0000001086713630_p443419713418"></a>父级模块名称</p>
</td>
</tr>
</tbody>
@@ -859,25 +830,20 @@ Ascend平台提供了脚本转换工具使用户能通过命令行方式将训
2. 执行脚本转换工具。
```
python3 ms_fmk_transplt.py -i 原始脚本路径 -o 脚本转换结果输出路径 [-r 自定义规则json文件路径] [-s] [-sim] [distributed -m 训练脚本的入口文件 -t 目标模型变量名]
python3 ms_fmk_transplt.py -i 原始脚本路径 -o 脚本转换结果输出路径 [-r 自定义规则json文件路径]
```
>![](public_sys-resources/icon-note.gif) **说明:**
>distributed及其参数-m、-t在语句最后指定。
3. 完成脚本转换。
<h2 id="结果解析.md">结果解析</h2>
脚本转换完成后,进入脚本转换结果输出路径查看结果文件,以GPU单卡脚本转换为NPU多卡脚本为例。
脚本转换完成后,进入脚本转换结果输出路径查看结果文件。
```
├── xxx_msft // 脚本转换结果输出目录,默认为原始脚本路径。xxx为原始脚本所在文件夹名称。
│ ├── 生成脚本文件 // 与转换前的脚本文件目录结构一致。
│ ├── msFmkTranspltlog.txt // 脚本转换过程日志文件。
│ ├── unsupported_op.xlsx // 不支持算子列表文件。
│ ├── change_list.csv // 修改记录文件。
│ ├── run_distributed_npu.sh // 多卡启动shell脚本。
```
<h2 id="手工迁移.md">手工迁移</h2>
@@ -1153,7 +1119,7 @@ def main():
基于NPU芯片的架构特性,会涉及到混合精度训练,即混合使用float16和float32数据类型的应用场景。使用float16代替float32有如下好处:
- 对于中间变量的内存占用更少,节省内存的使用。
- 因内存使用会减少,所以数据传出的时间也会相应减少。
- 因内存使用会减少,所以数据传出的时间也会减半。
- float16的计算单元可以提供更快的计算性能。
但是,混合精度训练受限于float16表达的精度范围,单纯将float32转换成float16会影响训练收敛情况,为了保证部分计算使用float16来进行加速的同时能保证训练收敛,这里采用混合精度模块Apex来达到以上效果。混合精度模块Apex是一个集优化性能、精度收敛于一身的综合优化库。
@@ -1178,12 +1144,12 @@ def main():
</thead>
<tbody><tr id="row1571763813334"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="p4502732153412"><a name="p4502732153412"></a><a name="p4502732153412"></a>O1配置模式</p>
</td>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="p640053920348"><a name="p640053920348"></a><a name="p640053920348"></a>Conv,Matmul等使用float16计算,其他如Softmax、BN使用float32。</p>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="p640053920348"><a name="p640053920348"></a><a name="p640053920348"></a>Conv,Matmal等使用<span>float16</span>计算,其他如Softmax、BN使用<span>float32</span>。</p>
</td>
</tr>
<tr id="row3717173817336"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="p11503103210344"><a name="p11503103210344"></a><a name="p11503103210344"></a>O2配置模式</p>
</td>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="p164001639143419"><a name="p164001639143419"></a><a name="p164001639143419"></a>除了BN使用float32外,其他绝大部分使用float16。</p>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="p164001639143419"><a name="p164001639143419"></a><a name="p164001639143419"></a>除了BN使用<span>float32</span>外,其他绝大部分使用<span>float16</span>。</p>
</td>
</tr>
<tr id="row14717193815334"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="p1950318328349"><a name="p1950318328349"></a><a name="p1950318328349"></a>静态Loss Scale功能</p>
@@ -1268,12 +1234,12 @@ def main():
**图 1** 远程登录控制台<a name="fig15869135420288"></a>
![](figures/远程登录控制台.png "远程登录控制台")
2. 在虚拟界面工具栏中,单击启动项工具![](figures/zh-cn_image_0000001144241932.png),弹出启动项配置界面,如[图2](#fig744814574243)。
2. 在虚拟界面工具栏中,单击启动项工具![](figures/zh-cn_image_0000001106016350.png),弹出启动项配置界面,如[图2](#fig744814574243)。
**图 2** 启动项工具<a name="fig744814574243"></a>
![](figures/启动项工具.png "启动项工具")
3. 在启动项配置界面选择,选择“BIOS设置”,然后在虚拟界面工具栏中单击重启工具![](figures/zh-cn_image_0000001190201999.png),重启服务器。
3. 在启动项配置界面选择,选择“BIOS设置”,然后在虚拟界面工具栏中单击重启工具![](figures/zh-cn_image_0000001152616281.png),重启服务器。
4. 系统重启后进入BIOS配置界面,依次选择“Advanced”\>“Socket Configuration”,如[图3](#fig4546303814)所示。
**图 3** Socket Configuration<a name="fig4546303814"></a>
@@ -1356,6 +1322,7 @@ def main():
systemctl start cpupower
```
3. 设置CPU为performance模式。
```
@@ -1375,12 +1342,12 @@ def main():
**图 1** 远程登录控制台<a name="fig15869135420288"></a>
![](figures/远程登录控制台-0.png "远程登录控制台-0")
2. 在虚拟界面工具栏中,单击启动项工具![](figures/zh-cn_image_0000001190202013.png),弹出启动项配置界面,如[图2](#fig744814574243)。
2. 在虚拟界面工具栏中,单击启动项工具![](figures/zh-cn_image_0000001152616289.png),弹出启动项配置界面,如[图2](#fig744814574243)。
**图 2** 启动项工具<a name="fig744814574243"></a>
![](figures/启动项工具-1.png "启动项工具-1")
3. 在启动项配置界面选择,选择“BIOS设置”,然后在虚拟界面工具栏中单击重启工具![](figures/zh-cn_image_0000001144082138.png),重启服务器。
3. 在启动项配置界面选择,选择“BIOS设置”,然后在虚拟界面工具栏中单击重启工具![](figures/zh-cn_image_0000001152736233.png),重启服务器。
4. 系统重启后进入BIOS配置界面,依次选择“Advanced”\>“ Performance Config”,如[图3](#fig4546303814)所示。
**图 3** Performance Config<a name="fig4546303814"></a>
@@ -1453,10 +1420,7 @@ def main():
<h2 id="模型训练.md">模型训练</h2>
训练脚本迁移完成后,需要参见[配置环境变量](#配置环境变量.md)设置环境变量,然后执行**python3** _xxx_进行模型训练。具体样例请参考[脚本执行](#脚本执行.md)。
>![](public_sys-resources/icon-note.gif) **说明:**
>执行“python3 xxx“命令时,须将python3软链接到与当前pytorch适配版本的python安装路径。
训练脚本迁移完成后,需要参见[配置环境变量](#配置环境变量.md)设置环境变量,然后执行**python3.7** _xxx_进行模型训练。具体样例请参考[脚本执行](#脚本执行.md)。
<h2 id="性能调优和分析.md">性能调优和分析</h2>
@@ -1497,51 +1461,23 @@ def main():
## Profiling数据采集<a name="section141471611314"></a>
当模型训练过程中吞吐量指标不达标时,可以通过采集训练过程中的profiling数据,分析哪个环节、哪个算子导致的性能消耗。Profiling数据采集分为PyTorch层面和CANN层面的采集,PyTorch层面采集的是PyTorch API的数据,CANN层面采集的是TBE算子的数据。
当吞吐量指标不达标时,需要通过采集训练过程中的profiling数据,分析哪个环节、哪个算子导致的性能消耗。请参见以下步骤进行profiling数据的获取。
请参见以下方式进行profiling数据的获取,并根据实际情况选择需要的数据采集方式。
- PyTorch层面Profiling数据采集。
1. 获取chrome\_trace文件。
使用profile接口对原始代码的loss计算和优化过程进行改造。
```
# 使用ascend-pytorch适配的profile接口,即可获得,推荐只运行一个step
with torch.autograd.profiler.profile(use_npu=True) as prof:
out = model(input_tensor)
loss=loss_func(out)
loss.backward()
optimizer.zero_grad()
optimizer.step()
# 导出chrome_trace文件到指定路径
output_path = '/home/HwHiAiUser/profile_data.json'
prof.export_chrome_trace(output_path)
```
2. 查看chrome\_trace文件。
chrome\_trace文件可以通过以下方式打开查看:在Chrome浏览器中输入“chrome://tracing“地址,然后将落盘文件拖到空白处即可打开文件内容,通过键盘W、A、S、D键,可以对profiler的结果进行缩放和移动。
- CANN层面Profiling数据采集。
1. 获取性能数据文件。
```
profiler_result_path = "/home/profiling_data" # profiling 数据保存的文件夹,需提前手动创建,请根据实际指定。
with torch.npu.profile(profiler_result_path) as prof:
out = model(input_tensor)
loss=loss_func(out)
loss.backward()
optimizer.zero_grad()
optimizer.step()
```
2. 解析性能数据文件。
请参见《CANN 开发辅助工具指南》中“Profiling工具使用指南(训练)”章节。
1. 获取chrome\_trace文件。使用profile接口对原始代码的loss计算和优化过程进行改造。
```
# 使用ascend-pytorch适配的profile接口,即可获得,推荐只运行一个step
with torch.autograd.profiler.profile(use_npu=True) as prof:
out = model(input_tensor)
loss=loss_func(out)
loss.backward()
optimizer.zero_grad()
optimizer.step()
# 导出chrome_trace文件到指定路径
prof.export_chrome_trace(output_path)
```
2. chrome\_trace文件可以通过以下方式打开查看:在Chrome浏览器中输入“chrome://tracing“地址,然后将落盘文件拖到空白处即可打开文件内容,通过键盘W、A、S、D键,可以对profiler的结果进行缩放和移动。
## 获取算子信息OP\_INFO<a name="section15654162853114"></a>
@@ -1605,7 +1541,7 @@ def main():
5. 解析host侧日志会在当前目录下得到OPInfo信息ascend\_op\_info\_summary.txt。
```
python3 get_ascend_op_info.py --host_log_folder $HOME/ascend/log/plog
python3.7 get_ascend_op_info.py --host_log_folder $HOME/ascend/log/plog
```
6. 分析TaskInfo中额外的task,尤其关注transdata。
@@ -1739,6 +1675,7 @@ def main():
- 解决方案:改进算子精度或功能问题。
2. <a name="li25281726103316"></a>loss计算错误。
- 定位思路:由于Loss的特殊性和可以自定义,在判断Loss计算错误后建议dump网络中的loss的输入来测试而非随机同shape tensor,这样才能更好地复现证明。
@@ -1746,6 +1683,7 @@ def main():
- 解决方案:改进算子精度或功能问题(loss也是由算子构成)。
3. 参数更新错误。
- 定位思路:在每个optim.step\(\)前对网络中的参数逐个打印其grad进行排查判断是哪个地方有较大嫌疑,然后构建单算子用例逐渐缩小错误范围,证明该算子在当前网络场景下梯度计算有误,可以对比CPU或GPU结果证明。该项优先级应低于[1.](#li17755175510322)与[2.](#li25281726103316),因为1与2的错误同样可以造成grad异常。
@@ -1754,6 +1692,7 @@ def main():
- 解决方案:改进计算grad的算子精度或功能问题。
4. 多卡计算错误。
- 定位思路:在保证单卡精度OK的前提下,稳定复现多卡不收敛。
@@ -1764,55 +1703,6 @@ def main():
<h2 id="精度调优方法.md">精度调优方法</h2>
模型出现精度问题一般有:因算子溢出导致的训练loss不收敛或者精度不达标问题,整个网络训练引起的性能不达标问题。用户可通过单算子溢出检测和整网调测适度解决模型精度不达标问题。
- **[单算子溢出检测](#单算子溢出检测.md)**
- **[整网调测](#整网调测.md)**
<h2 id="单算子溢出检测.md">单算子溢出检测</h2>
用户通过采集训练过程中各算子的运算结果(即Dump数据),然后查看算子是否产生溢出,从而帮助开发人员快速定位并解决算子精度问题。
## 约束说明<a name="section52762019181510"></a>
- 需要安装hdf5工具以支持算子dump功能,安装详情请参见[编译安装hdf5](#编译安装hdf5.md);
- 本功能只提供IR级别的算子溢出检测,且只支持AICORE的溢出检测,不支持Atomic溢出检测;
- 须在PyTorch源代码“build.sh“文件中添加“USE\_DUMP=1”字段。
```
修改前: DEBUG=0 USE_DISTRIBUTED=1 USE_HCCL=1 USE_MKLDNN=0 USE_CUDA=0 USE_NPU=1 BUILD_TEST=0 USE_NNPACK=0 python3 setup.py build bdist_wheel
修改后: DEBUG=0 USE_DISTRIBUTED=1 USE_HCCL=1 USE_MKLDNN=0 USE_CUDA=0 USE_NPU=1 BUILD_TEST=0 USE_NNPACK=0 USE_DUMP=1 python3 setup.py build
```
并参见《PyTorch安装指南》的“手动编译安装”章节重新编译并安装PyTorch。
- 使用单算子溢出检测功能时,请不要同时开启apex的动态loss scale模式和使用tensor融合功能。
## 采集算子Dump数据<a name="section121407268191"></a>
```
# check_overflow为溢出检测控制开关
# dump_path为dump文件保存路径
with torch.utils.dumper(check_overflow=check_overflow, dump_path=dump_path, load_file_path='') as dump:
# 需要算子采集的代码片段
```
模型运行过程中,如果有算子溢出,会打印出相应IR的名字。
## 查看Dump数据<a name="section155351957142017"></a>
如果训练过程中采集到了Dump数据,则会在\{dump\_path\}路径下生成dump数据的.h5文件,用户可进入路径自行查看。
## 解决方法<a name="section1729763162019"></a>
请将算子溢出的打印截图及采集到的.h5文件通过Issue附件形式反馈给华为开发人员。
<h2 id="整网调测.md">整网调测</h2>
用户也可通过分析整个网络的方式来进行网络模型的精度调测。
1. 通过对比CPU和昇腾AI处理器的结果,判断在昇腾AI处理器上计算是否正确。
代码样例(本样例只体现基本方法,禁止直接复制)如下:
@@ -1890,7 +1780,7 @@ with torch.utils.dumper(check_overflow=check_overflow, dump_path=dump_path, load
离线推理应用构建请参考《CANN 应用软件开发指南\(C&C++, 推理\)》。整体流程如下:
![](figures/zh-cn_image_0000001144082132.png)
![](figures/zh-cn_image_0000001106176222.png)
<h2 id="模型保存.md">模型保存</h2>
@@ -1923,6 +1813,7 @@ Pytorch在训练过程中,通常使用torch.save\(\)来保存Checkpoint文件
model.eval()
```
>![](public_sys-resources/icon-notice.gif) **须知:**
>保存.pth或.pt文件扩展名的文件时要提供模型定义文件,否则无法部署。
@@ -2170,10 +2061,10 @@ if __name__ == "__main__":
# if not torch.cuda.is_available():
# print('using CPU, this will be slow')
# elif args.distributed:
############## npu modify begin #############
############## npu modify begin #############
# 迁移后为直接判断是否进行分布式训练,去掉判断是否在GPU上进行训练
if args.distributed:
############## npu modify end #############
############## npu modify end #############
# For multiprocessing distributed, DistributedDataParallel constructor
# should always set the single device scope, otherwise,
# DistributedDataParallel will use all available devices.
@@ -2231,6 +2122,7 @@ if __name__ == "__main__":
############## npu modify end #############
```
- 代码位置:main.py文件中的validate\(\)函数(修改部分为字体加粗部分):
```
@@ -2250,6 +2142,7 @@ if __name__ == "__main__":
############## npu modify end #############
```
6. 设置当前正在使用的device。
代码位置:main.py文件中的主函数入口(修改部分为字体加粗部分):
@@ -2502,7 +2395,7 @@ if __name__ == "__main__":
if args.amp:
model, optimizer = amp.initialize(model, optimizer, opt_level=args.opt_level, loss_scale=args.loss_scale)
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], broadcast_buffers=False)
# optionally resume from a checkpoint
if args.resume:
@@ -2632,7 +2525,7 @@ if __name__ == "__main__":
单卡:
```
python3 main.py /home/data/resnet50/imagenet --batch-size 128 \ # 训练批次大小
python3.7 main.py /home/data/resnet50/imagenet --batch-size 128 \ # 训练批次大小
--lr 0.1 \ # 学习率
--epochs 90 \ # 训练迭代轮数
--arch resnet50 \ # 模型架构
@@ -2646,7 +2539,7 @@ python3 main.py /home/data/resnet50/imagenet --batch-size 128 \ # 训练
分布式:
```
python3 main.py /home/data/resnet50/imagenet --addr='1.1.1.1' \ # 示例IP地址,请根据实际修改
python3.7 main.py /home/data/resnet50/imagenet --addr='1.1.1.1' \ # 示例IP地址,请根据实际修改
--seed 49 \ # 随机种子
--workers 160 \ # 加载数据进程数
--lr 0.8 \
@@ -3219,8 +3112,6 @@ for group in [2, 4, 8]:
- **[安装7.3.0版本gcc](#安装7-3-0版本gcc.md)**
- **[编译安装hdf5](#编译安装hdf5.md)**
<h2 id="单算子样例编写说明.md">单算子样例编写说明</h2>
@@ -3412,7 +3303,7 @@ torch.npu.finalize_dump()
4. 调用Python,转换numpy文件为txt文件。举例:
**$ python3**
**$ python3.7.5**
**\>\>\> import numpy as np**
@@ -3540,43 +3431,6 @@ torch.npu.finalize_dump()
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
<h2 id="编译安装hdf5.md">编译安装hdf5</h2>
以下步骤请在root用户下执行。
1. 获取代码。
```
git clone https://github.com/HDFGroup/hdf5.git
```
2. 切换到hdf5-1\_10\_7分支。
```
cd hdf5
git checkout remotes/origin/hdf5_1_10_7
```
3. 编译hdf5。
```
./configure --prefix=/usr/local/hdf5 --enable-cxx
make -j72 #-j 后的数值可以根据CPU的核数设置
make check # run test suite.
make install
make check-install # verify installation.
```
4. 添加环境变量。
```
export PATH=/usr/local/hdf5/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/hdf5/lib:$LD_LIBRARY_PATH
export LIBRARY_PATH=/usr/local/hdf5/lib:$LIBRARY_PATH
export CPATH=/usr/local/hdf5/include:$CPATH
```
<h2 id="FAQ.md">FAQ</h2>
- **[软件安装常见问题](#软件安装常见问题.md)**
@@ -3634,7 +3488,7 @@ pip3.7 install pillow==5.3.0安装失败。
- **[在模型运行时遇到报错“MemCopySync:drvMemcpy failed.”](#在模型运行时遇到报错-MemCopySync-drvMemcpy-failed.md)**
- **[在模型运行时遇到报错“MemCopySync:drvMemcpy failed.”](#在模型运行时遇到报错-MemCopySync-drvMemcpy-failed-7.md)**
- **[在模型运行时遇到报错“MemCopySync:drvMemcpy failed.”1](#在模型运行时遇到报错-MemCopySync-drvMemcpy-failed-1.md)**
- **[在模型运行时将多任务下发关闭\(export TASK\_QUEUE\_ENABLE=0\)后仍然遇到报错“HelpACLExecute.”](#在模型运行时将多任务下发关闭(export-TASK_QUEUE_ENABLE-0)后仍然遇到报错-HelpACLExecute.md)**
@@ -3823,7 +3677,7 @@ shell报错是在同步操作中和AI CPU错误,而日志报错信息却是在
4. 打印stack所有参数的shape、dtype、npu\_format,通过构造单算子用例复现问题。定位到问题原因为减法计算输入参数数据类型不同,导致a-b和b-a结果的数据类型不一致,最终在stack算子中报错。
5. 将stack入参数据类型转换为一致即可临时规避问题。
<h2 id="在模型运行时遇到报错-MemCopySync-drvMemcpy-failed-7.md">在模型运行时遇到报错“MemCopySync:drvMemcpy failed.”</h2>
<h2 id="在模型运行时遇到报错-MemCopySync-drvMemcpy-failed-1.md">在模型运行时遇到报错“MemCopySync:drvMemcpy failed.”1</h2>
## 现象描述<a name="section1785905019184"></a>
@@ -4030,7 +3884,7 @@ pytorch算子在npu上运行,通过ACL接口调用底层经过优化的算子
## 现象描述<a name="section1785905019184"></a>
![](figures/model_faq11_20210728.jpg)
![](figures/FAQ12.png)
## 可能原因<a name="zh-cn_topic_0175549220_section169499490501"></a>
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

File diff suppressed because it is too large Load Diff
+139
View File
@@ -0,0 +1,139 @@
# PyTorch版本说明书
- [用户须知](#用户须知.md)
- [新增特性](#新增特性.md)
- [特性修改](#特性修改.md)
- [已修复问题](#已修复问题.md)
- [已知问题](#已知问题.md)
- [兼容性](#兼容性.md)
<h2 id="用户须知.md">用户须知</h2>
本框架基于Facebook主导的开源PyTorch1.5.0进行修改,延续原生的PyTorch特性,使用NPU进行动态图训练;以算子粒度进行模型适配,代码重用性好,支持现有的网络只修改设备类型或数据类型,即可迁移到NPU上使用。
<h2 id="新增特性.md">新增特性</h2>
**表 1** 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>一级特性</p>
</th>
<th class="cellrowborder" valign="top" width="26.3%" 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.21%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>说明</p>
</th>
</tr>
</thead>
<tbody><tr id="row171322953713"><td class="cellrowborder" rowspan="7" valign="top" width="10.489999999999998%" headers="mcps1.2.4.1.1 "><p id="p10237517181"><a name="p10237517181"></a><a name="p10237517181"></a>适配训练模型</p>
</td>
<td class="cellrowborder" valign="top" width="26.3%" headers="mcps1.2.4.1.2 "><p id="p6134294377"><a name="p6134294377"></a><a name="p6134294377"></a>YOLOV4</p>
</td>
<td class="cellrowborder" valign="top" width="63.21%" headers="mcps1.2.4.1.3 "><p id="p314533811397"><a name="p314533811397"></a><a name="p314533811397"></a>-</p>
</td>
</tr>
<tr id="row15990182233714"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p399019224374"><a name="p399019224374"></a><a name="p399019224374"></a>YOLOV3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1714553816396"><a name="p1714553816396"></a><a name="p1714553816396"></a>-</p>
</td>
</tr>
<tr id="row5301255373"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1530325123719"><a name="p1530325123719"></a><a name="p1530325123719"></a>DB</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p5146193819390"><a name="p5146193819390"></a><a name="p5146193819390"></a>-</p>
</td>
</tr>
<tr id="row274203413712"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p197423343379"><a name="p197423343379"></a><a name="p197423343379"></a>RFCN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p15828941153919"><a name="p15828941153919"></a><a name="p15828941153919"></a>-</p>
</td>
</tr>
<tr id="row78671918163714"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p188671318183713"><a name="p188671318183713"></a><a name="p188671318183713"></a>CRNN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p10828241123917"><a name="p10828241123917"></a><a name="p10828241123917"></a>-</p>
</td>
</tr>
<tr id="row16912221171"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p6913132676"><a name="p6913132676"></a><a name="p6913132676"></a>Densenset161</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p209131221474"><a name="p209131221474"></a><a name="p209131221474"></a>-</p>
</td>
</tr>
<tr id="row1016073314719"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p3160153320717"><a name="p3160153320717"></a><a name="p3160153320717"></a>Densenset191</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1516012331173"><a name="p1516012331173"></a><a name="p1516012331173"></a>-</p>
</td>
</tr>
<tr id="row9627165910386"><td class="cellrowborder" rowspan="4" valign="top" width="10.489999999999998%" headers="mcps1.2.4.1.1 "><p id="p1561535993811"><a name="p1561535993811"></a><a name="p1561535993811"></a>适配NPU的PyTorch特性</p>
</td>
<td class="cellrowborder" valign="top" width="26.3%" headers="mcps1.2.4.1.2 "><p id="p136151659163819"><a name="p136151659163819"></a><a name="p136151659163819"></a>框架基础功能</p>
</td>
<td class="cellrowborder" valign="top" width="63.21%" headers="mcps1.2.4.1.3 "><p id="p1661535983813"><a name="p1661535983813"></a><a name="p1661535983813"></a>新增适配算子开发(详见算子清单)。</p>
</td>
</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>精度对比工具</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p19616115953816"><a name="p19616115953816"></a><a name="p19616115953816"></a>新增精度对比工具,支持训练精度定界。</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>昇腾710芯片</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p186161459193813"><a name="p186161459193813"></a><a name="p186161459193813"></a>新增支持昇腾710芯片在线推理。</p>
</td>
</tr>
<tr id="row76261059153817"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p11616175953812"><a name="p11616175953812"></a><a name="p11616175953812"></a>OS兼容性</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p8935115971714"><a name="p8935115971714"></a><a name="p8935115971714"></a>新增支持ubuntu 18.04.5、OpenEuler 20.03 LTS系统</p>
</td>
</tr>
</tbody>
</table>
<h2 id="特性修改.md">特性修改</h2>
不涉及
<h2 id="已修复问题.md">已修复问题</h2>
不涉及
<h2 id="已知问题.md">已知问题</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>已知问题</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>
<h2 id="兼容性.md">兼容性</h2>
A800-9010:CentOS 7.6/Ubuntu 18.04/BC-Linux 7.6/Debian 9.9/Debian 10/OpenEuler 20.03 LTS
A800-9000:CentOS 7.6/Euler 2.8/Kylin v10/BC-Linux 7.6/OpenEuler 20.03 LTS

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 580 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 580 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 394 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 406 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 253 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 580 B

File diff suppressed because it is too large Load Diff
+1336 -903
View File
File diff suppressed because it is too large Load Diff
-48
View File
@@ -1,48 +0,0 @@
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
From https://gitee.com/ascend/pytorch
* branch master -> FETCH_HEAD
Already up to date.
+7
View File
@@ -25,6 +25,13 @@ function main()
# patch
cp $ROOT_DIR/patch/npu.patch $PT_DIR
cd $PT_DIR
dos2unix docs/make.bat
dos2unix scripts/appveyor/install.bat
dos2unix scripts/appveyor/install_cuda.bat
dos2unix scripts/build_windows.bat
dos2unix scripts/proto.ps1
dos2unix torch/distributions/von_mises.py
dos2unix torch/nn/modules/transformer.pyi.in
patch -p1 < npu.patch
cp -r $ROOT_DIR/src/* $PT_DIR
}
+13 -79
View File
@@ -980,8 +980,6 @@
NPU: conv_transpose2d_npu_
- func: conv_transpose3d.input(Tensor input, Tensor weight, Tensor? bias=None, int[3] stride=1, int[3] padding=0, int[3] output_padding=0, int groups=1, int[3] dilation=1) -> Tensor
npu_dispatch:
NPU: conv_transpose3d_npu_
- func: copy_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!)
manual_kernel_registration: True
@@ -1114,19 +1112,11 @@
- func: npu_conv_transpose2d(Tensor input, Tensor weight, Tensor? bias, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups) -> Tensor
npu_dispatch_only:
NPU: conv_transpose2d_npu
NPU: convolution_transpose_npu
- func: npu_convolution_transpose_backward(Tensor input, Tensor grad_output, Tensor weight, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
npu_dispatch_only:
NPU: npu_convolution_transpose_backward
- func: npu_conv_transpose2d_backward(Tensor input, Tensor grad_output, Tensor weight, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
npu_dispatch_only:
NPU: conv_transpose2d_backward_npu
- func: npu_conv_transpose3d_backward(Tensor input, Tensor grad_output, Tensor weight, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
npu_dispatch_only:
NPU: conv_transpose3d_backward_npu
NPU: convolution_transpose_backward_npu
- func: npu_convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor
npu_dispatch_only:
@@ -1136,10 +1126,6 @@
npu_dispatch_only:
NPU: npu_convolution_backward
- func: npu_convolution_double_backward(Tensor? ggI, Tensor? ggW, Tensor? ggb, Tensor input, Tensor gO, Tensor weight, int[] stride, int[] padding, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor)
npu_dispatch_only:
NPU: npu_convolution_double_backward
- func: npu_conv2d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor
npu_dispatch_only:
NPU: conv2d_npu
@@ -1193,30 +1179,34 @@
dispatch:
CPU: cummax_helper_cpu
CUDA: cummax_helper_cuda
npu_dispatch:
NPU: cummax_helper_npu
- func: cummin(Tensor self, int dim) -> (Tensor values, Tensor indices)
supports_named_tensor: True
variants: function, method
npu_dispatch:
NPU: cummin_npu
- func: cummin.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
supports_named_tensor: True
npu_dispatch:
NPU: cummin_out_npu
- func: cummin.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices)
supports_named_tensor: True
variants: function, method
npu_dispatch:
NPU: cummin_npu
- func: cummin.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices)
supports_named_tensor: True
npu_dispatch:
NPU: cummin_out_npu
- func: _cummin_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> ()
variants: function
dispatch:
CPU: cummin_helper_cpu
CUDA: cummin_helper_cuda
npu_dispatch:
NPU: cummin_helper_npu
- func: cumprod(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor
supports_named_tensor: True
@@ -1518,8 +1508,6 @@
use_c10_dispatcher: full
supports_named_tensor: True
variants: function, method
npu_dispatch:
NPU: erfc_npu
- func: erfc_(Tensor(a!) self) -> Tensor(a!)
supports_named_tensor: True
@@ -1527,16 +1515,12 @@
dispatch:
CPU: _erfc__cpu
CUDA: _erfc__cuda
npu_dispatch:
NPU: erfc_npu_
- func: erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)
supports_named_tensor: True
dispatch:
CPU: _erfc_out_cpu
CUDA: _erfc_out_cuda
npu_dispatch:
NPU: erfc_out_npu
- func: exp(Tensor self) -> Tensor
use_c10_dispatcher: full
@@ -5170,8 +5154,6 @@
dispatch:
CPU: __lshift__
CUDA: __lshift__
npu_dispatch:
NPU: __lshift___npu
- func: __lshift__.Tensor(Tensor self, Tensor other) -> Tensor
use_c10_dispatcher: full
@@ -5179,24 +5161,18 @@
dispatch:
CPU: __lshift__
CUDA: __lshift__
npu_dispatch:
NPU: __lshift___npu
- func: __ilshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
variants: method
dispatch:
CPU: __ilshift__
CUDA: __ilshift__
npu_dispatch:
NPU: __iLshift___npu
- func: __ilshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
variants: method
dispatch:
CPU: __ilshift__
CUDA: __ilshift__
npu_dispatch:
NPU: __iLshift___npu
- func: __rshift__.Scalar(Tensor self, Scalar other) -> Tensor
use_c10_dispatcher: full
@@ -5204,8 +5180,6 @@
dispatch:
CPU: __rshift__
CUDA: __rshift__
npu_dispatch:
NPU: __rshift___npu
- func: __rshift__.Tensor(Tensor self, Tensor other) -> Tensor
use_c10_dispatcher: full
@@ -5213,24 +5187,18 @@
dispatch:
CPU: __rshift__
CUDA: __rshift__
npu_dispatch:
NPU: __rshift___npu
- func: __irshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)
variants: method
dispatch:
CPU: __irshift__
CUDA: __irshift__
npu_dispatch:
NPU: __iRshift___npu
- func: __irshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)
variants: method
dispatch:
CPU: __irshift__
CUDA: __irshift__
npu_dispatch:
NPU: __iRshift___npu
- func: lgamma_(Tensor(a!) self) -> Tensor(a!)
supports_named_tensor: True
@@ -5474,15 +5442,11 @@
dispatch:
CPU: tril_indices_cpu
CUDA: tril_indices_cuda
npu_dispatch:
NPU: tril_indices_npu
- func: triu_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor
dispatch:
CPU: triu_indices_cpu
CUDA: triu_indices_cuda
npu_dispatch:
NPU: triu_indices_npu
- func: trace(Tensor self) -> Tensor
use_c10_dispatcher: full
@@ -5892,8 +5856,6 @@
dispatch:
CPU: _triangular_solve_helper_cpu
CUDA: _triangular_solve_helper_cuda
npu_dispatch:
NPU: _triangular_solve_helper_npu
- func: symeig.e(Tensor self, bool eigenvectors=False, bool upper=True, *, Tensor(a!) e, Tensor(b!) V) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
@@ -5905,8 +5867,6 @@
dispatch:
CPU: _symeig_helper_cpu
CUDA: _symeig_helper_cuda
npu_dispatch:
NPU: _symeig_helper_npu
- func: eig.e(Tensor self, bool eigenvectors=False, *, Tensor(a!) e, Tensor(b!) v) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors)
dispatch:
@@ -5929,8 +5889,6 @@
dispatch:
CPU: _svd_helper_cpu
CUDA: _svd_helper_cuda
npu_dispatch:
NPU: _svd_helper_npu
- func: cholesky.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!)
@@ -7160,30 +7118,22 @@
dispatch:
CPU: rrelu_with_noise_out_cpu
CUDA: legacy::cuda::_thnn_rrelu_with_noise_forward_out
npu_dispatch:
NPU: rrelu_with_noise_out_npu
- func: rrelu_with_noise(Tensor self, Tensor noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor
python_module: nn
dispatch:
CPU: rrelu_with_noise_cpu
CUDA: legacy::cuda::_thnn_rrelu_with_noise_forward
npu_dispatch:
NPU: rrelu_with_noise_npu
- func: rrelu_with_noise_backward(Tensor grad_output, Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, bool self_is_result) -> Tensor
use_c10_dispatcher: full
python_module: nn
npu_dispatch:
NPU: rrelu_with_noise_backward_npu
- func: rrelu_with_noise_(Tensor(a!) self, Tensor noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!)
python_module: nn
dispatch:
CPU: rrelu_with_noise_cpu_
CUDA: legacy::cuda::_thnn_rrelu_with_noise_forward_
npu_dispatch:
NPU: rrelu_with_noise_npu_
- func: softplus.out(Tensor self, Scalar beta=1, Scalar threshold=20, *, Tensor(a!) out) -> Tensor(a!)
python_module: nn
@@ -8140,27 +8090,19 @@
- func: slow_conv3d.out(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias=None, int[3] stride=1, int[3] padding=0, *, Tensor(a!) out) -> Tensor(a!)
python_module: nn
npu_dispatch:
NPU: slow_conv3d_out_npu
- func: slow_conv3d(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias=None, int[3] stride=1, int[3] padding=0) -> Tensor
python_module: nn
npu_dispatch:
NPU: slow_conv3d_npu
- func: slow_conv3d_forward.output(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias, int[3] stride, int[3] padding, *, Tensor(a!) output, Tensor(b!) finput, Tensor(c!) fgrad_input) -> (Tensor(a!), Tensor(b!), Tensor(c!))
python_module: nn
dispatch:
CPU: slow_conv3d_forward_out_cpu
npu_dispatch:
NPU: slow_conv3d_forward_out_npu
- func: slow_conv3d_forward(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias, int[3] stride, int[3] padding) -> (Tensor output, Tensor finput, Tensor fgrad_input)
python_module: nn
dispatch:
CPU: slow_conv3d_forward_cpu
npu_dispatch:
NPU: slow_conv3d_forward_npu
- func: slow_conv3d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, int[3] kernel_size, int[3] stride, int[3] padding, Tensor finput, Tensor fgrad_input, *, Tensor(a!)? grad_input, Tensor(b!)? grad_weight, Tensor(c!)? grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!))
python_module: nn
@@ -8472,12 +8414,12 @@
npu_dispatch_only:
NPU: dropout_backward_npu
- func: npu_indexing(Tensor self, int[] begin, int[] end, int[] strides, int begin_mask=0, int end_mask=0, int ellipsis_mask=0, int new_axis_mask=0, int shrink_axis_mask=0) -> Tensor
- func: npu_indexing(Tensor self, int[] begin, int[] end, int[] strides) -> Tensor
variants: function, method
npu_dispatch_only:
NPU: indexing_npu
- func: npu_indexing.out(Tensor self, int[] begin, int[] end, int[] strides, int begin_mask=0, int end_mask=0, int ellipsis_mask=0, int new_axis_mask=0, int shrink_axis_mask=0, *, Tensor(a!) out) -> Tensor(a!)
- func: npu_indexing.out(Tensor self, int[] begin, int[] end, int[] strides, *, Tensor(a!) out) -> Tensor(a!)
npu_dispatch_only:
NPU: indexing_out_npu
@@ -8606,12 +8548,4 @@
- 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_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
NPU: bert_apply_adam_npu
@@ -30,7 +30,7 @@ inline Tensor& any_out_npu_nocheck(
OpCommand cmd;
cmd.Name("ReduceAny")
.Input(self)
.Input(dimList)
.Input(dimList, at::kInt)
.Output(result)
.Attr("keep_dims", keepdim)
.Run();
@@ -32,10 +32,10 @@ Tensor argmin_npu(const Tensor& self, optional<int64_t> dim, bool keepdim) {
auto outputSize = reduce_ops_npu_output_size(input, realDim, realKeepDim);
// construct the output tensor of the NPU
Tensor result = OpPreparation::ApplyTensorWithFormat(
Tensor result = OpPreparation::ApplyTensor(
outputSize,
self.options().dtype(at::kInt),
ACL_FORMAT_ND);
self);
SmallVector<int64_t, N> DimVec = {realDim};
// calculate the output result of the NPU
OpCommand cmd;
@@ -27,13 +27,10 @@ Tensor& bmm_out_npu(Tensor& result, const Tensor& self, const Tensor& mat2) {
Tensor contiguousSelf = self;
Tensor contiguousMat2 = mat2;
bool isSelfT = CalcuOpUtil::is_transpose_last_two_dims(self);
bool isMat2T = CalcuOpUtil::is_transpose_last_two_dims(mat2);
if(!isSelfT){
if(! CalcuOpUtil::is_transpose_last_two_dims(self)){
contiguousSelf = NpuUtils::format_contiguous_add_copy_optimize(self);
}
if(!isMat2T){
if(! CalcuOpUtil::is_transpose_last_two_dims(mat2)){
contiguousMat2 = NpuUtils::format_contiguous_add_copy_optimize(mat2);
}
@@ -46,6 +43,9 @@ Tensor& bmm_out_npu(Tensor& result, const Tensor& self, const Tensor& mat2) {
return std::tie(pass, contiguousMat2);
};
bool isSelfT = CalcuOpUtil::is_transpose_last_two_dims(self);
bool isMat2T = CalcuOpUtil::is_transpose_last_two_dims(mat2);
// executing the NPU operator
OpCommand cmd;
cmd.Name("BatchMatMul")
@@ -57,7 +57,7 @@ Tensor& dtype_cast_npu_(Tensor& self, const Tensor& src) {
}
if (!NpuUtils::check_match(&self)) {
Tensor contiguousSelf = OpPreparation::ApplyTensor(self.sizes(), self.options().dtype(self.dtype()), self);
Tensor contiguousSelf = NpuUtils::format_contiguous(self);
Tensor result = cast_nocheck(contiguousSelf, src);
NpuUtils::format_fresh_view(self, result);
} else {
@@ -154,20 +154,6 @@ Tensor& _cat_out_npu(Tensor& result, TensorList tensors, int64_t dim) {
}
Tensor& cat_out_npu(Tensor& result, TensorList tensors, int64_t dim) {
SmallVector<Tensor, N> inputTensors = cat_dest_tensor_list(tensors);
int64_t dim_post_expr = 0;
if (inputTensors.size() > 0) {
dim_post_expr = inputTensors[0].dim();
}
dim = CalcuOpUtil::make_wrap_dim(dim, dim_post_expr);
auto outputSize = cat_npu_output_size(inputTensors, dim);
OpPreparation::CheckOut(
{tensors[0]},
result,
ACL_FORMAT_ND,
tensors[0].scalar_type(),
outputSize);
return at::_cat_out(result, tensors, dim);
}
@@ -88,21 +88,13 @@ Tensor constant_pad_nd_npu(const Tensor& self, IntArrayRef pad, Scalar value){
}
if (is_backward(pad)) {
TORCH_CHECK(self.dim() == 4 || self.dim() == 5,
"Only support 4D and 5D now, but self.dim is",self.dim());
TORCH_CHECK(pad.size() == 4 || pad.size() == 6,
"Length of pad must is 4 or 6 now, but pad.size() is", pad.size());
TORCH_CHECK(self.dim() == 4, "only support 4D now, but self.dim is",self.dim());
TORCH_CHECK(pad.size() == 4, "Length of pad must is 4 now, but pad.size() is", pad.size());
SmallVector<int64_t, SIZE> begin_list = {0, 0, -pad[2], -pad[0]};
SmallVector<int64_t, SIZE> end_list = {self.size(0), self.size(1), self.size(-2) + pad[3], self.size(-1) + pad[1]};
SmallVector<int64_t, SIZE> strides = {1, 1, 1, 1};
if (self.dim() == 5) {
begin_list = {0, 0, -pad[4], -pad[2], -pad[0]};
end_list = {self.size(0), self.size(1), self.size(-3) + pad[5], self.size(-2) + pad[3], self.size(-1) + pad[1]};
strides = {1, 1, 1, 1, 1};
}
return at::npu_indexing(self, begin_list, end_list, strides);
}
@@ -117,4 +109,4 @@ Tensor constant_pad_nd_npu(const Tensor& self, IntArrayRef pad, Scalar value){
}
} // namespace native
} // namespace at
} // namespace at
@@ -58,7 +58,7 @@ Tensor ctc_loss_backward_npu(
auto inputLengthsTensor = at::tensor(inputLengths, targetsCast.options().dtype(at::kInt));
auto targetLengthsTensor = at::tensor(targetLengths, targetsCast.options().dtype(at::kInt));
auto outputSize = input_same_output_size(logProbs);
auto outputSize = {logProbs.size(1), logProbs.size(0), logProbs.size(2)};
// construct the output tensor of the NPU
Tensor grad = OpPreparation::ApplyTensor(logProbsNeed, outputSize);
@@ -81,7 +81,8 @@ Tensor ctc_loss_backward_npu(
grad = grad.to(ScalarType::Half);
}
return grad;
//return grad;
return grad.permute({1,0,2});
}
} // namespace native
} // namespace at
@@ -1,47 +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"
namespace at {
namespace native {
using namespace at::native::npu;
void cummax_out_npu_nocheck (
Tensor& values,
Tensor& indices,
const Tensor& self,
int64_t dim) {
OpCommand cmd;
cmd.Name("Cummax")
.Input(self)
.Output(values)
.Output(indices)
.Attr("dim", dim)
.Run();
}
void cummax_helper_npu(const Tensor& self, Tensor& values, Tensor& indices, int64_t dim) {
Tensor valuesTemp = OpPreparation::ApplyTensor(self);
Tensor indicesTemp = OpPreparation::ApplyTensor(self, self.options().dtype(kLong));
cummax_out_npu_nocheck(valuesTemp, indicesTemp, self, dim);
values.copy_(valuesTemp);
indices.copy_(indicesTemp);
}
}}
+111 -50
View File
@@ -14,64 +14,125 @@
// 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"
#include "ATen/native/npu/utils/KernelNpuOutputSize.h"
#include "ATen/native/npu/utils/NpuUtils.h"
namespace at {
namespace native {
using namespace at::native::npu;
void cummin_out_npu_nocheck (
Tensor& values,
Tensor& indices,
const Tensor& self,
int64_t dim) {
OpCommand cmd;
cmd.Name("Cummin")
.Input(self)
.Output(values)
.Output(indices)
.Attr("dim", dim)
.Run();
SmallVector<NPUTensorDesc, N> cummin_npu_input(
const SmallVector<Tensor, N>& inputTensor) {
return CalcuOpUtil::create_npu_input_tensor_desc(inputTensor);
}
void cummin_helper_npu(const Tensor& self, Tensor& values, Tensor& indices, int64_t dim) {
//process aicpu
if(self.scalar_type() == ScalarType::Long){
Tensor valuesTemp = OpPreparation::ApplyTensor(self);
Tensor indicesTemp = OpPreparation::ApplyTensor(self, self.options().dtype(kLong));
cummin_out_npu_nocheck(valuesTemp, indicesTemp, self, dim);
values.copy_(valuesTemp);
indices.copy_(indicesTemp);
SmallVector<NPUTensorDesc, N> cummin_npu_output(
const SmallVector<Tensor, N>& outputTensor) {
return CalcuOpUtil::create_npu_output_tensor_desc(outputTensor);
}
SmallVector<NPUAttrDesc, N> cummin_npu_attr(int64_t dim) {
NPUAttrDesc npuAttrDim = NPUAttrDesc("dim", dim);
SmallVector<NPUAttrDesc, N> attrs = {npuAttrDim};
return attrs;
}
tuple<Tensor&, Tensor&> cummin_out_npu_no_transpose (
Tensor& values,
Tensor& indices,
const Tensor& self,
int64_t dim) {
// constructs the input and output NPUTensorDesc
auto inputs = cummin_npu_input({self});
auto outputs = cummin_npu_output({values, indices});
// constructs the attr of the NPUAttrDesc
auto attrs = cummin_npu_attr(dim);
// executing the NPU operator
CalcuOpUtil::execute_npu_operate("Cummin", inputs, outputs, attrs);
return std::tie(values, indices);
}
tuple<Tensor&, Tensor&> cummin_out_npu (
Tensor& values,
Tensor& indices,
const Tensor& self,
int64_t dim) {
auto indices_dtype = indices.scalar_type();
if(indices_dtype != c10::ScalarType::Long) {
AT_ERROR("indices must be int64 type.");
}
Tensor indices_int32 = indices.to(at::kInt);
const auto names = self.names();
Tensor self_no_name = self.rename(nullopt);
dim = CalcuOpUtil::make_wrap_dim(dim, self.dim());
int64_t firstDim = CalcuOpUtil::make_wrap_dim(0, self.dim());
if (dim != firstDim) {
SmallVector<int64_t, SHAPE_SIZE> perm;
for (int64_t i = 0; i < self.dim(); i++) {
perm.emplace_back(i);
}
std::swap(perm[dim], perm[firstDim]);
// construct the output tensor of the NPU
Tensor transposeSelf = at::npu_transpose(self_no_name, perm);
auto outputSize = transpose_npu_output_size(values, perm);
Tensor transposeValue = at::empty_with_format(
outputSize,
values.options(),
CalcuOpUtil::get_tensor_npu_format(values));
Tensor transposeIndices = at::empty_with_format(
outputSize,
indices_int32.options(),
CalcuOpUtil::get_tensor_npu_format(indices_int32));
cummin_out_npu_no_transpose(
transposeValue,
transposeIndices,
transposeSelf,
firstDim);
at::npu_transpose_out(values, transposeValue, perm);
at::npu_transpose_out(indices_int32, transposeIndices, perm);
} else {
//process aicore
int64_t firstDim = CalcuOpUtil::make_wrap_dim(0, self.dim());
if (dim != firstDim) {
SmallVector<int64_t, SHAPE_SIZE> perm;
for (int64_t i = 0; i < self.dim(); i++) {
perm.emplace_back(i);
}
std::swap(perm[dim], perm[firstDim]);
Tensor transposeSelf = at::npu_transpose(self, perm);
auto outputSize = transpose_npu_output_size(values, perm);
Tensor transposeValue = OpPreparation::ApplyTensor(self, outputSize);
Tensor transposeIndices = OpPreparation::ApplyTensor(outputSize, self.options().dtype(kInt), self);
cummin_out_npu_nocheck(transposeValue, transposeIndices, transposeSelf, firstDim);
//Indices must to be long
transposeIndices = transposeIndices.to(kLong);
at::npu_transpose_out(values, transposeValue, perm);
at::npu_transpose_out(indices, transposeIndices, perm);
} else {
Tensor valuesTemp = OpPreparation::ApplyTensor(self);
Tensor indicesTemp = OpPreparation::ApplyTensor(self, self.options().dtype(kInt));
cummin_out_npu_nocheck(valuesTemp, indicesTemp, self, dim);
indicesTemp = indicesTemp.to(kLong);
values.copy_(valuesTemp);
indices.copy_(indicesTemp);
}
}
cummin_out_npu_no_transpose(
values, indices_int32, self, firstDim);
}
indices.npu_dtype_cast_(indices_int32);
values.rename_(names);
indices.rename_(names);
return std::tie(values, indices);
}
}}
tuple<Tensor, Tensor> cummin_npu(const Tensor& self, int64_t dim) {
// calculate the output size
auto outputSize = input_same_output_size(self);
Tensor values = at::empty_with_format(
outputSize,
self.options(),
CalcuOpUtil::get_tensor_npu_format(self));
Tensor indices = at::empty_with_format(
outputSize,
self.options().dtype(kLong),
CalcuOpUtil::get_tensor_npu_format(self));
cummin_out_npu(values, indices, self, dim);
return std::tie(values, indices);
}
tuple<Tensor&, Tensor&> cummin_out_npu(
Tensor& values,
Tensor& indices,
const Tensor& self,
Dimname dim) {
// dimname_to_position(self, dim) : Dimname --> Int
return cummin_out_npu(
values, indices, self, dimname_to_position(self, dim));
}
tuple<Tensor, Tensor> cummin_npu(const Tensor& self, Dimname dim) {
return cummin_npu(self, dimname_to_position(self, dim));
}
} // namespace native
} // namespace at
@@ -20,19 +20,12 @@ using namespace at::native::npu;
Tensor& _cumsum_out_npu(Tensor& result, const Tensor& self, int64_t dim) {
OpCommand cmd;
if (!c10::npu::OptionsManager::CheckDynamicEnable()) {
// if dim = 0, performance in Aicpu is better than Aicore
// if dim > INT32_MAX, we should use long to store dim for ensuring function correctness.
// use host memory instead of scalar to improve delivery performance
Scalar dimScalar(dim);
if (!c10::npu::OptionsManager::CheckDynamicEnable()){
SmallVector<int64_t, N> dimvec = {dim};
cmd.Name("Cumsum")
.Input(self);
if (dim == 0 || dim > INT32_MAX) {
cmd.Input(dimScalar, at::kLong, MemoryType::MEMORY_HOST);
} else {
cmd.Input(dimScalar, at::kInt, MemoryType::MEMORY_HOST);
}
cmd.Output(result)
.Input(self)
.Input(dimvec, at::kInt)
.Output(result)
.Run();
} else {
cmd.Name("CumsumD")
@@ -46,12 +39,16 @@ Tensor& _cumsum_out_npu(Tensor& result, const Tensor& self, int64_t dim) {
}
Tensor _cumsum_npu(const Tensor& self, int64_t dim) {
Tensor input = self;
if(self.scalar_type() == ScalarType::Long){
input = self.to(ScalarType::Int);
}
// calculate the output size
auto outputSize = input_same_output_size(self);
// construct the output tensor of the NPU
Tensor result = OpPreparation::ApplyTensor(self, outputSize);
Tensor result = OpPreparation::ApplyTensor(input, outputSize);
// calculate the output result of the NPU
_cumsum_out_npu(result, self, dim);
_cumsum_out_npu(result, input, dim);
return result;
}
@@ -1,5 +1,4 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// All rights reserved.
// 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.
@@ -12,6 +11,7 @@
// 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/CalcuOpUtil.h"
#include "ATen/native/npu/utils/KernelNpuOutputSize.h"
#include "ATen/native/npu/utils/NpuUtils.h"
@@ -44,9 +44,12 @@ Tensor dropout_gen_mask(const Tensor& self, const Tensor& prob) {
Tensor mask = at::empty_with_format(
{length / 8},
self.options().dtype(at::kByte),
ACL_FORMAT_ND);
CalcuOpUtil::get_tensor_npu_format(self));
IntArrayRef selfShape = self.sizes();
Tensor cpu_shape =
from_blob((void*)self.sizes().data(), {self.dim()}, at::kLong)
.to(at::kInt);
Tensor npu_shape = CalcuOpUtil::copy_tensor_host_to_device(cpu_shape);
OpCommand cmd;
// If either seed or seed2 are set to be non-zero, the random number generator
@@ -54,7 +57,7 @@ Tensor dropout_gen_mask(const Tensor& self, const Tensor& prob) {
int64_t seed = 0;
int64_t seed2 = 0;
cmd.Name("DropOutGenMask")
.Input(selfShape)
.InputPair(npu_shape, /*cpu_input=*/cpu_shape)
.Input(prob)
.Output(mask)
.Attr("seed", seed)
@@ -74,6 +77,9 @@ std::tuple<Tensor, Tensor> dropout_v1_npu_impl(
TORCH_CHECK(
at::isFloatingType(self.scalar_type()),
"dropout only supports floating-point dtypes");
// dropout only supports NCHW foramt(aicpu restriction)
Tensor selfFormatCast = self.npu_format_cast(ACL_FORMAT_ND);
double retain = 1. - p;
Tensor prob;
@@ -85,22 +91,25 @@ std::tuple<Tensor, Tensor> dropout_v1_npu_impl(
// same time, according to the one-stream-one-pool principle, memory is also
// alloced from the pool of the secondary stream.
c10::npu::SecondaryStreamGuard guard(c10::npu::getCurrentSecondaryStream());
prob = scalar_to_tensor(retain).to(self.scalar_type());
mask = dropout_gen_mask(self, prob);
prob = CalcuOpUtil::CopyScalarToDevice(retain, selfFormatCast.scalar_type());
mask = dropout_gen_mask(selfFormatCast, prob);
}
// When tasks on multiple streams read and write the same block of memory,
// recordStream needs to be called to ensure the correctness of memory reuse.
c10::npu::NPUCachingAllocator::recordStream(prob.storage().data_ptr(), original_stream);
c10::npu::NPUCachingAllocator::recordStream(mask.storage().data_ptr(), original_stream);
dropout_do_mask(result, self, mask, prob);
dropout_do_mask(result, selfFormatCast, mask, prob);
return std::tie(result, mask);
}
std::tuple<Tensor, Tensor> _dropout_npu(
const Tensor& self,
double p) {
Tensor result = OpPreparation::ApplyTensor(self);
return dropout_v1_npu_impl(result, self, p);
Tensor selfFormatCast = self.npu_format_cast(ACL_FORMAT_ND);
auto outputSize = input_same_output_size(selfFormatCast);
Tensor result = at::empty_with_format(
outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(selfFormatCast));
return dropout_v1_npu_impl(result, selfFormatCast, p);
}
std::tuple<Tensor, Tensor> _dropout_npu_inplace(
@@ -1,5 +1,4 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// All rights reserved.
// 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.
@@ -12,6 +11,7 @@
// 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/CalcuOpUtil.h"
#include "ATen/native/npu/utils/KernelNpuOutputSize.h"
#include "ATen/native/npu/utils/NpuUtils.h"
@@ -1,17 +1,3 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// 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/CalcuOpUtil.h"
#include "ATen/native/npu/utils/KernelNpuOutputSize.h"
#include "ATen/native/npu/utils/NpuUtils.h"
@@ -1,5 +1,4 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// All rights reserved.
// 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.
@@ -12,6 +11,7 @@
// 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"
namespace at {
@@ -12,39 +12,71 @@
// 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"
#include "ATen/native/npu/utils/KernelNpuOutputSize.h"
#include "ATen/native/npu/utils/NpuUtils.h"
namespace at {
namespace native {
using namespace at::native::npu;
SmallVector<NPUTensorDesc, N> embedding_renorm_npu_input(
const SmallVector<Tensor, N>& inputTensor) {
return CalcuOpUtil::create_npu_input_tensor_desc(inputTensor);
}
SmallVector<NPUTensorDesc, N> embedding_renorm_npu_output(
const SmallVector<Tensor, N>& outputTensor) {
return CalcuOpUtil::create_npu_output_tensor_desc(outputTensor);
}
SmallVector<NPUAttrDesc, N> embedding_renorm_npu_attr(
double max_norm,
double norm_type){
int64_t dim = 0;
float max_norm_float = (float) max_norm;
float norm_type_float = (float) norm_type;
NPUAttrDesc npuAttrScalarP = NPUAttrDesc("p", norm_type_float);
NPUAttrDesc npuAttrScalarMaxnorm = NPUAttrDesc("maxnorm", max_norm_float);
NPUAttrDesc npuAttrDim = NPUAttrDesc("dim", dim);
SmallVector<NPUAttrDesc, N> attrs = {npuAttrScalarP, npuAttrDim, npuAttrScalarMaxnorm};
return attrs;
}
SmallVector<NPUAttrDesc, N> embedding_gather2d_npu_attr() {
NPUAttrDesc npuAttrAxis = NPUAttrDesc("axis", (int64_t)0);
SmallVector<NPUAttrDesc, N> attrs = {npuAttrAxis};
return attrs;
}
SmallVector<NPUAttrDesc, N> embedding_renorm_scatter_update_npu_attr(){
NPUAttrDesc npuAttrAxis = NPUAttrDesc("use_locking", false);
SmallVector<NPUAttrDesc, N> attrs = {npuAttrAxis};
return attrs;
}
Tensor& embedding_renorm_gather2d_out_npu(
Tensor& result,
const Tensor& self,
const Tensor& indices) {
OpCommand cmd;
cmd.Name("GatherV2D")
.Input(self)
.Input(indices)
.Output(result)
.Attr("axis", (int64_t)0)
.Run();
const Tensor& indices
){
// execute the NPU operate GatherV2D
auto inputs = embedding_renorm_npu_input({self, indices});
auto outputs = embedding_renorm_npu_output({result});
auto attrs = embedding_gather2d_npu_attr();
CalcuOpUtil::execute_npu_operate("GatherV2D", inputs, outputs, attrs);
return result;
}
Tensor& embedding_renorm_execute_out_npu(
Tensor& result,
const Tensor& self,
double max_norm,
double norm_type) {
OpCommand cmd;
cmd.Name("Renorm")
.Input(self)
.Output(result)
.Attr("p", (float)norm_type)
.Attr("dim", (int64_t)0)
.Attr("maxnorm", (float)max_norm)
.Run();
double max_norm,
double norm_type){
//execute the NPU operate Renorm
auto inputs = embedding_renorm_npu_input({self});
auto outputs = embedding_renorm_npu_output({result});
auto attrs = embedding_renorm_npu_attr(max_norm, norm_type);
CalcuOpUtil::execute_npu_operate("Renorm", inputs, outputs, attrs);
return result;
}
@@ -53,84 +85,82 @@ Tensor& embedding_renorm_scatter_update_out_npu(
Tensor& result,
const Tensor& self,
const Tensor& indices,
const Tensor& update) {
OpCommand cmd;
cmd.Name("ScatterUpdate")
.Input(self)
.Input(indices)
.Input(update)
.Output(result)
.Attr("use_locking", false)
.Run();
const Tensor& update){
auto inputs = embedding_renorm_npu_input({self, indices, update});
auto outputs = embedding_renorm_npu_output({result});
auto attrs = embedding_renorm_scatter_update_npu_attr();
CalcuOpUtil::execute_npu_operate("ScatterUpdate", inputs, outputs, attrs);
return result;
}
Tensor& embedding_renorm_out_npu(
Tensor& result,
const Tensor& self,
const Tensor& indices,
double max_norm,
Tensor& mid_input,
Tensor& mid_output,
double max_norm,
double norm_type){
//get the outSize of GatherV2 , the middle tensor
SmallVector<int64_t, SIZE> midSize = {indices.size(0), self.size(1)};
Tensor mid_input = OpPreparation::ApplyTensor(self, midSize);
Tensor mid_output = OpPreparation::ApplyTensor(self, midSize);
// execute the NPU operate GatherV2D, generate new tensor by indices
embedding_renorm_gather2d_out_npu(mid_input,self,indices);
//execute the NPU operate Renorm
embedding_renorm_execute_out_npu(mid_output, mid_input, max_norm, norm_type);
//execute the NPU operate ZerosLike or RangeD, generate new tensor by indices.numel()
Tensor mid_output_copy = mid_output.clone();
auto num_indices = indices.numel();
Tensor input_indices;
// RangeD not support range(0,0)
if (num_indices - 1 == 0) {
input_indices = at::zeros({1}, self.options()).to(at::kLong);
} else {
input_indices = at::range(0, num_indices-1, self.options()).to(at::kLong);
}
//execute the NPU operate MUL, generate change result
auto num_mid_output = mid_output.numel();
resize_npu_(mid_output_copy, num_mid_output);
Tensor scalar_out = OpPreparation::ApplyTensor(self, {num_indices, 1});
embedding_renorm_gather2d_out_npu(scalar_out, mid_output_copy, input_indices);
Tensor out_res = mid_input * scalar_out;
// executing the NPU operator ScatterUpdate
embedding_renorm_scatter_update_out_npu(result, self, indices, out_res);
// execute the NPU operate GatherV2D,generate new tensor by indices
embedding_renorm_gather2d_out_npu(
mid_input,
self,
indices);
//execute the NPU operate Renorm
embedding_renorm_execute_out_npu(
mid_output,
mid_input,
max_norm,
norm_type);
// executing the NPU operator ScatterUpdate
embedding_renorm_scatter_update_out_npu(
result,
self,
indices,
mid_output);
return result;
}
Tensor& embedding_renorm_npu_(
Tensor& self,
const Tensor& indices,
double max_norm,
double max_norm,
double norm_type) {
//check dim and type
//check dim and type
auto self_arg = TensorArg(self, "self", 1);
auto indices_arg = TensorArg(indices, "indices", 2);
checkDim("embedding_renorm_", self_arg, 2);
checkScalarType("embedding_renorm_", indices_arg, kLong);
//resize indices to 1D
// indices must be int64 in pytorch, but npu can only support int32
auto indices_int32 = indices.to("cpu");
indices_int32 = indices_int32.to(at::kInt);
indices_int32 = indices_int32.to("npu");
//resize indices to 1D
Tensor indices_copy = indices.clone();
auto num_indices = indices.numel();
resize_npu_(indices_copy, num_indices);
SmallVector<Tensor, N> inputs = {self};
SmallVector<Tensor, N> outputs = {self};
CalcuOpUtil::check_memory_over_laps(inputs, outputs);
OpPipeWithDefinedOut pipe;
pipe.CheckMemory({self, indices_copy}, {self})
.Func([&self, &indices_copy, max_norm, norm_type](Tensor& result){
embedding_renorm_out_npu(self, self, indices_copy, max_norm, norm_type);})
.Call(self);
//get the outSize of GatherV2 , the middle tensor
auto midSize = embedding_renorm_mid_npu_output_size(self, indices_copy);
Tensor mid = at::empty_with_format(midSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
Tensor mid1 = at::empty_with_format(midSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
//inplace operate
if (!NpuUtils::check_match(&self)) {
Tensor contiguousSelf = NpuUtils::format_contiguous(self);
Tensor result = embedding_renorm_out_npu(contiguousSelf, contiguousSelf, indices_copy, mid, mid1, max_norm, norm_type);
NpuUtils::format_fresh_view(self, result);
} else {
embedding_renorm_out_npu(self, self, indices_copy, mid, mid1, max_norm, norm_type);
}
return self;
}
@@ -1,57 +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"
namespace at {
namespace native {
using namespace at::native::npu;
Tensor& erfc_out_npu_no_check(Tensor& out, const Tensor& self){
OpCommand cmd;
cmd.Name("Erfc")
.Input(self)
.Output(out)
.Run();
return out;
}
Tensor& erfc_out_npu(Tensor& out, const Tensor& self) {
OpPreparation::CheckOut(
{self},
out,
self,
self.sizes());
OpPipeWithDefinedOut pipe;
return pipe.CheckMemory({self}, {out})
.Func([&self](Tensor& out){erfc_out_npu_no_check(out, self);})
.Call(out);
}
Tensor erfc_npu(const Tensor& self) {
Tensor result = OpPreparation::ApplyTensor(self);
erfc_out_npu_no_check(result, self);
return result;
}
Tensor& erfc_npu_(Tensor& self) {
erfc_out_npu(self, self);
return self;
}
} // native
} // at
@@ -23,12 +23,7 @@ using namespace at::native::npu;
Tensor& fill_out_npu(Tensor& result, Tensor& self, const Tensor& other) {
if (!c10::npu::OptionsManager::CheckDynamicEnable()) {
SmallVector<int64_t, N> dims;
if (self.dim() != 0){
dims = array_to_small_vector(self.sizes());
} {
dims = {1};
}
SmallVector<int64_t, N> dims = array_to_small_vector(self.sizes());
OpCommand cmd;
cmd.Name("Fill")
.Input(dims, at::kLong)
@@ -58,6 +58,7 @@ Tensor alloc_float_status_npu(const Tensor& self) {
// calculate the output result of the NPU
OpCommand cmd;
cmd.Name("NPUAllocFloatStatus")
.Input()
.Output(result)
.Run();
@@ -32,14 +32,12 @@ Tensor& floor_divide_out_npu(Tensor& result, const Tensor& self, Scalar other) {
}
Tensor& floor_divide_out_npu(Tensor& result, const Tensor& self, const Tensor& other) {
auto unified_result = OpPreparation::binary_op_check(result, self, other, true);
// executing the NPU operator
if (other.dim() == 0) {
floor_divide_out_npu(result, self, other.item());
} else {
OpCommand cmd;
cmd.Name("FloorDiv")
.Expect(unified_result)
.Input(self)
.Input(other)
.Output(result)
@@ -50,34 +48,30 @@ Tensor& floor_divide_out_npu(Tensor& result, const Tensor& self, const Tensor& o
}
Tensor floor_divide_npu(const Tensor& self, const Tensor& other) {
Tensor selfCast = self;
if(self.dtype() == ScalarType::Bool){
selfCast = self.to(ScalarType::Float);
}
Tensor temp = other;
if (other.scalar_type() == ScalarType::Double) {
temp = other.to(ScalarType::Float);
}
if (other.scalar_type() == ScalarType::Long) {
temp = other.to(ScalarType::Int);
}
// calculate the output size
bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(selfCast);
Tensor outputTensor = isSelfWrapped ? temp : selfCast;
Tensor temp = other;
if (other.scalar_type() == ScalarType::Double) {
temp = other.to(ScalarType::Float);
}
if (other.scalar_type() == ScalarType::Long) {
temp = other.to(ScalarType::Int);
}
// calculate the output size
bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self);
Tensor outputTensor = isSelfWrapped ? temp : self;
auto outputSize = broadcast_ops_npu_output_size(selfCast, temp);
auto outputSize = broadcast_ops_npu_output_size(self, temp);
// construct the output tensor of the NPU
Tensor result = at::empty_with_format(
outputSize,
outputTensor.options(),
CalcuOpUtil::get_tensor_npu_format(selfCast));
// construct the output tensor of the NPU
Tensor result = at::empty_with_format(
outputSize,
outputTensor.options(),
CalcuOpUtil::get_tensor_npu_format(self));
// calculate the output result of the NPU
floor_divide_out_npu(result, selfCast, temp);
// calculate the output result of the NPU
floor_divide_out_npu(result, self, temp);
return result;
return result;
}
Tensor floor_divide_npu(const Tensor& self, Scalar other) {
@@ -1,89 +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"
namespace at {
namespace native {
using namespace at::native::npu;
std::tuple<Tensor&, Tensor&>
giou_backward_inner_out_npu(
Tensor& dbboxes,
Tensor& dgtboxes,
const Tensor& grad,
const Tensor& bboxes,
const Tensor& gtboxes,
bool trans,
bool is_cross,
int64_t mode){
string mode_str = mode == 1 ? "iof" : "iou";
OpCommand cmd;
cmd.Name("GIoUGrad")
.Input(grad)
.Input(bboxes)
.Input(gtboxes)
.Output(dbboxes)
.Output(dgtboxes)
.Attr("trans", trans)
.Attr("is_cross", is_cross)
.Attr("mode", mode_str)
.Run();
return std::tie(dbboxes, dgtboxes);
}
std::tuple<Tensor, Tensor>
giou_backward_npu(
const Tensor& grad,
const Tensor& bboxes,
const Tensor& gtboxes,
bool trans,
bool is_cross,
int64_t mode){
TORCH_CHECK(trans && !is_cross && mode == 0,
"giou backward only support trans==True, ",
"is_cross==False, ",
"mode==0('iou') current version ",
"if you need to back propagation, ",
"please ensure your parameter is correct!");
// Op need form of [n] grad
// Note: temp avoid! it'll be remove while op deal with fp16 issue!
Tensor gradCp = at::squeeze(grad, 0);
if(gradCp.scalar_type() == at::kHalf){
gradCp = gradCp.npu_dtype_cast(at::kFloat);
}
Tensor bboxesCp = bboxes;
if(bboxesCp.scalar_type() == at::kHalf){
bboxesCp = bboxesCp.npu_dtype_cast(at::kFloat);
}
Tensor gtboxesCp = gtboxes;
if(gtboxesCp.scalar_type() == at::kHalf){
gtboxesCp = gtboxesCp.npu_dtype_cast(at::kFloat);
}
Tensor dbboxes = OpPreparation::ApplyTensor(bboxesCp);
Tensor dgtboxes = OpPreparation::ApplyTensor(gtboxesCp);
giou_backward_inner_out_npu(dbboxes, dgtboxes, gradCp, bboxesCp, gtboxesCp, trans, is_cross, mode);
if(bboxes.scalar_type() == at::kHalf || gtboxes.scalar_type() == at::kHalf){
dbboxes = dbboxes.npu_dtype_cast(at::kHalf);
dgtboxes = dgtboxes.npu_dtype_cast(at::kHalf);
}
return std::tie(dbboxes, dgtboxes);
}
} // namespace native
} // namespace at
@@ -1,97 +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"
namespace at {
namespace native {
using namespace at::native::npu;
SmallVector<int64_t, N> giou_output_size(
const Tensor& self,
const Tensor& gtboxes,
bool is_cross){
SmallVector<int64_t, N> output_size;
if(is_cross){
output_size = {gtboxes.size(0), self.size(0)};
} else {
output_size = {1, self.size(0)};
}
return output_size;
}
Tensor& giou_inner_out_npu(
Tensor& result,
const Tensor& self,
const Tensor& gtboxes,
bool trans,
bool is_cross,
int64_t mode){
auto output_size = giou_output_size(self, gtboxes, is_cross);
OpPreparation::CheckOut(
{self},
result,
self,
output_size);
string mode_str = mode == 1 ? "iof" : "iou";
OpCommand cmd;
cmd.Name("GIoU")
.Input(self)
.Input(gtboxes)
.Output(result)
.Attr("trans", trans)
.Attr("is_cross", is_cross)
.Attr("mode", mode_str)
.Run();
return result;
}
Tensor giou_npu(
const Tensor& self,
const Tensor& gtboxes,
bool trans,
bool is_cross,
int64_t mode){
TORCH_CHECK(trans && !is_cross && mode == 0,
"giou backward only support trans==True, ",
"is_cross==False, ",
"mode==0('iou') current version ",
"if you need to back propagation, ",
"please ensure your parameter is correct!");
// Op need form of [n, 4], but pass should be [4, n];
// Note: temp avoid! it'll be removed while op deal with fp16 issue!
Tensor selfCp = self.permute({1, 0});
if(selfCp.scalar_type() == at::kHalf){
selfCp = selfCp.npu_dtype_cast(at::kFloat);
}
Tensor gtboxesCp = gtboxes.permute({1, 0});
if(gtboxesCp.scalar_type() == at::kHalf){
gtboxesCp = gtboxesCp.npu_dtype_cast(at::kFloat);
}
auto output_size = giou_output_size(selfCp, gtboxesCp, is_cross);
Tensor result = OpPreparation::ApplyTensor(selfCp, output_size);
giou_inner_out_npu(result, selfCp, gtboxesCp, trans, is_cross, mode);
result = result.permute({1, 0});
if(self.scalar_type() == at::kHalf || gtboxes.scalar_type() == at::kHalf){
result = result.npu_dtype_cast(at::kHalf);
}
return result;
}
} // namespace native
} // namespace at
@@ -1,5 +1,4 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// All rights reserved.
// 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.
@@ -12,6 +11,7 @@
// 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/KernelNpuOutputSize.h"
#include "ATen/native/npu/utils/OpTemplate.h"
@@ -26,9 +26,6 @@ Tensor& index_put_nocheck(
const TensorList& indices,
const Tensor& value,
bool accumulate) {
if (value.numel() == 0) {
return result;
}
// masks corresponds to indices. 0 indicates undefined tensor.
SmallVector<int64_t, N> masks;
std::vector<Tensor> allDefinedIndices;
@@ -44,27 +41,16 @@ Tensor& index_put_nocheck(
auto masksTensor = CalcuOpUtil::copy_tensor_host_to_device(
from_blob(masks.data(), {masks.size()}, dtype(ScalarType::Long)));
Tensor tempSelf = self;
Tensor tempValue = value;
if (self.scalar_type() == ScalarType::Half) {
tempSelf = self.npu_dtype_cast(ScalarType::Float);
tempValue = value.npu_dtype_cast(ScalarType::Float);
result = result.npu_dtype_cast(ScalarType::Float);
}
OpCommand cmd;
cmd.Name("IndexPut")
.Input(tempSelf)
.Input(tempValue)
.Input(self)
.Input(value)
.Input(masksTensor)
.Inputs(allDefinedIndices)
.Output(result)
.Attr("accumulate", accumulate)
.Run();
if (self.scalar_type() == ScalarType::Half) {
result = result.npu_dtype_cast(ScalarType::Half);
}
return result;
}
@@ -22,7 +22,7 @@ namespace at {
namespace native {
using namespace at::native::npu;
Tensor& index_select_out_npu_nocheck(
Tensor& index_select_out_npu(
Tensor& result,
const Tensor& self,
int64_t dim,
@@ -61,50 +61,6 @@ Tensor& index_select_out_npu_nocheck(
return result;
}
Tensor& index_select_out_npu(
Tensor& result,
const Tensor& self,
int64_t dim,
const Tensor& index) {
Tensor indexTmp(index);
if (indexTmp.ndimension() == 0) {
indexTmp = index.unsqueeze(0);
}
// calculate the output size
auto outputSize = index_select_npu_output_size(self, dim, indexTmp);
int64_t npu_format = CalcuOpUtil::get_tensor_npu_format(self);
// scalar scene no support nz
if (outputSize.empty()) {
npu_format = ACL_FORMAT_ND;
}
Tensor input = self;
if (self.dtype() == kBool) {
// bool to int dtype
input = input.npu_dtype_cast(at::kInt);
}
OpPreparation::CheckOut(
{input},
result,
npu_format,
input.scalar_type(),
outputSize);
OpPipeWithDefinedOut pipe;
result = pipe.CheckMemory({input, indexTmp}, {result})
.Func([&input, &dim, &indexTmp](Tensor& result)
{index_select_out_npu_nocheck(result, input, dim, indexTmp);})
.Call(result);
if (self.dtype() == kBool) {
result = result.to(kBool);
}
return result;
}
Tensor index_select_npu(const Tensor& self, int64_t dim, const Tensor& index) {
Tensor indexTmp(index);
if (indexTmp.ndimension() == 0) {
@@ -130,7 +86,7 @@ Tensor index_select_npu(const Tensor& self, int64_t dim, const Tensor& index) {
at::empty_with_format(outputSize, input.options(), npu_format);
// calculate the output result of the NPU
index_select_out_npu_nocheck(result, input, dim, indexTmp);
index_select_out_npu(result, input, dim, indexTmp);
if (self.dtype() == kBool) {
// int to bool dtype 这里不转变回bool也能通过测试的比较
@@ -158,4 +114,4 @@ Tensor index_select_npu(const Tensor& self, Dimname dim, const Tensor& index) {
}
} // namespace native
} // namespace at
} // namespace at
@@ -25,12 +25,7 @@ Tensor& indexing_out_npu(
const Tensor& self,
IntArrayRef begin,
IntArrayRef end,
IntArrayRef strides,
int64_t begin_mask,
int64_t end_mask,
int64_t ellipsis_mask,
int64_t new_axis_mask,
int64_t shrink_axis_mask) {
IntArrayRef strides) {
OpCommand cmd;
cmd.Name("StridedSlice")
.Input(self)
@@ -38,11 +33,11 @@ Tensor& indexing_out_npu(
.Input(end)
.Input(strides)
.Output(result)
.Attr("begin_mask", begin_mask)
.Attr("end_mask", end_mask)
.Attr("ellipsis_mask", ellipsis_mask)
.Attr("new_axis_mask", new_axis_mask)
.Attr("shrink_axis_mask", shrink_axis_mask)
.Attr("begin_mask", (int64_t)0)
.Attr("end_mask", (int64_t)0)
.Attr("shrink_axis_mask", (int64_t)0)
.Attr("ellipsis_mask", (int64_t)0)
.Attr("new_axis_mask", (int64_t)0)
.Run();
return result;
@@ -52,12 +47,7 @@ Tensor indexing_npu(
const Tensor& self,
IntArrayRef begin,
IntArrayRef end,
IntArrayRef strides,
int64_t begin_mask,
int64_t end_mask,
int64_t ellipsis_mask,
int64_t new_axis_mask,
int64_t shrink_axis_mask) {
IntArrayRef strides) {
// calculate the output size
SmallVector<int64_t, SIZE> outputSize;
for (int i = 0; i < self.dim(); i++) {
@@ -66,8 +56,7 @@ Tensor indexing_npu(
}
// construct the output tensor of the NPU
Tensor result = OpPreparation::ApplyTensor(self, outputSize);
indexing_out_npu(result, self, begin, end, strides,begin_mask, end_mask,
ellipsis_mask, new_axis_mask, shrink_axis_mask);
indexing_out_npu(result, self, begin, end, strides);
return result;
}
@@ -39,9 +39,10 @@ Tensor isfinite_npu(const Tensor& self_ex) {
// calculate the output result of the NPU
OpCommand cmd;
cmd.Name("IsFinite")
cmd.Name("PTIsfinite")
.Input(self)
.Output(result)
.Attr("kernel_name", "PTIsfinite")
.Run();
return result;
}
@@ -29,7 +29,7 @@ tuple<Tensor &, Tensor &, Tensor &> layer_norm_backward_npu_nocheck(
const Tensor& dY,
const Tensor& X,
const Tensor& mean,
const Tensor& variance,
const Tensor& rstd,
const Tensor& gamma,
int64_t M,
int64_t N)
@@ -40,16 +40,24 @@ tuple<Tensor &, Tensor &, Tensor &> layer_norm_backward_npu_nocheck(
tmpSize[i] = 1;
}
Tensor mean_ex = mean.reshape(tmpSize);
Tensor variance_ex = variance.reshape(tmpSize);
double eps = 1e-05;
Tensor variance = 1 / at::pow(rstd, 2) - eps;
variance = variance.reshape(tmpSize);
Tensor formatCastOfdY = dY.npu_format_cast(ACL_FORMAT_ND);
Tensor formatCastOfX = X.npu_format_cast(ACL_FORMAT_ND);
Tensor formatCastOfVariance = variance.npu_format_cast(ACL_FORMAT_ND);
Tensor formatCastOfMean = mean_ex.npu_format_cast(ACL_FORMAT_ND);
Tensor formatCastOfGamma = gamma.npu_format_cast(ACL_FORMAT_ND);
OpCommand cmd;
cmd.Name("LayerNormGrad")
.Input(dY)
.Input(X)
.Input(variance_ex)
.Input(mean_ex)
.Input(gamma)
.Input(formatCastOfdY)
.Input(formatCastOfX)
.Input(formatCastOfVariance)
.Input(formatCastOfMean)
.Input(formatCastOfGamma)
.Output(dX)
.Output(dgamma)
.Output(dbeta)
@@ -62,7 +70,7 @@ std::tuple<Tensor, Tensor, Tensor> layer_norm_backward_npu(
const Tensor& dY,
const Tensor& X,
const Tensor& mean,
const Tensor& variance,
const Tensor& rstd,
const Tensor& gamma,
int64_t M,
int64_t N,
@@ -90,7 +98,7 @@ std::tuple<Tensor, Tensor, Tensor> layer_norm_backward_npu(
}
// calculate the output size
auto outputSizes = layer_norm_backward_npu_output_size(dY, X, mean, variance, gammaTemp, M, N);
auto outputSizes = layer_norm_backward_npu_output_size(dY, X, mean, rstd, gammaTemp, M, N);
if (M <= 0) {
dX = at::native::empty_like(X, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
@@ -100,12 +108,15 @@ std::tuple<Tensor, Tensor, Tensor> layer_norm_backward_npu(
}
// construct the output tensor
dX = OpPreparation::ApplyTensor(X, std::get<0>(outputSizes));
dgamma = OpPreparation::ApplyTensor(gammaTemp, std::get<1>(outputSizes));
dbeta = OpPreparation::ApplyTensor(gammaTemp, std::get<2>(outputSizes));
dX = at::empty_with_format(
std::get<0>(outputSizes), X.options(), ACL_FORMAT_NCHW);
dgamma = at::empty_with_format(
std::get<1>(outputSizes), gammaTemp.options(), ACL_FORMAT_NCHW);
dbeta = at::empty_with_format(
std::get<2>(outputSizes), gammaTemp.options(), ACL_FORMAT_NCHW);
// calculate the output result of the NPU
return layer_norm_backward_npu_nocheck(dX, dgamma, dbeta, dY, X, mean, variance, gammaTemp, M, N);
return layer_norm_backward_npu_nocheck(dX, dgamma, dbeta, dY, X, mean, rstd, gammaTemp, M, N);
}
}} // namespace at::native
@@ -37,10 +37,10 @@ std::tuple<Tensor, Tensor, Tensor> layer_norm_npu(
Tensor Y = at::empty_with_format(input.sizes(), input.options(), CalcuOpUtil::get_tensor_npu_format(input));
Tensor mean;
Tensor variance;
Tensor rstd;
if (M < 0) {
mean = at::empty_with_format({M}, input.options());
variance = at::empty_with_format({M}, input.options());
rstd = at::empty_with_format({M}, input.options());
} else {
int64_t numels = 1;
int64_t begin_dim = 0;
@@ -76,7 +76,7 @@ std::tuple<Tensor, Tensor, Tensor> layer_norm_npu(
}
mean = at::empty_with_format(reduceDims, weight.options());
variance = at::empty_with_format(reduceDims, weight.options());
rstd = at::empty_with_format(reduceDims, weight.options());
OpCommand cmd;
cmd.Name("LayerNorm")
@@ -85,18 +85,19 @@ std::tuple<Tensor, Tensor, Tensor> layer_norm_npu(
.Input(bias)
.Output(Y)
.Output(mean)
.Output(variance)
.Output(rstd)
.Attr("begin_norm_axis", begin_dim)
.Attr("begin_params_axis", begin_dim)
.Attr("epsilon", static_cast<float>(eps))
.Run();
rstd = 1 / at::sqrt(rstd + eps);
}
Tensor meanResult = mean.reshape({M});
Tensor varianceResult = variance.reshape({M});
Tensor rstdResult = rstd.reshape({M});
return std::tie(Y, meanResult, varianceResult);
return std::tie(Y, meanResult, rstdResult);
}
}}
@@ -18,7 +18,7 @@ namespace at {
namespace native {
using namespace at::native::npu;
Tensor& logspace_out_npu_nocheck(
Tensor& logspace_out_npu(
Tensor& result,
Scalar start,
Scalar end,
@@ -63,28 +63,6 @@ Tensor& logspace_out_npu_nocheck(
return result;
}
Tensor& logspace_out_npu(
Tensor& result,
Scalar start,
Scalar end,
int64_t steps,
double base) {
OpPreparation::CheckOut(
{ },
result,
ACL_FORMAT_ND,
result.scalar_type(),
{steps});
OpPipeWithDefinedOut pipe;
return pipe.CheckMemory({},{result})
.Func([&start, &end, &steps, &base](Tensor& result)
{logspace_out_npu_nocheck(result, start, end, steps, base);})
.Call(result);
return result;
}
Tensor logspace_npu(
Scalar start,
Scalar end,
@@ -94,7 +72,7 @@ Tensor logspace_npu(
Tensor result = OpPreparation::ApplyTensorWithFormat({steps}, options, ACL_FORMAT_ND);
return logspace_out_npu_nocheck(result, start, end, steps, base);
return logspace_out_npu(result, start, end, steps, base);
}
}
+4 -5
View File
@@ -24,8 +24,7 @@ using namespace at::native::npu;
Tensor& lt_out_npu_nocheck(Tensor& result, const Tensor& self, const Tensor& other) {
Tensor selfCast = self;
Tensor otherCast = other;
if(self.dtype() == ScalarType::Int || other.dtype() == ScalarType::Int
|| self.dtype() == ScalarType::Bool || other.dtype() == ScalarType::Bool){
if(self.dtype() == ScalarType::Int || other.dtype() == ScalarType::Int){
selfCast = self.to(ScalarType::Float);
otherCast = other.to(ScalarType::Float);
}
@@ -50,7 +49,7 @@ Tensor& lt_out_npu(Tensor& result, const Tensor& self, const Tensor& other) {
{self},
result,
ACL_FORMAT_ND,
kBool,
result.scalar_type(),
outputSize);
lt_out_npu_nocheck(result, formatCastOfSelf, formatCastOfOther);
@@ -59,7 +58,7 @@ Tensor& lt_out_npu(Tensor& result, const Tensor& self, const Tensor& other) {
Tensor& lt_out_npu_nocheck(Tensor& result, const Tensor& self, Scalar other) {
Tensor selfCast = self;
if(self.dtype() == ScalarType::Int || self.dtype() == ScalarType::Bool){
if(self.dtype() == ScalarType::Int){
selfCast = self.to(ScalarType::Float);
}
OpCommand cmd;
@@ -79,7 +78,7 @@ Tensor& lt_out_npu(Tensor& result, const Tensor& self, Scalar other) {
{self},
result,
ACL_FORMAT_ND,
kBool,
result.scalar_type(),
outputSize);
lt_out_npu_nocheck(result, formatCastOfSelf, other);
@@ -14,21 +14,26 @@
// 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"
#include "ATen/native/npu/utils/KernelNpuOutputSize.h"
#include "ATen/native/npu/utils/NpuUtils.h"
#include "ATen/native/npu/utils/OpTemplate.h"
namespace at {
namespace native {
using namespace at::native::npu;
SmallVector<int64_t, SIZE> masked_select_npu_output_size(
const Tensor& self,
const Tensor& mask) {
int64_t shape;
shape = mask.sum().item().toInt();
return {shape};
SmallVector<NPUTensorDesc, N> masked_select_npu_input(
const SmallVector<Tensor, N>& inputTensor) {
return CalcuOpUtil::create_npu_input_tensor_desc(inputTensor);
}
Tensor& masked_select_out_npu_nocheck(
SmallVector<NPUTensorDesc, N> masked_select_npu_output(
const SmallVector<Tensor, N>& outputTensor) {
return CalcuOpUtil::create_npu_output_tensor_desc(outputTensor);
}
Tensor& masked_select_out_npu(
Tensor& result,
const Tensor& self,
const Tensor& mask) {
@@ -37,72 +42,40 @@ Tensor& masked_select_out_npu_nocheck(
maskBool = mask.to(at::kBool);
}
// constructs the input and output NPUTensorDesc
auto inputs = masked_select_npu_input({self, maskBool});
auto outputs = masked_select_npu_output({result});
// executing the NPU operator
OpCommand cmd;
cmd.Name("MaskedSelect")
.Input(self)
.Input(maskBool)
.Output(result)
.Run();
CalcuOpUtil::execute_npu_operate("MaskedSelect", inputs, outputs, {});
return result;
}
Tensor& masked_select_out_npu(
Tensor& result,
const Tensor& self,
const Tensor& mask) {
Tensor masked_select_npu(const Tensor& self, const Tensor& mask) {
Tensor dtypeCastOfSelf = self;
Tensor maskCast = mask;
if (maskCast.sizes() != dtypeCastOfSelf.sizes()) {
maskCast = broadcast_npu(mask, dtypeCastOfSelf.sizes());
}
if (dtypeCastOfSelf.scalar_type() == ScalarType::Half) {
dtypeCastOfSelf = dtypeCastOfSelf.npu_dtype_cast(ScalarType::Float);
result = result.to(ScalarType::Float);
}
auto outputSize = masked_select_npu_output_size(dtypeCastOfSelf, maskCast);
OpPreparation::CheckOut(
{dtypeCastOfSelf},
result,
dtypeCastOfSelf,
outputSize);
OpPipeWithDefinedOut pipe;
result = pipe.CheckMemory({dtypeCastOfSelf, maskCast}, {result})
.Func([&dtypeCastOfSelf, &maskCast](Tensor& result)
{masked_select_out_npu_nocheck(result, dtypeCastOfSelf, maskCast);})
.Call(result);
if (result.scalar_type() != self.scalar_type()) {
result = result.npu_dtype_cast(ScalarType::Half);
}
return result;
}
Tensor masked_select_npu(
const Tensor& self,
const Tensor& mask) {
Tensor dtypeCastOfSelf = self;
Tensor maskCast = mask;
if (maskCast.sizes() != dtypeCastOfSelf.sizes()) {
maskCast = broadcast_npu(mask, dtypeCastOfSelf.sizes());
}
if (dtypeCastOfSelf.scalar_type() == ScalarType::Half) {
dtypeCastOfSelf = dtypeCastOfSelf.npu_dtype_cast(ScalarType::Float);
}
auto outputSize = masked_select_npu_output_size(dtypeCastOfSelf, maskCast);
Tensor result = OpPreparation::ApplyTensor(dtypeCastOfSelf, outputSize);
masked_select_out_npu_nocheck(result, dtypeCastOfSelf, maskCast);
Tensor result = at::empty_with_format(
outputSize, dtypeCastOfSelf.options(), CalcuOpUtil::get_tensor_npu_format(self));
masked_select_out_npu(result, dtypeCastOfSelf, maskCast);
if (result.scalar_type() != self.scalar_type()) {
result = result.npu_dtype_cast(ScalarType::Half);
}
return result;
}
} // namespace native
} // namespace at
+8 -19
View File
@@ -67,32 +67,21 @@ tuple<Tensor&, Tensor&> max_out_npu(
}
tuple<Tensor, Tensor> max_npu(const Tensor& self, int64_t dim, bool keepdim) {
Tensor selfCast = self;
if(self.dtype() == ScalarType::Bool || self.dtype() == ScalarType::Int){
selfCast = self.to(ScalarType::Float);
}
SmallVector<int64_t, SIZE> dims = {dim};
auto outputSize = reduce_ops_npu_output_size(selfCast, dims, keepdim);
auto outputSize = reduce_ops_npu_output_size(self, dims, keepdim);
SmallVector<int64_t, SIZE> indicesSize = outputSize;
auto func = [&selfCast, dim, keepdim](Tensor outputs, Tensor indices) {
max_out_npu_nocheck(outputs, indices, selfCast, dim, keepdim);
auto func = [&self, dim, keepdim](Tensor outputs, Tensor indices) {
max_out_npu_nocheck(outputs, indices, self, dim, keepdim);
};
Tensor outputs, indices;
OpPipeWithDefinedMultiOut<Tensor, Tensor> pipe(outputs, indices);
std::tie(outputs, indices) = pipe.ApplyOutputWithSpecailParams<0>(outputSize, selfCast.options(), ACL_FORMAT_ND)
.ApplyOutputWithSpecailParams<1>(indicesSize, selfCast.options().dtype(ScalarType::Int), ACL_FORMAT_ND) // use default format
.Call(func)
.ReflushOutputDtype<1>(ScalarType::Long)
.Return<Tensor, Tensor>();
if(self.dtype() == ScalarType::Bool || self.dtype() == ScalarType::Int){
outputs = outputs.to(self.dtype());
}
return std::tie(outputs, indices);
return pipe.ApplyOutputWithSpecailParams<0>(outputSize, self.options(), ACL_FORMAT_ND)
.ApplyOutputWithSpecailParams<1>(indicesSize, self.options().dtype(ScalarType::Int), ACL_FORMAT_ND) // use default format
.Call(func)
.ReflushOutputDtype<1>(ScalarType::Long)
.Return<Tensor, Tensor>();
}
tuple<Tensor&, Tensor&> max_out_npu(
+8 -19
View File
@@ -67,32 +67,21 @@ tuple<Tensor&, Tensor&> min_out_npu(
}
tuple<Tensor, Tensor> min_npu(const Tensor& self, int64_t dim, bool keepdim) {
Tensor selfCast = self;
if(self.dtype() == ScalarType::Bool){
selfCast = self.to(ScalarType::Float);
}
SmallVector<int64_t, SIZE> dims = {dim};
auto outputSize = reduce_ops_npu_output_size(selfCast, dims, keepdim);
auto outputSize = reduce_ops_npu_output_size(self, dims, keepdim);
SmallVector<int64_t, SIZE> indicesSize = outputSize;
auto func = [&selfCast, dim, keepdim](Tensor outputs, Tensor indices) {
min_out_npu_nocheck(outputs, indices, selfCast, dim, keepdim);
auto func = [&self, dim, keepdim](Tensor outputs, Tensor indices) {
min_out_npu_nocheck(outputs, indices, self, dim, keepdim);
};
Tensor outputs, indices;
OpPipeWithDefinedMultiOut<Tensor, Tensor> pipe(outputs, indices);
std::tie(outputs, indices) = pipe.ApplyOutputWithSpecailParams<0>(outputSize, selfCast.options(), ACL_FORMAT_ND)
.ApplyOutputWithSpecailParams<1>(indicesSize, selfCast.options().dtype(ScalarType::Int), ACL_FORMAT_NCHW)
.Call(func)
.ReflushOutputDtype<1>(ScalarType::Long)
.Return<Tensor, Tensor>();
if(self.dtype() == ScalarType::Bool){
outputs = outputs.to(ScalarType::Bool);
}
return std::tie(outputs, indices);
return pipe.ApplyOutputWithSpecailParams<0>(outputSize, self.options(), ACL_FORMAT_ND)
.ApplyOutputWithSpecailParams<1>(indicesSize, self.options().dtype(ScalarType::Int), ACL_FORMAT_NCHW)
.Call(func)
.ReflushOutputDtype<1>(ScalarType::Long)
.Return<Tensor, Tensor>();
}
tuple<Tensor&, Tensor&> min_out_npu(
+20 -28
View File
@@ -48,25 +48,20 @@ bool is_transpose_last_two_dims_flex(const Tensor& tensor) {
}
SmallVector<NPUTensorDesc, N> mm_npu_input(
const Tensor& self,
bool isSelfT,
const Tensor& mat2,
bool isMat2T) {
Tensor contiguousTensorSelf = self;
Tensor contiguousTensorMat2 = mat2;
const SmallVector<Tensor, N>& inputTensor) {
Tensor contiguousTensor;
SmallVector<NPUTensorDesc, N> inputs;
if (!isSelfT) {
contiguousTensorSelf = NpuUtils::format_contiguous_add_copy_optimize(self);
}
if (!isMat2T) {
contiguousTensorMat2 = NpuUtils::format_contiguous_add_copy_optimize(mat2);
}
for (int i = 0; i < inputTensor.size(); i++) {
// transpose scene is supported by matmul operator.
if (is_transpose_last_two_dims_flex(inputTensor[i])) {
contiguousTensor = inputTensor[i];
} else {
contiguousTensor = NpuUtils::format_contiguous_add_copy_optimize(inputTensor[i]);
}
inputs.emplace_back(NPUTensorDesc(contiguousTensorSelf));
inputs.emplace_back(NPUTensorDesc(contiguousTensorMat2));
inputs.emplace_back(NPUTensorDesc(contiguousTensor));
}
return inputs;
}
@@ -78,29 +73,26 @@ SmallVector<NPUTensorDesc, N> mm_npu_output(
SmallVector<NPUAttrDesc, N> mm_npu_attr(
const Tensor& self,
bool isSelfT,
const Tensor& mat2,
bool isMat2T) {
const Tensor& mat2) {
bool isSelfT = is_transpose_last_two_dims_flex(self);
bool isMat2T = is_transpose_last_two_dims_flex(mat2);
SmallVector<NPUAttrDesc, N> attrs;
NPUAttrDesc npuAttrSelfTranspose = NPUAttrDesc("transpose_x1", isSelfT);
NPUAttrDesc npuAttrMat2Transpose = NPUAttrDesc("transpose_x2", isMat2T);
attrs.emplace_back(NPUAttrDesc("transpose_x1", isSelfT));
attrs.emplace_back(NPUAttrDesc("transpose_x2", isMat2T));
SmallVector<NPUAttrDesc, N> attrs = {
npuAttrSelfTranspose, npuAttrMat2Transpose};
return attrs;
}
Tensor& mm_out_npu(Tensor& result, const Tensor& self, const Tensor& mat2) {
bool isSelfT = is_transpose_last_two_dims_flex(self);
bool isMat2T = is_transpose_last_two_dims_flex(mat2);
// constructs the input and output NPUTensorDesc
auto inputs = mm_npu_input(self, isSelfT, mat2, isMat2T);
auto inputs = mm_npu_input({self, mat2});
auto outputs = mm_npu_output({result});
// constructs the attr of the NPUAttrDesc
auto attrs = mm_npu_attr(self, isSelfT, mat2, isMat2T);
auto attrs = mm_npu_attr(self, mat2);
// executing the NPU operator
CalcuOpUtil::execute_npu_operate("MatMul", inputs, outputs, attrs);
+3 -28
View File
@@ -38,7 +38,7 @@ int64_t calculate_p(optional<Scalar> p) {
// norm.dtype_out
Tensor& norm_out_npu_nocheck(
Tensor& norm_out_npu(
Tensor& out,
const Tensor& self,
optional<Scalar> p,
@@ -80,36 +80,11 @@ Tensor& norm_out_npu(
optional<Scalar> p,
IntArrayRef dim,
bool keepdim) {
auto outputSize = reduce_ops_npu_output_size(self, dim, keepdim);
OpPreparation::CheckOut(
{self},
out,
ACL_FORMAT_ND,
self.scalar_type(),
outputSize);
norm_out_npu_nocheck(out, self, p, dim, keepdim, self.scalar_type());
norm_out_npu(out, self, p, dim, keepdim, self.scalar_type());
return out;
}
Tensor& norm_out_npu(
Tensor& out,
const Tensor& self,
optional<Scalar> p,
IntArrayRef dim,
bool keepdim,
ScalarType dtype) {
auto outputSize = reduce_ops_npu_output_size(self, dim, keepdim);
OpPreparation::CheckOut(
{self},
out,
ACL_FORMAT_ND,
self.scalar_type(),
outputSize);
norm_out_npu_nocheck(out, self, p, dim, keepdim, dtype);
return out;
}
// norm.ScalarOpt_dim_dtype
Tensor norm_npu(
const Tensor& self,
@@ -124,7 +99,7 @@ Tensor norm_npu(
Tensor out = OpPreparation::ApplyTensorWithSizes(outputSize, self.options().dtype(dtype));
// calculate the output result of the NPU
norm_out_npu_nocheck(out, self, p, dim, keepdim, dtype);
norm_out_npu(out, self, p, dim, keepdim, dtype);
return out;
}
@@ -86,6 +86,7 @@ Tensor& normal_out_npu(
if (dtypeCastOfStd.scalar_type() == ScalarType::Half) {
dtypeCastOfStd = dtypeCastOfStd.to(ScalarType::Float);
}
OpCommand cmd;
cmd.Name("Normal")
.Input(dtypeCastOfMean)
@@ -111,8 +112,8 @@ Tensor& normal_out_npu(
if (formatCastOfResult.scalar_type() == ScalarType::Half) {
formatCastOfResult = formatCastOfResult.to(ScalarType::Float);
}
Tensor meanTensor = OpPreparation::ApplyTensor(size, formatCastOfResult.options(), result);
Tensor meanTensor = OpPreparation::ApplyTensor(size, result.options(), result);
meanTensor.fill_(mean);
OpCommand cmd;
cmd.Name("Normal")
@@ -1,6 +1,4 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
// 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.
@@ -13,48 +11,87 @@
// 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"
#include "ATen/native/npu/utils/NpuUtils.h"
#include "ATen/native/npu/utils/KernelNpuOutputSize.h"
#include "ATen/native/npu/utils/OpTemplate.h"
namespace at {
namespace native {
using namespace at::native::npu;
SmallVector<NPUTensorDesc, N> reflection_pad2d_npu_input(SmallVector<Tensor, N> inputs) {
return CalcuOpUtil::create_npu_input_tensor_desc(inputs);
}
SmallVector<int64_t, SIZE> reflection_pad2d_npu_output_size(const Tensor& self, IntArrayRef padding) {
int64_t N = self.size(0);
int64_t C = self.size(1);
int64_t H = self.size(2);
int64_t W = self.size(3);
int64_t padding_l = 0;
int64_t padding_r = 0;
int64_t padding_t = 0;
int64_t padding_b = 0;
SmallVector<NPUTensorDesc, N> reflection_pad2d_npu_output(const SmallVector<Tensor, N> &outputTensor) {
return CalcuOpUtil::create_npu_output_tensor_desc(outputTensor);
}
padding_l = padding[0];
padding_r = padding[1];
padding_t = padding[2];
padding_b = padding[3];
SmallVector<NPUAttrDesc, N> reflection_pad2d_npu_attr(const Tensor& input, IntArrayRef paddingSize) {
int64_t pad_l = 0;
int64_t pad_r = 0;
int64_t pad_t = 0;
int64_t pad_b = 0;
int64_t pad_zeros = 0;
int64_t Ho = H + padding_t + padding_b;
int64_t Wo = W + padding_l + padding_r;
TORCH_CHECK(paddingSize.size() == 4, "padding size is expected to be 4");
SmallVector<int64_t, SIZE> outputSize = {N, C, Ho, Wo};
return outputSize;
pad_l = paddingSize[0];
pad_r = paddingSize[1];
pad_t = paddingSize[2];
pad_b = paddingSize[3];
SmallVector<int64_t, SIZE> vectorInt = {};
SmallVector<SmallVector<int64_t, SIZE>, SIZE> vectorVectorInt = {};
SmallVector<IntArrayRef, SIZE> vectorListInt = {};
SmallVector<int64_t, SIZE> paddingsVector = array_to_small_vector(paddingSize);
paddingsVector.resize(input.dim(), 0);
for (int i = 0; i < paddingsVector.size(); i ++) {
if (i<2) {
vectorInt.emplace_back(pad_zeros);
vectorInt.emplace_back(pad_zeros);
}
else if (i == 2) {
vectorInt.emplace_back(pad_t);
vectorInt.emplace_back(pad_b);
}
else {
vectorInt.emplace_back(pad_l);
vectorInt.emplace_back(pad_r);
}
vectorVectorInt.emplace_back(vectorInt);
vectorInt.clear();
vectorListInt.emplace_back(IntArrayRef(vectorVectorInt.back()));
}
int64_t constant_values = 0;
// string mode = "constant";
string mode = "reflect";
bool padding_contiguous = true;
NPUAttrDesc npuAttrConstantValues = NPUAttrDesc("constant_values", constant_values);
NPUAttrDesc npuAttrMode = NPUAttrDesc("mode", mode);
NPUAttrDesc npuAttrPaddingContiguous = NPUAttrDesc("padding_contiguous", padding_contiguous);
NPUAttrDesc npuAttrPadding = NPUAttrDesc("paddings", vectorListInt);
SmallVector<NPUAttrDesc, N> attrs = {
npuAttrPadding,
npuAttrConstantValues,
npuAttrMode,
npuAttrPaddingContiguous
};
return attrs;
}
Tensor& reflection_pad2d_out_npu_nocheck(Tensor& out, const Tensor& self, IntArrayRef padding) {
TORCH_CHECK(padding.size() == 4, "padding size is expected to be 4");
//constructs the input and output NPUTensorDesc
auto inputs = reflection_pad2d_npu_input({self});
auto outputs = reflection_pad2d_npu_output({out});
//constructs the attr of the NPUAttrDesc
SmallVector<int64_t, N> value_tensor = {(int64_t)0};
OpCommand cmd;
cmd.Name("PadV3")
.Input(self)
.Input(padding, at::kInt)
.Input(value_tensor, self.scalar_type())
.Output(out)
.Attr("mode", (string)"reflect")
.Attr("paddings_contiguous", true)
.Run();
auto attrs = reflection_pad2d_npu_attr(self, padding);
//executing the NPU operator
CalcuOpUtil::execute_npu_operate("PadV3D", inputs, outputs, attrs);
return out;
}
@@ -63,10 +100,12 @@ Tensor& reflection_pad2d_out_npu(Tensor& result, const Tensor& self, IntArrayRef
//calculate the output size
auto outputSize = reflection_pad2d_npu_output_size(self, padding);
//construct the output tensor of the NPU
result = at::empty_with_format(outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
OpPreparation::CheckOut(
{self},
result,
self,
CalcuOpUtil::get_tensor_npu_format(self),
self.scalar_type(),
outputSize);
reflection_pad2d_out_npu_nocheck(result, self, padding);
@@ -74,11 +113,11 @@ Tensor& reflection_pad2d_out_npu(Tensor& result, const Tensor& self, IntArrayRef
}
Tensor reflection_pad2d_npu(const Tensor& self, IntArrayRef padding) {
TORCH_CHECK(padding.size() == 4, "padding size is expected to be 4");
//calculate the output size
auto outputSize = reflection_pad2d_npu_output_size(self, padding);
//construct the output tensor of the NPU
Tensor out = OpPreparation::ApplyTensor(self, outputSize);
Tensor out = at::empty_with_format(outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
//calculate the output result of the NPU
reflection_pad2d_out_npu_nocheck(out, self, padding);
@@ -1,42 +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"
namespace at {
namespace native {
using namespace at::native::npu;
Tensor rrelu_with_noise_backward_npu(
const Tensor& grad_output,
const Tensor& self_or_result,
const Tensor& noise,
Scalar lower,
Scalar upper,
bool training,
bool is_result) {
auto folat_lower = lower.toFloat();
auto float_upper = upper.toFloat();
if (training && (float_upper - folat_lower > 1E-6)) {
return grad_output.mul(noise);
} else {
Scalar negative_slope = (folat_lower + float_upper) / 2;
return at::leaky_relu_backward(grad_output, self_or_result, negative_slope, is_result);
}
}
} // namespace native
} // namespace at
@@ -1,105 +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/core/DistributionsHelper.h>
namespace at {
namespace native {
using namespace at::native::npu;
void _rrelu_with_noise_train(
Tensor& output,
const Tensor& input,
const Tensor& noise,
Scalar lower_,
Scalar upper_,
Generator* generator) {
float lower = lower_.toFloat();
float upper = upper_.toFloat();
auto shape = output.sizes();
auto noise_shape = noise.sizes();
Tensor tmp_tensor = output.contiguous();
Tensor output_data = tmp_tensor.reshape({output.numel()});
Tensor input_data = input.reshape({input.numel()});
Tensor tmp_noise = noise;
tmp_noise = tmp_noise.reshape({tmp_noise.numel()});
auto gen = at::get_generator_or_default<CPUGenerator>(generator, detail::getDefaultCPUGenerator());
for (int64_t i = 0; i < input.numel(); i++) {
if (input_data[i].item().toFloat() <= 0) {
at::uniform_real_distribution<double> uniform(lower, upper);
const float r = uniform(gen);
output_data[i] = input_data[i] * r;
tmp_noise[i] = r;
} else {
tmp_noise[i] = 1;
output_data[i] = input_data[i];
}
}
if (!output.is_contiguous()) {
output.copy_(tmp_tensor);
}
tmp_noise.reshape(noise_shape);
noise.copy_(tmp_noise);
output.reshape(shape);
}
Tensor rrelu_with_noise_npu(
const Tensor& self,
const Tensor& noise,
Scalar lower,
Scalar upper,
bool training,
Generator* generator) {
auto output = at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
return rrelu_with_noise_out_npu(output, self, noise, lower, upper, training, generator);
}
Tensor& rrelu_with_noise_npu_(
Tensor& self,
const Tensor& noise,
Scalar lower,
Scalar upper,
bool training,
Generator* generator) {
return rrelu_with_noise_out_npu(self, self, noise, lower, upper, training, generator);
}
Tensor& rrelu_with_noise_out_npu(
Tensor& output,
const Tensor& self,
const Tensor& noise,
Scalar lower,
Scalar upper,
bool training,
Generator* generator) {
if (training) {
_rrelu_with_noise_train(output, self.contiguous(), noise, lower, upper, generator);
return output;
} else {
auto float_lower = lower.toFloat();
auto float_upper = upper.toFloat();
Scalar negative_slope = (float_lower + float_upper) / 2;
return at::leaky_relu_out(output, self, negative_slope);
}
}
} // namespace native
} // namespace at
@@ -15,7 +15,6 @@
// limitations under the License.
#include "ATen/native/npu/utils/OpAdapter.h"
#include "ATen/native/npu/utils/CalcuOpUtil.h"
namespace at {
namespace native {
@@ -38,17 +37,16 @@ Tensor& scatter_npu_(
}
Tensor src = src_ex;
if (src.scalar_type() != self.scalar_type()) {
src = src.npu_dtype_cast(self.scalar_type());
if (src.scalar_type() == ScalarType::Half) {
src = src.npu_dtype_cast(ScalarType::Float);
}
OpCommand cmd;
cmd.Name("ScatterElements")
.Input(self)
cmd.Name("ScatterTensor")
.Input(index)
.Input(src)
.Output(self)
.Attr("axis", dim)
.Attr("dim", dim)
.Run();
if(self.scalar_type() != selfType){
@@ -73,21 +71,13 @@ Tensor& scatter_npu_(
if (index.scalar_type() == ScalarType::Half) {
index = index.npu_dtype_cast(ScalarType::Float);
}
Tensor srcTensor = scalar_to_tensor(src).to(ScalarType::Float);
srcTensor = CalcuOpUtil::copy_tensor_host_to_device(srcTensor);
Tensor srcTensor_broadcast = at::npu_broadcast(srcTensor, array_to_small_vector(index.sizes()));
if (srcTensor_broadcast.scalar_type() != self.scalar_type()) {
srcTensor_broadcast = srcTensor_broadcast.npu_dtype_cast(self.scalar_type());
}
OpCommand cmd;
cmd.Name("ScatterElements")
.Input(self)
cmd.Name("ScatterScalar")
.Input(index)
.Input(srcTensor_broadcast)
.Output(self)
.Attr("axis", dim)
.Attr("dim", dim)
.Attr("value", src)
.Run();
if(self.scalar_type() != selfType){
@@ -25,14 +25,6 @@ Tensor& smooth_l1_loss_out_npu_nocheck(
const Tensor& self,
const Tensor& target,
int64_t reduction) {
//Check the self empty
if (self.numel()==0) {
// In this scenario, needs to return nan. And the nan of the NPU can only be fp32.
result = result.to(at::kFloat).fill_(0);
result = result / 0;
return result;
}
string reductionStr;
if (reduction == Reduction::None) {
reductionStr = "none";
@@ -30,25 +30,12 @@ Tensor softmax_backward_out_npu(
SmallVector<int64_t, N> dimList = {dim};
// executing the NPU operator
OpCommand cmd;
if (CalcuOpUtil::get_tensor_npu_format(output) == ACL_FORMAT_FRACTAL_NZ) {
float one = 1.;
Tensor one_tensor = CalcuOpUtil::CopyScalarToDevice(one, grad_output.scalar_type());
cmd.Name("SoftmaxGradExt")
.Input(grad_output)
.Input(output)
.Input(one_tensor)
.Output(grad_input)
.Attr("axes", dimList)
.Attr("keep_dims", true)
.Run();
} else {
cmd.Name("SoftmaxGrad")
.Input(output)
.Input(grad_output)
.Output(grad_input)
.Attr("axes", dimList)
.Run();
}
cmd.Name("SoftmaxGrad")
.Input(output)
.Input(grad_output)
.Output(grad_input)
.Attr("axes", dimList)
.Run();
return grad_input;
}
@@ -74,7 +74,7 @@ Tensor stack_npu(TensorList tensors, int64_t dim) {
Tensor result = at::empty_with_format(
outputSize,
tensors[0].options(),
ACL_FORMAT_ND);
CalcuOpUtil::get_tensor_npu_format(tensors[0]));
// calculate the output result of the NPU
stack_out_npu_nocheck(result, tensors, dim);
@@ -1,108 +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"
namespace at {
namespace native {
using namespace at::native::npu;
int64_t batch_count(const Tensor& batched_matrices) {
int64_t result = 1;
for (int64_t i = 0; i < batched_matrices.ndimension() - 2; i++) {
result *= batched_matrices.size(i);
}
return result;
}
void single_check_errors(int64_t info, const char* name, bool allow_singular=false, int64_t batch_idx=-1) {
std::string batch_info = "";
if (batch_idx >= 0) {
batch_info = ": For batch " + std::to_string(batch_idx);
}
if (info < 0) {
AT_ERROR(name, batch_info, ": Argument ", -info, " has illegal value");
} else if (info > 0) {
if (strstr(name, "svd")) {
AT_ERROR(name, ": the updating process of SBDSDC did not converge (error: ", info, ")");
} else if (strstr(name, "symeig")) {
AT_ERROR(name, batch_info, ": the algorithm failed to converge; ", info,
" off-diagonal elements of an intermediate tridiagonal form did not converge to zero.");
} else if (!allow_singular) {
AT_ERROR(name, batch_info, ": U(", info, ",", info, ") is zero, singular U.");
}
}
}
void batch_check_errors(std::vector<int64_t>& infos, const char* name, bool allow_singular=false) {
for (size_t i = 0; i < infos.size(); i++) {
auto info = infos[i];
single_check_errors(info, name, allow_singular, i);
}
}
std::tuple<Tensor, Tensor, Tensor> _svd_helper_npu(const Tensor& self, bool some, bool compute_uv) {
TORCH_CHECK(self.dtype() == at::kFloat, "svd_npu only supported Float, but get", self.dtype());
std::vector<int64_t> infos(batch_count(self), 0);
int64_t m = self.size(-2);
int64_t n = self.size(-1);
int64_t k = std::min(m, n);
Tensor U_working_copy, S_working_copy, VT_working_copy;
auto sizes = self.sizes().vec();
sizes[self.dim() - 1] = (compute_uv && some) ? std::min(m, n) : m;
U_working_copy = OpPreparation::ApplyTensor(self, sizes);
sizes[self.dim() - 2] = n;
sizes[self.dim() - 1] = (compute_uv && some) ? k : n;
VT_working_copy = OpPreparation::ApplyTensor(self, sizes);
sizes.pop_back();
sizes[self.dim() - 2] = std::min(m, n);
S_working_copy = OpPreparation::ApplyTensor(self, sizes);
if (self.numel() > 0) {
OpCommand cmd;
cmd.Name("Svd")
.Input(self)
.Output(S_working_copy)
.Output(U_working_copy)
.Output(VT_working_copy)
.Attr("compute_uv", compute_uv)
.Attr("full_matrices", !some)
.Run();
if (self.dim() > 2) {
batch_check_errors(infos, "svd_npu");
} else {
single_check_errors(infos[0], "svd_npu");
}
if (!compute_uv) {
VT_working_copy.zero_();
U_working_copy.zero_();
}
} else {
U_working_copy.zero_();
VT_working_copy.zero_();
}
return std::make_tuple(U_working_copy, S_working_copy, VT_working_copy);
}
}
}
@@ -1,50 +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/NamedTensorUtils.h>
namespace at {
namespace native {
using namespace at::native::npu;
std::tuple<Tensor, Tensor> _symeig_helper_npu(const Tensor& self, bool eigenvectors, bool upper) {
auto self_sizes = self.sizes().vec();
self_sizes.pop_back();
auto eigvals = at::empty(self_sizes, self.options());
if (self.numel() == 0) {
return std::tuple<Tensor, Tensor>(eigvals, at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT));
}
auto self_working_copy = self.clone();
OpCommand cmd;
cmd.Name("SelfAdjointEig")
.Input(self)
.Output(eigvals)
.Output(self_working_copy)
.Attr("compute_v", true)
.Run();
if (eigenvectors) {
return std::tuple<Tensor, Tensor>(eigvals, self_working_copy);
} else {
return std::tuple<Tensor, Tensor>(eigvals, at::empty({0}, self.options()));
}
}
} // namespace native
} // namespace at
+3 -33
View File
@@ -197,7 +197,7 @@ tuple<Tensor&, Tensor&> large_topk_out_npu(
return std::tie(values, indices);
}
tuple<Tensor&, Tensor&> topk_out_npu_nocheck(
tuple<Tensor&, Tensor&> topk_out_npu(
Tensor& values,
Tensor& indices,
const Tensor& self,
@@ -250,36 +250,6 @@ tuple<Tensor&, Tensor&> topk_out_npu_nocheck(
return tuple<Tensor&, Tensor&>(values, indices);
}
tuple<Tensor&, Tensor&> topk_out_npu(
Tensor& values,
Tensor& indices,
const Tensor& self,
int64_t k,
int64_t dim,
bool largest,
bool sorted) {
Tensor selfCp = OpPreparation::CastBackToOriFormat(self);
// calculate the output size
auto outputSize = topk_npu_output_size(selfCp, k, dim, largest, sorted);
SmallVector<int64_t, SIZE> indicesSize = outputSize;
// calculate the output result of the NPU
auto func = [&selfCp, k, dim, largest, sorted](Tensor& values, Tensor& indices) {
topk_out_npu_nocheck(values, indices, selfCp, k, dim, largest, sorted);
};
Tensor indices_tmp;
OpPipeWithMultiOut<Tensor&, Tensor&> pipe(values, indices_tmp);
return pipe.FixOutputSizeAndFormat<0>({selfCp}, selfCp, CalcuOpUtil::get_tensor_npu_format(selfCp), outputSize)
.ApplyOutputWithSpecailParams<1>(indicesSize, selfCp.options().dtype(kInt), ACL_FORMAT_ND)
.Call(func)
.ReflushOutputDtype<1>(ScalarType::Long)
.FixOutputExceptDtype<1>({selfCp}, ACL_FORMAT_ND, ScalarType::Long, indicesSize)
.FixOutputWithReplace<1>(indices)
.ReturnRef<Tensor&, Tensor&>();
}
tuple<Tensor, Tensor> topk_npu(
const Tensor& self,
int64_t k,
@@ -296,7 +266,7 @@ tuple<Tensor, Tensor> topk_npu(
outputSize, selfCp.options().dtype(kInt), ACL_FORMAT_ND);
// calculate the output result of the NPU
topk_out_npu_nocheck(values, indices, selfCp, k, dim, largest, sorted);
topk_out_npu(values, indices, selfCp, k, dim, largest, sorted);
// indices dtype transform Int64
indices = indices.to(at::kLong);
@@ -305,4 +275,4 @@ tuple<Tensor, Tensor> topk_npu(
}
} // namespace native
} // namespace at
} // namespace at
@@ -31,7 +31,7 @@ Tensor& transpose_out_npu(
OpCommand cmd;
cmd.Name("Transpose")
.Input(self)
.Input(perm)
.Input(perm, at::kInt)
.Output(result)
.Run();
} else {

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