Compare commits
548
Commits
ci-test
...
v2.4.0-6.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38dc4eecba | ||
|
|
c0cc6904d7 | ||
|
|
07b503164b | ||
|
|
6c610bdd7a | ||
|
|
68830ba896 | ||
|
|
cb9c315bff | ||
|
|
9e466b4e89 | ||
|
|
369f7a0e9f | ||
|
|
373f3e63d8 | ||
|
|
df395e2afa | ||
|
|
ac76042abc | ||
|
|
63d8467f31 | ||
|
|
ebfa1de36d | ||
|
|
db0de44aea | ||
|
|
88dab78e8d | ||
|
|
fc30376248 | ||
|
|
ef8792d210 | ||
|
|
80fa195a84 | ||
|
|
9eb788bb73 | ||
|
|
3bb08bf1d6 | ||
|
|
86d81de327 | ||
|
|
fa1227f450 | ||
|
|
c1b504f118 | ||
|
|
e6dc5ec341 | ||
|
|
c9e711d58d | ||
|
|
0b6f2c8cd1 | ||
|
|
cab50831f9 | ||
|
|
b784af8a84 | ||
|
|
1a2d6e563b | ||
|
|
612adf8f3b | ||
|
|
30f6625962 | ||
|
|
5863159a4a | ||
|
|
a6dd66b376 | ||
|
|
43a44d4e6b | ||
|
|
feeccede5f | ||
|
|
876e8ca927 | ||
|
|
39d0f8f1f9 | ||
|
|
719c6d806d | ||
|
|
d03cea2298 | ||
|
|
b8304214bd | ||
|
|
9c1b339930 | ||
|
|
02feb5589f | ||
|
|
16d27922f5 | ||
|
|
e0282cd2d1 | ||
|
|
02b99391cf | ||
|
|
4420071b72 | ||
|
|
7d5a7c65bf | ||
|
|
35c025e2e1 | ||
|
|
83de7cc305 | ||
|
|
731166565f | ||
|
|
f10237f6de | ||
|
|
8c35c50d0d | ||
|
|
1704e59011 | ||
|
|
7f29d481e7 | ||
|
|
c2cc66a424 | ||
|
|
f27f8223f6 | ||
|
|
4c66934d0e | ||
|
|
e5549d6c6c | ||
|
|
925dce873c | ||
|
|
9084229a10 | ||
|
|
0a6f87fc98 | ||
|
|
8ceffb7f66 | ||
|
|
9b54ce410c | ||
|
|
f4a4893d40 | ||
|
|
4c863edac2 | ||
|
|
730f41d371 | ||
|
|
3173c45a30 | ||
|
|
554b47e1bf | ||
|
|
5a7c94c678 | ||
|
|
addc01bf91 | ||
|
|
0df7667372 | ||
|
|
b21eb76edc | ||
|
|
0a5379ed43 | ||
|
|
0ed8f28239 | ||
|
|
25152a0b50 | ||
|
|
4461808264 | ||
|
|
d6aae77849 | ||
|
|
fc135ad5dc | ||
|
|
7183474f8a | ||
|
|
a8cc0c8613 | ||
|
|
6d004558fa | ||
|
|
b3e75d7a2b | ||
|
|
dbc20018c7 | ||
|
|
715b8b4f42 | ||
|
|
a76de95a47 | ||
|
|
82ba39f72d | ||
|
|
1aadb1ff1a | ||
|
|
c990923daf | ||
|
|
82c14fdf04 | ||
|
|
3f6ca83875 | ||
|
|
71ad32495b | ||
|
|
550ddc4c51 | ||
|
|
f3c1a0689e | ||
|
|
a614807dd1 | ||
|
|
896dc891de | ||
|
|
54e6ee3e99 | ||
|
|
bfd0173e9d | ||
|
|
1ee7aedf6f | ||
|
|
d36c1eff9a | ||
|
|
8d065d3be4 | ||
|
|
a551968c03 | ||
|
|
0f83e9e201 | ||
|
|
37f63e6078 | ||
|
|
690c852379 | ||
|
|
8095c5e6ac | ||
|
|
10cdb8f40a | ||
|
|
6925eebb50 | ||
|
|
38f8449226 | ||
|
|
d39664ac28 | ||
|
|
b3afafa279 | ||
|
|
7abe00a53a | ||
|
|
fcf4f7a0b0 | ||
|
|
89a1d6f3b0 | ||
|
|
40d71357fc | ||
|
|
1ac3b8f2ca | ||
|
|
a5fbf191d9 | ||
|
|
db56ec56a5 | ||
|
|
4c4e4d6714 | ||
|
|
d1fa427394 | ||
|
|
76280592e4 | ||
|
|
37c2822091 | ||
|
|
699200d40f | ||
|
|
a3e5b0d5c2 | ||
|
|
e6ff53109b | ||
|
|
9cdb0fba94 | ||
|
|
b959d613a0 | ||
|
|
5a30166e5c | ||
|
|
260a473128 | ||
|
|
ec3c372727 | ||
|
|
5ebc55fea5 | ||
|
|
9ac5edd761 | ||
|
|
9a81fb0f26 | ||
|
|
44dca990c0 | ||
|
|
14bc3d6ff9 | ||
|
|
693311de46 | ||
|
|
5afc705799 | ||
|
|
4f714e93d3 | ||
|
|
075f04536f | ||
|
|
b0a13f8e2e | ||
|
|
547d8c9fc1 | ||
|
|
5845bc9abd | ||
|
|
f892d8e7c3 | ||
|
|
c66f358a9b | ||
|
|
3bf2aa98f5 | ||
|
|
d645185f35 | ||
|
|
755d417283 | ||
|
|
b8eff4b1ee | ||
|
|
d58f6df58d | ||
|
|
afe34dcded | ||
|
|
8fd0b83807 | ||
|
|
3bc896fcbf | ||
|
|
9bac8bce83 | ||
|
|
26d6a31f4e | ||
|
|
e7804c5ddb | ||
|
|
cb457c6997 | ||
|
|
4dc501b179 | ||
|
|
1a5e42871e | ||
|
|
30567ea15e | ||
|
|
98ab4605f6 | ||
|
|
213137fdea | ||
|
|
8ea72e2de8 | ||
|
|
2f6244e5f6 | ||
|
|
6a55e416f3 | ||
|
|
b30332fc57 | ||
|
|
a34f655263 | ||
|
|
3855b77d1f | ||
|
|
3db5617b73 | ||
|
|
c0f84a844c | ||
|
|
759778d285 | ||
|
|
511a72c547 | ||
|
|
79df5c050f | ||
|
|
90a4bbe0c3 | ||
|
|
6448e491f8 | ||
|
|
a743ca74d7 | ||
|
|
79b926b2c0 | ||
|
|
16aff26de8 | ||
|
|
8eeb8e7a5a | ||
|
|
5743c1629b | ||
|
|
a8652a4ea1 | ||
|
|
76c3f91e0f | ||
|
|
a3d931dc5c | ||
|
|
d080024ff7 | ||
|
|
dfaa981cd2 | ||
|
|
e7abc8bf42 | ||
|
|
cc55185294 | ||
|
|
0d6571364d | ||
|
|
1aa63ddee5 | ||
|
|
559f9d283b | ||
|
|
40fec5ec19 | ||
|
|
56fca82cf7 | ||
|
|
5c5785b6e8 | ||
|
|
8a8b264af1 | ||
|
|
593ee90adc | ||
|
|
0356080510 | ||
|
|
e10b417c5d | ||
|
|
1eeb746bf0 | ||
|
|
53e7b30cb6 | ||
|
|
8d6d9ed7d4 | ||
|
|
59b3efdd7e | ||
|
|
21105f60a6 | ||
|
|
5b096530d4 | ||
|
|
8046516a9c | ||
|
|
4726c8ed76 | ||
|
|
ee49610801 | ||
|
|
6ed1c1e116 | ||
|
|
f38af7869a | ||
|
|
160af57add | ||
|
|
b7a33a344d | ||
|
|
b81f7f10ea | ||
|
|
4a19f78d2c | ||
|
|
81d6c2e29c | ||
|
|
6cb91f6510 | ||
|
|
bd8189ee0c | ||
|
|
a2c3f9d64f | ||
|
|
b3336a61df | ||
|
|
d7178a68e3 | ||
|
|
5c67a1e9de | ||
|
|
868ef5f5b6 | ||
|
|
7508eeee11 | ||
|
|
0ac1efed1b | ||
|
|
4daac7e8da | ||
|
|
39ba24e3e4 | ||
|
|
78a5a2ff9c | ||
|
|
a9db2d23d1 | ||
|
|
0560a38ca9 | ||
|
|
5d7494b468 | ||
|
|
7da83f34f2 | ||
|
|
663e873e58 | ||
|
|
a0096c5722 | ||
|
|
81f551ce33 | ||
|
|
107f98e447 | ||
|
|
d0068ea919 | ||
|
|
b698d6f856 | ||
|
|
bc71d1c647 | ||
|
|
1ce1c5ec3f | ||
|
|
36abb31d57 | ||
|
|
4f71bd0348 | ||
|
|
4c99b92ac7 | ||
|
|
49044d0208 | ||
|
|
b86dc93df0 | ||
|
|
89f568d3ce | ||
|
|
fdd2fd3098 | ||
|
|
71d325e181 | ||
|
|
cbad50c9c4 | ||
|
|
e9eccfb14e | ||
|
|
e9345b0b0e | ||
|
|
927349bc93 | ||
|
|
63a4835cac | ||
|
|
137d1232ef | ||
|
|
4889f552d2 | ||
|
|
8f506c86be | ||
|
|
be7ba196ab | ||
|
|
5a12e9e729 | ||
|
|
58b706de97 | ||
|
|
ae5d9b9b0a | ||
|
|
0cf2967ca3 | ||
|
|
483a398118 | ||
|
|
2e901d10e3 | ||
|
|
636e76ee08 | ||
|
|
2aaca0807d | ||
|
|
2dad0ff01b | ||
|
|
ab6670f0b7 | ||
|
|
11f99c7fb4 | ||
|
|
40f4728cd0 | ||
|
|
b111592c00 | ||
|
|
e911e5e8d3 | ||
|
|
49c0e6f508 | ||
|
|
a2880d07b5 | ||
|
|
2bbb5d7f25 | ||
|
|
60ec47071a | ||
|
|
23c43ddc04 | ||
|
|
9142b4ecf2 | ||
|
|
52a8ba3257 | ||
|
|
c599a75e03 | ||
|
|
27ec00e51b | ||
|
|
c39e398e75 | ||
|
|
93257f8fef | ||
|
|
70660968cb | ||
|
|
fe6d0e58ae | ||
|
|
afc3b1f9ea | ||
|
|
aa3c23b926 | ||
|
|
cd2afd5784 | ||
|
|
9198887cce | ||
|
|
3ed1c3f4af | ||
|
|
6479f2196d | ||
|
|
cd0a96c5a2 | ||
|
|
ae52726b3f | ||
|
|
38f20dde73 | ||
|
|
6ab555199e | ||
|
|
6ef196399c | ||
|
|
2733b9345a | ||
|
|
9661d84b69 | ||
|
|
cf029dfb6c | ||
|
|
eb297a85f9 | ||
|
|
e300f173a8 | ||
|
|
1ea0621815 | ||
|
|
1effd24c32 | ||
|
|
bf95670977 | ||
|
|
f1133a9c88 | ||
|
|
0daff1d4ff | ||
|
|
575edebc79 | ||
|
|
dfaf2f5f41 | ||
|
|
f06471cfe6 | ||
|
|
d709f41c45 | ||
|
|
46049fcd85 | ||
|
|
d3e75cdf47 | ||
|
|
48e2e38c0f | ||
|
|
137f5c8c3d | ||
|
|
7ba3af7e98 | ||
|
|
d9c9127019 | ||
|
|
52c6b7f8c7 | ||
|
|
0dbeaaf459 | ||
|
|
72efc85ea0 | ||
|
|
f123b5a7dd | ||
|
|
eb9c839055 | ||
|
|
1bd747e9d5 | ||
|
|
7c2b892177 | ||
|
|
44c06d6870 | ||
|
|
29b25c60f8 | ||
|
|
bff862114c | ||
|
|
4252170141 | ||
|
|
6815295a16 | ||
|
|
756f80bfae | ||
|
|
6a5a22ccb3 | ||
|
|
5343e0bb82 | ||
|
|
cb1dc5e065 | ||
|
|
f9f8bd41cc | ||
|
|
b841730a35 | ||
|
|
e2312e68d0 | ||
|
|
8e3a8df4a1 | ||
|
|
03cb79159c | ||
|
|
72b584b2cf | ||
|
|
9ec04e3a66 | ||
|
|
513a708da1 | ||
|
|
05940fe967 | ||
|
|
efa8cffb2d | ||
|
|
db3bf8ddc6 | ||
|
|
aaeda00fd8 | ||
|
|
c1418e2af0 | ||
|
|
6b25a307ae | ||
|
|
8393257a69 | ||
|
|
e90f12cc6c | ||
|
|
64c50b0424 | ||
|
|
85d7e14067 | ||
|
|
b19c8b58a6 | ||
|
|
fe42a8cc11 | ||
|
|
154e416c23 | ||
|
|
c80aea4aa1 | ||
|
|
2c16cb9a6f | ||
|
|
16e82d0526 | ||
|
|
0b3bf082a0 | ||
|
|
d80e087e12 | ||
|
|
bd26396598 | ||
|
|
d37b971b62 | ||
|
|
dab7efa6bd | ||
|
|
bb180d51d5 | ||
|
|
35754672b8 | ||
|
|
8a19b4ecb7 | ||
|
|
8efd5d5fcc | ||
|
|
fe54089634 | ||
|
|
df303752a7 | ||
|
|
19f8388c8b | ||
|
|
0361cc3281 | ||
|
|
51a30491fd | ||
|
|
d1c2331cf3 | ||
|
|
55c9fa669e | ||
|
|
ba6a3c2061 | ||
|
|
4ca6ae4205 | ||
|
|
253b798368 | ||
|
|
29428bb316 | ||
|
|
4536b37059 | ||
|
|
c9ecf79c26 | ||
|
|
03be6752b7 | ||
|
|
e9fd66af35 | ||
|
|
1f471f1e31 | ||
|
|
83344a9459 | ||
|
|
89d96105ab | ||
|
|
1e7a9fb79c | ||
|
|
66c122e728 | ||
|
|
d550f391ee | ||
|
|
ea628724fa | ||
|
|
40ea91e037 | ||
|
|
8d5daedb3c | ||
|
|
d0ae00bdc1 | ||
|
|
7c91133693 | ||
|
|
c5476513a5 | ||
|
|
f643267424 | ||
|
|
541a957c8a | ||
|
|
53c91313b3 | ||
|
|
bce0721a79 | ||
|
|
0e6ddfc79e | ||
|
|
e249eb93d5 | ||
|
|
ccc6a57ae9 | ||
|
|
b114669767 | ||
|
|
946a3860f7 | ||
|
|
40bb46139a | ||
|
|
0148161c10 | ||
|
|
495ffb8bbe | ||
|
|
5129fba8e7 | ||
|
|
082cb3812b | ||
|
|
73d3d2c0a2 | ||
|
|
f9ac4520a3 | ||
|
|
a6c7bef22b | ||
|
|
066d5e91f4 | ||
|
|
b961c3cca0 | ||
|
|
f2c1ead2df | ||
|
|
ba0fe05532 | ||
|
|
1895ce54a3 | ||
|
|
5e68a93e20 | ||
|
|
2fc7a0a3d8 | ||
|
|
6722db0236 | ||
|
|
ba32b2cc86 | ||
|
|
7a6ada6d85 | ||
|
|
6f37fae28a | ||
|
|
3d5e500734 | ||
|
|
f792aee96c | ||
|
|
8c7496e5fd | ||
|
|
2b7d72230e | ||
|
|
f464a8590d | ||
|
|
d6d94a8cea | ||
|
|
9afbac1363 | ||
|
|
2e46884872 | ||
|
|
b51dd4c5fd | ||
|
|
6358ef53ca | ||
|
|
24d8c73dea | ||
|
|
3e177f064e | ||
|
|
c09ec5148a | ||
|
|
67b38c24d7 | ||
|
|
955d6dac76 | ||
|
|
d30a39412e | ||
|
|
3a09fb8fc8 | ||
|
|
23f8135b18 | ||
|
|
99c072061a | ||
|
|
1b7eea0bfa | ||
|
|
dc3212eb75 | ||
|
|
47c57ffbee | ||
|
|
6031393ce4 | ||
|
|
2cac17c3f1 | ||
|
|
6e1b5d0298 | ||
|
|
0db2081608 | ||
|
|
669bd2159f | ||
|
|
3f8c197215 | ||
|
|
cfb5e34ef1 | ||
|
|
3e3fb3ea6c | ||
|
|
ea4a589fa0 | ||
|
|
5b6a2594f9 | ||
|
|
387037bef8 | ||
|
|
125c398230 | ||
|
|
9a5e52eb22 | ||
|
|
0d39bd3125 | ||
|
|
eb06b29078 | ||
|
|
a2e912ff7f | ||
|
|
263eb24522 | ||
|
|
5549804333 | ||
|
|
9761fcbc1c | ||
|
|
b717a5c2cd | ||
|
|
7c070c85e5 | ||
|
|
474758183d | ||
|
|
06e0b9f2b3 | ||
|
|
acfefb0597 | ||
|
|
3aea1c9694 | ||
|
|
10218e00ec | ||
|
|
89250c217d | ||
|
|
f0d543599f | ||
|
|
b083d951cc | ||
|
|
faaa1b8867 | ||
|
|
d27449e879 | ||
|
|
e2283a56e3 | ||
|
|
c64ca0cd74 | ||
|
|
d237f62beb | ||
|
|
5164b85711 | ||
|
|
2cb258c07d | ||
|
|
7d80df1d3a | ||
|
|
7e982238d6 | ||
|
|
7af9c51353 | ||
|
|
78a08499ea | ||
|
|
f00d95a9ae | ||
|
|
1683f6f6a8 | ||
|
|
7a0b10e5f6 | ||
|
|
67a1de77cb | ||
|
|
a6af702231 | ||
|
|
bf4dda5041 | ||
|
|
ad4ba53400 | ||
|
|
93712b7b10 | ||
|
|
30376fc5a0 | ||
|
|
eab5804e3c | ||
|
|
963ab455a0 | ||
|
|
1ea0cffc6d | ||
|
|
49c7a8ded4 | ||
|
|
5ef6797186 | ||
|
|
410cf2ea1e | ||
|
|
8614d923d9 | ||
|
|
779a913f6b | ||
|
|
1980a17707 | ||
|
|
637e756394 | ||
|
|
3cb0faca03 | ||
|
|
0cccc02cb6 | ||
|
|
07ddcb8f12 | ||
|
|
a612db5de7 | ||
|
|
7545317d04 | ||
|
|
faa0612ccb | ||
|
|
9da7de7dd1 | ||
|
|
7435a3d5a2 | ||
|
|
09d4170497 | ||
|
|
dc90836441 | ||
|
|
aae414f5ed | ||
|
|
14740183f1 | ||
|
|
5d5f544fe3 | ||
|
|
d7d0b7869e | ||
|
|
37aebaaca6 | ||
|
|
af068e1b96 | ||
|
|
1a4885ff90 | ||
|
|
2735e7043d | ||
|
|
1a901fbe71 | ||
|
|
d217d46d43 | ||
|
|
7def540387 | ||
|
|
8149d758d7 | ||
|
|
ba5affb786 | ||
|
|
2c867c4e42 | ||
|
|
bee8bfa839 | ||
|
|
f1833ae693 | ||
|
|
74dcd4a855 | ||
|
|
f96d23b0dc | ||
|
|
62cc9202ef | ||
|
|
c5b0a6402f | ||
|
|
cbd9d676fa | ||
|
|
6219ab6cd9 | ||
|
|
7229af8304 | ||
|
|
a0f60094af | ||
|
|
bfa851f6f9 | ||
|
|
2ba07dabf1 | ||
|
|
7fd6046d39 | ||
|
|
ed252aa74b | ||
|
|
a50a82585f | ||
|
|
149748733b | ||
|
|
0b082171f0 | ||
|
|
84a126505f | ||
|
|
69845a4a98 | ||
|
|
d1132b2781 | ||
|
|
4a511ad638 | ||
|
|
d748ff1a75 | ||
|
|
3a389844b6 | ||
|
|
18f0fe9fdd | ||
|
|
6210761f5b | ||
|
|
126168dcc7 | ||
|
|
140ce0fb51 | ||
|
|
5097c83359 | ||
|
|
57ac7979c9 |
@@ -43,7 +43,7 @@ jobs:
|
||||
- name: Compile torch
|
||||
working-directory: /root/build/pytorch/pytorch
|
||||
run: |
|
||||
pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
pip3 install -r requirements.txt -i https://mirrors.huaweicloud.com/repository/pypi/simple
|
||||
export _GLIBCXX_USE_CXX11_ABI=0
|
||||
export USE_CUDA=0
|
||||
export USE_XNNPACK=0
|
||||
@@ -51,11 +51,11 @@ jobs:
|
||||
- name: Compile and install torch_npu
|
||||
working-directory: /root/build/npu/pytorch
|
||||
run: |
|
||||
pip3 install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
pip3 install -r requirements.txt -i https://mirrors.huaweicloud.com/repository/pypi/simple
|
||||
bash ci/build.sh --python=3.8
|
||||
pip3 install dist/torch_npu*.whl
|
||||
- name: Do the test
|
||||
working-directory: /root/build
|
||||
run: |
|
||||
pip3 install -r npu/pytorch/test/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple --no-deps
|
||||
pip3 install -r npu/pytorch/test/requirements.txt -i https://mirrors.huaweicloud.com/repository/pypi/simple --no-deps
|
||||
python npu/pytorch/ci/access_control_test.py
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
path = third_party/op-plugin
|
||||
url = https://gitee.com/ascend/op-plugin.git
|
||||
ignore = dirty
|
||||
branch = 6.0.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 = 6.0.0
|
||||
[submodule "third_party/Tensorpipe"]
|
||||
path = third_party/Tensorpipe
|
||||
url = https://gitee.com/ascend/Tensorpipe.git
|
||||
|
||||
+33
-2
@@ -33,6 +33,34 @@ SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
|
||||
SET(CMAKE_CXX_FLAGS_RELEASE "-O2")
|
||||
SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -g")
|
||||
|
||||
# LTO&PGO optimization in compile option
|
||||
SET(IF_APPEND FALSE)
|
||||
if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
|
||||
SET(APPEND_FLAGS "-fGNU-compatibility -fuse-ld=lld -Wno-non-pod-varargs")
|
||||
if (DEFINED ENABLE_LTO)
|
||||
SET(IF_APPEND TRUE)
|
||||
SET(APPEND_FLAGS "${APPEND_FLAGS} -flto=thin")
|
||||
endif()
|
||||
if (DEFINED PGO_MODE)
|
||||
SET(IF_APPEND TRUE)
|
||||
if (PGO_MODE EQUAL 1)
|
||||
SET(APPEND_FLAGS "${APPEND_FLAGS} -fprofile-generate")
|
||||
elseif (PGO_MODE EQUAL 2)
|
||||
SET(APPEND_FLAGS "${APPEND_FLAGS} -fprofile-use=${CMAKE_CURRENT_SOURCE_DIR}/default.profdata")
|
||||
endif()
|
||||
endif()
|
||||
else()
|
||||
if (DEFINED ENABLE_LTO)
|
||||
message(FATAL_ERROR "Currently, LTO auto build is not supported in ${CMAKE_CXX_COMPILER_ID}")
|
||||
endif()
|
||||
if (DEFINED PGO_MODE)
|
||||
message(FATAL_ERROR "Currently, PGO auto build is not supported in ${CMAKE_CXX_COMPILER_ID}")
|
||||
endif()
|
||||
endif()
|
||||
if (IF_APPEND)
|
||||
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${APPEND_FLAGS}")
|
||||
endif()
|
||||
|
||||
# check and set CMAKE_CXX_STANDARD
|
||||
string(FIND "${CMAKE_CXX_FLAGS}" "-std=c++" env_cxx_standard)
|
||||
if(env_cxx_standard GREATER -1)
|
||||
@@ -196,6 +224,7 @@ set(FRAMEWORK_SRCS)
|
||||
|
||||
if (NOT DEFINED BUILD_LIBTORCH)
|
||||
set(DIST_SRCS)
|
||||
set(FLOP_SRCS)
|
||||
set(NPU_SRCS)
|
||||
set(PROF_SRCS)
|
||||
set(UTILS_SRCS)
|
||||
@@ -209,6 +238,7 @@ endif()
|
||||
add_subdirectory(${TORCHNPU_ROOT}/aten)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/core)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/framework)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/flopcount)
|
||||
|
||||
if (NOT DEFINED BUILD_LIBTORCH)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/distributed)
|
||||
@@ -235,10 +265,10 @@ if (DEFINED BUILD_TENSORPIPE)
|
||||
endif()
|
||||
|
||||
if (DEFINED BUILD_LIBTORCH)
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${FRAMEWORK_SRCS} ${NPU_CPP_LIBS_SRCS})
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${FLOP_SRCS} ${FRAMEWORK_SRCS} ${NPU_CPP_LIBS_SRCS})
|
||||
else()
|
||||
# Compile code with pybind11
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${DIST_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${UTILS_SRCS} ${SAN_SRCS})
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${DIST_SRCS} ${FLOP_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${UTILS_SRCS} ${SAN_SRCS})
|
||||
endif()
|
||||
|
||||
add_library(${PLUGIN_NAME} SHARED ${CPP_SRCS})
|
||||
@@ -316,3 +346,4 @@ if (DEFINED BUILD_LIBTORCH)
|
||||
${PROJECT_SOURCE_DIR}/build/Torch_npuConfig.cmake
|
||||
@ONLY)
|
||||
endif()
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ approvers:
|
||||
- atlasaccount
|
||||
- dilililiwhy
|
||||
- chenhao_1209
|
||||
- sunboquan
|
||||
- wangchao147
|
||||
reviewers:
|
||||
- xiaxia3
|
||||
- ascendzyj
|
||||
@@ -44,3 +46,4 @@ reviewers:
|
||||
- chuboning
|
||||
- guo-guanghao
|
||||
- yuhaiyan
|
||||
- wangchao147
|
||||
|
||||
@@ -19,13 +19,13 @@ Install **PyTorch** through pip.
|
||||
**For Aarch64:**
|
||||
|
||||
```Python
|
||||
pip3 install torch==2.1.0
|
||||
pip3 install torch==2.4.0
|
||||
```
|
||||
|
||||
**For x86:**
|
||||
|
||||
```Python
|
||||
pip3 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu
|
||||
pip3 install torch==2.4.0+cpu --index-url https://download.pytorch.org/whl/cpu
|
||||
```
|
||||
|
||||
2. **Install torch-npu dependencies**
|
||||
@@ -39,29 +39,31 @@ pip3 install setuptools
|
||||
|
||||
If the installation fails, use the download link or visit the [PyTorch official website](https://pytorch.org/) to download the installation package of the corresponding version.
|
||||
|
||||
| OS arch | Python version | link |
|
||||
| ------- | -------------- | ------------------------------------------------------------ |
|
||||
| x86 | Python3.8 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp38-cp38-linux_x86_64.whl#sha256=9e5cfd931a65b38d222755a45dabb53b836be31bc620532bc66fee77e3ff67dc) |
|
||||
| x86 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp39-cp39-linux_x86_64.whl#sha256=86cc28df491fa84738affe752f9870791026565342f69e4ab63e5b935f00a495) |
|
||||
| x86 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp310-cp310-linux_x86_64.whl#sha256=5077921fc2b54e69a534f3a9c0b98493c79a5547c49d46f5e77e42da3610e011) |
|
||||
| aarch64 | Python3.8 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=761822761fffaa1c18a62c5deb13abaa780862577d3eadc428f1daa632536905) |
|
||||
| aarch64 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=de7d63c6ecece118684415a3dbd4805af4a4c1ee1490cccf7405d8c240a481b4) |
|
||||
| aarch64 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=a04a0296d47f28960f51c18c5489a8c3472f624ec3b5bcc8e2096314df8c3342) |
|
||||
| OS arch | Python version | link |
|
||||
|---------|----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| x86 | Python3.8 | [link](https://download.pytorch.org/whl/cpu/torch-2.4.0%2Bcpu-cp38-cp38-linux_x86_64.whl#sha256=08753c3d776ae49dc9ddbae02e26720a513a4dc7997e41d95392bca71623a0cd) |
|
||||
| x86 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.4.0%2Bcpu-cp39-cp39-linux_x86_64.whl#sha256=040abaee8affa1bb0f3ca14ca693ba81d0d90d88df5b8a839af96933a7fa2d29) |
|
||||
| x86 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.4.0%2Bcpu-cp310-cp310-linux_x86_64.whl#sha256=0e59377b27823dda6d26528febb7ca06fc5b77816eaa58b4420cc8785e33d4ce) |
|
||||
| x86 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.4.0%2Bcpu-cp311-cp311-linux_x86_64.whl#sha256=14a7a8b595347dddca594f9e448b93ce68ce4f871acbd32cf04bda7c03664c0c) |
|
||||
| aarch64 | Python3.8 | [link](https://download.pytorch.org/whl/cpu/torch-2.4.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=9eba83f8a8f98542f917e39000c903f154655acf6375c073cfcd4306a154eb80) |
|
||||
| aarch64 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.4.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=2786a47c8d8dec176fc679d2aab9a6f549c25452510b49650ab134135266ba33) |
|
||||
| aarch64 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.4.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=7c159e89d4ecf08403f9d1373d554422240b9b1146a0a19129069dc357a72b2b) |
|
||||
| aarch64 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=38169cb0f1e6727c3dac8dac8b9a48d072a49f643b908a99155ef1d81b61bdeb) |
|
||||
|
||||
3. **Install torch-npu**
|
||||
|
||||
```
|
||||
pip3 install torch-npu==2.1.0.post3
|
||||
pip3 install torch-npu==2.4.0.post2
|
||||
```
|
||||
|
||||
### 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/:
|
||||
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.
|
||||
|
||||
1. **Clone torch-npu**
|
||||
|
||||
```
|
||||
git clone https://github.com/ascend/pytorch.git -b v2.1.0-6.0.rc1 --depth 1
|
||||
git clone https://github.com/ascend/pytorch.git -b v2.4.0-6.0.0 --depth 1
|
||||
```
|
||||
|
||||
2. **Build Docker Image**
|
||||
@@ -120,46 +122,80 @@ Refer to [API of Ascend Extension for PyTorch](docs/api/torch_npu_apis.md) for m
|
||||
## PyTorch and Python Version Matching Table
|
||||
|
||||
| PyTorch Version | Python Version |
|
||||
| ------------- | :----------------------------------------------------------- |
|
||||
| PyTorch1.11.0 | Python3.7.x(>=3.7.5),Python3.8.x,Python3.9.x,Python3.10.x |
|
||||
| PyTorch2.1.0 | Python3.8.x,Python3.9.x,Python3.10.x |
|
||||
| PyTorch2.2.0 | Python3.8.x,Python3.9.x,Python3.10.x |
|
||||
|-----------------|:----------------------------------------------------------|
|
||||
| PyTorch1.11.0 | Python3.7.x(>=3.7.5),Python3.8.x,Python3.9.x,Python3.10.x |
|
||||
| PyTorch2.1.0 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
|
||||
| PyTorch2.2.0 | Python3.8.x,Python3.9.x,Python3.10.x |
|
||||
| PyTorch2.3.1 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
|
||||
| PyTorch2.4.0 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
|
||||
|
||||
## Ascend Auxiliary Software
|
||||
|
||||
**PyTorch Extension** versions follow the naming convention `{PyTorch version}-{Ascend version}`, where the former represents the PyTorch version compatible with the **PyTorch Extension**, and the latter is used to match the CANN version. The detailed matching is as follows:
|
||||
|
||||
| CANN Version | Supported PyTorch Version | Supported Extension Version | Github Branch | AscendHub Image Version/Name([Link](https://ascendhub.huawei.com/#/detail/pytorch-modelzoo)) |
|
||||
|----------------|--------------|-------------------|-------------------|----------------------|
|
||||
| CANN 8.0.RC1 | 2.2.0 | 2.2.0 | v2.2.0-6.0.rc1 | - |
|
||||
| | 2.1.0 | 2.1.0.post3 | v2.1.0-6.0.rc1 | - |
|
||||
| | 1.11.0 | 1.11.0.post11 | v1.11.0-6.0.rc1 | - |
|
||||
| CANN 7.0.0 | 2.1.0 | 2.1.0 | v2.1.0-5.0.0 | - |
|
||||
| | 2.0.1 | 2.0.1.post1 | v2.0.1-5.0.0 | - |
|
||||
| | 1.11.0 | 1.11.0.post8 | v1.11.0-5.0.0 | - |
|
||||
| CANN 7.0.RC1 | 2.1.0 | 2.1.0.rc1 | v2.1.0-5.0.rc3 | - |
|
||||
| | 2.0.1 | 2.0.1 | v2.0.1-5.0.rc3 | - |
|
||||
| | 1.11.0 | 1.11.0.post4 | v1.11.0-5.0.rc3 | - |
|
||||
| CANN 6.3.RC3.1 | 1.11.0 | 1.11.0.post3 | v1.11.0-5.0.rc2.2 | - |
|
||||
| CANN 6.3.RC3 | 1.11.0 | 1.11.0.post2 | v1.11.0-5.0.rc2.1 | - |
|
||||
| CANN 6.3.RC2 | 2.0.1 | 2.0.1.rc1 | v2.0.1-5.0.rc2 | - |
|
||||
| | 1.11.0 | 1.11.0.post1 | v1.11.0-5.0.rc2 | 23.0.RC1-1.11.0 |
|
||||
| | 1.8.1 | 1.8.1.post2 | v1.8.1-5.0.rc2 | 23.0.RC1-1.8.1 |
|
||||
| CANN 6.3.RC1 | 1.11.0 | 1.11.0 | v1.11.0-5.0.rc1 | - |
|
||||
| | 1.8.1 | 1.8.1.post1 | v1.8.1-5.0.rc1 | - |
|
||||
| CANN 6.0.1 | 1.5.0 | 1.5.0.post8 | v1.5.0-3.0.0 | 22.0.0 |
|
||||
| | 1.8.1 | 1.8.1 | v1.8.1-3.0.0 | 22.0.0-1.8.1 |
|
||||
| | 1.11.0 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 | - |
|
||||
| CANN 6.0.RC1 | 1.5.0 | 1.5.0.post7 | v1.5.0-3.0.rc3 | 22.0.RC3 |
|
||||
| | 1.8.1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 | 22.0.RC3-1.8.1 |
|
||||
| | 1.11.0 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 | - |
|
||||
| CANN 5.1.RC2 | 1.5.0 | 1.5.0.post6 | v1.5.0-3.0.rc2 | 22.0.RC2 |
|
||||
| | 1.8.1 | 1.8.1.rc2 | v1.8.1-3.0.rc2 | 22.0.RC2-1.8.1 |
|
||||
| CANN 5.1.RC1 | 1.5.0 | 1.5.0.post5 | v1.5.0-3.0.rc1 | 22.0.RC1 |
|
||||
| | 1.8.1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 | - |
|
||||
| CANN 5.0.4 | 1.5.0 | 1.5.0.post4 | 2.0.4.tr5 | 21.0.4 |
|
||||
| CANN 5.0.3 | 1.8.1 | 1.5.0.post3 | 2.0.3.tr5 | 21.0.3 |
|
||||
| CANN 5.0.2 | 1.5.0 | 1.5.0.post2 | 2.0.2.tr5 | 21.0.2 |
|
||||
| CANN Version | Supported PyTorch Version | Supported Extension Version | Github Branch |
|
||||
|-----------------------|---------------------------|-----------------------------|-------------------|
|
||||
| CANN 8.0.0 | 2.4.0 | 2.4.0.post2 | v2.4.0-6.0.0 |
|
||||
| | 2.3.1 | 2.3.1.post4 | v2.3.1-6.0.0 |
|
||||
| | 2.1.0 | 2.1.0.post10 | v2.1.0-6.0.0 |
|
||||
| CANN 8.0.RC3 | 2.4.0 | 2.4.0 | v2.4.0-6.0.rc3 |
|
||||
| | 2.3.1 | 2.3.1.post2 | v2.3.1-6.0.rc3 |
|
||||
| | 2.1.0 | 2.1.0.post8 | v2.1.0-6.0.rc3 |
|
||||
| CANN 8.0.RC2 | 2.3.1 | 2.3.1 | v2.3.1-6.0.rc2 |
|
||||
| | 2.2.0 | 2.2.0.post2 | v2.2.0-6.0.rc2 |
|
||||
| | 2.1.0 | 2.1.0.post6 | v2.1.0-6.0.rc2 |
|
||||
| | 1.11.0 | 1.11.0.post14 | v1.11.0-6.0.rc2 |
|
||||
| CANN 8.0.RC2.alpha002 | 2.3.1 | 2.3.1rc1 | v2.3.1 |
|
||||
| CANN 8.0.RC1 | 2.2.0 | 2.2.0 | v2.2.0-6.0.rc1 |
|
||||
| | 2.1.0 | 2.1.0.post4 | v2.1.0-6.0.rc1 |
|
||||
| | 1.11.0 | 1.11.0.post11 | v1.11.0-6.0.rc1 |
|
||||
| CANN 7.0.0 | 2.1.0 | 2.1.0 | v2.1.0-5.0.0 |
|
||||
| | 2.0.1 | 2.0.1.post1 | v2.0.1-5.0.0 |
|
||||
| | 1.11.0 | 1.11.0.post8 | v1.11.0-5.0.0 |
|
||||
| CANN 7.0.RC1 | 2.1.0 | 2.1.0.rc1 | v2.1.0-5.0.rc3 |
|
||||
| | 2.0.1 | 2.0.1 | v2.0.1-5.0.rc3 |
|
||||
| | 1.11.0 | 1.11.0.post4 | v1.11.0-5.0.rc3 |
|
||||
| CANN 6.3.RC3.1 | 1.11.0 | 1.11.0.post3 | v1.11.0-5.0.rc2.2 |
|
||||
| CANN 6.3.RC3 | 1.11.0 | 1.11.0.post2 | v1.11.0-5.0.rc2.1 |
|
||||
| CANN 6.3.RC2 | 2.0.1 | 2.0.1.rc1 | v2.0.1-5.0.rc2 |
|
||||
| | 1.11.0 | 1.11.0.post1 | v1.11.0-5.0.rc2 |
|
||||
| | 1.8.1 | 1.8.1.post2 | v1.8.1-5.0.rc2 |
|
||||
| CANN 6.3.RC1 | 1.11.0 | 1.11.0 | v1.11.0-5.0.rc1 |
|
||||
| | 1.8.1 | 1.8.1.post1 | v1.8.1-5.0.rc1 |
|
||||
| CANN 6.0.1 | 1.5.0 | 1.5.0.post8 | v1.5.0-3.0.0 |
|
||||
| | 1.8.1 | 1.8.1 | v1.8.1-3.0.0 |
|
||||
| | 1.11.0 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 |
|
||||
| CANN 6.0.RC1 | 1.5.0 | 1.5.0.post7 | v1.5.0-3.0.rc3 |
|
||||
| | 1.8.1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 |
|
||||
| | 1.11.0 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 |
|
||||
| CANN 5.1.RC2 | 1.5.0 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
|
||||
| | 1.8.1 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
|
||||
| CANN 5.1.RC1 | 1.5.0 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
|
||||
| | 1.8.1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
|
||||
| CANN 5.0.4 | 1.5.0 | 1.5.0.post4 | 2.0.4.tr5 |
|
||||
| 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 |
|
||||
|
||||
## Hardware support
|
||||
|
||||
The Ascend training device includes the following models, all of which can be used as training environments for PyTorch models
|
||||
| Product series | Product model |
|
||||
|-----------------------|----------------------------------|
|
||||
| Atlas Training series products | Atlas 800(model: 9000) |
|
||||
| | Atlas 800(model:9010) |
|
||||
| | Atlas 900 PoD(model:9000) |
|
||||
| | Atlas 300T(model:9000) |
|
||||
| | Atlas 300T Pro(model:9000) |
|
||||
| Atlas A2 Training series products | Atlas 800T A2 |
|
||||
| | Atlas 900 A2 PoD |
|
||||
| | Atlas 200T A2 Box16 |
|
||||
| | Atlas 300T A2 |
|
||||
|
||||
The Ascend inference device includes the following models, all of which can be used as inference environments for large models
|
||||
| Product series | Product model |
|
||||
|-----------------------|----------------------------------|
|
||||
| Atlas 800I A2 Inference product | Atlas 800I A2 |
|
||||
|
||||
|
||||
## Pipeline Status
|
||||
|
||||
@@ -180,32 +216,33 @@ The version branches of AscendPyTorch have the following maintenance phases:
|
||||
| **Status** | **Duration** | **Description** |
|
||||
|-------------------|--------------|--------------------------------------------------------------------------------------------------------------------------------|
|
||||
| Planning | 1-3 months | Plan features. |
|
||||
| Development | 3 months | Develop features. |
|
||||
| Maintained | 6-12 months | Allow the incorporation of all resolved issues and release the version, Different versions of PyTorch adopt varying support policies. The maintenance periods for Regular Releases and Long-Term Support versions are 6 months and 12 months, respectively. |
|
||||
| Unmaintained | 0-3 months | Allow the incorporation of all resolved issues. No dedicated maintenance personnel are available. No version will be released. |
|
||||
| Development | 6-12 months | Develop new features and fix issues, regularly release new versions. Different strategies are adopted for different versions of PyTorch, with a regular branch development cycle of 6 months and a long-term support branch development cycle of 12 months. |
|
||||
| Maintained | 1 year/3.5 years | Regular Release branch for 1 year, Long Term Support branch maintenance for 3.5 years. Fix major issues, do not incorporate new features, and release patch versions based on the impact of fixed bugs. |
|
||||
| End Of Life (EOL) | N/A | Do not accept any modification to a branch. |
|
||||
|
||||
## PyTorch Maintenance Policies
|
||||
|
||||
| **PyTorch** | **Maintenance Policies** | **Status** | **Launch Date** | **Subsequent Status** | **EOL Date** |
|
||||
|-----------|--------------------|--------------|------------|-----------------|-----------|
|
||||
| 2.2.0 | Regular Release | Maintained | 2024/04/01 | Unmaintained 2024-10-15 estimated | |
|
||||
| 2.1.0 | Long Term Support | Maintained | 2023/10/15 | Unmaintained 2024-10-15 estimated | |
|
||||
| 2.4.0 | Regular Release | Development | 2024/10/15 |Expected to enter maintenance status from March 15, 2025 | |
|
||||
| 2.3.1 | Regular Release | Development | 2024/06/06 | Expected to enter maintenance status from December 6, 2024 | |
|
||||
| 2.2.0 | Regular Release | Maintained | 2024/04/01 | Expected to enter maintenance free status from September 10th, 2025| |
|
||||
| 2.1.0 | Long Term Support | Development | 2023/10/15 | Expected to enter maintenance status from March 30, 2025 | |
|
||||
| 2.0.1 | Regular Release | EOL | 2023/7/19 | | 2024/3/14 |
|
||||
| 1.11.0 | Long Term Support | Maintained | 2023/4/19 | Unmaintained 2024-4-19 estimated | |
|
||||
| 1.11.0 | Long Term Support | Maintained | 2023/4/19 | Expected to enter maintenance free status from September 10th, 2025 | |
|
||||
| 1.8.1 | Long Term Support | EOL | 2022/4/10 | | 2023/4/10 |
|
||||
| 1.5.0 | Long Term Support | EOL | 2021/7/29 | | 2022/7/29 |
|
||||
|
||||
## Reference Documents
|
||||
|
||||
For more detailed information on installation guides, model migration, training/inference tutorials, and API lists, please refer to the [Ascend Extension for PyTorch on the HiAI Community](https://www.hiascend.com/software/ai-frameworks/commercial).
|
||||
For more detailed information on installation guides, model migration, training/inference tutorials, and API lists, please refer to the [Ascend Extension for PyTorch on the HiAI Community](https://www.hiascend.com/software/ai-frameworks?framework=pytorch).
|
||||
|
||||
| Document Name | Document Link |
|
||||
| -------------------------------- | ------------------------------------------------------------ |
|
||||
| Installation Guide | [link](https://www.hiascend.com/document/detail/zh/Pytorch/60RC1/quickstart/instg) |
|
||||
| Network Model Migration and Training | [link](https://www.hiascend.com/document/detail/zh/Pytorch/60RC1/ptmoddevg/trainingmigrguide/PT_LMTMOG_0003.html) |
|
||||
| Operator Adaptation | [link](https://www.hiascend.com/document/detail/zh/canncommercial/700/operatordev/tbeaicpudevg/atlasopdev_10_0086.html) |
|
||||
| API List (PyTorch and Custom Interfaces) | [link](https://www.hiascend.com/document/detail/zh/Pytorch/60RC1/apiref/apilist/ptaoplist_000002.html) |
|
||||
| Document Name | Document Link |
|
||||
|------------------------------------------|-------------------------------------------------------------------------------------------------------------------------|
|
||||
| Installation Guide | [link](https://www.hiascend.com/document/detail/zh/Pytorch/60RC3/configandinstg/instg/insg_0001.html) |
|
||||
| Network Model Migration and Training | [link](https://www.hiascend.com/document/detail/zh/Pytorch/60RC3/ptmoddevg/trainingmigrguide/PT_LMTMOG_0003.html) |
|
||||
| Operator Adaptation | [link](https://www.hiascend.com/document/detail/zh/canncommercial/80RC3/operatordev/tbeaicpudevg/atlasopdev_10_0086.html) |
|
||||
| API List (PyTorch and Custom Interfaces) | [link](https://www.hiascend.com/document/detail/zh/Pytorch/60RC3/apiref/apilist/ptaoplist_000002.html) |
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+96
-59
@@ -19,25 +19,27 @@
|
||||
**aarch64:**
|
||||
|
||||
```Python
|
||||
pip3 install torch==2.1.0
|
||||
pip3 install torch==2.4.0
|
||||
```
|
||||
|
||||
**x86:**
|
||||
|
||||
```Python
|
||||
pip3 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu
|
||||
pip3 install torch==2.4.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) |
|
||||
| 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) |
|
||||
| 架构 | Python版本 | 下载链接 |
|
||||
|---------|------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| x86 | Python3.8 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.4.0%2Bcpu-cp38-cp38-linux_x86_64.whl#sha256=08753c3d776ae49dc9ddbae02e26720a513a4dc7997e41d95392bca71623a0cd) |
|
||||
| x86 | Python3.9 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.4.0%2Bcpu-cp39-cp39-linux_x86_64.whl#sha256=040abaee8affa1bb0f3ca14ca693ba81d0d90d88df5b8a839af96933a7fa2d29) |
|
||||
| x86 | Python3.10 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.4.0%2Bcpu-cp310-cp310-linux_x86_64.whl#sha256=0e59377b27823dda6d26528febb7ca06fc5b77816eaa58b4420cc8785e33d4ce) |
|
||||
| x86 | Python3.11 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.4.0%2Bcpu-cp311-cp311-linux_x86_64.whl#sha256=14a7a8b595347dddca594f9e448b93ce68ce4f871acbd32cf04bda7c03664c0c) |
|
||||
| aarch64 | Python3.8 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.4.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=9eba83f8a8f98542f917e39000c903f154655acf6375c073cfcd4306a154eb80) |
|
||||
| aarch64 | Python3.9 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.4.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=2786a47c8d8dec176fc679d2aab9a6f549c25452510b49650ab134135266ba33) |
|
||||
| aarch64 | Python3.10 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.4.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=7c159e89d4ecf08403f9d1373d554422240b9b1146a0a19129069dc357a72b2b) |
|
||||
| aarch64 | Python3.11 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.4.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=38169cb0f1e6727c3dac8dac8b9a48d072a49f643b908a99155ef1d81b61bdeb) |
|
||||
|
||||
2. **安装torch_npu依赖**
|
||||
|
||||
@@ -51,18 +53,18 @@ pip3 install setuptools
|
||||
3. **安装torch_npu**
|
||||
|
||||
```
|
||||
pip3 install torch-npu==2.1.0.post3
|
||||
pip3 install torch-npu==2.4.0.post2
|
||||
```
|
||||
如需要保存安装日志,可在pip3 install命令后面加上参数 `--log <PATH>`,并对您指定的目录`<PATH>`做好权限管控。
|
||||
|
||||
### 使用源代码进行安装
|
||||
|
||||
某些特殊场景下,用户可能需要自行编译**torch_npu**。可以根据[昇腾辅助软件表](#昇腾辅助软件)和[PyTorch与Python版本配套表](#PyTorch与Python版本配套表)选择合适的分支。推荐使用Docker镜像编译**torch_npu**,可以通过以下步骤获取(建议只挂载工作路径,并避开系统路径,以降低安全风险), 生成的.whl文件路径为./dist/:
|
||||
某些特殊场景下,用户可能需要自行编译**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-6.0.rc1 --depth 1
|
||||
git clone https://gitee.com/ascend/pytorch.git -b v2.4.0-6.0.0 --depth 1
|
||||
```
|
||||
|
||||
2. **构建镜像**
|
||||
@@ -128,47 +130,80 @@ print(z)
|
||||
|
||||
## PyTorch与Python版本配套表
|
||||
|
||||
| PyTorch版本 | Python版本 |
|
||||
| ------------- | :----------------------------------------------------------- |
|
||||
| PyTorch版本 | Python版本 |
|
||||
|---------------|:-------------------------------------------------------------|
|
||||
| PyTorch1.11.0 | Python3.7.x(>=3.7.5), Python3.8.x, Python3.9.x, Python3.10.x |
|
||||
| PyTorch2.1.0 | Python3.8.x, Python3.9.x, Python3.10.x |
|
||||
| PyTorch2.1.0 | Python3.8.x, Python3.9.x, Python3.10.x, Python 3.11.x |
|
||||
| PyTorch2.2.0 | Python3.8.x, Python3.9.x, Python3.10.x |
|
||||
| PyTorch2.3.1 | Python3.8.x, Python3.9.x, Python3.10.x, Python 3.11.x |
|
||||
| PyTorch2.4.0 | Python3.8.x, Python3.9.x, Python3.10.x, Python 3.11.x |
|
||||
|
||||
## 昇腾辅助软件
|
||||
|
||||
**PyTorch Extension**版本号采用`{PyTorch版本}-{昇腾版本}`命名规则,前者为**PyTorch Extension**匹配的PyTorch版本,后者用于匹配CANN版本,详细匹配如下:
|
||||
|
||||
| CANN版本 | 支持的PyTorch版本 | 支持的Extension版本 | Gitee分支 | AscendHub镜像版本/名称([链接](https://ascendhub.huawei.com/#/detail/pytorch-modelzoo)) |
|
||||
|----------------|--------------|-------------------|-------------------|----------------------|
|
||||
| CANN 8.0.RC1 | 2.2.0 | 2.2.0 | v2.2.0-6.0.rc1 | - |
|
||||
| | 2.1.0 | 2.1.0.post3 | v2.1.0-6.0.rc1 | - |
|
||||
| | 1.11.0 | 1.11.0.post11 | v1.11.0-6.0.rc1 | - |
|
||||
| CANN 7.0.0 | 2.1.0 | 2.1.0 | v2.1.0-5.0.0 | - |
|
||||
| | 2.0.1 | 2.0.1.post1 | v2.0.1-5.0.0 | - |
|
||||
| | 1.11.0 | 1.11.0.post8 | v1.11.0-5.0.0 | - |
|
||||
| CANN 7.0.RC1 | 2.1.0 | 2.1.0.rc1 | v2.1.0-5.0.rc3 | - |
|
||||
| | 2.0.1 | 2.0.1 | v2.0.1-5.0.rc3 | - |
|
||||
| | 1.11.0 | 1.11.0.post4 | v1.11.0-5.0.rc3 | - |
|
||||
| CANN 6.3.RC3.1 | 1.11.0 | 1.11.0.post3 | v1.11.0-5.0.rc2.2 | - |
|
||||
| CANN 6.3.RC3 | 1.11.0 | 1.11.0.post2 | v1.11.0-5.0.rc2.1 | - |
|
||||
| CANN 6.3.RC2 | 2.0.1 | 2.0.1.rc1 | v2.0.1-5.0.rc2 | - |
|
||||
| | 1.11.0 | 1.11.0.post1 | v1.11.0-5.0.rc2 | 23.0.RC1-1.11.0 |
|
||||
| | 1.8.1 | 1.8.1.post2 | v1.8.1-5.0.rc2 | 23.0.RC1-1.8.1 |
|
||||
| CANN 6.3.RC1 | 1.11.0 | 1.11.0 | v1.11.0-5.0.rc1 | - |
|
||||
| | 1.8.1 | 1.8.1.post1 | v1.8.1-5.0.rc1 | - |
|
||||
| CANN 6.0.1 | 1.5.0 | 1.5.0.post8 | v1.5.0-3.0.0 | 22.0.0 |
|
||||
| | 1.8.1 | 1.8.1 | v1.8.1-3.0.0 | 22.0.0-1.8.1 |
|
||||
| | 1.11.0 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 | - |
|
||||
| CANN 6.0.RC1 | 1.5.0 | 1.5.0.post7 | v1.5.0-3.0.rc3 | 22.0.RC3 |
|
||||
| | 1.8.1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 | 22.0.RC3-1.8.1 |
|
||||
| | 1.11.0 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 | - |
|
||||
| CANN 5.1.RC2 | 1.5.0 | 1.5.0.post6 | v1.5.0-3.0.rc2 | 22.0.RC2 |
|
||||
| | 1.8.1 | 1.8.1.rc2 | v1.8.1-3.0.rc2 | 22.0.RC2-1.8.1 |
|
||||
| CANN 5.1.RC1 | 1.5.0 | 1.5.0.post5 | v1.5.0-3.0.rc1 | 22.0.RC1 |
|
||||
| | 1.8.1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 | - |
|
||||
| CANN 5.0.4 | 1.5.0 | 1.5.0.post4 | 2.0.4.tr5 | 21.0.4 |
|
||||
| CANN 5.0.3 | 1.8.1 | 1.5.0.post3 | 2.0.3.tr5 | 21.0.3 |
|
||||
| CANN 5.0.2 | 1.5.0 | 1.5.0.post2 | 2.0.2.tr5 | 21.0.2 |
|
||||
| CANN版本 | 支持的PyTorch版本 | 支持的Extension版本 | Gitee分支 |
|
||||
|-----------------------|--------------|------------------|-------------------|
|
||||
| CANN 8.0.0 | 2.4.0 | 2.4.0.post2 | v2.4.0-6.0.0 |
|
||||
| | 2.3.1 | 2.3.1.post4 | v2.3.1-6.0.0 |
|
||||
| | 2.1.0 | 2.1.0.post10 | v2.1.0-6.0.0 |
|
||||
| CANN 8.0.RC3 | 2.4.0 | 2.4.0 | v2.4.0-6.0.rc3 |
|
||||
| | 2.3.1 | 2.3.1.post2 | v2.3.1-6.0.rc3 |
|
||||
| | 2.1.0 | 2.1.0.post8 | v2.1.0-6.0.rc3 |
|
||||
| CANN 8.0.RC2 | 2.3.1 | 2.3.1 | v2.3.1-6.0.rc2 |
|
||||
| | 2.2.0 | 2.2.0.post2 | v2.2.0-6.0.rc2 |
|
||||
| | 2.1.0 | 2.1.0.post6 | v2.1.0-6.0.rc2 |
|
||||
| | 1.11.0 | 1.11.0.post14 | v1.11.0-6.0.rc2 |
|
||||
| CANN 8.0.RC2.alpha002 | 2.3.1 | 2.3.1rc1 | v2.3.1 |
|
||||
| CANN 8.0.RC1 | 2.2.0 | 2.2.0 | v2.2.0-6.0.rc1 |
|
||||
| | 2.1.0 | 2.1.0.post4 | v2.1.0-6.0.rc1 |
|
||||
| | 1.11.0 | 1.11.0.post11 | v1.11.0-6.0.rc1 |
|
||||
| CANN 7.0.0 | 2.1.0 | 2.1.0 | v2.1.0-5.0.0 |
|
||||
| | 2.0.1 | 2.0.1.post1 | v2.0.1-5.0.0 |
|
||||
| | 1.11.0 | 1.11.0.post8 | v1.11.0-5.0.0 |
|
||||
| CANN 7.0.RC1 | 2.1.0 | 2.1.0.rc1 | v2.1.0-5.0.rc3 |
|
||||
| | 2.0.1 | 2.0.1 | v2.0.1-5.0.rc3 |
|
||||
| | 1.11.0 | 1.11.0.post4 | v1.11.0-5.0.rc3 |
|
||||
| CANN 6.3.RC3.1 | 1.11.0 | 1.11.0.post3 | v1.11.0-5.0.rc2.2 |
|
||||
| CANN 6.3.RC3 | 1.11.0 | 1.11.0.post2 | v1.11.0-5.0.rc2.1 |
|
||||
| CANN 6.3.RC2 | 2.0.1 | 2.0.1.rc1 | v2.0.1-5.0.rc2 |
|
||||
| | 1.11.0 | 1.11.0.post1 | v1.11.0-5.0.rc2 |
|
||||
| | 1.8.1 | 1.8.1.post2 | v1.8.1-5.0.rc2 |
|
||||
| CANN 6.3.RC1 | 1.11.0 | 1.11.0 | v1.11.0-5.0.rc1 |
|
||||
| | 1.8.1 | 1.8.1.post1 | v1.8.1-5.0.rc1 |
|
||||
| CANN 6.0.1 | 1.5.0 | 1.5.0.post8 | v1.5.0-3.0.0 |
|
||||
| | 1.8.1 | 1.8.1 | v1.8.1-3.0.0 |
|
||||
| | 1.11.0 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 |
|
||||
| CANN 6.0.RC1 | 1.5.0 | 1.5.0.post7 | v1.5.0-3.0.rc3 |
|
||||
| | 1.8.1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 |
|
||||
| | 1.11.0 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 |
|
||||
| CANN 5.1.RC2 | 1.5.0 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
|
||||
| | 1.8.1 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
|
||||
| CANN 5.1.RC1 | 1.5.0 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
|
||||
| | 1.8.1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
|
||||
| CANN 5.0.4 | 1.5.0 | 1.5.0.post4 | 2.0.4.tr5 |
|
||||
| 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 |
|
||||
|
||||
## 硬件配套
|
||||
|
||||
昇腾训练设备包含以下型号,都可作为PyTorch模型的训练环境
|
||||
| 产品系列 | 产品型号 |
|
||||
|-----------------------|----------------------------------|
|
||||
| Atlas 训练系列产品 | Atlas 800 训练服务器(型号:9000) |
|
||||
| | Atlas 800 训练服务器(型号:9010) |
|
||||
| | Atlas 900 PoD(型号:9000) |
|
||||
| | Atlas 300T 训练卡(型号:9000) |
|
||||
| | Atlas 300T Pro 训练卡(型号:9000)|
|
||||
| Atlas A2 训练系列产品 | Atlas 800T A2 训练服务器 |
|
||||
| | Atlas 900 A2 PoD 集群基础单元 |
|
||||
| | Atlas 200T A2 Box16 异构子框 |
|
||||
| | Atlas 300T A2 训练卡 |
|
||||
|
||||
昇腾推理设备包含以下型号,都可作为大模型的推理环境
|
||||
| 产品系列 | 产品型号 |
|
||||
|-----------------------|----------------------------------|
|
||||
| Atlas 800I A2推理产品 | Atlas 800I A2 推理服务器 |
|
||||
|
||||
## 建议与交流
|
||||
|
||||
@@ -178,22 +213,24 @@ print(z)
|
||||
|
||||
AscendPyTorch版本分支的维护阶段如下:
|
||||
|
||||
|
||||
| **状态** | **时间** | **说明** |
|
||||
| ------------------- | -------- | ------------------------------------------------ |
|
||||
| 计划 | 1—3 个月 | 计划特性 |
|
||||
| 开发 | 3 个月 | 开发特性 |
|
||||
| 维护 | 6-12 个月| 合入所有已解决的问题并发布版本,针对不同的PyTorch版本采取不同的维护策略,常规版本和长期支持版本维护周期分别为6个月和12个月 |
|
||||
| 无维护 | 0—3 个月 | 合入所有已解决的问题,无专职维护人员,无版本发布 |
|
||||
| 开发 | 6—12 个月 | 开发新特性并修复问题,定期发布新版本。针对不同的PyTorch版本采取不同的策略,常规分支的开发周期分别为6个月,长期支持分支的开发周期为12个月 |
|
||||
| 维护 | 1年/3.5年 | 常规分支维护1年,长期支持分支维护3.5年。对重大BUG进行修复,不合入新特性,并视BUG的影响发布补丁版本 |
|
||||
| 生命周期终止(EOL) | N/A | 分支不再接受任何修改 |
|
||||
|
||||
## PyTorch版本维护策略
|
||||
|
||||
| **PyTorch版本** | **维护策略** | **当前状态** | **发布时间** | **后续状态** | **EOL日期** |
|
||||
|-----------|-----------|--------|------------|-----------------------|-----------|
|
||||
| 2.2.0 | 常规版本 | 维护 | 2024/04/01 | 预计2024/10/15起无维护 | |
|
||||
| 2.1.0 | 长期支持 | 维护 | 2023/10/15 | 预计2024/10/15起无维护 | |
|
||||
| 2.0.1 | 常规版本 | EOL | 2023/7/19 | | 2024/3/14 |
|
||||
| 1.11.0 | 长期支持 | 维护 | 2023/4/19 | 预计2024/4/19起无维护 | |
|
||||
| 2.4.0 | 常规分支 | 开发 | 2024/10/15 | 预计2025/03/15起进入维护状态 | - |
|
||||
| 2.3.1 | 常规分支 | 开发 | 2024/06/06 | 预计2024/12/06起进入维护状态 | |
|
||||
| 2.2.0 | 常规分支 | 维护 | 2024/04/01 | 预计2025/9/10起进入无维护状态 | |
|
||||
| 2.1.0 | 长期支持 | 开发 | 2023/10/15 | 预计2025/03/30起进入维护状态 | |
|
||||
| 2.0.1 | 常规分支 | EOL | 2023/7/19 | | 2024/3/14 |
|
||||
| 1.11.0 | 长期支持 | 维护 | 2023/4/19 | 预计2025/9/10起进入无维护状态 | |
|
||||
| 1.8.1 | 长期支持 | EOL | 2022/4/10 | | 2023/4/10 |
|
||||
| 1.5.0 | 长期支持 | EOL | 2021/7/29 | | 2022/7/29 |
|
||||
|
||||
@@ -203,14 +240,14 @@ AscendPyTorch版本分支的维护阶段如下:
|
||||
|
||||
## 参考文档
|
||||
|
||||
有关安装指南、模型迁移和训练/推理教程和API列表等更多详细信息,请参考[昇腾社区Ascend Extension for PyTorch](https://www.hiascend.com/software/ai-frameworks/commercial)。
|
||||
有关安装指南、模型迁移和训练/推理教程和API列表等更多详细信息,请参考[昇腾社区Ascend Extension for PyTorch](https://www.hiascend.com/software/ai-frameworks?framework=pytorch)。
|
||||
|
||||
| 文档名称 | 文档链接 |
|
||||
| -------------------------- | ------------------------------------------------------------ |
|
||||
| 安装指南 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/60RC1/quickstart/instg/instg_0163.html) |
|
||||
| 网络模型迁移和训练 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/60RC1/ptmoddevg/trainingmigrguide/PT_LMTMOG_0003.html) |
|
||||
| 算子适配 | [参考链接](https://www.hiascend.com/document/detail/zh/canncommercial/700/operatordev/tbeaicpudevg/atlasopdev_10_0086.html) |
|
||||
| API清单(PyTorch原生接口与自定义接口) | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/60RC1/apiref/apilist/ptaoplist_000002.html) |
|
||||
| 安装指南 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/60RC3/configandinstg/instg/insg_0001.html) |
|
||||
| 网络模型迁移和训练 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/60RC3/ptmoddevg/trainingmigrguide/PT_LMTMOG_0003.html) |
|
||||
| 算子适配 | [参考链接](https://www.hiascend.com/document/detail/zh/canncommercial/80RC3/developmentguide/opdevg/Ascendcopdevg/atlas_ascendc_10_0048.html) |
|
||||
| API清单(PyTorch原生接口与自定义接口) | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/60RC3/apiref/apilist/ptaoplist_000002.html) |
|
||||
|
||||
## 许可证
|
||||
|
||||
|
||||
+36
-30
@@ -2,7 +2,7 @@
|
||||
|
||||
## 漏洞风险提示
|
||||
|
||||
PyTorch 1.11.0存在CVE-2022-45907漏洞,该漏洞因torch.jit.annotations.parse_type_line方法中不安全使用eval方法,存在可以执行任意代码风险。torch_npu已参考[LINK](https://github.com/pytorch/pytorch/issues/88868)进行修复。
|
||||
PyTorch 2.6.0以下版本存在CVE-2025-32434漏洞,该漏洞因torch/serialization.py组件兼容性处理导致潜在的远程代码执行(RCE)风险。 torch_npu已参考[LINK](https://github.com/pytorch/pytorch/pull/145020)进行修复。
|
||||
|
||||
## 系统安全加固
|
||||
|
||||
@@ -50,13 +50,13 @@ PyTorch 1.11.0存在CVE-2022-45907漏洞,该漏洞因torch.jit.annotations.par
|
||||
|
||||
torch_npu内集成性能分析工具profiler:
|
||||
- 集成原因:对标pytorch原生支持能力,提供NPU PyTorch框架开发性能分析能力,加速性能分析调试过程。
|
||||
- 使用场景:默认不采集,如用户需要进行性能分析时,可在模型训练脚本中添加AscendPyTorch Profiler接口,执行训练的同时采集性能数据,完成训练后直接输出可视化的性能数据文件。
|
||||
- 风险提示:使用该功能会在本地生成性能数据,用户需加强对相关性能数据的保护,请在需要模型性能分析时使用,分析完成后及时关闭。Profiler工具具体细节请参考[《PyTorch 模型迁移和训练指南》](https://www.hiascend.com/document/detail/zh/canncommercial/700/modeldevpt/ptmigr/AImpug_0001.html)。
|
||||
- 使用场景:默认不采集,如用户需要进行性能分析时,可在模型训练脚本中添加Ascend Extension for PyTorch Profiler接口,执行训练的同时采集性能数据,完成训练后直接输出可视化的性能数据文件。
|
||||
- 风险提示:使用该功能会在本地生成性能数据,用户需加强对相关性能数据的保护,请在需要模型性能分析时使用,分析完成后及时关闭。Profiler工具具体细节请参考[《PyTorch 性能分析工具介绍》](https://www.hiascend.com/document/detail/zh/Pytorch/60RC2/ptmoddevg/trainingmigrguide/performance_tuning_0013.html)。
|
||||
|
||||
## 数据安全声明
|
||||
|
||||
1. PyTorch使用过程中需要加载和保存数据,部分接口使用风险模块pickle,可能存在数据风险,如torch.load、torch.distributed.scatter_object_list等接口,可参考[torch.load](https://pytorch.org/docs/stable/generated/torch.load.html#torch.load)、[collective-functions](https://pytorch.org/docs/stable/distributed.html#collective-functions)了解具体风险。
|
||||
2. AscendPyTorch依赖CANN的基础能力实现AOE性能调优、算子dump、日志记录等功能,用户需要关注上述功能生成文件的权限控制,加强对相关数据的保护。
|
||||
1. PyTorch使用过程中需要加载和保存数据,部分接口使用风险模块pickle,可能存在数据风险,如torch.load、torch.distributed.scatter_object_list等接口,可参考[torch.load](https://pytorch.org/docs/2.4/generated/torch.load.html#torch.load)、[collective-functions](https://pytorch.org/docs/2.4/distributed.html#collective-functions)了解具体风险。
|
||||
2. Ascend Extension for PyTorch依赖CANN的基础能力实现AOE性能调优、算子dump、日志记录等功能,用户需要关注上述功能生成文件的权限控制,加强对相关数据的保护。
|
||||
|
||||
## 构建安全声明
|
||||
|
||||
@@ -73,32 +73,38 @@ torch_npu支持源码编译安装,在编译时会下载依赖第三方库并
|
||||
|
||||
##### 公网地址
|
||||
|
||||
| 类型 | 开源代码地址 | 文件名 | 公网IP地址/公网URL地址/域名/邮箱地址 | 用途说明 |
|
||||
|------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------|--------------------------------------------------------------------------------|--------------------------------|
|
||||
| 自研 | 不涉及 | 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源 |
|
||||
| 自研 | 不涉及 | 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-x86.txt | https://download.pytorch.org/whl/test/cpu | 下载链接,用于下载torch-cpu版本 |
|
||||
| 自研 | 不涉及 | test\requirements-x86.txt | https://data.pyg.org/whl/torch-2.3.0+cpu.html | 下载链接,用于下载torch-scatter的cpu版本 |
|
||||
| 自研 | 不涉及 | test\requirements-x86.txt | https://download.pytorch.org/whl/test/cpu | 下载链接,用于下载torchvision的cpu版本 |
|
||||
| 类型 | 开源代码地址 | 文件名 | 公网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 | 依赖的开源代码仓 |
|
||||
| 自研 | 不涉及 | 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源 |
|
||||
| 自研 | 不涉及 | .github\workflows\\_build-and-test.yml | https://mirrors.huaweicloud.com/repository/pypi/simple | workflow配置文件,用于配置pip源 |
|
||||
| 自研 | 不涉及 | setup.cfg | https://gitee.com/ascend/pytorch | 用于打包whl的url入参 |
|
||||
| 自研 | 不涉及 | setup.cfg | https://gitee.com/ascend/pytorch/tags | 用于打包whl的download_url入参 |
|
||||
| 自研 | 不涉及 | third_party\op-plugin\ci\build.sh | https://gitee.com/ascend/pytorch.git | 编译脚本根据torch_npu仓库地址拉取代码进行编译 |
|
||||
| 自研 | 不涉及 | third_party\op-plugin\ci\exec_ut.sh | https://gitee.com/ascend/pytorch.git | UT脚本根据torch_npu仓库地址下拉取代码进行UT测试 |
|
||||
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.4.0/test/nn/test_convolution.py <br> https://github.com/pytorch/pytorch/blob/v2.4.0/test/test_mps.py <br> https://github.com/pytorch/pytorch/blob/v2.4.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.4.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.4.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.4.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.4.0/test/test_nn.py <br> https://github.com/pytorch/pytorch/blob/v2.4.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.4.0+cpu.html | 下载链接,用于下载torch-scatter的cpu版本 |
|
||||
| 自研 | 不涉及 | requirements.txt | https://download.pytorch.org/whl/cpu | 下载链接,用于下载torchvision的cpu版本 |
|
||||
| 自研 | 不涉及 | test\get_synchronized_files.sh | https://github.com/pytorch/pytorch.git | 下载链接,用于下载pytorch的测试用例 |
|
||||
|
||||
## 公开接口声明
|
||||
|
||||
AscendPyTorch是PyTorch适配插件,支持用户使用PyTorch在昇腾设备上进行训练和推理。AscendPyTorch适配后支持用户使用PyTorch原生接口。除了原生PyTorch接口外,AscendPyTorch提供了部分自定义接口,包括自定义算子、亲和库和其他接口,支持PyTorch接口和自定义接口连接,具体可参考[《PyTorch 模型迁移和训练指南》](https://www.hiascend.com/document/detail/zh/canncommercial/700/modeldevpt/ptmigr/AImpug_000002.html)>API列表。
|
||||
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)。
|
||||
|
||||
参考[PyTorch社区公开接口规范](https://github.com/pytorch/pytorch/wiki/Public-API-definition-and-documentation),AscendPyTorch提供了对外的自定义接口。如果一个函数看起来符合公开接口的标准且在文档中有展示,则该接口是公开接口。否则,使用该功能前可以在社区询问该功能是否确实是公开的或意外暴露的接口,因为这些未暴露接口将来可能会被修改或者删除。
|
||||
参考[PyTorch社区公开接口规范](https://github.com/pytorch/pytorch/wiki/Public-API-definition-and-documentation),Ascend Extension for PyTorch提供了对外的自定义接口。如果一个函数看起来符合公开接口的标准且在文档中有展示,则该接口是公开接口。否则,使用该功能前可以在社区询问该功能是否确实是公开的或意外暴露的接口,因为这些未暴露接口将来可能会被修改或者删除。
|
||||
|
||||
AscendPyTorch项目采用C++和Python联合开发,当前除Libtorch场景外正式接口只提供Python接口,在torch_npu的二进制包中动态库不直接提供服务,暴露的接口为内部使用,不建议用户使用。
|
||||
Ascend Extension for PyTorch项目采用C++和Python联合开发,当前除Libtorch场景外正式接口只提供Python接口,在torch_npu的二进制包中动态库不直接提供服务,暴露的接口为内部使用,不建议用户使用。
|
||||
|
||||
## 通信安全加固
|
||||
|
||||
@@ -205,16 +211,16 @@ PyTorch提供分布式训练能力,支持在单机和多机场景下进行训
|
||||
| --------------------- | ------------------------------------ | ------------------------------------ |
|
||||
| 源设备 | 运行torch_npu进程的服务器 | 运行torch_npu进程的服务器 |
|
||||
| 源IP | 设备地址IP | 设备地址IP |
|
||||
| 源端口 | 操作系统自动分配,分配范围由操作系统的自身配置决定 | 默认值为60000,取值范围[0,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
|
||||
| 源端口 | 操作系统自动分配,分配范围由操作系统的自身配置决定 | 默认值为60000,取值范围[1024,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
|
||||
| 目的设备 | 运行torch_npu进程的服务器 | 运行torch_npu进程的服务器 |
|
||||
| 目的IP | 设备地址IP | 设备地址IP |
|
||||
| 目的端口 (侦听) | 默认29500/29400,用户可以设定端口号 | 默认值为60000,取值范围[0,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
|
||||
| 目的端口 (侦听) | 默认29500/29400,用户可以设定端口号 | 默认值为60000,取值范围[1024,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
|
||||
| 协议 | TCP | TCP |
|
||||
| 端口说明 | 1. 在静态分布式场景中(用torchrun/torch.distributed.launch使用的backend为static), 目的端口(默认29500)用于接收和发送数据,源端口用于接收和发送数据 <br> 2. 在动态分布式场景中(用torchrun或者torch.distributed.launch使用的backend为c10d), 目的端口(默认29400)用于接收和发送数据,源端口用于接收和发送数据。可以使用rdzv_endpoint和master_port指定端口号 <br> 3. 在分布式场景中,用torchrun或者torch.distributed.launch不指定任何参数时使用的端口号为29500 | 默认值为60000,取值范围[0,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
|
||||
| 端口说明 | 分布式场景下 <br> 1. torchrun/torch.distributed.launch <br> (1) backend为static时(默认该backend),目的端口(默认29500)用于接收和发送数据,源端口用于接收和发送数据。使用master-addr指定地址,master-port指定端口 <br> (2) backend为c10d时,目的端口(默认29400)用于接收和发送数据,源端口用于接收和发送数据。使用rdzv_endpoint指定地址和端口号,格式为"地址:端口号" <br> 2. torch_npu_run:目的端口(默认29500)用于接收和发送数据,源端口用于接收和发送数据。使用master-addr指定地址,master-port指定端口 | 默认值为60000,取值范围[1024,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
|
||||
| 侦听端口是否可更改 | 是 | 是 |
|
||||
| 认证方式 | 无认证方式 | 无认证方式 |
|
||||
| 加密方式 | 无 | 无 |
|
||||
| 所属平面 | 不涉及 | 不涉及 |
|
||||
| 版本 | 所有版本 | 所有版本 |
|
||||
| 特殊场景 | 无 | 无 |
|
||||
| 备注 | 该通信过程由开源软件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/700/reference/envvar/envref_07_0001.html)的“执行相关 > 集合通信与分布式训练 > 集合通信相关配置>HCCL_IF_BASE_PORT”和[《集合通信接口参考》](https://www.hiascend.com/document/detail/zh/canncommercial/700/reference/hcclapiref/hcclapi_07_0001.html) |
|
||||
| 备注 | 该通信过程由开源软件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” |
|
||||
|
||||
@@ -31,9 +31,11 @@ class TestMgr:
|
||||
'op_ut_files': []
|
||||
}
|
||||
|
||||
def load(self, modify_files):
|
||||
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:
|
||||
continue
|
||||
line = line.strip()
|
||||
self.modify_files.append(line)
|
||||
|
||||
|
||||
@@ -131,7 +131,7 @@ if __name__ == "__main__":
|
||||
elif options.distributed:
|
||||
test_mgr.load_distributed_ut()
|
||||
elif os.path.exists(cur_modify_files):
|
||||
test_mgr.load(cur_modify_files)
|
||||
test_mgr.load(cur_modify_files, world_size=options.world_size)
|
||||
test_mgr.analyze()
|
||||
else:
|
||||
test_mgr.load_core_ut()
|
||||
|
||||
+27
-19
@@ -3,9 +3,8 @@
|
||||
set -e
|
||||
|
||||
CUR_DIR=$(dirname $(readlink -f $0))
|
||||
SUPPORTED_PY_VERSION=(3.8 3.9 3.10)
|
||||
SUPPORTED_PY_VERSION=(3.8 3.9 3.10 3.11)
|
||||
PY_VERSION='3.8' # Default supported python version is 3.8
|
||||
DEFAULT_SCRIPT_ARGS_NUM=1 # Default supported input parameters
|
||||
export DISABLE_RPC_FRAMEWORK=FALSE
|
||||
|
||||
# Parse arguments inside script
|
||||
@@ -16,23 +15,7 @@ function parse_script_args() {
|
||||
return 0
|
||||
fi
|
||||
|
||||
while true; do
|
||||
if [[ "x${1}" = "x" ]]; then
|
||||
break
|
||||
fi
|
||||
if [[ "$(echo "${1}"|cut -b1-|cut -b-2)" == "--" ]]; then
|
||||
args_num=$((args_num+1))
|
||||
fi
|
||||
if [[ ${args_num} -eq ${DEFAULT_SCRIPT_ARGS_NUM} ]]; then
|
||||
break
|
||||
fi
|
||||
shift
|
||||
done
|
||||
|
||||
# if num of args are not fully parsed, throw an error.
|
||||
if [[ ${args_num} -lt ${DEFAULT_SCRIPT_ARGS_NUM} ]]; then
|
||||
return 1
|
||||
fi
|
||||
args_num=$#
|
||||
|
||||
while true; do
|
||||
case "${1}" in
|
||||
@@ -43,10 +26,35 @@ function parse_script_args() {
|
||||
;;
|
||||
--disable_torchair)
|
||||
export DISABLE_INSTALL_TORCHAIR=TRUE
|
||||
args_num=$((args_num-1))
|
||||
shift
|
||||
;;
|
||||
--disable_rpc)
|
||||
export DISABLE_RPC_FRAMEWORK=TRUE
|
||||
args_num=$((args_num-1))
|
||||
shift
|
||||
;;
|
||||
--enable_lto)
|
||||
export ENABLE_LTO=TRUE
|
||||
args_num=$((args_num-1))
|
||||
shift
|
||||
;;
|
||||
--enable_pgo=*)
|
||||
pgo_mode=$(echo "${1}"|cut -d"=" -f2)
|
||||
case $pgo_mode in
|
||||
1)
|
||||
export PGO_MODE=1
|
||||
args_num=$((args_num-1))
|
||||
;;
|
||||
2)
|
||||
export PGO_MODE=2
|
||||
args_num=$((args_num-1))
|
||||
;;
|
||||
*)
|
||||
echo "ERROR Unsupported parameters: ${1}"
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
;;
|
||||
-*)
|
||||
|
||||
@@ -6,6 +6,7 @@ RUN cd /usr/local/bin \
|
||||
&& ln -s /opt/_internal/cpython-3.8.18/bin/pip3.8 pip3.8 \
|
||||
&& ln -s /opt/_internal/cpython-3.9.18/bin/pip3.9 pip3.9 \
|
||||
&& ln -s /opt/_internal/cpython-3.10.13/bin/pip3.10 pip3.10 \
|
||||
&& ln -s /opt/_internal/cpython-3.11.6/bin/pip3.1 pip3.11 \
|
||||
&& ln -s python3.8 python3
|
||||
|
||||
# Set pip source
|
||||
@@ -17,16 +18,19 @@ RUN mkdir /root/.pip \
|
||||
|
||||
# Install pip package(build)
|
||||
RUN pip3.8 install pyyaml \
|
||||
&& pip3.8 install torch==2.1.0 \
|
||||
&& pip3.8 install torch==2.4.0 \
|
||||
&& pip3.8 install numpy==1.21.3
|
||||
|
||||
RUN pip3.9 install pyyaml \
|
||||
&& pip3.9 install torch==2.1.0 \
|
||||
&& pip3.9 install torch==2.4.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.4.0 \
|
||||
&& pip3.10 install numpy==1.21.3
|
||||
|
||||
WORKDIR /home
|
||||
RUN pip3.11 install pyyaml \
|
||||
&& pip3.11 install torch==2.4.0 \
|
||||
&& pip3.11 install numpy==1.23.2
|
||||
|
||||
WORKDIR /home
|
||||
|
||||
@@ -6,10 +6,12 @@ RUN cd /usr/local/bin \
|
||||
&& ln -s /opt/_internal/cpython-3.8.1/bin/pip3.8 pip3.8 \
|
||||
&& ln -s /opt/_internal/cpython-3.9.0/bin/pip3.9 pip3.9 \
|
||||
&& ln -s /opt/_internal/cpython-3.10.1/bin/pip3.10 pip3.10 \
|
||||
&& ln -s /opt/_internal/cpython-3.11.0/bin/pip3.11 pip3.11 \
|
||||
&& ln -s /opt/_internal/cpython-3.7.5/bin/python3.7 python3.7 \
|
||||
&& ln -s /opt/_internal/cpython-3.8.1/bin/python3.8 python3.8 \
|
||||
&& ln -s /opt/_internal/cpython-3.9.0/bin/python3.9 python3.9 \
|
||||
&& ln -s /opt/_internal/cpython-3.10.1/bin/python3.10 python3.10 \
|
||||
&& ln -s /opt/_internal/cpython-3.11.0/bin/python3.11 python3.11 \
|
||||
&& ln -s python3.8 python3
|
||||
|
||||
# Set pip source
|
||||
@@ -21,17 +23,20 @@ RUN mkdir /root/.pip \
|
||||
|
||||
# Install pip package(build)
|
||||
RUN pip3.8 install pyyaml \
|
||||
&& pip3.8 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
|
||||
&& pip3.8 install torch==2.4.0+cpu --index-url https://download.pytorch.org/whl/cpu \
|
||||
&& pip3.8 install numpy==1.21.3
|
||||
|
||||
|
||||
RUN pip3.9 install pyyaml \
|
||||
&& pip3.9 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
|
||||
&& pip3.9 install torch==2.4.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.4.0+cpu --index-url https://download.pytorch.org/whl/cpu \
|
||||
&& pip3.10 install numpy==1.21.3
|
||||
|
||||
WORKDIR /home
|
||||
RUN pip3.11 install pyyaml \
|
||||
&& pip3.11 install torch==2.4.0+cpu --index-url https://download.pytorch.org/whl/cpu \
|
||||
&& pip3.11 install numpy==1.23.2
|
||||
|
||||
WORKDIR /home
|
||||
|
||||
@@ -16,11 +16,15 @@ from torchgen.packaged.autograd.gen_inplace_or_view_type import (
|
||||
)
|
||||
from torchgen.packaged.autograd.gen_trace_type import type_wrapper_name
|
||||
from torchgen.packaged.autograd.gen_variable_type import (
|
||||
emit_body, gen_wrapper_registration
|
||||
emit_body, gen_wrapper_registration, GRADIENT_IMPLEMENTED_FOR_COMPLEX
|
||||
)
|
||||
|
||||
from .utils import NPU_AUTOGRAD_FUNCTION
|
||||
|
||||
GRADIENT_IMPLEMENTED_FOR_COMPLEX.update((
|
||||
"stft",
|
||||
))
|
||||
|
||||
NPU_NATIVEFUNCTIONS = {'npu_format_cast', '_npu_format_cast'}
|
||||
|
||||
try_jit_decomposition_pattern = (r'if \(\(.*?\)\) \{.*?static c10::OperatorName full_name\("aten::.*?", .*?\);\n.*?'
|
||||
|
||||
@@ -75,6 +75,7 @@ def parse_custom_yaml(custom_path: str, tag_path: str) -> ParsedYaml:
|
||||
METHOD_DEFINITION = CodeTemplate("""\
|
||||
${return_type} ${name}(${args_str}) {
|
||||
${unpack_out}
|
||||
${unsafe_tensor_check}
|
||||
${device_guard}
|
||||
${type_definition_body}
|
||||
}
|
||||
@@ -123,7 +124,27 @@ def compute_op_definition(f: NativeFunction):
|
||||
f.func.arguments.out,
|
||||
f.func.arguments.flat_positional,
|
||||
)
|
||||
candidate_tensor_args = []
|
||||
for a in candidate_args:
|
||||
if a.type.is_tensor_like():
|
||||
candidate_tensor_args.append(f"{a.name}")
|
||||
|
||||
unsafe_tensor_check = """ // No check"""
|
||||
if len(candidate_tensor_args) > 0:
|
||||
unsafe_tensor_check = """
|
||||
if (c10_npu::get_npu_data_unsafe_flag()) {"""
|
||||
for tensor_arg in candidate_tensor_args:
|
||||
unsafe_tensor_check = unsafe_tensor_check + f"""
|
||||
c10_npu::check_npu_tensor_is_safe({tensor_arg});"""
|
||||
unsafe_tensor_check = unsafe_tensor_check + """
|
||||
}
|
||||
"""
|
||||
|
||||
candidate_args = itertools.chain(
|
||||
self_arg,
|
||||
f.func.arguments.out,
|
||||
f.func.arguments.flat_positional,
|
||||
)
|
||||
# Only tensor like arguments are eligible
|
||||
device_of = next(
|
||||
(
|
||||
@@ -133,7 +154,7 @@ def compute_op_definition(f: NativeFunction):
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
if has_tensor_options and device_of is not None:
|
||||
device_guard = f"""
|
||||
c10::OptionalDeviceGuard device_guard(device_of({device_of}));
|
||||
@@ -154,6 +175,7 @@ const c10::DeviceGuard device_guard(device_or_default(device));"""
|
||||
name=name,
|
||||
args_str=','.join(a.defn() for a in args[:-out_num]) + ', at::TensorList out' if out_num > 1 else args_str,
|
||||
unpack_out=unpack_out,
|
||||
unsafe_tensor_check=unsafe_tensor_check,
|
||||
device_guard=device_guard,
|
||||
type_definition_body=[TRACE_DISPATCH.substitute(impl_name=impl_name, args_exprs_str=args_exprs_str)]
|
||||
)]
|
||||
@@ -183,6 +205,9 @@ class RegisterCustomSchema:
|
||||
if tags == "{}":
|
||||
tag_index = ""
|
||||
|
||||
pattern = r'\bself\b(?=[,\)])'
|
||||
func_schema = re.sub(pattern, 'input', func_schema)
|
||||
|
||||
if f.has_composite_explicit_autograd_kernel:
|
||||
name = DispatcherSignature.from_schema(f.func, prefix=f'wrapper_{f.func.name.overload_name}_').name()
|
||||
return f'{maybe_tags}m.def({cpp_string(func_schema)}, TORCH_FN(at_npu::native::{name}){tag_index});\n'
|
||||
|
||||
@@ -391,6 +391,7 @@ def gen_dispatcher_registrations(
|
||||
backend_index = backend_indices[backend_dispatch_key]
|
||||
ns_helper = NamespaceHelper(namespace_str="at")
|
||||
native_func_header = """\
|
||||
#include "torch_npu/csrc/core/npu/NPURecovery.h"
|
||||
#ifndef BUILD_LIBTORCH
|
||||
#include "torch_npu/csrc/profiler/utils.h"
|
||||
#endif
|
||||
@@ -604,7 +605,7 @@ def gen_functionalization(fm: FileManager,
|
||||
"func_registrations",
|
||||
},
|
||||
)
|
||||
return
|
||||
return
|
||||
|
||||
|
||||
def gen_target_registration(
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/VariableType.h"
|
||||
#include "torch_npu/csrc/core/npu/NPUException.h"
|
||||
#include "torch_npu/csrc/core/npu/NPURecovery.h"
|
||||
#include "op_plugin/OpInterface.h"
|
||||
|
||||
namespace at_npu {
|
||||
|
||||
+33
-2
@@ -339,6 +339,7 @@ return {self_arg_name};
|
||||
torch_npu::profiler::NPURecordFunction guard;
|
||||
#endif
|
||||
"""
|
||||
unsafe_tensor_check = """ // No data check"""
|
||||
if self.backend_index.device_guard:
|
||||
has_tensor_options = any(
|
||||
isinstance(a, TensorOptionsArguments)
|
||||
@@ -358,6 +359,37 @@ torch_npu::profiler::NPURecordFunction guard;
|
||||
f.func.arguments.flat_positional,
|
||||
)
|
||||
|
||||
candidate_tensor_args = []
|
||||
for a in candidate_args:
|
||||
if a.type.is_tensor_like():
|
||||
candidate_tensor_args.append(f"{a.name}")
|
||||
|
||||
candidate_tensor_args = list(set(candidate_tensor_args))
|
||||
unsafe_tensor_check = """// No data check."""
|
||||
if len(candidate_tensor_args) > 0:
|
||||
unsafe_tensor_check = """
|
||||
if (c10_npu::get_npu_data_unsafe_flag()) {"""
|
||||
|
||||
if name in ["wrapper_NPU__copy_", "wrapper_NPU___foreach_copy_"]:
|
||||
tensor_arg = candidate_tensor_args[0] + ", " +\
|
||||
candidate_tensor_args[1]
|
||||
unsafe_tensor_check = unsafe_tensor_check + f"""
|
||||
c10_npu::check_and_update_npu_tensor_for_copy(self, src);"""
|
||||
else:
|
||||
for tensor_arg in candidate_tensor_args:
|
||||
unsafe_tensor_check = unsafe_tensor_check + f"""
|
||||
c10_npu::check_npu_tensor_is_safe({tensor_arg});"""
|
||||
|
||||
if len(candidate_tensor_args) > 0:
|
||||
unsafe_tensor_check = unsafe_tensor_check + """
|
||||
}
|
||||
"""
|
||||
candidate_args = itertools.chain(
|
||||
self_arg,
|
||||
f.func.arguments.out,
|
||||
f.func.arguments.flat_positional,
|
||||
)
|
||||
|
||||
# Only tensor like arguments are eligible
|
||||
device_of = next(
|
||||
(
|
||||
@@ -367,7 +399,6 @@ torch_npu::profiler::NPURecordFunction guard;
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
if has_tensor_options and device_of is not None:
|
||||
device_guard = f"""
|
||||
OptionalDeviceGuard device_guard(device_of({device_of}));
|
||||
@@ -414,7 +445,7 @@ namespace {{
|
||||
|
||||
{returns_type} {name}({args_str}) {{
|
||||
{device_check}
|
||||
|
||||
{unsafe_tensor_check}
|
||||
{device_guard}
|
||||
{record_func_def}
|
||||
{return_code}
|
||||
|
||||
@@ -1,302 +0,0 @@
|
||||
# 构建自定义算子wheel包工程
|
||||
|
||||
## 简介
|
||||
|
||||
本样例介绍自定义API样例打包工程,包括如何编写自定义API,绑定前反向自动求导,编译生成wheel包。具体代码样例详见[样例工程代码](https://gitee.com/ascend/samples/tree/master/operator/AddCustomSample/FrameworkLaunch/CppExtensions/setup),具体使用方法详见[使用说明](https://gitee.com/ascend/samples/tree/master/operator/AddCustomSample/FrameworkLaunch#%E4%BD%BF%E7%94%A8%E7%BC%96%E8%AF%91wheel%E5%8C%85%E7%9A%84%E6%96%B9%E5%BC%8F%E8%B0%83%E7%94%A8)。
|
||||
|
||||
> 注:使用该样例工程之前需要先编译并部署底层的自定义算子包,详见[编译部署自定义算子包](https://gitee.com/ascend/samples/tree/master/operator/AddCustomSample/FrameworkLaunch#%E7%BC%96%E8%AF%91%E7%AE%97%E5%AD%90%E5%B7%A5%E7%A8%8B%E9%83%A8%E7%BD%B2%E7%AE%97%E5%AD%90%E5%8C%85)。
|
||||
|
||||
## 代码介绍
|
||||
|
||||
### 目录结构
|
||||
|
||||
```
|
||||
setup
|
||||
├── csrc # 算子适配层及绑定代码
|
||||
│ ├── extension_add1.cpp # 自定义算子适配层
|
||||
│ ├── extension_add.cpp # 自定义算子适配层
|
||||
│ ├── function.h # 自定义算子函数声明
|
||||
│ ├── pytorch_npu_helper.hpp # 算子下发框架(无需关注)
|
||||
│ └── register.cpp # 自定义算子注册绑定等
|
||||
├── custom_ops # python打包目录
|
||||
│ ├── add_custom.py # 定义python侧接口
|
||||
│ └── __init__.py # 初始化代码
|
||||
├── graph # 图模式相关代码
|
||||
│ ├── CMakeLists.txt # 编译文件(无需关注)
|
||||
│ ├── codegen.cpp # 编译文件(无需关注)
|
||||
│ ├── custom_reg_op.h # 存放算子原型REG_OP
|
||||
│ └── operator_reg.h # 编译所需头文件(无需关注)
|
||||
├── setup.py # 编译打包文件
|
||||
└── test # 测试用例
|
||||
├── test_add_custom_graph.py # 图模式测试用例
|
||||
└── test_add_custom.py # 自定义算子测试用例
|
||||
|
||||
```
|
||||
|
||||
### 注册自定义算子
|
||||
|
||||
#### 注册自定义算子schema
|
||||
|
||||
首先通过TORCH_LIBRARY宏注册一个名为`myops`的命名空间,注意命名空间名字必须是唯一的。在`myops`命名空间里注册两个自定义schema,分别为前向和反向。如果需要注册多个schema,只需在同一个命名空间里继续添加即可。
|
||||
|
||||
```c++
|
||||
// register.cpp
|
||||
#include <torch/library.h>
|
||||
|
||||
TORCH_LIBRARY(myops, m) {
|
||||
m.def("my_op(Tensor self, Tensor other) -> Tensor");
|
||||
m.def("my_op_backward(Tensor self) -> (Tensor, Tensor)");
|
||||
}
|
||||
```
|
||||
|
||||
#### 适配层kernel编写
|
||||
|
||||
以add算子为例,编写自定义add的kernel,通过aclnn方式调用底层npu算子实现。
|
||||
|
||||
```c++
|
||||
// extension_add.cpp
|
||||
// 为NPU设备注册前向实现
|
||||
at::Tensor my_op_impl_npu(const at::Tensor& self, const at::Tensor& other) {
|
||||
// 创建输出内存
|
||||
at::Tensor result = at::Tensor(self);
|
||||
|
||||
// 调用底层aclnn接口计算
|
||||
EXEC_NPU_CMD(aclnnAddCustom, self, other, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
// 为NPU设备注册反向实现
|
||||
std::tuple<at::Tensor, at::Tensor> my_op_backward_impl_npu(const at::Tensor& self) {
|
||||
// 创建输出内存
|
||||
at::Tensor result = at::Tensor(self);
|
||||
|
||||
return {result, result};
|
||||
}
|
||||
```
|
||||
|
||||
#### 为NPU设备绑定前向和反向的对应实现
|
||||
|
||||
给新注册的schema添加了PrivateUse1设备的前反向对应实现,npu在Pytorch2.1及以上版本用的dispatch key是`PrivateUse1`,2.1以下是`XLA`。
|
||||
|
||||
```c++
|
||||
// extension_add.cpp
|
||||
TORCH_LIBRARY_IMPL(myops, PrivateUse1, m) {
|
||||
m.impl("my_op", &my_op_impl_npu);
|
||||
m.impl("my_op_backward", &my_op_backward_impl_npu);
|
||||
}
|
||||
```
|
||||
|
||||
#### 添加前反向绑定
|
||||
|
||||
调用my_op的时候通过注册的schema和对应的disptach key来找到对应的实现。
|
||||
|
||||
```c++
|
||||
// extension_add.cpp
|
||||
// 寻找注册在my_op上的不同设备的实现
|
||||
at::Tensor my_op_impl(const at::Tensor& self, const at::Tensor& other) {
|
||||
static auto op = torch::Dispatcher::singleton()
|
||||
.findSchemaOrThrow("myops::my_op", "")
|
||||
.typed<decltype(my_op_impl)>();
|
||||
return op.call(self, other);
|
||||
}
|
||||
// 寻找注册my_op_backward上的不同设备的实现
|
||||
std::tuple<at::Tensor, at::Tensor> my_op_backward_impl(const at::Tensor& self) {
|
||||
static auto op = torch::Dispatcher::singleton()
|
||||
.findSchemaOrThrow("myops::my_op_backward", "")
|
||||
.typed<decltype(my_op_backward_impl)>();
|
||||
return op.call(self);
|
||||
}
|
||||
```
|
||||
|
||||
Pytorch提供了`torch::autograd::Function`方法实现前反向绑定,在里面定义`forward`和`backward`函数,通过`apply`方法调用,同时把自动求导的方法实现注册到`AutogradPrivateUse1`,实现自动求导,如果pytorch版本是2.1以下,需要将`AutogradPrivateUse1`换成`AutogradXLA`。
|
||||
|
||||
```c++
|
||||
// extension_add.cpp
|
||||
class MyAddFunction : public torch::autograd::Function<MyAddFunction> {
|
||||
public:
|
||||
static at::Tensor forward(AutogradContext *ctx, at::Tensor self, at::Tensor other) {
|
||||
at::AutoDispatchBelowADInplaceOrView guard;
|
||||
return my_op_impl(self, other);
|
||||
}
|
||||
|
||||
static tensor_list backward(AutogradContext *ctx, tensor_list grad_outputs) {
|
||||
auto grad_output = grad_outputs[0];
|
||||
auto result = my_op_backward_impl(grad_output);
|
||||
return {std::get<0>(result), std::get<1>(result)};
|
||||
}
|
||||
};
|
||||
|
||||
at::Tensor my_op_impl_autograd(const at::Tensor& self, const at::Tensor& other) {
|
||||
return MyAddFunction::apply(self, other);
|
||||
}
|
||||
|
||||
TORCH_LIBRARY_IMPL(myops, PrivateUse1, m) {
|
||||
m.impl("my_op", &my_op_impl_npu);
|
||||
m.impl("my_op_backward", &my_op_backward_impl_npu);
|
||||
}
|
||||
|
||||
// 给自定义op绑定NPU的自动求导实现
|
||||
// 如果是pytorch 2.1以下的版本,AutogradPrivateUse1需要改成AutogradXLA
|
||||
TORCH_LIBRARY_IMPL(myops, AutogradPrivateUse1, m) {
|
||||
m.impl("my_op", &my_op_impl_autograd);
|
||||
}
|
||||
```
|
||||
|
||||
#### 通过pybind绑定C++和Python接口
|
||||
|
||||
通过pybind11提供的接口将C++侧接口和Python侧接口绑定,这样在python可以用`add_custom`调用。
|
||||
|
||||
```c++
|
||||
// register.cpp
|
||||
#include <torch/extension.h>
|
||||
#include "function.h"
|
||||
|
||||
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
||||
m.def("add_custom", &my_op_impl_autograd, "x + y");
|
||||
}
|
||||
```
|
||||
|
||||
`add_custom`:python侧调用的接口名,可以自定义名称。
|
||||
|
||||
`my_op_impl_autograd`:c++侧的函数名,需要是上面已经定义的函数。
|
||||
|
||||
`"x + y"`:接口描述,无实际用途,可选参数。
|
||||
|
||||
### 添加python侧调用接口
|
||||
|
||||
c++侧代码最终会编译生成so(具体编译步骤在下面章节[编译打包工程](#编译打包工程)会介绍),这里假设生成的so名称为`custom_ops_lib`,需要在python提供对外接口以供调用。在custom_ops目录下的add_custom.py里面新增python侧接口,并在__init__.py里面import该接口。
|
||||
|
||||
```python
|
||||
# add_custom.py
|
||||
import custom_ops_lib
|
||||
|
||||
def add_custom(self, other):
|
||||
return custom_ops_lib.add_custom(self, other)
|
||||
|
||||
# __init__.py
|
||||
import custom_ops_lib
|
||||
from .add_custom import add_custom
|
||||
```
|
||||
|
||||
### 图模式适配(可选)
|
||||
|
||||
此步骤可以让用户注册的自定义算子增加入图能力,实现图模式的功能,如不需要入图则可以跳过。
|
||||
|
||||
> 注:入图前需要完成前面步骤的自定义算子注册。
|
||||
|
||||
#### 添加meta设备的实现
|
||||
|
||||
meta tensor用于图模式中的infershape,是一种没有具体值的tensor,只有形状,数据类型,内存结构等信息。注册方法与npu设备一样,需要实现前反向,并且注册到`Meta`这个dispatch key上。
|
||||
|
||||
```c++
|
||||
// extension_add.cpp
|
||||
|
||||
// 为Meta设备注册前向实现
|
||||
at::Tensor my_op_impl_meta(const at::Tensor& self, const at::Tensor& other) {
|
||||
return empty_like(self);
|
||||
}
|
||||
|
||||
// 为Meta设备注册反向实现
|
||||
std::tuple<at::Tensor, at::Tensor> my_op_backward_impl_meta(const at::Tensor& self) {
|
||||
auto result = empty_like(self);
|
||||
return std::make_tuple(result, result);
|
||||
}
|
||||
|
||||
TORCH_LIBRARY_IMPL(myops, Meta, m) {
|
||||
m.impl("my_op", &my_op_impl_meta);
|
||||
m.impl("my_op_backward", &my_op_backward_impl_meta);
|
||||
}
|
||||
```
|
||||
|
||||
#### 编译生成GE构图API
|
||||
|
||||
通过自动生成脚本将算子原型REG_OP转换为GE构图API,并通过torchair仓提供的接口完成converter注册,从而使能自定义算子的入图能力。
|
||||
|
||||
> 注:此步骤为NPU设备上入图特有的操作。
|
||||
|
||||
将自定义算子的算子原型REG_OP添加到graph目录下的custom_reg_op.h文件中。算子原型来源于算子工程编译结果。
|
||||
|
||||
```c++
|
||||
// custom_reg_op.h
|
||||
#include "operator_reg.h"
|
||||
|
||||
namespace ge {
|
||||
REG_OP(AddCustom)
|
||||
.INPUT(x, ge::TensorType::ALL())
|
||||
.INPUT(y, ge::TensorType::ALL())
|
||||
.OUTPUT(z, ge::TensorType::ALL())
|
||||
.OP_END_FACTORY_REG(AddCustom);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
执行编译命令,会在graph目录下生成文件auto_generated_ge_raw_custom_ops.py,将其拷贝到自己的工程或者拷贝源码至自己的调用文件里,保证能够调用到即可。
|
||||
|
||||
```bash
|
||||
mkdir build
|
||||
cd build
|
||||
cmake ..
|
||||
make generate_ge_raw_custom_ops
|
||||
```
|
||||
|
||||
通过torchair提供的装饰器@register_fx_node_ge_converter完成自定义aten ir的converter注册。
|
||||
|
||||
```python
|
||||
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union, Callable
|
||||
import torchair
|
||||
from torchair.ge_concrete_graph.utils import dtype_promote
|
||||
from torchair.ge_concrete_graph.fx2ge_converter import register_fx_node_ge_converter
|
||||
from torchair.ge_concrete_graph.ge_graph import Tensor, TensorSpec
|
||||
from auto_generated_ge_raw_custom_ops import AddCustom
|
||||
|
||||
@register_fx_node_ge_converter(torch.ops.myops.my_op.default)
|
||||
def conveter_custom_op(
|
||||
input1: Tensor,
|
||||
input2: Tensor,
|
||||
out: Tensor = None,
|
||||
meta_outputs: Any = None):
|
||||
input1, input2 = dtype_promote(input1, input2, target_dtype=meta_outputs.dtype)
|
||||
return AddCustom(input1, input2)
|
||||
```
|
||||
|
||||
至此完成自定义算子入图适配工作,用户可以运行参考用例中的示例验证。
|
||||
|
||||
### 编译打包工程
|
||||
|
||||
完成自定义算子注册以后,需要通过setuptools工具来同时编译c++代码,并将生成的so和custom_ops目录下的python代码一起生成wheel包。setuptools工具通过执行setup.py来编译打包,里面会指定编译的一些参数。
|
||||
|
||||
```python
|
||||
# setup.py
|
||||
import torch
|
||||
from setuptools import setup, find_packages
|
||||
from torch.utils.cpp_extension import BuildExtension
|
||||
import torch_npu
|
||||
from torch_npu.utils.cpp_extension import NpuExtension
|
||||
|
||||
USE_NINJA = os.getenv('USE_NINJA') == '1'
|
||||
exts = []
|
||||
ext1 = NpuExtension(
|
||||
name="custom_ops_lib",
|
||||
# 如果还有其他cpp文件参与编译,需要在这里添加
|
||||
sources=["./csrc/extension_add.cpp", "./csrc/extension_add1.cpp", "./csrc/register.cpp"],
|
||||
extra_compile_args = [
|
||||
'-I' + os.path.join(PYTORCH_NPU_INSTALL_PATH, "include/third_party/acl/inc"),
|
||||
],
|
||||
)
|
||||
exts.append(ext1)
|
||||
|
||||
setup(
|
||||
name="custom_ops",
|
||||
version='1.0',
|
||||
keywords='custom_ops',
|
||||
ext_modules=exts,
|
||||
packages=find_packages(),
|
||||
cmdclass={"build_ext": BuildExtension.with_options(use_ninja=USE_NINJA)},
|
||||
)
|
||||
```
|
||||
|
||||
setup里面指定了wheel包的名称、版本号、需要编译的扩展、打包的文件、编译命令等,同时ext_modules里面指定了c++编译源文件、头文件路径、编译选项等参数。通过执行`python3 setup.py build bdist_wheel`命令会编译打包,在dist目录下会生成wheel包,通过pip install的方式可以安装该wheel包,具体使用方法参考测试用例。
|
||||
|
||||
### 测试用例
|
||||
|
||||
在test目录下提供了两个测试用例,test_add_custom.py是自定义API调用的测试用例,里面包含了whl包具体调用方法和API调用方法;test_add_custom_graph.py则是图模式的相关测试用例
|
||||
@@ -1,3 +1,6 @@
|
||||
--extra-index-url https://download.pytorch.org/whl/cpu
|
||||
|
||||
pyyaml
|
||||
setuptools
|
||||
auditwheel
|
||||
torch==2.4.0
|
||||
|
||||
@@ -41,6 +41,12 @@ if os.environ.get("DISABLE_INSTALL_TORCHAIR") is not None:
|
||||
DISABLE_RPC = "FALSE"
|
||||
if os.environ.get("DISABLE_RPC_FRAMEWORK") is not None:
|
||||
DISABLE_RPC = os.environ.get("DISABLE_RPC_FRAMEWORK")
|
||||
ENABLE_LTO = "FALSE"
|
||||
if os.environ.get("ENABLE_LTO") is not None:
|
||||
ENABLE_LTO = os.environ.get("ENABLE_LTO")
|
||||
PGO_MODE = 0
|
||||
if os.environ.get("PGO_MODE") is not None:
|
||||
PGO_MODE = int(os.environ.get("PGO_MODE"))
|
||||
|
||||
|
||||
def get_submodule_folders():
|
||||
@@ -337,6 +343,11 @@ class CPPLibBuild(build_clib, object):
|
||||
if DISABLE_RPC == 'FALSE':
|
||||
if check_tensorpipe_valid(BASE_DIR):
|
||||
cmake_args.append('-DBUILD_TENSORPIPE=on')
|
||||
|
||||
if ENABLE_LTO == "TRUE":
|
||||
cmake_args.append('-DENABLE_LTO=on')
|
||||
if PGO_MODE != 0:
|
||||
cmake_args.append('-DPGO_MODE=' + str(PGO_MODE))
|
||||
|
||||
build_args = ['-j', str(multiprocessing.cpu_count())]
|
||||
|
||||
@@ -469,7 +480,6 @@ class BdistWheelBuild(bdist_wheel):
|
||||
|
||||
dependencies = torch_dependencies + cann_dependencies + other_dependencies
|
||||
|
||||
self.run_command('egg_info')
|
||||
bdist_wheel.run(self)
|
||||
|
||||
if is_manylinux:
|
||||
@@ -572,8 +582,10 @@ classifiers = [
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
]
|
||||
|
||||
requirements = ['torch==2.4.0+cpu' if platform.machine() == 'x86_64' else 'torch==2.4.0']
|
||||
|
||||
setup(
|
||||
name=os.environ.get('TORCH_NPU_PACKAGE_NAME', 'torch_npu'),
|
||||
@@ -598,6 +610,7 @@ setup(
|
||||
define_macros=[('_GLIBCXX_USE_CXX11_ABI', '0'), ('GLIBCXX_USE_CXX11_ABI', '0')]
|
||||
),
|
||||
],
|
||||
install_requires=requirements,
|
||||
extras_require={
|
||||
},
|
||||
package_data={
|
||||
@@ -610,7 +623,11 @@ setup(
|
||||
'build_ext': Build,
|
||||
'build_py': PythonPackageBuild,
|
||||
'bdist_wheel': BdistWheelBuild,
|
||||
'egg_info': EggInfoBuild,
|
||||
'install': InstallCmd,
|
||||
'clean': Clean
|
||||
},
|
||||
entry_points={
|
||||
'console_scripts': [
|
||||
'torch_npu_run = torch_npu.distributed.run:_main',
|
||||
],
|
||||
})
|
||||
|
||||
+1
-7
@@ -2,13 +2,7 @@
|
||||
test目录为PTA相关的测试用例。
|
||||
## 安装依赖
|
||||
|
||||
如果是x86环境,请用requirements-x86.txt进行安装:
|
||||
|
||||
`pip3 install -r requirements-x86.txt`
|
||||
|
||||
如果是arm环境,请用requirements-arm.txt进行安装:
|
||||
|
||||
`pip3 install -r requirements-arm.txt`
|
||||
`pip3 install -r requirements.txt`
|
||||
|
||||
## 补全脚本
|
||||
该操作需要联网
|
||||
|
||||
+166
-232
@@ -46,6 +46,9 @@
|
||||
"scatter",
|
||||
"gather"
|
||||
],
|
||||
"torch.csrc.jit.tensorexpr.scripts.bisect": [
|
||||
"bisect"
|
||||
],
|
||||
"torch.cuda.nccl": [
|
||||
"init_rank",
|
||||
"is_available",
|
||||
@@ -89,6 +92,7 @@
|
||||
"ProcessGroupMPI",
|
||||
"ProcessGroupNCCL",
|
||||
"is_hccl_available",
|
||||
"reinit_process_group",
|
||||
"batch_isend_irecv",
|
||||
"gather",
|
||||
"gather_object"
|
||||
@@ -636,7 +640,8 @@
|
||||
"apply_permutation"
|
||||
],
|
||||
"torch.nn.parallel": [
|
||||
"DistributedDataParallelCPU"
|
||||
"DistributedDataParallelCPU",
|
||||
"data_parallel"
|
||||
],
|
||||
"torch.nn.parallel.comm": [
|
||||
"List"
|
||||
@@ -937,7 +942,9 @@
|
||||
"cast",
|
||||
"closing",
|
||||
"contextmanager",
|
||||
"get_source_lines_and_file"
|
||||
"get_source_lines_and_file",
|
||||
"get_default_mmap_options",
|
||||
"set_default_mmap_options"
|
||||
],
|
||||
"torch.sparse": [
|
||||
"BFloat16Tensor",
|
||||
@@ -1631,6 +1638,11 @@
|
||||
"cast",
|
||||
"dataclass"
|
||||
],
|
||||
"torch.distributed.distributed_c10d": [
|
||||
"gather",
|
||||
"gather_object",
|
||||
"batch_isend_irecv"
|
||||
],
|
||||
"torch.distributed.elastic.rendezvous.c10d_rendezvous_backend": [
|
||||
"Any",
|
||||
"FileStore",
|
||||
@@ -1752,7 +1764,12 @@
|
||||
"env",
|
||||
"get_logger",
|
||||
"macros",
|
||||
"record"
|
||||
"record",
|
||||
"DefaultLogsSpecs",
|
||||
"LogsSpecs",
|
||||
"Optional",
|
||||
"Set",
|
||||
"Type"
|
||||
],
|
||||
"torch.fx.annotate": [
|
||||
"Proxy",
|
||||
@@ -1970,7 +1987,8 @@
|
||||
"track_tensor",
|
||||
"track_tensor_tree",
|
||||
"wrap_key",
|
||||
"wrapper_and_args_for_make_fx"
|
||||
"wrapper_and_args_for_make_fx",
|
||||
"TorchFunctionMetadataMode"
|
||||
],
|
||||
"torch.fx.experimental.rewriter": [
|
||||
"Any",
|
||||
@@ -2029,6 +2047,7 @@
|
||||
"LoggingShapeGuardPrinter",
|
||||
"RelaxedUnspecConstraint",
|
||||
"RuntimeAssert",
|
||||
"SymExprPrinter",
|
||||
"ShapeGuardPrinter",
|
||||
"StrictMinMaxConstraint",
|
||||
"bind_symbols",
|
||||
@@ -2051,7 +2070,15 @@
|
||||
"parallel_and",
|
||||
"parallel_or",
|
||||
"safe_expand",
|
||||
"uninteresting_files"
|
||||
"uninteresting_files",
|
||||
"CallMethodKey",
|
||||
"DivideByKey",
|
||||
"InnerTensorKey",
|
||||
"PropagateUnbackedSymInts",
|
||||
"ShapeEnvSettings",
|
||||
"log_lru_cache_stats",
|
||||
"PendingUnbackedSymbolNotFound",
|
||||
"lru_cache"
|
||||
],
|
||||
"torch.fx.experimental.unification.match": [
|
||||
"first",
|
||||
@@ -2642,6 +2669,116 @@
|
||||
"torch.version": [
|
||||
"get_file_path"
|
||||
],
|
||||
"torch.ao.nn.intrinsic.modules": [
|
||||
"_FusedModule"
|
||||
],
|
||||
"torch.distributed.benchmarks.benchmark_ddp_rpc": [
|
||||
"BackendType",
|
||||
"DDP",
|
||||
"DistributedOptimizer",
|
||||
"RRef",
|
||||
"TensorPipeRpcBackendOptions"
|
||||
],
|
||||
"torch.distributed.pipelining": [
|
||||
"Pipe",
|
||||
"PipelineStage",
|
||||
"SplitPoint",
|
||||
"pipe_split",
|
||||
"pipeline"
|
||||
],
|
||||
"torch.distributed.pipelining.microbatch": [
|
||||
"Any",
|
||||
"Dict",
|
||||
"List",
|
||||
"Optional",
|
||||
"Tuple",
|
||||
"tree_flatten",
|
||||
"tree_unflatten"
|
||||
],
|
||||
"torch.export": [
|
||||
"Constraint",
|
||||
"ShapesCollection"
|
||||
],
|
||||
"torch.export.dynamic_shapes": [
|
||||
"Constraint",
|
||||
"ShapesCollection"
|
||||
],
|
||||
"torch.export.graph_signature": [
|
||||
"TokenArgument"
|
||||
],
|
||||
"torch.fx.experimental.shape_inference.infer_shape": [
|
||||
"DimDynamic",
|
||||
"FakeTensorMode",
|
||||
"LocalSource",
|
||||
"ShapeEnv",
|
||||
"defaultdict",
|
||||
"infer_symbol_values",
|
||||
"make_fx"
|
||||
],
|
||||
"torch.fx.experimental.shape_inference.infer_symbol_values": [
|
||||
"Any",
|
||||
"DefaultDict",
|
||||
"Dict",
|
||||
"List",
|
||||
"Tuple",
|
||||
"Union"
|
||||
],
|
||||
"torch.fx.passes.runtime_assert": [
|
||||
"Any",
|
||||
"Dict",
|
||||
"GraphModule",
|
||||
"Optional",
|
||||
"Set",
|
||||
"ShapeEnv",
|
||||
"SymNode",
|
||||
"compatibility",
|
||||
"lazy_format_graph_code"
|
||||
],
|
||||
"torch.library": [
|
||||
"opcheck",
|
||||
"register_autograd",
|
||||
"register_kernel"
|
||||
],
|
||||
"torch.mtia": [
|
||||
"DeferredMtiaCallError",
|
||||
"StreamContext"
|
||||
],
|
||||
"torch.onnx.symbolic_helper": [
|
||||
"Any",
|
||||
"Callable",
|
||||
"List",
|
||||
"Literal",
|
||||
"NoReturn",
|
||||
"Number",
|
||||
"Optional",
|
||||
"Sequence",
|
||||
"Set",
|
||||
"Tuple",
|
||||
"Union"
|
||||
],
|
||||
"torch.onnx.symbolic_opset18": [
|
||||
"amax",
|
||||
"amin",
|
||||
"aminmax",
|
||||
"embedding_bag",
|
||||
"linalg_vector_norm",
|
||||
"max",
|
||||
"maximum",
|
||||
"min",
|
||||
"minimum"
|
||||
],
|
||||
"torch.onnx.symbolic_opset20": [
|
||||
"_affine_grid_generator",
|
||||
"_grid_sampler",
|
||||
"convert_grid_sample_mode"
|
||||
],
|
||||
"torch.utils.data.datapipes.dataframe.dataframe_wrapper": [
|
||||
"Any",
|
||||
"Optional"
|
||||
],
|
||||
"torch.utils.hipify.hipify_python": [
|
||||
"TrieNode"
|
||||
],
|
||||
"torch_npu": [
|
||||
"_npu_dropout",
|
||||
"copy_memory_",
|
||||
@@ -2657,7 +2794,26 @@
|
||||
"npu_random_choice_with_mask",
|
||||
"npu_rms_norm",
|
||||
"npu_fused_infer_attention_score",
|
||||
"npu_convert_weight_to_int4pack"
|
||||
"npu_convert_weight_to_int4pack",
|
||||
"npu_ffn",
|
||||
"npu_geglu",
|
||||
"npu_grouped_matmul",
|
||||
"npu_quant_matmul",
|
||||
"npu_quant_scatter",
|
||||
"npu_scatter_nd_update_",
|
||||
"npu_swiglu",
|
||||
"npu_group_quant",
|
||||
"npu_dynamic_quant",
|
||||
"npu_dynamic_quant_asymmetric",
|
||||
"npu_yolo_boxes_encode",
|
||||
"npu_yolo_boxes_encode",
|
||||
"npu_weight_quant_batchmatmul",
|
||||
"npu_transpose",
|
||||
"npu_trans_quant_param",
|
||||
"npu_stride_add",
|
||||
"npu_sort_v2",
|
||||
"npu_gelu",
|
||||
"npu_gelu_backward"
|
||||
],
|
||||
"torch_npu.contrib": [
|
||||
"npu_fused_attention_with_layernorm",
|
||||
@@ -2681,7 +2837,6 @@
|
||||
"_compute_bucket_assignment_by_size",
|
||||
"_register_builtin_comm_hook",
|
||||
"_register_comm_hook",
|
||||
"_verify_params_across_processes",
|
||||
"is_available"
|
||||
],
|
||||
"torch_npu.npu": [
|
||||
@@ -2694,241 +2849,20 @@
|
||||
"IntTensor",
|
||||
"LongTensor",
|
||||
"ShortTensor",
|
||||
"BFloat16Tensor"
|
||||
"BFloat16Tensor",
|
||||
"restart_device",
|
||||
"stop_device"
|
||||
],
|
||||
"torch_npu.profiler": [
|
||||
"ProfilerActivity",
|
||||
"_ExperimentalConfig"
|
||||
],
|
||||
"torch_npu.profiler.analysis.npu_profiler": [
|
||||
"NpuProfiler",
|
||||
"ProfContext",
|
||||
"ProfProcessPool"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.event_bean": [
|
||||
"EventBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.ge_memory_record_bean": [
|
||||
"GeMemoryRecordBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.ge_op_memory_bean": [
|
||||
"GeOpMemoryBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.memory_use_bean": [
|
||||
"MemoryEnum",
|
||||
"MemoryUseBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.npu_mem_bean": [
|
||||
"NpuMemoryBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.npu_module_mem_bean": [
|
||||
"NpuModuleMemoryBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.op_mark_bean": [
|
||||
"OpMarkBean",
|
||||
"OpMarkEnum"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.op_summary_bean": [
|
||||
"OpSummaryBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.python_func_call_bean": [
|
||||
"PythonFuncCallBean",
|
||||
"PythonFuncCallEnum"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.python_module_call_bean": [
|
||||
"PythonModuleCallBean",
|
||||
"PythonModuleCallEnum"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.torch_op_bean": [
|
||||
"TorchOpBean",
|
||||
"TorchOpEnum"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.torch_op_node": [
|
||||
"TorchOpNode"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.constant": [
|
||||
"Constant",
|
||||
"convert_ns2us_float",
|
||||
"convert_ns2us_str",
|
||||
"convert_us2ns",
|
||||
"print_error_msg",
|
||||
"print_info_msg",
|
||||
"print_warn_msg",
|
||||
"DbConstant",
|
||||
"TableColumnsManager",
|
||||
"contact_2num"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.file_manager": [
|
||||
"FileManager"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.file_tag": [
|
||||
"FileTag"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.path_manager": [
|
||||
"ProfilerPathManager"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.task_manager": [
|
||||
"ConcurrentMode",
|
||||
"ConcurrentTask",
|
||||
"ConcurrentTasksManager",
|
||||
"TaskInfo",
|
||||
"TaskMsgType",
|
||||
"TaskStatus",
|
||||
"send_print_req_to_manager",
|
||||
"send_result_to_manager"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.tlv_decoder": [
|
||||
"TLVDecoder"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.trace_event_manager": [
|
||||
"TraceEventManager"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.tree_builder": [
|
||||
"TreeBuilder"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_config.fwk_file_parser_config": [
|
||||
"FwkFileParserConfig"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_config.parser_config": [
|
||||
"ParserConfig"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_config.parser_deps_config": [
|
||||
"ConcurrentMode",
|
||||
"Constant",
|
||||
"ParserDepsConfig"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_parse.cann_file_parser": [
|
||||
"CANNDataEnum",
|
||||
"CANNFileParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_parse.fwk_cann_relation_parser": [
|
||||
"FwkCANNRelationParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_parse.fwk_file_parser": [
|
||||
"FwkFileParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_parse.python_trace_parser": [
|
||||
"CallType",
|
||||
"PyTraceEvent",
|
||||
"PythonTraceParser",
|
||||
"ReplayFrame",
|
||||
"TraceTag"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.base_parser": [
|
||||
"BaseParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.cann_parse.cann_analyze": [
|
||||
"CANNAnalyzeParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.cann_parse.cann_export": [
|
||||
"CANNExportParser",
|
||||
"CANNTimelineParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.communication_parser": [
|
||||
"CommunicationParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.integrate_parser": [
|
||||
"IntegrateParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.kernel_view_parser": [
|
||||
"KernelViewParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.memory_prepare_parser": [
|
||||
"MemoryPrepareParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.memory_view_parser": [
|
||||
"MemoryViewParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.operator_view_parser": [
|
||||
"OperatorViewParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.prepare_parse.fwk_pre_parser": [
|
||||
"TracePreParser",
|
||||
"TreeBuildParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.prepare_parse.relation_parser": [
|
||||
"RelationParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.stack_view_parser": [
|
||||
"StackViewParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.trace_step_time_parser": [
|
||||
"TraceStepTimeParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.trace_view_parser": [
|
||||
"TraceViewParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.profiling_parser": [
|
||||
"ProfilingParser"
|
||||
],
|
||||
"torch_npu.profiler.profiler": [
|
||||
"ProfActionController",
|
||||
"ProfInterface"
|
||||
],
|
||||
"torch_npu.profiler.profiler_action_controller": [
|
||||
"ProfActionController"
|
||||
],
|
||||
"torch_npu.profiler.profiler_interface": [
|
||||
"ProfInterface"
|
||||
],
|
||||
"torch_npu.profiler.scheduler": [
|
||||
"default_schedule_fn"
|
||||
"_KinetoProfile"
|
||||
],
|
||||
"torch_npu.profiler.experimental_config": [
|
||||
"_ExperimentalConfig"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.ai_cpu_bean": [
|
||||
"AiCpuBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.common_bean": [
|
||||
"CommonBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.l2_cache_bean": [
|
||||
"L2CacheBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.api_statistic_bean": [
|
||||
"ApiStatisticBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_bean.op_statistic_bean": [
|
||||
"OpStatisticBean"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.cann_package_manager": [
|
||||
"CannPackageManager"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.db_manager": [
|
||||
"DbManager",
|
||||
"EmptyClass"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_common_func.time_range_calculator": [
|
||||
"CommunicationTimeRange",
|
||||
"RangeCaculator",
|
||||
"TimeRange"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.prof_db_parse.communication_db_parser": [
|
||||
"CommBandwidthTableRow",
|
||||
"CommMatarixTableRow",
|
||||
"CommTimeTableRow",
|
||||
"CommunicationDbParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.prof_db_parse.db_parser" : [
|
||||
"DbParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.prof_db_parse.fwk_api_db_parser": [
|
||||
"FwkApiDbParser",
|
||||
"FwkApiInfoTableRow",
|
||||
"FwkApiTableRow"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.prof_db_parse.memory_db_parser": [
|
||||
"MemoryDbParser",
|
||||
"MemoryRecordTableRow",
|
||||
"OpMemoryTableRow"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.prof_db_parse.step_info_db_parser": [
|
||||
"StepInfoDbParser"
|
||||
],
|
||||
"torch_npu.profiler.analysis.prof_view.prof_db_parse.trace_step_time_db_parser": [
|
||||
"TraceStepTimeDbParser"
|
||||
],
|
||||
"torch_npu.dynamo.torchair": [
|
||||
"CompilerConfig",
|
||||
"dynamo_export",
|
||||
|
||||
@@ -19,7 +19,7 @@ class TestFuseAddSoftmaxDropout(TestCase):
|
||||
|
||||
def test_fuse_add_softmax_dropout(self):
|
||||
training = True
|
||||
dropout = nn.DropoutWithByteMask(0)
|
||||
dropout = torch_npu.contrib.module.DropoutWithByteMask(0)
|
||||
npu_input1 = torch.rand(96, 12, 384, 384).npu().half()
|
||||
npu_input2 = torch.rand(96, 12, 384, 384).npu().half()
|
||||
alpha = 64
|
||||
|
||||
@@ -18,7 +18,7 @@ class TestLinearA8W8Quant(TestCase):
|
||||
return output
|
||||
|
||||
@unittest.skipIf(DEVICE_NAME == 'Ascend910A' or DEVICE_NAME == 'Ascend310P',
|
||||
"OP `QuantBatchMatmulV3` is not only supported on 910A and 310P, skip this ut for this device type!")
|
||||
"OP `QuantBatchMatmulV3` is not supported on 910A or 310P, skip this ut for this device type!")
|
||||
def test_npu_linear_quant(self):
|
||||
x1 = torch.randint(-1, 1, (1, 5), dtype=torch.int8).npu()
|
||||
x2 = torch.randint(-1, 1, (127, 5), dtype=torch.int8).npu()
|
||||
@@ -29,5 +29,21 @@ class TestLinearA8W8Quant(TestCase):
|
||||
npu_out = self.npu_linear_quant(in_features, out_features, x1, x2, scale)
|
||||
self.assertRtolEqual(supported_output, npu_out, 0.001)
|
||||
|
||||
@unittest.skipIf(DEVICE_NAME == 'Ascend910A' or DEVICE_NAME == 'Ascend310P',
|
||||
"OP `QuantBatchMatmulV3` is not supported on 910A or 310P, skip this ut for this device type!")
|
||||
def test_npu_linear_quant_out_bf16(self):
|
||||
x1 = torch.randint(-1, 1, (1, 5), dtype=torch.int8).npu()
|
||||
x2 = torch.randint(-1, 1, (127, 5), dtype=torch.int8).npu()
|
||||
scale = torch.randn(1, dtype=torch.float32).npu()
|
||||
out_dtype = torch.bfloat16
|
||||
supported_output = torch_npu.npu_quant_matmul(x1, x2.t(), scale, output_dtype=out_dtype)
|
||||
in_features = 5
|
||||
out_features = 127
|
||||
model = LinearA8W8Quant(in_features, out_features, bias=False, offset=False, pertoken_scale=False, output_dtype=out_dtype)
|
||||
model.weight.data = x2
|
||||
model.scale.data = scale
|
||||
npu_out = model(x1)
|
||||
self.assertRtolEqual(supported_output, npu_out, 0.001)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,49 @@
|
||||
import unittest
|
||||
import torch
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.contrib.module import LinearQuant
|
||||
|
||||
DEVICE_NAME = torch_npu.npu.get_device_name(0)[:10]
|
||||
|
||||
|
||||
class TestLinearQuant(TestCase):
|
||||
|
||||
def npu_linear_quant(self, in_features, out_features, x1, x2, scale):
|
||||
model = LinearQuant(in_features, out_features, bias=False, pertoken_scale=False, offset=False)
|
||||
model = model.npu()
|
||||
model.weight.data = x2
|
||||
model.scale.data = scale
|
||||
output = model(x1)
|
||||
return output
|
||||
|
||||
@unittest.skipIf(DEVICE_NAME == 'Ascend910A' or DEVICE_NAME == 'Ascend310P',
|
||||
"OP `QuantBatchMatmulV3` is not supported on 910A or 310P, skip this ut for this device type!")
|
||||
def test_npu_linear_quant(self):
|
||||
x1 = torch.randint(-1, 1, (1, 2), dtype=torch.int32).npu()
|
||||
x2 = torch.randint(-1, 1, (128, 2), dtype=torch.int32).npu()
|
||||
scale = torch.randn(1, dtype=torch.float32).npu()
|
||||
supported_output = torch_npu.npu_quant_matmul(x1, x2.t(), scale)
|
||||
in_features = 2
|
||||
out_features = 128
|
||||
npu_out = self.npu_linear_quant(in_features, out_features, x1, x2, scale)
|
||||
self.assertRtolEqual(supported_output, npu_out, 0.001)
|
||||
|
||||
@unittest.skipIf(DEVICE_NAME == 'Ascend910A' or DEVICE_NAME == 'Ascend310P',
|
||||
"OP `QuantBatchMatmulV3` is not supported on 910A or 310P, skip this ut for this device type!")
|
||||
def test_npu_linear_quant_out_bf16(self):
|
||||
x1 = torch.randint(-1, 1, (1, 5), dtype=torch.int8).npu()
|
||||
x2 = torch.randint(-1, 1, (128, 5), dtype=torch.int8).npu()
|
||||
scale = torch.randn(1, dtype=torch.float32).npu()
|
||||
out_dtype = torch.bfloat16
|
||||
supported_output = torch_npu.npu_quant_matmul(x1, x2.t(), scale, output_dtype=out_dtype)
|
||||
in_features = 5
|
||||
out_features = 128
|
||||
model = LinearQuant(in_features, out_features, bias=False, offset=False, pertoken_scale=False, output_dtype=out_dtype)
|
||||
model.weight.data = x2
|
||||
model.scale.data = scale
|
||||
npu_out = model(x1)
|
||||
self.assertRtolEqual(supported_output, npu_out, 0.001)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -3,14 +3,14 @@ import numpy as np
|
||||
import torch
|
||||
import torch_npu
|
||||
from torch_npu.contrib.module import MultiheadAttention
|
||||
from torch_npu.contrib.module.multihead_attention import MHAConfig
|
||||
from torch_npu.contrib.module.multihead_attention import _MHAConfig
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.testing.common_utils import create_common_tensor
|
||||
|
||||
FORMAT_ND = 2
|
||||
FORMAT_NZ = 29
|
||||
npu_device = "npu:0"
|
||||
MHAConfig.set_fussion()
|
||||
_MHAConfig.set_fussion()
|
||||
|
||||
|
||||
class TestMultiheadAttention(unittest.TestCase):
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import torch
|
||||
from torch.nn.parameter import UninitializedTensorMixin
|
||||
from torch.utils.data import TensorDataset
|
||||
import torch_npu
|
||||
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
@@ -63,7 +65,33 @@ class TestTransferToNpu(TestCase):
|
||||
device = out.weight.device
|
||||
self.assertEqual(device.type, 'meta')
|
||||
|
||||
def test_set_default_device(self):
|
||||
torch.set_default_device("cuda")
|
||||
a = torch.tensor(1)
|
||||
self.assertEqual(a.device.type, 'npu')
|
||||
|
||||
def test_device_context(self):
|
||||
device = torch.device('cuda')
|
||||
with device:
|
||||
a = torch.tensor(1)
|
||||
self.assertEqual(a.device.type, 'npu')
|
||||
|
||||
def test_data_loader_pin_memory(self):
|
||||
images = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)
|
||||
labels = torch.arange(10 * 5, dtype=torch.float32).view(10, 5)
|
||||
dataset = TensorDataset(images, labels)
|
||||
data_loader = torch.utils.data.DataLoader(
|
||||
dataset, num_workers=2, pin_memory=True)
|
||||
|
||||
data_iter = iter(data_loader)
|
||||
images0, _ = next(data_iter)
|
||||
self.assertTrue(images0.is_pinned())
|
||||
|
||||
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变成普通函数,而不是原来的绑定方法
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -83,10 +83,7 @@ Tensor blocking_ops(Tensor x)
|
||||
std::this_thread::sleep_for(std::chrono::seconds(180));
|
||||
return 0;
|
||||
};
|
||||
at_npu::native::OpCommand cmd;
|
||||
cmd.Name("blocking_ops");
|
||||
cmd.SetCustomHandler(blocking_call);
|
||||
cmd.Run();
|
||||
at_npu::native::OpCommand::RunOpApi("blocking_ops", blocking_call);
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,13 @@ class TestFastGelu(TestCase):
|
||||
custom_output = self.custom_op_exec(npu_input)
|
||||
self.assertRtolEqual(supported_output, custom_output)
|
||||
|
||||
def test_fast_gelu_input_arg(self):
|
||||
item = [np.float32, 0, [3, 16, 32]]
|
||||
_, npu_input = create_common_tensor(item, 0, 100)
|
||||
supported_output = self.supported_op_exec(npu_input)
|
||||
custom_output = torch_npu.fast_gelu(input=npu_input)
|
||||
self.assertRtolEqual(supported_output, custom_output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -35,6 +35,10 @@ class TestAntiQuant(TestCase):
|
||||
[[np.int8, -1, [10, 100]], [np.float32, -1, [100]], [np.float32, -1, [100]], torch.bfloat16, None],
|
||||
[[np.int8, -1, [10, 100]], [np.float32, -1, [100]], [np.float32, -1, [100]], torch.float16, torch.int8],
|
||||
[[np.int8, -1, [10, 100]], [np.float32, -1, [100]], [np.float32, -1, [100]], torch.bfloat16, torch.int8],
|
||||
[[np.int32, -1, [10, 25]], [np.float32, -1, [200]], [np.float32, -1, [200]], torch.float16, None],
|
||||
[[np.int32, -1, [10, 25]], [np.float32, -1, [200]], [np.float32, -1, [200]], torch.bfloat16, None],
|
||||
[[np.int32, -1, [10, 25]], [np.float32, -1, [200]], [np.float32, -1, [200]], torch.float16, torch.quint4x2],
|
||||
[[np.int32, -1, [10, 25]], [np.float32, -1, [200]], [np.float32, -1, [200]], torch.bfloat16, torch.quint4x2],
|
||||
]
|
||||
|
||||
for item in shape_format:
|
||||
|
||||
@@ -13,7 +13,7 @@ class TestFusedAttentionScoreFwd(TestCase):
|
||||
attn_scores = mask + attention_scores * scale
|
||||
attn_probss = torch.nn.functional.softmax(attn_scores, dim=-1)
|
||||
drop_p = 1 - keep_prob
|
||||
drop = torch.nn.DropoutWithByteMask(p=drop_p).npu()
|
||||
drop = torch_npu.contrib.module.DropoutWithByteMask(p=drop_p).npu()
|
||||
attn_probs = drop(attn_probss)
|
||||
context_layer = torch.matmul(attn_probs, v)
|
||||
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import os
|
||||
import warnings
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch_npu
|
||||
|
||||
warnings.filterwarnings('always')
|
||||
|
||||
|
||||
def error_param():
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29500"
|
||||
os.environ["HCCL_WHITELIST_DISABLE"] = "1"
|
||||
backend = "hccl"
|
||||
dist.init_process_group(backend)
|
||||
new_pg = dist.new_group([0])
|
||||
rank = dist.get_rank()
|
||||
torch.npu.set_device(rank)
|
||||
input_ = torch.tensor(2).npu()
|
||||
|
||||
dist.broadcast(input_, src=0, group=new_pg)
|
||||
|
||||
|
||||
error_param()
|
||||
@@ -0,0 +1,19 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch_npu
|
||||
|
||||
|
||||
def cpu_tensor():
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29500"
|
||||
os.environ["HCCL_WHITELIST_DISABLE"] = "1"
|
||||
backend = "hccl"
|
||||
dist.init_process_group(backend)
|
||||
rank = dist.get_rank()
|
||||
torch.npu.set_device(rank)
|
||||
input_ = torch.rand(2, 3)
|
||||
dist.all_reduce(input_)
|
||||
|
||||
|
||||
cpu_tensor()
|
||||
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch_npu
|
||||
|
||||
|
||||
def diff_dtype():
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29500"
|
||||
os.environ["HCCL_WHITELIST_DISABLE"] = "1"
|
||||
backend = "hccl"
|
||||
dist.init_process_group(backend)
|
||||
rank = dist.get_rank()
|
||||
torch.npu.set_device(rank)
|
||||
output = torch.rand(2, 3).npu()
|
||||
input_list = [torch.tensor(var).npu() for var in range(2)]
|
||||
dist.reduce_scatter(output, input_list)
|
||||
|
||||
|
||||
diff_dtype()
|
||||
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch_npu
|
||||
|
||||
|
||||
def diff_type():
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29500"
|
||||
os.environ["HCCL_WHITELIST_DISABLE"] = "1"
|
||||
backend = "hccl"
|
||||
dist.init_process_group(backend)
|
||||
rank = dist.get_rank()
|
||||
torch.npu.set_device(rank)
|
||||
output = torch.tensor(2).npu()
|
||||
input_list = [torch.tensor(var).npu() for var in range(2)]
|
||||
dist.reduce_scatter(input_list, output)
|
||||
|
||||
|
||||
diff_type()
|
||||
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch_npu
|
||||
|
||||
|
||||
def discontinuous_tensor():
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29500"
|
||||
os.environ["HCCL_WHITELIST_DISABLE"] = "1"
|
||||
backend = "hccl"
|
||||
dist.init_process_group(backend)
|
||||
rank = dist.get_rank()
|
||||
torch.npu.set_device(rank)
|
||||
input_ = torch.rand(2, 3).npu()
|
||||
input_ = input_.T
|
||||
dist.all_reduce(input_)
|
||||
|
||||
|
||||
discontinuous_tensor()
|
||||
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch_npu
|
||||
|
||||
|
||||
def double_init():
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29500"
|
||||
os.environ["HCCL_WHITELIST_DISABLE"] = "1"
|
||||
backend = "hccl"
|
||||
dist.init_process_group(backend)
|
||||
dist.init_process_group(backend)
|
||||
rank = dist.get_rank()
|
||||
torch.npu.set_device(rank)
|
||||
input_ = torch.tensor(2).npu()
|
||||
dist.all_reduce(input_)
|
||||
|
||||
|
||||
double_init()
|
||||
@@ -0,0 +1,25 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch_npu
|
||||
|
||||
|
||||
def hccl_timeout():
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29500"
|
||||
os.environ["HCCL_WHITELIST_DISABLE"] = "1"
|
||||
os.environ["HCCL_EXEC_TIMEOUT"] = "180"
|
||||
backend = "hccl"
|
||||
dist.init_process_group(backend)
|
||||
rank = dist.get_rank()
|
||||
torch.npu.set_device(rank)
|
||||
tensor = torch.randn(10, 10, dtype=torch.float16).npu()
|
||||
zeros = torch.zeros(10, 10, dtype=torch.float16).npu()
|
||||
out = zeros if rank > 0 else tensor
|
||||
dist.all_reduce(out)
|
||||
if rank == 1:
|
||||
exit()
|
||||
dist.all_reduce(out)
|
||||
|
||||
|
||||
hccl_timeout()
|
||||
@@ -0,0 +1,20 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch_npu
|
||||
|
||||
|
||||
def error_size():
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29500"
|
||||
os.environ["HCCL_WHITELIST_DISABLE"] = "1"
|
||||
backend = "hccl"
|
||||
dist.init_process_group(backend)
|
||||
rank = dist.get_rank()
|
||||
torch.npu.set_device(rank)
|
||||
output = torch.tensor(2).npu()
|
||||
input_list = [torch.tensor(var).npu() for var in range(3)]
|
||||
dist.reduce_scatter(output, input_list)
|
||||
|
||||
|
||||
error_size()
|
||||
@@ -0,0 +1,19 @@
|
||||
import os
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch_npu
|
||||
|
||||
|
||||
def same_addr():
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29500"
|
||||
os.environ["HCCL_WHITELIST_DISABLE"] = "1"
|
||||
backend = "hccl"
|
||||
dist.init_process_group(backend)
|
||||
rank = dist.get_rank()
|
||||
torch.npu.set_device(rank)
|
||||
input_ = torch.randn(100, 100, 20).npu()
|
||||
dist.all_reduce(input_)
|
||||
|
||||
|
||||
same_addr()
|
||||
@@ -18,7 +18,7 @@ from typing import (
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
from torch_npu.npu.amp.sharded_grad_scaler import ShardedGradScaler as NpuShardedGradScaler
|
||||
from torch_npu.npu.amp.sharded_grad_scaler import _ShardedGradScaler as NpuShardedGradScaler
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
@@ -6,7 +6,7 @@ import torch
|
||||
import torch.distributed as dist
|
||||
|
||||
import torch_npu
|
||||
from torch_npu.npu.amp.sharded_grad_scaler import ShardedGradScaler as NpuShardedGradScaler
|
||||
from torch_npu.npu.amp.sharded_grad_scaler import _ShardedGradScaler as NpuShardedGradScaler
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import os
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.multiprocessing as mp
|
||||
from torch.distributed.distributed_c10d import _world
|
||||
import torch_npu
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class GetHcclCommNameTest(TestCase):
|
||||
@classmethod
|
||||
def _init_dist_hccl(cls, rank, world_size):
|
||||
os.environ['MASTER_ADDR'] = '127.0.0.1'
|
||||
os.environ['MASTER_PORT'] = '29500'
|
||||
os.environ['HCCL_WHITELIST_DISABLE'] = '1'
|
||||
torch_npu.npu.set_device(rank)
|
||||
dist.init_process_group(backend='hccl', world_size=world_size, rank=rank)
|
||||
return dist
|
||||
|
||||
@classmethod
|
||||
def _test_hccl_name(cls, rank, world_size, init_pg):
|
||||
dist_group = init_pg(rank, world_size)
|
||||
pg1 = torch.distributed.new_group()
|
||||
assert pg1._get_backend(torch.device('npu')).get_hccl_comm_name(rank) != ""
|
||||
pg2 = torch.distributed.new_group()
|
||||
assert pg2._get_backend(torch.device('npu')).get_hccl_comm_name(rank, init_comm=False) == ""
|
||||
assert pg2._get_backend(torch.device('npu')).get_hccl_comm_name(rank, init_comm=True) != ""
|
||||
pg3 = torch.distributed.new_group()
|
||||
assert pg3._get_backend(torch.device('npu')).get_hccl_comm_name(rank, init_comm=True) != ""
|
||||
|
||||
def _test_multiprocess(self, f, init_pg, world_size):
|
||||
ctx = mp.get_context('spawn')
|
||||
ps = []
|
||||
for rank in range(world_size):
|
||||
p = ctx.Process(target=f, args=(rank, world_size, init_pg))
|
||||
p.start()
|
||||
ps.append(p)
|
||||
|
||||
for p in ps:
|
||||
p.join()
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_dist_get_hccl_name(self):
|
||||
# CI currently supports only 2 devices
|
||||
ranks = [2]
|
||||
for world_size in ranks:
|
||||
self._test_multiprocess(GetHcclCommNameTest._test_hccl_name,
|
||||
GetHcclCommNameTest._init_dist_hccl, world_size)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
@@ -0,0 +1,76 @@
|
||||
import os
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.multiprocessing as mp
|
||||
from torch.distributed.distributed_c10d import _world
|
||||
import torch_npu
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class SetHcclCommNameTest(TestCase):
|
||||
@classmethod
|
||||
def _init_dist_hccl(cls, rank, world_size):
|
||||
os.environ['MASTER_ADDR'] = '127.0.0.1'
|
||||
os.environ['MASTER_PORT'] = '29501'
|
||||
os.environ['HCCL_WHITELIST_DISABLE'] = '1'
|
||||
torch_npu.npu.set_device(rank)
|
||||
dist.init_process_group(backend='hccl', world_size=world_size, rank=rank)
|
||||
return dist
|
||||
|
||||
@classmethod
|
||||
def _test_set_hccl_name(cls, rank, world_size, init_pg):
|
||||
dist_group = init_pg(rank, world_size)
|
||||
|
||||
pg1 = torch.distributed.new_group()
|
||||
isSupportHcclName = torch_npu.distributed._is_support_hccl_comm_name()
|
||||
assert isSupportHcclName
|
||||
pg1._get_backend(torch.device('npu'))._set_hccl_comm_name("test")
|
||||
pg1._get_backend(torch.device('npu'))._set_hccl_comm_name("test")
|
||||
pg_name = pg1._get_backend(torch.device('npu')).get_hccl_comm_name(rank)
|
||||
assert pg_name == "test"
|
||||
pg2 = torch.distributed.new_group()
|
||||
pg_name = pg2._get_backend(torch.device('npu')).get_hccl_comm_name(rank)
|
||||
pg_name_new = pg2._get_backend(torch.device('npu')).get_hccl_comm_name(rank)
|
||||
assert pg_name == pg_name_new
|
||||
|
||||
def _test_multiprocess(self, f, init_pg, world_size):
|
||||
ctx = mp.get_context('spawn')
|
||||
ps = []
|
||||
for rank in range(world_size):
|
||||
p = ctx.Process(target=f, args=(rank, world_size, init_pg))
|
||||
p.start()
|
||||
ps.append(p)
|
||||
|
||||
for p in ps:
|
||||
p.join()
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_dist_set_hccl_name(self):
|
||||
# CI currently supports only 2 devices
|
||||
ranks = [2]
|
||||
for world_size in ranks:
|
||||
self._test_multiprocess(SetHcclCommNameTest._test_set_hccl_name,
|
||||
SetHcclCommNameTest._init_dist_hccl, world_size)
|
||||
|
||||
def test_dist_set_hccl_name_case_failed(self):
|
||||
dist_group = SetHcclCommNameTest._init_dist_hccl(0, 1)
|
||||
pg1 = torch.distributed.new_group()
|
||||
with self.assertRaises(RuntimeError):
|
||||
pg1._get_backend(torch.device('npu'))._set_hccl_comm_name("")
|
||||
with self.assertRaises(RuntimeError):
|
||||
pg1._get_backend(torch.device('npu'))._set_hccl_comm_name(
|
||||
"0123456789012345678901234567890123456789012345678901234567890123456789"
|
||||
"0123456789012345678901234567890123456789012345678901234567")
|
||||
with self.assertRaises(RuntimeError):
|
||||
pg1._get_backend(torch.device('npu'))._set_hccl_comm_name("test")
|
||||
pg1._get_backend(torch.device('npu'))._set_hccl_comm_name("test2")
|
||||
with self.assertRaises(RuntimeError):
|
||||
pg2 = torch.distributed.new_group()
|
||||
pg2._get_backend(torch.device('npu')).get_hccl_comm_name(0)
|
||||
pg2._get_backend(torch.device('npu'))._set_hccl_comm_name("test")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
@@ -9,9 +9,14 @@ import torch
|
||||
import torch.distributed as dist
|
||||
import torch.distributed._functional_collectives as funcol
|
||||
from torch.distributed._functional_collectives import (
|
||||
all_gather_into_tensor_coalesced,
|
||||
all_gather_tensor,
|
||||
all_reduce,
|
||||
all_reduce_coalesced,
|
||||
all_to_all_single,
|
||||
AsyncCollectiveTensor,
|
||||
reduce_scatter_tensor,
|
||||
reduce_scatter_tensor_coalesced,
|
||||
)
|
||||
from torch.testing._internal.common_distributed import (
|
||||
MultiProcessTestCase,
|
||||
@@ -177,6 +182,185 @@ class TestWithHccl(MultiProcessTestCase):
|
||||
"max",
|
||||
"default",
|
||||
)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_all_reduce_coalesced(self) -> None:
|
||||
self._init_process_group()
|
||||
|
||||
inputs = [
|
||||
torch.full((i, i), float(self.rank * i), device=self.device)
|
||||
for i in range(10)
|
||||
]
|
||||
outputs = torch.ops._c10d_functional.all_reduce_coalesced(
|
||||
inputs,
|
||||
"sum",
|
||||
"default",
|
||||
)
|
||||
for i, (output, input) in enumerate(zip(outputs, inputs)):
|
||||
output = torch.ops._c10d_functional.wait_tensor(output)
|
||||
assert id(output) != id(input)
|
||||
assert output.eq(sum(self.ranks) * i).all()
|
||||
|
||||
# Test Python API and AsyncCollectiveTensor
|
||||
outputs = all_reduce_coalesced(
|
||||
inputs,
|
||||
"sum",
|
||||
"default",
|
||||
)
|
||||
for i, (output, input) in enumerate(zip(outputs, inputs)):
|
||||
assert not output.completed
|
||||
assert output.eq(sum(self.ranks) * i).all()
|
||||
assert output.completed
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_all_reduce_coalesced_(self) -> None:
|
||||
self._init_process_group()
|
||||
|
||||
inputs = [
|
||||
torch.full((i, i), float(self.rank * i), device=self.device)
|
||||
for i in range(10)
|
||||
]
|
||||
outputs = torch.ops._c10d_functional.all_reduce_coalesced_(
|
||||
inputs,
|
||||
"sum",
|
||||
"default",
|
||||
)
|
||||
for i, (output, input) in enumerate(zip(outputs, inputs)):
|
||||
output = torch.ops._c10d_functional.wait_tensor(output)
|
||||
assert id(output) == id(input)
|
||||
assert output.eq(sum(self.ranks) * i).all()
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_all_gather_into_tensor_single(self) -> None:
|
||||
self._init_process_group()
|
||||
|
||||
input = torch.full((10, 10), float(self.rank), device=self.device)
|
||||
output = torch.ops._c10d_functional.all_gather_into_tensor(
|
||||
input,
|
||||
self.world_size,
|
||||
"default",
|
||||
)
|
||||
output = torch.ops._c10d_functional.wait_tensor(output)
|
||||
expect = torch.cat(
|
||||
[
|
||||
torch.full((10, 10), float(rank), device=self.device)
|
||||
for rank in self.ranks
|
||||
]
|
||||
)
|
||||
assert torch.allclose(output, expect)
|
||||
assert output.eq(expect).all()
|
||||
|
||||
# Test out-variant of all_gather_into_tensor
|
||||
output = torch.empty(expect.shape, device=self.device)
|
||||
output = torch.ops._c10d_functional.all_gather_into_tensor_out(
|
||||
input,
|
||||
self.world_size,
|
||||
"default",
|
||||
out=output,
|
||||
)
|
||||
output = torch.ops._c10d_functional.wait_tensor(output)
|
||||
assert torch.allclose(output, expect)
|
||||
assert output.eq(expect).all()
|
||||
|
||||
# Test Python API and AsyncCollectiveTensor
|
||||
output = all_gather_tensor(
|
||||
input,
|
||||
0,
|
||||
"default",
|
||||
)
|
||||
assert isinstance(output, AsyncCollectiveTensor)
|
||||
assert not output.completed
|
||||
assert output.eq(expect).all()
|
||||
assert output.completed
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_all_gather_into_tensor_coalesced(self) -> None:
|
||||
self._init_process_group()
|
||||
|
||||
inputs = [
|
||||
torch.full((10, 10), float(self.rank * i), device=self.device)
|
||||
for i in range(10)
|
||||
]
|
||||
outputs = torch.ops._c10d_functional.all_gather_into_tensor_coalesced(
|
||||
inputs,
|
||||
self.world_size,
|
||||
"default",
|
||||
)
|
||||
expect = [
|
||||
torch.cat(
|
||||
[
|
||||
torch.full((10, 10), float(rank) * i, device=self.device)
|
||||
for rank in self.ranks
|
||||
]
|
||||
)
|
||||
for i in range(10)
|
||||
]
|
||||
for i, output in enumerate(outputs):
|
||||
output = torch.ops._c10d_functional.wait_tensor(output)
|
||||
assert output.eq(expect[i]).all()
|
||||
|
||||
# Test Python API and AsyncCollectiveTensor
|
||||
outputs = all_gather_into_tensor_coalesced(
|
||||
inputs,
|
||||
"default",
|
||||
)
|
||||
for i, output in enumerate(outputs):
|
||||
assert not output.completed
|
||||
assert output.eq(expect[i]).all()
|
||||
assert output.completed
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_reduce_scatter_tensor_single(self) -> None:
|
||||
self._init_process_group()
|
||||
|
||||
input = torch.tensor(self.ranks, device=self.device)
|
||||
output = torch.ops._c10d_functional.reduce_scatter_tensor(
|
||||
input,
|
||||
"sum",
|
||||
self.world_size,
|
||||
"default",
|
||||
)
|
||||
output = torch.ops._c10d_functional.wait_tensor(output)
|
||||
assert output.eq(self.rank * self.world_size).all()
|
||||
|
||||
# Test Python API and AsyncCollectiveTensor
|
||||
output = reduce_scatter_tensor(
|
||||
input,
|
||||
"sum",
|
||||
0,
|
||||
"default",
|
||||
)
|
||||
assert isinstance(output, AsyncCollectiveTensor)
|
||||
assert not output.completed
|
||||
assert output.eq(self.rank * self.world_size).all()
|
||||
assert output.completed
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_reduce_scatter_tensor_coalesced(self) -> None:
|
||||
self._init_process_group()
|
||||
|
||||
inputs = [torch.tensor(self.ranks, device=self.device) * i for i in range(10)]
|
||||
outputs = torch.ops._c10d_functional.reduce_scatter_tensor_coalesced(
|
||||
inputs,
|
||||
"sum",
|
||||
self.world_size,
|
||||
"default",
|
||||
)
|
||||
for i, output in enumerate(outputs):
|
||||
output = torch.ops._c10d_functional.wait_tensor(output)
|
||||
assert output.eq(self.rank * i * self.world_size).all()
|
||||
|
||||
# Test Python API and AsyncCollectiveTensor
|
||||
outputs = reduce_scatter_tensor_coalesced(
|
||||
inputs,
|
||||
"sum",
|
||||
[0] * 10,
|
||||
"default",
|
||||
)
|
||||
for i, output in enumerate(outputs):
|
||||
assert not output.completed
|
||||
assert output.eq(self.rank * i * self.world_size).all()
|
||||
assert output.completed
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from functools import wraps
|
||||
from functools import partial, wraps
|
||||
import os
|
||||
import types
|
||||
|
||||
@@ -10,6 +10,21 @@ from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
|
||||
|
||||
def with_comms(func=None):
|
||||
if func is None:
|
||||
return partial(
|
||||
with_comms,
|
||||
)
|
||||
|
||||
@wraps(func)
|
||||
def wrapper(self, *args, **kwargs):
|
||||
self.dist_init()
|
||||
func(self)
|
||||
self.destroy_comms()
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
class TestObjectCollectives(TestCase):
|
||||
MAIN_PROCESS_RANK = -1
|
||||
|
||||
@@ -67,21 +82,26 @@ class TestObjectCollectives(TestCase):
|
||||
self.rank = rank
|
||||
getattr(self, test_name)()
|
||||
|
||||
def destroy_comms(self):
|
||||
# Wait for all ranks to reach here before starting shutdown.
|
||||
dist.barrier()
|
||||
dist.destroy_process_group()
|
||||
|
||||
def dist_init(self):
|
||||
torch.npu.set_device(self.rank)
|
||||
dist.init_process_group(backend="hccl", rank=self.rank, world_size=self.world_size)
|
||||
|
||||
@skipIfUnsupportMultiNPU(4)
|
||||
@with_comms()
|
||||
def test_all_gather_object(self):
|
||||
self.dist_init()
|
||||
gather_objects = ["foo", 12, {1: 2}, ["foo", 12, {1: 2}]]
|
||||
output = [None for _ in gather_objects]
|
||||
dist.all_gather_object(output, gather_objects[dist.get_rank()])
|
||||
self.assertEqual(output, gather_objects)
|
||||
|
||||
@skipIfUnsupportMultiNPU(4)
|
||||
@with_comms()
|
||||
def test_broadcast_object_list(self):
|
||||
self.dist_init()
|
||||
expected_objects = ["foo", 12, {1: 2}, ["foo", 12, {1: 2}]]
|
||||
if dist.get_rank() == 0:
|
||||
objects = expected_objects # any picklable object
|
||||
@@ -91,8 +111,8 @@ class TestObjectCollectives(TestCase):
|
||||
self.assertEqual(objects, expected_objects)
|
||||
|
||||
@skipIfUnsupportMultiNPU(4)
|
||||
@with_comms()
|
||||
def test_scatter_object_list(self):
|
||||
self.dist_init()
|
||||
input_list = list(range(dist.get_world_size())) if self.rank == 0 else None
|
||||
output_list = [None]
|
||||
dist.scatter_object_list(
|
||||
|
||||
@@ -24,7 +24,7 @@ from torch._utils_internal import TEST_MASTER_ADDR as MASTER_ADDR
|
||||
from torch._utils_internal import TEST_MASTER_PORT as MASTER_PORT
|
||||
|
||||
import torch_npu
|
||||
from torch_npu.utils.path_manager import PathManager
|
||||
from torch_npu.utils._path_manager import PathManager
|
||||
from torch_npu.testing.common_distributed import TEST_SKIPS, skipIfUnsupportMultiNPU
|
||||
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import os.path
|
||||
import subprocess
|
||||
import torch
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
|
||||
|
||||
class TestMode(TestCase):
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_dist_init_duplicate(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_double_init.py')
|
||||
process = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"trying to initialize the default process group twice!",
|
||||
message
|
||||
)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_dist_use_same_addr(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_use_same_addr.py')
|
||||
|
||||
processes = []
|
||||
p = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}", "&"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
processes.append(p)
|
||||
p = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
processes.append(p)
|
||||
|
||||
for index, p in enumerate(processes):
|
||||
stdout, stderr = p.communicate(timeout=1800)
|
||||
if index == 1:
|
||||
self.assertIn(
|
||||
"address already in use",
|
||||
stderr
|
||||
)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_broadcast_group(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_broadcast_param.py')
|
||||
process = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"UserWarning: Running broadcast on global rank 1 which does not belong to the given group.",
|
||||
message
|
||||
)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_cpu_tensor(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_cpu_tensor.py')
|
||||
process = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"No backend type associated with device type cpu",
|
||||
message
|
||||
)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_diff_dtype(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_diff_dtype.py')
|
||||
process = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"Invalid usage of tensors with different dtypesFound torch.float32 and torch.int64",
|
||||
message
|
||||
)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_diff_type(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_diff_type.py')
|
||||
process = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"Invalid function argument. Expected parameter `output` of type torch.Tensor",
|
||||
message
|
||||
)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_error_size(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_size.py')
|
||||
process = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"Tensor list input to scatter/gather must match number of collective participants",
|
||||
message
|
||||
)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_discontinuous_tensor(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_discontinuous_tensor.py')
|
||||
process = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"RuntimeError: Tensors must be contiguous",
|
||||
message
|
||||
)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_hccl_timeout(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_hccl_timeout.py')
|
||||
process = subprocess.Popen(["torchrun", "--nproc-per-node=2", f"{path}"], shell=False, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"EI0002",
|
||||
message
|
||||
)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
@@ -24,10 +25,23 @@ class HcclStreamIdTest(TestCase):
|
||||
dist_group = init_pg(rank, world_size)
|
||||
input1 = torch.tensor([1]).npu()
|
||||
dist_group.all_reduce(input1)
|
||||
|
||||
collective_stream_id = _world.default_pg._get_backend(torch.device('npu'))._get_stream_id(False)
|
||||
p2p_stream_id = _world.default_pg._get_backend(torch.device('npu'))._get_stream_id(True)
|
||||
assert0 = ((collective_stream_id & 8) == 8)
|
||||
|
||||
send_tensor = torch.ones(2, 2).to(f"npu:{rank}") * 6
|
||||
recv_tensor = torch.ones(2, 2).to(f"npu:{rank}") * -1
|
||||
dst = 0
|
||||
src = 1
|
||||
if src == rank:
|
||||
dist_group.send(send_tensor, dst)
|
||||
p2p_stream_id = _world.default_pg._get_backend(torch.device('npu'))._get_stream_id(True, dst)
|
||||
elif dst == rank:
|
||||
dist_group.recv(recv_tensor, src)
|
||||
p2p_stream_id = _world.default_pg._get_backend(torch.device('npu'))._get_stream_id(True, src)
|
||||
|
||||
stream_num = os.environ.get("STREAMS_PER_DEVICE", 8)
|
||||
if stream_num != 32:
|
||||
stream_num = 8
|
||||
assert0 = ((collective_stream_id & stream_num) == stream_num)
|
||||
assert1 = (collective_stream_id == p2p_stream_id)
|
||||
collective_stream = torch.npu.Stream(stream_id=collective_stream_id, device_type=20)
|
||||
p2p_stream = torch.npu.Stream(stream_id=collective_stream_id, device_type=20)
|
||||
@@ -53,12 +67,13 @@ class HcclStreamIdTest(TestCase):
|
||||
p.join()
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_dist_get_hccl_stream_id(self):
|
||||
def test_dist_get_hccl_stream_id_same(self):
|
||||
# CI currently supports only 2 devices
|
||||
ranks = [2]
|
||||
for world_size in ranks:
|
||||
self._test_multiprocess(HcclStreamIdTest._test_hccl_stream_id,
|
||||
HcclStreamIdTest._init_dist_hccl, world_size)
|
||||
with patch.dict(os.environ, {"P2P_HCCL_BUFFSIZE": "0"}):
|
||||
ranks = [2]
|
||||
for world_size in ranks:
|
||||
self._test_multiprocess(HcclStreamIdTest._test_hccl_stream_id,
|
||||
HcclStreamIdTest._init_dist_hccl, world_size)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -7,7 +7,7 @@ import torch.distributed as dist
|
||||
import torch.multiprocessing as mp
|
||||
import torch_npu
|
||||
|
||||
from torch_npu.utils.path_manager import PathManager
|
||||
from torch_npu.utils._path_manager import PathManager
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import os
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.distributed.distributed_c10d as c10d
|
||||
import torch.multiprocessing as mp
|
||||
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.testing.common_utils import create_common_tensor
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
import torch_npu
|
||||
|
||||
|
||||
class OptionsTest(TestCase):
|
||||
@classmethod
|
||||
def _init_dist_hccl(cls, rank, options, world_size):
|
||||
os.environ['MASTER_ADDR'] = '127.0.0.1'
|
||||
os.environ['MASTER_PORT'] = '29500'
|
||||
os.environ['HCCL_WHITELIST_DISABLE'] = '1'
|
||||
torch_npu.npu.set_device(rank)
|
||||
dist.init_process_group(backend='hccl', pg_options=options, world_size=world_size, rank=rank)
|
||||
|
||||
@classmethod
|
||||
def _test_all_reduce_with_options(cls, rank, ranks, world_size, input1):
|
||||
options = torch_npu._C._distributed_c10d.ProcessGroupHCCL.Options()
|
||||
hccl_config1 = {"hccl_buffer_size":300}
|
||||
options.hccl_config = hccl_config1
|
||||
OptionsTest._init_dist_hccl(rank, options, world_size)
|
||||
input1 = input1.npu()
|
||||
dist.all_reduce(input1)
|
||||
hccl_config2 = {"hccl_buffer_size":200}
|
||||
options.hccl_config = hccl_config2
|
||||
dist.all_reduce(input1)
|
||||
default_pg = c10d._get_default_group()._get_backend(torch.device('npu'))
|
||||
test_case = TestCase()
|
||||
test_case.assertEqual(default_pg.options.hccl_config, hccl_config1,
|
||||
"Once Options are set for a ProcessGroupHCCL, later changes to Options won't affect that ProcessGroupHCCL.")
|
||||
pg = dist.new_group(backend='hccl', ranks=ranks, pg_options=options)
|
||||
dist.all_reduce(input1, group=pg)
|
||||
|
||||
@classmethod
|
||||
def _test_options_wrong_type(cls, rank, ranks, world_size, input1):
|
||||
options = torch._C._distributed_c10d.ProcessGroup.Options("hccl")
|
||||
test_case = TestCase()
|
||||
with test_case.assertRaisesRegex(AssertionError,
|
||||
"Expected pg_options argument to be of type torch_npu._C._distributed_c10d.ProcessGroupHCCL.Options"):
|
||||
OptionsTest._init_dist_hccl(rank, options, world_size)
|
||||
|
||||
|
||||
def _test_multiprocess(self, f, input1, world_size):
|
||||
ctx = mp.get_context('spawn')
|
||||
|
||||
ps = []
|
||||
ranks = range(world_size)
|
||||
for rank in ranks:
|
||||
p = ctx.Process(
|
||||
target=f,
|
||||
args=(rank, ranks, world_size, input1.cpu()))
|
||||
p.start()
|
||||
ps.append(p)
|
||||
|
||||
for p in ps:
|
||||
p.join()
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_all_reduce_with_options(self):
|
||||
ranks = [2]
|
||||
shape = [np.int32, 0, [2, 3, 16]]
|
||||
for world_size in ranks:
|
||||
exp_input, input1 = create_common_tensor(shape, -10, 10)
|
||||
self._test_multiprocess(OptionsTest._test_all_reduce_with_options,
|
||||
input1, world_size)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_options_wrong_type(self):
|
||||
ranks = [2]
|
||||
shape = [np.int32, 0, [2, 3, 16]]
|
||||
for world_size in ranks:
|
||||
exp_input, input1 = create_common_tensor(shape, -10, 10)
|
||||
self._test_multiprocess(OptionsTest._test_options_wrong_type,
|
||||
input1, world_size)
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
@@ -0,0 +1,77 @@
|
||||
import random
|
||||
import unittest
|
||||
from torch_npu.distributed import ParallelStore
|
||||
|
||||
|
||||
class ParallelStoreTest(unittest.TestCase):
|
||||
def __init__(self, method_name='runTest'):
|
||||
super(ParallelStoreTest, self).__init__(method_name)
|
||||
self._begin_port = random.randint(10000, 15000)
|
||||
self._port_offset = 0
|
||||
self._client = None
|
||||
self._server = None
|
||||
|
||||
def setUp(self):
|
||||
self._port_offset += 1
|
||||
tcp_port = self._begin_port + self._port_offset
|
||||
self._server = ParallelStore(port=tcp_port, is_server=True, wait_workers=False, multi_tenant=True)
|
||||
self._client = ParallelStore(port=tcp_port, is_server=False)
|
||||
|
||||
def tearDown(self):
|
||||
self._client = None
|
||||
self._server = None
|
||||
|
||||
def test_client_set_and_server_get(self):
|
||||
key = 'key/ParallelStoreTest/client_set_and_server_get'
|
||||
value = b'value/ParallelStoreTest/client_set_and_server_get'
|
||||
self._client.set(key, value)
|
||||
|
||||
result = self._server.get(key)
|
||||
self.assertEqual(value, result)
|
||||
|
||||
def test_client_server_add(self):
|
||||
key = 'key/ParallelStoreTest/client_server_add'
|
||||
expected = 1
|
||||
value = self._client.add(key, 1)
|
||||
self.assertEqual(expected, value)
|
||||
|
||||
for i in range(0, 100):
|
||||
expected += 1
|
||||
value = self._server.add(key, 1)
|
||||
self.assertEqual(expected, value)
|
||||
|
||||
expected += 1
|
||||
value = self._client.add(key, 1)
|
||||
self.assertEqual(expected, value)
|
||||
|
||||
def test_set_delete_key_and_key_count(self):
|
||||
key_base = 'key/ParallelStoreTest/set_delete_key_and_key_count'
|
||||
value_base = 'value/ParallelStoreTest/set_delete_key_and_key_count'
|
||||
keys = list()
|
||||
for i in range(0, 100):
|
||||
key = f'{key_base}/{i}'
|
||||
value = f'{value_base}/{i}'
|
||||
keys.append(key)
|
||||
|
||||
old_key_count = self._server.num_keys()
|
||||
self._client.set(key, value)
|
||||
new_key_count = self._server.num_keys()
|
||||
self.assertEqual(old_key_count + 1, new_key_count)
|
||||
|
||||
for key in keys:
|
||||
old_key_count = self._server.num_keys()
|
||||
self._client.delete_key(key)
|
||||
new_key_count = self._server.num_keys()
|
||||
self.assertEqual(old_key_count - 1, new_key_count)
|
||||
|
||||
def test_multi_server_set_get(self):
|
||||
key = 'key/ParallelStoreTest/test_multi_server_set_get'
|
||||
tcp_port = self._begin_port + self._port_offset
|
||||
server2 = ParallelStore(port=tcp_port, is_server=True, wait_workers=False, multi_tenant=True)
|
||||
value1 = server2.add(key, 100)
|
||||
value2 = self._server.add(key, 0)
|
||||
self.assertEqual(value1, value2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,31 @@
|
||||
import threading
|
||||
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import TestCase, run_tests
|
||||
|
||||
import torch_npu
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
|
||||
|
||||
class TestPinMemory(TestCase):
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_pin_memory(self):
|
||||
torch.npu.set_device(1)
|
||||
|
||||
def worker_function():
|
||||
torch.npu.set_device(0)
|
||||
|
||||
t = threading.Thread(target=worker_function)
|
||||
t.start()
|
||||
t.join()
|
||||
|
||||
device = torch.npu.current_device()
|
||||
self.assertEqual(device, 1)
|
||||
pinmemory_tensor = torch.empty(32, pin_memory=True)
|
||||
device = torch.npu.current_device()
|
||||
self.assertEqual(device, 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -1,4 +1,5 @@
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import os
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
@@ -45,6 +46,21 @@ class HcclSendRecvDistTest(TestCase):
|
||||
pg.recv(res, src)
|
||||
c2p.put((src, res.cpu()))
|
||||
|
||||
@classmethod
|
||||
def _test_send_recv_dist_with_p2p(
|
||||
cls, rank, shared_tensors, world_size, init_pg, c2p, p2c):
|
||||
pg = init_pg(rank, world_size)
|
||||
res = torch.ones(2, 2).to(shared_tensors.dtype).to(f"npu:{rank}")
|
||||
xs = shared_tensors.to(f"npu:{rank}")
|
||||
dst = 0
|
||||
src = 1
|
||||
if src == rank:
|
||||
pg.send(xs, dst)
|
||||
c2p.put((dst, xs.cpu()))
|
||||
elif rank == dst:
|
||||
pg.recv(res, src)
|
||||
c2p.put((src, res.cpu()))
|
||||
|
||||
@classmethod
|
||||
def _test_send_recv_dist_recv_with_format(
|
||||
cls, rank, shared_tensors, world_size, init_pg, c2p, p2c):
|
||||
@@ -123,8 +139,9 @@ class HcclSendRecvDistTest(TestCase):
|
||||
pg.recv(res, src, tag).wait()
|
||||
c2p.put((src, res[0].cpu()))
|
||||
|
||||
def _test_multiprocess(self, f, shared_tensors, init_pg):
|
||||
ws = self.world_size
|
||||
def _test_multiprocess(self, f, shared_tensors, init_pg, ws=0):
|
||||
if not ws:
|
||||
ws = self.world_size
|
||||
# file store will delete the test file on destruction
|
||||
ctx = mp.get_context('spawn')
|
||||
c2p = ctx.Queue(2)
|
||||
@@ -139,7 +156,7 @@ class HcclSendRecvDistTest(TestCase):
|
||||
p.start()
|
||||
ps.append(p)
|
||||
|
||||
for _ in range(ws):
|
||||
for _ in range(2):
|
||||
pid, output = c2p.get()
|
||||
if pid == 0:
|
||||
expected = output
|
||||
@@ -154,7 +171,7 @@ class HcclSendRecvDistTest(TestCase):
|
||||
).format(pid, expected, result)
|
||||
)
|
||||
|
||||
for _ in range(ws):
|
||||
for _ in range(2):
|
||||
p2c.put(0)
|
||||
|
||||
for p in ps:
|
||||
@@ -166,6 +183,16 @@ class HcclSendRecvDistTest(TestCase):
|
||||
HcclSendRecvDistTest._test_send_recv_dist,
|
||||
torch.randn(2, 2),
|
||||
HcclSendRecvDistTest._init_dist_hccl)
|
||||
|
||||
@skipIfUnsupportMultiNPU(4)
|
||||
def test_send_recv_hccl_dist_with_p2p(self):
|
||||
with patch.dict(os.environ, {"P2P_HCCL_BUFFSIZE": "20"}):
|
||||
world_size = 4
|
||||
self._test_multiprocess(
|
||||
HcclSendRecvDistTest._test_send_recv_dist_with_p2p,
|
||||
torch.randn(2, 2),
|
||||
HcclSendRecvDistTest._init_dist_hccl,
|
||||
world_size)
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_send_recv_hccl_dist_with_format(self):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import os
|
||||
import unittest
|
||||
import time
|
||||
import torch.distributed.run as launch
|
||||
from torch_npu.testing.testcase import run_tests, TestCase
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
@@ -11,15 +12,12 @@ def path(script):
|
||||
|
||||
class ElasticLaunchTest(TestCase):
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_communicate_npu_watchdog_timeout(self):
|
||||
def test_npu_watchdog_timeout(self):
|
||||
try:
|
||||
error = None
|
||||
launch.main(
|
||||
[
|
||||
"--run-path",
|
||||
"--nnodes=1",
|
||||
"--nproc-per-node=2",
|
||||
"--monitor-interval=1",
|
||||
path("watchdog/watchdog_base.py"),
|
||||
]
|
||||
)
|
||||
@@ -30,5 +28,25 @@ class ElasticLaunchTest(TestCase):
|
||||
raise RuntimeError("Test case fail")
|
||||
|
||||
|
||||
@skipIfUnsupportMultiNPU(2)
|
||||
def test_npu_watchdog_quick_exit(self):
|
||||
start_time = time.time()
|
||||
try:
|
||||
launch.main(
|
||||
[
|
||||
"--nproc-per-node=2",
|
||||
path("watchdog/watchdog_quick_exit.py"),
|
||||
]
|
||||
)
|
||||
except Exception:
|
||||
print("Program fail and exit")
|
||||
|
||||
end_time = time.time()
|
||||
excution_time = end_time - start_time
|
||||
if excution_time > 120:
|
||||
print(f"Excution time using time.time(): {excution_time} seconds")
|
||||
raise RuntimeError("Test case fail")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -12,15 +12,12 @@ def main():
|
||||
device = torch.device('npu:{}'.format(local_rank))
|
||||
torch.npu.set_device(device)
|
||||
|
||||
dist.init_process_group(backend='hccl', timeout=datetime.timedelta(seconds=1))
|
||||
tensor = torch.tensor([1024]).npu(non_blocking=True)
|
||||
dist.init_process_group(backend='hccl', rank=rank, world_size=2, timeout=datetime.timedelta(seconds=10))
|
||||
tensor = torch.tensor(1).npu()
|
||||
|
||||
for i in range(10):
|
||||
dist.all_reduce(tensor)
|
||||
if rank == 0:
|
||||
dist.all_reduce(tensor)
|
||||
if rank == 1:
|
||||
time.sleep(10)
|
||||
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import os
|
||||
import time
|
||||
import datetime
|
||||
import torch.distributed as dist
|
||||
import torch
|
||||
import torch_npu
|
||||
|
||||
|
||||
def main():
|
||||
torch.npu.set_compile_mode(jit_compile=True)
|
||||
rank = int(os.environ['RANK'])
|
||||
local_rank = int(os.environ['LOCAL_RANK'])
|
||||
device = torch.device('npu:{}'.format(local_rank))
|
||||
torch.npu.set_device(device)
|
||||
dist.init_process_group(backend='hccl', rank=rank, world_size=2, timeout=datetime.timedelta(seconds=120))
|
||||
tensor = torch.tensor(1).npu()
|
||||
dist.all_reduce(tensor)
|
||||
if rank == 0:
|
||||
x1 = torch.randn(3).float().npu()
|
||||
x2 = torch.randn(1).long().npu()
|
||||
x3 = torch.randn(1).float().npu()
|
||||
y = torch.addcmul(x1, x2, x3)
|
||||
dist.all_reduce(tensor)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+27
-240
@@ -34,9 +34,15 @@ from torch.testing._internal.common_utils import dtype2prec_DONTUSE
|
||||
from torch.testing._internal.common_cuda import tf32_on_and_off, tf32_is_not_fp32
|
||||
|
||||
from url import get_url
|
||||
from torch_npu.testing.common_utils import SupportedDevices
|
||||
|
||||
AMPERE_OR_ROCM = TEST_WITH_ROCM or tf32_is_not_fp32()
|
||||
|
||||
DEVICE_NAME = torch_npu.npu.get_device_name(0)
|
||||
|
||||
device_is_910A = False
|
||||
if "Ascend910A" in DEVICE_NAME or "Ascend910P" in DEVICE_NAME:
|
||||
device_is_910A = True
|
||||
|
||||
if TEST_SCIPY:
|
||||
import scipy.signal
|
||||
@@ -938,7 +944,7 @@ class TestConvolutionNNDeviceType(NNTestCase):
|
||||
x = net2(x)
|
||||
x = net3(x)
|
||||
x.backward(torch.randn_like(x))
|
||||
if device_name == 'npu':
|
||||
if device == 'npu':
|
||||
torch_npu.npu.synchronize()
|
||||
|
||||
@onlyPRIVATEUSE1
|
||||
@@ -1535,229 +1541,6 @@ class TestConvolutionNNDeviceType(NNTestCase):
|
||||
output = m(inp, output_size=output_size)
|
||||
self.assertEqual(output.shape, output_size)
|
||||
|
||||
@skipMeta
|
||||
@parametrize_test("input_shape,transposed,dilated,groups,layout,backend_expected", [
|
||||
# === slow ===
|
||||
subtest(((2, 6, 7), False, False, 3, torch.strided, torch._C._ConvBackend.Slow2d),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow1d'),
|
||||
subtest(((2, 6, 7), True, False, 3, torch.strided, torch._C._ConvBackend.SlowTranspose2d),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow1d_transposed'),
|
||||
subtest(((2, 6, 7), False, True, 3, torch.strided, torch._C._ConvBackend.SlowDilated2d),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow1d_dilated'),
|
||||
subtest(((2, 6, 7), True, True, 3, torch.strided, torch._C._ConvBackend.SlowTranspose2d),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow1d_dilated_transposed'),
|
||||
subtest(((2, 6, 7, 8), False, False, 3, torch.strided, torch._C._ConvBackend.Slow2d),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow2d'),
|
||||
subtest(((2, 6, 7, 8), True, False, 3, torch.strided, torch._C._ConvBackend.SlowTranspose2d),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow2d_transposed'),
|
||||
subtest(((2, 6, 7, 8), False, True, 3, torch.strided, torch._C._ConvBackend.SlowDilated2d),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow2d_dilated'),
|
||||
subtest(((2, 6, 7, 8), True, True, 3, torch.strided, torch._C._ConvBackend.SlowTranspose2d),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow2d_dilated_transposed'),
|
||||
subtest(((2, 6, 7, 8, 9), False, False, 3, torch.strided, torch._C._ConvBackend.Slow3d),
|
||||
decorators=[onlyCPU, disableMkldnn], name='slow3d_cpu'),
|
||||
# CUDA doesn't have a slow 3D implementation, so it goes to the dilated 3D implementation instead
|
||||
subtest(((2, 6, 7, 8, 9), False, False, 3, torch.strided, torch._C._ConvBackend.SlowDilated3d),
|
||||
decorators=[onlyPRIVATEUSE1, disablecuDNN], name='slow3d_cuda'),
|
||||
# subtest(((2, 6, 7, 8, 9), True, False, 3, torch.strided, torch._C._ConvBackend.SlowTranspose3d),
|
||||
# decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow3d_transposed'),
|
||||
subtest(((2, 6, 7, 8, 9), False, True, 3, torch.strided, torch._C._ConvBackend.SlowDilated3d),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow3d_dilated'),
|
||||
# subtest(((2, 6, 7, 8, 9), True, True, 3, torch.strided, torch._C._ConvBackend.SlowTranspose3d),
|
||||
# decorators=[onlyNativeDeviceTypes, disableMkldnn, disablecuDNN], name='slow3d_dilated_transposed'),
|
||||
subtest(((0, 6, 7), False, False, 3, torch.strided, torch._C._ConvBackend.Empty),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn], name='empty_batch1d'),
|
||||
subtest(((2, 0, 7), False, False, 3, torch.strided, torch._C._ConvBackend.Empty),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn], name='empty_channel1d'),
|
||||
subtest(((0, 0, 7), False, False, 3, torch.strided, torch._C._ConvBackend.Empty),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn], name='empty_batch_channel1d'),
|
||||
subtest(((0, 6, 7, 8), False, False, 3, torch.strided, torch._C._ConvBackend.Empty),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn], name='empty_batch2d'),
|
||||
subtest(((2, 0, 7, 8), False, False, 3, torch.strided, torch._C._ConvBackend.Empty),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn], name='empty_channel2d'),
|
||||
subtest(((0, 0, 7, 8), False, False, 3, torch.strided, torch._C._ConvBackend.Empty),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn], name='empty_batch_channel2d'),
|
||||
subtest(((0, 6, 7, 8, 9), False, False, 3, torch.strided, torch._C._ConvBackend.Empty),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn], name='empty_batch3d'),
|
||||
subtest(((2, 0, 7, 8, 9), False, False, 3, torch.strided, torch._C._ConvBackend.Empty),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn], name='empty_channel3d'),
|
||||
subtest(((0, 0, 7, 8, 9), False, False, 3, torch.strided, torch._C._ConvBackend.Empty),
|
||||
decorators=[onlyNativeDeviceTypes, disableMkldnn], name='empty_batch_channel3d'),
|
||||
# === cuda ===
|
||||
# Note that disablecuDNN disables miopen as well.
|
||||
subtest(((2, 6, 7), False, False, 6, torch.strided, torch._C._ConvBackend.CudaDepthwise2d),
|
||||
decorators=[onlyPRIVATEUSE1, disablecuDNN], name='cuda_depthwise1d'),
|
||||
subtest(((2, 6, 7, 8), False, False, 6, torch.strided, torch._C._ConvBackend.CudaDepthwise2d),
|
||||
decorators=[onlyPRIVATEUSE1, disablecuDNN], name='cuda_depthwise2d'),
|
||||
subtest(((2, 6, 7, 8, 9), False, False, 6, torch.strided, torch._C._ConvBackend.CudaDepthwise3d),
|
||||
decorators=[onlyPRIVATEUSE1, disablecuDNN], name='cuda_depthwise3d'),
|
||||
# === cudnn ===
|
||||
subtest(((2, 6, 7), False, False, 3, torch.strided, torch._C._ConvBackend.Cudnn),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoCudnn, skipCUDAIfMiopen], name='cudnn1d'),
|
||||
subtest(((2, 6, 7, 8), False, False, 3, torch.strided, torch._C._ConvBackend.Cudnn),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoCudnn, skipCUDAIfMiopen], name='cudnn2d'),
|
||||
subtest(((2, 6, 7, 8, 9), False, False, 3, torch.strided, torch._C._ConvBackend.Cudnn),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoCudnn, skipCUDAIfMiopen], name='cudnn3d'),
|
||||
subtest(((2, 6, 7), True, False, 3, torch.strided, torch._C._ConvBackend.CudnnTranspose),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoCudnn, skipCUDAIfMiopen], name='cudnn1d_transposed'),
|
||||
subtest(((2, 6, 7, 8), True, False, 3, torch.strided, torch._C._ConvBackend.CudnnTranspose),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoCudnn, skipCUDAIfMiopen], name='cudnn2d_transposed'),
|
||||
# subtest(((2, 6, 7, 8, 9), True, False, 3, torch.strided, torch._C._ConvBackend.CudnnTranspose),
|
||||
# decorators=[onlyPRIVATEUSE1, skipCUDAIfNoCudnn, skipCUDAIfMiopen], name='cudnn3d_transposed'),
|
||||
# === miopen ===
|
||||
subtest(((2, 6, 7), False, False, 3, torch.strided, torch._C._ConvBackend.Miopen),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoMiopen], name='miopen1d'),
|
||||
subtest(((2, 6, 7, 8), False, False, 3, torch.strided, torch._C._ConvBackend.Miopen),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoMiopen], name='miopen2d'),
|
||||
subtest(((2, 6, 7, 8, 9), False, False, 3, torch.strided, torch._C._ConvBackend.Miopen),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoMiopen], name='miopen3d'),
|
||||
subtest(((2, 6, 7), True, False, 3, torch.strided, torch._C._ConvBackend.MiopenTranspose),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoMiopen], name='miopen1d_transposed'),
|
||||
subtest(((2, 6, 7, 8), True, False, 3, torch.strided, torch._C._ConvBackend.MiopenTranspose),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoMiopen], name='miopen2d_transposed'),
|
||||
subtest(((2, 6, 7, 8, 9), True, False, 3, torch.strided, torch._C._ConvBackend.MiopenTranspose),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoMiopen], name='miopen3d_transposed'),
|
||||
subtest(((2, 6, 7), False, False, 6, torch.strided, torch._C._ConvBackend.MiopenDepthwise),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoMiopen], name='miopen_depthwise1d'),
|
||||
subtest(((2, 6, 7, 8), False, False, 6, torch.strided, torch._C._ConvBackend.MiopenDepthwise),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoMiopen], name='miopen_depthwise2d'),
|
||||
subtest(((2, 6, 7, 8, 9), False, False, 6, torch.strided, torch._C._ConvBackend.MiopenDepthwise),
|
||||
decorators=[onlyPRIVATEUSE1, skipCUDAIfNoMiopen], name='miopen_depthwise3d'),
|
||||
# === mkldnn ===
|
||||
subtest(((2, 6, 7), False, False, 3, torch._mkldnn, torch._C._ConvBackend.Mkldnn),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn1d'),
|
||||
subtest(((2, 6, 7, 8), False, False, 3, torch._mkldnn, torch._C._ConvBackend.Mkldnn),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn2d'),
|
||||
subtest(((2, 6, 7, 8, 9), False, False, 3, torch._mkldnn, torch._C._ConvBackend.Mkldnn),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn3d'),
|
||||
subtest(((2, 6, 7), True, False, 3, torch._mkldnn, torch._C._ConvBackend.Mkldnn),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn, unittest.expectedFailure], name='mkldnn1d_transposed'),
|
||||
subtest(((2, 6, 7, 8), True, False, 3, torch._mkldnn, torch._C._ConvBackend.Mkldnn),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn, unittest.expectedFailure], name='mkldnn2d_transposed'),
|
||||
subtest(((2, 6, 7, 8, 9), True, False, 3, torch._mkldnn, torch._C._ConvBackend.Mkldnn),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn, unittest.expectedFailure], name='mkldnn3d_transposed'),
|
||||
subtest(((2, 6, 7), False, True, 3, torch.strided, torch._C._ConvBackend.Mkldnn),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn1d_cpu_input'),
|
||||
subtest(((2, 6, 7, 8), False, True, 3, torch.strided, torch._C._ConvBackend.Mkldnn),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn2d_cpu_input'),
|
||||
subtest(((2, 6, 7, 8, 9), False, True, 3, torch.strided, torch._C._ConvBackend.Mkldnn),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn3d_cpu_input'),
|
||||
subtest(((0, 6, 7), False, False, 3, torch._mkldnn, torch._C._ConvBackend.MkldnnEmpty),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn_empty_batch1d'),
|
||||
subtest(((2, 0, 7), False, False, 3, torch._mkldnn, torch._C._ConvBackend.MkldnnEmpty),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn_empty_channel1d'),
|
||||
subtest(((0, 0, 7), False, False, 3, torch._mkldnn, torch._C._ConvBackend.MkldnnEmpty),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn_empty_batch_channel1d'),
|
||||
subtest(((0, 6, 7, 8), False, False, 3, torch._mkldnn, torch._C._ConvBackend.MkldnnEmpty),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn_empty_batch2d'),
|
||||
subtest(((2, 0, 7, 8), False, False, 3, torch._mkldnn, torch._C._ConvBackend.MkldnnEmpty),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn_empty_channel2d'),
|
||||
subtest(((0, 0, 7, 8), False, False, 3, torch._mkldnn, torch._C._ConvBackend.MkldnnEmpty),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn_empty_batch_channel2d'),
|
||||
subtest(((0, 6, 7, 8, 9), False, False, 3, torch._mkldnn, torch._C._ConvBackend.MkldnnEmpty),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn_empty_batch3d'),
|
||||
subtest(((2, 0, 7, 8, 9), False, False, 3, torch._mkldnn, torch._C._ConvBackend.MkldnnEmpty),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn_empty_channel3d'),
|
||||
subtest(((0, 0, 7, 8, 9), False, False, 3, torch._mkldnn, torch._C._ConvBackend.MkldnnEmpty),
|
||||
decorators=[onlyCPU, skipCPUIfNoMkldnn], name='mkldnn_empty_batch_channel3d'),
|
||||
# Note: Tests for mobile backends are not currently supported. This comprises
|
||||
# NnpackSpatial, Winograd3x3Depthwise, and Xnnpack2d backends. Testing these
|
||||
# requires the ability to gate tests by whether PyTorch is built with USE_MOBILE=1.
|
||||
])
|
||||
# Test with both bias and no bias.
|
||||
@parametrize_test("has_bias", [False, True])
|
||||
# Test with both stride=1 and stride>1 cases.
|
||||
@parametrize_test("strided", [False, True])
|
||||
# Test with both contiguous and non-contiguous inputs.
|
||||
@parametrize_test("contiguous", [False, True])
|
||||
def test_conv_backend(
|
||||
self, device, input_shape, has_bias, strided, contiguous, transposed, dilated, groups,
|
||||
layout, backend_expected):
|
||||
# Build up inputs.
|
||||
dtype = torch.float32
|
||||
C_in, C_out, dim, kernel_size = input_shape[1], 12, len(input_shape) - 2, 3
|
||||
x = torch.randn(*input_shape, device=device, dtype=dtype, requires_grad=True)
|
||||
weight = torch.randn(C_in if transposed else C_out,
|
||||
C_out // groups if transposed else C_in // groups,
|
||||
*[kernel_size for _ in range(dim)],
|
||||
device=device, dtype=dtype, requires_grad=True)
|
||||
bias = torch.randn(C_out, device=device, dtype=dtype, requires_grad=True) if has_bias else None
|
||||
|
||||
def _make_noncontiguous(inp):
|
||||
if inp is None:
|
||||
return None
|
||||
old_requires_grad = inp.requires_grad
|
||||
inp = torch.repeat_interleave(inp, 2, dim=-1)
|
||||
inp = inp[..., ::2].detach().requires_grad_(old_requires_grad)
|
||||
return inp
|
||||
|
||||
if not contiguous:
|
||||
x = _make_noncontiguous(x)
|
||||
weight = _make_noncontiguous(weight)
|
||||
bias = _make_noncontiguous(bias)
|
||||
|
||||
if layout is torch._mkldnn:
|
||||
x = x.to_mkldnn()
|
||||
# Note that weight and bias are not supported as mkldnn tensors during training.
|
||||
|
||||
stride = (2,) * dim if strided else (1,) * dim
|
||||
padding = (0,) * dim
|
||||
dilation = (2,) * dim if dilated else (1,) * dim
|
||||
output_padding = (0,) * dim
|
||||
inputs = [x, weight, bias, stride, padding, dilation, transposed, output_padding, groups]
|
||||
|
||||
# Ensure correct backend is selected.
|
||||
backend_actual = torch._C._select_conv_backend(*inputs)
|
||||
self.assertEqual(backend_actual, backend_expected)
|
||||
|
||||
# Ensure backward call succeeds.
|
||||
convolution = torch.ops.aten.convolution
|
||||
output = convolution(*inputs)
|
||||
grad_output = torch.randn(output.shape, device=device, dtype=dtype)
|
||||
if not contiguous:
|
||||
grad_output = _make_noncontiguous(grad_output)
|
||||
if layout is torch._mkldnn:
|
||||
grad_output = grad_output.to_mkldnn()
|
||||
output.backward(grad_output)
|
||||
|
||||
# mkldnn doesn't support gradcheck :(
|
||||
if layout is torch._mkldnn:
|
||||
return
|
||||
|
||||
if backend_actual != torch._C._ConvBackend.Empty:
|
||||
# Forward AD and forward-over-reverse AD smoke test in float32
|
||||
with fwAD.dual_level():
|
||||
dual_inputs = [(fwAD.make_dual(i, torch.rand_like(i)) if isinstance(i, torch.Tensor) else i)
|
||||
for i in inputs]
|
||||
# Forward AD
|
||||
output = convolution(*dual_inputs)
|
||||
# Forward over reverse AD
|
||||
grad_output_d = fwAD.make_dual(torch.rand_like(output), torch.rand_like(output))
|
||||
if has_bias:
|
||||
torch.autograd.grad(output, [x, weight, bias], grad_output_d)
|
||||
else:
|
||||
torch.autograd.grad(output, [x, weight], grad_output_d)
|
||||
|
||||
# Convert to float64 for gradcheck.
|
||||
x = x.to(torch.float64).detach().requires_grad_(True)
|
||||
weight = weight.to(torch.float64).detach().requires_grad_(True)
|
||||
if bias is not None:
|
||||
bias = bias.to(torch.float64).detach().requires_grad_(True)
|
||||
inputs = [x, weight, bias, stride, padding, dilation, transposed, output_padding, groups]
|
||||
|
||||
# Set some backend-specific validation settings.
|
||||
gradcheck_nondet_tol = 0.0
|
||||
if torch.backends.cudnn.is_available():
|
||||
# cuDNN introduces non-determinism
|
||||
gradcheck_nondet_tol = GRADCHECK_NONDET_TOL
|
||||
|
||||
self.assertTrue(gradcheck(convolution, inputs, nondet_tol=gradcheck_nondet_tol))
|
||||
|
||||
# double backward doesn't support bias gradients
|
||||
if bias is not None:
|
||||
bias.requires_grad_(False)
|
||||
self.assertTrue(gradgradcheck(convolution, inputs, nondet_tol=gradcheck_nondet_tol))
|
||||
|
||||
@onlyCPU
|
||||
def test_conv_contiguous_for_oneDNN(self):
|
||||
for dtype in [torch.float, torch.bfloat16, torch.half]:
|
||||
@@ -1971,7 +1754,10 @@ class TestConvolutionNNDeviceType(NNTestCase):
|
||||
F.conv2d(x, torch.randn(1, 16, 1, 1, device=device))
|
||||
|
||||
@onlyPRIVATEUSE1
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_Conv2d_size_1_kernel(self, device):
|
||||
if not device_is_910A:
|
||||
torch.npu.conv.allow_hf32 = False
|
||||
x_cpu = torch.randn(2, 3, 5, 5)
|
||||
conv_cpu = torch.nn.Conv2d(3, 3, kernel_size=1)
|
||||
y_cpu = conv_cpu(x_cpu)
|
||||
@@ -1979,17 +1765,18 @@ class TestConvolutionNNDeviceType(NNTestCase):
|
||||
y_cpu.backward(y)
|
||||
|
||||
with cudnn.flags(enabled=False):
|
||||
conv_cuda = torch.nn.Conv2d(3, 3, kernel_size=1).to(device)
|
||||
conv_cuda.bias.data.copy_(conv_cpu.bias.data)
|
||||
conv_cuda.weight.data.copy_(conv_cpu.weight.data)
|
||||
y_cuda = conv_cuda(x_cpu.to(device))
|
||||
y_cuda.backward(y.to(device))
|
||||
conv_npu = torch.nn.Conv2d(3, 3, kernel_size=1).to(device)
|
||||
conv_npu.bias.data.copy_(conv_cpu.bias.data)
|
||||
conv_npu.weight.data.copy_(conv_cpu.weight.data)
|
||||
y_npu = conv_npu(x_cpu.to(device))
|
||||
y_npu.backward(y.to(device))
|
||||
|
||||
self.assertEqual(y_cpu, y_cuda, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(conv_cpu.bias.grad.data, conv_cuda.bias.grad.data, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(conv_cpu.weight.grad.data, conv_cuda.weight.grad.data, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(y_cpu, y_npu, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(conv_cpu.bias.grad.data, conv_npu.bias.grad.data, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(conv_cpu.weight.grad.data, conv_npu.weight.grad.data, atol=1e-5, rtol=0, exact_device=False)
|
||||
|
||||
@onlyPRIVATEUSE1
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_ConvTranspose2d_size_1_kernel(self, device):
|
||||
x_cpu = torch.randn(2, 3, 5, 5)
|
||||
conv_cpu = torch.nn.ConvTranspose2d(3, 3, kernel_size=1)
|
||||
@@ -1998,15 +1785,15 @@ class TestConvolutionNNDeviceType(NNTestCase):
|
||||
y_cpu.backward(y)
|
||||
|
||||
with cudnn.flags(enabled=False):
|
||||
conv_cuda = torch.nn.ConvTranspose2d(3, 3, kernel_size=1).to(device)
|
||||
conv_cuda.bias.data.copy_(conv_cpu.bias.data)
|
||||
conv_cuda.weight.data.copy_(conv_cpu.weight.data)
|
||||
y_cuda = conv_cuda(x_cpu.to(device))
|
||||
y_cuda.backward(y.to(device))
|
||||
conv_npu = torch.nn.ConvTranspose2d(3, 3, kernel_size=1).to(device)
|
||||
conv_npu.bias.data.copy_(conv_cpu.bias.data)
|
||||
conv_npu.weight.data.copy_(conv_cpu.weight.data)
|
||||
y_npu = conv_npu(x_cpu.to(device))
|
||||
y_npu.backward(y.to(device))
|
||||
|
||||
self.assertEqual(y_cpu, y_cuda, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(conv_cpu.bias.grad.data, conv_cuda.bias.grad.data, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(conv_cpu.weight.grad.data, conv_cuda.weight.grad.data, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(y_cpu, y_npu, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(conv_cpu.bias.grad.data, conv_npu.bias.grad.data, atol=1e-5, rtol=0, exact_device=False)
|
||||
self.assertEqual(conv_cpu.weight.grad.data, conv_npu.weight.grad.data, atol=1e-5, rtol=0, exact_device=False)
|
||||
|
||||
@onlyPRIVATEUSE1
|
||||
def test_ConvTranspose3d_size_1_kernel(self, device):
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import torch
|
||||
import torch_npu
|
||||
|
||||
|
||||
def error_aclop():
|
||||
torch.npu.set_compile_mode(jit_compile=True)
|
||||
x1 = torch.randn(3).float().npu()
|
||||
x2 = torch.randn(1).long().npu()
|
||||
x3 = torch.randn(1).float().npu()
|
||||
y = torch.addcmul(x1, x2, x3)
|
||||
|
||||
|
||||
error_aclop()
|
||||
@@ -0,0 +1,23 @@
|
||||
import multiprocessing
|
||||
|
||||
import torch
|
||||
import torch_npu
|
||||
|
||||
|
||||
def _worker(i: int) -> None:
|
||||
torch_npu.npu.set_device(0)
|
||||
|
||||
|
||||
def set_device():
|
||||
torch_npu.npu.set_device(0)
|
||||
multiprocessing.set_start_method("spawn", force=True)
|
||||
jobs = [multiprocessing.Process(target=_worker, args=(i,)) for i in range(70)]
|
||||
|
||||
for p in jobs:
|
||||
p.start()
|
||||
|
||||
for p in jobs:
|
||||
p.join()
|
||||
|
||||
|
||||
set_device()
|
||||
@@ -0,0 +1,61 @@
|
||||
import threading
|
||||
import torch
|
||||
from torch.utils.data import Dataset
|
||||
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class RandomDataset(Dataset):
|
||||
def __init__(self, size, length):
|
||||
self.len = length
|
||||
self.data = torch.randn(length, size)
|
||||
|
||||
def __len__(self):
|
||||
return self.len
|
||||
|
||||
def __getitem__(self, index):
|
||||
return self.data[index].clone()
|
||||
|
||||
|
||||
def thread_worker(data, device, results, index):
|
||||
for _ in range(50):
|
||||
data = data.to(device, non_blocking=True)
|
||||
results.append(data)
|
||||
|
||||
|
||||
class TestModel:
|
||||
|
||||
def run(self):
|
||||
torch.npu.set_device(0)
|
||||
device = torch.device(f'npu:{0}')
|
||||
|
||||
dataset = RandomDataset(1000, 1000)
|
||||
|
||||
results = [None] * len(dataset)
|
||||
|
||||
threads = []
|
||||
batch_size = 64
|
||||
for i in range(0, len(dataset), batch_size):
|
||||
batch = dataset[i:i + batch_size]
|
||||
thread = threading.Thread(target=thread_worker, args=(batch, device, results, i))
|
||||
threads.append(thread)
|
||||
thread.start()
|
||||
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
|
||||
class AllocatorMultiThreadProf(TestCase):
|
||||
test_model = TestModel()
|
||||
|
||||
def test_model_run_succ(self):
|
||||
res = True
|
||||
try:
|
||||
self.test_model.run()
|
||||
except Exception as e:
|
||||
res = False
|
||||
self.assertEqual(res, True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -4,7 +4,7 @@ import torch
|
||||
import torch_npu
|
||||
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.utils.path_manager import PathManager
|
||||
from torch_npu.utils._path_manager import PathManager
|
||||
|
||||
|
||||
class SmallModel(torch.nn.Module):
|
||||
|
||||
@@ -81,6 +81,12 @@ class TestCombineTensors(TestCase):
|
||||
self.assertEqual(tensor_new.storage(), tensor.storage())
|
||||
idx += torch_npu.get_storage_size(tensor)
|
||||
|
||||
@Dtypes(torch.half, torch.float, torch.bfloat16)
|
||||
def test_untyped_storage_resize(self, dtype, device="npu"):
|
||||
a = torch.randn((2, 2, 2, 2, 2), device=device, dtype=dtype)
|
||||
a.untyped_storage().resize_(0)
|
||||
a.untyped_storage().resize_(128)
|
||||
|
||||
@Dtypes(torch.half, torch.float, torch.bfloat16)
|
||||
def test_combine_tensors(self, dtype, device="npu"):
|
||||
x = torch.zeros((2, 2, 2, 2), device=device, dtype=dtype)
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
import importlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import warnings
|
||||
from typing import Callable
|
||||
from itertools import chain
|
||||
from pathlib import Path
|
||||
import pkgutil
|
||||
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import TestCase, run_tests
|
||||
from torch._utils_internal import get_file_path_2
|
||||
import torch_npu
|
||||
|
||||
|
||||
NOT_IMPORT_LIST = [
|
||||
"torch_npu.npu.BoolTensor",
|
||||
"torch_npu.npu.ByteTensor",
|
||||
"torch_npu.npu.CharTensor",
|
||||
"torch_npu.npu.DoubleTensor",
|
||||
"torch_npu.npu.FloatTensor",
|
||||
"torch_npu.npu.HalfTensor",
|
||||
"torch_npu.npu.IntTensor",
|
||||
"torch_npu.npu.LongTensor",
|
||||
"torch_npu.npu.ShortTensor",
|
||||
"torch_npu.npu.BFloat16Tensor",
|
||||
"torch_npu.distributed._verify_params_across_processes",
|
||||
"torch_npu.dynamo.torchair.ge.attr.Bool",
|
||||
"torch_npu.dynamo.torchair.ge.attr.DataType",
|
||||
"torch_npu.dynamo.torchair.ge.attr.Float",
|
||||
"torch_npu.dynamo.torchair.ge.attr.Int",
|
||||
"torch_npu.dynamo.torchair.ge.attr.ListBool",
|
||||
"torch_npu.dynamo.torchair.ge.attr.ListDataType",
|
||||
"torch_npu.dynamo.torchair.ge.attr.ListFloat",
|
||||
"torch_npu.dynamo.torchair.ge.attr.ListInt",
|
||||
"torch_npu.dynamo.torchair.ge.attr.ListListFloat",
|
||||
"torch_npu.dynamo.torchair.ge.attr.ListListInt",
|
||||
"torch_npu.dynamo.torchair.ge.attr.ListStr",
|
||||
"torch_npu.dynamo.torchair.ge.attr.Str",
|
||||
"torch_npu.profiler.ProfilerActivity"
|
||||
]
|
||||
|
||||
|
||||
def set_failure_list(api_str, value, signature, failure_list):
|
||||
failure_list.append(f"# {api_str}:")
|
||||
failure_list.append(f" - function signature is different: ")
|
||||
failure_list.append(f" - the base signature is {value}.")
|
||||
failure_list.append(f" - now it is {signature}.")
|
||||
|
||||
|
||||
def is_not_compatibility_for_cpp_api(base_signature: str, file: str):
|
||||
content = []
|
||||
with open(file, mode="r") as fp:
|
||||
subs = ""
|
||||
start_concat = False
|
||||
for line in fp.readlines():
|
||||
if "(" in line and ")" not in line and not subs:
|
||||
start_concat = True
|
||||
if start_concat:
|
||||
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)
|
||||
line = subs
|
||||
subs = ""
|
||||
if not start_concat:
|
||||
content.append(line)
|
||||
text = "".join(content)
|
||||
|
||||
base_signature = re.escape(base_signature)
|
||||
if not re.search(rf" +{base_signature}", text):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def is_not_compatibility(base_str, new_str, api_str=None):
|
||||
base_io_params = base_str.split("->")
|
||||
new_io_params = new_str.split("->")
|
||||
base_input_params = base_io_params[0].strip()
|
||||
new_input_params = new_io_params[0].strip()
|
||||
base_out_params = "" if len(base_io_params) == 1 else base_io_params[1].strip()
|
||||
new_out_params = "" if len(new_io_params) == 1 else new_io_params[1].strip()
|
||||
|
||||
# output params
|
||||
if base_out_params != new_out_params:
|
||||
return True
|
||||
|
||||
base_params = base_input_params[1:-1].split(",")
|
||||
new_params = new_input_params[1:-1].split(",")
|
||||
base_diff_params = set(base_params) - set(new_params)
|
||||
# special case
|
||||
if api_str == "torch_npu.profiler.profiler.analyse" and base_diff_params:
|
||||
delete_special = [elem for elem in base_diff_params if "max_process_number" not in elem]
|
||||
base_diff_params = delete_special
|
||||
|
||||
# case: delete/different default value/different parameter name/different parameter dtype
|
||||
if base_diff_params:
|
||||
return True
|
||||
|
||||
new_diff_params = set(new_params) - set(base_params)
|
||||
for elem in new_diff_params:
|
||||
# case: add params
|
||||
if "=" not in elem:
|
||||
return True
|
||||
|
||||
# case: position parameters
|
||||
base_arr = [elem for elem in base_params if "=" not in elem]
|
||||
new_arr = [elem for elem in new_params if "=" not in elem]
|
||||
i = 0
|
||||
while i < len(base_arr):
|
||||
if base_arr[i] != new_arr[i]:
|
||||
return True
|
||||
i += 1
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def api_signature(obj, api_str, content, base_schema, failure_list):
|
||||
signature = inspect.signature(obj)
|
||||
signature = str(signature)
|
||||
if re.search("Any = <module 'pickle' from .+.py'>", signature):
|
||||
signature = re.sub("Any = <module 'pickle' from .+\\.py'>", "Any = <module 'pickle'>", signature)
|
||||
if re.search(" at 0x[\\da-zA-Z]+>", signature):
|
||||
signature = re.sub(" at 0x[\\da-zA-Z]+>", ">", signature)
|
||||
if api_str in base_schema.keys():
|
||||
value = base_schema[api_str]["signature"]
|
||||
if is_not_compatibility(value, signature, api_str=api_str):
|
||||
set_failure_list(api_str, value, signature, failure_list)
|
||||
content[api_str] = {"signature": signature}
|
||||
|
||||
|
||||
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"]:
|
||||
continue
|
||||
func = getattr(obj, variable)
|
||||
api_str = f"{modname}.{elem}.{variable}"
|
||||
api_signature(func, api_str, content, base_schema, failure_list)
|
||||
|
||||
|
||||
def func_from_yaml(content, base_schema, failure_list):
|
||||
torch_npu_path = torch_npu.__path__[0]
|
||||
yaml_path = os.path.join(torch_npu_path, "csrc/aten/npu_native_functions_by_codegen.yaml")
|
||||
with open(yaml_path, 'r') as f:
|
||||
for line in f.readlines():
|
||||
if " func:" in line:
|
||||
strings = line.split(" func:")
|
||||
if len(strings) < 2:
|
||||
continue
|
||||
func = strings[1].strip()
|
||||
if "(" in func:
|
||||
func_name = func.split("(")[0]
|
||||
signature = func.split(func_name)[1]
|
||||
else:
|
||||
func_name = func
|
||||
signature = ""
|
||||
if "func: " + func_name in base_schema.keys():
|
||||
value = base_schema["func: " + func_name]["signature"]
|
||||
if is_not_compatibility(value, signature, api_str=func_name):
|
||||
set_failure_list("func: " + func_name, value, signature, failure_list)
|
||||
content["func: " + func_name] = {"signature": signature}
|
||||
|
||||
|
||||
def _find_all_importables(pkg):
|
||||
"""Find all importables in the project.
|
||||
|
||||
Return them in order.
|
||||
"""
|
||||
return sorted(
|
||||
set(
|
||||
chain.from_iterable(
|
||||
_discover_path_importables(Path(p), pkg.__name__)
|
||||
for p in pkg.__path__
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _discover_path_importables(pkg_pth, pkg_name):
|
||||
"""Yield all importables under a given path and package.
|
||||
|
||||
This is like pkgutil.walk_packages, but does *not* skip over namespace
|
||||
packages.
|
||||
"""
|
||||
for dir_path, _d, file_names in os.walk(pkg_pth):
|
||||
pkg_dir_path = Path(dir_path)
|
||||
|
||||
if pkg_dir_path.parts[-1] == '__pycache__':
|
||||
continue
|
||||
|
||||
if all(Path(_).suffix != '.py' for _ in file_names):
|
||||
continue
|
||||
|
||||
rel_pt = pkg_dir_path.relative_to(pkg_pth)
|
||||
pkg_pref = '.'.join((pkg_name,) + rel_pt.parts)
|
||||
yield from (
|
||||
pkg_path
|
||||
for _, pkg_path, _ in pkgutil.walk_packages(
|
||||
(str(pkg_dir_path),), prefix=f'{pkg_pref}.',
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class TestPublicApiCompatibility(TestCase):
|
||||
@staticmethod
|
||||
def _is_mod_public(modname):
|
||||
split_strs = modname.split('.')
|
||||
for elem in split_strs:
|
||||
if elem.startswith("_"):
|
||||
return False
|
||||
return True
|
||||
|
||||
def test_api_compatibility(self):
|
||||
failure_list = []
|
||||
|
||||
try:
|
||||
file_abspath = os.path.abspath(__file__)
|
||||
air_path = 'third_party/torchair/torchair/tests/st/allowlist_for_publicAPI.json'
|
||||
with open(
|
||||
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(file_abspath))),
|
||||
air_path)) as json_file_torchair:
|
||||
allow_dict_torchair = json.load(json_file_torchair)
|
||||
update_allow_dict_torchair = {f"torch_npu.dynamo.{key}": value for key, value in
|
||||
allow_dict_torchair.items()}
|
||||
except Exception:
|
||||
update_allow_dict_torchair = {}
|
||||
warnings.warn(
|
||||
"if you are debugging UT file in clone repo, please recursively update the torchair submodule")
|
||||
|
||||
with open(get_file_path_2(os.path.dirname(os.path.dirname(__file__)),
|
||||
'allowlist_for_publicAPI.json')) as json_file:
|
||||
allow_dict = json.load(json_file)
|
||||
for modname in allow_dict["being_migrated"]:
|
||||
if modname in allow_dict:
|
||||
allow_dict[allow_dict["being_migrated"][modname]] = allow_dict[modname]
|
||||
|
||||
if update_allow_dict_torchair:
|
||||
allow_dict.update(update_allow_dict_torchair)
|
||||
|
||||
# load torch_npu_schema.json
|
||||
base_schema = {}
|
||||
with open(get_file_path_2(os.path.dirname(os.path.dirname(__file__)), "torch_npu_schema.json")) as fp:
|
||||
base_schema0 = json.load(fp)
|
||||
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
|
||||
|
||||
content = {}
|
||||
|
||||
def test_module(modname):
|
||||
try:
|
||||
if "__main__" in modname or \
|
||||
modname in ["torch_npu.dynamo.torchair.core._backend",
|
||||
"torch_npu.dynamo.torchair.core._torchair"]:
|
||||
return
|
||||
mod = importlib.import_module(modname)
|
||||
except Exception:
|
||||
# It is ok to ignore here as we have a test above that ensures
|
||||
# this should never happen
|
||||
return
|
||||
|
||||
if not self._is_mod_public(modname):
|
||||
return
|
||||
|
||||
def check_one_element(elem, modname, mod, *, is_public):
|
||||
if f"{modname}.{elem}" in NOT_IMPORT_LIST:
|
||||
return
|
||||
obj = getattr(mod, elem)
|
||||
if not (isinstance(obj, (Callable, torch.dtype)) or inspect.isclass(obj)):
|
||||
return
|
||||
elem_module = getattr(obj, '__module__', None)
|
||||
|
||||
modname = allow_dict["being_migrated"].get(modname, modname)
|
||||
elem_modname_starts_with_mod = elem_module is not None and \
|
||||
elem_module.startswith(modname) and \
|
||||
'._' not in elem_module
|
||||
|
||||
looks_public = not elem.startswith('_') and elem_modname_starts_with_mod
|
||||
is_public_api = False
|
||||
if is_public != looks_public:
|
||||
if modname in allow_dict and elem in allow_dict[modname]:
|
||||
is_public_api = True
|
||||
elif is_public and looks_public:
|
||||
is_public_api = True
|
||||
if is_public_api:
|
||||
api_str = f"{modname}.{elem}"
|
||||
api_signature(obj, api_str, content, base_schema, failure_list)
|
||||
|
||||
# function in class
|
||||
if inspect.isclass(obj):
|
||||
func_in_class(obj, content, modname, elem, base_schema, failure_list)
|
||||
|
||||
if hasattr(mod, '__all__'):
|
||||
public_api = mod.__all__
|
||||
all_api = dir(mod)
|
||||
for elem in all_api:
|
||||
check_one_element(elem, modname, mod, is_public=elem in public_api)
|
||||
else:
|
||||
all_api = dir(mod)
|
||||
for elem in all_api:
|
||||
if not elem.startswith('_'):
|
||||
check_one_element(elem, modname, mod, is_public=True)
|
||||
|
||||
for modname in _find_all_importables(torch_npu):
|
||||
test_module(modname)
|
||||
|
||||
test_module('torch_npu')
|
||||
|
||||
# functions from npu_native_functions_by_codegen.yaml
|
||||
func_from_yaml(content, base_schema, failure_list)
|
||||
|
||||
base_funcs = base_schema.keys()
|
||||
now_funcs = content.keys()
|
||||
deleted_apis = set(base_funcs) - set(now_funcs)
|
||||
for func in deleted_apis:
|
||||
failure_list.append(f"# {func}:")
|
||||
failure_list.append(f" - {func} has been deleted.")
|
||||
|
||||
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."
|
||||
msg += "\n\nFull list:\n"
|
||||
msg += "\n".join(map(str, failure_list))
|
||||
# empty lists are considered false in python
|
||||
self.assertTrue(not failure_list, msg)
|
||||
|
||||
def test_torch_cpp_api_compatibility(self):
|
||||
torch_npu_path = os.path.abspath(os.path.dirname(torch_npu.__file__))
|
||||
|
||||
with open(get_file_path_2(os.path.dirname(os.path.dirname(__file__)), "torch_npu_schema.json")) as fp:
|
||||
base_schema = json.load(fp)
|
||||
|
||||
failure_list = []
|
||||
special_type = ["char *"]
|
||||
|
||||
for key, value in base_schema.items():
|
||||
if key.startswith("torch_c_func"):
|
||||
if "(" in key:
|
||||
func = key.split("(")[0].split("::")[-1]
|
||||
elif "::" in key:
|
||||
func = key.split("::")[-1]
|
||||
else:
|
||||
func = key.replace("torch_c_func: ", "")
|
||||
signature = value["signature"].replace("c10_npu::", "")
|
||||
input_out = signature.split(" -> ")
|
||||
input_params = input_out[0]
|
||||
out_type = input_out[1] if len(input_out) > 1 else ""
|
||||
if "namespace" in value.keys():
|
||||
func = value["namespace"] + func
|
||||
if out_type and out_type not in special_type:
|
||||
base_sign = out_type + " " + func + input_params
|
||||
else:
|
||||
base_sign = out_type + func + input_params
|
||||
file0 = value["file"]
|
||||
file1 = os.path.join(torch_npu_path, "include", file0)
|
||||
if is_not_compatibility_for_cpp_api(base_sign, file1):
|
||||
failure_list.append(f"# {key}:")
|
||||
failure_list.append(f" - the signature '{base_sign}' has been changed in the file '{file0}'")
|
||||
|
||||
msg = "All the C++ 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."
|
||||
msg += "\n\nFull list:\n"
|
||||
msg += "\n".join(map(str, failure_list))
|
||||
|
||||
self.assertTrue(not failure_list, msg)
|
||||
|
||||
def test_public_environments(self):
|
||||
torch_npu_path = os.path.abspath(os.path.dirname(torch_npu.__file__))
|
||||
|
||||
with open(get_file_path_2(os.path.dirname(os.path.dirname(__file__)), "torch_npu_schema.json")) as fp:
|
||||
base_schema = json.load(fp)
|
||||
failure_list = []
|
||||
|
||||
file = "torch_npu/csrc/core/npu/register/OptionsManager.h"
|
||||
path = os.path.join(torch_npu_path, "include", file)
|
||||
|
||||
with open(path, mode='r') as fp:
|
||||
context = fp.read()
|
||||
|
||||
for key, value in base_schema.items():
|
||||
if key.startswith("torch_npu_public_env"):
|
||||
base_mode = value["mode"]
|
||||
if base_mode not in context:
|
||||
key = key.replace("torch_npu_public_env: ", "")
|
||||
failure_list.append(f"# {key}:")
|
||||
failure_list.append(f" - the mode of the environment variable {key} has been changed.")
|
||||
|
||||
msg = "All the environment variable's mode 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."
|
||||
msg += "\n\nFull list:\n"
|
||||
msg += "\n".join(map(str, failure_list))
|
||||
# empty lists are considered false in python
|
||||
self.assertTrue(not failure_list, msg)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
@@ -0,0 +1,259 @@
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import TestCase, run_tests
|
||||
from torch.utils.checkpoint import checkpoint
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
os.environ["ASCEND_LAUNCH_BLOCKING"] = '0'
|
||||
import torch_npu
|
||||
|
||||
|
||||
class TestMode(TestCase):
|
||||
|
||||
def test_distributed_launch_param(self):
|
||||
process = subprocess.Popen(["python", "-m", "torch.distributed.launch", "--enable-tcmalloc=2", "test.py"],
|
||||
shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"launch.py: error: unrecognized arguments",
|
||||
message
|
||||
)
|
||||
|
||||
def test_torchrun_param(self):
|
||||
process = subprocess.Popen(["torchrun", "--enable-jemalloc=4", "test.py"], shell=False,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"torchrun: error: unrecognized arguments",
|
||||
message
|
||||
)
|
||||
|
||||
def test_npu_set_option(self):
|
||||
with self.assertRaisesRegex(ValueError, "value of ACL_PRECISION_MODE should be in \\['allow_fp32_to_fp16', "
|
||||
"'must_keep_origin_dtype'\\] but got allow_fp32_to_fp32"):
|
||||
option = {"ACL_PRECISION_MODE": "allow_fp32_to_fp32"}
|
||||
torch.npu.set_option(option)
|
||||
|
||||
with self.assertRaisesRegex(TypeError, "npu option must be a dict"):
|
||||
torch.npu.set_option("allow_fp32_to_fp32")
|
||||
|
||||
with self.assertRaisesRegex(RuntimeError, "invalid npu option name:ACL_OP_SELECT_IMPL"):
|
||||
option = {"ACL_OP_SELECT_IMPL": "high_precision"}
|
||||
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)
|
||||
|
||||
def test_distributed_init_param(self):
|
||||
with self.assertRaisesRegex(ValueError, "Error initializing torch.distributed"):
|
||||
torch.distributed.init_process_group(backend="hccl", rank=0, world_size=1)
|
||||
|
||||
with self.assertRaisesRegex(RuntimeError, "Distributed package doesn't have NCCL built in"):
|
||||
os.environ["MASTER_ADDR"] = "127.0.0.1"
|
||||
os.environ["MASTER_PORT"] = "29689"
|
||||
torch.distributed.init_process_group(backend="nccl", rank=0, world_size=1)
|
||||
|
||||
def test_ckpt_param(self):
|
||||
with self.assertRaisesRegex(ValueError,
|
||||
"Passing `context_fn` or `debug` is only supported when use_reentrant=False"):
|
||||
use_reentrant = True
|
||||
a = torch.tensor(1., device="npu:0", requires_grad=True)
|
||||
|
||||
def fn(x):
|
||||
return x.sin().cos().exp()
|
||||
|
||||
out = checkpoint(fn, a, use_reentrant=use_reentrant, debug=True)
|
||||
out.backward()
|
||||
|
||||
def test_load(self):
|
||||
path = "./data.pt"
|
||||
with self.assertRaisesRegex(FileNotFoundError, "No such file or directory"):
|
||||
torch.load(path)
|
||||
|
||||
def test_dataloader(self):
|
||||
import torchvision
|
||||
from torch.utils.data import DataLoader
|
||||
import torchvision.transforms as transforms
|
||||
|
||||
data_transform = transforms.Compose([
|
||||
transforms.Resize(299),
|
||||
transforms.CenterCrop(299),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
||||
std=[0.229, 0.224, 0.225])
|
||||
])
|
||||
with self.assertRaisesRegex(FileNotFoundError, "No such file or directory"):
|
||||
train_dataset = torchvision.datasets.ImageFolder(root="imagenet/train", transform=data_transform)
|
||||
train_dataset_loader = DataLoader(train_dataset, batch_size=4, shuffle=True, num_workers=4)
|
||||
|
||||
def test_generator(self):
|
||||
with self.assertRaisesRegex(RuntimeError, r"Device type CUDA is not supported for torch.Generator\(\) api."):
|
||||
torch.Generator(device="cuda")
|
||||
|
||||
def test_not_supported_ops(self):
|
||||
with self.assertRaisesRegex(RuntimeError, "_copy_from_and_resize now only support copy with same size!"):
|
||||
with self.assertRaisesRegex(Warning, "CAUTION: The operator 'aten::linalg_lstsq.out' is not currently "
|
||||
"supported on the NPU backend and will fall back to run on the CPU. "
|
||||
"This may have performance implications. (function npu_cpu_fallback)"):
|
||||
torch.linalg.lstsq(torch.randn(1, 3, 3).npu(), torch.randn(2, 3, 3).npu())
|
||||
|
||||
def test_param_verification(self):
|
||||
with self.assertRaisesRegex(RuntimeError, "Expected all tensors to be on the same device. "
|
||||
"Expected NPU tensor, please check whether the input tensor "
|
||||
"device is correct."):
|
||||
torch.add(torch.rand(2), torch.rand(2).npu())
|
||||
|
||||
def test_custom_ops(self):
|
||||
with self.assertRaisesRegex(NotImplementedError, "Could not run 'npu::fast_gelu' with "
|
||||
"arguments from the 'CPU' backend."):
|
||||
input1 = torch.rand(4)
|
||||
torch_npu.fast_gelu(input1)
|
||||
|
||||
def test_autograd_backward(self):
|
||||
with self.assertRaisesRegex(RuntimeError, "one of the variables needed for gradient computation has "
|
||||
"been modified by an inplace operation"):
|
||||
a = torch.randn(5, requires_grad=True)
|
||||
d1 = a + 1
|
||||
d2 = d1 ** 2
|
||||
d1 += 1
|
||||
torch.autograd.grad(d2.sum(), a)
|
||||
|
||||
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")
|
||||
|
||||
def test_memory_allocated(self):
|
||||
x = torch.tensor(2).npu()
|
||||
with self.assertRaisesRegex(RuntimeError, "Invalid device argument"):
|
||||
torch.npu.memory_allocated(device="npu:8")
|
||||
|
||||
def test_memory_reserved(self):
|
||||
x = torch.tensor(2).npu()
|
||||
with self.assertRaisesRegex(RuntimeError, "Invalid device argument"):
|
||||
torch.npu.memory_reserved(device="npu:8")
|
||||
|
||||
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")
|
||||
|
||||
def test_aclrtSetDevice(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_set_device.py')
|
||||
process = subprocess.Popen(["python", f"{path}"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"_npu_setDevice",
|
||||
message
|
||||
)
|
||||
self.assertIn(
|
||||
"Initialize",
|
||||
message
|
||||
)
|
||||
|
||||
def test_checkpoint_module(self):
|
||||
class Net1(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
module_list = [
|
||||
nn.Linear(100, 50),
|
||||
nn.ReLU(),
|
||||
]
|
||||
self.module_list = nn.ModuleList(module_list)
|
||||
|
||||
def forward(self, input_):
|
||||
for layer in self.module_list:
|
||||
input_ = layer(input_)
|
||||
return input_
|
||||
|
||||
class Net2(nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.features = nn.Sequential(
|
||||
nn.Conv2d(3, 6, 5),
|
||||
nn.ReLU(),
|
||||
nn.MaxPool2d(2, 2),
|
||||
nn.Conv2d(6, 16, 5),
|
||||
nn.ReLU(),
|
||||
nn.MaxPool2d(2, 2)
|
||||
)
|
||||
|
||||
self.classifiter = nn.Sequential(
|
||||
nn.Linear(16 * 5 * 5, 120),
|
||||
nn.ReLU(),
|
||||
nn.Linear(120, 84),
|
||||
nn.ReLU(),
|
||||
nn.Linear(84, 10)
|
||||
)
|
||||
|
||||
def forward(self, input_):
|
||||
x = self.features(input_)
|
||||
x = x.view(-1, 16 * 5 * 5)
|
||||
x = self.classifiter(x)
|
||||
return x
|
||||
|
||||
model1 = Net1()
|
||||
optimizer1 = torch.optim.SGD(model1.parameters(), 1e-4)
|
||||
|
||||
# resume
|
||||
model2 = Net2()
|
||||
optimizer2 = torch.optim.SGD(
|
||||
[{'params': model2.features.parameters()},
|
||||
{'params': model2.classifiter.parameters(), 'lr': 1e-2}], lr=1e-5
|
||||
)
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "loaded state dict has a different number of parameter groups"):
|
||||
optimizer1.load_state_dict(optimizer2.state_dict())
|
||||
|
||||
def test_aclopCompile(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_aclopCompileAndExecute.py')
|
||||
process = subprocess.Popen(["python", f"{path}"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=True)
|
||||
out, error = process.communicate(timeout=1800)
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"EZ9999",
|
||||
error
|
||||
)
|
||||
|
||||
def test_ascyn(self):
|
||||
path = os.path.join(os.path.dirname(__file__), '_fault_mode_cases/error_aclopCompileAndExecute.py')
|
||||
process = subprocess.Popen(["python", f"{path}"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=True)
|
||||
message = process.stderr.read()
|
||||
process.stderr.close()
|
||||
process.stdout.close()
|
||||
process.terminate()
|
||||
process.wait()
|
||||
self.assertIn(
|
||||
"Since the operator is called asynchronously, the stacktrace may be inaccurate. "
|
||||
"If you want to get the accurate stacktrace",
|
||||
message
|
||||
)
|
||||
|
||||
def test_aclrtMallocAlign32(self):
|
||||
with self.assertRaisesRegex(RuntimeError, "NPU out of memory. Tried to allocate"):
|
||||
x = torch.randn(2000, 2000, 200, 20, device="npu:0")
|
||||
y = torch.randn(2000, 2000, 200, 20, device="npu:0")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,42 @@
|
||||
import os
|
||||
import shutil
|
||||
import importlib.util
|
||||
import unittest
|
||||
|
||||
# has_triton_package will be called during torch.testing init, remove existed triton due to init issue in torch 2.4
|
||||
if os.path.isdir("triton"):
|
||||
shutil.rmtree("triton")
|
||||
if os.path.isfile("triton"):
|
||||
os.remove("triton")
|
||||
|
||||
from torch.utils import _triton
|
||||
from torch.testing._internal.common_utils import TestCase, run_tests
|
||||
|
||||
TRITON_IS_INSTALLED = importlib.util.find_spec("triton") is not None
|
||||
# clear lru cache
|
||||
_triton.has_triton_package.cache_clear()
|
||||
|
||||
|
||||
class TestHasTritonPackage(TestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
if not os.path.exists("triton"):
|
||||
os.mkdir("triton")
|
||||
|
||||
def tearDown(self):
|
||||
super().tearDown()
|
||||
if os.path.isdir("triton"):
|
||||
shutil.rmtree("triton")
|
||||
|
||||
@unittest.skipIf(TRITON_IS_INSTALLED, "Skip this case due to triton is installed.")
|
||||
def test_has_triton_package(self):
|
||||
self.assertTrue(_triton.has_triton_package())
|
||||
|
||||
@unittest.skipIf(TRITON_IS_INSTALLED, "Skip this case due to triton is installed.")
|
||||
def test_has_triton_package_with_patch(self):
|
||||
import torch_npu
|
||||
self.assertFalse(_triton.has_triton_package())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
@@ -1,11 +1,11 @@
|
||||
import expecttest
|
||||
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import TestCase, run_tests
|
||||
|
||||
import torch_npu
|
||||
import torch_npu._C
|
||||
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class TestJitCompile(TestCase):
|
||||
def test_jit_compile_false(self):
|
||||
|
||||
@@ -4,7 +4,7 @@ import shutil
|
||||
import torch
|
||||
import torch_npu.jit
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.utils.path_manager import PathManager
|
||||
from torch_npu.utils._path_manager import PathManager
|
||||
|
||||
|
||||
class TestJitOpsFusion(TestCase):
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import torch
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class TestMstx(TestCase):
|
||||
mark_msg = ''
|
||||
range_msg = ''
|
||||
range_id = 0
|
||||
|
||||
def setUp(self):
|
||||
def stub_mark(message : str = ''):
|
||||
self.mark_msg = message
|
||||
|
||||
def stub_range_start_on_host(message : str) -> int:
|
||||
self.range_msg = message
|
||||
self.range_id += 1
|
||||
return self.range_id
|
||||
|
||||
def stub_range_start(message : str, stream=None):
|
||||
self.range_msg = message
|
||||
self.range_id += 1
|
||||
return self.range_id
|
||||
|
||||
def stub_range_end(range_id: int):
|
||||
self.range_id = range_id
|
||||
|
||||
torch_npu._C._mark = stub_mark
|
||||
torch_npu._C._mstx._range_start = stub_range_start
|
||||
torch_npu._C._mstx._range_start_on_host = stub_range_start_on_host
|
||||
torch_npu._C._mstx._range_end = stub_range_end
|
||||
|
||||
def test_mark(self):
|
||||
torch_npu.npu.mstx.mark("test1")
|
||||
self.assertEqual("test1", self.mark_msg)
|
||||
torch_npu.npu.mstx().mark("test2") # Verify compatibility
|
||||
self.assertEqual("test2", self.mark_msg)
|
||||
|
||||
def test_range_start(self):
|
||||
self.range_id = 0
|
||||
ret_id = torch_npu.npu.mstx.range_start("")
|
||||
self.assertEqual(0, ret_id)
|
||||
ret_id = torch_npu.npu.mstx.range_start("test1")
|
||||
self.assertEqual(1, ret_id)
|
||||
self.assertEqual("test1", self.range_msg)
|
||||
ret_id = torch_npu.npu.mstx.range_start("test2", None)
|
||||
self.assertEqual(2, ret_id)
|
||||
self.assertEqual("test2", self.range_msg)
|
||||
|
||||
torch.npu.set_device(0)
|
||||
current_stream = torch.npu.current_stream()
|
||||
ret_id = torch_npu.npu.mstx.range_start("test3", current_stream)
|
||||
self.assertEqual(3, ret_id)
|
||||
self.assertEqual("test3", self.range_msg)
|
||||
ret_id = torch_npu.npu.mstx.range_start("test4", 'invalid_stream')
|
||||
self.assertEqual(0, ret_id)
|
||||
|
||||
def test_range_end(self):
|
||||
self.range_id = 0
|
||||
torch_npu.npu.mstx.range_end('invalid_range_id')
|
||||
self.assertEqual(0, self.range_id)
|
||||
torch_npu.npu.mstx.range_end(1)
|
||||
self.assertEqual(1, self.range_id)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
+30
-1
@@ -347,7 +347,7 @@ class TestNpu(TestCase):
|
||||
|
||||
for dst, try_non_blocking in product(("npu", "cpu"), (True, False)):
|
||||
# Creates source on the opposite device from destination.
|
||||
src = torch.randn(10000, 10000, 2,
|
||||
src = torch.randn(1000, 1000, 2, 100,
|
||||
device="npu" if dst == "cpu" else "cpu",
|
||||
pin_memory=True if dst == "npu" else False)
|
||||
_test_to_non_blocking(src, try_non_blocking, dst)
|
||||
@@ -722,5 +722,34 @@ class TestNpu(TestCase):
|
||||
npu_allocator_name = torch.npu.get_allocator_backend()
|
||||
self.assertEqual(npu_allocator_name, "native")
|
||||
|
||||
def test_contiguous(self):
|
||||
def run_once():
|
||||
x = torch.randn(4, 3, 8, 8).npu()
|
||||
x = x.permute(0, 2, 1, 3)
|
||||
x = x.contiguous()
|
||||
return x
|
||||
|
||||
with torch._subclasses.fake_tensor.FakeTensorMode():
|
||||
y = run_once()
|
||||
self.assertTrue(y.is_contiguous())
|
||||
|
||||
x = torch.randn(1, 16, 5, 5).npu()
|
||||
self.assertTrue(x.is_contiguous())
|
||||
stride = list(x.stride())
|
||||
stride[0] = 20
|
||||
# change the stride in dimension 0. the tensor is still contiguous because size[0] is 1
|
||||
x.set_(x.storage(), 0, x.size(), stride)
|
||||
self.assertTrue(x.is_contiguous())
|
||||
|
||||
x.contiguous(memory_format=torch.contiguous_format)
|
||||
x.contiguous(memory_format=torch.preserve_format)
|
||||
|
||||
with self.assertRaisesRegex(RuntimeError, "ERR01007 OPS feature not supported"):
|
||||
x.contiguous(memory_format=torch.channels_last)
|
||||
|
||||
with self.assertRaisesRegex(RuntimeError, "ERR01007 OPS feature not supported"):
|
||||
x.contiguous(memory_format=torch.channels_last_3d)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
|
||||
@@ -12,12 +12,68 @@ from pathlib import Path
|
||||
|
||||
import pkgutil
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import TestCase, run_tests, IS_JETSON, IS_WINDOWS, IS_MACOS, skipIfTorchDynamo
|
||||
from torch._utils_internal import get_file_path_2
|
||||
import torch_npu
|
||||
import torch_npu.testing
|
||||
from torch.testing._internal.common_utils import TestCase, run_tests, IS_JETSON, IS_WINDOWS
|
||||
from torch._utils_internal import get_file_path_2
|
||||
|
||||
temp_filter = {
|
||||
"torch_npu.npu.amp.autocast_mode.Any",
|
||||
"torch_npu.npu.amp.autocast_mode.ErrCode",
|
||||
"torch_npu.npu.amp.autocast_mode.pta_error",
|
||||
"torch_npu.npu.amp.grad_scaler.BaseGradScaler",
|
||||
"torch_npu.npu.amp.grad_scaler.ErrCode",
|
||||
"torch_npu.npu.amp.grad_scaler.List",
|
||||
"torch_npu.npu.amp.grad_scaler.OptState",
|
||||
"torch_npu.npu.amp.grad_scaler.amp_definitely_not_available",
|
||||
"torch_npu.npu.amp.grad_scaler.defaultdict",
|
||||
"torch_npu.npu.amp.grad_scaler.pta_error",
|
||||
"torch_npu.profiler.analysis.prof_bean.node_info_bean.List",
|
||||
"torch_npu.profiler.analysis.prof_bean.node_info_bean.convert_us2ns",
|
||||
"torch_npu.testing.common_distributed.Any",
|
||||
"torch_npu.testing.common_distributed.Dict",
|
||||
"torch_npu.testing.common_distributed.Tuple",
|
||||
"torch_npu.testing.common_distributed.contextmanager",
|
||||
"torch_npu.testing.common_distributed.namedtuple",
|
||||
"torch_npu.testing.common_distributed.wraps",
|
||||
"torch_npu.testing.common_methods_invocations.List",
|
||||
"torch_npu.testing.common_methods_invocations.make_tensor",
|
||||
"torch_npu.testing.common_methods_invocations.partial",
|
||||
"torch_npu.testing.common_methods_invocations.sample_inputs_normal_common",
|
||||
"torch_npu.testing.common_methods_invocations.wraps",
|
||||
"torch_npu.testing.common_utils.List",
|
||||
"torch_npu.testing.common_utils.PathManager",
|
||||
"torch_npu.testing.common_utils.contextmanager",
|
||||
"torch_npu.testing.common_utils.product",
|
||||
"torch_npu.testing.common_utils.wraps",
|
||||
"torch_npu.testing.decorator.partialmethod",
|
||||
"torch_npu.testing.decorator.wraps",
|
||||
"torch_npu.testing.testcase.Number",
|
||||
"torch_npu.testing.testcase.OrderedDict",
|
||||
"torch_npu.testing.testcase.Sequence",
|
||||
"torch_npu.testing.testcase.TestResult",
|
||||
"torch_npu.testing.testcase.contextmanager",
|
||||
"torch_npu.testing.testcase.is_iterable",
|
||||
"torch_npu.testing.testcase.iter_indices",
|
||||
"torch_npu.testing.testcase.set_npu_device",
|
||||
"torch_npu.testing.testcase.strclass",
|
||||
"torch_npu.utils.collect_env.namedtuple",
|
||||
"torch_npu.utils.profiler.ErrCode",
|
||||
"torch_npu.utils.profiler.Optional",
|
||||
"torch_npu.utils.profiler.prof_error",
|
||||
"torch_npu.utils.flops_count.FlopsCounter",
|
||||
"torch_npu.npu_add_rms_norm",
|
||||
"torch_npu.npu_deep_norm",
|
||||
"torch_npu.npu_fast_gelu",
|
||||
"torch_npu.npu_fused_attention_layernorm_qkv_fwd",
|
||||
"torch_npu.npu_fused_attention_score_fwd",
|
||||
"torch_npu.npu_group_norm_silu",
|
||||
"torch_npu.npu_lstm_cell",
|
||||
"torch_npu.npu_masked_softmax_with_rel_pos_bias",
|
||||
"torch_npu.npu_moe_compute_expert_tokens",
|
||||
"torch_npu.npu_moe_finalize_routing",
|
||||
"torch_npu.npu_quantize",
|
||||
"torch_npu.npu_stride_copy",
|
||||
"torch_npu.fast_gelu",
|
||||
"torch_npu.npu_anchor_response_flags",
|
||||
"torch_npu.npu_anti_quant",
|
||||
@@ -37,13 +93,10 @@ temp_filter = {
|
||||
"torch_npu.npu_diou",
|
||||
"torch_npu.npu_dropout_with_add_softmax",
|
||||
"torch_npu.npu_dtype_cast",
|
||||
"torch_npu.npu_ffn",
|
||||
"torch_npu.npu_format_cast",
|
||||
"torch_npu.npu_fused_attention_score",
|
||||
"torch_npu.npu_geglu",
|
||||
"torch_npu.npu_giou",
|
||||
"torch_npu.npu_grid_assign_positive",
|
||||
"torch_npu.npu_grouped_matmul",
|
||||
"torch_npu.npu_gru",
|
||||
"torch_npu.npu_ifmr",
|
||||
"torch_npu.npu_incre_flash_attention",
|
||||
@@ -66,8 +119,6 @@ temp_filter = {
|
||||
"torch_npu.npu_prompt_flash_attention",
|
||||
"torch_npu.npu_ps_roi_pooling",
|
||||
"torch_npu.npu_ptiou",
|
||||
"torch_npu.npu_quant_matmul",
|
||||
"torch_npu.npu_quant_scatter",
|
||||
"torch_npu.npu_reshape",
|
||||
"torch_npu.npu_roi_align",
|
||||
"torch_npu.npu_rotary_mul",
|
||||
@@ -78,21 +129,12 @@ temp_filter = {
|
||||
"torch_npu.npu_scaled_masked_softmax",
|
||||
"torch_npu.npu_scatter",
|
||||
"torch_npu.npu_scatter_nd_update",
|
||||
"torch_npu.npu_scatter_nd_update_",
|
||||
"torch_npu.npu_sign_bits_pack",
|
||||
"torch_npu.npu_sign_bits_unpack",
|
||||
"torch_npu.npu_silu",
|
||||
"torch_npu.npu_slice",
|
||||
"torch_npu.npu_softmax_cross_entropy_with_logits",
|
||||
"torch_npu.npu_sort_v2",
|
||||
"torch_npu.npu_stride_add",
|
||||
"torch_npu.npu_swiglu",
|
||||
"torch_npu.npu_trans_quant_param",
|
||||
"torch_npu.npu_transpose",
|
||||
"torch_npu.npu_weight_quant_batchmatmul",
|
||||
"torch_npu.npu_yolo_boxes_encode",
|
||||
"torch_npu.one_",
|
||||
"torch_npu.pta_error"
|
||||
}
|
||||
|
||||
|
||||
@@ -127,12 +169,12 @@ def _discover_path_importables(pkg_pth, pkg_name):
|
||||
continue
|
||||
|
||||
rel_pt = pkg_dir_path.relative_to(pkg_pth)
|
||||
pkg_pref = '.'.join((pkg_name, ) + rel_pt.parts)
|
||||
pkg_pref = '.'.join((pkg_name,) + rel_pt.parts)
|
||||
yield from (
|
||||
pkg_path
|
||||
for _, pkg_path, _ in pkgutil.walk_packages(
|
||||
(str(pkg_dir_path), ), prefix=f'{pkg_pref}.',
|
||||
)
|
||||
(str(pkg_dir_path),), prefix=f'{pkg_pref}.',
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -359,9 +401,11 @@ class TestPublicBindings(TestCase):
|
||||
return False
|
||||
return True
|
||||
|
||||
@unittest.skipIf(IS_WINDOWS or IS_MACOS, "Inductor/Distributed modules hard fail on windows and macos")
|
||||
@skipIfTorchDynamo("Broken and not relevant for now")
|
||||
def test_modules_can_be_imported(self):
|
||||
failures = []
|
||||
for _, modname, _ in _discover_path_importables(str(torch.__path__), "torch"):
|
||||
for modname in _find_all_importables(torch):
|
||||
try:
|
||||
if "__main__" in modname:
|
||||
continue
|
||||
@@ -370,9 +414,11 @@ class TestPublicBindings(TestCase):
|
||||
# Some current failures are not ImportError
|
||||
failures.append((modname, type(e)))
|
||||
|
||||
for _, modname, _ in _discover_path_importables(str(torch_npu.__path__), "torch_npu"):
|
||||
for modname in _find_all_importables(torch_npu):
|
||||
try:
|
||||
if "__main__" in modname:
|
||||
if "__main__" in modname or \
|
||||
modname in ["torch_npu.dynamo.torchair.core._backend",
|
||||
"torch_npu.dynamo.torchair.core._torchair"]:
|
||||
continue
|
||||
import_module(modname)
|
||||
except Exception as e:
|
||||
@@ -385,6 +431,7 @@ class TestPublicBindings(TestCase):
|
||||
"torch._inductor.codegen.cuda.cuda_kernel",
|
||||
"torch.onnx._internal.fx._pass",
|
||||
"torch.onnx._internal.fx.analysis",
|
||||
"torch.onnx._internal.fx.analysis.unsupported_nodes",
|
||||
"torch.onnx._internal.fx.decomposition_skip",
|
||||
"torch.onnx._internal.fx.diagnostics",
|
||||
"torch.onnx._internal.fx.fx_onnx_interpreter",
|
||||
@@ -392,6 +439,13 @@ class TestPublicBindings(TestCase):
|
||||
"torch.onnx._internal.fx.onnxfunction_dispatcher",
|
||||
"torch.onnx._internal.fx.op_validation",
|
||||
"torch.onnx._internal.fx.passes",
|
||||
"torch.onnx._internal.fx.passes._utils",
|
||||
"torch.onnx._internal.fx.passes.decomp",
|
||||
"torch.onnx._internal.fx.passes.functionalization",
|
||||
"torch.onnx._internal.fx.passes.modularization",
|
||||
"torch.onnx._internal.fx.passes.readability",
|
||||
"torch.onnx._internal.fx.passes.type_promotion",
|
||||
"torch.onnx._internal.fx.passes.virtualization",
|
||||
"torch.onnx._internal.fx.type_utils",
|
||||
"torch.testing._internal.common_distributed",
|
||||
"torch.testing._internal.common_fsdp",
|
||||
@@ -423,7 +477,7 @@ class TestPublicBindings(TestCase):
|
||||
"torch.utils.tensorboard._caffe2_graph",
|
||||
"torch._inductor.codegen.cuda.cuda_template",
|
||||
"torch._inductor.codegen.cuda.gemm_template",
|
||||
"torch._inductor.triton_helpers",
|
||||
"torch._inductor.runtime.triton_helpers",
|
||||
"torch.ao.pruning._experimental.data_sparsifier.lightning.callbacks.data_sparsity",
|
||||
"torch.backends._coreml.preprocess",
|
||||
"torch.contrib._tensorboard_vis",
|
||||
@@ -458,6 +512,33 @@ class TestPublicBindings(TestCase):
|
||||
"torch.distributed.examples.memory_tracker_example",
|
||||
"torch.testing._internal.distributed.rpc.fb.thrift_rpc_agent_test_fixture",
|
||||
"torch.utils._cxx_pytree",
|
||||
"torch.utils.tensorboard._convert_np",
|
||||
"torch.utils.tensorboard._embedding",
|
||||
"torch.utils.tensorboard._onnx_graph",
|
||||
"torch.utils.tensorboard._proto_graph",
|
||||
"torch.utils.tensorboard._pytorch_graph",
|
||||
"torch.utils.tensorboard._utils",
|
||||
"torch_npu.dynamo.torchair._tf_concrete_graph.fx2tf_converter",
|
||||
"torch_npu.dynamo.torchair.core._abi_compat_ge_apis",
|
||||
"torch_npu.dynamo.torchair.core._backend",
|
||||
"torch_npu.dynamo.torchair.core._torchair",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.aten.bernoulli",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.aten.multinomial",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.aten.native_dropout",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.aten.rand",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.aten.randint",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.aten.randn",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.aten.randperm",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.aten.uniform",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.custom.npu_dynamic_quant",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.custom.fused_infer_attention_score",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.experimental.patch_for_hcom_allreduce",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.experimental.hcom_allgather",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.experimental.hcom_allreduce",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.experimental.hcom_alltoall",
|
||||
"torch_npu.dynamo.torchair._ge_concrete_graph.ge_converter.experimental.hcom_broadcast",
|
||||
"torch_npu.utils.collect_hccl_info",
|
||||
|
||||
}
|
||||
|
||||
# No new entries should be added to this list.
|
||||
@@ -495,6 +576,12 @@ class TestPublicBindings(TestCase):
|
||||
"torch.distributed.tensor.parallel",
|
||||
"torch.distributed.utils",
|
||||
"torch.utils.tensorboard",
|
||||
"torch.utils.tensorboard.summary",
|
||||
"torch.utils.tensorboard.writer",
|
||||
"torch.ao.quantization.experimental.fake_quantize",
|
||||
"torch.ao.quantization.experimental.linear",
|
||||
"torch.ao.quantization.experimental.observer",
|
||||
"torch.ao.quantization.experimental.qconfig",
|
||||
}
|
||||
|
||||
errors = []
|
||||
@@ -510,7 +597,8 @@ class TestPublicBindings(TestCase):
|
||||
self.assertEqual("", "\n".join(errors))
|
||||
|
||||
# AttributeError: module 'torch.distributed' has no attribute '_shard'
|
||||
@unittest.skipIf(IS_WINDOWS or IS_JETSON, "Distributed Attribute Error")
|
||||
@unittest.skipIf(IS_WINDOWS or IS_JETSON or IS_MACOS, "Distributed Attribute Error")
|
||||
@skipIfTorchDynamo("Broken and not relevant for now")
|
||||
def test_correct_module_names(self):
|
||||
'''
|
||||
An API is considered public, if its `__module__` starts with `torch.`
|
||||
@@ -523,16 +611,20 @@ class TestPublicBindings(TestCase):
|
||||
`__module__` that start with the current submodule.
|
||||
'''
|
||||
failure_list = []
|
||||
|
||||
|
||||
try:
|
||||
file_abspath = os.path.abspath(__file__)
|
||||
air_path = 'third_party/torchair/torchair/tests/st/allowlist_for_publicAPI.json'
|
||||
with open(
|
||||
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'third_party/torchair/torchair/tests/st/allowlist_for_publicAPI.json')) as json_file_torchair:
|
||||
os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(file_abspath))),
|
||||
air_path)) as json_file_torchair:
|
||||
allow_dict_torchair = json.load(json_file_torchair)
|
||||
update_allow_dict_torchair = {f"torch_npu.dynamo.{key}": value for key, value in allow_dict_torchair.items()}
|
||||
except Exception:
|
||||
update_allow_dict_torchair = {}
|
||||
warnings.warn("if you are debugging UT file in clone repo, please recursively update the torchair submodule")
|
||||
|
||||
warnings.warn(
|
||||
"if you are debugging UT file in clone repo, please recursively update the torchair submodule")
|
||||
|
||||
with open(get_file_path_2(os.path.dirname(os.path.dirname(__file__)),
|
||||
'allowlist_for_publicAPI.json')) as json_file:
|
||||
# no new entries should be added to this allow_dict.
|
||||
@@ -544,13 +636,15 @@ class TestPublicBindings(TestCase):
|
||||
for modname in allow_dict["being_migrated"]:
|
||||
if modname in allow_dict:
|
||||
allow_dict[allow_dict["being_migrated"][modname]] = allow_dict[modname]
|
||||
|
||||
|
||||
if update_allow_dict_torchair:
|
||||
allow_dict.update(update_allow_dict_torchair)
|
||||
|
||||
|
||||
def test_module(modname):
|
||||
try:
|
||||
if "__main__" in modname:
|
||||
if "__main__" in modname or \
|
||||
modname in ["torch_npu.dynamo.torchair.core._backend",
|
||||
"torch_npu.dynamo.torchair.core._torchair"]:
|
||||
return
|
||||
mod = importlib.import_module(modname)
|
||||
except Exception:
|
||||
@@ -564,7 +658,7 @@ class TestPublicBindings(TestCase):
|
||||
# verifies that each public API has the correct module name and naming semantics
|
||||
def check_one_element(elem, modname, mod, *, is_public, is_all):
|
||||
obj = getattr(mod, elem)
|
||||
if not (isinstance(obj, Callable) or inspect.isclass(obj)):
|
||||
if not (isinstance(obj, (Callable, torch.dtype)) or inspect.isclass(obj)):
|
||||
return
|
||||
elem_module = getattr(obj, '__module__', None)
|
||||
# Only used for nice error message below
|
||||
@@ -576,11 +670,11 @@ class TestPublicBindings(TestCase):
|
||||
# if there is a "from foo import a" inside the "bar.py".
|
||||
modname = allow_dict["being_migrated"].get(modname, modname)
|
||||
elem_modname_starts_with_mod = elem_module is not None and \
|
||||
elem_module.startswith(modname) and \
|
||||
'._' not in elem_module
|
||||
elem_module.startswith(modname) and \
|
||||
'._' not in elem_module
|
||||
if not why_not_looks_public and not elem_modname_starts_with_mod:
|
||||
why_not_looks_public = f"because its `__module__` attribute (`{elem_module}`) is not within the " \
|
||||
f"torch library or does not start with the submodule where it is defined (`{modname}`)"
|
||||
f"torch library or does not start with the submodule where it is defined (`{modname}`)"
|
||||
# elem's name must NOT begin with an `_` and it's module name
|
||||
# SHOULD start with it's current module since it's a public API
|
||||
looks_public = not elem.startswith('_') and elem_modname_starts_with_mod
|
||||
@@ -588,7 +682,9 @@ class TestPublicBindings(TestCase):
|
||||
why_not_looks_public = f"because it starts with `_` (`{elem}`)"
|
||||
|
||||
if is_public != looks_public:
|
||||
if f"{modname}.{elem}" in temp_filter:
|
||||
# Skip some APIs which don't meet the guidelines for public API until they are fixed.
|
||||
if f"{modname}.{elem}" in temp_filter or \
|
||||
modname.startswith("torch_npu.dynamo.torchair.ge_concrete_graph"):
|
||||
return
|
||||
|
||||
if modname in allow_dict and elem in allow_dict[modname]:
|
||||
@@ -607,13 +703,13 @@ class TestPublicBindings(TestCase):
|
||||
|
||||
if looks_public:
|
||||
why_looks_public = "it does look public because it follows the rules from the doc above " \
|
||||
"(does not start with `_` and has a proper `__module__`)."
|
||||
"(does not start with `_` and has a proper `__module__`)."
|
||||
fix_looks_public = "make its name start with `_`"
|
||||
else:
|
||||
why_looks_public = why_not_looks_public
|
||||
if not elem_modname_starts_with_mod:
|
||||
fix_looks_public = "make sure the `__module__` is properly set and points to a submodule "\
|
||||
f"of `{modname}`"
|
||||
fix_looks_public = "make sure the `__module__` is properly set and points to a submodule " \
|
||||
f"of `{modname}`"
|
||||
else:
|
||||
fix_looks_public = "remove the `_` at the beginning of the name"
|
||||
|
||||
@@ -638,10 +734,10 @@ class TestPublicBindings(TestCase):
|
||||
if not elem.startswith('_'):
|
||||
check_one_element(elem, modname, mod, is_public=True, is_all=False)
|
||||
|
||||
for _, modname, _ in _discover_path_importables(str(torch.__path__), "torch"):
|
||||
for modname in _find_all_importables(torch):
|
||||
test_module(modname)
|
||||
|
||||
for _, modname, _ in _discover_path_importables(str(torch_npu.__path__), "torch_npu"):
|
||||
for modname in _find_all_importables(torch_npu):
|
||||
test_module(modname)
|
||||
|
||||
test_module('torch')
|
||||
@@ -650,8 +746,8 @@ class TestPublicBindings(TestCase):
|
||||
msg = "All the APIs below do not meet our guidelines for public API from " \
|
||||
"pytorch/wiki/Public-API-definition-and-documentation.\n"
|
||||
msg += "Make sure that everything that is public is expected (in particular that the module " \
|
||||
"has a properly populated `__all__` attribute) and that everything that is supposed to be public " \
|
||||
"does look public (it does not start with `_` and has a `__module__` that is properly populated)."
|
||||
"has a properly populated `__all__` attribute) and that everything that is supposed to be public " \
|
||||
"does look public (it does not start with `_` and has a `__module__` that is properly populated)."
|
||||
msg += "\n\nFull list:\n"
|
||||
msg += "\n".join(map(str, failure_list))
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import torch
|
||||
import torch_npu
|
||||
|
||||
from torch_npu.npu._recovery import check_npu_tensor_is_safe, mark_all_npu_tensor_unsafe, set_npu_tensor_unsafe_check_flag
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class TestNpu(TestCase):
|
||||
|
||||
def test_catch_data_check_error(self):
|
||||
torch.npu.set_device(0)
|
||||
tensor_a = torch.randn(2, 255, 255, device="npu:0")
|
||||
tensor_b = torch.randn(2, 255, 255, device="npu:0")
|
||||
set_npu_tensor_unsafe_check_flag(True)
|
||||
mark_all_npu_tensor_unsafe(0)
|
||||
self.assertFalse(check_npu_tensor_is_safe(tensor_a))
|
||||
self.assertFalse(check_npu_tensor_is_safe(tensor_b))
|
||||
with self.assertRaisesRegex(RuntimeError, "There is unsafe data in the input tensor."):
|
||||
tensor_c = tensor_a + tensor_b
|
||||
|
||||
def test_mark_all_npu_tensors_unsafe_and_update_safe(self):
|
||||
torch.npu.set_device(0)
|
||||
tensor_a = torch.randn(2, 255, 255, device="npu:0")
|
||||
tensor_b = torch.randn(2, 255, 255, device="npu:0")
|
||||
self.assertTrue(check_npu_tensor_is_safe(tensor_a))
|
||||
self.assertTrue(check_npu_tensor_is_safe(tensor_b))
|
||||
# data on device 0 is marked unsafe
|
||||
mark_all_npu_tensor_unsafe(0)
|
||||
self.assertFalse(check_npu_tensor_is_safe(tensor_a))
|
||||
self.assertFalse(check_npu_tensor_is_safe(tensor_b))
|
||||
# release tensor_a and empty again, the data is safe
|
||||
del tensor_a
|
||||
tensor_a_new = torch.randn(2, 255, 255, device="npu:0")
|
||||
self.assertTrue(check_npu_tensor_is_safe(tensor_a_new))
|
||||
# d2d copy can update the unsafe tag to safe
|
||||
tensor_b.copy_(tensor_a_new)
|
||||
self.assertTrue(check_npu_tensor_is_safe(tensor_b))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
@@ -1,6 +1,7 @@
|
||||
import io
|
||||
import os
|
||||
import tempfile
|
||||
import tarfile
|
||||
import argparse
|
||||
|
||||
import torch
|
||||
@@ -274,6 +275,25 @@ class TestSerialization(TestCase):
|
||||
b = torch.tensor([], dtype=other_dtype, device='npu')
|
||||
save_load_check(a, b)
|
||||
|
||||
def test_tarfile_with_weights_only_unpickler(self):
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
path = os.path.join(tmpdir, "mock.tar")
|
||||
with tarfile.open(path, 'w') as tar:
|
||||
tar.add(os.path.devnull, arcname="empty_file")
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
Exception, "Cannot use ``weights_only=True`` with files saved in the legacy .tar format"
|
||||
):
|
||||
torch.load(path, weights_only=True)
|
||||
|
||||
with self.assertRaisesRegex(Exception, "Unsupported operand"):
|
||||
with open(path, "rb") as opened_file:
|
||||
try:
|
||||
with tarfile.open(fileobj=opened_file, mode="r:", format=tarfile.PAX_FORMAT):
|
||||
pass
|
||||
finally:
|
||||
torch.load(opened_file, weights_only=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import itertools
|
||||
import torch
|
||||
from torch.testing import make_tensor
|
||||
from torch.testing._internal.common_utils import DeterministicGuard
|
||||
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
@@ -303,6 +304,13 @@ class TestTensor(TestCase):
|
||||
|
||||
self.assertEqual(res1.to('cpu'), expected.to('cpu'))
|
||||
|
||||
def test_empty_with_deterministic(self):
|
||||
with DeterministicGuard(True, fill_uninitialized_memory=True):
|
||||
empty_tensor = torch.empty(2, 3, 4)
|
||||
empty_strided_tensor = torch.empty_strided((2, 3, 4), (1, 1, 1))
|
||||
self.assertTrue(empty_tensor.isnan().all())
|
||||
self.assertTrue(empty_strided_tensor.isnan().all())
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
|
||||
@@ -248,8 +248,7 @@ class TorchNPUApiTestCase(TestCase):
|
||||
except Exception as e:
|
||||
queue.put(e)
|
||||
|
||||
option = {"MM_BMM_ND_ENABLE": "disable"}
|
||||
torch_npu.npu.set_option(option)
|
||||
torch_npu.npu.current_device()
|
||||
with self.assertRaisesRegex(RuntimeError, "Cannot re-initialize NPU in forked subprocess"):
|
||||
result_queue = multiprocessing.Queue()
|
||||
p = multiprocessing.Process(target=run, args=(result_queue,))
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.multiprocessing as mp
|
||||
import torch.nn as nn
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
import torch.optim as optim
|
||||
from torch.utils.data import DataLoader, TensorDataset
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
os.environ['MASTER_ADDR'] = '127.0.0.1'
|
||||
os.environ['MASTER_PORT'] = '29529'
|
||||
|
||||
|
||||
class SimpleModel(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(SimpleModel, self).__init__()
|
||||
self.fc = torch.nn.Linear(10, 10)
|
||||
|
||||
def forward(self, x):
|
||||
return self.fc(x)
|
||||
|
||||
|
||||
def train(rank, world_size, error_queue):
|
||||
torch.npu.set_device(rank)
|
||||
dist.init_process_group("hccl", rank=rank, world_size=world_size)
|
||||
|
||||
# Create the model and move it to the appropriate device
|
||||
model = SimpleModel().npu()
|
||||
ddp_model = DDP(model, device_ids=[rank])
|
||||
data = torch.randn(100, 10)
|
||||
targets = torch.randn(100, 1)
|
||||
# Create a simple dataset and dataloader
|
||||
dataset = TensorDataset(data, targets)
|
||||
dataloader = DataLoader(dataset, batch_size=10)
|
||||
criterion = nn.MSELoss()
|
||||
optimizer = optim.SGD(ddp_model.parameters(), lr=0.001)
|
||||
|
||||
for epoch in range(2):
|
||||
for i, (inputs, labels) in enumerate(dataloader):
|
||||
try:
|
||||
if rank == 1 and epoch == 0 and i == 2:
|
||||
raise RuntimeError("UCE ERROR")
|
||||
inputs, labels = inputs.to('npu'), labels.to('npu')
|
||||
optimizer.zero_grad()
|
||||
outputs = ddp_model(inputs)
|
||||
loss = criterion(outputs, labels)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
torch.npu.synchronize()
|
||||
|
||||
print(f"Rank {rank}, Epoch [{epoch+1}/2], Iter [{i+1}/10], Loss: {loss.item()}")
|
||||
|
||||
except RuntimeError as e:
|
||||
print(f"Rank {rank}: Caught RuntimeError during training")
|
||||
if "UCE ERROR" in str(e):
|
||||
print(f"Rank {rank}: Detected UCE ERROR")
|
||||
try:
|
||||
error_queue.put((rank, str(e)))
|
||||
continue
|
||||
except Exception as queue_error:
|
||||
raise queue_error
|
||||
if "FORCE STOP" in str(e):
|
||||
try:
|
||||
error_queue.put((rank, str(e)))
|
||||
except Exception as queue_error:
|
||||
raise queue_error
|
||||
else:
|
||||
raise e # Reraise other uncaught exceptions
|
||||
|
||||
# Destroy the process group
|
||||
dist.destroy_process_group()
|
||||
|
||||
|
||||
def monitor(error_queue, stop_event):
|
||||
while not stop_event.is_set():
|
||||
try:
|
||||
rank, error_msg = error_queue.get(timeout=1)
|
||||
if "UCE ERROR" in error_msg:
|
||||
torch_npu.npu.stop_device(0)
|
||||
torch_npu.npu.stop_device(1)
|
||||
if "FORCE STOP" in error_msg:
|
||||
if not torch_npu.npu.check_uce_in_memory(0):
|
||||
torch_npu.npu.restart_device(0)
|
||||
if not torch_npu.npu.check_uce_in_memory(1):
|
||||
torch_npu.npu.restart_device(1)
|
||||
except queue.Empty:
|
||||
continue
|
||||
except Exception as e:
|
||||
raise e
|
||||
|
||||
|
||||
def run(rank, world_size, error_queue):
|
||||
# Create the monitor thread
|
||||
stop_event = threading.Event()
|
||||
monitor_thread = threading.Thread(target=monitor, args=(error_queue, stop_event))
|
||||
monitor_thread.start()
|
||||
|
||||
# Start training
|
||||
train(rank, world_size, error_queue)
|
||||
|
||||
# After training ends, set the stop event and wait for the monitor thread to finish
|
||||
stop_event.set()
|
||||
monitor_thread.join()
|
||||
|
||||
|
||||
def main():
|
||||
world_size = 2
|
||||
ctx = mp.get_context('spawn')
|
||||
error_queue = ctx.Queue(4)
|
||||
mp.spawn(run, args=(world_size, error_queue), nprocs=world_size, join=True)
|
||||
|
||||
|
||||
class TestDistributedTraining(TestCase):
|
||||
|
||||
def test_distributed_training(self):
|
||||
main()
|
||||
@@ -9,7 +9,7 @@ from torch.nn import init
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
import torch_npu.onnx
|
||||
from torch_npu.utils.path_manager import PathManager
|
||||
from torch_npu.utils._path_manager import PathManager
|
||||
|
||||
|
||||
class TestOnnxOps(TestCase):
|
||||
|
||||
@@ -8,7 +8,7 @@ import torch_npu
|
||||
import torch_npu.onnx
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.testing.common_utils import SupportedDevices
|
||||
from torch_npu.utils.path_manager import PathManager
|
||||
from torch_npu.utils._path_manager import PathManager
|
||||
|
||||
# acl format
|
||||
FORMAT_ND = 2
|
||||
@@ -1337,6 +1337,85 @@ class TestOnnxOps(TestCase):
|
||||
export_onnx(onnx_model_name)
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path, onnx_model_name)))
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_wrapper_npu_dynamic_quant(self):
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
|
||||
def forward(self, input_dummy, smooth_scales_dummy):
|
||||
output, scale = torch_npu.npu_dynamic_quant(input_dummy, smooth_scales=smooth_scales_dummy)
|
||||
return output, scale
|
||||
|
||||
def export_onnx(onnx_model_name):
|
||||
input_dummy = torch.rand(4, 1024, 512).uniform_(-3, 3).npu().to(torch.float16)
|
||||
smooth_scales_dummy = torch.rand(512).uniform_(-3, 3).npu().to(torch.float16)
|
||||
model = Model().to("npu")
|
||||
model(input_dummy, smooth_scales_dummy)
|
||||
self.onnx_export(model, (input_dummy, smooth_scales_dummy), onnx_model_name,
|
||||
["input", "smooth_scale_dummy"], ["output", "scale"])
|
||||
onnx_model_name = "model_npu_dynamic_quant.onnx"
|
||||
export_onnx(onnx_model_name)
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path, onnx_model_name)))
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_wrapper_npu_dynamic_quant_with_group_index(self):
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
|
||||
def forward(self, input_dummy, smooth_scales_dummy, group_index_dummy):
|
||||
output, scale = torch_npu.npu_dynamic_quant(input_dummy, smooth_scales=smooth_scales_dummy, group_index=group_index_dummy)
|
||||
return output, scale
|
||||
|
||||
def export_onnx(onnx_model_name):
|
||||
input_dummy = torch.rand(4, 1024, 512).uniform_(-3, 3).npu().to(torch.float16)
|
||||
group_num = 10
|
||||
smooth_scales_dummy = torch.randn((group_num, input_dummy.shape[-1])).uniform_(-3, 3).npu().to(torch.float16)
|
||||
row_num = input_dummy.numel() // input_dummy.shape[-1]
|
||||
group_index_list = []
|
||||
for _ in range(group_num):
|
||||
group_index_list.append(np.random.randint(0, row_num))
|
||||
group_index_list = sorted(group_index_list)
|
||||
group_index_list[-1] = row_num
|
||||
group_index_dummy = torch.tensor(group_index_list).npu().to(torch.int32)
|
||||
model = Model().to("npu")
|
||||
model(input_dummy, smooth_scales_dummy, group_index_dummy)
|
||||
self.onnx_export(model, (input_dummy, smooth_scales_dummy, group_index_dummy), onnx_model_name,
|
||||
["input", "smooth_scale_dummy", "group_index_dummy"], ["output", "scale"])
|
||||
onnx_model_name = "model_npu_dynamic_quant.onnx"
|
||||
export_onnx(onnx_model_name)
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path, onnx_model_name)))
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_wrapper_npu_dynamic_quant_asymmetric(self):
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
|
||||
def forward(self, input_dummy, smooth_scales_dummy, group_index_dummy):
|
||||
output, scale, offset = torch_npu.npu_dynamic_quant_asymmetric(input_dummy, smooth_scales=smooth_scales_dummy, group_index=group_index_dummy)
|
||||
return output, scale, offset
|
||||
|
||||
def export_onnx(onnx_model_name):
|
||||
input_dummy = torch.rand(4, 1024, 512).uniform_(-3, 3).npu().to(torch.float16)
|
||||
group_num = 10
|
||||
smooth_scales_dummy = torch.randn((group_num, input_dummy.shape[-1])).uniform_(-3, 3).npu().to(torch.float16)
|
||||
row_num = input_dummy.numel() // input_dummy.shape[-1]
|
||||
group_index_list = []
|
||||
for _ in range(group_num):
|
||||
group_index_list.append(np.random.randint(0, row_num))
|
||||
group_index_list = sorted(group_index_list)
|
||||
group_index_list[-1] = row_num
|
||||
group_index_dummy = torch.tensor(group_index_list).npu().to(torch.int32)
|
||||
model = Model().to("npu")
|
||||
model(input_dummy, smooth_scales_dummy, group_index_dummy)
|
||||
self.onnx_export(model, (input_dummy, smooth_scales_dummy, group_index_dummy), onnx_model_name,
|
||||
["input", "smooth_scale_dummy", "group_index_dummy"], ["output", "scale", "offset"])
|
||||
onnx_model_name = "model_npu_dynamic_quant_asymmetric.onnx"
|
||||
export_onnx(onnx_model_name)
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path, onnx_model_name)))
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_wrapper_npu_weight_quant_batchmatmul(self):
|
||||
class Model(torch.nn.Module):
|
||||
@@ -1403,6 +1482,32 @@ class TestOnnxOps(TestCase):
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
|
||||
onnx_model_name)))
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_wrapper_npu_group_quant(self):
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
def forward(self, x, scale, group_index, offset):
|
||||
dtype = torch.qint8
|
||||
return torch_npu.npu_group_quant(x, scale, group_index, offset=offset, dst_dtype=dtype)
|
||||
|
||||
def export_onnx(onnx_model_name):
|
||||
S, H, E = 6, 4, 4
|
||||
x_shape, scale_shape, offset_shape = (S, H), (E, H), (1,)
|
||||
x = torch.randn(*x_shape).to(torch.float).npu()
|
||||
scale = torch.randn(*scale_shape).to(torch.float).npu()
|
||||
group_index = torch.tensor([1, 2, 4, 6]).to(torch.int32).npu()
|
||||
offset = torch.tensor(*offset_shape).to(torch.float).npu()
|
||||
model = Model().to("npu")
|
||||
model(x, scale, group_index, offset)
|
||||
self.onnx_export(model, (x, scale, group_index, offset), onnx_model_name)
|
||||
|
||||
onnx_model_name = "model_npu_group_quant.onnx"
|
||||
export_onnx(onnx_model_name)
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
|
||||
onnx_model_name)))
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_wrapper_npu_moe_finalize_routing(self):
|
||||
class Model(torch.nn.Module):
|
||||
@@ -1435,5 +1540,29 @@ class TestOnnxOps(TestCase):
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
|
||||
onnx_model_name)))
|
||||
|
||||
@SupportedDevices(['Ascend910B'])
|
||||
def test_wrapper_npu_gelu(self):
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
|
||||
def forward(self, x):
|
||||
y = torch_npu.npu_gelu(x, approximate="none")
|
||||
return y
|
||||
|
||||
def export_onnx(onnx_model_name):
|
||||
x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]],
|
||||
dtype=torch.float16).npu()
|
||||
model = Model().to("npu")
|
||||
model(x)
|
||||
self.onnx_export(model, (x), onnx_model_name,
|
||||
input_names=["x"],
|
||||
output_names=["y"])
|
||||
|
||||
onnx_model_name = "model_npu_gelu_none.onnx"
|
||||
export_onnx(onnx_model_name)
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
|
||||
onnx_model_name)))
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
|
||||
@@ -232,7 +232,7 @@ class TestFusedOptim(TestCase):
|
||||
for p, p_clone in zip(params, params_clone):
|
||||
if p.grad is not None:
|
||||
self.assertRtolEqual(p.grad, p_clone.grad, prec=1e-3)
|
||||
self.assertRtolEqual(grad_norm, grad_norm_fused, prec=1e-3)
|
||||
self.assertRtolEqual(grad_norm.float(), grad_norm_fused, prec=1e-3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -36,6 +36,7 @@ from torch._dynamo import disable as disable_dynamo
|
||||
from torch.testing._internal.common_device_type import largeTensorTest
|
||||
from torch.optim.optimizer import register_optimizer_step_pre_hook, register_optimizer_step_post_hook
|
||||
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU
|
||||
from torch_npu.testing.common_utils import SupportedDevices
|
||||
|
||||
# load_tests from common_utils is used to automatically filter tests for
|
||||
# sharding on sandcastle. This line silences flake warnings
|
||||
@@ -476,6 +477,7 @@ class TestOptim(TestCase):
|
||||
def _build_params_dict_single(self, weight, bias, **kwargs):
|
||||
return [dict(params=bias, **kwargs)]
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_sgd(self):
|
||||
self._test_basic_cases(
|
||||
lambda weight, bias, maximize, foreach: SGD(
|
||||
@@ -1032,6 +1034,7 @@ class TestOptim(TestCase):
|
||||
optimizer = optimizer_ctor(params, fused=True, **optimizer_params)
|
||||
optimizer.step()
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_adam(self):
|
||||
self._test_basic_cases(
|
||||
lambda weight, bias, maximize, foreach: Adam(
|
||||
@@ -1209,6 +1212,7 @@ class TestOptim(TestCase):
|
||||
Adam, lr=torch.tensor(.001), weight_decay=0.2, amsgrad=True,
|
||||
))
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_adamw(self):
|
||||
self._test_basic_cases(
|
||||
lambda weight, bias, maximize, foreach: AdamW(
|
||||
@@ -1313,6 +1317,7 @@ class TestOptim(TestCase):
|
||||
SparseAdam([{"params": [torch.zeros(3, layout=torch.sparse_coo)]}])
|
||||
|
||||
# ROCm precision is too low to pass this test
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_adadelta(self):
|
||||
self.rel_tol = 4e-3
|
||||
self._test_basic_cases(
|
||||
@@ -1363,6 +1368,7 @@ class TestOptim(TestCase):
|
||||
lambda weight: Adadelta([weight], rho=0.95, weight_decay=1, foreach=foreach)
|
||||
)
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_nadam(self):
|
||||
self._test_basic_cases(
|
||||
lambda weight, bias, foreach: NAdam(
|
||||
@@ -1450,6 +1456,7 @@ class TestOptim(TestCase):
|
||||
)
|
||||
)
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_adagrad(self):
|
||||
self._test_basic_cases(
|
||||
lambda weight, bias, maximize, foreach: Adagrad(
|
||||
@@ -1536,6 +1543,7 @@ class TestOptim(TestCase):
|
||||
)
|
||||
)
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_adamax(self):
|
||||
self._test_basic_cases(
|
||||
lambda weight, bias, maximize, foreach: Adamax(
|
||||
@@ -1572,6 +1580,7 @@ class TestOptim(TestCase):
|
||||
):
|
||||
Adamax(None, lr=1e-2, betas=(0.0, 1.0))
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_radam(self):
|
||||
self._test_basic_cases(
|
||||
lambda weight, bias, foreach: RAdam(
|
||||
@@ -1649,6 +1658,7 @@ class TestOptim(TestCase):
|
||||
)
|
||||
)
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_rmsprop(self):
|
||||
for foreach in (False, True):
|
||||
self._test_basic_cases(
|
||||
@@ -1739,6 +1749,7 @@ class TestOptim(TestCase):
|
||||
with self.assertRaisesRegex(ValueError, "Invalid momentum value: -1.0"):
|
||||
RMSprop(None, lr=1e-2, momentum=-1.0, foreach=foreach)
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_asgd(self):
|
||||
for foreach in (False, True):
|
||||
self._test_basic_cases(
|
||||
@@ -1791,6 +1802,7 @@ class TestOptim(TestCase):
|
||||
|
||||
@skipIfRocm
|
||||
@skipIfTorchDynamo()
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_rprop(self):
|
||||
is_npu_sm86 = torch.npu.is_available()
|
||||
for foreach in (False, True):
|
||||
@@ -1825,6 +1837,7 @@ class TestOptim(TestCase):
|
||||
with self.assertRaisesRegex(ValueError, "Invalid eta values: 1.0, 0.5"):
|
||||
Rprop(None, lr=1e-2, etas=(1.0, 0.5), foreach=foreach)
|
||||
|
||||
@SupportedDevices(["Ascend910B"])
|
||||
def test_lbfgs(self):
|
||||
self._test_basic_cases(
|
||||
lambda weight, bias: LBFGS([weight, bias]), ignore_multidevice=True
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from collections import OrderedDict
|
||||
|
||||
from torch_npu.profiler.analysis.prof_bean.ai_cpu_bean import AiCpuBean
|
||||
from torch_npu.profiler.analysis.prof_bean._ai_cpu_bean import AiCpuBean
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from torch_npu.profiler.analysis.prof_bean.api_statistic_bean import ApiStatisticBean
|
||||
from torch_npu.profiler.analysis.prof_bean._api_statistic_bean import ApiStatisticBean
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from torch_npu.profiler.analysis.prof_bean.event_bean import EventBean
|
||||
from torch_npu.profiler.analysis.prof_bean._event_bean import EventBean
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import random
|
||||
import struct
|
||||
from torch_npu.profiler.analysis.prof_bean._gc_record_bean import GCRecordBean
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class TestGCRecordBean(TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.sample_num = 3
|
||||
cls.test_cases = [cls.generate_sample() for _ in range(cls.sample_num)]
|
||||
|
||||
@classmethod
|
||||
def generate_sample(cls):
|
||||
process_id = random.randint(0, 2**64 - 1)
|
||||
start_ns = random.randint(0, 2**64 - 1)
|
||||
end_ns = random.randint(0, 2**64 - 1)
|
||||
sample = {
|
||||
"data": struct.pack("<3Q", process_id, start_ns, end_ns),
|
||||
"process_id": process_id, "start_ns": start_ns, "end_ns": end_ns
|
||||
}
|
||||
return sample
|
||||
|
||||
def test_property(self):
|
||||
for test_case in self.test_cases:
|
||||
gc_record_bean = GCRecordBean(test_case.get("data"))
|
||||
self.assertEqual(test_case.get("process_id"), gc_record_bean.pid)
|
||||
self.assertEqual(test_case.get("start_ns"), gc_record_bean.ts)
|
||||
self.assertEqual(test_case.get("end_ns") - test_case.get("start_ns"), gc_record_bean.dur)
|
||||
self.assertEqual("GC", gc_record_bean.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -1,4 +1,4 @@
|
||||
from torch_npu.profiler.analysis.prof_bean.ge_memory_record_bean import GeMemoryRecordBean
|
||||
from torch_npu.profiler.analysis.prof_bean._ge_memory_record_bean import GeMemoryRecordBean
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from torch_npu.profiler.analysis.prof_bean.ge_op_memory_bean import GeOpMemoryBean
|
||||
from torch_npu.profiler.analysis.prof_bean._ge_op_memory_bean import GeOpMemoryBean
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from collections import OrderedDict
|
||||
|
||||
from torch_npu.profiler.analysis.prof_bean.l2_cache_bean import L2CacheBean
|
||||
from torch_npu.profiler.analysis.prof_bean._l2_cache_bean import L2CacheBean
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import struct
|
||||
import random
|
||||
|
||||
from torch_npu.profiler.analysis.prof_bean.memory_use_bean import MemoryUseBean
|
||||
from torch_npu.profiler.analysis.prof_common_func.constant import Constant
|
||||
from torch_npu.profiler.analysis.prof_bean._memory_use_bean import MemoryUseBean
|
||||
from torch_npu.profiler.analysis.prof_common_func._constant import Constant
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
@@ -26,13 +26,13 @@ class TestMemoryUsageBean(TestCase):
|
||||
device_type = random.choice([0, 20])
|
||||
data_type = random.choice([0, 9])
|
||||
allocator_type = random.choice([0, 9])
|
||||
device_index = random.randint(0, 2**8 - 1)
|
||||
device_index = random.randint(-2**7, 2**7 - 1)
|
||||
stream_ptr = random.randint(0, 2**63 - 1)
|
||||
thread_id = random.randint(0, 2**64 - 1)
|
||||
process_id = random.randint(0, 2**64 - 1)
|
||||
sample = {
|
||||
Constant.CONSTANT_BYTES: struct.pack(
|
||||
"<7qb3B2Q", ptr, time_ns, alloc_size, total_alloc, total_reserve, total_active, stream_ptr, device_type,
|
||||
"<7q2b2B2Q", ptr, time_ns, alloc_size, total_alloc, total_reserve, total_active, stream_ptr, device_type,
|
||||
device_index, data_type, allocator_type, thread_id, process_id),
|
||||
"ptr": ptr, "time_ns": time_ns, "alloc_size": alloc_size / Constant.B_TO_KB, "alloc_size_for_db": alloc_size,
|
||||
"total_alloc": total_alloc / Constant.B_TO_MB, "total_alloc_for_db": total_alloc,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import random
|
||||
from collections import namedtuple
|
||||
|
||||
from torch_npu.profiler.analysis.prof_bean.node_info_bean import NodeInfoBean
|
||||
from torch_npu.profiler.analysis.prof_common_func.constant import convert_us2ns
|
||||
from torch_npu.profiler.analysis.prof_bean._node_info_bean import NodeInfoBean
|
||||
from torch_npu.profiler.analysis.prof_common_func._constant import convert_us2ns
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import random
|
||||
|
||||
from torch_npu.profiler.analysis.prof_bean.npu_mem_bean import NpuMemoryBean
|
||||
from torch_npu.profiler.analysis.prof_common_func.constant import Constant
|
||||
from torch_npu.profiler.analysis.prof_bean._npu_mem_bean import NpuMemoryBean
|
||||
from torch_npu.profiler.analysis.prof_common_func._constant import Constant
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import struct
|
||||
import random
|
||||
|
||||
from torch_npu.profiler.analysis.prof_bean.op_mark_bean import OpMarkBean
|
||||
from torch_npu.profiler.analysis.prof_common_func.constant import Constant
|
||||
from torch_npu.profiler.analysis.prof_bean._op_mark_bean import OpMarkBean
|
||||
from torch_npu.profiler.analysis.prof_common_func._constant import Constant
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from torch_npu.profiler.analysis.prof_bean.op_statistic_bean import OpStatisticBean
|
||||
from torch_npu.profiler.analysis.prof_bean._op_statistic_bean import OpStatisticBean
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from torch_npu.profiler.analysis.prof_bean.op_summary_bean import OpSummaryBean
|
||||
from torch_npu.profiler.analysis.prof_common_func.csv_headers import CsvHeaders
|
||||
from torch_npu.profiler.analysis.prof_bean._op_summary_bean import OpSummaryBean
|
||||
from torch_npu.profiler.analysis.prof_common_func._csv_headers import CsvHeaders
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import random
|
||||
import struct
|
||||
import string
|
||||
from torch_npu.profiler.analysis.prof_bean._param_tensor_bean import ParamTensorBean
|
||||
from torch_npu.profiler.analysis.prof_common_func._constant import Constant
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class TestParamTensorBean(TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.sample_num = 4
|
||||
cls.test_cases = [cls.generate_sample() for _ in range(cls.sample_num)]
|
||||
|
||||
@staticmethod
|
||||
def generate_param_string():
|
||||
random_strings = []
|
||||
for _ in range(10):
|
||||
param = ''.join(random.choice(string.ascii_letters) for _ in range(10))
|
||||
random_strings.append(param)
|
||||
params = '}'.join(random_strings)
|
||||
return params
|
||||
|
||||
@classmethod
|
||||
def generate_sample(cls):
|
||||
key = random.randint(0, 2**64 - 1)
|
||||
if random.choice([True, False]):
|
||||
module_params = cls.generate_param_string()
|
||||
sample = {
|
||||
Constant.CONSTANT_BYTES: struct.pack("<Q", key),
|
||||
"key": key,
|
||||
1: module_params,
|
||||
}
|
||||
else:
|
||||
optimizer_params = cls.generate_param_string()
|
||||
sample = {
|
||||
Constant.CONSTANT_BYTES: struct.pack("<Q", key),
|
||||
"key": key,
|
||||
2: optimizer_params,
|
||||
}
|
||||
return sample
|
||||
|
||||
def test_property(self):
|
||||
for test_case in self.test_cases:
|
||||
param_tensor_bean = ParamTensorBean(test_case)
|
||||
self.assertEqual(test_case.get("key"), param_tensor_bean.key)
|
||||
module_params = test_case.get(1)
|
||||
optimizer_params = test_case.get(2)
|
||||
if module_params is not None:
|
||||
self.assertEqual(module_params, '}'.join(param_tensor_bean.params.module_params))
|
||||
if optimizer_params is not None:
|
||||
self.assertEqual(optimizer_params, '}'.join(param_tensor_bean.params.optimizer_params))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -1,38 +0,0 @@
|
||||
import random
|
||||
import struct
|
||||
from torch_npu.profiler.analysis.prof_bean.python_module_call_bean import PythonModuleCallBean
|
||||
from torch_npu.profiler.analysis.prof_common_func.constant import Constant
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class TestPythonModuleCallBean(TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.sample_num = 3
|
||||
cls.test_cases = [cls.generate_sample() for _ in range(cls.sample_num)]
|
||||
|
||||
@classmethod
|
||||
def generate_sample(cls):
|
||||
idx = random.randint(0, 2**64 - 1)
|
||||
thread_id = random.randint(0, 2**64 - 1)
|
||||
process_id = random.randint(0, 2**64 - 1)
|
||||
sample = {
|
||||
Constant.CONSTANT_BYTES: struct.pack("<3Q", idx, thread_id, process_id),
|
||||
"idx": idx, "thread_id": thread_id, "process_id": process_id
|
||||
}
|
||||
return sample
|
||||
|
||||
def test_property(self):
|
||||
for test_case in self.test_cases:
|
||||
python_mudole_call_bean = PythonModuleCallBean(test_case)
|
||||
self.assertEqual(test_case.get("idx"), python_mudole_call_bean.idx)
|
||||
self.assertEqual(test_case.get("thread_id"), python_mudole_call_bean.tid)
|
||||
self.assertEqual(test_case.get("process_id"), python_mudole_call_bean.pid)
|
||||
self.assertEqual(test_case.get("module_uid", ""), python_mudole_call_bean.module_uid)
|
||||
self.assertEqual(test_case.get("module_name", ""), python_mudole_call_bean.module_name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
+9
-7
@@ -1,11 +1,11 @@
|
||||
import random
|
||||
import struct
|
||||
from torch_npu.profiler.analysis.prof_bean.python_func_call_bean import PythonFuncCallBean
|
||||
from torch_npu.profiler.analysis.prof_common_func.constant import Constant
|
||||
from torch_npu.profiler.analysis.prof_bean._python_tracer_func_bean import PythonTracerFuncBean
|
||||
from torch_npu.profiler.analysis.prof_common_func._constant import Constant
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class TestPythonFuncCallBean(TestCase):
|
||||
class TestPythonTracerFuncBean(TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
@@ -18,21 +18,23 @@ class TestPythonFuncCallBean(TestCase):
|
||||
start_ns = random.randint(0, 2**64 - 1)
|
||||
thread_id = random.randint(0, 2**64 - 1)
|
||||
process_id = random.randint(0, 2**64 - 1)
|
||||
key = random.randint(0, 2**64 - 1)
|
||||
trace_tag = random.randint(0, 3)
|
||||
sample = {
|
||||
Constant.CONSTANT_BYTES: struct.pack("<3QB", start_ns, thread_id, process_id, trace_tag),
|
||||
"start_ns": start_ns, "thread_id": thread_id, "process_id": process_id, "trace_tag": trace_tag
|
||||
"data": struct.pack("<4QB", start_ns, thread_id, process_id, key, trace_tag),
|
||||
"start_ns": start_ns, "thread_id": thread_id, "process_id": process_id,
|
||||
"key": key, "trace_tag": trace_tag
|
||||
}
|
||||
return sample
|
||||
|
||||
def test_property(self):
|
||||
for test_case in self.test_cases:
|
||||
python_func_call_bean = PythonFuncCallBean(test_case)
|
||||
python_func_call_bean = PythonTracerFuncBean(test_case.get("data"))
|
||||
self.assertEqual(test_case.get("start_ns"), python_func_call_bean.start_ns)
|
||||
self.assertEqual(test_case.get("thread_id"), python_func_call_bean.tid)
|
||||
self.assertEqual(test_case.get("process_id"), python_func_call_bean.pid)
|
||||
self.assertEqual(test_case.get("trace_tag"), python_func_call_bean.trace_tag)
|
||||
self.assertEqual(test_case.get("name", ""), python_func_call_bean.name)
|
||||
self.assertEqual(test_case.get("key"), python_func_call_bean.key)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -0,0 +1,36 @@
|
||||
import random
|
||||
import struct
|
||||
import string
|
||||
from torch_npu.profiler.analysis.prof_bean._python_tracer_hash_bean import PythonTracerHashBean
|
||||
from torch_npu.profiler.analysis.prof_common_func._constant import Constant
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
class TestPythonTracerHashBean(TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.sample_num = 3
|
||||
cls.test_cases = [cls.generate_sample() for _ in range(cls.sample_num)]
|
||||
|
||||
@classmethod
|
||||
def generate_sample(cls):
|
||||
key = random.randint(0, 2**64 - 1)
|
||||
value = ''.join(random.choice(string.ascii_letters) for _ in range(10))
|
||||
value_idx = 1
|
||||
sample = {
|
||||
Constant.CONSTANT_BYTES: struct.pack("<Q", key),
|
||||
"key": key, value_idx: value, "value": value
|
||||
}
|
||||
return sample
|
||||
|
||||
def test_property(self):
|
||||
for test_case in self.test_cases:
|
||||
python_tracer_hash_bean = PythonTracerHashBean(test_case)
|
||||
self.assertEqual(test_case.get("key"), python_tracer_hash_bean.key)
|
||||
self.assertEqual(test_case.get("value"), python_tracer_hash_bean.value)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -1,4 +1,4 @@
|
||||
from torch_npu.profiler.analysis.prof_bean.step_trace_bean import StepTraceBean
|
||||
from torch_npu.profiler.analysis.prof_bean._step_trace_bean import StepTraceBean
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import random
|
||||
import struct
|
||||
|
||||
from torch_npu.profiler.analysis.prof_bean.torch_op_bean import TorchOpBean
|
||||
from torch_npu.profiler.analysis.prof_common_func.constant import Constant
|
||||
from torch_npu.profiler.analysis.prof_bean._torch_op_bean import TorchOpBean
|
||||
from torch_npu.profiler.analysis.prof_common_func._constant import Constant
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
@@ -23,17 +23,18 @@ class TestTorchOpBean(TestCase):
|
||||
start_thread_id = random.randint(0, 2**64 - 1)
|
||||
end_thread_id = random.randint(0, 2**64 - 1)
|
||||
forward_thread_id = random.randint(0, 2**64 - 1)
|
||||
scope = random.randint(0, 2**8 - 1)
|
||||
is_async = random.choice([0, 1])
|
||||
name_id = random.randint(0, 100)
|
||||
|
||||
sample = {
|
||||
Constant.CONSTANT_BYTES: struct.pack(
|
||||
"<3q4Q?", start_ns, end_ns, sequence_number, process_id,
|
||||
start_thread_id, end_thread_id, forward_thread_id, is_async),
|
||||
"<3q4QB?", start_ns, end_ns, sequence_number, process_id,
|
||||
start_thread_id, end_thread_id, forward_thread_id, scope, is_async),
|
||||
"start_ns": start_ns, "end_ns": end_ns, "sequence_number": sequence_number,
|
||||
"process_id": process_id, "start_thread_id": start_thread_id, "end_thread_id": end_thread_id,
|
||||
"forward_thread_id": forward_thread_id, "is_async": is_async, "dur": end_ns - start_ns,
|
||||
"args": {Constant.SEQUENCE_UNMBER: sequence_number, Constant.FORWORD_THREAD_ID: forward_thread_id}
|
||||
"forward_thread_id": forward_thread_id, "scope": scope, "is_async": is_async, "dur": end_ns - start_ns,
|
||||
"args": {Constant.SEQUENCE_NUMBER: sequence_number, Constant.FORWARD_THREAD_ID: forward_thread_id}
|
||||
}
|
||||
|
||||
return sample
|
||||
@@ -43,6 +44,7 @@ class TestTorchOpBean(TestCase):
|
||||
torch_op_bean = TorchOpBean(test_case)
|
||||
self.assertEqual(test_case.get("process_id"), torch_op_bean.pid)
|
||||
self.assertEqual(test_case.get("start_thread_id"), torch_op_bean.tid)
|
||||
self.assertEqual(test_case.get("scope"), torch_op_bean.scope)
|
||||
self.assertEqual(test_case.get("name", ""), torch_op_bean.name)
|
||||
self.assertEqual(test_case.get("start_ns"), torch_op_bean.ts)
|
||||
self.assertEqual(test_case.get("dur"), torch_op_bean.dur)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import unittest
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from torch_npu.profiler.analysis.prof_bean.torch_op_node import TorchOpNode
|
||||
from torch_npu.profiler.analysis.prof_common_func.constant import Constant
|
||||
from torch_npu.profiler.analysis.prof_bean._torch_op_node import TorchOpNode
|
||||
from torch_npu.profiler.analysis.prof_common_func._constant import Constant
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user