Compare commits

...
Author SHA1 Message Date
yuliangbin 090d1a0bf9 !23695 [torch_2.8.0] 修复单CPU场景PROF文件权限校验
Merge pull request !23695 from yuliangbin/bug_fix_memory_v2.8.0
2025-08-07 13:28:20 +00:00
pta-robot 931b2d90ec !23697 Update op_plugin commit id
Merge pull request !23697 from pta-robot/v2.8.0
2025-08-07 13:20:07 +00:00
dilililiwhy ae67dca561 !23609 Release 2.8.0rc1
Merge pull request !23609 from dilililiwhy/280_release_issue
2025-08-07 11:07:30 +00:00
yuhaiyan 8eac3cda88 !23668 Support reading torch_npu_schema.json from torchair
Merge pull request !23668 from yuhaiyan/v2.8.0-dev1
2025-08-07 01:44:59 +00:00
hhz886 f9618a45c3 !23683 [Profiler]multi device feature
Merge pull request !23683 from hhz886/v2.8.0
2025-08-06 14:12:58 +00:00
王超 8549824c8f !23679 Fix p2p detect with multiple calls.
Merge pull request !23679 from 王超/v2.8.0_stresshccl3
2025-08-06 11:24:23 +00:00
huangyunlong 961e6878c6 !23413 add needsetdevice
Merge pull request !23413 from huangyunlong/2.8need
2025-08-06 10:16:04 +00:00
Gallium adc3e0d5af !23566 get streamId from npustream
Merge pull request !23566 from Gallium/bug_fix2.8.0
2025-08-06 09:40:33 +00:00
huangyunlong 1c55855995 !23630 release gil when AclSetCompileopt
Merge pull request !23630 from huangyunlong/2.8aclop
2025-08-05 13:14:31 +00:00
zyb ce6abb612a !23564 Use different dlopen flags based on so name in PTA Profiler
Merge pull request !23564 from zyb/v2.8.0
2025-08-05 09:09:24 +00:00
龚昊宇 01c6d01fa8 !23573 ADD msleaks Workspace memorypool collection.
Merge pull request !23573 from 龚昊宇/ws_leaks_v2.8.0
2025-08-05 01:26:41 +00:00
王超 72ae81096d !23590 fix p2p bug with ranktable
Merge pull request !23590 from 王超/v2.8.0_rankp2p
2025-08-05 01:07:42 +00:00
郭光浩 1163a3b286 !23602 add segment_pool_id in memory snapshot
Merge pull request !23602 from 郭光浩/v2.8.0
2025-08-04 09:25:40 +00:00
yuhaiyan 25095a50e2 !23575 Update torch_npu_schema.json and Check the compatibility of new apis
Merge pull request !23575 from yuhaiyan/v2.8.0-dev3
2025-08-04 07:37:51 +00:00
dilililiwhy e0c1433c7b !23536 Reland reduce_ex patch
Merge pull request !23536 from dilililiwhy/reland_reduce_ex_patch_280
2025-08-04 06:10:47 +00:00
刘嘉巍 17e72cfeb1 !23584 skip testcase
Merge pull request !23584 from 刘嘉巍/v2.8.0
2025-08-04 03:54:56 +00:00
wgb 3a61f0d312 !23572 Supports dynamic allow_internal_format settings.
Merge pull request !23572 from wgb/v2.8.0
2025-08-02 06:26:22 +00:00
51 changed files with 652 additions and 522 deletions
+26 -25
View File
@@ -19,13 +19,13 @@ Install **PyTorch** through pip.
**For Aarch64:**
```bash
pip3 install torch==2.1.0
pip3 install torch==2.8.0
```
**For x86:**
```bash
pip3 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu
pip3 install torch==2.8.0+cpu --index-url https://download.pytorch.org/whl/cpu
```
2. **Install torch-npu dependencies**
@@ -39,21 +39,19 @@ 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) |
| x86 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp311-cp311-linux_x86_64.whl#sha256=5954924ce74bc7e6a6c811e3fa4bdda9936d9889f6369fd068420c444bfd1cae) |
| 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) |
| aarch64 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=8132efb782cd181cc2dcca5e58effbe4217cdb2581206ac71466d535bf778867) |
| OS arch | Python version | link |
|---------|----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| x86 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp39-cp39-manylinux_2_28_x86_64.whl#sha256=bda4f93d64dcd9ae5d51844bbccc6fcb7d603522bcc95d256b5fe3bdb9dccca3) |
| x86 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp310-cp310-manylinux_2_28_x86_64.whl#sha256=16d75fa4e96ea28a785dfd66083ca55eb1058b6d6c5413f01656ca965ee2077e) |
| x86 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp311-cp311-manylinux_2_28_x86_64.whl#sha256=cb06175284673a581dd91fb1965662ae4ecaba6e5c357aa0ea7bb8b84b6b7eeb) |
| aarch64 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp39-cp39-manylinux_2_28_aarch64.whl#sha256=eac8b7ef5c7ca106daec5e829dfa8ca56ca47601db13b402d2608861ad3ab926) |
| aarch64 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp310-cp310-manylinux_2_28_aarch64.whl#sha256=b2149858b8340aeeb1f3056e0bff5b82b96e43b596fe49a9dba3184522261213) |
| aarch64 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp311-cp311-manylinux_2_28_aarch64.whl#sha256=680129efdeeec3db5da3f88ee5d28c1b1e103b774aef40f9d638e2cce8f8d8d8) |
3. **Install torch-npu**
```
pip3 install torch-npu==2.1.0.post13
pip3 install torch-npu==2.8.0rc1
```
### From Source
@@ -63,7 +61,7 @@ In some special scenarios, users may need to compile **torch-npu** by themselves
1. **Clone torch-npu**
```
git clone https://github.com/ascend/pytorch.git -b 2.1.0-7.1.0 --depth 1
git clone https://github.com/ascend/pytorch.git -b 2.8.0 --depth 1
```
2. **Build Docker Image**
@@ -82,16 +80,16 @@ In some special scenarios, users may need to compile **torch-npu** by themselves
4. **Compile torch-npu**
Take **Python 3.8** as an example.
Take **Python 3.9** as an example.
```
cd /home/pytorch
bash ci/build.sh --python=3.8
bash ci/build.sh --python=3.9
```
**Tips**
If you would like to compile with new C++ ABI, then first run this command, at this point, the recommended compilation environment is same to community torch package: glibc 2.28, gcc 11.2.1
If you would like to compile with new C++ ABI, then first run this command, at this point, the recommended compilation environment is same to community torch package: glibc 2.28, gcc 13.3.1
```
export _GLIBCXX_USE_CXX11_ABI=1
@@ -100,7 +98,7 @@ In some special scenarios, users may need to compile **torch-npu** by themselves
Meanwhile, we support configuring -fabi-version using the following variables,require consistency with the community torch package
```
export _ABI_VERSION=16
export _ABI_VERSION=18
```
## Getting Started
@@ -144,6 +142,7 @@ Refer to [API of Ascend Extension for PyTorch](docs/api/torch_npu_apis.md) for m
| PyTorch2.4.0 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.5.1 | Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.6.0 | Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.8.0 | Python3.9.x,Python3.10.x,Python3.11.x |
## Ascend Auxiliary Software
@@ -151,9 +150,10 @@ Refer to [API of Ascend Extension for PyTorch](docs/api/torch_npu_apis.md) for m
| CANN Version | Supported PyTorch Version | Supported Extension Version | Github Branch |
|-----------------------|---------------------------|-----------------------------|-------------------|
| CANN 8.2.RC1 | 2.6.0 | 2.6.0 | v2.6.0-7.1.0 |
| | 2.5.1 | 2.5.1.post1 | v2.5.1-7.1.0 |
| | 2.1.0 | 2.1.0.post13 | v2.1.0-7.1.0 |
| CANN 8.3.RC1.alpha001 | 2.8.0 | 2.8.0rc1 | v2.8.0 |
| CANN 8.2.RC1 | 2.6.0 | 2.6.0 | v2.6.0-7.1.0 |
| | 2.5.1 | 2.5.1.post1 | v2.5.1-7.1.0 |
| | 2.1.0 | 2.1.0.post13 | v2.1.0-7.1.0 |
| CANN 8.1.RC1 | 2.5.1 | 2.5.1 | v2.5.1-7.0.0 |
| | 2.4.0 | 2.4.0.post4 | v2.4.0-7.0.0 |
| | 2.3.1 | 2.3.1.post6 | v2.3.1-7.0.0 |
@@ -245,10 +245,11 @@ The version branches of AscendPyTorch have the following maintenance phases:
| **PyTorch** | **Maintenance Policies** | **Status** | **Launch Date** | **Subsequent Status** | **EOL Date** |
|-------------|--------------------------|-------------|-----------------|-------------------------------------------------------------------|--------------|
| 2.6.0 | Regular Release | Development | 2025/07/25 | Expected to enter maintenance status from January 25, 2026 | - |
| 2.5.1 | Regular Release | Development | 2024/11/08 | Expected to enter maintenance status from August 8, 2025 | |
| 2.4.0 | Regular Release | Maintained | 2024/10/15 | Expected to enter maintenance free status from June 15, 2026 | |
| 2.3.1 | Regular Release | Maintained | 2024/06/06 | Expected to enter maintenance free status from June 7, 2026 | |
| 2.8.0 | Regular Release | Development | 2025/08/08 | Expected to enter maintenance status from February 8, 2026 | |
| 2.6.0 | Regular Release | Development | 2025/07/25 | Expected to enter maintenance status from January 25, 2026 | |
| 2.5.1 | Regular Release | Development | 2024/11/08 | Expected to enter maintenance status from August 8, 2025 | |
| 2.4.0 | Regular Release | Maintained | 2024/10/15 | Expected to enter maintenance free status from June 15, 2026 | |
| 2.3.1 | Regular Release | Maintained | 2024/06/06 | Expected to enter maintenance free status from June 7, 2026 | |
| 2.2.0 | Regular Release | Maintained | 2024/04/01 | Expected to enter maintenance free status from September 10, 2025 | |
| 2.1.0 | Long Term Support | Development | 2023/10/15 | Expected to enter maintenance status from September 15, 2025 | |
| 2.0.1 | Regular Release | EOL | 2023/7/19 | | 2024/3/14 |
+23 -22
View File
@@ -19,27 +19,25 @@
**aarch64:**
```bash
pip3 install torch==2.1.0
pip3 install torch==2.8.0
```
**x86:**
```bash
pip3 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu
pip3 install torch==2.8.0+cpu --index-url https://download.pytorch.org/whl/cpu
```
若使用pip命令安装失败,请使用下载链接或进入[PyTorch官方网站](https://pytorch.org/)进行查询下载对应版本。
| 架构 | Python版本 | 下载链接 |
|---------|------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| x86 | Python3.8 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp38-cp38-linux_x86_64.whl#sha256=9e5cfd931a65b38d222755a45dabb53b836be31bc620532bc66fee77e3ff67dc) |
| x86 | Python3.9 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp39-cp39-linux_x86_64.whl#sha256=86cc28df491fa84738affe752f9870791026565342f69e4ab63e5b935f00a495) |
| x86 | Python3.10 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp310-cp310-linux_x86_64.whl#sha256=5077921fc2b54e69a534f3a9c0b98493c79a5547c49d46f5e77e42da3610e011) |
| x86 | Python3.11 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp311-cp311-linux_x86_64.whl#sha256=5954924ce74bc7e6a6c811e3fa4bdda9936d9889f6369fd068420c444bfd1cae) |
| aarch64 | Python3.8 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=761822761fffaa1c18a62c5deb13abaa780862577d3eadc428f1daa632536905) |
| aarch64 | Python3.9 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=de7d63c6ecece118684415a3dbd4805af4a4c1ee1490cccf7405d8c240a481b4) |
| aarch64 | Python3.10 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=a04a0296d47f28960f51c18c5489a8c3472f624ec3b5bcc8e2096314df8c3342) |
| aarch64 | Python3.11 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=8132efb782cd181cc2dcca5e58effbe4217cdb2581206ac71466d535bf778867) |
| 架构 | Python版本 | 下载链接 |
|---------|------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| x86 | Python3.9 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp39-cp39-manylinux_2_28_x86_64.whl#sha256=bda4f93d64dcd9ae5d51844bbccc6fcb7d603522bcc95d256b5fe3bdb9dccca3) |
| x86 | Python3.10 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp310-cp310-manylinux_2_28_x86_64.whl#sha256=16d75fa4e96ea28a785dfd66083ca55eb1058b6d6c5413f01656ca965ee2077e) |
| x86 | Python3.11 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp311-cp311-manylinux_2_28_x86_64.whl#sha256=cb06175284673a581dd91fb1965662ae4ecaba6e5c357aa0ea7bb8b84b6b7eeb) |
| aarch64 | Python3.9 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp39-cp39-manylinux_2_28_aarch64.whl#sha256=eac8b7ef5c7ca106daec5e829dfa8ca56ca47601db13b402d2608861ad3ab926) |
| aarch64 | Python3.10 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp310-cp310-manylinux_2_28_aarch64.whl#sha256=b2149858b8340aeeb1f3056e0bff5b82b96e43b596fe49a9dba3184522261213) |
| aarch64 | Python3.11 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp311-cp311-manylinux_2_28_aarch64.whl#sha256=680129efdeeec3db5da3f88ee5d28c1b1e103b774aef40f9d638e2cce8f8d8d8) |
2. **安装torch_npu依赖**
@@ -53,7 +51,7 @@ pip3 install setuptools
3. **安装torch_npu**
```bash
pip3 install torch-npu==2.1.0.post13
pip3 install torch-npu==2.8.0rc1
```
如需要保存安装日志,可在pip3 install命令后面加上参数 `--log <PATH>`,并对您指定的目录`<PATH>`做好权限管控。
@@ -64,7 +62,7 @@ pip3 install torch-npu==2.1.0.post13
1. **克隆torch_npu代码仓**
```
git clone https://gitee.com/ascend/pytorch.git -b v2.1.0-7.1.0 --depth 1
git clone https://gitee.com/ascend/pytorch.git -b v2.8.0 --depth 1
```
2. **构建镜像**
@@ -83,16 +81,16 @@ pip3 install torch-npu==2.1.0.post13
4. **编译torch_npu**
以**Python 3.8** 为例。
以**Python 3.9** 为例。
```
cd /home/pytorch
bash ci/build.sh --python=3.8
bash ci/build.sh --python=3.9
```
**提示**
如果想使用新的C++ ABI编译,请首先运行如下命令,此时推荐和社区torch包相同的编译环境:glibc 2.28, gcc 11.2.1
如果想使用新的C++ ABI编译,请首先运行如下命令,此时推荐和社区torch包相同的编译环境:glibc 2.28, gcc 13.3.1
```
export _GLIBCXX_USE_CXX11_ABI=1
@@ -101,7 +99,7 @@ pip3 install torch-npu==2.1.0.post13
同时,我们支持使用如下变量配置-fabi-version,要求和社区torch包ABI版本一致
```
export _ABI_VERSION=16
export _ABI_VERSION=18
```
@@ -153,6 +151,7 @@ print(z)
| PyTorch2.4.0 | Python3.8.x, Python3.9.x, Python3.10.x, Python 3.11.x |
| PyTorch2.5.1 | Python3.9.x, Python3.10.x, Python 3.11.x |
| PyTorch2.6.0 | Python3.9.x, Python3.10.x, Python 3.11.x |
| PyTorch2.8.0 | Python3.9.x, Python3.10.x, Python 3.11.x |
## 昇腾辅助软件
@@ -160,6 +159,7 @@ print(z)
| CANN版本 | 支持的PyTorch版本 | 支持的Extension版本 | Gitee分支 |
|-----------------------|--------------|------------------|-------------------|
| CANN 8.3.RC1.alpha001 | 2.8.0 | 2.8.0rc1 | v2.8.0 |
| CANN 8.2.RC1 | 2.6.0 | 2.6.0 | v2.6.0-7.1.0 |
| | 2.5.1 | 2.5.1.post1 | v2.5.1-7.1.0 |
| | 2.1.0 | 2.1.0.post13 | v2.1.0-7.1.0 |
@@ -247,10 +247,11 @@ AscendPyTorch版本分支的维护阶段如下:
| **PyTorch版本** | **维护策略** | **当前状态** | **发布时间** | **后续状态** | **EOL日期** |
|---------------|----------|----------|------------|----------------------|-----------|
| 2.6.0 | 常规分支 | 开发 | 2025/07/25 | 预计2026/01/25起进入维护状态 | - |
| 2.5.1 | 常规分支 | 开发 | 2024/11/08 | 预计2025/08/08起进入维护状态 | - |
| 2.4.0 | 常规分支 | 维护 | 2024/10/15 | 预计2026/06/15起进入无维护状态 | - |
| 2.3.1 | 常规分支 | 维护 | 2024/06/06 | 预计2026/06/07起进入无维护状态 | |
| 2.8.0 | 常规分支 | 开发 | 2025/08/08 | 预计2026/02/08起进入维护状态 | |
| 2.6.0 | 常规分支 | 开发 | 2025/07/25 | 预计2026/01/25起进入维护状态 | |
| 2.5.1 | 常规分支 | 开发 | 2024/11/08 | 预计2025/08/08起进入维护状态 | |
| 2.4.0 | 常规分支 | 维护 | 2024/10/15 | 预计2026/06/15起进入无维护状态 | |
| 2.3.1 | 常规分支 | 维护 | 2024/06/06 | 预计2026/06/07起进入无维护状态 | |
| 2.2.0 | 常规分支 | 维护 | 2024/04/01 | 预计2025/09/10起进入无维护状态 | |
| 2.1.0 | 长期支持 | 开发 | 2023/10/15 | 预计2025/09/15起进入维护状态 | |
| 2.0.1 | 常规分支 | EOL | 2023/7/19 | | 2024/3/14 |
+28 -28
View File
@@ -70,34 +70,34 @@ torch_npu支持源码编译安装,在编译时会下载依赖第三方库并
##### 公网地址
| 类型 | 开源代码地址 | 文件名 | 公网IP地址/公网URL地址/域名/邮箱地址 | 用途说明 |
|------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------|--------------------------------------------------------------------------------|--------------------------------|
| 自研 | 不涉及 | .gitmodules | https://gitee.com/ascend/op-plugin.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/googletest.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/ascend/torchair.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/ascend/Tensorpipe.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/fmt.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/nlohmann-json.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://mirrors.huaweicloud.com/repository/pypi/simple | docker配置文件,用于配置pip源 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://download.pytorch.org/whl/cpu | docker配置源,用于配置torch下载连接 |
| 自研 | 不涉及 | ci\docker\ARM\Dockerfile | https://mirrors.huaweicloud.com/repository/pypi/simple | docker配置文件,用于配置pip源 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo | docker配置文件,用于配置yum源 |
| 自研 | 不涉及 | ci\docker\ARM\Dockerfile | https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo | docker配置文件,用于配置yum源 |
| 自研 | 不涉及 | .github\workflows\\_build-and-test.yml | https://mirrors.huaweicloud.com/repository/pypi/simple | workflow配置文件,用于配置pip源 |
| 自研 | 不涉及 | setup.cfg | https://gitee.com/ascend/pytorch | 用于打包whl的url入参 |
| 自研 | 不涉及 | setup.cfg | https://gitee.com/ascend/pytorch/tags | 用于打包whl的download_url入参 |
| 自研 | 不涉及 | third_party\op-plugin\ci\build.sh | https://gitee.com/ascend/pytorch.git | 编译脚本根据torch_npu仓库地址拉取代码进行编译 |
| 自研 | 不涉及 | third_party\op-plugin\ci\exec_ut.sh | https://gitee.com/ascend/pytorch.git | UT脚本根据torch_npu仓库地址下拉取代码进行UT测试 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/main/test/nn/test_convolution.py <br> https://github.com/pytorch/pytorch/blob/main/test/test_mps.py <br> https://github.com/pytorch/pytorch/blob/main/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/legacy_conv2d.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/main/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/legacy_serialized.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/main/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/gpu_tensors.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/main/test/onnx/test_utility_funs.py | test\url.ini | https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml | issue的链接 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/main/test/test_nn.py <br> https://github.com/pytorch/pytorch/blob/main/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/linear.pt | 用于test脚本下载相关pt文件 |
| 自研 | 不涉及 | torch_npu\npu\config.yaml | https://raw.githubusercontent.com/brendangregg/FlameGraph/master/flamegraph.pl | 火焰图脚本下载路径 |
| 自研 | 不涉及 | test\requirements.txt | https://download.pytorch.org/whl/nightly/cpu | 下载链接,用于下载torch-cpu版本 |
| 自研 | 不涉及 | test\requirements.txt | https://data.pyg.org/whl/torch-2.4.0+cpu.html | 下载链接,用于下载torch-scatter的cpu版本 |
| 自研 | 不涉及 | requirements.txt | https://download.pytorch.org/whl/nightly/cpu | 下载链接,用于下载torch-cpu版本 |
| 自研 | 不涉及 | test\get_synchronized_files.sh | https://github.com/pytorch/pytorch.git | 下载链接,用于下载pytorch的测试用例 |
| 类型 | 开源代码地址 | 文件名 | 公网IP地址/公网URL地址/域名/邮箱地址 | 用途说明 |
|------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------|--------------------------------------------------------------------------------|--------------------------------|
| 自研 | 不涉及 | .gitmodules | https://gitee.com/ascend/op-plugin.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/googletest.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/ascend/torchair.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/ascend/Tensorpipe.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/fmt.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/nlohmann-json.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://mirrors.huaweicloud.com/repository/pypi/simple | docker配置文件,用于配置pip源 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://download.pytorch.org/whl/cpu | docker配置源,用于配置torch下载连接 |
| 自研 | 不涉及 | ci\docker\ARM\Dockerfile | https://mirrors.huaweicloud.com/repository/pypi/simple | docker配置文件,用于配置pip源 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo | docker配置文件,用于配置yum源 |
| 自研 | 不涉及 | ci\docker\ARM\Dockerfile | https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo | docker配置文件,用于配置yum源 |
| 自研 | 不涉及 | .github\workflows\\_build-and-test.yml | https://mirrors.huaweicloud.com/repository/pypi/simple | workflow配置文件,用于配置pip源 |
| 自研 | 不涉及 | setup.cfg | https://gitee.com/ascend/pytorch | 用于打包whl的url入参 |
| 自研 | 不涉及 | setup.cfg | https://gitee.com/ascend/pytorch/tags | 用于打包whl的download_url入参 |
| 自研 | 不涉及 | third_party\op-plugin\ci\build.sh | https://gitee.com/ascend/pytorch.git | 编译脚本根据torch_npu仓库地址拉取代码进行编译 |
| 自研 | 不涉及 | third_party\op-plugin\ci\exec_ut.sh | https://gitee.com/ascend/pytorch.git | UT脚本根据torch_npu仓库地址下拉取代码进行UT测试 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/nn/test_convolution.py <br> https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_mps.py <br> https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/legacy_conv2d.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/legacy_serialized.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/gpu_tensors.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/onnx/test_utility_funs.py | test\url.ini | https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml | issue的链接 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_nn.py <br> https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/linear.pt | 用于test脚本下载相关pt文件 |
| 自研 | 不涉及 | torch_npu\npu\config.yaml | https://raw.githubusercontent.com/brendangregg/FlameGraph/master/flamegraph.pl | 火焰图脚本下载路径 |
| 自研 | 不涉及 | test\requirements.txt | https://download.pytorch.org/whl/cpu | 下载链接,用于下载torch-cpu版本 |
| 自研 | 不涉及 | test\requirements.txt | https://data.pyg.org/whl/torch-2.7.0+cpu.html | 下载链接,用于下载torch-scatter的cpu版本 |
| 自研 | 不涉及 | requirements.txt | https://download.pytorch.org/whl/cpu | 下载链接,用于下载torch-cpu版本 |
| 自研 | 不涉及 | test\get_synchronized_files.sh | https://github.com/pytorch/pytorch.git | 下载链接,用于下载pytorch的测试用例 |
## 公开接口声明
+17 -9
View File
@@ -1,11 +1,19 @@
FROM quay.io/pypa/manylinux2014_aarch64:2023-10-07-c1e05d1
FROM pytorch/manylinux2_28_aarch64-builder:cpu-aarch64-2.8
# Set pip
ENV PATH /usr/local/bin:$PATH
RUN echo "alias ll='ls -l --color=auto'" >> /root/.bashrc
# Set pip&python
RUN cd /usr/local/bin \
&& 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 /opt/_internal/cpython-3.11.6/bin/pip3.11 pip3.11 \
&& ln -s python3.9 python3
&& ln -sf /opt/_internal/cpython-3.9.23/bin/pip3.9 pip3.9 \
&& ln -sf /opt/_internal/cpython-3.10.18/bin/pip3.10 pip3.10 \
&& ln -sf /opt/_internal/cpython-3.11.13/bin/pip3.11 pip3.11 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/pip3.9 pip3 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/python3.9 python3.9 \
&& ln -sf /opt/_internal/cpython-3.10.18/bin/python3.10 python3.10 \
&& ln -sf /opt/_internal/cpython-3.11.13/bin/python3.11 python3.11 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/python3.9 python3
# Set pip source
RUN mkdir /root/.pip \
@@ -33,15 +41,15 @@ RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
# Install pip package(build)
RUN pip3.9 install pyyaml \
&& pip3.9 install torch==2.1.0 \
&& pip3.9 install torch==2.8.0 \
&& pip3.9 install numpy==1.21.3
RUN pip3.10 install pyyaml \
&& pip3.10 install torch==2.1.0 \
&& pip3.10 install torch==2.8.0 \
&& pip3.10 install numpy==1.21.3
RUN pip3.11 install pyyaml \
&& pip3.11 install torch==2.1.0 \
&& pip3.11 install torch==2.8.0 \
&& pip3.11 install numpy==1.23.2
WORKDIR /home
+17 -12
View File
@@ -1,14 +1,19 @@
FROM pytorch/manylinux-builder:cpu-2.1
FROM pytorch/manylinux2_28-builder:cpu-2.8
# Install python
ENV PATH /usr/local/bin:$PATH
RUN echo "alias ll='ls -l --color=auto'" >> /root/.bashrc
# Set pip&python
RUN cd /usr/local/bin \
&& 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.11.0/bin/pip3.11 pip3.11 \
&& 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 /opt/_internal/cpython-3.11.0/bin/python3.11 python3.11 \
&& ln -s python3.9 python3
&& ln -sf /opt/_internal/cpython-3.9.23/bin/pip3.9 pip3.9 \
&& ln -sf /opt/_internal/cpython-3.10.18/bin/pip3.10 pip3.10 \
&& ln -sf /opt/_internal/cpython-3.11.13/bin/pip3.11 pip3.11 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/pip3.9 pip3 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/python3.9 python3.9 \
&& ln -sf /opt/_internal/cpython-3.10.18/bin/python3.10 python3.10 \
&& ln -sf /opt/_internal/cpython-3.11.13/bin/python3.11 python3.11 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/python3.9 python3
# Set pip source
RUN mkdir /root/.pip \
@@ -36,15 +41,15 @@ RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
# Install pip package(build)
RUN pip3.9 install pyyaml \
&& pip3.9 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.9 install torch==2.8.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 torch==2.8.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.10 install numpy==1.21.3
RUN pip3.11 install pyyaml \
&& pip3.11 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.11 install torch==2.8.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.11 install numpy==1.23.2
WORKDIR /home
+1 -1
View File
@@ -1,4 +1,4 @@
--extra-index-url https://download.pytorch.org/whl/test/cpu
--extra-index-url https://download.pytorch.org/whl/cpu
pyyaml
setuptools
+2
View File
@@ -623,6 +623,7 @@ classifiers = [
"Programming Language :: Python :: 3.11",
]
requirements = ['torch==2.8.0+cpu' if platform.machine() == 'x86_64' else 'torch==2.8.0']
setup(
name=os.environ.get('TORCH_NPU_PACKAGE_NAME', 'torch_npu'),
@@ -647,6 +648,7 @@ setup(
define_macros=[('_GLIBCXX_USE_CXX11_ABI', '1' if USE_CXX11_ABI else '0'), ('GLIBCXX_USE_CXX11_ABI', '1' if USE_CXX11_ABI else '0')]
),
],
install_requires=requirements,
extras_require={
},
package_data={
+3 -73
View File
@@ -2815,83 +2815,13 @@
"TrieNode"
],
"torch_npu": [
"_npu_dropout",
"copy_memory_",
"empty_with_format",
"empty_with_swapped_memory",
"npu_alloc_float_status",
"npu_apply_adam",
"npu_advance_step_flashattn",
"npu_batch_gather_matmul",
"npu_batch_gather_matmul_",
"npu_bert_apply_adam",
"npu_clear_float_status",
"npu_cross_entropy_loss",
"npu_format_cast_",
"npu_fusion_attention",
"npu_fusion_attention_v2",
"npu_get_float_status",
"npu_nms_rotated",
"npu_random_choice_with_mask",
"npu_rms_norm",
"npu_add_rms_norm_cast",
"npu_fused_infer_attention_score",
"npu_fused_infer_attention_score_v2",
"npu_mla_prolog",
"npu_mla_prolog_v2",
"npu_convert_weight_to_int4pack",
"npu_ffn",
"npu_fused_matmul",
"npu_geglu",
"npu_grouped_matmul",
"npu_quant_matmul",
"npu_quant_scatter",
"npu_scatter_nd_update_",
"npu_swiglu",
"npu_dequant_bias",
"npu_group_quant",
"npu_dynamic_quant",
"npu_dynamic_quant_asymmetric",
"npu_yolo_boxes_encode",
"npu_yolo_boxes_encode",
"npu_gemma_rms_norm",
"npu_weight_quant_batchmatmul",
"npu_transpose",
"npu_trans_quant_param",
"npu_stride_add",
"npu_sort_v2",
"npu_dtype_cast",
"npu_group_quant",
"npu_gelu",
"npu_gelu_backward",
"npu_all_gather_base_mm",
"npu_mm_reduce_scatter_base",
"npu_prefetch",
"npu_quant_scatter_",
"scatter_update",
"scatter_update_",
"npu_kronecker_quant",
"npu_moe_compute_expert_tokens",
"npu_geglu",
"npu_moe_gating_top_k_softmax",
"npu_moe_init_routing",
"npu_group_norm_swish",
"npu_mrope",
"npu_grouped_matmul_finalize_routing",
"npu_alltoallv_gmm",
"npu_gmm_alltoallv",
"npu_nsa_compress",
"npu_nsa_compress_infer",
"npu_nsa_compress_attention",
"npu_nsa_compress_attention_infer",
"npu_nsa_select_attention",
"npu_nsa_select_attention_infer",
"npu_transpose_batchmatmul",
"npu_gather_sparse_index",
"npu_moe_distribute_combine_add_rms_norm",
"npu_moe_eplb_update_expert",
"npu_moe_distribute_dispatch_setup",
"npu_moe_distribute_dispatch_teardown",
"npu_moe_distribute_combine_setup",
"npu_moe_distribute_combine_teardown"
"npu_fused_infer_attention_score_v2"
],
"torch_npu.contrib": [
"npu_fused_attention_with_layernorm",
+67
View File
@@ -0,0 +1,67 @@
import threading
import torch
from torch.testing._internal.common_distributed import MultiProcessTestCase
from torch.testing._internal.common_utils import run_tests
import torch_npu
class TestDevice(MultiProcessTestCase):
def setUp(self):
super().setUp()
self._spawn_processes()
@property
def world_size(self):
return 1
def test_event_create(self):
a = torch.full((3, 4), float(0), device='npu:0')
e = torch.npu.Event()
s = torch.npu.Stream()
def target_fuc(result):
e.record(s)
e.synchronize()
result[0] = 1
result = [0]
t = threading.Thread(target=target_fuc, args=(result, ))
t.start()
t.join()
self.assertEqual(result[0], 1)
def test_stream_create(self):
s = torch_npu._C._npu_getCurrentStream(0)
def test_tensor(self):
a = torch.full((3, 4), float(0), device='npu:0')
def target_fuc(result):
b = torch.full((3, 4), float(0), device='npu:0')
result[0] = 1
result = [0]
t = threading.Thread(target=target_fuc, args=(result, ))
t.start()
t.join()
self.assertEqual(result[0], 1)
def test_storage(self):
s = torch.npu.Stream()
def target_fuc(result):
b = torch.npu.FloatStorage(10)
result[0] = 1
result = [0]
t = threading.Thread(target=target_fuc, args=(result, ))
t.start()
t.join()
self.assertEqual(result[0], 1)
if __name__ == "__main__":
run_tests()
+24
View File
@@ -254,6 +254,19 @@ class TestPublicApiCompatibility(TestCase):
for key, value in base_schema0.items():
if not key.startswith("torch_c_func:") and not key.startswith("torch_npu_public_env:"):
base_schema[key] = value
# load torchair torch_npu_schema.json
torchair_schema = {}
try:
air_path = 'third_party/torchair/torchair/tests/st/torch_npu_schema.json'
with open(get_file_path_2(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), air_path)) as fp:
torchair_schema = json.load(fp)
except Exception:
warnings.warn(
"if you are debugging UT file in clone repo, please recursively update the torchair submodule")
if torchair_schema:
base_schema.update(torchair_schema)
content = {}
@@ -282,6 +295,10 @@ class TestPublicApiCompatibility(TestCase):
return
elem_module = getattr(obj, '__module__', None)
# the compatibility of apis from torch._ops.npu is checked in op-plugin.
if elem_module == "torch._ops.npu":
return
modname = allow_dict["being_migrated"].get(modname, modname)
elem_modname_starts_with_mod = elem_module is not None and \
elem_module.startswith(modname) and \
@@ -327,6 +344,13 @@ class TestPublicApiCompatibility(TestCase):
for func in deleted_apis:
failure_list.append(f"# {func}:")
failure_list.append(f" - {func} has been deleted.")
newly_apis = set(now_funcs) - set(base_funcs)
for func in newly_apis:
failure_list.append(f"# {func}:")
failure_list.append(f" - {func} is new. Please add it to the torch_npu_schema.json")
signature = content[func]["signature"]
failure_list.append(f" - it's signature is {signature}.")
msg = "All the APIs below do not meet the compatibility guidelines. "
msg += "If the change timeline has been reached, you can modify the torch_npu_schema.json to make it OK."
@@ -0,0 +1,16 @@
import torch
from torch.testing._internal.common_utils import TestCase, run_tests
import torch_npu
class TestPinMemory(TestCase):
def test_pin_memory(self):
# pin_memory -> getPinnedMemoryAllocator -> Initialize -> InitAclops -> aclSetCompileopt
# now pin_memory hold gil, aclSetCompileopt will fail if we don't release gil
pin_tensor = torch.tensor((2, 3), pin_memory=True)
if __name__ == '__main__':
run_tests()
+31
View File
@@ -622,6 +622,14 @@ class TestPublicBindings(TestCase):
`__module__` that start with the current submodule.
'''
failure_list = []
def _get_test_torch_version():
torch_npu_version = torch_npu.__version__
version_list = torch_npu_version.split('.')
if len(version_list) > 2:
return f'v{version_list[0]}.{version_list[1]}'
else:
raise RuntimeError("Invalid torch_npu version.")
try:
file_abspath = os.path.abspath(__file__)
@@ -633,6 +641,23 @@ class TestPublicBindings(TestCase):
except Exception:
update_allow_dict_torchair = {}
warnings.warn("if you are debugging UT file in clone repo, please recursively update the torchair submodule")
try:
file_abspath = os.path.abspath(__file__)
op_plugin_path = 'third_party/op-plugin/test/allowlist_for_publicAPI.json'
with open(
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(file_abspath))), op_plugin_path)) as json_file_op_plugin:
version_tag = _get_test_torch_version()
allow_dict_info = json.load(json_file_op_plugin)
allow_dict_op_plugin = {}
if "torch_npu" in allow_dict_info and "all_version" in allow_dict_info["torch_npu"]:
allow_dict_op_plugin["torch_npu"] = allow_dict_info["torch_npu"]["all_version"]
if version_tag in allow_dict_info["torch_npu"] and allow_dict_info["torch_npu"][version_tag]:
allow_dict_op_plugin["torch_npu"].extend(allow_dict_info["torch_npu"][version_tag])
except Exception as e:
allow_dict_op_plugin = {}
warnings.warn(f"{e}")
with open(get_file_path_2(os.path.dirname(os.path.dirname(__file__)),
'allowlist_for_publicAPI.json')) as json_file:
@@ -652,6 +677,12 @@ class TestPublicBindings(TestCase):
if update_allow_dict_torchair:
allow_dict.update(update_allow_dict_torchair)
if allow_dict_op_plugin and "torch_npu" in allow_dict_op_plugin:
if "torch_npu" in allow_dict:
allow_dict["torch_npu"].extend(allow_dict_op_plugin["torch_npu"])
else:
allow_dict.update(allow_dict_op_plugin["torch_npu"])
def test_module(modname):
try:
if "__main__" in modname or \
-2
View File
@@ -2,7 +2,6 @@ import io
import os
import tempfile
import argparse
import unittest
import torch
import torch.nn as nn
@@ -96,7 +95,6 @@ class TestSerialization(TestCase):
self.assertExpectedInline(f'{x_loaded.device.type}:{x_loaded.device.index}', 'npu:0')
self.assertRtolEqual(x, x_loaded.cpu())
@unittest.skip("pytorch/issues/146969, pytorch/issues/125465, pytorch/pull/142214")
def test_save_npu_format(self):
with tempfile.TemporaryDirectory() as tmpdir:
path = os.path.join(tmpdir, 'data.pt')
@@ -69,25 +69,25 @@ class TestPathManager(TestCase):
self.assertEqual(host_path, ProfilerPathManager.get_host_path(cann_path))
def test_get_device_path(self):
self.assertEqual("", ProfilerPathManager.get_device_path(self.tmp_dir))
self.assertEqual([], ProfilerPathManager.get_device_path(self.tmp_dir))
cann_path = os.path.join(self.tmp_dir, "PROF_1_2_3a")
device_path = os.path.join(cann_path, "device_0")
os.makedirs(device_path)
self.assertEqual(device_path, ProfilerPathManager.get_device_path(cann_path))
self.assertEqual([device_path], ProfilerPathManager.get_device_path(cann_path))
def test_get_device_id(self):
self.assertEqual(Constant.INVALID_VALUE, ProfilerPathManager.get_device_id(""))
self.assertEqual([], ProfilerPathManager.get_device_id(""))
cann_path = os.path.join(self.tmp_dir, "PROF_1_2_3a")
os.makedirs(cann_path)
self.assertEqual(Constant.INVALID_VALUE, ProfilerPathManager.get_device_id(cann_path))
self.assertEqual([], ProfilerPathManager.get_device_id(cann_path))
invalid_device_path = os.path.join(cann_path, "device")
os.makedirs(invalid_device_path)
self.assertEqual(Constant.INVALID_VALUE, ProfilerPathManager.get_device_id(cann_path))
self.assertEqual([], ProfilerPathManager.get_device_id(cann_path))
invalid_device_path = os.path.join(cann_path, "device_xx")
self.assertEqual(Constant.INVALID_VALUE, ProfilerPathManager.get_device_id(cann_path))
self.assertEqual([], ProfilerPathManager.get_device_id(cann_path))
invalid_device_path = os.path.join(cann_path, "device_0")
os.makedirs(invalid_device_path)
self.assertEqual(0, ProfilerPathManager.get_device_id(cann_path))
self.assertEqual([0], ProfilerPathManager.get_device_id(cann_path))
def test_get_start_info_path(self):
self.assertEqual("", ProfilerPathManager.get_start_info_path(self.tmp_dir))
@@ -139,21 +139,6 @@ class TestPathManager(TestCase):
fp.write("something")
self.assertEqual(3, len(ProfilerPathManager.get_output_all_file_list_by_type(cann_path, "mindstudio_profiler_output")))
def test_get_feature_json_path(self):
self.assertEqual("", ProfilerPathManager.get_feature_json_path(self.tmp_dir))
cann_path = os.path.join(self.tmp_dir, "PROF_001_111111_AAA")
PathManager.make_dir_safety(cann_path)
self.assertEqual("", ProfilerPathManager.get_feature_json_path(self.tmp_dir))
host_path = os.path.join(cann_path, "host")
PathManager.make_dir_safety(host_path)
self.assertEqual("", ProfilerPathManager.get_feature_json_path(self.tmp_dir))
feature_file = os.path.join(host_path, "incompatible_features.json")
FileManager.create_json_file_by_path(feature_file, {"attr": {"version": "1"}})
self.assertEqual(feature_file, ProfilerPathManager.get_feature_json_path(self.tmp_dir))
def test_get_analyze_all_file(self):
self.assertEqual([], ProfilerPathManager.get_analyze_all_file(self.tmp_dir, "analyse"))
cann_path = os.path.join(self.tmp_dir, "PROF_1_2_3a")
+2 -2
View File
@@ -1,11 +1,11 @@
--extra-index-url https://download.pytorch.org/whl/test/cpu
--extra-index-url https://download.pytorch.org/whl/cpu
-f https://data.pyg.org/whl/torch-2.7.0+cpu.html
coverage
beartype==0.17.0
expecttest==0.1.3
hypothesis
mypy==1.14.0
mypy==1.16.0
numpy==1.24.4
onnx==1.18.0
onnxruntime==1.18.1
+60 -102
View File
@@ -785,9 +785,6 @@
"torch_npu.npu.NPUGraph.capture_end": {
"signature": "(self)"
},
"torch_npu.npu_mla_prolog": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu.MemPoolContext": {
"signature": "(pool: torch_npu.npu.memory.MemPool)"
},
@@ -806,9 +803,6 @@
"torch_npu.npu.graphs.NPUGraph.reset": {
"signature": "(self)"
},
"torch_npu.npu_cross_entropy_loss": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu.memory.use_mem_pool": {
"signature": "(pool: torch_npu.npu.memory.MemPool, device=None)"
},
@@ -818,15 +812,9 @@
"torch_npu.npu.graphs.graph_task_update_begin": {
"signature": "(stream, handle)"
},
"torch_npu.npu_grouped_matmul_finalize_routing": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu.streams.ExternalEvent.record": {
"signature": "(self, stream=None)"
},
"torch_npu.npu_advance_step_flashattn": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.contrib.module.activations.Swish.forward": {
"signature": "(self, x)"
},
@@ -851,21 +839,72 @@
"torch_npu.npu.streams.ExternalEvent": {
"signature": "()"
},
"torch_npu.utils.save_async": {
"signature": "(obj: object, f, pickle_module: Any = <module 'pickle'>, pickle_protocol: int = 2, _use_new_zipfile_serialization: bool = True, _disable_byteorder_record: bool = False, model: torch.nn.modules.module.Module = None) -> None"
},
"torch_npu.npu.set_device_limit": {
"signature": "(*args, **kwargs)"
},
"torch_npu.dynamo.torchair.ops.npu_record_tagged_stream": {
"signature": "(self: torch.Tensor, tagged_stream: str)"
},
"torch_npu.profiler.HostSystem": {
"signature": "()"
},
"torch_npu.profiler.experimental_config._ExperimentalConfig._check_host_sys_params": {
"signature": "(self)"
},
"torch_npu.profiler.experimental_config.HostSystem": {
"signature": "()"
},
"torch_npu.npu.npu_config.get_device_limit": {
"signature": "(device)"
},
"torch_npu.profiler._ExperimentalConfig._check_host_sys_params": {
"signature": "(self)"
},
"torch_npu.npu.npu_config.set_device_limit": {
"signature": "(*args, **kwargs)"
},
"torch_npu.dynamo.torchair.ops.npu_tagged_event_record": {
"signature": "(event)"
},
"torch_npu.dynamo.torchair.ops.npu_fused_infer_attention_score_v2": {
"signature": "(*args, **kwargs)"
},
"torch_npu.npu.graphs.NPUGraph.update": {
"signature": "(self, cpu_update_input)"
},
"torch_npu.dynamo.torchair.ops.npu_tagged_event_wait": {
"signature": "(event)"
},
"torch_npu.profiler.profile._set_step_num_offset_for_dynamic_prof": {
"signature": "(self, step: int)"
},
"torch_npu.profiler.profiler.profile._set_step_num_offset_for_dynamic_prof": {
"signature": "(self, step: int)"
},
"torch_npu.dynamo.torchair.ops.npu_create_tagged_event": {
"signature": "(tag: str)"
},
"torch_npu.npu.NPUGraph.update": {
"signature": "(self, cpu_update_input)"
},
"torch_npu.utils.serialization.save_async": {
"signature": "(obj: object, f, pickle_module: Any = <module 'pickle'>, pickle_protocol: int = 2, _use_new_zipfile_serialization: bool = True, _disable_byteorder_record: bool = False, model: torch.nn.modules.module.Module = None) -> None"
},
"torch_npu.npu.get_device_limit": {
"signature": "(device)"
},
"torch_npu.dynamo.torchair.ops.npu_fused_infer_attention_score": {
"signature": "(*args, **kwargs)"
},
"torch_npu.npu.NPUGraph.pool": {
"signature": "(self)"
},
"torch_npu.contrib.module.activations.SiLU.forward": {
"signature": "(self, x)"
},
"torch_npu.empty_with_swapped_memory": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_gmm_alltoallv": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_mrope": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu.streams.Event.recorded_time": {
"signature": "(self)"
},
@@ -881,9 +920,6 @@
"torch_npu.npu.Event.recorded_time": {
"signature": "(self)"
},
"torch_npu.npu_alltoallv_gmm": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu.graphs.NPUGraph.replay": {
"signature": "(self)"
},
@@ -893,9 +929,6 @@
"torch_npu.npu.NPUGraph.replay": {
"signature": "(self)"
},
"torch_npu.npu_group_norm_swish": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu.graphs.NPUGraph.capture_end": {
"signature": "(self)"
},
@@ -2459,15 +2492,9 @@
"torch_npu.utils.syncbatchnorm.SyncBatchNorm.backward": {
"signature": "(self, grad_output)"
},
"torch_npu._npu_dropout": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.fast_gelu": {
"signature": "(self)"
},
"torch_npu.npu_alloc_float_status": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_anchor_response_flags": {
"signature": "(self, featmap_size, stride, num_base_anchors)"
},
@@ -2477,9 +2504,6 @@
"torch_npu.npu_batch_nms": {
"signature": "(self, scores, score_threshold, iou_threshold, max_size_per_class, max_total_size, change_coordinate_frame=False, transpose_box=False)"
},
"torch_npu.npu_bert_apply_adam": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_bmmV2": {
"signature": "(self, mat2, output_sizes)"
},
@@ -2489,18 +2513,12 @@
"torch_npu.npu_bounding_box_encode": {
"signature": "(anchor_box, ground_truth_box, means0, means1, means2, means3, stds0, stds1, stds2, stds3)"
},
"torch_npu.npu_clear_float_status": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_confusion_transpose": {
"signature": "(self, perm, shape, transpose_first)"
},
"torch_npu.npu_conv3d": {
"signature": "(input_, weight, bias, stride, padding, dilation, groups)"
},
"torch_npu.npu_convert_weight_to_int4pack": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_deformable_conv2d": {
"signature": "(inputs, weight, offset, bias, kernel_size, stride, padding, dilation=[1, 1, 1, 1], groups=1, deformable_groups=1, modulated=True)"
},
@@ -2522,33 +2540,18 @@
"torch_npu.npu_stride_add": {
"signature": "(self, other, offset1, offset2, c1_len)"
},
"torch_npu.npu_ffn": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_format_cast": {
"signature": "(self, acl_format, customize_dtype=None)"
},
"torch_npu.npu_format_cast_": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_fused_attention_score": {
"signature": "(query_layer, key_layer, value_layer, attention_mask, scale, keep_prob, query_transpose=False, key_transpose=False, bmm_score_transpose_a=False, bmm_score_transpose_b=False, value_transpose=False, dx_transpose=False)"
},
"torch_npu.npu_fusion_attention": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_geglu": {
"signature": "(self, dim=-1, approximate=1, activate_left=False)"
},
"torch_npu.npu_get_float_status": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_grid_assign_positive": {
"signature": "(self, overlaps, box_responsible_flags, max_overlaps, argmax_overlaps, gt_max_overlaps, gt_argmax_overlaps, num_gts, pos_iou_thr, min_pos_iou, gt_max_assign_all)"
},
"torch_npu.npu_grouped_matmul": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_incre_flash_attention": {
"signature": "(self, query, key, value, padding_mask, atten_mask, pse_shift, actual_seq_lengths, num_heads, scale_value, input_layout, num_key_value_heads)"
},
@@ -2585,15 +2588,6 @@
"torch_npu.npu_ps_roi_pooling": {
"signature": "(self, rois, spatial_scale, group_size, output_dim)"
},
"torch_npu.npu_quant_matmul": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_quant_scatter": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_random_choice_with_mask": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_rms_norm": {
"signature": "(self, gamma, epsilon=1e-06)"
},
@@ -2615,9 +2609,6 @@
"torch_npu.npu_scatter_nd_update": {
"signature": "(self, indices, updates)"
},
"torch_npu.npu_scatter_nd_update_": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_sign_bits_pack": {
"signature": "(self, size)"
},
@@ -2630,18 +2621,9 @@
"torch_npu.npu_softmax_cross_entropy_with_logits": {
"signature": "(self, labels)"
},
"torch_npu.npu_swiglu": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_trans_quant_param": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_transpose": {
"signature": "(self, perm, require_contiguous=True, out=None)"
},
"torch_npu.npu_transpose_batchmatmul": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_weight_quant_batchmatmul": {
"signature": "(x, weight, antiquant_scale, antiquant_offset=None, quant_scale=None, quant_offset=None, bias=None, antiquant_group_size=0, inner_precise=0)"
},
@@ -2672,36 +2654,15 @@
"torch_npu.utils.FlopsCounter.get_flops": {
"signature": "(self)"
},
"torch_npu.scatter_update": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.scatter_update_": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_quantize": {
"signature": "(inputs, scales, zero_points, dtype, axis, div_mode=True)"
},
"torch_npu.npu_quant_scatter_": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_prefetch": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_moe_init_routing": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_moe_gating_top_k_softmax": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_moe_finalize_routing": {
"signature": "(expanded_permuted_rows, skip1, skip2, bias, scales, expanded_src_to_dst_row, export_for_source_row, drop_pad_mode=0)"
},
"torch_npu.npu_moe_compute_expert_tokens": {
"signature": "(sorted_experts, num_experts=1)"
},
"torch_npu.npu_mm_reduce_scatter_base": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.npu_group_norm_silu": {
"signature": "(x, gamma, beta, group, eps=1e-05)"
},
@@ -2711,9 +2672,6 @@
"torch_npu.npu_fast_gelu": {
"signature": "(self)"
},
"torch_npu.npu_all_gather_base_mm": {
"signature": "(*args: _P.args, **kwargs: _P.kwargs) -> ~_T"
},
"torch_npu.utils.set_thread_affinity": {
"signature": "(core_range: List[int] = None)"
},
@@ -187,6 +187,7 @@
"test_rand_like_npu_float32 (__main__.TestFunctionalizationRngOpsPRIVATEUSE1)": ["", [""]],
"test_rand_privateuse1_float32 (__main__.TestFunctionalizationRngOpsPRIVATEUSE1)": ["", [""]],
"test_set_get_rng_state_npu_float32 (__main__.TestFunctionalizationRngOpsPRIVATEUSE1)": ["", [""]],
"test_rand_npu_float32 (__main__.TestFunctionalizationRngOpsPRIVATEUSE1)": ["", [""]],
"test_nn_functional_lp_pool3d (__main__.TestFunctionalTracing)": ["", [""]],
"test_nn_functional_adaptive_max_pool1d (__main__.TestFunctionalTracing)": ["", [""]],
"test_nn_functional_adaptive_max_pool2d (__main__.TestFunctionalTracing)": ["", [""]],
+1
View File
@@ -195,6 +195,7 @@ def _apply_distributed_methods_patch():
torch.distributed.launcher.api._get_addr_and_port = torch_npu.distributed.distributed_c10d._trigger__get_addr_and_port_decorator(torch.distributed.launcher.api._get_addr_and_port)
torch.serialization.add_safe_globals([torch_npu.npu._format.Format])
torch.utils.rename_privateuse1_backend("npu")
# rename device name to 'npu' and register funcs
torch._register_device_module('npu', torch_npu.npu)
@@ -1562,7 +1562,7 @@ public:
#ifndef BUILD_LIBTORCH
if (torch_npu::profiler::MstxMgr::GetInstance()->isMsleaksEnable()) {
mstxDomainHandle_t msleaksDomain = torch_npu::profiler::MstxMgr::GetInstance()->createLeaksDomain(
torch_npu::profiler::DOMAIN_MSLEAKS.c_str());
torch_npu::profiler::DOMAIN_CACHING.c_str());
mstxMemVirtualRangeDesc_t heapDesc{ block->device, block->ptr,
stats.reserved_bytes[static_cast<size_t>(StatType::AGGREGATE)].current };
torch_npu::profiler::MstxMgr::GetInstance()->memHeapRegister(msleaksDomain, &heapDesc);
@@ -1628,7 +1628,7 @@ public:
#ifndef BUILD_LIBTORCH
if (torch_npu::profiler::MstxMgr::GetInstance()->isMsleaksEnable()) {
mstxDomainHandle_t msleaksDomain = torch_npu::profiler::MstxMgr::GetInstance()->createLeaksDomain(
torch_npu::profiler::DOMAIN_MSLEAKS.c_str());
torch_npu::profiler::DOMAIN_CACHING.c_str());
mstxMemVirtualRangeDesc_t desc{ block->device, orig_block_ptr,
stats.reserved_bytes[static_cast<size_t>(StatType::AGGREGATE)].current };
torch_npu::profiler::MstxMgr::GetInstance()->memHeapRegister(msleaksDomain, &desc);
@@ -3509,6 +3509,7 @@ public:
}
int device = 0;
NPU_CHECK_ERROR(c10_npu::GetDevice(&device));
LazySetDevice();
void *devPtr = nullptr;
void (*deleteFunc)(void *) = &local_raw_delete;
+2
View File
@@ -1,4 +1,5 @@
#include "torch_npu/csrc/core/npu/NPUEvent.h"
#include "torch_npu/csrc/core/npu/NPUFunctions.h"
#include "torch_npu/csrc/core/npu/NPUGuard.h"
#include "torch_npu/csrc/core/npu/NPUException.h"
#include "torch_npu/csrc/core/npu/NPUEventManager.h"
@@ -179,6 +180,7 @@ void NPUEvent::createEvent(c10::DeviceIndex device_index)
{
device_index_ = device_index;
NPUGuard guard(device_index_);
LazySetDevice();
NPU_CHECK_ERROR_WITHOUT_UCE(c10_npu::acl::AclrtCreateEventWithFlag(&event_, flags_));
ASCEND_LOGI("Event: aclrtCreateEventWithFlag is successfully executed, event=%p", event_);
#ifndef BUILD_LIBTORCH
+7
View File
@@ -288,6 +288,13 @@ int GetLocalDevice()
return local_device;
}
void LazySetDevice()
{
if (local_device < 0) {
NPU_CHECK_ERROR_WITHOUT_UCE(SetDevice(0));
}
}
void warn_or_error_on_sync()
{
if (warning_state().get_sync_debug_mode() == SyncDebugMode::L_ERROR) {
+2
View File
@@ -81,6 +81,8 @@ int MaybeExchangeDevice(int to_device);
void SetTargetDevice();
void LazySetDevice();
int GetLocalDevice();
aclError SetDeviceResLimit(int32_t device, int32_t type, uint32_t value);
+1
View File
@@ -231,6 +231,7 @@ static void initNPUStreamsOnce()
c10::DeviceIndex device_index = current_device();
// makesure on real devcie
SetTargetDevice();
LazySetDevice();
if (!initialize_flag[device_index]) {
std::lock_guard<std::mutex> lock(mtx[device_index]);
if (!initialize_flag[device_index]) {
@@ -93,8 +93,9 @@ public:
update_stat(stats.reserved_bytes, -block->size);
#ifndef BUILD_LIBTORCH
if (torch_npu::profiler::MstxMgr::GetInstance()->isMsleaksEnable()) {
mstxDomainHandle_t msleaksDomain = torch_npu::profiler::MstxMgr::GetInstance()->createLeaksDomain(torch_npu::profiler::DOMAIN_MSLEAKS.c_str());
torch_npu::profiler::MstxMgr::GetInstance()->memRegionsUnregister(msleaksDomain, block->data_ptr);
mstxDomainHandle_t workspaceDomain = torch_npu::profiler::MstxMgr::GetInstance()->createLeaksDomain(torch_npu::profiler::DOMAIN_WORKSPACE.c_str());
mstxMemVirtualRangeDesc_t desc{ device, block->data_ptr, stats.reserved_bytes.current };
torch_npu::profiler::MstxMgr::GetInstance()->memHeapRegister(workspaceDomain, &desc);
}
record_mem_size_decrement(block->size);
const c10_npu::impl::PyCallbackTrigger* trigger = c10_npu::impl::NPUTrace::getTrace();
@@ -138,9 +139,9 @@ public:
update_stat(stats.reserved_bytes, block->size);
#ifndef BUILD_LIBTORCH
if (torch_npu::profiler::MstxMgr::GetInstance()->isMsleaksEnable()) {
mstxDomainHandle_t msleaksDomain = torch_npu::profiler::MstxMgr::GetInstance()->createLeaksDomain(torch_npu::profiler::DOMAIN_MSLEAKS.c_str());
mstxMemVirtualRangeDesc_t desc{device, block->data_ptr, block->size};
torch_npu::profiler::MstxMgr::GetInstance()->memRegionsRegister(msleaksDomain, &desc);
mstxDomainHandle_t workspaceDomain = torch_npu::profiler::MstxMgr::GetInstance()->createLeaksDomain(torch_npu::profiler::DOMAIN_WORKSPACE.c_str());
mstxMemVirtualRangeDesc_t desc{ device, block->data_ptr, stats.reserved_bytes.current };
torch_npu::profiler::MstxMgr::GetInstance()->memHeapRegister(workspaceDomain, &desc);
}
record_mem_size_increment(block->size);
torch_npu::profiler::reportMemoryDataToNpuProfiler({
@@ -169,6 +170,11 @@ public:
allocated_size = block->size;
update_stat(stats.allocated_bytes, block->size);
#ifndef BUILD_LIBTORCH
if (torch_npu::profiler::MstxMgr::GetInstance()->isMsleaksEnable()) {
mstxDomainHandle_t workspaceDomain = torch_npu::profiler::MstxMgr::GetInstance()->createLeaksDomain(torch_npu::profiler::DOMAIN_WORKSPACE.c_str());
mstxMemVirtualRangeDesc_t desc{ device, block->data_ptr, stats.allocated_bytes.current };
torch_npu::profiler::MstxMgr::GetInstance()->memRegionsRegister(workspaceDomain, &desc);
}
torch_npu::profiler::reportMemoryDataToNpuProfiler({
static_cast<int8_t>(c10::DeviceType::PrivateUse1),
device,
@@ -193,6 +199,10 @@ public:
update_stat(stats.allocated_bytes, -allocated_size);
#ifndef BUILD_LIBTORCH
if (this->last_block && this->last_block->data_ptr && this->last_stream) {
if (torch_npu::profiler::MstxMgr::GetInstance()->isMsleaksEnable()) {
mstxDomainHandle_t workspaceDomain = torch_npu::profiler::MstxMgr::GetInstance()->createLeaksDomain(torch_npu::profiler::DOMAIN_WORKSPACE.c_str());
torch_npu::profiler::MstxMgr::GetInstance()->memRegionsUnregister(workspaceDomain, this->last_block->data_ptr);
}
torch_npu::profiler::reportMemoryDataToNpuProfiler({
static_cast<int8_t>(c10::DeviceType::PrivateUse1),
device,
@@ -234,8 +244,10 @@ public:
update_stat(stats.reserved_bytes, -block_pair.second->size);
#ifndef BUILD_LIBTORCH
if (torch_npu::profiler::MstxMgr::GetInstance()->isMsleaksEnable()) {
mstxDomainHandle_t msleaksDomain = torch_npu::profiler::MstxMgr::GetInstance()->createLeaksDomain(torch_npu::profiler::DOMAIN_MSLEAKS.c_str());
torch_npu::profiler::MstxMgr::GetInstance()->memRegionsUnregister(msleaksDomain, block_pair.second->data_ptr);
mstxDomainHandle_t workspaceDomain = torch_npu::profiler::MstxMgr::GetInstance()->
createLeaksDomain(torch_npu::profiler::DOMAIN_WORKSPACE.c_str());
mstxMemVirtualRangeDesc_t desc{ device, block_pair.second->data_ptr, stats.reserved_bytes.current };
torch_npu::profiler::MstxMgr::GetInstance()->memHeapRegister(workspaceDomain, &desc);
}
record_mem_size_decrement(block_pair.second->size);
const c10_npu::impl::PyCallbackTrigger* trigger = c10_npu::impl::NPUTrace::getTrace();
@@ -1,13 +1,13 @@
#include <dlfcn.h>
#include "torch_npu/csrc/core/npu/NPUException.h"
#include "torch_npu/csrc/core/npu/register/FunctionLoader.h"
namespace c10_npu {
namespace option {
FunctionLoader::FunctionLoader(const std::string &name)
FunctionLoader::FunctionLoader(const std::string &name, int flags)
{
this->fileName = name + ".so";
this->flags = flags;
}
FunctionLoader::~FunctionLoader()
@@ -25,7 +25,7 @@ void FunctionLoader::Set(const std::string &name)
void *FunctionLoader::Get(const std::string &name)
{
if (this->handle == nullptr) {
auto handle = dlopen(this->fileName.c_str(), RTLD_LAZY | RTLD_GLOBAL);
auto handle = dlopen(this->fileName.c_str(), this->flags);
if (handle == nullptr) {
AT_ERROR(dlerror());
return nullptr;
@@ -1,3 +1,4 @@
#include <dlfcn.h>
#include <mutex>
#include <memory>
#include <string>
@@ -14,7 +15,7 @@ public:
/**
ctr
*/
explicit FunctionLoader(const std::string& filename);
explicit FunctionLoader(const std::string& filename, int flags = RTLD_LAZY);
/**
dectr
*/
@@ -30,6 +31,7 @@ public:
private:
mutable std::mutex mu_;
std::string fileName;
int flags;
void* handle = nullptr;
mutable std::unordered_map<std::string, void*> registry;
}; // class FunctionLoader
@@ -81,9 +83,9 @@ public:
} // namespace register_function
#define REGISTER_LIBRARY(soName) \
auto library_##soName = \
::std::unique_ptr<c10_npu::option::FunctionLoader>(new c10_npu::option::FunctionLoader(#soName)); \
#define REGISTER_LIBRARY(soName, ...) \
auto library_##soName = ::std::unique_ptr<c10_npu::option::FunctionLoader>( \
new c10_npu::option::FunctionLoader(#soName, ##__VA_ARGS__)); \
static c10_npu::option::register_function::FunctionRegisterBuilder \
register_library_##soName(#soName, library_##soName);
+76 -87
View File
@@ -2204,7 +2204,7 @@ void ProcessGroupHCCL::setNSLBCommConfig(HcclCommConfig** commConfig)
}
}
void ProcessGroupHCCL::createHCCLComm(
void ProcessGroupHCCL::createHCCLCommOrigin(
const std::string& devicesKey,
const std::vector<at::Device>& devices,
HcclCommType commType,
@@ -2268,6 +2268,7 @@ void ProcessGroupHCCL::createHCCLComm(
}
bool ProcessGroupHCCL::createHCCLCommEx(
const std::string& devicesKey,
const std::vector<at::Device>& devices,
HcclCommType commType,
HcclCommConfig* commConfig,
@@ -2355,10 +2356,27 @@ bool ProcessGroupHCCL::createHCCLCommEx(
}
commConfig = &config;
}
auto subComm = HCCLComm::createSubHcclComm(globalHcclComm, numRanks, options_->global_ranks_in_group.data(), hcclid, rank, commConfig);
std::shared_ptr<HCCLComm> subComm = nullptr;
if (commType == HcclCommType::P2P && options_->global_ranks_in_group.empty()) {
uint32_t peer = static_cast<uint32_t>(getP2pPeer());
uint32_t lowRank = rank_ < peer ? rank_ : peer;
uint32_t highRank = rank_ < peer ? peer : rank_;
std::vector<uint32_t> p2pRanks = {lowRank, highRank};
hcclid = (std::hash<string>{}(devicesKey));
std::string p2pName = "p2p_" + std::to_string(lowRank) + "_" + std::to_string(highRank);
if (strlen(commConfig->hcclCommName) > 0) {
torch_npu::toolkit::profiler::Utils::safe_strcpy_s(commConfig->hcclCommName, p2pName.c_str(), COMM_NAME_MAX_LENGTH);
}
if (strlen(commConfig->hcclUdi) > 0) {
torch_npu::toolkit::profiler::Utils::safe_strcpy_s(commConfig->hcclUdi, p2pName.c_str(), UDI_MAX_LENGTH);
}
subComm = HCCLComm::createSubHcclComm(globalHcclComm, numRanks, p2pRanks.data(), hcclid, rank, commConfig);
} else {
subComm = HCCLComm::createSubHcclComm(globalHcclComm, numRanks, options_->global_ranks_in_group.data(), hcclid, rank, commConfig);
}
if (subComm == nullptr) {
ASCEND_LOGI("Create sub hccl comm by hcclCreateSubCommConfig failed, group id is %s, subCommId is %llu.",
options_->group_id.c_str(), hcclid);
ASCEND_LOGI("Create sub hccl comm by hcclCreateSubCommConfig failed, group id is %s, subCommId is %llu, devicesKey is %s.",
options_->group_id.c_str(), hcclid, devicesKey.c_str());
return false;
}
hcclComms[i] = subComm;
@@ -2370,10 +2388,10 @@ bool ProcessGroupHCCL::createHCCLCommEx(
}
auto subEndTime = std::chrono::steady_clock::now();
auto subTimeElapsed = std::chrono::duration_cast<std::chrono::milliseconds>(subEndTime - subStartTime);
ASCEND_LOGI("Create sub hccl comm by hcclCreateSubCommConfig success, group id is %s, subCommId is %llu, use %d ms.",
options_->group_id.c_str(), hcclid, subTimeElapsed.count());
logger->info("Create sub hccl comm by hcclCreateSubCommConfig success, group id is %s, subCommId is %llu, use %d ms.",
options_->group_id.c_str(), hcclid, subTimeElapsed.count());
ASCEND_LOGI("Create sub hccl comm by hcclCreateSubCommConfig success, group id is %s, subCommId is %llu, devicesKey is %s, use %d ms.",
options_->group_id.c_str(), hcclid, devicesKey.c_str(), subTimeElapsed.count());
logger->info("Create sub hccl comm by hcclCreateSubCommConfig success, group id is %s, subCommId is %llu, devicesKey is %s, use %d ms.",
options_->group_id.c_str(), hcclid, devicesKey.c_str(), subTimeElapsed.count());
return true;
}
@@ -2444,8 +2462,8 @@ std::vector<std::shared_ptr<HCCLComm>>& ProcessGroupHCCL::createHCCLComm(
std::vector<c10_npu::NPUStream> streamVal;
streamVal.reserve(devices.size());
if (!createHCCLCommEx(devices, commType, commConfig, hcclComms, streamVal, p2pRank)) {
createHCCLComm(devicesKey, devices, commType, commConfig, hcclComms, streamVal, p2pRank);
if (!createHCCLCommEx(devicesKey, devices, commType, commConfig, hcclComms, streamVal, p2pRank)) {
createHCCLCommOrigin(devicesKey, devices, commType, commConfig, hcclComms, streamVal, p2pRank);
}
hcclStreams_.emplace(devicesKey, std::move(streamVal));
@@ -3773,7 +3791,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allreduce(
std::vector<at::Tensor> tensors_cp = {tensors[0]};
std::string functionName = __FUNCTION__;
auto streamId = getStreamId(false, -1);
return collective(
tensors_cp,
tensors_cp,
@@ -3786,9 +3803,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allreduce(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(input);
auto hcclReduceOp = getHcclReduceOp(opts.reduceOp, input);
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAllreduce", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclAllreduce", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclAllReduce(
inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream.stream(false));
@@ -3831,7 +3848,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::batch_isend_irecv(
}
std::vector<at::Tensor> tensors_tmp = {tensors[0]};
auto streamId = getStreamId(false, -1);
return collective(
tensors_tmp,
tensors_tmp,
@@ -3846,7 +3862,7 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::batch_isend_irecv(
numel_list.push_back(getNumelForHCCL(tensors[i]));
type_list.push_back(getHcclDataType(tensors[i].scalar_type()));
}
auto hccl_call = [tensor_ptr_list, numel_list, type_list, remote_rank_list, op_type, itemNum, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [tensor_ptr_list, numel_list, type_list, remote_rank_list, op_type, itemNum, comm, stream, is_dispatched]() -> int {
HcclSendRecvItem sendRecvInfo[itemNum];
HcclSendRecvType currType;
for (size_t i = 0; i < op_type.size(); ++i) {
@@ -3865,7 +3881,7 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::batch_isend_irecv(
};
}
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclBatchSendRecv", sendRecvInfo[0].count, sendRecvInfo[0].dataType, comm, streamId, -1, -1),
getMstxHcclMsg("HcclBatchSendRecv", sendRecvInfo[0].count, sendRecvInfo[0].dataType, comm, stream.id(), -1, -1),
stream.stream(false), torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclBatchIsendIrecv(sendRecvInfo, itemNum, comm, stream.stream(false));
*is_dispatched = true;
@@ -3900,7 +3916,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::broadcast(
if (C10_UNLIKELY(at_npu::native::env::CheckOpHookEnable())) {
at_npu::native::OpHook::GetInstance().PreHook("broadcast", tensors);
}
auto streamId = getStreamId(false, -1);
return collective(
tensors,
tensors,
@@ -3911,9 +3926,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::broadcast(
auto inputDataPtr = input.data_ptr();
auto numel = getNumelForHCCL(input);
auto hcclType = getHcclDataType(input.scalar_type());
auto hccl_call = [inputDataPtr, numel, hcclType, root, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, numel, hcclType, root, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclBroadcast", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclBroadcast", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclBroadcast(inputDataPtr, numel, hcclType, root, comm, stream.stream(false));
*is_dispatched = true;
@@ -3947,7 +3962,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allreduce_coalesced(
check_npu_tensors_same_device(tensors);
std::vector<at::Tensor> tensors_cp = tensors;
std::string functionName = __FUNCTION__;
auto streamId = getStreamId(false, -1);
return collectiveCoalesced(
tensors_cp,
tensors_cp,
@@ -3960,9 +3974,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allreduce_coalesced(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(input);
auto hcclReduceOp = getHcclReduceOp(opts.reduceOp, input);
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAllreduce", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclAllreduce", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclAllReduce(
inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream.stream(false));
@@ -4015,7 +4029,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::reduce(
std::string functionName = __FUNCTION__;
uint64_t rank = opts.rootRank;
std::vector<at::Tensor> tensors_cp = {tensors[0]};
auto streamId = getStreamId(false, -1);
return collective(
tensors_cp,
tensors_cp,
@@ -4028,9 +4041,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::reduce(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(input);
auto reduceOp = getHcclReduceOp(opts.reduceOp, input);
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, reduceOp, rank, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, reduceOp, rank, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclReduce", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclReduce", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclReduce(
inputDataPtr, outputDataPtr, numel, hcclType, reduceOp, rank, comm, stream.stream(false));
@@ -4075,7 +4088,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_reduce_oop(
std::vector<at::Tensor> inputTensors = {inputTensor};
std::vector<at::Tensor> outputTensors = {outputTensor};
std::string functionName = __FUNCTION__;
auto streamId = getStreamId(false, -1);
return collective(
inputTensors,
outputTensors,
@@ -4088,9 +4100,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_reduce_oop(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(input);
auto reduceOp = getHcclReduceOp(opts.reduceOp, input);
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, reduceOp, rank, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, reduceOp, rank, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclReduce", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclReduce", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclReduce(
inputDataPtr, outputDataPtr, numel, hcclType, reduceOp, rank, comm, stream.stream(false));
@@ -4187,7 +4199,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_reduce_scatter_base_uneven(
auto inputTensors_ = cast_to_origin_format(inputTensors);
auto outputTensors_ = cast_to_origin_format(outputTensors);
auto streamId = getStreamId(false, -1);
return collective(
inputTensors_,
outputTensors_,
@@ -4210,10 +4221,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_reduce_scatter_base_uneven(
numel,
comm,
stream,
is_dispatched,
streamId]() -> int {
is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclReduceScatterV", numel, hcclType, comm, streamId, -1, -1),
getMstxHcclMsg("HcclReduceScatterV", numel, hcclType, comm, stream.id(), -1, -1),
stream.stream(false), torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclReduceScatterV(
inputDataPtr,
@@ -4275,7 +4285,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_allgather_base_uneven(
auto inputTensors_ = cast_to_origin_format(inputTensors);
auto outputTensors_ = cast_to_origin_format(outputTensors);
auto streamId = getStreamId(false, -1);
return collective(
inputTensors_,
outputTensors_,
@@ -4296,10 +4305,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_allgather_base_uneven(
numel,
comm,
stream,
is_dispatched,
streamId]() -> int {
is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAllGatherV", numel, hcclType, comm, streamId, -1, -1),
getMstxHcclMsg("HcclAllGatherV", numel, hcclType, comm, stream.id(), -1, -1),
stream.stream(false), torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclAllGatherV(
inputDataPtr,
@@ -4354,7 +4362,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather(
auto outputFlattened =
flatten_for_scatter_gather(byte_alignment_outputTensors, byte_alignment_inputTensors_, size_);
check_npu_tensors_different_devices(outputFlattened);
auto streamId = getStreamId(false, -1);
return collective(
byte_alignment_inputTensors_,
outputFlattened,
@@ -4368,9 +4375,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(input);
auto hcclType = getHcclDataType(input.scalar_type());
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAllGather", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclAllGather", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclAllGather(inputDataPtr, outputDataPtr, numel, hcclType, comm, stream.stream(false));
*is_dispatched = true;
@@ -4425,7 +4432,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather(
}
std::vector<at::Tensor> inputFlattened = {at::flatten(inputTensors[0])};
std::vector<at::Tensor> outputFlattened = {at::cat(flattenedOutputTensors, 0)};
auto streamId = getStreamId(false, -1);
return collective(
inputFlattened,
outputFlattened,
@@ -4446,10 +4452,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather(
numel,
comm,
stream,
is_dispatched,
streamId]() -> int {
is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAllGatherV", numel, hcclType, comm, streamId, -1, -1),
getMstxHcclMsg("HcclAllGatherV", numel, hcclType, comm, stream.id(), -1, -1),
stream.stream(false), torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclAllGatherV(
inputDataPtr,
@@ -4500,7 +4505,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather(
const auto num_devices = outputTensors.size();
const auto num_reduces = outputTensors[0].size();
std::vector<c10::intrusive_ptr<c10d::Work>> works;
auto streamId = getStreamId(false, -1);
// Need to add a method like startCoalescing();
for (const auto i : c10::irange(num_reduces)) {
std::vector<at::Tensor> inputs_multi_dev(num_devices);
@@ -4525,7 +4529,7 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather(
auto numel = getNumelForHCCL(input);
auto hcclType = getHcclDataType(input.scalar_type());
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclBroadcast", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclBroadcast", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclBroadcast(inputDataPtr, numel, hcclType, root, comm, stream.stream());
*is_dispatched = true;
@@ -4550,7 +4554,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather_into_tensor_coalesced
const c10d::AllgatherOptions& opts)
{
auto inputTensors_ = cast_to_origin_format(inputs);
auto streamId = getStreamId(false, -1);
return collectiveCoalesced(
inputTensors_,
outputs,
@@ -4563,9 +4566,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather_into_tensor_coalesced
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(input);
auto hcclType = getHcclDataType(input.scalar_type());
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAllGather", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclAllGather", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclAllGather(inputDataPtr, outputDataPtr, numel, hcclType, comm, stream.stream(false));
*is_dispatched = true;
@@ -4596,7 +4599,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather_togather(
}
auto inputTensors_ = cast_to_origin_format(inputTensors);
auto streamId = getStreamId(false, -1);
return collective(
inputTensors_,
outputTensors,
@@ -4609,9 +4611,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::allgather_togather(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(input);
auto hcclType = getHcclDataType(input.scalar_type());
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAllGather", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclAllGather", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclAllGather(inputDataPtr, outputDataPtr, numel, hcclType, comm, stream.stream(false));
*is_dispatched = true;
@@ -4647,7 +4649,7 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_allgather_base(
}
auto inputTensors_ = cast_to_origin_format(inputTensors);
auto streamId = getStreamId(false, -1);
return collective(
inputTensors_,
outputTensors,
@@ -4660,9 +4662,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_allgather_base(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(input);
auto hcclType = getHcclDataType(input.scalar_type());
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAllGather", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclAllGather", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclAllGather(inputDataPtr, outputDataPtr, numel, hcclType, comm, stream.stream(false));
*is_dispatched = true;
@@ -4687,7 +4689,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::reduce_scatter(
if (C10_UNLIKELY(at_npu::native::env::CheckOpHookEnable())) {
at_npu::native::OpHook::GetInstance().PreHook("reduce_scatter", outputTensors, inputTensors);
}
auto streamId = getStreamId(false, -1);
bool same_size = check_same_size(inputTensors.back());
if (same_size) {
auto inputFlattened = flatten_for_scatter_gather(inputTensors, outputTensors, size_);
@@ -4707,9 +4708,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::reduce_scatter(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(output);
auto hcclReduceOp = getHcclReduceOp(opts.reduceOp, input);
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclReduceScatter", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclReduceScatter", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclReduceScatter(
inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream.stream(false));
@@ -4789,10 +4790,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::reduce_scatter(
numel,
comm,
stream,
is_dispatched,
streamId]() -> int {
is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclReduceScatterV", numel, hcclType, comm, streamId, -1, -1),
getMstxHcclMsg("HcclReduceScatterV", numel, hcclType, comm, stream.id(), -1, -1),
stream.stream(false), torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclReduceScatterV(
inputDataPtr,
@@ -4887,7 +4887,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_reduce_scatter_base(
if (C10_UNLIKELY(at_npu::native::env::CheckOpHookEnable())) {
at_npu::native::OpHook::GetInstance().PreHook("_reduce_scatter_base", outputs, inputs);
}
auto streamId = getStreamId(false, -1);
std::string functionName = __FUNCTION__;
return collective(
inputs,
@@ -4903,9 +4902,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::_reduce_scatter_base(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(output);
auto hcclReduceOp = getHcclReduceOp(opts.reduceOp, input);
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclReduceScatter", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclReduceScatter", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclReduceScatter(
inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream.stream(false));
@@ -4934,7 +4933,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::reduce_scatter_tensor_coalesced
const c10d::ReduceScatterOptions& opts)
{
std::string functionName = __FUNCTION__;
auto streamId = getStreamId(false, -1);
return collectiveCoalesced(
inputTensors,
outputTensors,
@@ -4949,9 +4947,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::reduce_scatter_tensor_coalesced
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(output);
auto hcclReduceOp = getHcclReduceOp(opts.reduceOp, input);
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclReduceScatter", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclReduceScatter", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclReduceScatter(
inputDataPtr, outputDataPtr, numel, hcclType, hcclReduceOp, comm, stream.stream(false));
@@ -5071,7 +5069,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::scatter(
inputTensors.push_back(empty);
inputFlattened = flatten_for_scatter_gather(inputTensors, outputTensors, size_);
}
auto streamId = getStreamId(false, -1);
return collective(
inputFlattened,
outputTensors,
@@ -5085,9 +5082,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::scatter(
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(output);
auto hcclType = getHcclDataType(input.scalar_type());
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, root, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, outputDataPtr, numel, hcclType, root, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclScatter", numel, hcclType, comm, streamId, -1, -1), stream.stream(false),
getMstxHcclMsg("HcclScatter", numel, hcclType, comm, stream.id(), -1, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclScatter(inputDataPtr, outputDataPtr, numel, hcclType, root, comm, stream.stream(false));
*is_dispatched = true;
@@ -5128,7 +5125,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::send(std::vector<at::Tensor>& t
if (C10_UNLIKELY(at_npu::native::env::CheckOpHookEnable())) {
at_npu::native::OpHook::GetInstance().PreHook("send", tensors);
}
auto streamId = getStreamId(true, dstRank);
auto tensors_ = cast_to_origin_format(tensors);
auto ret = pointToPoint(
tensors_,
@@ -5137,9 +5133,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::send(std::vector<at::Tensor>& t
auto inputDataPtr = input.data_ptr();
auto numel = getNumelForHCCL(input);
auto hcclType = getHcclDataType(input.scalar_type());
auto hccl_call = [inputDataPtr, numel, hcclType, dst_rank, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [inputDataPtr, numel, hcclType, dst_rank, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclSend", numel, hcclType, comm, streamId, -1, dst_rank), stream.stream(false),
getMstxHcclMsg("HcclSend", numel, hcclType, comm, stream.id(), -1, dst_rank), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclSend(inputDataPtr, numel, hcclType, static_cast<uint32_t>(dst_rank), comm, stream.stream(false));
*is_dispatched = true;
@@ -5160,7 +5156,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::recv(std::vector<at::Tensor>& t
if (C10_UNLIKELY(at_npu::native::env::CheckOpHookEnable())) {
at_npu::native::OpHook::GetInstance().PreHook("recv", tensors);
}
auto streamId = getStreamId(true, srcRank);
auto tensors_ = create_base_format_tensors(tensors);
auto ret = pointToPoint(
tensors_,
@@ -5172,9 +5167,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::recv(std::vector<at::Tensor>& t
auto outputDataPtr = output.data_ptr();
auto numel = getNumelForHCCL(output);
auto hcclType = getHcclDataType(output.scalar_type());
auto hccl_call = [outputDataPtr, numel, hcclType, src_rank, comm, stream, is_dispatched, streamId]() -> int {
auto hccl_call = [outputDataPtr, numel, hcclType, src_rank, comm, stream, is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclRecv", numel, hcclType, comm, streamId, src_rank, -1), stream.stream(false),
getMstxHcclMsg("HcclRecv", numel, hcclType, comm, stream.id(), src_rank, -1), stream.stream(false),
torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = HcclRecv(outputDataPtr, numel, hcclType, static_cast<uint32_t>(src_rank), comm, stream.stream(false));
*is_dispatched = true;
@@ -5246,7 +5241,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::alltoall_base(
DIST_ERROR(ErrCode::PARAM));
uint64_t output_counts = static_cast<uint64_t>(outputTensor.numel() / ranks);
uint64_t input_counts = static_cast<uint64_t>(inputTensor.numel() / ranks);
auto streamId = getStreamId(false, -1);
check_npu_tensors_different_devices(inputTensors);
check_npu_tensors_different_devices(outputTensors);
return collective(
@@ -5269,10 +5263,9 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::alltoall_base(
outputhcclDataType,
comm,
stream,
is_dispatched,
streamId]() -> int {
is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAlltoAll", input_counts, inputhcclDataType, comm, streamId, -1, -1),
getMstxHcclMsg("HcclAlltoAll", input_counts, inputhcclDataType, comm, stream.id(), -1, -1),
stream.stream(false), torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclAlltoAll(
inputDataPtr,
@@ -5346,7 +5339,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::alltoall_base(
inputSpl.push_back(inputSpl[i - 1] + inputCounts[i - 1]);
}
}
auto streamId = getStreamId(false, -1);
check_npu_tensors_different_devices(inputTensors);
check_npu_tensors_different_devices(outputTensors);
return collective(
@@ -5368,11 +5360,10 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::alltoall_base(
outputhcclDataType,
comm,
stream,
is_dispatched,
streamId]() -> int {
is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAlltoAllV", static_cast<uint64_t>(inputCounts.size()),
inputhcclDataType, comm, streamId, -1, -1),
inputhcclDataType, comm, stream.id(), -1, -1),
stream.stream(false), torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclAlltoAllV(
inputDataPtr,
@@ -5475,7 +5466,6 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::alltoall(
check_npu_tensors_different_devices(in_tensors);
check_npu_tensors_different_devices(out_tensors);
auto streamId = getStreamId(false, -1);
return collective(
input_tensors_,
output_tensors_,
@@ -5495,11 +5485,10 @@ c10::intrusive_ptr<c10d::Work> ProcessGroupHCCL::alltoall(
outputhcclDataType,
comm,
stream,
is_dispatched,
streamId]() -> int {
is_dispatched]() -> int {
torch_npu::profiler::MstxRange range(
getMstxHcclMsg("HcclAlltoAllV", static_cast<uint64_t>(input_counts.size()),
inputhcclDataType, comm, streamId, -1, -1),
inputhcclDataType, comm, stream.id(), -1, -1),
stream.stream(false), torch_npu::profiler::DOMAIN_COMMUNICATION);
auto hccl_result = hcclAlltoAllV(
inputDataPtr,
@@ -926,6 +926,8 @@ protected:
int peer_;
std::vector<uint32_t> global_ranks_in_group;
std::exception_ptr watchDogException_ = nullptr;
std::shared_ptr<ProcessGroupStatus> pgStatus_ = std::make_shared<ProcessGroupStatus>();
@@ -1003,7 +1005,7 @@ private:
HcclCommConfig* commConfig = nullptr,
int p2pRank = 0);
void createHCCLComm(
void createHCCLCommOrigin(
const std::string& devicesKey,
const std::vector<at::Device>& devices,
HcclCommType commType,
@@ -1013,6 +1015,7 @@ private:
int p2pRank);
bool createHCCLCommEx(
const std::string& devicesKey,
const std::vector<at::Device>& devices,
HcclCommType commType,
HcclCommConfig* commConfig,
+1 -9
View File
@@ -191,18 +191,10 @@ void LazyInitAclops()
}
}
void InitAclopsCore()
{
SetPrecisionMode();
MakeCompileCacheDirAndSetOption();
GetAndSetDefaultJitCompileByAcl();
SetHF32DefaultValue();
}
void InitAclops()
{
RECORD_FUNCTION("InitAclops", std::vector<c10::IValue>({}));
InitAclopsCore();
LazyInitAclopsCore();
ASCEND_LOGI("Init for aclops finished.")
}
@@ -162,7 +162,7 @@ REGISTER_OPTION(MM_BMM_ND_ENABLE)
REGISTER_OPTION_BOOL_FUNCTION_UNIQ(CheckMmBmmNDDisable, MM_BMM_ND_ENABLE, "enable", "disable")
REGISTER_OPTION(ALLOW_INTERNAL_FORMAT)
REGISTER_OPTION_BOOL_FUNCTION_UNIQ(CheckForbidInternalFormat, ALLOW_INTERNAL_FORMAT, "enable", "disable")
REGISTER_OPTION_BOOL_FUNCTION(CheckForbidInternalFormat, ALLOW_INTERNAL_FORMAT, "enable", "disable")
REGISTER_OPTION_HOOK(ALLOW_CONV_HF32, [](const std::string &val) {
static const std::string mm_hf32_option_name = "ALLOW_MATMUL_HF32";
@@ -14,7 +14,7 @@ namespace native {
GET_FUNCTION(libmsprofiler, funcName)
REGISTER_LIBRARY(libmsprofiler)
REGISTER_LIBRARY(libmsprofiler, RTLD_LAZY | RTLD_GLOBAL)
LOAD_FUNCTION(aclprofWarmup)
LOAD_FUNCTION(aclprofSetConfig)
LOAD_FUNCTION(aclprofGetSupportedFeatures)
+3
View File
@@ -172,6 +172,7 @@ std::string _memory_snapshot_pickled()
c10::IValue requested_size_s = "requested_size";
c10::IValue stream_s = "stream";
c10::IValue segment_type_s = "segment_type";
c10::IValue segment_pool_id = "segment_pool_id";
c10::IValue large_s = "large";
c10::IValue small_s = "small";
c10::IValue size_s = "size";
@@ -213,6 +214,8 @@ std::string _memory_snapshot_pickled()
segmentDict.insert(stream_s, int64_t(segmentInfo.stream));
segmentDict.insert(segment_type_s,
(segmentInfo.is_large ? large_s : small_s));
segmentDict.insert(segment_pool_id,
std::tuple<int64_t, int64_t>(segmentInfo.owner_private_pool_id));
segmentDict.insert(is_expandable_s, segmentInfo.is_expandable);
add_frame_key(segmentDict, segmentInfo.context_when_allocated);
+2 -1
View File
@@ -13,7 +13,8 @@ namespace profiler {
const std::string DOMAIN_COMMUNICATION = "communication";
const std::string DOMAIN_DEFAULT = "default";
const std::string DOMAIN_MSLEAKS = "msleaks";
const std::string DOMAIN_CACHING = "ptaCaching";
const std::string DOMAIN_WORKSPACE = "ptaWorkspace";
class MstxMgr : public torch_npu::toolkit::profiler::Singleton<MstxMgr> {
friend class torch_npu::toolkit::profiler::Singleton<MstxMgr>;
+13 -13
View File
@@ -385,23 +385,23 @@ def stress_detect(mode=0):
warnings.warn("The torch.distributed should to be initialized for p2p detection.")
return 1
global hccl_detect_group
rank = int(os.getenv('RANK', -1))
local_world_size = int(os.getenv('LOCAL_WORLD_SIZE', -1))
if rank == -1 or local_world_size == -1:
warnings.warn("Environment variable 'RANK' or 'LOCAL_WORLD_SIZE' is not set.")
return 1
worker_index = rank // local_world_size
local_rank = rank % local_world_size
if hccl_detect_group is None:
rank = int(os.getenv('RANK', -1))
local_world_size = int(os.getenv('LOCAL_WORLD_SIZE', -1))
if rank == -1 or local_world_size == -1:
warnings.warn("Environment variable 'RANK' or 'LOCAL_WORLD_SIZE' is not set.")
return 1
worker_index = rank // local_world_size
local_rank = rank % local_world_size
local_ranks = []
for i in range(local_world_size):
local_ranks.append(local_world_size * worker_index + i)
try:
hccl_detect_group = torch.distributed.new_group(ranks=local_ranks)
comm = hccl_detect_group._get_backend(torch.device('npu')).get_hccl_comm(local_rank)
except Exception as err:
warnings.warn("Create local hccl group for p2p detection failed.")
return 1
hccl_detect_group = torch.distributed.new_group(ranks=local_ranks)
try:
comm = hccl_detect_group._get_backend(torch.device('npu')).get_hccl_comm(local_rank)
except Exception as err:
warnings.warn("Create local hccl group for p2p detection failed.")
return 1
return torch_npu._C._npu_stress_detect(mode, comm)
@@ -156,7 +156,9 @@ class ProfilerConfig:
self._rank_id = info_json.get(Constant.RANK_ID, -1)
def load_timediff_info(self, profiler_path: str, info_json: dict):
self._localtime_diff = CANNFileParser(profiler_path).get_localtime_diff()
if (Constant.NPU_ACTIVITIES in info_json.get(Constant.CONFIG, {}).get(Constant.COMMON_CONFIG, {})
.get(Constant.ACTIVITIES, [])):
self._localtime_diff = CANNFileParser(profiler_path).get_localtime_diff()
end_info = info_json.get(Constant.END_INFO, {})
if not self._localtime_diff and end_info:
self._localtime_diff = int(end_info.get(Constant.FWK_END_TIME, 0)) - int(
@@ -7,6 +7,7 @@ from .prof_common_func._cann_package_manager import CannPackageManager
from .prof_common_func._path_manager import ProfilerPathManager
from .prof_common_func._task_manager import ConcurrentTasksManager
from .prof_common_func._log import ProfilerLogger
from .prof_common_func._utils import no_exception_func
from .prof_config._parser_config import ParserConfig
from .prof_parse._cann_file_parser import CANNFileParser
from ._profiler_config import ProfilerConfig
@@ -31,13 +32,14 @@ class ProfilingParser:
@staticmethod
def simplify_data(profiler_path: str, simplify_flag: bool):
cann_path = ProfilerPathManager.get_cann_path(profiler_path)
device_path = ProfilerPathManager.get_device_path(cann_path)
device_paths = ProfilerPathManager.get_device_path(cann_path)
host_path = ProfilerPathManager.get_host_path(cann_path)
rm_dirs = ['sqlite', 'summary', 'timeline'] if simplify_flag else ['sqlite']
for rm_dir in rm_dirs:
if device_path:
target_path = os.path.join(device_path, rm_dir)
PathManager.remove_path_safety(target_path)
if device_paths:
for device_path in device_paths:
target_path = os.path.join(device_path, rm_dir)
PathManager.remove_path_safety(target_path)
if host_path:
target_path = os.path.join(host_path, rm_dir)
PathManager.remove_path_safety(target_path)
@@ -82,6 +84,7 @@ class ProfilingParser:
if re.match(patten, filename) and os.path.isfile(os.path.join(cann_path, filename)):
PathManager.remove_file_safety(os.path.join(cann_path, filename))
@no_exception_func()
def analyse_profiling_data(self):
ProfilerLogger.init(self._profiler_path, "ProfilingParser")
self.logger = ProfilerLogger.get_instance()
@@ -43,5 +43,5 @@ class GeMemoryRecordBean(CommonBean):
return None
@property
def device_tag(self) -> float:
def device_tag(self) -> str:
return self._data.get("Device", "")
@@ -35,6 +35,7 @@ class MemoryUseBean(CommonBean):
def __init__(self, data: dict):
super().__init__(data)
self._constant_data = struct.unpack(self.CONSTANT_STRUCT, self._data.get(Constant.CONSTANT_BYTES))
self._device_index = -1
@property
def ptr(self) -> int:
@@ -87,7 +88,12 @@ class MemoryUseBean(CommonBean):
@property
def device_index(self) -> int:
return int(self._constant_data[MemoryEnum.DEVICE_INDEX.value])
return (self._device_index if self._device_index != -1 else
int(self._constant_data[MemoryEnum.DEVICE_INDEX.value]))
@device_index.setter
def device_index(self, value: int) -> None:
self._device_index = value
@property
def component_type(self) -> int:
@@ -102,6 +102,7 @@ class Constant(object):
RANK_ID = "rank_id"
COMMON_CONFIG = "common_config"
ACTIVITIES = "activities"
NPU_ACTIVITIES = "ProfilerActivity.NPU"
EXPERIMENTAL_CONFIG = "experimental_config"
PROFILER_LEVEL = '_profiler_level'
AI_CORE_METRICS = '_aic_metrics'
@@ -60,61 +60,49 @@ class ProfilerPathManager:
return ""
@classmethod
def get_device_path(cls, cann_path: str) -> str:
def get_device_path(cls, cann_path: str) -> list:
device_paths = []
sub_dirs = os.listdir(os.path.realpath(cann_path))
for sub_dir in sub_dirs:
sub_path = os.path.join(cann_path, sub_dir)
if os.path.isdir(sub_path) and re.match(r"^device_\d", sub_dir):
return sub_path
return ""
device_paths.append(sub_path)
return device_paths
@classmethod
def get_device_id(cls, cann_path: str) -> int:
def get_device_id(cls, cann_path: str) -> list:
if not cann_path:
return Constant.INVALID_VALUE
device_path = cls.get_device_path(cann_path)
if not device_path:
return Constant.INVALID_VALUE
device_path_split = os.path.basename(device_path).split("_")
if len(device_path_split) != 2:
return Constant.INVALID_VALUE
if not device_path_split[1].isdigit:
return Constant.INVALID_VALUE
return int(device_path_split[1])
return []
device_paths = cls.get_device_path(cann_path)
if not device_paths:
return []
device_id_list = []
for device_path in device_paths:
device_path_split = os.path.basename(device_path).split("_")
if len(device_path_split) != 2:
return []
if not device_path_split[1].isdigit():
return []
device_id_list.append(int(device_path_split[1]))
return device_id_list
@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:
device_paths = cls.get_device_path(cann_path)
if not device_paths:
return ""
device_path_split = os.path.basename(device_path).split("_")
device_path_split = os.path.basename(device_paths[0]).split("_")
if len(device_path_split) != 2:
return ""
start_info_file = f"start_info.{device_path_split[1]}"
start_info_path = os.path.join(device_path, start_info_file)
start_info_path = os.path.join(device_paths[0], start_info_file)
if os.path.exists(start_info_path):
return start_info_path
return ""
@classmethod
def get_feature_json_path(cls, profiler_path: str) -> str:
cann_path = cls.get_cann_path(profiler_path)
if cann_path is None:
return ""
device_path = cls.get_host_path(cann_path)
if not device_path:
device_path = cls.get_device_path(cann_path)
if not device_path:
return ""
sub_files = os.listdir(device_path)
for sub_file in sub_files:
if sub_file == "incompatible_features.json":
return os.path.join(device_path, sub_file)
return ""
@classmethod
def get_profiler_path_list(cls, input_path: str) -> list:
@@ -195,14 +195,15 @@ class CANNFileParser:
return localtime_diff
def del_summary_and_timeline_data(self):
device_path = ProfilerPathManager.get_device_path(self._cann_path)
if not device_path:
device_paths = ProfilerPathManager.get_device_path(self._cann_path)
if not device_paths:
self.logger.error("Delete summary and timeline data failed, the device path is not exist.")
return
summary_path = os.path.join(device_path, "summary")
timeline_path = os.path.join(device_path, "timeline")
PathManager.remove_path_safety(summary_path)
PathManager.remove_path_safety(timeline_path)
for device_path in device_paths:
summary_path = os.path.join(device_path, "summary")
timeline_path = os.path.join(device_path, "timeline")
PathManager.remove_path_safety(summary_path)
PathManager.remove_path_safety(timeline_path)
def del_output_path_data(self):
output_path = os.path.join(self._cann_path, self.MINDSTUDIO_PROFILER_OUTPUT)
@@ -332,7 +332,12 @@ class FwkFileParser:
if not gc_events:
return []
cann_path = ProfilerPathManager.get_cann_path(self._profiler_path)
device_id = ProfilerPathManager.get_device_id(cann_path)
device_ids = ProfilerPathManager.get_device_id(cann_path)
device_id = None
if not device_ids:
device_id = Constant.INVALID_VALUE
else:
device_id = device_ids[0]
event_list = [None] * len(gc_events)
for idx, event in enumerate(gc_events):
event.pid = TraceEventManager.get_pid_format(event.pid, TraceEventManager.GC_SORT_INDEX, device_id)
@@ -198,6 +198,9 @@ class MemoryPrepareParser(BaseParser):
def _complete_record_entry(self, ptr_records: list, torch_ops: list) -> list:
ret_list = list()
cann_path = ProfilerPathManager.get_cann_path(self._profiler_path)
device_ids = ProfilerPathManager.get_device_id(cann_path)
device_tag = "NPU:" + str(device_ids[0]) if len(device_ids) == 1 else ""
torch_ops = [torch_op for torch_op in torch_ops if torch_op.name != "empty_tensor" and torch_op.name != "malloc_workspace"]
for records in ptr_records:
combine_data = list()
@@ -215,7 +218,7 @@ class MemoryPrepareParser(BaseParser):
combine_data = [op_name, records[0].alloc_size, convert_ns2us_str(records[0].time_ns, "\t"), None, None, None, None,
records[0].total_allocated, records[0].total_reserved, records[0].total_active,
None, None, None,
records[0].stream_ptr, records[0].device_tag]
records[0].stream_ptr, device_tag or records[0].device_tag]
elif records_len == 2:
if hasattr(records[0], 'component_type') and records[0].component_type == Constant.CACHING_TYPE:
self._incomplete_num += 1
@@ -226,7 +229,7 @@ class MemoryPrepareParser(BaseParser):
combine_data = [op_name, records[0].alloc_size, convert_ns2us_str(records[0].time_ns, "\t"), release_time, active_release_time, duration_time,
active_duration_time, records[0].total_allocated, records[0].total_reserved, records[0].total_active,
records[1].total_allocated, records[1].total_reserved, records[1].total_active,
records[0].stream_ptr, records[0].device_tag]
records[0].stream_ptr, device_tag or records[0].device_tag]
elif records_len == 3:
free_idx = 1 if records[1].data_type == Constant.MEMORY_FREE else 2
active_idx = 1 if free_idx == 2 else 2
@@ -237,12 +240,15 @@ class MemoryPrepareParser(BaseParser):
combine_data = [op_name, records[0].alloc_size, convert_ns2us_str(records[0].time_ns, "\t"), release_time, active_release_time, duration_time,
active_duration_time, records[0].total_allocated, records[0].total_reserved, records[0].total_active,
records[free_idx].total_allocated, records[free_idx].total_reserved, records[free_idx].total_active,
records[0].stream_ptr, records[0].device_tag]
records[0].stream_ptr, device_tag or records[0].device_tag]
ret_list.append(combine_data[:])
return ret_list
def _complete_record_entry_for_db(self, ptr_records: list, torch_ops: list) -> list:
ret_list = list()
cann_path = ProfilerPathManager.get_cann_path(self._profiler_path)
device_ids = ProfilerPathManager.get_device_id(cann_path)
device_index = device_ids[0] if len(device_ids) == 1 else -1
torch_ops = [torch_op for torch_op in torch_ops if torch_op.name != "empty_tensor" and torch_op.name != "malloc_workspace"]
for records in ptr_records:
combine_data = list()
@@ -260,7 +266,7 @@ class MemoryPrepareParser(BaseParser):
combine_data = [op_name, records[0].alloc_size_for_db, records[0].time_ns, None, None, None, None,
records[0].total_allocated_for_db, records[0].total_reserved_for_db, records[0].total_active_for_db,
None, None, None,
records[0].stream_ptr, records[0].device_index]
records[0].stream_ptr, device_index if device_index != -1 else records[0].device_index]
elif records_len == 2:
if hasattr(records[0], 'component_type') and records[0].component_type == Constant.CACHING_TYPE:
self._incomplete_num += 1
@@ -271,7 +277,7 @@ class MemoryPrepareParser(BaseParser):
combine_data = [op_name, records[0].alloc_size_for_db, records[0].time_ns, release_time, active_release_time, duration_time,
active_duration_time, records[0].total_allocated_for_db, records[0].total_reserved_for_db, records[0].total_active_for_db,
records[1].total_allocated_for_db, records[1].total_reserved_for_db, records[1].total_active_for_db,
records[0].stream_ptr, records[0].device_index]
records[0].stream_ptr, device_index if device_index != -1 else records[0].device_index]
elif records_len == 3:
free_idx = 1 if records[1].data_type == Constant.MEMORY_FREE else 2
active_idx = 1 if free_idx == 2 else 2
@@ -280,7 +286,7 @@ class MemoryPrepareParser(BaseParser):
combine_data = [op_name, records[0].alloc_size_for_db, records[0].time_ns, records[free_idx].time_ns, records[active_idx].time_ns, duration_time,
active_duration_time, records[0].total_allocated_for_db, records[0].total_reserved_for_db, records[0].total_active_for_db,
records[free_idx].total_allocated_for_db, records[free_idx].total_reserved_for_db, records[free_idx].total_active_for_db,
records[0].stream_ptr, records[0].device_index]
records[0].stream_ptr, device_index if device_index != -1 else records[0].device_index]
ret_list.append(combine_data[:])
return ret_list
@@ -29,6 +29,7 @@ class MemoryViewParser(BaseParser):
def __init__(self, name: str, param_dict: dict):
super().__init__(name, param_dict)
self._activities = param_dict.get(Constant.ACTIVITIES, [])
self.size_record_list = []
self.pta_record_list = []
self.ge_record_list = []
@@ -57,12 +58,13 @@ class MemoryViewParser(BaseParser):
cur_record.stream_ptr, cur_record.device_tag]
return [cur_record_list]
cur_record_list = cur_record.row
if last_record:
if last_record.get(cur_record.device_tag):
last_record_data = last_record[cur_record.device_tag]
pta_ge_record_list = [Constant.PTA_GE, convert_ns2us_str(cur_record.time_ns, tail="\t"),
cur_record.total_allocated + last_record.total_allocated,
cur_record.total_reserved + last_record.total_reserved,
cur_record.total_active + last_record.total_active,
cur_record.stream_ptr if cur_record.stream_ptr else last_record.stream_ptr,
cur_record.total_allocated + last_record_data.total_allocated,
cur_record.total_reserved + last_record_data.total_reserved,
cur_record.total_active + last_record_data.total_active,
cur_record.stream_ptr if cur_record.stream_ptr else last_record_data.stream_ptr,
cur_record.device_tag]
else:
pta_ge_record_list = [Constant.PTA_GE, convert_ns2us_str(cur_record.time_ns, tail="\t"),
@@ -76,6 +78,9 @@ class MemoryViewParser(BaseParser):
try:
self.memory_data = deps_data.get(Constant.MEMORY_PREPARE, {}).get("memory_data", {}).get(Constant.Text, [])
self.pta_record_list = deps_data.get(Constant.MEMORY_PREPARE, {}).get("pta_record_list", [])
cann_path = ProfilerPathManager.get_cann_path(self._profiler_path)
device_ids = ProfilerPathManager.get_device_id(cann_path)
self.device_index = device_ids[0] if len(device_ids) == 1 else -1
self.generate_view()
except Exception as e:
self.logger.error("Failed to generate operator_memory.csv or memory_record.csv, error: %s", str(e), exc_info=True)
@@ -101,26 +106,28 @@ class MemoryViewParser(BaseParser):
raise RuntimeError(f"Can't sort records for cann memory record" + prof_error(ErrCode.INTERNAL)) from e
ge_ptr = 0
pta_ptr = 0
last_ge_record = None
last_pta_record = None
last_ge_record = {}
last_pta_record = {}
while ge_ptr < len(self.ge_record_list) and pta_ptr < len(self.pta_record_list):
ge_record = self.ge_record_list[ge_ptr]
pta_record = self.pta_record_list[pta_ptr]
pta_record.device_index = self.device_index
if ge_record.time_ns >= pta_record.time_ns:
self.size_record_list.extend(self._combine_record(last_ge_record, pta_record))
pta_ptr += 1
if hasattr(pta_record, 'component_type') and pta_record.component_type != Constant.WORKSPACE_TYPE:
last_pta_record = pta_record
last_pta_record[pta_record.device_tag] = pta_record
else:
self.size_record_list.extend(self._combine_record(last_pta_record, ge_record))
ge_ptr += 1
last_ge_record = ge_record
last_ge_record[ge_record.device_tag] = ge_record
while ge_ptr < len(self.ge_record_list):
ge_record = self.ge_record_list[ge_ptr]
self.size_record_list.extend(self._combine_record(last_pta_record, ge_record))
ge_ptr += 1
while pta_ptr < len(self.pta_record_list):
pta_record = self.pta_record_list[pta_ptr]
pta_record.device_index = self.device_index
self.size_record_list.extend(self._combine_record(last_ge_record, pta_record))
pta_ptr += 1
@@ -140,13 +147,16 @@ class MemoryViewParser(BaseParser):
"""
add ge memory and app memory from cann files
"""
npu_app_memory_file_set = CANNFileParser(self._profiler_path).get_file_list_by_type(CANNDataEnum.NPU_MEMORY)
npu_app_memory_file_set = CANNFileParser(self._profiler_path).get_file_list_by_type(CANNDataEnum.NPU_MEMORY) \
if Constant.NPU_ACTIVITIES in self._activities else set()
app_record_data = self._get_data_from_file(npu_app_memory_file_set, NpuMemoryBean)
self.size_record_list.extend(app_record_data)
self._add_device_type_for_npu()
ge_memory_record_file = CANNFileParser(self._profiler_path).get_file_list_by_type(CANNDataEnum.GE_MEMORY_RECORD)
ge_memory_record_file = CANNFileParser(self._profiler_path).get_file_list_by_type(CANNDataEnum.GE_MEMORY_RECORD) \
if Constant.NPU_ACTIVITIES in self._activities else set()
self.split_component_ge(self._get_data_from_file(ge_memory_record_file, GeMemoryRecordBean, bean_list=True))
ge_op_memory_file = CANNFileParser(self._profiler_path).get_file_list_by_type(CANNDataEnum.GE_OPERATOR_MEMORY)
ge_op_memory_file = CANNFileParser(self._profiler_path).get_file_list_by_type(CANNDataEnum.GE_OPERATOR_MEMORY) \
if Constant.NPU_ACTIVITIES in self._activities else set()
self.memory_data.extend(self._get_data_from_file(ge_op_memory_file, GeOpMemoryBean))
def _init_pta_data(self):
@@ -120,16 +120,21 @@ class CANNExportParser(BaseParser):
def _check_prof_data_size(self):
if not self._cann_path:
return
device_data_path = os.path.join(ProfilerPathManager.get_device_path(self._cann_path), "data")
host_data_path = os.path.join(self._cann_path, "host", "data")
device_paths = ProfilerPathManager.get_device_path(self._cann_path)
prof_data_size = 0
for root, dirs, files in os.walk(device_data_path):
host_data_path = os.path.join(self._cann_path, "host", "data")
for root, _, files in os.walk(host_data_path):
prof_data_size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
for root, dirs, files in os.walk(host_data_path):
prof_data_size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
if prof_data_size >= Constant.PROF_WARN_SIZE:
print_warn_msg("The parsing time is expected to exceed 30 minutes, "
"and you can choose to stop the process and use offline parsing.")
if not device_paths and prof_data_size < Constant.PROF_WARN_SIZE:
return
for device_path in device_paths:
device_data_path = os.path.join(device_path, "data")
for root, _, files in os.walk(device_data_path):
prof_data_size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
if prof_data_size >= Constant.PROF_WARN_SIZE:
print_warn_msg("The parsing time is expected to exceed 30 minutes, "
"and you can choose to stop the process and use offline parsing.")
return
class CANNTimelineParser(BaseParser):
@@ -60,10 +60,16 @@ class BasicDbParser(BaseParser):
def save_rank_info_to_db(self):
if ProfilerConfig().rank_id == -1:
return
device_ids = ProfilerPathManager.get_device_id(self._cann_path)
device_id = None
if len(device_ids) != 1:
device_id = Constant.INVALID_VALUE
else:
device_id = device_ids[0]
TorchDb().create_table_with_headers(DbConstant.TABLE_RANK_DEVICE_MAP,
TableColumnsManager.TableColumns.get(DbConstant.TABLE_RANK_DEVICE_MAP))
TorchDb().insert_data_into_table(DbConstant.TABLE_RANK_DEVICE_MAP,
[[ProfilerConfig().rank_id, ProfilerPathManager.get_device_id(self._cann_path)]])
[[ProfilerConfig().rank_id, device_id]])
def save_host_info_to_db(self):
if TorchDb().judge_table_exist(DbConstant.TABLE_HOST_INFO):
@@ -69,15 +69,19 @@ class MemoryDbParser(BaseParser):
return [cur_record]
pta_ge_record_list = cur_record[:]
pta_ge_record_list[MemoryRecordTableRow.COMPONENT.value] = Str2IdManager().get_id_from_str(Constant.PTA_GE)
if last_record:
pta_ge_record_list[MemoryRecordTableRow.TOTAL_ALLOCATED.value] = last_record[MemoryRecordTableRow.TOTAL_ALLOCATED.value] + cur_record[MemoryRecordTableRow.TOTAL_ALLOCATED.value]
pta_ge_record_list[MemoryRecordTableRow.TOTAL_RESERVED.value] = last_record[MemoryRecordTableRow.TOTAL_RESERVED.value] + cur_record[MemoryRecordTableRow.TOTAL_RESERVED.value]
pta_ge_record_list[MemoryRecordTableRow.TOTAL_ACTIVATE.value] = last_record[MemoryRecordTableRow.TOTAL_ACTIVATE.value] + cur_record[MemoryRecordTableRow.TOTAL_ACTIVATE.value]
if last_record.get(cur_record[MemoryRecordTableRow.DEVICE_ID.value]):
last_record_data = last_record[cur_record[MemoryRecordTableRow.DEVICE_ID.value]]
pta_ge_record_list[MemoryRecordTableRow.TOTAL_ALLOCATED.value] = last_record_data[MemoryRecordTableRow.TOTAL_ALLOCATED.value] + cur_record[MemoryRecordTableRow.TOTAL_ALLOCATED.value]
pta_ge_record_list[MemoryRecordTableRow.TOTAL_RESERVED.value] = last_record_data[MemoryRecordTableRow.TOTAL_RESERVED.value] + cur_record[MemoryRecordTableRow.TOTAL_RESERVED.value]
pta_ge_record_list[MemoryRecordTableRow.TOTAL_ACTIVATE.value] = last_record_data[MemoryRecordTableRow.TOTAL_ACTIVATE.value] + cur_record[MemoryRecordTableRow.TOTAL_ACTIVATE.value]
pta_ge_record_list[MemoryRecordTableRow.STREAM_PTR.value] = cur_record[MemoryRecordTableRow.STREAM_PTR.value] if cur_record[MemoryRecordTableRow.STREAM_PTR.value] else last_record[MemoryRecordTableRow.STREAM_PTR.value]
return [cur_record, pta_ge_record_list]
def run(self, deps_data: dict):
try:
cann_path = ProfilerPathManager.get_cann_path(self._profiler_path)
device_ids = ProfilerPathManager.get_device_id(cann_path)
self.device_index = device_ids[0] if len(device_ids) == 1 else -1
self.init_db_connect()
self.set_start_string_id()
self._pta_op_memory_data = deps_data.get(Constant.MEMORY_PREPARE, {}).get("memory_data", {}).get(Constant.Db, [])
@@ -185,12 +189,12 @@ class MemoryDbParser(BaseParser):
self._pta_record_list.append([Str2IdManager().get_id_from_str(Constant.WORKSPACE), memory_bean.time_ns,
memory_bean.total_allocated_for_db, memory_bean.total_reserved_for_db,
memory_bean.total_active_for_db, memory_bean.stream_ptr,
memory_bean.device_index])
continue
self._pta_record_list.append([Str2IdManager().get_id_from_str(Constant.PTA), memory_bean.time_ns,
memory_bean.total_allocated_for_db, memory_bean.total_reserved_for_db,
memory_bean.total_active_for_db, memory_bean.stream_ptr,
memory_bean.device_index])
self.device_index if self.device_index != -1 else memory_bean.device_index])
else:
self._pta_record_list.append([Str2IdManager().get_id_from_str(Constant.PTA), memory_bean.time_ns,
memory_bean.total_allocated_for_db, memory_bean.total_reserved_for_db,
memory_bean.total_active_for_db, memory_bean.stream_ptr,
self.device_index if self.device_index != -1 else memory_bean.device_index])
def get_pta_ge_record_list(self):
"""
@@ -204,8 +208,8 @@ class MemoryDbParser(BaseParser):
raise RuntimeError(f"Can't sort records for cann memory record") from e
ge_ptr = 0
pta_ptr = 0
last_ge_record = None
last_pta_record = None
last_ge_record = {}
last_pta_record = {}
while ge_ptr < len(self._ge_record_list) and pta_ptr < len(self._pta_record_list):
ge_record = self._ge_record_list[ge_ptr]
pta_record = self._pta_record_list[pta_ptr]
@@ -214,11 +218,11 @@ class MemoryDbParser(BaseParser):
pta_ptr += 1
if pta_record[MemoryRecordTableRow.COMPONENT.value] != \
Str2IdManager().get_id_from_str(Constant.WORKSPACE):
last_pta_record = pta_record
last_pta_record[pta_record[MemoryRecordTableRow.DEVICE_ID.value]] = pta_record
else:
self._record_list.extend(self._combine_record(last_pta_record, ge_record))
ge_ptr += 1
last_ge_record = ge_record
last_ge_record[ge_record[MemoryRecordTableRow.DEVICE_ID.value]] = ge_record
while ge_ptr < len(self._ge_record_list):
ge_record = self._ge_record_list[ge_ptr]
self._record_list.extend(self._combine_record(last_pta_record, ge_record))
+1
View File
@@ -575,3 +575,4 @@ def _add_serialization_methods():
torch.save = save
torch.load = load
torch.serialization._save = _npu_save
torch.serialization.add_safe_globals([torch_npu.utils.storage._rebuild_npu_tensor])
+51 -4
View File
@@ -1,9 +1,14 @@
__all__ = []
import copy
from typing import Any, Dict
from collections import OrderedDict
from typing import Union
import torch
from torch.storage import _warn_typed_storage_removal
from torch.overrides import has_torch_function_unary, handle_torch_function
from torch._namedtensor_internals import check_serializing_named_tensor
import torch_npu
from . import serialization as se
@@ -11,12 +16,13 @@ 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."
"Warning: The current version of the file storing weights is old, "
"and it is relanded due to internal bug of torch and compatibility issue. "
"We will deprecate the loading support for this type of file in the future, "
"please use 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 = torch.tensor([], dtype=storage.dtype, device=storage._untyped_storage.device)
tensor.set_(storage, storage_offset, size, stride)
tensor.requires_grad = requires_grad
tensor._backward_hooks = backward_hooks
@@ -28,6 +34,47 @@ def _rebuild_npu_tensor(storage, storage_offset, size, stride, requires_grad, ba
return tensor
def _reduce_ex(self, proto):
materialize_fake_tensors = (
torch.serialization._serialization_tls.materialize_fake_tensors
)
state = torch._utils._get_obj_state(self)
# Ignore all state when using FakeTensor with skip_data(materialize_fake_tensors) because FakeTensor has
# some state that cannot be pickled
if (
# will remove hasattr, it's a hack to support versions of torch that don't have _subclasses
hasattr(torch, "_subclasses")
and isinstance(self, torch._subclasses.fake_tensor.FakeTensor)
and materialize_fake_tensors
) or (isinstance(self, torch.Tensor) and not state):
# For npu tensor with internal format
check_serializing_named_tensor(self)
torch.utils.hooks.warn_if_has_hooks(self)
backward_hooks: Dict[Any, Any] = OrderedDict()
if self.device.type == "npu":
npu_storage_format = torch_npu.get_npu_format(self)
tmp_tensor = self.cpu()
arg_npu = (
tmp_tensor.storage() if has_torch_function_unary(tmp_tensor) else tmp_tensor._typed_storage(),
tmp_tensor.storage_offset(),
tuple(tmp_tensor.size()),
tmp_tensor.stride(),
tmp_tensor.requires_grad,
backward_hooks,
npu_storage_format
)
return _rebuild_npu_tensor, arg_npu
# Fast path for regular tensor without Python state.
return self._reduce_ex_internal(proto)
if has_torch_function_unary(self):
return handle_torch_function(torch.Tensor.__reduce_ex__, (self,), self, proto)
func, args = self._reduce_ex_internal(proto)
# sizes / strides cache needs to be cleared here because it'll just be re-cached
# if cleared earlier. Note that state references the -actual- tensor dict.
self._clear_non_serializable_cached_data()
return torch._tensor._rebuild_from_type_v2, (func, type(self), args, state)
def _cpu(self):
"""Returns a CPU copy of this storage if it's not already on the CPU"""
if self.device.type != 'cpu':
+2
View File
@@ -4,6 +4,7 @@ import torch
import torch_npu
from torch_npu.utils._error_code import ErrCode, pta_error
from torch_npu.utils.storage import _reduce_ex
__all__ = []
@@ -84,3 +85,4 @@ def _npu_type(self, dtype=None, non_blocking=False, **kwargs):
def _add_tensor_methods():
torch.Tensor.type_raw = torch.Tensor.type
torch.Tensor.type = _npu_type
torch.Tensor.__reduce_ex__ = _reduce_ex