Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cd9812281 | ||
|
|
01acfc970f | ||
|
|
d315f8d97d | ||
|
|
c559cf795f | ||
|
|
467a2966d2 | ||
|
|
4667694e3d | ||
|
|
6ab2e3a763 | ||
|
|
45963d6328 | ||
|
|
07900dd748 | ||
|
|
a1e78535ac | ||
|
|
546cacc078 | ||
|
|
f232fb98a5 | ||
|
|
4bc56dc633 | ||
|
|
3503cf36bc | ||
|
|
d6be04857a | ||
|
|
44553555b7 | ||
|
|
7667c75f70 | ||
|
|
e0688a49f2 | ||
|
|
3139f7434e | ||
|
|
65a34ea62a | ||
|
|
84d41d6b89 | ||
|
|
693a3ca406 | ||
|
|
6215cff0b6 | ||
|
|
952cf683ec | ||
|
|
4b4ea01275 | ||
|
|
14aac97251 | ||
|
|
1d095d14c8 | ||
|
|
2e48493182 | ||
|
|
f9953c4b44 | ||
|
|
bec31ca25c | ||
|
|
bb3ef86eab | ||
|
|
74bdfcd69d | ||
|
|
c95df4bd03 | ||
|
|
46ac6d1bc1 | ||
|
|
cb99fcd39a | ||
|
|
e2d155ee32 | ||
|
|
e304769ef4 | ||
|
|
43904c2582 | ||
|
|
ede2d83ff6 | ||
|
|
a3e9cf47e6 | ||
|
|
434bce5cb4 | ||
|
|
f6b2609555 | ||
|
|
b816cca312 | ||
|
|
c190d7f377 | ||
|
|
7842f91b40 | ||
|
|
8e794d254b | ||
|
|
7eaee6a04f | ||
|
|
5a41e76c8e | ||
|
|
e78e5bf6b4 | ||
|
|
95e7b2d7b9 | ||
|
|
17c1bb71ec | ||
|
|
b70ff16868 | ||
|
|
056821c723 | ||
|
|
6e79ae29a5 | ||
|
|
026f29193b | ||
|
|
fc71ddd8ce | ||
|
|
3fba9fc551 | ||
|
|
e501579435 | ||
|
|
e6276b9370 | ||
|
|
5a4d350ede | ||
|
|
792299e9aa | ||
|
|
cf2a39e1a4 | ||
|
|
53e2d6a39d | ||
|
|
00300f6584 | ||
|
|
f7bb302789 | ||
|
|
cc3a5ff520 | ||
|
|
b7b38e036e | ||
|
|
898a546690 | ||
|
|
0ae38cdac4 | ||
|
|
79921ee37e | ||
|
|
2d1a3ad39d | ||
|
|
5a0029e1ea | ||
|
|
595f5a215b | ||
|
|
6739f38785 | ||
|
|
20a5a6d574 | ||
|
|
8e2647f5cd | ||
|
|
1936f65838 | ||
|
|
d5d5c93290 | ||
|
|
58033698c4 | ||
|
|
df1a2e030f |
@@ -3,8 +3,6 @@ approvers:
|
||||
- nalinaly
|
||||
- weili10
|
||||
reviewers:
|
||||
- tgsmdww
|
||||
- zhou_sinan
|
||||
- shibo19
|
||||
- Ronnie_zheng
|
||||
- xiaxia3
|
||||
@@ -13,10 +11,7 @@ reviewers:
|
||||
- td__lihan
|
||||
- ascendzyj
|
||||
- wudingyuan
|
||||
- wangyu0516
|
||||
- yskhhh
|
||||
- lvpeiyuan
|
||||
- xchu42
|
||||
- matrixplayer
|
||||
- li_jing_hw
|
||||
- wangjiangben_hw
|
||||
|
||||
@@ -30,19 +30,22 @@ apt-get install -y gcc==7.3.0 cmake==3.12.0
|
||||
|
||||
|
||||
# Ascend配套软件
|
||||
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 | Gitee分支名称 |
|
||||
| :------------ | :----------- | :----------- | ------------- |
|
||||
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
|
||||
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
|
||||
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
|
||||
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 | Gitee分支名称 | AscendHub镜像版本 |
|
||||
| :------------ | :----------- | :----------- | ------------- | ------------- |
|
||||
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 | 21.0.2 |
|
||||
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 | 21.0.3 |
|
||||
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 | 21.0.4 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 | 22.0.RC1 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 | \ |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 | 22.0.RC2 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 | 22.0.RC2-1.8.1 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.5.0.post7 | v1.5.0-3.0.rc3 | \ |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 | 22.0.RC3-1.8.1 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.11.0.rc1 | v1.11.0-3.0.rc3 | \ |
|
||||
|
||||
# 安装方式
|
||||
|
||||
## 安装Pytorch依赖环境
|
||||
## 安装PyTorch依赖环境
|
||||
|
||||
如果使用非root用户安装,用户需要在本步骤的每句命令后加**--user**,示例如:pip3 install pyyaml --user。
|
||||
|
||||
@@ -57,17 +60,19 @@ pip3 install wheel
|
||||
|
||||
```sh
|
||||
#x86_64
|
||||
pip3 install torch==1.8.1+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
|
||||
pip3 install torch==1.11.0+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
|
||||
|
||||
#aarch64
|
||||
#社区未提供arm架构cpu安装包,请参见FAQ第一条,使用源码编译安装pytorch
|
||||
#aarch64(推荐使用镜像)
|
||||
可在docker中使用AscendHub镜像仓库提供的基于PyTorch版本制作的基础镜像,包含训练、转换和推理等功能。
|
||||
#镜像仓库地址:(https://ascendhub.huawei.com/#/detail/pytorch-modelzoo)
|
||||
#社区未提供arm架构cpu安装包,如需尝试编译安装PyTorch框架,可参见FAQ第一条,使用源码编译安装pytorch。
|
||||
```
|
||||
|
||||
编译生成pytorch插件的二进制安装包。
|
||||
|
||||
```
|
||||
# 下载master分支代码,进入插件根目录
|
||||
git clone -b master https://gitee.com/ascend/pytorch.git
|
||||
# 下载v1.11.0-3.0.rc3分支代码,进入插件根目录
|
||||
git clone -b v1.11.0-3.0.rc3 https://gitee.com/ascend/pytorch.git
|
||||
cd pytorch
|
||||
# 指定python版本编包方式:
|
||||
bash ci/build.sh --python=3.7
|
||||
@@ -80,7 +85,7 @@ bash ci/build.sh --python=3.9
|
||||
然后安装pytorch/dist下生成的插件torch_npu包,{arch}为架构名称。
|
||||
|
||||
```
|
||||
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
|
||||
pip3 install --upgrade dist/torch_npu-1.11.0rc3-cp37-cp37m-linux_{arch}.whl
|
||||
```
|
||||
|
||||
下载torchvision。
|
||||
@@ -141,7 +146,7 @@ python3 test_div.py
|
||||
|
||||
# 安装混合精度模块(可选)
|
||||
|
||||
AscendPyTorch1.8.1集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
|
||||
AscendPyTorch1.11.0集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
|
||||
|
||||
- AMP
|
||||
- 动态loss scale:动态计算loss scale的值并判断是否溢出。
|
||||
@@ -186,25 +191,32 @@ Ascend PyTorch的版本分支有以下几种维护阶段:
|
||||
| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained <br> 2023-01-15 estimated | |
|
||||
| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained <br> 2023-04-10 estimated | |
|
||||
| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained <br> 2023-07-15 estimated | |
|
||||
| **v3.0.rc3** | Maintained | 2022-10-20 | Unmaintained <br> 2023-10-20 estimated | |
|
||||
|
||||
# FAQ
|
||||
|
||||
## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch1.8.1,需要使用源码编译安装。
|
||||
## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch,需要使用源码编译安装。
|
||||
|
||||
下载PyTorch v1.8.1源码包。
|
||||
下载PyTorch v1.11.0源码包。
|
||||
|
||||
```
|
||||
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
|
||||
git clone -b v1.11.0 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.11.0
|
||||
```
|
||||
|
||||
进入源码包获取被动依赖代码。
|
||||
|
||||
```
|
||||
cd pytorch_v1.8.1
|
||||
cd pytorch_v1.11.0
|
||||
git submodule sync
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
配置环境变量
|
||||
|
||||
```
|
||||
export USE_XNNPACK=0
|
||||
```
|
||||
|
||||
执行编译安装。
|
||||
|
||||
```
|
||||
@@ -485,7 +497,7 @@ warning如下图所示,由Tensor.set_data浅拷贝操作触发。主要原因
|
||||
|
||||
该warning不影响模型的精度和性能,可以忽略。
|
||||
|
||||
待NPU 设备号合入社区或者后续Pytorch版本`_has_compatible_shallow_copy_type`注册方式发生变动,该warning会被解决。
|
||||
待NPU 设备号合入社区或者后续PyTorch版本`_has_compatible_shallow_copy_type`注册方式发生变动,该warning会被解决。
|
||||
|
||||

|
||||
|
||||
@@ -493,9 +505,53 @@ warning如下图所示,由Tensor.set_data浅拷贝操作触发。主要原因
|
||||
|
||||
验证torch_npu的引入,请切换至其他目录进行,在编译目录执行会提示如下错误。
|
||||
|
||||
|
||||
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
|
||||
|
||||
## 在执行import torch_npu时出现ModuleNotFooundError: NO module named '_lzma'报错问题
|
||||
|
||||
在python命令行下,执行import torch_npu测试时,出现ModuleNotFooundError: NO module named '_lzma'问题,可能由于Python环境失效,重装Python即可。<img src="figures/QA.png" />
|
||||
|
||||
## 编译过程中出现XNNPACK相关的Make Error报错
|
||||
|
||||
编译原生pytorch时,未配置相关环境变量,导致编译不成功。
|
||||
|
||||

|
||||
|
||||
1. 执行命令设置环境变量
|
||||
|
||||
```
|
||||
export USE_XNNPACK=0
|
||||
```
|
||||
|
||||
2. 执行命令清除当前编译内容
|
||||
|
||||
```
|
||||
make clean
|
||||
```
|
||||
|
||||
3. 重新编译
|
||||
|
||||
## 编译时出现Breakpad error: field 'regs' has incomplete type 'google_breakpad::user_regs_struct'报错
|
||||
|
||||
编译原生pytorch时,未配置相关环境变量,导致编译不成功。
|
||||
|
||||
1. 执行命令配置环境变量
|
||||
|
||||
```
|
||||
export BUILD_BREAKPAD=0
|
||||
```
|
||||
|
||||
2. 执行命令清除当前编译内容
|
||||
|
||||
```
|
||||
make clean
|
||||
```
|
||||
|
||||
3. 重新编译
|
||||
|
||||
## 多卡训练初始化阶段卡顿至超时
|
||||
|
||||
init_process_group 函数中使用了IPV6地址,例如::1(注意localhost 可能指向IPv6的地址),使用IPv4可以避免这个问题
|
||||
# 版本说明
|
||||
|
||||
版本说明请参阅[ReleseNote](docs/zh/RELEASENOTE)
|
||||
@@ -856,7 +856,7 @@ if [ -d ${install_path}/toolkit ]; then
|
||||
export ASCEND_OPP_PATH=${install_path}/opp
|
||||
else
|
||||
if [ -d ${install_path}/nnae/latest ];then
|
||||
exportLD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
|
||||
export LD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
|
||||
export PATH=$PATH:${install_path}/nnae/latest/fwkacllib/ccec_compiler/bin/:${install_path}/nnae/latest/toolkit/tools/ide_daemon/bin/
|
||||
export ASCEND_OPP_PATH=${install_path}/nnae/latest/opp/
|
||||
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
|
||||
|
||||
@@ -52,6 +52,9 @@ apt-get install -y gcc==7.3.0 cmake==3.12.0
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.5.0.post7 | v1.5.0-3.0.rc3 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.11.0.rc1 | v1.11.0-3.0.rc3 |
|
||||
|
||||
# 安装方式<a name="安装方式"></a>
|
||||
|
||||
@@ -70,7 +73,7 @@ pip3 install wheel
|
||||
|
||||
```sh
|
||||
#x86_64
|
||||
pip3 install torch==1.8.1+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
|
||||
pip3 install torch==1.11.0+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
|
||||
|
||||
#aarch64
|
||||
#社区未提供arm架构cpu安装包,请参见FAQ第一条,使用源码编译安装pytorch
|
||||
@@ -79,8 +82,8 @@ pip3 install torch==1.8.1+cpu #若使用pip命令安装cpu版本PyTorch报错,
|
||||
编译生成pytorch插件的二进制安装包。
|
||||
|
||||
```
|
||||
# 下载master分支代码,进入插件根目录
|
||||
git clone -b master https://gitee.com/ascend/pytorch.git
|
||||
# 下载v1.11.0-3.0.rc3分支代码,进入插件根目录
|
||||
git clone -b v1.11.0-3.0.rc3 https://gitee.com/ascend/pytorch.git
|
||||
cd pytorch
|
||||
# 指定python版本编包方式:
|
||||
bash ci/build.sh --python=3.7
|
||||
@@ -93,7 +96,7 @@ bash ci/build.sh --python=3.9
|
||||
然后安装pytorch/dist下生成的插件torch_npu包,{arch}为架构名称。
|
||||
|
||||
```
|
||||
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
|
||||
pip3 install --upgrade dist/torch_npu-1.11.0rc3-cp37-cp37m-linux_{arch}.whl
|
||||
```
|
||||
下载torchvision。
|
||||
```
|
||||
@@ -153,7 +156,7 @@ python3 test_div.py
|
||||
|
||||
# 安装混合精度模块(可选)<a name="安装混合精度模块(可选)"></a>
|
||||
|
||||
AscendPyTorch1.8.1集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
|
||||
AscendPyTorch1.11.0集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
|
||||
|
||||
- AMP
|
||||
|
||||
@@ -170,18 +173,18 @@ AscendPyTorch1.8.1集成了AMP模块,也可用于混合精度训练等应用
|
||||
|
||||
# FAQ<a name="FAQ"></a>
|
||||
|
||||
## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch1.8.1,需要使用源码编译安装。
|
||||
## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch1.11.0,需要使用源码编译安装。
|
||||
|
||||
下载PyTorch v1.8.1源码包。
|
||||
下载PyTorch v1.11.0源码包。
|
||||
|
||||
```
|
||||
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
|
||||
git clone -b v1.11.0 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.11.0
|
||||
```
|
||||
|
||||
进入源码包获取被动依赖代码。
|
||||
|
||||
```
|
||||
cd pytorch_v1.8.1
|
||||
cd pytorch_v1.11.0
|
||||
git submodule sync
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
@@ -475,8 +478,53 @@ warning如下图所示,由Tensor.set_data浅拷贝操作触发。主要原因
|
||||
|
||||
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
|
||||
|
||||
## 在执行import torch_npu时出现ModuleNotFooundError: NO module named '_lzma'报错问题
|
||||
|
||||
在python命令行下,执行import torch_npu测试时,出现ModuleNotFooundError: NO module named '_lzma'问题,可能由于Python环境失效,重装Python即可。<img src="figures/QA.png" />
|
||||
|
||||
## 编译过程中出现XNNPACK相关的Make Error报错
|
||||
|
||||
编译原生pytorch时,未配置相关环境变量,导致编译不成功。
|
||||
|
||||

|
||||
|
||||
1. 执行命令设置环境变量
|
||||
|
||||
```
|
||||
export USE_XNNPACK=0
|
||||
```
|
||||
|
||||
2. 执行命令清除当前编译内容
|
||||
|
||||
```
|
||||
make clean
|
||||
```
|
||||
|
||||
3. 重新编译
|
||||
|
||||
## 编译时出现Breakpad error: field 'regs' has incomplete type 'google_breakpad::user_regs_struct'报错
|
||||
|
||||
编译原生pytorch时,未配置相关环境变量,导致编译不成功。
|
||||
|
||||
1. 执行命令配置环境变量
|
||||
|
||||
```
|
||||
export BUILD_BREAKPAD=0
|
||||
```
|
||||
|
||||
2. 执行命令清除当前编译内容
|
||||
|
||||
```
|
||||
make clean
|
||||
```
|
||||
|
||||
3. 重新编译
|
||||
|
||||
## 多卡训练初始化阶段卡顿至超时
|
||||
|
||||
init_process_group 函数中使用了IPV6地址,例如::1(注意localhost 可能指向IPv6的地址),使用IPv4可以避免这个问题
|
||||
|
||||
|
||||
# 版本说明<a name='版本说明'></a>
|
||||
|
||||
版本说明请参阅[ReleseNote](https://gitee.com/ascend/pytorch/blob/master/docs/zh/RELEASENOTE/RELEASENOTE.md)
|
||||
版本说明请参阅[ReleseNote](https://gitee.com/ascend/pytorch/blob/v1.11.0-3.0.rc3/docs/zh/RELEASENOTE/RELEASENOTE.md)
|
||||
|
||||
|
After Width: | Height: | Size: 377 KiB |
|
After Width: | Height: | Size: 288 KiB |
@@ -846,7 +846,7 @@ if [ -d ${install_path}/toolkit ]; then
|
||||
export ASCEND_OPP_PATH=${install_path}/opp
|
||||
else
|
||||
if [ -d ${install_path}/nnae/latest ];then
|
||||
exportLD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
|
||||
export LD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
|
||||
export PATH=$PATH:${install_path}/nnae/latest/fwkacllib/ccec_compiler/bin/:${install_path}/nnae/latest/toolkit/tools/ide_daemon/bin/
|
||||
export ASCEND_OPP_PATH=${install_path}/nnae/latest/opp/
|
||||
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
- [获取PyTorch源码](#获取PyTorch源码md)
|
||||
- [注册算子开发](#注册算子开发md)
|
||||
- [概述](#概述md)
|
||||
- [PyTorch1.8.1 注册算子开发](#PyTorch1-8-1-注册算子开发md)
|
||||
- [PyTorch1.11.0 注册算子开发](#PyTorch1-8-1-注册算子开发md)
|
||||
- [算子适配插件开发](#算子适配插件开发md)
|
||||
- [编译和安装PyTorch框架](#编译和安装PyTorch框架md)
|
||||
- [算子功能验证](#算子功能验证md)
|
||||
@@ -29,7 +29,7 @@
|
||||
- [自定义算子导出方法](#自定义算子导出方法md)
|
||||
<h2 id="简介md">简介</h2>
|
||||
|
||||
### 概述<a name="zh-cn_topic_0000001125558589_section7405182695312"></a>
|
||||
## 概述<a name="zh-cn_topic_0000001125558589_section7405182695312"></a>
|
||||
|
||||
为了实现PyTorch深度学习框架在昇腾AI处理器上运行,需要将框架算子用TBE自定义开发。
|
||||
|
||||
@@ -167,7 +167,7 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
|
||||
- 当前昇腾AI处理器中支持的算子以及对应的算子约束可以通过以下两种方式查询。
|
||||
- 命令行开发方式下,您可以参见《CANN 算子清单 \(Ascend 910\)》进行离线查询。
|
||||
- MindStudio开发方式下,您可以通过MindStudio进行在线查询,详细查看方法可参见《MindStudio 用户指南》中的“算子&模型速查”章节。
|
||||
- 当前PyTorch适配的算子列表可以参见[《PyTorch API支持清单》](https://gitee.com/ascend/pytorch/blob/master/docs/zh/PyTorch%20API%E6%94%AF%E6%8C%81%E6%B8%85%E5%8D%95.md)。
|
||||
- 当前PyTorch适配的算子列表可以参见[《PyTorch API支持清单》](https://gitee.com/ascend/pytorch/blob/v1.11.0-3.0.rc3/docs/zh/PyTorch%20API%E6%94%AF%E6%8C%81%E6%B8%85%E5%8D%95.md)。
|
||||
|
||||
<h2 id="算子适配开发md">算子适配开发</h2>
|
||||
|
||||
@@ -189,18 +189,18 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
|
||||
|
||||
<h3 id="获取PyTorch源码md">获取PyTorch源码</h3>
|
||||
|
||||
针对pytorch1.8.1版本,PyTorch源码获取请参见[《PyTorch安装指南》](https://gitee.com/ascend/pytorch/blob/master/docs/zh/PyTorch%E5%AE%89%E8%A3%85%E6%8C%87%E5%8D%97/PyTorch%E5%AE%89%E8%A3%85%E6%8C%87%E5%8D%97.md)中“安装PyTorch框架”章节,完成在"pytorch/pytorch_v1.8.1"目录生成适配昇腾AI处理器的全量代码步骤。将在pytorch/pytorch目录中进行PyTorch 算子适配开发。
|
||||
针对pytorch1.11.0版本,PyTorch源码获取请参见[《PyTorch安装指南》](https://gitee.com/ascend/pytorch/blob/v1.11-3.0.rc3/docs/zh/PyTorch%E5%AE%89%E8%A3%85%E6%8C%87%E5%8D%97/PyTorch%E5%AE%89%E8%A3%85%E6%8C%87%E5%8D%97.md)中“安装PyTorch框架”章节,完成在"pytorch/pytorch_v1.11.0"目录生成适配昇腾AI处理器的全量代码步骤。将在pytorch/pytorch目录中进行PyTorch 算子适配开发。
|
||||
|
||||
<h3 id="注册算子开发md">注册算子开发</h3>
|
||||
|
||||
- **[概述](#概述md)**
|
||||
|
||||
- **[PyTorch1.8.1 注册算子开发](#PyTorch1-8-1-注册算子开发md)**
|
||||
- **[PyTorch1.11.0 注册算子开发](#PyTorch1-8-1-注册算子开发md)**
|
||||
|
||||
|
||||
<h4 id="概述md">概述</h4>
|
||||
|
||||
当前制定的NPU适配派发原则是NPU算子的派发不经过框架公共函数,直接派发成NPU适配的函数,即算子执行调用栈中只包含NPU适配的函数调用,不包含框架公共函数。PyTorch框架在编译时,会根据 native\_functions.yaml 的定义,按框架中定义的类型和设备分发原则,生成相应的新算子的中间层的调用说明。对于NPU,会生成在 build/aten/src/ATen/NPUType.cpp。
|
||||
当前制定的NPU适配派发原则是NPU算子的派发不经过框架公共函数,直接派发成NPU适配的函数,即算子执行调用栈中只包含NPU适配的函数调用,不包含框架公共函数。PyTorch框架在编译时,会根据 native\_functions.yaml 的定义,按框架中定义的类型和设备分发原则,生成相应的新算子的中间层的调用说明。对于NPU,会生成在torch_npu/csrc/aten/RegisterNPU.cpp。
|
||||
|
||||
<h4 id="PyTorch1-8-1-注册算子开发md">PyTorch1.8.1 注册算子开发</h4>
|
||||
|
||||
@@ -208,7 +208,7 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
|
||||
|
||||
1. 打开native\_functions.yaml文件。
|
||||
|
||||
native\_functions.yaml 文件中,定义了所有算子函数原型,包括函数名称和参数等信息,每个算子函数支持不同硬件平台的派发信息。该文件所在路径为pytorch/aten/src/ATen/native/native\_functions.yaml。
|
||||
native\_functions.yaml 文件中,定义了所有算子函数原型,包括函数名称和参数等信息,每个算子函数支持不同硬件平台的派发信息。该文件所在路径为scripts/codegen/native\_functions.yaml。
|
||||
|
||||
2. 确定需要派发函数。
|
||||
- yaml 中已存在的算子
|
||||
@@ -576,7 +576,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
|
||||
bash ci/build.sh --python=3.9
|
||||
```
|
||||
|
||||
请指定环境中python版本进行编译。编译成功后,会在pytorch/dist”文件夹目录下生成二进制包 torch_npu\*.whl ,例如:torch_npu-1.8.1rc1-cp37-cp37m-linux_x86_64.whl。
|
||||
请指定环境中python版本进行编译。编译成功后,会在pytorch/dist”文件夹目录下生成二进制包 torch_npu\*.whl ,例如:torch_npu-1.11.0rc3-cp37-cp37m-linux_x86_64.whl。
|
||||
|
||||
|
||||
#### 安装PyTorch插件<a name="zh-cn_topic_0000001125736777_section119821419153412"></a>
|
||||
@@ -584,7 +584,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
|
||||
进入“pytorch/dist“文件夹目录,执行如下命令安装。
|
||||
|
||||
```
|
||||
pip3 install --upgrade torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
|
||||
pip3 install --upgrade torch_npu-1.11.0rc3-cp37-cp37m-linux_{arch}.whl
|
||||
```
|
||||
|
||||
**\{arch\}**表示架构信息,为aarch64或x86\_64。
|
||||
@@ -688,7 +688,7 @@ pip3 install --upgrade torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
|
||||
|
||||
3. 执行测试用例脚本
|
||||
|
||||
进入test\_add.py所在的目录,执行:
|
||||
进入test\_add.py所在的目录/test/test_network_ops,执行:
|
||||
|
||||
```
|
||||
python3.7 test_add.py
|
||||
@@ -831,7 +831,7 @@ pip3.7 install torchvision --no-deps
|
||||
至此步骤,不应该有错误,屏幕应该输出 "add" 中增加的日志打印。若出错,请完成代码清理排查,保证无新开发的代码影响测试。
|
||||
|
||||
3. 将新开发的“自定义TBE算子”合并到"cann"中,在对应的在算子入口增加日志打印,作为运行标识。
|
||||
4. 完成上面的"cann"编译、安装,调用“python3.7.5 test\_add.py”进行测试。
|
||||
4. 完成上面的"cann"编译、安装,调用“python3.7 test\_add.py”进行测试。
|
||||
|
||||
> **说明:**
|
||||
>根据Ascend的设计逻辑,用户开发安装的“custom”算子包优先级高于“built-in”的内置算子包,在运行加载时,会优先加载调度“custom”包中的算子。过程中,若解析“custom”中的算子信息文件失败,则会跳过“custom”算子包,不加载调度任何“custom”算子包中的任何算子。
|
||||
@@ -839,11 +839,11 @@ pip3.7 install torchvision --no-deps
|
||||
>- 若此步骤出错,或屏幕未输出 "add" 中增加的日志打印,则说明新开发的“自定义TBE算子”有错误,影响了“自定义算子包”的加载,建议**优先排查新开发的“自定义TBE算子”中的“算子信息定义”是否正确**。
|
||||
>- 若此步骤正确,至少说明 **新开发的“自定义TBE算子”中的“算子信息定义”不影响运行**。
|
||||
|
||||
5. 调用“python3.7.5 xxx\_testcase.py”进行测试;
|
||||
5. 调用“python3.7 xxx\_testcase.py”进行测试,xxx为新增算子名称;
|
||||
|
||||
> **说明:**
|
||||
>- 若屏幕正常输出新开发的“自定义TBE算子”中增加的日志打印,则至少说明调度到了新开发的算子。
|
||||
>- 若屏幕未输出新开发的“自定义TBE算子”中增加的日志打印,则问题可能出现在“PyTorch适配”中,需要排查这一部分的实现代码,较多的可能会出现在“XxxxKernelNpu.cpp”中的输入、输出未能正确适配。
|
||||
>- 若屏幕未输出新开发的“自定义TBE算子”中增加的日志打印,则问题可能出现在“PyTorch适配”中,需要排查这一部分的实现代码,较多的可能会出现在“XxxxKernelNpu.cpp”中的输入、输出未能正确适配,XxxxKernelNpu.cpp为新增算子信息文件。
|
||||
|
||||
|
||||
|
||||
@@ -859,7 +859,7 @@ pip3.7 install torchvision --no-deps
|
||||
1. 打开安装在用户目录下的算子包安装目录。
|
||||
|
||||
```
|
||||
cd ~/.local/Ascend/opp/op_impl/built-in/ai_core/tbe/impl
|
||||
cd /usr/local/Ascend/ascend-toolkit/op_impl/build-in/ai_core/tbe/config/ascend910/
|
||||
ll
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
# **PyTorch精度对比工具使用指南**
|
||||
- [**PyTorch精度对比工具使用指南**](#pytorch精度对比工具使用指南)
|
||||
- [**使用场景**](#使用场景)
|
||||
- [**前提条件**](#前提条件)
|
||||
- [**精度比对基本原理**](#精度比对基本原理)
|
||||
- [**算子匹配条件**](#算子匹配条件)
|
||||
- [**计算精度评价指标**](#计算精度评价指标)
|
||||
- [**快速上手样例参考**](#快速上手样例参考)
|
||||
|
||||
|
||||
## **使用场景**
|
||||
|
||||
在同一模型或算子调试过程中,遇到算子相关的计算精度问题,定位时费时费力,所以推出了一个精度比对工具。
|
||||
|
||||
精度对比工具,通过在PyTorch模型中注入hook,跟踪计算图中算子的前向传播与反向传播时的输入与输出,排查存在计算精度误差,进行问题的精准定位。
|
||||
|
||||
主要的使用场景包括:
|
||||
|
||||
- 同一模型,从gpu(或cpu)移植到npu中存在精度下降问题,对比npu芯片中的算子计算数值与gpu(cpu)芯片中的算子计算数值,进行问题定位。
|
||||
- 同一模型,进行迭代(模型、算子或设备迭代)时存在的精度下降问题,对比相同模型在迭代前后版本的算子计算数值,进行问题定位。
|
||||
|
||||
## **前提条件**
|
||||
|
||||
已完成PyTorch Adapter插件的编译安装,具体操作请参考[《AscendPyTorch安装指南》](../PyTorch安装指南/PyTorch安装指南.md)。
|
||||
|
||||
## **精度比对基本原理**
|
||||
|
||||
普遍适用的方法是以模型为单位,采用hook机制挂在模型的上。当模型在CPU(或GPU)上进行正向传播时跟踪并dump每一层的数值输入与输出,在反向传播时跟踪并dump每一层的梯度输入值与输出值;同样的当模型在NPU中进行计算时采用相同的方式记录下相应的数据,通过对比dump出的数值,计算余弦相似度和均方根误差的方式,
|
||||
定位和排查NPU算子存在的计算精度问题。
|
||||
|
||||

|
||||
|
||||
图1即为精度对比的基本逻辑,思路清晰明了,但其中存在较多的细节问题:
|
||||
|
||||
1. 需要对大量的变量进行控制,要确保模型结构参数等相同。
|
||||
2. 相同的模型在不同的硬件设备上进行运算时可能会出现相同的计算会调用不同的底层算子,造成npu算子可能出现的不匹配情形。
|
||||
3. NPU与CPU/GPU的计算结果误差可能会随着模型的执行不断累积,最终会出现同一个算子因为输入的数据差异较大而无法匹配对比计算精度的情况。
|
||||
|
||||
其中细节问题2可能表现如下图2:
|
||||
|
||||

|
||||
|
||||
由于可能会出现融合算子,所以在算子的逐一匹配时可能会出现错误匹配或无法匹配的问题,例如图2中NPU算子npu_op_1与npu_op_2无法和cpu_op_k进行匹配,才去跳过的方式,直到到npu_op_3和cpu_op_3才从新对齐开始匹配。
|
||||
|
||||
### **算子匹配条件**
|
||||
|
||||
判断运行在cpu和npu上的两个算子是否相同采用的步骤如下:
|
||||
|
||||
1. 两个算子的名字是否相同
|
||||
1. 两个算子的输入输出Tensor数量和各个Tensor的shape是否相同
|
||||
|
||||
通常满足以上的两个条件,就认为是同一个算子,成功进行算子的匹配,后续进行相应的计算精度比对。
|
||||
|
||||
### **计算精度评价指标**
|
||||
|
||||
在进行计算精度匹配时,基本共识为默认CPU或GPU的算子计算结果是准确的,最终比对生成的csv文件中主要包括以下的几个属性:
|
||||
| Name | Npu Tensor Dtype | Bench Tensor Dtype | Npu Tensor Shape | Bench Tensor Shape | Cosine | RMSE | MAPE |
|
||||
| :---: | :--------------: | :----------------: | :--------------: | :----------------: | :----: | :---: | :---: |
|
||||
|
||||
其中主要使用算子Name、Dtype、Shape用于描述算子的基本特征,Cosine(余弦相似)、RMSE(均方根误差)、MAPE(绝对百分比误差)作为评价计算精度的主要评估指标:
|
||||
|
||||
1. 余弦相似度(通过计算两个向量的余弦值来判断其相似度):
|
||||
|
||||
$$
|
||||
\Large
|
||||
cos(\theta) = \frac{\sum_{i=1}^{n} (\hat{y_{i}} \times y_{i})}
|
||||
{\sqrt{\sum_{i=1}^{n}\hat{y_{i}}} \times \sqrt{\sum_{i=1}^{n}y_{i}^{2}}}
|
||||
$$
|
||||
当余弦夹角数值越接近于1说明计算出的两个张量越相似,在计算中可能会存在nan,主要由于可能会出现其中一个向量为0
|
||||
|
||||
2. 均方根误差(RMSE):
|
||||
|
||||
$$
|
||||
\Large
|
||||
RMSE = \sqrt{\frac{1}{n} \sum_{i=1}^{n} (\hat{y_{i}} - y_{i})^{2}}
|
||||
$$
|
||||
当均方根误差越接近0表示其计算的平均误差越小
|
||||
|
||||
3. 平均绝对百分比误差(MAPE):
|
||||
|
||||
$$
|
||||
\Large
|
||||
MAPE = \frac{1}{n} \sum_{i=1}^{n}|\frac{\hat{y_{i}} - y_{i}}{y_{i}}|
|
||||
$$
|
||||
绝对百分比误差衡量计算误差的百分比,越接近0越好,但当其中的实际计算结果中存在0时是无法进行计算的
|
||||
|
||||
## **快速上手样例参考**
|
||||
|
||||
使用精度比对工具进行模型的精度比对,样例代码如下:
|
||||
|
||||
```python
|
||||
# 根据需要import包
|
||||
import os
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from torch_npu.hooks import set_dump_path, seed_all, register_acc_cmp_hook
|
||||
from torch_npu.hooks.tools import compare
|
||||
|
||||
|
||||
# 定义一个简单的网络
|
||||
class ModuleOP(nn.Module):
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.linear_1 = nn.Linear(in_features=2, out_features=2)
|
||||
self.linear_2 = nn.Linear(in_features=2, out_features=1)
|
||||
self.relu = nn.ReLU()
|
||||
|
||||
def forward(self, x):
|
||||
x1 = self.linear_1(x)
|
||||
x2 = self.linear_2(x1)
|
||||
r1 = self.relu(x2)
|
||||
return r1
|
||||
|
||||
|
||||
# 对该网络进行hook注入和数据dump
|
||||
module = ModuleOp()
|
||||
register_acc_cmp_hook(module) # 对模型注入forwar和backward的hooks
|
||||
seed_all()
|
||||
x = torch.randn(2, 2)
|
||||
|
||||
# cpu上计算,dump数据
|
||||
set_dump_path("./cpu_module_op.pkl")
|
||||
out = module(x)
|
||||
loss = out.sum()
|
||||
loss.backward()
|
||||
set_dump_path("./npu_mpdule_op.pkl")
|
||||
|
||||
# npu上计算,dump数据
|
||||
module.npu()
|
||||
x = x.npu()
|
||||
out = module(x)
|
||||
loss = out.sum()
|
||||
loss.backward()
|
||||
|
||||
# 对比dump出的数据精度,生成csv文件
|
||||
compare("./npu_module_op.pkl", "./cpu_module_op.pkl", "./module_result.csv")
|
||||
|
||||
```
|
||||
|
||||
|
||||
使用精度比对工具进行torchvision下现有模型的计算精度比对,整体思路相同,其中cpu/gpu和npu的对比思路与npu和npu的对比思路也是相同,以resnet50模型为例代码如下:
|
||||
```python
|
||||
import os
|
||||
import copy
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import models, datasets, transforms
|
||||
|
||||
from torch_npu.hooks import set_dump_path, seed_all, register_acc_cmp_hook
|
||||
from torch_npu.hooks.tools import compare
|
||||
|
||||
|
||||
# 选取需要的模型
|
||||
model_cpu = models.resnet50()
|
||||
model_cpu.eval()
|
||||
model_npu = copy.deepcopy(model_cpu)
|
||||
model_npu.eval()
|
||||
|
||||
# 对该计算进行hook注入和数据dump
|
||||
register_acc_cmp_hook(model_cpu)
|
||||
register_acc_cmp_hook(model_npu)
|
||||
seed_all()
|
||||
|
||||
# 需要根据不同的模型输入和标签生成相应的tensor(或读取实际数据),损失函数等,如果是随机生成的标签需要保证数据的有效性
|
||||
inputs = torch.randn(1, 3, 244, 244)
|
||||
labels = torch.randn(1).long()
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
|
||||
# cpu,若需要使用gpu或npu进行对比采用model_gpu = model.to("cuda:0")或model_npu = model.to("npu:0")
|
||||
set_dump_path("./cpu_resnet50_op.pkl")
|
||||
output = model_cpu(inputs)
|
||||
loss = criterion(output, labels)
|
||||
loss.backward()
|
||||
|
||||
# npu
|
||||
set_dump_path("./npu_resnet50_op.pkl")
|
||||
model_npu.npu()
|
||||
inputs = inputs.npu()
|
||||
labels = labels.npu()
|
||||
output = model_npu(inputs)
|
||||
loss = criterion(output, labels)
|
||||
loss.backward()
|
||||
|
||||
# 对比dump出的数据精度,生成csv文件
|
||||
compare("./npu_resnet50_op.pkl", "./cpu_resnet50_op.pkl", "./resnet50_result.csv")
|
||||
```
|
||||
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 38 KiB |
@@ -0,0 +1,37 @@
|
||||
# **框架侧精度对比工具开发背景**
|
||||
|
||||
- [**框架侧精度对比工具开发背景**](#框架侧精度对比工具开发背景)
|
||||
- [**计算精度对比需求**](#计算精度对比需求)
|
||||
- [**已有的精度对比脚本工具**](#已有的精度对比脚本工具)
|
||||
- [**框架侧精度对比工具优势**](#框架侧精度对比工具优势)
|
||||
|
||||
|
||||
## **计算精度对比需求**
|
||||
|
||||
华为对自有训练模型算子进行了优化,其中包括算子消除、算子融合、算子拆分等,以更好的适配NPU等训练设备。
|
||||
因此在模型迁移的过程中,有时会遇到自有实现的算子运算的结果与业界标准算子运算结果存在偏差,精度不达标的问题,需要借助计算精度比对工具得出模型中的哪些算子在GPU和NPU的计算中会存在较大的差异,从而重点分析这些算子的表现性能,帮助开发人员快速定位并解决算子精度问题。
|
||||
|
||||
此外在进行模型版本迭代、底层算子迭代、计算设备(npu)迭代时也可能会引入计算精度的问题,有时会遇到新实现的算子运算的结果与要被替代的算子运算结果存在偏差等,需要借助计算精度对比工具得出那些算子在不同的版本或在不同的设备上存在较大的计算差异,从而快速定位计算精度问题。
|
||||
## **已有的精度对比脚本工具**
|
||||
|
||||
目前已经有一些可以进行精度比对的脚本示例,其主要思路都是相同的,包括整网对比和单算子对比,如图所示。
|
||||

|
||||
|
||||
其中dump出的数据常见为h5文件格式,其内部结构为树形层次结构
|
||||

|
||||
|
||||
更多的H5文件使用方式,可以参考以下文档:https://www.hdfgroup.org/solutions/hdf5/
|
||||
|
||||
同时配套存在一些dump数据生成H5文件,并存在处理H5文件的相关脚本,进行算子的匹配和精度比对的计算。
|
||||
|
||||
## **框架侧精度对比工具优势**
|
||||
|
||||
相比于现有的精度比对脚本,在框架侧开发的精度比对工具有以下几点优势:
|
||||
|
||||
1. 使用环境配置简单,且不会出现兼容性等问题,仅需要完成PyTorch Adapter插件的编译安装即可。
|
||||
|
||||
2. 集成度更高,开发人员或使用人员不用关心精度比对工具的底层实现。
|
||||
|
||||
3. 工具的可维护性更强,相比于民间流传的工具脚本,在框架侧的功能维护与功能特性的更新迭代更有保障。
|
||||
|
||||
4. 可以支持更丰富的使用方式,例如在原先的脚本的精度对比是不支持function类的算子,在框架测进行开发则可以支持;且未来框架侧有望实现精度实时比对,避免了dump大量的同质化数据。
|
||||
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 8.0 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 126 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 607 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 126 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 101 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 82 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 946 B |
|
After Width: | Height: | Size: 356 B |
|
After Width: | Height: | Size: 946 B |
|
After Width: | Height: | Size: 356 B |
|
After Width: | Height: | Size: 329 KiB |
|
After Width: | Height: | Size: 144 KiB |
|
After Width: | Height: | Size: 140 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 8.0 KiB |
|
After Width: | Height: | Size: 580 B |
|
After Width: | Height: | Size: 580 B |
|
After Width: | Height: | Size: 394 B |
|
After Width: | Height: | Size: 406 B |
|
After Width: | Height: | Size: 253 B |
|
After Width: | Height: | Size: 580 B |
@@ -1,4 +1,11 @@
|
||||
# FrameworkPTAdapter 3.0.RC2 版本说明书
|
||||
# FrameworkPTAdapter 3.0.RC3 版本说明书
|
||||
- [FrameworkPTAdapter 3.0.RC3](#FrameworkPTAdapter-3-0-RC3md)
|
||||
- [用户须知](#用户须知md)
|
||||
- [新增特性](#新增特性md)
|
||||
- [特性修改](#特性修改md)
|
||||
- [已修复问题](#已修复问题md)
|
||||
- [已知问题](#已知问题md)
|
||||
- [兼容性](#兼容性md)
|
||||
- [FrameworkPTAdapter 3.0.RC2](#FrameworkPTAdapter-3-0-RC2md)
|
||||
- [用户须知](#用户须知md)
|
||||
- [新增特性](#新增特性md)
|
||||
@@ -35,6 +42,54 @@
|
||||
- [已知问题](#已知问题-4md)
|
||||
- [兼容性](#兼容性-5md)
|
||||
|
||||
<h2 id="FrameworkPTAdapter-3-0-RC3md">FrameworkPTAdapter 3.0.RC3</h2>
|
||||
|
||||
<h3 id="用户须知md">用户须知</h3>
|
||||
|
||||
本框架基于Facebook主导的开源PyTorch进行修改,延续原生的PyTorch特性,使用NPU进行动态图训练;以算子粒度进行模型适配,代码重用性好,支持现有的网络只修改设备类型或数据类型,即可迁移到NPU上使用。
|
||||
|
||||
PyTorch1.8.1版本开始采用插件化适配方式,与原生PyTorch框架实现彻底解耦,功能、性能与PyTorch1.5.0基本保持一致,对后端算子适配提供较好开发体验。
|
||||
|
||||
<h3 id="新增特性md">新增特性</h3>
|
||||
|
||||
**表 1** PyTorch支持的版本特性列表
|
||||
|
||||
| 一级特性 | 二级特性 | 说明 |
|
||||
| -------------------------- | -------------------------------- | ---------------------------------------------- |
|
||||
| 适配NPU的PyTorch1.5.0特性 | 框架基础功能 | 适配CANN算子IR变更。 |
|
||||
| 适配NPU的PyTorch1.8.1特性 | 精度对比工具 | 支持NPU与CPU精度对比工具。 |
|
||||
| profiling | 支持自定义算子profiling。 | |
|
||||
| API满足度提升 | 新增部分API适配(详见API清单)。 | |
|
||||
| 适配NPU的PyTorch1.11.0特性 | 框架基础功能 | 支持模型训练功能,适配算子API(详见API清单)。 |
|
||||
| 混合精度 | 支持apex混合精度训练。 | |
|
||||
| 分布式 | 支持DDP分布式训练功能。 | |
|
||||
| profiling | 支持E2E profiling功能。 | |
|
||||
|
||||
<h3 id="特性修改md">特性修改</h3>
|
||||
|
||||
不涉及
|
||||
|
||||
<h3 id="已修复问题md">已修复问题</h3>
|
||||
|
||||
不涉及
|
||||
|
||||
<h3 id="已知问题md">已知问题</h3>
|
||||
|
||||
| 已知问题 | 问题描述 |
|
||||
| --------------------------------------------- | ------------------------------------------------------------ |
|
||||
| 数据类型支持 | NPU不支持float16类型的inf/nan数据输入输出。 |
|
||||
| 数据Format | 出现4D以上的format时不能降维。 |
|
||||
| 集合通信约束 | 要求一次训练任务中不同device上执行的图相同。 |
|
||||
| 当前只支持1/2/4/8P粒度的分配。 | |
|
||||
| 只支持int8,int32,float16和float32数据类型。 | |
|
||||
| Apex功能支持 | Apex当前版本的实现方式主要为python实现,不支持APEX中的自定义优化CUDA Kernel。 |
|
||||
|
||||
<h3 id="兼容性md">兼容性</h3>
|
||||
|
||||
A800-9010:CentOS 7.6/Ubuntu 18.04, 2.04/BC-Linux 7.6/Debian 9.9/Debian 10/OpenEuler 20.03 LTS
|
||||
|
||||
A800-9000:CentOS 7.6/Ubuntu 18.04, 2.04/Euler 2.8, 2.10/Kylin v10/BC-Linux 7.6/OpenEuler 20.03 LTS/UOS 20 1020e
|
||||
|
||||
<h2 id="FrameworkPTAdapter-3-0-RC2md">FrameworkPTAdapter 3.0.RC2</h2>
|
||||
|
||||
|
||||
|
||||
@@ -41,11 +41,8 @@ export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/lib/aarch64_64-linux-gnu
|
||||
export HCCL_WHITELIST_DISABLE=1
|
||||
|
||||
export TASK_QUEUE_ENABLE=0 # 使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1
|
||||
#export DYNAMIC_COMPILE_ENABLE=1 # 动态shape特性功能,针对shape变化场景,可选 开启设置为1
|
||||
#export COMBINED_ENABLE=1 # 非连续两个算子组合类场景优化,可选,开启设置为1
|
||||
#export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
|
||||
#export DYNAMIC_OP="ADD#MUL" # 算子实现,ADD和MUL算子在不同场景下有不同的性能表现。可选
|
||||
#export BMMV2_ENABLE=1 # matmul选择npu内部实现,高维Tensor矩阵乘有针对优化。可选,开启设置为1
|
||||
|
||||
# log
|
||||
export ASCEND_SLOG_PRINT_TO_STDOUT=0 #日志打屏, 可选
|
||||
|
||||
|
After Width: | Height: | Size: 377 KiB |
|
After Width: | Height: | Size: 288 KiB |
@@ -45,7 +45,7 @@ struct C10_API StorageImpl : public c10::intrusive_ptr_target {
|
||||
StorageImpl() = delete;
|
||||
StorageImpl(StorageImpl&& other) = default;
|
||||
StorageImpl(const StorageImpl&) = delete;
|
||||
~StorageImpl() = default;
|
||||
~StorageImpl() override = default;
|
||||
|
||||
void reset() {
|
||||
data_ptr_.clear();
|
||||
@@ -86,12 +86,18 @@ struct C10_API StorageImpl : public c10::intrusive_ptr_target {
|
||||
return data_ptr_;
|
||||
};
|
||||
|
||||
// Returns the previous data_ptr
|
||||
// Returns the previous data_ptr
|
||||
at::DataPtr set_data_ptr(at::DataPtr&& data_ptr) {
|
||||
std::swap(data_ptr_, data_ptr);
|
||||
return std::move(data_ptr);
|
||||
at::DataPtr old_data_ptr(std::move(data_ptr_));
|
||||
data_ptr_ = std::move(data_ptr);
|
||||
return old_data_ptr;
|
||||
};
|
||||
|
||||
void set_data_ptr_noswap(at::DataPtr&& data_ptr) {
|
||||
data_ptr_ = std::move(data_ptr);
|
||||
}
|
||||
|
||||
// TODO: Return const ptr eventually if possible
|
||||
void* data() {
|
||||
return data_ptr_.get();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,691 @@
|
||||
#pragma once
|
||||
|
||||
#include <c10/macros/Macros.h>
|
||||
#include <c10/util/C++17.h>
|
||||
#include <c10/util/reverse_iterator.h>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
C10_CLANG_DIAGNOSTIC_PUSH()
|
||||
#if C10_CLANG_HAS_WARNING("-Wdeprecated")
|
||||
C10_CLANG_DIAGNOSTIC_IGNORE("-Wdeprecated")
|
||||
#endif
|
||||
|
||||
namespace c10 {
|
||||
|
||||
/**
|
||||
* Reimplementation of std::string_view for C++11.
|
||||
* Implemented following the interface definition in
|
||||
* https://en.cppreference.com/w/cpp/string/basic_string_view
|
||||
* See there for the API documentation.
|
||||
*
|
||||
* Difference: We don't have a Traits template parameter because
|
||||
* std::char_traits isn't constexpr and we'd have to reimplement
|
||||
* std::char_traits if we wanted to use it with our constexpr basic_string_view.
|
||||
*/
|
||||
template <class CharT>
|
||||
class basic_string_view final {
|
||||
public:
|
||||
using value_type = CharT;
|
||||
using pointer = CharT*;
|
||||
using const_pointer = const CharT*;
|
||||
using reference = CharT&;
|
||||
using const_reference = const CharT&;
|
||||
using const_iterator = const CharT*;
|
||||
using iterator = const_iterator;
|
||||
using const_reverse_iterator = c10::reverse_iterator<const_iterator>;
|
||||
using reverse_iterator = const_reverse_iterator;
|
||||
using size_type = std::size_t;
|
||||
using difference_type = std::ptrdiff_t;
|
||||
|
||||
static constexpr size_type npos = size_type(-1);
|
||||
|
||||
constexpr basic_string_view() noexcept : begin_(nullptr), size_(0) {}
|
||||
|
||||
explicit constexpr basic_string_view(const_pointer str, size_type count)
|
||||
: begin_(str), size_(count) {}
|
||||
|
||||
/* implicit */ constexpr basic_string_view(const_pointer str)
|
||||
: basic_string_view(str, strlen_(str)) {}
|
||||
|
||||
/* implicit */ basic_string_view(const ::std::basic_string<CharT>& str)
|
||||
: basic_string_view(str.data(), str.size()) {}
|
||||
|
||||
constexpr basic_string_view(const basic_string_view&) noexcept = default;
|
||||
|
||||
constexpr basic_string_view& operator=(
|
||||
const basic_string_view& rhs) noexcept {
|
||||
begin_ = rhs.begin_;
|
||||
size_ = rhs.size_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
explicit operator ::std::basic_string<CharT>() const {
|
||||
return ::std::basic_string<CharT>(data(), size());
|
||||
}
|
||||
|
||||
constexpr const_iterator begin() const noexcept {
|
||||
return cbegin();
|
||||
}
|
||||
|
||||
constexpr const_iterator cbegin() const noexcept {
|
||||
return begin_;
|
||||
}
|
||||
|
||||
constexpr const_iterator end() const noexcept {
|
||||
return cend();
|
||||
}
|
||||
|
||||
constexpr const_iterator cend() const noexcept {
|
||||
return begin_ + size_;
|
||||
}
|
||||
|
||||
constexpr const_reverse_iterator rbegin() const noexcept {
|
||||
return crbegin();
|
||||
}
|
||||
|
||||
constexpr const_reverse_iterator crbegin() const noexcept {
|
||||
return const_reverse_iterator(this->end());
|
||||
}
|
||||
|
||||
constexpr const_reverse_iterator rend() const noexcept {
|
||||
return crend();
|
||||
}
|
||||
|
||||
constexpr const_reverse_iterator crend() const noexcept {
|
||||
return const_reverse_iterator(this->begin());
|
||||
}
|
||||
|
||||
friend constexpr const_iterator begin(basic_string_view sv) noexcept {
|
||||
return sv.begin();
|
||||
}
|
||||
|
||||
friend constexpr const_iterator end(basic_string_view sv) noexcept {
|
||||
return sv.end();
|
||||
}
|
||||
|
||||
constexpr const_reference operator[](size_type pos) const {
|
||||
// TODO: split out
|
||||
return at_(pos);
|
||||
}
|
||||
|
||||
constexpr const_reference at(size_type pos) const {
|
||||
#if !defined( \
|
||||
__CUDA_ARCH__) // CUDA doesn't like std::out_of_range in device code
|
||||
return C10_UNLIKELY(pos >= size_)
|
||||
? (throw std::out_of_range(
|
||||
"string_view::operator[] or string_view::at() out of range. Index: " +
|
||||
c10::guts::to_string(pos) +
|
||||
", size: " + c10::guts::to_string(size())),
|
||||
at_(0))
|
||||
: at_(pos);
|
||||
#else
|
||||
return at_(pos);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr const_reference front() const {
|
||||
return *begin_;
|
||||
}
|
||||
|
||||
constexpr const_reference back() const {
|
||||
return *(begin_ + size_ - 1);
|
||||
}
|
||||
|
||||
constexpr const_pointer data() const noexcept {
|
||||
return begin_;
|
||||
}
|
||||
|
||||
constexpr size_type size() const noexcept {
|
||||
return size_;
|
||||
}
|
||||
|
||||
constexpr size_type length() const noexcept {
|
||||
return size();
|
||||
}
|
||||
|
||||
constexpr size_type max_size() const noexcept {
|
||||
return std::numeric_limits<difference_type>::max();
|
||||
}
|
||||
|
||||
C10_NODISCARD constexpr bool empty() const noexcept {
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
CONSTEXPR_EXCEPT_GCC5 void remove_prefix(size_type n) {
|
||||
if (n > size()) {
|
||||
throw std::out_of_range(
|
||||
"basic_string_view::remove_prefix: out of range. PrefixLength: " +
|
||||
c10::guts::to_string(n) + ", size: " + c10::guts::to_string(size()));
|
||||
}
|
||||
begin_ += n;
|
||||
size_ -= n;
|
||||
}
|
||||
|
||||
CONSTEXPR_EXCEPT_GCC5 void remove_suffix(size_type n) {
|
||||
if (n > size()) {
|
||||
throw std::out_of_range(
|
||||
"basic_string_view::remove_suffix: out of range. SuffixLength: " +
|
||||
c10::guts::to_string(n) + ", size: " + c10::guts::to_string(size()));
|
||||
}
|
||||
size_ -= n;
|
||||
}
|
||||
|
||||
CONSTEXPR_EXCEPT_GCC5 void swap(basic_string_view& sv) noexcept {
|
||||
auto tmp = *this;
|
||||
*this = sv;
|
||||
sv = tmp;
|
||||
}
|
||||
|
||||
size_type copy(pointer dest, size_type count, size_type pos = 0) const {
|
||||
if (pos > size_) {
|
||||
throw std::out_of_range(
|
||||
"basic_string_view::copy: out of range. Index: " +
|
||||
c10::guts::to_string(pos) +
|
||||
", size: " + c10::guts::to_string(size()));
|
||||
}
|
||||
size_type copy_length = guts::min(count, size_ - pos);
|
||||
for (auto iter = begin() + pos, end = iter + copy_length; iter != end;) {
|
||||
*(dest++) = *(iter++);
|
||||
}
|
||||
return copy_length;
|
||||
}
|
||||
|
||||
constexpr basic_string_view substr(size_type pos = 0, size_type count = npos)
|
||||
const {
|
||||
#if !defined( \
|
||||
__CUDA_ARCH__) // CUDA doesn't like std::out_of_range in device code
|
||||
return (pos > size_)
|
||||
? (throw std::out_of_range(
|
||||
"basic_string_view::substr parameter out of bounds. Index: " +
|
||||
c10::guts::to_string(pos) +
|
||||
", size: " + c10::guts::to_string(size())),
|
||||
substr_())
|
||||
: substr_(pos, count);
|
||||
#else
|
||||
return substr_(pos, count);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr int compare(basic_string_view rhs) const noexcept {
|
||||
#if __cpp_constexpr >= 201304
|
||||
// if we are in C++14, write it iteratively. This is faster.
|
||||
for (size_t i = 0, end = guts::min(size(), rhs.size()); i < end; ++i) {
|
||||
if (at_(i) < rhs.at_(i)) {
|
||||
return -1;
|
||||
} else if (at_(i) > rhs.at_(i)) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (size() < rhs.size()) {
|
||||
return -1;
|
||||
} else if (size() > rhs.size()) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
#else
|
||||
// if we are in C++11, we need to do it recursively because of constexpr
|
||||
// restrictions.
|
||||
return (size() == 0 && rhs.size() == 0) ? 0
|
||||
: (size() == 0) ? -1
|
||||
: (rhs.size() == 0) ? 1
|
||||
: (front() < rhs.front()) ? -1
|
||||
: (front() > rhs.front()) ? 1
|
||||
: substr_(1).compare(rhs.substr_(1));
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr int compare(size_type pos1, size_type count1, basic_string_view v)
|
||||
const {
|
||||
return substr(pos1, count1).compare(v);
|
||||
}
|
||||
|
||||
constexpr int compare(
|
||||
size_type pos1,
|
||||
size_type count1,
|
||||
basic_string_view v,
|
||||
size_type pos2,
|
||||
size_type count2) const {
|
||||
return substr(pos1, count1).compare(v.substr(pos2, count2));
|
||||
}
|
||||
|
||||
constexpr int compare(const_pointer s) const {
|
||||
return compare(basic_string_view(s));
|
||||
}
|
||||
|
||||
constexpr int compare(size_type pos1, size_type count1, const_pointer s)
|
||||
const {
|
||||
return substr(pos1, count1).compare(basic_string_view(s));
|
||||
}
|
||||
|
||||
constexpr int compare(
|
||||
size_type pos1,
|
||||
size_type count1,
|
||||
const_pointer s,
|
||||
size_type count2) const {
|
||||
return substr(pos1, count1).compare(basic_string_view(s, count2));
|
||||
}
|
||||
|
||||
friend constexpr bool operator==(
|
||||
basic_string_view lhs,
|
||||
basic_string_view rhs) noexcept {
|
||||
return lhs.equals_(rhs);
|
||||
}
|
||||
|
||||
friend constexpr bool operator!=(
|
||||
basic_string_view lhs,
|
||||
basic_string_view rhs) noexcept {
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
friend constexpr bool operator<(
|
||||
basic_string_view lhs,
|
||||
basic_string_view rhs) noexcept {
|
||||
return lhs.compare(rhs) < 0;
|
||||
}
|
||||
|
||||
friend constexpr bool operator>=(
|
||||
basic_string_view lhs,
|
||||
basic_string_view rhs) noexcept {
|
||||
return !(lhs < rhs);
|
||||
}
|
||||
|
||||
friend constexpr bool operator>(
|
||||
basic_string_view lhs,
|
||||
basic_string_view rhs) noexcept {
|
||||
return rhs < lhs;
|
||||
}
|
||||
|
||||
friend constexpr bool operator<=(
|
||||
basic_string_view lhs,
|
||||
basic_string_view rhs) noexcept {
|
||||
return !(lhs > rhs);
|
||||
}
|
||||
|
||||
constexpr bool starts_with(basic_string_view prefix) const noexcept {
|
||||
return (prefix.size() > size()) ? false
|
||||
: prefix.equals_(substr_(0, prefix.size()));
|
||||
}
|
||||
|
||||
constexpr bool starts_with(CharT prefix) const noexcept {
|
||||
return !empty() && prefix == front();
|
||||
}
|
||||
|
||||
constexpr bool starts_with(const_pointer prefix) const {
|
||||
return starts_with(basic_string_view(prefix));
|
||||
}
|
||||
|
||||
constexpr bool ends_with(basic_string_view suffix) const noexcept {
|
||||
return (suffix.size() > size())
|
||||
? false
|
||||
: suffix.equals_(substr_(size() - suffix.size(), suffix.size()));
|
||||
}
|
||||
|
||||
constexpr bool ends_with(CharT suffix) const noexcept {
|
||||
return !empty() && suffix == back();
|
||||
}
|
||||
|
||||
constexpr bool ends_with(const_pointer suffix) const {
|
||||
return ends_with(basic_string_view(suffix));
|
||||
}
|
||||
|
||||
constexpr size_type find(basic_string_view v, size_type pos = 0)
|
||||
const noexcept {
|
||||
#if __cpp_constexpr >= 201304
|
||||
// if we are in C++14, write it iteratively. This is faster.
|
||||
if (v.size() == 0) {
|
||||
return pos <= size() ? pos : npos;
|
||||
}
|
||||
|
||||
if (pos + v.size() <= size()) {
|
||||
for (size_type cur = pos, end = size() - v.size(); cur <= end; ++cur) {
|
||||
if (v.at_(0) == at_(cur) &&
|
||||
v.substr_(1).equals_(substr_(cur + 1, v.size() - 1))) {
|
||||
return cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
return npos;
|
||||
#else
|
||||
// if we are in C++11, we need to do it recursively because of constexpr
|
||||
// restrictions.
|
||||
return (v.size() == 0) ? (pos <= size() ? pos : npos)
|
||||
: (pos + v.size() > size()) ? npos
|
||||
: (v.at_(0) == at_(pos) &&
|
||||
v.substr_(1).equals_(substr_(pos + 1, v.size() - 1)))
|
||||
? pos
|
||||
: find(v, pos + 1);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr size_type find(CharT ch, size_type pos = 0) const noexcept {
|
||||
return find_first_if_(pos, charIsEqual_{ch});
|
||||
}
|
||||
|
||||
constexpr size_type find(const_pointer s, size_type pos, size_type count)
|
||||
const {
|
||||
return find(basic_string_view(s, count), pos);
|
||||
}
|
||||
|
||||
constexpr size_type find(const_pointer s, size_type pos = 0) const {
|
||||
return find(basic_string_view(s), pos);
|
||||
}
|
||||
|
||||
constexpr size_type rfind(basic_string_view v, size_type pos = npos)
|
||||
const noexcept {
|
||||
#if __cpp_constexpr >= 201304
|
||||
// if we are in C++14, write it iteratively. This is faster.
|
||||
if (v.size() == 0) {
|
||||
return pos <= size() ? pos : size();
|
||||
}
|
||||
|
||||
if (v.size() <= size()) {
|
||||
pos = guts::min(size() - v.size(), pos);
|
||||
do {
|
||||
if (v.at_(0) == at_(pos) &&
|
||||
v.substr_(1).equals_(substr_(pos + 1, v.size() - 1))) {
|
||||
return pos;
|
||||
}
|
||||
} while (pos-- > 0);
|
||||
}
|
||||
return npos;
|
||||
#else
|
||||
// if we are in C++11, we need to do it recursively because of constexpr
|
||||
// restrictions.
|
||||
return (v.size() == 0) ? (pos <= size() ? pos : size())
|
||||
: (v.size() > size()) ? npos
|
||||
: (size() - v.size() < pos) ? rfind(v, size() - v.size())
|
||||
: (v.at_(0) == at_(pos) &&
|
||||
v.substr_(1).equals_(substr_(pos + 1, v.size() - 1)))
|
||||
? pos
|
||||
: (pos == 0) ? npos
|
||||
: rfind(v, pos - 1);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr size_type rfind(CharT ch, size_type pos = npos) const noexcept {
|
||||
return find_last_if_(pos, charIsEqual_{ch});
|
||||
}
|
||||
|
||||
constexpr size_type rfind(const_pointer s, size_type pos, size_type count)
|
||||
const {
|
||||
return rfind(basic_string_view(s, count), pos);
|
||||
}
|
||||
|
||||
constexpr size_type rfind(const_pointer s, size_type pos = npos) const {
|
||||
return rfind(basic_string_view(s), pos);
|
||||
}
|
||||
|
||||
constexpr size_type find_first_of(basic_string_view v, size_type pos = 0)
|
||||
const noexcept {
|
||||
return find_first_if_(pos, stringViewContainsChar_{v});
|
||||
}
|
||||
|
||||
constexpr size_type find_first_of(CharT ch, size_type pos = 0)
|
||||
const noexcept {
|
||||
return find_first_if_(pos, charIsEqual_{ch});
|
||||
}
|
||||
|
||||
constexpr size_type find_first_of(
|
||||
const_pointer s,
|
||||
size_type pos,
|
||||
size_type count) const {
|
||||
return find_first_of(basic_string_view(s, count), pos);
|
||||
}
|
||||
|
||||
constexpr size_type find_first_of(const_pointer s, size_type pos = 0) const {
|
||||
return find_first_of(basic_string_view(s), pos);
|
||||
}
|
||||
|
||||
constexpr size_type find_last_of(basic_string_view v, size_type pos = npos)
|
||||
const noexcept {
|
||||
return find_last_if_(pos, stringViewContainsChar_{v});
|
||||
}
|
||||
|
||||
constexpr size_type find_last_of(CharT ch, size_type pos = npos)
|
||||
const noexcept {
|
||||
return find_last_if_(pos, charIsEqual_{ch});
|
||||
}
|
||||
|
||||
constexpr size_type find_last_of(
|
||||
const_pointer s,
|
||||
size_type pos,
|
||||
size_type count) const {
|
||||
return find_last_of(basic_string_view(s, count), pos);
|
||||
}
|
||||
|
||||
constexpr size_type find_last_of(const_pointer s, size_type pos = npos)
|
||||
const {
|
||||
return find_last_of(basic_string_view(s), pos);
|
||||
}
|
||||
|
||||
constexpr size_type find_first_not_of(basic_string_view v, size_type pos = 0)
|
||||
const noexcept {
|
||||
return find_first_if_(pos, stringViewDoesNotContainChar_{v});
|
||||
}
|
||||
|
||||
constexpr size_type find_first_not_of(CharT ch, size_type pos = 0)
|
||||
const noexcept {
|
||||
return find_first_if_(pos, charIsNotEqual_{ch});
|
||||
}
|
||||
|
||||
constexpr size_type find_first_not_of(
|
||||
const_pointer s,
|
||||
size_type pos,
|
||||
size_type count) const {
|
||||
return find_first_not_of(basic_string_view(s, count), pos);
|
||||
}
|
||||
|
||||
constexpr size_type find_first_not_of(const_pointer s, size_type pos = 0)
|
||||
const {
|
||||
return find_first_not_of(basic_string_view(s), pos);
|
||||
}
|
||||
|
||||
constexpr size_type find_last_not_of(
|
||||
basic_string_view v,
|
||||
size_type pos = npos) const noexcept {
|
||||
return find_last_if_(pos, stringViewDoesNotContainChar_{v});
|
||||
}
|
||||
|
||||
constexpr size_type find_last_not_of(CharT ch, size_type pos = npos)
|
||||
const noexcept {
|
||||
return find_last_if_(pos, charIsNotEqual_{ch});
|
||||
}
|
||||
|
||||
constexpr size_type find_last_not_of(
|
||||
const_pointer s,
|
||||
size_type pos,
|
||||
size_type count) const {
|
||||
return find_last_not_of(basic_string_view(s, count), pos);
|
||||
}
|
||||
|
||||
constexpr size_type find_last_not_of(const_pointer s, size_type pos = npos)
|
||||
const {
|
||||
return find_last_not_of(basic_string_view(s), pos);
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr size_type strlen_(const_pointer str) noexcept {
|
||||
#if __cpp_constexpr >= 201304
|
||||
// if we are in C++14, write it iteratively. This is faster.
|
||||
const_pointer current = str;
|
||||
while (*current != '\0') {
|
||||
++current;
|
||||
}
|
||||
return current - str;
|
||||
#else
|
||||
// if we are in C++11, we need to do it recursively because of constexpr
|
||||
// restrictions.
|
||||
return (*str == '\0') ? 0 : 1 + strlen_(str + 1);
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr const_reference at_(size_type pos) const noexcept {
|
||||
return *(begin_ + pos);
|
||||
}
|
||||
|
||||
constexpr basic_string_view substr_(size_type pos = 0, size_type count = npos)
|
||||
const {
|
||||
return basic_string_view{begin_ + pos, guts::min(count, size() - pos)};
|
||||
}
|
||||
|
||||
template <class Condition>
|
||||
constexpr size_type find_first_if_(size_type pos, Condition&& condition)
|
||||
const noexcept {
|
||||
#if __cpp_constexpr >= 201304
|
||||
// if we are in C++14, write it iteratively. This is faster.
|
||||
if (pos + 1 <= size()) {
|
||||
for (size_type cur = pos; cur < size(); ++cur) {
|
||||
if (condition(at_(cur))) {
|
||||
return cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
return npos;
|
||||
#else
|
||||
// if we are in C++11, we need to do it recursively because of constexpr
|
||||
// restrictions.
|
||||
return (pos + 1 > size()) ? npos
|
||||
: condition(at_(pos))
|
||||
? pos
|
||||
: find_first_if_(pos + 1, std::forward<Condition>(condition));
|
||||
#endif
|
||||
}
|
||||
|
||||
template <class Condition>
|
||||
constexpr size_type find_last_if_(size_type pos, Condition&& condition)
|
||||
const noexcept {
|
||||
#if __cpp_constexpr >= 201304
|
||||
// if we are in C++14, write it iteratively. This is faster.
|
||||
if (size() > 0) {
|
||||
pos = guts::min(size() - 1, pos);
|
||||
do {
|
||||
if (condition(at_(pos))) {
|
||||
return pos;
|
||||
}
|
||||
} while (pos-- > 0);
|
||||
}
|
||||
return npos;
|
||||
#else
|
||||
// if we are in C++11, we need to do it recursively because of constexpr
|
||||
// restrictions.
|
||||
return (size() == 0) ? npos
|
||||
: (pos >= size())
|
||||
? find_last_if_(size() - 1, std::forward<Condition>(condition))
|
||||
: condition(at_(pos)) ? pos
|
||||
: (pos == 0)
|
||||
? npos
|
||||
: find_last_if_(pos - 1, std::forward<Condition>(condition));
|
||||
#endif
|
||||
}
|
||||
|
||||
constexpr bool equals_(basic_string_view rhs) const {
|
||||
// We don't use string_view::compare() here but implement it manually
|
||||
// because only looking at equality allows for more optimized code.
|
||||
#if defined(__GNUC__) && !defined(__CUDACC__)
|
||||
return size() == rhs.size() &&
|
||||
0 == __builtin_memcmp(data(), rhs.data(), size());
|
||||
#elif __cpp_constexpr >= 201304
|
||||
// if we are in C++14, write it iteratively. This is faster than the
|
||||
// recursive C++11 implementation below.
|
||||
if (size() != rhs.size()) {
|
||||
return false;
|
||||
}
|
||||
// Yes, memcmp would be laster than this loop, but memcmp isn't constexpr
|
||||
// and I didn't feel like implementing a constexpr memcmp variant.
|
||||
// TODO At some point this should probably be done, including tricks
|
||||
// like comparing one machine word instead of a byte per iteration.
|
||||
for (typename basic_string_view<CharT>::size_type pos = 0; pos < size();
|
||||
++pos) {
|
||||
if (at_(pos) != rhs.at_(pos)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
#else
|
||||
// if we are in C++11, we need to do it recursively because of constexpr
|
||||
// restrictions.
|
||||
return (size() != rhs.size()) ? false
|
||||
: (size() == 0) ? true
|
||||
: (front() != rhs.front()) ? false
|
||||
: (substr_(1).equals_(rhs.substr_(1)));
|
||||
#endif
|
||||
}
|
||||
|
||||
struct charIsEqual_ final {
|
||||
CharT expected;
|
||||
constexpr bool operator()(CharT actual) const noexcept {
|
||||
return expected == actual;
|
||||
}
|
||||
};
|
||||
|
||||
struct charIsNotEqual_ final {
|
||||
CharT expected;
|
||||
constexpr bool operator()(CharT actual) const noexcept {
|
||||
return expected != actual;
|
||||
}
|
||||
};
|
||||
|
||||
struct stringViewContainsChar_ final {
|
||||
basic_string_view expected;
|
||||
constexpr bool operator()(CharT ch) const noexcept {
|
||||
return npos != expected.find(ch);
|
||||
}
|
||||
};
|
||||
|
||||
struct stringViewDoesNotContainChar_ final {
|
||||
basic_string_view expected;
|
||||
constexpr bool operator()(CharT ch) const noexcept {
|
||||
return npos == expected.find(ch);
|
||||
}
|
||||
};
|
||||
|
||||
const_pointer begin_;
|
||||
size_type size_;
|
||||
};
|
||||
|
||||
template <class CharT>
|
||||
const typename basic_string_view<CharT>::size_type
|
||||
basic_string_view<CharT>::npos;
|
||||
|
||||
template <class CharT>
|
||||
inline std::basic_ostream<CharT>& operator<<(
|
||||
std::basic_ostream<CharT>& stream,
|
||||
basic_string_view<CharT> sv) {
|
||||
// The rules for operator<< are quite complex, but std::string has the same.
|
||||
// Let's just rely on the std::string implementation. This might be a bit
|
||||
// slower, but I don't think performance matters here.
|
||||
return stream << ::std::basic_string<CharT>(sv);
|
||||
}
|
||||
|
||||
template <class CharT>
|
||||
CONSTEXPR_EXCEPT_GCC5 inline void swap(
|
||||
basic_string_view<CharT>& lhs,
|
||||
basic_string_view<CharT>& rhs) {
|
||||
lhs.swap(rhs);
|
||||
}
|
||||
|
||||
using string_view = basic_string_view<char>;
|
||||
|
||||
} // namespace c10
|
||||
|
||||
namespace std {
|
||||
template <class CharT>
|
||||
struct hash<::c10::basic_string_view<CharT>> {
|
||||
size_t operator()(::c10::basic_string_view<CharT> x) const {
|
||||
// The standard says that std""string_view hashing must do the same as
|
||||
// std::string hashing but leaves the details of std::string hashing
|
||||
// up to the implementer. So, to be conformant, we need to have the same
|
||||
// behavior as the implementer-defined std::string hasher of the STL
|
||||
// we're built against. Let's just call it. This is probably slow
|
||||
// but the only way to be conformant.
|
||||
return std::hash<::std::basic_string<CharT>>()(
|
||||
::std::basic_string<CharT>(x));
|
||||
}
|
||||
};
|
||||
} // namespace std
|
||||
|
||||
C10_CLANG_DIAGNOSTIC_POP()
|
||||
@@ -3,123 +3,138 @@
|
||||
#include <ATen/ATen.h>
|
||||
#include <ATen/core/ivalue.h>
|
||||
#include <c10d/ProcessGroup.hpp>
|
||||
#include <torch/csrc/Export.h>
|
||||
|
||||
namespace c10d {
|
||||
|
||||
// Broadcast many tensors to all processes in the process group.
|
||||
void broadcast_coalesced(
|
||||
TORCH_API void broadcast_coalesced(
|
||||
c10::intrusive_ptr<c10d::ProcessGroup> process_group,
|
||||
at::TensorList tensors,
|
||||
size_t buffer_size,
|
||||
int rank = 0);
|
||||
|
||||
// This class passes bucket contents tensor (for multiple replicas) to
|
||||
// DDP communication hook.
|
||||
// Optionally in the future this can be enhanced with parameter to bucket
|
||||
// mappings as well.
|
||||
class GradBucket {
|
||||
// This class passes bucket contents tensor to DDP communication hook.
|
||||
class TORCH_API GradBucket {
|
||||
public:
|
||||
explicit GradBucket(
|
||||
size_t index,
|
||||
const std::vector<at::Tensor>& tensors,
|
||||
const std::vector<size_t>& offsets = {},
|
||||
const std::vector<size_t>& lengths = {},
|
||||
const std::vector<c10::IntArrayRef>& sizes_vec = {})
|
||||
size_t bucket_count,
|
||||
const at::Tensor& tensor,
|
||||
const std::vector<size_t>& offsets,
|
||||
const std::vector<size_t>& lengths,
|
||||
const std::vector<c10::IntArrayRef>& sizes_vec,
|
||||
const std::vector<at::Tensor>& parameters)
|
||||
: index_(index),
|
||||
tensors_(tensors),
|
||||
bucket_count_(bucket_count),
|
||||
buffer_(tensor),
|
||||
offsets_(offsets),
|
||||
lengths_(lengths),
|
||||
sizes_vec_(sizes_vec) {}
|
||||
sizes_vec_(sizes_vec),
|
||||
parameters_(parameters) {}
|
||||
|
||||
// Returns the index of the bucket, which is unique across all the buckets.
|
||||
size_t getIndex() const {
|
||||
return index_;
|
||||
}
|
||||
|
||||
// Each tensor in the list that getTensors returns refers to the replica on
|
||||
// each device. There will be multiple replicas only in the case of single
|
||||
// process multiple device mode. In the single process single device mode,
|
||||
// this list would consist of only a single tensor.
|
||||
const std::vector<at::Tensor>& getTensors() const {
|
||||
return tensors_;
|
||||
const at::Tensor& getBuffer() const {
|
||||
return buffer_;
|
||||
}
|
||||
|
||||
// Returns a mutable tensor vector compared with the above method.
|
||||
std::vector<at::Tensor>& getTensorsRef() {
|
||||
return tensors_;
|
||||
// Returns a mutable buffer compared with the above method.
|
||||
at::Tensor& getBufferRef() {
|
||||
return buffer_;
|
||||
}
|
||||
|
||||
// Returns the start index of each variable in tensors_[0].
|
||||
const std::vector<size_t>& getOffsets() const {
|
||||
return offsets_;
|
||||
// Overwrites the buffer at a specific index.
|
||||
void setBuffer(at::Tensor& buffer) {
|
||||
buffer_ = buffer;
|
||||
}
|
||||
|
||||
// Returns the total (i.e., flattened) length of each variable in
|
||||
// tensors_[0].
|
||||
const std::vector<size_t>& getLengths() const {
|
||||
return lengths_;
|
||||
// Each tensor in the list that getGradients corresponds to a
|
||||
// parameter.
|
||||
std::vector<at::Tensor> getGradients() const;
|
||||
|
||||
// Returns model parameters belonging to this bucket. They are returned in the
|
||||
// same order as gradient tensors via getGradients(). For example,
|
||||
// getParameters[i] will have its gradient stored in
|
||||
// getGradients[i]
|
||||
const std::vector<at::Tensor> getParameters() const {
|
||||
return parameters_;
|
||||
}
|
||||
|
||||
// Returns the multi-dimensional sizes/shape of each variable in tensors_[0].
|
||||
const std::vector<c10::IntArrayRef>& getSizesVec() const {
|
||||
return sizes_vec_;
|
||||
// Returns whther this bucket is the last bucket to allreduce in an iteration.
|
||||
bool isLast() const {
|
||||
return index_ == bucket_count_ - 1;
|
||||
}
|
||||
|
||||
private:
|
||||
size_t index_;
|
||||
std::vector<at::Tensor> tensors_;
|
||||
size_t bucket_count_;
|
||||
at::Tensor buffer_;
|
||||
|
||||
// Per-variable info in tensors_[0].
|
||||
// Per-variable info in buffer_.
|
||||
std::vector<size_t> offsets_;
|
||||
std::vector<size_t> lengths_;
|
||||
std::vector<c10::IntArrayRef> sizes_vec_;
|
||||
// Model parameters for this bucket.
|
||||
const std::vector<at::Tensor> parameters_;
|
||||
};
|
||||
|
||||
// Base class of both `PythonCommHook` and `CppCommHook`.
|
||||
// Requires implementing 1) `runHook` method that communicates gradients
|
||||
// asynchronously, and 2) `parseHookResult` method that converts the hook
|
||||
// result into a tensor vector.
|
||||
class TORCH_PYTHON_API CommHookInterface {
|
||||
// result into a tensor.
|
||||
class TORCH_API CommHookInterface {
|
||||
public:
|
||||
virtual ~CommHookInterface() {}
|
||||
virtual ~CommHookInterface() = default;
|
||||
|
||||
// Passes the input grad bucket to the registered communication hook.
|
||||
// Once the tensors in the bucket are ready, kicks off the hook asynchronously
|
||||
// Once the tensor in the bucket are ready, kicks off the hook asynchronously
|
||||
// and returns a future that holds the communication results.
|
||||
virtual c10::intrusive_ptr<c10::ivalue::Future> runHook(
|
||||
GradBucket& bucket) = 0;
|
||||
|
||||
// Returns the resulting tensors once the communication hook result is
|
||||
// ready. The resulting tensors will then be copied to the grads of
|
||||
// Returns the resulting tensor once the communication hook result is
|
||||
// ready. The resulting tensor will then be copied to the grads of
|
||||
// individual parameters.
|
||||
virtual std::vector<at::Tensor> parseHookResult(
|
||||
virtual at::Tensor parseHookResult(
|
||||
const c10::IValue& result) = 0;
|
||||
};
|
||||
|
||||
namespace detail {
|
||||
// This helper function is called both by CppCommHookInterface below and inside
|
||||
// reducer.
|
||||
inline at::Tensor parseCppCommHookResult(
|
||||
const c10::IValue& result) {
|
||||
TORCH_INTERNAL_ASSERT(
|
||||
result.isTensor() || result.isTensorList(),
|
||||
"expected the hook result is either a Tensor or a TensorList");
|
||||
|
||||
if (result.isTensor()) {
|
||||
return result.toTensor();
|
||||
}
|
||||
|
||||
return result.toTensorVector()[0];
|
||||
}
|
||||
} // namespace detail
|
||||
|
||||
// This CppCommHook interface only requires implementing runHook method that
|
||||
// potentially uses a state.
|
||||
// Still need TORCH_PYTHON_API instead of TORCH_API to support Windows platform.
|
||||
template <typename T>
|
||||
class TORCH_PYTHON_API CppCommHookInterface : public CommHookInterface {
|
||||
class CppCommHookInterface : public CommHookInterface {
|
||||
public:
|
||||
explicit CppCommHookInterface(T& state) : state_(state) {}
|
||||
|
||||
virtual ~CppCommHookInterface() {}
|
||||
~CppCommHookInterface() override = default;
|
||||
|
||||
std::vector<at::Tensor> parseHookResult(const c10::IValue& result) override {
|
||||
TORCH_INTERNAL_ASSERT(
|
||||
result.isTensor() || result.isTensorList(),
|
||||
"expected the hook result is either a Tensor or a TensorList");
|
||||
|
||||
if (result.isTensor()) {
|
||||
return {result.toTensor()};
|
||||
}
|
||||
|
||||
return result.toTensorVector();
|
||||
at::Tensor parseHookResult(const c10::IValue& result) override {
|
||||
return detail::parseCppCommHookResult(result);
|
||||
}
|
||||
|
||||
protected:
|
||||
T state_; // Not owned.
|
||||
T state_;
|
||||
};
|
||||
|
||||
} // namespace c10d
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright (c) Meta Platforms, Inc. and its affiliates.
|
||||
// All rights reserved.
|
||||
//
|
||||
// This source code is licensed under the BSD-style license found in the
|
||||
// LICENSE file in the root directory of this source tree.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <c10/macros/Macros.h>
|
||||
|
||||
namespace c10d {
|
||||
|
||||
enum class DebugLevel {
|
||||
Off,
|
||||
Info,
|
||||
Detail
|
||||
};
|
||||
|
||||
TORCH_API void setDebugLevel(DebugLevel level);
|
||||
|
||||
// Sets the debug level based on the value of the `TORCH_DISTRIBUTED_DEBUG`
|
||||
// environment variable.
|
||||
TORCH_API void setDebugLevelFromEnvironment();
|
||||
|
||||
TORCH_API DebugLevel debug_level() noexcept;
|
||||
|
||||
} // namespace c10d
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <c10d/comm.hpp>
|
||||
#include <c10d/ProcessGroup.hpp>
|
||||
#include <c10d/comm.hpp>
|
||||
|
||||
namespace c10d {
|
||||
|
||||
@@ -15,7 +15,7 @@ class AllReduceCommHook : public CppCommHookInterface<ProcessGroup*> {
|
||||
explicit AllReduceCommHook(ProcessGroup* state)
|
||||
: CppCommHookInterface<ProcessGroup*>(state) {}
|
||||
|
||||
~AllReduceCommHook() override {}
|
||||
~AllReduceCommHook() override = default;
|
||||
|
||||
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
|
||||
};
|
||||
@@ -25,7 +25,22 @@ class FP16CompressCommHook : public CppCommHookInterface<ProcessGroup*> {
|
||||
explicit FP16CompressCommHook(ProcessGroup* state)
|
||||
: CppCommHookInterface<ProcessGroup*>(state) {}
|
||||
|
||||
~FP16CompressCommHook() override {}
|
||||
~FP16CompressCommHook() override = default;
|
||||
|
||||
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
|
||||
};
|
||||
|
||||
// Almost same as AllReduceCommHook, but without division inside the hook.
|
||||
// This enables the optimization of fusing copy and division and saves one scan
|
||||
// over all the input parameters, when no communication hook is provided by the user.
|
||||
// Only used internally and not released as a public built-in communication hook.
|
||||
class _AllReduceBySumCommHook
|
||||
: public CppCommHookInterface<ProcessGroup*> {
|
||||
public:
|
||||
explicit _AllReduceBySumCommHook(ProcessGroup* state)
|
||||
: CppCommHookInterface<ProcessGroup*>(state) {}
|
||||
|
||||
~_AllReduceBySumCommHook() override = default;
|
||||
|
||||
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
|
||||
};
|
||||
|
||||
@@ -1,261 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <ATen/ATen.h>
|
||||
#include <c10/util/Optional.h>
|
||||
#include <c10d/ProcessGroup.hpp>
|
||||
#include <c10d/Store.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace c10d {
|
||||
|
||||
#ifdef USE_C10D_GLOO
|
||||
constexpr char* GLOO_SOCKET_IFNAME_ENV = "GLOO_SOCKET_IFNAME";
|
||||
#endif
|
||||
|
||||
inline std::vector<std::string> split(
|
||||
char separator,
|
||||
const std::string& string) {
|
||||
std::vector<std::string> pieces;
|
||||
std::stringstream ss(string);
|
||||
std::string item;
|
||||
while (std::getline(ss, item, separator)) {
|
||||
pieces.push_back(std::move(item));
|
||||
}
|
||||
return pieces;
|
||||
}
|
||||
|
||||
class Backend {
|
||||
public:
|
||||
// Maps to Backend.__new__ in Python.
|
||||
static std::string get(const std::string&);
|
||||
|
||||
// TODO: How to support registering third_party backend?
|
||||
static void registerBackend();
|
||||
|
||||
private:
|
||||
// TODO: Should this be an enum list instead since this set doesn't
|
||||
// change at all.
|
||||
std::unordered_set<std::string> registered_backends_;
|
||||
};
|
||||
|
||||
class TORCH_PYTHON_API DistributedC10d : public torch::CustomClassHolder {
|
||||
public:
|
||||
static c10::intrusive_ptr<DistributedC10d> get();
|
||||
|
||||
DistributedC10d() = default;
|
||||
|
||||
void initProcessGroup(
|
||||
const std::string& backend,
|
||||
const std::string& init_method,
|
||||
const std::chrono::milliseconds& timeout,
|
||||
int64_t world_size,
|
||||
int64_t rank,
|
||||
c10::intrusive_ptr<Store> store,
|
||||
const std::string& group_name);
|
||||
|
||||
void destroyProcessGroup(c10::intrusive_ptr<ProcessGroup> group);
|
||||
int64_t getRank(const c10::intrusive_ptr<ProcessGroup>& group) const;
|
||||
int64_t getWorldSize(const c10::intrusive_ptr<ProcessGroup>& group) const;
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> isend(
|
||||
at::Tensor tensor,
|
||||
int64_t dst,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
c10::optional<int64_t>& tag);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> irecv(
|
||||
at::Tensor tensor,
|
||||
int64_t src,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
c10::optional<int64_t>& tag);
|
||||
|
||||
void send(
|
||||
at::Tensor tensor,
|
||||
int64_t dst,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
c10::optional<int64_t>& tag);
|
||||
|
||||
int64_t recv(
|
||||
at::Tensor tensor,
|
||||
const c10::optional<int64_t>& src,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
c10::optional<int64_t>& tag);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> broadcastMultiGPU(
|
||||
std::vector<at::Tensor>& tensor_list,
|
||||
int64_t src,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
bool async_op = false,
|
||||
int64_t src_tensor = 0);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> broadcast(
|
||||
at::Tensor tensor,
|
||||
int64_t src,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> allReduceMultiGPU(
|
||||
std::vector<at::Tensor>& tensor_list,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
ReduceOp op = ReduceOp::SUM,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> allReduce(
|
||||
at::Tensor tensor,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
ReduceOp op = ReduceOp::SUM,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> allReduceCoalesced(
|
||||
std::vector<at::Tensor>& tensors,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
ReduceOp op = ReduceOp::SUM,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> reduceMultiGPU(
|
||||
std::vector<at::Tensor>& tensor_list,
|
||||
int64_t dst,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
ReduceOp op = ReduceOp::SUM,
|
||||
bool async_op = false,
|
||||
int64_t dst_tensor = 0);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> reduce(
|
||||
at::Tensor tensor,
|
||||
int64_t dst,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
ReduceOp op = ReduceOp::SUM,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> allGatherMultiGPU(
|
||||
std::vector<std::vector<at::Tensor>>& output_tensor_lists,
|
||||
std::vector<at::Tensor>& input_tensor_list,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> allGather(
|
||||
std::vector<at::Tensor>& tensor_list,
|
||||
at::Tensor tensor,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> allGatherCoalesced(
|
||||
std::vector<std::vector<at::Tensor>>& output_tensor_lists,
|
||||
std::vector<at::Tensor>& input_tensor_list,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> gather(
|
||||
at::Tensor tensor,
|
||||
const c10::optional<std::vector<at::Tensor>>& gather_list,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
int64_t dst = 0,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> scatter(
|
||||
at::Tensor tensor,
|
||||
std::vector<at::Tensor>& scatter_list,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
int64_t src = 0,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> reduceScatterMultiGPU(
|
||||
std::vector<at::Tensor>& output_tensor_list,
|
||||
std::vector<std::vector<at::Tensor>>& input_tensor_lists,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
ReduceOp op = ReduceOp::SUM,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> reduceScatter(
|
||||
at::Tensor output,
|
||||
std::vector<at::Tensor>& input_tensor_list,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
ReduceOp op = ReduceOp::SUM,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> allToAllSingle(
|
||||
at::Tensor output,
|
||||
at::Tensor input,
|
||||
std::vector<int64_t>& output_split_sizes,
|
||||
std::vector<int64_t>& input_split_sizes,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> allToAll(
|
||||
std::vector<at::Tensor>& output_tensor_list,
|
||||
std::vector<at::Tensor>& input_tensor_list,
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup::Work> barrier(
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
bool async_op = false);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup> newGroup(
|
||||
std::vector<int64_t> ranks,
|
||||
std::chrono::milliseconds timeout,
|
||||
Backend backend);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup> worldProcessGroup();
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup> newProcessGroupHelper(
|
||||
const int64_t world_size,
|
||||
const int64_t rank,
|
||||
const std::vector<int64_t>& group_ranks,
|
||||
const std::string& backend_str,
|
||||
const c10::intrusive_ptr<Store>& store,
|
||||
c10::optional<std::string> group_name,
|
||||
int64_t timeout_milisesonds);
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup> getProcessGroupByName(
|
||||
const std::string& name) const;
|
||||
|
||||
std::string getNameOfProcessGroup(
|
||||
const c10::intrusive_ptr<ProcessGroup>& pg) const;
|
||||
|
||||
void registerProcessGroupName(const c10::intrusive_ptr<ProcessGroup>& process_group, const std::string& name);
|
||||
|
||||
private:
|
||||
|
||||
bool rankNotInGroup(const c10::intrusive_ptr<ProcessGroup>& group) const;
|
||||
int64_t getGroupRank(
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
const int64_t rank) const;
|
||||
int64_t getGlobalRank(
|
||||
const c10::intrusive_ptr<ProcessGroup>& group,
|
||||
const int64_t group_rank) const;
|
||||
void checkDefaultPg() const;
|
||||
int64_t getGroupSize(const c10::intrusive_ptr<ProcessGroup>& group) const;
|
||||
std::string getBackend(const c10::intrusive_ptr<ProcessGroup>& group);
|
||||
|
||||
std::string backend_;
|
||||
// TODO: Ask Alex what kind of equality we need. It determine whether we
|
||||
// need to use ProcessGroup or ProcesGroup* as key.
|
||||
std::unordered_map<
|
||||
c10::intrusive_ptr<ProcessGroup>,
|
||||
std::pair<std::string, c10::intrusive_ptr<Store>>>
|
||||
pg_map_;
|
||||
|
||||
// Note, this is different mapping relationship than original Python
|
||||
// implementation.
|
||||
std::unordered_map<c10::intrusive_ptr<ProcessGroup>, std::string> pg_names_;
|
||||
|
||||
// Process group's global rank to local rank mapping
|
||||
std::unordered_map<
|
||||
c10::intrusive_ptr<ProcessGroup>,
|
||||
std::unordered_map<int64_t, int64_t>>
|
||||
pg_group_ranks_;
|
||||
|
||||
c10::intrusive_ptr<ProcessGroup> default_pg_;
|
||||
|
||||
// Default value should be "env://"
|
||||
std::string default_pg_init_method_;
|
||||
|
||||
int64_t group_count_;
|
||||
};
|
||||
|
||||
} // namespace c10d
|
||||
@@ -0,0 +1,110 @@
|
||||
#include <c10/util/Logging.h>
|
||||
#include <c10d/reducer.hpp>
|
||||
|
||||
#include <mutex>
|
||||
|
||||
namespace c10d {
|
||||
|
||||
class TORCH_API Logger {
|
||||
public:
|
||||
explicit Logger(std::shared_ptr<c10d::Reducer> reducer);
|
||||
// Set logging data that can be got during DistributedDataParallel
|
||||
// construction time.
|
||||
void set_construction_data_and_log(
|
||||
const std::string& module_name,
|
||||
const std::vector<int>& device_ids,
|
||||
int output_device,
|
||||
bool broadcast_buffers,
|
||||
bool has_sync_bn);
|
||||
|
||||
void set_static_graph();
|
||||
|
||||
// An interface for users to get DDPLoggingData and log them
|
||||
// in the applications. Explanation of logging fields are in
|
||||
// "struct DDPLoggingData" of "torch/c10/util/Logging.h".
|
||||
at::DDPLoggingData get_ddp_logging_data();
|
||||
|
||||
// Stream insertion operator for logging data to stream under
|
||||
// TORCH_DISTRIBUTED_DEBUG.
|
||||
friend std::ostream& operator<<(std::ostream& output, const Logger& logger);
|
||||
|
||||
~Logger() noexcept(false) {
|
||||
// Log if DDP graph is static in Logger dtor instead of Reducer dtor since
|
||||
// Logger is deleted before Reducer.
|
||||
log_if_graph_static(reducer_->ddp_graph_static());
|
||||
}
|
||||
|
||||
// Set environment variables.
|
||||
void set_env_variables();
|
||||
// Set parameters stats.
|
||||
void set_parameter_stats();
|
||||
// Get size of each bucket (Bytes).
|
||||
std::vector<int> get_bucket_sizes();
|
||||
// Get bucket size limits specified during DDP construction.
|
||||
std::vector<int> get_bucket_size_limits();
|
||||
// Get variable indices for each bucket.
|
||||
std::vector<std::vector<size_t>> get_per_bucket_variable_indices();
|
||||
// Set comm. hook, if used
|
||||
void set_comm_hook(const std::string& hook);
|
||||
// Set running with uneven input detection (model.join() context manager)
|
||||
void set_uneven_input_join();
|
||||
|
||||
// Reset performance stats at current iteration
|
||||
void reset_performance_stats();
|
||||
|
||||
// Calculate avg stats using cpu timer and gpu timer
|
||||
// that has been recorded in reducer.
|
||||
void calculate_avg_time(
|
||||
int64_t& avg_time,
|
||||
int64_t& time_duration,
|
||||
Timer& timer,
|
||||
Timer::Event start_event,
|
||||
Timer::Event end_event);
|
||||
|
||||
// Set the absolute time of the event that has been recorded in reducer.
|
||||
void set_event_time(
|
||||
int64_t& event_time,
|
||||
Timer& timer,
|
||||
Timer::Event event
|
||||
);
|
||||
// Set stats that can be collected only during
|
||||
// training loop. It is called at the beginning of forward call
|
||||
// to record the run time stats of sampled iterations that previouly ran.
|
||||
// GPU performance stats are collected only for single process
|
||||
// single device program and single device module right now.
|
||||
// TODO to support single process multiple devices and multi device modules,
|
||||
// events need to be created and recorded on multiple devices.
|
||||
void set_runtime_stats_and_log();
|
||||
|
||||
// Called when DDP/reducer is failing with an error. The
|
||||
// logging data structure will have two fields filled: "has_error" indicating
|
||||
// that this iteration encountered an error and other fields are not valid,
|
||||
// and "error", a string which contains the error message that DDP failed
|
||||
// with.
|
||||
template <typename... Args>
|
||||
void set_error_and_log(const std::string& ddp_error, const Args&... args) {
|
||||
ddp_logging_data_->ints_map["has_error"] = 1;
|
||||
auto err = c10::str(ddp_error, args...);
|
||||
ddp_logging_data_->strs_map["error"] = err;
|
||||
// Report the iteration we are erroring at so user knows how many examples
|
||||
// successfully processed before this error was hit.
|
||||
ddp_logging_data_->ints_map["iteration"] = reducer_->num_iterations_;
|
||||
at::LogPyTorchDDPUsage(*ddp_logging_data_);
|
||||
}
|
||||
|
||||
// When running without static graph, called when reducer is destroyed to log
|
||||
// if graph was actually static and is a candidate for static graph
|
||||
// optimization.
|
||||
void log_if_graph_static(bool is_static);
|
||||
|
||||
|
||||
private:
|
||||
// ddp_logging_data_ is used to hold all the ddp related logging
|
||||
// data fields.
|
||||
std::unique_ptr<at::DDPLoggingData> ddp_logging_data_;
|
||||
std::shared_ptr<c10d::Reducer> reducer_;
|
||||
// track the number of iterations when runtime stats are collected so far.
|
||||
long num_iterations_stats_recorded_ = 0;
|
||||
};
|
||||
|
||||
} // namespace c10d
|
||||
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include <torch/csrc/WindowsTorchApiMacro.h>
|
||||
#include <cstdint>
|
||||
|
||||
namespace torch {
|
||||
|
||||
@@ -14,7 +14,7 @@ class TORCH_PYTHON_API PythonCommHook : public CommHookInterface {
|
||||
// Takes a state and a callable hook. The inputs are Python objects.
|
||||
// The state is passed to the hook in runHook method, and it can be used to
|
||||
// maintain and update any state information during the execution of the hook.
|
||||
// The hook performs user-specified processing and returns a future indicating
|
||||
// The hook performs user-specifieds processing and returns a future indicating
|
||||
// asychronous communication of gradients.
|
||||
PythonCommHook(py::object state, py::object hook)
|
||||
: state_(std::move(state)), hook_(std::move(hook)) {}
|
||||
@@ -23,7 +23,7 @@ class TORCH_PYTHON_API PythonCommHook : public CommHookInterface {
|
||||
|
||||
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
|
||||
|
||||
std::vector<at::Tensor> parseHookResult(const c10::IValue& result) override;
|
||||
at::Tensor parseHookResult(const c10::IValue& result) override;
|
||||
|
||||
private:
|
||||
// Only needed for stateful communication.
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include <torch/csrc/utils/future.h>
|
||||
#include <torch/types.h>
|
||||
#include <vector>
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
|
||||
#include <torch/csrc/distributed/rpc/rref_impl.h>
|
||||
#include <torch/csrc/python_headers.h>
|
||||
#include <torch/csrc/utils/pybind.h>
|
||||
|
||||
namespace torch {
|
||||
namespace distributed {
|
||||
namespace rpc {
|
||||
|
||||
enum RRefProxyType { RPC_SYNC, RPC_ASYNC, REMOTE };
|
||||
|
||||
// Python wrapper of an RRef shared_ptr that supports Python
|
||||
// pickle and unpickle.
|
||||
class PYBIND11_EXPORT PyRRef {
|
||||
public:
|
||||
// The first ctor can only be called while holding GIL. See its implementation
|
||||
// for more explanations.
|
||||
explicit PyRRef(const py::object& value, const py::object& type_hint);
|
||||
explicit PyRRef(c10::intrusive_ptr<RRef> rref);
|
||||
~PyRRef();
|
||||
|
||||
bool isOwner() const;
|
||||
bool confirmedByOwner() const;
|
||||
WorkerInfo owner() const;
|
||||
std::string ownerName() const;
|
||||
py::object toHere(
|
||||
const float timeoutSeconds =
|
||||
torch::distributed::rpc::kUnsetRpcTimeout) const;
|
||||
py::object localValue() const;
|
||||
std::string str() const;
|
||||
py::tuple pickle() const;
|
||||
static PyRRef unpickle(const py::tuple& t);
|
||||
c10::IValue toIValue() const;
|
||||
// Future that is associated with the creation of this RRef on the remote end.
|
||||
// This is only used to get the future corresponding to the rref for profiling
|
||||
// use cases.
|
||||
c10::intrusive_ptr<JitFuture> getFuture() const;
|
||||
// Keeps track of the future responsible for profiling owner creation
|
||||
// acknowledgement
|
||||
c10::intrusive_ptr<JitFuture> getProfilingFuture() const;
|
||||
// Sets the future responsible for profiling owner creation acknowledgement.
|
||||
// This future is set from python to be a future that returns when profiling
|
||||
// callbacks have been run.
|
||||
void setProfilingFuture(c10::intrusive_ptr<JitFuture> profilingFuture);
|
||||
|
||||
// create a proxy on this RRef, which can be used to launch RPC on the owner
|
||||
// of this RRef to run functions on the object referenced by this RRef.
|
||||
py::object createRRefProxy(
|
||||
const RRefProxyType& mode,
|
||||
float timeoutSeconds = rpc::kUnsetRpcTimeout) const;
|
||||
|
||||
// get the type of the data object referenced by this RRef. Timeout argument
|
||||
// is only used in the first invocation of this function as an argument to the
|
||||
// RPC to the owner node of the RRef.
|
||||
py::object getRRefType(
|
||||
float timeout = rpc::kUnsetRpcTimeout,
|
||||
bool blocking = true);
|
||||
|
||||
// Run the backward pass with the RRef as the root.
|
||||
void backward(int64_t autogradContextId, bool retainGraph);
|
||||
|
||||
// Helper static function to run backward on a given rref.
|
||||
static void backward(
|
||||
int64_t autogradContextId,
|
||||
bool retainGraph,
|
||||
const c10::intrusive_ptr<RRef>& rref);
|
||||
|
||||
// Specialization of backward if the rref is an OwnerRRef.
|
||||
static void backwardOwnerRRef(
|
||||
int64_t autogradContextId,
|
||||
bool retainGraph,
|
||||
IValue value);
|
||||
|
||||
private:
|
||||
c10::intrusive_ptr<RRef> rref_;
|
||||
c10::optional<c10::intrusive_ptr<JitFuture>> profilingFuture_;
|
||||
c10::optional<py::object> type_;
|
||||
};
|
||||
|
||||
} // namespace rpc
|
||||
} // namespace distributed
|
||||
} // namespace torch
|
||||
@@ -0,0 +1,413 @@
|
||||
#pragma once
|
||||
|
||||
#include <ATen/core/jit_type.h>
|
||||
#include <ATen/core/rref_interface.h>
|
||||
#include <c10/core/Event.h>
|
||||
#include <c10/util/Optional.h>
|
||||
#include <torch/csrc/distributed/rpc/message.h>
|
||||
#include <torch/csrc/distributed/rpc/rpc_agent.h>
|
||||
#include <torch/csrc/distributed/rpc/types.h>
|
||||
|
||||
#include <atomic>
|
||||
|
||||
namespace torch {
|
||||
namespace distributed {
|
||||
namespace rpc {
|
||||
|
||||
class RRef;
|
||||
class RRefContext;
|
||||
class UserRRef;
|
||||
|
||||
constexpr int OWNER_IDX = 0; // index of ownerId in the tuple
|
||||
constexpr int RREFID_ON_IDX = 1; // index of RRefId.createdOn_ in the tuple
|
||||
constexpr int RREFID_ID_IDX = 2; // index of RRefId.localId_ in the tuple
|
||||
constexpr int FORKID_ON_IDX = 3; // index of ForkId.createdOn_ in the tuple
|
||||
constexpr int FORKID_ID_IDX = 4; // index of ForkId.localId_ in the tuple
|
||||
constexpr int PARENT_IDX = 5; // index of parent in the tuple
|
||||
constexpr int TYPE_IDX = 6; // index of parent in the tuple
|
||||
|
||||
// NB: if more fields are added, make sure this field is also bumped
|
||||
constexpr int RFD_TUPLE_SIZE = 7; // number of RRefForkData fields in py::tuple
|
||||
|
||||
// Represents fork of an RRef to be sent over the wire.
|
||||
struct TORCH_API RRefForkData {
|
||||
const worker_id_t ownerId_;
|
||||
const RRefId rrefId_;
|
||||
const ForkId forkId_;
|
||||
const worker_id_t parent_;
|
||||
const std::string typeStr_;
|
||||
|
||||
RRefForkData(
|
||||
worker_id_t ownerId,
|
||||
const RRefId& rrefId,
|
||||
const ForkId& forkId,
|
||||
worker_id_t parent,
|
||||
std::string typeStr);
|
||||
};
|
||||
|
||||
// Note [RRef Protocol]
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// [Background]
|
||||
//
|
||||
// RRef stands for Remote REFerence. Each RRef is owned by a single worker
|
||||
// (i.e., owner) and can be used by multiple users. The owner stores the real
|
||||
// data referenced by its RRefs. RRef needs to support fast and scalable RPC.
|
||||
// Hence, in the design, we avoid using a single global master to keep RRef
|
||||
// states, instead owners will keep track of the global reference counts
|
||||
// for its RRefs. Every RRef can be uniquely identified by a global RRefId,
|
||||
// which is assigned at the time it is first created either on a user or on the
|
||||
// owner.
|
||||
//
|
||||
// On the owner worker, there is only one OwnerRRef instance, which contains the
|
||||
// real data, while on user workers, there can be as many UserRRefs as
|
||||
// necessary, and UserRRef does not hold the data. All usage on the OwnerRRef
|
||||
// should retrieve the unique OwnerRRef instance using the globally unique
|
||||
// RRefId. //A UserRRef will be created when it is used as an argument or return
|
||||
// value in dist.rpc or dist.remote call, but RRef forking and reference
|
||||
// counting (RC) are completely transparent to applications. Every UserRRef will
|
||||
// also have its globally unique ForkId.
|
||||
//
|
||||
// [Assumptions]
|
||||
//
|
||||
// 1. Transient Network Failures
|
||||
//
|
||||
// The RRef design handles transient network failures by retrying
|
||||
// messages. Node crashes or permanent network partition is beyond the scope.
|
||||
// When those incidents occur, the application may take down all workers, revert
|
||||
// to the previous checkpoint, and resume training.
|
||||
//
|
||||
// 2. Non-idempotent UDFs
|
||||
//
|
||||
// We assume UDFs are not idempotent and therefore cannot be retried. However,
|
||||
// internal RRef control messages are idempotent and retried upon message
|
||||
// failure.
|
||||
//
|
||||
// 3. Out of Order Message Delivery
|
||||
//
|
||||
// We do not assume message delivery order between any pair of nodes, because
|
||||
// both sender and receiver are using multiple threads. There is no guarantee on
|
||||
// which message will be processed first.
|
||||
//
|
||||
// [RRef Lifetime]
|
||||
//
|
||||
// The goal of the protocol is to delete an OwnerRRef at an appropriate time.
|
||||
// The right time to delete an OwnerRRef is when there are no living UserRRefs
|
||||
// and Python GC also agrees to delete the OwnerRRef instance on the owner. The
|
||||
// tricky part is to determine if there are any living UserRRefs.
|
||||
//
|
||||
// A user can get a UserRRef in three situations:
|
||||
//
|
||||
// (1). Receiving a UserRRef from the owner.
|
||||
// (2). Receiving a UserRRef from another user.
|
||||
// (3). Creating a new UserRRef owned by another worker.
|
||||
//
|
||||
// (1) is the simplest case where the owner initiates the fork, and hence it can
|
||||
// easily increment local RC. The only requirement is that any UserRRef must
|
||||
// notify the owner before destruction. Hence, we need the first guarantee:
|
||||
//
|
||||
// G1. The owner will be notified when any UserRRef is deleted.
|
||||
//
|
||||
// As messages might come delayed or out-of-order, we need more one guarantee to
|
||||
// make sure the delete message is not sent out too soon. Let us first introduce
|
||||
// a new concept. If A sends an RPC to B that involves an RRef, we call the RRef
|
||||
// on A the parent RRef and the RRef on B the child RRef.
|
||||
//
|
||||
// G2. Parent RRef cannot be deleted until the child RRef is confirmed by the
|
||||
// owner.
|
||||
//
|
||||
// Under (1), where the caller is UserRRef and callee is OwnerRRef, it simply
|
||||
// means that the user will not send out the delete message until all previous
|
||||
// messages are ACKed. Note that ACKed does not mean the owner finishes
|
||||
// executing the function, instead, it only means the owner has retrieved its
|
||||
// local OwnerRRef and about to pass it to the function, which is sufficient to
|
||||
// keep the OwnerRRef alive even if the delete message from the user arrives at
|
||||
// the owner before the function finishes execution.
|
||||
//
|
||||
// With (2) and (3), it is possible that the owner only partially knows the RRef
|
||||
// fork graph or not even knowing it at all. For example, the RRef could be
|
||||
// constructed on a user, and before the owner receives the RPC call, the
|
||||
// creator user might have already shared the RRef with other users, and those
|
||||
// users could further share the RRef. One invariant is that the fork graph of
|
||||
// any RRef is always a tree rooted at the owner, because forking an RRef always
|
||||
// creates a new RRef instance, and hence every RRef has a single parent. One
|
||||
// nasty detail is that when an RRef is created on a user, technically the owner
|
||||
// is not its parent but we still consider it that way and it does not break the
|
||||
// argument below.
|
||||
//
|
||||
// The owner's view on any node (fork) in the tree has three stages:
|
||||
//
|
||||
// 1) unknown -> 2) known -> 3) deleted.
|
||||
//
|
||||
// The owner's view on the entire tree keeps changing. The owner deletes its
|
||||
// OwnerRRef instance when it thinks there are no living UserRRefs, i.e., when
|
||||
// OwnerRRef is deleted, all UserRRefs could be either indeed deleted or
|
||||
// unknown. The dangerous case is when some forks are unknown and others are
|
||||
// deleted.
|
||||
//
|
||||
// G2 trivially guarantees that no parent UserRRef Y can be deleted before the
|
||||
// owner knows all of Y's children UserRRefs.
|
||||
//
|
||||
// However, it is possible that the child UserRRef Z may be deleted before the
|
||||
// owner knows its parent Y. More specifically, this can happen when all of Z's
|
||||
// messages are processed by the owner before all messages from Y, including the
|
||||
// delete message. Nevertheless, this does not cause any problem. Because, at
|
||||
// least one of Y's ancestor will be alive, and it will prevent the owner from
|
||||
// deleting the OwnerRRef. Consider the following example: (NB: this scenario
|
||||
// will no longer relevant when we block UDF until all RRefs are confirmed by
|
||||
// the owner)
|
||||
//
|
||||
// OwnerRRef -> A -> Y -> Z
|
||||
//
|
||||
// OwnerRRef forks to A, then A forks to Y, and Y forks to Z. Z can be deleted
|
||||
// without OwnerRRef knowing Y. However, the OwnerRRef will at least know A, as
|
||||
// the owner directly forks the RRef to A. A won't die before the owner knows Y.
|
||||
//
|
||||
// Things get a little trickier if the RRef is created on a user:
|
||||
//
|
||||
// OwnerRRef
|
||||
// ^
|
||||
// |
|
||||
// A -> Y -> Z
|
||||
//
|
||||
// If Z calls to_here on the UserRRef, the owner at least knows A when Z is
|
||||
// deleted, because otherwise to_here wouldn't finish. If Z does not call
|
||||
// to_here, it is possible that the owner receives all messages from Z before
|
||||
// any message from A and Y. In this case, as the real data of the OwnerRRef has
|
||||
// not been created yet, there is nothing to be deleted either. It is the same
|
||||
// as Z does not exist at all Hence, it's still OK.
|
||||
//
|
||||
// See #26759 for more details and discussions.
|
||||
//
|
||||
// ``RRef`` is the base type for both ``UserRRef`` and ``OwnerRRef``.
|
||||
// Each ``RRef`` has a globally unique ``RRefId``.
|
||||
class TORCH_API RRef : public RRefInterface {
|
||||
public:
|
||||
// RRef is made NOT copyable NOT movable to prevent messing up reference
|
||||
// counting.
|
||||
explicit RRef(const RRef& other) = delete;
|
||||
explicit RRef(RRef&& other) = delete;
|
||||
RRef& operator=(RRef&& other) = delete;
|
||||
|
||||
~RRef() override = default;
|
||||
|
||||
// returns the worker id of the owner
|
||||
inline worker_id_t owner() const override {
|
||||
return ownerId_;
|
||||
}
|
||||
|
||||
// returns the worker name of the owner
|
||||
inline std::string ownerName() const override {
|
||||
return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_).name_;
|
||||
}
|
||||
|
||||
// returns the worker info of the owner
|
||||
inline WorkerInfo ownerWorkerInfo() const {
|
||||
return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_);
|
||||
}
|
||||
|
||||
// Returns the globally unique RRefId of this RRef
|
||||
inline const RRefId& rrefId() const {
|
||||
return rrefId_;
|
||||
}
|
||||
|
||||
inline bool isPyObj() const {
|
||||
return type_ == PyObjectType::get();
|
||||
}
|
||||
inline const TypePtr type() const override {
|
||||
return type_;
|
||||
}
|
||||
|
||||
// Save the future corresponding to the creation of this RRef on a remote
|
||||
// node. Note that this is only set when processing requests invoked with
|
||||
// rpc.remote. This is only used to get the future corresponding to the rref
|
||||
// for profiling use cases.
|
||||
inline void registerOwnerCreationFuture(c10::intrusive_ptr<JitFuture> fut) {
|
||||
ownerCreationFuture_ = std::move(fut);
|
||||
}
|
||||
|
||||
// Get the future corresponding to the creation of this rref.
|
||||
inline c10::intrusive_ptr<JitFuture> getOwnerCreationFuture() const {
|
||||
return ownerCreationFuture_;
|
||||
}
|
||||
|
||||
// Check if creation of this RRef on owner node has timed out.
|
||||
inline bool getTimedOut() const {
|
||||
return timedOut_.load();
|
||||
}
|
||||
|
||||
// Dispatches an error to the correct handler based on its RPCErrorType.
|
||||
void handleError(RPCErrorType errorType, const JitFuture& JitFuture);
|
||||
|
||||
// Send delete UserRRef request to Owner,
|
||||
// if the request hasn't been sent yet.
|
||||
// There are 2 cases to call it,
|
||||
// 1, Python GC decides end of UserRRef lifetime, calling destructor.
|
||||
// 2, RPC module graceful shutdown calls it on all UserRRefs tracked
|
||||
// in the RRefContext.
|
||||
virtual void tryDel() {}
|
||||
|
||||
protected:
|
||||
// Indicates that the creation of this RRef on owner node has timed out.
|
||||
inline void setTimedOut() {
|
||||
timedOut_ = true;
|
||||
}
|
||||
friend class RRefContext;
|
||||
|
||||
RRef(worker_id_t ownerId, const RRefId& rrefId, TypePtr type);
|
||||
|
||||
virtual RRefForkData fork() const;
|
||||
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
||||
const worker_id_t ownerId_;
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
||||
const RRefId rrefId_;
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
||||
std::atomic<bool> timedOut_{false};
|
||||
|
||||
// type field to denote the type of the element that the RRef is holding
|
||||
// it could be any TypePtr that JIT support, including PyObjectType
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
||||
const TypePtr type_;
|
||||
// Future corresponding to request to create RRef on remote node.
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
|
||||
c10::intrusive_ptr<JitFuture> ownerCreationFuture_;
|
||||
};
|
||||
|
||||
// ``UserRRef`` represents a user of an RRef. Besides the ``RRefId``, each user
|
||||
// also has a globally unique ``ForkId`` to identify this user. ``UserRRef``
|
||||
// never owns the real value, the only way to get the value of the ``RRef`` is
|
||||
// to call ``to_here()`` and get a copy..
|
||||
class TORCH_API UserRRef final : public RRef {
|
||||
public:
|
||||
UserRRef(const UserRRef& other) = delete;
|
||||
UserRRef(UserRRef&& other) = delete;
|
||||
UserRRef& operator=(const UserRRef& other) = delete;
|
||||
UserRRef& operator=(UserRRef&& other) = delete;
|
||||
|
||||
UserRRef(
|
||||
worker_id_t ownerId,
|
||||
const RRefId& rrefId,
|
||||
const ForkId& forkId,
|
||||
TypePtr type);
|
||||
|
||||
inline bool isOwner() const override {
|
||||
return false;
|
||||
}
|
||||
|
||||
inline bool confirmedByOwner() const override {
|
||||
return confirmedByOwner_;
|
||||
}
|
||||
|
||||
// Returns the globally unique ForkId of this RRef
|
||||
const ForkId& forkId() const;
|
||||
|
||||
// Get of copy of the value from the ``OwnerRRef``. If the value is not ready
|
||||
// yet, this call will block.
|
||||
IValue toHere(
|
||||
const float timeoutSeconds =
|
||||
torch::distributed::rpc::kUnsetRpcTimeout) const;
|
||||
|
||||
void tryDel() override;
|
||||
|
||||
// Will be called when refcount reaches 0.
|
||||
// Upon destruction, this ``UserRRef`` will tell the owner to deref.
|
||||
void release_resources() override;
|
||||
|
||||
// Will be called when both refcount and weakcount reach 0. See
|
||||
// https://github.com/pytorch/pytorch/blob/9116f02bebf3a5260feef5732d36c54ecb3b4033/c10/util/intrusive_ptr.h#L204
|
||||
// This is called on destructing the wrapping intrusive_ptr_target instance
|
||||
// and it's data members. We don't need to implement anything here.
|
||||
~UserRRef() override = default;
|
||||
|
||||
private:
|
||||
friend class RRefContext;
|
||||
|
||||
RRefForkData fork() const override;
|
||||
inline void confirm() {
|
||||
confirmedByOwner_ = true;
|
||||
}
|
||||
|
||||
const ForkId forkId_;
|
||||
|
||||
// Indicates if this user has sent delete message to it's owner.
|
||||
// Note, thread safety is needed because delete message could be sent by
|
||||
// either the destructor called by Python garbage collection or RRefContext
|
||||
// proactive cleanup on RPC graceful shutdown.
|
||||
std::mutex deletedOnOwnerMutex_;
|
||||
bool deletedOnOwner_{false};
|
||||
// Indicating whether this UserRRef has been confirmed by its owner.
|
||||
std::atomic<bool> confirmedByOwner_;
|
||||
};
|
||||
|
||||
// Keep the template only on the derived class because ``RRefContext`` needs to
|
||||
// erase the type on ``RRef`` and keep them in one map.
|
||||
class TORCH_API OwnerRRef final : public RRef {
|
||||
public:
|
||||
OwnerRRef(const OwnerRRef& other) = delete;
|
||||
OwnerRRef(OwnerRRef&& other) = delete;
|
||||
OwnerRRef& operator=(const OwnerRRef& other) = delete;
|
||||
OwnerRRef& operator=(OwnerRRef&& other) = delete;
|
||||
|
||||
OwnerRRef(
|
||||
worker_id_t ownerId,
|
||||
const RRefId& rrefId,
|
||||
TypePtr type,
|
||||
std::vector<c10::Device> devices);
|
||||
|
||||
OwnerRRef(
|
||||
worker_id_t ownerId,
|
||||
const RRefId& rrefId,
|
||||
TypePtr type,
|
||||
c10::optional<IValue> value,
|
||||
std::vector<c10::Device> devices);
|
||||
|
||||
inline bool isOwner() const override {
|
||||
return true;
|
||||
}
|
||||
|
||||
// OwnerRRef is always confirmed, while UserRRef is only confirmed when the
|
||||
// owner knows about it.
|
||||
inline bool confirmedByOwner() const override {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Get a constant reference of the real value. This method will block if the
|
||||
// value is not ready. This method does not need GIL as it does not create
|
||||
// any new py::object. It will throw if there is an error.
|
||||
const IValue& getValue() const;
|
||||
|
||||
// Set the value of this ``OwnerRRef``. This method does not need GIL as it
|
||||
// does not create any new py::object.
|
||||
void setValue(IValue&& value);
|
||||
// Sets the value of this ``OwnerRRef`` to contain an exception.
|
||||
void setError(std::exception_ptr eptr);
|
||||
|
||||
// Has a value or error been set?
|
||||
bool hasValue() const;
|
||||
// Gets a future that is satisfied when the value or error is set.
|
||||
c10::intrusive_ptr<JitFuture> getFuture();
|
||||
|
||||
private:
|
||||
friend class RRefContext;
|
||||
|
||||
c10::intrusive_ptr<JitFuture> future_;
|
||||
};
|
||||
|
||||
TORCH_API std::ostream& operator<<(std::ostream& os, const RRef& rref);
|
||||
|
||||
// Helper function that casts from c10::RRefInterface to OwnerRRef
|
||||
inline TORCH_API c10::intrusive_ptr<OwnerRRef> fromRRefInterface(
|
||||
const c10::intrusive_ptr<c10::RRefInterface>& rrefInterface) {
|
||||
return c10::static_intrusive_pointer_cast<OwnerRRef>(rrefInterface);
|
||||
}
|
||||
|
||||
// Helper function that casts from OwnerRRef to c10::RRefInterface
|
||||
inline TORCH_API c10::intrusive_ptr<c10::RRefInterface> fromOwnerRRef(
|
||||
const c10::intrusive_ptr<RRef>& ownerRRef) {
|
||||
return c10::static_intrusive_pointer_cast<c10::RRefInterface>(ownerRRef);
|
||||
}
|
||||
|
||||
} // namespace rpc
|
||||
} // namespace distributed
|
||||
} // namespace torch
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
#include <torch/csrc/StorageDefs.h>
|
||||
|
||||
THP_API PyObject * THPStorage_(New)(THWStorage *ptr);
|
||||
TORCH_PYTHON_API PyObject * THPStorage_(New)(c10::intrusive_ptr<c10::StorageImpl> ptr);
|
||||
extern PyObject *THPStorageClass;
|
||||
|
||||
#include <torch/csrc/Types.h>
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
#else
|
||||
|
||||
template <class io>
|
||||
void THPStorage_(writeFileRaw)(THWStorage *self, io fd, bool save_size);
|
||||
void THPStorage_(writeFileRaw)(c10::StorageImpl *self, io fd, bool save_size, uint64_t element_size);
|
||||
|
||||
template <class io>
|
||||
THWStorage * THPStorage_(readFileRaw)(io fd, THWStorage *storage);
|
||||
c10::intrusive_ptr<c10::StorageImpl> THPStorage_(readFileRaw)(
|
||||
io fd, c10::intrusive_ptr<c10::StorageImpl> storage, uint64_t element_size);
|
||||
|
||||
#endif
|
||||
|
||||
@@ -11,8 +11,6 @@
|
||||
struct THPStorage;
|
||||
struct THSPTensor;
|
||||
|
||||
typedef class THPPointer<THWStorage> THWStoragePtr;
|
||||
typedef class THPPointer<THWTensor> THWTensorPtr;
|
||||
typedef class THPPointer<THPStorage> THPStoragePtr;
|
||||
|
||||
#if (!defined(THC_GENERIC_FILE)) && \
|
||||
|
||||