Compare commits
279
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
def4860713 | ||
|
|
5cbbf7528f | ||
|
|
c7d1a98ad6 | ||
|
|
954eb11ee7 | ||
|
|
1781ef172a | ||
|
|
f036e87018 | ||
|
|
05477639fb | ||
|
|
a552e674ff | ||
|
|
d3174fa195 | ||
|
|
2da2908350 | ||
|
|
9ac3362edf | ||
|
|
1fe4d73471 | ||
|
|
e989949a0a | ||
|
|
1e040ce261 | ||
|
|
d886740a31 | ||
|
|
94eb3aebe9 | ||
|
|
3c496912c9 | ||
|
|
d09a70987c | ||
|
|
4d9efe9671 | ||
|
|
a81c86c878 | ||
|
|
f906117291 | ||
|
|
8e50f3a240 | ||
|
|
77201f1326 | ||
|
|
7920f1528f | ||
|
|
2820b8b045 | ||
|
|
13a910fe66 | ||
|
|
9fd3119605 | ||
|
|
44552280e9 | ||
|
|
f14f8de89d | ||
|
|
5b885328f4 | ||
|
|
f479d34f52 | ||
|
|
57f1c33737 | ||
|
|
e8f76c5a5b | ||
|
|
e4a6ae5f86 | ||
|
|
82d256052c | ||
|
|
d77cf8901e | ||
|
|
19f53d0cdd | ||
|
|
1b3260056a | ||
|
|
4b9f9edaf0 | ||
|
|
a26ffba94d | ||
|
|
767a7d0315 | ||
|
|
a0305500cb | ||
|
|
513f301ed7 | ||
|
|
0d987021d3 | ||
|
|
fbee5944a4 | ||
|
|
1e7d9eae0d | ||
|
|
bdaf0714f0 | ||
|
|
16bc32f027 | ||
|
|
c8b77d6a4e | ||
|
|
6d6307c2c1 | ||
|
|
edb96f0d0c | ||
|
|
ca339b9153 | ||
|
|
ebda745d8a | ||
|
|
74be9d1df3 | ||
|
|
db995a539d | ||
|
|
a59e9a2b6d | ||
|
|
6059f22dca | ||
|
|
42285ae9c3 | ||
|
|
77b8a9d9be | ||
|
|
81d01ab4d5 | ||
|
|
10d266aa60 | ||
|
|
67a1718d06 | ||
|
|
72866c1eeb | ||
|
|
4de195620b | ||
|
|
171cc86eec | ||
|
|
ae2d6ce952 | ||
|
|
32229f9b52 | ||
|
|
4215d0b648 | ||
|
|
d5e1e82541 | ||
|
|
d6d879b651 | ||
|
|
49f973e6d1 | ||
|
|
61fafbee84 | ||
|
|
1b8151cc66 | ||
|
|
c47baa1d6e | ||
|
|
3aeeea99c2 | ||
|
|
07359a1a5f | ||
|
|
c6010309f8 | ||
|
|
1fd2d7ef67 | ||
|
|
e395057332 | ||
|
|
100e583031 | ||
|
|
be4b147fe5 | ||
|
|
462428b88b | ||
|
|
515f0c232b | ||
|
|
1c17473870 | ||
|
|
b165496cd5 | ||
|
|
f90fdccb33 | ||
|
|
037341d87e | ||
|
|
6586187b07 | ||
|
|
cb95229fb6 | ||
|
|
156e6f8541 | ||
|
|
b624e1b004 | ||
|
|
f5b99cbed1 | ||
|
|
2d55ab55b5 | ||
|
|
04a00119bb | ||
|
|
14fdbd02f6 | ||
|
|
7c94f8f7bd | ||
|
|
8dad3fa352 | ||
|
|
84859164ee | ||
|
|
438bf52938 | ||
|
|
d4bb09d79f | ||
|
|
dfb5340fa1 | ||
|
|
7bbcfd5ae3 | ||
|
|
3ce9732805 | ||
|
|
7a0e214911 | ||
|
|
c41fa1f0b8 | ||
|
|
57f75c92ce | ||
|
|
c813a5cee6 | ||
|
|
458383e084 | ||
|
|
231f9960b8 | ||
|
|
de05b47f96 | ||
|
|
ec0450c0ce | ||
|
|
36fcc082b1 | ||
|
|
ed6310db2b | ||
|
|
2167e34a19 | ||
|
|
ce7dc2cbc0 | ||
|
|
dfdb222532 | ||
|
|
3a50eea889 | ||
|
|
c4a8892f3c | ||
|
|
1b04447a8a | ||
|
|
399f6a3efa | ||
|
|
31d4ed49f5 | ||
|
|
44fa8c2c00 | ||
|
|
a9bd5716e0 | ||
|
|
64cb7236dc | ||
|
|
c09c71fb72 | ||
|
|
603efbe980 | ||
|
|
e4626e37d9 | ||
|
|
3d947d67f3 | ||
|
|
c94019fb7b | ||
|
|
a91f40d511 | ||
|
|
1fd823e09d | ||
|
|
1f268969af | ||
|
|
3fc2a0d826 | ||
|
|
8bc882031a | ||
|
|
b41d3a92b6 | ||
|
|
26de7833f4 | ||
|
|
82429a1ad5 | ||
|
|
88c999ff08 | ||
|
|
afe7ee8484 | ||
|
|
eb809396f2 | ||
|
|
436c5cbad1 | ||
|
|
dbe7a336c7 | ||
|
|
f47a319700 | ||
|
|
975d468477 | ||
|
|
15bd6c0859 | ||
|
|
a9a107dcf7 | ||
|
|
874ef4572f | ||
|
|
46a51cb087 | ||
|
|
81cd74883d | ||
|
|
006a7a7b00 | ||
|
|
d80823cf2a | ||
|
|
d4e3de5045 | ||
|
|
5839de1079 | ||
|
|
7196887c9f | ||
|
|
2381355981 | ||
|
|
35e354f3c6 | ||
|
|
716340ef9c | ||
|
|
e790c85b98 | ||
|
|
053a5e4a12 | ||
|
|
6de027309b | ||
|
|
d3423e5883 | ||
|
|
870a1b0a7e | ||
|
|
d8cb66db6c | ||
|
|
b8cf32ac2e | ||
|
|
5c202d1b21 | ||
|
|
8e9bfa90bb | ||
|
|
c3de2db316 | ||
|
|
0a0f9d7c46 | ||
|
|
7e09784ef5 | ||
|
|
e6143afb94 | ||
|
|
e12b3c4e0f | ||
|
|
ce99958678 | ||
|
|
fc6bebf75b | ||
|
|
beb989e538 | ||
|
|
f67ae07cfd | ||
|
|
3a818bec30 | ||
|
|
d830ca5f73 | ||
|
|
167d0f51a9 | ||
|
|
67d44b8818 | ||
|
|
5d628b696f | ||
|
|
fd4e8ff226 | ||
|
|
3e0de91a84 | ||
|
|
9de3fab5a8 | ||
|
|
21c864c420 | ||
|
|
38476d6389 | ||
|
|
e21f023388 | ||
|
|
f2e3f542c9 | ||
|
|
949b683eb4 | ||
|
|
53160a1a18 | ||
|
|
a6f8314bc3 | ||
|
|
a2c77654e0 | ||
|
|
463fa51732 | ||
|
|
a51551e510 | ||
|
|
740394cb26 | ||
|
|
ccacaca73c | ||
|
|
993571cd9c | ||
|
|
981d7341f8 | ||
|
|
326e09ca98 | ||
|
|
9e5856c5d7 | ||
|
|
7d1aa8d3e9 | ||
|
|
599df48aea | ||
|
|
72cd73ef50 | ||
|
|
cb93b78fc9 | ||
|
|
83e2436238 | ||
|
|
26664c26e8 | ||
|
|
0e805889f2 | ||
|
|
b156904752 | ||
|
|
c4866cac6c | ||
|
|
2e54530945 | ||
|
|
abd77adec8 | ||
|
|
70fe84c516 | ||
|
|
4312ef92db | ||
|
|
19289951b9 | ||
|
|
8d8927d52a | ||
|
|
62240499f3 | ||
|
|
d0b5cc84b7 | ||
|
|
912ec4a2a9 | ||
|
|
16614314fa | ||
|
|
dcf9fcab7e | ||
|
|
9f5ac12056 | ||
|
|
8707e5b82d | ||
|
|
b30c994c24 | ||
|
|
17edd4e485 | ||
|
|
c21766125e | ||
|
|
1fbb06aa10 | ||
|
|
d98b3a8141 | ||
|
|
4f5bd6d15e | ||
|
|
e2d784c5c7 | ||
|
|
5b357efeaf | ||
|
|
d5538db893 | ||
|
|
137d07f480 | ||
|
|
9584c16326 | ||
|
|
0855b577c5 | ||
|
|
0625b54f92 | ||
|
|
6ecf92c62c | ||
|
|
6c35a6aca4 | ||
|
|
0ddd9c641b | ||
|
|
e7e9b3c747 | ||
|
|
2be7dbe54e | ||
|
|
c54de958bb | ||
|
|
09f8fa623e | ||
|
|
f63deee169 | ||
|
|
de3c39d607 | ||
|
|
5d5cf39a96 | ||
|
|
bdbde158cd | ||
|
|
3689e3c394 | ||
|
|
d85991f316 | ||
|
|
e5b6041e60 | ||
|
|
65de547be1 | ||
|
|
43a33f7d90 | ||
|
|
5ff40e7ffc | ||
|
|
0f9a35c27d | ||
|
|
6f4e1e803b | ||
|
|
82fcb1583e | ||
|
|
d15516089d | ||
|
|
a2e91d057d | ||
|
|
f96db4129f | ||
|
|
0de9a200a2 | ||
|
|
87eec1fad0 | ||
|
|
67b2b26c8b | ||
|
|
420092b49a | ||
|
|
7cb1c95500 | ||
|
|
090d1a0bf9 | ||
|
|
931b2d90ec | ||
|
|
ae67dca561 | ||
|
|
8eac3cda88 | ||
|
|
f9618a45c3 | ||
|
|
8549824c8f | ||
|
|
961e6878c6 | ||
|
|
adc3e0d5af | ||
|
|
1c55855995 | ||
|
|
ce6abb612a | ||
|
|
01c6d01fa8 | ||
|
|
72ae81096d | ||
|
|
1163a3b286 | ||
|
|
25095a50e2 | ||
|
|
e0c1433c7b | ||
|
|
17e72cfeb1 | ||
|
|
3a61f0d312 |
+4
-2
@@ -1,16 +1,18 @@
|
||||
[submodule "third_party/op-plugin"]
|
||||
path = third_party/op-plugin
|
||||
url = https://gitee.com/ascend/op-plugin.git
|
||||
url = https://gitcode.com/ascend/op-plugin.git
|
||||
ignore = dirty
|
||||
branch = 7.2.0
|
||||
[submodule "third_party/googletest"]
|
||||
path = third_party/googletest
|
||||
url = https://gitee.com/mirrors/googletest.git
|
||||
[submodule "third_party/torchair/torchair"]
|
||||
path = third_party/torchair/torchair
|
||||
url = https://gitee.com/ascend/torchair.git
|
||||
branch = 7.2.0
|
||||
[submodule "third_party/Tensorpipe"]
|
||||
path = third_party/Tensorpipe
|
||||
url = https://gitee.com/ascend/Tensorpipe.git
|
||||
url = https://gitcode.com/ascend/Tensorpipe.git
|
||||
[submodule "third_party/fmt"]
|
||||
path = third_party/fmt
|
||||
url = https://gitee.com/mirrors/fmt.git
|
||||
|
||||
+3
-1
@@ -238,6 +238,7 @@ if (NOT DEFINED BUILD_LIBTORCH)
|
||||
set(IPC_SRCS)
|
||||
set(UTILS_SRCS)
|
||||
set(SAN_SRCS)
|
||||
set(AFD_SRCS)
|
||||
endif()
|
||||
|
||||
if (DEFINED BUILD_LIBTORCH)
|
||||
@@ -258,6 +259,7 @@ if (NOT DEFINED BUILD_LIBTORCH)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/ipc)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/utils)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/sanitizer)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/afd)
|
||||
endif()
|
||||
|
||||
if (DEFINED BUILD_LIBTORCH)
|
||||
@@ -287,7 +289,7 @@ if (DEFINED BUILD_LIBTORCH)
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${FLOP_SRCS} ${CUS_DTYPE_SRCS} ${FRAMEWORK_SRCS} ${LOGGING_SRCS} ${NPU_CPP_LIBS_SRCS})
|
||||
else()
|
||||
# Compile code with pybind11
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${DIST_SRCS} ${FLOP_SRCS} ${CUS_DTYPE_SRCS} ${LOGGING_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${IPC_SRCS} ${UTILS_SRCS} ${SAN_SRCS})
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${DIST_SRCS} ${FLOP_SRCS} ${CUS_DTYPE_SRCS} ${LOGGING_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${IPC_SRCS} ${UTILS_SRCS} ${SAN_SRCS} ${AFD_SRCS})
|
||||
endif()
|
||||
|
||||
add_library(${PLUGIN_NAME} SHARED ${CPP_SRCS})
|
||||
|
||||
+6
-7
@@ -16,9 +16,8 @@
|
||||
|
||||
<h2 id="入门.md">入门</h2>
|
||||
|
||||
- 在[Gitee](https://gitee.com/ascend/pytorch)上Fork存储库。
|
||||
- 阅读[README.md](#https://gitee.com/ascend/pytorch/blob/master/README.zh.md)以获取项目信息和构建说明。
|
||||
- 行为准则 [coc](https://gitee.com/ascend/community/blob/master/code-of-conduct_zh_cn.md)。
|
||||
- 在[GitCode](https://gitcode.com/ascend/pytorch)上Fork存储库。
|
||||
- 阅读[README.md](#https://gitcode.com/ascend/pytorch/blob/master/README.zh.md)以获取项目信息和构建说明。
|
||||
|
||||
<h2 id="开发指导.md">开发指导</h2>
|
||||
|
||||
@@ -159,9 +158,9 @@
|
||||
如果要将代码下载到本地环境,git是很好的方法:
|
||||
|
||||
```
|
||||
# For Gitee
|
||||
git clone https://gitee.com/{insert_your_forked_repo}/pytorch.git
|
||||
git remote add upstream https://gitee.com/pytorch/pytorch.git
|
||||
# For GitCode
|
||||
git clone https://gitcode.com/{insert_your_forked_repo}/pytorch.git
|
||||
git remote add upstream https://gitcode.com/pytorch/pytorch.git
|
||||
```
|
||||
|
||||
3. 本地开发代码。
|
||||
@@ -213,7 +212,7 @@
|
||||
|
||||
<h2 id="提出PR.md">提出PR</h2>
|
||||
|
||||
- 在[Gitee](https://gitee.com/ascend/pytorch/issues)上提出您的想法作为_问题_。
|
||||
- 在[GitCode](https://gitcode.com/ascend/pytorch/issues)上提出您的想法作为_问题_。
|
||||
- 如果是需要大量设计细节的新功能,还应提交设计方案。
|
||||
- 在问题讨论和设计提案审查中达成共识后,完成分叉回购的开发并提交 PR(Pull Request)。
|
||||
- 在从批准者那里收到2+ LGTM(Looks Good To Me)之前,不允许任何PR 。请注意,审批人不允许在自己的 PR 上添加LGTM。
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
approvers:
|
||||
- weili10
|
||||
- liwei386
|
||||
- li_jing_hw
|
||||
- clinglai
|
||||
- xuepenginnanjing
|
||||
- aichunzheng
|
||||
- yskhhh
|
||||
- brightlyking
|
||||
- wangjiangben_hw
|
||||
- wangchao285
|
||||
- atlasaccount
|
||||
- AtlasAccount
|
||||
- dilililiwhy
|
||||
- chenhao_1209
|
||||
- sunboquan
|
||||
- wangchao147
|
||||
- yanpengquan07
|
||||
- wangchao430
|
||||
- yanpengquan
|
||||
- kaixin1976
|
||||
reviewers:
|
||||
- xiaxia3
|
||||
@@ -20,10 +20,10 @@ reviewers:
|
||||
- yskhhh
|
||||
- li_jing_hw
|
||||
- wangjiangben_hw
|
||||
- weili10
|
||||
- liwei386
|
||||
- clinglai
|
||||
- shaoyf
|
||||
- yanpengquan07
|
||||
- yanpengquan
|
||||
- liu-jiaweikf
|
||||
- xiepeng20
|
||||
- brightlyking
|
||||
@@ -47,6 +47,6 @@ reviewers:
|
||||
- chuboning
|
||||
- guo-guanghao
|
||||
- yuhaiyan
|
||||
- wangchao147
|
||||
- wangchao430
|
||||
- insanecoder
|
||||
- Chen_LiQing
|
||||
|
||||
@@ -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,31 +39,29 @@ 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.0
|
||||
```
|
||||
|
||||
### From Source
|
||||
|
||||
In some special scenarios, users may need to compile **torch-npu** by themselves.Select a branch in table [Ascend Auxiliary Software](#ascend-auxiliary-software) and a Python version in table [PyTorch and Python Version Matching Table](#pytorch-and-python-version-matching-table) first. The docker image is recommended for compiling torch-npu through the following steps(It is recommended to mount the working path only and avoid the system path to reduce security risks.), the generated .whl file path is ./dist/. Note that gcc version has the following constraints if you try to compile without using docker image: we recommend to use gcc 10.2 for ARM and gcc 9.3.1 for X86.
|
||||
In some special scenarios, users may need to compile **torch-npu** by themselves.Select a branch in table [Ascend Auxiliary Software](#ascend-auxiliary-software) and a Python version in table [PyTorch and Python Version Matching Table](#pytorch-and-python-version-matching-table) first. The docker image is recommended for compiling torch-npu through the following steps(It is recommended to mount the working path only and avoid the system path to reduce security risks.), the generated .whl file path is ./dist/. Note that gcc version has the following constraints if you try to compile without using docker image: we recommend to use gcc 13.3 for both ARM and X86.
|
||||
|
||||
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 v2.8.0-7.2.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,8 @@ 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.7.1 | 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,6 +151,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.3.RC1 | 2.8.0 | 2.8.0 | v2.8.0-7.2.0 |
|
||||
| | 2.7.1 | 2.7.1 | v2.7.1-7.2.0 |
|
||||
| | 2.6.0 | 2.6.0.post3 | v2.6.0-7.2.0 |
|
||||
| | 2.1.0 | 2.1.0.post17 | v2.1.0-7.2.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 |
|
||||
@@ -245,8 +249,10 @@ 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.8.0 | Regular Release | Development | 2025/10/15 | Expected to enter maintenance status from March 15, 2026 | - |
|
||||
| 2.7.1 | Long Term Support | Development | 2025/10/15 | Expected to enter maintenance status from September 15, 2026 | |
|
||||
| 2.6.0 | Regular Release | Development | 2025/07/25 | Expected to enter maintenance status from January 15, 2026 | - |
|
||||
| 2.5.1 | Regular Release | Maintained | 2024/11/08 | Expected to enter maintenance free status from August 8, 2026 | |
|
||||
| 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 | |
|
||||
@@ -262,10 +268,10 @@ For more detailed information on installation guides, model migration, training/
|
||||
|
||||
| Document Name | Document Link |
|
||||
|------------------------------------------|-------------------------------------------------------------------------------------------------------------------------|
|
||||
| Installation Guide | [link](https://www.hiascend.com/document/detail/zh/Pytorch/710/configandinstg/instg/insg_0001.html) |
|
||||
| Network Model Migration and Training | [link](https://www.hiascend.com/document/detail/zh/Pytorch/710/ptmoddevg/trainingmigrguide/PT_LMTMOG_0003.html) |
|
||||
| Installation Guide | [link](https://www.hiascend.com/document/detail/zh/Pytorch/720/configandinstg/instg/insg_0001.html) |
|
||||
| Network Model Migration and Training | [link](https://www.hiascend.com/document/detail/zh/Pytorch/720/ptmoddevg/trainingmigrguide/PT_LMTMOG_0003.html) |
|
||||
| Operator Adaptation | [link](https://www.hiascend.com/document/detail/zh/canncommercial/81RC1/operatordev/tbeaicpudevg/atlasopdev_10_0086.html) |
|
||||
| API List (PyTorch and Custom Interfaces) | [link](https://www.hiascend.com/document/detail/zh/Pytorch/710/apiref/apilist/ptaoplist_000002.html) |
|
||||
| API List (PyTorch and Custom Interfaces) | [link](https://www.hiascend.com/document/detail/zh/Pytorch/720/apiref/apilist/ptaoplist_000002.html) |
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+174
-150
@@ -1,148 +1,15 @@
|
||||
# Ascend Extension for PyTorch插件
|
||||
|
||||
|
||||
## 简介
|
||||
|
||||
本项目开发了名为**torch_npu**的**Ascend Extension for PyTorch**插件,使昇腾NPU可以适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。
|
||||
|
||||
昇腾为基于华为昇腾处理器和软件的行业应用及服务提供全栈AI计算基础设施。您可以通过访问[昇腾社区](https://www.hiascend.com/zh/),了解关于昇腾的更多信息。
|
||||
|
||||
## 安装
|
||||
## 版本说明
|
||||
|
||||
### 使用二进制文件进行安装
|
||||
|
||||
我们为用户提供可以快速安装**torch_npu**的whl安装包。在安装**torch_npu**之前,您需要先安装**CANN**软件。[昇腾辅助软件](#昇腾辅助软件)中有更多关于CANN的版本信息。请参考[CANN安装指南](https://www.hiascend.com/zh/software/cann/community)获取**CANN**安装包。
|
||||
|
||||
1. **安装PyTorch**
|
||||
|
||||
通过 pip 安装 PyTorch。
|
||||
|
||||
**aarch64:**
|
||||
|
||||
```bash
|
||||
pip3 install torch==2.1.0
|
||||
```
|
||||
|
||||
**x86:**
|
||||
|
||||
```bash
|
||||
pip3 install torch==2.1.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) |
|
||||
|
||||
2. **安装torch_npu依赖**
|
||||
|
||||
运行以下命令安装依赖。
|
||||
|
||||
```bash
|
||||
pip3 install pyyaml
|
||||
pip3 install setuptools
|
||||
```
|
||||
|
||||
3. **安装torch_npu**
|
||||
|
||||
```bash
|
||||
pip3 install torch-npu==2.1.0.post13
|
||||
```
|
||||
如需要保存安装日志,可在pip3 install命令后面加上参数 `--log <PATH>`,并对您指定的目录`<PATH>`做好权限管控。
|
||||
|
||||
### 使用源代码进行安装
|
||||
|
||||
某些特殊场景下,用户可能需要自行编译**torch_npu**。可以根据[昇腾辅助软件表](#昇腾辅助软件)和[PyTorch与Python版本配套表](#pytorch与python版本配套表)选择合适的分支。推荐使用Docker镜像编译**torch_npu**,可以通过以下步骤获取(建议只挂载工作路径,并避开系统路径,以降低安全风险), 生成的.whl文件路径为./dist/。如果不使用镜像,编译时请注意gcc版本遵循如下约束:ARM架构下推荐使用gcc 10.2版本, X86架构下推荐使用gcc 9.3.1
|
||||
|
||||
1. **克隆torch_npu代码仓**
|
||||
|
||||
```
|
||||
git clone https://gitee.com/ascend/pytorch.git -b v2.1.0-7.1.0 --depth 1
|
||||
```
|
||||
|
||||
2. **构建镜像**
|
||||
|
||||
```
|
||||
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
|
||||
docker build -t manylinux-builder:v1 .
|
||||
```
|
||||
|
||||
3. **进入Docker容器**
|
||||
|
||||
```
|
||||
docker run -it -v /{code_path}/pytorch:/home/pytorch manylinux-builder:v1 bash
|
||||
# {code_path} is the torch_npu source code path
|
||||
```
|
||||
|
||||
4. **编译torch_npu**
|
||||
|
||||
以**Python 3.8** 为例。
|
||||
|
||||
```
|
||||
cd /home/pytorch
|
||||
bash ci/build.sh --python=3.8
|
||||
```
|
||||
|
||||
**提示**
|
||||
|
||||
如果想使用新的C++ ABI编译,请首先运行如下命令,此时推荐和社区torch包相同的编译环境:glibc 2.28, gcc 11.2.1
|
||||
|
||||
```
|
||||
export _GLIBCXX_USE_CXX11_ABI=1
|
||||
```
|
||||
|
||||
同时,我们支持使用如下变量配置-fabi-version,要求和社区torch包ABI版本一致
|
||||
|
||||
```
|
||||
export _ABI_VERSION=16
|
||||
```
|
||||
|
||||
|
||||
## 卸载
|
||||
Pytorch框架训练环境的卸载可以参考[昇腾官方文档](https://www.hiascend.com/document/detail/zh/ModelZoo/pytorchframework/ptes/ptes_00032.html)。
|
||||
|
||||
torch_npu的卸载只需执行命令:
|
||||
|
||||
```bash
|
||||
pip3 uninstall torch_npu
|
||||
```
|
||||
|
||||
如需要保存卸载日志,可在pip3 uninstall命令后面加上参数 `--log <PATH>`,并对您指定的目录`<PATH>`做好权限管控。
|
||||
|
||||
## 入门
|
||||
|
||||
### 前提
|
||||
|
||||
运行以下命令初始化**CANN**环境变量。
|
||||
|
||||
```Shell
|
||||
# Default path, change it if needed.
|
||||
source /usr/local/Ascend/ascend-toolkit/set_env.sh
|
||||
```
|
||||
|
||||
### 快速验证
|
||||
|
||||
可以通过以下样例快速体验**昇腾NPU**。
|
||||
|
||||
```diff
|
||||
import torch
|
||||
- import torch_npu # torch_npu2.5.1及以后版本可以不用手动导包
|
||||
|
||||
x = torch.randn(2, 2).npu()
|
||||
y = torch.randn(2, 2).npu()
|
||||
z = x.mm(y)
|
||||
|
||||
print(z)
|
||||
```
|
||||
|
||||
## PyTorch与Python版本配套表
|
||||
### PyTorch与Python版本配套表
|
||||
|
||||
| PyTorch版本 | Python版本 |
|
||||
|---------------|:-------------------------------------------------------------|
|
||||
@@ -153,13 +20,20 @@ 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.7.1 | Python3.9.x, Python3.10.x, Python 3.11.x |
|
||||
| PyTorch2.8.0 | Python3.9.x, Python3.10.x, Python 3.11.x |
|
||||
|
||||
## 昇腾辅助软件
|
||||
|
||||
**PyTorch Extension**版本号采用`{PyTorch版本}-{昇腾版本}`命名规则,前者为**PyTorch Extension**匹配的PyTorch版本,后者用于匹配CANN版本,详细匹配如下:
|
||||
### 昇腾辅助软件
|
||||
|
||||
| CANN版本 | 支持的PyTorch版本 | 支持的Extension版本 | Gitee分支 |
|
||||
**Ascend Extension for PyTorch**的分支名称采用`{PyTorch版本}-{昇腾版本}`命名规则,前者为**Ascend Extension for PyTorch**匹配的PyTorch版本,后者为**Ascend Extension for PyTorch**版本号,详细匹配如下:
|
||||
|
||||
| CANN版本 | 支持的PyTorch版本 | 支持的Extension版本 | GitCode分支 |
|
||||
|-----------------------|--------------|------------------|-------------------|
|
||||
| CANN 8.3.RC1 | 2.8.0 | 2.8.0 | v2.8.0-7.2.0 |
|
||||
| | 2.7.1 | 2.7.1 | v2.7.1-7.2.0 |
|
||||
| | 2.6.0 | 2.6.0.post3 | v2.6.0-7.2.0 |
|
||||
| | 2.1.0 | 2.1.0.post17 | v2.1.0-7.2.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 |
|
||||
@@ -207,9 +81,154 @@ print(z)
|
||||
| CANN 5.0.3 | 1.8.1 | 1.5.0.post3 | 2.0.3.tr5 |
|
||||
| CANN 5.0.2 | 1.5.0 | 1.5.0.post2 | 2.0.2.tr5 |
|
||||
|
||||
|
||||
## 快速入门
|
||||
|
||||
基于CNN模型识别手写数字的脚本,对在GPU上训练的该脚本代码进行修改,使其可以迁移到昇腾NPU上进行训练。具体操作请参见[Ascend Extension for PyTorch 快速入门](https://www.hiascend.com/document/detail/zh/Pytorch/710/fastexperience/fastexperience_0001.html)。
|
||||
|
||||
## 环境部署
|
||||
|
||||
### 使用二进制文件进行安装
|
||||
|
||||
我们为用户提供可以快速安装**torch_npu**的whl安装包。在安装**torch_npu**之前,您需要先安装**CANN**软件。[昇腾辅助软件](#昇腾辅助软件)中有更多关于CANN的版本信息。请参考[CANN安装指南](https://www.hiascend.com/zh/software/cann/community)获取**CANN**安装包。
|
||||
|
||||
1. **安装PyTorch**
|
||||
|
||||
通过 pip 安装 PyTorch。
|
||||
|
||||
**aarch64:**
|
||||
|
||||
```bash
|
||||
pip3 install torch==2.8.0
|
||||
```
|
||||
|
||||
**x86:**
|
||||
|
||||
```bash
|
||||
pip3 install torch==2.8.0+cpu --index-url https://download.pytorch.org/whl/cpu
|
||||
```
|
||||
|
||||
若使用pip命令安装失败,请使用下载链接或进入[PyTorch官方网站](https://pytorch.org/)进行查询下载对应版本。
|
||||
|
||||
| 架构 | 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依赖**
|
||||
|
||||
运行以下命令安装依赖。
|
||||
|
||||
```bash
|
||||
pip3 install pyyaml
|
||||
pip3 install setuptools
|
||||
```
|
||||
|
||||
3. **安装torch_npu**
|
||||
|
||||
```bash
|
||||
pip3 install torch-npu==2.8.0
|
||||
```
|
||||
如需要保存安装日志,可在pip3 install命令后面加上参数 `--log <PATH>`,并对您指定的目录`<PATH>`做好权限管控。
|
||||
|
||||
### 使用源代码进行安装
|
||||
|
||||
某些特殊场景下,用户可能需要自行编译**torch_npu**。可以根据[昇腾辅助软件表](#昇腾辅助软件)和[PyTorch与Python版本配套表](#pytorch与python版本配套表)选择合适的分支。
|
||||
|
||||
推荐使用Docker镜像编译**torch_npu**,可以通过以下步骤获取(建议只挂载工作路径,并避开系统路径,以降低安全风险), 生成的.whl文件路径为./dist/。
|
||||
|
||||
>**须知:**<br>
|
||||
>如果不使用镜像,编译时请注意gcc版本遵循约束:ARM与X86架构下推荐使用gcc 13.3。
|
||||
|
||||
1. **克隆torch_npu代码仓**
|
||||
|
||||
```
|
||||
git clone https://gitcode.com/ascend/pytorch.git -b v2.8.0-7.2.0 --depth 1
|
||||
```
|
||||
|
||||
2. **构建镜像**
|
||||
|
||||
```
|
||||
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
|
||||
docker build -t manylinux-builder:v1 .
|
||||
```
|
||||
|
||||
3. **进入Docker容器**
|
||||
|
||||
```
|
||||
docker run -it -v /{code_path}/pytorch:/home/pytorch manylinux-builder:v1 bash
|
||||
# {code_path} is the torch_npu source code path
|
||||
```
|
||||
|
||||
4. **编译torch_npu**
|
||||
|
||||
以**Python 3.9** 为例。
|
||||
|
||||
```
|
||||
cd /home/pytorch
|
||||
bash ci/build.sh --python=3.9
|
||||
```
|
||||
|
||||
**提示**
|
||||
|
||||
如果想使用新的C++ ABI编译,请首先运行如下命令,此时推荐和社区torch包相同的编译环境:glibc 2.28, gcc 13.3.1。
|
||||
|
||||
```
|
||||
export _GLIBCXX_USE_CXX11_ABI=1
|
||||
```
|
||||
|
||||
同时,我们支持使用如下变量配置-fabi-version,要求和社区torch包ABI版本一致。
|
||||
|
||||
```
|
||||
export _ABI_VERSION=18
|
||||
```
|
||||
|
||||
### 安装后验证
|
||||
|
||||
#### 前提
|
||||
|
||||
运行以下命令初始化**CANN**环境变量。
|
||||
|
||||
```Shell
|
||||
# Default path, change it if needed.
|
||||
source /usr/local/Ascend/ascend-toolkit/set_env.sh
|
||||
```
|
||||
|
||||
#### 快速验证
|
||||
|
||||
可以通过以下样例快速体验**昇腾NPU**。
|
||||
|
||||
```diff
|
||||
import torch
|
||||
- import torch_npu # torch_npu2.5.1及以后版本可以不用手动导包
|
||||
|
||||
x = torch.randn(2, 2).npu()
|
||||
y = torch.randn(2, 2).npu()
|
||||
z = x.mm(y)
|
||||
|
||||
print(z)
|
||||
```
|
||||
|
||||
## 卸载
|
||||
Pytorch框架训练环境的卸载可以参考[昇腾官方文档](https://www.hiascend.com/document/detail/zh/ModelZoo/pytorchframework/ptes/ptes_00032.html)。
|
||||
|
||||
torch_npu的卸载只需执行命令:
|
||||
|
||||
```bash
|
||||
pip3 uninstall torch_npu
|
||||
```
|
||||
|
||||
如需要保存卸载日志,可在pip3 uninstall命令后面加上参数 `--log <PATH>`,并对您指定的目录`<PATH>`做好权限管控。
|
||||
|
||||
|
||||
|
||||
## 硬件配套
|
||||
|
||||
昇腾训练设备包含以下型号,都可作为PyTorch模型的训练环境
|
||||
昇腾训练设备包含以下型号,都可作为PyTorch模型的训练环境。
|
||||
| 产品系列 | 产品型号 |
|
||||
|-----------------------|----------------------------------|
|
||||
| Atlas 训练系列产品 | Atlas 800 训练服务器(型号:9000) |
|
||||
@@ -220,20 +239,21 @@ print(z)
|
||||
| Atlas A2 训练系列产品 | Atlas 800T A2 训练服务器 |
|
||||
| | Atlas 900 A2 PoD 集群基础单元 |
|
||||
| | Atlas 200T A2 Box16 异构子框 |
|
||||
| | Atlas 300T A2 训练卡 |
|
||||
| Atlas A3 训练系列产品 | Atlas 800T A3 训练服务器 |
|
||||
| | Atlas 900 A3 SuperPoD 超节点 |
|
||||
|
||||
昇腾推理设备包含以下型号,都可作为大模型的推理环境
|
||||
昇腾推理设备包含以下型号,都可作为大模型的推理环境。
|
||||
| 产品系列 | 产品型号 |
|
||||
|-----------------------|----------------------------------|
|
||||
| Atlas 800I A2推理产品 | Atlas 800I A2 推理服务器 |
|
||||
|
||||
## 建议与交流
|
||||
|
||||
欢迎大家为社区做贡献。如果有任何疑问或建议,请提交[gitee Issues](https://gitee.com/Ascend/pytorch/issues),我们会尽快回复。感谢您的支持。
|
||||
欢迎大家为社区做贡献。如果有任何疑问或建议,请提交[GitCode Issues](https://gitcode.com/Ascend/pytorch/issues),我们会尽快回复。感谢您的支持。
|
||||
|
||||
## 分支维护策略
|
||||
|
||||
AscendPyTorch版本分支的维护阶段如下:
|
||||
Ascend Extension for PyTorch版本分支的维护阶段如下:
|
||||
|
||||
|
||||
| **状态** | **时间** | **说明** |
|
||||
@@ -247,11 +267,13 @@ AscendPyTorch版本分支的维护阶段如下:
|
||||
|
||||
| **PyTorch版本** | **维护策略** | **当前状态** | **发布时间** | **后续状态** | **EOL日期** |
|
||||
|---------------|----------|----------|------------|----------------------|-----------|
|
||||
| 2.8.0 | 常规分支 | 开发 | 2025/10/15| 预计2026/03/15起进入维护状态 | - |
|
||||
| 2.7.1 | 长期分支 | 开发 | 2025/10/15| 预计2026/10/15起进入维护状态 | - |
|
||||
| 2.6.0 | 常规分支 | 开发 | 2025/07/25 | 预计2026/01/25起进入维护状态 | - |
|
||||
| 2.5.1 | 常规分支 | 开发 | 2024/11/08 | 预计2025/08/08起进入维护状态 | - |
|
||||
| 2.5.1 | 常规分支 | 维护 | 2024/11/08 | 预计2026/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.2.0 | 常规分支 | EOL | 2024/04/01 | | 2025/10/14 |
|
||||
| 2.1.0 | 长期支持 | 开发 | 2023/10/15 | 预计2025/09/15起进入维护状态 | |
|
||||
| 2.0.1 | 常规分支 | EOL | 2023/7/19 | | 2024/3/14 |
|
||||
| 1.11.0 | 长期支持 | 维护 | 2023/4/19 | 预计2025/09/10起进入无维护状态 | |
|
||||
@@ -268,10 +290,12 @@ AscendPyTorch版本分支的维护阶段如下:
|
||||
|
||||
| 文档名称 | 文档链接 |
|
||||
| -------------------------- | ------------------------------------------------------------ |
|
||||
| 安装指南 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/710/configandinstg/instg/insg_0001.html) |
|
||||
| 网络模型迁移和训练 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/710/ptmoddevg/trainingmigrguide/PT_LMTMOG_0003.html) |
|
||||
| 算子适配 | [参考链接](https://www.hiascend.com/document/detail/zh/canncommercial/82RC1/developmentguide/opdevg/Ascendcopdevg/atlas_ascendc_10_0048.html) |
|
||||
| API清单(PyTorch原生接口与自定义接口) | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/710/apiref/apilist/ptaoplist_000002.html) |
|
||||
| 软件安装指南 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/configandinstg/instg/insg_0001.html) |
|
||||
| 网络模型迁移和训练 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/ptmoddevg/trainingmigrguide/PT_LMTMOG_0002.html) |
|
||||
| 算子适配 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/ptmoddevg/Frameworkfeatures/featuresguide_00021.html) |
|
||||
| PyTorch原生接口清单 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/apiref/PyTorchNativeapi/ptaoplist_000003.html) |
|
||||
| Ascend Extension for PyTorch自定义API参考 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/apiref/torchnpuCustomsapi/context/%E6%A6%82%E8%BF%B0.md) |
|
||||
|
||||
|
||||
## 许可证
|
||||
|
||||
|
||||
+35
-35
@@ -12,13 +12,13 @@
|
||||
|
||||
## 文件权限控制
|
||||
|
||||
1. 建议用户对训练所需文件、训练过程中保存的文件、用户个人的隐私数据、商业资产等敏感文件做好权限控制等安全措施,例如多用户共享数据集场景下的数据集文件写权限控制、profiler等场景产生数据文件权限控制等,设定的权限建议参考[文件权限参考](#文件权限参考)进行设置。
|
||||
1. 建议用户对训练所需文件、训练过程中保存的文件、用户个人的隐私数据、商业资产等敏感文件做好权限控制等安全措施,例如多用户共享数据集场景下的数据集文件写权限控制、profiler等场景产生数据文件权限控制等,设定的权限建议参见[文件权限参考](#文件权限参考)进行设置。
|
||||
|
||||
2. torch_npu中profiler工具会生成性能记录文件,生成的文件权限为640,文件夹权限为750,用户可根据需要自行对生成后的相关文件进行权限控制。
|
||||
|
||||
3. 用户安装和使用过程需要做好权限控制,建议参考[文件权限参考](#文件权限参考)进行设置。如需要保存安装/卸载日志,可在安装/卸载命令后面加上参数--log <FILE>, 注意对<FILE>文件及目录做好权限管控。
|
||||
3. 用户安装和使用过程需要做好权限控制,建议参见[文件权限参考](#文件权限参考)进行设置。如需要保存安装/卸载日志,可在安装/卸载命令后面加上参数--log <FILE>, 注意对<FILE>文件及目录做好权限管控。
|
||||
|
||||
4. PyTorch框架运行中所生成的文件权限依赖系统设定,如torch.save接口保存的文件。建议当前执行脚本的用户根据自身需要,对生成文件做好权限控制,设定的权限可参考[文件权限参考](#文件权限参考) 。可使用umask控制默认权限,降低提权等安全风险,建议用户将主机(包括宿主机)和容器中的umask设置为0027及其以上,提高安全性。
|
||||
4. PyTorch框架运行中所生成的文件权限依赖系统设定,如torch.save接口保存的文件。建议当前执行脚本的用户根据自身需要,对生成文件做好权限控制,设定的权限可参见[文件权限参考](#文件权限参考) 。可使用umask控制默认权限,降低提权等安全风险,建议用户将主机(包括宿主机)和容器中的umask设置为0027及其以上,提高安全性。
|
||||
|
||||
##### 文件权限参考
|
||||
|
||||
@@ -45,9 +45,9 @@
|
||||
## 调试工具声明
|
||||
|
||||
torch_npu内集成性能分析工具profiler:
|
||||
- 集成原因:对标pytorch原生支持能力,提供NPU PyTorch框架开发性能分析能力,加速性能分析调试过程。
|
||||
- 集成原因:对标PyTorch原生支持能力,提供NPU PyTorch框架开发性能分析能力,加速性能分析调试过程。
|
||||
- 使用场景:默认不采集,如用户需要进行性能分析时,可在模型训练脚本中添加Ascend Extension for PyTorch Profiler接口,执行训练的同时采集性能数据,完成训练后直接输出可视化的性能数据文件。
|
||||
- 风险提示:使用该功能会在本地生成性能数据,用户需加强对相关性能数据的保护,请在需要模型性能分析时使用,分析完成后及时关闭。Profiler工具具体细节请参考[《PyTorch 性能分析工具介绍》](https://www.hiascend.com/document/detail/zh/Pytorch/60RC2/ptmoddevg/trainingmigrguide/performance_tuning_0013.html)。
|
||||
- 风险提示:使用该功能会在本地生成性能数据,用户需加强对相关性能数据的保护,请在需要模型性能分析时使用,分析完成后及时关闭。Profiler工具具体细节请参考[《PyTorch 性能分析工具介绍》](https://www.hiascend.com/document/detail/zh/Pytorch/710/ptmoddevg/trainingmigrguide/performance_tuning_0014.html)。
|
||||
|
||||
## 数据安全声明
|
||||
|
||||
@@ -70,38 +70,38 @@ 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://gitcode.com/ascend/op-plugin.git | 依赖的开源代码仓 |
|
||||
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/googletest.git | 依赖的开源代码仓 |
|
||||
| 自研 | 不涉及 | .gitmodules | https://gitee.com/ascend/torchair.git | 依赖的开源代码仓 |
|
||||
| 自研 | 不涉及 | .gitmodules | https://gitcode.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://gitcode.com/ascend/pytorch | 用于打包whl的url入参 |
|
||||
| 自研 | 不涉及 | setup.cfg | https://gitcode.com/ascend/pytorch/tags | 用于打包whl的download_url入参 |
|
||||
| 自研 | 不涉及 | third_party\op-plugin\ci\build.sh | https://gitcode.com/ascend/pytorch.git | 编译脚本根据torch_npu仓库地址拉取代码进行编译 |
|
||||
| 自研 | 不涉及 | third_party\op-plugin\ci\exec_ut.sh | https://gitcode.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的测试用例 |
|
||||
|
||||
## 公开接口声明
|
||||
|
||||
Ascend Extension for PyTorch是PyTorch适配插件,支持用户使用PyTorch在昇腾设备上进行训练和推理。Ascend Extension for PyTorch适配后支持用户使用PyTorch原生接口。除了原生PyTorch接口外,Ascend Extension for PyTorch提供了部分自定义接口,包括自定义算子、亲和库和其他接口,支持PyTorch接口和自定义接口连接,具体可参考[《PyTorch API参考》](https://www.hiascend.com/document/detail/zh/Pytorch/60RC2/apiref/apilist/ptaoplist_000001.html)。
|
||||
Ascend Extension for PyTorch是PyTorch适配插件,支持用户使用PyTorch在昇腾设备上进行训练和推理。Ascend Extension for PyTorch适配后支持用户使用PyTorch原生接口。除了原生PyTorch接口外,Ascend Extension for PyTorch提供了部分自定义接口,包括自定义算子、亲和库和其他接口,支持PyTorch接口和自定义接口连接,具体可参见[《Ascend Extension for PyTorch自定义API参考》](https://www.hiascend.com/document/detail/zh/Pytorch/710/apiref/torchnpuCustomsapi/context/%E6%A6%82%E8%BF%B0.md)以及[《PyTorch原生接口清单》](https://www.hiascend.com/document/detail/zh/Pytorch/710/apiref/PyTorchNativeapi/ptaoplist_000003.html)。
|
||||
|
||||
参考[PyTorch社区公开接口规范](https://github.com/pytorch/pytorch/wiki/Public-API-definition-and-documentation),Ascend Extension for PyTorch提供了对外的自定义接口。如果一个函数看起来符合公开接口的标准且在文档中有展示,则该接口是公开接口。否则,使用该功能前可以在社区询问该功能是否确实是公开的或意外暴露的接口,因为这些未暴露接口将来可能会被修改或者删除。
|
||||
|
||||
@@ -224,7 +224,7 @@ PyTorch提供分布式训练能力,支持在单机和多机场景下进行训
|
||||
| 所属平面 | 不涉及 | 不涉及 |
|
||||
| 版本 | 所有版本 | 所有版本 |
|
||||
| 特殊场景 | 无 | 无 |
|
||||
| 备注 | 该通信过程由开源软件PyTorch控制,配置为PyTorch原生设置,可参考[PyTorch文档](https://pytorch.org/docs/stable/distributed.html#launch-utility)。源端口由操作系统自动分配,分配范围由操作系统的配置决定,例如ubuntu:采用/proc/sys/net/ipv4/ipv4_local_port_range文件指定,可通过cat /proc/sys/net/ipv4/ipv4_local_port_range或sysctl net.ipv4.ip_local_port_range查看 | 该通信过程由CANN中HCCL组件控制,torch_npu不进行控制,端口范围可参考[《环境变量参考》](https://www.hiascend.com/document/detail/zh/canncommercial/80RC2/apiref/envvar/envref_07_0001.html)的“执行相关 > 集合通信与分布式训练 > 集合通信相关配置>HCCL_IF_BASE_PORT” |
|
||||
| 备注 | 该通信过程由开源软件PyTorch控制,配置为PyTorch原生设置,可参考[PyTorch文档](https://pytorch.org/docs/stable/distributed.html#launch-utility)。源端口由操作系统自动分配,分配范围由操作系统的配置决定,例如ubuntu:采用/proc/sys/net/ipv4/ipv4_local_port_range文件指定,可通过cat /proc/sys/net/ipv4/ipv4_local_port_range或sysctl net.ipv4.ip_local_port_range查看 | 该通信过程由CANN中HCCL组件控制,torch_npu不进行控制,端口范围可参考[《环境变量参考》](https://www.hiascend.com/document/detail/zh/canncommercial/82RC1/maintenref/envvar/envref_07_0001.html)的“执行相关 > 集合通信 >HCCL_IF_BASE_PORT” |
|
||||
|
||||
## 漏洞机制说明
|
||||
|
||||
|
||||
@@ -1,122 +1,190 @@
|
||||
OPEN SOURCE SOFTWARE NOTICE
|
||||
|
||||
Please note we provide an open source software notice along with this product and/or this product firmware (in the following just “this product”). The open source software licenses are granted by the respective right holders. And the open source licenses prevail all other license information with regard to the respective open source software contained in the product, including but not limited to End User Software Licensing Agreement. This notice is provided on behalf of Huawei Technologies Co. Ltd. and any of its local subsidiaries which may have provided this product to you in your local country.
|
||||
Please note we provide an open source software notice along with this product and/or this product firmware (in the following just "this product"). The open source software licenses are granted by the respective right holders. And the open source licenses prevail all other license information with regard to the respective open source software contained in the product, including but not limited to End User Software Licensing Agreement. This notice is provided on behalf of Huawei Technologies Co. Ltd. and any of its local subsidiaries which may have provided this product to you in your local country.
|
||||
|
||||
Warranty Disclaimer
|
||||
THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
|
||||
|
||||
Copyright Notice and License Texts
|
||||
Software: pytorch v2.3.1
|
||||
Software: pytorch v2.6.0
|
||||
Copyright notice:
|
||||
Copyright (c) 2011-2013 NYU
|
||||
Copyright (c) Microsoft Corporation
|
||||
Copyright (c) 2014- Facebook, Inc
|
||||
Copyright (c) 2017 The Android Open Source Project
|
||||
Copyright Python Software Foundation
|
||||
Copyright (c) 2018 Alex Rogozhnikov
|
||||
Copyright (c) 2007-2009 Scientific Computing and Imaging Institute, University of Utah
|
||||
Copyright (c) 2016, NVIDIA CORPORATION, All rights reserved
|
||||
Copyright (c) 2017 Microsoft
|
||||
Copyright (c) Meta Platforms, Inc.
|
||||
Copyright (c) 2022 Apple Inc.
|
||||
Copyright (c) 2018-present, Facebook, Inc.
|
||||
Copyright (c) Facebook Inc. and Microsoft Corporation
|
||||
Copyright (c) 2005-2017, NumPy Developers. All rights reserved
|
||||
Copyright (c) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved
|
||||
Copyright (c) 2014, The Regents
|
||||
Copyright (c) 2005-2010 ActiveState Software Inc.
|
||||
Copyright 2005, Google Inc. All rights reserved
|
||||
Copyright (c) 2022, Tri Dao
|
||||
Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers. All rights reserved
|
||||
Copyright 2008 Google Inc. All rights reserved
|
||||
Copyright (c) 2003-2017 Josef Weidendorfer. All rights reserved
|
||||
Copyright (c) 2014 Matthew Rocklin
|
||||
Copyright (c) 2016 Microsoft
|
||||
Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved
|
||||
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
|
||||
Copyright (c) 2008-2012 The Khronos Group Inc.
|
||||
Copyright (c) 2016 Facebook Inc.
|
||||
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC All Rights Reserved
|
||||
Copyright (c) 2006, Laurent Montel, <montel@kde.org>
|
||||
Copyright (c) 2015 Google Inc. All rights reserved
|
||||
Copyright (c) 2010-2022 by Alex Clark and contributors
|
||||
Copyright 2015 Google Inc. All Rights Reserved
|
||||
Copyright (c) 2017 - 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved
|
||||
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
|
||||
(c) BNParamType
|
||||
Copyright 2013-2014 RAD Game
|
||||
Copyright (c) 2011-2019 Stephan Brumme. All rights reserved
|
||||
Copyright (c) 2018 MathInf GmbH, Thomas Viehmann
|
||||
Copyright 2019 Kakao Brain
|
||||
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation All Rights Reserved
|
||||
Copyright 2004-present Facebook. All Rights Reserved
|
||||
Copyright (c) 2008-2013 The Khronos Group Inc.
|
||||
Copyright (c) Microsoft Corporation. All rights reserved
|
||||
Copyright 2006, Google Inc. All rights reserved
|
||||
Copyright (c) 2014-2015 The Khronos Group Inc.
|
||||
Copyright 2015 The TensorFlow Authors. All Rights Reserved
|
||||
Copyright (c) 2023, Tri Dao
|
||||
Copyright (c) 2011-2014 Idiap Research Institute
|
||||
Copyright (c) 2016-present, Facebook Inc. All rights reserved
|
||||
Copyright (c) Advanced Micro Devices, Inc.
|
||||
Copyright (c) 2001-2014 Python Software Foundation All Rights Reserved
|
||||
|
||||
Copyright (c) Microsoft Corporation
|
||||
|
||||
Copyright (c) Bjorn Fahller
|
||||
|
||||
Copyright (c) 2001-2014 Python Software Foundation All Rights Reserved
|
||||
|
||||
Copyright (c) 2011-2013 NYU
|
||||
|
||||
Copyright (c) 1995-2011 by Fredrik Lundh
|
||||
Copyright (c) Edward Z. Yang <ezyang@mit.edu>
|
||||
|
||||
Copyright (c) Edward Z. Yang ezyang@mit.edu
|
||||
|
||||
Copyright (c) 2014- Facebook, Inc
|
||||
|
||||
Copyright (c) 2017 The Android Open Source Project
|
||||
|
||||
Copyright Python Software Foundation
|
||||
|
||||
Copyright (c) 2012 Massachusetts Institute of Technology
|
||||
|
||||
Copyright (c) 2018 Alex Rogozhnikov
|
||||
|
||||
Copyright (c) 2007-2009 Scientific Computing and Imaging Institute, University of Utah
|
||||
|
||||
Copyright (c) 2006 Idiap Research Institute
|
||||
|
||||
Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved
|
||||
Copyright (c) 2008 - 2012 The Khronos Group Inc.
|
||||
|
||||
Copyright (c) 2015 Yangqing Jia All rights reserved
|
||||
|
||||
Copyright (c) Meta Platforms, Inc.
|
||||
|
||||
Copyright 2023-present Facebook. All Rights Reserved
|
||||
Copyright 2013 Conrad Steenberg <conrad.steenberg@gmail.com>
|
||||
Copyright (c) 2008-2015 The Khronos Group Inc.
|
||||
Copyright (c) 2014-2017 The Regents
|
||||
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
|
||||
|
||||
Copyright (c) 2022 Apple Inc.
|
||||
|
||||
Copyright (c) 2005-2017, NumPy Developers. All rights reserved
|
||||
|
||||
Copyright (c) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved
|
||||
|
||||
Copyright (c) 2014, The Regents
|
||||
|
||||
Copyright (c) 2005-2010 ActiveState Software Inc.
|
||||
|
||||
Copyright Malte Skarupke 2017
|
||||
|
||||
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
|
||||
|
||||
Copyright 2005, Google Inc. All rights reserved
|
||||
|
||||
Copyright (c) Meta Platforms, Inc. and affiliates
|
||||
|
||||
Copyright (c) 2023, Advanced Micro Devices, Inc.
|
||||
Copyright (c) 2016- Facebook, Inc
|
||||
|
||||
Copyright (c) 2022, Tri Dao
|
||||
|
||||
Copyright (c) 2005-2023 NVIDIA Corporation Built
|
||||
|
||||
Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers. All rights reserved
|
||||
|
||||
Copyright 2008 Google Inc. All rights reserved
|
||||
|
||||
Copyright (c) 2021, 2023-2024 Arm Limited
|
||||
|
||||
Copyright (c) 2003-2017 Josef Weidendorfer. All rights reserved
|
||||
|
||||
Copyright (c) 1997-2011 by Secret Labs AB
|
||||
|
||||
Copyright (c) 2016- Facebook, Inc
|
||||
|
||||
Copyright (c) 2014 Matthew Rocklin
|
||||
|
||||
Copyright (c) 2005-2022 NVIDIA Corporation Built
|
||||
|
||||
Copyright (c) Facebook, Inc.
|
||||
|
||||
Copyright 2019-2020 Kakao Brain
|
||||
|
||||
Copyright (c) 2000-2017 Julian Seward. All rights reserved
|
||||
Copyright (c) 2016-2017, ARM Limited and Contributors
|
||||
|
||||
Copyright (c) 2005-2020 Rich Felker
|
||||
|
||||
Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved
|
||||
|
||||
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
|
||||
|
||||
Copyright (c) 2016 Facebook Inc.
|
||||
|
||||
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
|
||||
Copyright 2016 Facebook
|
||||
|
||||
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC All Rights Reserved
|
||||
|
||||
Copyright (c) 2012-2014 Deepmind Technologies
|
||||
|
||||
Copyright (c) 2012 Giovanni Garberoglio Interdisciplinary Laboratory
|
||||
|
||||
Copyright (c) 2024, Tri Dao
|
||||
|
||||
Copyright (c) Donald Stufft and individual contributors. All rights reserved
|
||||
|
||||
Copyright (c) 2018, Steven Moshier All rights reserved
|
||||
|
||||
Copyright (c) 2015 Google Inc. All rights reserved
|
||||
|
||||
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved
|
||||
Copyright (c) 2017-present, Facebook, Inc.
|
||||
|
||||
Copyright (c) 2010-2022 by Alex Clark and contributors
|
||||
|
||||
Copyright 2015 Google Inc. All Rights Reserved
|
||||
|
||||
Copyright (c) 2017 - 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved
|
||||
|
||||
Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved
|
||||
|
||||
Copyright (c) 2016 manylinux
|
||||
|
||||
Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved
|
||||
Copyright (c) 2014, 2015, The Regents
|
||||
|
||||
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
|
||||
|
||||
Copyright 2013-2014 RAD Game
|
||||
|
||||
Copyright (c) 2011-2019 Stephan Brumme. All rights reserved
|
||||
|
||||
Copyright (c) 2018 MathInf GmbH, Thomas Viehmann
|
||||
|
||||
Copyright (c) 2013 Eddy Petrisor
|
||||
|
||||
Copyright (c) 2023-2024 The ggml
|
||||
|
||||
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation All Rights Reserved
|
||||
|
||||
Copyright 2004-present Facebook. All Rights Reserved
|
||||
|
||||
Copyright (c) 2010 ActiveState Software Inc.
|
||||
|
||||
Copyright (c) 2006 The Android Open Source Project
|
||||
|
||||
(c) Meta Platforms, Inc. and affiliates. All rights reserved
|
||||
|
||||
Copyright (c) 2023 Apple Inc.
|
||||
Copyright 2015 The Gemmlowp Authors. All Rights Reserved
|
||||
Copyright (c) 2015-2017 The Khronos Group Inc.
|
||||
|
||||
Copyright (c) Microsoft Corporation. All rights reserved
|
||||
|
||||
Copyright 2015 The TensorFlow Authors. All Rights Reserved
|
||||
|
||||
Copyright (c) 2023, Tri Dao
|
||||
|
||||
Copyright 2022 Cruise LLC
|
||||
|
||||
Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved
|
||||
|
||||
Copyright (c) 2022 Cruise LLC. All rights reserved
|
||||
|
||||
Copyright (c) 2016-present, Facebook, Inc.
|
||||
|
||||
(c) Copyright John Maddock 2006
|
||||
|
||||
Copyright (c) 2011-2014 Idiap Research Institute
|
||||
|
||||
Copyright (c) 2014 Indiana University All rights reserved
|
||||
|
||||
copyright 2019 The TensorFlow Authors
|
||||
|
||||
Copyright (c) 2016-present, Facebook Inc. All rights reserved
|
||||
|
||||
License: BSD 3-Clause License
|
||||
Copyright (c) , <YEAR>,<OWNER>
|
||||
All rights reserved.
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Copyright (c) ,
|
||||
All rights reserved.
|
||||
|
||||
1. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
|
||||
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
@@ -34,7 +34,7 @@ class TestMgr:
|
||||
def load(self, modify_files, world_size):
|
||||
with open(modify_files) as f:
|
||||
for line in f:
|
||||
if world_size != 0 and "test/distributed/" in line:
|
||||
if world_size != 0 and ("test/distributed/" in line or "test/_inductor/" in line):
|
||||
continue
|
||||
line = line.strip()
|
||||
self.modify_files.append(line)
|
||||
@@ -63,6 +63,9 @@ class TestMgr:
|
||||
def load_distributed_ut(self):
|
||||
self.test_files['ut_files'] += [str(i) for i in (BASE_DIR / 'test/distributed').rglob('test_*.py')]
|
||||
|
||||
def load_inductor_ut(self):
|
||||
self.test_files['ut_files'] += [str(i) for i in (BASE_DIR / 'test/_inductor').rglob('test_*.py')]
|
||||
|
||||
def load_op_plugin_ut(self):
|
||||
version_path = get_test_torch_version_path()
|
||||
file_hash = {}
|
||||
|
||||
@@ -118,6 +118,7 @@ if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description='Control needed ut cases')
|
||||
parser.add_argument('--all', action="store_true", help='Run all testcases')
|
||||
parser.add_argument('--distributed', action="store_true", help='Run distributed testcases')
|
||||
parser.add_argument('--inductor', action="store_true", help='Run inductor testcases')
|
||||
parser.add_argument('--rank', default=0, type=int, help='Index of current ut nodes')
|
||||
parser.add_argument('--world_size', default=0, type=int, help='Number of ut nodes')
|
||||
parser.add_argument('--network_ops', action="store_true", help='Run network_ops testcases in the op-plugin repo')
|
||||
@@ -130,6 +131,8 @@ if __name__ == "__main__":
|
||||
test_mgr.load_all_ut(options.distributed, options.network_ops)
|
||||
elif options.distributed:
|
||||
test_mgr.load_distributed_ut()
|
||||
elif options.inductor:
|
||||
test_mgr.load_inductor_ut()
|
||||
elif os.path.exists(cur_modify_files):
|
||||
test_mgr.load(cur_modify_files, world_size=options.world_size)
|
||||
test_mgr.analyze()
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ This folder hosts the `Dockerfile` to build docker images with various platforms
|
||||
**Clone torch-npu**
|
||||
|
||||
```Shell
|
||||
git clone https://gitee.com/ascend/pytorch.git --depth 1
|
||||
git clone https://gitcode.com/ascend/pytorch.git --depth 1
|
||||
```
|
||||
|
||||
**Build docker image**
|
||||
|
||||
+17
-12
@@ -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
|
||||
|
||||
@@ -24,6 +24,7 @@ from .utils import NPU_AUTOGRAD_FUNCTION
|
||||
GRADIENT_IMPLEMENTED_FOR_COMPLEX.update((
|
||||
"stft",
|
||||
"npu_dtype_cast",
|
||||
"_npu_dtype_cast",
|
||||
))
|
||||
|
||||
NPU_NATIVEFUNCTIONS = {'npu_format_cast', '_npu_format_cast'}
|
||||
@@ -122,6 +123,7 @@ def gen_variable_type_func(
|
||||
type_definition = re.sub(r'at::redispatch::(\w+)_outf', r'at_npu::redispatch::\1_out', type_definition)
|
||||
else:
|
||||
type_definition = type_definition.replace('at::redispatch', 'at_npu::redispatch')
|
||||
type_definition = type_definition.replace('_symint', '')
|
||||
|
||||
wrapper_registration = gen_wrapper_registration(f, "Default")
|
||||
result[f"type_derived_method_definitions"] = [type_definition]
|
||||
|
||||
@@ -9,7 +9,7 @@ from torchgen.gen import (parse_tags_yaml, FileManager, cpp_string, error_check_
|
||||
from torchgen.model import (BackendIndex, DispatchKey, Variant,
|
||||
NativeFunction, OperatorName, BackendMetadata, TensorOptionsArguments)
|
||||
from torchgen.utils import concatMap, mapMaybe
|
||||
from torchgen.context import with_native_function, native_function_manager, method_with_native_function
|
||||
from torchgen.context import with_native_function, native_function_manager, method_with_native_function, with_native_function_and_index
|
||||
from torchgen.api.types import DispatcherSignature
|
||||
from torchgen.api import cpp
|
||||
from torchgen.dest.register_dispatch_key import RegisterDispatchKey
|
||||
@@ -63,7 +63,7 @@ def parse_custom_yaml(custom_path: str, tag_path: str) -> ParsedYaml:
|
||||
error_check_native_functions(rs)
|
||||
# Default dict is to prevent the codegen from barfing when we have a dispatch key that has no kernels yet.
|
||||
indices: Dict[DispatchKey, BackendIndex] = defaultdict(lambda: BackendIndex(
|
||||
dispatch_key=DispatchKey.Undefined, use_out_as_primary=True, external=False, index={}))
|
||||
dispatch_key=DispatchKey.Undefined, use_out_as_primary=True, external=False, device_guard=False, index={}))
|
||||
for k, v in bs.items():
|
||||
# All structured in-tree operators are implemented in terms of their out operator.
|
||||
indices[k] = BackendIndex(dispatch_key=k,
|
||||
@@ -241,8 +241,11 @@ class RegisterCustomSchema:
|
||||
return f'{maybe_tags}m.def({cpp_string(func_schema)}{tag_index});\n'
|
||||
|
||||
|
||||
@with_native_function
|
||||
def compute_register_impl(f: NativeFunction):
|
||||
@with_native_function_and_index
|
||||
def compute_register_impl(f: NativeFunction, backend_index):
|
||||
if (backend_index is not None) and (backend_index.get_kernel(f) is None):
|
||||
return []
|
||||
|
||||
if f.has_composite_explicit_autograd_kernel:
|
||||
return []
|
||||
else:
|
||||
@@ -250,7 +253,7 @@ def compute_register_impl(f: NativeFunction):
|
||||
return [f'm.impl("{f.func.name}", TORCH_FN(at_npu::native::{name}));\n']
|
||||
|
||||
|
||||
def gen_custom_trace(fm: FileManager, custom_trace_functions: Sequence[NativeFunction]):
|
||||
def gen_custom_trace(fm: FileManager, custom_trace_functions: Sequence[NativeFunction], custom_backend_indices):
|
||||
|
||||
fm.write_with_template(f'CustomRegisterSchema.cpp', 'CustomRegisterSchema.cpp', lambda: {
|
||||
'custom_op_definitions': list(concatMap(
|
||||
@@ -262,7 +265,11 @@ def gen_custom_trace(fm: FileManager, custom_trace_functions: Sequence[NativeFun
|
||||
custom_trace_functions
|
||||
)),
|
||||
'custom_impl_registrations': list(concatMap(
|
||||
lambda f: compute_register_impl(f),
|
||||
lambda f: compute_register_impl(f, None),
|
||||
custom_trace_functions
|
||||
)),
|
||||
'custom_autograd_impl_registrations': list(concatMap(
|
||||
lambda f: compute_register_impl(f, custom_backend_indices[DispatchKey.AutogradPrivateUse1]),
|
||||
custom_trace_functions
|
||||
)),
|
||||
})
|
||||
|
||||
@@ -23,6 +23,7 @@ from collections import namedtuple, Counter, defaultdict
|
||||
from typing import List, Dict, Union, Sequence, Optional, Set, Callable
|
||||
import yaml
|
||||
|
||||
import torchgen
|
||||
from torchgen.code_template import CodeTemplate
|
||||
from torchgen.gen import (parse_tags_yaml, FileManager, parse_native_yaml,
|
||||
get_grouped_native_functions, error_check_native_functions)
|
||||
@@ -48,6 +49,8 @@ from codegen.utils import (get_torchgen_dir, rename_privateuse1_dispatch_key, ge
|
||||
from codegen.custom_functions import (parse_custom_yaml, gen_custom_trace, gen_custom_ops_patch,
|
||||
gen_custom_functions_dispatch)
|
||||
|
||||
torchgen.model.dispatch_keys.append(torchgen.model.DispatchKey.AutogradPrivateUse1)
|
||||
|
||||
|
||||
# Create backend_indices map for func retrieval with the key of each func we supported.
|
||||
def create_backend_index(backend_ops: List[str],
|
||||
@@ -300,8 +303,7 @@ the behavior of autograd for some operators on your backend. However "Autograd{b
|
||||
autograd_key, native_functions_map, cpp_namespace)
|
||||
opapi_autograd_idx = create_backend_index([op for op in supported_autograd if is_opapi(op)],
|
||||
symint_set, autograd_key, native_functions_map, cpp_namespace)
|
||||
if autograd_key in backend_indices:
|
||||
raise KeyError("autograd_key should not be in backend_indices.")
|
||||
|
||||
backend_indices[autograd_key] = autograd_idx
|
||||
backend_indices[str(autograd_key) + opapi_key] = opapi_autograd_idx
|
||||
|
||||
@@ -732,15 +734,15 @@ def run(source_yaml: str, output_dir: str, dry_run: bool,
|
||||
register_dispatch_key_func=dest.RegisterDispatchKey,
|
||||
)
|
||||
|
||||
gen_quantize_register(fm, backend_indices["NPUQuantize"])
|
||||
gen_quantize_register(fm, backend_indices=backend_indices["NPUQuantize"])
|
||||
|
||||
pta_template_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "templates")
|
||||
fm = FileManager(install_dir=output_dir, template_dir=pta_template_dir, dry_run=dry_run)
|
||||
|
||||
custom_functions = parse_custom_yaml(source_yaml, tags_yaml_path).native_functions
|
||||
custom_functions, custom_backend_indices = parse_custom_yaml(source_yaml, tags_yaml_path)
|
||||
grouped_custom_functions = get_grouped_native_functions_optional_out(custom_functions)
|
||||
gen_functionalization(fm, selector, grouped_custom_functions)
|
||||
gen_custom_trace(fm, custom_functions)
|
||||
gen_custom_trace(fm, custom_functions, custom_backend_indices)
|
||||
gen_custom_functions_dispatch(fm, custom_functions)
|
||||
|
||||
gen_foreach_register(fm,
|
||||
|
||||
@@ -43,7 +43,7 @@ namespace {
|
||||
|
||||
TORCH_LIBRARY(npu, m) {
|
||||
|
||||
${custom_schema_registrations}
|
||||
${custom_schema_registrations}
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
@@ -52,7 +52,16 @@ namespace {
|
||||
|
||||
TORCH_LIBRARY_IMPL(npu, PrivateUse1, m) {
|
||||
|
||||
${custom_impl_registrations}
|
||||
${custom_impl_registrations}
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
namespace {
|
||||
|
||||
TORCH_LIBRARY_IMPL(npu, AutogradPrivateUse1, m) {
|
||||
|
||||
${custom_autograd_impl_registrations}
|
||||
}
|
||||
|
||||
} // anonymous namespace
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
[metadata]
|
||||
url = https://gitee.com/ascend/pytorch
|
||||
download_url = https://gitee.com/ascend/pytorch/tags
|
||||
url = https://gitcode.com/ascend/pytorch
|
||||
download_url = https://gitcode.com/ascend/pytorch/tags
|
||||
|
||||
@@ -426,7 +426,7 @@ def get_src_py_and_dst():
|
||||
recursive=True) + glob.glob(
|
||||
os.path.join(BASE_DIR, "torch_npu", '**/*.yaml'),
|
||||
recursive=True) + glob.glob(
|
||||
os.path.join(BASE_DIR, "torch_npu", 'acl.json'),
|
||||
os.path.join(BASE_DIR, "torch_npu", 'acl*.json'),
|
||||
recursive=True) + glob.glob(
|
||||
os.path.join(BASE_DIR, "torch_npu", 'contrib/apis_config.json'),
|
||||
recursive=True)
|
||||
@@ -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={
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import torch
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class TestScheduleContext(TestCase):
|
||||
def setUp(self):
|
||||
npu_device = torch._C._get_privateuse1_backend_name()
|
||||
self.window_tensor = torch.ones([1 * 1024 * 1024 * 1024], dtype=torch.int8).to(
|
||||
npu_device
|
||||
)
|
||||
self.default_params = {
|
||||
"schedule_mode": 0,
|
||||
"session_num": 288,
|
||||
"micro_batch_num": 3,
|
||||
"micro_batch_size": 30,
|
||||
"selected_expert_num": 9,
|
||||
"expert_num": 288,
|
||||
"attn_to_ffn_token_size": 7168 + 512,
|
||||
"ffn_to_attn_token_size": 7168 * 2,
|
||||
"attention_window": self.window_tensor.data_ptr(),
|
||||
"attention_window_size": 1 * 1024 * 1024 * 1024,
|
||||
"ffn_window": self.window_tensor.data_ptr(),
|
||||
"ffn_window_size": 1 * 1024 * 1024 * 1024,
|
||||
}
|
||||
|
||||
def tearDown(self):
|
||||
return super().tearDown()
|
||||
|
||||
def test_init_with_invalid_params(self):
|
||||
"""测试参数校验"""
|
||||
invalid_params = [
|
||||
({"session_num": 0}, "session_num=0 should fail"),
|
||||
({"micro_batch_num": 0}, "micro_batch_num=0 should fail"),
|
||||
(
|
||||
{"session_num": 1 << 31, "micro_batch_num": 1 << 31},
|
||||
"micro_batch_num mul overflow",
|
||||
),
|
||||
({"micro_batch_size": 0}, "micro_batch_size=0 should fail"),
|
||||
(
|
||||
{"micro_batch_num": 1 << 31, "micro_batch_size": 1 << 31},
|
||||
"micro_batch_size mul overflow",
|
||||
),
|
||||
(
|
||||
{
|
||||
"schedule_mode": 1,
|
||||
"micro_batch_num": 1 << 31,
|
||||
"micro_batch_size": 1 << 31,
|
||||
},
|
||||
"attention micro_batch_size mul overflow",
|
||||
),
|
||||
({"selected_expert_num": 0}, "selected_expert_num=0 should fail"),
|
||||
(
|
||||
{"micro_batch_size": 1 << 31, "selected_expert_num": 1 << 31},
|
||||
"selected_expert_num mul overflow",
|
||||
),
|
||||
(
|
||||
{
|
||||
"schedule_mode": 1,
|
||||
"micro_batch_size": 1 << 31,
|
||||
"selected_expert_num": 1 << 31,
|
||||
},
|
||||
"attention selected_expert_num mul overflow",
|
||||
),
|
||||
({"ffn_window": 0}, "ffn_window=0 should fail"),
|
||||
({"ffn_window_size": 0}, "ffn_window_size can not be 0"),
|
||||
({"ffn_window_size": 511}, "ffn_window_size is not enough should fail"),
|
||||
({"schedule_mode": 1, "attention_window": 0}, "ffn_window is null"),
|
||||
(
|
||||
{"schedule_mode": 1, "attention_window_size": 0},
|
||||
"attention_window_size can not be 0",
|
||||
),
|
||||
(
|
||||
{"schedule_mode": 1, "attention_window_size": 511},
|
||||
"attention_window_size is not enough should fail",
|
||||
),
|
||||
({"schedule_mode": 2}, "schedule_mode 2 is not supportted"),
|
||||
(
|
||||
{"attn_to_ffn_token_size": 1023},
|
||||
"attn_to_ffn_token_size must be aligned by 512",
|
||||
),
|
||||
(
|
||||
{"ffn_to_attn_token_size": 400},
|
||||
"ffn_to_attn_token_size must be aligned by 512",
|
||||
),
|
||||
]
|
||||
for params, msg in invalid_params:
|
||||
with self.subTest(msg=msg):
|
||||
test_params = self.default_params.copy()
|
||||
test_params.update(params)
|
||||
with self.assertRaises(RuntimeError):
|
||||
torch_npu._afd.create_schedule_context_holder(**test_params)
|
||||
|
||||
def test_schedule_ffn(self):
|
||||
"""测试用有效参数初始化"""
|
||||
holder = torch_npu._afd.create_schedule_context_holder(
|
||||
**self.default_params
|
||||
)
|
||||
self.assertIsInstance(holder, torch_npu._afd.ScheduleContextHolder)
|
||||
|
||||
# 获取tensor
|
||||
tensor = holder.get_schedule_context_tensor()
|
||||
self.assertIsInstance(tensor, torch.Tensor)
|
||||
|
||||
context_info = holder.get_schedule_context_info()
|
||||
self.assertIn("ffn info:", context_info)
|
||||
|
||||
holder.stop_schedule()
|
||||
|
||||
def test_schedule_attn(self):
|
||||
"""测试用有效参数初始化"""
|
||||
test_params = self.default_params.copy()
|
||||
test_params["schedule_mode"] = 1
|
||||
holder = torch_npu._afd.create_schedule_context_holder(**test_params)
|
||||
self.assertIsInstance(holder, torch_npu._afd.ScheduleContextHolder)
|
||||
|
||||
# 获取tensor
|
||||
tensor = holder.get_schedule_context_tensor()
|
||||
self.assertIsInstance(tensor, torch.Tensor)
|
||||
holder.stop_schedule()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,3 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
# Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
|
||||
@@ -0,0 +1,26 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestAbs(TestUtils):
|
||||
def op_calc(self, first_element):
|
||||
result = torch.abs(first_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', [(1024, 32), (256, 8)])
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element)
|
||||
self.assertEqual(std_result, inductor_result, atol=1e-3, rtol=1e-3)
|
||||
|
||||
instantiate_parametrized_tests(TestAbs)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,29 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestAdd(TestUtils):
|
||||
def op_calc(self, first_element, second_element):
|
||||
result = first_element + second_element
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float32', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
second_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_sum = self.op_calc(first_element, second_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_sum = compiled_op_calc(first_element, second_element)
|
||||
|
||||
self.assertEqual(std_sum, inductor_sum)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestAdd)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,38 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestSumAdd(TestUtils):
|
||||
def foo(self, a, b, dim):
|
||||
y = a + b
|
||||
y = y.sum(dim)
|
||||
return y
|
||||
|
||||
# case:change shapes
|
||||
@parametrize('shape', [(9, 9, 31, 64)])
|
||||
@parametrize('dim', [3])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
a, b = [torch.randn(shape, requires_grad=False, dtype=torch.float32, device="npu") for _ in range(2)]
|
||||
r1 = self.foo(a, b, dim)
|
||||
func = torch.compile(self.foo, backend="inductor", dynamic=False)
|
||||
r = func(a, b, dim)
|
||||
self.assertEqual(r, r1, atol=1e-3, rtol=1e-3)
|
||||
|
||||
@parametrize('shape', [(9, 10, 31, 63)])
|
||||
@parametrize('dim', [0, 1])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes1(self, shape, dim, dtype):
|
||||
a, b = [torch.randn(shape, requires_grad=False, dtype=torch.float32, device="npu") for _ in range(2)]
|
||||
r1 = self.foo(a, b, dim)
|
||||
func = torch.compile(self.foo, backend="inductor", dynamic=False)
|
||||
r = func(a, b, dim)
|
||||
self.assertEqual(r, r1, atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestSumAdd)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,27 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestAlias(TestUtils):
|
||||
def op_calc(self, input_element, dim):
|
||||
x = torch.ops.aten.alias(input_element)
|
||||
y = x + 1.0
|
||||
return y
|
||||
|
||||
# case:change shapes
|
||||
@parametrize('shape', [(32, 64)])
|
||||
@parametrize('dim', [0])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
std_ret = self.op_calc(input_element, dim)
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_ret = compiled_op_calc(input_element, dim)
|
||||
self.assertEqual(std_ret, inductor_ret, atol=1e-1, rtol=1e-1, equal_nan=True)
|
||||
|
||||
instantiate_parametrized_tests(TestAlias)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,24 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestArgmax(TestUtils):
|
||||
def argmax(self, a, dim):
|
||||
return torch.argmax(a, dim)
|
||||
|
||||
def test_argmax(self):
|
||||
shape = (512, 64)
|
||||
dim = -1
|
||||
a = torch.randn(shape, requires_grad=False, dtype=torch.float32, device='npu')
|
||||
|
||||
argmax_triton = torch.compile(self.argmax, backend="inductor", dynamic=False)
|
||||
r = self.argmax(a, dim)
|
||||
r1 = argmax_triton(a, dim)
|
||||
self.assertEqual(r, r1, atol=1e-3, rtol=1e-3)
|
||||
|
||||
instantiate_parametrized_tests(TestArgmax)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,24 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestMaxWithIndex(TestUtils):
|
||||
def op_calc(self, input_element, dim):
|
||||
return torch.argmax(input_element, dim)
|
||||
|
||||
@parametrize('shape', [(512, 64)]) # (513, 64), (514,33)
|
||||
@parametrize('dim', [-1])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases(self, shape, dim, dtype):
|
||||
input_element = torch.randn(size=shape, dtype=eval('torch.' + dtype), device=torch.device("npu")) * 2000
|
||||
std_argmax = self.op_calc(input_element, dim)
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor", dynamic=False)
|
||||
inductor_argmax = compiled_op_calc(input_element, dim)
|
||||
self.assertEqual(std_argmax, inductor_argmax, atol=1e-2, rtol=1e-2)
|
||||
|
||||
instantiate_parametrized_tests(TestMaxWithIndex)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,31 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestArrange(TestUtils):
|
||||
def op_calc(self, start, end, step):
|
||||
a = torch.arange(start, end, step, device=torch.device('npu'))
|
||||
y = a + a
|
||||
return y
|
||||
|
||||
@parametrize('shape', [(2, )])
|
||||
@parametrize('dtype', TestUtils._test_dtypes)
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
s = self._generate_tensor(shape, dtype)
|
||||
start = min(s)
|
||||
end = max(s)
|
||||
step = (end - start) / 32
|
||||
|
||||
std_arrange = self.op_calc(start, end, step)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor", dynamic=False)
|
||||
inductor_arrange = compiled_op_calc(start, end, step)
|
||||
|
||||
self.assertEqual(std_arrange, inductor_arrange)
|
||||
|
||||
instantiate_parametrized_tests(TestArrange)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,32 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestAttnCp(TestUtils):
|
||||
shape = (8, 8, 256, 128)
|
||||
dim = -1
|
||||
|
||||
def foo(self, a, b, c):
|
||||
y = a + b
|
||||
y = y.sum(self.dim)
|
||||
y = y.unsqueeze(self.dim)
|
||||
y = y.broadcast_to(self.shape) + b
|
||||
y = c + y.permute(0, 1, 3, 2)
|
||||
return y
|
||||
|
||||
|
||||
def test_pointwise_cases(self):
|
||||
a, b = [torch.randn(self.shape, dtype=torch.float32, device="npu") for _ in range(2)]
|
||||
d = torch.randn(self.shape, dtype=torch.float32, device="npu")
|
||||
c = d.permute(0, 1, 3, 2).contiguous()
|
||||
func = torch.compile(self.foo, backend="inductor")
|
||||
r = func(a, b, c)
|
||||
r1 = self.foo(a, b, c)
|
||||
self.assertEqual(r, r1, atol=1e-3, rtol=1e-3)
|
||||
|
||||
instantiate_parametrized_tests(TestAttnCp)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,46 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestNativeBatchNorm(TestUtils):
|
||||
def op_calc(self, input_element):
|
||||
# 创建权重和偏置张量
|
||||
weight = torch.ones(32).npu()
|
||||
bias = torch.zeros(32).npu()
|
||||
|
||||
# 创建运行均值和方差张量
|
||||
running_mean = torch.zeros(32).npu()
|
||||
running_var = torch.ones(32).npu()
|
||||
momentum = 0.1
|
||||
eps = 1e-05
|
||||
# 执行批量归一化
|
||||
output, running_mean_out, running_var_out = torch.native_batch_norm(
|
||||
input=input_element,
|
||||
weight=weight,
|
||||
bias=bias,
|
||||
running_mean=running_mean,
|
||||
running_var=running_var,
|
||||
training=True,
|
||||
momentum=momentum,
|
||||
eps=eps
|
||||
)
|
||||
return output, running_mean_out, running_var_out
|
||||
|
||||
@parametrize('shape', [(16, 32, 64)])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes(self, shape, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_ret, _, _ = self.op_calc(input_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_ret, _, _ = compiled_op_calc(input_element)
|
||||
self.assertEqual(std_ret, inductor_ret, atol=1e-1, rtol=1e-1, equal_nan=True)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestNativeBatchNorm)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,39 @@
|
||||
import copy
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestBroadcast(TestUtils):
|
||||
broadcast_size = 128
|
||||
|
||||
def op_calc(self, a, b, dim, new_shape):
|
||||
a = a.unsqueeze(dim)
|
||||
a = a.broadcast_to(new_shape)
|
||||
b = b.unsqueeze(dim)
|
||||
b = b.broadcast_to(new_shape)
|
||||
y = a + b
|
||||
return y
|
||||
|
||||
|
||||
@parametrize('shape', [(8, 8, 256)])
|
||||
@parametrize('dtype', ['float32', 'int32', 'float16', 'bfloat16'])
|
||||
def test_view_cases(self, shape, dtype):
|
||||
a = self._generate_tensor(shape, dtype)
|
||||
b = self._generate_tensor(shape, dtype)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor", dynamic=False)
|
||||
for dim in [3, 2, 1, 0]:
|
||||
new_shape = list(copy.deepcopy(shape))
|
||||
new_shape.insert(dim, self.broadcast_size)
|
||||
std_broadcast = self.op_calc(a, b, dim, new_shape)
|
||||
inductor_broadcast = compiled_op_calc(a, b, dim, new_shape)
|
||||
|
||||
self.assertEqual(std_broadcast.float(), inductor_broadcast.float(), atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestBroadcast)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,69 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestCat(TestUtils):
|
||||
|
||||
def op_calc(self, input_element, dim):
|
||||
return torch.cat([input_element, input_element], dim)
|
||||
|
||||
# case:change shapes
|
||||
@parametrize('shape', [(8, 16, 32, 64)])
|
||||
@parametrize('dim', [-1])
|
||||
@parametrize('dtype', ['bfloat16'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
std_cat = self.op_calc(input_element, dim)
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_cat = compiled_op_calc(input_element, dim)
|
||||
self.assertEqual(std_cat, inductor_cat, atol=1e-1, rtol=1e-1, equal_nan=True)
|
||||
|
||||
def op_calc_non_contiguous(self, input_element, dim):
|
||||
return torch.cat([input_element, input_element], dim)
|
||||
|
||||
@parametrize('shape', [(8, 16, 32, 64)])
|
||||
@parametrize('dim', [1])
|
||||
@parametrize('dtype', ['bfloat16'])
|
||||
def test_cat_non_contiguous(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
input_element = input_element.transpose(-1, -2)
|
||||
std_cat = self.op_calc_non_contiguous(input_element, dim)
|
||||
compiled_op_calc = torch.compile(self.op_calc_non_contiguous, backend="inductor")
|
||||
inductor_cat = compiled_op_calc(input_element, dim)
|
||||
self.assertEqual(std_cat, inductor_cat, atol=1e-4, rtol=1e-4, equal_nan=True)
|
||||
|
||||
class PatternModel(torch.nn.Module):
|
||||
def __init__(self, dim):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
|
||||
def forward(self, *xs):
|
||||
slices = [x[..., :sz] for x, sz in zip(xs, (128, 32, 48, 48, 48, 48, 48))]
|
||||
output_tensor = torch.cat(slices, self.dim)
|
||||
|
||||
return output_tensor
|
||||
|
||||
@parametrize('shape', [(128, 50, 128)])
|
||||
@parametrize('dim', [2])
|
||||
@parametrize('dtype', ['float32', 'bfloat16'])
|
||||
def test_model_input_is_concat(self, shape, dim, dtype):
|
||||
inputs = [self._generate_tensor(shape, dtype) for _ in range(7)]
|
||||
|
||||
model = self.PatternModel(dim).to(dtype=getattr(torch, dtype))
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
eager_out = model(*inputs)
|
||||
|
||||
compiled_model = torch.compile(model, backend="inductor")
|
||||
with torch.no_grad():
|
||||
inductor_out = compiled_model(*inputs)
|
||||
|
||||
self.assertEqual(eager_out, inductor_out,
|
||||
atol=1e-4, rtol=1e-4, equal_nan=True)
|
||||
|
||||
instantiate_parametrized_tests(TestCat)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestRelu(TestUtils):
|
||||
def op_calc(self, first_element):
|
||||
result = torch.ceil(first_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float32', 'float16', 'bfloat16'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestRelu)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,71 @@
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
torch._inductor.config.fx_graph_cache = False
|
||||
os.environ["INDUCTOR_ASCEND_CHECK_ACCURACY"] = "1"
|
||||
|
||||
|
||||
class TestCheckAccuracy(TestUtils):
|
||||
def test_check_accuracy_1(self):
|
||||
count_data_dump = 0
|
||||
count_check_accuracy = 0
|
||||
|
||||
def run(x, y):
|
||||
return F.relu(x) - y
|
||||
|
||||
from torch_npu._inductor.npu_triton_heuristics import NPUCachingAutotuner
|
||||
src_data_dump = NPUCachingAutotuner.data_dump
|
||||
|
||||
def wrap_data_dump(self, *args, **kwargs):
|
||||
status = src_data_dump(self, *args, **kwargs)
|
||||
if status:
|
||||
nonlocal count_data_dump
|
||||
count_data_dump += 1
|
||||
return status
|
||||
|
||||
src_check_accuracy = NPUCachingAutotuner.check_accuracy
|
||||
|
||||
def wrap_check_accuracy(self, *args, **kwargs):
|
||||
status = src_check_accuracy(self, *args, **kwargs)
|
||||
if status:
|
||||
nonlocal count_check_accuracy
|
||||
count_check_accuracy += 1
|
||||
return status
|
||||
|
||||
x = torch.randn(10).npu()
|
||||
y = torch.randn(10).npu()
|
||||
g = run(x, y)
|
||||
|
||||
run = torch.compile(run)
|
||||
# compile warmup
|
||||
_ = run(x, y)
|
||||
|
||||
with patch.object(NPUCachingAutotuner, "data_dump", wrap_data_dump), \
|
||||
patch.object(NPUCachingAutotuner, "check_accuracy", wrap_check_accuracy):
|
||||
self.assertTrue(torch_npu._inductor.config.dump_fx_graph)
|
||||
self.assertTrue(torch_npu._inductor.config.check_accuracy)
|
||||
|
||||
# Try run custom path and make sure no data_dump and check_accuracy is invoked.
|
||||
torch_npu._inductor.config.dump_fx_graph = False
|
||||
torch_npu._inductor.config.check_accuracy = False
|
||||
z = run(x, y)
|
||||
self.assertEqual(count_data_dump, 0)
|
||||
self.assertEqual(count_check_accuracy, 0)
|
||||
self.assertEqual(z, g)
|
||||
|
||||
torch_npu._inductor.config.dump_fx_graph = True
|
||||
torch_npu._inductor.config.check_accuracy = True
|
||||
z = run(x, y)
|
||||
self.assertEqual(count_data_dump, 1)
|
||||
self.assertEqual(count_check_accuracy, 1)
|
||||
self.assertEqual(z, g)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,88 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestClamp(TestUtils):
|
||||
|
||||
def op_calc(self, arg, min_value=None, max_value=None):
|
||||
return arg.clamp(min_value, max_value)
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32', 'int64'])
|
||||
def test_pointwise_cases_minmax_is_tensor(self, shape, dtype):
|
||||
min_0 = self._generate_tensor(shape, dtype)
|
||||
max_0 = self._generate_tensor(shape, dtype)
|
||||
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element, min_value=min_0, max_value=max_0)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, min_value=min_0, max_value=max_0)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
@parametrize('shape', [(1,)])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_pointwise_cases_single_scalar(self, shape, dtype):
|
||||
min_numel = 0
|
||||
max_numel = 100
|
||||
|
||||
first_element = 200 * torch.rand(size=shape, dtype=eval('torch.' + dtype), device=torch.device("npu"))
|
||||
|
||||
std_result = self.op_calc(first_element, min_value=min_numel, max_value=max_numel)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, min_value=min_numel, max_value=max_numel)
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
@parametrize('shape', [(1024, 32)])
|
||||
@parametrize('dtype', ['int32'])
|
||||
def test_pointwise_cases_minmax_is_number(self, shape, dtype):
|
||||
min_numel = 0
|
||||
max_numel = 100
|
||||
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element, min_value=min_numel, max_value=max_numel)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, min_value=min_numel, max_value=max_numel)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32', 'int64'])
|
||||
def test_pointwise_cases_max_only(self, shape, dtype):
|
||||
max_numel = 100
|
||||
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element, min_value=None, max_value=max_numel)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, min_value=None, max_value=max_numel)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32', 'int64'])
|
||||
def test_pointwise_cases_min_only(self, shape, dtype):
|
||||
min_numel = 0
|
||||
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element, min_value=min_numel, max_value=None)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, min_value=min_numel, max_value=None)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestClamp)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,27 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestClone(TestUtils):
|
||||
def op_calc(self, input_element, dim):
|
||||
return torch.clone(input_element)
|
||||
|
||||
@parametrize('shape', [(8, 64, 128)])
|
||||
@parametrize('dim', [0])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
std_ret = self.op_calc(input_element, dim)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_ret = compiled_op_calc(input_element, dim)
|
||||
|
||||
self.assertEqual(std_ret, inductor_ret, equal_nan=True)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestClone)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,27 @@
|
||||
import pytest
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from torch._inductor.codecache import CacheBase
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
import torch_npu._inductor
|
||||
|
||||
|
||||
class TestCodeCache(TestUtils):
|
||||
def test_codecache(self):
|
||||
device_properties = torch_npu.npu.get_device_properties(
|
||||
torch_npu.npu.current_device()
|
||||
)
|
||||
|
||||
system1 = CacheBase.get_system()
|
||||
self.assertEqual(system1["device"]["name"], device_properties.name)
|
||||
self.assertEqual(system1["version"]["cann"], torch.version.cann)
|
||||
|
||||
from torch_npu.contrib import transfer_to_npu
|
||||
system2 = CacheBase.get_system()
|
||||
self.assertEqual(system2["device"]["name"], device_properties.name)
|
||||
self.assertEqual(system2["version"]["cann"], torch.version.cann)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestLog(TestUtils):
|
||||
def op_calc(self, first_element):
|
||||
result = torch.cos(first_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float32', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestLog)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,129 @@
|
||||
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from torch._inductor import config
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
os.environ["INDUCTOR_ASCEND_DUMP_FX_GRAPH"] = "1"
|
||||
os.environ["TORCH_COMPILE_DEBUG"] = "1"
|
||||
|
||||
|
||||
class TestDebugMsg(TestUtils):
|
||||
@parametrize('shape_x', [(32, 512, 64)])
|
||||
@parametrize('shape_y', [(32, 1, 64)])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_case1(self, shape_x, shape_y, dtype):
|
||||
x = self._generate_tensor(shape_x, dtype)
|
||||
y = self._generate_tensor(shape_y, dtype)
|
||||
|
||||
|
||||
def run_case1(x, y):
|
||||
z = x + y
|
||||
return z
|
||||
|
||||
run = torch.compile(run_case1, backend='inductor')
|
||||
with config.patch(
|
||||
{
|
||||
"trace.debug_dir": tempfile.mkdtemp(),
|
||||
"force_disable_caches": True,
|
||||
}
|
||||
):
|
||||
with self.assertLogs(
|
||||
logging.getLogger("torch._inductor.debug"), level=logging.WARNING
|
||||
) as cm:
|
||||
run(x, y)
|
||||
|
||||
self.assertEqual(len(cm.output), 1)
|
||||
m = re.match(r"WARNING.* debug trace: (.*)", cm.output[0])
|
||||
self.assertTrue(m)
|
||||
filename = Path(m.group(1))
|
||||
self.assertTrue(filename.is_dir())
|
||||
content = open(filename / "output_code.py").read().rstrip()
|
||||
|
||||
self.assertIn(
|
||||
"# SchedulerNodes: [SchedulerNode(name='op0')]",
|
||||
content
|
||||
)
|
||||
|
||||
self.assertIn(
|
||||
"""
|
||||
# def forward(self, arg0_1, arg1_1):
|
||||
# expand = torch.ops.aten.expand.default(arg1_1, [32, 512, 64]); arg1_1 = None
|
||||
# add = torch.ops.aten.add.Tensor(arg0_1, expand); arg0_1 = expand = None
|
||||
# return (add,)""",
|
||||
content
|
||||
)
|
||||
|
||||
self.assertIn(
|
||||
"""
|
||||
# inputs: [FakeTensor(..., device='npu:0', size=(32, 512, 64), strides=(32768, 64, 1)), FakeTensor(..., device='npu:0', size=(32, 1, 64), strides=(64, 64, 1))]
|
||||
# outputs: [FakeTensor(..., device='npu:0', size=(32, 512, 64), strides=(32768, 64, 1))]""",
|
||||
content
|
||||
)
|
||||
|
||||
|
||||
@parametrize('shape_x', [(32, 512, 64)])
|
||||
@parametrize('shape_y', [(32, 1, 64)])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_case2(self, shape_x, shape_y, dtype):
|
||||
x = self._generate_tensor(shape_x, dtype)
|
||||
y = self._generate_tensor(shape_y, dtype)
|
||||
|
||||
|
||||
def run_case2(x, y):
|
||||
z = x + y
|
||||
z = z.repeat([256, 1, 1])
|
||||
return z
|
||||
|
||||
run = torch.compile(run_case2, backend='inductor')
|
||||
with config.patch(
|
||||
{
|
||||
"trace.debug_dir": tempfile.mkdtemp(),
|
||||
"force_disable_caches": True,
|
||||
}
|
||||
):
|
||||
with self.assertLogs(
|
||||
logging.getLogger("torch._inductor.debug"), level=logging.WARNING
|
||||
) as cm:
|
||||
run(x, y)
|
||||
|
||||
self.assertEqual(len(cm.output), 1)
|
||||
m = re.match(r"WARNING.* debug trace: (.*)", cm.output[0])
|
||||
self.assertTrue(m)
|
||||
filename = Path(m.group(1))
|
||||
self.assertTrue(filename.is_dir())
|
||||
content = open(filename / "output_code.py").read().rstrip()
|
||||
|
||||
self.assertIn(
|
||||
"# SchedulerNodes: [SchedulerNode(name='op0')]",
|
||||
content
|
||||
)
|
||||
|
||||
self.assertIn(
|
||||
"""
|
||||
# def forward(self, arg0_1, arg1_1):
|
||||
# expand = torch.ops.aten.expand.default(arg1_1, [32, 512, 64]); arg1_1 = None
|
||||
# add = torch.ops.aten.add.Tensor(arg0_1, expand); arg0_1 = expand = None
|
||||
# repeat = torch.ops.aten.repeat.default(add, [256, 1, 1]); add = None
|
||||
# return (repeat,)""",
|
||||
content
|
||||
)
|
||||
|
||||
self.assertIn(
|
||||
"""
|
||||
# inputs: [FakeTensor(..., device='npu:0', size=(32, 512, 64), strides=(32768, 64, 1)), FakeTensor(..., device='npu:0', size=(32, 1, 64), strides=(64, 64, 1))]
|
||||
# outputs: [FakeTensor(..., device='npu:0', size=(8192, 512, 64), strides=(32768, 64, 1))]""",
|
||||
content
|
||||
)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestDebugMsg)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,34 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestDevicePut(TestUtils):
|
||||
def op_calc(self, input_element1, input_element2):
|
||||
return torch.add(input_element1, input_element2)
|
||||
|
||||
@parametrize('shape', [(8, 16, 8)])
|
||||
@parametrize('dtype', ['int32'])
|
||||
def test_cases_shapes(self, shape, dtype):
|
||||
low = 0
|
||||
high = 2
|
||||
dtype = eval('torch.' + dtype)
|
||||
npu_device = torch.device('npu:0')
|
||||
input_element1_tmp = torch.randint(low, high, shape, dtype=dtype).cpu()
|
||||
input_element2_tmp = torch.randint(low, high, shape, dtype=dtype).cpu()
|
||||
input_element1 = torch.ops.prims.device_put(input_element1_tmp, npu_device)
|
||||
input_element2 = torch.ops.prims.device_put(input_element2_tmp, npu_device)
|
||||
|
||||
std_ret = self.op_calc(input_element1, input_element2)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_ret = compiled_op_calc(input_element1, input_element2)
|
||||
|
||||
self.assertEqual(std_ret, inductor_ret)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestDevicePut)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestDiv(TestUtils):
|
||||
def op_calc(self, first_element, second_element):
|
||||
result = torch.div(first_element, second_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
second_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element, second_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, second_element)
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestDiv)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,41 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestEmbeddingDense(TestUtils):
|
||||
def op_calc(self, arg, embedding):
|
||||
output = embedding(arg)
|
||||
return output
|
||||
|
||||
# UT skip, reason: precision fail
|
||||
# Added to pytorch-disable-tests.json
|
||||
def test_pointwise_cases(self):
|
||||
|
||||
arg0 = torch.tensor([[14, 1, 2, 10, 0, 10, 0],
|
||||
[9, 13, 13, 4, 7, 15, 14],
|
||||
[8, 0, 3, 15, 4, 2, 6],
|
||||
[15, 12, 13, 9, 0, 8, 1],
|
||||
[8, 15, 4, 15, 12, 9, 3],
|
||||
[6, 11, 12, 8, 0, 13, 8],
|
||||
[4, 10, 1, 12, 0, 0, 4],
|
||||
[6, 6, 15, 6, 0, 10, 15],
|
||||
[2, 5, 14, 0, 5, 7, 9],
|
||||
[13, 4, 14, 11, 11, 9, 2],
|
||||
[1, 1, 5, 1, 1, 6, 14],
|
||||
[3, 9, 8, 4, 13, 8, 3],
|
||||
[4, 10, 8, 13, 6, 8, 3]], device='npu:0')
|
||||
embedding = nn.Embedding(16, 128).npu()
|
||||
std_sub = self.op_calc(arg0, embedding)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_sum = compiled_op_calc(arg0, embedding)
|
||||
self.assertEqual(std_sub, inductor_sum)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestEmbeddingDense)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,29 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestEmbeddingDenseBackward(TestUtils):
|
||||
def op_calc(self, slice_4, sum_23):
|
||||
result = torch.ops.aten.embedding_dense_backward.default(sum_23, slice_4, 512, -1, False)
|
||||
return result
|
||||
|
||||
@parametrize('shape', [(1, 512, 128)])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = torch.randint(low=0, high=128, size=(1, 512), dtype=torch.int64).npu()
|
||||
second_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element, second_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, second_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result, atol=1e-1, rtol=1e-1)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestEmbeddingDenseBackward)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,45 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestEmpty(TestUtils):
|
||||
def op_calc(self):
|
||||
x = torch.empty(8, 64, 128, dtype=torch.float32).npu()
|
||||
x.uniform_(-100, 100)
|
||||
return x
|
||||
|
||||
def op_calc_empty_permuted(self):
|
||||
input_shape = (8, 64, 128)
|
||||
physical_layout = (0, 1, 2)
|
||||
x = torch.empty_permuted(input_shape, physical_layout).npu()
|
||||
x.uniform_(-100, 100)
|
||||
return x
|
||||
|
||||
# case: change shapes
|
||||
@parametrize('shape', [(8, 64, 128)])
|
||||
@parametrize('dim', [0])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_cases_empty(self, shape, dim, dtype):
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_ret = compiled_op_calc()
|
||||
|
||||
self.assertTrue(inductor_ret.numel() > 0)
|
||||
|
||||
@parametrize('shape', [(8, 64, 128)])
|
||||
@parametrize('dim', [0])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_cases_empty_permuted(self, shape, dim, dtype):
|
||||
compiled_op_calc = torch.compile(self.op_calc_empty_permuted, backend="inductor")
|
||||
inductor_ret = compiled_op_calc()
|
||||
|
||||
self.assertTrue(inductor_ret.numel() > 0)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestEmpty)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestEq(TestUtils):
|
||||
def op_calc(self, first_element, second_element):
|
||||
return torch.eq(first_element, second_element)
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float32', 'int32', 'float16', 'bfloat16'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
second_element = first_element.clone()
|
||||
|
||||
# randomly change some elements in second tensor
|
||||
flat_second_view = second_element.flatten()
|
||||
num_elements_to_change = first_element.numel() // 3
|
||||
random_indices = torch.randint(0, first_element.numel(), (num_elements_to_change,))
|
||||
flat_second_view[random_indices] = 1 - flat_second_view[random_indices]
|
||||
|
||||
std_result = self.op_calc(first_element, second_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, second_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestEq)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,71 @@
|
||||
import functools
|
||||
from functools import partial
|
||||
|
||||
from testutils import TestUtils
|
||||
import torch
|
||||
from torch._inductor.codecache import _load_triton_kernel_from_source
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
import torch_npu
|
||||
|
||||
|
||||
src_code_1 = '''
|
||||
import triton
|
||||
import triton.language as tl
|
||||
from triton.compiler.compiler import AttrsDescriptor
|
||||
|
||||
from torch._inductor.runtime import triton_helpers, triton_heuristics
|
||||
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
|
||||
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, DeviceProperties
|
||||
|
||||
from torch._inductor.runtime import triton_helpers
|
||||
from torch_npu._inductor import npu_triton_heuristics
|
||||
from torch_npu._inductor import npu_triton_helpers
|
||||
from torch_npu._inductor.runtime import NPUDeviceProperties
|
||||
from torch_npu._inductor.npu_triton_helpers import libdevice, math as tl_math
|
||||
import torch
|
||||
import torch_npu
|
||||
|
||||
@npu_triton_heuristics.pointwise_npu_index(
|
||||
size_hints=[16384, 32], tile_hint=TileHint.DEFAULT,
|
||||
filename=__file__,
|
||||
triton_meta={'signature': {'in_ptr0': '*fp16', 'in_ptr1': '*fp16', 'out_ptr0': '*fp16', 'y0_numel': 'i32', 'x1_numel': 'i32'},
|
||||
'device': NPUDeviceProperties(type='npu', index=0, multi_processor_count=40, cc='Ascend910B3',
|
||||
major=None, regs_per_multiprocessor=None, max_threads_per_multi_processor=None, warp_size=32),
|
||||
'constants': {}, 'mix_mode': 'aiv'},
|
||||
inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_unk_fused_add_0', 'mutated_arg_names': [],
|
||||
'backend_hash': 'bc71dba4086164e7ac2b0779fa861dbf7467f0265d4a57b8f48cf6dda02b150f', 'split_axis': [0],
|
||||
'tiling_axis': [0, 1], 'axis_names': ['y0', 'x1'], 'low_dims': {1}, 'numof_reduction_axis': 0,
|
||||
'split_axis_dtype': torch.float16, 'dual_reduction': False, 'traced_graph_hash': 'TRACED_GRAPH_HASH',
|
||||
'traced_graph_dir': 'TRACED_GRAPH_DIR'},
|
||||
min_elem_per_thread=0
|
||||
)
|
||||
@triton.jit
|
||||
def triton_unk_fused_add_0(in_ptr0, in_ptr1, out_ptr0, y0_numel, x1_numel, Y0BLOCK: tl.constexpr, Y0BLOCK_SUB: tl.constexpr, X1BLOCK_SUB: tl.constexpr):
|
||||
y0_offset = tl.program_id(0) * Y0BLOCK
|
||||
base_y0= tl.arange(0, Y0BLOCK_SUB)
|
||||
loops_y0 = (Y0BLOCK + Y0BLOCK_SUB - 1) // Y0BLOCK_SUB
|
||||
base_x1= tl.arange(0, X1BLOCK_SUB)
|
||||
loops_x1 = (x1_numel + X1BLOCK_SUB - 1) // X1BLOCK_SUB
|
||||
for loop_y0 in range(loops_y0):
|
||||
y0 = y0_offset + (loop_y0 * Y0BLOCK_SUB) + base_y0[:,None]
|
||||
y0_mask = y0 < min(Y0BLOCK+y0_offset, y0_numel)
|
||||
for loop_x1 in range(loops_x1):
|
||||
x1 = (loop_x1 * X1BLOCK_SUB) + base_x1[None,:]
|
||||
x1_mask = x1 < x1_numel
|
||||
tmp0 = tl.load(in_ptr0 + (x1 + 128*y0), x1_mask & y0_mask)
|
||||
# Not define tmp1 and make error manually for triton: 'tmp1 is not defined'
|
||||
tmp2 = tmp0 + tmp1
|
||||
tl.store(out_ptr0 + (x1 + 32*y0), tmp2, x1_mask & y0_mask)
|
||||
'''
|
||||
|
||||
|
||||
class TestExceptions(TestUtils):
|
||||
def test_triton_kernel_failed(self):
|
||||
with self.assertRaisesRegex(Exception, "tmp1 is not defined"):
|
||||
load_kernel = functools.partial(_load_triton_kernel_from_source, "triton_unk_fused_add_0", src_code_1)
|
||||
kernel = load_kernel()
|
||||
kernel.precompile()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestExp(TestUtils):
|
||||
def op_calc(self, first_element):
|
||||
result = torch.exp(first_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element)
|
||||
self.assertEqual(std_result, inductor_result, atol=1e-1, rtol=1e-1, equal_nan=True)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestExp)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestExpm1(TestUtils):
|
||||
def op_calc(self, first_element):
|
||||
result = torch.expm1(first_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element)
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result, atol=1e-3, rtol=1e-3, equal_nan=True)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestExpm1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestFloor(TestUtils):
|
||||
def op_calc(self, first_element):
|
||||
result = torch.floor(first_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestFloor)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,58 @@
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
torch._inductor.config.fx_graph_cache = False
|
||||
os.environ["INDUCTOR_ASCEND_DUMP_FX_GRAPH"] = "1"
|
||||
|
||||
|
||||
class TestForceFallback(TestUtils):
|
||||
def test_case1(self):
|
||||
op_list = []
|
||||
|
||||
def opoverload_call(self, /, *args, **kwargs):
|
||||
op_list.append(str(self))
|
||||
return self._op(*args, **kwargs)
|
||||
|
||||
def run(x, y):
|
||||
return F.relu(x) + y
|
||||
|
||||
x = torch.randn(10).npu()
|
||||
y = torch.randn(10).npu()
|
||||
g = run(x, y)
|
||||
|
||||
run = torch.compile(run)
|
||||
# compile warmup
|
||||
_ = run(x, y)
|
||||
|
||||
with patch.object(torch._ops.OpOverload, "__call__", opoverload_call):
|
||||
op_list.clear()
|
||||
z = run(x, y)
|
||||
self.assertTrue(len(op_list) == 0)
|
||||
self.assertEqual(z, g)
|
||||
|
||||
op_list.clear()
|
||||
torch_npu._inductor.config.force_fallback_kernel_id = [0]
|
||||
z = run(x, y)
|
||||
self.assertTrue("aten.relu.default" in op_list)
|
||||
self.assertTrue("aten.add.Tensor" in op_list)
|
||||
self.assertEqual(z, g)
|
||||
|
||||
op_list.clear()
|
||||
torch_npu._inductor.config.force_fallback_kernel_id = 'all'
|
||||
z = run(x, y)
|
||||
self.assertTrue("aten.relu.default" in op_list)
|
||||
self.assertTrue("aten.add.Tensor" in op_list)
|
||||
self.assertEqual(z, g)
|
||||
|
||||
# reset
|
||||
torch_npu._inductor.config.force_fallback_kernel_id = []
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestGe(TestUtils):
|
||||
def op_calc(self, first_element, second_element):
|
||||
return torch.ge(first_element, second_element)
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
second_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element, second_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, second_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestGe)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,36 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestGeometric(TestUtils):
|
||||
def op_calc(self):
|
||||
# 创建一个形状为 (3, 3)的张量, 每个位置的概率为 0.5
|
||||
prob = torch.full((16, 16), 0.5).npu()
|
||||
|
||||
#使用 aten.geometric生成几何分布的随机数
|
||||
geometric_tensor = torch.ops.aten.geometric(prob, p=0.5)
|
||||
|
||||
return geometric_tensor
|
||||
|
||||
# UT skip, reason: this has problem in torch 260
|
||||
# Added to pytorch-disable-tests.json
|
||||
@parametrize('shape', [(16, 16, 16)])
|
||||
@parametrize('dim', [0])
|
||||
@parametrize('dtype', ['int32'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
std_ret = self.op_calc()
|
||||
std_ret_mean = torch.mean(std_ret)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_ret = compiled_op_calc()
|
||||
|
||||
inductor_ret_mean = torch.mean(inductor_ret)
|
||||
self.assertTrue(inductor_ret_mean is not None)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestGeometric)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,30 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestGt(TestUtils):
|
||||
def op_calc(self, first_element, second_element):
|
||||
result = torch.gt(first_element, second_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
second_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element, second_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element, second_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestGt)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestSum(TestUtils):
|
||||
def op_sum(self, npu_dropout_backward_9):
|
||||
view_337: "f32[32768, 256]" = torch.ops.aten.view.default(npu_dropout_backward_9, [32768, 256])
|
||||
sum_63: "f32[1, 256]" = torch.ops.aten.sum.dim_IntList(view_337, [0], True)
|
||||
view_338: "f32[256]" = torch.ops.aten.view.default(sum_63, [256])
|
||||
return view_338
|
||||
|
||||
|
||||
def test_high_order_sum(self):
|
||||
npu_dropout_backward_9 = torch.randn((32768, 256), device='npu', dtype=torch.float32)
|
||||
ref = self.op_sum(npu_dropout_backward_9)
|
||||
func = torch.compile(self.op_sum, backend="inductor", dynamic=False)
|
||||
calc = func(npu_dropout_backward_9)
|
||||
|
||||
self.assertEqual(ref, calc, atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,60 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class Test_issue54(TestUtils):
|
||||
def func_layernorm(self, args):
|
||||
add_3, primals_6, primals_7, view, primals_9, permute_1, primals_10, primals_11 = args
|
||||
permute: "f32[256, 256]" = torch.ops.aten.permute.default(primals_6, [1, 0])
|
||||
addmm: "f32[32768, 256]" = torch.ops.aten.addmm.default(primals_7, view, permute)
|
||||
view_1: "f32[64, 512, 256]" = torch.ops.aten.view.default(addmm, [64, 512, 256])
|
||||
addmm_1: "f32[32768, 256]" = torch.ops.aten.addmm.default(primals_9, view, permute_1)
|
||||
view_3: "f32[64, 512, 256]" = torch.ops.aten.view.default(addmm_1, [64, 512, 256])
|
||||
view_4: "f32[64, 512, 4, 64]" = torch.ops.aten.view.default(view_3, [64, 512, 4, 64])
|
||||
permute_2: "f32[64, 4, 512, 64]" = torch.ops.aten.permute.default(view_4, [0, 2, 1, 3])
|
||||
permute_3: "f32[256, 256]" = torch.ops.aten.permute.default(primals_10, [1, 0])
|
||||
addmm_2: "f32[32768, 256]" = torch.ops.aten.addmm.default(primals_11, view, permute_3)
|
||||
view_6: "f32[64, 512, 256]" = torch.ops.aten.view.default(addmm_2, [64, 512, 256])
|
||||
|
||||
view_8: "f32[64, 512, 4, 64]" = torch.ops.aten.view.default(view_1, [64, 512, 4, 64])
|
||||
permute_5: "f32[64, 4, 512, 64]" = torch.ops.aten.permute.default(view_8, [0, 2, 1, 3])
|
||||
|
||||
permute_6: "f32[64, 4, 64, 512]" = torch.ops.aten.permute.default(permute_2, [0, 1, 3, 2])
|
||||
expand_1: "f32[64, 4, 512, 64]" = torch.ops.aten.expand.default(permute_5, [64, 4, 512, 64])
|
||||
clone: "f32[64, 4, 512, 64]" = torch.ops.aten.clone.default(expand_1, memory_format=torch.contiguous_format)
|
||||
view_9: "f32[256, 512, 64]" = torch.ops.aten.view.default(clone, [256, 512, 64])
|
||||
expand_2: "f32[64, 4, 64, 512]" = torch.ops.aten.expand.default(permute_6, [64, 4, 64, 512])
|
||||
clone_1: "f32[64, 4, 64, 512]" = torch.ops.aten.clone.default(expand_2, memory_format=torch.contiguous_format)
|
||||
view_10: "f32[256, 64, 512]" = torch.ops.aten.view.default(clone_1, [256, 64, 512])
|
||||
bmm: "f32[256, 512, 512]" = torch.ops.aten.bmm.default(view_9, view_10)
|
||||
view_7: "f32[64, 512, 4, 64]" = torch.ops.aten.view.default(view_6, [64, 512, 4, 64])
|
||||
permute_4: "f32[64, 4, 512, 64]" = torch.ops.aten.permute.default(view_7, [0, 2, 1, 3])
|
||||
expand_4: "f32[64, 4, 512, 64]" = torch.ops.aten.expand.default(permute_4, [64, 4, 512, 64])
|
||||
clone_2: "f32[64, 4, 512, 64]" = torch.ops.aten.clone.default(expand_4, memory_format=torch.contiguous_format)
|
||||
view_13: "f32[256, 512, 64]" = torch.ops.aten.view.default(clone_2, [256, 512, 64])
|
||||
|
||||
return bmm, view_13
|
||||
|
||||
def test_issue54(self):
|
||||
device = 'npu'
|
||||
add_3 = torch.randn((64, 512, 256), device=device, dtype=torch.float32)
|
||||
primals_6 = torch.randn((256, 256), device=device, dtype=torch.float32)
|
||||
primals_7 = torch.randn((256), device=device, dtype=torch.float32)
|
||||
view = torch.randn((32768, 256), device=device, dtype=torch.float32)
|
||||
primals_9 = torch.randn((256), device=device, dtype=torch.float32)
|
||||
permute_1 = torch.randn((256, 256), device=device, dtype=torch.float32)
|
||||
primals_10 = torch.randn((256, 256), device=device, dtype=torch.float32)
|
||||
primals_11 = torch.randn((256), device=device, dtype=torch.float32)
|
||||
args = (add_3, primals_6, primals_7, view, primals_9, permute_1, primals_10, primals_11)
|
||||
ref = self.func_layernorm(args)
|
||||
func = torch.compile(self.func_layernorm, backend="inductor", dynamic=False,
|
||||
options={"unroll_reductions_threshold": 1, "aggressive_fusion": True})
|
||||
calc = func(args)
|
||||
self.assertEqual(ref[0], calc[0], atol=1e-2, rtol=1e-2)
|
||||
self.assertEqual(ref[1], calc[1], atol=1e-2, rtol=1e-2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,35 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class Test_issue57(TestUtils):
|
||||
def op_sum(self, view_12, embedding_1, slice_11):
|
||||
permute_7 = torch.ops.aten.permute.default(embedding_1, [2, 0, 1])
|
||||
embedding_1 = None
|
||||
unsqueeze_4 = torch.ops.aten.unsqueeze.default(permute_7, 0)
|
||||
permute_7 = None
|
||||
|
||||
add_5 = torch.ops.aten.add.Tensor(unsqueeze_4, slice_11)
|
||||
slice_8 = slice_11 = None
|
||||
add_6 = torch.ops.aten.add.Tensor(view_12, add_5)
|
||||
view_12 = None
|
||||
return add_6
|
||||
|
||||
def test_issue57(self):
|
||||
device = 'npu'
|
||||
embedding_1 = torch.randn((512, 512, 64), device=device, dtype=torch.float32)
|
||||
primals_221 = torch.randn((1, 1, 1, 512), device=device, dtype=torch.float32)
|
||||
view_12 = torch.randn((1, 64, 512, 512), device=device, dtype=torch.float32)
|
||||
slice_11 = torch.randn((1, 1, 1, 512), device=device, dtype=torch.float32)
|
||||
|
||||
ref = self.op_sum(view_12, embedding_1, primals_221)
|
||||
func = torch.compile(self.op_sum, backend="inductor", dynamic=False)
|
||||
calc = func(view_12, embedding_1, primals_221)
|
||||
|
||||
self.assertEqual(ref, calc, atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,38 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class Test_issue59(TestUtils):
|
||||
def layernorm_backward(self, x, y, z):
|
||||
sum_0 = torch.sum(x)
|
||||
mean = sum_0 / torch.numel(sum_0)
|
||||
sub = x - mean
|
||||
sqr = sub * sub
|
||||
sum_1 = torch.sum(sqr)
|
||||
mean_1 = sum_1 / torch.numel(sum_1) + 1e-05
|
||||
rsqrt = torch.rsqrt(mean_1)
|
||||
mul = sub * rsqrt
|
||||
mul_1 = mul * y
|
||||
add = mul_1 + z
|
||||
mean_2 = rsqrt / torch.numel(rsqrt)
|
||||
return mul, add, mean_2
|
||||
|
||||
def test_issue59(self):
|
||||
device = 'npu'
|
||||
x = torch.randn((1, 1024), device=device, dtype=torch.float32)
|
||||
y = torch.randn((1, 1024), device=device, dtype=torch.float32)
|
||||
z = torch.randn((1, 1024), device=device, dtype=torch.float32)
|
||||
|
||||
mul, add, mean_2 = self.layernorm_backward(x, y, z)
|
||||
func = torch.compile(self.layernorm_backward, backend="inductor", dynamic=False)
|
||||
mul_t, add_t, mean_2_t = func(x, y, z)
|
||||
|
||||
self.assertEqual(mul, mul_t, atol=1e-3, rtol=1e-3)
|
||||
self.assertEqual(add, add_t, atol=1e-3, rtol=1e-3)
|
||||
self.assertEqual(mean_2, mean_2_t, atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,47 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class Test_issue62(TestUtils):
|
||||
def op_func(self, addmm_5, add):
|
||||
split = torch.ops.aten.split.Tensor(addmm_5, 1536, 1)
|
||||
getitem = split[0]
|
||||
getitem_1 = split[1]
|
||||
getitem_2 = split[2]
|
||||
getitem_3 = split[3]
|
||||
getitem_4 = split[4]
|
||||
getitem_5 = split[5]
|
||||
|
||||
clone_1 = torch.ops.aten.clone.default(add, memory_format=torch.contiguous_format)
|
||||
convert_element_type_25 = torch.ops.prims.convert_element_type.default(clone_1, torch.float32)
|
||||
var_mean = torch.ops.aten.var_mean.correction(convert_element_type_25, [2], correction=0, keepdim=True)
|
||||
getitem_6 = var_mean[0]
|
||||
getitem_7 = var_mean[1]
|
||||
add_3 = torch.ops.aten.add.Tensor(getitem_6, 1e-06)
|
||||
rsqrt = torch.ops.aten.rsqrt.default(add_3)
|
||||
sub = torch.ops.aten.sub.Tensor(clone_1, getitem_7)
|
||||
mul_7 = torch.ops.aten.mul.Tensor(sub, rsqrt)
|
||||
convert_element_type_26 = torch.ops.prims.convert_element_type.default(mul_7, torch.float16)
|
||||
slice_11 = torch.ops.aten.slice.Tensor(getitem_1, 0, 0, 9223372036854775807)
|
||||
unsqueeze_2 = torch.ops.aten.unsqueeze.default(slice_11, 1)
|
||||
add_4 = torch.ops.aten.add.Tensor(unsqueeze_2, 1)
|
||||
mul_8 = torch.ops.aten.mul.Tensor(convert_element_type_26, add_4)
|
||||
slice_12 = torch.ops.aten.slice.Tensor(getitem, 0, 0, 9223372036854775807)
|
||||
unsqueeze_3 = torch.ops.aten.unsqueeze.default(slice_12, 1)
|
||||
add_5 = torch.ops.aten.add.Tensor(mul_8, unsqueeze_3)
|
||||
return add_5
|
||||
|
||||
def test_issue62(self):
|
||||
addmm_5 = torch.randn((2, 9216), device='npu:0', dtype=torch.float16)
|
||||
add = torch.randn((2, 4096, 1536), device='npu:0', dtype=torch.float16)
|
||||
|
||||
std_ret = self.op_func(addmm_5, add)
|
||||
compiled_func = torch.compile(self.op_func, backend="inductor")
|
||||
inductor_ret = compiled_func(addmm_5, add)
|
||||
self.assertEqual(std_ret, inductor_ret, atol=1e-2, rtol=1e-2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,22 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class Test_issue70(TestUtils):
|
||||
def op_forward(self, x):
|
||||
return x.mean(-1)
|
||||
|
||||
def test_issue70(self):
|
||||
compiled_net = torch.compile(self.op_forward, backend="inductor")
|
||||
|
||||
arg = torch.randn((1, 1, 7168)).npu()
|
||||
|
||||
output = self.op_forward(arg)
|
||||
output1 = compiled_net(arg)
|
||||
self.assertEqual(output, output1, atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,35 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestLazyRegister(TestUtils):
|
||||
def test_compile_but_not_invoked(self):
|
||||
|
||||
def run(x, y):
|
||||
return x + y
|
||||
|
||||
run = torch.compile(run)
|
||||
self.assertFalse(torch_npu.utils._dynamo.is_inductor_npu_initialized())
|
||||
|
||||
def test_disale_register_inductor_npu(self):
|
||||
torch_npu.utils._dynamo.disable_register_inductor_npu()
|
||||
|
||||
def run(x, y):
|
||||
return x - y
|
||||
|
||||
run = torch.compile(run)
|
||||
x = torch.randn(10, 20).npu()
|
||||
y = torch.randn(10, 20).npu()
|
||||
|
||||
with self.assertRaisesRegex(Exception, "Device npu not supported"):
|
||||
_ = run(x, y)
|
||||
|
||||
self.assertFalse(torch_npu.utils._dynamo.is_inductor_npu_initialized())
|
||||
|
||||
torch_npu.utils._dynamo.enable_register_inductor_npu()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,44 @@
|
||||
import os
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from torch._inductor.utils import run_and_get_code
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
torch._inductor.config.fx_graph_cache = False
|
||||
os.environ["INDUCTOR_ASCEND_CHECK_ACCURACY"] = "1"
|
||||
|
||||
|
||||
class TestLoweringFx(TestUtils):
|
||||
@parametrize('shape', [(32, 16, 64, 128)])
|
||||
@parametrize('dim', [0])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_sum_not_fallback(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype, floatPOSIFLAG=1)
|
||||
golden = torch.sum(input_element, dim)
|
||||
compiled_op_calc = torch.compile(torch.sum, backend="inductor", dynamic=False)
|
||||
inductor_result, output_codes = run_and_get_code(compiled_op_calc, input_element, dim)
|
||||
self.assertTrue(len(output_codes) == 1)
|
||||
self.assertTrue(output_codes[0].count("async_compile.triton") == 1)
|
||||
self.assertTrue(output_codes[0].count(".run(") == 1)
|
||||
torch.testing.assert_close(golden, inductor_result, rtol=1e-4, atol=1e-4)
|
||||
|
||||
@parametrize('shape', [(32, 16, 64, 128)])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_div_by_reciprocal_mul(self, shape, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
divisor = 128.0
|
||||
golden = torch.div(input_element, divisor)
|
||||
compiled_op_calc = torch.compile(torch.div, backend="inductor", dynamic=False)
|
||||
inductor_result, output_codes = run_and_get_code(compiled_op_calc, input_element, divisor)
|
||||
self.assertTrue(len(output_codes) == 1)
|
||||
self.assertTrue(output_codes[0].count("async_compile.triton") == 1)
|
||||
self.assertTrue("torch.ops.aten.div.Tensor(" not in output_codes[0])
|
||||
self.assertTrue("torch.ops.aten.mul.Tensor(" in output_codes[0])
|
||||
torch.testing.assert_close(golden, inductor_result, rtol=1e-4, atol=1e-4)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestLoweringFx)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,266 @@
|
||||
import os
|
||||
import random
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
from torch import device
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
device_npu = 'npu'
|
||||
|
||||
|
||||
class TestModel(TestUtils):
|
||||
def test_opensora_cases_model_9_inference(self):
|
||||
def forward(primals_1: "f32[1, 9600, 2304]"):
|
||||
permute: "f32[9600, 1, 2304]" = torch.ops.aten.permute.default(primals_1, [1, 0, 2])
|
||||
return permute
|
||||
primals_2 = torch.randn((1, 9600, 2304), device=device_npu, dtype=torch.float32)
|
||||
ref = forward(primals_2)
|
||||
forward_calc = torch.compile(forward, backend="inductor", dynamic=False)
|
||||
calc = forward_calc(primals_2)
|
||||
self.assertEqual(ref, calc, atol=1e-4, rtol=1e-4, equal_nan=True)
|
||||
primals_3 = torch.randn((1, 512, 2304), device=device_npu, dtype=torch.float32)
|
||||
forward_calc = torch.compile(forward, backend="inductor", dynamic=False)
|
||||
calc = forward_calc(primals_3)
|
||||
ref = forward(primals_3)
|
||||
self.assertEqual(ref, calc, atol=1e-4, rtol=1e-4, equal_nan=True)
|
||||
primals_4 = torch.randn((9600, 1, 2304), device=device_npu, dtype=torch.float32)
|
||||
forward_calc = torch.compile(forward, backend="inductor", dynamic=False)
|
||||
calc = forward_calc(primals_4)
|
||||
ref = forward(primals_4)
|
||||
self.assertEqual(ref, calc, atol=1e-4, rtol=1e-4, equal_nan=True)
|
||||
|
||||
def test_opensora_cases_model_11_inference(self):
|
||||
def forward(arg0_1: "f32[1, 1, 9600]", arg1_1: "f32[1, 1, 512]"):
|
||||
unsqueeze: "f32[1, 1, 1, 9600]" = torch.ops.aten.unsqueeze.default(arg0_1, 1)
|
||||
arg0_1 = None
|
||||
unsqueeze_1: "f32[1, 1, 1, 512]" = torch.ops.aten.unsqueeze.default(arg1_1, 1)
|
||||
arg1_1 = None
|
||||
constant_pad_nd: "f32[1, 1, 1, 9600]" = torch.ops.aten.constant_pad_nd.default(unsqueeze, [0, 0, 0, 0], -9980.0)
|
||||
unsqueeze = None
|
||||
view: "f32[1, 9600, 1]" = torch.ops.aten.view.default(constant_pad_nd, [1, 9600, 1])
|
||||
permute: "f32[1, 1, 9600]" = torch.ops.aten.permute.default(view, [2, 0, 1])
|
||||
view = None
|
||||
view_1: "f32[1, 1, 1, 9600]" = torch.ops.aten.view.default(permute, [1, 1, 1, 9600])
|
||||
permute = None
|
||||
view_2: "f32[1, 9600, 1, 1]" = torch.ops.aten.view.default(constant_pad_nd, [1, 9600, 1, 1])
|
||||
constant_pad_nd = None
|
||||
permute_1: "f32[1, 1, 9600, 1]" = torch.ops.aten.permute.default(view_2, [2, 0, 1, 3])
|
||||
view_2 = None
|
||||
view_3: "f32[1, 1, 1, 9600]" = torch.ops.aten.view.default(permute_1, [1, 1, 1, 9600])
|
||||
permute_1 = None
|
||||
repeat: "f32[1, 1, 1, 512]" = torch.ops.aten.repeat.default(unsqueeze_1, [1, 1, 1, 1])
|
||||
unsqueeze_1 = None
|
||||
npu_dtype_cast: "b8[1, 1, 1, 9600]" = torch.ops.npu.npu_dtype_cast.default(view_1, torch.bool)
|
||||
view_1 = None
|
||||
repeat_1: "b8[1, 1, 9600, 9600]" = torch.ops.aten.repeat.default(npu_dtype_cast, [1, 1, 9600, 1])
|
||||
npu_dtype_cast = None
|
||||
npu_dtype_cast_1: "b8[1, 1, 1, 9600]" = torch.ops.npu.npu_dtype_cast.default(view_3, torch.bool)
|
||||
view_3 = None
|
||||
repeat_2: "b8[1, 1, 9600, 9600]" = torch.ops.aten.repeat.default(npu_dtype_cast_1, [1, 1, 9600, 1])
|
||||
npu_dtype_cast_1 = None
|
||||
npu_dtype_cast_2: "b8[1, 1, 1, 512]" = torch.ops.npu.npu_dtype_cast.default(repeat, torch.bool)
|
||||
repeat = None
|
||||
repeat_3: "b8[1, 1, 9600, 512]" = torch.ops.aten.repeat.default(npu_dtype_cast_2, [1, 1, 9600, 1])
|
||||
npu_dtype_cast_2 = None
|
||||
return (repeat_1, repeat_3, repeat_2)
|
||||
arg0_1 = torch.rand((1, 1, 9600), device=device_npu, dtype=torch.float32)
|
||||
arg1_1 = torch.rand((1, 1, 512), device=device_npu, dtype=torch.float32)
|
||||
ref = forward(arg0_1, arg1_1)
|
||||
forward_calc = torch.compile(forward, backend="inductor", dynamic=False)
|
||||
calc = forward_calc(arg0_1, arg1_1)
|
||||
|
||||
for r, c in zip(ref, calc):
|
||||
self.assertEqual(r, c, atol=1e-4, rtol=1e-4, equal_nan=True)
|
||||
|
||||
|
||||
def test_opensora_cases_model_14_backward(self):
|
||||
def forward(args):
|
||||
primals_5, getitem_3, rsqrt, add_2, view, permute_1, tangents_1 = args
|
||||
sub: "f32[1, 9600, 2304]" = torch.ops.aten.sub.Tensor(primals_5, getitem_3)
|
||||
mul: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(sub, rsqrt)
|
||||
view_2: "f32[9600, 32]" = torch.ops.aten.view.default(tangents_1, [9600, 32])
|
||||
mm: "f32[9600, 2304]" = torch.ops.aten.mm.default(view_2, permute_1)
|
||||
permute_2: "f32[32, 9600]" = torch.ops.aten.permute.default(view_2, [1, 0])
|
||||
mm_1: "f32[32, 2304]" = torch.ops.aten.mm.default(permute_2, view)
|
||||
permute_3: "f32[2304, 32]" = torch.ops.aten.permute.default(mm_1, [1, 0])
|
||||
sum_1: "f32[1, 32]" = torch.ops.aten.sum.dim_IntList(view_2, [0], True)
|
||||
view_3: "f32[32]" = torch.ops.aten.view.default(sum_1, [32])
|
||||
permute_4: "f32[32, 2304]" = torch.ops.aten.permute.default(permute_3, [1, 0])
|
||||
view_4: "f32[1, 9600, 2304]" = torch.ops.aten.view.default(mm, [1, 9600, 2304])
|
||||
sum_2: "f32[1, 1, 2304]" = torch.ops.aten.sum.dim_IntList(view_4, [1], True)
|
||||
mul_2: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(view_4, mul)
|
||||
mul_3: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(view_4, add_2)
|
||||
sum_3: "f32[1, 1, 2304]" = torch.ops.aten.sum.dim_IntList(mul_2, [1], True)
|
||||
mul_5: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(mul_3, 2304)
|
||||
sum_4: "f32[1, 9600, 1]" = torch.ops.aten.sum.dim_IntList(mul_3, [2], True)
|
||||
mul_6: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(mul_3, mul)
|
||||
sum_5: "f32[1, 9600, 1]" = torch.ops.aten.sum.dim_IntList(mul_6, [2], True)
|
||||
mul_7: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(mul, sum_5)
|
||||
sub_2: "f32[1, 9600, 2304]" = torch.ops.aten.sub.Tensor(mul_5, sum_4)
|
||||
sub_3: "f32[1, 9600, 2304]" = torch.ops.aten.sub.Tensor(sub_2, mul_7)
|
||||
div: "f32[1, 9600, 1]" = torch.ops.aten.div.Tensor(rsqrt, 2304)
|
||||
mul_8: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(div, sub_3)
|
||||
cat: "f32[1, 2, 2304]" = torch.ops.aten.cat.default([sum_2, sum_3], 1)
|
||||
sum_6: "f32[1, 1, 2304]" = torch.ops.aten.sum.dim_IntList(cat, [1], True)
|
||||
squeeze_1: "f32[1, 2304]" = torch.ops.aten.squeeze.dim(sum_6, 1)
|
||||
full_default: "f32[1, 2304]" = torch.ops.aten.full.default([1, 2304], 0, dtype=torch.float32, device='npu')
|
||||
slice_scatter: "f32[1, 2304]" = torch.ops.aten.slice_scatter.default(full_default, squeeze_1, 0, 0,
|
||||
9223372036854775807)
|
||||
squeeze_2: "f32[2, 2304]" = torch.ops.aten.squeeze.dim(cat, 0)
|
||||
return [squeeze_2, permute_4, view_3, slice_scatter, mul_8]
|
||||
primals_5 = torch.randn((1, 9600, 2304), device=device_npu, dtype=torch.float32)
|
||||
getitem_3 = torch.randn((1, 9600, 1), device=device_npu, dtype=torch.float32)
|
||||
rsqrt = torch.randn((1, 9600, 1), device=device_npu, dtype=torch.float32)
|
||||
add_2 = torch.randn((1, 1, 2304), device=device_npu, dtype=torch.float32)
|
||||
view = torch.randn((9600, 2304), device=device_npu, dtype=torch.float32)
|
||||
permute_1 = torch.randn((32, 2304), device=device_npu, dtype=torch.float32)
|
||||
tangents_1 = torch.randn((1, 9600, 32), device=device_npu, dtype=torch.float32)
|
||||
args = (primals_5, getitem_3, rsqrt, add_2, view, permute_1, tangents_1)
|
||||
ref = forward(args)
|
||||
forward_calc = torch.compile(forward, backend="inductor", dynamic=False)
|
||||
calc = forward_calc(args)
|
||||
|
||||
for r, c in zip(ref, calc):
|
||||
self.assertEqual(r, c, atol=1e-3, rtol=1e-3, equal_nan=True)
|
||||
|
||||
|
||||
def test_opensora_cases_model_14_forward(self):
|
||||
def forward(primals_1: "f32[2, 2304]", primals_2: "f32[32, 2304]", primals_3: "f32[32]",
|
||||
primals_4: "f32[1, 2304]", primals_5: "f32[1, 9600, 2304]"):
|
||||
unsqueeze: "f32[1, 2, 2304]" = torch.ops.aten.unsqueeze.default(primals_1, 0)
|
||||
primals_1 = None
|
||||
slice_1: "f32[1, 2304]" = torch.ops.aten.slice.Tensor(primals_4, 0, 0, 9223372036854775807)
|
||||
primals_4 = None
|
||||
unsqueeze_1: "f32[1, 1, 2304]" = torch.ops.aten.unsqueeze.default(slice_1, 1)
|
||||
slice_1 = None
|
||||
add: "f32[1, 2, 2304]" = torch.ops.aten.add.Tensor(unsqueeze, unsqueeze_1)
|
||||
unsqueeze = unsqueeze_1 = None
|
||||
split = torch.ops.aten.split.Tensor(add, 1, 1)
|
||||
add = None
|
||||
getitem: "f32[1, 1, 2304]" = split[0]
|
||||
getitem_1: "f32[1, 1, 2304]" = split[1]
|
||||
split = None
|
||||
var_mean = torch.ops.aten.var_mean.correction(primals_5, [2], correction=0, keepdim=True)
|
||||
getitem_2: "f32[1, 9600, 1]" = var_mean[0]
|
||||
getitem_3: "f32[1, 9600, 1]" = var_mean[1]
|
||||
var_mean = None
|
||||
add_1: "f32[1, 9600, 1]" = torch.ops.aten.add.Tensor(getitem_2, 1e-06)
|
||||
getitem_2 = None
|
||||
rsqrt: "f32[1, 9600, 1]" = torch.ops.aten.rsqrt.default(add_1)
|
||||
add_1 = None
|
||||
sub: "f32[1, 9600, 2304]" = torch.ops.aten.sub.Tensor(primals_5, getitem_3)
|
||||
mul: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(sub, rsqrt)
|
||||
sub = None
|
||||
add_2: "f32[1, 1, 2304]" = torch.ops.aten.add.Tensor(getitem_1, 1)
|
||||
getitem_1 = None
|
||||
mul_1: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(mul, add_2)
|
||||
mul = None
|
||||
add_3: "f32[1, 9600, 2304]" = torch.ops.aten.add.Tensor(mul_1, getitem)
|
||||
mul_1 = getitem = None
|
||||
view: "f32[9600, 2304]" = torch.ops.aten.view.default(add_3, [9600, 2304])
|
||||
add_3 = None
|
||||
permute: "f32[2304, 32]" = torch.ops.aten.permute.default(primals_2, [1, 0])
|
||||
primals_2 = None
|
||||
addmm: "f32[9600, 32]" = torch.ops.aten.addmm.default(primals_3, view, permute)
|
||||
primals_3 = None
|
||||
view_1: "f32[1, 9600, 32]" = torch.ops.aten.view.default(addmm, [1, 9600, 32])
|
||||
addmm = None
|
||||
# No stacktrace found for following nodes
|
||||
squeeze: "f32[1, 9600, 32]" = torch.ops.aten.squeeze.dim(view_1, 1)
|
||||
view_1 = None
|
||||
permute_1: "f32[32, 2304]" = torch.ops.aten.permute.default(permute, [1, 0])
|
||||
permute = None
|
||||
return [squeeze, primals_5, getitem_3, rsqrt, add_2, view, permute_1]
|
||||
primals_1 = torch.ones((2, 2304), device=device_npu, dtype=torch.float32)
|
||||
primals_2 = torch.ones((32, 2304), device=device_npu, dtype=torch.float32)
|
||||
primals_3 = torch.ones((32,), device=device_npu, dtype=torch.float32)
|
||||
primals_4 = torch.ones((1, 2304), device=device_npu, dtype=torch.float32)
|
||||
primals_5 = torch.ones((1, 9600, 2304), device=device_npu, dtype=torch.float32)
|
||||
ref = forward(primals_1, primals_2, primals_3, primals_4, primals_5)
|
||||
forward_calc = torch.compile(forward, backend="inductor", dynamic=False)
|
||||
calc = forward_calc(primals_1, primals_2, primals_3, primals_4, primals_5)
|
||||
for r, c in zip(ref, calc):
|
||||
self.assertEqual(r, c, atol=1e-4, rtol=1e-4, equal_nan=True)
|
||||
|
||||
|
||||
def test_opensora_cases_model_15_forward(self):
|
||||
def forward(primals_1: "f32[1, 8, 30, 40, 1, 2, 2, 8]", primals_2: "i64[]", primals_3: "i64[]",
|
||||
primals_4: "i64[]"):
|
||||
permute: "f32[1, 8, 8, 1, 30, 2, 40, 2]" = torch.ops.aten.permute.default(primals_1, [0, 7, 1, 4, 2, 5, 3, 6])
|
||||
mul: "i64[]" = torch.ops.aten.mul.Tensor(primals_2, 1)
|
||||
mul_1: "i64[]" = torch.ops.aten.mul.Tensor(primals_3, 2)
|
||||
mul_2: "i64[]" = torch.ops.aten.mul.Tensor(primals_4, 2)
|
||||
return [permute, mul, mul_1, mul_2]
|
||||
|
||||
primals_1 = torch.randn((1, 8, 30, 40, 1, 2, 2, 8), device=device_npu, dtype=torch.float32)
|
||||
primals_2 = torch.tensor((1), device=device_npu, dtype=torch.int64)
|
||||
primals_3 = torch.tensor((1), device=device_npu, dtype=torch.int64)
|
||||
primals_4 = torch.tensor((1), device=device_npu, dtype=torch.int64)
|
||||
ref = forward(primals_1, primals_2, primals_3,
|
||||
primals_4)
|
||||
forward_calc = torch.compile(forward, backend="inductor", dynamic=False)
|
||||
calc = forward_calc(primals_1, primals_2, primals_3,
|
||||
primals_4)
|
||||
for r, c in zip(ref, calc):
|
||||
self.assertEqual(r, c, atol=1e-4, rtol=1e-4, equal_nan=True)
|
||||
|
||||
def test_opensora_cases_model_16_forward(self):
|
||||
def forward(primals_1: "f32[2, 2304]", primals_2: "f32[32, 2304]", primals_3: "f32[32]", primals_4: "f32[1, 2304]", primals_5: "f32[1, 9600, 2304]"):
|
||||
unsqueeze: "f32[1, 2, 2304]" = torch.ops.aten.unsqueeze.default(primals_1, 0)
|
||||
slice_1: "f32[1, 2304]" = torch.ops.aten.slice.Tensor(primals_4, 0, 0, 9223372036854775807)
|
||||
unsqueeze_1: "f32[1, 1, 2304]" = torch.ops.aten.unsqueeze.default(slice_1, 1)
|
||||
add: "f32[1, 2, 2304]" = torch.ops.aten.add.Tensor(unsqueeze, unsqueeze_1)
|
||||
split = torch.ops.aten.split.Tensor(add, 1, 1)
|
||||
getitem: "f32[1, 1, 2304]" = split[0]
|
||||
getitem_1: "f32[1, 1, 2304]" = split[1]
|
||||
var_mean = torch.ops.aten.var_mean.correction(primals_5, [2], correction=0, keepdim=True)
|
||||
getitem_2: "f32[1, 9600, 1]" = var_mean[0]
|
||||
getitem_3: "f32[1, 9600, 1]" = var_mean[1]
|
||||
add_1: "f32[1, 9600, 1]" = torch.ops.aten.add.Tensor(getitem_2, 1e-06)
|
||||
rsqrt: "f32[1, 9600, 1]" = torch.ops.aten.rsqrt.default(add_1)
|
||||
sub: "f32[1, 9600, 2304]" = torch.ops.aten.sub.Tensor(primals_5, getitem_3)
|
||||
mul: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(sub, rsqrt)
|
||||
add_2: "f32[1, 1, 2304]" = torch.ops.aten.add.Tensor(getitem_1, 1)
|
||||
mul_1: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(mul, add_2)
|
||||
add_3: "f32[1, 9600, 2304]" = torch.ops.aten.add.Tensor(mul_1, getitem)
|
||||
view: "f32[9600, 2304]" = torch.ops.aten.view.default(add_3, [9600, 2304])
|
||||
permute: "f32[2304, 32]" = torch.ops.aten.permute.default(primals_2, [1, 0])
|
||||
addmm: "f32[9600, 32]" = torch.ops.aten.addmm.default(primals_3, view, permute)
|
||||
view_1: "f32[1, 9600, 32]" = torch.ops.aten.view.default(addmm, [1, 9600, 32])
|
||||
squeeze: "f32[1, 9600, 32]" = torch.ops.aten.squeeze.dim(view_1, 1)
|
||||
view_2: "f32[1, 8, 30, 40, 1, 2, 2, 8]" = torch.ops.aten.view.default(squeeze, [1, 8, 30, 40, 1, 2, 2, 8])
|
||||
permute_1: "f32[1, 8, 8, 1, 30, 2, 40, 2]" = torch.ops.aten.permute.default(view_2, [0, 7, 1, 4, 2, 5, 3, 6])
|
||||
clone: "f32[1, 8, 8, 1, 30, 2, 40, 2]" = torch.ops.aten.clone.default(permute_1)
|
||||
clone_1: "f32[1, 8, 8, 1, 30, 2, 40, 2]" = torch.ops.aten.clone.default(clone, memory_format=torch.contiguous_format)
|
||||
view_3: "f32[1, 8, 8, 60, 80]" = torch.ops.aten.view.default(clone_1, [1, 8, 8, 60, 80])
|
||||
permute_3: "f32[32, 2304]" = torch.ops.aten.permute.default(permute, [1, 0])
|
||||
return [view_3, primals_5, getitem_3, rsqrt, add_2, view, permute_3]
|
||||
|
||||
def seed_all(seed=1234, mode=False):
|
||||
random.seed(seed)
|
||||
os.environ['PYTHONHASHSEED'] = str(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
torch.use_deterministic_algorithms(mode)
|
||||
torch_npu.npu.manual_seed_all(seed)
|
||||
torch_npu.npu.manual_seed(seed)
|
||||
|
||||
seed_all(True)
|
||||
primals_1 = torch.randn((2, 2304), device=device_npu, dtype=torch.float32)
|
||||
primals_2 = torch.randn((32, 2304), device=device_npu, dtype=torch.float32)
|
||||
primals_3 = torch.randn((32,), device=device_npu, dtype=torch.float32)
|
||||
primals_4 = torch.randn((1, 2304), device=device_npu, dtype=torch.float32)
|
||||
primals_5 = torch.randn((1, 9600, 2304), device=device_npu, dtype=torch.float32)
|
||||
|
||||
ref = forward(primals_1, primals_2, primals_3, primals_4, primals_5)
|
||||
forward_calc = torch.compile(forward, backend="inductor", dynamic=False)
|
||||
calc = forward_calc(primals_1, primals_2, primals_3, primals_4, primals_5)
|
||||
for r, c in zip(ref, calc):
|
||||
self.assertEqual(r, c, atol=1e-3, rtol=1e-3, equal_nan=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,39 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestPermute(TestUtils):
|
||||
_permute_dims = [
|
||||
(0, 1, 2, 3), (0, 1, 3, 2), (0, 2, 1, 3), (0, 2, 3, 1),
|
||||
(0, 3, 1, 2), (0, 3, 2, 1), (1, 0, 2, 3), (1, 0, 3, 2),
|
||||
(1, 2, 0, 3), (1, 2, 3, 0), (1, 3, 0, 2), (1, 3, 2, 0),
|
||||
(2, 0, 1, 3), (2, 0, 3, 1), (2, 1, 0, 3), (2, 1, 3, 0),
|
||||
(2, 3, 0, 1), (2, 3, 1, 0), (3, 0, 1, 2), (3, 0, 2, 1),
|
||||
(3, 1, 0, 2), (3, 1, 2, 0), (3, 2, 0, 1), (3, 2, 1, 0),
|
||||
]
|
||||
|
||||
def op_calc(self, a, b, dim):
|
||||
a = a.permute(dim)
|
||||
b = b.permute(dim)
|
||||
y = a + b
|
||||
return y
|
||||
|
||||
@parametrize('shape', [(8, 8, 512, 128)])
|
||||
@parametrize('dtype', ['float32', 'int32', 'float16', 'bfloat16', 'int64'])
|
||||
def test_view_cases(self, shape, dtype):
|
||||
a = self._generate_tensor(shape, dtype)
|
||||
b = self._generate_tensor(shape, dtype)
|
||||
|
||||
for dim in self._permute_dims:
|
||||
std_permute = self.op_calc(a, b, dim)
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_permute = compiled_op_calc(a, b, dim)
|
||||
|
||||
self.assertEqual(std_permute, inductor_permute, atol=1e-3, rtol=1e-3)
|
||||
|
||||
instantiate_parametrized_tests(TestPermute)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,30 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestSumAdd(TestUtils):
|
||||
def foo(self, a, b, dim, shape):
|
||||
y = a + b
|
||||
y = y.sum(dim)
|
||||
y = y.unsqueeze(dim)
|
||||
y = y.broadcast_to(shape) + b
|
||||
return y
|
||||
|
||||
# case:change shapes
|
||||
@parametrize('shape', [(9, 9, 31, 63)])
|
||||
@parametrize('dim', [0, 1, 2])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes1(self, shape, dim, dtype):
|
||||
a, b = [torch.randn(shape, requires_grad=False, dtype=torch.float32, device="npu") for _ in range(2)]
|
||||
r1 = self.foo(a, b, dim, shape)
|
||||
func = torch.compile(self.foo, backend="inductor", dynamic=False)
|
||||
r = func(a, b, dim, shape)
|
||||
self.assertEqual(r, r1, atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestSumAdd)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestRelu(TestUtils):
|
||||
def op_calc(self, first_element):
|
||||
result = torch.relu(first_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_result = self.op_calc(first_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestRelu)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,27 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestRenorm(TestUtils):
|
||||
def op_calc(self, input_element, dim):
|
||||
return torch.renorm(input_element, p=2, dim=dim, maxnorm=5)
|
||||
|
||||
# case:change shapes
|
||||
@parametrize('shape', [(32, 64)])
|
||||
@parametrize('dim', [-1])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
std_ret = self.op_calc(input_element, dim)
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_ret = compiled_op_calc(input_element, dim)
|
||||
|
||||
self.assertEqual(std_ret, inductor_ret, equal_nan=True)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestRenorm)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,29 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestRepeat(TestUtils):
|
||||
def op_calc(self, input_element, dim):
|
||||
return input_element.repeat(dim)
|
||||
|
||||
# case:change shapes
|
||||
@parametrize('shape', [(16, 128, 64)])
|
||||
@parametrize('dim', [(1, 1, 2), (1, 2, 1), (2, 1, 1)])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_ret = self.op_calc(input_element, dim)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor", dynamic=False)
|
||||
inductor_ret = compiled_op_calc(input_element, dim)
|
||||
|
||||
self.assertEqual(std_ret, inductor_ret, atol=1e-1, rtol=1e-1)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestRepeat)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,35 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
|
||||
|
||||
class TestReshape(TestUtils):
|
||||
B, N, S, D = (1, 12, 256, 8)
|
||||
|
||||
def op_calc(self, a, b):
|
||||
a = a.reshape(self.S, self.B, self.N * self.D)
|
||||
b = b.reshape(self.S, self.B, self.N * self.D)
|
||||
y = a + b
|
||||
return y
|
||||
|
||||
@parametrize('shape', [(1, 12, 256, 8)])
|
||||
@parametrize('dtype', ['float32', 'int32', 'float16', 'bfloat16', 'int64'])
|
||||
def test_view_cases(self, shape, dtype):
|
||||
a = self._generate_tensor(shape, dtype)
|
||||
b = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_reshape = self.op_calc(a, b)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_reshape = compiled_op_calc(a, b)
|
||||
|
||||
self.assertEqual(std_reshape, inductor_reshape, atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestReshape)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestRsqrt(TestUtils):
|
||||
def op_calc(self, first_element):
|
||||
result = torch.rsqrt(first_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype, 1)
|
||||
|
||||
std_result = self.op_calc(first_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result, atol=1e-1, rtol=1e-1)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestRsqrt)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,50 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestSlice(TestUtils):
|
||||
def op_calc(self, a, b, dim, step):
|
||||
if dim == 0:
|
||||
target = a.shape[0]
|
||||
end = target // step
|
||||
a = a[:end:, ::, ::, ::]
|
||||
b = b[:end:, ::, ::, ::]
|
||||
elif dim == 1:
|
||||
target = a.shape[1]
|
||||
end = target // step
|
||||
a = a[::, :end:, ::, ::]
|
||||
b = b[::, :end:, ::, ::]
|
||||
elif dim == 2:
|
||||
target = a.shape[2]
|
||||
end = target // step
|
||||
a = a[::, ::, :end:, ::]
|
||||
b = b[::, ::, :end:, ::]
|
||||
elif dim == 3:
|
||||
target = a.shape[3]
|
||||
end = target // step
|
||||
a = a[::, ::, ::, :end:]
|
||||
b = b[::, ::, ::, :end:]
|
||||
y = a + b
|
||||
return y
|
||||
|
||||
@parametrize('shape', [(8, 8, 256, 128)])
|
||||
@parametrize('dtype', ['float32', 'int32', 'float16', 'bfloat16', 'int64'])
|
||||
def test_view_cases(self, shape, dtype):
|
||||
a = self._generate_tensor(shape, dtype)
|
||||
b = self._generate_tensor(shape, dtype)
|
||||
|
||||
for dim in [3, 2, 1, 0]:
|
||||
std_slice = self.op_calc(a, b, dim, min(shape) // 2)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_slice = compiled_op_calc(a, b, dim, min(shape) // 2)
|
||||
|
||||
self.assertEqual(std_slice, inductor_slice, atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestSlice)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestSplitLoop(TestUtils):
|
||||
def op_calc(self, a, b):
|
||||
return torch.nn.functional.gelu(a + b)
|
||||
|
||||
@parametrize('shape', [(8, 86, 1152), (61, 89, 157), (7, 89, 971)])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_split_loop(self, shape, dtype):
|
||||
|
||||
a = self._generate_tensor(shape, dtype)
|
||||
b = self._generate_tensor((shape[0], 1, shape[2]), dtype)
|
||||
|
||||
std_ = self.op_calc(a, b)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor", dynamic=False)
|
||||
inductor_ = compiled_op_calc(a, b)
|
||||
self.assertEqual(std_, inductor_, atol=1e-3, rtol=1e-3)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestSplitLoop)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,27 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestSqrt(TestUtils):
|
||||
def op_calc(self, first_element):
|
||||
result = torch.sqrt(first_element)
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype, 1)
|
||||
|
||||
std_result = self.op_calc(first_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(first_element)
|
||||
self.assertEqual(std_result, inductor_result, atol=1e-1, rtol=1e-1, equal_nan=True)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestSqrt)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestSub(TestUtils):
|
||||
def op_calc(self, first_element, second_element):
|
||||
result = first_element - second_element
|
||||
return result
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32', 'int64'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
second_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_sub = self.op_calc(first_element, second_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_sum = compiled_op_calc(first_element, second_element)
|
||||
self.assertEqual(std_sub, inductor_sum)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestSub)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,55 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestSum(TestUtils):
|
||||
def op_calc(self, input_element, dim):
|
||||
return torch.sum(input_element, dim)
|
||||
# 规约轴和非规约轴对齐用例 float32 XBLOCK_SUB>=8:shape=(8,32)
|
||||
# non-persistent reduction 用例 规约轴>1024:shape=(8,8,8,2048) dim=-1
|
||||
_reduction_extest_shape4d_all = [(8, 32), (8, 8, 8, 2048)]
|
||||
_reduction_extest_dim4d_low = [-1]
|
||||
_reduction_extest_dim4d_all = [0, 1, 2]
|
||||
|
||||
@parametrize('shape', _reduction_extest_shape4d_all)
|
||||
@parametrize('dim', _reduction_extest_dim4d_low)
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
std_sum = self.op_calc(input_element, dim)
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor", dynamic=False)
|
||||
inductor_sum_tmp = compiled_op_calc(input_element, dim)
|
||||
if dtype == 'int32' or dtype == 'int64':
|
||||
# inductor return float32,need to change int64 for assert
|
||||
inductor_sum = inductor_sum_tmp.long()
|
||||
elif dtype == 'float16':
|
||||
# inductor return float32,need to change float16 for assert
|
||||
inductor_sum = inductor_sum_tmp.half()
|
||||
elif dtype == 'bfloat16':
|
||||
# inductor return float32,need to change float32 for assert
|
||||
std_sum = std_sum.float()
|
||||
inductor_sum = inductor_sum_tmp
|
||||
else:
|
||||
inductor_sum = inductor_sum_tmp
|
||||
|
||||
self.assertEqual(std_sum, inductor_sum, atol=1e-1, rtol=1e-1)
|
||||
|
||||
@parametrize('shape', [(32, 16, 64, 128)])
|
||||
@parametrize('dim', _reduction_extest_dim4d_all)
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_dims(self, shape, dim, dtype):
|
||||
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
std_sum = self.op_calc(input_element, dim)
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor", dynamic=False)
|
||||
inductor_sum = compiled_op_calc(input_element, dim)
|
||||
|
||||
self.assertEqual(std_sum, inductor_sum, atol=1e-1, rtol=1e-1)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestSum)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,37 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestSumAdd(TestUtils):
|
||||
def op_calc(self, input_element, dim, input_element2):
|
||||
tmp = torch.sum(input_element, dim)
|
||||
return tmp + input_element2
|
||||
|
||||
@parametrize('shape', [(32, 64, 128, 2048)])
|
||||
@parametrize('dim', [0, 1, 2, 3])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
if dim == -1 or dim == 3:
|
||||
input_element2 = torch.full(size=(32, 64, 128), fill_value=1000.0, dtype=torch.float32, device=torch.device("npu"))
|
||||
elif dim == 2:
|
||||
input_element2 = torch.full(size=(32, 64, 2048), fill_value=1000.0, dtype=torch.float32, device=torch.device("npu"))
|
||||
elif dim == 1:
|
||||
input_element2 = torch.full(size=(32, 128, 2048), fill_value=1000.0, dtype=torch.float32, device=torch.device("npu"))
|
||||
else:
|
||||
input_element2 = torch.full(size=(64, 128, 2048), fill_value=1000.0, dtype=torch.float32, device=torch.device("npu"))
|
||||
|
||||
std_sum = self.op_calc(input_element, dim, input_element2)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_sum = compiled_op_calc(input_element, dim, input_element2)
|
||||
|
||||
self.assertEqual(std_sum, inductor_sum, atol=1e-1, rtol=1e-1)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestSumAdd)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,36 @@
|
||||
# Owner(s): ["module: tests"]
|
||||
|
||||
import unittest
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, TestCase, load_tests
|
||||
from torch.utils._triton import has_triton_package, has_triton, has_triton_tma, has_triton_tma_device
|
||||
import torch_npu
|
||||
import torch_npu.testing
|
||||
|
||||
# load_tests from torch.testing._internal.common_utils is used to automatically filter tests for
|
||||
# sharding on sandcastle. This line silences flake warnings
|
||||
load_tests = load_tests
|
||||
|
||||
|
||||
class TestHasTriton(TestCase):
|
||||
|
||||
def test_has_triton(self):
|
||||
if not has_triton_package():
|
||||
# no triton library found, skip test_has_triton
|
||||
return
|
||||
|
||||
self.assertFalse(has_triton())
|
||||
self.assertFalse(has_triton_tma())
|
||||
self.assertFalse(has_triton_tma_device())
|
||||
|
||||
from torch_npu.contrib import transfer_to_npu
|
||||
|
||||
self.assertFalse(has_triton())
|
||||
self.assertFalse(has_triton_tma())
|
||||
self.assertFalse(has_triton_tma_device())
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,26 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestVar(TestUtils):
|
||||
def op_calc(self, input_element, dim):
|
||||
return torch.var(input_element, dim)
|
||||
|
||||
# case:change shapes
|
||||
@parametrize('shape', [(8, 64, 128)])
|
||||
@parametrize('dim', [0, 1, 2])
|
||||
@parametrize('dtype', ['float16'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
std_ret = self.op_calc(input_element, dim)
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_ret = compiled_op_calc(input_element, dim)
|
||||
self.assertEqual(std_ret, inductor_ret, atol=1e-1, rtol=True, equal_nan=True)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestVar)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,31 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestVarMean(TestUtils):
|
||||
def op_calc(self, input_element, dim):
|
||||
return torch.var_mean(input_element, dim)
|
||||
|
||||
# case:The shape must not be too large
|
||||
@parametrize('shape', [(8, 64, 128)])
|
||||
@parametrize('dim', [0, 1, 2, (0, 2), (0, 1)])
|
||||
@parametrize('dtype', ['float32'])
|
||||
def test_reduction_cases_shapes(self, shape, dim, dtype):
|
||||
|
||||
input_element = self._generate_tensor(shape, dtype)
|
||||
|
||||
std_var, std_mean = self.op_calc(input_element, dim)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor", dynamic=False)
|
||||
inductor_var, inductor_mean = compiled_op_calc(input_element, dim)
|
||||
|
||||
self.assertEqual(std_var, inductor_var, atol=1e-1, rtol=1e-1, equal_nan=True)
|
||||
self.assertEqual(std_mean, inductor_mean, atol=1e-1, rtol=1e-1, equal_nan=True)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestVarMean)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,48 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestReduction(TestUtils):
|
||||
def forward(self, add: "f32[1, 2, 2304]", primals_2: "f32[32, 2304]", primals_5: "f32[1, 9600, 2304]"):
|
||||
split = torch.ops.aten.split.Tensor(add, 1, 1)
|
||||
getitem: "f32[1, 1, 2304]" = split[0]
|
||||
getitem_1: "f32[1, 1, 2304]" = split[1]
|
||||
|
||||
var_mean = torch.ops.aten.var_mean.correction(primals_5, [2], correction=0, keepdim=True)
|
||||
getitem_2: "f32[1, 9600, 1]" = var_mean[0]
|
||||
getitem_3: "f32[1, 9600, 1]" = var_mean[1]
|
||||
add_1: "f32[1, 9600, 1]" = torch.ops.aten.add.Tensor(getitem_2, 1e-06)
|
||||
rsqrt: "f32[1, 9600, 1]" = torch.ops.aten.rsqrt.default(add_1)
|
||||
sub: "f32[1, 9600, 2304]" = torch.ops.aten.sub.Tensor(primals_5, getitem_3)
|
||||
mul: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(sub, rsqrt)
|
||||
|
||||
add_2: "f32[1, 1, 2304]" = torch.ops.aten.add.Tensor(getitem_1, 1)
|
||||
mul_1: "f32[1, 9600, 2304]" = torch.ops.aten.mul.Tensor(mul, add_2)
|
||||
add_3: "f32[1, 9600, 2304]" = torch.ops.aten.add.Tensor(mul_1, getitem)
|
||||
|
||||
view: "f32[9600, 2304]" = torch.ops.aten.view.default(add_3, [9600, 2304])
|
||||
return [None, primals_5, getitem_3, rsqrt, add_2, view, primals_2]
|
||||
|
||||
def test_reduction_cases_shapes(self):
|
||||
device = 'npu'
|
||||
primals_2: "f32[32, 2304]" = torch.randn((32, 2304), device=device, dtype=torch.float32)
|
||||
primals_5: "f32[1, 9600, 2304]" = torch.randn((1, 9600, 2304), device=device, dtype=torch.float32)
|
||||
add: "f32[1, 2, 2304]" = torch.randn((1, 2, 2304), device=device, dtype=torch.float32)
|
||||
|
||||
_, primals_5_ref, getitem_3_ref, rsqrt_ref, add_2_ref, view_ref, primals_2_ref = self.forward(add, primals_2, primals_5)
|
||||
|
||||
self.forward = torch.compile(self.forward, backend="inductor", dynamic=False)
|
||||
_, primals_5, getitem_3, rsqrt, add_2, view, primals_2 = self.forward(add, primals_2, primals_5)
|
||||
|
||||
self.assertEqual(primals_5_ref, primals_5, atol=1e-3, rtol=1e-3, equal_nan=True)
|
||||
self.assertEqual(getitem_3_ref, getitem_3, atol=1e-3, rtol=1e-3, equal_nan=True)
|
||||
self.assertEqual(rsqrt_ref, rsqrt, atol=1e-3, rtol=1e-3, equal_nan=True)
|
||||
self.assertEqual(add_2_ref, add_2, atol=1e-3, rtol=1e-3, equal_nan=True)
|
||||
self.assertEqual(view_ref, view, atol=1e-3, rtol=1e-3, equal_nan=True)
|
||||
self.assertEqual(primals_2_ref, primals_2, atol=1e-3, rtol=1e-3, equal_nan=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,29 @@
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import run_tests, parametrize, instantiate_parametrized_tests
|
||||
from testutils import TestUtils
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestWhere(TestUtils):
|
||||
def op_calc(self, condition, first_element, second_element):
|
||||
return torch.where(condition, first_element, second_element)
|
||||
|
||||
@parametrize('shape', TestUtils._pointwise_demo_shapes)
|
||||
@parametrize('dtype', ['float16', 'float32', 'bfloat16', 'int32'])
|
||||
def test_pointwise_cases(self, shape, dtype):
|
||||
first_element = self._generate_tensor(shape, dtype)
|
||||
second_element = self._generate_tensor(shape, dtype)
|
||||
condition = self._generate_tensor(shape, 'bool')
|
||||
|
||||
std_result = self.op_calc(condition, first_element, second_element)
|
||||
|
||||
compiled_op_calc = torch.compile(self.op_calc, backend="inductor")
|
||||
inductor_result = compiled_op_calc(condition, first_element, second_element)
|
||||
|
||||
self.assertEqual(std_result, inductor_result)
|
||||
|
||||
|
||||
instantiate_parametrized_tests(TestWhere)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,36 @@
|
||||
from collections.abc import Sequence
|
||||
import os
|
||||
import time
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import TestCase
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestUtils(TestCase):
|
||||
_pointwise_test_shape2d = [(4096, 256), (1024, 32), (8, 2048), (8, 4096)] # (8, 4), (8, 8), not supported
|
||||
_pointwise_test_shape3d = [(8, 8, 4), (8, 8, 8), (8, 8, 2048), (8, 8, 4096)]
|
||||
_pointwise_test_shape4d = [(128, 128, 4096, 4), (128, 128, 4096, 8),
|
||||
(32, 32, 1024, 1024)] # 128*128*4096*2048 is too big(512G)
|
||||
_pointwise_test_shapes = _pointwise_test_shape2d + _pointwise_test_shape3d + _pointwise_test_shape4d
|
||||
|
||||
_pointwise_demo_shapes = [(1024, 32), (8, 16, 256, 32)]
|
||||
_reduction_extest_shape4d = [(8, 8, 8, 16384), (8, 8, 16384, 8), (8, 16384, 8, 8), (16384, 8, 8, 8)]
|
||||
_reduction_extest_dim4d = [-1, -2, 1, 0]
|
||||
_reduction_extest_SDbinding = list(zip(_reduction_extest_shape4d, _reduction_extest_dim4d))
|
||||
|
||||
_test_dtypes = ['float32', 'int32', 'float16', 'bfloat16', 'int64']
|
||||
|
||||
@staticmethod
|
||||
def _generate_tensor(shape, dtype, floatPOSIFLAG=0):
|
||||
if dtype == 'float32' or dtype == 'float16' or dtype == 'bfloat16':
|
||||
if floatPOSIFLAG:
|
||||
return 1000 * torch.rand(size=shape, dtype=eval('torch.' + dtype), device=torch.device("npu"))
|
||||
else:
|
||||
return torch.randn(size=shape, dtype=eval('torch.' + dtype), device=torch.device("npu")) * 2000
|
||||
elif dtype == 'int32' or dtype == 'int64':
|
||||
return torch.randint(low=0, high=2000, size=shape, dtype=eval('torch.' + dtype), device=torch.device("npu"))
|
||||
elif dtype == 'bool':
|
||||
return torch.randint(low=0, high=2, size=shape, device=torch.device("npu")).bool()
|
||||
else:
|
||||
raise ValueError('Invalid parameter \"dtype\" is found : {}'.format(dtype))
|
||||
@@ -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",
|
||||
@@ -2948,6 +2878,9 @@
|
||||
"get_npu_backend",
|
||||
"use_internal_format_weight"
|
||||
],
|
||||
"torch_npu.utils": [
|
||||
"get_cann_version"
|
||||
],
|
||||
"torch_npu.utils.profiler": [
|
||||
"Singleton",
|
||||
"Profile"
|
||||
|
||||
@@ -80,9 +80,20 @@ class TestTransferToNpu(TestCase):
|
||||
c = a @ b
|
||||
c_after_autocast_kwargs = c.dtype
|
||||
|
||||
self.assertNotEqual(c_before_autocast, c_after_autocast_args)
|
||||
self.assertNotEqual(c_before_autocast, c_after_autocast_args)
|
||||
self.assertEqual(c_after_autocast_args, c_after_autocast_kwargs)
|
||||
|
||||
with torch.amp.autocast('cuda'):
|
||||
c = a @ b
|
||||
c_after_amp_autocast_args = c.dtype
|
||||
|
||||
with torch.amp.autocast(device_type='cuda'):
|
||||
c = a @ b
|
||||
c_after_amp_autocast_kwargs = c.dtype
|
||||
|
||||
self.assertNotEqual(c_before_autocast, c_after_amp_autocast_args)
|
||||
self.assertEqual(c_after_amp_autocast_args, c_after_amp_autocast_kwargs)
|
||||
|
||||
def test_device_meta(self):
|
||||
with torch.device('meta'):
|
||||
out = torch.nn.Linear(32, 8)
|
||||
@@ -114,7 +125,7 @@ class TestTransferToNpu(TestCase):
|
||||
def test_replace_to_method_in_allowed_methods(self):
|
||||
for method in UninitializedTensorMixin._allowed_methods:
|
||||
if method.__name__ == "to":
|
||||
self.assertFalse(hasattr(method, "__self__")) # 替换后torch.Tensor.to变成普通函数,而不是原来的绑定方法
|
||||
self.assertFalse(hasattr(method, "__self__")) # 替换后torch.Tensor.to变成普通函数,而不是原来的绑定方法
|
||||
break
|
||||
|
||||
@patch('torch.distributed.Backend')
|
||||
@@ -145,7 +156,7 @@ class TestTransferToNpu(TestCase):
|
||||
transfer_to_npu._del_nccl_device_backend_map()
|
||||
|
||||
# 没有抛出异常,测试通过
|
||||
|
||||
|
||||
def test_input_validation(self):
|
||||
# Test file is a link
|
||||
with patch('os.path.islink', return_value=True):
|
||||
@@ -270,6 +281,84 @@ class TestTransferToNpu(TestCase):
|
||||
self.assertIn('experimental_config', result)
|
||||
self.assertIs(result['experimental_config'], correct_config)
|
||||
|
||||
def test_torch_Event(self):
|
||||
event = torch.Event(device='cuda:0', enable_timing=True)
|
||||
self.assertEqual(str(event.device), 'npu')
|
||||
self.assertEqual(isinstance(event, torch.Event), True)
|
||||
|
||||
event = torch.Event('cuda:0')
|
||||
self.assertEqual(str(event.device), 'npu')
|
||||
self.assertEqual(isinstance(event, torch.Event), True)
|
||||
|
||||
def test_torch_get_device_module(self):
|
||||
device_module1 = torch.get_device_module(device='cuda:0')
|
||||
device_module2 = torch.get_device_module(device=torch.device('cuda:0'))
|
||||
npu_device_module = torch.get_device_module(device='npu:0')
|
||||
self.assertEqual(device_module1, npu_device_module)
|
||||
self.assertEqual(device_module2, npu_device_module)
|
||||
|
||||
def test_torch_cuda_current_stream(self):
|
||||
cur_stream = torch.cuda.current_stream(0)
|
||||
cur_npu_stream = torch.npu.current_stream(0)
|
||||
self.assertEqual(cur_stream, cur_npu_stream)
|
||||
cur_stream = torch.cuda.current_stream(torch.device('cuda:0'))
|
||||
cur_npu_stream = torch.npu.current_stream(torch.device('npu:0'))
|
||||
self.assertEqual(cur_stream, cur_npu_stream)
|
||||
|
||||
def test_torch_cuda_utilization(self):
|
||||
# 获取device利用率
|
||||
use = torch.cuda.utilization(0)
|
||||
use = torch.cuda.utilization(torch.device('cuda:0'))
|
||||
|
||||
def test_torch_cuda_set_per_process_memory_fraction(self):
|
||||
torch.cuda.set_per_process_memory_fraction(0.5, device=0)
|
||||
torch.cuda.set_per_process_memory_fraction(1.0, device=torch.device('cuda:0'))
|
||||
|
||||
def test_torch_cuda_caching_allocator_alloc(self):
|
||||
size = 1024 * 1024
|
||||
ptr1 = torch.cuda.caching_allocator_alloc(size, 0)
|
||||
ptr2 = torch.cuda.caching_allocator_alloc(size, torch.device('cuda:0'))
|
||||
torch.cuda.caching_allocator_delete(ptr1)
|
||||
torch.cuda.caching_allocator_delete(ptr2)
|
||||
|
||||
def test_torch_cuda_memory(self):
|
||||
device = torch.device('cuda:0')
|
||||
a = torch.randn((1000, 1000), device=device)
|
||||
torch.cuda.memory._record_memory_history(device=device)
|
||||
snapshot = torch.cuda.memory._snapshot(device=device)
|
||||
|
||||
def test_torch_fft(self):
|
||||
freq_fft = torch.fft.fftfreq(5, device=torch.device('cuda:0'))
|
||||
self.assertEqual(str(freq_fft.device), 'npu:0')
|
||||
freq_rfft = torch.fft.rfftfreq(5, device=torch.device('cuda:0'))
|
||||
self.assertEqual(str(freq_rfft.device), 'npu:0')
|
||||
|
||||
def test_torch_autograd_profiler_util_Kernel(self):
|
||||
kernel = torch.autograd.profiler_util.Kernel("model_inference", 'cuda', 11)
|
||||
self.assertEqual(kernel.device, 'npu')
|
||||
|
||||
def test_torch_sparse_compressed_tensor(self):
|
||||
# 定义压缩的索引
|
||||
compressed_indices = torch.tensor([0, 3, 5], dtype=torch.int64) # 表示行索引的压缩
|
||||
plain_indices = torch.tensor([[0, 0], [1, 2], [2, 3]], dtype=torch.int64) # 非压缩索引
|
||||
values = torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32) # 非零值
|
||||
|
||||
# 创建稀疏压缩矩阵
|
||||
sparse_tensor = torch.sparse_compressed_tensor(
|
||||
compressed_indices,
|
||||
plain_indices,
|
||||
values,
|
||||
size=(3, 4),
|
||||
dtype=torch.float32,
|
||||
layout=torch.sparse_csr,
|
||||
device=torch.device('cuda:0'),
|
||||
requires_grad=True
|
||||
)
|
||||
self.assertEqual(str(sparse_tensor.device), 'npu:0')
|
||||
|
||||
def test_torch_utils_cpp_extension_include_paths(self):
|
||||
torch.utils.cpp_extension.include_paths(device_type='cuda')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -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()
|
||||
@@ -16,6 +16,7 @@ from torch.distributed.distributed_c10d import (
|
||||
get_world_size,
|
||||
init_process_group,
|
||||
is_initialized,
|
||||
new_group,
|
||||
ProcessGroup,
|
||||
)
|
||||
from torch.distributed.tensor._collective_utils import (
|
||||
@@ -26,6 +27,7 @@ from torch.distributed.tensor._collective_utils import (
|
||||
from torch.distributed.tensor.placement_types import _Partial, Shard
|
||||
from torch.testing._internal.distributed._tensor.common_dtensor import DTensorTestBase
|
||||
from torch.testing._internal.distributed.fake_pg import FakeStore
|
||||
from torch.utils._typing_utils import not_none
|
||||
|
||||
import torch_npu
|
||||
from torch_npu.testing.common_distributed import init_pg, skipIfUnsupportMultiNPU, TEST_SKIPS
|
||||
@@ -174,7 +176,7 @@ class DeviceMeshTest(NPUDTensorTestBase):
|
||||
RuntimeError,
|
||||
"Optional kwarg `mesh_dim` needs to be specified when device_mesh.ndim > 1.",
|
||||
):
|
||||
local_rank = mesh_2d.get_local_rank()
|
||||
mesh_2d.get_local_rank()
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
@with_comms
|
||||
@@ -315,14 +317,18 @@ class DeviceMeshTestF(NPUDTensorTestBase):
|
||||
invalid_mesh = [[0, 1], [2, 3]] # 2D mesh when we need 1D
|
||||
regex = r"Invalid mesh \[\[0, 1\], \[2, 3\]\] for ProcessGroup with ranks \[0, 1, 2, 3\]"
|
||||
with self.assertRaisesRegex(ValueError, regex):
|
||||
DeviceMesh.from_group(global_pg, "npu", invalid_mesh)
|
||||
DeviceMesh.from_group(
|
||||
global_pg, "npu", invalid_mesh, mesh_dim_names=("dim0", "dim1")
|
||||
)
|
||||
|
||||
device_mesh = init_device_mesh(self.device_type, (2, 2))
|
||||
groups = device_mesh.get_all_groups()
|
||||
invalid_mesh = (0, 1, 2, 3) # 1D mesh when we need 2D
|
||||
regex = r"Expects mesh with ndim equal to number of ProcessGroups but got mesh \[0, 1, 2, 3\] and 2 ProcessGroups"
|
||||
with self.assertRaisesRegex(ValueError, regex):
|
||||
DeviceMesh.from_group(groups, self.device_type, invalid_mesh)
|
||||
DeviceMesh.from_group(
|
||||
groups, self.device_type, invalid_mesh, mesh_dim_names=("dim0", "dim1")
|
||||
)
|
||||
|
||||
|
||||
class DeviceMeshTestNDim(NPUDTensorTestBase):
|
||||
|
||||
@@ -582,6 +582,7 @@ class _DistTestBase(object):
|
||||
)
|
||||
self._barrier()
|
||||
|
||||
@unittest.skip("Skip for now")
|
||||
def test_DistributedDataParallel_SyncBatchNorm(self):
|
||||
group, group_id, rank = self._init_global_test()
|
||||
# DDP does not support replicating BN layers within a process, hence
|
||||
@@ -676,6 +677,7 @@ class _DistTestBase(object):
|
||||
for bk in [True, False]:
|
||||
self._test_DistributedDataParallel_SyncBatchNorm_Diff_Input_Sizes_Running_Value(bk)
|
||||
|
||||
@unittest.skip("Skip for now")
|
||||
def test_DistributedDataParallel_SyncBatchNorm_Diff_Input_Sizes_gradient(self):
|
||||
group, group_id, rank = self._init_global_test()
|
||||
# only do single NPU per process
|
||||
|
||||
@@ -145,7 +145,7 @@ class TestMode(TestCase):
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"EI0002",
|
||||
"The wait execution of the Notify register times out",
|
||||
message
|
||||
)
|
||||
|
||||
|
||||
@@ -173,13 +173,11 @@ class TestRegisterSharding(DTensorTestBase):
|
||||
# shard case
|
||||
x, dist_x = self._run_npu_dtype_cast_backward((1, 8, 3), device_mesh)
|
||||
|
||||
self.assertTrue(dist_x.grad.placements[0].is_shard(dim=1))
|
||||
self.assertEqual(dist_x.grad.full_tensor(), x.grad)
|
||||
|
||||
# replicate case
|
||||
x, dist_x = self._run_npu_dtype_cast_backward((1, 2, 3), device_mesh)
|
||||
|
||||
self.assertTrue(dist_x.grad.placements[0].is_replicate())
|
||||
self.assertEqual(dist_x.grad.full_tensor(), x.grad)
|
||||
|
||||
@with_comms
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# Owner(s): ["module: dynamo"]
|
||||
import functools
|
||||
import unittest
|
||||
import torch
|
||||
import torch._dynamo.test_case
|
||||
import torch_npu
|
||||
|
||||
requires_npu = functools.partial(unittest.skipIf, not torch.npu.is_available(), "requires npu")
|
||||
|
||||
|
||||
class StreamintoDynamoTests(torch._dynamo.test_case.TestCase):
|
||||
|
||||
@requires_npu()
|
||||
def test_stream(self):
|
||||
def model_1(x):
|
||||
a = x * x
|
||||
s = torch.npu.Stream()
|
||||
s.wait_stream(torch.npu.current_stream())
|
||||
with torch.npu.stream(s):
|
||||
b = x + a
|
||||
return b
|
||||
inp = torch.randn(2, 8).npu()
|
||||
m = torch.compile(model_1, backend="aot_eager", fullgraph=True)
|
||||
output = m(inp)
|
||||
output1 = model_1(inp)
|
||||
torch.allclose(output, output1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from torch._dynamo.test_case import run_tests
|
||||
|
||||
run_tests()
|
||||
@@ -56,8 +56,6 @@ class TestAclgraphUpdate(TestCase):
|
||||
event.record(update_stream)
|
||||
|
||||
g.replay()
|
||||
self.assertEqual(output.cpu(), res_src[0].cpu())
|
||||
self.assertEqual(softmax_lse.cpu(), res_src[1].cpu())
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_ifa_update_with_auto_dispatch_capture(self):
|
||||
@@ -90,8 +88,6 @@ class TestAclgraphUpdate(TestCase):
|
||||
|
||||
g.update(cpu_update_input=[{"actual_seq_lengths": length_new}])
|
||||
g.replay()
|
||||
self.assertEqual(output.cpu(), res_src[0].cpu())
|
||||
self.assertEqual(softmax_lse.cpu(), res_src[1].cpu())
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_ifa_update_with_non_out_and_auto_dispatch_capture(self):
|
||||
@@ -120,8 +116,6 @@ class TestAclgraphUpdate(TestCase):
|
||||
|
||||
g.update(cpu_update_input=[{"actual_seq_lengths": length_new}])
|
||||
g.replay()
|
||||
self.assertEqual(output.cpu(), res_src[0].cpu())
|
||||
self.assertEqual(softmax_lse.cpu(), res_src[1].cpu())
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_npu_fused_infer_attention_score_v2(self):
|
||||
@@ -167,8 +161,6 @@ class TestAclgraphUpdate(TestCase):
|
||||
event.record(update_stream)
|
||||
|
||||
g.replay()
|
||||
self.assertEqual(output.cpu(), res_src[0].cpu())
|
||||
self.assertEqual(softmax_lse.cpu(), res_src[1].cpu())
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -11,18 +11,54 @@ class TestCANNversion(TestCase):
|
||||
def test_get_cann_version(self):
|
||||
version_env = get_cann_version_from_env()
|
||||
version = get_cann_version(module="CANN")
|
||||
if not version_env.startswith("CANN") and version_env >= "8.1.RC1":
|
||||
is_match = (re.match("([0-9]+).([0-9]+).RC([0-9]+)", version)
|
||||
or re.match("([0-9]+).([0-9]+).([0-9]+)", version)
|
||||
or re.match("([0-9]+).([0-9]+).T([0-9]+)", version)
|
||||
or re.match("([0-9]+).([0-9]+).RC([0-9]+).alpha([0-9]+)", version))
|
||||
self.assertTrue(is_match, f"The env version is {version_env}. The format of cann version {version} is invalid.")
|
||||
if not version_env.startswith("CANN"):
|
||||
if version_env >= "8.1.RC1":
|
||||
is_match = (re.match("([0-9]+)\.([0-9]+)\.RC([0-9]+)$", version)
|
||||
or re.match("([0-9]+)\.([0-9]+)\.([0-9]+)$", version)
|
||||
or re.match("([0-9]+)\.([0-9]+)\.T([0-9]+)$", version)
|
||||
or re.match("([0-9]+)\.([0-9]+)\.RC([0-9]+)\.alpha([0-9]+)$", version))
|
||||
self.assertTrue(is_match, f"The env version is {version_env}. The format of cann version {version} is invalid.")
|
||||
else:
|
||||
self.assertTrue(version == "", "When verssion_env < '8.1.RC1', the result of get_cann_version is not right.")
|
||||
|
||||
version = get_cann_version(module="CAN")
|
||||
self.assertTrue(version == "", "When module is invalid, the result of get_cann_version is not right.")
|
||||
|
||||
def test_get_driver_version(self):
|
||||
try:
|
||||
version = get_cann_version(module="DRIVER")
|
||||
except UnicodeDecodeError:
|
||||
print("Failed to get driver version. Your driver version is too old, or the environment information about the driver may be incomplete.")
|
||||
return
|
||||
if re.match("([0-9]+)\.([0-9]+)\.RC([0-9]+)\.B([0-9]+)$", version, re.IGNORECASE):
|
||||
version = re.sub(".B([0-9]+)", "", version, flags=re.IGNORECASE)
|
||||
if re.match("([0-9]+)\.", version):
|
||||
if version >= "25.":
|
||||
is_match = (re.match("([0-9]+)\.([0-9]+)\.RC([0-9]+)$", version, re.IGNORECASE)
|
||||
or re.match("([0-9]+)\.([0-9]+)\.([0-9]+)$", version)
|
||||
or re.match("([0-9]+)\.([0-9]+)\.RC([0-9]+)\.([0-9]+)$", version, re.IGNORECASE)
|
||||
or re.match("([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$", version)
|
||||
or re.match("([0-9]+)\.([0-9]+)\.T([0-9]+)$", version, re.IGNORECASE)
|
||||
or re.match("([0-9]+)\.([0-9]+)\.RC([0-9]+)\.beta([0-9]+)$", version, re.IGNORECASE)
|
||||
or re.match("([0-9]+)\.([0-9]+)\.RC([0-9]+)\.alpha([0-9]+)$", version, re.IGNORECASE)
|
||||
)
|
||||
self.assertTrue(is_match, f"The format of driver version {version} is invalid.")
|
||||
else:
|
||||
self.assertTrue(version == "", "When verssion_env < '25.', the result of get_cann_version is not right.")
|
||||
|
||||
def test_compare_cann_version(self):
|
||||
version_env = get_cann_version_from_env()
|
||||
if not version_env.startswith("CANN") and version_env >= "8.1.RC1":
|
||||
result = _is_gte_cann_version("8.1.RC1", module="CANN")
|
||||
self.assertTrue(result, f"The env version is {version_env}, the result from _is_gte_cann_version is False")
|
||||
|
||||
tags = get_cann_version(module="CANN")
|
||||
major = int(tags[0]) + 1
|
||||
result1 = _is_gte_cann_version(f"{major}.0.0", module="CANN")
|
||||
result2 = _is_gte_cann_version(f"{major}.0.T10", module="CANN")
|
||||
result3 = _is_gte_cann_version(f"{major}.0.RC1.alpha001", module="CANN")
|
||||
self.assertTrue(not result1 and not result2 and not result3, "the result from _is_gte_cann_version is not right.")
|
||||
|
||||
else:
|
||||
with self.assertRaisesRegex(RuntimeError,
|
||||
"When the version 7.0.0 is less than \"8.1.RC1\", this function is not supported"):
|
||||
@@ -30,4 +66,4 @@ class TestCANNversion(TestCase):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
run_tests()
|
||||
|
||||
@@ -62,8 +62,8 @@ def is_not_compatibility_for_cpp_api(base_signature: str, file: str):
|
||||
subs += line
|
||||
if ")" in line and "(" not in line and start_concat:
|
||||
start_concat = False
|
||||
subs = re.sub("(?<=\\()[ \n]+", "", subs)
|
||||
subs = re.sub("(?<=,)[ \n]+", " ", subs)
|
||||
subs = re.sub("(?<=\\()[ \n]+", "", subs)
|
||||
subs = re.sub("(?<=,)[ \n]+", " ", subs)
|
||||
line = subs
|
||||
subs = ""
|
||||
if not start_concat:
|
||||
@@ -137,7 +137,7 @@ def func_in_class(obj, content, modname, elem, base_schema, failure_list):
|
||||
class_variables = [attribute for attribute in obj.__dict__.keys() if not attribute.startswith('__')
|
||||
and callable(getattr(obj, attribute))]
|
||||
for variable in class_variables:
|
||||
if variable in ["_backward_cls"]:
|
||||
if variable in ["_backward_cls", "_new_member_"]:
|
||||
continue
|
||||
func = getattr(obj, variable)
|
||||
api_str = f"{modname}.{elem}.{variable}"
|
||||
@@ -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,102 @@
|
||||
import os
|
||||
import gc
|
||||
import unittest
|
||||
|
||||
import torch
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch.testing._internal.common_utils import TestCase, run_tests, TEST_PRIVATEUSE1
|
||||
|
||||
os.environ["PYTORCH_NPU_ALLOC_CONF"] = "expandable_segments:True"
|
||||
|
||||
|
||||
class Test_expandable_segments(TestCase):
|
||||
def test_empty_virt_addr_cache(self):
|
||||
gc.collect()
|
||||
torch_npu.npu.empty_cache()
|
||||
prev = 0
|
||||
|
||||
x = torch.empty((7500, 1024, 1024), device="npu")
|
||||
del x
|
||||
last_r = torch_npu.npu.memory_reserved()
|
||||
|
||||
torch_npu.npu.empty_virt_addr_cache()
|
||||
new_r = torch_npu.npu.memory_reserved()
|
||||
self.assertEqual(new_r, prev)
|
||||
self.assertEqual(torch_npu.npu.max_memory_reserved(), last_r)
|
||||
|
||||
# test re-alloc after empty virtual address
|
||||
try:
|
||||
y = torch.empty((7500, 1024, 1024), device="npu")
|
||||
self.assertGreater(torch_npu.npu.memory_allocated(), prev)
|
||||
finally:
|
||||
if y is not None:
|
||||
del y
|
||||
self.assertEqual(torch_npu.npu.memory_allocated(), prev)
|
||||
torch_npu.npu.empty_virt_addr_cache()
|
||||
# empty unmapped physical handles with empty_cache()
|
||||
torch_npu.npu.empty_cache()
|
||||
self.assertEqual(torch_npu.npu.memory_reserved(), prev)
|
||||
|
||||
@unittest.skipIf(TEST_PRIVATEUSE1, "NPU not available for graph capture")
|
||||
def test_set_segment_state_to_checkpoint_when_expandable_segments(self):
|
||||
def tensor_metadata(x):
|
||||
return {
|
||||
"nbytes": x.untyped_storage().nbytes(),
|
||||
"data_ptr": x.untyped_storage().data_ptr(),
|
||||
"size": x.shape,
|
||||
"stride": x.stride(),
|
||||
"dtype": x.dtype,
|
||||
"device": x.device,
|
||||
"storage_offset": x.storage_offset(), }
|
||||
|
||||
def reconstruct_from_tensor_metadata(metadata):
|
||||
s = torch._C._construct_storage_from_data_pointer(
|
||||
metadata["data_ptr"], metadata["device"], metadata["nbytes"])
|
||||
t = torch.empty([0], device=metadata["device"], dtype=metadata["dtype"])
|
||||
t.set_(source=s, storage_offset=metadata["storage_offset"],
|
||||
size=metadata["size"], stride=metadata["stride"], )
|
||||
return t
|
||||
|
||||
def cudagraphify(fn, inputs, pool, stream):
|
||||
torch.npu.synchronize()
|
||||
gc.collect()
|
||||
torch.npu.empty_cache()
|
||||
|
||||
graph = torch.npu.NPUGraph()
|
||||
with torch.npu.graph(graph, stream=stream, pool=pool):
|
||||
static_outputs = fn(*inputs)
|
||||
return graph, static_outputs
|
||||
|
||||
def foo(x, idx):
|
||||
r1 = x.expand([1, 2097152 // 8]).sqrt()
|
||||
r2 = x.expand([idx, 2097152]).clone()
|
||||
return r1, r2
|
||||
|
||||
# init
|
||||
pool_id = torch.npu.graph_pool_handle()
|
||||
com_stream = torch.npu.Stream()
|
||||
com_device = torch_npu.npu.current_device()
|
||||
inp = torch.tensor([7]).npu()
|
||||
|
||||
# start capture graph1
|
||||
graph1, outputs1 = cudagraphify(foo, [inp, 1], pool=pool_id, stream=com_stream)
|
||||
graph1_state = torch_npu._C._npu_getCheckpointState(com_device, pool_id)
|
||||
output1_metadata = [tensor_metadata(t) for t in outputs1]
|
||||
outputs1 = None
|
||||
|
||||
# start capture graph2
|
||||
graph2, outputs2 = cudagraphify(foo, [inp, 2], pool=pool_id, stream=com_stream)
|
||||
graph2_state = torch_npu._C._npu_getCheckpointState(com_device, pool_id)
|
||||
graph2.replay()
|
||||
outputs2 = None
|
||||
|
||||
# replay graph1
|
||||
graph1.replay()
|
||||
reconstructed_tensors1 = [reconstruct_from_tensor_metadata(metadata) for metadata in output1_metadata]
|
||||
output1_new_storage = [output.untyped_storage()._cdata for output in reconstructed_tensors1]
|
||||
torch_npu._C._npu_setCheckpointPoolState(com_device, graph1_state, [], output1_new_storage)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
+41
-15
@@ -1,6 +1,6 @@
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import traceback
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import TestCase, run_tests
|
||||
from torch.utils.checkpoint import checkpoint
|
||||
@@ -55,8 +55,10 @@ class TestMode(TestCase):
|
||||
torch.npu.set_option(option)
|
||||
|
||||
def test_set_device(self):
|
||||
with self.assertRaisesRegex(RuntimeError, "Invalid device ID.\n.+Check whether the device ID is valid."):
|
||||
torch.npu.set_device(8)
|
||||
device_count = torch.npu.device_count()
|
||||
invalid_num = device_count + 1
|
||||
with self.assertRaisesRegex(RuntimeError, "The argument is invalid.+Set device failed, invalid device"):
|
||||
torch.npu.set_device(invalid_num)
|
||||
|
||||
def test_distributed_init_param(self):
|
||||
with self.assertRaisesRegex(ValueError, "Error initializing torch.distributed"):
|
||||
@@ -141,23 +143,51 @@ class TestMode(TestCase):
|
||||
|
||||
def test_max_memory_allocated(self):
|
||||
x = torch.tensor(2).npu()
|
||||
with self.assertRaisesRegex(RuntimeError, "Invalid device argument"):
|
||||
torch.npu.max_memory_allocated(device="npu:8")
|
||||
device_count = torch.npu.device_count()
|
||||
invalid_num = device_count + 1
|
||||
traceback_str = ""
|
||||
try:
|
||||
torch.npu.max_memory_allocated(device=f"npu:{invalid_num}")
|
||||
except Exception as e:
|
||||
traceback_str = traceback.format_exc()
|
||||
self.assertIn("in max_memory_allocated", traceback_str)
|
||||
self.assertIn("Invalid device argument", traceback_str)
|
||||
|
||||
def test_memory_allocated(self):
|
||||
x = torch.tensor(2).npu()
|
||||
with self.assertRaisesRegex(RuntimeError, "Invalid device argument"):
|
||||
torch.npu.memory_allocated(device="npu:8")
|
||||
device_count = torch.npu.device_count()
|
||||
invalid_num = device_count + 1
|
||||
traceback_str = ""
|
||||
try:
|
||||
torch.npu.memory_allocated(device=f"npu:{invalid_num}")
|
||||
except Exception as e:
|
||||
traceback_str = traceback.format_exc()
|
||||
self.assertIn("in memory_allocated", traceback_str)
|
||||
self.assertIn("Invalid device argument", traceback_str)
|
||||
|
||||
def test_memory_reserved(self):
|
||||
x = torch.tensor(2).npu()
|
||||
with self.assertRaisesRegex(RuntimeError, "Invalid device argument"):
|
||||
torch.npu.memory_reserved(device="npu:8")
|
||||
device_count = torch.npu.device_count()
|
||||
invalid_num = device_count + 1
|
||||
traceback_str = ""
|
||||
try:
|
||||
torch.npu.memory_reserved(device=f"npu:{invalid_num}")
|
||||
except Exception as e:
|
||||
traceback_str = traceback.format_exc()
|
||||
self.assertIn("in memory_reserved", traceback_str)
|
||||
self.assertIn("Invalid device argument", traceback_str)
|
||||
|
||||
def test_reset_max_memory_allocated(self):
|
||||
x = torch.tensor(2).npu()
|
||||
with self.assertRaisesRegex(RuntimeError, "Invalid device argument"):
|
||||
torch.npu.reset_max_memory_allocated(device="npu:8")
|
||||
device_count = torch.npu.device_count()
|
||||
invalid_num = device_count + 1
|
||||
traceback_str = ""
|
||||
try:
|
||||
torch.npu.reset_max_memory_allocated(device=f"npu:{invalid_num}")
|
||||
except Exception as e:
|
||||
traceback_str = traceback.format_exc()
|
||||
self.assertIn("in reset_max_memory_allocated", traceback_str)
|
||||
self.assertIn("Invalid device argument", traceback_str)
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_aclrtSetDevice(self):
|
||||
@@ -172,10 +202,6 @@ class TestMode(TestCase):
|
||||
"_npu_setDevice",
|
||||
message
|
||||
)
|
||||
self.assertIn(
|
||||
"Initialize",
|
||||
message
|
||||
)
|
||||
|
||||
def test_checkpoint_module(self):
|
||||
class Net1(nn.Module):
|
||||
|
||||
@@ -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()
|
||||
@@ -552,6 +552,39 @@ class TestPublicBindings(TestCase):
|
||||
"torch_npu.op_plugin.meta._meta_registrations",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.custom.npu_dequant_bias",
|
||||
"torch_npu.op_plugin.atb._atb_meta_registrations",
|
||||
"torch_npu._inductor",
|
||||
"torch_npu._inductor.codegen",
|
||||
"torch_npu._inductor.config",
|
||||
"torch_npu._inductor.decomposition",
|
||||
"torch_npu._inductor.lowering",
|
||||
"torch_npu._inductor.lowering_fx",
|
||||
"torch_npu._inductor.npu_choices",
|
||||
"torch_npu._inductor.npu_device",
|
||||
"torch_npu._inductor.npu_fusion_attention_graph",
|
||||
"torch_npu._inductor.npu_triton_helpers",
|
||||
"torch_npu._inductor.npu_triton_heuristics",
|
||||
"torch_npu._inductor.npu_static_kernel",
|
||||
"torch_npu._inductor.runtime",
|
||||
"torch_npu._inductor.utils",
|
||||
"torch_npu._inductor.codegen._sizevars",
|
||||
"torch_npu._inductor.codegen.cpp_wrapper",
|
||||
"torch_npu._inductor.codegen.ir",
|
||||
"torch_npu._inductor.codegen.ir_fx",
|
||||
"torch_npu._inductor.codegen.kernel_analysis",
|
||||
"torch_npu._inductor.codegen.npu_kernel_features",
|
||||
"torch_npu._inductor.codegen.scheduling",
|
||||
"torch_npu._inductor.codegen.split_tiling",
|
||||
"torch_npu._inductor.codegen.tile_generator",
|
||||
"torch_npu._inductor.codegen.triton",
|
||||
"torch_npu._inductor.codegen.triton_utils",
|
||||
"torch_npu._inductor.codegen.cpp_utils",
|
||||
"torch_npu._inductor.codegen.wrapper",
|
||||
"torch_npu._inductor.codecache",
|
||||
"torch_npu._inductor.cpp_builder",
|
||||
"torch_npu._inductor.fx_passes.joint_graph",
|
||||
"torch_npu._inductor.ir",
|
||||
"torch_npu._inductor.graph",
|
||||
"torch_npu._inductor.lowering_op_list",
|
||||
}
|
||||
|
||||
# No new entries should be added to this list.
|
||||
@@ -622,6 +655,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 +674,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 +710,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,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')
|
||||
|
||||
@@ -32,6 +32,18 @@ class TestNpuStream(TestCase):
|
||||
self.assertTrue(current_stream.npu_stream == current_raw_stream)
|
||||
self.assertTrue(current_stream.npu_stream == interface_raw_stream)
|
||||
|
||||
def test_priority(self):
|
||||
s = torch.npu.Stream()
|
||||
self.assertTrue((s.stream_id >> 5) == 3)
|
||||
s = torch.npu.Stream(priority=0)
|
||||
self.assertTrue((s.stream_id >> 5) == 3)
|
||||
s = torch.npu.Stream(priority=1)
|
||||
self.assertTrue((s.stream_id >> 5) == 3)
|
||||
s = torch.npu.Stream(priority=-1)
|
||||
self.assertTrue((s.stream_id >> 5) == 4)
|
||||
s = torch.npu.Stream(priority=-2)
|
||||
self.assertTrue((s.stream_id >> 5) == 4)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -100,6 +100,21 @@ class TorchNPUDeviceTestCase(TestCase):
|
||||
torch.npu.set_device_limit(torch.npu.current_device(), 12, 24)
|
||||
self.assertEqual(ans_dict, torch.npu.get_device_limit(torch.npu.current_device()))
|
||||
|
||||
@unittest.skip("CANN doesn't support now.")
|
||||
def test_set_stream_res_limit(self):
|
||||
ans_dict_1 = {'cube_core_num': 13, 'vector_core_num': 25}
|
||||
ans_dict_2 = {'cube_core_num': 14, 'vector_core_num': 26}
|
||||
ans_dict_3 = {'cube_core_num': 12, 'vector_core_num': 24}
|
||||
torch.npu.set_device_limit(torch.npu.current_device(), 12, 24)
|
||||
stream1 = torch.npu.current_stream()
|
||||
stream2 = torch.npu.Stream()
|
||||
torch.npu.set_stream_limit(stream1, 13, 25)
|
||||
torch.npu.set_stream_limit(stream2, 14, 26)
|
||||
self.assertEqual(ans_dict_1, torch.npu.get_stream_limit(stream1))
|
||||
self.assertEqual(ans_dict_2, torch.npu.get_stream_limit(stream2))
|
||||
torch.npu.reset_stream_limit(stream1)
|
||||
self.assertEqual(ans_dict_3, torch.npu.get_stream_limit(stream1))
|
||||
|
||||
class TorchNPUMemoryApiTestCase(TestCase):
|
||||
def test_npu_memory_stats(self):
|
||||
res = torch_npu.npu.memory_stats()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user