Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f88a00a21a | ||
|
|
56f3bb219b | ||
|
|
a538497f59 | ||
|
|
19cd190e3f | ||
|
|
0b2ab39356 | ||
|
|
603afe6766 | ||
|
|
ae8127baa1 | ||
|
|
4ecb83fbce | ||
|
|
512ee2b65b | ||
|
|
f5e0cc1f07 | ||
|
|
e926388805 | ||
|
|
2d4d1e5a1b | ||
|
|
4fde9fa1b9 | ||
|
|
3cec1c1cfe | ||
|
|
f532c9b752 | ||
|
|
906726d910 | ||
|
|
d36d0ec290 | ||
|
|
77b6fb806e | ||
|
|
cb1d8a2c28 | ||
|
|
42af859b44 | ||
|
|
38a0e62a3e | ||
|
|
ddee779f77 | ||
|
|
756dbca545 | ||
|
|
d4626a9fa0 | ||
|
|
28a1634b9a | ||
|
|
46667a35f1 | ||
|
|
31a1abcedd | ||
|
|
4e10b42dcb | ||
|
|
68935fd96f | ||
|
|
79131f0ed7 | ||
|
|
195973bfaa | ||
|
|
7e42915d22 | ||
|
|
6fb2529e7b | ||
|
|
026318d011 | ||
|
|
0c84bc5ac1 | ||
|
|
170b08e0d2 | ||
|
|
0fb902e015 | ||
|
|
06b60acb9e | ||
|
|
0f17858241 | ||
|
|
24bb368bcc | ||
|
|
95ae807b6d | ||
|
|
f118eb1083 | ||
|
|
7e09a22788 | ||
|
|
144bc77742 | ||
|
|
5122896b91 | ||
|
|
32d70b4038 | ||
|
|
5663059394 | ||
|
|
96b8b009a2 | ||
|
|
6900aae386 | ||
|
|
6523535ba9 | ||
|
|
9f68ec2cbb | ||
|
|
8eddb4b6a3 | ||
|
|
d338cd358c | ||
|
|
938fb1f720 | ||
|
|
7bef164a6d | ||
|
|
df2f34de5b | ||
|
|
fb8e4aaf13 | ||
|
|
416303682f | ||
|
|
2383422b68 | ||
|
|
c779c72c50 | ||
|
|
750ff7fe4f | ||
|
|
81d672880e | ||
|
|
4afddfcb8f | ||
|
|
0e515a7f2a | ||
|
|
219738354c | ||
|
|
185b7b4e0a | ||
|
|
0a0b9bb852 | ||
|
|
c007ee1cbe | ||
|
|
f7357be81e | ||
|
|
f3735572a7 | ||
|
|
adc1109bd6 | ||
|
|
a138577098 | ||
|
|
d8bdf54268 | ||
|
|
8e08b7fb4c | ||
|
|
7f787ff8d2 | ||
|
|
dd8769799b | ||
|
|
a27540b719 | ||
|
|
af5e0f5dd9 | ||
|
|
68f90c1b80 | ||
|
|
12068adce8 | ||
|
|
0413b53608 | ||
|
|
1d6fc4fdcc | ||
|
|
fa1a698e7d | ||
|
|
eb13e4af2b | ||
|
|
569eacd08c | ||
|
|
64d507f32c | ||
|
|
fd87b7f678 | ||
|
|
ef47a4d8e3 | ||
|
|
59bf37805f | ||
|
|
6577976e8d | ||
|
|
8ce20fe213 | ||
|
|
ae965f2075 | ||
|
|
11fc2307fb | ||
|
|
3e5d81d509 | ||
|
|
7d4457922b | ||
|
|
bdae65f5b1 | ||
|
|
181eec7fbc | ||
|
|
4dc80c4a96 | ||
|
|
1ce31cec98 | ||
|
|
47285663c7 | ||
|
|
ff1a542a04 | ||
|
|
5078ed052f | ||
|
|
c4965940ae | ||
|
|
dffec8246c | ||
|
|
e0c1ae859c | ||
|
|
41814ccec9 | ||
|
|
517633ddab | ||
|
|
88d08ed069 | ||
|
|
805722b01a | ||
|
|
e14cc14023 | ||
|
|
a5ac48d964 | ||
|
|
223f14ac04 | ||
|
|
cb5e7854c5 | ||
|
|
ecb82ae3f0 | ||
|
|
adf91cf9cc | ||
|
|
050a42f571 | ||
|
|
ccd25e5ceb | ||
|
|
e7cdb7395c | ||
|
|
2bc784b27d | ||
|
|
30ea9fc4e3 | ||
|
|
58416fc03b | ||
|
|
4356839fd9 | ||
|
|
4618bf1eec | ||
|
|
86773348c6 | ||
|
|
fb86cd4adb | ||
|
|
71ec59af34 | ||
|
|
e2cdd05214 | ||
|
|
33274e2f7f | ||
|
|
c98e57cf82 | ||
|
|
1c3af9d9d7 | ||
|
|
4cb2bd9c14 | ||
|
|
85efdd3570 | ||
|
|
f49a5963f5 | ||
|
|
6d4beb57d4 | ||
|
|
3eabfefbda | ||
|
|
4eba282bf6 | ||
|
|
bd1768767c | ||
|
|
a0f5177f80 | ||
|
|
4f9dad9047 | ||
|
|
d10347340e | ||
|
|
b09d3b94d6 | ||
|
|
98638b44ec | ||
|
|
775e0998fa | ||
|
|
ec8f8d9baf | ||
|
|
aad94342bf | ||
|
|
2c5467d884 | ||
|
|
9af82239b1 | ||
|
|
0d99ec1c95 | ||
|
|
553fee0239 | ||
|
|
fee91ebf65 | ||
|
|
cc3103a295 | ||
|
|
3b45846a51 | ||
|
|
318c393bce | ||
|
|
2d4d9718bd | ||
|
|
39b204a6e6 | ||
|
|
f4c6b6094e | ||
|
|
430c5c2f94 | ||
|
|
418b3a3984 | ||
|
|
9ed6e41198 | ||
|
|
97264f66ec | ||
|
|
fd1a22a26c | ||
|
|
604e8415a4 | ||
|
|
a312794efe | ||
|
|
ebc77698bd | ||
|
|
f2fffab19a | ||
|
|
53fbed4d35 | ||
|
|
85bca4946f | ||
|
|
920d88ac28 | ||
|
|
85728a332d | ||
|
|
7275a94942 | ||
|
|
e57a52fe9c | ||
|
|
0ff9946e9d | ||
|
|
6ae13a31b0 | ||
|
|
b5d7ba5d1a | ||
|
|
bbcd9ef109 | ||
|
|
0bc66c1b6c | ||
|
|
ce16d822bb | ||
|
|
66e7cb5350 | ||
|
|
8917a72c3a | ||
|
|
4497ba11d4 | ||
|
|
6603a558a1 | ||
|
|
90cbf43488 | ||
|
|
28e1d943b9 | ||
|
|
ab58ce6967 | ||
|
|
4988421705 | ||
|
|
e46b4eafeb | ||
|
|
b920df19a5 | ||
|
|
1acb807f7f | ||
|
|
43398f6f8c | ||
|
|
612682fa6d | ||
|
|
761c973adf | ||
|
|
0325389d2b | ||
|
|
00e313fd85 | ||
|
|
9c840a2ed9 | ||
|
|
2ea2d86e55 | ||
|
|
2297e73ff8 | ||
|
|
e034df7a08 | ||
|
|
a858d2119e | ||
|
|
329b39a5a9 | ||
|
|
ac22be1ed3 | ||
|
|
59f16c912b | ||
|
|
06c19d2e52 | ||
|
|
fc10134eb9 | ||
|
|
6ba29b2227 | ||
|
|
64093abaf5 | ||
|
|
b6052cb85c | ||
|
|
69b059e791 | ||
|
|
d570dbb582 | ||
|
|
2e5ec43567 | ||
|
|
00368d6dd7 | ||
|
|
951e379132 | ||
|
|
3a8ee9a901 | ||
|
|
7ede7dc326 | ||
|
|
712ce80a78 | ||
|
|
67cd14794d | ||
|
|
392279649d | ||
|
|
98745abe88 | ||
|
|
b0aafbd4e8 | ||
|
|
244c83b81e | ||
|
|
a3160d129f | ||
|
|
5cf7c55de9 | ||
|
|
ff81f207ee | ||
|
|
3e74e3328c | ||
|
|
75d4714f72 | ||
|
|
ab148143cb | ||
|
|
68cdd57237 | ||
|
|
706ce76ea4 | ||
|
|
81435460ae | ||
|
|
5ef9627a0e | ||
|
|
d281876507 | ||
|
|
4201aebfda | ||
|
|
71265b10eb | ||
|
|
e043d6e451 | ||
|
|
2ae40194f5 | ||
|
|
bd2df86313 | ||
|
|
77a9c27900 | ||
|
|
d7b5bd636a | ||
|
|
ec3c015fe1 | ||
|
|
ab22ff657e | ||
|
|
9554cf77e6 | ||
|
|
908b3e8694 | ||
|
|
13b0dce9bd | ||
|
|
0c8e6d4213 | ||
|
|
2393293c81 | ||
|
|
748a00159f | ||
|
|
34c9f17eba | ||
|
|
f6ee0d33ef | ||
|
|
354f47aca6 | ||
|
|
0c4aa35681 | ||
|
|
d4b45042c0 | ||
|
|
43708a8bf6 | ||
|
|
4b94310443 | ||
|
|
3356f3701f | ||
|
|
a7e7320808 | ||
|
|
1c327d96a6 | ||
|
|
16d27b43ae | ||
|
|
14ce47a51d | ||
|
|
795e527ed7 | ||
|
|
b010233bd0 | ||
|
|
08f17a4dde | ||
|
|
7b5d2421eb | ||
|
|
56d1f2db3d | ||
|
|
171bd21ad8 | ||
|
|
54d1f16da8 | ||
|
|
be0630c160 | ||
|
|
8a819be35e | ||
|
|
d056930764 | ||
|
|
c833b916c2 | ||
|
|
4df3b3f678 | ||
|
|
afb69ac33e | ||
|
|
0538236b1e | ||
|
|
1a069561fc | ||
|
|
e377dc0283 | ||
|
|
54b0f7126b | ||
|
|
72e41b8e47 | ||
|
|
58cb4bedea | ||
|
|
5287176deb | ||
|
|
ccb2200a1b | ||
|
|
bf754d7bc0 | ||
|
|
5340ee6f6c | ||
|
|
f5b6d26c23 | ||
|
|
e536e35617 | ||
|
|
dab155b170 | ||
|
|
db24b9a054 | ||
|
|
b53ec7fec9 | ||
|
|
baa99a0507 | ||
|
|
73c2db15cd | ||
|
|
81cd832b5e | ||
|
|
a86b5f46ec | ||
|
|
b595c7afdc | ||
|
|
9f6f8220b6 | ||
|
|
7cdc9414b3 | ||
|
|
9f1067bc35 | ||
|
|
4a314b171f | ||
|
|
6bc8c786a8 | ||
|
|
ef0c0f4c84 | ||
|
|
a42e50c0f9 | ||
|
|
f3fbe062e4 | ||
|
|
fe17155b17 | ||
|
|
e019e2c0ea | ||
|
|
b5f0714ebc | ||
|
|
8da378d72f | ||
|
|
1ca96c3887 | ||
|
|
cf93f428f7 | ||
|
|
efcb27cfe3 | ||
|
|
0ec39852ae | ||
|
|
153490f0ed | ||
|
|
4789b3c28e | ||
|
|
3fc05d486d | ||
|
|
cbd0cc73c8 | ||
|
|
d0e35c02a9 | ||
|
|
80cd4b4a37 | ||
|
|
a83dec1111 | ||
|
|
3caec95134 | ||
|
|
6d5791e967 | ||
|
|
a901d5a9b9 | ||
|
|
fcf28becb2 | ||
|
|
08acf60c3c | ||
|
|
4088f0b895 | ||
|
|
b73b4054ae | ||
|
|
51c61ec9cb | ||
|
|
19740f7a75 | ||
|
|
6a98a54278 | ||
|
|
40b90290a2 | ||
|
|
4fedd8df68 | ||
|
|
30db38ddca | ||
|
|
01554314d1 | ||
|
|
3299eceb18 | ||
|
|
81a665e09e | ||
|
|
3c268615ce | ||
|
|
500b50ff95 | ||
|
|
8491713a91 | ||
|
|
cdafc4de0e | ||
|
|
ac8caded56 | ||
|
|
6e4e84ac76 | ||
|
|
7439ae5cce | ||
|
|
2577dcf72e | ||
|
|
8ffaadd68a | ||
|
|
bfa4a58efc | ||
|
|
1f1765f4b3 | ||
|
|
8e01258655 | ||
|
|
e672675d13 | ||
|
|
218ea4a965 | ||
|
|
694e7ed93b | ||
|
|
6311d0d748 | ||
|
|
3c637ec022 | ||
|
|
c602fd97cb | ||
|
|
ea7b131819 | ||
|
|
019e7cb16e | ||
|
|
4a079401b5 | ||
|
|
863ca112de | ||
|
|
083d8b1db2 | ||
|
|
69c4092660 | ||
|
|
32d69d12a9 | ||
|
|
91c840476d | ||
|
|
9d7a6e248e | ||
|
|
0620f02bfb | ||
|
|
fb396531f4 | ||
|
|
0fa9e7353f | ||
|
|
bffaedbbac | ||
|
|
ad167affff | ||
|
|
1871cb1934 | ||
|
|
769ff87a21 | ||
|
|
31beaac68e | ||
|
|
9da3639213 | ||
|
|
668e45e5d4 | ||
|
|
7457160ace | ||
|
|
22b276758e | ||
|
|
c47920038b | ||
|
|
e857d105b9 | ||
|
|
214b62590c | ||
|
|
a894f74ec4 | ||
|
|
676cfa48fd | ||
|
|
e63811e40f | ||
|
|
ef3204b2f7 | ||
|
|
c73ae1d729 | ||
|
|
ed285bdf7e | ||
|
|
05a2f2e587 | ||
|
|
87229b5a06 | ||
|
|
07750c3eae | ||
|
|
0b5ebb435b | ||
|
|
899a56efb9 | ||
|
|
2475770ccf | ||
|
|
8b036cd83b | ||
|
|
4605b0db1b | ||
|
|
b0bc2fe45d | ||
|
|
d6f7030a20 | ||
|
|
4416abba79 | ||
|
|
905996ae5c | ||
|
|
8d776ee382 | ||
|
|
75d1234976 | ||
|
|
400f4c9856 | ||
|
|
aba9fb6683 | ||
|
|
8e2d27d5c3 | ||
|
|
5b188b0049 | ||
|
|
4231c4a323 | ||
|
|
30c096e611 | ||
|
|
1ae147d00a | ||
|
|
a1d5d4bbe9 | ||
|
|
2fbf703b78 | ||
|
|
3232a6cba5 | ||
|
|
571201df7f | ||
|
|
8b63680b3b | ||
|
|
42cd0a401e | ||
|
|
59393c2526 | ||
|
|
a4f5dd6afa | ||
|
|
49f0951c8d | ||
|
|
316f285e5a | ||
|
|
beec80f38f | ||
|
|
7f90d27c8b | ||
|
|
394b9560cc | ||
|
|
24f15345ca | ||
|
|
b5c0fe5d0a | ||
|
|
0dc985df9d | ||
|
|
578956016c | ||
|
|
ca5852a72d | ||
|
|
8c97c4fbc5 | ||
|
|
c8d43c1b02 | ||
|
|
c24bf7125d | ||
|
|
22d30c44e6 | ||
|
|
97c0d5a5e8 | ||
|
|
3dc216c21e | ||
|
|
8a287fd8af | ||
|
|
a29abc7fda | ||
|
|
f25131f3da | ||
|
|
56c6b810d7 | ||
|
|
17b0f999b6 | ||
|
|
d0aec24385 | ||
|
|
99910676c5 | ||
|
|
62dfc27033 | ||
|
|
3ce7bb411a | ||
|
|
98af8a6276 | ||
|
|
36006a1528 | ||
|
|
e2981565e8 | ||
|
|
c586e665fc | ||
|
|
af608371b5 | ||
|
|
b7268705e3 | ||
|
|
821fcbdca1 | ||
|
|
af2be91571 | ||
|
|
0bb47aa178 | ||
|
|
f6c27b8a74 | ||
|
|
fcdeee2fdd | ||
|
|
87dedabbf4 | ||
|
|
d9e976a44e | ||
|
|
fe7916bbab | ||
|
|
ca35b63288 | ||
|
|
7e4c91f644 | ||
|
|
8fafe8d7a0 | ||
|
|
2944aac13a | ||
|
|
77b8f70814 | ||
|
|
fbab1d9c05 | ||
|
|
b4c130b56a | ||
|
|
84908800b4 | ||
|
|
984f693765 | ||
|
|
1fdaacfd07 | ||
|
|
41a9302ecc | ||
|
|
795bff9363 | ||
|
|
d4836c9240 | ||
|
|
88655029be | ||
|
|
531a74a666 | ||
|
|
280acf6eaa | ||
|
|
91bde61256 | ||
|
|
631c7609dd | ||
|
|
5ab30c2515 | ||
|
|
3fee9987f4 | ||
|
|
5b786a6a16 | ||
|
|
db67635aeb | ||
|
|
0a094266b6 | ||
|
|
f33a7b3475 | ||
|
|
51744de4ad | ||
|
|
2a7b1fb710 | ||
|
|
042b81869f | ||
|
|
2f025c65b3 | ||
|
|
44a98a83e7 | ||
|
|
6230586449 | ||
|
|
95e74b625c | ||
|
|
1a84ad2e71 | ||
|
|
c44a8447fd | ||
|
|
8910373487 | ||
|
|
6b329bb814 | ||
|
|
222da74df6 | ||
|
|
0374a18c67 | ||
|
|
a8327275b8 | ||
|
|
acac9814d1 | ||
|
|
9bafbf675e | ||
|
|
e3182552a0 | ||
|
|
7a787674c3 | ||
|
|
a3b062177f | ||
|
|
bb82c454bf | ||
|
|
0a2771537b | ||
|
|
a4b44ed58c | ||
|
|
2ea5c9c837 | ||
|
|
ed40d2c200 | ||
|
|
b018bb5841 | ||
|
|
45f5eb2537 | ||
|
|
f5d67aeafa | ||
|
|
06e197ed6d | ||
|
|
ab0ab22b51 | ||
|
|
bcae12b756 | ||
|
|
a65f3caff4 | ||
|
|
17836e0a06 | ||
|
|
640b13d02d | ||
|
|
2c8c588d3e | ||
|
|
bc6dd05a85 | ||
|
|
8efad6d006 | ||
|
|
fc7ca3f80f | ||
|
|
234bbae07e | ||
|
|
56813b97e5 | ||
|
|
4cb3be0e56 | ||
|
|
5c4c4050a4 | ||
|
|
e60830426a | ||
|
|
f7d498b87a | ||
|
|
0a430d4c16 | ||
|
|
45b14f68e5 | ||
|
|
64ddb54721 | ||
|
|
23ea30c62f | ||
|
|
cd97940976 | ||
|
|
afe81a0e2c | ||
|
|
dce1b6051b | ||
|
|
dfafe1c14e | ||
|
|
b4c0182ec5 | ||
|
|
c09de005ef | ||
|
|
5746fcd494 | ||
|
|
16a3474fd2 | ||
|
|
467386d15d | ||
|
|
7296246129 | ||
|
|
761e5be7fc | ||
|
|
ae60e160c4 | ||
|
|
e1a81306fe | ||
|
|
e2df607544 | ||
|
|
91e02c1dca | ||
|
|
af062aeb4d | ||
|
|
b5ba3440c2 | ||
|
|
3f44203970 | ||
|
|
a3da1ccaa9 | ||
|
|
bb376ee271 | ||
|
|
52334374d4 | ||
|
|
df3424a747 | ||
|
|
3038116634 | ||
|
|
71cf0f2e33 | ||
|
|
97a11afe8e | ||
|
|
acb9916e6a | ||
|
|
50fe7a9dc0 | ||
|
|
802e51b486 | ||
|
|
e9ba56a881 | ||
|
|
e806e7bb3f | ||
|
|
cf29817301 | ||
|
|
caa8f21b20 | ||
|
|
df8017d8b8 | ||
|
|
0644764af0 | ||
|
|
54c9eb2adc | ||
|
|
fb39e0fe98 | ||
|
|
eb958f2cb8 | ||
|
|
a626b9d7ac | ||
|
|
488a00a41f | ||
|
|
9d28bb2e81 | ||
|
|
f0e0ee0600 | ||
|
|
4572f6dad5 | ||
|
|
4fa43712a3 | ||
|
|
fd7b68341a | ||
|
|
8aecacde9d | ||
|
|
1cad7d98f7 | ||
|
|
7f2eb6dd32 | ||
|
|
d05791a6f4 | ||
|
|
27c2d44b4c | ||
|
|
28011235ef | ||
|
|
e6dbc75118 | ||
|
|
02c9a1375a | ||
|
|
d9497766b9 | ||
|
|
9c9db5b9ca | ||
|
|
b5136487ce | ||
|
|
f198c39549 | ||
|
|
d6ce1ee4ee | ||
|
|
d9cd088abd | ||
|
|
0349431952 | ||
|
|
6829a63297 | ||
|
|
bd5d280d26 | ||
|
|
c894bde4c9 | ||
|
|
531b053d07 | ||
|
|
637b4e56a8 | ||
|
|
c981fd9a90 | ||
|
|
c8be8e3201 | ||
|
|
11e79f720e | ||
|
|
0c361fce90 | ||
|
|
d229ec138f | ||
|
|
f1d92c84fc | ||
|
|
5b86087213 | ||
|
|
98e8f254b2 | ||
|
|
0b87a5f86d | ||
|
|
ae3b041f2c | ||
|
|
33483dee61 | ||
|
|
e4bea2a1e6 | ||
|
|
d5e9beefa3 | ||
|
|
59dc1c08b9 | ||
|
|
0496cae434 | ||
|
|
b0b6c9aeef | ||
|
|
f0f5ded9af | ||
|
|
c75e3453b4 | ||
|
|
cbee7908e7 | ||
|
|
eaf51789a3 | ||
|
|
743f85fd6a | ||
|
|
e9a88148e4 | ||
|
|
79f97d6faf | ||
|
|
3008e810f0 | ||
|
|
86f2fb343b | ||
|
|
acd1344110 | ||
|
|
0f54bc31c7 | ||
|
|
541b06723e | ||
|
|
e4881465bb | ||
|
|
1235e10dd7 | ||
|
|
35d13ad2b6 | ||
|
|
4f24433e65 | ||
|
|
6865f903bb | ||
|
|
a083f19a2e | ||
|
|
d10e745dfe | ||
|
|
e29cdc0ce0 | ||
|
|
e0a6954d09 | ||
|
|
84277629bf | ||
|
|
13e74f596e | ||
|
|
1cc15c74db | ||
|
|
96cdca2b87 | ||
|
|
c39619f3b6 | ||
|
|
38b321ea66 | ||
|
|
4c8fbf775f | ||
|
|
5854088d63 | ||
|
|
36592dd2d6 | ||
|
|
e235eaea66 | ||
|
|
b9f77ee6e2 | ||
|
|
2bc88f9c80 | ||
|
|
37ed15eb08 | ||
|
|
40828f1a8f | ||
|
|
5e0c24e900 | ||
|
|
0e2d101ad1 | ||
|
|
7bda7fa158 | ||
|
|
173a0a53bd | ||
|
|
cddeb21aeb | ||
|
|
58a3cd26df | ||
|
|
ca830defcc | ||
|
|
91ad5e0aa4 | ||
|
|
7e50d454bf | ||
|
|
8fe250db9a | ||
|
|
254e2075a3 | ||
|
|
4f04bb0202 | ||
|
|
dc33615bdc | ||
|
|
df1b14b3e3 | ||
|
|
e06786ec83 | ||
|
|
f722beb774 | ||
|
|
c097719dfc | ||
|
|
22c1dfb7fd | ||
|
|
766005b953 | ||
|
|
6dccf9529c | ||
|
|
d8cd9955e9 | ||
|
|
69af833543 | ||
|
|
053e08f354 | ||
|
|
43a8bc21e8 | ||
|
|
c5f54b8e80 | ||
|
|
70d068b6ee | ||
|
|
8305c7e681 | ||
|
|
f72dcf4673 | ||
|
|
06b1fb68bf | ||
|
|
79512f48d3 | ||
|
|
548ca2002d | ||
|
|
2d31aa3017 | ||
|
|
2d3042ae0f | ||
|
|
e07fe4f7b9 | ||
|
|
2df5874875 | ||
|
|
07ceee671c | ||
|
|
6884d31656 | ||
|
|
5e02263aba | ||
|
|
be839d5f38 | ||
|
|
99aa79ff5c | ||
|
|
ab2d1b148f | ||
|
|
6384e7f4d4 | ||
|
|
9c85d508e7 | ||
|
|
970f14f4ba | ||
|
|
5d98864402 | ||
|
|
1aeebf1e55 | ||
|
|
a6bbba4bef | ||
|
|
a6c7c3fc4a | ||
|
|
7145c9f786 | ||
|
|
13a03f75f0 | ||
|
|
cc18215871 | ||
|
|
1cb34f68de | ||
|
|
81c3135a9d | ||
|
|
212e4f00de | ||
|
|
e654ffdd5e | ||
|
|
0b2e994399 | ||
|
|
2d7145f421 | ||
|
|
83c0a19448 | ||
|
|
2925d7e022 | ||
|
|
544a42c5f6 | ||
|
|
0059f7e350 | ||
|
|
20800d2e83 | ||
|
|
e5f6878048 | ||
|
|
958305ad28 | ||
|
|
fd28453df3 | ||
|
|
1b4d83f230 | ||
|
|
d6fb7864e5 | ||
|
|
a283f40286 | ||
|
|
1af6a37b69 | ||
|
|
360317efc5 | ||
|
|
2a2d3870d5 | ||
|
|
0f547c35cc | ||
|
|
1cf7737314 | ||
|
|
a503cb839a | ||
|
|
1a41cf7773 | ||
|
|
b747bcd4a8 | ||
|
|
2e237b83e1 | ||
|
|
1a935fadc5 | ||
|
|
1fc3673653 | ||
|
|
e6b82d358a | ||
|
|
e2f6481825 | ||
|
|
c533d2a7ca | ||
|
|
c5b0246ea9 | ||
|
|
f8cd015cb7 | ||
|
|
5463ac1261 | ||
|
|
10ac4bdb99 | ||
|
|
b55e7b75c0 | ||
|
|
1f0e857c11 | ||
|
|
16da77be78 | ||
|
|
6967c22f5d | ||
|
|
08da087f84 | ||
|
|
b7f3d15927 | ||
|
|
978be93b50 | ||
|
|
c15559db8d | ||
|
|
0c52b61e0d | ||
|
|
df06968a03 | ||
|
|
fd5d50c47a | ||
|
|
5868a64322 | ||
|
|
d44c3a69cb | ||
|
|
bb584d217f | ||
|
|
d9e2344f5c | ||
|
|
ea84a66227 | ||
|
|
3f18792ad6 | ||
|
|
0de28eccf4 | ||
|
|
7364d556ce | ||
|
|
41397946b5 | ||
|
|
b86053a03e | ||
|
|
00178dbabd | ||
|
|
1f7eb235f6 | ||
|
|
850ec52a64 | ||
|
|
090da68ef5 | ||
|
|
f109c0c391 | ||
|
|
06a935aabf | ||
|
|
e679e0148f | ||
|
|
16678c3a95 | ||
|
|
92b01dfa9b | ||
|
|
3a4b1a7ba5 | ||
|
|
65c969c041 | ||
|
|
833249aba8 | ||
|
|
41ca455c8f | ||
|
|
594463aa28 | ||
|
|
9600236732 | ||
|
|
df4d3cd0ab | ||
|
|
c37d7a503f | ||
|
|
7b0d81b276 | ||
|
|
520a201d85 | ||
|
|
cde81ba099 | ||
|
|
9c54f441db | ||
|
|
5de6dbec2b | ||
|
|
bf687ce7c0 | ||
|
|
787c40813d | ||
|
|
da7503f088 | ||
|
|
3938ee89b9 | ||
|
|
f296e8584b | ||
|
|
86fabd9a3e | ||
|
|
d0f3bb4b91 | ||
|
|
c9cf97d466 | ||
|
|
22305f9a31 | ||
|
|
71f4a3b8ad | ||
|
|
32720f937e | ||
|
|
9c14ce9fb6 | ||
|
|
0c1edc359f | ||
|
|
2242370db7 | ||
|
|
1d88b003f9 | ||
|
|
7a7d375f4c | ||
|
|
e719faa568 | ||
|
|
eab18eea79 | ||
|
|
1c722f39cd | ||
|
|
ad23806589 | ||
|
|
adf0dd0d21 | ||
|
|
4a16edbf83 | ||
|
|
70efb590da | ||
|
|
73411490ab | ||
|
|
098a7268cf | ||
|
|
09ed1d1ece | ||
|
|
00147fe6e8 | ||
|
|
7fce2bc7e7 | ||
|
|
2f2105d115 | ||
|
|
6e8160d05b | ||
|
|
7f8559628e | ||
|
|
753c3f59ee | ||
|
|
81f92f7917 | ||
|
|
8dcbbd6d2a | ||
|
|
f172b8bcd3 | ||
|
|
0c29dd5ba6 | ||
|
|
fd5300a907 | ||
|
|
6707e09ad8 | ||
|
|
b277702854 | ||
|
|
30c0c89640 | ||
|
|
8f9e5dd4a4 | ||
|
|
b63b652747 | ||
|
|
41204b7102 | ||
|
|
4ea78ef838 | ||
|
|
dfd3398c6b | ||
|
|
96029971af | ||
|
|
4814f794a6 | ||
|
|
0ce6c56cd7 | ||
|
|
f1f0b0e34c | ||
|
|
73a8051005 | ||
|
|
a248a70379 | ||
|
|
5e05522c62 | ||
|
|
05fafa4046 | ||
|
|
9c73a875e7 | ||
|
|
7f3f3f9274 | ||
|
|
c9ef4b0ff7 | ||
|
|
b0a2f29441 | ||
|
|
b3cb7d5919 | ||
|
|
001a6e8d07 | ||
|
|
4436ffbd95 | ||
|
|
a9425d1e0e | ||
|
|
e2d8bcb7e8 | ||
|
|
4618770dd5 | ||
|
|
31eaff14dd | ||
|
|
0f64213c10 | ||
|
|
069d1d59dd | ||
|
|
3efc04b8c6 | ||
|
|
1c60a5418a | ||
|
|
283252d706 | ||
|
|
ee8908e469 | ||
|
|
5436f62167 | ||
|
|
383df14b5f | ||
|
|
1c658ae65e | ||
|
|
37cd3ae55b | ||
|
|
f3c6cf7c9e | ||
|
|
1c99b9b757 | ||
|
|
34bb5c2614 | ||
|
|
c7c34a3a54 | ||
|
|
85049f1213 | ||
|
|
52c1f397ce | ||
|
|
5acdefec48 | ||
|
|
968376f803 | ||
|
|
570229f047 | ||
|
|
b1cd14c745 | ||
|
|
60dbac7071 | ||
|
|
a6055fcbae | ||
|
|
14a496d500 |
@@ -1,13 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
|
||||
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
|
||||
|
||||
project(TORCHNPU CXX C)
|
||||
|
||||
option(USE_GRAPH_MODE "enable graph mode" OFF)
|
||||
|
||||
if(USE_GRAPH_MODE)
|
||||
add_definitions(-DUSE_GRAPH_MODE=1)
|
||||
endif()
|
||||
|
||||
set(LINUX TRUE)
|
||||
set(CMAKE_INSTALL_MESSAGE NEVER)
|
||||
# set(CMAKE_VERBOSE_MAKEFILE ON)
|
||||
@@ -84,6 +78,7 @@ endif()
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=pedantic")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=redundant-decls")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=old-style-cast")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__FILENAME__='\"$(notdir $(abspath $<))\"'")
|
||||
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp")
|
||||
# These flags are not available in GCC-4.8.5. Set only when using clang.
|
||||
@@ -140,16 +135,26 @@ else()
|
||||
set(CXXFLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-s,-z,noexecstack -fPIE -pie ${CXXFLAGS}")
|
||||
endif()
|
||||
|
||||
|
||||
if (DEFINED BUILD_LIBTORCH)
|
||||
add_compile_definitions(BUILD_LIBTORCH)
|
||||
endif()
|
||||
|
||||
|
||||
include_directories(${PROJECT_SOURCE_DIR})
|
||||
include_directories(${PROJECT_SOURCE_DIR}/torch_npu/csrc/aten)
|
||||
include_directories(${PROJECT_SOURCE_DIR}/third_party/hccl/inc)
|
||||
include_directories(${PROJECT_SOURCE_DIR}/third_party/acl/inc)
|
||||
|
||||
if (NOT DEFINED BUILD_LIBTORCH)
|
||||
include_directories(${PROJECT_SOURCE_DIR}/patch/include)
|
||||
include_directories(${PROJECT_SOURCE_DIR}/patch/include/torch/csrc/distributed)
|
||||
endif()
|
||||
|
||||
# Set installed PyTorch dir
|
||||
if(DEFINED PYTORCH_INSTALL_DIR)
|
||||
include_directories(${PYTORCH_INSTALL_DIR}/include)
|
||||
include_directories(${PYTORCH_INSTALL_DIR}/include/torch/csrc/api/include/)
|
||||
include_directories(${PYTORCH_INSTALL_DIR}/include/torch/csrc/api/include)
|
||||
else()
|
||||
message(FATAL_ERROR, "Cannot find installed PyTorch directory")
|
||||
endif()
|
||||
@@ -164,23 +169,33 @@ endif()
|
||||
# sources
|
||||
set(ATEN_SRCS)
|
||||
set(CORE_SRCS)
|
||||
set(DIST_SRCS)
|
||||
set(FRAMEWORK_SRCS)
|
||||
set(NPU_SRCS)
|
||||
set(PROF_SRCS)
|
||||
set(UTILS_SRCS)
|
||||
|
||||
if (NOT DEFINED BUILD_LIBTORCH)
|
||||
set(DIST_SRCS)
|
||||
set(NPU_SRCS)
|
||||
set(PROF_SRCS)
|
||||
set(UTILS_SRCS)
|
||||
endif()
|
||||
|
||||
|
||||
add_subdirectory(${TORCHNPU_ROOT}/aten)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/core)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/distributed)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/framework)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/npu)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/profiler)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/utils)
|
||||
|
||||
if (NOT DEFINED BUILD_LIBTORCH)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/distributed)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/npu)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/profiler)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/utils)
|
||||
endif()
|
||||
|
||||
if (DEFINED BUILD_LIBTORCH)
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${FRAMEWORK_SRCS})
|
||||
else()
|
||||
# Compile code with pybind11
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${DIST_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${UTILS_SRCS})
|
||||
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${DIST_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${UTILS_SRCS})
|
||||
endif()
|
||||
|
||||
add_library(${PLUGIN_NAME} SHARED ${CPP_SRCS})
|
||||
|
||||
@@ -188,27 +203,42 @@ link_directories(${PYTORCH_INSTALL_DIR}/lib)
|
||||
link_directories(${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs)
|
||||
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libhccl.so)
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC ${PYTORCH_INSTALL_DIR}/lib/libtorch_python.so)
|
||||
|
||||
if (NOT DEFINED BUILD_LIBTORCH)
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC ${PYTORCH_INSTALL_DIR}/lib/libtorch_python.so)
|
||||
endif()
|
||||
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libascendcl.so)
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libacl_op_compiler.so)
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libge_runner.so)
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libgraph.so)
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libacl_tdt_channel.so)
|
||||
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC torch torch_cpu c10 python3.7m)
|
||||
|
||||
set(ATEN_THREADING "OMP" CACHE STRING "ATen parallel backend")
|
||||
message(STATUS "Using ATen parallel backend: ${ATEN_THREADING}")
|
||||
if ("${ATEN_THREADING}" STREQUAL "OMP")
|
||||
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_OPENMP=1")
|
||||
elseif ("${ATEN_THREADING}" STREQUAL "NATIVE")
|
||||
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE=1")
|
||||
elseif ("${ATEN_THREADING}" STREQUAL "TBB")
|
||||
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE_TBB=1")
|
||||
if (DEFINED BUILD_LIBTORCH)
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC torch torch_cpu c10)
|
||||
else()
|
||||
message(FATAL_ERROR "Unknown ATen parallel backend: ${ATEN_THREADING}")
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC torch torch_cpu c10 python3.7m)
|
||||
endif()
|
||||
|
||||
include(GNUInstallDirs)
|
||||
target_compile_options(${PLUGIN_NAME} PRIVATE "-DC10_BUILD_MAIN_LIB")
|
||||
install(TARGETS ${PLUGIN_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
|
||||
if(DEFINED ENV{BSCPP_OPS_ENABLE})
|
||||
message(STATUS "env BSCPP_OPS_ENABLE exists")
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC bscpp_ops)
|
||||
endif()
|
||||
|
||||
if (NOT DEFINED BUILD_LIBTORCH)
|
||||
set(ATEN_THREADING "OMP" CACHE STRING "ATen parallel backend")
|
||||
message(STATUS "Using ATen parallel backend: ${ATEN_THREADING}")
|
||||
if ("${ATEN_THREADING}" STREQUAL "OMP")
|
||||
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_OPENMP=1")
|
||||
elseif ("${ATEN_THREADING}" STREQUAL "NATIVE")
|
||||
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE=1")
|
||||
elseif ("${ATEN_THREADING}" STREQUAL "TBB")
|
||||
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE_TBB=1")
|
||||
else()
|
||||
message(FATAL_ERROR "Unknown ATen parallel backend: ${ATEN_THREADING}")
|
||||
endif()
|
||||
|
||||
include(GNUInstallDirs)
|
||||
target_compile_options(${PLUGIN_NAME} PRIVATE "-DC10_BUILD_MAIN_LIB")
|
||||
install(TARGETS ${PLUGIN_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
|
||||
endif()
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
approvers:
|
||||
- blian
|
||||
- nalinaly
|
||||
- weili10
|
||||
- you-ansheng
|
||||
reviewers:
|
||||
- shibo19
|
||||
- Ronnie_zheng
|
||||
- xiaxia3
|
||||
- li_chao10
|
||||
- petissue
|
||||
- td__lihan
|
||||
- ascendzyj
|
||||
@@ -20,4 +19,14 @@ reviewers:
|
||||
- fairwarning
|
||||
- you-ansheng
|
||||
- yinzijun
|
||||
- weili10
|
||||
- weili10
|
||||
- granpad7
|
||||
- clinglai
|
||||
- shaoyf
|
||||
- yanpengquan07
|
||||
- xiong05
|
||||
- liu-jiaweikf
|
||||
- xiepeng20
|
||||
- brightlyking
|
||||
- chenhao_1209
|
||||
- wbigat
|
||||
@@ -14,13 +14,13 @@ This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch
|
||||
|
||||
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
|
||||
|
||||
yum install -y gcc==7.3.0 cmake==3.12.0
|
||||
yum install -y gcc==7.5.0 cmake==3.12.0
|
||||
|
||||
## Ubuntu
|
||||
|
||||
apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
|
||||
|
||||
apt-get install -y gcc==7.3.0 cmake==3.12.0
|
||||
apt-get install -y gcc==7.5.0 cmake==3.12.0
|
||||
|
||||
> **NOTE:**
|
||||
>If an error occurs during the installation of the GCC and CMake dependency commands, use the source code for installation. For details, see the FAQ.
|
||||
@@ -52,7 +52,7 @@ Install the official torch package, and then compile and install the plugin.
|
||||
|
||||
```sh
|
||||
#x86_64
|
||||
pip3 install torch==1.8.1+cpu # If an error is reported when you run the pip command to install PyTorch of the CPU version, manually download the .whl package from https://download.pytorch.org/whl/torch.
|
||||
pip3 install torch==1.11.0+cpu # If an error is reported when you run the pip command to install PyTorch of the CPU version, manually download the .whl package from https://download.pytorch.org/whl/torch.
|
||||
|
||||
#AArch64
|
||||
#The community does not provide the CPU installation package of the ARM architecture. For details, see the first FAQ to compile and install PyTorch using the source code.
|
||||
@@ -62,7 +62,7 @@ Compile and generate the binary installation package of the PyTorch plugin.
|
||||
Download code of the corresponding branch and go to the root directory of the plugin.
|
||||
```
|
||||
#
|
||||
git clone -b v1.8.1-3.0.rc2 https://gitee.com/ascend/pytorch.git
|
||||
git clone -b master https://gitee.com/ascend/pytorch.git
|
||||
cd pytorch
|
||||
# Specify the Python version packaging mode:
|
||||
bash ci/build.sh --python=3.7
|
||||
@@ -75,11 +75,11 @@ bash ci/build.sh --python=3.9
|
||||
Install the **torch_npu** package generated in the **pytorch/dist** directory. *{arch}* indicates the architecture name.
|
||||
|
||||
```
|
||||
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
|
||||
pip3 install --upgrade dist/torch_npu-1.11.0-cp37-cp37m-linux_{arch}.whl
|
||||
```
|
||||
Download TorchVision.
|
||||
```
|
||||
pip3 install torchvision==0.9.1
|
||||
pip3 install torchvision==0.12.0
|
||||
```
|
||||
|
||||
|
||||
@@ -137,7 +137,7 @@ python3 test_div.py
|
||||
|
||||
# (Optional) Installing the Mixed Precision Module
|
||||
|
||||
AscendPyTorch 1.8.1 integrates the AMP module and can be used for training with mixed precision. The differences between the AMP module and the Apex module are as follows. You can select a desired module. For details about how to compile and install the Apex module, see the related [**README.en**](https://gitee.com/ascend/apex) file.
|
||||
AscendPyTorch 1.11.0 integrates the AMP module and can be used for training with mixed precision. The differences between the AMP module and the Apex module are as follows. You can select a desired module. For details about how to compile and install the Apex module, see the related [**README.en**](https://gitee.com/ascend/apex) file.
|
||||
|
||||
- AMP
|
||||
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
|
||||
@@ -184,23 +184,23 @@ The version branches of AscendPyTorch have the following maintenance phases:
|
||||
| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained <br> 2023-07-15 estimated |
|
||||
# FAQs
|
||||
|
||||
## When the CPU architecture is ARM, PyTorch 1.8.1 cannot be installed using the PIP3 command because the community does not provide the torch package for the ARM CPU architecture. In this case, use the source code to compile and install PyTorch 1.8.1.
|
||||
## When the CPU architecture is ARM, PyTorch 1.11.0 cannot be installed using the PIP3 command because the community does not provide the torch package for the ARM CPU architecture. In this case, use the source code to compile and install PyTorch 1.11.0.
|
||||
|
||||
Download the PyTorch 1.8.1 source package.
|
||||
Download the PyTorch 1.11.0 source package.
|
||||
|
||||
```
|
||||
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
|
||||
git clone -b v1.11.0 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.11.0
|
||||
```
|
||||
|
||||
Access the source package to obtain the passive dependency code.
|
||||
|
||||
```
|
||||
cd pytorch_v1.8.1
|
||||
cd pytorch_v1.11.0
|
||||
git submodule sync
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
Compile and install PyTorch 1.8.1.
|
||||
Compile and install PyTorch 1.11.0.
|
||||
|
||||
```
|
||||
python3 setup.py install
|
||||
@@ -316,7 +316,7 @@ When downloading GCC from some sources, you may be prompted by an error message
|
||||
|
||||
Perform the following steps as the **root** user.
|
||||
|
||||
1. Download **gcc-7.3.0.tar.gz** from [https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz).
|
||||
1. Download **gcc-7.5.0.tar.gz** from [https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz).
|
||||
|
||||
2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
|
||||
|
||||
@@ -340,20 +340,20 @@ Perform the following steps as the **root** user.
|
||||
|
||||
4. Compile and install GCC.
|
||||
|
||||
1. Go to the directory where the source package **gcc-7.3.0.tar.gz** is located and run the following command to decompress it:
|
||||
1. Go to the directory where the source package **gcc-7.5.0.tar.gz** is located and run the following command to decompress it:
|
||||
|
||||
```
|
||||
tar -zxvf gcc-7.3.0.tar.gz
|
||||
tar -zxvf gcc-7.5.0.tar.gz
|
||||
```
|
||||
|
||||
2. Go to the extracted directory and download the GCC dependency packages:
|
||||
|
||||
```
|
||||
cd gcc-7.3.0
|
||||
cd gcc-7.5.0
|
||||
./contrib/download_prerequisites
|
||||
```
|
||||
|
||||
If an error is reported during the command execution, run the following commands in the **gcc-7.3.0/** directory to download the dependency packages:
|
||||
If an error is reported during the command execution, run the following commands in the **gcc-7.5.0/** directory to download the dependency packages:
|
||||
|
||||
```
|
||||
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
|
||||
@@ -373,13 +373,13 @@ Perform the following steps as the **root** user.
|
||||
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>Run the configuration, compilation, and installation commands.
|
||||
|
||||
```
|
||||
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
|
||||
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.5.0
|
||||
make -j15 # Check the number of CPUs by running **grep -w processor /proc/cpuinfo|wc -l**. In this example, the number is 15. You can set the parameters as required.
|
||||
make install
|
||||
```
|
||||
|
||||
> **NOTICE:**
|
||||
>The **--prefix** option is used to specify the **linux\_gcc7.3.0** installation path, which is configurable. Do not set it to **/usr/local** or **/usr,** which is the default installation path for the GCC installed by using the software source. Otherwise, a conflict occurs and the original GCC compilation environment of the system is damaged. In this example, the installation path is set to **/usr/local/linux\_gcc7.3.0**.
|
||||
>The **--prefix** option is used to specify the **linux\_gcc7.5.0** installation path, which is configurable. Do not set it to **/usr/local** or **/usr,** which is the default installation path for the GCC installed by using the software source. Otherwise, a conflict occurs and the original GCC compilation environment of the system is damaged. In this example, the installation path is set to **/usr/local/linux\_gcc7.5.0**.
|
||||
4. Change the soft links.
|
||||
|
||||
```
|
||||
@@ -398,14 +398,14 @@ Perform the following steps as the **root** user.
|
||||
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
|
||||
```
|
||||
|
||||
**${install_path}** indicates the GCC 7.3.0 installation path configured in [3](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310). In this example, the GCC 7.3.0 installation path is **/usr/local/gcc7.3.0/**.
|
||||
**${install_path}** indicates the GCC 7.5.0 installation path configured in [3](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310). In this example, the GCC 7.5.0 installation path is **/usr/local/gcc7.5.0/**.
|
||||
|
||||
> **NOTE:**
|
||||
>Skip this step if you do not need to use the compilation environment with GCC upgraded.
|
||||
|
||||
If the PyTorch compilation fails, check whether the soft link library is correct.
|
||||
|
||||
libstdc++->libstdc++.so.6.0.24(7.3.0)
|
||||
libstdc++->libstdc++.so.6.0.24(7.5.0)
|
||||
|
||||
## libblas.so cannot be found.
|
||||
|
||||
@@ -488,6 +488,11 @@ To verify the torch_npu reference, switch to another directory. If you perform t
|
||||
|
||||
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
|
||||
|
||||
## Multi card training is stuck in initialization stage until timeout
|
||||
|
||||
IPv6 address is used in the "init_process_group" function of multi card communication, for example ::1 (Note that the localhost may point to the IPv6 address)
|
||||
Use IPv4 to avoid this problem
|
||||
|
||||
# Version Description
|
||||
|
||||
For details, see [Release Notes](https://gitee.com/ascend/pytorch/tree/master/docs/en/RELEASENOTE).
|
||||
|
||||
@@ -14,13 +14,13 @@
|
||||
|
||||
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
|
||||
|
||||
yum install -y gcc==7.3.0 cmake==3.12.0
|
||||
yum install -y gcc==7.5.0 cmake==3.12.0
|
||||
|
||||
## Ubuntu
|
||||
|
||||
apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
|
||||
|
||||
apt-get install -y gcc==7.3.0 cmake==3.12.0
|
||||
apt-get install -y gcc==7.5.0 cmake==3.12.0
|
||||
|
||||
|
||||
|
||||
@@ -30,19 +30,25 @@ apt-get install -y gcc==7.3.0 cmake==3.12.0
|
||||
|
||||
|
||||
# Ascend配套软件
|
||||
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 | Gitee分支名称 |
|
||||
| :------------ | :----------- | :----------- | ------------- |
|
||||
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
|
||||
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
|
||||
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
|
||||
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 | Gitee分支名称 | AscendHub镜像版本 |
|
||||
| :------------ | :----------- | :----------- | ------------- | ------------- |
|
||||
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 | 21.0.2 |
|
||||
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 | 21.0.3 |
|
||||
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 | 21.0.4 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 | 22.0.RC1 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 | \ |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 | 22.0.RC2 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 | 22.0.RC2-1.8.1 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.5.0.post7 | v1.5.0-3.0.rc3 | \ |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 | 22.0.RC3-1.8.1 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 | \ |
|
||||
| 3.0.0 | CANN 6.0.1 | 1.5.0.post8 | v1.5.0-3.0.0 | \ |
|
||||
| 3.0.0 | CANN 6.0.1 | 1.8.1 | v1.8.1-3.0.0 | \ |
|
||||
| 3.0.0 | CANN 6.0.1 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 | \ |
|
||||
|
||||
# 安装方式
|
||||
|
||||
## 安装Pytorch依赖环境
|
||||
## 安装PyTorch依赖环境
|
||||
|
||||
如果使用非root用户安装,用户需要在本步骤的每句命令后加**--user**,示例如:pip3 install pyyaml --user。
|
||||
|
||||
@@ -57,10 +63,14 @@ pip3 install wheel
|
||||
|
||||
```sh
|
||||
#x86_64
|
||||
pip3 install torch==1.8.1+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
|
||||
pip3 install torch==1.11.0+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
|
||||
|
||||
#aarch64
|
||||
#社区未提供arm架构cpu安装包,请参见FAQ第一条,使用源码编译安装pytorch
|
||||
#aarch64(推荐使用镜像)
|
||||
1.可在docker中使用AscendHub镜像仓库提供的基于PyTorch版本制作的基础镜像,包含训练、转换和推理等功能。
|
||||
#镜像仓库地址:(https://ascendhub.huawei.com/#/detail/pytorch-modelzoo)
|
||||
2.鲲鹏arm服务器可在鲲鹏开源软件文件共享中心获取编译好的PyTorch二进制安装包。
|
||||
#鲲鹏文件共享中心地址:(https://mirrors.huaweicloud.com/kunpeng/archive/Ascend/PyTorch/)
|
||||
3.社区未提供的arm架构cpu安装包,可参见FAQ第一条,使用源码编译安装pytorch。
|
||||
```
|
||||
|
||||
编译生成pytorch插件的二进制安装包。
|
||||
@@ -80,12 +90,12 @@ bash ci/build.sh --python=3.9
|
||||
然后安装pytorch/dist下生成的插件torch_npu包,{arch}为架构名称。
|
||||
|
||||
```
|
||||
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
|
||||
pip3 install --upgrade dist/torch_npu-1.11.0-cp37-cp37m-linux_{arch}.whl
|
||||
```
|
||||
|
||||
下载torchvision。
|
||||
```
|
||||
pip3 install torchvision==0.9.1
|
||||
pip3 install torchvision==0.12.0
|
||||
```
|
||||
|
||||
# 运行
|
||||
@@ -141,7 +151,7 @@ python3 test_div.py
|
||||
|
||||
# 安装混合精度模块(可选)
|
||||
|
||||
AscendPyTorch1.8.1集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
|
||||
AscendPyTorch1.11.0集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
|
||||
|
||||
- AMP
|
||||
- 动态loss scale:动态计算loss scale的值并判断是否溢出。
|
||||
@@ -181,30 +191,38 @@ Ascend PyTorch的版本分支有以下几种维护阶段:
|
||||
|
||||
| **分支名** | **当前状态** | **上线时间** | **后续状态** | **EOL 日期**|
|
||||
|------------|--------------|----------------------|----------------------------------------|------------|
|
||||
| **v2.0.2** | Maintained | 2021-07-29 | Unmaintained <br> 2022-07-29 estimated | |
|
||||
| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained <br> 2022-10-15 estimated | |
|
||||
| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained <br> 2023-01-15 estimated | |
|
||||
| **v2.0.2** | EOL | 2021-07-29 | N/A | |
|
||||
| **v2.0.3** | EOL | 2021-10-15 | N/A | |
|
||||
| **v2.0.4** | Unmaintained | 2022-01-15 | EOL <br> 2023-04-15 estimated | |
|
||||
| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained <br> 2023-04-10 estimated | |
|
||||
| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained <br> 2023-07-15 estimated | |
|
||||
| **v3.0.rc3** | Maintained | 2022-10-20 | Unmaintained <br> 2023-10-20 estimated | |
|
||||
| **v3.0.0** | Maintained | 2023-1-18 | Unmaintained <br> 2024-1-18 estimated | |
|
||||
|
||||
# FAQ
|
||||
|
||||
## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch1.8.1,需要使用源码编译安装。
|
||||
## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch,需要使用源码编译安装。
|
||||
|
||||
下载PyTorch v1.8.1源码包。
|
||||
下载PyTorch v1.11.0源码包。
|
||||
|
||||
```
|
||||
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
|
||||
git clone -b v1.11.0 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.11.0
|
||||
```
|
||||
|
||||
进入源码包获取被动依赖代码。
|
||||
|
||||
```
|
||||
cd pytorch_v1.8.1
|
||||
cd pytorch_v1.11.0
|
||||
git submodule sync
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
配置环境变量
|
||||
|
||||
```
|
||||
export USE_XNNPACK=0
|
||||
```
|
||||
|
||||
执行编译安装。
|
||||
|
||||
```
|
||||
@@ -324,7 +342,7 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
|
||||
以下步骤请在root用户下执行。
|
||||
|
||||
1. 下载gcc-7.3.0.tar.gz,下载地址为[https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz)。
|
||||
1. 下载gcc-7.5.0.tar.gz,下载地址为[https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz)。
|
||||
|
||||
2. 安装gcc时候会占用大量临时空间,所以先执行下面的命令清空/tmp目录:
|
||||
|
||||
@@ -348,20 +366,20 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
|
||||
4. 编译安装gcc。
|
||||
|
||||
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
|
||||
1. 进入gcc-7.5.0.tar.gz源码包所在目录,解压源码包,命令为:
|
||||
|
||||
```
|
||||
tar -zxvf gcc-7.3.0.tar.gz
|
||||
tar -zxvf gcc-7.5.0.tar.gz
|
||||
```
|
||||
|
||||
2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
|
||||
|
||||
```
|
||||
cd gcc-7.3.0
|
||||
cd gcc-7.5.0
|
||||
./contrib/download_prerequisites
|
||||
```
|
||||
|
||||
如果执行上述命令报错,需要执行如下命令在“gcc-7.3.0/“文件夹下下载依赖包:
|
||||
如果执行上述命令报错,需要执行如下命令在“gcc-7.5.0/“文件夹下下载依赖包:
|
||||
|
||||
```
|
||||
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
|
||||
@@ -381,20 +399,20 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>执行配置、编译和安装命令:
|
||||
|
||||
```
|
||||
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
|
||||
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.5.0
|
||||
make -j15 # 通过grep -w processor /proc/cpuinfo|wc -l查看cpu数,示例为15,用户可自行设置相应参数。
|
||||
make install
|
||||
```
|
||||
|
||||
> **须知:**
|
||||
>其中“--prefix“参数用于指定linux\_gcc7.3.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.3.0“。
|
||||
>其中“--prefix“参数用于指定linux\_gcc7.5.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.5.0“。
|
||||
|
||||
4. 修改软连接。
|
||||
|
||||
```
|
||||
ln -s ${install_path}/gcc-7.3.0/bin/gcc /usr/bin/gcc
|
||||
ln -s ${install_path}/gcc-7.3.0/bin/g++ /usr/bin/g++
|
||||
ln -s ${install_path}/gcc-7.3.0/bin/c++ /usr/bin/c++
|
||||
ln -s ${install_path}/gcc-7.5.0/bin/gcc /usr/bin/gcc
|
||||
ln -s ${install_path}/gcc-7.5.0/bin/g++ /usr/bin/g++
|
||||
ln -s ${install_path}/gcc-7.5.0/bin/c++ /usr/bin/c++
|
||||
```
|
||||
|
||||
5.配置环境变量。
|
||||
@@ -405,7 +423,7 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
|
||||
```
|
||||
|
||||
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.3.0安装路径,本示例为“/usr/local/gcc7.3.0/“。
|
||||
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.5.0安装路径,本示例为“/usr/local/gcc7.5.0/“。
|
||||
|
||||
> **说明:**
|
||||
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
|
||||
@@ -413,7 +431,7 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
若存在pytorch编译不过,请检查软连接的库是否正确。
|
||||
|
||||
|
||||
libstdc++->libstdc++.so.6.0.24(7.3.0)
|
||||
libstdc++->libstdc++.so.6.0.24(7.5.0)
|
||||
|
||||
## 找不到libblas.so问题
|
||||
|
||||
@@ -485,7 +503,7 @@ warning如下图所示,由Tensor.set_data浅拷贝操作触发。主要原因
|
||||
|
||||
该warning不影响模型的精度和性能,可以忽略。
|
||||
|
||||
待NPU 设备号合入社区或者后续Pytorch版本`_has_compatible_shallow_copy_type`注册方式发生变动,该warning会被解决。
|
||||
待NPU 设备号合入社区或者后续PyTorch版本`_has_compatible_shallow_copy_type`注册方式发生变动,该warning会被解决。
|
||||
|
||||

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

|
||||
|
||||
1. 执行命令设置环境变量
|
||||
|
||||
```
|
||||
export USE_XNNPACK=0
|
||||
```
|
||||
|
||||
2. 执行命令清除当前编译内容
|
||||
|
||||
```
|
||||
make clean
|
||||
```
|
||||
|
||||
3. 重新编译
|
||||
|
||||
## 编译时出现Breakpad error: field 'regs' has incomplete type 'google_breakpad::user_regs_struct'报错
|
||||
|
||||
编译原生pytorch时,未配置相关环境变量,导致编译不成功。
|
||||
|
||||
1. 执行命令配置环境变量
|
||||
|
||||
```
|
||||
export BUILD_BREAKPAD=0
|
||||
```
|
||||
|
||||
2. 执行命令清除当前编译内容
|
||||
|
||||
```
|
||||
make clean
|
||||
```
|
||||
|
||||
3. 重新编译
|
||||
|
||||
## 多卡训练初始化阶段卡顿至超时
|
||||
|
||||
init_process_group 函数中使用了IPV6地址,例如::1(注意localhost 可能指向IPv6的地址),使用IPv4可以避免这个问题
|
||||
# 版本说明
|
||||
|
||||
版本说明请参阅[ReleseNote](docs/zh/RELEASENOTE)
|
||||
@@ -0,0 +1,225 @@
|
||||
# Copyright (c) 2020 Huawei Technologies Co., Ltd
|
||||
# All rights reserved.
|
||||
#
|
||||
# Licensed under the BSD 3-Clause License (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://opensource.org/licenses/BSD-3-Clause
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import multiprocessing
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import traceback
|
||||
import platform
|
||||
|
||||
from sysconfig import get_paths
|
||||
from distutils.version import LooseVersion
|
||||
from distutils import file_util
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def which(thefile):
|
||||
path = os.environ.get("PATH", os.defpath).split(os.pathsep)
|
||||
for d in path:
|
||||
fname = os.path.join(d, thefile)
|
||||
fnames = [fname]
|
||||
if sys.platform == 'win32':
|
||||
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
|
||||
fnames += [fname + ext for ext in exts]
|
||||
for name in fnames:
|
||||
if os.access(name, os.F_OK | os.X_OK) and not os.path.isdir(name):
|
||||
return name
|
||||
return None
|
||||
|
||||
|
||||
def get_cmake_command():
|
||||
def _get_version(cmd):
|
||||
for line in subprocess.check_output([cmd, '--version']).decode('utf-8').split('\n'):
|
||||
if 'version' in line:
|
||||
return LooseVersion(line.strip().split(' ')[2])
|
||||
raise RuntimeError('no version found')
|
||||
"Returns cmake command."
|
||||
cmake_command = 'cmake'
|
||||
if platform.system() == 'Windows':
|
||||
return cmake_command
|
||||
cmake3 = which('cmake3')
|
||||
cmake = which('cmake')
|
||||
if cmake3 is not None and _get_version(cmake3) >= LooseVersion("3.12.0"):
|
||||
cmake_command = 'cmake3'
|
||||
return cmake_command
|
||||
elif cmake is not None and _get_version(cmake) >= LooseVersion("3.12.0"):
|
||||
return cmake_command
|
||||
else:
|
||||
raise RuntimeError('no cmake or cmake3 with version >= 3.12.0 found')
|
||||
|
||||
|
||||
def get_build_type():
|
||||
build_type = 'Release'
|
||||
if os.getenv('DEBUG', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
|
||||
build_type = 'Debug'
|
||||
|
||||
if os.getenv('REL_WITH_DEB_INFO', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
|
||||
build_type = 'RelWithDebInfo'
|
||||
|
||||
return build_type
|
||||
|
||||
|
||||
def get_pytorch_dir():
|
||||
try:
|
||||
import torch
|
||||
return os.path.dirname(os.path.abspath(torch.__file__))
|
||||
except Exception:
|
||||
_, _, exc_traceback = sys.exc_info()
|
||||
frame_summary = traceback.extract_tb(exc_traceback)[-1]
|
||||
return os.path.dirname(frame_summary.filename)
|
||||
|
||||
|
||||
def generate_bindings_code(base_dir, verbose):
|
||||
generate_code_cmd = ["bash", os.path.join(base_dir, 'generate_code.sh'), verbose]
|
||||
if subprocess.call(generate_code_cmd) != 0:
|
||||
print(
|
||||
'Failed to generate ATEN bindings: {}'.format(generate_code_cmd),
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def build_stub(base_dir):
|
||||
build_stub_cmd = ["sh", os.path.join(base_dir, 'third_party/acl/libs/build_stub.sh')]
|
||||
if subprocess.call(build_stub_cmd) != 0:
|
||||
print(
|
||||
'Failed to build stub: {}'.format(build_stub_cmd),
|
||||
file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def clean_generated_files():
|
||||
f_ignore = open(os.path.join(BASE_DIR, '.gitignore'), 'r')
|
||||
ignores = f_ignore.read()
|
||||
pat = re.compile(r'^#( BEGIN NOT-CLEAN-FILES )?')
|
||||
for wildcard in filter(None, ignores.split('\n')):
|
||||
match = pat.match(wildcard)
|
||||
if match:
|
||||
if match.group(1):
|
||||
# Marker is found and stop reading .gitignore.
|
||||
break
|
||||
# Ignore lines which begin with '#'.
|
||||
else:
|
||||
for filename in glob.glob(wildcard):
|
||||
shutil.rmtree(filename, ignore_errors=True)
|
||||
f_ignore.close()
|
||||
clean_files = ['torch_npu/csrc/aten/RegisterCPU.cpp', 'torch_npu/csrc/aten/RegisterNPU.cpp',
|
||||
'torch_npu/csrc/aten/RegisterAutogradNPU.cpp', 'torch_npu/csrc/aten/NpuNativeFunctions.h']
|
||||
for file in clean_files:
|
||||
if os.path.exists(os.path.join(BASE_DIR, file)):
|
||||
os.remove(os.path.join(BASE_DIR, file))
|
||||
if os.path.exists(os.path.join(BASE_DIR, "libtorch")):
|
||||
shutil.rmtree(os.path.join(BASE_DIR, "libtorch"))
|
||||
|
||||
|
||||
def run_cmake():
|
||||
cmake = get_cmake_command()
|
||||
|
||||
if cmake is None:
|
||||
raise RuntimeError(
|
||||
"CMake must be installed to build the following extensions: ")
|
||||
|
||||
build_dir = os.path.join(BASE_DIR, "build")
|
||||
build_type_dir = os.path.join(build_dir, get_build_type())
|
||||
output_lib_path = os.path.join(build_type_dir, "packages/torch_npu/lib")
|
||||
os.makedirs(build_type_dir, exist_ok=True)
|
||||
os.makedirs(output_lib_path, exist_ok=True)
|
||||
cmake_args = [
|
||||
'-DCMAKE_BUILD_TYPE=' + get_build_type(),
|
||||
'-DCMAKE_INSTALL_PREFIX=' + os.path.abspath(output_lib_path),
|
||||
'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + os.path.abspath(output_lib_path),
|
||||
'-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=' + os.path.abspath(output_lib_path),
|
||||
'-DTORCHNPU_INSTALL_LIBDIR=' + os.path.abspath(output_lib_path),
|
||||
'-DPYTHON_INCLUDE_DIR=' + get_paths()['include'],
|
||||
'-DPYTORCH_INSTALL_DIR=' + get_pytorch_dir(),
|
||||
'-DBUILD_LIBTORCH=' + "ON"]
|
||||
|
||||
build_args = ['-j', str(multiprocessing.cpu_count())]
|
||||
|
||||
subprocess.check_call([cmake, BASE_DIR] + cmake_args, cwd=build_type_dir, env=os.environ)
|
||||
subprocess.check_call(['make'] + build_args, cwd=build_type_dir, env=os.environ)
|
||||
|
||||
|
||||
def copy_file(infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1):
|
||||
"""Copy a file respecting verbose, dry-run and force flags. (The
|
||||
former two default to whatever is in the Distribution object, and
|
||||
the latter defaults to false for commands that don't define it.)
|
||||
"""
|
||||
return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, True, link)
|
||||
|
||||
|
||||
def copy_hpp():
|
||||
def get_src_py_and_dst():
|
||||
ret = []
|
||||
|
||||
header_files = [
|
||||
"torch_npu/csrc/aten/*.h",
|
||||
"torch_npu/csrc/aten/*/*.h",
|
||||
"torch_npu/csrc/aten/*/*/*.h",
|
||||
"torch_npu/csrc/core/*.h",
|
||||
"torch_npu/csrc/core/*/*.h",
|
||||
"torch_npu/csrc/core/*/*/*.h",
|
||||
"torch_npu/csrc/framework/*.h",
|
||||
"torch_npu/csrc/framework/*/*.h",
|
||||
"torch_npu/csrc/framework/*/*/*.h",
|
||||
"third_party/acl/inc/*/*.h",
|
||||
"third_party/acl/inc/*/*/*.h"
|
||||
]
|
||||
glob_header_files = []
|
||||
for regex_pattern in header_files:
|
||||
glob_header_files += glob.glob(os.path.join(BASE_DIR, regex_pattern), recursive=True)
|
||||
|
||||
for src in glob_header_files:
|
||||
dst = os.path.join(
|
||||
os.path.join(BASE_DIR, f"libtorch/include/torch_npu"),
|
||||
os.path.relpath(src, os.path.join(BASE_DIR, "torch_npu")))
|
||||
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
||||
ret.append((src, dst))
|
||||
|
||||
return ret
|
||||
ret = get_src_py_and_dst()
|
||||
for src, dst in ret:
|
||||
copy_file(src, dst)
|
||||
|
||||
|
||||
def copy_lib():
|
||||
lib_file = [f"build/{get_build_type()}/packages/torch_npu/lib/*.*"]
|
||||
glob_lib_files = []
|
||||
|
||||
for regex_pattern in lib_file:
|
||||
glob_lib_files += glob.glob(os.path.join(BASE_DIR, regex_pattern), recursive=True)
|
||||
dst_path = os.path.join(BASE_DIR, f"libtorch/lib")
|
||||
os.makedirs(dst_path, exist_ok=True)
|
||||
|
||||
for src in glob_lib_files:
|
||||
_, src_file_name = os.path.split(src)
|
||||
copy_file(src, os.path.join(dst_path, src_file_name))
|
||||
|
||||
|
||||
def build_libtorch_npu():
|
||||
clean_generated_files()
|
||||
generate_bindings_code(BASE_DIR, "True")
|
||||
build_stub(BASE_DIR)
|
||||
run_cmake()
|
||||
copy_hpp()
|
||||
copy_lib()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
build_libtorch_npu()
|
||||
@@ -23,6 +23,7 @@ from abc import ABCMeta, abstractmethod
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
DEFAULT_UT_FILE = os.path.join(BASE_DIR, 'ci/pytorch_resnet.py')
|
||||
TEST_OPS = os.path.join(BASE_DIR, 'test/test_ops.py')
|
||||
|
||||
|
||||
class AccurateTest(metaclass=ABCMeta):
|
||||
@@ -64,7 +65,7 @@ class OpStrategy(AccurateTest):
|
||||
if filename.find('KernelNpu') >= 0:
|
||||
feature_line = filename.split('KernelNpu')[0]
|
||||
features = re.findall('[A-Z][^A-Z]*', feature_line)
|
||||
regex = '*' + '*'.join(["%s" % feature.lower() for feature in features]) + '*'
|
||||
regex = '*' + '*'.join([f"{feature.lower()}" for feature in features]) + '*'
|
||||
return AccurateTest.find_ut_by_regex(regex)
|
||||
return []
|
||||
|
||||
@@ -75,9 +76,7 @@ class DirectoryStrategy(AccurateTest):
|
||||
"""
|
||||
def identify(self, modify_file):
|
||||
second_dir = modify_file.split("/")[0]
|
||||
if second_dir == 'test':
|
||||
return [os.path.join(BASE_DIR, modify_file)]
|
||||
return []
|
||||
return [os.path.join(BASE_DIR, modify_file)] if second_dir == 'test' else []
|
||||
|
||||
|
||||
class CopyOptStrategy(AccurateTest):
|
||||
@@ -94,7 +93,10 @@ class CopyOptStrategy(AccurateTest):
|
||||
class TestMgr():
|
||||
def __init__(self):
|
||||
self.modify_files = []
|
||||
self.ut_files = []
|
||||
self.test_files = {
|
||||
'ut_files': [],
|
||||
'op_ut_files': []
|
||||
}
|
||||
|
||||
def load(self, modify_files):
|
||||
with open(modify_files) as f:
|
||||
@@ -104,20 +106,22 @@ class TestMgr():
|
||||
|
||||
def analyze(self):
|
||||
for modify_file in self.modify_files:
|
||||
self.ut_files += DirectoryStrategy().identify(modify_file)
|
||||
self.ut_files += OpStrategy().identify(modify_file)
|
||||
self.ut_files += CopyOptStrategy().identify(modify_file)
|
||||
unique_files = set(self.ut_files)
|
||||
self.test_files['ut_files'] += DirectoryStrategy().identify(modify_file)
|
||||
self.test_files['ut_files'] += CopyOptStrategy().identify(modify_file)
|
||||
self.test_files['ut_files'] += OpStrategy().identify(modify_file)
|
||||
self.test_files['op_ut_files'] += OpStrategy().identify(modify_file)
|
||||
unique_files = set(self.test_files['ut_files'])
|
||||
|
||||
exist_ut_file = []
|
||||
for changed_file in unique_files:
|
||||
if os.path.exists(changed_file):
|
||||
exist_ut_file.append(changed_file)
|
||||
self.ut_files = exist_ut_file
|
||||
self.ut_files.append(DEFAULT_UT_FILE)
|
||||
exist_ut_file = [
|
||||
changed_file
|
||||
for changed_file in unique_files
|
||||
if os.path.exists(changed_file)
|
||||
]
|
||||
self.test_files['ut_files'] = exist_ut_file
|
||||
self.test_files['ut_files'].append(DEFAULT_UT_FILE)
|
||||
|
||||
def get_ut_files(self):
|
||||
return self.ut_files
|
||||
def get_test_files(self):
|
||||
return self.test_files
|
||||
|
||||
def print_modify_files(self):
|
||||
print("modify files:")
|
||||
@@ -126,46 +130,74 @@ class TestMgr():
|
||||
|
||||
def print_ut_files(self):
|
||||
print("ut files:")
|
||||
for ut_file in self.ut_files:
|
||||
for ut_file in self.test_files['ut_files']:
|
||||
print(ut_file)
|
||||
|
||||
def print_op_ut_files(self):
|
||||
print("op ut files:")
|
||||
for op_ut_file in self.test_files['op_ut_files']:
|
||||
print(op_ut_file)
|
||||
|
||||
|
||||
def exec_ut(ut_files):
|
||||
def exec_ut(files):
|
||||
"""
|
||||
执行单元测试文件,其中存在失败,则标识异常并打印相关信息
|
||||
"""
|
||||
def change_dir_and_exec(ut_path):
|
||||
ut_dir = os.path.dirname(ut_path)
|
||||
ut_file = os.path.basename(ut_path)
|
||||
def get_ut_name(ut_file):
|
||||
return ut_file.split('/')[-1].split('.')[0].lstrip('test_')
|
||||
|
||||
def change_dir_and_exec(ut_path, is_op_ut=False):
|
||||
if is_op_ut:
|
||||
ut_dir = os.path.dirname(TEST_OPS)
|
||||
cmd = f'python3 -m unittest test_ops.py -v -k {ut_path}_'
|
||||
else:
|
||||
ut_dir = os.path.dirname(ut_path)
|
||||
ut_file = os.path.basename(ut_path)
|
||||
cmd = f'python3 {ut_file}'
|
||||
|
||||
os.chdir(ut_dir)
|
||||
cmd = "python3 {}".format(ut_file)
|
||||
p = subprocess.Popen(['python3', ut_file], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
|
||||
p = subprocess.Popen(cmd.split(' '), stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
|
||||
|
||||
try:
|
||||
msg = p.communicate(timeout=300)
|
||||
msg = p.communicate(timeout=2000)
|
||||
ret = p.poll()
|
||||
if ret:
|
||||
print(msg)
|
||||
|
||||
stdout = msg[0].decode('utf-8')
|
||||
stderr = msg[1].decode('utf-8') if msg[1] else msg[1]
|
||||
print(stdout, stderr)
|
||||
except subprocess.TimeoutExpired:
|
||||
p.kill()
|
||||
p.terminate()
|
||||
ret = 1
|
||||
print("Timeout: Command '" + cmd + "' timed out after 300 seconds")
|
||||
print(f"Timeout: Command '{cmd}' timed out after 2000 seconds")
|
||||
except Exception as err:
|
||||
ret = 1
|
||||
print(err)
|
||||
return ret
|
||||
|
||||
ut_files = files['ut_files']
|
||||
op_ut_files = files['op_ut_files']
|
||||
ret_status = 0
|
||||
exec_infos = []
|
||||
for ut_file in ut_files:
|
||||
temp_ret = change_dir_and_exec(ut_file)
|
||||
|
||||
if temp_ret:
|
||||
ret_status = temp_ret
|
||||
exec_infos.append("exec ut {} failed.".format(ut_file))
|
||||
else:
|
||||
exec_infos.append("exec ut {} success.".format(ut_file))
|
||||
|
||||
|
||||
for op_ut_file in op_ut_files:
|
||||
ut_name = get_ut_name(op_ut_file)
|
||||
op_ut_ret = change_dir_and_exec(ut_name, True)
|
||||
|
||||
if op_ut_ret:
|
||||
ret_status = op_ut_ret
|
||||
exec_infos.append("exec ut test_ops.py {} failed.".format(ut_name))
|
||||
else:
|
||||
exec_infos.append("exec ut test_ops.py {} success.".format(ut_name))
|
||||
|
||||
print("***** Total result:")
|
||||
for exec_info in exec_infos:
|
||||
print(exec_info)
|
||||
@@ -177,10 +209,11 @@ if __name__ == "__main__":
|
||||
test_mgr = TestMgr()
|
||||
test_mgr.load(cur_modify_files)
|
||||
test_mgr.analyze()
|
||||
cur_ut_files = test_mgr.get_ut_files()
|
||||
cur_test_files = test_mgr.get_test_files()
|
||||
|
||||
test_mgr.print_modify_files()
|
||||
test_mgr.print_ut_files()
|
||||
test_mgr.print_op_ut_files()
|
||||
|
||||
ret_ut = exec_ut(cur_ut_files)
|
||||
sys.exit(ret_ut)
|
||||
ret_ut = exec_ut(cur_test_files)
|
||||
sys.exit(ret_ut)
|
||||
|
||||
@@ -58,12 +58,10 @@ def name(func: FunctionSchema, *, faithful_name_for_out_overloads: bool = False)
|
||||
# types. Returns None if the type in question is not a value type.
|
||||
def valuetype_type(t: Type, *, binds: ArgName) -> Optional[NamedCType]:
|
||||
if isinstance(t, BaseType):
|
||||
if t.name == BaseTy.Tensor:
|
||||
if t.name == BaseTy.Tensor or t.name == BaseTy.Scalar:
|
||||
return None
|
||||
elif t.name in BaseTypeToCppMapping:
|
||||
return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name]))
|
||||
else:
|
||||
raise AssertionError(f"unsupported type {repr(t)}")
|
||||
# All other BaseType currently map directly to BaseCppTypes.
|
||||
return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name]))
|
||||
elif isinstance(t, OptionalType):
|
||||
elem = valuetype_type(t.elem, binds=binds)
|
||||
if elem is None:
|
||||
@@ -205,7 +203,7 @@ JIT_TO_CPP_DEFAULT = {
|
||||
'None': 'c10::nullopt', # UGH this one is type directed
|
||||
'Mean': 'at::Reduction::Mean',
|
||||
'[]': '{}',
|
||||
'contiguous_format': 'MemoryFormat::Contiguous',
|
||||
'contiguous_format': 'c10::MemoryFormat::Contiguous',
|
||||
'long': 'at::kLong',
|
||||
}
|
||||
|
||||
@@ -58,25 +58,35 @@ def returns_type(rs: Sequence[Return]) -> CType:
|
||||
# At present, there is no difference. But there could be!
|
||||
return cpp.returns_type(rs)
|
||||
|
||||
def jit_arguments(func: FunctionSchema) -> List[Argument]:
|
||||
def to_argument(a: Union[Argument, TensorOptionsArguments, SelfArgument]) -> List[Argument]:
|
||||
if isinstance(a, Argument):
|
||||
return [a]
|
||||
elif isinstance(a, SelfArgument):
|
||||
return [a.argument]
|
||||
elif isinstance(a, TensorOptionsArguments):
|
||||
return [a.dtype, a.layout, a.device, a.pin_memory]
|
||||
else:
|
||||
assert_never(a)
|
||||
return list(concat_map(to_argument, itertools.chain(
|
||||
func.arguments.positional,
|
||||
func.arguments.kwarg_only,
|
||||
func.arguments.out)))
|
||||
def argument(a: Union[Argument, SelfArgument, TensorOptionsArguments], *, is_out: bool) -> List[Binding]:
|
||||
|
||||
should_default = not is_out
|
||||
if isinstance(a, Argument):
|
||||
default: Optional[str] = None
|
||||
if should_default and a.default is not None:
|
||||
default = cpp.default_expr(a.default, a.type)
|
||||
return [
|
||||
Binding(
|
||||
nctype=argument_type(a, binds=a.name),
|
||||
name=a.name,
|
||||
default=default,
|
||||
argument=a)
|
||||
]
|
||||
elif isinstance(a, SelfArgument):
|
||||
return argument(a.argument, is_out=is_out)
|
||||
elif isinstance(a, TensorOptionsArguments):
|
||||
return (
|
||||
argument(a.dtype, is_out=is_out) +
|
||||
argument(a.layout, is_out=is_out) +
|
||||
argument(a.device, is_out=is_out) +
|
||||
argument(a.pin_memory, is_out=is_out)
|
||||
)
|
||||
else:
|
||||
assert_never(a)
|
||||
|
||||
def arguments(func: FunctionSchema) -> List[Binding]:
|
||||
return [
|
||||
Binding(
|
||||
nctype=argument_type(a, binds=a.name),
|
||||
name=a.name,
|
||||
argument=a,
|
||||
) for a in jit_arguments(func)]
|
||||
args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
|
||||
args.extend(func.arguments.positional)
|
||||
args.extend(func.arguments.kwarg_only)
|
||||
args.extend(func.arguments.out)
|
||||
return [r for arg in args for r in argument(arg, is_out=func.is_out_fn())]
|
||||
@@ -17,8 +17,7 @@
|
||||
from typing import Union, Sequence, List, Optional
|
||||
|
||||
from codegen.model import (Argument, FunctionSchema, Return,
|
||||
SelfArgument, TensorOptionsArguments, Type, UseC10Dispatcher,
|
||||
assert_never)
|
||||
SelfArgument, TensorOptionsArguments, Type)
|
||||
|
||||
from codegen.api.types import (ArgName, BaseCType, Binding,
|
||||
ConstRefCType, NamedCType, CType, MutRefCType, ListCType,
|
||||
@@ -26,6 +25,7 @@ from codegen.api.types import (ArgName, BaseCType, Binding,
|
||||
deviceT, boolT, scalarTypeT)
|
||||
from codegen.api import cpp
|
||||
from codegen import local
|
||||
from codegen.model import assert_never
|
||||
|
||||
# This file describes the translation of JIT schema to the native functions API.
|
||||
# This looks a lot like the C++ API (which makes historical sense, because the
|
||||
@@ -53,6 +53,10 @@ def argumenttype_type(t: Type, *, mutable: bool, binds: ArgName) -> NamedCType:
|
||||
return NamedCType(binds, ConstRefCType(tensor_type))
|
||||
elif str(t) == 'Tensor?[]':
|
||||
return NamedCType(binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))))
|
||||
elif str(t) == 'Scalar':
|
||||
return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
|
||||
elif str(t) == 'Scalar?':
|
||||
return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT))))
|
||||
return cpp.argumenttype_type(t, mutable=mutable, binds=binds)
|
||||
|
||||
def returns_type(rs: Sequence[Return]) -> CType:
|
||||
@@ -120,15 +124,4 @@ def arguments(func: FunctionSchema) -> List[Binding]:
|
||||
args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
|
||||
args.extend(func.arguments.non_out)
|
||||
args.extend(func.arguments.out)
|
||||
return [r for arg in args for r in argument(arg, is_out=func.is_out_fn())]
|
||||
|
||||
def native_arguments(func: FunctionSchema, dispatch: UseC10Dispatcher) -> List[Binding]:
|
||||
args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
|
||||
if dispatch is UseC10Dispatcher.full:
|
||||
args.extend(func.arguments.non_out)
|
||||
args.extend(func.arguments.out)
|
||||
else:
|
||||
args.extend(func.arguments.out)
|
||||
args.extend(func.arguments.non_out)
|
||||
|
||||
return [r for arg in args for r in argument(arg, is_out=func.is_out_fn())]
|
||||
@@ -641,7 +641,7 @@ def argument_type_str(t: Type, *, simple_type: bool = False) -> str:
|
||||
BaseTy.Tensor: 'Tensor',
|
||||
BaseTy.int: 'int64_t',
|
||||
BaseTy.float: 'double',
|
||||
BaseTy.str: 'std::string'
|
||||
BaseTy.str: 'c10::string_view'
|
||||
}
|
||||
if t.name in base_dict:
|
||||
return base_dict[t.name]
|
||||
@@ -1048,7 +1048,7 @@ def arg_parser_unpack_method(t: Type, has_default: bool) -> str:
|
||||
BaseTy.int: 'toInt64',
|
||||
BaseTy.bool: 'toBool',
|
||||
BaseTy.float: 'toDouble',
|
||||
BaseTy.str: 'string'
|
||||
BaseTy.str: 'stringView'
|
||||
}
|
||||
if t.name in [BaseTy.Tensor, BaseTy.Stream, BaseTy.Storage,
|
||||
BaseTy.Scalar, BaseTy.Dimname]:
|
||||
@@ -49,7 +49,7 @@ intT = BaseCppType('', 'int64_t')
|
||||
doubleT = BaseCppType('', 'double')
|
||||
boolT = BaseCppType('', 'bool')
|
||||
voidT = BaseCppType('', 'void')
|
||||
stringT = BaseCppType('std', 'string')
|
||||
stringT = BaseCppType('c10', 'string_view')
|
||||
generatorT = BaseCppType('at', 'Generator')
|
||||
scalarTypeT = BaseCppType('at', 'ScalarType')
|
||||
tensorT = BaseCppType('at', 'Tensor')
|
||||
@@ -366,7 +366,11 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
|
||||
device_check = RegisterDispatchKey.gen_device_check(f.device_check, list(device_check_args), name)
|
||||
|
||||
device_guard = "// DeviceGuard omitted" # default
|
||||
record_func_def = "torch_npu::profiler::NPURecordFunction guard;"
|
||||
record_func_def = """
|
||||
#ifndef BUILD_LIBTORCH
|
||||
torch_npu::profiler::NPURecordFunction guard;
|
||||
#endif
|
||||
"""
|
||||
if f.device_guard and is_cuda_dispatch_key(self.backend_index.dispatch_key):
|
||||
has_tensor_options = any(isinstance(a.argument, TensorOptionsArguments) for a in args)
|
||||
if has_tensor_options:
|
||||
@@ -36,7 +36,6 @@ from codegen.api.signature import (CppSignature, CppSignatureGroup, kernel_signa
|
||||
import codegen.api.meta as meta
|
||||
import codegen.api.cpp as cpp
|
||||
import codegen.api.structured as structured
|
||||
import codegen.api.native as native_arguments
|
||||
from codegen.api.translate import translate
|
||||
from codegen.selective_build.selector import SelectiveBuilder
|
||||
from codegen.api.types import (BaseCType, TupleCType, BaseCppType)
|
||||
@@ -19,15 +19,19 @@ from codegen.api.types import (BaseCType, TupleCType, OptionalCType, BaseCppType
|
||||
|
||||
from codegen.api.signature import DispatcherSignature, NativeSignature
|
||||
from codegen.model import SchemaKind, NativeFunction
|
||||
from codegen.api.native import native_arguments
|
||||
from codegen.api.native import arguments
|
||||
|
||||
backend = None
|
||||
|
||||
def transfer_args_of_wrapper_func_to_cpu(sig: DispatcherSignature, func: NativeFunction) -> Tuple[str, List[str]]:
|
||||
convert: str = f"// Convert args to cpu in order to use at::native kernel \n " \
|
||||
f"std::cout << \"Cur kernel: {sig.func.name} is running on cpu.\" << std::endl; \n "
|
||||
f"static auto warn_once = [](){{ \n " \
|
||||
f"std::cout << \"Warning: kernel [{sig.func.name}] is not supported by NPU currently. " \
|
||||
f"Now this kernel is running on CPU.\" << std::endl; \n " \
|
||||
f"return true; \n " \
|
||||
f"}}(); \n "
|
||||
args_names: List[str] = []
|
||||
args = native_arguments(sig.func, func.use_c10_dispatcher)
|
||||
args = arguments(sig.func)
|
||||
for arg in args:
|
||||
arg_type = str(arg.type)
|
||||
if 'Tensor' not in arg_type:
|
||||
@@ -126,4 +130,4 @@ auto cpu_ret = {func_call};
|
||||
else:
|
||||
assert False, f'Do not support cur func type {sig.func.kind()}'
|
||||
|
||||
return ret_code
|
||||
return ret_code
|
||||
@@ -41,6 +41,8 @@ def create_backend_index(backend_ops: List[str],
|
||||
for op in backend_ops:
|
||||
op_name = OperatorName.parse(op)
|
||||
assert op_name in native_funcs_map, f"Found an invalid operator name: {op_name}"
|
||||
if os.environ.get('BSCPP_OPS_ENABLE') is None and native_funcs_map[op_name].bscpp_op:
|
||||
continue
|
||||
# See Note [External Backends Follow Dispatcher API]
|
||||
kernel_name = dispatcher.name(native_funcs_map[op_name].func)
|
||||
# TODO: allow structured external backends later.
|
||||
@@ -153,7 +155,8 @@ def parse_backend_yaml(
|
||||
|
||||
valid_keys = ['backend', 'cpp_namespace', 'extra_headers', 'supported', 'autograd', 'custom', 'custom_autograd']
|
||||
|
||||
true_backend = yaml_values.pop('backend', None)
|
||||
yaml_backend = yaml_values.pop('backend', None)
|
||||
true_backend = 'XLA' if yaml_backend=='NPU' else yaml_backend
|
||||
assert true_backend is not None, 'You must provide a value for "backend"'
|
||||
backend = "NPU"
|
||||
|
||||
@@ -242,16 +245,10 @@ def error_on_missing_kernels(
|
||||
expected_backend_kernel_name_counts[dispatcher.name(native_f.func)].append(native_f)
|
||||
|
||||
missing_kernels_err_msg = ""
|
||||
unsupported_ops_list = ""
|
||||
for expected_name, funcs in expected_backend_kernel_name_counts.items():
|
||||
expected_overload_count = len(funcs)
|
||||
actual_overload_count = actual_backend_kernel_name_counts[expected_name]
|
||||
if actual_overload_count == 0:
|
||||
for func in funcs:
|
||||
backend_indices[backend_key].index.pop(func.func.name, None)
|
||||
backend_indices[autograd_key].index.pop(func.func.name, None)
|
||||
unsupported_ops_list += f"{func.func.name}\n"
|
||||
elif expected_overload_count != actual_overload_count:
|
||||
if expected_overload_count != actual_overload_count:
|
||||
def create_decl(f: NativeFunction) -> str:
|
||||
with native_function_manager(f):
|
||||
return DispatcherSignature.from_schema(f.func).decl()
|
||||
@@ -262,8 +259,7 @@ but expected {expected_overload_count} kernel(s). The expected function schemas
|
||||
{expected_schemas_str}
|
||||
"""
|
||||
assert missing_kernels_err_msg == "", missing_kernels_err_msg
|
||||
if unsupported_ops_list != "":
|
||||
print(f"Unsupported Ops List:\n{unsupported_ops_list}")
|
||||
|
||||
|
||||
def error_on_cpu_kernels(
|
||||
cur_backend_key: DispatchKey,
|
||||
@@ -283,6 +279,7 @@ def error_on_cpu_kernels(
|
||||
for func in funcs:
|
||||
backend_indices[DispatchKey.CPU].index.pop(func.func.name, None)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description='Generate backend stub files')
|
||||
parser.add_argument(
|
||||
@@ -301,6 +298,7 @@ def main() -> None:
|
||||
|
||||
run(options.to_cpu, options.source_yaml, options.output_dir, options.dry_run, options.impl_path)
|
||||
|
||||
|
||||
def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path: Optional[str]) -> None:
|
||||
|
||||
template_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "templates")
|
||||
@@ -323,6 +321,8 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
|
||||
backend_indices = parsed_backend_yaml.backend_indices
|
||||
|
||||
selector = SelectiveBuilder.get_nop_selector()
|
||||
|
||||
|
||||
if backend_key is not None:
|
||||
backend_dispatch_key: DispatchKey = backend_key
|
||||
autograd_dispatch_key: DispatchKey = autograd_key
|
||||
@@ -393,7 +393,7 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
|
||||
grouped_native_functions
|
||||
)),
|
||||
})
|
||||
|
||||
|
||||
if to_cpu.upper() in ['OFF', '0', 'NO', 'FALSE', 'F', 'N']:
|
||||
return
|
||||
|
||||
@@ -441,5 +441,6 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
|
||||
)),
|
||||
})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
from collections import defaultdict, namedtuple
|
||||
from typing import Dict, Optional, List, Tuple, Set, Sequence, Callable
|
||||
@@ -138,6 +139,9 @@ def parse_custom_yaml(custom_path: str) -> ParsedYaml:
|
||||
|
||||
@with_native_function
|
||||
def should_generate_py_binding(f: NativeFunction) -> bool:
|
||||
if os.environ.get('BSCPP_OPS_ENABLE') is None and f.bscpp_op:
|
||||
return False
|
||||
|
||||
name = cpp.name(f.func)
|
||||
for skip_regex in SKIP_PYTHON_BINDINGS:
|
||||
if skip_regex.match(name):
|
||||
@@ -344,6 +348,9 @@ static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs)
|
||||
}, /*traceable=*/${traceable});
|
||||
torch::ParsedArgs<${max_args}> parsed_args;
|
||||
auto _r = parser.parse(${self_}, args, kwargs, parsed_args);
|
||||
if(_r.has_torch_function()) {
|
||||
return torch::handle_torch_function(_r, args, kwargs, THPVariableFunctionsModule, "torch");
|
||||
}
|
||||
switch (_r.idx) {
|
||||
${dispatch}
|
||||
}
|
||||
@@ -371,6 +378,9 @@ static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs)
|
||||
}, /*traceable=*/${traceable});
|
||||
torch::ParsedArgs<${max_args}> parsed_args;
|
||||
auto _r = parser.parse(${self_}, args, kwargs, parsed_args);
|
||||
if(_r.has_torch_function()) {
|
||||
return torch::handle_torch_function(_r, args, kwargs, THPVariableFunctionsModule, "torch");
|
||||
}
|
||||
${dispatch}
|
||||
${method_footer}
|
||||
}
|
||||
@@ -95,6 +95,7 @@ class DispatchKey(Enum):
|
||||
PrivateUse3 = auto()
|
||||
EndOfBackendKeys = PrivateUse3
|
||||
|
||||
ZeroTensor = auto()
|
||||
Meta = auto()
|
||||
BackendSelect = auto()
|
||||
Named = auto()
|
||||
@@ -172,6 +173,19 @@ class DeviceCheckType(Enum):
|
||||
NoCheck = 0
|
||||
ExactSame = 1
|
||||
|
||||
class Tag(Enum):
|
||||
inplace_view = 0
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
@staticmethod
|
||||
def parse(value: str) -> 'Tag':
|
||||
for k, v in Tag.__members__.items():
|
||||
if k == value:
|
||||
return v
|
||||
raise AssertionError(f'unknown tag {value}')
|
||||
|
||||
# The basic input to the code generation is native_functions.yaml.
|
||||
# The name "native", BTW, comes from the distinction between native
|
||||
# functions and legacy TH functions. The legacy TH functions are gone,
|
||||
@@ -193,10 +207,6 @@ class NativeFunction:
|
||||
# classes for expository clarity.)
|
||||
func: 'FunctionSchema'
|
||||
|
||||
# Corresponds to the 'use_c10_dispatcher' field. The default
|
||||
# is 'full'
|
||||
use_c10_dispatcher: UseC10Dispatcher
|
||||
|
||||
# Whether or not to generate mutable tensor arguments like regular
|
||||
# ones
|
||||
use_const_ref_for_mutable_tensors: bool
|
||||
@@ -273,6 +283,14 @@ class NativeFunction:
|
||||
has_composite_implicit_autograd_kernel: bool
|
||||
has_composite_explicit_autograd_kernel: bool
|
||||
|
||||
# Tags are used to describe semantic information about (groups of) operators,
|
||||
# That aren't easily inferrable directly from the operator's schema.
|
||||
# For now operators have at most one tag.
|
||||
tag: Optional['Tag']
|
||||
|
||||
# Whether or not the NativeFunction is bishengcpp kernel
|
||||
bscpp_op: bool
|
||||
|
||||
# NB: The benefit of defining a dataclass is that we automatically get
|
||||
# a constructor defined for all the fields we specify. No need
|
||||
# to explicitly write it out.
|
||||
@@ -295,19 +313,6 @@ class NativeFunction:
|
||||
cpp_no_default_args = set(cpp_no_default_args_list)
|
||||
return cpp_no_default_args
|
||||
|
||||
def parse_use_dispatcher(e):
|
||||
use_c10_dispatcher_s = e.pop('use_c10_dispatcher', None)
|
||||
assert use_c10_dispatcher_s != 'full', \
|
||||
"No need to specify 'use_c10_dispatcher: full' anymore. This is the default now. Just remove the line."
|
||||
if use_c10_dispatcher_s is None:
|
||||
use_c10_dispatcher = UseC10Dispatcher.full
|
||||
elif use_c10_dispatcher_s == 'hacky_wrapper_for_legacy_signatures':
|
||||
use_c10_dispatcher = UseC10Dispatcher.hacky_wrapper_for_legacy_signatures
|
||||
else:
|
||||
raise AssertionError(f'use_c10_dispatcher must be full or hacky_wrapper_for_legacy_signatures,'
|
||||
f' got {use_c10_dispatcher_s}')
|
||||
return use_c10_dispatcher
|
||||
|
||||
def parse_variants(e):
|
||||
variants_s = e.pop('variants', 'function')
|
||||
assert isinstance(variants_s, str)
|
||||
@@ -323,7 +328,6 @@ class NativeFunction:
|
||||
|
||||
func = parse_func(e)
|
||||
cpp_no_default_args = parse_cpp_no_default_args(e)
|
||||
use_c10_dispatcher = parse_use_dispatcher(e)
|
||||
variants = parse_variants(e)
|
||||
|
||||
use_const_ref_for_mutable_tensors = e.pop('use_const_ref_for_mutable_tensors', False)
|
||||
@@ -374,6 +378,15 @@ class NativeFunction:
|
||||
|
||||
precomputed = parse_precomputed(e, structured)
|
||||
|
||||
def parse_tag(e, structured):
|
||||
tag_str = e.pop('tags', None)
|
||||
assert tag_str is None or isinstance(tag_str, str), f'not a str: {tag_str}'
|
||||
tag = Tag.parse(tag_str) if tag_str else None
|
||||
return tag
|
||||
|
||||
tag = parse_tag(e, structured)
|
||||
bscpp_op = e.pop("bscpp_op", False)
|
||||
|
||||
from codegen.api import cpp
|
||||
|
||||
def parse_dispatch(e, func, manual_kernel_registration, structured_delegate, structured):
|
||||
@@ -433,7 +446,7 @@ class NativeFunction:
|
||||
f"if structured_delegate, then must not have {key} in dispatch dictionary " \
|
||||
"(it is delegated!)"
|
||||
assert_last(e, structured_delegate, dispatch)
|
||||
return NativeFunction(func=func, use_c10_dispatcher=use_c10_dispatcher,
|
||||
return NativeFunction(func=func,
|
||||
use_const_ref_for_mutable_tensors=use_const_ref_for_mutable_tensors,
|
||||
variants=variants, structured=structured, structured_delegate=structured_delegate,
|
||||
structured_inherits=structured_inherits, precomputed=precomputed,
|
||||
@@ -441,7 +454,8 @@ class NativeFunction:
|
||||
python_module=python_module, category_override=category_override, device_guard=device_guard,
|
||||
device_check=device_check, cpp_no_default_args=cpp_no_default_args, is_abstract=is_abstract,
|
||||
has_composite_implicit_autograd_kernel=has_composite_implicit_autograd_kernel,
|
||||
has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel), backend_metadata
|
||||
has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel, tag=tag,
|
||||
bscpp_op=bscpp_op), backend_metadata
|
||||
|
||||
|
||||
def validate_unstructured(self) -> None:
|
||||
@@ -481,9 +495,6 @@ class NativeFunction:
|
||||
if a.default is not None}
|
||||
invalid_args = set.difference(self.cpp_no_default_args, defaulted_arguments)
|
||||
assert len(invalid_args) == 0, f'Invalid cpp_no_default_args: {invalid_args}'
|
||||
if self.structured or self.structured_delegate:
|
||||
assert self.use_c10_dispatcher is UseC10Dispatcher.full, \
|
||||
"Structured kernels MUST be use_c10_dispatcher: full; port your argument order"
|
||||
if self.structured_inherits is not None:
|
||||
assert self.structured, "structured_inherits must also imply structured: True"
|
||||
if str(self.func.name).startswith('_foreach'):
|
||||
@@ -682,7 +693,7 @@ class BackendIndex:
|
||||
elif isinstance(g, NativeFunctionsGroup):
|
||||
f = self.primary(g)
|
||||
else:
|
||||
assert_never(f)
|
||||
assert_never(g)
|
||||
if f.func.name not in self.index:
|
||||
return None
|
||||
return self.index[f.func.name]
|
||||
@@ -771,7 +782,9 @@ class FunctionSchema:
|
||||
def parse(func: str) -> 'FunctionSchema':
|
||||
# We should probably get a proper parser here
|
||||
assert ' -> ' in func, "function schema missing return type (spaces are mandatory)"
|
||||
func_decl, return_decl = [x.strip() for x in func.split(' -> ')]
|
||||
last_index = func.rfind(" -> ")
|
||||
func_decl = func[:last_index]
|
||||
return_decl = func[last_index + len(" -> "):]
|
||||
ops, args = func_decl.split('(', 1)
|
||||
assert args[-1] == ")", "Expecting closing )"
|
||||
args = args[:-1]
|
||||
@@ -912,19 +925,31 @@ class Annotation:
|
||||
# we can conveniently assume it is canonically ordered
|
||||
alias_set: Tuple[str, ...]
|
||||
is_write: bool
|
||||
alias_set_after: str
|
||||
|
||||
@staticmethod
|
||||
def parse(ann: str) -> 'Annotation':
|
||||
m = re.match(r'^([a-z])(!?)(!?)$', ann)
|
||||
# Only handling afterSet == Wildcard for now
|
||||
becomes_wildcard_index = ann.find(" -> *")
|
||||
if becomes_wildcard_index != -1:
|
||||
after_set = "*"
|
||||
# TODO: im not good enough with regexes to ignore -> *
|
||||
m = re.match(r'^([a-z])(!?)(!?)$',
|
||||
ann[:becomes_wildcard_index] + ann[becomes_wildcard_index + len(" -> *"):])
|
||||
else:
|
||||
after_set = ""
|
||||
m = re.match(r'^([a-z])(!?)(!?)$', ann)
|
||||
assert m is not None, f'unrecognized alias annotation {ann}'
|
||||
alias_set = (m.group(1),)
|
||||
is_write = m.group(2) == '!'
|
||||
r = Annotation(alias_set=alias_set, is_write=is_write)
|
||||
r = Annotation(alias_set=alias_set, is_write=is_write, alias_set_after=after_set)
|
||||
assert str(r) == ann, f'{r} != {ann}'
|
||||
return r
|
||||
|
||||
def __str__(self) -> str:
|
||||
alias_set = '|'.join(self.alias_set)
|
||||
if self.alias_set_after:
|
||||
alias_set = f'{alias_set}{" -> "}{self.alias_set_after}'
|
||||
is_write = '!' if self.is_write else ''
|
||||
return f'{alias_set}{is_write}'
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Copyright (c) 2023 Huawei Technologies Co., Ltd
|
||||
// Copyright (c) 2022, Facebook CORPORATION.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Licensed under the BSD 3-Clause License (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://opensource.org/licenses/BSD-3-Clause
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
#ifndef __SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__
|
||||
#define __SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__
|
||||
|
||||
|
||||
#include <ATen/Tensor.h>
|
||||
#include <ATen/ATen.h>
|
||||
#include <c10/core/Device.h>
|
||||
|
||||
namespace at_npu {
|
||||
namespace key {
|
||||
static constexpr c10::DeviceType NativeDeviceType = c10::DeviceType::XLA;
|
||||
static constexpr c10::DispatchKey NativeDispatchKey = c10::DispatchKey::XLA;
|
||||
static constexpr c10::DispatchKey NativeAutogradDispatchKey = c10::DispatchKey::AutogradXLA;
|
||||
static constexpr c10::Backend NativeBackend = c10::Backend::XLA;
|
||||
static const std::string npu_device_str = "npu";
|
||||
static const std::string default_device_str = "xla";
|
||||
|
||||
static bool isDeviceTensor(const at::Tensor &tensor) {
|
||||
return tensor.is_xla();
|
||||
}
|
||||
|
||||
} // namespace key
|
||||
} // namespace at_npu
|
||||
|
||||
// ${generated_comment}
|
||||
namespace ${cpp_namespace} {
|
||||
|
||||
struct ${class_name} {
|
||||
|
||||
${dispatch_declarations}
|
||||
|
||||
};
|
||||
} // namespace ${cpp_namespace}
|
||||
|
||||
#endif
|
||||
@@ -33,7 +33,6 @@
|
||||
#include <ATen/WrapDimUtils.h>
|
||||
#include <ATen/Dispatch.h>
|
||||
#include <c10/util/Half.h>
|
||||
#include <c10/core/TensorImpl.h>
|
||||
#include <c10/core/UndefinedTensorImpl.h>
|
||||
#include <c10/util/Optional.h>
|
||||
#include <ATen/Tensor.h>
|
||||
@@ -46,11 +45,12 @@
|
||||
#include <utility>
|
||||
|
||||
#include <ATen/Config.h>
|
||||
#include <ATen/core/op_registration/hacky_wrapper_for_legacy_signatures.h>
|
||||
#include <torch/library.h>
|
||||
#include "torch_npu/csrc/profiler/utils.h"
|
||||
|
||||
$legacy_th_headers
|
||||
#ifndef BUILD_LIBTORCH
|
||||
#include "torch_npu/csrc/profiler/utils.h"
|
||||
#endif
|
||||
|
||||
$external_backend_headers
|
||||
$namespaced_headers
|
||||
|
||||
@@ -1,3 +1,19 @@
|
||||
// Copyright (c) 2020 Huawei Technologies Co., Ltd
|
||||
// Copyright (c) 2019, Facebook CORPORATION.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Licensed under the BSD 3-Clause License (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://opensource.org/licenses/BSD-3-Clause
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// ${generated_comment}
|
||||
|
||||
// Python bindings for torch.* functions implemented through ATen.
|
||||
@@ -31,6 +47,7 @@
|
||||
#include <torch/csrc/utils/structseq.h>
|
||||
#include <torch/csrc/utils/cuda_lazy_init.h>
|
||||
#include <ATen/ATen.h>
|
||||
#include <ATen/record_function.h>
|
||||
|
||||
#include <functional>
|
||||
#include <initializer_list>
|
||||
@@ -39,6 +56,7 @@
|
||||
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/utils/LazyInit.h"
|
||||
#include "torch_npu/csrc/utils/DeviceParser.h"
|
||||
|
||||
using at::Tensor;
|
||||
using at::Device;
|
||||
@@ -13,18 +13,11 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import numpy
|
||||
import torch
|
||||
|
||||
|
||||
import torch_npu
|
||||
from torch_npu.utils.device_guard import torch_device_guard, device
|
||||
|
||||
|
||||
@torch_device_guard
|
||||
def _device(*args, **kwargs):
|
||||
new_device = torch_npu.new_device(*args, **kwargs)
|
||||
if new_device.type == torch.npu.native_device:
|
||||
return device(type=torch_npu.npu.npu_device, index=new_device.index)
|
||||
return new_device
|
||||
from torch_npu.utils.device_guard import torch_device_guard
|
||||
|
||||
|
||||
@torch_device_guard
|
||||
@@ -62,26 +55,31 @@ def _npu_dropout_gen_mask(*args, **kwargs):
|
||||
return torch_npu.npu_dropout_gen_mask(*args, **kwargs)
|
||||
|
||||
|
||||
@torch_device_guard
|
||||
def _new_device(*args, **kwargs):
|
||||
return torch_npu._C.device(*args, **kwargs)
|
||||
|
||||
|
||||
def jit_script(obj, optimize=None, _frames_up=0, _rcb=None):
|
||||
# (Ascend) Disable extension of torch.jit.script
|
||||
return obj
|
||||
|
||||
|
||||
def _as_tensor(*args, **kwargs):
|
||||
if isinstance(args[0], torch.Tensor):
|
||||
dst_device = args[0].device
|
||||
else:
|
||||
dst_device = "cpu"
|
||||
|
||||
if kwargs and "device" in kwargs:
|
||||
dst_device = kwargs.get("device")
|
||||
if "npu" in str(dst_device):
|
||||
if isinstance(args[0], numpy.ndarray):
|
||||
return torch.from_numpy(args[0]).to(dst_device)
|
||||
else:
|
||||
return args[0].to(dst_device)
|
||||
return torch._C._VariableFunctions.as_tensor(*args, **kwargs)
|
||||
dst_device = kwargs.pop("device")
|
||||
|
||||
return torch._C._VariableFunctions.as_tensor(*args, **kwargs).to(dst_device)
|
||||
|
||||
|
||||
${device_methods_def_py_dispatch}
|
||||
|
||||
def add_torch_funcs():
|
||||
torch.device = _device
|
||||
torch.tensor = _tensor
|
||||
torch.full = _full
|
||||
torch.randint = _randint
|
||||
@@ -91,5 +89,6 @@ def add_torch_funcs():
|
||||
torch.npu_dropout_gen_mask = _npu_dropout_gen_mask
|
||||
torch.jit.script = jit_script
|
||||
torch.as_tensor = _as_tensor
|
||||
torch.new_device = _new_device
|
||||
|
||||
${device_methods_def_py}
|
||||
@@ -375,6 +375,7 @@
|
||||
| 255 | torch.trapz | Supported |
|
||||
| 256 | torch.triangular_solve | Supported |
|
||||
| 257 | torch.vdot | Supported |
|
||||
| 258 | torch.aminmax | Supported |
|
||||
|
||||
## Utilities
|
||||
|
||||
|
||||
@@ -438,7 +438,7 @@ The following uses the torch.add() operator as an example to describe the develo
|
||||
at::Tensor result = OpPreparation::ApplyTensorWithFormat(
|
||||
outputSize,
|
||||
outputTensor.options(),
|
||||
CalcuOpUtil::get_tensor_npu_format(outputTensor));
|
||||
CalcuOpUtil::GetTensorNpuFormat(outputTensor));
|
||||
|
||||
// calculate the output result of the NPU
|
||||
add_out_npu_nocheck(result, self, other, alpha);
|
||||
@@ -454,7 +454,7 @@ The following uses the torch.add() operator as an example to describe the develo
|
||||
auto outputSize = input_same_output_size(self);
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensorWithFormat(
|
||||
outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
|
||||
outputSize, self.options(), CalcuOpUtil::GetTensorNpuFormat(self));
|
||||
|
||||
// calculate the output result of the NPU
|
||||
adds_out_npu_nocheck(result, self, other, alpha);
|
||||
@@ -472,7 +472,7 @@ The following uses the torch.add() operator as an example to describe the develo
|
||||
{
|
||||
c10::SmallVector<at::Tensor, N> inputs = {self, other};
|
||||
c10::SmallVector<at::Tensor, N> outputs = {self};
|
||||
CalcuOpUtil::check_memory_over_laps(inputs, outputs);
|
||||
CalcuOpUtil::CheckMemoryOverLaps(inputs, outputs);
|
||||
|
||||
if (!NpuUtils::check_match(&self))
|
||||
{
|
||||
@@ -516,7 +516,7 @@ The following uses the torch.add() operator as an example to describe the develo
|
||||
at::Scalar alpha,
|
||||
at::Tensor &result)
|
||||
{
|
||||
bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self);
|
||||
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(self);
|
||||
|
||||
at::Tensor outputTensor;
|
||||
if (not isSelfWrapped)
|
||||
@@ -531,7 +531,7 @@ The following uses the torch.add() operator as an example to describe the develo
|
||||
OpPreparation::CheckOut(
|
||||
{self},
|
||||
result,
|
||||
CalcuOpUtil::get_tensor_npu_format(result),
|
||||
CalcuOpUtil::GetTensorNpuFormat(result),
|
||||
outputTensor.scalar_type(),
|
||||
outputSize);
|
||||
|
||||
|
||||
@@ -43,15 +43,18 @@ apt-get install -y gcc==7.3.0 cmake==3.12.0
|
||||
|
||||
# Ascend配套软件<a name="Ascend配套软件"></a>
|
||||
|
||||
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 | Gitee分支名称 |
|
||||
| :---------------- | :----------- | :-------------- | -------------- |
|
||||
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
|
||||
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
|
||||
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
|
||||
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 | Gitee分支名称 |
|
||||
| :---------------- | :----------- | :-------------- | --------------- |
|
||||
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
|
||||
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
|
||||
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.5.0.post7 | v1.5.0-3.0.rc3 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 |
|
||||
| 3.0.rc3 | CANN 6.0.RC1 | 1.11.0.rc1 | v1.11.0-3.0.rc3 |
|
||||
|
||||
# 安装方式<a name="安装方式"></a>
|
||||
|
||||
@@ -475,6 +478,51 @@ warning如下图所示,由Tensor.set_data浅拷贝操作触发。主要原因
|
||||
|
||||
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
|
||||
|
||||
## 在执行import torch_npu时出现ModuleNotFooundError: NO module named '_lzma'报错问题
|
||||
|
||||
5在python命令行下,执行import torch_npu测试时,出现ModuleNotFooundError: NO module named '_lzma'问题,可能由于Python环境失效,重装Python即可。<img src="figures/QA.png" />
|
||||
|
||||
## 编译过程中出现XNNPACK相关的Make Error报错
|
||||
|
||||
编译原生pytorch时,未配置相关环境变量,导致编译不成功。
|
||||
|
||||

|
||||
|
||||
1. 执行命令设置环境变量
|
||||
|
||||
```
|
||||
export USE_XNNPACK=0
|
||||
```
|
||||
|
||||
2. 执行命令清除当前编译内容
|
||||
|
||||
```
|
||||
make clean
|
||||
```
|
||||
|
||||
3. 重新编译
|
||||
|
||||
## 编译时出现Breakpad error: field 'regs' has incomplete type 'google_breakpad::user_regs_struct'报错
|
||||
|
||||
编译原生pytorch时,未配置相关环境变量,导致编译不成功。
|
||||
|
||||
1. 执行命令配置环境变量
|
||||
|
||||
```
|
||||
export BUILD_BREAKPAD=0
|
||||
```
|
||||
|
||||
2. 执行命令清除当前编译内容
|
||||
|
||||
```
|
||||
make clean
|
||||
```
|
||||
|
||||
3. 重新编译
|
||||
|
||||
## 多卡训练初始化阶段卡顿至超时
|
||||
|
||||
init_process_group 函数中使用了IPV6地址,例如::1(注意localhost 可能指向IPv6的地址),使用IPv4可以避免这个问题
|
||||
|
||||
|
||||
# 版本说明<a name='版本说明'></a>
|
||||
|
||||
|
After Width: | Height: | Size: 377 KiB |
|
After Width: | Height: | Size: 288 KiB |
@@ -1,923 +0,0 @@
|
||||
# 概述
|
||||
|
||||
用户可以从Ascend ModelZoo获得PyTorch训练模型,但不支持多机多卡训练,需要根据模型的实际代码进行修改。本文帮助用户快速实现Pytorch模型在多机多卡上使用DDP(Distributed Data Parallel)模式训练。
|
||||
|
||||
# 训练流程
|
||||
|
||||
PyTorch模型多机多卡训练流程一般包括准备环境、准备模型、修改模型、启动训练四个部分。
|
||||
|
||||
1. 准备环境。
|
||||
|
||||
准备多机多卡训练的软件、硬件、网络环境,包括开发和运行环境搭建、集群组网链接、芯片IP设置、防火墙设置等。
|
||||
|
||||
2. 准备模型。
|
||||
|
||||
准备PyTorch模型、数据加载器、优化器等训练需要的模块,从[开源社区](https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch)获取,也可以自行实现。
|
||||
|
||||
3. 修改模型。
|
||||
|
||||
在基础模型上进行修改,添加DDP需要的代码和环境变量,使模型支持在多机多卡训练。
|
||||
|
||||
4. 启动训练。
|
||||
|
||||
实现在多机多卡环境启动模型训练并查看训练日志。
|
||||
|
||||
|
||||
|
||||
# 快速上手
|
||||
|
||||
## 概述
|
||||
|
||||
通过示例帮助用户快速了解PyTorch模型是如何在多机多卡上训练的。该示例使用自定义模型实现两台计算机8卡训练。两台计算机分别命名为AI Server0、AI Server1,每台计算机上的8个Ascend 910处理器命名为device 0~7。
|
||||
|
||||
## 准备环境
|
||||
|
||||
首先您需要具有至少两台装有Ascend 910处理器的计算机,并保证每台计算机都正确的安装NPU固件和驱动。
|
||||
|
||||
1. 准备开发和运行环境。
|
||||
|
||||
在每台计算机上分别完成开发和运行环境准备。
|
||||
|
||||
- 完成CANN开发和运行环境的安装,请参见《CANN 软件安装指南》,支持5.0.3以后版本。
|
||||
|
||||
- 安装适配NPU的PyTorch,安装方法请参见《PyTorch安装指南》。
|
||||
|
||||
2. 准备组网。
|
||||
|
||||
通过交换机或光口直连的方式完成计算设备组网搭建,搭建方法请参见《[数据中心训练场景组网](https://support.huawei.com/enterprise/zh/doc/EDOC1100221993/229cc0e4)》。
|
||||
|
||||
该示例中采用两台计算机8卡进行训练,故可以采用光口直连的方式准备组网。
|
||||
|
||||
3. 配置device IP
|
||||
|
||||
在AI Server0上配置device IP。
|
||||
|
||||
```shell
|
||||
hccn_tool -i 0 -ip -s address 192.168.100.101 netmask 255.255.255.0
|
||||
hccn_tool -i 1 -ip -s address 192.168.101.101 netmask 255.255.255.0
|
||||
hccn_tool -i 2 -ip -s address 192.168.102.101 netmask 255.255.255.0
|
||||
hccn_tool -i 3 -ip -s address 192.168.103.101 netmask 255.255.255.0
|
||||
hccn_tool -i 4 -ip -s address 192.168.100.100 netmask 255.255.255.0
|
||||
hccn_tool -i 5 -ip -s address 192.168.101.100 netmask 255.255.255.0
|
||||
hccn_tool -i 6 -ip -s address 192.168.102.100 netmask 255.255.255.0
|
||||
hccn_tool -i 7 -ip -s address 192.168.103.100 netmask 255.255.255.0
|
||||
```
|
||||
|
||||
在AI Server1上配置device IP。
|
||||
|
||||
```shell
|
||||
hccn_tool -i 0 -ip -s address 192.168.100.111 netmask 255.255.255.0
|
||||
hccn_tool -i 1 -ip -s address 192.168.101.111 netmask 255.255.255.0
|
||||
hccn_tool -i 2 -ip -s address 192.168.102.111 netmask 255.255.255.0
|
||||
hccn_tool -i 3 -ip -s address 192.168.103.111 netmask 255.255.255.0
|
||||
hccn_tool -i 4 -ip -s address 192.168.100.110 netmask 255.255.255.0
|
||||
hccn_tool -i 5 -ip -s address 192.168.101.110 netmask 255.255.255.0
|
||||
hccn_tool -i 6 -ip -s address 192.168.102.110 netmask 255.255.255.0
|
||||
hccn_tool -i 7 -ip -s address 192.168.103.110 netmask 255.255.255.0
|
||||
```
|
||||
|
||||
4. 配置防火墙
|
||||
|
||||
- Ubuntu系统防火墙关闭命令
|
||||
|
||||
```shell
|
||||
ufw disable
|
||||
|
||||
- Redhat或CentOS 7系统防火墙关闭命令
|
||||
|
||||
```shell
|
||||
systemctl stop firewalld
|
||||
|
||||
## 准备模型
|
||||
|
||||
该示例创建一个简单的模型,供用户快速了解多机多卡训练。用户也可以从[开源社区](https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch)获取基于Ascned NPU的PyTorch训练模型。
|
||||
|
||||
1. DDP模型。
|
||||
|
||||
实现一个简单的样例main.py用于多机多卡训练。
|
||||
|
||||
```python
|
||||
import argparse
|
||||
import os
|
||||
import torch
|
||||
import torch_npu
|
||||
import torchvision
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import torch.distributed as dist
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
|
||||
### 1.基础模块 ###
|
||||
# 搭建模型
|
||||
class ToyModel(nn.Module):
|
||||
def __init__(self):
|
||||
super(ToyModel, self).__init__()
|
||||
self.conv1 = nn.Conv2d(3, 6, 5)
|
||||
self.pool = nn.MaxPool2d(2, 2)
|
||||
self.conv2 = nn.Conv2d(6, 16, 5)
|
||||
self.fc1 = nn.Linear(16 * 5 * 5, 120)
|
||||
self.fc2 = nn.Linear(120, 84)
|
||||
self.fc3 = nn.Linear(84, 10)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.pool(F.relu(self.conv1(x)))
|
||||
x = self.pool(F.relu(self.conv2(x)))
|
||||
x = x.view(-1, 16 * 5 * 5)
|
||||
x = F.relu(self.fc1(x))
|
||||
x = F.relu(self.fc2(x))
|
||||
x = self.fc3(x)
|
||||
return x
|
||||
|
||||
# 获取数据集方法
|
||||
def get_dataset():
|
||||
transform = torchvision.transforms.Compose([
|
||||
torchvision.transforms.ToTensor(),
|
||||
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
|
||||
])
|
||||
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
|
||||
download=True, transform=transform)
|
||||
|
||||
train_sampler = torch.utils.data.distributed.DistributedSampler(my_trainset)
|
||||
trainloader = torch.utils.data.DataLoader(my_trainset,
|
||||
batch_size=16, num_workers=2, sampler=train_sampler)
|
||||
return trainloader
|
||||
|
||||
|
||||
### 2. 初始化参数、数据、模型、损失函数、优化器 ####
|
||||
# 获取local_rank和addr参数
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--local_rank", default=-1, type=int)
|
||||
parser.add_argument("--addr", default='127.0.0.1', type=str, help='master addr')
|
||||
|
||||
FLAGS = parser.parse_args()
|
||||
local_rank = FLAGS.local_rank
|
||||
addr = FLAGS.addr
|
||||
|
||||
# 设置系统的Master地址和端口
|
||||
os.environ['MASTER_ADDR'] = addr
|
||||
os.environ['MASTER_PORT'] = '29501'
|
||||
|
||||
# DDP backend初始化
|
||||
loc = 'npu:{}'.format(local_rank)
|
||||
torch.npu.set_device(loc)
|
||||
dist.init_process_group(backend='hccl') # hccl是NPU设备上的后端
|
||||
|
||||
|
||||
# 准备数据,要在DDP初始化之后进行
|
||||
trainloader = get_dataset()
|
||||
|
||||
# 实例化模型
|
||||
model = ToyModel().to(loc)
|
||||
|
||||
# 加载模型权重,在构造DDP模型之前,且只需要在master上加载就行了。
|
||||
ckpt_path = None
|
||||
if dist.get_rank() == 0 and ckpt_path is not None:
|
||||
model.load_state_dict(torch.load(ckpt_path))
|
||||
|
||||
# 构造DDP model
|
||||
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
|
||||
|
||||
# 初始化优化器,在构造DDP model之后,用model初始化optimizer。
|
||||
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
|
||||
|
||||
# 初始化损失函数
|
||||
loss_func = nn.CrossEntropyLoss().to(loc)
|
||||
|
||||
### 3. 网络训练 ###
|
||||
model.train()
|
||||
iterator = range(100)
|
||||
for epoch in iterator:
|
||||
trainloader.sampler.set_epoch(epoch)
|
||||
for data, label in trainloader:
|
||||
data, label = data.to(local_rank), label.to(local_rank)
|
||||
optimizer.zero_grad()
|
||||
prediction = model(data)
|
||||
loss = loss_func(prediction, label)
|
||||
loss.backward()
|
||||
print("loss = %0.3f \n" % loss)
|
||||
optimizer.step()
|
||||
|
||||
# 1. save模型的时候,和DP模式一样,有一个需要注意的点:保存的是model.module而不是model。
|
||||
# 因为model其实是DDP model,参数是被`model=DDP(model)`包起来的。
|
||||
# 2. 只需要在进程0上保存一次就行了,避免多次保存重复的东西。
|
||||
if dist.get_rank() == 0:
|
||||
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
|
||||
```
|
||||
|
||||
2. 在单机多卡上运行训练,确保模型正确。
|
||||
|
||||
1. 用户自行安装模型脚本需要的Python第三方库。
|
||||
|
||||
2. 配置NPU环境变量,env_npu.sh脚本请参见附录。
|
||||
|
||||
```shell
|
||||
source env_npu.sh
|
||||
```
|
||||
|
||||
3. 使用torch.distributed.launch执行main.py如下命令在单机多卡上训练模型。
|
||||
|
||||
```shell
|
||||
python -m torch.distributed.launch --nproc_per_node 8 main.py
|
||||
```
|
||||
|
||||
`--nproc_per_node` 为训练卡的数量。
|
||||
|
||||
运行成功后,模型在该设备的8张NPU上进行训练。
|
||||
|
||||
|
||||
|
||||
## 修改模型
|
||||
|
||||
该快速上手提供的示例,已经对多机多卡训练进行了适配,不需要对脚本进行修改。其他模型的多机多卡适配修改,请参考”多机多卡训练“章节。
|
||||
|
||||
## 启动训练
|
||||
|
||||
1. 将main.py模型脚本上传至AI Server0和AI Server1任意路径下。
|
||||
|
||||
2. 查询服务器的host IP:
|
||||
|
||||
```shell
|
||||
hostname -I
|
||||
```
|
||||
|
||||
打印出所有IP,第一个为IP当前服务器的host IP。
|
||||
|
||||
比如:AI Server0服务器的host IP为:192.168.xx.22, AI Server1服务器的host IP为:192.168.xx.23。
|
||||
|
||||
3. 使用AI Server0为master节点,我们现在拉起2 x 8的集群。
|
||||
|
||||
在AI server0服务器上启动命令:
|
||||
|
||||
```shell
|
||||
# 设置环境变量,env_npu.sh脚本内容从附录获取
|
||||
source env_npu.sh
|
||||
# 关闭HCCL通道白名单
|
||||
export HCCL_WHITELIST_DISABLE=1
|
||||
# HCCL初始化通信网卡IP,设置为当前服务器的host IP
|
||||
export HCCL_IF_IP=192.168.xx.22
|
||||
#
|
||||
python3.7 -m torch.distributed.launch --nnodes=2 --node_rank=0 --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
|
||||
```
|
||||
|
||||
在AI server1服务器上启动命令:
|
||||
|
||||
```shell
|
||||
# 设置环境变量,env_npu.sh脚本内容从附录获取
|
||||
source env_npu.sh
|
||||
# 关闭HCCL通道白名单
|
||||
export HCCL_WHITELIST_DISABLE=1
|
||||
# HCCL初始化通信网卡IP,设置为当前服务器的host IP
|
||||
export HCCL_IF_IP=192.168.xx.23
|
||||
|
||||
python3.7 -m torch.distributed.launch --nnodes=2 --node_rank=1 --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
|
||||
```
|
||||
|
||||
参数说明。
|
||||
|
||||
--nnode:指定用来分布式训练脚本的节点数。
|
||||
|
||||
--node_rank:多节点分布式训练时,指定当前节点的 rank。
|
||||
|
||||
--nproc_per_node:指定当前节点上,使用GPU训练的进程数。
|
||||
|
||||
--master_addr:master节点(rank为0)的地址,应该为ip地址或者node 0 的 hostname。
|
||||
|
||||
--master_port:指定分布式训练中,master 节点使用的端口号。
|
||||
|
||||
--addr:main.py 脚本的入参,输入master节点的host IP。
|
||||
|
||||
3. host日志查看
|
||||
|
||||
host日志保存在`~/ascend/log`路径下,用户可以到该路径下查看每个host的device日志。
|
||||
|
||||
通过该简单的示例您已经完成了多机多卡模型的训练。
|
||||
|
||||
# 多机多卡训练
|
||||
|
||||
|
||||
|
||||
## 常用概念及参数介绍
|
||||
|
||||
pytorch分布式训练基本概念
|
||||
|
||||
| 基本概念 | 说明 |
|
||||
| ---------- | ------------------------------------------------------------ |
|
||||
| AI Server | 带有Ascend 910处理器的计算机,多台计算机用AI Server0+序号表示,如AI Server0、AI Server1。 |
|
||||
| device | AI Server上Ascend 910卡,多卡用device 0、device 1……device 7表示。 |
|
||||
| host | AI Server主机。 |
|
||||
| master | 在多台AI Server选取一台作为master,作为数据通信的主机。 |
|
||||
| group | 即进程组。默认情况下,只有一个组,采用用默认的就行。 |
|
||||
| world size | 表示全局的进程并行数,可通过torch.distributed.get_world_size()获取, 在不同进程里,该值是一样的。 |
|
||||
| rank | 表示当前进的序号, 用于进程间通讯。比如是2x8的集群,world size 就是16,rank在每个进程里依次是0,1,2,…,15。 |
|
||||
| local_rank | 每台机子上的进程的序号。机器一上有0,1,2,3,4,5,6,7,机器二上也有0,1,2,3,4,5,6,7。一般情况下,你需要用这个local_rank来设置当前模型是跑在当前机器的哪块GPU/NPU上面的。 |
|
||||
|
||||
使用torch.distributed.launch启动多卡训练时的参数
|
||||
|
||||
| 参数名称 | 说明 |
|
||||
| ------------------ | ------------------------------------------------------------ |
|
||||
| **nnodes** | 指定用来分布式训练脚本的节点数 |
|
||||
| **node_rank** | 多节点分布式训练时,指定当前节点的 rank |
|
||||
| **nproc_per_node** | 指定当前节点上,使用GPU训练的进程数。建议将该参数设置为当前节点的GPU数量,这样每个进程都能单独控制一个GPU,效率最高。 |
|
||||
| **master_addr** | master节点(rank为0)的地址,应该为ip地址或者node 0 的 hostname。对于单节点多进程训练的情况,该参数可以设置为 127.0.0.1。 |
|
||||
| **master_port**: | 指定分布式训练中,master 节点使用的端口号,必须与其他应用的端口号不冲突。 |
|
||||
|
||||
## 多机多卡训练流程
|
||||
|
||||
### 准备环境
|
||||
|
||||
首先您需要具有至少两台AI Server(装有Ascend 910处理器的计算机),并保证每台计算机已安装正确版本的NPU固件和驱动。
|
||||
|
||||
1. 准备开发和运行环境。
|
||||
|
||||
在每台计算机上分别完成开发和运行环境准备。
|
||||
|
||||
- 完成CANN开发和运行环境的安装,请参见《CANN 软件安装指南》,支持5.0.3以后版本。
|
||||
|
||||
- 安装适配NPU的PyTorch,安装方法请参见《PyTorch安装指南》。
|
||||
|
||||
2. 准备组网。
|
||||
|
||||
集群训练由多台装有Ascend 910处理器的计算机完成(最多128台),需要配合交换机组成数据面全连接主备网络,支持8 x n卡训练场景,2台机器可以采用光口直连的方式。搭建方法请参见《[数据中心训练场景组网](https://support.huawei.com/enterprise/zh/doc/EDOC1100221993/229cc0e4)》。
|
||||
|
||||
3. 配置device IP
|
||||
|
||||
使用hccn_tool工具配置device IP,hccn_tool工具CANN软件以提供。
|
||||
|
||||
```shell
|
||||
hccn_tool -i 0 -ip -s address 192.168.100.111 netmask 255.255.255.0
|
||||
```
|
||||
|
||||
配置device IP需遵守以下规则:
|
||||
|
||||
1. AI Server中的第0/4,1/5,2/6,3/7号device需处于同一网段,第0/1/2/3号device在不同网段,第4/5/6/7号device在不同网段。
|
||||
2. 对于集群场景,各AI Server对应的位置的device需处于同一网段,AI Server0和AI Server1的0号网卡需处于同一网段、1号网卡需要在同一网段
|
||||
3. 每个IP都不能冲突,相同网段下的IP需在最后8位做区分
|
||||
|
||||
使用hccn_tool工具验证device IP是否配置正确。
|
||||
|
||||
- 查询每个device的ip。
|
||||
|
||||
```shell
|
||||
hccn_tool -i 0 -ip –g
|
||||
```
|
||||
|
||||
打印查询结果:
|
||||
|
||||
> ipaddr:192.168.100.101
|
||||
>
|
||||
> netmask:255.255.255.0
|
||||
|
||||
- 使用hccn_tool 确保2机器的卡间连通性,从device0 - devcie7 测试8次,确保所有两机间所有卡都连通。
|
||||
|
||||
```shell
|
||||
hccn_tool -i 0 -netdetect -s address xx.xx.xx.xx
|
||||
|
||||
hccn_tool -i 0 -net_health –g
|
||||
```
|
||||
|
||||
-i:device序号
|
||||
|
||||
-s address:xx.xx.xx.xx是另外一台机器的device i的IP
|
||||
|
||||
如果返回`success`则表示已经连通。
|
||||
|
||||
4. 配置防火墙
|
||||
|
||||
在进行HCCL通信的时候可能出现防火墙拦截通信端口导致通信超时,因此在运行pytorch的集群训练的时候需要注意将服务器上的防火墙关闭。
|
||||
|
||||
- Ubuntu系统防火墙关闭命令
|
||||
|
||||
```shell
|
||||
ufw disable
|
||||
```
|
||||
|
||||
- Redhat或CentOS 7系统防火墙关闭命令
|
||||
|
||||
```shell
|
||||
systemctl stop firewalld
|
||||
```
|
||||
|
||||
### 准备模型
|
||||
|
||||
准备模型阶段主要有两种方式。
|
||||
|
||||
- 从[开源社区](https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch)下载PyTorch训练模型
|
||||
|
||||
从开源社区获取的模型已经支持单机多卡训练,请用户参照“修改模型”小节需要修改的项目,根据具体模型完成相应修改。
|
||||
|
||||
- 手动搭建PyTorch训练模型
|
||||
|
||||
1. 准备PyTorch训练模型、数据加载器
|
||||
|
||||
准备PyTorch模型。
|
||||
|
||||
```python
|
||||
class ToyModel(nn.Module):
|
||||
def __init__(self):
|
||||
...
|
||||
def forward(self,x):
|
||||
...
|
||||
```
|
||||
|
||||
准备数据获取方法。
|
||||
|
||||
```python
|
||||
def get_dataset():
|
||||
transform = torchvision.transforms.Compose([
|
||||
torchvision.transforms.ToTensor(),
|
||||
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
|
||||
])
|
||||
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
|
||||
download=True, transform=transform)
|
||||
|
||||
trainloader = torch.utils.data.DataLoader(my_trainset,batch_size=16,)
|
||||
return trainloader
|
||||
|
||||
trainloader=get_dataset()
|
||||
```
|
||||
|
||||
2. 实例化模型
|
||||
|
||||
```python
|
||||
# 实例化模型
|
||||
model = ToyModel().to(loc)
|
||||
|
||||
# 加载模型权重
|
||||
if ckpt_path is not None:
|
||||
model.load_state_dict(torch.load(ckpt_path))
|
||||
```
|
||||
|
||||
3. 准备损失函数和优化器。
|
||||
|
||||
```python
|
||||
# 初始化优化器,在构造DDP model之后,用model初始化optimizer。
|
||||
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
|
||||
|
||||
# 初始化损失函数
|
||||
loss_func = nn.CrossEntropyLoss().to(loc)
|
||||
```
|
||||
|
||||
4. 训练模型
|
||||
|
||||
```python
|
||||
### 3. 网络训练 ###
|
||||
model.train()
|
||||
iterator = range(100)
|
||||
for epoch in iterator:
|
||||
for data, label in trainloader:
|
||||
data, label = data.to(local_rank), label.to(local_rank)
|
||||
optimizer.zero_grad()
|
||||
prediction = model(data)
|
||||
loss = loss_func(prediction, label)
|
||||
loss.backward()
|
||||
print("loss = %0.3f \n" % loss)
|
||||
optimizer.step()
|
||||
|
||||
torch.save(model.state_dict(), "%d.ckpt" % epoch)
|
||||
```
|
||||
|
||||
|
||||
|
||||
### 修改模型
|
||||
|
||||
模型修改主要涉及以下6项,包括master ip地址和端口的设置,distributed初始化,模型DDP初始化,数据DDP初始化,优化器初始化,DDP模型训练方法修改。请用户结合初始模型代码,灵活修改。
|
||||
|
||||
1. 设置master ip地址和端口,在NPU进行分布式训练使用HCCL进行通信,在PyTorch中使用的是自动拓扑探测的HCCL通信机制,即不需要使用RANK_TABLE_FLIE,但是其依赖于host侧的网卡进行通信,因此需要在代码中设置环境变量来设置通信网卡。
|
||||
|
||||
```python
|
||||
os.environ['MASTER_ADDR'] = xxx.xxx.xxx.xxx
|
||||
os.environ['MASTER_PORT'] = 'xxx'
|
||||
```
|
||||
|
||||
MASTER_ADDR:设置为集群中master的IP(任意挑选一台作为master即可)
|
||||
|
||||
MASTER_PORT:设置为master的一个空闲端口
|
||||
|
||||
master ip地址和端口在模型代码中一般会设置为传参的形式,也有可能某些开源代码中设置为"127.0.0.1",需要进行修改。
|
||||
|
||||
上述变量需在调用torch.distributed.init_process_group()之前声明。
|
||||
|
||||
2. distributed初始化
|
||||
|
||||
PyTorch中使用`dist.init_process_group(backend='hccl', world_size=world_size, rank=rank)`来初始化线程组其中参数含义如下。
|
||||
|
||||
`backend`:进行分布式训练的使用的通信协议,在NPU上只能使用"hccl"
|
||||
|
||||
`world_size`:进行训练时使用的device的总数
|
||||
|
||||
`rank`: 当前初始化的device的rank_id,也就是全局的逻辑ID
|
||||
|
||||
有两种方法启动多卡训练,分别初始化的方法如下。
|
||||
|
||||
- 使用torch.distributed.launch启动多卡训练。
|
||||
|
||||
```python
|
||||
import torch.distributed as dist
|
||||
|
||||
dist.init_process_group(backend='hccl') # hccl是NPU设备上的后端
|
||||
```
|
||||
|
||||
- 使用mp.spawn启动多卡训练。
|
||||
|
||||
```python
|
||||
import torch.distributed as dist
|
||||
|
||||
def main_worker(pid_idx, device_nums_per_node, args):
|
||||
args.distributed_rank = args.rank * device_nums_per_node + pid_idx
|
||||
dist.init_process_group(backend=args.dist_backend, world_size=args.distributed_world_size, rank=args.distributed_rank)
|
||||
```
|
||||
|
||||
其中:
|
||||
|
||||
`pid_idx`:device序号。
|
||||
|
||||
`device_nums_per_node`:每个AI Server的device数量。
|
||||
|
||||
3. 模型DDP初始化
|
||||
|
||||
```python
|
||||
# 实例化模型
|
||||
model = ToyModel().to(loc)
|
||||
|
||||
# 加载模型权重,在构造DDP模型之前,且只需要在master上加载。
|
||||
if dist.get_rank() == 0 and ckpt_path is not None:
|
||||
model.load_state_dict(torch.load(ckpt_path))
|
||||
|
||||
# 构造DDP model
|
||||
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
|
||||
```
|
||||
|
||||
4. 数据DDP初始化
|
||||
|
||||
```python
|
||||
def get_dataset():
|
||||
transform = torchvision.transforms.Compose([
|
||||
torchvision.transforms.ToTensor(),
|
||||
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
|
||||
])
|
||||
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
|
||||
download=True, transform=transform)
|
||||
|
||||
train_sampler = torch.utils.data.distributed.DistributedSampler(my_trainset)
|
||||
trainloader = torch.utils.data.DataLoader(my_trainset,
|
||||
batch_size=16, num_workers=2, sampler=train_sampler)
|
||||
return trainloader
|
||||
|
||||
trainloader = get_dataset()
|
||||
```
|
||||
|
||||
5. 损失方法、优化器。
|
||||
|
||||
```python
|
||||
# 初始化优化器,在构造DDP model之后,用model初始化optimizer。
|
||||
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
|
||||
|
||||
# 初始化损失函数
|
||||
loss_func = nn.CrossEntropyLoss().to(loc)
|
||||
```
|
||||
|
||||
6. DDP模型训练
|
||||
|
||||
```python
|
||||
model.train()
|
||||
iterator = range(100)
|
||||
for epoch in iterator:
|
||||
# 设置epoch
|
||||
trainloader.sampler.set_epoch(epoch)
|
||||
|
||||
for data, label in trainloader:
|
||||
data, label = data.to(local_rank), label.to(local_rank)
|
||||
optimizer.zero_grad()
|
||||
prediction = model(data)
|
||||
loss = loss_func(prediction, label)
|
||||
loss.backward()
|
||||
print("loss = %0.3f \n" % loss)
|
||||
optimizer.step()
|
||||
|
||||
# 1. save模型的时候,和DP模式一样,有一个需要注意的点:保存的是model.module而不是model。
|
||||
# 因为model其实是DDP model,参数是被`model=DDP(model)`包起来的。
|
||||
# 2. 只需要在进程0上保存一次就行了,避免多次保存重复的东西。
|
||||
if dist.get_rank() == 0:
|
||||
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
|
||||
```
|
||||
|
||||
### 启动训练
|
||||
|
||||
启动训练提供两种方式,手动启动和shell脚本启动
|
||||
|
||||
- 手动启动(使用torch.distributed.launch方式启动)
|
||||
|
||||
1. 配置NPU 环境变量,请参考附录提供的env_npu.sh脚本
|
||||
|
||||
2. 添加环境变量,多机训练需要增加`HCCL_WHITELIST_DISABLE`和`HCCL_IF_IP`环境变量。
|
||||
|
||||
- HCCL_WHITELIST_DISABLE:HCCL通道白名单,一般性设置为1表示关闭白名单。
|
||||
- HCCL_IF_IP:HCCL初始化通信网卡IP,设置为当前服务器的host网卡IP。
|
||||
|
||||
3. 将修改的模型脚本上传至每个AI Server
|
||||
|
||||
4. 在每个AI Server上安装必要Python库
|
||||
|
||||
5. 任选一个AI Server作为masker节点,并查询每个AI Server的IP。
|
||||
|
||||
6. 在每个AI server服务器上启动命令
|
||||
|
||||
```
|
||||
python3 -m torch.distributed.launch --nnodes=${nnodes} --node_rank=i --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
|
||||
```
|
||||
|
||||
其中:
|
||||
|
||||
--nnodes:用来分布式训练脚本的AI server数。
|
||||
|
||||
--node_rank:AI server的序号,每个AI server有对应的序号。
|
||||
|
||||
--nproc_per_node:每个AI server的device数量。
|
||||
|
||||
--master_addr:作为maskter节点的AI server IP地址。
|
||||
|
||||
--master_port: 作为maskter节点的AI server 端口号。
|
||||
|
||||
main.py:请修改为启动脚本名称。
|
||||
|
||||
--addr :传入启动脚本的参数,master IP地址。
|
||||
|
||||
- 使用OpenMPI启动
|
||||
|
||||
1. 安装 OpenMPI开源库
|
||||
|
||||
多机多卡环境下分布式训练部署依赖于OpenMPI开源库,参与模型训练的每台服务器都需要安装OpenMPI开源库。目前OpenMPI开源库的版本要求为4.0.1、4.0.2或4.0.3。
|
||||
执行`mpirun --version`命令检查是否已安装OpenMPI。如果返回`mpirun (Open MPI) 4.0.2 Report bugs to http://www.open-mpi.org/community/help/` ,说明已经安装。如果已安装,且版本为4.0.1、4.0.2或4.0.3其中一个,则无需再安装。
|
||||
|
||||
否则请按照如下步骤安装OpenMPI:
|
||||
|
||||
1. 访问如下链接下载OpenMPI软件包。例如openmpi-4.0.2.tar.bz2。
|
||||
https://www.open-mpi.org/software/ompi/v4.0/
|
||||
|
||||
2. 以root用户登录安装环境。
|
||||
|
||||
3. 将下载的OpenMPI软件包上传到安装环境的某一目录下。
|
||||
|
||||
4. 进入软件包所在目录,执行如下命令解压软件包。
|
||||
|
||||
```shell
|
||||
tar -jxvf openmpi-4.0.2.tar.bz2
|
||||
```
|
||||
|
||||
5. 进入解压后的目录,执行如下命令配置、编译和安装。
|
||||
|
||||
```shell
|
||||
./configure --prefix=/usr/local/mpirun4.0.2
|
||||
make
|
||||
make install
|
||||
```
|
||||
|
||||
其中“--prefix”参数用于指定OpenMPI安装路径,用户根据实际情况进行修改。
|
||||
|
||||
6. 执行vi ~/.bashrc命令,打开.bashrc文件,在文件的最后添加如下环境变量。
|
||||
|
||||
```shell
|
||||
export OPENMPI=/usr/local/mpirun4.0.2
|
||||
export LD_LIBRARY_PATH=$OPENMPI/lib
|
||||
export PATH=$OPENMPI/bin:$PATH
|
||||
```
|
||||
|
||||
其中“/usr/local/mpirun4.0.2”为OpenMPI安装路径,用户需要根据实际进行修改。
|
||||
执行:wq!命令保存文件并退出。
|
||||
|
||||
7. 执行如下命令使环境变量生效。
|
||||
|
||||
```
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
8. 安装完成之后,执行如下命令查看安装版本,如果返回正确的版本信息,则说明安装成功。
|
||||
|
||||
```
|
||||
mpirun --version
|
||||
```
|
||||
|
||||
2. 配置AI Server SSH免密登录
|
||||
|
||||
如果使用OpenMPI在多机多卡环境下分布式训练部署,需要在每两台服务器之间配置SSH免密登录,确保服务器之间可以互通。具体操作步骤如下:
|
||||
|
||||
1. 以root用户登录每台服务器。
|
||||
|
||||
2. 配置集群中主机间的可信度。
|
||||
|
||||
打开并编辑**/etc/ssh/ssh_config**文件,在文件最后增加如下字段:
|
||||
|
||||
```
|
||||
StrictHostKeyChecking no
|
||||
UserKnownHostsFile /dev/null
|
||||
```
|
||||
|
||||
3. 在每台服务器上分别打开**/etc/hosts**文件,在该文件中添加本服务器对应的IP地址和主机名,且需要添加到该文件的首行。如果文件中已添加,则跳过此步骤。添加内容示例如下:
|
||||
|
||||
```
|
||||
xxx.xxx.xxx.111 ubuntu
|
||||
```
|
||||
|
||||
其中xxx.xxx.xxx.111为该服务器的IP地址,ubuntu为主机名。
|
||||
|
||||
4. 在第一台服务器执行如下命令生成公钥(例如第一台服务器IP为xxx.xxx.xxx.111)。
|
||||
|
||||
```
|
||||
cd ~/.ssh/ # 若没有该目录,请先执行一次ssh localhost
|
||||
ssh-keygen -t rsa # 生成秘钥,会出现提示,连续点击3次"Enter"即可
|
||||
mv id_rsa.pub authorized_keys # 将生成的秘钥id_rsa.pub重命名为公钥authorized_keys
|
||||
```
|
||||
|
||||
5. 在其他每台服务器上都生成秘钥,并复制到第一台服务器的authorized_keys文件中。
|
||||
|
||||
1. 在其他每台服务器上执行如下命令生成秘钥。
|
||||
|
||||
cd ~/.ssh/
|
||||
ssh-keygen -t rsa
|
||||
|
||||
2. 将其他每台服务器上生成的秘钥文件id_rsa.pub下载到本地,并复制该文件中的秘钥。
|
||||
|
||||
3. 在第一台服务器内执行如下命令打开公钥文件authorized_keys,将[5.b](#li361025101116 "link to:#li361025101116
|
||||
ctrl +click to jump")复制的其他每台服务器的秘钥粘贴到第一台服务器的公钥后面。
|
||||
|
||||
```
|
||||
vi ~/.ssh/authorized_keys
|
||||
```
|
||||
|
||||
执行**:wq!**保存该文件。
|
||||
|
||||
6. 在其他每台服务器上执行如下命令将第一台服务器制作好的公钥复制到其他每台服务器内。
|
||||
|
||||
cd ~/.ssh/
|
||||
scp root@xxx.xxx.xxx.111:~/.ssh/authorized_keys ./
|
||||
|
||||
7. 在每台服务器执行如下命令测试免密登录。
|
||||
|
||||
```
|
||||
ssh 用户名@IP地址
|
||||
```
|
||||
|
||||
例如:在第一台服务器xxx.xxx.xxx.111免密登录服务器xxx.xxx.xxx.222,执行**ssh root@xxx.xxx.xxx.222**命令。
|
||||
|
||||
若显示类似如下信息,说明已免密登录服务器xxx.xxx.xxx.222。
|
||||
|
||||
```
|
||||
Linux ubuntu 4.19.28 #1 SMP Tue Jun 23 19:05:23 EDT 2020 x86_64
|
||||
|
||||
The programs included with the ubuntu GNU/Linux system are free software;
|
||||
the exact distribution terms for each program are described in the
|
||||
individual files in /usr/share/doc/*/copyright.
|
||||
|
||||
ubuntu GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
|
||||
permitted by applicable law.
|
||||
Last login: Tue Sep 15 14:37:21 2020 from 10.254.88.75
|
||||
```
|
||||
|
||||
执行**exit**命令可以退出登录,若显示类似如下信息,说明已退出登录。
|
||||
|
||||
```
|
||||
logout
|
||||
Connection to xxx.xxx.xxx.222 closed.
|
||||
```
|
||||
|
||||
3. 使用OpenMPI拉起模型训练。
|
||||
|
||||
1. 分别为每一个AI server编写启动脚本,如train.sh,并将启动脚本分别移到相应AI server的同一路径下。
|
||||
|
||||
```
|
||||
# 配置NPU环境变量,env_npu.sh脚本参见附录
|
||||
source env_npu.sh
|
||||
#关闭HCCL通道白名单
|
||||
export HCCL_WHITELIST_DISABLE=1
|
||||
# HCCL初始化通信网卡IP,设置为当前服务器的host IP
|
||||
export HCCL_IF_IP=xxx.xxx.xx.xxx
|
||||
python3 -m torch.distributed.launch --nnodes=${nnodes} --node_rank=i --nproc_per_node 8 --master_addr xxx.xxx.xx.xxx --master_port 29501 main.py --addr xxx.xxx.xx.xxx
|
||||
```
|
||||
|
||||
脚本参数请参见手动启动。
|
||||
|
||||
2. 编写启动脚本
|
||||
|
||||
```
|
||||
# 配置mpirun环境变量
|
||||
export PATH=$PATH:/usr/local/mpirun4.0.2/bin
|
||||
# 执行mpirun工具
|
||||
mpirun -H xxx.xxx.xxx.xxx:1,xxx.xxx.xxx.xxx:1 \
|
||||
--bind-to none -map-by slot \
|
||||
--mca btl_tcp_if_exclude lo,docker0,endvnic\
|
||||
--allow-run-as-root \
|
||||
--prefix /usr/local/mpirun4.0.2/ \
|
||||
./train.sh
|
||||
```
|
||||
|
||||
其中
|
||||
|
||||
-H:每个AI server的IP:启动进程数。
|
||||
|
||||
--bind-to:绑定进程的策略。
|
||||
|
||||
--mca:特定上下文的MCA参数,arg0为参数名,arg1为参数值。
|
||||
|
||||
--allow-run-as-root:允许使用root用户运行。
|
||||
|
||||
--prefix:mpirun4.0.2路径。
|
||||
|
||||
./train.sh:各个AI server的启动脚本路径。
|
||||
|
||||
4.
|
||||
|
||||
训练成功后可以查看日志信息。
|
||||
|
||||
host日志保存在`~/ascend/log`路径下,用户可以到该路径下查看每个host的device日志。
|
||||
|
||||
# 附录
|
||||
|
||||
NPU环境变量配置脚本env_npu.sh,可使用该脚本进行运行和开发环境变量的配置。
|
||||
|
||||
```shell
|
||||
#!/bin/bash
|
||||
export install_path=/usr/local/Ascend
|
||||
|
||||
if [ -d ${install_path}/toolkit ]; then
|
||||
export LD_LIBRARY_PATH=/usr/include/hdf5/lib/:/usr/local/:/usr/local/lib/:/usr/lib/:${install_path}/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons:${path_lib}:${LD_LIBRARY_PATH}
|
||||
export PATH=${install_path}/fwkacllib/ccec_compiler/bin:${install_path}/fwkacllib/bin:$PATH
|
||||
export PYTHONPATH=${install_path}/fwkacllib/python/site-packages:${install_path}/tfplugin/python/site-packages:${install_path}/toolkit/python/site-packages:$PYTHONPATH
|
||||
export PYTHONPATH=/usr/local/python3.7.5/lib/python3.7/site-packages:$PYTHONPATH
|
||||
export ASCEND_OPP_PATH=${install_path}/opp
|
||||
else
|
||||
if [ -d ${install_path}/nnae/latest ];then
|
||||
export LD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
|
||||
export PATH=$PATH:${install_path}/nnae/latest/fwkacllib/ccec_compiler/bin/:${install_path}/nnae/latest/toolkit/tools/ide_daemon/bin/
|
||||
export ASCEND_OPP_PATH=${install_path}/nnae/latest/opp/
|
||||
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
|
||||
export PYTHONPATH=${install_path}/nnae/latest/fwkacllib/python/site-packages/:${install_path}/nnae/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:${install_path}/nnae/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
|
||||
export ASCEND_AICPU_PATH=${install_path}/nnae/latest
|
||||
else
|
||||
export LD_LIBRARY_PATH=/usr/local/:/usr/local/lib/:/usr/lib64/:/usr/lib/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64-linux-gnu:$LD_LIBRARY_PATH
|
||||
export PATH=$PATH:${install_path}/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin/:${install_path}/ascend-toolkit/latest/toolkit/tools/ide_daemon/bin/
|
||||
export ASCEND_OPP_PATH=${install_path}/ascend-toolkit/latest/opp/
|
||||
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
|
||||
export PYTHONPATH=${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/:${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
|
||||
export ASCEND_AICPU_PATH=${install_path}/ascend-toolkit/latest
|
||||
fi
|
||||
fi
|
||||
|
||||
#将Host日志输出到串口,0-关闭/1-开启
|
||||
export ASCEND_SLOG_PRINT_TO_STDOUT=0
|
||||
#设置默认日志级别,0-debug/1-info/2-warning/3-error
|
||||
export ASCEND_GLOBAL_LOG_LEVEL=3
|
||||
#设置Event日志开启标志,0-关闭/1-开启
|
||||
export ASCEND_GLOBAL_EVENT_ENABLE=0
|
||||
#设置是否开启taskque,0-关闭/1-开启
|
||||
export TASK_QUEUE_ENABLE=1
|
||||
#HCCL白名单开关,1-关闭/0-开启
|
||||
export HCCL_WHITELIST_DISABLE=1
|
||||
|
||||
#设置device侧日志登记为error
|
||||
${install_path}/driver/tools/msnpureport -g error -d 0
|
||||
${install_path}/driver/tools/msnpureport -g error -d 1
|
||||
${install_path}/driver/tools/msnpureport -g error -d 2
|
||||
${install_path}/driver/tools/msnpureport -g error -d 3
|
||||
${install_path}/driver/tools/msnpureport -g error -d 4
|
||||
${install_path}/driver/tools/msnpureport -g error -d 5
|
||||
${install_path}/driver/tools/msnpureport -g error -d 6
|
||||
${install_path}/driver/tools/msnpureport -g error -d 7
|
||||
#关闭Device侧Event日志
|
||||
${install_path}/driver/tools/msnpureport -e disable
|
||||
|
||||
path_lib=$(python3.7 -c """
|
||||
import sys
|
||||
import re
|
||||
result=''
|
||||
for index in range(len(sys.path)):
|
||||
match_sit = re.search('-packages', sys.path[index])
|
||||
if match_sit is not None:
|
||||
match_lib = re.search('lib', sys.path[index])
|
||||
|
||||
if match_lib is not None:
|
||||
end=match_lib.span()[1]
|
||||
result += sys.path[index][0:end] + ':'
|
||||
|
||||
result+=sys.path[index] + '/torch/lib:'
|
||||
print(result)"""
|
||||
)
|
||||
|
||||
echo ${path_lib}
|
||||
|
||||
export LD_LIBRARY_PATH=/usr/local/python3.7.5/lib/:${path_lib}:$LD_LIBRARY_PATH
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
# PyTorch毕昇C++算子开发指南
|
||||
- [简介](#简介md)
|
||||
- [环境准备](#环境准备md)
|
||||
- [C++ Extension方式开发算子](#Extension方式开发算子md)
|
||||
- [环境准备](#环境准备md)
|
||||
- [示例:add算子实现](#add算子md)
|
||||
- [示例:add算子编译](#add算子安装代码md)
|
||||
- [示例:add算子测试](#add算子测试md)
|
||||
- [框架联合编译方式开发算子](#框架联合编译方式开发算子md)
|
||||
- [FAQ](#FAQmd)
|
||||
- [示例add算子编译失败](#python-setup_py-install失败md)
|
||||
- [示例add算子测试失败](#python-test_add_bisheng_py失败md)
|
||||
<h2 id="简介md">简介</h2>
|
||||
毕昇C++提供了面向昇腾芯片的通用编程模型抽象,让开发者可以使用标准C++语法编写适用于昇腾芯片的算子。
|
||||
|
||||
昇腾PyTorch支持C++ Extension和框架联合编译两种方式开发毕昇C++算子,该文档介绍了怎么在PyTorch中使用毕昇C++开发算子。
|
||||
<h2 id="环境准备md">环境准备</h2>
|
||||
在PyTorch框架中开发毕昇C++算子环境准备包括两部分内容:一是CANN和毕昇C++的安装,二是PyTorch框架安装:
|
||||
|
||||
- CANN和毕昇C++的安装:当前毕昇C++内置于CANN 6.3.T100版本,安装CANN时同时安装毕昇C++,使用CANN内置脚本配置CANN环境变量时会同时配置毕昇C++环境变量。
|
||||
- CANN 6.3.T100下载地址及毕昇C++文档请参考:[CANN 6.3.T100(毕昇C++)安装包及文档](https://support.huawei.com/enterprise/zh/ascend-computing/cann-pid-251168373/software/259218207?idAbsPath=fixnode01%7C23710424%7C251366513%7C22892968%7C251168373);
|
||||
- CANN安装请参考昇腾社区文档中环境安装环节[《CANN软件安装》](https://www.hiascend.com/document?tag=community-developer)
|
||||
- 安装后运行CANN安装目录下的`set_env.sh`自动配置CANN和毕昇C++相关环境变量。
|
||||
|
||||
安装CANN并完成环境变量配置后可以查看CANN和毕昇C++的环境变量:
|
||||
```
|
||||
echo $BISHENG_CPP_HOME
|
||||
echo $ASCEND_HOME_PATH
|
||||
```
|
||||
|
||||
- 参考README里编译安装原生PyTorch和昇腾PyTorch
|
||||
|
||||
<h2 id="Extension方式开发算子md">C++ Extension方式开发算子</h2>
|
||||
<h3 id="环境准备md">环境准备</h3>
|
||||
|
||||
参考前文安装CANN、毕昇C++和PyTorch,并配置环境变量
|
||||
|
||||
<h3 id="add算子md">示例:add算子实现</h3>
|
||||
add_bisheng.cpp
|
||||
|
||||
```
|
||||
// Copyright (c) 2023 Huawei Technologies Co., Ltd
|
||||
// All rights reserved.
|
||||
//
|
||||
// Licensed under the BSD 3-Clause License (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://opensource.org/licenses/BSD-3-Clause
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <sycl/sycl.hpp>
|
||||
#include <acl/acl.h>
|
||||
#include <torch/extension.h>
|
||||
#include <torch_npu/csrc/core/npu/NPUStream.h>
|
||||
|
||||
using namespace at;
|
||||
using namespace sycl;
|
||||
using namespace sycl::access;
|
||||
template <typename T>
|
||||
using LocalAccessor = accessor<T, 1, mode::read_write, target::local>;
|
||||
|
||||
template <typename T, int group_count, typename kernel_name>
|
||||
void add_bisheng_kernel(queue &sycl_queue, const T *in1, const T *in2, T *out, size_t length) {
|
||||
sycl_queue.submit([&](handler &cgh)
|
||||
{
|
||||
LocalAccessor<T> local_in1(length, cgh);
|
||||
LocalAccessor<T> local_in2(length, cgh);
|
||||
LocalAccessor<T> local_out(length, cgh);
|
||||
cgh.parallel_for_work_group<kernel_name>(sycl::range<1> { group_count }, [=](group<1> grp) {
|
||||
const auto gid = grp.get_id(0);
|
||||
const auto idx_base = gid * length;
|
||||
[[loop::parallel]] for (size_t i = 0; i < length; ++i) {
|
||||
local_in1[i] = in1[i + idx_base];
|
||||
local_in2[i] = in2[i + idx_base];
|
||||
local_out[i] = local_in1[i] + local_in2[i];
|
||||
out[i + idx_base] = local_out[i];
|
||||
}
|
||||
}); });
|
||||
sycl_queue.wait();
|
||||
}
|
||||
|
||||
template <class T, class kernel_name>
|
||||
Tensor add_bisheng_launch(const Tensor &self, const Tensor &other) {
|
||||
Tensor result = at::empty(self.sizes(), self.options());
|
||||
const T *self_ptr = static_cast<T *>(self.storage().data_ptr().get());
|
||||
const T *other_ptr = static_cast<T *>(other.storage().data_ptr().get());
|
||||
T *result_ptr = static_cast<T *>(result.storage().data_ptr().get());
|
||||
|
||||
aclrtContext acl_context;
|
||||
aclrtGetCurrentContext(&acl_context);
|
||||
sycl::context sycl_context = sycl::make_context<sycl::backend::cce>(acl_context);
|
||||
int device_id = 0;
|
||||
aclrtGetDevice(&device_id);
|
||||
auto npu_stream = c10_npu::getCurrentNPUStream(device_id);
|
||||
auto acl_stream = npu_stream.stream();
|
||||
queue sycl_queue = sycl::make_queue<sycl::backend::cce>(acl_stream, sycl_context);
|
||||
|
||||
const T *input1 = self_ptr;
|
||||
const T *input2 = other_ptr;
|
||||
constexpr size_t group_count = 1;
|
||||
size_t len = result.numel() / group_count;
|
||||
add_bisheng_kernel<T, group_count, kernel_name>(sycl_queue, input1, input2, result_ptr, len);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Tensor add_bisheng(const Tensor &self, const Tensor &other) {
|
||||
if (self.scalar_type() == at::kHalf) {
|
||||
return add_bisheng_launch<half, class addhalf>(self, other);
|
||||
} else if (self.scalar_type() == at::kFloat) {
|
||||
return add_bisheng_launch<float, class addfloat>(self, other);
|
||||
} else {
|
||||
return add_bisheng_launch<int64_t, class addint>(self, other);
|
||||
}
|
||||
}
|
||||
|
||||
PYBIND11_MODULE(add_bisheng, m) {
|
||||
m.def("add", &add_bisheng, "x + y");
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
<h3 id="add算子安装代码md">示例:add算子编译</h3>
|
||||
python setup.py install
|
||||
|
||||
```
|
||||
# Copyright (c) 2023 Huawei Technologies Co., Ltd
|
||||
# All rights reserved.
|
||||
#
|
||||
# Licensed under the BSD 3-Clause License (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://opensource.org/licenses/BSD-3-Clause
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from setuptools import setup
|
||||
from torch.utils.cpp_extension import BuildExtension
|
||||
|
||||
from torch_npu.utils.cpp_extension import BiShengExtension
|
||||
|
||||
|
||||
setup(
|
||||
name='add_bisheng',
|
||||
ext_modules=[
|
||||
BiShengExtension(
|
||||
name='add_bisheng',
|
||||
sources=['add_bisheng.cpp']),
|
||||
],
|
||||
cmdclass={
|
||||
'build_ext': BuildExtension
|
||||
})
|
||||
|
||||
```
|
||||
<h3 id="add算子测试md">示例:add算子测试</h3>
|
||||
python test_add_bisheng.py
|
||||
|
||||
```
|
||||
# Copyright (c) 2023 Huawei Technologies Co., Ltd
|
||||
# All rights reserved.
|
||||
#
|
||||
# Licensed under the BSD 3-Clause License (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://opensource.org/licenses/BSD-3-Clause
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
import time
|
||||
import torch
|
||||
|
||||
import torch_npu
|
||||
|
||||
|
||||
JIT_COMPILE_EXTENSION = True
|
||||
if JIT_COMPILE_EXTENSION:
|
||||
from torch_npu.utils.cpp_extension import load
|
||||
module = load(name="add_bisheng", sources=["./add_bisheng.cpp"], verbose=1)
|
||||
else:
|
||||
# python setup.py install
|
||||
import add_bisheng as module
|
||||
|
||||
torch.manual_seed(0)
|
||||
npu_device = os.environ.get('SET_NPU_DEVICE')
|
||||
if npu_device is None:
|
||||
torch.npu.set_device("npu:0")
|
||||
else:
|
||||
torch.npu.set_device(f"npu:{npu_device}")
|
||||
|
||||
a = torch.rand(2, 10).npu()
|
||||
b = torch.rand(2, 10).npu()
|
||||
print("A: " + str(a))
|
||||
print("B: " + str(b))
|
||||
add_result = module.add(a, b)
|
||||
print("add_result: " + str(add_result))
|
||||
|
||||
print("\n")
|
||||
a = torch.randint(0, 10, (2, 10)).npu()
|
||||
b = torch.randint(0, 10, (2, 10)).npu()
|
||||
print("A int: " + str(a))
|
||||
print("B int: " + str(b))
|
||||
add_result = module.add(a, b)
|
||||
print("add_result int: " + str(add_result))
|
||||
|
||||
print("\n")
|
||||
a = torch.rand(2, 10).half()
|
||||
b = torch.rand(2, 10).half()
|
||||
a = a.npu()
|
||||
b = b.npu()
|
||||
print("A half: " + str(a))
|
||||
print("B half: " + str(b))
|
||||
add_result = module.add(a, b)
|
||||
print("add_result half: " + str(add_result))
|
||||
|
||||
```
|
||||
|
||||
<h2 id="框架联合编译方式开发算子md">框架联合编译方式开发算子</h2>
|
||||
|
||||
- 在torch_npu/csrc/aten/npu_native_functions.yaml增加接口定义, 参考:bscpp_add
|
||||
```
|
||||
- func: bscpp_add(Tensor self, Tensor other) -> Tensor
|
||||
bscpp_op: True
|
||||
```
|
||||
- 在torch_npu/csrc/aten/bscpp_ops目录下增加算子实现CPP文件,参考:AddKernel.cpp
|
||||
|
||||
- 编译框架:
|
||||
```
|
||||
# BSCPP_SYCL_TARGET设置请参考毕昇C++文档
|
||||
BSCPP_OPS_ENABLE=1 BSCPP_SYCL_TARGET=ascend_910-cce bash ci/build.sh
|
||||
```
|
||||
|
||||
- 安装框架:
|
||||
```
|
||||
pip install --upgrade --force-reinstall dist/*.whl
|
||||
```
|
||||
|
||||
<h2 id="FAQmd">FAQ</h2>
|
||||
|
||||
- **[示例add算子编译失败](#python-setup_py-install失败md)**
|
||||
- **[示例add算子测试失败](#python-test_add_bisheng_py失败md)**
|
||||
|
||||
<h3 id="python-setup_py-install失败md">示例add算子编译失败</h3>
|
||||
|
||||
#### 现象描述
|
||||
|
||||
/opt/BiShengCPP/bin/clang: error while loading shared libraries: libtinfo.so.6: cannot open shared object file: No such file or directory
|
||||
|
||||
|
||||
#### 处理方法
|
||||
|
||||
复制libtinfo.so.6到 ${BISHENTCPP_ROOT}/lib
|
||||
|
||||
```
|
||||
(***111) root@ubuntu:/home/***/add_bisheng# find / -name "libtinfo.so.6"
|
||||
/root/miniconda3/pkgs/ncurses-6.3-h2f4d8fa_2/lib/libtinfo.so.6
|
||||
/root/miniconda3/pkgs/ncurses-6.3-h998d150_3/lib/libtinfo.so.6
|
||||
/root/miniconda3/envs/pt181/lib/libtinfo.so.6
|
||||
/root/miniconda3/envs/pt111/lib/libtinfo.so.6
|
||||
/root/miniconda3/envs/***111/lib/libtinfo.so.6
|
||||
/root/miniconda3/lib/libtinfo.so.6
|
||||
/home/syf/miniconda3/pkgs/ncurses-6.3-h2f4d8fa_2/lib/libtinfo.so.6
|
||||
/home/syf/miniconda3/pkgs/ncurses-6.3-h998d150_3/lib/libtinfo.so.6
|
||||
/home/syf/miniconda3/lib/libtinfo.so.6
|
||||
(***111) root@ubuntu:/home/***/add_bisheng# cp /root/miniconda3/lib/libtinfo.so.6 ${BISHENTCPP_ROOT}/lib
|
||||
|
||||
```
|
||||
|
||||
<h3 id="python-test_add_bisheng_py失败md">示例add算子测试失败</h3>
|
||||
|
||||
#### 现象描述
|
||||
|
||||
```
|
||||
ERROR: setUpClass (__main__.test_add_bisheng)
|
||||
----------------------------------------------------------------------
|
||||
Traceback (most recent call last):
|
||||
File "/root/miniconda3/envs/***111/lib/python3.7/site-packages/torch_npu/testing/testcase.py", line 71, in setUpClass
|
||||
self.npu_device = set_npu_device()
|
||||
File "/root/miniconda3/envs/***111/lib/python3.7/site-packages/torch_npu/testing/common_utils.py", line 83, in set_npu_device
|
||||
torch.npu.set_device(npu_device)
|
||||
File "/root/miniconda3/envs/***111/lib/python3.7/site-packages/torch_npu/npu/utils.py", line 149, in set_device
|
||||
torch_npu._C._npu_setDevice(torch.device(device).index)
|
||||
RuntimeError: Initialize:/home/***/PyTorch/torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.cpp:97 NPU error, error code is 507033
|
||||
EL0003: The argument is invalid.
|
||||
Solution: Try again with a valid argument.
|
||||
TraceBack (most recent call last):
|
||||
Failed to open device, retCode=0x7020014, deviceId=0.[FUNC:Init][FILE:device.cc][LINE:227]
|
||||
Check param failed, dev can not be NULL![FUNC:DeviceRetain][FILE:runtime.cc][LINE:2133]
|
||||
Check param failed, dev can not be NULL![FUNC:PrimaryContextRetain][FILE:runtime.cc][LINE:1946]
|
||||
Check param failed, ctx can not be NULL![FUNC:PrimaryContextRetain][FILE:runtime.cc][LINE:1973]
|
||||
Check param failed, context can not be null.[FUNC:NewDevice][FILE:api_impl.cc][LINE:1315]
|
||||
new device failed, retCode=0x7010006[FUNC:SetDevice][FILE:api_impl.cc][LINE:1336]
|
||||
rtSetDevice execute failed, reason=[device retain error][FUNC:FuncErrorReason][FILE:error_message_manage.cc][LINE:49]
|
||||
open device 0 failed, runtime result = 507033.[FUNC:ReportCallError][FILE:log_inner.cpp][LINE:161]
|
||||
ctx is NULL![FUNC:GetDevErrMsg][FILE:api_impl.cc][LINE:3490]
|
||||
rtGetDevMsg execute failed, reason=[context pointer null][FUNC:FuncErrorReason][FILE:error_message_manage.cc][LINE:49]
|
||||
```
|
||||
|
||||
|
||||
#### 处理方法
|
||||
|
||||
export SET_NPU_DEVICE=1
|
||||
@@ -200,7 +200,7 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
|
||||
|
||||
<h4 id="概述md">概述</h4>
|
||||
|
||||
当前制定的NPU适配派发原则是NPU算子的派发不经过框架公共函数,直接派发成NPU适配的函数,即算子执行调用栈中只包含NPU适配的函数调用,不包含框架公共函数。PyTorch框架在编译时,会根据 native\_functions.yaml 的定义,按框架中定义的类型和设备分发原则,生成相应的新算子的中间层的调用说明。对于NPU,会生成在 build/aten/src/ATen/NPUType.cpp。
|
||||
当前制定的NPU适配派发原则是NPU算子的派发不经过框架公共函数,直接派发成NPU适配的函数,即算子执行调用栈中只包含NPU适配的函数调用,不包含框架公共函数。PyTorch框架在编译时,会根据 native\_functions.yaml 的定义,按框架中定义的类型和设备分发原则,生成相应的新算子的中间层的调用说明。对于NPU,会生成在 torch_npu/csrc/aten/RegisterNPU.cpp。
|
||||
|
||||
<h4 id="PyTorch1-8-1-注册算子开发md">PyTorch1.8.1 注册算子开发</h4>
|
||||
|
||||
@@ -208,7 +208,7 @@ PyTorch算子开发包含TBE算子开发和PyTorch框架下的算子适配。
|
||||
|
||||
1. 打开native\_functions.yaml文件。
|
||||
|
||||
native\_functions.yaml 文件中,定义了所有算子函数原型,包括函数名称和参数等信息,每个算子函数支持不同硬件平台的派发信息。该文件所在路径为pytorch/aten/src/ATen/native/native\_functions.yaml。
|
||||
native\_functions.yaml 文件中,定义了所有算子函数原型,包括函数名称和参数等信息,每个算子函数支持不同硬件平台的派发信息。该文件所在路径为scripts/codegen/native\_functions.yaml。
|
||||
|
||||
2. 确定需要派发函数。
|
||||
- yaml 中已存在的算子
|
||||
@@ -446,7 +446,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
|
||||
at::Tensor result = OpPreparation::ApplyTensorWithFormat(
|
||||
outputSize,
|
||||
outputTensor.options(),
|
||||
CalcuOpUtil::get_tensor_npu_format(outputTensor));
|
||||
CalcuOpUtil::GetTensorNpuFormat(outputTensor));
|
||||
|
||||
// calculate the output result of the NPU
|
||||
add_out_npu_nocheck(result, self, other, alpha);
|
||||
@@ -462,7 +462,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
|
||||
auto outputSize = input_same_output_size(self);
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensorWithFormat(
|
||||
outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
|
||||
outputSize, self.options(), CalcuOpUtil::GetTensorNpuFormat(self));
|
||||
|
||||
// calculate the output result of the NPU
|
||||
adds_out_npu_nocheck(result, self, other, alpha);
|
||||
@@ -480,7 +480,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
|
||||
{
|
||||
c10::SmallVector<at::Tensor, N> inputs = {self, other};
|
||||
c10::SmallVector<at::Tensor, N> outputs = {self};
|
||||
CalcuOpUtil::check_memory_over_laps(inputs, outputs);
|
||||
CalcuOpUtil::CheckMemoryOverLaps(inputs, outputs);
|
||||
|
||||
if (!NpuUtils::check_match(&self))
|
||||
{
|
||||
@@ -524,7 +524,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
|
||||
at::Scalar alpha,
|
||||
at::Tensor &result)
|
||||
{
|
||||
bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self);
|
||||
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(self);
|
||||
|
||||
at::Tensor outputTensor;
|
||||
if (not isSelfWrapped)
|
||||
@@ -539,7 +539,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
|
||||
OpPreparation::CheckOut(
|
||||
{self},
|
||||
result,
|
||||
CalcuOpUtil::get_tensor_npu_format(result),
|
||||
CalcuOpUtil::GetTensorNpuFormat(result),
|
||||
outputTensor.scalar_type(),
|
||||
outputSize);
|
||||
|
||||
@@ -688,7 +688,7 @@ pip3 install --upgrade torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
|
||||
|
||||
3. 执行测试用例脚本
|
||||
|
||||
进入test\_add.py所在的目录,执行:
|
||||
进入test\_add.py所在的目录/test/test_network_ops,执行:
|
||||
|
||||
```
|
||||
python3.7 test_add.py
|
||||
@@ -831,7 +831,7 @@ pip3.7 install torchvision --no-deps
|
||||
至此步骤,不应该有错误,屏幕应该输出 "add" 中增加的日志打印。若出错,请完成代码清理排查,保证无新开发的代码影响测试。
|
||||
|
||||
3. 将新开发的“自定义TBE算子”合并到"cann"中,在对应的在算子入口增加日志打印,作为运行标识。
|
||||
4. 完成上面的"cann"编译、安装,调用“python3.7.5 test\_add.py”进行测试。
|
||||
4. 完成上面的"cann"编译、安装,调用“python3.7 test\_add.py”进行测试。
|
||||
|
||||
> **说明:**
|
||||
>根据Ascend的设计逻辑,用户开发安装的“custom”算子包优先级高于“built-in”的内置算子包,在运行加载时,会优先加载调度“custom”包中的算子。过程中,若解析“custom”中的算子信息文件失败,则会跳过“custom”算子包,不加载调度任何“custom”算子包中的任何算子。
|
||||
@@ -839,11 +839,11 @@ pip3.7 install torchvision --no-deps
|
||||
>- 若此步骤出错,或屏幕未输出 "add" 中增加的日志打印,则说明新开发的“自定义TBE算子”有错误,影响了“自定义算子包”的加载,建议**优先排查新开发的“自定义TBE算子”中的“算子信息定义”是否正确**。
|
||||
>- 若此步骤正确,至少说明 **新开发的“自定义TBE算子”中的“算子信息定义”不影响运行**。
|
||||
|
||||
5. 调用“python3.7.5 xxx\_testcase.py”进行测试;
|
||||
5. 调用“python3.7 xxx\_testcase.py”进行测试,xxx为新增算子名称;
|
||||
|
||||
> **说明:**
|
||||
>- 若屏幕正常输出新开发的“自定义TBE算子”中增加的日志打印,则至少说明调度到了新开发的算子。
|
||||
>- 若屏幕未输出新开发的“自定义TBE算子”中增加的日志打印,则问题可能出现在“PyTorch适配”中,需要排查这一部分的实现代码,较多的可能会出现在“XxxxKernelNpu.cpp”中的输入、输出未能正确适配。
|
||||
>- 若屏幕未输出新开发的“自定义TBE算子”中增加的日志打印,则问题可能出现在“PyTorch适配”中,需要排查这一部分的实现代码,较多的可能会出现在“XxxxKernelNpu.cpp”中的输入、输出未能正确适配,XxxxKernelNpu.cpp为新增算子信息文件。
|
||||
|
||||
|
||||
|
||||
@@ -859,7 +859,7 @@ pip3.7 install torchvision --no-deps
|
||||
1. 打开安装在用户目录下的算子包安装目录。
|
||||
|
||||
```
|
||||
cd ~/.local/Ascend/opp/op_impl/built-in/ai_core/tbe/impl
|
||||
cd /usr/local/Ascend/ascend-toolkit/op_impl/build-in/ai_core/tbe/config/ascend910/
|
||||
ll
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
# **PyTorch精度对比和溢出检测工具使用指南**
|
||||
- [**PyTorch精度对比工具使用指南**](#pytorch精度对比工具使用指南)
|
||||
- [**使用场景**](#使用场景)
|
||||
- [**前提条件**](#前提条件)
|
||||
- [**注意事项**](#注意事项)
|
||||
- [**精度比对基本原理**](#精度比对基本原理)
|
||||
- [**算子匹配条件**](#算子匹配条件)
|
||||
- [**计算精度评价指标**](#计算精度评价指标)
|
||||
- [**快速上手样例参考**](#快速上手样例参考)
|
||||
|
||||
|
||||
## **使用场景**
|
||||
|
||||
在同一模型或算子调试过程中,遇到算子相关的计算精度问题,定位时费时费力,所以推出了一个精度比对工具。
|
||||
|
||||
精度对比工具,通过在PyTorch模型中注入hook,跟踪计算图中算子的前向传播与反向传播时的输入与输出,排查存在计算精度误差,进行问题的精准定位。
|
||||
|
||||
主要的使用场景包括:
|
||||
|
||||
- 同一模型,从cpu(或npu)移植到npu中存在精度下降问题,对比npu芯片中的算子计算数值与cpu芯片中的算子计算数值,进行问题定位。
|
||||
- 同一模型,进行迭代(模型、算子或设备迭代)时存在的精度下降问题,对比相同模型在迭代前后版本的算子计算数值,进行问题定位。
|
||||
|
||||
以gpu为参照定位精度问题,使用ptdbg_ascend插件来进行数据dump和比对,请参考[ptdbg_ascend](https://gitee.com/ascend/tools/tree/master/ptdbg_ascend)。
|
||||
|
||||
## **前提条件**
|
||||
|
||||
已完成PyTorch Adapter插件的编译安装,具体操作请参考[《AscendPyTorch安装指南》](../PyTorch安装指南/PyTorch安装指南.md)。
|
||||
|
||||
## **注意事项**
|
||||
|
||||
训练脚本中使用torch.utils.data.DataLoader加载数据时,请将num_workers参数设为0。
|
||||
```python
|
||||
from torch.utils.data import DataLoader
|
||||
|
||||
loader=DataLoader(...,num_workers=0,...)
|
||||
```
|
||||
|
||||
## **精度比对基本原理**
|
||||
|
||||
普遍适用的方法是以模型为单位,采用hook机制挂在模型的上。当模型在CPU上进行正向传播时跟踪并dump每一层的数值输入与输出,在反向传播时跟踪并dump每一层的梯度输入值与输出值;同样的当模型在NPU中进行计算时采用相同的方式记录下相应的数据,通过对比dump出的数值,计算余弦相似度和均方根误差的方式,
|
||||
定位和排查NPU算子存在的计算精度问题。
|
||||
|
||||
精度比对工具dump数据说明:在实际使用场景中网络模型通常较大,基于整网全量数据的dump,耗时长且储存文件大。因此内部默认使用部分网络参数和统计量的方式dump数据来提升效率。如需dump全量数据,请将register_hook函数中的sample参数设为False(默认为True)。
|
||||
|
||||

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

|
||||
|
||||
由于可能会出现融合算子,所以在算子的逐一匹配时可能会出现错误匹配或无法匹配的问题,例如图2中NPU算子npu_op_1与npu_op_2无法和cpu_op_k进行匹配,才去跳过的方式,直到到npu_op_3和cpu_op_3才从新对齐开始匹配。
|
||||
|
||||
### **算子匹配条件**
|
||||
|
||||
判断运行在cpu和npu上的两个算子是否相同采用的步骤如下:
|
||||
|
||||
1. 两个算子的名字是否相同
|
||||
1. 两个算子的输入输出Tensor数量和各个Tensor的shape是否相同
|
||||
|
||||
通常满足以上的两个条件,就认为是同一个算子,成功进行算子的匹配,后续进行相应的计算精度比对。
|
||||
|
||||
### **计算精度评价指标**
|
||||
|
||||
在进行计算精度匹配时,基本共识为默认CPU或GPU的算子计算结果是准确的,最终比对生成的csv文件中主要包括以下的几个属性:
|
||||
| Name | Npu Tensor Dtype | Bench Tensor Dtype | Npu Tensor Shape | Bench Tensor Shape | Cosine | RMSE | MAPE |
|
||||
| :---: | :--------------: | :----------------: | :--------------: | :----------------: | :----: | :---: | :---: |
|
||||
|
||||
其中主要使用算子Name、Dtype、Shape用于描述算子的基本特征,Cosine(余弦相似)、RMSE(均方根误差)、MAPE(绝对百分比误差)作为评价计算精度的主要评估指标:
|
||||
|
||||
1. 余弦相似度(通过计算两个向量的余弦值来判断其相似度):
|
||||
|
||||
$$
|
||||
\Large
|
||||
cos(\theta) = \frac{\sum_{i=1}^{n} (\hat{y_{i}} \times y_{i})}
|
||||
{\sqrt{\sum_{i=1}^{n}\hat{y_{i}}} \times \sqrt{\sum_{i=1}^{n}y_{i}^{2}}}
|
||||
$$
|
||||
当余弦夹角数值越接近于1说明计算出的两个张量越相似,在计算中可能会存在nan,主要由于可能会出现其中一个向量为0
|
||||
|
||||
2. 均方根误差(RMSE):
|
||||
|
||||
$$
|
||||
\Large
|
||||
RMSE = \sqrt{\frac{1}{n} \sum_{i=1}^{n} (\hat{y_{i}} - y_{i})^{2}}
|
||||
$$
|
||||
当均方根误差越接近0表示其计算的平均误差越小
|
||||
|
||||
3. 平均绝对百分比误差(MAPE):
|
||||
|
||||
$$
|
||||
\Large
|
||||
MAPE = \frac{1}{n} \sum_{i=1}^{n}|\frac{\hat{y_{i}} - y_{i}}{y_{i}}|
|
||||
$$
|
||||
绝对百分比误差衡量计算误差的百分比,越接近0越好,但当其中的实际计算结果中存在0时是无法进行计算的
|
||||
|
||||
## **快速上手样例参考**
|
||||
相关函数导入
|
||||
```python
|
||||
from torch_npu.hooks import set_dump_path, seed_all, register_hook, wrap_acc_cmp_hook
|
||||
from torch_npu.hooks.tools import compare
|
||||
```
|
||||
相关函数说明:
|
||||
```python
|
||||
seed_all(seed=1234)->None
|
||||
功能:
|
||||
设置随机数种子, 固定网络初始化中的随机数
|
||||
参数:
|
||||
seed: 随机数种子
|
||||
例子:
|
||||
>>>seed_all()
|
||||
>>>seed_all(1234)
|
||||
```
|
||||
```python
|
||||
set_dump_path(fpath=None)->None
|
||||
功能:
|
||||
设置dump数据文件
|
||||
参数:
|
||||
fpath: dump数据文件
|
||||
例子:
|
||||
>>>set_dump_path("./cpu_module_op.pkl")
|
||||
>>>set_dump_path("/home/xxx/npu_module_op.pkl")
|
||||
```
|
||||
```python
|
||||
register_hook(model, hook, **kwargs)->None
|
||||
功能:
|
||||
对模型注入hooks, 开启dump数据功能
|
||||
参数:
|
||||
model: 需要dump数据的网络模型
|
||||
hook: 需要注册的函数, 精度比对工具使用wrap_acc_cmp_hook函数
|
||||
sample:是否使用数据采样方式dump数据, 默认为True
|
||||
例子:
|
||||
>>>register_hook(model, wrap_acc_cmp_hook)
|
||||
>>>register_hook(model, wrap_acc_cmp_hook, sample=False)
|
||||
>>>register_hook(model, wrap_acc_cmp_hook, sample=True)
|
||||
```
|
||||
```python
|
||||
compare(pkl_path1, pkl_path2, output_path, shape_flag=False)->None
|
||||
功能:
|
||||
对dump下来的两份数据进行比对
|
||||
参数:
|
||||
pkl_path1: 模型dump数据文件1
|
||||
pkl_path2: 模型dump数据文件2
|
||||
output_path: 精度比对结果文件输出路径
|
||||
shape_flag: False时只使用算子名字进行匹配, True时使用算子名称, 输入输出大小进行匹配
|
||||
例子:
|
||||
>>>compare("./npu_module_op.pkl", "./cpu_module_op.pkl", "./module_result.csv")
|
||||
```
|
||||
|
||||
使用精度比对工具进行模型的精度比对,样例代码如下:
|
||||
|
||||
```python
|
||||
# 根据需要import包
|
||||
import os
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from torch_npu.hooks import set_dump_path, seed_all, register_hook, wrap_acc_cmp_hook
|
||||
from torch_npu.hooks.tools import compare
|
||||
|
||||
|
||||
# 定义一个简单的网络
|
||||
class ModuleOP(nn.Module):
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.linear_1 = nn.Linear(in_features=2, out_features=2)
|
||||
self.linear_2 = nn.Linear(in_features=2, out_features=1)
|
||||
self.relu = nn.ReLU()
|
||||
|
||||
def forward(self, x):
|
||||
x1 = self.linear_1(x)
|
||||
x2 = self.linear_2(x1)
|
||||
r1 = self.relu(x2)
|
||||
return r1
|
||||
|
||||
module = ModuleOP()
|
||||
# 对模型注入forwar和backward的hooks,采样功能默认开启,如需关闭,请使用register_hook(model_cpu, wrap_acc_cmp_hook, sample=False)
|
||||
register_hook(model_cpu, wrap_acc_cmp_hook)
|
||||
seed_all()
|
||||
x = torch.randn(2, 2)
|
||||
|
||||
# cpu上计算,dump数据
|
||||
set_dump_path("./cpu_module_op.pkl")
|
||||
out = module(x)
|
||||
loss = out.sum()
|
||||
loss.backward()
|
||||
|
||||
module.npu()
|
||||
x = x.npu()
|
||||
# npu上计算,dump数据
|
||||
set_dump_path("./npu_module_op.pkl")
|
||||
out = module(x)
|
||||
loss = out.sum()
|
||||
loss.backward()
|
||||
|
||||
# 对比dump出的数据精度,生成csv文件
|
||||
compare("./npu_module_op.pkl", "./cpu_module_op.pkl", "./module_result.csv")
|
||||
|
||||
```
|
||||
|
||||
|
||||
使用精度比对工具进行torchvision下现有模型的计算精度比对,整体思路相同,其中cpu和npu的对比思路与npu和npu的对比思路也是相同,以resnet50模型为例代码如下:
|
||||
```python
|
||||
import os
|
||||
import copy
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import models, datasets, transforms
|
||||
|
||||
from torch_npu.hooks import set_dump_path, seed_all, register_hook, wrap_acc_cmp_hook
|
||||
from torch_npu.hooks.tools import compare
|
||||
|
||||
|
||||
# 选取需要的模型
|
||||
model_cpu = models.resnet50()
|
||||
model_cpu.eval()
|
||||
model_npu = copy.deepcopy(model_cpu)
|
||||
model_npu.eval()
|
||||
|
||||
seed_all()
|
||||
# 对该计算进行hook注入和数据dump,采样功能默认开启,如需关闭,请使用register_hook(model_cpu, wrap_acc_cmp_hook, sample=False)
|
||||
register_hook(model_cpu, wrap_acc_cmp_hook)
|
||||
register_hook(model_npu, wrap_acc_cmp_hook)
|
||||
|
||||
# 需要根据不同的模型输入和标签生成相应的tensor(或读取实际数据),损失函数等,如果是随机生成的标签需要保证数据的有效性
|
||||
inputs = torch.randn(1, 3, 244, 244)
|
||||
labels = torch.randn(1).long()
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
|
||||
# cpu
|
||||
set_dump_path("./cpu_resnet50_op.pkl")
|
||||
output = model_cpu(inputs)
|
||||
loss = criterion(output, labels)
|
||||
loss.backward()
|
||||
|
||||
# npu
|
||||
set_dump_path("./npu_resnet50_op.pkl")
|
||||
model_npu.npu()
|
||||
inputs = inputs.npu()
|
||||
labels = labels.npu()
|
||||
output = model_npu(inputs)
|
||||
loss = criterion(output, labels)
|
||||
loss.backward()
|
||||
|
||||
# 对比dump出的数据精度,生成csv文件
|
||||
compare("./npu_resnet50_op.pkl", "./cpu_resnet50_op.pkl", "./resnet50_result.csv")
|
||||
```
|
||||
如需对生成的pkl文件解析读取数据,可参考下列代码
|
||||
```python
|
||||
import json
|
||||
|
||||
pkl_file=open("./cpu_resnet50_op.pkl",'r')
|
||||
tensor_line=pkl_file.readline() # 读取行数据
|
||||
tensor_data=json.loads(tensor_line)
|
||||
|
||||
print(tensor_data[0]) # 算子名称
|
||||
print(tensor_data[1]) # 对应数据
|
||||
print(tensor_data[2]) # 数据类型
|
||||
print(tensor_data[3]) # 数据尺寸
|
||||
|
||||
```
|
||||
基于step粒度控制精度对比数据导出,通过在register_hook方法设置schedule参数控制需要导出数据的step。
|
||||
* **schedule**用于控制使能的step,入参分别为:**起始step(begin=0)、终止step(end=sys.maxsize)、步长(stride=1)**,例:
|
||||
schedule() 使能所有step;
|
||||
schedule(4, 10, 2) 使能的step为:4,6,8,10;
|
||||
schedule(begin=5, stride=3) 使能的step为:5,8,11,14...;
|
||||
schedule(end=10, stride=3) 使能的step为:0,3,6,9。
|
||||
* 变量step_num用于记录step数,调用**step_schedule.step**使变量step_num加1,step_num初始值为0;**step_schedule.reset_step**初始化step_num为0。
|
||||
```python
|
||||
from torch_npu.hooks import register_hook, wrap_acc_cmp_hook, schedule, step_schedule
|
||||
|
||||
# add step schedule, begin=4 end=10 stride=2
|
||||
register_hook(model, wrap_acc_cmp_hook, schedule=schedule(4, 10, 2))
|
||||
|
||||
for epoch in range(num_train_epochs):
|
||||
# init step_num as 0
|
||||
step_schedule.reset_step()
|
||||
for step, inputs in enumerate(dataloader):
|
||||
output = model(inputs)
|
||||
loss = output.sum()
|
||||
loss.backward()
|
||||
# step_num increase 1
|
||||
step_schedule.step()
|
||||
```
|
||||
异步算子数据导出wrap_async_datadump_hook(仅应用于npu算子导出);针对精度对比工具同步tensor数据导出,npu同cpu数据同步耗时较长的问题,利用npu上tdtchannel实现tensor数据的异步导出。
|
||||
* 通过register_hook方法注册异步导出hook wrap_async_datadump_hook,并通过path参数指定导出tensor数据的路径;导出算子较多时,可以通过capacity参数调整异步导出队列长度,默认3,参数范围3~2048。
|
||||
* 导出的文件名为:唯一索引_算子名_前反向_输入输出_shape_stride_offset_format.npy,例:16_Functional_relu_backward_input0_shape[2,1]_stride[1,1]_offset[0]_format[2].npy;导出的文件可以使用numpy.load方便导入。
|
||||
* wrap_async_datadump_hook依赖OutfeedEnqueueOpV2算子,该算子不支持runtime2.0;需设置环境变量规避**export RUNTIME_V2_BLACKLIST=OutfeedEnqueueOpV2**。
|
||||
```python
|
||||
from torch_npu.hooks import register_hook, wrap_async_datadump_hook, schedule, step_schedule
|
||||
|
||||
# register wrap_async_datadump_hook and add datadump path
|
||||
register_hook(module, wrap_async_datadump_hook, path='./output', schedule=schedule(1, 2))
|
||||
|
||||
# load datadump data by numpy
|
||||
numpy.load('./output/16_Functional_relu_backward_input0_shape[2,1]_stride[1,1]_offset[0]_format[2].npy')
|
||||
```
|
||||
|
||||
|
||||
- [**PyTorch溢出检测工具使用指南**](#pytorch精度对比工具使用指南)
|
||||
- [**使用场景**](#使用场景)
|
||||
- [**前提条件**](#前提条件)
|
||||
- [**基本原理**](#基本原理)
|
||||
- [**使用方法**](#使用方法)
|
||||
- [**快速上手样例参考**](#快速上手样例参考)
|
||||
|
||||
|
||||
## **使用场景**
|
||||
|
||||
在模型训练或调测中,遇到溢出问题,定位费时费力,可以使用溢出检测工具,快速定位溢出层位置。
|
||||
|
||||
溢出检测工具,通过在pytorch模型中注入hook,监测网络每一层是否有溢出问题,从而进行问题的精准定位。
|
||||
|
||||
## **前提条件**
|
||||
|
||||
已完成PyTorch Adapter插件的编译安装,具体操作请参考[《AscendPyTorch安装指南》](../PyTorch安装指南/PyTorch安装指南.md)。
|
||||
|
||||
## **基本原理**
|
||||
采用hook机制,对模型每一层执行前向和反向的过程调用溢出检测函数。溢出检测函数通过设定全局溢出标志位来判断是否有数值溢出情况,若有溢出,则会抛出error,输出对应api层名字,且在当前目录下自动生成含有溢出信息的文件。
|
||||
|
||||
## **使用方法**
|
||||
步骤1:引入库代码
|
||||
```python
|
||||
from torch_npu.hooks import register_hook, wrap_checkoverflow_hook
|
||||
```
|
||||
步骤2:对模型注册溢出检测函数hook
|
||||
```python
|
||||
register_hook(model,wrap_checkoverflow_hook)
|
||||
```
|
||||
|
||||
## **快速上手样例参考**
|
||||
使用溢出检测工具进行模型的溢出问题定位,样例代码如下:
|
||||
|
||||
|
||||
```python
|
||||
import os
|
||||
import copy
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import models, datasets, transforms
|
||||
|
||||
#import溢出检测工具相关函数
|
||||
from torch_npu.hooks import register_hook, wrap_checkoverflow_hook
|
||||
|
||||
# 需要定位问题的网络模型
|
||||
model = models.resnet50()
|
||||
model.npu()
|
||||
|
||||
#对模型注册溢出检测函数hook
|
||||
register_hook(model,wrap_checkoverflow_hook)
|
||||
|
||||
inputs = torch.randn(1, 3, 244, 244)
|
||||
labels = torch.randn(1).long()
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
|
||||
inputs = inputs.npu()
|
||||
labels = labels.npu()
|
||||
output = model_npu(inputs)
|
||||
loss = criterion(output, labels)
|
||||
loss.backward()
|
||||
|
||||
|
Before Width: | Height: | Size: 108 KiB After Width: | Height: | Size: 108 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 38 KiB |
@@ -11,6 +11,7 @@
|
||||
华为对自有训练模型算子进行了优化,其中包括算子消除、算子融合、算子拆分等,以更好的适配NPU等训练设备。
|
||||
因此在模型迁移的过程中,有时会遇到自有实现的算子运算的结果与业界标准算子运算结果存在偏差,精度不达标的问题,需要借助计算精度比对工具得出模型中的哪些算子在GPU和NPU的计算中会存在较大的差异,从而重点分析这些算子的表现性能,帮助开发人员快速定位并解决算子精度问题。
|
||||
|
||||
此外在进行模型版本迭代、底层算子迭代、计算设备(npu)迭代时也可能会引入计算精度的问题,有时会遇到新实现的算子运算的结果与要被替代的算子运算结果存在偏差等,需要借助计算精度对比工具得出那些算子在不同的版本或在不同的设备上存在较大的计算差异,从而快速定位计算精度问题。
|
||||
## **已有的精度对比脚本工具**
|
||||
|
||||
目前已经有一些可以进行精度比对的脚本示例,其主要思路都是相同的,包括整网对比和单算子对比,如图所示。
|
||||
@@ -1,184 +0,0 @@
|
||||
# **PyTorch精度对比工具使用指南**
|
||||
- [**PyTorch精度对比工具使用指南**](#pytorch精度对比工具使用指南)
|
||||
- [**使用场景**](#使用场景)
|
||||
- [**前提条件**](#前提条件)
|
||||
- [**精度比对基本原理**](#精度比对基本原理)
|
||||
- [**算子匹配条件**](#算子匹配条件)
|
||||
- [**计算精度评价指标**](#计算精度评价指标)
|
||||
- [**快速上手样例参考**](#快速上手样例参考)
|
||||
|
||||
|
||||
## **使用场景**
|
||||
|
||||
在同一模型或算子调试过程中,遇到算子相关的计算精度问题,定位时费时费力,所以推出了一个精度比对工具。
|
||||
|
||||
精度对比工具,通过在PyTorch模型中注入hook,跟踪计算图中算子的前向传播与反向传播时的输入与输出,对比npu芯片中的算子计算数值与cpu(gpu)芯片中的算子计算数值进行对比,排查npu算子在npu芯片中存在计算精度误差,进行问题的精准定位。
|
||||
|
||||
## **前提条件**
|
||||
|
||||
已完成PyTorch Adapter插件的编译安装,具体操作请参考[《AscendPyTorch安装指南》](../PyTorch安装指南/PyTorch安装指南.md)。
|
||||
|
||||
## **精度比对基本原理**
|
||||
|
||||
普遍适用的方法是以模型为单位,采用hook机制挂在模型的上。当模型在CPU(或GPU)上进行正向传播时跟踪并dump每一层的数值输入与输出,在反向传播时跟踪并dump每一层的梯度输入值与输出值;同样的当模型在NPU中进行计算时采用相同的方式记录下相应的数据,通过对比dump出的数值,计算余弦相似度和均方根误差的方式,
|
||||
定位和排查NPU算子存在的计算精度问题。
|
||||
|
||||

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

|
||||
|
||||
由于可能会出现融合算子,所以在算子的逐一匹配时可能会出现错误匹配或无法匹配的问题,例如图2中NPU算子npu_op_1与npu_op_2无法和cpu_op_k进行匹配,才去跳过的方式,直到到npu_op_3和cpu_op_3才从新对齐开始匹配。
|
||||
|
||||
### **算子匹配条件**
|
||||
|
||||
判断运行在cpu和npu上的两个算子是否相同采用的步骤如下:
|
||||
|
||||
1. 两个算子的名字是否相同
|
||||
1. 两个算子的输入输出Tensor数量和各个Tensor的shape是否相同
|
||||
|
||||
通常满足以上的两个条件,就认为是同一个算子,成功进行算子的匹配,后续进行相应的计算精度比对。
|
||||
|
||||
### **计算精度评价指标**
|
||||
|
||||
在进行计算精度匹配时,基本共识为默认CPU或GPU的算子计算结果是准确的,最终比对生成的csv文件中主要包括以下的几个属性:
|
||||
| Name | Npu Tensor Dtype | Bench Tensor Dtype | Npu Tensor Shape | Bench Tensor Shape | Cosine | RMSE | MAPE |
|
||||
| :---: | :--------------: | :----------------: | :--------------: | :----------------: | :----: | :---: | :---: |
|
||||
|
||||
其中主要使用算子Name、Dtype、Shape用于描述算子的基本特征,Cosine(余弦相似)、RMSE(均方根误差)、MAPE(绝对百分比误差)作为评价计算精度的主要评估指标:
|
||||
|
||||
1. 余弦相似度(通过计算两个向量的余弦值来判断其相似度):
|
||||
|
||||
$$
|
||||
\Large
|
||||
cos(\theta) = \frac{\sum_{i=1}^{n} (\hat{y_{i}} \times y_{i})}
|
||||
{\sqrt{\sum_{i=1}^{n}\hat{y_{i}}} \times \sqrt{\sum_{i=1}^{n}y_{i}^{2}}}
|
||||
$$
|
||||
当余弦夹角数值越接近于1说明计算出的两个张量越相似
|
||||
|
||||
2. 均方根误差(RMSE):
|
||||
|
||||
$$
|
||||
\Large
|
||||
RMSE = \sqrt{\frac{1}{n} \sum_{i=1}^{n} (\hat{y_{i}} - y_{i})^{2}}
|
||||
$$
|
||||
当均方根误差越接近0表示其计算的平均误差越小
|
||||
|
||||
3. 平均绝对百分比误差(MAPE):
|
||||
|
||||
$$
|
||||
\Large
|
||||
MAPE = \frac{1}{n} \sum_{i=1}^{n}|\frac{\hat{y_{i}} - y_{i}}{y_{i}}|
|
||||
$$
|
||||
绝对百分比误差衡量计算误差的百分比,越接近0越好,但当其中的实际计算结果中存在0时是无法进行计算的
|
||||
|
||||
## **快速上手样例参考**
|
||||
|
||||
使用精度比对工具进行模型的精度比对,样例代码如下:
|
||||
|
||||
```python
|
||||
# 根据需要import包
|
||||
import os
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from torch_npu.hooks import set_dump_path, seed_all, register_acc_cmp_hook
|
||||
from torch_npu.hooks.tools import compare
|
||||
|
||||
|
||||
# 定义一个简单的网络
|
||||
class ModuleOP(nn.Module):
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.linear_1 = nn.Linear(in_features=2, out_features=2)
|
||||
self.linear_2 = nn.Linear(in_features=2, out_features=1)
|
||||
self.relu = nn.ReLU()
|
||||
|
||||
def forward(self, x):
|
||||
x1 = self.linear_1(x)
|
||||
x2 = self.linear_2(x1)
|
||||
r1 = self.relu(x2)
|
||||
return r1
|
||||
|
||||
|
||||
# 对该网络进行hook注入和数据dump
|
||||
module = ModuleOp()
|
||||
register_acc_cmp_hook(module) # 对模型注入forwar和backward的hooks
|
||||
seed_all()
|
||||
x = torch.randn(2, 2)
|
||||
|
||||
# cpu上计算,dump数据
|
||||
set_dump_path("./cpu_module_op.pkl")
|
||||
out = module(x)
|
||||
loss = out.sum()
|
||||
loss.backward()
|
||||
set_dump_path("./npu_mpdule_op.pkl")
|
||||
|
||||
# npu上计算,dump数据
|
||||
module.npu()
|
||||
x = x.npu()
|
||||
out = module(x)
|
||||
loss = out.sum()
|
||||
loss.backward()
|
||||
|
||||
# 对比dump出的数据精度,生成csv文件
|
||||
compare("./npu_module_op.pkl", "./cpu_module_op.pkl", "./module_result.csv")
|
||||
|
||||
```
|
||||
|
||||
|
||||
使用精度比对工具进行torchvision下现有模型的计算精度比对,整体思路相同,以resnet50模型为例代码如下:
|
||||
```python
|
||||
import os
|
||||
import copy
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torchvision import models, datasets, transforms
|
||||
|
||||
from torch_npu.hooks import set_dump_path, seed_all, register_acc_cmp_hook
|
||||
from torch_npu.hooks.tools import compare
|
||||
|
||||
|
||||
# 选取需要的模型
|
||||
model_cpu = models.resnet50()
|
||||
model_cpu.eval()
|
||||
model_npu = copy.deepcopy(model_cpu)
|
||||
model_npu.eval()
|
||||
|
||||
# 对该计算进行hook注入和数据dump
|
||||
register_acc_cmp_hook(model_cpu)
|
||||
register_acc_cmp_hook(model_npu)
|
||||
seed_all()
|
||||
|
||||
# 需要根据不同的模型输入和标签生成相应的tensor(或读取实际数据),损失函数等
|
||||
inputs = torch.randn(1, 3, 244, 244)
|
||||
labels = torch.randn(1).long()
|
||||
criterion = nn.CrossEntropyLoss()
|
||||
|
||||
# cpu
|
||||
set_dump_path("./cpu_resnet50_op.pkl")
|
||||
output = model_cpu(inputs)
|
||||
loss = criterion(output, labels)
|
||||
loss.backward()
|
||||
|
||||
# npu
|
||||
set_dump_path("./npu_resnet50_op.pkl")
|
||||
model_npu.npu()
|
||||
inputs = inputs.npu()
|
||||
labels = labels.npu()
|
||||
output = model_npu(inputs)
|
||||
loss = criterion(output, labels)
|
||||
loss.backward()
|
||||
|
||||
# 对比dump出的数据精度,生成csv文件
|
||||
compare("./npu_resnet50_op.pkl", "./cpu_resnet50_op.pkl", "./resnet50_result.csv")
|
||||
```
|
||||
|
||||
|
Before Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 8.0 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 126 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 607 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 7.8 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 126 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 72 KiB After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 55 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
|
After Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 121 KiB After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 82 KiB |