Compare commits

...
46 Commits
Author SHA1 Message Date
pta-robot 34bf0fd1fc !8676 Update op_plugin commit id
Merge pull request !8676 from pta-robot/v2.1.0-5.0.rc3
2023-12-30 00:08:53 +00:00
huangyunlong 54db8c4f92 !7347 [Feature]support new socversion.
Merge pull request !7347 from huangyunlong/2.1r3
2023-11-13 03:42:39 +00:00
pta-robot b440c2759b !7252 Update op_plugin commit id
Merge pull request !7252 from pta-robot/v2.1.0-5.0.rc3
2023-11-09 12:55:59 +00:00
weili10 b6656eb341 update README.md.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-10-23 08:09:42 +00:00
weili10 6a009df7a9 update README.zh.md.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-10-23 08:06:29 +00:00
weili10 75e0c9fb87 update README.zh.md.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-10-23 08:01:05 +00:00
pta-robot 842bae84a8 !6697 Update op_plugin commit id
Merge pull request !6697 from pta-robot/v2.1.0-5.0.rc3
2023-10-19 12:00:30 +00:00
彭子荣 ee21f9e7e5 !6580 Update readme.zh & readme
Merge pull request !6580 from 彭子荣/v2.1.0-5.0.rc3
2023-10-16 13:30:02 +00:00
赖长铃 579994f831 !6590 update commit id of opplugin
Merge pull request !6590 from 赖长铃/update_id_v2.1.0-5.0.rc3_10_13_8_31
2023-10-13 11:09:36 +00:00
chuboning 7d164f7213 !6529 Add Dockerfile for building
Merge pull request !6529 from chuboning/v2.1.0-5.0.rc3
2023-10-13 06:20:39 +00:00
pta-robot 3ab2c5a533 !6569 Update op_plugin commit id
Merge pull request !6569 from pta-robot/v2.1.0-5.0.rc3
2023-10-13 04:44:47 +00:00
pta-robot 163311aad6 !6522 Update op_plugin commit id
Merge pull request !6522 from pta-robot/v2.1.0-5.0.rc3
2023-10-12 12:37:27 +00:00
xudaohong 1a0fd40a67 !6494 [feat] change event destroy from sync to async in NPUGuardImpl
Merge pull request !6494 from xudaohong/cherry-pick-1697004900
2023-10-12 09:56:24 +00:00
pta-robot 632f0629d6 !6509 Update op_plugin commit id
Merge pull request !6509 from pta-robot/v2.1.0-5.0.rc3
2023-10-12 00:31:33 +00:00
闫鹏全 9a3a91e7b5 !6432 [Fix] fix fsdp by saving and recovering context.
Merge pull request !6432 from 闫鹏全/v2.1.0-5.0.rc3
2023-10-11 11:27:50 +00:00
chuboning 08d86fca7c !6498 Add pypi support for torch_npu
Merge pull request !6498 from chuboning/v2.1.0-5.0.rc3
2023-10-11 09:57:05 +00:00
刘哲续 71d923f5b6 !6477 update commit id in v2.1.0-5.0.rc3
Merge pull request !6477 from 刘哲续/update_id_v2r1_10_10_2_30
2023-10-10 15:17:33 +00:00
chuboning 39cb05a7c2 !6434 Update readme for installing torch
Merge pull request !6434 from chuboning/v2.1.0-5.0.rc3
2023-10-10 12:11:11 +00:00
lj_new 4f8deaa917 !6419 [bugfix]Use work wait instead of future wait in FSDP
Merge pull request !6419 from lj_new/v2.1.0-5.0.rc3
2023-10-10 12:07:18 +00:00
louyujing a47ebea0ea !6429 Due to grammar, torch.jit.script will be disabled by transfer_to_npu
Merge pull request !6429 from louyujing/v2.1.0-5.0.rc3
2023-10-10 11:24:44 +00:00
张喻翔 268729f574 !6407 【PTA】Reset v2.1.0 op_plugin commit id to 763622e
Merge pull request !6407 from 张喻翔/v2.1.0-5.0.rc3
2023-10-09 14:59:41 +00:00
戢芳 46440d918d !6396 Update op_plugin commit id.
Merge pull request !6396 from 戢芳/op_id_v2.1.0-5.0.rc3_2023_10_09
2023-10-09 11:40:12 +00:00
will-devil f0003a288d !6380 [Feature] Change 1D Tensor of 1 element to 0D Tensor.
Merge pull request !6380 from will-devil/v2.1.0-5.0.rc3
2023-10-09 03:34:39 +00:00
陈睿敏 d670b5c24e !6376 [PT2.1] fix bugs while deepcopy cpu tensors
Merge pull request !6376 from 陈睿敏/v2.1.0-5.0.rc3
2023-10-08 14:47:37 +00:00
王姜奔 670383b8f8 !6365 [fix] fix storage deepcopy patch
Merge pull request !6365 from 王姜奔/v2.1.0-5.0.rc3
2023-10-08 09:53:38 +00:00
戢芳 efa4ecee2e !6366 Update op_plugin commit id.
Merge pull request !6366 from 戢芳/op_id_v2.1.0-5.0.rc3_2023_10_08
2023-10-08 09:34:26 +00:00
邵非凡 be05cba5fe !6332 delete future_work in ddp
Merge pull request !6332 from 邵非凡/107
2023-10-08 06:34:52 +00:00
戢芳 d78ccbf328 !6337 Update op_plugin commit id.
Merge pull request !6337 from 戢芳/op_id_v2.1.0-5.0.rc3_2023_10_07
2023-10-07 15:22:05 +00:00
yangxiaorun aa7baf269b !6259 bugfix: Set op execute timeout to max 547s
Merge pull request !6259 from yangxiaorun/cherry-pick-1695862672
2023-10-07 10:01:15 +00:00
关龙锋 88f37de15e !6248 update untypestorage _cpu
Merge pull request !6248 from 关龙锋/cherry-pick-1695806825
2023-10-07 01:04:44 +00:00
王姜奔 cfca80b648 !6289 回退6250
* 回退 'Pull Request !6250 : reduce remove future_work'
2023-10-05 06:06:01 +00:00
weili10 3bf7c0fe89 update version
Signed-off-by: weili10 <liwei386@huawei.com>
2023-09-28 10:16:32 +00:00
李金鑫 3c62585553 !6282 update op_plugin commit id 2.1-5.0.rc3
Merge pull request !6282 from 李金鑫/op_id_v2.1.0-5.0.rc3_2023_09_28
2023-09-28 09:42:36 +00:00
cai_huan 396a6e6709 !6223 enable hostapi of copy_ in v2.1.0
Merge pull request !6223 from cai_huan/v2.1.0-5.0.rc3
2023-09-28 09:17:36 +00:00
邵非凡 0b22b11d5f !6250 reduce remove future_work
Merge pull request !6250 from 邵非凡/5.0.rc3
2023-09-28 08:21:56 +00:00
yangxiaorun 4a766281cd !6262 Change inf\nan default mode to enable
Merge pull request !6262 from yangxiaorun/cherry-pick-1695865446
2023-09-28 08:06:53 +00:00
王强 014862cc0f !6264 [Fix] Add compatibility handling for different soc_versions
Merge pull request !6264 from 王强/cherry-pick-1695866035
2023-09-28 08:01:35 +00:00
周先琪 45ce7466f5 !6177 Bug Fix For Trace View Not Include Msprof Slice
Merge pull request !6177 from 周先琪/v2.1.0-5.0.rc3
2023-09-28 07:12:22 +00:00
李金鑫 4f2c38446e !6255 update op_plugin commit id v2.1.0-5.0.rc3
Merge pull request !6255 from 李金鑫/op_id_v2.1.0-5.0.rc3_2023_09_27
2023-09-27 16:26:10 +00:00
刘嘉巍 be632b7f52 !6249 Expose NpuStorageOffsetGuard to op-plugin.
Merge pull request !6249 from 刘嘉巍/v2.1.0-5.0.rc3
2023-09-27 12:28:12 +00:00
王广斌 450ccdf8c8 !6149 [Bugfix]Verify acl_format before npu_format_cast_impl
Merge pull request !6149 from 王广斌/bugfix_format_cast_rc3
2023-09-27 10:02:48 +00:00
闫鹏全 762ddc812f !6134 [FIX] Compatible with older version files.
Merge pull request !6134 from 闫鹏全/v2.1.0-5.0.rc3
2023-09-27 06:15:25 +00:00
张海杰 0f0f7f65cb !6164 torch2.x PFA and IFA, metainfer func and onnx export single op
Merge pull request !6164 from 张海杰/v2.1.0-5.0.rc3
2023-09-26 13:39:38 +00:00
jiangpengfei af6f7bf66d !6182 [BugFix] Solve the problem that std::call_once stuck at the second time the function be called if the function throw an exception at first time be called
Merge pull request !6182 from jiangpengfei/v2.1.0-5.0.rc3
2023-09-26 09:31:21 +00:00
shaoyf b191e5e7c3 !6137 Make ddp use npu reducer
Merge pull request !6137 from shaoyf/ddp_reducer_rc3
2023-09-26 01:21:00 +00:00
zhaolei156 26d92583b0 !6113 update op_plugin commit id AND update submodule branch
Merge pull request !6113 from zhaolei156/op_id_v2.1.0-5.0.rc3_2023_09_22
2023-09-23 07:16:16 +00:00
65 changed files with 4911 additions and 1233 deletions
+1
View File
@@ -2,6 +2,7 @@
path = third_party/op-plugin
url = https://gitee.com/ascend/op-plugin.git
ignore = dirty
branch = 5.0.rc3
[submodule "third_party/googletest"]
path = third_party/googletest
url = https://gitee.com/mirrors/googletest.git
-508
View File
@@ -1,508 +0,0 @@
# AscendPyTorch
## Overview
This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch framework so that developers who use the PyTorch framework can obtain powerful compute capabilities of Ascend AI Processors. When setting up the environments for PyTorch model development and operating, developers can manually compile related modules on servers. It is recommended to select branch in table *Ascend Auxiliary Software* while master is unstable. For development purposes on master, please refer to FAQ [Compile and Install PyTorch](#FAQs).
## Prerequisites
- The development or operating environment of CANN has been installed. For details, see the *CANN Software Installation Guide*.
- Python 3.8, and 3.9 are supported.
# System Dependencies
## CentOS & EulerOS
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
yum install -y gcc==7.5.0 cmake==3.18.0
## Ubuntu
apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
apt-get install -y gcc==7.5.0 cmake==3.18.0
>![](figures/icon-note.gif) **NOTE:**
>If an error occurs during the installation of the GCC and CMake dependency commands, use the source code for installation. For details, see the FAQ.
# Ascend Auxiliary Software
| AscendPyTorch Version | CANN Version | Supported PyTorch Version | Gitee Branch |
|:----------------------|:-------------|:--------------------------|----------------|
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
# Installation Methods
## Install the PyTorch environment dependencies.
If you install dependencies as a non-root user, add **--user** at the end of each command in this step, for example, **pip3 install pyyaml --user**.
```sh
pip3 install pyyaml
pip3 install wheel
```
## Compile and install the PyTorch and Ascend plugin.
Install the official torch package, and then compile and install the plugin.
```sh
# See the first FAQ to compile and install PyTorch using the source code.
```
Compile and generate the binary installation package of the PyTorch plugin.
Download code of the corresponding branch and go to the root directory of the plugin.
```
#
git clone -b master https://gitee.com/ascend/pytorch.git
cd pytorch
# Specify the Python version packaging mode:
bash ci/build.sh --python=3.8
# or
bash ci/build.sh --python=3.9
```
Install the **torch_npu** package generated in the **pytorch/dist** directory. *{arch}* indicates the architecture name.
```
pip3 install --upgrade dist/torch_npu-2.1.0-cp38-cp38m-linux_{arch}.whl
```
Download TorchVision.
```
pip3 install torchvision=0.15.1 --no-deps
```
# Running
## Execute environment variables.
Run the script for setting environment variables in the root directory of the current repository.
```
source env.sh
```
## Customize environment variables.
The following are optional environment variables that may affect running models:
```
export COMBINED_ENABLE=1 # (Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency.
export ACL_DUMP_DATA=1 # (Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.
```
**Table 1** Description of environment variables
<a name="zh-cn_topic_0000001152616261_table42017516135"></a>
<table><thead align="left"><tr id="zh-cn_topic_0000001152616261_row16198951191317"><th class="cellrowborder" valign="top" width="55.48%" id="mcps1.2.3.1.1"><p id="zh-cn_topic_0000001152616261_p51981251161315"><a name="zh-cn_topic_0000001152616261_p51981251161315"></a><a name="zh-cn_topic_0000001152616261_p51981251161315"></a>Environment Variable</p>
</th>
<th class="cellrowborder" valign="top" width="44.519999999999996%" id="mcps1.2.3.1.2"><p id="zh-cn_topic_0000001152616261_p9198135114133"><a name="zh-cn_topic_0000001152616261_p9198135114133"></a><a name="zh-cn_topic_0000001152616261_p9198135114133"></a>Description</p>
</td>
</tr>
<tr id="row78312162301"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1832171673019"><a name="p1832171673019"></a><a name="p1832171673019"></a>COMBINED_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency. However, the host delivery performance may deteriorate.</p>
</td>
</tr>
<tr id="row183041355123411"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p730435533415"><a name="p730435533415"></a><a name="p730435533415"></a>ACL_DUMP_DATA</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p16304105533412"><a name="p16304105533412"></a><a name="p16304105533412"></a>(Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.</p>
</td>
</tr>
</tbody>
</table>
## Run the unit test script.
Verify the running. The output is **OK**.
```shell
cd test/test_network_ops/
python3 test_div.py
```
# (Optional) Installing the Mixed Precision Module
AscendPyTorch integrates the AMP module and can be used for training with mixed precision. The differences between the AMP module and the Apex module are as follows. You can select a desired module. For details about how to compile and install the Apex module, see the related [**README.en**](https://gitee.com/ascend/apex) file.
- AMP
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
- Tensor fusion is not supported.
- Apex
- O1 configuration mode: Conv and Matmul use the float16 precision for computing, and Softmax and BN use float32.
- O2 configuration mode: BN uses the float32 precision for computing, and others use float16.
- Static loss scale: Parameters are statically set to ensure the convergence of training with mixed precision.
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
# Documents
For more details about the installation guide, model porting and training/inference tutorials, and API list, see [User Documents](https://gitee.com/ascend/pytorch/tree/master/docs/en).
# Suggestions and Communication
We sincerely welcome you to join discussions in the community and contribute your suggestions. We will reply to you as soon as possible.
# Branch Maintenance Policies
The version branches of AscendPyTorch have the following maintenance phases:
| **Status** | **Duration** | **Description** |
|-------------------|--------------|--------------------------------------------------------------------------------------------------------------------------------|
| Planning | 1-3 months | Plan features. |
| Development | 3 months | Develop features. |
| Maintained | 6-12 months | Allow the incorporation of all resolved issues and release the version. |
| Unmaintained | 0-3 months | Allow the incorporation of all resolved issues. No dedicated maintenance personnel are available. No version will be released. |
| End Of Life (EOL) | N/A | Do not accept any modification to a branch. |
# Maintenance Status of Existing Branches
| **Branch Name** | **Status** | **Launch Date** | **Subsequent Status** | **EOL Date** |
|-----------------|------------|-----------------|----------------------------------------|--------------|
| **v2.0.2** | Maintained | 2021-07-29 | Unmaintained <br> 2022-07-29 estimated | |
| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained <br> 2022-10-15 estimated | |
| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained <br> 2023-01-15 estimated | |
| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained <br> 2023-04-10 estimated | |
| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained <br> 2023-07-15 estimated |
# FAQs
## When the CPU architecture is ARM, PyTorch cannot be installed using the PIP3 command because the community does not provide the torch package for the ARM CPU architecture. In this case, use the source code to compile and install PyTorch.
Download the PyTorch master source package.
```
git clone https://github.com/pytorch/pytorch.git --depth=1 pytorch_master
```
Access the source package to obtain the passive dependency code.
```
cd pytorch_master
git submodule sync
git submodule update --init --recursive
```
Compile and install PyTorch master.
```
python3 setup.py install
```
Compile torch_npu.
```
git clone https://gitee.com/ascend/pytorch.git
cd pytorch
# Compile with python version(--python=3.8 or --python=3.9)
bash ci/build.sh --python=3.8
```
Install torch_npu
```
# replace aarch64 with x86_64 when using environment in x86 arch
pip3 install --upgrade dist/torch_npu-2.1.0-cp38-cp38m-linux_aarch64.whl
```
## When PIP is set to the Huawei source, a Python environment error occurs after the typing dependency in the **requirements.txt** file is installed.
When PIP is set to the Huawei source, open the **requirements.txt** file, delete the typing dependency, and then run the following command:
```
pip3 install -r requirments.txt
```
## The error message "no module named yaml/typing_extensions." is displayed when **bash build.sh** is run during compilation.
PyTorch compilation depends on the YAML and typing_extensions libraries, which need to be manually installed.
```
pip3 install pyyaml
pip3 install typing_extensions
```
After the installation is successful, run **make clean** and then **bash build.sh** to perform compilation. Otherwise, an unknown compilation error may occur due to the cache.
## TE cannot be found during running.
Development state:
```
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 # {arch} is the architecture name.
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
User state:
```
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 # {arch} is the architecture name.
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
## During CMake installation through the CLI, an error is reported indicating that the package cannot be found. During CMake compilation, another error is reported indicating that the version is too early. In this cause, you can use the installation script or source code to compile and install CMake.
Method 1: Download the installation script and install CMake. (For details, see the CMake official website.)
​ x86_64 environment: cmake-3.18.0-Linux-x86_64.sh
​ AArch64 environment: cmake-3.18.0-Linux-aarch64.sh
1. Run the following command:
```
./cmake-3.18.0-Linux-{arch}.sh # {arch} indicates the architecture name.
```
2. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
3. Run the following command to check whether CMake has been installed:
```
cmake --version
```
If the message "cmake version 3.18.0" is displayed, the installation is successful.
Method 2: Use the source code to compile and install.
1. Obtain the CMake software package.
```
wget https://cmake.org/files/v3.18/cmake-3.18.0.tar.gz --no-check-certificate
```
2. Decompress the package and go to the software package directory.
```
tar -xf cmake-3.18.0.tar.gz
cd cmake-3.18.0/
```
3. Run the configuration, compilation, and installation commands.
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. Run the following command to check whether CMake has been installed:
```
cmake --version
```
If the message "cmake version 3.18.0" is displayed, the installation is successful.
## During GCC installation through the CLI, an error is reported indicating that the package cannot be found. During GCC compilation, another error is reported.
When downloading GCC from some sources, you may be prompted by an error message indicating that the package cannot be found. In this case, use the source code to compile and install GCC.
Perform the following steps as the **root** user.
1. Download **gcc-7.5.0.tar.gz** from [https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz).
2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
```
sudo rm -rf /tmp/*
```
3. Install the dependency package. (CentOS and Ubuntu are used as examples.)
- For CentOS, run the following command:
```
yum install bzip2
```
- For Ubuntu, run the following command:
```
apt-get install bzip2
```
4. Compile and install GCC.
1. Go to the directory where the source package **gcc-7.5.0.tar.gz** is located and run the following command to decompress it:
```
tar -zxvf gcc-7.5.0.tar.gz
```
2. Go to the extracted directory and download the GCC dependency packages:
```
cd gcc-7.5.0
./contrib/download_prerequisites
```
If an error is reported during the command execution, run the following commands in the **gcc-7.5.0/** directory to download the dependency packages:
```
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
```
After the preceding dependencies are downloaded, run the following command again:
```
./contrib/download_prerequisites
```
If the verification fails, check whether there are duplicate dependency packages in the folder. If yes, delete duplicate ones.
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>Run the configuration, compilation, and installation commands.
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.5.0
make -j15 # Check the number of CPUs by running **grep -w processor /proc/cpuinfo|wc -l**. In this example, the number is 15. You can set the parameters as required.
make install
```
>![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/docs/en/PyTorch%20Network%20Model%20Porting%20and%20Training%20Guide/public_sys-resources/icon-notice.gif) **NOTICE:**
>The **--prefix** option is used to specify the **linux\_gcc7.5.0** installation path, which is configurable. Do not set it to **/usr/local** or **/usr,** which is the default installation path for the GCC installed by using the software source. Otherwise, a conflict occurs and the original GCC compilation environment of the system is damaged. In this example, the installation path is set to **/usr/local/linux\_gcc7.5.0**.
4. Change the soft links.
```
ln -s ${install_path}/bin/gcc /usr/bin/gcc
ln -s ${install_path}/bin/g++ /usr/bin/g++
ln -s ${install_path}/bin/c++ /usr/bin/c++
```
5. Configure the environment variable.
Training must be performed in the compilation environment with GCC upgraded. If you want to run training, configure the following environment variable in your training script:
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
**${install_path}** indicates the GCC 7.5.0 installation path configured in [3](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310). In this example, the GCC 7.5.0 installation path is **/usr/local/gcc7.5.0/**.
>![](figures/icon-note.gif) **NOTE:**
>Skip this step if you do not need to use the compilation environment with GCC upgraded.
If the PyTorch compilation fails, check whether the soft link library is correct.
libstdc++->libstdc++.so.6.0.24(7.5.0)
## libblas.so cannot be found.
The OpenBLAS library is missing in the environment. You need to install it.
CentOS and EulerOS
```sh
yum -y install openblas
```
Ubuntu
```sh
apt install libopenblas-dev
```
## No device is mounted to the container.
An NPU-related error is reported when a script is run in the container. The **device** parameter is not set before container instance startup. As a result, the instance cannot be started.
![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/figures/FAQ.png)
Run the following command to restart the container:
```sh
docker run -it --ipc=host \
--device=/dev/davinciX \
--device=/dev/davinci_manager \
--device=/dev/devmm_svm \
--device=/dev/hisi_hdc \
-v /usr/local/Ascend/driver \
-v /usr/local/dcmi \
-v /usr/local/bin/npu-smi \
${image name}:{tag} \
/bin/bash
```
Parameter description:
**/dev/davinci*X***: NPU device. *X* is the physical ID of the chip, for example, **davinci0**.
**/dev/davinci_manager**: management device
**/dev/devmm_svm**: management device
**/dev/hisi_hdc**: management device
**/usr/local/Ascend/driver**: driver directory
**/usr/local/dcmi**: DCMI directory
**/usr/local/bin/npu-smi**: npu-smi tool
**$*{image name}:{tag}***: image name and version
## An error is reported during installation of -torch--whl-, indicating that -torch-1-5-0xxxx- and -torchvision- versions do not match.
During installation of **torch-\*.whl**, the message "ERROR: torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible" is displayed.
![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/figures/zh-cn_image_0000001190081735.png)
When the PyTorch is installed, the version check is automatically triggered. The version of the torchvision installed in the environment is 0.6.0. During the check, it is found that the version of the **torch-\*.whl** is inconsistent with the required version 1.5.0. As a result, an error message is displayed, but the installation is successful.
This problem does not affect the actual result, and no action is required.
## When you run **import torch_npu**, if "_has_compatible_shallow_copy_type" is output, a warning about a repeated registration error is displayed.
The warning is triggered by the shallow copy operation of **Tensor.set_data**, as shown in the following figure. The main cause is that after the PyTorch plugin is decoupled, `_has_compatible_shallow_copy_type` cannot detect shallow copy of NPU tensors. You need to register `_has_compatible_shallow_copy_type` again.
This error can be ignored because it does not affect the model accuracy and performance.
It will be resolved after the NPU's device ID is incorporated into the community or the `_has_compatible_shallow_copy_type` registration mode is changed in a later PyTorch version.
![Input Image Description](https://images.gitee.com/uploads/images/2022/0701/153621_2b5080c4_7902902.png)
## An error is reported when torch_npu is referenced with Python commands in the compilation directory.
To verify the torch_npu reference, switch to another directory. If you perform the verification in the compilation directory, the following error message is displayed:
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
## Multi card training is stuck in initialization stage until timeout
IPv6 address is used in the "init_process_group" function of multi card communication, for example ::1 (Note that the localhost may point to the IPv6 address)
Use IPv4 to avoid this problem
# Version Description
For details, see [Release Notes](https://gitee.com/ascend/pytorch/tree/master/docs/en/RELEASENOTE).
+410
View File
@@ -0,0 +1,410 @@
# PyTorch Ascend Adapter
## Overview
This repository develops the **PyTorch Ascend Adapter** named **torch_npu** to adapt **Ascend NPU** to **PyTorch** so that developers who use the **PyTorch** can obtain powerful compute capabilities of **Ascend AI Processors**.
Ascend is a full-stack AI computing infrastructure for industry applications and services based on Huawei Ascend processors and software. For more information about Ascend, see [Ascend Community](https://www.hiascend.com/en/).
## Installation
### From Binary
Provide users with wheel package to quickly install **torch_npu**. Before installing **torch_npu**, complete the installation of **CANN** according to [Ascend Auxiliary Software](#ascend-auxiliary-software). To obtain the **CANN** installation package, refer to the [CANN Installation](https://www.hiascend.com/en/software/cann/community).
1. **Install PyTorch**
Install **PyTorch** through pip.
**For Aarch64:**
```Python
pip3 install torch==2.1.0
```
**For x86:**
```Python
pip3 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu
```
2. **Install torch-npu dependencies**
Run the following command to install dependencies.
```Python
pip3 install pyyaml
pip3 install setuptools
```
If the installation fails, use the download link or visit the [PyTorch official website](https://pytorch.org/) to download the installation package of the corresponding version.
| OS arch | Python version | link |
| ------- | -------------- | ------------------------------------------------------------ |
| x86 | Python3.8 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp38-cp38-linux_x86_64.whl#sha256=9e5cfd931a65b38d222755a45dabb53b836be31bc620532bc66fee77e3ff67dc) |
| x86 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp39-cp39-linux_x86_64.whl#sha256=86cc28df491fa84738affe752f9870791026565342f69e4ab63e5b935f00a495) |
| x86 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp310-cp310-linux_x86_64.whl#sha256=5077921fc2b54e69a534f3a9c0b98493c79a5547c49d46f5e77e42da3610e011) |
| aarch64 | Python3.8 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=761822761fffaa1c18a62c5deb13abaa780862577d3eadc428f1daa632536905) |
| aarch64 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=de7d63c6ecece118684415a3dbd4805af4a4c1ee1490cccf7405d8c240a481b4) |
| aarch64 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=a04a0296d47f28960f51c18c5489a8c3472f624ec3b5bcc8e2096314df8c3342) |
3. **Install torch-npu**
```Python
pip3 install torch-npu==2.1.0rc1
```
### From Source
In some special scenarios, users may need to compile **torch-npu** by themselves.Select a branch in table [Ascend Auxiliary Software](#ascend-auxiliary-software) and a Python version in table [PyTorch and Python Version Matching Table](#pytorch-and-python-version-matching-table) first. The docker image is recommended for compiling torch-npu through the following steps:
1. **Clone torch-npu**
```
git clone https://github.com/ascend/pytorch.git -b v2.1.0-5.0.rc3 --depth 1
```
2. **Build Docker Image**
```
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
docker build -t manylinux-builder:v1 .
```
3. **Enter Docker Container**
```
docker run -it -v /{code_path}/pytorch:/home/pytorch manylinux-builder:v1 bash
# {code_path} is the torch_npu source code path
```
4. **Compile torch-npu**
Take **Python 3.8** as an example.
```
cd /home/pytorch
bash ci/build.sh --python=3.8
```
## Getting Started
### Prerequisites
Initialize **CANN** environment variable by running the command as shown below.
```Shell
# Default path, change it if needed.
source /usr/local/Ascend/ascend-toolkit/set_env.sh
```
### Quick Verification
You can quickly experience **Ascend NPU** by the following simple examples.
```Python
import torch
import torch_npu
x = torch.randn(2, 2).npu()
y = torch.randn(2, 2).npu()
z = x.mm(y)
print(z)
```
## User Manual
Refer to [API of PyTorch Ascend Adapter](docs/api/torch_npu_apis.md) for more detailed informations.
## PyTorch and Python Version Matching Table
| PyTorch Version | Python Version |
| ------------- | :----------------------------------------------------------- |
| PyTorch1.11.0 | Python3.7.x(>=3.7.5),Python3.8.x,Python3.9.x,Python3.10.x |
| PyTorch2.0.1 | Python3.8.x,Python3.9.x,Python3.10.x |
| PyTorch2.1.0 | Python3.8.x,Python3.9.x,Python3.10.x |
## Ascend Auxiliary Software
<table><thead align="left"><tr id="row721911327225"><th class="cellrowborder" valign="top" id="mcps1.2.6.1.1"><p id="p0878358152310"><a name="p0878358152310"></a><a name="p0878358152310"></a>CANN Version</p>
</th>
<th class="cellrowborder" valign="top" id="mcps1.2.6.1.2"><p id="p1833820270243"><a name="p1833820270243"></a><a name="p1833820270243"></a>Supported PyTorch Version</p>
</th>
<th class="cellrowborder" valign="top" id="mcps1.2.6.1.3"><p id="p7878175817236"><a name="p7878175817236"></a><a name="p7878175817236"></a>Supported Adapter Version</p>
</th>
<th class="cellrowborder" valign="top" id="mcps1.2.6.1.4"><p id="p58781058202311"><a name="p58781058202311"></a><a name="p58781058202311"></a>Github Branch</p>
</th>
<th class="cellrowborder" valign="top" id="mcps1.2.6.1.5"><p id="p1887865812234"><a name="p1887865812234"></a><a name="p1887865812234"></a>AscendHub Image Version/Name(<a href="https://ascendhub.huawei.com/#/detail/pytorch-modelzoo" target="_blank" rel="noopener noreferrer">Link</a>)</p>
</th>
</tr>
</thead>
<tbody><tr id="row1121913217224"><td class="cellrowborder" rowspan="3" valign="top" headers="mcps1.2.6.1.1 "><p id="p387812581238"><a name="p387812581238"></a><a name="p387812581238"></a>CANN 7.0.RC1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p633892712241"><a name="p633892712241"></a><a name="p633892712241"></a>2.1.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p13878165862310"><a name="p13878165862310"></a><a name="p13878165862310"></a>2.1.0.rc1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p5878658162312"><a name="p5878658162312"></a><a name="p5878658162312"></a>v2.1.0-5.0.rc3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p1887895818234"><a name="p1887895818234"></a><a name="p1887895818234"></a>-</p>
</td>
</tr>
<tr id="row122191232122216"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p1333872762420"><a name="p1333872762420"></a><a name="p1333872762420"></a>2.0.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p08788581239"><a name="p08788581239"></a><a name="p08788581239"></a>2.0.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p88793589233"><a name="p88793589233"></a><a name="p88793589233"></a>v2.0.1-5.0.rc3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p18791958192318"><a name="p18791958192318"></a><a name="p18791958192318"></a>-</p>
</td>
</tr>
<tr id="row1220113211225"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p16339162718249"><a name="p16339162718249"></a><a name="p16339162718249"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p587919583231"><a name="p587919583231"></a><a name="p587919583231"></a>1.11.0.post4</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p1879185852316"><a name="p1879185852316"></a><a name="p1879185852316"></a>v1.11.0-5.0.rc3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p987915814231"><a name="p987915814231"></a><a name="p987915814231"></a>-</p>
</td>
</tr>
<tr id="row92207321228"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p5879195862316"><a name="p5879195862316"></a><a name="p5879195862316"></a>CANN 6.3.RC3.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p13391127102419"><a name="p13391127102419"></a><a name="p13391127102419"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p987935812311"><a name="p987935812311"></a><a name="p987935812311"></a>1.11.0.post3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p178797587233"><a name="p178797587233"></a><a name="p178797587233"></a>v1.11.0-5.0.rc2.2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p16879458102316"><a name="p16879458102316"></a><a name="p16879458102316"></a>-</p>
</td>
</tr>
<tr id="row17220143220221"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p287917582235"><a name="p287917582235"></a><a name="p287917582235"></a>CANN 6.3.RC3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p933902762410"><a name="p933902762410"></a><a name="p933902762410"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p10879135819230"><a name="p10879135819230"></a><a name="p10879135819230"></a>1.11.0.post2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p17879125816231"><a name="p17879125816231"></a><a name="p17879125816231"></a>v1.11.0-5.0.rc2.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p10879155882310"><a name="p10879155882310"></a><a name="p10879155882310"></a>-</p>
</td>
</tr>
<tr id="row422116324224"><td class="cellrowborder" rowspan="3" valign="top" headers="mcps1.2.6.1.1 "><p id="p13879165832316"><a name="p13879165832316"></a><a name="p13879165832316"></a>CANN 6.3.RC2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p1191901662516"><a name="p1191901662516"></a><a name="p1191901662516"></a>2.0.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p198791258142317"><a name="p198791258142317"></a><a name="p198791258142317"></a>2.0.1.rc1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p1587955816237"><a name="p1587955816237"></a><a name="p1587955816237"></a>v2.0.1-5.0.rc2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p0879558192313"><a name="p0879558192313"></a><a name="p0879558192313"></a>-</p>
</td>
</tr>
<tr id="row1522123282216"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p19191169254"><a name="p19191169254"></a><a name="p19191169254"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p4879185815238"><a name="p4879185815238"></a><a name="p4879185815238"></a>1.8.1.post2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p887935810232"><a name="p887935810232"></a><a name="p887935810232"></a>v1.8.1-5.0.rc2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p14879358172313"><a name="p14879358172313"></a><a name="p14879358172313"></a>23.0.RC1-1.8.1</p>
</td>
</tr>
<tr id="row19716641182317"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p691981615257"><a name="p691981615257"></a><a name="p691981615257"></a>1.8.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p208791758142314"><a name="p208791758142314"></a><a name="p208791758142314"></a>1.11.0.post1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p1987935852319"><a name="p1987935852319"></a><a name="p1987935852319"></a>v1.11.0-5.0.rc2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p1087918585237"><a name="p1087918585237"></a><a name="p1087918585237"></a>23.0.RC1-1.11.0</p>
</td>
</tr>
<tr id="row822143252217"><td class="cellrowborder" rowspan="2" valign="top" headers="mcps1.2.6.1.1 "><p id="p108803589235"><a name="p108803589235"></a><a name="p108803589235"></a>CANN 6.3.RC1</p>
<p id="p129081558152312"><a name="p129081558152312"></a><a name="p129081558152312"></a></p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p12346162018257"><a name="p12346162018257"></a><a name="p12346162018257"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p6880205814236"><a name="p6880205814236"></a><a name="p6880205814236"></a>1.8.1.post1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p6880258162313"><a name="p6880258162313"></a><a name="p6880258162313"></a>v1.8.1-5.0.rc1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p08807589236"><a name="p08807589236"></a><a name="p08807589236"></a>-</p>
</td>
</tr>
<tr id="row13745135213239"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p183463202251"><a name="p183463202251"></a><a name="p183463202251"></a>1.8.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p1888019580230"><a name="p1888019580230"></a><a name="p1888019580230"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p15880105813236"><a name="p15880105813236"></a><a name="p15880105813236"></a>v1.11.0-5.0.rc1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p1588012586230"><a name="p1588012586230"></a><a name="p1588012586230"></a>-</p>
</td>
</tr>
<tr id="row1667135119236"><td class="cellrowborder" rowspan="3" valign="top" headers="mcps1.2.6.1.1 "><p id="p188801958102315"><a name="p188801958102315"></a><a name="p188801958102315"></a>CANN 6.0.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p43395279244"><a name="p43395279244"></a><a name="p43395279244"></a>1.5.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p118801658182310"><a name="p118801658182310"></a><a name="p118801658182310"></a>1.5.0.post8</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p4880125819233"><a name="p4880125819233"></a><a name="p4880125819233"></a>v1.5.0-3.0.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p8880858122319"><a name="p8880858122319"></a><a name="p8880858122319"></a>22.0.0</p>
</td>
</tr>
<tr id="row123884481236"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p0339162717244"><a name="p0339162717244"></a><a name="p0339162717244"></a>1.8.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p15880115811236"><a name="p15880115811236"></a><a name="p15880115811236"></a>1.8.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p68808584233"><a name="p68808584233"></a><a name="p68808584233"></a>v1.8.1-3.0.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p1688035812238"><a name="p1688035812238"></a><a name="p1688035812238"></a>22.0.0-1.8.1</p>
</td>
</tr>
<tr id="row133914572237"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p10339102719241"><a name="p10339102719241"></a><a name="p10339102719241"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p9880205892318"><a name="p9880205892318"></a><a name="p9880205892318"></a>1.11.0.rc2(beta)</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p888005822314"><a name="p888005822314"></a><a name="p888005822314"></a>v1.11.0-3.0.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p6880145812238"><a name="p6880145812238"></a><a name="p6880145812238"></a>-</p>
</td>
</tr>
<tr id="row127654514238"><td class="cellrowborder" rowspan="3" valign="top" headers="mcps1.2.6.1.1 "><p id="p1288085862314"><a name="p1288085862314"></a><a name="p1288085862314"></a>CANN 6.0.RC1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p20327103216255"><a name="p20327103216255"></a><a name="p20327103216255"></a>1.5.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p7880145811235"><a name="p7880145811235"></a><a name="p7880145811235"></a>1.5.0.post7</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p1788095815239"><a name="p1788095815239"></a><a name="p1788095815239"></a>v1.5.0-3.0.rc3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p6880115810237"><a name="p6880115810237"></a><a name="p6880115810237"></a>22.0.RC3</p>
</td>
</tr>
<tr id="row129461142152313"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p14327173292510"><a name="p14327173292510"></a><a name="p14327173292510"></a>1.8.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p1588035812311"><a name="p1588035812311"></a><a name="p1588035812311"></a>1.8.1.rc3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p13880165816233"><a name="p13880165816233"></a><a name="p13880165816233"></a>v1.8.1-3.0.rc3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p108806581238"><a name="p108806581238"></a><a name="p108806581238"></a>22.0.RC3-1.8.1</p>
</td>
</tr>
<tr id="row36411150122319"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p1132743211257"><a name="p1132743211257"></a><a name="p1132743211257"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p168800589238"><a name="p168800589238"></a><a name="p168800589238"></a>1.11.0.rc1(beta)</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p28816580233"><a name="p28816580233"></a><a name="p28816580233"></a>v1.11.0-3.0.rc3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p198811588236"><a name="p198811588236"></a><a name="p198811588236"></a>-</p>
</td>
</tr>
<tr id="row12371144713235"><td class="cellrowborder" rowspan="2" valign="top" headers="mcps1.2.6.1.1 "><p id="p11881558122317"><a name="p11881558122317"></a><a name="p11881558122317"></a>CANN 5.1.RC2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p629873412510"><a name="p629873412510"></a><a name="p629873412510"></a>1.5.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p3881105818236"><a name="p3881105818236"></a><a name="p3881105818236"></a>1.5.0.post6</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p1088125852319"><a name="p1088125852319"></a><a name="p1088125852319"></a>v1.5.0-3.0.rc2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p20881258112316"><a name="p20881258112316"></a><a name="p20881258112316"></a>22.0.RC2</p>
</td>
</tr>
<tr id="row14956184342315"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p929893462515"><a name="p929893462515"></a><a name="p929893462515"></a>1.8.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p688120581238"><a name="p688120581238"></a><a name="p688120581238"></a>1.8.1.rc2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p198819587236"><a name="p198819587236"></a><a name="p198819587236"></a>v1.8.1-3.0.rc2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p1388175832319"><a name="p1388175832319"></a><a name="p1388175832319"></a>22.0.RC2-1.8.1</p>
</td>
</tr>
<tr id="row1522133210223"><td class="cellrowborder" rowspan="2" valign="top" headers="mcps1.2.6.1.1 "><p id="p7881205813233"><a name="p7881205813233"></a><a name="p7881205813233"></a>CANN 5.1.RC1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p1610094112517"><a name="p1610094112517"></a><a name="p1610094112517"></a>1.5.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p12881165818235"><a name="p12881165818235"></a><a name="p12881165818235"></a>1.5.0.post5</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p14881105892315"><a name="p14881105892315"></a><a name="p14881105892315"></a>v1.5.0-3.0.rc1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p5881115812234"><a name="p5881115812234"></a><a name="p5881115812234"></a>22.0.RC1</p>
</td>
</tr>
<tr id="row182218327224"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p19100441202520"><a name="p19100441202520"></a><a name="p19100441202520"></a>1.8.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p688165810235"><a name="p688165810235"></a><a name="p688165810235"></a>1.8.1.rc1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p6881195818236"><a name="p6881195818236"></a><a name="p6881195818236"></a>v1.8.1-3.0.rc1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p58817582239"><a name="p58817582239"></a><a name="p58817582239"></a>-</p>
</td>
</tr>
<tr id="row137028392234"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p208815585236"><a name="p208815585236"></a><a name="p208815585236"></a>CANN 5.0.4</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p1289474162511"><a name="p1289474162511"></a><a name="p1289474162511"></a>1.5.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p68812058102318"><a name="p68812058102318"></a><a name="p68812058102318"></a>1.5.0.post4</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p17881658122311"><a name="p17881658122311"></a><a name="p17881658122311"></a>2.0.4.tr5</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p1588119588233"><a name="p1588119588233"></a><a name="p1588119588233"></a>21.0.4</p>
</td>
</tr>
<tr id="row182227322224"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p1188113584232"><a name="p1188113584232"></a><a name="p1188113584232"></a>CANN 5.0.3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p1389417414253"><a name="p1389417414253"></a><a name="p1389417414253"></a>1.8.1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p14881358112314"><a name="p14881358112314"></a><a name="p14881358112314"></a>1.5.0.post3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p9881205862316"><a name="p9881205862316"></a><a name="p9881205862316"></a>2.0.3.tr5</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p68811858122317"><a name="p68811858122317"></a><a name="p68811858122317"></a>21.0.3</p>
</td>
</tr>
<tr id="row17222203202219"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p68814580234"><a name="p68814580234"></a><a name="p68814580234"></a>CANN 5.0.2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p610954522514"><a name="p610954522514"></a><a name="p610954522514"></a>1.5.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p1882758112318"><a name="p1882758112318"></a><a name="p1882758112318"></a>1.5.0.post2</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.4 "><p id="p988215589234"><a name="p988215589234"></a><a name="p988215589234"></a>2.0.2.tr5</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.5 "><p id="p6882115811231"><a name="p6882115811231"></a><a name="p6882115811231"></a>21.0.2</p>
</td>
</tr>
</tbody>
</table>
## Suggestions and Communication
Everyone is welcome to contribute to the community. If you have any questions or suggestions, you can submit [Github Issues](https://github.com/Ascend/pytorch/issues). We will reply to you as soon as possible. Thank you very much.
## Branch Maintenance Policies
The version branches of AscendPyTorch have the following maintenance phases:
| **Status** | **Duration** | **Description** |
|-------------------|--------------|--------------------------------------------------------------------------------------------------------------------------------|
| Planning | 1-3 months | Plan features. |
| Development | 3 months | Develop features. |
| Maintained | 6-12 months | Allow the incorporation of all resolved issues and release the version. |
| Unmaintained | 0-3 months | Allow the incorporation of all resolved issues. No dedicated maintenance personnel are available. No version will be released. |
| End Of Life (EOL) | N/A | Do not accept any modification to a branch. |
## Maintenance Status of Existing Branches
| **Branch Name** | **Status** | **Launch Date** | **Subsequent Status** | **EOL Date** |
| --------------- | ---------- | --------------- | --------------------------------------- | ------------ |
| **v2.0.2** | EOL | 2021/7/29 | N/A | |
| **v2.0.3** | EOL | 2021/10/15 | N/A | |
| **v2.0.4** | EOL | 2022/1/15 | N/A | |
| **v3.0.rc1** | EOL | 2022/4/10 | N/A | |
| **v3.0.rc2** | EOL | 2022/7/15 | N/A | |
| **v3.0.rc3** | Maintained | 2022/10/20 | Unmaintained <br> 2023-10-20 estimated | |
| **v3.0.0** | Maintained | 2023/1/18 | Unmaintained <br> 2024-1-18 estimated | |
| **v5.0.rc1** | Maintained | 2023/4/19 | Unmaintained <br> 2024-4-19 estimated | |
| **v5.0.rc2** | Maintained | 2023/7/19 | Unmaintained <br> 2024-7-19 estimated | |
| **v5.0.rc3** | Maintained | 2023/10/15 | Unmaintained <br> 2024-10-15 estimated | |
## License
PyTorch Ascend Adapter has a BSD-style license, as found in the [LICENSE](LICENSE) file.
+301 -607
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
FROM quay.io/pypa/manylinux2014_aarch64:2023-10-07-c1e05d1
# Set pip
RUN cd /usr/local/bin \
&& ln -s /opt/_internal/cpython-3.7.17/bin/pip3.7 pip3.7 \
&& ln -s /opt/_internal/cpython-3.8.18/bin/pip3.8 pip3.8 \
&& ln -s /opt/_internal/cpython-3.9.18/bin/pip3.9 pip3.9 \
&& ln -s /opt/_internal/cpython-3.10.13/bin/pip3.10 pip3.10 \
&& ln -s python3.8 python3
# Set pip source
RUN mkdir /root/.pip \
&& echo "[global]" > /root/.pip/pip.conf \
&& echo "index-url=https://mirrors.aliyun.com/pypi/simple" >> /root/.pip/pip.conf \
&& echo "trusted-host=mirrors.aliyun.com" >> /root/.pip/pip.conf \
&& echo "timeout=120" >> /root/.pip/pip.conf
# Install pip package(build)
RUN pip3.8 install pyyaml \
&& pip3.8 install torch==2.1.0 \
&& pip3.8 install numpy==1.21.3
RUN pip3.9 install pyyaml \
&& pip3.9 install torch==2.1.0 \
&& pip3.9 install numpy==1.21.3
RUN pip3.10 install pyyaml \
&& pip3.10 install torch==2.1.0 \
&& pip3.10 install numpy==1.21.3
WORKDIR /home
+31
View File
@@ -0,0 +1,31 @@
## Ascend Pytorch Dockerfile Repository
This folder hosts the `Dockerfile` to build docker images with various platforms.
### Build torch_npu from Docker container
**Clone torch-npu**
```Shell
git clone https://github.com/ascend/pytorch.git -b v2.1.0-5.0.rc3 --depth 1
```
**Build docker image**
```Shell
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
docker build -t manylinux-builder:v1 .
```
**Enter docker Container**
```Shell
docker run -it -v /{code_path}/pytorch:/home/pytorch manylinux-builder:v1 bash
# {code_path} is the torch_npu source code path
```
**Compile torch_npu**
Take Python 3.8 as an example
```Shell
cd /home/pytorch
bash ci/build.sh --python=3.8
```
+37
View File
@@ -0,0 +1,37 @@
FROM pytorch/manylinux-builder:cpu-2.1
# Install python
RUN cd /usr/local/bin \
&& ln -s /opt/_internal/cpython-3.7.5/bin/pip3.7 pip3.7 \
&& ln -s /opt/_internal/cpython-3.8.1/bin/pip3.8 pip3.8 \
&& ln -s /opt/_internal/cpython-3.9.0/bin/pip3.9 pip3.9 \
&& ln -s /opt/_internal/cpython-3.10.1/bin/pip3.10 pip3.10 \
&& ln -s /opt/_internal/cpython-3.7.5/bin/python3.7 python3.7 \
&& ln -s /opt/_internal/cpython-3.8.1/bin/python3.8 python3.8 \
&& ln -s /opt/_internal/cpython-3.9.0/bin/python3.9 python3.9 \
&& ln -s /opt/_internal/cpython-3.10.1/bin/python3.10 python3.10 \
&& ln -s python3.8 python3
# Set pip source
RUN mkdir /root/.pip \
&& echo "[global]" > /root/.pip/pip.conf \
&& echo "index-url=https://mirrors.huaweicloud.com/repository/pypi/simple" >> /root/.pip/pip.conf \
&& echo "trusted-host=repo.huaweicloud.com" >> /root/.pip/pip.conf \
&& echo "timeout=120" >> /root/.pip/pip.conf
# Install pip package(build)
RUN pip3.8 install pyyaml \
&& pip3.8 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.8 install numpy==1.21.3
RUN pip3.9 install pyyaml \
&& pip3.9 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.9 install numpy==1.21.3
RUN pip3.10 install pyyaml \
&& pip3.10 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.10 install numpy==1.21.3
WORKDIR /home
+2 -1
View File
@@ -21,6 +21,7 @@ from torchgen.packaged.autograd.gen_variable_type import (
from .utils import NPU_AUTOGRAD_FUNCTION
NPU_NATIVEFUNCTIONS = {'npu_format_cast', '_npu_format_cast'}
try_jit_decomposition_pattern = (r'if \(\(.*?\)\) \{.*?static c10::OperatorName full_name\("aten::.*?", .*?\);\n.*?'
r'return impl::run_jit_decomposition_with_args_for_jvp<.*?>'
@@ -111,7 +112,7 @@ def gen_variable_type_func(
type_definition = re.sub(try_jit_decomposition_pattern, r"\1", type_definition, flags=re.DOTALL)
type_definition = re.sub(use_count_pattern, "", type_definition, flags=re.DOTALL)
if str(f.func.name) in NPU_AUTOGRAD_FUNCTION:
if str(f.func.name) == 'npu_format_cast':
if str(f.func.name) in NPU_NATIVEFUNCTIONS:
type_definition = type_definition.replace('at::redispatch', 'at_npu::native::NPUNativeFunctions')
else:
type_definition = type_definition.replace('at::redispatch', 'op_plugin')
+26 -2
View File
@@ -41,7 +41,8 @@ from torchgen.gen_backend_stubs import gen_dispatchkey_nativefunc_headers
from codegen.utils import (get_torchgen_dir, rename_privateuse1_dispatch_key, gen_unstructured,
add_header_to_template_file, parse_npu_yaml, get_opplugin_wrap_name,
parse_opplugin_yaml, merge_custom_yaml, filed_tag, gen_custom_yaml_path)
parse_opplugin_yaml, merge_custom_yaml, filed_tag, gen_custom_yaml_path,
update_opapi_info, is_opapi)
from codegen.custom_functions import (parse_custom_yaml, gen_custom_trace, gen_custom_ops_patch,
gen_custom_functions_dispatch)
@@ -125,6 +126,9 @@ def parse_native_and_custom_yaml(path: str, tag_path: str, custom_path: str) ->
source_es = parse_npu_yaml(custom_path)
custom_es = source_es.get('custom', []) + source_es.get('custom_autograd', [])
supported_es = source_es.get('supported', []) + source_es.get('autograd', []) + custom_es
for es in supported_es:
update_opapi_info(es)
custom_es = filed_tag(custom_es)
for e in custom_es:
funcs = e.get('func')
@@ -228,13 +232,17 @@ def parse_backend_yaml(
Only the following keys are supported: {", ".join(valid_keys)}')
backend_key: Optional[DispatchKey] = None
opapi_key = "OpApi"
if len(supported) > 0:
with context(lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.'):
backend_key = DispatchKey.parse(backend)
backend_idx = create_backend_index(supported, symint_set, backend_key, native_functions_map, cpp_namespace)
opapi_backend_idx = create_backend_index([op for op in supported if is_opapi(op)],
symint_set, backend_key, native_functions_map, cpp_namespace)
assert backend_key not in backend_indices
backend_indices[backend_key] = backend_idx
backend_indices[str(backend_key) + opapi_key] = opapi_backend_idx
autograd_key: Optional[DispatchKey] = None
if len(supported_autograd) > 0:
@@ -244,8 +252,11 @@ the behavior of autograd for some operators on your backend. However "Autograd{b
autograd_idx = create_backend_index(supported_autograd, symint_set,
autograd_key, native_functions_map, cpp_namespace)
opapi_autograd_idx = create_backend_index([op for op in supported_autograd if is_opapi(op)],
symint_set, autograd_key, native_functions_map, cpp_namespace)
assert autograd_key not in backend_indices
backend_indices[autograd_key] = autograd_idx
backend_indices[str(autograd_key) + opapi_key] = opapi_autograd_idx
check_op_on_cpu_kernels(supported_tocpu, backend_indices)
check_grouped_native_functions(backend_key, autograd_key, backend_indices, grouped_native_functions)
@@ -406,6 +417,9 @@ def gen_dispatcher_registrations(
#endif
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/framework/interface/EnvVariables.h"
#include "torch_npu/csrc/aten/NPUOpApiNativeFunctions.h"
#include "torch_npu/csrc/framework/FormatHelper.h"
#ifdef USE_GEN_HEADER
#include "op_plugin/OpInterface.h"
#else
@@ -574,6 +588,16 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool,
autograd_key,
)
gen_dispatchkey_nativefunc_headers(
fm,
"NPUNativeOpApiFunctions",
cpp_namespace,
backend_indices,
grouped_native_functions,
str(backend_key) + "OpApi",
autograd_key,
)
for dispatch_key in [backend_dispatch_key, autograd_dispatch_key]:
if not dispatch_key:
continue
@@ -617,4 +641,4 @@ def apply_torchgen_patch():
if __name__ == '__main__':
apply_torchgen_patch()
main()
main()
+41 -5
View File
@@ -37,9 +37,10 @@ from torchgen.utils import Target
from torchgen.gen import LineLoader
GLOBAL_STRUCTURED_OP_INFO_CACHE = defaultdict(str)
GLOBAL_OPAPI_INFO_CACHE = set()
CUSTOM_YAML_NAME = "npu_native_functions_by_codegen.yaml"
FIELDS_TO_REMOVE = ["wrap_impl", "impl_name", "impl_ns"]
FIELDS_TO_REMOVE = ["wrap_impl", "impl_name", "impl_ns", "op_api"]
def parse_npu_yaml(custom_path: str) -> Dict:
@@ -235,7 +236,6 @@ return {self_arg_name};
impl_name = f"{metadata.cpp_namespace}::{metadata.kernel}"
else:
impl_name = f"{metadata.cpp_namespace}::{self.class_method_name}::{metadata.kernel}"
kernel_sig = kernel_signature(f, self.backend_index)
args_exprs_str = ", ".join(
@@ -303,12 +303,32 @@ const DeviceGuard device_guard(device_or_default(device));"""
)
if device_of is not None:
device_guard = f"const OptionalDeviceGuard device_guard(device_of({device_of}));"
op_key = str(f.func.name)
if enable_opplugin():
op_key = str(f.func.name)
if op_key in GLOBAL_STRUCTURED_OP_INFO_CACHE:
impl_name = f"op_plugin::{GLOBAL_STRUCTURED_OP_INFO_CACHE[op_key]}"
if is_opapi(op_key) and not is_op_valid(op_key):
op_api_impl_name = f"{metadata.cpp_namespace}::NPUNativeOpApiFunctions::{metadata.kernel}"
tensor_check_str = ""
tensor_check_list = []
for a in args:
if a.argument.type.is_tensor_like():
tensor_check_list.append(f"at_npu::native::FormatHelper::IsOpInputBaseFormat({a.name})")
if tensor_check_list:
tensor_check_str = f" && {' && '.join(tensor_check_list)}"
return_code = f"""\
if (at_npu::native::env::CheckJitDisable(){tensor_check_str}) {{
return {op_api_impl_name}({args_exprs_str});
}} else {{
return {impl_name}({args_exprs_str});
}}
"""
else:
return_code = f"""\
return {impl_name}({args_exprs_str});
"""
return f"""\
namespace {{
@@ -317,7 +337,7 @@ namespace {{
{device_guard}
{record_func_def}
return {impl_name}({args_exprs_str});
{return_code}
}}
}} // anonymous namespace
@@ -389,3 +409,19 @@ def get_opplugin_wrap_name(func) -> str:
def gen_custom_yaml_path(original_path, codegen_yaml_filename=CUSTOM_YAML_NAME):
new_path = os.path.join(os.path.dirname(original_path), codegen_yaml_filename)
return new_path
def update_opapi_info(op_info):
global GLOBAL_OPAPI_INFO_CACHE
if isinstance(op_info, str):
return
elif isinstance(op_info, dict):
if op_info.get("op_api", False):
GLOBAL_OPAPI_INFO_CACHE.add(op_info.get("func").split("(")[0])
else:
print(f"Warning: Unsupported parameter types, only str and dict is supported, but input is {type(op_info)}")
def is_opapi(op_key):
global GLOBAL_OPAPI_INFO_CACHE
return op_key in GLOBAL_OPAPI_INFO_CACHE
+2 -1
View File
@@ -1,2 +1,3 @@
pyyaml
setuptools
setuptools
auditwheel
+84 -3
View File
@@ -23,10 +23,11 @@ from setuptools.command.install import install
from setuptools import setup, distutils, Extension
from setuptools.command.build_clib import build_clib
from setuptools.command.egg_info import egg_info
from wheel.bdist_wheel import bdist_wheel
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
THIRD_PARTY_PATH = os.path.join(BASE_DIR, "third_party")
VERSION = '2.1.0'
VERSION = '2.1.0.rc1'
UNKNOWN = "Unknown"
DISABLE_TORCHAIR = os.environ.get("DISABLE_INSTALL_TORCHAIR")
@@ -400,6 +401,31 @@ class PythonPackageBuild(build_py, object):
super(PythonPackageBuild, self).finalize_options()
class BdistWheelBuild(bdist_wheel):
def run(self):
torch_dependencies = ["libc10.so", "libtorch.so", "libtorch_cpu.so", "libtorch_python.so"]
cann_dependencies = ["libhccl.so", "libascendcl.so", "libacl_op_compiler.so", "libge_runner.so",
"libgraph.so", "libacl_tdt_channel.so", "libfmk_parser.so", "libascend_protobuf.so"]
other_dependencies = ["libtorch_npu.so", "libnpu_profiler.so", "libgomp.so.1"]
dependencies = torch_dependencies + cann_dependencies + other_dependencies
self.run_command('egg_info')
bdist_wheel.run(self)
if is_manylinux:
file = glob.glob(os.path.join(self.dist_dir, "*linux*.whl"))[0]
auditwheel_cmd = ["auditwheel", "-v", "repair", "-w", self.dist_dir, file]
for i in dependencies:
auditwheel_cmd += ["--exclude", i]
try:
subprocess.run(auditwheel_cmd, check=True, stdout=subprocess.PIPE)
finally:
os.remove(file)
build_mode = _get_build_mode()
if build_mode not in ['clean']:
# Generate bindings code, including RegisterNPU.cpp & NPUNativeFunctions.h.
@@ -439,12 +465,66 @@ else:
extra_compile_args += ['-DNDEBUG']
extra_link_args += ['-Wl,-z,now,-s']
# valid manylinux tags
manylinux_tags = [
"manylinux1_x86_64",
"manylinux2010_x86_64",
"manylinux2014_x86_64",
"manylinux2014_aarch64",
"manylinux_2_5_x86_64",
"manylinux_2_12_x86_64",
"manylinux_2_17_x86_64",
"manylinux_2_17_aarch64",
"manylinux_2_24_x86_64",
"manylinux_2_24_aarch64",
"manylinux_2_27_x86_64",
"manylinux_2_27_aarch64",
"manylinux_2_28_x86_64",
"manylinux_2_28_aarch64",
"manylinux_2_31_x86_64",
"manylinux_2_31_aarch64",
"manylinux_2_34_x86_64",
"manylinux_2_34_aarch64",
"manylinux_2_35_x86_64"
"manylinux_2_35_aarch64",
]
is_manylinux = os.environ.get("AUDITWHEEL_PLAT", None) in manylinux_tags
readme = os.path.join(BASE_DIR, "README.md")
if not os.path.exists(readme):
raise FileNotFoundError("Unable to find 'README.md'")
with open(readme, encoding="utf-8") as fdesc:
long_description = fdesc.read()
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: POSIX :: Linux",
"Topic :: Scientific/Engineering",
"Topic :: Scientific/Engineering :: Mathematics",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
"Programming Language :: Python",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
]
setup(
name=os.environ.get('TORCH_NPU_PACKAGE_NAME', 'torch_npu'),
version=VERSION,
description='NPU bridge for PyTorch',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://gitee.com/ascend/pytorch',
download_url="https://gitee.com/ascend/pytorch/tags",
license="BSD License",
classifiers=classifiers,
packages=["torch_npu"],
libraries=[('torch_npu', {'sources': list()})],
package_dir={'': os.path.relpath(os.path.join(BASE_DIR, f"build/{get_build_type()}/packages"))},
@@ -470,7 +550,8 @@ setup(
'build_clib': CPPLibBuild,
'build_ext': Build,
'build_py': PythonPackageBuild,
'bdist_wheel': BdistWheelBuild,
'egg_info': EggInfoBuild,
'clean': Clean,
'install': InstallCmd
'install': InstallCmd,
'clean': Clean
})
@@ -0,0 +1,49 @@
import math
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestIncreFlashAttention(TestCase):
def supported_op_exec(self, query, past_key, past_value, head_dim, hidden_size):
attn_weights1 = torch.matmul(query, past_key.transpose(2, 3)) / 0.0078125
attn_weights1 = torch.max(attn_weights1, torch.full((1, 1), torch.finfo(attn_weights1.dtype).min, device=attn_weights1.device))
attn_weights1 = torch.nn.functional.softmax(attn_weights1, dim=-1, dtype=torch.float32).to(query.dtype)
attn_output1 = torch.matmul(attn_weights1, past_value)
attn_output1 = attn_output1.transpose(1, 2)
attn_output1 = attn_output1.reshape(1, 1, hidden_size) # IFA (1, 1, 4096)
return attn_output1
def trans_BNSD2BSH(self, tensor: torch.Tensor):
tensor = torch.transpose(tensor, 1, 2)
tensor = torch.reshape(tensor, (tensor.shape[0], tensor.shape[1], -1))
return tensor
def custom_op_exec(self, q, k, v, head_dim):
scale = 1 / 0.0078125
return torch_npu.npu_incre_flash_attention(q, k, v, num_heads=32, input_layout="BSH", scale_value=scale)
def test_npu_incre_flash_attention(self, device="npu"):
q = torch.randn(1, 32, 1, 128, dtype=torch.float16).npu()
k = torch.randn(1, 32, 2048, 128, dtype=torch.float16).npu()
v = torch.randn(1, 32, 2048, 128, dtype=torch.float16).npu()
q_FA = self.trans_BNSD2BSH(q)
k_FA = self.trans_BNSD2BSH(k)
v_FA = self.trans_BNSD2BSH(v)
head_dim = 128
hidden_size = 4096
supported_output = self.supported_op_exec(q, k, v, head_dim, hidden_size)
custom_output = self.custom_op_exec(q_FA, k_FA, v_FA, head_dim)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,49 @@
import math
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestPromptFlashAttention(TestCase):
def supported_op_exec(self, query, past_key, past_value, head_dim, hidden_size):
attn_weights1 = torch.matmul(query, past_key.transpose(2, 3)) / 0.0078125
attn_weights1 = torch.max(attn_weights1, torch.full((1, 1), torch.finfo(attn_weights1.dtype).min, device=attn_weights1.device))
attn_weights1 = torch.nn.functional.softmax(attn_weights1, dim=-1, dtype=torch.float32).to(query.dtype)
attn_output1 = torch.matmul(attn_weights1, past_value)
attn_output1 = attn_output1.transpose(1, 2)
attn_output1 = attn_output1.reshape(1, 1, hidden_size) # IFA (1, 1, 4096)
return attn_output1
def trans_BNSD2BSH(self, tensor: torch.Tensor):
tensor = torch.transpose(tensor, 1, 2)
tensor = torch.reshape(tensor, (tensor.shape[0], tensor.shape[1], -1))
return tensor
def custom_op_exec(self, q, k, v, head_dim):
scale = 1 / 0.0078125
return torch_npu.npu_prompt_flash_attention(q, k, v, num_heads=32, input_layout="BSH", scale_value=scale)
def test_npu_prompt_flash_attention(self, device="npu"):
q = torch.randn(1, 32, 1, 128, dtype=torch.float16).npu()
k = torch.randn(1, 32, 2048, 128, dtype=torch.float16).npu()
v = torch.randn(1, 32, 2048, 128, dtype=torch.float16).npu()
q_FA = self.trans_BNSD2BSH(q)
k_FA = self.trans_BNSD2BSH(k)
v_FA = self.trans_BNSD2BSH(v)
head_dim = 128
hidden_size = 4096
supported_output = self.supported_op_exec(q, k, v, head_dim, hidden_size)
custom_output = self.custom_op_exec(q_FA, k_FA, v_FA, head_dim)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,36 @@
from typing import Any, Dict, List, Tuple, Union
import functools
import math
import numpy as np
from torch._functorch.aot_autograd import aot_module_simplified
import torch
from torch.library import Library, impl
from torch._subclasses.fake_tensor import FakeTensorMode
# include meta infer
import meta
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
fake_mode = FakeTensorMode()
class TestIncreFlashAttention(TestCase):
def testIncreFlashAttention(self):
with fake_mode:
q = torch.randn(1, 40, 1, 128, dtype=torch.float16).npu()
k = torch.randn(1, 40, 1, 128, dtype=torch.float16).npu()
v = torch.randn(1, 40, 1, 128, dtype=torch.float16).npu()
q.requires_grad = True
k.requires_grad = True
v.requires_grad = True
res = torch.ops.npu.npu_incre_flash_attention(q, k, v)
print("q.shape: ", q.shape)
print("res.shape: ", res.shape)
self.assertTrue(q.shape == res.shape)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,36 @@
rom typing import Any, Dict, List, Tuple, Union
import functools
import math
import numpy as np
from torch._functorch.aot_autograd import aot_module_simplified
import torch
from torch.library import Library, impl
from torch._subclasses.fake_tensor import FakeTensorMode
# include meta infer
import meta
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
fake_mode = FakeTensorMode()
class TestPromptFlashAttention(TestCase):
def testPromptFlashAttention(self):
with fake_mode:
q = torch.randn(1, 40, 1, 128, dtype=torch.float16).npu()
k = torch.randn(1, 40, 1, 128, dtype=torch.float16).npu()
v = torch.randn(1, 40, 1, 128, dtype=torch.float16).npu()
q.requires_grad = True
k.requires_grad = True
v.requires_grad = True
res = torch.ops.npu.npu_prompt_flash_attention(q, k, v)
print("q.shape: ", q.shape)
print("res.shape: ", res.shape)
self.assertTrue(q.shape == res.shape)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,53 @@
import math
import torch
import numpy as np
import torch_npu
import torch_npu.npu.utils as utils
from torch_npu.testing.testcase import TestCase, run_tests
class TestIncreFlashAttention(TestCase):
def baseline(self, query_states1, past_key, past_value, head_dim, hidden_size):
attn_weights1 = torch.matmul(query_states1, past_key.transpose(2, 3)) / 0.0078125
attn_weights1 = torch.max(attn_weights1, torch.full((1, 1), torch.finfo(attn_weights1.dtype).min, device=attn_weights1.device))
attn_weights1 = torch.nn.functional.softmax(attn_weights1, dim=-1, dtype=torch.float32).to(query_states1.dtype)
attn_output1 = torch.matmul(attn_weights1, past_value)
attn_output1 = attn_output1.transpose(1, 2)
attn_output1 = attn_output1.reshape(1, 1, hidden_size) # IFA (1, 1, 4096)
return attn_output1
def trans_BNSD2BSH(self, tensor: torch.Tensor):
tensor = torch.transpose(tensor, 1, 2)
tensor = torch.reshape(tensor, (tensor.shape[0], tensor.shape[1], -1))
return tensor
def incre_flash_attention_npu(self, q, k, v, head_dim):
scale = 1 / 0.0078125
return torch_npu.npu_incre_flash_attention(q, k, v, num_heads=32, input_layout="BSH", scale_value=scale)
def test_op_exec(self):
q = torch.randn(1, 32, 1, 128, dtype=torch.float16).npu()
k = torch.randn(1, 32, 2048, 128, dtype=torch.float16).npu()
v = torch.randn(1, 32, 2048, 128, dtype=torch.float16).npu()
q_FA = self.trans_BNSD2BSH(q)
k_FA = self.trans_BNSD2BSH(k)
v_FA = self.trans_BNSD2BSH(v)
print("input tensor size: q k v")
print(q_FA.size(), k_FA.size(), v_FA.size())
head_dim = 128
hidden_size = 4096
ifa_out = self.incre_flash_attention_npu(q_FA, k_FA, v_FA, head_dim)
print("IFA output", ifa_out, ifa_out.shape)
baseline_out = self.baseline(q, k, v, head_dim, hidden_size)
print("baseline output", baseline_out, baseline_out.shape)
self.assertRtolEqual(ifa_out, baseline_out)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,41 @@
mport math
import torch
import numpy as np
import torch_npu
import torch_npu.npu.utils as utils
from torch_npu.testing.testcase import TestCase, run_tests
class TestPromptFlashAttetion(TestCase):
def baseline(self, query_states1, past_key, past_value, head_dim):
attn_weights1 = torch.matmul(query_states1, past_key.transpose(2, 3)) / 0.0078125
attn_weights1 = torch.max(attn_weights1, torch.full((1, 1), torch.finfo(attn_weights1.dtype).min, device=attn_weights1.device))
attn_weights1 = torch.nn.functional.softmax(attn_weights1, dim=-1, dtype=torch.float32).to(query_states1.dtype)
attn_output1 = torch.matmul(attn_weights1, past_value)
return attn_output1
def prompt_flash_attention_npu(self, q, k, v, head_dim):
scale = 1 / 0.0078125
return torch_npu.npu_prompt_flash_attention(q, k, v, num_heads=32, input_layout="BNSD", scale_value=scale, pre_tokens=65535, next_tokens=65535)
def test_op_exec(self):
q = torch.randn(1, 32, 2048, 128, dtype=torch.float16).npu()
k = torch.randn(1, 32, 2048, 128, dtype=torch.float16).npu()
v = torch.randn(1, 32, 2048, 128, dtype=torch.float16).npu()
print("input tensor size: q k v")
print(q.size(), k.size(), v.size())
head_dim = 128
pfa_out = self.prompt_flash_attention_npu(q, k, v, head_dim)
print("PFA output", pfa_out, pfa_out.shape)
baseline_out = self.baseline(q, k, v, head_dim)
print("baseline output", baseline_out, baseline_out.shape)
self.assertRtolEqual(pfa_out, baseline_out)
if __name__ == "__main__":
run_tests()
+1 -1
View File
@@ -129,7 +129,7 @@ class ComputeBucketAssignmentTest(TestCase):
torch.empty([50], dtype=torch.float).npu(),
]
result = dist._compute_bucket_assignment_by_size(tensors, [1792 * 4 + 1])
expec_result = ([[0, 1, 2, 3]], [7169])
expec_result = ([[0, 1], [2, 3]], [7169, 7169])
self.assertEqual(expec_result, result)
def test_single_limit_multi_dtype(self):
+15
View File
@@ -1,3 +1,4 @@
import copy
import torch
import torch_npu
@@ -312,6 +313,20 @@ class TestStorage(TestCase):
self.assertIsInstance(getattr(y.npu(), dtype)(), getattr(torch.npu, dtype.title() + "Storage"))
self.assertIsInstance(getattr(y.float().cpu(), dtype)(), getattr(torch, dtype.title() + "Storage"))
def test_deepcopy(self):
x = torch.tensor([1])
y = copy.deepcopy(x)
x = torch.tensor([1]).npu()
y = copy.deepcopy(x)
self.assertNotEqual(x.storage().data_ptr(), y.storage().data_ptr())
x = torch.rand(3, 3).npu()
x = torch_npu.npu_format_cast(x, 29)
y = copy.deepcopy(x)
self.assertEqual(torch_npu.get_npu_format(y), 29)
self.assertEqual(x, y)
if __name__ == '__main__':
run_tests()
+11
View File
@@ -1184,6 +1184,17 @@ ACL_FUNC_VISIBILITY aclError aclrtSetOpWaitTimeout(uint32_t timeout);
*/
ACL_FUNC_VISIBILITY aclError aclrtSetDeviceSatMode(aclrtFloatOverflowMode mode);
/**
* @ingroup AscendCL
* @brief Set the timeout interval for op executing
*
* @param timeout [IN] op execute timeout
*
* @retval ACL_SUCCESS The function is successfully executed.
* @retval OtherValues Failure
*/
ACL_FUNC_VISIBILITY aclError aclrtSetOpExecuteTimeOut(uint32_t timeout);
/**
* @ingroup AscendCL
* @brief enable or disable overflow switch on some stream
+8 -2
View File
@@ -34,9 +34,9 @@ except ImportError as e:
else:
traceback.print_exc()
import torch_npu.optim
import torch_npu.npu.amp
import torch_npu.npu.aclnn
import torch_npu.optim
import torch_npu.dynamo
import torch_npu._C
from torch_npu import profiler
@@ -47,6 +47,7 @@ from torch_npu.utils import apply_module_patch, add_tensor_methods, \
import torch_npu.utils.custom_ops
from torch_npu.utils import cann_package_check, add_intercept_methods
from .version import __version__ as __version__
from .meta import meta_registrations
cann_package_check()
@@ -108,6 +109,11 @@ def _apply_patches(monkey_patches):
setattr(dest_module, attr, getattr(patch, attr))
def _apply_distributed_patches():
torch.nn.parallel.DistributedDataParallel._ddp_init_helper = torch_npu.utils.module._ddp_init_helper
_apply_patches([["distributed", torch_npu.distributed]])
def apply_class_patches():
add_storage_methods()
apply_module_patch()
@@ -126,6 +132,7 @@ torch.utils.generate_methods_for_privateuse1_backend(for_tensor=True, for_module
# Apply monkey-patches.
_apply_patches(all_monkey_patches)
_apply_distributed_patches()
apply_class_patches()
torch.distributed.is_hccl_available = lambda : True
@@ -133,7 +140,6 @@ torch.distributed.is_hccl_available = lambda : True
torch_npu._C._initExtension()
# init and register hccl backend
torch_npu._C._c10d_npu_init()
torch.distributed.Backend.register_backend("hccl", lambda store, group_rank, group_size, timeout :
torch_npu._C._distributed_c10d.ProcessGroupHCCL(store, group_rank, group_size, timeout), devices=["npu"])
+9
View File
@@ -118,6 +118,13 @@ def wrapper_profiler(fn):
return decorated
def jit_script(obj, optimize=None, _frames_up=0, _rcb=None, example_inputs=None):
msg = 'torch.jit.script will be disabled by transfer_to_npu, which currently does not support it, ' \
'if you need to enable torch.jit.script, please do not use transfer_to_npu.'
warnings.warn(msg, RuntimeWarning)
return obj
def patch_cuda():
patchs = [
['cuda', torch_npu.npu], ['cuda.amp', torch_npu.npu.amp],
@@ -202,5 +209,7 @@ def init():
# torch.utils.data.DataLoader
torch.utils.data.DataLoader.__init__ = wrapper_data_loader(torch.utils.data.DataLoader.__init__)
torch.jit.script = jit_script
init()
+2 -1
View File
@@ -2,7 +2,8 @@ FILE(GLOB _ATEN_SRCS
*.cpp
common/*.cpp
mirror/*.cpp
ops/*.cpp)
ops/*.cpp
ops/op_api/*.cpp)
FILE(GLOB _EXCLUDE
VariableTypeEverything.cpp
@@ -122,10 +122,19 @@ int64_t NPUNativeFunctions::get_npu_format(const at::Tensor& src) {
return src_desc.npu_format_;
}
at::Tensor NPUNativeFunctions::_npu_format_cast(const at::Tensor& self,
int64_t acl_format) {
return npu_format_cast_impl(self, acl_format);
}
at::Tensor NPUNativeFunctions::npu_format_cast(const at::Tensor& self,
int64_t acl_format) {
torch_npu::utils::torch_check_npu(self);
return npu_format_cast_impl(self, acl_format);
if (NPUNativeFunctions::get_npu_format(self) == acl_format) {
ASCEND_LOGD("no need to do format cast");
return self;
}
return custom_ops::_npu_format_cast(self, acl_format);
}
} // namespace native
+15 -8
View File
@@ -84,23 +84,30 @@ at::Tensor& NPUNativeFunctions::set_(at::Tensor& self, c10::Storage src) {
return self;
}
at::Tensor& set_tensor_with_storage_format(at::Tensor& self, c10::Storage src) {
at::Tensor set_tensor_with_storage_format(c10::Storage src) {
if (StorageDescHelper::CheckDescInit(src)) {
// The storage object src has complete description information,
// and the tensor object self needs to be brushed to be the same
auto desc = torch_npu::NPUBridge::GetNpuStorageImpl(src.unsafeGetStorageImpl())->npu_desc_;
set_storage_nd_npu(self, src, 0, desc.base_sizes_.size(), desc.base_sizes_, desc.base_strides_);
auto dist_tensor = NPUNativeFunctions::empty(
{0}, desc.data_type_.toScalarType(), c10::nullopt,
at::Device(c10::DeviceType::PrivateUse1), false, c10::MemoryFormat::Contiguous);
set_storage_nd_npu(dist_tensor, src, 0, desc.base_sizes_.size(), desc.base_sizes_, desc.base_strides_);
return dist_tensor;
} else {
// The storage object src doesn't have complete description information,
// and the tensor object self needs to be brushed to be the 1 dimension
int64_t new_size = static_cast<int64_t>(src.nbytes() / self.dtype().itemsize());
set_storage_nd_npu(self, src, 0, 1, {new_size}, {});
auto dist_tensor = NPUNativeFunctions::empty(
{0}, at::ScalarType::Char, c10::nullopt,
at::Device(c10::DeviceType::PrivateUse1), false, c10::MemoryFormat::Contiguous);
int64_t new_size = static_cast<int64_t>(src.nbytes() / dist_tensor.dtype().itemsize());
set_storage_nd_npu(dist_tensor, src, 0, 1, {new_size}, {});
StorageDescHelper::SetDesc(
self,
self.unsafeGetTensorImpl()->sizes(),
self.unsafeGetTensorImpl()->strides());
dist_tensor,
dist_tensor.unsafeGetTensorImpl()->sizes(),
dist_tensor.unsafeGetTensorImpl()->strides());
return dist_tensor;
}
return self;
}
} // namespace native
+1 -1
View File
@@ -12,7 +12,7 @@
namespace at_npu {
namespace native {
at::Tensor& set_tensor_with_storage_format(at::Tensor& self, c10::Storage src);
at::Tensor set_tensor_with_storage_format(c10::Storage src);
} // namespace native
} // namespace at_npu
@@ -11,9 +11,11 @@ supported:
- bartlett_window.periodic
- blackman_window
- blackman_window.periodic
- clone
- func: clone
op_api: True
- contiguous
- copy_
- func: copy_
op_api: True
- copy_memory_
- empty.memory_format
- empty_like
@@ -74,6 +76,7 @@ custom:
- func: copy_memory_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!)
- func: get_storage_size(Tensor self) -> int
- func: npu_format_cast(Tensor self, int acl_format) -> Tensor
- func: _npu_format_cast(Tensor self, int acl_format) -> Tensor
symint:
- as_strided_
@@ -0,0 +1,167 @@
// Copyright (c) 2023 Huawei Technologies Co., Ltd
// Copyright (c) 2023, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "torch_npu/csrc/core/npu/NPUGuard.h"
#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h"
#include "torch_npu/csrc/framework/contiguous/ContiguousOpt.h"
#include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h"
#include "torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h"
#include "torch_npu/csrc/aten/NPUOpApiNativeFunctions.h"
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "third_party/op-plugin/op_plugin/utils/op_api_common.h"
namespace at_npu {
namespace native {
// the format of dst and src is base format now
// the dtype of dst and src is same
// and src and dst are contiguous
void copy_between_host_and_device_opapi(at::Tensor& dst, const at::Tensor& src, aclrtMemcpyKind kind,
bool non_blocking)
{
int64_t nbytes = dst.numel() * dst.element_size();
c10_npu::NPUStream stream = c10_npu::getCurrentNPUStream();
if (non_blocking) {
auto ret = CalcuOpUtil::LaunchAsyncCopyTaskWithModeSwitch(dst, nbytes, src, nbytes, kind);
NPU_CHECK_ERROR(ret);
ASCEND_LOGD("non_blocking copy without StreamSynchronize.");
void* ptr = torch_npu::utils::is_npu(dst) ? src.data_ptr() : dst.data_ptr();
NPU_CHECK_ERROR(THNPUCachingHostAllocator_recordEvent(ptr, stream));
} else {
aclError error = aclrtSynchronizeStream(stream);
auto ret = CalcuOpUtil::AclrtMemcpyWithModeSwitch(
std::make_pair(dst.storage().unsafeGetStorageImpl(), dst.storage_offset() * dst.itemsize()), nbytes,
std::make_pair(src.storage().unsafeGetStorageImpl(), src.storage_offset() * src.itemsize()), nbytes, kind);
NPU_CHECK_ERROR(ret);
if (error != ACL_ERROR_NONE) {
C10_NPU_SHOW_ERR_MSG();
if (c10_npu::option::OptionsManager::IsResumeModeEnable()) {
TORCH_NPU_WARN("ACL stream synchronize failed, error code:", error,
". But in checkpoint-resume mode will not throw exceptions.");
} else {
AT_ERROR("ACL stream synchronize failed, error code:", error);
}
}
}
}
// the format of dst and src is base format now
// the dtype of dst and src is same
// and src and dst are contiguous
void copy_h2d_baseformat_dtype_contigous_opapi(at::Tensor& dst, const at::Tensor& src, bool non_blocking)
{
c10_npu::OptionalNPUGuard device_guard;
device_guard.set_device(dst.device());
aclrtMemcpyKind kind = aclrtMemcpyKind::ACL_MEMCPY_HOST_TO_DEVICE;
copy_between_host_and_device_opapi(dst, src, kind, non_blocking);
}
// the format of dst and src is baseformat now
// the dtype of dst and src is same
// and src and dst are contiguous
void copy_d2h_baseformat_dtype_contigous_opapi(at::Tensor& dst, const at::Tensor& src, bool non_blocking)
{
c10_npu::OptionalNPUGuard device_guard;
device_guard.set_device(src.device());
aclrtMemcpyKind kind = aclrtMemcpyKind::ACL_MEMCPY_DEVICE_TO_HOST;
copy_between_host_and_device_opapi(dst, src, kind, non_blocking);
}
// the format of dst and src is baseformat now
void copy_h2d_baseformat_opapi(at::Tensor& dst, const at::Tensor& src, bool non_blocking,
bool dst_must_be_contiguous = false)
{
bool same_type = (src.dtype() == dst.dtype());
bool dst_is_contiguous = dst_must_be_contiguous ? true : dst.is_contiguous();
if (same_type && dst_is_contiguous && src.is_contiguous()) {
copy_h2d_baseformat_dtype_contigous_opapi(dst, src, non_blocking);
return;
}
at::Tensor dst_contig = dst_is_contiguous ? dst : at::empty_like(dst);
at::Tensor src_contig;
if (!same_type) {
src_contig = src.to(dst.dtype()).expand_as(dst).contiguous();
} else {
src_contig = src.expand_as(dst).contiguous();
}
// perform a same-dtype copy on contiguous tensors
TORCH_INTERNAL_ASSERT(dst_contig.sizes().equals(src_contig.sizes()));
TORCH_INTERNAL_ASSERT(dst_contig.scalar_type() == src_contig.scalar_type());
copy_h2d_baseformat_dtype_contigous_opapi(dst_contig, src_contig, non_blocking);
// if necessary, copy back into dst
if (!dst_contig.is_same(dst)) {
TORCH_INTERNAL_ASSERT(dst_contig.device() == dst.device());
copy_d2d_dtype(dst, dst_contig, non_blocking);
}
}
// the format of dst and src is baseformat now
void copy_d2h_baseformat_opapi(at::Tensor& dst, const at::Tensor& src, bool non_blocking)
{
bool same_type = (src.dtype() == dst.dtype());
bool dst_is_contiguous = dst.is_contiguous();
if (same_type && dst_is_contiguous && src.is_contiguous()) {
copy_d2h_baseformat_dtype_contigous_opapi(dst, src, non_blocking);
return;
}
at::Tensor dst_contig = (dst_is_contiguous && same_type) ? dst : at::empty_like(dst, src.dtype());
at::Tensor src_contig = src.expand_as(dst).contiguous();
// perform a same-dtype copy on contiguous tensors
TORCH_INTERNAL_ASSERT(dst_contig.sizes().equals(src_contig.sizes()));
TORCH_INTERNAL_ASSERT(dst_contig.scalar_type() == src_contig.scalar_type());
copy_d2h_baseformat_dtype_contigous_opapi(dst_contig, src_contig, non_blocking);
// if necessary, copy back into dst
if (!dst_contig.is_same(dst)) {
TORCH_INTERNAL_ASSERT(dst_contig.device() == dst.device());
dst.copy_(dst_contig, non_blocking); // h2h, use cpu copy
}
}
at::Tensor& NPUNativeOpApiFunctions::copy_(at::Tensor& self, const at::Tensor& src, bool non_blocking)
{
DO_COMPATIBILITY(aclnnInplaceCopy, NPUNativeFunctions::copy_(self, src, non_blocking));
if (self.numel() == 0) {
return self;
}
// save tensor dim name
c10::optional<at::DimnameList> names = src.opt_names();
if (names.has_value()) {
internal_set_names_inplace(self, names);
}
if (torch_npu::utils::is_npu(self)) {
if (torch_npu::utils::is_npu(src)) {
c10::SmallVector<at::Tensor, N> inputs = {src};
c10::SmallVector<at::Tensor, N> outputs = {self};
CalcuOpUtil::CheckMemoryOverLaps(inputs, outputs);
EXEC_NPU_CMD(aclnnInplaceCopy, self, src);
} else {
copy_h2d_baseformat_opapi(self, src, non_blocking);
}
} else {
if (torch_npu::utils::is_npu(src)) {
copy_d2h_baseformat_opapi(self, src, non_blocking);
}
}
return self;
}
} // namespace native
} // namespace at_npu
@@ -0,0 +1,36 @@
// Copyright (c) 2023 Huawei Technologies Co., Ltd
// Copyright (c) 2023, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "third_party/op-plugin/op_plugin/utils/op_api_common.h"
#include "torch_npu/csrc/framework/utils/OpPreparation.h"
#include "torch_npu/csrc/aten/NPUOpApiNativeFunctions.h"
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
namespace at_npu {
namespace native {
at::Tensor NPUNativeOpApiFunctions::clone(const at::Tensor &src, c10::optional<c10::MemoryFormat> format)
{
DO_COMPATIBILITY(aclnnInplaceCopy, NPUNativeFunctions::clone(src, format));
auto baseSelf = OpPreparation::apply_tensor_without_format(src);
EXEC_NPU_CMD(aclnnInplaceCopy, baseSelf, src);
return baseSelf;
}
} // namespace native
} // namespace at_npu
@@ -19,6 +19,7 @@
#include "torch_npu/csrc/core/npu/NPUCachingAllocator.h"
#include "torch_npu/csrc/core/npu/NPUGuard.h"
#include "NPUBlockHandle.h"
#include "torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.h"
#include "torch_npu/csrc/core/npu/NPUEvent.h"
namespace c10_npu {
@@ -1175,8 +1176,9 @@ class DeviceCachingAllocator {
}
void insert_events(Block* block) {
int prev_device = 0;
NPU_CHECK_ERROR(aclrtGetDevice(&prev_device));
aclrtContext* compiler_ctx = new aclrtContext();
aclError ret_ctx = aclrtGetCurrentContext(compiler_ctx);
NPU_CHECK_ERROR(aclrtSetCurrentContext(c10_npu::NpuSysCtrl::GetInstance().InitializedContext()));
stream_set streams(std::move(block->stream_uses));
AT_ASSERT(block->stream_uses.empty());
@@ -1196,13 +1198,8 @@ class DeviceCachingAllocator {
block->event_count++;
npu_events[stream].emplace_back(std::move(event), block);
}
int cur_device = 0;
aclError ret = aclrtGetDevice(&cur_device);
if (ret != ACL_ERROR_NONE) {
NPU_CHECK_ERROR(aclrtSetDevice(prev_device));
} else if (cur_device != prev_device) {
NPU_CHECK_ERROR(aclrtSetDevice(prev_device));
if (ret_ctx == ACL_ERROR_NONE) {
NPU_CHECK_ERROR(aclrtSetCurrentContext(*compiler_ctx));
}
}
+10 -2
View File
@@ -47,7 +47,8 @@ static constexpr int kStreamsPerPool = 1 << kStreamsPerPoolBits;
// static constexpr unsigned int kDefaultFlags = npuStreamNonBlocking;
// Default streams
static std::once_flag init_flag;
static int initialize_flag = 0;
std::mutex mtx;
static LeakyStreamInternals default_streams[C10_COMPILE_TIME_MAX_NPUS];
// In a specific scenario, the two operators have no value dependence
@@ -176,7 +177,14 @@ static void initDeviceStreamState(c10::DeviceIndex device_index) {
static void initNPUStreamsOnce() {
// Inits default and secondary streams (once, globally)
std::call_once(init_flag, initGlobalStreamState);
if (initialize_flag == 0) {
mtx.lock();
if (initialize_flag == 0) {
initGlobalStreamState();
initialize_flag = 1;
}
mtx.unlock();
}
if (current_streams) {
return;
+1
View File
@@ -21,6 +21,7 @@ static std::map<std::string, SocVersion> socVersionMap = {
{"Ascend310P4", SocVersion::Ascend310P4},
{"Ascend910B1", SocVersion::Ascend910B1},
{"Ascend910B2", SocVersion::Ascend910B2},
{"Ascend910B2C", SocVersion::Ascend910B2C},
{"Ascend910B3", SocVersion::Ascend910B3},
{"Ascend910B4", SocVersion::Ascend910B4},
{"Ascend310B1", SocVersion::Ascend310B1},
+1
View File
@@ -15,6 +15,7 @@ enum class SocVersion {
Ascend310P4,
Ascend910B1 = 220,
Ascend910B2,
Ascend910B2C,
Ascend910B3,
Ascend910B4,
Ascend310B1 = 240,
+1 -2
View File
@@ -87,8 +87,7 @@ struct NPUGuardImpl final : public c10::impl::DeviceGuardImplInterface {
if (!event)
return;
auto acl_event = static_cast<aclrtEvent>(event);
int orig_device;
NPU_CHECK_WARN(aclrtDestroyEvent(acl_event));
NPU_CHECK_WARN(c10_npu::NPUEventManager::GetInstance().LazyDestroy(acl_event));
ASCEND_LOGI("Event: aclrtDestroyEvent is successfully executed, acl_event=%p.", acl_event);
}
@@ -13,7 +13,7 @@ namespace acl {
#define LOAD_FUNCTION(funcName) \
REGISTER_FUNCTION(libascendcl, funcName)
#undef GET_FUNC
#define GET_FUNC(funcName) \
#define GET_FUNC(funcName) \
GET_FUNCTION(libascendcl, funcName)
REGISTER_LIBRARY(libascendcl)
@@ -36,6 +36,7 @@ LOAD_FUNCTION(aclrtSetStreamFailureMode)
LOAD_FUNCTION(aclrtSetOpWaitTimeout)
LOAD_FUNCTION(aclrtCreateStreamWithConfig)
LOAD_FUNCTION(aclrtSetDeviceSatMode)
LOAD_FUNCTION(aclrtSetOpExecuteTimeOut)
LOAD_FUNCTION(aclrtSetStreamOverflowSwitch)
LOAD_FUNCTION(aclrtGetStreamOverflowSwitch)
LOAD_FUNCTION(aclrtSynchronizeStreamWithTimeout)
@@ -303,6 +304,18 @@ aclError AclrtSetStreamOverflowSwitch(aclrtStream stream, uint32_t flag) {
return func(stream, flag);
}
aclError AclrtSetOpExecuteTimeOut(uint32_t timeout) {
typedef aclError (*AclrtSetOpExecuteTimeOut)(uint32_t);
static AclrtSetOpExecuteTimeOut func = nullptr;
if (func == nullptr) {
func = (AclrtSetOpExecuteTimeOut)GET_FUNC(aclrtSetOpExecuteTimeOut);
}
if (func == nullptr) {
return ACL_ERROR_RT_FEATURE_NOT_SUPPORT;
}
return func(timeout);
}
aclError AclrtGetStreamOverflowSwitch(aclrtStream stream, uint32_t *flag) {
typedef aclError (*AclrtGetStreamOverflowSwitch)(aclrtStream, uint32_t*);
static AclrtGetStreamOverflowSwitch func = nullptr;
@@ -116,6 +116,8 @@ aclError AclrtSetStreamOverflowSwitch(aclrtStream stream, uint32_t flag);
aclError AclrtGetStreamOverflowSwitch(aclrtStream stream, uint32_t *flag);
aclError AclrtSetOpExecuteTimeOut(uint32_t timeout);
aclError AclrtSynchronizeStreamWithTimeout(aclrtStream stream);
aclError AclrtDestroyStreamForce(aclrtStream stream);
@@ -26,7 +26,7 @@ bool OptionsManager::IsMultiStreamMemoryReuse() {
bool OptionsManager::CheckInfNanModeEnable() {
const static bool checkInfNanModeEnable = []() -> bool {
int32_t enable = OptionsManager::GetBoolTypeOption("INF_NAN_MODE_ENABLE", 0);
int32_t enable = OptionsManager::GetBoolTypeOption("INF_NAN_MODE_ENABLE", 1);
return enable != 0;
}();
return checkInfNanModeEnable;
@@ -31,6 +31,7 @@
#endif
namespace {
const uint32_t kMaxOpExecuteTimeOut = 547U;
const size_t kMaxPathLen = 4096U;
std::string GetCurDirPath() {
char buff[kMaxPathLen] = {'\0'};
@@ -130,6 +131,8 @@ NpuSysCtrl::NpuSysCtrl() : init_flag_(false), device_id_(0) {}
ASCEND_LOGE("Npu device %d has been set before global init.", device_id_);
}
NPU_CHECK_ERROR(aclrtGetCurrentContext(&ctx_));
if (c10_npu::option::OptionsManager::CheckAclDumpDateEnable()) {
const char *aclConfigPath = "acl.json";
NPU_CHECK_ERROR(aclmdlSetDump(aclConfigPath));
@@ -161,6 +164,7 @@ NpuSysCtrl::NpuSysCtrl() : init_flag_(false), device_id_(0) {}
SetHF32DefaultValue();
NPU_CHECK_ERROR(at_npu::native::AclrtCtxSetSysParamOpt(aclSysParamOpt::ACL_OPT_DETERMINISTIC, 0));
NPU_CHECK_SUPPORTED_OR_ERROR(c10_npu::acl::AclrtSetOpExecuteTimeOut(kMaxOpExecuteTimeOut));
init_flag_ = true;
ASCEND_LOGD("Npu sys ctrl initialize successfully.");
@@ -172,6 +176,7 @@ NpuSysCtrl::NpuSysCtrl() : init_flag_(false), device_id_(0) {}
NPU_CHECK_ERROR(aclrtResetDevice(pre_device));
NPU_CHECK_ERROR(aclrtSetDevice(device));
device_id_= device;
aclrtGetCurrentContext(&ctx_);
return INIT_SUCC;
}
@@ -61,6 +61,15 @@ public:
return -1;
}
aclrtContext InitializedContext()
{
if (GetInitFlag()) {
return ctx_;
}
TORCH_CHECK(false, "no npu device context has been initialized!");
return nullptr;
}
// Register fn to be called during stage of exit and
// the callability of fn is guaranteed by the caller.
void RegisterReleaseFn(ReleaseFn release_fn,
@@ -71,6 +80,7 @@ private:
private:
bool init_flag_;
int device_id_;
aclrtContext ctx_;
std::map<ReleasePriority, std::vector<ReleaseFn>> release_fn_;
};
+261
View File
@@ -18,8 +18,10 @@
#include <torch/csrc/distributed/c10d/python_comm_hook.h>
#include "torch_npu/csrc/distributed/ProcessGroupHCCL.hpp"
#include "torch_npu/csrc/distributed/reducer.hpp"
#include "torch_npu/csrc/distributed/Init.h"
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/aten/CustomFunctions.h"
#include "torch_npu/csrc/core/NPUBridge.h"
@@ -89,6 +91,112 @@ template <typename T>
using intrusive_ptr_no_gil_destructor_class_ =
py::class_<T, IntrusivePtrNoGilDestructor<T>>;
class BroadcastWork {
public:
inline std::vector<at::Tensor> cast_tensors(at::TensorList tensors) {
static auto cast_back_to_ori_format = [](const at::Tensor &t) {
return at_npu::native::custom_ops::npu_format_cast(t, torch_npu::NPUBridge::GetNpuStorageImpl(t)->npu_desc_.origin_format_);
};
return c10::fmap(tensors, cast_back_to_ori_format);
}
BroadcastWork(
const c10::intrusive_ptr<c10d::ProcessGroup>& process_group,
std::vector<at::Tensor> bucket_tensors,
int root_rank = 0)
: bucket_tensors_(std::move(bucket_tensors)),
cast_tensors_(cast_tensors(bucket_tensors_)),
flat_tensor_({torch::utils::flatten_dense_tensors(cast_tensors_)}) {
c10d::BroadcastOptions broadcastOptions;
broadcastOptions.rootRank = root_rank;
work_ = process_group->broadcast(flat_tensor_, broadcastOptions);
}
void finish() {
work_->wait();
auto output_tensors = torch::utils::unflatten_dense_tensors(
flat_tensor_.front(), cast_tensors_);
TORCH_INTERNAL_ASSERT(output_tensors.size() == bucket_tensors_.size());
for (const auto i : c10::irange(output_tensors.size())) {
bucket_tensors_[i].copy_(output_tensors[i], true);
}
}
protected:
// The list of tensors to broadcast. They are guaranteed to be
// placed on the same device and have the same dtype.
std::vector<at::Tensor> bucket_tensors_;
// Some tensors with format, such as FRACTAL_Z, 5HD, may be padded to
// keep alignment with 16*16 cube kernel which will modify storage as
// input tensor for cat operation during flatten to a buffer tensor.
// So, it needs to cast all bucket tensors to tensors with format HCHW
std::vector<at::Tensor> cast_tensors_;
// The vector with a single flattened tensor containing the contents
// of the tensors in bucket_tensors_. It must be stored in a vector
// because c10d::ProcessGroup::broadcast takes a vector argument.
std::vector<at::Tensor> flat_tensor_;
private:
// The broadcast work that is kicked off upon construction.
c10::intrusive_ptr<c10d::Work> work_;
};
// Broadcast many tensors to all processes in the process group.
void broadcast_coalesced(
c10::intrusive_ptr<c10d::ProcessGroup> process_group,
at::TensorList tensors,
size_t buffer_size,
int rank) {
// Coalesce tensors into buckets taking into account the maximum buffer size.
// This routine is multi-device aware, so the tensors can be split across
// multiple devices and can contain a mix of CPU and CUDA tensors.
std::vector<std::vector<size_t>> buckets;
std::tie(buckets, std::ignore) =
c10d_npu::compute_bucket_assignment_by_size(tensors.vec(), {buffer_size});
// Returns tensor at specified index in input tensor list.
const auto lookup = [&tensors](size_t index) { return tensors[index]; };
// We maintain a maximum of 2 in flight broadcast operations to avoid
// allocating too much memory (in case the specified tensors are very large).
std::deque<BroadcastWork> in_flight;
constexpr auto max_in_flight = 2;
for (const auto& bucket : buckets) {
if (in_flight.size() >= max_in_flight) {
in_flight.front().finish();
in_flight.pop_front();
}
in_flight.emplace_back(process_group, c10::fmap(bucket, lookup), rank);
}
while (!in_flight.empty()) {
in_flight.front().finish();
in_flight.pop_front();
}
}
// Called from DDP's Python API to create a c10d Python comm hook object.
// The input state and callable comm_hook are Python objects. It later calls
// register_comm_hook function of the reducer input to register the hook.
void _register_comm_hook(
c10d_npu::Reducer& reducer,
py::object state,
py::object comm_hook) {
reducer.register_comm_hook(std::make_unique<::c10d::PythonCommHook>(
std::move(state), std::move(comm_hook)));
}
// Called from DDP's Python API to create a c10d C++ comm hook.
// The input is an enum hook type. It later calls register_builtin_comm_hook
// function of the reducer input to set the hook type.
void _register_builtin_comm_hook(
c10d_npu::Reducer& reducer,
::c10d::BuiltinCommHookType comm_hook_type) {
reducer.register_builtin_comm_hook(comm_hook_type);
}
PyObject* c10d_npu_init(PyObject* _unused, PyObject* noargs) {
auto torch_npu_C_module = THPObjectPtr(PyImport_ImportModule("torch_npu._C"));
@@ -101,6 +209,159 @@ PyObject* c10d_npu_init(PyObject* _unused, PyObject* noargs) {
torch_npu_C_m.def_submodule("_distributed_c10d", "distributed c10d bindings");
auto module = py::handle(m).cast<py::module>();
module.def("_compute_bucket_assignment_by_size",
[](const std::vector<at::Tensor>& tensors,
const std::vector<size_t>& bucket_size_limits,
const std::vector<bool>& expect_sparse_gradient,
const std::vector<int64_t>& tensor_indices,
const c10::optional<std::shared_ptr<::c10d::Logger>>& logger) {
if (logger.has_value()) {
std::weak_ptr<::c10d::Logger> logger_weakref = logger.value();
return ::c10d_npu::compute_bucket_assignment_by_size(tensors, bucket_size_limits, expect_sparse_gradient, tensor_indices, {logger_weakref});
} else {
return ::c10d_npu::compute_bucket_assignment_by_size(tensors, bucket_size_limits, expect_sparse_gradient, tensor_indices, {});
}
},
py::arg("tensors"),
py::arg("bucket_size"),
py::arg("expect_sparse_gradient") = std::vector<bool>(),
py::arg("tensor_indices") = std::vector<int64_t>(),
py::arg("logger") = c10::optional<std::shared_ptr<::c10d::Logger>>{},
py::call_guard<py::gil_scoped_release>());
module.def("_verify_params_across_processes",
[](const c10::intrusive_ptr<::c10d::ProcessGroup>& process_group,
const std::vector<at::Tensor>& params,
const c10::optional<std::shared_ptr<::c10d::Logger>>& logger) {
if (logger.has_value()) {
std::weak_ptr<::c10d::Logger> logger_weakref = logger.value();
c10d_npu::verify_params_across_processes(process_group, params, {logger_weakref});
} else {
c10d_npu::verify_params_across_processes(process_group, params, {});
}
},
py::arg("process_group"),
py::arg("params"),
py::arg("logger") = c10::optional<std::shared_ptr<::c10d::Logger>>{},
py::call_guard<py::gil_scoped_release>());
module
.def("_register_comm_hook",
&_register_comm_hook,
py::arg("reducer"),
py::arg("state"),
py::arg("comm_hook"),
py::call_guard<py::gil_scoped_release>())
.def("_register_builtin_comm_hook",
&_register_builtin_comm_hook,
py::arg("reducer"),
py::arg("comm_hook_type"));
module.def("_broadcast_coalesced",
// Define a lambda such that the pybind11 prototype can take a std::vector
// for the tensor list argument, but still pass it to the underlying
// function as a c10::ArrayRef.
[](c10::intrusive_ptr<::c10d::ProcessGroup> process_group,
std::vector<at::Tensor> tensors, // NOLINT
size_t buffer_size,
int rank) {
torch_npu::distributed::broadcast_coalesced(
std::move(process_group), tensors, buffer_size, rank);
},
py::arg("process_group"),
py::arg("tensors"),
py::arg("buffer_size"),
// The source of truth rank to broadcast the tensors from.
py::arg("src") = 0,
py::call_guard<py::gil_scoped_release>());
shared_ptr_class_<c10d_npu::Reducer>(module, "Reducer")
.def(py::init<
std::vector<at::Tensor>,
std::vector<std::vector<size_t>>,
std::vector<size_t>,
c10::intrusive_ptr<::c10d::ProcessGroup>,
std::vector<bool>,
int64_t,
bool,
bool,
std::unordered_map<size_t, std::string>,
int64_t>(),
py::arg("params"),
py::arg("bucket_indices"),
py::arg("per_bucket_size_limits"),
py::arg("process_group"),
py::arg("expect_sparse_gradients") = std::vector<bool>(),
py::arg("bucket_bytes_cap") = ::c10d::kDefaultBucketBytesCap,
py::arg("find_unused_parameters") = false,
py::arg("gradient_as_bucket_view") = false,
py::arg("param_to_name_mapping") =
std::unordered_map<size_t, std::string>(),
py::arg("first_bucket_bytes_cap") = ::c10d::kDefaultFirstBucketBytes,
py::call_guard<py::gil_scoped_release>())
.def("prepare_for_forward",
&c10d_npu::Reducer::prepare_for_forward,
py::call_guard<py::gil_scoped_release>())
.def("prepare_for_backward",
&c10d_npu::Reducer::prepare_for_backward,
py::call_guard<py::gil_scoped_release>())
.def("prepare_for_backward",
[](c10d_npu::Reducer& reducer, const at::Tensor& output)
-> void { reducer.prepare_for_backward({output}); },
py::call_guard<py::gil_scoped_release>())
.def("get_backward_stats", &c10d_npu::Reducer::get_backward_stats)
.def("_install_post_backward_futures", [](::c10d_npu::Reducer& reducer, const std::vector<std::shared_ptr<torch::jit::PythonFutureWrapper>>& futs) {
c10::List<c10::intrusive_ptr<c10::ivalue::Future>> futures(c10::FutureType::create(c10::TensorType::get()));
for (const auto &fut : futs) {
futures.push_back(fut->fut);
}
reducer.install_futures(std::move(futures));
},
py::call_guard<py::gil_scoped_release>())
.def("_rebuild_buckets",
&::c10d_npu::Reducer::rebuild_buckets,
py::call_guard<py::gil_scoped_release>())
.def("_get_zeros_like_grad_buckets",
[](::c10d_npu::Reducer& reducer) {
return reducer.get_grad_buckets(true);
},
py::call_guard<py::gil_scoped_release>())
.def("_push_all_rebuilt_params",
&::c10d_npu::Reducer::push_rebuilt_params_for_all_indices,
py::call_guard<py::gil_scoped_release>())
.def("_set_forward_pass_work_handle",
&::c10d_npu::Reducer::set_forward_pass_work_handle,
py::call_guard<py::gil_scoped_release>())
.def("_get_local_used_map",
&::c10d_npu::Reducer::get_local_used_map_on_device)
.def("_set_ddp_runtime_logging_sample_rate",
&::c10d_npu::Reducer::set_ddp_runtime_logging_sample_rate,
py::arg("sample_rate"),
py::call_guard<py::gil_scoped_release>())
.def("_set_static_graph",
&::c10d_npu::Reducer::set_static_graph,
py::call_guard<py::gil_scoped_release>())
.def("_ddp_graph_static",
&::c10d_npu::Reducer::ddp_graph_static,
py::call_guard<py::gil_scoped_release>())
.def("_delay_all_reduce",
&::c10d_npu::Reducer::delay_all_reduce,
py::call_guard<py::gil_scoped_release>())
.def("_run_comm_hook",
[](::c10d_npu::Reducer& reducer, ::c10d::GradBucket& bucket)
-> std::shared_ptr<torch::jit::PythonFutureWrapper> {
c10::intrusive_ptr<c10::ivalue::Future> fut =
reducer.run_comm_hook(bucket);
return std::make_shared<torch::jit::PythonFutureWrapper>(fut);
},
py::call_guard<py::gil_scoped_release>())
.def("set_logger",
[](::c10d_npu::Reducer& reducer,
const std::shared_ptr<::c10d::Logger> logger) {
std::weak_ptr<::c10d::Logger> logger_weakref = logger;
reducer.set_logger(logger_weakref);
});
py::module_ dist = py::module_::import("torch._C._distributed_c10d");
auto processGroupHCCL = intrusive_ptr_no_gil_destructor_class_<::c10d_npu::ProcessGroupHCCL>(
module, "ProcessGroupHCCL", dist.attr("Backend"))
@@ -655,8 +655,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::collective(
syncStreams(devices, hcclEvents_[key], hcclStreams);
// Work itself will create the events on all NPUs of tensors
auto work = initWork(devices);
// Store references to outputs to be used by WorkHCCL::result and operator<<.
work->outputs_ = std::make_shared<std::vector<at::Tensor>>(outputs);
c10_npu::OptionalNPUGuard npuGuard;
pre(hcclStreams, work);
@@ -694,15 +692,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::collective(
}
post(hcclStreams, work);
{
c10_npu::NPUMultiStreamGuard guard(hcclStreams);
work->future_ = c10::make_intrusive<at::ivalue::Future>(
c10::ListType::create(c10::TensorType::get()),
devices);
work->future_->markCompleted(at::IValue(*work->outputs_));
}
for (size_t i = 0; i < inputs.size(); ++i) {
c10_npu::NPUStream& hcclStream = hcclStreams_[key][i];
work->npuEvents_[i].record(hcclStream);
@@ -0,0 +1,52 @@
#include <c10d/default_comm_hooks.hpp>
#include <c10/core/ScalarType.h>
#include <c10/util/Exception.h>
#include <c10d/ProcessGroup.hpp>
#include <c10d/comm.hpp>
#include <torch/torch.h>
namespace c10d {
c10::intrusive_ptr<c10::ivalue::Future> AllReduceCommHook::runHook(
GradBucket& bucket) {
std::vector<at::Tensor> tensors = {bucket.getBufferRef()};
// Apply the division first to avoid overflow, especially for FP16.
tensors[0] /= state_->getSize();
return state_->allreduce(tensors)->getFuture();
}
c10::intrusive_ptr<c10::ivalue::Future> FP16CompressCommHook::runHook(
GradBucket& bucket) {
auto compressed_tensor = bucket.getBufferRef().to(torch::kFloat16);
// Apply the division first to avoid overflow.
compressed_tensor /= state_->getSize();
std::vector<at::Tensor> tensors = {compressed_tensor};
auto allreduce_fut = state_->allreduce(tensors)->getFuture();
auto decompressed_tensor = bucket.getBufferRef();
auto decompress = [decompressed_tensor](c10::ivalue::Future& allreduce_fut) {
auto result = allreduce_fut.value();
TORCH_INTERNAL_ASSERT(
result.isTensorList(),
"ProcessGroup::allreduce should return TensorList");
auto reduce_tensor = result.toTensorVector()[0];
TORCH_INTERNAL_ASSERT_DEBUG_ONLY(
reduce_tensor.scalar_type() == at::ScalarType::Half,
"Expected reduced tensor to be fp16 in FP16CompressHook, but got type ",
reduce_tensor.scalar_type()
);
decompressed_tensor.copy_(reduce_tensor);
return c10::IValue(decompressed_tensor);
};
return allreduce_fut->then(decompress, allreduce_fut->elementType());
}
c10::intrusive_ptr<c10::ivalue::Future> _AllReduceBySumCommHook::runHook(GradBucket& bucket) {
std::vector<at::Tensor> tensors = {bucket.getBufferRef()};
return state_->allreduce(tensors)->getFuture();
}
} // namespace c10d
@@ -0,0 +1,48 @@
#pragma once
#include <c10d/ProcessGroup.hpp>
#include <c10d/comm.hpp>
namespace c10d {
enum class BuiltinCommHookType {
ALLREDUCE = 1,
FP16_COMPRESS = 2,
};
class AllReduceCommHook : public CppCommHookInterface<c10::intrusive_ptr<ProcessGroup>> {
public:
explicit AllReduceCommHook(c10::intrusive_ptr<ProcessGroup> state)
: CppCommHookInterface<c10::intrusive_ptr<ProcessGroup>>(state) {}
~AllReduceCommHook() override = default;
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
};
class FP16CompressCommHook : public CppCommHookInterface<c10::intrusive_ptr<ProcessGroup>> {
public:
explicit FP16CompressCommHook(c10::intrusive_ptr<ProcessGroup> state)
: CppCommHookInterface<c10::intrusive_ptr<ProcessGroup>>(state) {}
~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<c10::intrusive_ptr<ProcessGroup>> {
public:
explicit _AllReduceBySumCommHook(c10::intrusive_ptr<ProcessGroup> state)
: CppCommHookInterface<c10::intrusive_ptr<ProcessGroup>>(state) {}
~_AllReduceBySumCommHook() override = default;
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
};
} // namespace c10d
File diff suppressed because it is too large Load Diff
+617
View File
@@ -0,0 +1,617 @@
#pragma once
#include <atomic>
#include <memory>
#include <mutex>
#include <tuple>
#include <unordered_map>
#include <vector>
#include <ATen/core/ivalue_inl.h>
#include <c10/macros/Macros.h>
#include <c10/util/intrusive_ptr.h>
#include <c10d/ProcessGroup.hpp>
#include <c10d/Utils.hpp>
#include <c10d/Work.hpp>
#include <c10d/comm.hpp>
#include <c10d/default_comm_hooks.hpp>
#include <torch/csrc/autograd/function.h>
#include <torch/csrc/autograd/profiler.h>
#include <torch/csrc/autograd/variable.h>
#ifndef _WIN32
#include <torch/csrc/distributed/autograd/context/context.h>
#endif
#include <c10d/logger.hpp>
#include <c10d/debug.h>
namespace c10d_npu {
constexpr int kDefaultFirstBucketBytes = int(1024 * 1024);
constexpr int kDefaultBucketBytesCap = int(25 * 1024 * 1024);
// Collect runtime stats once for every kDDPRuntimeLoggingSampleRate iterations.
constexpr int kDDPRuntimeLoggingSampleRate = 100;
constexpr int kUnsetTime = -1;
inline int64_t current_time_in_nanos() {
return torch::profiler::impl::getTime();
}
// Forward declaration
class Logger;
class TORCH_API Timer {
private:
// The timestamp of forward call start time in each iteration.
int64_t forward_start_time = kUnsetTime;
// The timestamp of backward computation start and end time in each
// iteration.
int64_t backward_compute_start_time = kUnsetTime;
int64_t backward_compute_end_time = kUnsetTime;
// The timestamp of first communication call start time in each iteration.
int64_t backward_comm_start_time = kUnsetTime;
// The timestamp of last communication call end time in each iteration.
int64_t backward_comm_end_time = kUnsetTime;
public:
enum class Event {
kForwardStart,
kBackwardComputeStart,
kBackwardComputeEnd,
kBackwardCommStart,
kBackwardCommEnd,
};
// Record the current event, i.e., mark it as having occurred now. Default
// CPU implementation.
virtual void record(Event event) {
getTimeRef(event) = current_time_in_nanos();
}
// Return the difference between when two events occurred, in nanoseconds.
// Or nullopt if one of them hasn't been recorded.
virtual c10::optional<int64_t> measureDifference(Event start, Event end) = 0;
virtual ~Timer() = default;
// Return host-side timestamp, or nullopt if it has not yet been recorded.
c10::optional<int64_t> getTimestamp(Event event) {
auto time = getTimeRef(event);
if (time == kUnsetTime) {
return c10::nullopt;
} else {
return time;
}
}
// Return host-side time member variable corresponding to the given event.
int64_t& getTimeRef(Event event) {
switch (event) {
case Event::kForwardStart:
return forward_start_time;
case Event::kBackwardComputeStart:
return backward_compute_start_time;
case Event::kBackwardComputeEnd:
return backward_compute_end_time;
case Event::kBackwardCommStart:
return backward_comm_start_time;
case Event::kBackwardCommEnd:
return backward_comm_end_time;
default:
TORCH_INTERNAL_ASSERT(false);
}
}
};
// Local accumulator type for a single bucket.
struct BucketAccumulator {
std::vector<size_t> indices;
size_t size = 0;
size_t size_limit = 0;
};
C10_DECLARE_TYPED_REGISTRY(TimerRegistry, c10::DeviceType, Timer, std::unique_ptr, c10::Device);
class Reducer {
public:
// The constructor takes a list of variables for every model replica.
// The bucket assignment for this reducer is specified as a list of
// buckets, each of which is specified as a list of indices into the
// variables list for **a single replica** (i.e. `variables[0]`).
explicit Reducer(
std::vector<at::Tensor> params,
std::vector<std::vector<size_t>> bucket_indices,
std::vector<size_t> per_bucket_size_limits,
c10::intrusive_ptr<c10d::ProcessGroup> process_group,
std::vector<bool> expect_sparse_gradients,
int64_t bucket_bytes_cap,
bool find_unused_parameters,
bool gradient_as_bucket_view,
std::unordered_map<size_t, std::string> paramNames,
int64_t first_bucket_bytes_cap);
~Reducer() noexcept(false);
// To (re-)initialize bucket assignment, pass a list of buckets, each
// of which is specified by a list of indices in the variables list.
// This function performs validation that the variables within a bucket
// all live on the same device and have the same dimensionality.
void initialize_buckets(
std::vector<std::vector<size_t>> bucket_indices,
std::vector<size_t> per_bucket_sizes);
// This function is called when the forward function has produced an output,
// and the user wishes to reduce gradients in the backwards pass.
// If they don't, and wish to accumulate gradients before reducing them,
// a call to this function can simply be omitted.
void prepare_for_backward(const std::vector<at::Tensor>& outputs);
// Called at the begginning of forward() inside DistributedDataParallel,
// right now it caputures the starting time of forward in each iteration.
void prepare_for_forward();
// Returns the relative time in nanoseconds when gradients were ready,
// with respect to the time `prepare_for_backward` was called. The
// vector is for parameters for a single model replica.
std::vector<int64_t> get_backward_stats() const {
return backward_stats_;
}
// Registers a hook to the reducer. The hook is `CommHookInterface`
// type to allow both Python and CPP hooks. This function can only
// be called once before calling backward.
// Cannot combine with the call of `register_builtin_comm_hook`.
void register_comm_hook(std::unique_ptr<c10d::CommHookInterface> iface);
// Registers a built-in C++ comm hook to the reducer. This function can only
// be called once before calling backward.
// Cannot combine with the call of `register_comm_hook`.
void register_builtin_comm_hook(c10d::BuiltinCommHookType comm_hook_type);
// Runs allreduce or installed communication hook given GradBucket instance.
c10::intrusive_ptr<c10::ivalue::Future> run_comm_hook(
c10d::GradBucket& grad_bucket);
// Runs default allreduce hook.
c10::intrusive_ptr<c10::ivalue::Future> run_allreduce_hook(
c10d::GradBucket& grad_bucket);
// Returns gradient buckets in sequential order of buckets_. This is the order
// in which buckets are reduced across processes. If return_zero_tensors=true,
// will return zero tensors of the same shape instead of the true tensors.
std::vector<c10d::GradBucket> get_grad_buckets(
bool return_zero_tensors = true) const;
// Rebuild buckets based on rebuilt_params_ and rebuilt_param_indices_
// according to when tensors received grads in the backward pass.
bool rebuild_buckets();
// Install futures that should be awaited at end of backwards. Currently these
// are only used by user-defined custom buffer reduction hooks, but can be generalized
// to any user-originating futures that need to be awaited.
void install_futures(c10::List<c10::intrusive_ptr<c10::ivalue::Future>> futs);
// Returns true if we should rebuild buckets, else false. We only rebuild
// buckets once after the first iteration and never rebuild them if
// find_unused_parameters_.
inline bool should_rebuild_buckets() const {
return (static_graph_ || !find_unused_parameters_) && !has_rebuilt_bucket_;
}
// Pushes all parameters to be rebuilt.
void push_rebuilt_params_for_all_indices();
// Creates and sets ForwardPassWorkHandle given a ProcessGroup::Work and the
// corresponding tensor being reduced.
void set_forward_pass_work_handle(
c10::intrusive_ptr<c10d::Work> forwardPassWorkHandle,
bool useStaticWorldSize);
// Retrieve on-device tensors used to track locally unused parameters. It is
// a tensor where index i = 1 if the Variable with that index has been used.
at::Tensor get_local_used_map_on_device() const;
// An function for users to set sample_rate of collecting
// runtime stats. The time stats will be recorded for the
// first 10 iterations, after 10 iteratons time stats will be
// recorded once every "sample_rate" training iterations.
void set_ddp_runtime_logging_sample_rate(int sample_rate);
// Specify the training graph is static.
void set_static_graph();
// Delay all reduce to be after all gradients' calculation is complete.
void delay_all_reduce();
// Weak reference to associated DDP logger. The reference is weak to avoid
// refcycle between reducer and logger.
void set_logger(std::weak_ptr<c10d::Logger> logger);
// When graph is not explicitly set by user as static and has unused
// parameters, this will return whether the graph has been static until the
// current iteration, which means unused params set has not changed.
bool ddp_graph_static();
protected:
// Forward declaration.
struct Bucket;
void push_rebuilt_params(const size_t& index);
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
mutable std::mutex mutex_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
const std::vector<at::Tensor> params_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
const c10::intrusive_ptr<::c10d::ProcessGroup> process_group_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
std::vector<bool> expect_sparse_gradients_;
std::vector<std::shared_ptr<torch::autograd::Node>>
grad_accumulators_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
std::unordered_map<torch::autograd::Node*, size_t> gradAccToVariableMap_;
std::vector<std::pair<uintptr_t, std::shared_ptr<torch::autograd::Node>>>
hooks_; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes)
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
bool expect_autograd_hooks_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
bool require_finalize_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
size_t next_bucket_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
bool has_marked_unused_parameters_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
const bool find_unused_parameters_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
const bool gradient_as_bucket_view_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
std::vector<size_t> unused_parameters_;
// Previous iteration's unused params, used for checking if unused parameters
// change between iterations. Only filled during the first backwards call.
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
std::vector<size_t> prev_iteration_unused_parameters_;
// Whether graph is static or not. When user does not explicitly set static
// graph, the only possible dynamism is set of unused parameters changing
// between iterations which is tracked by this flag.
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
bool ddp_graph_static_{true};
// Locally used parameter maps indicating if parameters are used locally
// during the current iteration or no_sync session if no_sync is on.
// Each map is a one-dim int32 tensor of number of parameters. These tensors
// are marked in autograd_hook to indicate the corresponding param has been
// used, and get allreduced in the end of backward step of current iteration
// or no_sync session for figuring out the globally unused parameters.
//
// local_used_map_: CPU tensor for bookkeeping locally used params
// local_used_map_dev_: dev tensor for reducing globally unused params
at::Tensor local_used_map_;
at::Tensor local_used_map_dev_;
// Indicate that reduction is done and D2H copy is done as well.
bool local_used_map_reduced_;
// Weak pointer to associated DDP logger.
std::weak_ptr<c10d::Logger> logger_;
// List of futures installed by Reducer::install_futures that should be awaited
// at the end of backwards pass.
c10::optional<c10::List<c10::intrusive_ptr<c10::ivalue::Future>>> installed_futures_{c10::nullopt};
// Work handle for allreduce on local_used_map_
c10::intrusive_ptr<c10d::Work> local_used_work_;
void mark_variable_ready_dense(size_t variable_index);
void mark_variable_ready_sparse(size_t variable_index);
void mark_variable_ready(size_t variable_index);
void autograd_hook(size_t index);
void mark_bucket_ready(size_t bucket_index);
void finalize_bucket_dense(Bucket& replica);
void finalize_backward();
// Returns list of model parameters corresponding to the given bucket.
// bucket_index is a key to cache after buckets are rebuilt, after which this
// mapping never changes.
std::vector<at::Tensor> get_variables_for_bucket(
size_t bucket_index, const Bucket& bucket) const;
// Asserts that the reduction for the previous iteration has finished before
// rebuilding buckets or kicking off the next one.
void ensure_prior_reduction_finished();
// Broadcast rebuilt buckets from rank 0 to other ranks before initializing
// the buckets
void sync_bucket_indices(std::vector<std::vector<size_t>>& bucket_indices);
// We'd like to use DistAutogradContext::GradCallback here but dist autograd
// doesn't exist under Windows. So we just directly use the concrete type but
// to preserve and enforce our original intent we do a static assert when dist
// autograd is available.
using GradCallback = std::function<bool(at::Tensor&)>;
#ifndef _WIN32
static_assert(
std::is_same<
GradCallback,
torch::distributed::autograd::DistAutogradContext::GradCallback>::
value,
"");
#endif
void runGradCallbackForVariable(at::Tensor& variable, GradCallback&& cb);
// A bucket replica represents [1..N] gradients to be reduced,
// with the same dtype, on the same device.
//
// Batching gradients together before reducing them can result in lower
// overhead and/or faster time to completion. Only gradients of the same type
// and on the same device can be batched. The tensor that represents the
// flattened gradient uses the same type and is placed on the same device.
// Buckets are filled as the gradients they hold are computed (triggered by
// autograd hooks). Buckets are reduced in a predetermined order that is
// identical across processes.
struct BucketReplica {
// Flattened (1 dimensional) contents of bucket.
at::Tensor contents;
// Views into contents for each grad. Each view will be created with
// layout (sizes + strides) matching the grad's expected layout
// ("Gradient Layout Contract" in torch/csrc/autograd/AccumulateGrad.h).
// `bucket_views_in[i].copy_(grad)` and
// `grad.copy_(bucket_views_out[i])`
// provide convenient ways to move grad data in/out of contents.
// The reason we keep two states for bucket_views is that if DDP
// communication hook was registered, `bucket_views_out` could be
// re-initialized with the value of hook's `future_work`. We still need to
// keep a separate view reference to replica's original contents for
// `bucket_views_in[i].copy_(grad)` call.
std::vector<at::Tensor> bucket_views_in;
std::vector<at::Tensor> bucket_views_out;
// Variables that contribute to this bucket replica. Use refcounted value
// here so that we can easily unflatten the bucket contents into the
// participating variables after reduction has completed.
std::vector<at::Tensor> variables;
// Per-variable offset/length into the flat bucket contents tensor and grad
// bucket.
std::vector<size_t> offsets;
std::vector<size_t> lengths;
// Per-variable sizes into the grad bucekt.
std::vector<c10::IntArrayRef> sizes_vec;
// Number of tensors to be added before this bucket is complete.
// This is reset to `variables.size()` every iteration.
size_t pending;
};
// This function is called inside `initialize_buckets`, it initializes both
// bucket_views_in and bucket_views_out into the contents tensor for each
// variable's grad. Views serve as entry points to copy_ each grad's data
// in/out of the flat contents tensor.
void initialize_bucket_views(BucketReplica& replica, at::Tensor& contents);
// This function is called inside `finalize_backward`, it happens only if
// DDP communication hook was registered to recreate just bucket_views_out
// with the result of `future_work`.
void populate_bucket_views_out(BucketReplica& replica, at::Tensor& tensor);
// If gradient_as_bucket_view_ is false, after allreduce buckets,
// copy bucket results back to grads.
void copy_bucket_to_grad(
at::Tensor& variable,
Reducer::BucketReplica& replica,
size_t intra_bucket_index,
bool global_unused);
// Check layout of grad and bucket_view before copying the grad to bucket.
void check_grad_layout(const at::Tensor& grad, const at::Tensor& bucket_view);
// If gradient_as_bucket_view_ is false, before allreduce buckets,
// copy grads to buckets.
void copy_grad_to_bucket(const at::Tensor& grad, at::Tensor& bucket_view);
// A bucket holds N bucket replicas (1 per model replica).
//
// If every bucket in this struct is ready, the reduction can be kicked off.
// One bucket per replica. Reduction is kicked off when every bucket is ready.
//
struct Bucket {
std::vector<BucketReplica> replicas;
// Global indices of participating variables in the bucket
std::vector<size_t> variable_indices;
// Number of replicas to be marked done before this bucket is ready.
size_t pending;
// Keep work handle around when this set of buckets is being reduced.
c10::intrusive_ptr<c10d::Work> work;
// Keep future work handle around DDP comm hook.
// If no hook is registered, a temporary vanilla allreduce hook will be
// used.
c10::intrusive_ptr<at::ivalue::Future> future_work;
// If this bucket should expect a single sparse gradient.
// Implies: replicas[i].variables.size() == 1.
bool expect_sparse_gradient = false;
// "Limit" of cumulative parameter sizes that this bucket manages. It is
// actually a soft limit because we don't shard parameters across buckets
// so a single parameter may push it over the cap.
size_t bucket_size_limit;
};
std::vector<Bucket> buckets_;
// A variable locator locates a particular variable in the bucket
// structure. The `bucket_index` field points to the bucket in the `buckets_`
// vector. The `intra_bucket_index` field points to the index of the variable
// in any of the vector fields in the bucket replica.
struct VariableLocator {
// Index into the `buckets_` variable.
size_t bucket_index;
// Index of parameter in single bucket replica.
size_t intra_bucket_index;
VariableLocator() = default;
VariableLocator(size_t bucket_index_, size_t intra_bucket_index_) {
bucket_index = bucket_index_;
intra_bucket_index = intra_bucket_index_;
}
};
// Map the index of a variable to its location in the bucket structure.
std::vector<VariableLocator> variable_locators_;
// track the number of iterations to synchronize grads in training so far.
long num_iterations_;
// track the number of buckets that have been ready for
// communication calls like allReduce or communication hooks.
int num_buckets_ready_;
// Timing information.
int64_t backward_compute_start_time_ = -1;
std::unique_ptr<Timer> timer_;
// We collect the relative timestamp of every gradient being ready
// when executing autograd. This can be used to derive a timeline of
// the point in time buckets were ready, or ideal bucket assignment/ordering.
std::vector<int64_t> backward_stats_;
bool should_collect_runtime_stats();
void record_forward_compute_start_time();
void record_backward_compute_start_time();
void record_backward_compute_end_time();
void record_backward_comm_start_time();
void record_backward_comm_end_time();
int get_ddp_runtime_logging_sample_rate();
int ddp_runtime_logging_sample_rate_ = kDDPRuntimeLoggingSampleRate;
bool is_multi_device_module_ = false;
// Following variables are to help build dynamic bucket order
bool has_rebuilt_bucket_;
std::vector<at::Tensor> rebuilt_params_;
std::vector<int64_t> rebuilt_param_indices_;
const int64_t bucket_bytes_cap_;
#ifndef _WIN32
struct RpcContext {
using ContextPtr = torch::distributed::autograd::ContextPtr;
// The shared_ptr is to hold the context instance.
ContextPtr context_ptr_holder;
std::atomic<ContextPtr::element_type*> context_ptr{nullptr};
void set(ContextPtr&& new_context_ptr);
};
RpcContext rpc_context_;
#endif
// A struct containing work handle and tensor for allreduce scheduled in
// forward pass, if applicable.
struct ForwardPassAllreduceWork {
c10::intrusive_ptr<c10d::Work> workHandle;
at::Tensor resultTensor;
// whether we should divide by the initial world_size or the no. of
// remaining DDP ranks.
bool useStaticWorldSize;
};
// Handle for the currently scheduled allreduce in the forward pass, if
// applicable.
ForwardPassAllreduceWork forwardPassWorkHandle_;
// Division factor for reduction of gradients.
// Equal to the process group size, with an exception of handling uneven
// input.
int div_factor_;
bool static_graph_;
// Key: size_t (index), Value: the number of times that a variable's
// autograd_hook() should be triggered before marking this variable's grad as
// ready for communication. Map will not change after 1st iteration.
std::unordered_map<size_t, int> numGradHooksTriggeredMap_;
// Key: size_t (index), Value: the number of times that a variable's
// autograd_hook() are left to be triggered before marking this variable's
// grad as ready for communication. Map will change after 1st iteration to
// track a grad is ready for communication or not.
std::unordered_map<size_t, int> numGradHooksTriggeredMapPerIteration_;
private:
// reset counting for buckets before backward starts
void reset_bucket_counting();
// search unused parameters beore backward starts
void search_unused_parameters(
const std::vector<torch::autograd::Variable>& outputs);
void set_divide_factor();
// kick off all reduce for the ready bucket
void all_reduce_bucket(Bucket& bucket);
// kick off all reduce to local used map, it can help find global unused
// parameters
void all_reduce_local_used_map();
// initialize locally used parameter maps
void initialize_local_used_map();
// get current cuda stream
const c10::Stream get_current_stream();
bool dynamic_graph_find_unused();
bool static_graph_first_iteration();
bool static_graph_after_first_iteration();
// comm_hook_ is used to access the DDP communication hook if registered.
std::unique_ptr<c10d::CommHookInterface> comm_hook_;
// Debug level setting. It is parsed once when Reducer is constructed, and
// remains the same across a single invocation of DDP training.
c10d::DebugLevel ddp_debug_level_;
// Mapping of variable index to fully qualified name of model to notify users
// about errors when certain parameters do not get gradient.
std::unordered_map<size_t, std::string> param_names_;
// Variable indices stored sequentially in order of when the gradient is ready
// for the current backwards pass.
std::vector<int> grad_ready_order_indices_;
// Bytes capacity of first bucket, can be configured by user
int64_t first_bucket_bytes_cap_;
// Per iteration set of parameter indices that have been marked ready.
std::unordered_set<size_t> perIterationReadyParams_;
// Retrieves parameter names that have not been marked as ready as part of
// previous iteration.
std::vector<std::string> getUnmarkedParamsForIteration();
// Retrives parameter indices that have not been marked as ready as part of
// previous iteration.
std::vector<size_t> getUnmarkedParamIndicesForIteration();
// Raises appropriate error if mark_variable_ready is called on the same
// variable twice, which is unexpected.
void checkAndRaiseMarkedTwiceError(size_t curVariableIndex);
// Retrieves parameter corresponding to the given VariableIndex.
at::Tensor& get_param_from_index(size_t index);
// Cached bucket index to model parameter mapping. Populated after buckets
// are rebuilt after which this mapping is static.
mutable std::unordered_map<size_t, std::vector<at::Tensor>> cached_variables_for_bucket_;
friend class Logger;
};
// This is equivalent to take_tensors but returns indices into the
// tensor list argument for bucket assignment. Also, it is aware
// of device placement and will not allow buckets to span devices.
// The index of tensors[i] assigned to bucket is tensor_indices[i],
// when tensor_indices is empty, the index of tensors[i] assigned to
// bucket is i.
std::tuple<std::vector<std::vector<size_t>>, std::vector<size_t>> compute_bucket_assignment_by_size(
const std::vector<at::Tensor>& tensors,
const std::vector<size_t>& bucket_size,
const std::vector<bool>& expect_sparse_gradient = {},
const std::vector<int64_t>& tensor_indices = {},
const c10::optional<std::weak_ptr<c10d::Logger>>& logger = {});
// Verify models across all processes are the same as model on rank 0 with
// respect to no. of params and matching dtype/size/layout.
void verify_params_across_processes(
const c10::intrusive_ptr<c10d::ProcessGroup>& process_group,
const std::vector<at::Tensor>& params,
const c10::optional<std::weak_ptr<c10d::Logger>>& logger);
} // namespace c10d_npu
@@ -3,3 +3,4 @@
#include "torch_npu/csrc/framework/StorageDescHelper.h"
#include "torch_npu/csrc/framework/FormatHelper.h"
#include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h"
#include "torch_npu/csrc/framework/utils/NpuStorageOffsetGuard.h"
+6 -7
View File
@@ -723,22 +723,21 @@ PyObject* THNPModule_npu_get_sync_debug_mode(PyObject* self, PyObject* noargs) {
END_HANDLE_TH_ERRORS
}
PyObject* THNPModule_set_storage_with_format(PyObject* self, PyObject* args) {
PyObject* THNPModule_tensor_construct_from_storage(PyObject* self, PyObject* args) {
HANDLE_TH_ERRORS
static torch::PythonArgParser parser(
{"set_storage_with_format_(Tensor dst, Storage source)",},
{"set_storage_with_format_(Storage source)",},
/*traceable=*/false
);
torch::ParsedArgs<2> parsed_args;
torch::ParsedArgs<1> parsed_args;
auto _r = parser.parse(args, nullptr, parsed_args);
at::Tensor dst = _r.tensor(0);
at::ScalarType storage_scalar_type;
bool is_typed_storage = true;
c10::Storage storage = _r.storage(1, storage_scalar_type, is_typed_storage);
return THPVariable_Wrap(at_npu::native::set_tensor_with_storage_format(dst, storage));
c10::Storage storage = _r.storage(0, storage_scalar_type, is_typed_storage);
return THPVariable_Wrap(at_npu::native::set_tensor_with_storage_format(storage));
END_HANDLE_TH_ERRORS
}
@@ -781,7 +780,7 @@ static struct PyMethodDef THNPModule_methods[] = {
{"_npu_getOption", (PyCFunction)THNPModule_getOption_wrap, METH_O, nullptr},
{"_npu_set_sync_debug_mode", (PyCFunction)THNPModule_npu_set_sync_debug_mode, METH_O, nullptr},
{"_npu_get_sync_debug_mode", (PyCFunction)THNPModule_npu_get_sync_debug_mode, METH_NOARGS, nullptr},
{"_set_storage_with_format", (PyCFunction)THNPModule_set_storage_with_format, METH_VARARGS, nullptr},
{"_tensor_construct_from_storage", (PyCFunction)THNPModule_tensor_construct_from_storage, METH_VARARGS, nullptr},
{nullptr}};
PyMethodDef* THNPModule_get_methods() {
+26
View File
@@ -0,0 +1,26 @@
import torch_npu
__all__ = ["Reducer", "_register_comm_hook", "_register_builtin_comm_hook",
"_compute_bucket_assignment_by_size", "_verify_params_across_processes", "_broadcast_coalesced"]
def is_available():
"""
Returns ``True`` if the distributed package is available. Otherwise,
``torch.distributed`` does not expose any other APIs.
"""
return hasattr(torch_npu._C, "_c10d_npu_init")
if is_available() and not torch_npu._C._c10d_npu_init():
raise RuntimeError("Failed to initialize torch_npu.distributed")
from torch_npu._C._distributed_c10d import (
Reducer,
_register_comm_hook,
_register_builtin_comm_hook,
_compute_bucket_assignment_by_size,
_verify_params_across_processes,
_broadcast_coalesced
)
+16
View File
@@ -0,0 +1,16 @@
import torch
from torch.library import Library, impl
#meta register implementation
m = Library("npu", "IMPL", "Meta")
@impl(m, "npu_incre_flash_attention")
def npu_incre_flash_attention_forward(query, key, value, *, padding_mask=None, atten_mask=None, actual_seq_lengths=None, num_heads=1, scale_value=1.0, input_layout="BSH", num_key_value_heads=0):
return torch.empty_like(query, dtype=query.dtype)
@impl(m, "npu_prompt_flash_attention")
# pre_tokens, default value, INT_MAX 2147473647
def npu_prompt_flash_attention_forward(query, key, value, *, padding_mask=None, atten_mask=None, actual_seq_lengths=None, num_heads=1, scale_value=1.0, pre_tokens=2147473647, next_tokens=0, input_layout="BSH", num_key_value_heads=0):
return torch.empty_like(query, dtype=query.dtype)
+6 -6
View File
@@ -122,8 +122,8 @@ class GradScaler(Cuda_GradScaler):
def _lazy_init_scale_growth_tracker(self, dev):
assert self._growth_tracker is None, "_growth_tracker initialized before _scale"
self._scale = torch.full((1,), self._init_scale, dtype=torch.float32).pin_memory().to(dev, non_blocking=True)
self._growth_tracker = torch.full((1,), self._init_growth_tracker, dtype=torch.int32)
self._scale = torch.full((), self._init_scale, dtype=torch.float32).pin_memory().to(dev, non_blocking=True)
self._growth_tracker = torch.full((), self._init_growth_tracker, dtype=torch.int32)
self._growth_tracker = self._growth_tracker.pin_memory().to(dev, non_blocking=True)
def _lazy_init_dist_flag_and_dist_overflow_count(self):
@@ -214,7 +214,7 @@ class GradScaler(Cuda_GradScaler):
[grads_combined_one_dtype],
per_device_found_inf.get(device),
per_device_inv_scale.get(device))
if per_device_found_inf.get(device)[0].item() > 0:
if per_device_found_inf.get(device).item() > 0:
self._has_overflow = True
else:
grads_combined_one_dtype.mul_(
@@ -245,7 +245,7 @@ class GradScaler(Cuda_GradScaler):
torch._amp_foreach_non_finite_check_and_unscale_(grads,
per_device_found_inf.get(device),
per_device_inv_scale.get(device))
if per_device_found_inf.get(device)[0].item() > 0:
if per_device_found_inf.get(device).item() > 0:
self._has_overflow = True
else:
for grad in grads:
@@ -306,7 +306,7 @@ class GradScaler(Cuda_GradScaler):
# FP32 division can be imprecise for certain compile options, so we carry out the reciprocal in FP64.
assert self._scale is not None
inv_scale = self._scale.float().reciprocal()
found_inf = torch.full((1,), 0.0, dtype=torch.float32).pin_memory().to(self._scale.device, non_blocking=True)
found_inf = torch.full((), 0.0, dtype=torch.float32).pin_memory().to(self._scale.device, non_blocking=True)
optimizer_state["found_inf_per_device"] = self._unscale_grads_(optimizer, inv_scale, found_inf, False)
optimizer_state["stage"] = OptState.UNSCALED
@@ -404,7 +404,7 @@ class GradScaler(Cuda_GradScaler):
if new_scale is not None:
# Accept a new user-defined scale.
if isinstance(new_scale, float):
self._scale = torch.full((1,), new_scale, dtype=torch.float32)
self._scale = torch.full((), new_scale, dtype=torch.float32)
self._scale = self._scale.pin_memory().to(_scale.device, non_blocking=True)
else:
reason = "new_scale should be a float or a 1-element torch.npu.FloatTensor with requires_grad=False."
+8 -8
View File
@@ -266,27 +266,27 @@ class ShardedGradScaler(GradScaler):
# Synchronize the detected inf across the ranks
optimizer_state = self._per_optimizer_states[id(optimizer)]
future_handles = []
work_handles = []
for v in optimizer_state["found_inf_per_device"].values():
if v.device.type == "cpu":
v_on_npu = v.npu()
future_handles.append(
work_handles.append(
dist.all_reduce(
v_on_npu, async_op=True, group=self.process_group
).get_future()
)
)
)
v.copy_(v_on_npu.cpu())
else:
future_handles.append(
work_handles.append(
dist.all_reduce(
v, async_op=True, group=self.process_group
).get_future()
)
)
# Make sure that the calls are done before moving out.
if future_handles:
torch.futures.wait_all(future_handles)
for work in work_handles:
work.wait()
def step(self, optimizer: SGD, *args, **kwargs) -> Optional[float]:
return super().step(optimizer, *args, **kwargs)
+2 -1
View File
@@ -344,7 +344,8 @@ def npu_check_overflow(grad):
def clear_npu_overflow_flag():
if is_support_inf_nan():
raise RuntimeError("Unsupported api when soc_version >= Ascend910B1, please use npu_check_overflow")
warnings.warn("When soc_version >= Ascend910B1, clear_npu_overflow_flag is useless, please remove it.")
return
float_status = torch.zeros(8).npu()
torch_npu.npu_clear_float_status(float_status)
+49
View File
@@ -587,6 +587,41 @@ class NPURotaryMulOP(torch.autograd.Function):
return g.op("npu::NPURotaryMul", x, r1, r2)
class NPUPromptFlashAttentionOP(torch.autograd.Function):
@staticmethod
def forward(ctx, *args, **kwargs):
return torch.ops.npu.prompt_flash_attention(*args, **kwargs)
@staticmethod
def symbolic(g, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
padding_mask: Optional[Tensor], atten_mask: Optional[Tensor],
actual_seq_lengths: Optional[Tensor], num_heads: int = 1,
scale_value: float = 1.0, pre_tokens: int = 2147473647, # pre_tokens, default value, INT_MAX 2147473647
next_tokens: int = 0, input_layout: str = "BSH", num_key_value_heads: int = 0):
return g.op("npu::NPUPromptFlashAttention", self, query, key, value,
padding_mask, atten_mask, actual_seq_lengths,
num_heads, scale_value, pre_tokens, next_tokens,
input_layout, num_key_value_heads)
class NPUIncreFlashAttentionOP(torch.autograd.Function):
@staticmethod
def forward(ctx, *args, **kwargs):
return torch.ops.npu.incre_flash_attention(*args, **kwargs)
@staticmethod
def symbolic(g, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor,
padding_mask: Optional[Tensor], atten_mask: Optional[Tensor],
actual_seq_lengths: Optional[Tensor],
num_heads: int = 1, scale_value: float = 1.0,
input_layout: str = "BSH", num_key_value_heads: int = 0):
return g.op("npu::NPUIncreFlashAttention", self, query, key, value,
padding_mask, atten_mask, actual_seq_lengths,
num_heads, scale_value, input_layout, num_key_value_heads)
def wrapper_npu_one_hot(self, num_classes=-1, depth=1, on_value=1, off_value=0):
return NPUOneHotOP.apply(self, num_classes, depth, on_value, off_value)
@@ -805,6 +840,18 @@ def wrapper_npu_rotary_mul(x, r1, r2):
return NPURotaryMulOP.apply(x, r1, r2)
def wrapper_npu_prompt_flash_attention(self, query, key, value, padding_mask, atten_mask, actual_seq_lengths,
num_heads, scale_value, pre_tokens, next_tokens, input_layout, num_key_value_heads):
return NPUPromptFlashAttentionOP.apply(self, query, key, value, padding_mask, atten_mask, actual_seq_lengths,
num_heads, scale_value, pre_tokens, next_tokens, input_layout, num_key_value_heads)
def wrapper_npu_incre_flash_attention(self, query, key, value, padding_mask, atten_mask, actual_seq_lengths,
num_heads, scale_value, input_layout, num_key_value_heads):
return NPUIncreFlashAttentionOP.apply(self, query, key, value, padding_mask, atten_mask, actual_seq_lengths,
num_heads, scale_value, input_layout, num_key_value_heads)
def add_onnx_ops():
torch_npu.npu_one_hot = wrapper_npu_one_hot
torch_npu.npu_slice = wrapper_npu_slice
@@ -850,3 +897,5 @@ def add_onnx_ops():
torch_npu.npu_scaled_masked_softmax = wrapper_npu_scaled_masked_softmax
torch_npu.npu_mish = wrapper_npu_mish
torch_npu.npu_rotary_mul = wrapper_npu_rotary_mul
torch_npu.npu_prompt_flash_attention = wrapper_npu_prompt_flash_attention
torch_npu.npu_incre_flash_attention = wrapper_npu_incre_flash_attention
@@ -69,27 +69,15 @@ class FileManager:
cls.create_json_file_by_path(file_path, data)
@classmethod
def create_json_file_by_path(cls, output_path: str, data: list) -> None:
def create_json_file_by_path(cls, output_path: str, data: list, indent: int = None) -> None:
dir_name = os.path.dirname(output_path)
if not os.path.exists(dir_name):
try:
os.makedirs(dir_name, mode=Constant.DIR_AUTHORITY)
except Exception:
raise RuntimeError(f"Can't create directory: {dir_name}")
cls.make_dir_safety(dir_name)
try:
with os.fdopen(os.open(output_path, os.O_WRONLY | os.O_CREAT, Constant.FILE_AUTHORITY), "w") as file:
json.dump(data, file)
json.dump(data, file, indent=indent)
except Exception:
raise RuntimeError(f"Can't create file: {output_path}")
@classmethod
def remove_and_make_output_dir(cls, output_path: str) -> None:
cls.remove_file_safety(output_path)
try:
os.makedirs(output_path, mode=Constant.DIR_AUTHORITY)
except Exception:
raise RuntimeError(f"Can't create directory: {output_path}")
@classmethod
def check_input_path(cls, path):
"""
@@ -133,4 +121,17 @@ class FileManager:
try:
shutil.rmtree(path)
except Exception:
print(f"[WARNING] [{os.getpid()}] profiler.py: Can't remove the directory: {path}")
print(f"[WARNING] [{os.getpid()}] profiler.py: Can't remove the directory: {path}")
@classmethod
def make_dir_safety(cls, path: str):
if os.path.islink(path):
msg = f"Invalid path is soft link: {path}"
raise RuntimeError(msg)
if os.path.exists(path):
return
try:
os.makedirs(path, mode=Constant.DIR_AUTHORITY)
os.chmod(path, Constant.DIR_AUTHORITY)
except Exception:
raise RuntimeError("Can't create directory: " + path)
@@ -43,6 +43,9 @@ class PathManager:
@classmethod
def get_start_info_path(cls, cann_path: str) -> str:
start_info_path = os.path.join(cann_path, "host", "start_info")
if os.path.exists(start_info_path):
return start_info_path
device_path = cls.get_device_path(cann_path)
if not device_path:
return ""
@@ -41,6 +41,7 @@ class CANNFileParser:
r"^npu_mem_\d+_\d+_\d+_\d+\.csv"],
CANNDataEnum.MSPROF_TIMELINE: [r"^msprof_\d+_\d+\.json", r"^msprof_\d+_\d+_\d+\.json",
r"^msprof_\d+_\d+_\d+_\d+\.json", r"^msprof_\d+_\d+_slice_\d+\.json",
r"^msprof_\d+_\d+_slice_\d+_\d+\.json",
r"^msprof_\d+_\d+_\d+_slice_\d+\.json",
r"^msprof_\d+_\d+_\d+_slice_\d+_\d+\.json"],
CANNDataEnum.STEP_TRACE: [r"^step_trace_\d+_\d+\.csv", r"^step_trace_\d+_\d+_\d+\.csv",
@@ -26,7 +26,8 @@ class ViewParserFactory:
GlobalVar.init(profiler_path)
if analysis_type == Constant.TENSORBOARD_TRACE_HANDLER:
output_path = os.path.join(profiler_path, Constant.OUTPUT_DIR)
FileManager.remove_and_make_output_dir(output_path)
FileManager.remove_file_safety(output_path)
FileManager.make_dir_safety(output_path)
for parser in ViewParserConfig.CONFIG_DICT.get(analysis_type):
parser(profiler_path).generate_view(output_path, **kwargs)
cls.simplify_data(profiler_path)
+3 -2
View File
@@ -5,6 +5,8 @@ import torch
import torch_npu._C
from .analysis.prof_common_func.file_manager import FileManager
class ProfilerActivity:
CPU = torch_npu._C._profiler.ProfilerActivity.CPU
@@ -47,5 +49,4 @@ class MsProfilerInterface:
total_info["rank_id"] = rank_id
else:
path = os.path.join(os.path.abspath(self.path), 'profiler_info.json')
with open(path, "w") as f:
json.dump(total_info, f, indent=4)
FileManager.create_json_file_by_path(path, total_info, indent=4)
@@ -25,14 +25,6 @@ class NpuProfCreator:
except Exception:
print(f"[WARNING] [{os.getpid()}] profiler.py: Profiling data parsing failed.")
@classmethod
def make_dir(cls, target_path: str) -> any:
if not os.path.isdir(target_path):
try:
os.makedirs(target_path, mode=Constant.DIR_AUTHORITY, exist_ok=True)
except Exception:
raise RuntimeError("Can't create directory: " + target_path)
def create_prof_dir(self) -> str:
FileManager.check_input_path(self._dir_name)
if not self._worker_name:
@@ -41,7 +33,7 @@ class NpuProfCreator:
time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())))
total_path = os.path.join(self._dir_name, worker_span_name)
self.make_dir(total_path)
FileManager.make_dir_safety(total_path)
FileManager.check_directory_path_writable(total_path)
return total_path
@@ -51,7 +43,7 @@ class NpuProfCreator:
target_path = "{}_{}_ascend_pt".format(self.DEFAULT_PROF_SUFFIX,
time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())))
target_path = os.path.join(dir_name, target_path)
self.make_dir(target_path)
FileManager.make_dir_safety(target_path)
FileManager.check_directory_path_writable(target_path)
return target_path
+97
View File
@@ -2,11 +2,14 @@ from typing import Optional
from statistics import mode
import warnings
import logging
import sys
import torch
import torch.nn.functional as F
import torch.distributed as pytorch_dist
from torch import Tensor
from torch.distributed.algorithms.join import Join
from torch.distributed import Reducer
from torch.nn.parameter import Parameter, UninitializedParameter, UninitializedBuffer
from torch.nn.modules.batchnorm import _NormBase, _LazyNormBase
from torch.nn.modules.module import Module
@@ -14,6 +17,7 @@ from torch.nn.parallel._functions import _streams
import torch_npu
from torch_npu.utils.syncbatchnorm import SyncBatchNorm as sync_batch_norm
import torch_npu.distributed as dist
def npu(self, device=None):
@@ -245,6 +249,99 @@ def syncbn_forward(self, input1: torch.Tensor) -> torch.Tensor:
self.eps, exponential_average_factor, process_group, world_size)
def _ddp_init_helper(
self,
parameters,
expect_sparse_gradient,
param_to_name_mapping,
static_graph,):
"""
Initialization helper function that does the following:
(1) bucketing the parameters for reductions
(2) resetting the bucketing states
(3) registering the grad hooks
(4) Logging construction-time DDP logging data
(5) passing a handle of DDP to SyncBatchNorm Layer
"""
if static_graph is True or self.find_unused_parameters is False:
bucket_size_limits = [sys.maxsize]
else:
bucket_size_limits = [
pytorch_dist._DEFAULT_FIRST_BUCKET_BYTES,
self.bucket_bytes_cap,
]
(bucket_indices, per_bucket_size_limits) = dist._compute_bucket_assignment_by_size(
parameters,
bucket_size_limits,
expect_sparse_gradient)
# Note: reverse list of buckets because we want to approximate the
# order in which their gradients are produced, and assume they
# are used in the forward pass in the order they are defined.
self.reducer = dist.Reducer(
parameters,
list(reversed(bucket_indices)),
list(reversed(per_bucket_size_limits)),
self.process_group,
expect_sparse_gradient,
# The bucket size limit is specified in the constructor.
# Additionally, we allow for a single small bucket for parameters
# that are defined first, such that their gradients don't spill into
# a much larger bucket, adding unnecessary latency after gradient
# computation finishes. Experiments showed 1MB is a reasonable value.
self.bucket_bytes_cap,
self.find_unused_parameters,
self.gradient_as_bucket_view,
param_to_name_mapping,
# User can set dist._DEFAULT_FIRST_BUCKET_BYTES to tune DDP first
# bucket.
pytorch_dist._DEFAULT_FIRST_BUCKET_BYTES)
ori_reducer = Reducer(
parameters,
list(reversed(bucket_indices)),
list(reversed(per_bucket_size_limits)),
self.process_group,
expect_sparse_gradient,
# The bucket size limit is specified in the constructor.
# Additionally, we allow for a single small bucket for parameters
# that are defined first, such that their gradients don't spill into
# a much larger bucket, adding unnecessary latency after gradient
# computation finishes. Experiments showed 1MB is a reasonable value.
self.bucket_bytes_cap,
self.find_unused_parameters,
self.gradient_as_bucket_view,
param_to_name_mapping,
# User can set dist._DEFAULT_FIRST_BUCKET_BYTES to tune DDP first
# bucket.
pytorch_dist._DEFAULT_FIRST_BUCKET_BYTES,
)
self.logger = pytorch_dist.Logger(ori_reducer)
# Set as a weak reference to avoid reference cycle between
# logger and reducer.
self.reducer.set_logger(self.logger)
has_sync_bn = False
for submodule in self.module.modules():
if isinstance(submodule, torch.nn.SyncBatchNorm):
has_sync_bn = True
break
# Set logging data that can be got during construction time.
self.logger.set_construction_data_and_log(
self.module.__class__.__name__,
[] if self.device_ids is None else self.device_ids,
-1 if self.output_device is None else self.output_device,
self.broadcast_buffers,
has_sync_bn,
static_graph,
)
# passing a handle to torch.nn.SyncBatchNorm layer
self._passing_sync_batchnorm_handle(self.module)
def apply_module_patch():
torch.nn.Module.npu = npu
torch.nn.Module.to = to
+15 -7
View File
@@ -9,6 +9,7 @@ from torch.serialization import _check_dill_version, _open_file_like, _is_zipfil
_legacy_load, _load, FILE_LIKE, MAP_LOCATION, DEFAULT_PROTOCOL
ALWAYS_WARN_LEGACY_SERIALIZATION = False
RE_MAP_CPU = False
def _get_always_warn_legacy_serialization():
@@ -20,16 +21,16 @@ def _set_always_warn_legacy_serialization(always_warn:bool):
ALWAYS_WARN_LEGACY_SERIALIZATION = always_warn
def _warn_legacy_serialization(warn_massages, load_flag):
def is_first_time(load_flag):
warn_key = "has_warned_for_load" if load_flag else "has_warned_for_save"
def _warn_legacy_serialization(warn_massages, key_flag:str):
def is_first_time(flag):
warn_key = "has_warned_for" + flag if flag else None
if not hasattr(_warn_legacy_serialization, warn_key):
_warn_legacy_serialization.__dict__[warn_key] = True
return True
else:
return not _warn_legacy_serialization.__dict__[warn_key]
if _get_always_warn_legacy_serialization() or is_first_time(load_flag):
if _get_always_warn_legacy_serialization() or is_first_time(key_flag):
print(warn_massages)
@@ -110,6 +111,13 @@ def _remap_result(cpu_result, map_location):
return cpu_result
def update_cpu_remap_info(map_location):
global RE_MAP_CPU
RE_MAP_CPU = False
if isinstance(map_location, (str, torch.device)) and 'cpu' in str(map_location):
RE_MAP_CPU = True
def load(
f: FILE_LIKE,
map_location: MAP_LOCATION = None,
@@ -119,7 +127,7 @@ def load(
mmap: Optional[bool] = None,
**pickle_load_args: Any
) -> Any:
update_cpu_remap_info(map_location)
torch._C._log_api_usage_once("torch.load")
UNSAFE_MESSAGE = (
"Weights only load failed. Re-running `torch.load` with `weights_only` set to `False`"
@@ -181,7 +189,7 @@ def load(
"If parameter types of map_location is \"Callable[[torch.Tensor, str], torch.Tensor]\" or \"Dict[str, str]\", which is only support for zipfile,"
"all tensors are currently loaded onto the CPU, which may introduce problems"
)
_warn_legacy_serialization(warn_massage, True)
_warn_legacy_serialization(warn_massage, "load")
if map_location is not None and isinstance(map_location, (torch.device, str)):
cpu_result = _legacy_load(opened_file, "cpu", pickle_module, **pickle_load_args)
@@ -205,7 +213,7 @@ def save(
"Warning: torch.save with \"_use_new_zipfile_serialization = False\" is not recommended for npu tensor, which may bring unexpected errors and hopefully set \"_use_new_zipfile_serialization = True\"",
"if it is necessary to use this, please convert the npu tensor to cpu tensor for saving"
)
_warn_legacy_serialization(warn_massage, False)
_warn_legacy_serialization(warn_massage, "save")
return torch.serialization.save(obj, f, pickle_module,pickle_protocol, True, _disable_byteorder_record)
+29 -4
View File
@@ -1,20 +1,45 @@
import copy
import torch
import torch_npu
from . import serialization as se
def _rebuild_npu_tensor(storage, storage_offset, size, stride, requires_grad, backward_hooks, npu_storage_info):
warn_massages = (
"Warning: The current version of the file storing weights is old,"
"and in the future we will deprecate the loading support for this type of file,"
"please use 2.1 and newer torch to re-store the weight file."
)
se._warn_legacy_serialization(warn_massages, "oldfile")
tensor = torch.tensor([], dtype=storage.dtype, device=storage.device)
tensor.set_(storage, storage_offset, size, stride)
tensor.requires_grad = requires_grad
tensor._backward_hooks = backward_hooks
if not se.RE_MAP_CPU:
if isinstance(npu_storage_info, bool):
tensor = tensor.npu()
else:
tensor = torch_npu.npu_format_cast(tensor.npu(), npu_storage_info)
return tensor
def _cpu(self):
"""Returns a CPU copy of this storage if it's not already on the CPU"""
if self.device.type != 'cpu':
fake_tensor = torch.tensor([], device=self.device.type)
fake_tensor = torch_npu._C._set_storage_with_format(fake_tensor, self)
fake_tensor = torch_npu._C._tensor_construct_from_storage(self)
return fake_tensor.cpu().untyped_storage()
else:
return self
def _deepcopy(self, memo):
tmp_tensor = torch.tensor([], dtype=self.dtype, device=self._untyped_storage.device).set_(self)
return tmp_tensor._typed_storage()
if self.device.type != 'cpu':
src_tensor = torch_npu._C._tensor_construct_from_storage(self)
dst_tensor = src_tensor.clone()
dst_tensor = torch_npu.npu_format_cast(dst_tensor, torch_npu.get_npu_format(src_tensor))
return dst_tensor._typed_storage()
else:
return self._new_wrapped_storage(copy.deepcopy(self._untyped_storage, memo))
def add_storage_methods():