Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61a88f2d9c | ||
|
|
29cf9f9731 | ||
|
|
5fa74ae2bf | ||
|
|
6853bea62c | ||
|
|
bf2e368e9e | ||
|
|
97408652d2 | ||
|
|
e46d1d858a | ||
|
|
136f595bff | ||
|
|
ad98a6df3d | ||
|
|
84eafd7023 | ||
|
|
7e588d48be | ||
|
|
67fadc1559 | ||
|
|
c489360227 | ||
|
|
1bd634c092 | ||
|
|
f030743edf | ||
|
|
ccb53d7c16 | ||
|
|
120b602ba8 | ||
|
|
18682df054 | ||
|
|
03683b4d47 | ||
|
|
6b9284c55e | ||
|
|
139aebde18 | ||
|
|
7e19fd8b91 | ||
|
|
323dd633d1 | ||
|
|
f7d8433f33 | ||
|
|
c1e9625f89 | ||
|
|
d974ab78de | ||
|
|
8a717bf965 | ||
|
|
c5df068ed0 | ||
|
|
77fcfabe1e | ||
|
|
fd1b0557a3 | ||
|
|
65fe503c24 | ||
|
|
34404edd2e | ||
|
|
26797f41a8 | ||
|
|
0d0dcff1ab | ||
|
|
f2b3dbb536 | ||
|
|
a3e9149254 | ||
|
|
ba24f74264 | ||
|
|
4d84ffa349 | ||
|
|
13d6d9d3fb | ||
|
|
d9f6c20251 | ||
|
|
793cfa0051 | ||
|
|
cc6eea5c82 | ||
|
|
b0ac9888a7 | ||
|
|
cb4e26deeb | ||
|
|
926d82e7af | ||
|
|
8c2ff96724 | ||
|
|
a9c484f1b1 | ||
|
|
653b277b36 | ||
|
|
7de0f7c5e2 | ||
|
|
b23060a9f4 | ||
|
|
ee173a114a | ||
|
|
1a5da3ea49 | ||
|
|
1be5186e1c | ||
|
|
8fea6aa4e4 | ||
|
|
2b87ec310b | ||
|
|
975c77d466 | ||
|
|
0ebb907c62 | ||
|
|
ebbd7f4278 | ||
|
|
5d65ce5d0e | ||
|
|
bafb482c30 | ||
|
|
68b58e7b99 | ||
|
|
6f180ff325 | ||
|
|
5039749a1a | ||
|
|
cdfe6142f4 | ||
|
|
ec2d71534b | ||
|
|
877aa41236 | ||
|
|
ee36446b85 | ||
|
|
93438b05b5 | ||
|
|
711df330a0 | ||
|
|
33d417b0c8 | ||
|
|
dc1e741543 | ||
|
|
a8f26113fe | ||
|
|
b8a9c8e502 | ||
|
|
7c60eadeef | ||
|
|
953e85bb51 | ||
|
|
1a8ac6f700 | ||
|
|
d0ce417e74 | ||
|
|
74d442d71c | ||
|
|
ec5559c8d8 | ||
|
|
118cc0ceea | ||
|
|
e7b0a9bfab | ||
|
|
78de784489 | ||
|
|
f1616ae3ea | ||
|
|
cc50209e76 | ||
|
|
28b1c31a28 | ||
|
|
08b19d4bcc | ||
|
|
d542633e9a | ||
|
|
ee19239a40 | ||
|
|
54d69a20ca | ||
|
|
339dec4ba1 | ||
|
|
98d2546ad9 | ||
|
|
67e8722811 | ||
|
|
c5efbc0e89 | ||
|
|
b776210b0b | ||
|
|
8083ce705c | ||
|
|
cb0bbee678 | ||
|
|
073554ad2d | ||
|
|
5bbf0dd4d3 | ||
|
|
d49da19ab4 | ||
|
|
023a258644 | ||
|
|
ce8cf517cf | ||
|
|
29f0e092fe | ||
|
|
a0b7b96b6a | ||
|
|
691a2b73fd | ||
|
|
356a29da7c | ||
|
|
55e34b5a63 | ||
|
|
d59451b678 | ||
|
|
1fd4234919 | ||
|
|
ec6c4f621c | ||
|
|
a1df360e92 | ||
|
|
afbcd275fc | ||
|
|
83ff2ca5a2 | ||
|
|
cd3a32e96b | ||
|
|
e6271e18af | ||
|
|
54915aaaa8 | ||
|
|
9ee8f1bc41 | ||
|
|
903e87e05f | ||
|
|
189b64ca02 | ||
|
|
c78d94a819 | ||
|
|
1d7c9c9e6b | ||
|
|
32020c4c15 | ||
|
|
c745b9b922 | ||
|
|
61927f5646 | ||
|
|
88f64d090c | ||
|
|
7630784a30 | ||
|
|
d968332a17 | ||
|
|
2e0426fa6c | ||
|
|
5766d8c37e | ||
|
|
207cbb926e | ||
|
|
80c6a58048 | ||
|
|
3ec0058635 | ||
|
|
0d86f9fae0 | ||
|
|
0ff8f74699 | ||
|
|
b3b6b7cfcc | ||
|
|
102c9e9b5d | ||
|
|
9aafa48f70 | ||
|
|
e6a9901a2c | ||
|
|
7fed3531ab | ||
|
|
f90b406b8d | ||
|
|
5beb22e635 | ||
|
|
1efba9d60f | ||
|
|
45aa5eb61f | ||
|
|
dfb70dfe63 | ||
|
|
d22e06c19c | ||
|
|
d7af7cf8e7 | ||
|
|
56ec12706b | ||
|
|
66a0eabc02 | ||
|
|
aeb50c8de3 | ||
|
|
bd7359f8db | ||
|
|
c08f59460c | ||
|
|
009f65d518 | ||
|
|
fc31aa86ca | ||
|
|
71cdfa507a | ||
|
|
4bdb45e799 | ||
|
|
39acd478a4 | ||
|
|
ea095827c4 | ||
|
|
b73b7478a2 | ||
|
|
d0dc162e94 | ||
|
|
eb2abca8c3 | ||
|
|
cb64e08167 | ||
|
|
af5a572abb | ||
|
|
720208b752 | ||
|
|
64ec395b2f | ||
|
|
17db8ee60e | ||
|
|
f511e5f780 | ||
|
|
48cc081d4d | ||
|
|
3d690ae125 | ||
|
|
41ab954562 | ||
|
|
06ddf258a5 | ||
|
|
07bbcc1950 | ||
|
|
67ac790bfb | ||
|
|
d823a6f633 | ||
|
|
950bf73356 | ||
|
|
5617b3aba2 | ||
|
|
76995073ef | ||
|
|
bc058f71d8 | ||
|
|
48dc033838 | ||
|
|
875b7eaa92 | ||
|
|
585d6f9738 | ||
|
|
68ce64599e | ||
|
|
a893e8c936 | ||
|
|
dbe1463001 | ||
|
|
2781cdcf25 | ||
|
|
2f8e9370e6 | ||
|
|
c1ecb3943f | ||
|
|
f6d2654ffb | ||
|
|
409f00c0b5 | ||
|
|
2d7ed1b445 | ||
|
|
93ee72eaa9 | ||
|
|
631bf8969b | ||
|
|
f40aa576eb | ||
|
|
bc3b0f6670 | ||
|
|
9415c1dcf5 | ||
|
|
8958aa5b81 | ||
|
|
a2fd07f92a | ||
|
|
f2613f58e8 | ||
|
|
e8da7eec6f | ||
|
|
156fec16de | ||
|
|
d46d13162a | ||
|
|
226254c107 | ||
|
|
1cfb73709b | ||
|
|
177dfbdab2 | ||
|
|
7b7f9e1ca6 | ||
|
|
087d93b0fd | ||
|
|
30d6c720d3 | ||
|
|
48d7320ba7 | ||
|
|
7245355c0e | ||
|
|
a6f28107cc | ||
|
|
2ba6708135 | ||
|
|
3d636ec2bc | ||
|
|
6bd29a2bc5 | ||
|
|
6cce587de3 | ||
|
|
17135c3bbc | ||
|
|
4b6fcc67b3 | ||
|
|
e3ab8ba3c2 | ||
|
|
c909295e5c | ||
|
|
068e2d53ed | ||
|
|
fa50733e19 | ||
|
|
f10429494c | ||
|
|
66b8848bf2 | ||
|
|
01fe2cd138 | ||
|
|
cedde8a215 | ||
|
|
95f40a18f2 | ||
|
|
0968bc3e1d | ||
|
|
a258b284a5 | ||
|
|
bc20a15bd3 | ||
|
|
961b8d9425 | ||
|
|
dd90ae9230 | ||
|
|
7a2f796020 | ||
|
|
9e9cc9fd8d | ||
|
|
6edc2cf973 | ||
|
|
52dae67830 | ||
|
|
83649ad545 | ||
|
|
9b51e8d77f | ||
|
|
09a24d592e | ||
|
|
1da5004433 | ||
|
|
2b083bbf82 | ||
|
|
f758f47678 | ||
|
|
d045333ff1 | ||
|
|
fb14e43a30 | ||
|
|
b3a3d7d415 | ||
|
|
876cf6238e | ||
|
|
d207a5b26a | ||
|
|
f444acf8b0 | ||
|
|
9d15c4561c | ||
|
|
ff81613a74 | ||
|
|
6fe1803baa | ||
|
|
091eee882f | ||
|
|
330c191227 | ||
|
|
df5b8d32c1 | ||
|
|
74b850aba2 | ||
|
|
9bf987e171 | ||
|
|
711c8bd404 | ||
|
|
b98710bbcf | ||
|
|
21b5f2cff1 | ||
|
|
0f837d6e55 | ||
|
|
4b66ee744e | ||
|
|
48e2562807 | ||
|
|
58aba4a39d | ||
|
|
f7e0a56db8 | ||
|
|
b79b6666e2 | ||
|
|
906460c323 | ||
|
|
d019e71aaf | ||
|
|
827160731b | ||
|
|
a21569f658 | ||
|
|
f830fc680b | ||
|
|
b264619b87 | ||
|
|
85d33a150a | ||
|
|
bab025553e | ||
|
|
5450f86271 | ||
|
|
5068f89805 | ||
|
|
561a19dd1d | ||
|
|
21415a613a | ||
|
|
756ab48356 | ||
|
|
bdc135936b | ||
|
|
25aa5e28af | ||
|
|
f2a393e7ed | ||
|
|
04b70e70a3 | ||
|
|
359a5a8a20 | ||
|
|
7686ec2f33 | ||
|
|
da2a51c833 | ||
|
|
f102c343b6 | ||
|
|
d197f6d249 | ||
|
|
b38cf3b172 | ||
|
|
2148cb28d3 | ||
|
|
b081ddfc8b | ||
|
|
0800d3a5d9 | ||
|
|
dec4263ecd | ||
|
|
30f96b53c0 | ||
|
|
cba8c77812 | ||
|
|
080316b457 | ||
|
|
c8d951553b | ||
|
|
3ff156d300 | ||
|
|
b1ca653ba2 | ||
|
|
fa900c0525 | ||
|
|
dd5c25aaf5 | ||
|
|
b8093c410e | ||
|
|
641ace894a | ||
|
|
a5b628e4e0 | ||
|
|
2dcb73ad27 | ||
|
|
e489caa877 | ||
|
|
5327ca8b38 | ||
|
|
920f00ddff | ||
|
|
ae42d2cd5d | ||
|
|
a863ac8674 | ||
|
|
8ab3983917 | ||
|
|
7c0a68670d | ||
|
|
fce48cc674 | ||
|
|
35390757ad | ||
|
|
cd4d58d1a1 | ||
|
|
8107a527d1 | ||
|
|
ddda05b1b4 | ||
|
|
7cfc9a4cf6 | ||
|
|
81451d727c | ||
|
|
52790f0c60 | ||
|
|
e7b584e574 | ||
|
|
35d70249e5 | ||
|
|
6bcbba14df | ||
|
|
104170bf29 | ||
|
|
fd9cb4c8b1 | ||
|
|
e1228d0d4c | ||
|
|
cce09a2b2a | ||
|
|
13f0520808 | ||
|
|
93a5ac327c | ||
|
|
32e66d08fc | ||
|
|
e2c213d3d5 | ||
|
|
7a3d4c895b | ||
|
|
7befd2158e | ||
|
|
e01d923111 | ||
|
|
d71fe03d67 | ||
|
|
2974d71e48 | ||
|
|
f5bb61eaff | ||
|
|
978dd0324e | ||
|
|
1231d057cc | ||
|
|
e672154215 | ||
|
|
f8661b84df | ||
|
|
c7e3d7db8c | ||
|
|
25fb08a037 | ||
|
|
4d4c86e4fc | ||
|
|
d9b18855e9 | ||
|
|
b0601ff8e6 | ||
|
|
ad163a3120 | ||
|
|
e2fdd668ee | ||
|
|
3aa1549def | ||
|
|
03f752fa58 | ||
|
|
5de17d8416 | ||
|
|
0ffe4f56a8 | ||
|
|
7ee6ef246f | ||
|
|
12816facc1 | ||
|
|
d5a12c14fd | ||
|
|
d0a96f0629 | ||
|
|
583bb87fba | ||
|
|
e2fe0753e8 | ||
|
|
88a88f5519 | ||
|
|
d5109355cc | ||
|
|
9cc8ddb24c | ||
|
|
b6ac1263b3 | ||
|
|
6663f93b41 | ||
|
|
aa8e2dc3e2 | ||
|
|
ebba6c7a5c | ||
|
|
ac7df74e40 | ||
|
|
e1c945930a | ||
|
|
b6abad5e57 | ||
|
|
6eb4723c8a |
@@ -193,3 +193,11 @@ TAGS
|
||||
|
||||
# bazel symlinks
|
||||
bazel-*
|
||||
|
||||
# Generated files
|
||||
torch_npu/version.py
|
||||
torch_npu/csrc/aten/NPUNativeFunctions.h
|
||||
torch_npu/csrc/aten/RegisterAutogradNPU.cpp
|
||||
torch_npu/csrc/aten/RegisterCPU.cpp
|
||||
torch_npu/csrc/aten/RegisterNPU.cpp
|
||||
torch_npu/csrc/aten/python_custom_functions.cpp
|
||||
|
||||
@@ -7,6 +7,10 @@ set(CMAKE_INSTALL_MESSAGE NEVER)
|
||||
# set(CMAKE_VERBOSE_MAKEFILE ON)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
if(DEFINED TORCH_VERSION)
|
||||
add_definitions(-DPYTORCH_NPU_VERSION="${TORCH_VERSION}")
|
||||
endif()
|
||||
|
||||
set(PLUGIN_NAME torch_npu)
|
||||
|
||||
set(RPATH_VALUE $ORIGIN)
|
||||
@@ -178,6 +182,9 @@ if (NOT DEFINED BUILD_LIBTORCH)
|
||||
set(UTILS_SRCS)
|
||||
endif()
|
||||
|
||||
if (DEFINED BUILD_LIBTORCH)
|
||||
set(NPU_CPP_LIBS_SRCS)
|
||||
endif()
|
||||
|
||||
add_subdirectory(${TORCHNPU_ROOT}/aten)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/core)
|
||||
@@ -191,7 +198,11 @@ if (NOT DEFINED BUILD_LIBTORCH)
|
||||
endif()
|
||||
|
||||
if (DEFINED BUILD_LIBTORCH)
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${FRAMEWORK_SRCS})
|
||||
add_subdirectory(${TORCHNPU_ROOT}/libs)
|
||||
endif()
|
||||
|
||||
if (DEFINED BUILD_LIBTORCH)
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${FRAMEWORK_SRCS} ${NPU_CPP_LIBS_SRCS})
|
||||
else()
|
||||
# Compile code with pybind11
|
||||
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${DIST_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${UTILS_SRCS})
|
||||
@@ -242,3 +253,8 @@ if (NOT DEFINED BUILD_LIBTORCH)
|
||||
target_compile_options(${PLUGIN_NAME} PRIVATE "-DC10_BUILD_MAIN_LIB")
|
||||
install(TARGETS ${PLUGIN_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
|
||||
endif()
|
||||
|
||||
if (NOT DEFINED BUILD_LIBTORCH)
|
||||
add_subdirectory(${TORCHNPU_ROOT}/toolkit)
|
||||
target_link_libraries(${PLUGIN_NAME} PUBLIC npu_profiler)
|
||||
endif()
|
||||
|
||||
@@ -3,23 +3,20 @@ approvers:
|
||||
- weili10
|
||||
- you-ansheng
|
||||
- yskhhh
|
||||
- clinglai
|
||||
- lvpeiyuan
|
||||
- xiepeng20
|
||||
- xiong05
|
||||
- guang-jun-zhang2
|
||||
reviewers:
|
||||
- shibo19
|
||||
- Ronnie_zheng
|
||||
- xiaxia3
|
||||
- petissue
|
||||
- td__lihan
|
||||
- ascendzyj
|
||||
- wudingyuan
|
||||
- yskhhh
|
||||
- matrixplayer
|
||||
- li_jing_hw
|
||||
- wangjiangben_hw
|
||||
- qingfenxiaochong
|
||||
- goodjobwubai
|
||||
- fairwarning
|
||||
- you-ansheng
|
||||
- yinzijun
|
||||
- weili10
|
||||
- granpad7
|
||||
- clinglai
|
||||
@@ -31,4 +28,26 @@ reviewers:
|
||||
- brightlyking
|
||||
- chenhao_1209
|
||||
- wbigat
|
||||
- will-devil
|
||||
- will-devil
|
||||
- ckirchhoff
|
||||
- liu-tianlong
|
||||
- jayshu
|
||||
- lvpeiyuan
|
||||
- luyoubing
|
||||
- dai-yuwen
|
||||
- jia8liang
|
||||
- w_a_n_g_q_i
|
||||
- simonzhouchun
|
||||
- luo-hui46
|
||||
- yang-renfeihuawei
|
||||
- y00580292
|
||||
- AllenYaWang
|
||||
- lidezhao1
|
||||
- ma-dongfang
|
||||
- wangchao285
|
||||
- dilililiwhy
|
||||
- sunjiayang
|
||||
- huangyunlong2022
|
||||
- misty-rain-typhoid
|
||||
- du-jin-hang
|
||||
- xqiangx1991
|
||||
@@ -44,7 +44,42 @@
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody><tr id="row1452975217222"><td class="cellrowborder" rowspan="3" valign="top" width="18.16%" headers="mcps1.2.6.1.1 "><p id="p1849173117229"><a name="p1849173117229"></a><a name="p1849173117229"></a>3.0.0</p>
|
||||
<tbody><tr id="row1452975217222"><td class="cellrowborder" rowspan="2" valign="top" width="18.16%" headers="mcps1.2.6.1.1 "><p id="p1849173117229"><a name="p1849173117229"></a><a name="p1849173117229"></a>5.0.RC1</p>
|
||||
</td>
|
||||
<td class="cellrowborder" rowspan="2" valign="top" width="15.78%" headers="mcps1.2.6.1.2 "><p id="p13849183142218"><a name="p13849183142218"></a><a name="p13849183142218"></a>CANN 6.3.RC1</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="17.080000000000002%" headers="mcps1.2.6.1.3 "><p id="p197571831182710"><a name="p197571831182710"></a><a name="p197571831182710"></a>1.8.1.post1</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="17.05%" headers="mcps1.2.6.1.4 "><p id="p18655452182620"><a name="p18655452182620"></a><a name="p18655452182620"></a>v1.8.1-5.0.rc1</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="31.929999999999996%" headers="mcps1.2.6.1.5 "><p id="p2087128165411"><a name="p2087128165411"></a><a name="p2087128165411"></a>-</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row16995654102215"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p48506347263"><a name="p48506347263"></a><a name="p48506347263"></a>1.11.0</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p10655452142612"><a name="p10655452142612"></a><a name="p10655452142612"></a>v1.11.0-5.0.rc1</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p2087118825410"><a name="p2087118825410"></a><a name="p2087118825410"></a>-</p>
|
||||
</td>
|
||||
<tr id="row1452975217222"><td class="cellrowborder" rowspan="2" valign="top" width="18.16%" headers="mcps1.2.6.1.1 "><p id="p1849173117229"><a name="p1849173117229"></a><a name="p1849173117229"></a>5.0.RC1(适用于昇腾910B处理器)</p>
|
||||
</td>
|
||||
<td class="cellrowborder" rowspan="2" valign="top" width="15.78%" headers="mcps1.2.6.1.2 "><p id="p13849183142218"><a name="p13849183142218"></a><a name="p13849183142218"></a>CANN 6.1.RC1</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="17.080000000000002%" headers="mcps1.2.6.1.3 "><p id="p197571831182710"><a name="p197571831182710"></a><a name="p197571831182710"></a>1.8.1.post1</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="17.05%" headers="mcps1.2.6.1.4 "><p id="p18655452182620"><a name="p18655452182620"></a><a name="p18655452182620"></a>v1.8.1-5.0.rc1</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="31.929999999999996%" headers="mcps1.2.6.1.5 "><p id="p2087128165411"><a name="p2087128165411"></a><a name="p2087128165411"></a>-</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row16995654102215"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p48506347263"><a name="p48506347263"></a><a name="p48506347263"></a>1.11.0</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p10655452142612"><a name="p10655452142612"></a><a name="p10655452142612"></a>v1.11.0-5.0.rc1</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p2087118825410"><a name="p2087118825410"></a><a name="p2087118825410"></a>-</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row1452975217222"><td class="cellrowborder" rowspan="3" valign="top" width="18.16%" headers="mcps1.2.6.1.1 "><p id="p1849173117229"><a name="p1849173117229"></a><a name="p1849173117229"></a>3.0.0</p>
|
||||
</td>
|
||||
<td class="cellrowborder" rowspan="3" valign="top" width="15.78%" headers="mcps1.2.6.1.2 "><p id="p13849183142218"><a name="p13849183142218"></a><a name="p13849183142218"></a>CANN 6.0.1</p>
|
||||
</td>
|
||||
@@ -212,21 +247,21 @@ pip3 install wheel
|
||||
|
||||
```
|
||||
# 若用户在x86架构下安装插件,请将命令中文件包名中的“aarch64”改为“x86_64”。
|
||||
wget https://gitee.com/ascend/pytorch/releases/download/v3.0.0-pytorch1.11.0/torch_npu-1.11.0rc2-cp37-cp37m-linux_aarch64.whl
|
||||
wget https://gitee.com/ascend/pytorch/releases/download/v5.0.rc1-pytorch1.11.0/torch_npu-1.11.0-cp37-cp37m-linux_aarch64.whl
|
||||
```
|
||||
|
||||
2. 执行如下命令安装。如果使用非root用户安装,需要在命令后加**--user。**
|
||||
|
||||
```
|
||||
# 若用户在x86架构下安装插件,请将命令中文件包名中的“aarch64”改为“x86_64”。
|
||||
pip3 install torch_npu-1.11.0rc2-cp37-cp37m-linux_aarch64.whl
|
||||
pip3 install torch_npu-1.11.0-cp37-cp37m-linux_aarch64.whl
|
||||
```
|
||||
|
||||
3. 安装对应框架版本的torchvision。
|
||||
|
||||
```
|
||||
#PyTorch 1.11.0需安装0.12.0版本
|
||||
pip3 install torchvision==0.9.1
|
||||
pip3 install torchvision==0.12.0
|
||||
```
|
||||
|
||||
**安装APEX混合精度模块<a name="section154215015416"></a>**
|
||||
@@ -257,11 +292,12 @@ Ascend PyTorch的版本分支有以下几种维护阶段:
|
||||
| ------------ | ------------ | ------------ | -------------------------------------- | ------------ |
|
||||
| **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 | |
|
||||
| **v2.0.4** | EOL | 2022-01-15 | N/A | |
|
||||
| **v3.0.rc1** | UnMaintained | 2022-04-10 | EOL <br> 2023-07-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 | |
|
||||
| **v5.0.rc1** | Maintained | 2023-4-19 | Unmaintained <br/> 2024-4-19 estimated | |
|
||||
|
||||
# FAQ
|
||||
|
||||
@@ -348,8 +384,8 @@ Debian、UOS20、UOS20 SP1、Linx系统可参考Ubuntu进行安装。
|
||||
1. 编译生成PyTorch插件的二进制安装包。
|
||||
|
||||
```
|
||||
# 下载对应PyTorch版本分支代码,进入插件根目录,以v1.11.0-3.0.0为例
|
||||
git clone -b v1.11.0-3.0.0 https://gitee.com/ascend/pytorch.git
|
||||
# 下载对应PyTorch版本分支代码,进入插件根目录,以v1.11.0为例
|
||||
git clone -b v1.11.0 https://gitee.com/ascend/pytorch.git
|
||||
cd pytorch
|
||||
# 指定Python版本编包方式,以Python3.7为例,其他Python版本请使用 --python=3.8或--python3.9
|
||||
bash ci/build.sh --python=3.7
|
||||
@@ -366,7 +402,7 @@ Debian、UOS20、UOS20 SP1、Linx系统可参考Ubuntu进行安装。
|
||||
|
||||
```
|
||||
#PyTorch 1.11.0需安装0.12.0版本
|
||||
pip3 install torchvision==0.9.1
|
||||
pip3 install torchvision==0.12.0
|
||||
```
|
||||
|
||||
4. 配置环境变量,验证是否安装成功。
|
||||
@@ -414,9 +450,6 @@ pip3 install typing_extensions
|
||||
|
||||
```
|
||||
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 #{arch}为架构名称
|
||||
|
||||
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
|
||||
|
||||
pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
```
|
||||
|
||||
@@ -424,9 +457,6 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
|
||||
```
|
||||
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 #{arch}为架构名称
|
||||
|
||||
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
|
||||
|
||||
pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
```
|
||||
|
||||
|
||||
@@ -120,7 +120,7 @@ def clean_generated_files():
|
||||
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']
|
||||
'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))
|
||||
@@ -163,6 +163,14 @@ def copy_file(infile, outfile, preserve_mode=1, preserve_times=1, link=None, lev
|
||||
"""
|
||||
return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, True, link)
|
||||
|
||||
def move_special_hpp(ret):
|
||||
hpp_name = "library_npu.h"
|
||||
for _, dst in ret:
|
||||
if dst.endswith(hpp_name):
|
||||
dir_name = os.path.join(os.path.dirname(dst), "../../" + hpp_name)
|
||||
copy_file(dst, dir_name)
|
||||
return
|
||||
|
||||
|
||||
def copy_hpp():
|
||||
def get_src_py_and_dst():
|
||||
@@ -174,6 +182,7 @@ def copy_hpp():
|
||||
"torch_npu/csrc/aten/*/*/*.h",
|
||||
"torch_npu/csrc/core/*.h",
|
||||
"torch_npu/csrc/core/*/*.h",
|
||||
"torch_npu/csrc/libs/*.h",
|
||||
"torch_npu/csrc/core/*/*/*.h",
|
||||
"torch_npu/csrc/framework/*.h",
|
||||
"torch_npu/csrc/framework/*/*.h",
|
||||
@@ -187,7 +196,7 @@ def copy_hpp():
|
||||
|
||||
for src in glob_header_files:
|
||||
dst = os.path.join(
|
||||
os.path.join(BASE_DIR, f"libtorch/include/torch_npu"),
|
||||
os.path.join(BASE_DIR, "libtorch_npu/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))
|
||||
@@ -196,7 +205,7 @@ def copy_hpp():
|
||||
ret = get_src_py_and_dst()
|
||||
for src, dst in ret:
|
||||
copy_file(src, dst)
|
||||
|
||||
move_special_hpp(ret)
|
||||
|
||||
def copy_lib():
|
||||
lib_file = [f"build/{get_build_type()}/packages/torch_npu/lib/*.*"]
|
||||
@@ -204,7 +213,7 @@ def copy_lib():
|
||||
|
||||
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")
|
||||
dst_path = os.path.join(BASE_DIR, "libtorch_npu/lib")
|
||||
os.makedirs(dst_path, exist_ok=True)
|
||||
|
||||
for src in glob_lib_files:
|
||||
|
||||
@@ -19,10 +19,11 @@ import re
|
||||
import sys
|
||||
import subprocess
|
||||
from abc import ABCMeta, abstractmethod
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
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_DIR = os.path.join(BASE_DIR, 'test')
|
||||
TEST_OPS = os.path.join(BASE_DIR, 'test/test_ops.py')
|
||||
|
||||
|
||||
@@ -75,8 +76,9 @@ class DirectoryStrategy(AccurateTest):
|
||||
通过识别测试文件的目录确认需要进行UT的文件
|
||||
"""
|
||||
def identify(self, modify_file):
|
||||
second_dir = modify_file.split("/")[0]
|
||||
return [os.path.join(BASE_DIR, modify_file)] if second_dir == 'test' else []
|
||||
is_test_file = modify_file.split("/")[0] == "test" \
|
||||
and re.match("test_(.+).py", os.path.basename(modify_file))
|
||||
return [os.path.join(BASE_DIR, modify_file)] if is_test_file else []
|
||||
|
||||
|
||||
class CopyOptStrategy(AccurateTest):
|
||||
@@ -89,6 +91,43 @@ class CopyOptStrategy(AccurateTest):
|
||||
return AccurateTest.find_ut_by_regex(regex)
|
||||
return []
|
||||
|
||||
class DirectoryMappingStrategy(AccurateTest):
|
||||
"""
|
||||
Map the modified files to the corresponding test cases
|
||||
"""
|
||||
mapping_list = {
|
||||
'contrib': 'test/test_contrib',
|
||||
'cpp_extension': 'test/test_cpp_extension',
|
||||
'distributed': 'test/test_distributed',
|
||||
'fx': 'test/test_fx',
|
||||
'hooks': 'test/test_hooks',
|
||||
'optim': 'test/test_optim',
|
||||
'profiler': 'test/test_profiler',
|
||||
'onnx': 'test/test_onnx',
|
||||
'utils': 'test/test_utils',
|
||||
'testing': 'test/test_testing.py',
|
||||
}
|
||||
|
||||
def identify(self, modify_file):
|
||||
current_all_ut_path = []
|
||||
if str(Path(modify_file).parts[0]) == 'torch_npu':
|
||||
CORE_TEST_LIST = [str(i) for i in (Path(BASE_DIR) / 'test/test_npu').rglob('test_*.py')]
|
||||
current_all_ut_path = CORE_TEST_LIST
|
||||
|
||||
mapped_ut_path = []
|
||||
module_name = str(Path(modify_file).parts[1])
|
||||
if module_name in self.mapping_list:
|
||||
mapped_ut_path.append(self.mapping_list[module_name])
|
||||
file_name = str(Path(modify_file).stem)
|
||||
if file_name in self.mapping_list:
|
||||
mapped_ut_path.append(self.mapping_list[file_name])
|
||||
|
||||
for mapped_path in mapped_ut_path:
|
||||
if Path.is_file(Path(BASE_DIR) / mapped_path):
|
||||
current_all_ut_path.append(str(Path(BASE_DIR) / mapped_path))
|
||||
else:
|
||||
current_all_ut_path += [str(i) for i in (Path(BASE_DIR) / mapped_path).rglob('test_*.py')]
|
||||
return current_all_ut_path
|
||||
|
||||
class TestMgr():
|
||||
def __init__(self):
|
||||
@@ -106,10 +145,11 @@ class TestMgr():
|
||||
|
||||
def analyze(self):
|
||||
for modify_file in self.modify_files:
|
||||
self.test_files['ut_files'] += DirectoryStrategy().identify(modify_file)
|
||||
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)
|
||||
self.test_files['ut_files'] += DirectoryMappingStrategy().identify(modify_file)
|
||||
unique_files = set(self.test_files['ut_files'])
|
||||
|
||||
exist_ut_file = [
|
||||
@@ -118,7 +158,6 @@ class TestMgr():
|
||||
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_test_files(self):
|
||||
return self.test_files
|
||||
@@ -143,20 +182,21 @@ def exec_ut(files):
|
||||
"""
|
||||
执行单元测试文件,其中存在失败,则标识异常并打印相关信息
|
||||
"""
|
||||
def get_ut_name(ut_file):
|
||||
def get_op_name(ut_file):
|
||||
return ut_file.split('/')[-1].split('.')[0].lstrip('test_')
|
||||
|
||||
def get_ut_name(ut_file):
|
||||
return os.path.relpath(ut_file, TEST_DIR)[:-3]
|
||||
|
||||
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}'
|
||||
def get_ut_cmd(ut_type, ut_file):
|
||||
cmd = [sys.executable, "run_test.py", "-v", "-i"]
|
||||
if ut_type == "op_ut_files":
|
||||
return cmd + ["test_ops", "--", "-k", get_op_name(ut_file)]
|
||||
return cmd + [get_ut_name(ut_file)]
|
||||
|
||||
os.chdir(ut_dir)
|
||||
p = subprocess.Popen(cmd.split(' '), stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
|
||||
def run_cmd_with_timeout(cmd):
|
||||
os.chdir(TEST_DIR)
|
||||
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
|
||||
|
||||
try:
|
||||
msg = p.communicate(timeout=2000)
|
||||
@@ -175,28 +215,22 @@ def exec_ut(files):
|
||||
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)
|
||||
def run_tests(files):
|
||||
exec_infos = []
|
||||
has_failed = 0
|
||||
for ut_type, ut_files in files.items():
|
||||
for ut_file in ut_files:
|
||||
cmd = get_ut_cmd(ut_type, ut_file)
|
||||
ut_info = " ".join(cmd[4:]).replace(" -- -k", "")
|
||||
ret = run_cmd_with_timeout(cmd)
|
||||
if ret:
|
||||
has_failed = ret
|
||||
exec_infos.append("exec ut {} failed.".format(ut_info))
|
||||
else:
|
||||
exec_infos.append("exec ut {} success.".format(ut_info))
|
||||
return has_failed, exec_infos
|
||||
|
||||
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))
|
||||
ret_status, exec_infos = run_tests(files)
|
||||
|
||||
print("***** Total result:")
|
||||
for exec_info in exec_infos:
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 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.
|
||||
|
||||
CUR_DIR=$(dirname $(readlink -f $0))
|
||||
|
||||
cd ${CUR_DIR}/../examples/libtorch_resnet
|
||||
|
||||
if [ -f ./resnet_model.pt ]; then
|
||||
rm ./resnet_model.pt
|
||||
fi
|
||||
|
||||
python3 resnet_trace.py
|
||||
|
||||
if [ $? != 0 ]; then
|
||||
echo "Failed to trace resnet model."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -d "build" ]; then
|
||||
rm -rf ./build
|
||||
fi
|
||||
|
||||
mkdir build && cd build && \
|
||||
cmake -DCMAKE_PREFIX_PATH=`python3 -c 'import torch;print(torch.utils.cmake_prefix_path)'` .. && \
|
||||
make && ./libtorch_resnet ../resnet_model.pt
|
||||
@@ -23,6 +23,7 @@ from codegen.api import cpp
|
||||
from codegen.model import (Argument, BaseTy, BaseType, ListType,
|
||||
NativeFunction, OptionalType, Return, Type,
|
||||
Variant)
|
||||
from codegen.autograd.utils import type_wrapper_name
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
|
||||
#
|
||||
@@ -992,13 +993,20 @@ def cpp_record_func(f: NativeFunction, custom=False) -> str:
|
||||
return record_func
|
||||
raise RuntimeError(f'could not dispatch, neither function nor method: {f.func}')
|
||||
|
||||
def cpp_dispatch_target(f: NativeFunction, custom=False) -> str:
|
||||
name = cpp.name(f.func)
|
||||
def cpp_dispatch_target(f: NativeFunction, custom=False, is_npu_autograd=False) -> str:
|
||||
if is_npu_autograd:
|
||||
name = type_wrapper_name(f)
|
||||
else:
|
||||
name = cpp.name(f.func)
|
||||
|
||||
if Variant.method in f.variants and not custom:
|
||||
return f'self.{name}'
|
||||
if Variant.function in f.variants:
|
||||
if custom:
|
||||
namespace = 'at_npu::native::NPUNativeFunctions'
|
||||
if is_npu_autograd:
|
||||
namespace = 'at_npu::autograd::VariableType'
|
||||
else:
|
||||
namespace = 'at_npu::native::NPUNativeFunctions'
|
||||
elif has_tensor_options(f) or f.func.name.name.base.endswith('_like'):
|
||||
namespace = 'torch'
|
||||
else:
|
||||
|
||||
@@ -49,6 +49,7 @@ intT = BaseCppType('', 'int64_t')
|
||||
doubleT = BaseCppType('', 'double')
|
||||
boolT = BaseCppType('', 'bool')
|
||||
voidT = BaseCppType('', 'void')
|
||||
longT = BaseCppType('', 'int64_t')
|
||||
stringT = BaseCppType('c10', 'string_view')
|
||||
generatorT = BaseCppType('at', 'Generator')
|
||||
scalarTypeT = BaseCppType('at', 'ScalarType')
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# Copyright (c) 2023 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.
|
||||
|
||||
import functools
|
||||
from typing import Callable
|
||||
|
||||
from codegen.api.autograd import NativeFunctionWithDifferentiabilityInfo as NFWDI
|
||||
from codegen.context import native_function_manager
|
||||
from codegen.utils import T
|
||||
|
||||
|
||||
# Like tools.api.context.with_native_function, but for
|
||||
# NativeFunctionWithDifferentiabilityInfo.
|
||||
def with_native_function_with_differentiability_info(func: Callable[[NFWDI], T]) -> Callable[[NFWDI], T]:
|
||||
@functools.wraps(func)
|
||||
def wrapper(f: NFWDI) -> T:
|
||||
with native_function_manager(f.func):
|
||||
return func(f)
|
||||
return wrapper
|
||||
@@ -0,0 +1,6 @@
|
||||
# Defines derivative formulas and Python signatures of methods on Variable
|
||||
#
|
||||
#If you need any guidance, please refer to the comments in derivatives.yaml in PyTorch.
|
||||
|
||||
- name: fast_gelu(Tensor self) -> Tensor
|
||||
self: fast_gelu_backward(grad, self)
|
||||
@@ -0,0 +1,139 @@
|
||||
# Copyright (c) 2023 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.
|
||||
|
||||
"""
|
||||
To run this file by hand from the root of the PyTorch
|
||||
repository, run:
|
||||
|
||||
python -m codegen.autograd.gen_autograd \
|
||||
--native_functions_dir="./codegen/native_functions.yaml" \
|
||||
--npu_native_function_dir="./torch_npu/csrc/aten/npu_native_functions.yaml" \
|
||||
--out_dir=$OUTPUT_DIR \
|
||||
--autograd_dir="./codegen/autograd/"
|
||||
|
||||
Where $OUTPUT_DIR is where you would like the files to be
|
||||
generated. In the full build system, OUTPUT_DIR is
|
||||
torch_npu/csrc/aten/
|
||||
"""
|
||||
|
||||
# gen_autograd.py generates C++ autograd functions and Python bindings.
|
||||
#
|
||||
# It delegates to the following scripts:
|
||||
#
|
||||
# gen_autograd_functions.py: generates subclasses of torch::autograd::Node
|
||||
# gen_variable_type.py: generates VariableType.h which contains all tensor methods
|
||||
# gen_python_functions.py: generates Python bindings to THPVariable
|
||||
#
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from typing import List, Sequence
|
||||
|
||||
from codegen.api.autograd import (
|
||||
match_differentiability_info, NativeFunctionWithDifferentiabilityInfo,
|
||||
DifferentiabilityInfo
|
||||
)
|
||||
from codegen.gen_backend_stubs import parse_native_and_custom_yaml
|
||||
from codegen.model import NativeFunction
|
||||
from .gen_autograd_functions import gen_autograd_functions_lib
|
||||
from .gen_variable_type import (
|
||||
gen_variable_type, gen_npu_variable_type,
|
||||
NPU_AUTOGRAD_FUNCTION, gen_variable_type_head
|
||||
)
|
||||
from .gen_inplace_or_view_type import gen_inplace_or_view_type
|
||||
from .gen_variable_factories import gen_variable_factories
|
||||
from .load_derivatives import load_derivatives
|
||||
|
||||
|
||||
def gen_autograd(
|
||||
native_functions_path: str,
|
||||
out: str,
|
||||
autograd_dir: str,
|
||||
npu_native_functions_path: str
|
||||
) -> None:
|
||||
differentiability_infos = load_derivatives(
|
||||
os.path.join(autograd_dir, 'derivatives.yaml'), native_functions_path, npu_native_functions_path)
|
||||
|
||||
template_path = os.path.join(autograd_dir, 'templates')
|
||||
|
||||
native_funcs = parse_native_and_custom_yaml(native_functions_path, npu_native_functions_path).native_functions
|
||||
funcs = filte_out_native_autograd_function(native_funcs, differentiability_infos)
|
||||
funcs_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo] = []
|
||||
funcs_with_diff_infos = match_differentiability_info(funcs, differentiability_infos)
|
||||
|
||||
torch_funcs_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo] = []
|
||||
npu_funcs_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo] = []
|
||||
for func in funcs_with_diff_infos:
|
||||
f = func.func
|
||||
name = str(f.func.name)
|
||||
if name in NPU_AUTOGRAD_FUNCTION:
|
||||
npu_funcs_with_diff_infos.append(func)
|
||||
else:
|
||||
torch_funcs_with_diff_infos.append(func)
|
||||
|
||||
# Generate VariableType.h/cpp
|
||||
gen_variable_type(out, torch_funcs_with_diff_infos, template_path)
|
||||
|
||||
gen_npu_variable_type(out, npu_funcs_with_diff_infos, template_path)
|
||||
|
||||
gen_variable_type_head(out, funcs_with_diff_infos, template_path)
|
||||
|
||||
gen_inplace_or_view_type(out, funcs_with_diff_infos, template_path)
|
||||
|
||||
# Generate Functions.h/cpp
|
||||
gen_autograd_functions_lib(out, differentiability_infos, template_path)
|
||||
|
||||
# Generate variable_factories.h
|
||||
gen_variable_factories(out, native_functions_path, npu_native_functions_path, template_path)
|
||||
|
||||
|
||||
def filte_out_native_autograd_function(
|
||||
native_funcs: List[NativeFunction],
|
||||
differentiability_infos: Sequence[DifferentiabilityInfo],
|
||||
):
|
||||
result: List[NativeFunction] = []
|
||||
derivatives_name_list: List[str] = []
|
||||
|
||||
for info in differentiability_infos:
|
||||
derivatives_name_list.append(str(info.func.func.name))
|
||||
for funcs in native_funcs:
|
||||
func_name = str(funcs.func.name)
|
||||
func_base_name = str(funcs.func.name.name.base)
|
||||
if (func_name in derivatives_name_list) or (func_base_name in derivatives_name_list):
|
||||
result.append(funcs)
|
||||
return result
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Generate autograd C++ files')
|
||||
parser.add_argument('--native_functions_dir', metavar='NATIVE',
|
||||
help='path to native_functions.yaml')
|
||||
parser.add_argument('--out_dir', metavar='OUT',
|
||||
help='path to output directory')
|
||||
parser.add_argument('--autograd_dir', metavar='AUTOGRAD',
|
||||
help='path to autograd directory')
|
||||
parser.add_argument('--npu_native_function_dir',
|
||||
help='path to npu_native_functions.yaml')
|
||||
args = parser.parse_args()
|
||||
gen_autograd(args.native_functions_dir,
|
||||
args.out_dir,
|
||||
args.autograd_dir,
|
||||
args.npu_native_function_dir)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,583 @@
|
||||
# Copyright (c) 2023 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.
|
||||
|
||||
# Generates C++ autograd functions for the derivatives of ATen operations
|
||||
#
|
||||
# This writes two files:
|
||||
# Functions.h/cpp: subclasses of autograd::Node
|
||||
# python_functions.h/cpp: Python bindings for the above classes
|
||||
#
|
||||
|
||||
from typing import List, Sequence, Tuple
|
||||
|
||||
from codegen.api.autograd import (
|
||||
Derivative, DifferentiabilityInfo,
|
||||
SavedAttribute, uses_retain_variables,
|
||||
uses_single_grad
|
||||
)
|
||||
from codegen.api.types import (
|
||||
Binding, BaseCType, OptionalCType, tensorT, longT,
|
||||
doubleT, scalarT, stringT, boolT, intArrayRefT,
|
||||
tensorListT, MutRefCType, ListCType, ArrayRefCType
|
||||
)
|
||||
from codegen.code_template import CodeTemplate
|
||||
from codegen.gen import FileManager
|
||||
from codegen.model import Argument
|
||||
|
||||
from .gen_inplace_or_view_type import VIEW_FUNCTIONS
|
||||
|
||||
FUNCTION_DECLARATION = CodeTemplate("""\
|
||||
struct TORCH_API ${op} : public ${superclass} {
|
||||
using ${superclass}::${superclass};
|
||||
variable_list apply(variable_list&& grads) override;
|
||||
std::string name() const override { return "${op}"; }
|
||||
void release_variables() override {
|
||||
${thread_lock}
|
||||
${release_variables}
|
||||
}
|
||||
${will_release_variables}
|
||||
${saved_variables}
|
||||
${saved_list_sizes}
|
||||
};
|
||||
""")
|
||||
|
||||
WILL_RELEASE_VARIABLES = CodeTemplate("""\
|
||||
bool retain_variables = true;
|
||||
void will_release_variables() override {
|
||||
retain_variables = false;
|
||||
}
|
||||
""")
|
||||
|
||||
FUNCTION_DEFINITION = CodeTemplate("""\
|
||||
variable_list ${op}::apply(variable_list&& grads) {
|
||||
${thread_lock}
|
||||
${asserts}
|
||||
IndexRangeGenerator gen;
|
||||
${compute_index_ranges}
|
||||
variable_list grad_inputs(gen.size());
|
||||
${body}
|
||||
return grad_inputs;
|
||||
}
|
||||
""")
|
||||
|
||||
GRAD_INPUT_MASK = CodeTemplate("""\
|
||||
auto grad_input_mask = std::array<bool, ${n}>{
|
||||
${masks}
|
||||
};\
|
||||
""")
|
||||
|
||||
DERIVATIVE_SINGLE = CodeTemplate("""\
|
||||
if (should_compute_output({ ${name}_ix })) {
|
||||
auto grad_result = ${derivative};
|
||||
copy_range(grad_inputs, ${name}_ix, grad_result);
|
||||
}
|
||||
""")
|
||||
|
||||
DERIVATIVE_MULTI_COPY_RANGE = CodeTemplate("""\
|
||||
if (should_compute_output({ ${name}_ix })) {
|
||||
copy_range(grad_inputs, ${name}_ix, std::get<${i}>(grad_result));
|
||||
}
|
||||
""")
|
||||
|
||||
DERIVATIVE_MULTI = CodeTemplate("""\
|
||||
if (should_compute_output({ ${idx_ranges} })) {
|
||||
${grad_input_mask}
|
||||
auto grad_result = ${derivative};
|
||||
${copy_ranges}
|
||||
}
|
||||
""")
|
||||
|
||||
# Generates python bindings
|
||||
#
|
||||
# This generates the definitions for:
|
||||
# (1) The PyTypeObject for each backward grad_fn subclassing Node
|
||||
# (2) The entry for PyTypeObject's tp_getset slot (an array of PyGetSetDef structs)
|
||||
# We generate one PyGetSetDef struct for each of grad_fn's saved inputs and outputs
|
||||
# Each PyGetSetDef has a function ptr to a getter, also defined here (3).
|
||||
# (3) Getters for each of grad_fn's saved inputs and outputs.
|
||||
#
|
||||
PY_FUNCTION_DEFINITION = CodeTemplate("""\
|
||||
static PyTypeObject ${op}Class;
|
||||
addClass<${op}>(${op}Class, "${op}", ${op}_properties);
|
||||
""")
|
||||
|
||||
PY_FUNCTION_PROPS_AND_GETTERS = CodeTemplate("""\
|
||||
${all_getter_definitions}
|
||||
|
||||
static struct PyGetSetDef ${op}_properties[] = {
|
||||
THP_FUNCTION_DEFAULT_PROPERTIES,
|
||||
${all_getsetdef_structs}
|
||||
{nullptr} /* sentinel */
|
||||
};
|
||||
|
||||
""")
|
||||
|
||||
PY_GETSETDEF_STRUCT = CodeTemplate("""\
|
||||
{(char*)"_saved_${name}", (getter)THP${op}_${name}_getter, nullptr, nullptr, nullptr}""")
|
||||
|
||||
PY_RAW_GETSETDEF_STRUCT = CodeTemplate("""\
|
||||
{(char*)"_raw_saved_${name}", (getter)THP${op}_${name}_raw_getter, nullptr, nullptr, nullptr}""")
|
||||
|
||||
# Getter templates
|
||||
GETTER_DEFINITION = CodeTemplate("""\
|
||||
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
|
||||
HANDLE_TH_ERRORS
|
||||
auto prop = static_cast<${op}*>(self->cdata.get())->${name};
|
||||
${body}
|
||||
END_HANDLE_TH_ERRORS
|
||||
}
|
||||
""")
|
||||
|
||||
GETTER_DEFINITION_SAVEDVAR = CodeTemplate("""\
|
||||
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
|
||||
HANDLE_TH_ERRORS
|
||||
const auto& prop = static_cast<${op}*>(self->cdata.get())->${name}_;
|
||||
${body}
|
||||
END_HANDLE_TH_ERRORS
|
||||
}
|
||||
""")
|
||||
|
||||
GETTER_DEFINITION_RAW_SAVEDVAR = CodeTemplate("""\
|
||||
PyObject* THP${op}_${name}_raw_getter(THPCppFunction *self, void *_unused) {
|
||||
HANDLE_TH_ERRORS
|
||||
const auto& prop = static_cast<${op}*>(self->cdata.get())->${name}_;
|
||||
${body}
|
||||
END_HANDLE_TH_ERRORS
|
||||
}
|
||||
""")
|
||||
|
||||
GETTER_DEFINITION_VEC_SAVEDVAR = CodeTemplate("""\
|
||||
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
|
||||
HANDLE_TH_ERRORS
|
||||
const auto *node = static_cast<${op}*>(self->cdata.get());
|
||||
const auto& prop = node->${name}_;
|
||||
if (node->${name}_released_) {
|
||||
PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE);
|
||||
return nullptr;
|
||||
}
|
||||
${body}
|
||||
END_HANDLE_TH_ERRORS
|
||||
}
|
||||
""")
|
||||
|
||||
GETTER_DEFINITION_RAW_VEC_SAVEDVAR = CodeTemplate("""\
|
||||
PyObject* THP${op}_${name}_raw_getter(THPCppFunction *self, void *_unused) {
|
||||
HANDLE_TH_ERRORS
|
||||
const auto *node = static_cast<${op}*>(self->cdata.get());
|
||||
const auto& prop = node->${name}_;
|
||||
if (node->${name}_released_) {
|
||||
PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE);
|
||||
return nullptr;
|
||||
}
|
||||
${body}
|
||||
END_HANDLE_TH_ERRORS
|
||||
}
|
||||
""")
|
||||
|
||||
GETTER_DEFINITION_OPT = CodeTemplate("""\
|
||||
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
|
||||
HANDLE_TH_ERRORS
|
||||
auto opt_prop = static_cast<${op}*>(self->cdata.get())->${name};
|
||||
if (!opt_prop.has_value()) {
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
auto prop = opt_prop.value();
|
||||
${body}
|
||||
END_HANDLE_TH_ERRORS
|
||||
}
|
||||
""")
|
||||
|
||||
GETTER_DEFINITION_OPT_ARRAYREF = CodeTemplate("""\
|
||||
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
|
||||
HANDLE_TH_ERRORS
|
||||
auto opt_prop = static_cast<${op}*>(self->cdata.get())->${name};
|
||||
if (!opt_prop.list.has_value()) {
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
auto prop = opt_prop.list.value();
|
||||
${body}
|
||||
END_HANDLE_TH_ERRORS
|
||||
}
|
||||
""")
|
||||
|
||||
# Getter body
|
||||
GETTER_BODY_SAVEDVAR = """\
|
||||
return THPVariable_Wrap(prop.unpack(self->cdata));
|
||||
"""
|
||||
|
||||
GETTER_BODY_RAW_SAVEDVAR = """\
|
||||
pybind11::object obj = pybind11::cast(prop, pybind11::return_value_policy::reference);
|
||||
return obj.release().ptr();
|
||||
"""
|
||||
|
||||
GETTER_BODY_VEC_SAVEDVAR = """\
|
||||
PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
|
||||
for (int i = 0; i < prop.size(); i++) {
|
||||
PyTuple_SetItem(tup, (Py_ssize_t) i, THPVariable_Wrap(prop[i].unpack(self->cdata)));
|
||||
}
|
||||
return tup;
|
||||
"""
|
||||
|
||||
GETTER_BODY_RAW_VEC_SAVEDVAR = """\
|
||||
PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
|
||||
for (int i = 0; i < prop.size(); i++) {
|
||||
pybind11::object obj = pybind11::cast(prop[i], pybind11::return_value_policy::reference);
|
||||
PyTuple_SetItem(tup, (Py_ssize_t) i, obj.release().ptr());
|
||||
}
|
||||
return tup;
|
||||
"""
|
||||
|
||||
GETTER_BODY_ARRAYREF_LONG = """\
|
||||
PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
|
||||
for (int i = 0; i < prop.size(); i++) {
|
||||
PyTuple_SetItem(tup, (Py_ssize_t) i, PyLong_FromUnsignedLong((uint64_t) prop[i]));
|
||||
}
|
||||
return tup;
|
||||
"""
|
||||
|
||||
GETTER_BODY_ARRAYREF_DOUBLE = """\
|
||||
PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
|
||||
for (int i = 0; i < prop.size(); i++) {
|
||||
PyTuple_SetItem(tup, (Py_ssize_t) i, PyFloat_FromDouble((double) prop[i]));
|
||||
}
|
||||
return tup;
|
||||
"""
|
||||
|
||||
GETTER_BODY_INT64_T = """\
|
||||
return PyLong_FromUnsignedLong((int64_t) prop);
|
||||
"""
|
||||
|
||||
GETTER_BODY_DOUBLE = """\
|
||||
return PyFloat_FromDouble((double) prop);
|
||||
"""
|
||||
|
||||
GETTER_BODY_BOOL = """\
|
||||
if (prop) {
|
||||
Py_RETURN_TRUE;
|
||||
} else {
|
||||
Py_RETURN_FALSE;
|
||||
}
|
||||
"""
|
||||
|
||||
GETTER_BODY_STRING = """\
|
||||
return PyUnicode_FromStringAndSize(prop.data(), prop.size());
|
||||
"""
|
||||
|
||||
GETTER_BODY_SCALAR = """\
|
||||
if (prop.isComplex()) {
|
||||
auto cprop = prop.to<c10::complex<double>>();
|
||||
return PyComplex_FromDoubles(cprop.real(), cprop.imag());
|
||||
} else if (prop.isFloatingPoint()) {
|
||||
return PyFloat_FromDouble(prop.to<double>());
|
||||
} else if (prop.isIntegral(/*includeBool=*/false)) {
|
||||
return PyLong_FromLong(prop.to<int64_t>());
|
||||
} else if (prop.isBoolean()) {
|
||||
if (prop.to<bool>()) {
|
||||
Py_RETURN_TRUE;
|
||||
} else {
|
||||
Py_RETURN_FALSE;
|
||||
}
|
||||
} else {
|
||||
PyErr_SetString(PyExc_RuntimeError, "Unknown scalar type");
|
||||
return nullptr;
|
||||
}
|
||||
"""
|
||||
|
||||
MISC_GETTER_DEFS = {
|
||||
OptionalCType(BaseCType(longT)): (GETTER_DEFINITION_OPT, GETTER_BODY_INT64_T),
|
||||
BaseCType(doubleT): (GETTER_DEFINITION, GETTER_BODY_DOUBLE),
|
||||
OptionalCType(BaseCType(doubleT)): (GETTER_DEFINITION_OPT, GETTER_BODY_DOUBLE),
|
||||
BaseCType(boolT): (GETTER_DEFINITION, GETTER_BODY_BOOL),
|
||||
BaseCType(scalarT): (GETTER_DEFINITION, GETTER_BODY_SCALAR),
|
||||
OptionalCType(BaseCType(scalarT)): (GETTER_DEFINITION_OPT, GETTER_BODY_SCALAR),
|
||||
}
|
||||
|
||||
# These functions have backwards which cannot be traced, and so must have
|
||||
# their backward functions traced opaquely.
|
||||
# VIEW_FUNCTIONS are not traceable because they use as_strided, which
|
||||
# has an untraceable backwards, see
|
||||
# https://github.com/pytorch/pytorch/issues/4250
|
||||
# TODO: This is probably not exhaustive, but it's a start
|
||||
UNTRACEABLE_FUNCTIONS = VIEW_FUNCTIONS
|
||||
|
||||
|
||||
def gen_autograd_functions_lib(
|
||||
out: str,
|
||||
differentiability_infos: Sequence[DifferentiabilityInfo],
|
||||
template_path: str,
|
||||
) -> None:
|
||||
"""Functions.h and Functions.cpp body
|
||||
|
||||
These contain the auto-generated subclasses of torch::autograd::Node
|
||||
for each every differentiable torch function.
|
||||
"""
|
||||
|
||||
# only create an autograd function if we are actually going to calculate a derivative
|
||||
infos = list(filter(lambda info: info.args_with_derivatives, differentiability_infos))
|
||||
declarations = list(map(lambda f: process_function(f, FUNCTION_DECLARATION), infos))
|
||||
definitions = list(map(lambda f: process_function(f, FUNCTION_DEFINITION), infos))
|
||||
|
||||
file_basename = 'Functions'
|
||||
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
|
||||
for suffix in ['.h', '.cpp']:
|
||||
fname = file_basename + suffix
|
||||
fm.write_with_template(fname, fname, lambda: {
|
||||
'generated_comment': '@' + f'generated from {fm.template_dir}/' + fname,
|
||||
'autograd_function_declarations': declarations,
|
||||
'autograd_function_definitions': definitions,
|
||||
})
|
||||
|
||||
|
||||
def gen_autograd_functions_python(
|
||||
out: str,
|
||||
differentiability_infos: Sequence[DifferentiabilityInfo],
|
||||
template_path: str,
|
||||
) -> None:
|
||||
|
||||
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
|
||||
num_shards = 5
|
||||
fm.write('python_functions.h', lambda: {
|
||||
'generated_comment': f'@generated from {fm.template_dir}/python_functions.h',
|
||||
'shard_forward_declare': [
|
||||
f"void initialize_autogenerated_functions_{i}();"
|
||||
for i in range(num_shards)
|
||||
],
|
||||
'shard_call': [
|
||||
f"initialize_autogenerated_functions_{i}();"
|
||||
for i in range(num_shards)
|
||||
]
|
||||
})
|
||||
|
||||
infos = list(filter(lambda info: info.args_with_derivatives, differentiability_infos))
|
||||
fm.write_sharded(
|
||||
'python_functions.cpp',
|
||||
infos,
|
||||
key_fn=lambda info: info.name,
|
||||
base_env={
|
||||
'generated_comment': f'@generated from {fm.template_dir}/python_functions.cpp',
|
||||
},
|
||||
env_callable=lambda info: {
|
||||
'py_function_initializers': [process_function(info, PY_FUNCTION_DEFINITION)],
|
||||
'py_function_props_and_getters': [process_function(info, PY_FUNCTION_PROPS_AND_GETTERS)],
|
||||
},
|
||||
num_shards=num_shards,
|
||||
sharded_keys={'py_function_initializers', 'py_function_props_and_getters'}
|
||||
)
|
||||
|
||||
|
||||
def process_function(info: DifferentiabilityInfo, template: CodeTemplate) -> str:
|
||||
saved_variables: List[str] = []
|
||||
release_variables: List[str] = []
|
||||
saved_list_sizes: List[str] = []
|
||||
unpack: List[str] = []
|
||||
asserts: List[str] = []
|
||||
compute_index_ranges: List[str] = []
|
||||
getter_definitions: List[str] = []
|
||||
py_getsetdef_structs: List[str] = []
|
||||
|
||||
for arg in info.args_with_derivatives:
|
||||
if arg.type == 'at::TensorList' or arg.type == 'const c10::List<c10::optional<at::Tensor>> &':
|
||||
size = f'{arg.name}_size_'
|
||||
saved_list_sizes.append(f'size_t {arg.name}_size_;')
|
||||
else:
|
||||
size = '1'
|
||||
compute_index_ranges.append(f'auto {arg.name}_ix = gen.range({size});')
|
||||
|
||||
def save_var(var: SavedAttribute, is_output: bool) -> None:
|
||||
name = var.nctype.name
|
||||
func_type = var.nctype.type
|
||||
should_append_getsetdef = True
|
||||
should_append_raw_getsetdef = False
|
||||
|
||||
if func_type == BaseCType(tensorT) or func_type == OptionalCType(BaseCType(tensorT)) or \
|
||||
func_type == MutRefCType(OptionalCType(BaseCType(tensorT))) or \
|
||||
(func_type == BaseCType(scalarT) and is_output):
|
||||
saved_variables.append(f'SavedVariable {name}_;')
|
||||
release_variables.append(f'{name}_.reset_data();')
|
||||
ptr = 'shared_from_this()' if is_output else ''
|
||||
unpack.append(f'auto {name} = {name}_.unpack({ptr});')
|
||||
getter_definitions.append(GETTER_DEFINITION_SAVEDVAR.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_SAVEDVAR))
|
||||
getter_definitions.append(GETTER_DEFINITION_RAW_SAVEDVAR.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_RAW_SAVEDVAR))
|
||||
should_append_raw_getsetdef = True
|
||||
elif func_type == BaseCType(tensorListT):
|
||||
saved_variables.append(f'std::vector<SavedVariable> {name}_;')
|
||||
saved_variables.append(f'bool {name}_released_ = false;')
|
||||
# Just clear() is sufficient, we don't need to loop and clear each variable.
|
||||
# Because the SavedVariable owns a tensor and a grad_fn,
|
||||
# removing the SavedVariable makes them go away as well.
|
||||
release_variables.append(f'{name}_.clear();')
|
||||
release_variables.append(f'{name}_released_ = true;')
|
||||
unpack.append(f'auto {name} = unpack_list({name}_);')
|
||||
asserts.append(f'TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);')
|
||||
getter_definitions.append(GETTER_DEFINITION_VEC_SAVEDVAR.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_VEC_SAVEDVAR))
|
||||
getter_definitions.append(GETTER_DEFINITION_RAW_VEC_SAVEDVAR.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_RAW_VEC_SAVEDVAR))
|
||||
should_append_raw_getsetdef = True
|
||||
elif func_type == ListCType(OptionalCType(BaseCType(tensorT))):
|
||||
saved_variables.append(f'std::vector<SavedVariable> {name}_;')
|
||||
saved_variables.append(f'bool {name}_released_ = false;')
|
||||
# Just clear() is sufficient, we don't need to loop and clear each variable.
|
||||
# Because the SavedVariable owns a tensor and a grad_fn,
|
||||
# removing the SavedVariable makes them go away as well.
|
||||
release_variables.append(f'{name}_.clear();')
|
||||
release_variables.append(f'{name}_released_ = true;')
|
||||
unpack.append(f'auto {name} = unpack_opt_list({name}_);')
|
||||
asserts.append(f'TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);')
|
||||
getter_definitions.append(GETTER_DEFINITION_VEC_SAVEDVAR.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_VEC_SAVEDVAR))
|
||||
getter_definitions.append(GETTER_DEFINITION_RAW_VEC_SAVEDVAR.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_RAW_VEC_SAVEDVAR))
|
||||
should_append_raw_getsetdef = True
|
||||
elif func_type == BaseCType(intArrayRefT):
|
||||
saved_variables.append(f'std::vector<int64_t> {name};')
|
||||
getter_definitions.append(GETTER_DEFINITION.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG))
|
||||
elif func_type == OptionalCType(BaseCType(intArrayRefT)):
|
||||
saved_variables.append(f'c10::OptionalArray<int64_t> {name};')
|
||||
getter_definitions.append(GETTER_DEFINITION_OPT_ARRAYREF.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG))
|
||||
elif func_type == OptionalCType(ArrayRefCType(BaseCType(doubleT))):
|
||||
saved_variables.append(f'c10::OptionalArray<double> {name};')
|
||||
getter_definitions.append(GETTER_DEFINITION_OPT_ARRAYREF.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_ARRAYREF_DOUBLE))
|
||||
elif func_type == BaseCType(longT):
|
||||
saved_variables.append(f'{func_type.cpp_type()} {name} = 0;')
|
||||
getter_definitions.append(GETTER_DEFINITION.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_INT64_T))
|
||||
elif func_type == BaseCType(stringT):
|
||||
saved_variables.append(f'std::string {name};')
|
||||
getter_definitions.append(GETTER_DEFINITION.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_STRING))
|
||||
elif func_type == OptionalCType(BaseCType(stringT)):
|
||||
saved_variables.append(f'c10::optional<std::string> {name};')
|
||||
getter_definitions.append(GETTER_DEFINITION_OPT.substitute(
|
||||
op=info.op, name=name, body=GETTER_BODY_STRING))
|
||||
else:
|
||||
saved_variables.append(f'{func_type.cpp_type()} {name};')
|
||||
|
||||
if func_type in MISC_GETTER_DEFS:
|
||||
getter_def, body = MISC_GETTER_DEFS[func_type]
|
||||
getter_definitions.append(getter_def.substitute(op=info.op, name=name, body=body))
|
||||
else:
|
||||
# Types we don't expose python bindings to yet:
|
||||
# TypeAndSize, at::ScalarType, TensorOptions, TensorGeometry,
|
||||
# std::vector<std::vector<int64_t>>, std::vector<at::ScalarType>
|
||||
should_append_getsetdef = False
|
||||
|
||||
if should_append_getsetdef:
|
||||
py_getsetdef_structs.append(PY_GETSETDEF_STRUCT.substitute(op=info.op, name=name))
|
||||
if should_append_raw_getsetdef:
|
||||
py_getsetdef_structs.append(PY_RAW_GETSETDEF_STRUCT.substitute(op=info.op, name=name))
|
||||
|
||||
for var in info.all_saved_inputs:
|
||||
save_var(var, is_output=False)
|
||||
for var in info.all_saved_outputs:
|
||||
save_var(var, is_output=True)
|
||||
|
||||
# lock the mutex when we release variables and in Node::apply to protect thread safety
|
||||
# see Note [Thread Safety on Autograd Node]
|
||||
if len(release_variables) > 0:
|
||||
thread_lock = 'std::lock_guard<std::mutex> lock(mutex_);'
|
||||
else:
|
||||
thread_lock = ''
|
||||
|
||||
if uses_retain_variables(info):
|
||||
will_release_variables = WILL_RELEASE_VARIABLES.substitute()
|
||||
else:
|
||||
will_release_variables = ''
|
||||
|
||||
body: List[str] = []
|
||||
|
||||
if uses_single_grad(info):
|
||||
body.append('const auto& grad = grads[0];')
|
||||
else:
|
||||
# Generate aliases for gradients named for returned values.
|
||||
body.extend(
|
||||
f'const auto& {name} = grads[{info.available_named_gradients.index(name)}];'
|
||||
for name in info.used_named_gradients)
|
||||
|
||||
def emit_derivative(
|
||||
derivative: Derivative,
|
||||
args_with_derivatives: Sequence[Binding],
|
||||
) -> Tuple[bool, str]:
|
||||
formula = derivative.formula
|
||||
var_names = derivative.var_names
|
||||
if len(var_names) == 1:
|
||||
checks_any_grad_defined = False
|
||||
if 'not_implemented' not in formula:
|
||||
matching_args = [
|
||||
arg for arg in args_with_derivatives
|
||||
if arg.name == var_names[0]]
|
||||
if len(matching_args) == 1:
|
||||
# We can add undefined grad support if the input variable is a Tensor
|
||||
arg = matching_args[0]
|
||||
if isinstance(arg.argument, Argument) and str(arg.argument.type) in ('Tensor', 'Tensor?'):
|
||||
formula = 'any_grad_defined ? (' + formula + ') : Tensor()'
|
||||
checks_any_grad_defined = True
|
||||
return (checks_any_grad_defined,
|
||||
DERIVATIVE_SINGLE.substitute(name=var_names[0], derivative=formula))
|
||||
else:
|
||||
if 'grad_input_mask' in formula:
|
||||
masks = [f'should_compute_output({{ {n}_ix }}),' for n in var_names]
|
||||
grad_input_mask = GRAD_INPUT_MASK.substitute(masks=masks, n=len(var_names))
|
||||
else:
|
||||
grad_input_mask = ''
|
||||
idx_ranges = ', '.join(f'{n}_ix' for n in var_names)
|
||||
copy_ranges: List[str] = []
|
||||
for i, n in enumerate(var_names):
|
||||
copy_ranges.append(DERIVATIVE_MULTI_COPY_RANGE.substitute(name=n, i=i))
|
||||
return False, DERIVATIVE_MULTI.substitute(
|
||||
idx_ranges=idx_ranges, copy_ranges=copy_ranges,
|
||||
derivative=formula,
|
||||
grad_input_mask=grad_input_mask)
|
||||
|
||||
body.extend(unpack)
|
||||
need_any_grad_defined_var = False
|
||||
for derivative in info.derivatives:
|
||||
checks_any_grad_defined, derivative_text = emit_derivative(derivative, info.args_with_derivatives)
|
||||
body.append(derivative_text)
|
||||
need_any_grad_defined_var |= checks_any_grad_defined
|
||||
# Since single-output derivative formulas need to check if grads are
|
||||
# defined, only perform the check once, before all the formulas
|
||||
if need_any_grad_defined_var:
|
||||
body.insert(-len(info.derivatives),
|
||||
'bool any_grad_defined = any_variable_defined(grads);')
|
||||
|
||||
if info.name in UNTRACEABLE_FUNCTIONS:
|
||||
superclass = 'Node'
|
||||
else:
|
||||
superclass = 'TraceableFunction'
|
||||
|
||||
all_getsetdef_structs = ",\n".join(py_getsetdef_structs) + "," if len(py_getsetdef_structs) != 0 else ""
|
||||
all_getter_definitions = "\n".join(getter_definitions)
|
||||
|
||||
return template.substitute(
|
||||
op=info.op,
|
||||
compute_index_ranges=compute_index_ranges,
|
||||
saved_variables=saved_variables,
|
||||
release_variables=release_variables,
|
||||
saved_list_sizes=saved_list_sizes,
|
||||
asserts=asserts,
|
||||
thread_lock=thread_lock,
|
||||
will_release_variables=will_release_variables,
|
||||
body=body,
|
||||
superclass=superclass,
|
||||
all_getter_definitions=all_getter_definitions,
|
||||
all_getsetdef_structs=all_getsetdef_structs
|
||||
)
|
||||
@@ -0,0 +1,486 @@
|
||||
# Copyright (c) 2023 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.
|
||||
|
||||
# Generates ADInplaceOrViewType.h/cpp
|
||||
#
|
||||
|
||||
from typing import List, Optional, Sequence, Tuple, Dict
|
||||
|
||||
from codegen.api import cpp
|
||||
from codegen.api.autograd import (
|
||||
NativeFunctionWithDifferentiabilityInfo,
|
||||
gen_differentiable_outputs,
|
||||
dispatch_strategy,
|
||||
)
|
||||
from codegen.api.types import (
|
||||
Binding, CType, BaseCType,
|
||||
OptionalCType, longT, boolT, intArrayRefT
|
||||
)
|
||||
from codegen.api.signature import DispatcherSignature
|
||||
from codegen.code_template import CodeTemplate
|
||||
from codegen.context import with_native_function
|
||||
from codegen.model import (
|
||||
Type, NativeFunction, SelfArgument,
|
||||
TensorOptionsArguments, SchemaKind, is_foreach_op,
|
||||
)
|
||||
from codegen.gen import FileManager
|
||||
|
||||
from .context import with_native_function_with_differentiability_info
|
||||
from .utils import (
|
||||
MANUAL_BACKEND, MANUAL_AUTOGRAD_AND_TRACER, type_wrapper_name,
|
||||
tie_return_values, get_return_value
|
||||
)
|
||||
|
||||
# See NOTE [ Autograd View Variables ] in variable.h for details.
|
||||
# If you update list VIEW_FUNCTIONS or RETURNS_VIEWS_OF_INPUT,
|
||||
# you **MUST** also update the public list of view ops accordingly in
|
||||
# docs/source/tensor_view.rst. Note not all ATen functions are exposed to public,
|
||||
# e.g alias & sparse_coo_tensor_with_dims_and_tensors.
|
||||
#
|
||||
# A map: function name => name of the argument that all outputs are view of
|
||||
|
||||
VIEW_FUNCTIONS_WITH_METADATA_CHANGE = [
|
||||
'view_as_complex',
|
||||
'view_as_real',
|
||||
'_conj',
|
||||
'_neg_view'
|
||||
]
|
||||
|
||||
VIEW_FUNCTIONS = {
|
||||
'numpy_T': 'self',
|
||||
'alias': 'self',
|
||||
'as_strided': 'self',
|
||||
'diagonal': 'self',
|
||||
'expand': 'self',
|
||||
'permute': 'self',
|
||||
'select': 'self',
|
||||
'slice': 'self',
|
||||
'split': 'self',
|
||||
'split_with_sizes': 'self',
|
||||
'squeeze': 'self',
|
||||
't': 'self',
|
||||
'transpose': 'self',
|
||||
'unfold': 'self',
|
||||
'unsqueeze': 'self',
|
||||
'flatten': 'self',
|
||||
'view': 'self',
|
||||
'unbind': 'self',
|
||||
'_indices': 'self',
|
||||
'_values': 'self',
|
||||
'indices': 'self',
|
||||
'values': 'self',
|
||||
'crow_indices': 'self',
|
||||
'col_indices': 'self',
|
||||
# sparse_coo ctor output should really be views of both indices and values,
|
||||
# but we only supports making as view of a single variable, and indices is
|
||||
# discrete anyways.
|
||||
# FIXME: clone indices on construction.
|
||||
'sparse_coo_tensor_with_dims_and_tensors': 'values',
|
||||
'_reshape_alias': 'self',
|
||||
}
|
||||
|
||||
for key in VIEW_FUNCTIONS_WITH_METADATA_CHANGE:
|
||||
VIEW_FUNCTIONS[key] = 'self'
|
||||
|
||||
MANUAL_AUTOGRAD = MANUAL_BACKEND | MANUAL_AUTOGRAD_AND_TRACER
|
||||
|
||||
# note: some VIEW_FUNCTIONS are just compositions of the view functions above
|
||||
# this list contains both the root view functions and any that are purely composed
|
||||
# of viewing functions, and is used by the JIT to determine when an operator
|
||||
# may return a view of its inputs; however they may sometimes return a copy.
|
||||
# (e.g. `contiguous`)
|
||||
RETURNS_VIEWS_OF_INPUT = set(VIEW_FUNCTIONS.keys()).union({
|
||||
'chunk', 'detach', 'contiguous', 'reshape', 'reshape_as',
|
||||
'expand_as', 'view_as', 'real', 'imag', 'narrow', 'movedim',
|
||||
'tensor_split', 'swapdims', 'swapaxes', 'mT', 'mH', 'adjoint', 'matrix_H'
|
||||
})
|
||||
|
||||
# These are the functions we consider views for the purposes of validating
|
||||
# StorageImpl and TensorImpl in gen_variable_type.
|
||||
# `_unsafe_view` is not included in VIEW_FUNCTIONS above because it is not a
|
||||
# view for the purposes of ADInplaceOrView kernel, we do not want to call as_view
|
||||
# See NOTE [Unsafe View] for more info.
|
||||
ALL_VIEW_FUNCTIONS = {
|
||||
**VIEW_FUNCTIONS,
|
||||
'_unsafe_view': 'self',
|
||||
}
|
||||
|
||||
ARRAYREF_TO_VEC = CodeTemplate("""\
|
||||
auto ${vec} = ${arg}.vec();
|
||||
""")
|
||||
|
||||
OPTIONAL_TO_VAL = CodeTemplate("""\
|
||||
auto ${val} = ${arg}.value_or(${default});
|
||||
""")
|
||||
|
||||
CALL_DISPATCH = CodeTemplate("""\
|
||||
at::_ops::${unambiguous_name}::call(${unpacked_args})""")
|
||||
|
||||
SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE = CodeTemplate("""\
|
||||
std::function<at::Tensor(const at::Tensor&)> func=nullptr;
|
||||
if (${is_view_with_metadata_change} || !self.unsafeGetTensorImpl()->support_as_strided()) {
|
||||
${replay_view_func}
|
||||
}
|
||||
""")
|
||||
|
||||
REPLAY_VIEW_LAMBDA_FUNC = CodeTemplate("""\
|
||||
func = [=](const at::Tensor& ${input_base}) {
|
||||
return ${replay_view_call};
|
||||
};
|
||||
""")
|
||||
|
||||
METHOD_DEFINITION = CodeTemplate("""\
|
||||
${return_type} ${type_wrapper_name}(${formals}) {
|
||||
${type_definition_body}
|
||||
}
|
||||
""")
|
||||
|
||||
WRAPPER_REGISTRATION = CodeTemplate("""\
|
||||
m.impl("${unqual_operator_name_with_overload}",
|
||||
TORCH_FN(${class_type}::${type_wrapper_name})
|
||||
);
|
||||
""")
|
||||
|
||||
AUTOGRAD_NOT_IMPLEMENTED_REGISTRATION = CodeTemplate("""\
|
||||
m.impl("${unqual_operator_name_with_overload}", torch::autograd::autogradNotImplementedFallback());
|
||||
""")
|
||||
|
||||
INPLACE_REDISPATCH = CodeTemplate("""\
|
||||
{
|
||||
at::AutoDispatchBelowADInplaceOrView guard;
|
||||
at::_ops::${unambiguous_name}::redispatch(${unpacked_args});
|
||||
}
|
||||
""")
|
||||
|
||||
ASSIGN_RETURN_VALUE = CodeTemplate("""\
|
||||
${return_values} = ${rhs_value};
|
||||
""")
|
||||
|
||||
VIEW_REDISPATCH = CodeTemplate("""\
|
||||
${assign_return_values} ([&]() {
|
||||
at::AutoDispatchBelowADInplaceOrView guard;
|
||||
return at::_ops::${unambiguous_name}::redispatch(${unpacked_args});
|
||||
})();
|
||||
""")
|
||||
|
||||
TMP_VAR = '_tmp'
|
||||
|
||||
|
||||
# FIXME: Ideally these functions should be methods on Type class, but we have a
|
||||
# comment in codegen/model.py there saying these concepts are not well defined.
|
||||
# Thus we put a version that commonly used by autograd codegen here.
|
||||
def is_tensor_type(t: Type) -> bool:
|
||||
# TODO: Should handle optional here?
|
||||
return t.is_tensor_like() and t.is_list_like() is None
|
||||
|
||||
|
||||
def is_tensor_list_type(t: Type) -> bool:
|
||||
# TODO: Should handle optional here?
|
||||
return t.is_tensor_like() and t.is_list_like() is not None
|
||||
|
||||
UNPACK_TENSOR = CodeTemplate("""\
|
||||
auto${ref} ${arg_name}_ = unpack${suffix}(${arg_name}, "${arg_name}", ${arg_pos});""")
|
||||
|
||||
|
||||
def unpacked_name(arg_name: str) -> str:
|
||||
return arg_name + '_'
|
||||
|
||||
|
||||
@with_native_function
|
||||
def unpack_args(f: NativeFunction) -> Tuple[List[str], List[Binding]]:
|
||||
body: List[str] = []
|
||||
unpacked_bindings: List[Binding] = []
|
||||
|
||||
bindings = [r for a in f.func.schema_order_arguments()
|
||||
for r in cpp.argument(a,
|
||||
method=False,
|
||||
cpp_no_default_args=set(),
|
||||
faithful=False,
|
||||
has_tensor_options=False)]
|
||||
|
||||
for i, binding in enumerate(bindings):
|
||||
assert not isinstance(binding.argument, SelfArgument)
|
||||
if isinstance(binding.argument, TensorOptionsArguments):
|
||||
raise RuntimeError("VariableKernel shouldn't take TensorOptions")
|
||||
|
||||
is_nullable = binding.argument.type.is_nullable()
|
||||
if not binding.argument.type.is_tensor_like() or is_nullable:
|
||||
unpacked_bindings.append(binding)
|
||||
continue
|
||||
|
||||
is_tensor_list = is_tensor_list_type(binding.argument.type)
|
||||
ref = (not is_nullable) and not is_tensor_list
|
||||
suffix = '_opt' if is_nullable and not is_tensor_list else ''
|
||||
body.append(UNPACK_TENSOR.substitute(
|
||||
arg_name=binding.name,
|
||||
arg_pos=i,
|
||||
suffix=suffix,
|
||||
ref='&' if ref else '',
|
||||
))
|
||||
unpacked_bindings.append(Binding(
|
||||
name=unpacked_name(binding.name),
|
||||
nctype=binding.nctype,
|
||||
argument=binding.argument,
|
||||
default=binding.default,
|
||||
))
|
||||
|
||||
return body, unpacked_bindings
|
||||
|
||||
|
||||
def get_base_name(f: NativeFunction) -> str:
|
||||
return f.func.name.name.base # TODO: should be str(f.func.name.name)?
|
||||
|
||||
|
||||
def get_view_info(f: NativeFunction) -> Optional[str]:
|
||||
base_name = get_base_name(f)
|
||||
view_info = VIEW_FUNCTIONS.get(base_name, None)
|
||||
if view_info is None and base_name in RETURNS_VIEWS_OF_INPUT:
|
||||
view_info = "self"
|
||||
return view_info
|
||||
|
||||
|
||||
# For view replay calls, we generate an ordinary Dispatcher::call() instead, because:
|
||||
# - We want to replay the entire call into the op, including any previously-set dispatch keys (including autograd!).
|
||||
# - The view replay call also is not part of the hot path.
|
||||
def emit_view_call(f: NativeFunction, input_base: str, unpacked_args: Sequence[str]) -> str:
|
||||
# View replay functions use the standard Dispatcher::call API.
|
||||
return CALL_DISPATCH.substitute(
|
||||
unambiguous_name=f.func.name.unambiguous_name(),
|
||||
unpacked_args=unpacked_args)
|
||||
|
||||
|
||||
def emit_view_lambda(f: NativeFunction, unpacked_bindings: List[Binding]) -> str:
|
||||
"""
|
||||
Generate an additional lambda function to recover views in backward when as_strided is not supported.
|
||||
See Note [View + Inplace update for base tensor] and [View + Inplace update for view tensor] for more details.
|
||||
"""
|
||||
input_base = 'input_base'
|
||||
replay_view_func = ''
|
||||
updated_unpacked_args: List[str] = []
|
||||
known_view_arg_simple_types: List[CType] = [
|
||||
BaseCType(longT),
|
||||
OptionalCType(BaseCType(longT)),
|
||||
BaseCType(boolT),
|
||||
BaseCType(intArrayRefT)]
|
||||
for unpacked_binding in unpacked_bindings:
|
||||
arg, arg_type = unpacked_binding.name, unpacked_binding.nctype.type
|
||||
if arg == 'self_':
|
||||
updated_unpacked_args.append(input_base)
|
||||
continue
|
||||
if arg_type not in known_view_arg_simple_types:
|
||||
known_types_str = ', '.join([str(t) for t in known_view_arg_simple_types])
|
||||
raise TypeError(f'You are adding an {arg_type} {arg} argument to '
|
||||
f'op {cpp.name(f.func)} in addition to known types: '
|
||||
f'{known_types_str}. Please update the list or materialize it so that it can be closed '
|
||||
'over by value, also add a test in pytorch/xla/test/test_operations.py where this code '
|
||||
'is exercised.')
|
||||
|
||||
if arg_type == BaseCType(intArrayRefT):
|
||||
# It's not safe to close over IntArrayRef by value, since this is a
|
||||
# reference type, so materialize a vector to close over by value
|
||||
arg_vec = arg + '_vec'
|
||||
replay_view_func += ARRAYREF_TO_VEC.substitute(arg=arg, vec=arg_vec)
|
||||
updated_unpacked_args.append(arg_vec)
|
||||
elif arg_type == OptionalCType(BaseCType(longT)):
|
||||
# Materialize int64_t? to int64_t
|
||||
arg_value = arg + '_val'
|
||||
replay_view_func += OPTIONAL_TO_VAL.substitute(arg=arg, val=arg_value, default='0')
|
||||
updated_unpacked_args.append(arg_value)
|
||||
else:
|
||||
updated_unpacked_args.append(arg)
|
||||
|
||||
replay_view_call = emit_view_call(f, input_base, updated_unpacked_args)
|
||||
replay_view_func += REPLAY_VIEW_LAMBDA_FUNC.substitute(
|
||||
input_base=input_base,
|
||||
replay_view_call=replay_view_call)
|
||||
|
||||
is_view_with_metadata_change = 'true' if cpp.name(f.func) in VIEW_FUNCTIONS_WITH_METADATA_CHANGE else 'false'
|
||||
|
||||
return SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE.substitute(
|
||||
is_view_with_metadata_change=is_view_with_metadata_change,
|
||||
replay_view_func=replay_view_func)
|
||||
|
||||
|
||||
def emit_view_body(fn: NativeFunctionWithDifferentiabilityInfo, var: str) -> Tuple[str, str]:
|
||||
# See NOTE [ Autograd View Variables ] in variable.h for details.
|
||||
f = fn.func
|
||||
base_name = get_base_name(f)
|
||||
view_info = get_view_info(f)
|
||||
call = ''
|
||||
differentiable_outputs = gen_differentiable_outputs(fn)
|
||||
differentiable_output_vars = {r.name for r in differentiable_outputs}
|
||||
if not isinstance(view_info, str):
|
||||
raise TypeError(f'The view info should be a string for {base_name}, but it is: {view_info}')
|
||||
if len(differentiable_output_vars) == 0:
|
||||
# no output is differentiable (.indices() for SparseTensors for example)
|
||||
rhs_value = (f'as_view({view_info}, {var}, '
|
||||
f'/* is_bw_differentiable */ false, /* is_fw_differentiable */ false)')
|
||||
elif len(differentiable_output_vars) == 1:
|
||||
# Single differentiable output (Tensor or Tensor[])
|
||||
return_info = differentiable_outputs[0]
|
||||
# We only support simple Tensor or a TensorList for functions that return views
|
||||
if not is_tensor_type(return_info.type) and not is_tensor_list_type(return_info.type):
|
||||
raise RuntimeError(f'{base_name} that return differentiable views can only return Tensor or Tensor[]')
|
||||
|
||||
# See Note [ View + Inplace detection]
|
||||
def get_creation_meta_in_mode(original: str) -> str:
|
||||
creation_meta_with_grad_mode = f'(at::GradMode::is_enabled() ? {original} : CreationMeta::NO_GRAD_MODE)'
|
||||
return f'InferenceMode::is_enabled() ? CreationMeta::INFERENCE_MODE : {creation_meta_with_grad_mode}'
|
||||
|
||||
# Only allow rebasing of the history if we return a single Tensor
|
||||
# If we are in a no grad block, raise a warning
|
||||
# See NOTE [ View + Inplace detection ] for more details about this logic
|
||||
if is_tensor_list_type(return_info.type):
|
||||
creation_meta = get_creation_meta_in_mode('CreationMeta::MULTI_OUTPUT_NODE')
|
||||
call += (f'as_view(/* base */ {view_info}, /* output */ {var}, /* is_bw_differentiable */ true, '
|
||||
'/* is_fw_differentiable */ true, '
|
||||
f'/* creation_meta */ {creation_meta});')
|
||||
rhs_value = f'std::move({var})'
|
||||
else:
|
||||
_, unpacked_bindings = unpack_args(f)
|
||||
call += emit_view_lambda(f, unpacked_bindings)
|
||||
creation_meta = get_creation_meta_in_mode('CreationMeta::DEFAULT')
|
||||
rhs_value = (f'as_view(/* base */ {view_info}, /* output */ {var}, /* is_bw_differentiable */ true, '
|
||||
'/* is_fw_differentiable */ true, '
|
||||
f'/* view_func */ func, /* creation_meta */ {creation_meta})')
|
||||
else:
|
||||
# This could be supported but we don't need it at the moment, so keeping things simple.
|
||||
raise RuntimeError('Function that return multiple differentiable output '
|
||||
'when at least one of them is view is not supported.')
|
||||
return call, rhs_value
|
||||
|
||||
|
||||
def modifies_arguments(f: NativeFunction) -> bool:
|
||||
return f.func.kind() in [SchemaKind.inplace, SchemaKind.out]
|
||||
|
||||
|
||||
@with_native_function_with_differentiability_info
|
||||
def emit_inplace_or_view_body(fn: NativeFunctionWithDifferentiabilityInfo) -> List[str]:
|
||||
f = fn.func
|
||||
inplace_view_body: List[str] = []
|
||||
|
||||
dispatcher_sig = DispatcherSignature.from_schema(f.func)
|
||||
dispatcher_exprs = dispatcher_sig.exprs()
|
||||
|
||||
# code-generated ADInplaceOrView kernels plumb and
|
||||
# recompute dispatch keys directly through the kernel for performance.
|
||||
# See Note [Plumbing Keys Through The Dispatcher] for details.
|
||||
dispatch_key_set = 'ks & c10::after_ADInplaceOrView_keyset'
|
||||
redispatch_args = ', '.join([dispatch_key_set] + [a.expr for a in dispatcher_exprs])
|
||||
|
||||
# Note that this calls the slow, dispatching variants of manual_cpp_binding ops.
|
||||
# We could probably work harder to ensure that the fast variants are called instead,
|
||||
# but the perf benefit would be minimal.
|
||||
if modifies_arguments(f): # inplace op
|
||||
inplace_view_body.append(INPLACE_REDISPATCH.substitute(
|
||||
unambiguous_name=f.func.name.unambiguous_name(),
|
||||
unpacked_args=redispatch_args,
|
||||
))
|
||||
for r in cpp.return_names(f):
|
||||
inplace_view_body.append(f'increment_version({r});')
|
||||
else:
|
||||
assert(get_view_info(f) is not None)
|
||||
inplace_view_body.append(VIEW_REDISPATCH.substitute(
|
||||
assign_return_values='auto ' + TMP_VAR + ' = ',
|
||||
unambiguous_name=f.func.name.unambiguous_name(),
|
||||
unpacked_args=redispatch_args,
|
||||
))
|
||||
call, rhs_value = emit_view_body(fn, TMP_VAR)
|
||||
inplace_view_body.append(call)
|
||||
assert rhs_value is not None
|
||||
inplace_view_body.append(
|
||||
ASSIGN_RETURN_VALUE.substitute(return_values=tie_return_values(f), rhs_value=rhs_value))
|
||||
if f.func.returns:
|
||||
inplace_view_body.append(f'return {get_return_value(f)};')
|
||||
return inplace_view_body
|
||||
|
||||
|
||||
@with_native_function
|
||||
def gen_formals(f: NativeFunction) -> str:
|
||||
return ', '.join(
|
||||
# code-generated autograd kernels plumb and recompute dispatch keys directly through the kernel for performance.
|
||||
# See Note [Plumbing Keys Through The Dispatcher] for details.
|
||||
['c10::DispatchKeySet ks'] +
|
||||
[f'{cpp.argument_type(a, binds="__placeholder__").cpp_type()} {a.name}'
|
||||
for a in f.func.schema_order_arguments()]
|
||||
)
|
||||
|
||||
|
||||
@with_native_function_with_differentiability_info
|
||||
def inplace_or_view_method_definition(fn: NativeFunctionWithDifferentiabilityInfo) -> Optional[str]:
|
||||
f = fn.func
|
||||
if get_view_info(f) is None and (not modifies_arguments(f) or is_foreach_op(str(f.func.name))):
|
||||
return None
|
||||
return METHOD_DEFINITION.substitute(
|
||||
return_type=cpp.returns_type(f.func.returns).cpp_type(),
|
||||
type_wrapper_name=type_wrapper_name(f),
|
||||
formals=gen_formals(f),
|
||||
type_definition_body=emit_inplace_or_view_body(fn),
|
||||
)
|
||||
|
||||
|
||||
@with_native_function_with_differentiability_info
|
||||
def inplace_or_view_method_registration(fn: NativeFunctionWithDifferentiabilityInfo) -> Optional[str]:
|
||||
f = fn.func
|
||||
if get_view_info(f) is None and (not modifies_arguments(f) or is_foreach_op(str(f.func.name))):
|
||||
return None
|
||||
return WRAPPER_REGISTRATION.substitute(
|
||||
unqual_operator_name_with_overload=f.func.name,
|
||||
type_wrapper_name=type_wrapper_name(f),
|
||||
class_type='ADInplaceOrView',
|
||||
)
|
||||
|
||||
|
||||
def use_derived(fn: NativeFunctionWithDifferentiabilityInfo) -> bool:
|
||||
f = fn.func
|
||||
name = cpp.name(f.func)
|
||||
return name not in MANUAL_AUTOGRAD and dispatch_strategy(fn) == 'use_derived'
|
||||
|
||||
|
||||
def gen_inplace_or_view_type_env(fn: NativeFunctionWithDifferentiabilityInfo) -> Dict[str, List[str]]:
|
||||
definition = inplace_or_view_method_definition(fn)
|
||||
registration = inplace_or_view_method_registration(fn)
|
||||
|
||||
return {
|
||||
'ops_headers': ([f'#include <ATen/ops/{fn.func.root_name}_ops.h>']
|
||||
if definition is not None else []),
|
||||
'inplace_or_view_method_definitions': [definition] if definition is not None else [],
|
||||
'inplace_or_view_wrapper_registrations': [registration] if registration is not None else [],
|
||||
}
|
||||
|
||||
|
||||
def gen_inplace_or_view_type(
|
||||
out: str,
|
||||
fns_with_infos: List[NativeFunctionWithDifferentiabilityInfo],
|
||||
template_path: str
|
||||
) -> None:
|
||||
# NOTE: see Note [Sharded File] at the top of the VariableType.cpp
|
||||
# template regarding sharding of the generated files.
|
||||
|
||||
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
|
||||
fm.write_sharded(
|
||||
'ADInplaceOrViewType.cpp',
|
||||
[fn for fn in fns_with_infos if use_derived(fn)],
|
||||
key_fn=lambda fn: fn.func.root_name,
|
||||
base_env={
|
||||
'generated_comment':
|
||||
f'@generated from {template_path}/ADInplaceOrViewType.cpp',
|
||||
},
|
||||
env_callable=gen_inplace_or_view_type_env,
|
||||
num_shards=1,
|
||||
sharded_keys={'ops_headers', 'inplace_or_view_method_definitions',
|
||||
'inplace_or_view_wrapper_registrations'}
|
||||
)
|
||||
@@ -0,0 +1,120 @@
|
||||
# Copyright (c) 2023 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.
|
||||
|
||||
# Generates C++ functions that wrap ATen tensor factory methods to turn them into Variables.
|
||||
#
|
||||
# This writes one file: variable_factories.h
|
||||
|
||||
import re
|
||||
from typing import Optional, List
|
||||
|
||||
import codegen.api.python as python
|
||||
from codegen.api.signature import CppSignatureGroup
|
||||
from codegen.api import cpp
|
||||
from codegen.gen_backend_stubs import parse_native_and_custom_yaml
|
||||
from codegen.context import with_native_function
|
||||
from codegen.gen import FileManager
|
||||
from codegen.utils import map_maybe
|
||||
from codegen.model import NativeFunction, TensorOptionsArguments, Variant
|
||||
from .gen_variable_type import NPU_AUTOGRAD_FUNCTION
|
||||
|
||||
OPTIONAL_TYPE_PATTERN = re.compile(r"c10::optional<(.+)>")
|
||||
TYPE_PATTERN = re.compile(r"(?:const\s+)?([A-Z]\w+)")
|
||||
|
||||
|
||||
# Add 'at::' to types defined in ATen namespace, e.g. Tensor, TensorList, IntArrayRef and etc.
|
||||
# TODO: maybe update the cpp argument API to take optional namespace argument?
|
||||
def fully_qualified_type(argument_type: str) -> str:
|
||||
def maybe_optional_type(input_type: str, is_opt: bool) -> str:
|
||||
return f'c10::optional<{input_type}>' if is_opt else input_type
|
||||
|
||||
opt_match = OPTIONAL_TYPE_PATTERN.match(argument_type)
|
||||
is_opt = opt_match is not None
|
||||
if opt_match:
|
||||
argument_type = argument_type[opt_match.start(1):opt_match.end(1)]
|
||||
match = TYPE_PATTERN.match(argument_type)
|
||||
if match is None:
|
||||
return maybe_optional_type(argument_type, is_opt)
|
||||
index = match.start(1)
|
||||
qualified_type = f'{argument_type[:index]}at::{argument_type[index:]}'
|
||||
return maybe_optional_type(qualified_type, is_opt)
|
||||
|
||||
|
||||
def gen_variable_factories(
|
||||
out: str,
|
||||
native_yaml_path: str,
|
||||
npu_native_yaml_path: str,
|
||||
template_path: str
|
||||
) -> None:
|
||||
native_functions = parse_native_and_custom_yaml(native_yaml_path,
|
||||
npu_native_yaml_path).native_functions
|
||||
factory_functions = [fn for fn in native_functions if
|
||||
(is_factory_function(fn) and fn.func.name.name.base in NPU_AUTOGRAD_FUNCTION)]
|
||||
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
|
||||
fm.write_with_template('variable_factories.h', 'variable_factories.h', lambda: {
|
||||
'generated_comment': '@' + f'generated from {fm.template_dir}/variable_factories.h',
|
||||
'ops_headers': [f'#include <ATen/ops/{fn.root_name}.h>' for fn in factory_functions],
|
||||
'function_definitions': list(map_maybe(process_function, factory_functions)),
|
||||
})
|
||||
|
||||
|
||||
@with_native_function
|
||||
def is_factory_function(f: NativeFunction) -> bool:
|
||||
if Variant.function not in f.variants:
|
||||
return False
|
||||
|
||||
name = cpp.name(f.func)
|
||||
has_tensor_options = python.has_tensor_options(f)
|
||||
return has_tensor_options or name.endswith("_like")
|
||||
|
||||
|
||||
@with_native_function
|
||||
def process_function(f: NativeFunction) -> Optional[str]:
|
||||
name = cpp.name(f.func)
|
||||
has_tensor_options = python.has_tensor_options(f)
|
||||
is_factory = has_tensor_options or name.endswith("_like")
|
||||
|
||||
if Variant.function not in f.variants or not is_factory:
|
||||
return None
|
||||
|
||||
sig = CppSignatureGroup.from_native_function(f, method=False).signature
|
||||
formals: List[str] = []
|
||||
exprs: List[str] = []
|
||||
requires_grad = 'false'
|
||||
for arg in sig.arguments():
|
||||
qualified_type = fully_qualified_type(arg.type)
|
||||
if arg.default:
|
||||
formals.append(f'{qualified_type} {arg.name} = {arg.default}')
|
||||
else:
|
||||
formals.append(f'{qualified_type} {arg.name}')
|
||||
|
||||
if isinstance(arg.argument, TensorOptionsArguments):
|
||||
# note: we remove the requires_grad setting from the TensorOptions because
|
||||
# it is ignored anyways (and we actually have an assertion that it isn't set
|
||||
# which would fail otherwise). We handle requires_grad explicitly here
|
||||
# instead of passing it through to the kernel.
|
||||
exprs.append(f'at::TensorOptions({arg.name}).requires_grad(c10::nullopt)')
|
||||
# Manually set the requires_grad bit on the result tensor.
|
||||
requires_grad = f'{arg.name}.requires_grad()'
|
||||
else:
|
||||
exprs.append(arg.name)
|
||||
|
||||
return f"""\
|
||||
inline at::Tensor {name}({', '.join(formals)}) {{
|
||||
at::AutoDispatchBelowADInplaceOrView guard;
|
||||
return autograd::make_variable(at::{name}({', '.join(exprs)}), /*requires_grad=*/{requires_grad});
|
||||
}}
|
||||
"""
|
||||
@@ -0,0 +1,674 @@
|
||||
# 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.
|
||||
|
||||
# Parses derivatives.yaml into autograd functions
|
||||
#
|
||||
# Each autograd function is represented by `DifferentiabilityInfo` containing
|
||||
# a list of `Derivative`. See `tools.codegen.api.autograd` for the data models.
|
||||
from collections import defaultdict
|
||||
import re
|
||||
from typing import Counter, Sequence, Any, Tuple, List, Set, Dict, Match, Optional
|
||||
import yaml
|
||||
|
||||
from codegen.api.autograd import (
|
||||
Derivative, DifferentiabilityInfo,
|
||||
SavedAttribute, ForwardDerivative
|
||||
)
|
||||
from codegen.api.types import (
|
||||
Binding, NamedCType, BaseCType, VectorCType,
|
||||
intArrayRefT, tensorOptionsT, typeAndSizeT, longT, boolT,
|
||||
tensorGeometryT, scalarTypeT, SpecialArgName,
|
||||
OptionalCType, stringT
|
||||
)
|
||||
from codegen.api.signature import CppSignatureGroup
|
||||
from codegen.api import cpp
|
||||
from codegen.gen_backend_stubs import parse_native_and_custom_yaml
|
||||
from codegen.context import with_native_function
|
||||
from codegen.model import FunctionSchema, NativeFunction, Variant, Type
|
||||
from codegen.utils import IDENT_REGEX, split_name_params, YamlLoader
|
||||
|
||||
|
||||
_GLOBAL_LOAD_DERIVATIVE_CACHE = {}
|
||||
|
||||
|
||||
def load_derivatives(
|
||||
derivatives_yaml_path: str,
|
||||
native_yaml_path: str,
|
||||
npu_native_yaml_path: str
|
||||
) -> Sequence[DifferentiabilityInfo]:
|
||||
# Do some caching as this is a deterministic function
|
||||
global _GLOBAL_LOAD_DERIVATIVE_CACHE
|
||||
key = (derivatives_yaml_path, native_yaml_path)
|
||||
if key not in _GLOBAL_LOAD_DERIVATIVE_CACHE:
|
||||
|
||||
with open(derivatives_yaml_path, 'r') as f:
|
||||
definitions = yaml.load(f, Loader=YamlLoader)
|
||||
|
||||
functions = parse_native_and_custom_yaml(native_yaml_path, npu_native_yaml_path).native_functions
|
||||
|
||||
# What's the difference between function schema v.s. signature?
|
||||
# function schema is the complete declaration including mutability annotation / default value and etc.
|
||||
# signature is the canonical schema for a group of functions (in-place/out/functional variants)
|
||||
# that are semantically related.
|
||||
functions_by_signature: Dict[FunctionSchema, List[NativeFunction]] = defaultdict(list)
|
||||
functions_by_schema: Dict[str, NativeFunction] = dict()
|
||||
for function in functions:
|
||||
functions_by_signature[function.func.signature()].append(function)
|
||||
assert str(function.func) not in functions_by_schema
|
||||
functions_by_schema[str(function.func)] = function
|
||||
|
||||
# Keep track of how many of which ops we've seen so we can
|
||||
# disambiguate them with a numeric suffix.
|
||||
op_counter = Counter[str]()
|
||||
|
||||
infos = [
|
||||
create_differentiability_info(defn, functions_by_signature, functions_by_schema, op_counter)
|
||||
for defn in definitions]
|
||||
|
||||
_GLOBAL_LOAD_DERIVATIVE_CACHE[key] = infos
|
||||
|
||||
return _GLOBAL_LOAD_DERIVATIVE_CACHE[key]
|
||||
|
||||
|
||||
@with_native_function
|
||||
def cpp_arguments(f: NativeFunction) -> Sequence[Binding]:
|
||||
return CppSignatureGroup.from_native_function(f, method=False).signature.arguments()
|
||||
|
||||
|
||||
def create_derivative(f: NativeFunction, formula: str, var_names: Tuple[str, ...],
|
||||
available_named_gradients: Sequence[str]) -> Derivative:
|
||||
original_formula = formula
|
||||
arguments: List[NamedCType] = [a.nctype.remove_const_ref() for a in cpp_arguments(f)]
|
||||
|
||||
return_names = tuple(n if n != 'self' else 'result' for n in cpp.return_names(f))
|
||||
return_types = tuple(cpp.return_type(r).remove_const_ref() for r in f.func.returns)
|
||||
|
||||
named_returns = [NamedCType(name, type) for name, type in zip(return_names, return_types)]
|
||||
|
||||
formula, saved_inputs = saved_variables(formula, arguments, var_names)
|
||||
formula, saved_outputs = saved_variables(formula, named_returns, var_names)
|
||||
|
||||
used_named_gradients = {name for name in available_named_gradients if re.search(IDENT_REGEX.format(name), formula)}
|
||||
|
||||
# Check that the referenced derivatives in the formula are in bounds
|
||||
for i in used_gradient_indices(formula):
|
||||
if i >= len(f.func.returns):
|
||||
raise RuntimeError(
|
||||
f'Out of bounds grads access: derivative formula for {cpp.name(f.func)} '
|
||||
f'used grads[{i}], but the forward only returns {len(f.func.returns)} outputs.'
|
||||
)
|
||||
|
||||
return Derivative(
|
||||
formula=formula,
|
||||
original_formula=original_formula,
|
||||
var_names=var_names,
|
||||
saved_inputs=saved_inputs,
|
||||
saved_outputs=saved_outputs,
|
||||
named_gradients=used_named_gradients,
|
||||
)
|
||||
|
||||
|
||||
def create_forward_derivative(f: NativeFunction, formula: str, names: Tuple[str, ...]) -> ForwardDerivative:
|
||||
assert len(names) == 1, "Forward derivatives can define gradients for only one output at a time"
|
||||
var_name = names[0]
|
||||
var_type: Optional[Type] = None
|
||||
for r in f.func.returns:
|
||||
if r.name == var_name:
|
||||
var_type = r.type
|
||||
break
|
||||
# Handle default return names
|
||||
if var_type is None:
|
||||
if var_name == "result":
|
||||
assert len(f.func.returns) == 1
|
||||
var_type = f.func.returns[0].type
|
||||
else:
|
||||
res = re.findall(r"^result(\d+)$", var_name)
|
||||
if len(res) == 1:
|
||||
arg_idx = int(res[0])
|
||||
var_type = f.func.returns[arg_idx].type
|
||||
|
||||
assert var_type is not None, "No matching output for forward derivative definition"
|
||||
return ForwardDerivative(
|
||||
formula=formula,
|
||||
var_name=var_name,
|
||||
var_type=var_type,
|
||||
required_inputs_fw_grad=None,
|
||||
required_inputs_primal=None,
|
||||
required_original_self_value=False,
|
||||
is_reusing_outplace_formula=False)
|
||||
|
||||
|
||||
def postprocess_forward_derivatives(
|
||||
f: NativeFunction,
|
||||
defn_name: str,
|
||||
all_arg_names: List[str],
|
||||
derivatives: List[Derivative],
|
||||
forward_derivatives: List[ForwardDerivative],
|
||||
args_with_derivatives: Sequence[Binding]
|
||||
) -> List[ForwardDerivative]:
|
||||
|
||||
def find_required_inputs(formula: str, postfix: str) -> Tuple[str, ...]:
|
||||
required_inputs = set()
|
||||
for arg in args_with_derivatives:
|
||||
if arg.type == 'at::TensorList':
|
||||
# The functions taking TensorList handle everything internally
|
||||
continue
|
||||
arg_name = arg.name
|
||||
|
||||
found = re.search(IDENT_REGEX.format(arg_name), formula)
|
||||
if found:
|
||||
raise RuntimeError(f"The forward formula for {defn_name} is using the base name of the {arg_name} "
|
||||
f"argument which is ambiguous. You should use {arg_name}_p to access the primal "
|
||||
f"value and {arg_name}_t to access the tangent.")
|
||||
|
||||
found = re.search(IDENT_REGEX.format(arg_name + postfix), formula)
|
||||
if found:
|
||||
required_inputs.add(arg_name)
|
||||
|
||||
return tuple(required_inputs)
|
||||
|
||||
updated_derivatives: List[ForwardDerivative] = []
|
||||
|
||||
for defn in forward_derivatives:
|
||||
formula = defn.formula
|
||||
required_inputs_tangent = find_required_inputs(formula, "_t")
|
||||
if formula == "auto_element_wise":
|
||||
if (not len(args_with_derivatives) == 1) or len(forward_derivatives) > 1:
|
||||
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml defines the "
|
||||
"forward definition of gradient as element_wise but this only "
|
||||
"works for functions with a single differentiable input and a "
|
||||
"single differentiable output.")
|
||||
if not len(derivatives) == 1:
|
||||
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml defines the "
|
||||
"forward definition of gradient as element_wise but it does not "
|
||||
"defines the gradient formula for its argument which is required.")
|
||||
# This transformation is based on the observation that for element-wise functions,
|
||||
# the Jacobian matrix is diagonal and thus doing J * v
|
||||
# is the same as(v^T J)^T (in practice, we ignore the transpositions)
|
||||
# For the complex case, we use hermitian transpose and get (v.conj() J).conj()
|
||||
# So here we are going to re-use the backward formula and replace two things:
|
||||
# 1) all occurrences of "grad" with "foo_t.conj()",
|
||||
# where foo is the name of the unique differentiable input.
|
||||
# 2) all usage of an original input "foo" with its primal value "foo_p".
|
||||
# 3) conjugate the final result
|
||||
# For example, for abs, the backward formula is:
|
||||
# grad * self.sgn()
|
||||
# And this function generates a forward formula that is:
|
||||
# (self_t.conj() * self_p.sgn()).conj()
|
||||
|
||||
backward_formula = derivatives[0].original_formula
|
||||
input_name = args_with_derivatives[0].name
|
||||
|
||||
# Do replacement 1) of the grad
|
||||
def repl(m: Any) -> str:
|
||||
return f"{m.group(1)}{input_name}_t.conj(){m.group(2)}"
|
||||
fw_formula = re.sub(IDENT_REGEX.format("grad"), repl, backward_formula)
|
||||
|
||||
# Do replacement 2) of the input variables
|
||||
for arg in args_with_derivatives:
|
||||
arg_name = arg.name
|
||||
|
||||
def repl(m: Any) -> str:
|
||||
return f"{m.group(1)}{arg_name}_p{m.group(2)}"
|
||||
fw_formula = re.sub(IDENT_REGEX.format(arg_name), repl, fw_formula)
|
||||
|
||||
# Do the final conjugate 3)
|
||||
fw_formula = f"({fw_formula}).conj()"
|
||||
|
||||
# Since there is a single differentiable inputs and we necessarily need its tangent we can
|
||||
# simply require all differentiable input's tangent.
|
||||
required_inputs_tangent = tuple(all_arg_names)
|
||||
formula = fw_formula
|
||||
elif formula == "auto_linear":
|
||||
if len(forward_derivatives) > 1:
|
||||
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml defines the "
|
||||
"forward definition of gradient as linear but this only works "
|
||||
"for functions with a single differentiable output.")
|
||||
# This transformation is based on the observation that linear functions can be written as:
|
||||
# y = f(x) = A * x
|
||||
# For some matrix A and the Jacobian of the function f is also A.
|
||||
# So doing J * v = A * v = f(v).
|
||||
# Hence to do the jvp, we simply need to evaluate the function at the point v instead of x.
|
||||
# We do this by calling the forward again by replacing any occurrence of the differentiable
|
||||
# input "foo" by it's tangent "foo_t".
|
||||
# Note that multiple inputs are not a problem as long as the function is truly linear wrt to
|
||||
# the vector where all the differentiable inputs are stacked.
|
||||
|
||||
diff_arg_names = [arg.name for arg in args_with_derivatives]
|
||||
assert len(diff_arg_names) > 0
|
||||
|
||||
# Do replacement of input variables
|
||||
new_args = []
|
||||
for arg_name in all_arg_names:
|
||||
if arg_name in diff_arg_names:
|
||||
arg_name = arg_name + "_t"
|
||||
new_args.append(arg_name)
|
||||
|
||||
# Call into the forward again. We need two cases here to handle both Tensor methods and at:: functions.
|
||||
if Variant.function in f.variants:
|
||||
fw_formula = "at::{}({})".format(defn_name, ", ".join(new_args))
|
||||
else:
|
||||
assert Variant.method in f.variants
|
||||
fw_formula = "{}.{}({})".format(new_args[0], defn_name, ", ".join(new_args[1:]))
|
||||
|
||||
# All of the input tangents are always used so all of them are required here.
|
||||
required_inputs_tangent = tuple(diff_arg_names)
|
||||
formula = fw_formula
|
||||
|
||||
# At this point, the formula is final and is not modified anymore.
|
||||
|
||||
# During forward formula, we use the primal instead of the input Tensors.
|
||||
# This call inspects the formula to find for which input's primal are used.
|
||||
required_inputs_primal = find_required_inputs(formula, "_p")
|
||||
|
||||
updated_derivatives.append(ForwardDerivative(
|
||||
formula=formula,
|
||||
var_name=defn.var_name,
|
||||
var_type=defn.var_type,
|
||||
required_inputs_fw_grad=required_inputs_tangent,
|
||||
required_inputs_primal=required_inputs_primal,
|
||||
required_original_self_value=False,
|
||||
is_reusing_outplace_formula=False))
|
||||
|
||||
return updated_derivatives
|
||||
|
||||
|
||||
def is_forward_derivative_definition(all_arg_names: List[str], names: Tuple[str, ...]) -> bool:
|
||||
if len(names) > 1:
|
||||
# Forward definition are always for a single output at a time
|
||||
return False
|
||||
name = names[0]
|
||||
if name not in all_arg_names:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def create_differentiability_info(
|
||||
defn: Dict[Any, Any],
|
||||
functions_by_signature: Dict[FunctionSchema, List[NativeFunction]],
|
||||
functions_by_schema: Dict[str, NativeFunction],
|
||||
op_counter: Counter[str],
|
||||
) -> DifferentiabilityInfo:
|
||||
"""Processes a single entry `defn` in derivatives.yaml"""
|
||||
|
||||
def canonical_function(functions: Sequence[NativeFunction], name: str) -> NativeFunction:
|
||||
for f in functions:
|
||||
if cpp.name(f.func) == name:
|
||||
return f
|
||||
# some functions only have in-place variants
|
||||
assert name + '_' == cpp.name(functions[0].func)
|
||||
return functions[0]
|
||||
|
||||
def split_names(raw_names: str) -> Tuple[str, ...]:
|
||||
"""Given "foo, bar", return ["foo", "bar"]."""
|
||||
return tuple(x.strip() for x in raw_names.split(','))
|
||||
|
||||
def check_grad_usage(defn_name: str, derivatives: Sequence[Derivative]) -> None:
|
||||
"""
|
||||
Check for some subtle mistakes one might make when writing derivatives.
|
||||
These mistakes will compile, but will be latent until a function is
|
||||
used with double backwards.
|
||||
"""
|
||||
|
||||
uses_grad = False # true if any derivative uses "grad"
|
||||
num_grads_uses = 0 # count of uses of "grads" or "grads[INDEX]"
|
||||
uses_named_grads = False # true if any derivative uses "grad_{name}"
|
||||
used_grads_indices: List[int] = [] # which indices of grads are used
|
||||
for d in derivatives:
|
||||
formula = d.formula
|
||||
uses_grad = uses_grad or bool(re.findall(IDENT_REGEX.format('grad'), formula))
|
||||
num_grads_uses += len(re.findall(IDENT_REGEX.format('grads'), formula))
|
||||
uses_named_grads = uses_named_grads or bool(d.named_gradients)
|
||||
used_grads_indices.extend(used_gradient_indices(formula))
|
||||
# This is a basic sanity check: the number of places we see
|
||||
# "grads" should be no fewer than the number of indices we see
|
||||
# inside "grads". They may not be equal because we may use
|
||||
# "grads" without an index.
|
||||
assert num_grads_uses >= len(used_grads_indices)
|
||||
# Thus if the number is equal, every use of grads is also
|
||||
# indexed.
|
||||
only_used_grads_indices = num_grads_uses == len(used_grads_indices)
|
||||
|
||||
if uses_grad and num_grads_uses > 0:
|
||||
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml illegally "
|
||||
"mixes use of 'grad' and 'grads'. Consider replacing "
|
||||
"occurrences of 'grad' with 'grads[0]'")
|
||||
|
||||
if only_used_grads_indices and set(used_grads_indices) == {0}:
|
||||
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml solely "
|
||||
"refers to 'grads[0]'. If the first output is indeed the "
|
||||
"only differentiable output, replace 'grads[0]' with 'grad'; "
|
||||
"otherwise, there is a likely error in your derivatives "
|
||||
"declaration.")
|
||||
|
||||
if uses_named_grads and (uses_grad or num_grads_uses > 0):
|
||||
raise RuntimeError(
|
||||
f'Derivative definition of {defn_name} in derivatives.yaml illegally '
|
||||
'mixes use of "grad_RETURN_NAME" and "grad" or "grads[x]". Use '
|
||||
'only one method for identifying gradients.')
|
||||
|
||||
|
||||
@with_native_function
|
||||
def set_up_derivatives(f: NativeFunction) -> Tuple[
|
||||
Sequence[Derivative],
|
||||
Sequence[ForwardDerivative],
|
||||
Sequence[Binding],
|
||||
Sequence[str],
|
||||
Sequence[str],
|
||||
]:
|
||||
# Set up the derivative information
|
||||
derivatives: List[Derivative] = []
|
||||
forward_derivatives: List[ForwardDerivative] = []
|
||||
non_differentiable_arg_names: List[str] = []
|
||||
args_with_derivatives_set: Set[str] = set()
|
||||
|
||||
all_arg_names = [a.name for a in cpp_arguments(f)]
|
||||
|
||||
# output_differentiability is captured from the enclosed
|
||||
# scope. Don't modify it.
|
||||
#
|
||||
# If it is not present, then no output is explicitly
|
||||
# undifferentiable.
|
||||
#
|
||||
# It may be present and shorter than the length of return
|
||||
# values. If that's the case, any return value that does not
|
||||
# have a corresponding entry is considered not differentiable.
|
||||
differentiability = output_differentiability or [True] * len(f.func.returns)
|
||||
# A return is available as a named gradient ...
|
||||
available_named_gradients = [
|
||||
f'grad_{ret.name}' for ret, differentiable in zip(f.func.returns, differentiability)
|
||||
# if it has not been explicitly made undifferentiable
|
||||
if differentiable
|
||||
# and if it has a name
|
||||
and ret.name is not None
|
||||
# and if its type is differentiable
|
||||
and ret.type.is_tensor_like()]
|
||||
|
||||
for raw_names in sorted(defn.keys()):
|
||||
formula = defn[raw_names]
|
||||
names = split_names(raw_names)
|
||||
|
||||
if is_forward_derivative_definition(all_arg_names, names):
|
||||
forward_derivatives.append(create_forward_derivative(f, formula, names))
|
||||
else:
|
||||
if formula.lower().strip() == 'non_differentiable':
|
||||
non_differentiable_arg_names += names
|
||||
else:
|
||||
derivative = create_derivative(f, formula, names,
|
||||
available_named_gradients)
|
||||
derivatives.append(derivative)
|
||||
args_with_derivatives_set |= set(names)
|
||||
|
||||
overlap = args_with_derivatives_set.intersection(non_differentiable_arg_names)
|
||||
if overlap:
|
||||
raise RuntimeError(f'derivatives definition for {defn} have overlapped non_differentiable '
|
||||
f'and differentiable variables: {overlap}')
|
||||
|
||||
# Next, let us determine the list of inputs in order.
|
||||
# TODO: do we need eagerly calculate and save it here? Can it be derived
|
||||
# from NativeFunction and `derivatives` on callsites instead?
|
||||
args_with_derivatives = [a for a in cpp_arguments(f) if a.name in args_with_derivatives_set]
|
||||
|
||||
# Postprocess forward derivatives definitions now that we know the differentiable arguments
|
||||
forward_derivatives = postprocess_forward_derivatives(f, defn_name, all_arg_names, derivatives,
|
||||
forward_derivatives, args_with_derivatives)
|
||||
|
||||
# Test to see if the use of 'grads' makes sense.
|
||||
check_grad_usage(defn_name, derivatives)
|
||||
|
||||
return (derivatives, forward_derivatives, args_with_derivatives,
|
||||
non_differentiable_arg_names, available_named_gradients)
|
||||
|
||||
# NB: Removes 'name' from defn dictionary
|
||||
specification = defn.pop('name')
|
||||
defn_name, _ = split_name_params(specification)
|
||||
# NB: Removes 'output_differentiability' from defn dictionary
|
||||
# `None` means all differentiable.
|
||||
output_differentiability = defn.pop('output_differentiability', None)
|
||||
output_differentiability_conditions = None
|
||||
if output_differentiability and any([isinstance(diff, str) for diff in output_differentiability]):
|
||||
if len(output_differentiability) != 1:
|
||||
raise RuntimeError(f'Not supported: for {specification},'
|
||||
f'output_differentiability must either be '
|
||||
f'List[bool] or a List[str] where each str is a '
|
||||
f'condition. In the case where it is a condition, '
|
||||
f'we only support single-output functions. '
|
||||
f'Please file us an issue. ')
|
||||
output_differentiability_conditions = output_differentiability
|
||||
output_differentiability = [True]
|
||||
|
||||
schema_function = functions_by_schema.get(specification)
|
||||
if not schema_function:
|
||||
avail = '\n'.join(k for k, v in functions_by_schema.items() if cpp.name(v.func) == defn_name)
|
||||
raise RuntimeError(f'could not find ATen function for schema: {specification} '
|
||||
f'. Available signatures:\n{avail}')
|
||||
|
||||
# now map this to the legacy schema; this isn't technically necessary, but we'd need some logic here
|
||||
# to map in-place schemas to the out-of-place variants.
|
||||
# TODO: maybe the logic to handle the legacy schema is no longer necessary?
|
||||
signature = schema_function.func.signature()
|
||||
functions = functions_by_signature[signature]
|
||||
if len(functions) == 0:
|
||||
avail = '\n'.join(str(k) for k, v in functions_by_signature.items() if cpp.name(k) == defn_name)
|
||||
raise RuntimeError(f'could not find ATen function for legacy signature: {signature} '
|
||||
f'corresponding to schema {specification}. Please report a bug to PyTorch. '
|
||||
f'Available signatures:\n{avail}')
|
||||
|
||||
canonical = canonical_function(functions, defn_name)
|
||||
if 'grad_input_mask' in (a.name for a in cpp_arguments(canonical)):
|
||||
raise RuntimeError(f"Schema for {defn_name} has an argument named grad_input_mask, "
|
||||
"but this name would be shadowed by our codegen. "
|
||||
"Please use a different name in native_functions.yaml.")
|
||||
|
||||
if 'result' in (a.name for a in cpp_arguments(canonical)):
|
||||
raise RuntimeError(f"Schema for {defn_name} has an argument named result, "
|
||||
"but this is only allowed for outputs."
|
||||
"Please use a different name in native_functions.yaml.")
|
||||
|
||||
(derivatives, forward_derivatives, args_with_derivatives,
|
||||
non_differentiable_arg_names, available_named_gradients) = set_up_derivatives(canonical)
|
||||
|
||||
used_named_gradients: Set[str] = set()
|
||||
for d in derivatives:
|
||||
used_named_gradients |= d.named_gradients
|
||||
|
||||
# only assign an op name if we are actually going to calculate a derivative
|
||||
op = None
|
||||
if args_with_derivatives:
|
||||
op_prefix = _create_op_prefix(defn_name)
|
||||
op = f'{op_prefix}{op_counter[op_prefix]}'
|
||||
op_counter[op_prefix] += 1
|
||||
|
||||
return DifferentiabilityInfo(
|
||||
name=defn_name,
|
||||
func=canonical,
|
||||
op=op,
|
||||
derivatives=derivatives,
|
||||
forward_derivatives=forward_derivatives,
|
||||
all_saved_inputs=dedup_vars([v for d in derivatives for v in d.saved_inputs]),
|
||||
all_saved_outputs=dedup_vars([v for d in derivatives for v in d.saved_outputs]),
|
||||
available_named_gradients=available_named_gradients,
|
||||
used_named_gradients=used_named_gradients,
|
||||
args_with_derivatives=args_with_derivatives,
|
||||
non_differentiable_arg_names=non_differentiable_arg_names,
|
||||
output_differentiability=output_differentiability,
|
||||
output_differentiability_conditions=output_differentiability_conditions,
|
||||
)
|
||||
|
||||
|
||||
GRAD_INDEX_REGEX = r'(?:^|\W)grads\[(\d+)\]'
|
||||
|
||||
|
||||
def used_gradient_indices(formula: str) -> List[int]:
|
||||
"""Determine a list of gradient indices (the i in grads[i]) that
|
||||
are used by the formula.
|
||||
|
||||
>>> used_gradient_indices("foo(grads[0], grads[1])")
|
||||
[0, 1]
|
||||
"""
|
||||
return [int(i) for i in re.findall(GRAD_INDEX_REGEX, formula)]
|
||||
|
||||
def saved_variables(
|
||||
formula: str,
|
||||
nctypes: List[NamedCType],
|
||||
var_names: Tuple[str, ...],
|
||||
) -> Tuple[str, Tuple[SavedAttribute, ...]]:
|
||||
|
||||
def stride_expr(name: str) -> str:
|
||||
assert var_names == (name,), (
|
||||
'Replacement for ".strides()" is currently only supported for single derivatives of the same tensor '
|
||||
'that ".strides()" is being called on.')
|
||||
return f'strides_or_error({name}, "{name}")'
|
||||
|
||||
REPLACEMENTS: List[Tuple[str, Dict[str, Any]]] = [
|
||||
# replace self.sizes() with self_sizes
|
||||
(r'{}.sizes\(\)', {
|
||||
'suffix': '_sizes',
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(intArrayRefT)),
|
||||
}),
|
||||
# replace self->sizes() with self_sizes_opt
|
||||
(r'{}->sizes\(\)', {
|
||||
'suffix': '_sizes_opt',
|
||||
'nctype': lambda name: NamedCType(name, OptionalCType(BaseCType(intArrayRefT))),
|
||||
'expr': lambda name: f'{name}.has_value() ? c10::optional<IntArrayRef>({name}->sizes()) : c10::nullopt',
|
||||
}),
|
||||
# replace self.options() with self_options
|
||||
(r'{}.options\(\)', {
|
||||
'suffix': '_options',
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(tensorOptionsT)),
|
||||
}),
|
||||
# replace zeros_like(self) with self_info
|
||||
(r'zeros_like\({}\)', {
|
||||
'suffix': '_info',
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(typeAndSizeT)),
|
||||
'expr': lambda name: name, # at save-time
|
||||
'res': lambda name: name + '_info.zeros()', # at eval-time
|
||||
}),
|
||||
# replace self.size(2) with self_size_2
|
||||
(r'{}.size\((\w+)\)', {
|
||||
'suffix': lambda m: '_argsize_{}'.format(*m.groups()),
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(longT)),
|
||||
}),
|
||||
# replace self.numel() with self_numel
|
||||
(r'{}.numel\(\)', {
|
||||
'suffix': '_numel',
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(longT)),
|
||||
}),
|
||||
# replace to_args_sizes(self) with self_args_sizes
|
||||
(r'to_args_sizes\({}\)', {
|
||||
'suffix': '_args_sizes',
|
||||
'nctype': lambda name: NamedCType(name, VectorCType(VectorCType(BaseCType(longT)))),
|
||||
}),
|
||||
# replace to_args_scalartypes(self) with self_args_scalartypes
|
||||
(r'to_args_scalartypes\({}\)', {
|
||||
'suffix': '_args_scalartypes',
|
||||
'nctype': lambda name: NamedCType(name, VectorCType(BaseCType(scalarTypeT))),
|
||||
}),
|
||||
# replace TensorGeometry(self) with self_geometry
|
||||
(r'TensorGeometry\({}\)', {
|
||||
'suffix': '_geometry',
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(tensorGeometryT)),
|
||||
}),
|
||||
(r'{}.scalar_type\(\)', {
|
||||
'suffix': '_scalar_type',
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(scalarTypeT)),
|
||||
}),
|
||||
# replace self.dim() with self_dim
|
||||
(r'{}.dim\(\)', {
|
||||
'suffix': '_dim',
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(longT)),
|
||||
}),
|
||||
# replace self.strides() with self_strides
|
||||
(r'{}.strides\(\)', {
|
||||
'suffix': '_strides',
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(intArrayRefT)),
|
||||
'expr': stride_expr,
|
||||
}),
|
||||
# replace self.is_conj() with self_conjugate
|
||||
(r'{}.is_conj\(\)', {
|
||||
'suffix': '_conjugate',
|
||||
'nctype': lambda name: NamedCType(name, BaseCType(boolT)),
|
||||
})
|
||||
]
|
||||
|
||||
# find which arguments need to be saved
|
||||
saved: List[SavedAttribute] = []
|
||||
|
||||
for nctype in nctypes:
|
||||
name = nctype.name.name if isinstance(nctype.name, SpecialArgName) else nctype.name
|
||||
# First search the formula for expressions which can be evaluated
|
||||
# when the autograd Function is created to avoid saving variables
|
||||
for regex, info in REPLACEMENTS:
|
||||
def repl(m: Match[str]) -> str:
|
||||
suffix: str = info['suffix'](m) if callable(info['suffix']) else info['suffix']
|
||||
expr: str = info['expr'](name) if 'expr' in info else m.group(0)
|
||||
saved.append(SavedAttribute(
|
||||
nctype=info['nctype'](name + suffix),
|
||||
expr=expr,
|
||||
))
|
||||
if 'res' in info:
|
||||
replacement: str = info['res'](name)
|
||||
return replacement
|
||||
return name + suffix
|
||||
|
||||
formula = re.sub(regex.format(name), repl, formula)
|
||||
|
||||
# c10::optional<std::string> types stored in Backward nodes must be
|
||||
# converted to c10::optional<c10::string_view> before being passed into
|
||||
# the backward function
|
||||
if nctype.type == OptionalCType(BaseCType(stringT)):
|
||||
formula = re.sub(
|
||||
rf'\b{name}\b',
|
||||
f'{name}.has_value() ? c10::optional<c10::string_view>({name}.value()) : c10::nullopt',
|
||||
formula)
|
||||
|
||||
# Find any variables which remain in the formula and save them
|
||||
if re.search(IDENT_REGEX.format(name), formula):
|
||||
saved.append(SavedAttribute(
|
||||
nctype=nctype,
|
||||
expr=name,
|
||||
))
|
||||
|
||||
return formula, tuple(saved)
|
||||
|
||||
|
||||
def _create_op_prefix(name: str) -> str:
|
||||
"""Takes a native function name converts to a op prefix name.
|
||||
|
||||
Note that the "name" parameter must be the native function name
|
||||
without the optional variant suffix, so "add" instead of
|
||||
"add.out".
|
||||
|
||||
OP names correspond to classes, hence the change to title case.
|
||||
|
||||
Example::
|
||||
>>> _create_op_prefix('add')
|
||||
'AddBackward'
|
||||
"""
|
||||
camel_case = ''.join([p.title() for p in name.split('_')])
|
||||
return (camel_case + 'Backward').replace('ForwardBackward', 'Backward')
|
||||
|
||||
|
||||
def dedup_vars(variables: Sequence[SavedAttribute]) -> Sequence[SavedAttribute]:
|
||||
seen: Set[str] = set()
|
||||
saved: List[SavedAttribute] = []
|
||||
for var in variables:
|
||||
name = var.nctype.name.name if isinstance(var.nctype.name, SpecialArgName) else var.nctype.name
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
saved.append(var)
|
||||
return saved
|
||||
@@ -0,0 +1,51 @@
|
||||
// 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.
|
||||
|
||||
#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
|
||||
#include <torch/csrc/autograd/VariableTypeUtils.h>
|
||||
|
||||
#include <torch/library.h>
|
||||
|
||||
// ${generated_comment}
|
||||
|
||||
#ifndef AT_PER_OPERATOR_HEADERS
|
||||
#include <ATen/Operators.h>
|
||||
#else
|
||||
$ops_headers
|
||||
#endif
|
||||
|
||||
using namespace at;
|
||||
using torch::autograd::CreationMeta;
|
||||
using torch::autograd::as_view;
|
||||
using torch::autograd::increment_version;
|
||||
|
||||
namespace at_npu {
|
||||
|
||||
namespace ADInplaceOrView {
|
||||
|
||||
namespace {
|
||||
${inplace_or_view_method_definitions}
|
||||
} // namespace
|
||||
} // namespace ADInplaceOrView
|
||||
|
||||
namespace {
|
||||
|
||||
TORCH_LIBRARY_IMPL(aten, ADInplaceOrView, m) {
|
||||
${inplace_or_view_wrapper_registrations}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace at_npu
|
||||
@@ -0,0 +1,35 @@
|
||||
// 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.
|
||||
|
||||
#include "torch_npu/csrc/framework/autograd/FunctionsManual.h"
|
||||
|
||||
// ${generated_comment}
|
||||
|
||||
// The manual function definitions that used to be here are now in torch/csrc/autograd/FunctionsManual.cpp
|
||||
// This speeds up re-compilation and allow to share these implementations so that they can be
|
||||
// used for forward mode AD formulas as well.
|
||||
|
||||
using namespace at_npu::autograd::generated::details;
|
||||
using at::Tensor;
|
||||
using at::Scalar;
|
||||
using at::IntArrayRef;
|
||||
using at::TensorList;
|
||||
|
||||
namespace at_npu { namespace autograd { namespace generated {
|
||||
|
||||
${autograd_function_definitions}
|
||||
|
||||
}}} // namespace at_npu::autograd::generated
|
||||
@@ -0,0 +1,77 @@
|
||||
// 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
|
||||
|
||||
// ${generated_comment}
|
||||
|
||||
#include <ATen/ATen.h>
|
||||
#include <ATen/core/functional.h>
|
||||
#include <ATen/TensorGeometry.h>
|
||||
|
||||
#include <torch/csrc/autograd/function.h>
|
||||
#include <torch/csrc/autograd/variable.h>
|
||||
#include <torch/csrc/autograd/saved_variable.h>
|
||||
#include <torch/csrc/Export.h>
|
||||
|
||||
using namespace torch::autograd;
|
||||
|
||||
namespace at_npu { namespace autograd { namespace generated {
|
||||
|
||||
using at::Scalar;
|
||||
using at::Tensor;
|
||||
using at::IntArrayRef;
|
||||
using at::ArrayRef;
|
||||
using at::Type;
|
||||
using at::TensorGeometry;
|
||||
using at::ScalarType;
|
||||
using c10::optional;
|
||||
using c10::fmap;
|
||||
|
||||
inline std::vector<Tensor> unpack_list(at::ArrayRef<SavedVariable> xs) {
|
||||
// NB: we must explicitly do the conversion in the lambda, otherwise template
|
||||
// deduction will give a Tensor of Variable which is not convertible
|
||||
return fmap(xs, [](const SavedVariable& x) {
|
||||
return static_cast<Tensor>(x.unpack());
|
||||
});
|
||||
}
|
||||
|
||||
inline c10::List<c10::optional<Tensor>> unpack_opt_list(at::ArrayRef<SavedVariable> xs) {
|
||||
torch::List<c10::optional<Tensor>> result;
|
||||
result.reserve(xs.size());
|
||||
for (const SavedVariable& v : xs) {
|
||||
result.push_back(v.unpack());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
struct TypeAndSize {
|
||||
TypeAndSize() : options(at::TensorOptions()) {}
|
||||
/* implicit */
|
||||
TypeAndSize(const Tensor & t)
|
||||
: sizes(t.sizes().vec())
|
||||
, options(t.options()) {}
|
||||
|
||||
Tensor zeros() { return at::zeros(sizes, options); }
|
||||
|
||||
private:
|
||||
std::vector<int64_t> sizes;
|
||||
at::TensorOptions options;
|
||||
};
|
||||
|
||||
${autograd_function_declarations}
|
||||
|
||||
}}} // namespace at_npu::autograd::generated
|
||||
@@ -0,0 +1,78 @@
|
||||
// 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.
|
||||
|
||||
#include <torch/csrc/autograd/VariableTypeUtils.h>
|
||||
|
||||
#include <ATen/RedispatchFunctions.h>
|
||||
#include <torch/library.h>
|
||||
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/VariableType.h"
|
||||
#include "torch_npu/csrc/framework/autograd/FunctionsManual.h"
|
||||
|
||||
|
||||
// ${generated_comment}
|
||||
|
||||
// NOTE [Sharded File]: on this file's split-into-shards state
|
||||
//
|
||||
// Back in the good old days, VariableType.cpp was generated as one
|
||||
// file with every function in it, and everything was great and
|
||||
// simple.
|
||||
//
|
||||
// However, this file was also very large (over 36,000 lines), and
|
||||
// compiling it was very slow, and in fact was a significant
|
||||
// bottleneck for incremental rebuilds. To address this, we now
|
||||
// generate the file split across multiple shards, named
|
||||
// VariableType_0.cpp and so on, which can be compiled in parallel.
|
||||
//
|
||||
// For ease of inspection and debugging, so that it's not necessary to
|
||||
// go rooting around in multiple files, we also generate all the
|
||||
// functions together in VariableTypeEverything.cpp. This generated
|
||||
// file is only for convenience; it's not actually used in the
|
||||
// build. If the file you're looking at now is one of the shards, you
|
||||
// may want to switch over to the Everything variant to make you
|
||||
// grepping smoother.
|
||||
|
||||
using namespace at;
|
||||
using namespace at_npu::autograd::generated;
|
||||
using namespace at_npu::autograd::generated::details;
|
||||
|
||||
namespace at_npu { namespace autograd {
|
||||
|
||||
namespace VariableType {
|
||||
namespace{
|
||||
C10_UNUSED void reset_grad_accumulator(Variable & self) {
|
||||
AutogradMeta* meta = torch::autograd::impl::get_autograd_meta(self);
|
||||
if (meta != nullptr) {
|
||||
meta->grad_accumulator_.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
${type_derived_method_definitions}
|
||||
}
|
||||
} // namespace VariableType
|
||||
|
||||
namespace {
|
||||
|
||||
TORCH_LIBRARY_IMPL(aten, AutogradXLA, m) {
|
||||
${wrapper_registrations}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}} // namespace at_npu::autograd
|
||||
@@ -0,0 +1,74 @@
|
||||
// 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
|
||||
|
||||
// ${generated_comment}
|
||||
|
||||
#include <cstdint> // for size_t
|
||||
#include <functional> // for function
|
||||
#include <memory> // for unique_ptr
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <ATen/core/Tensor.h>
|
||||
#include <ATen/Context.h>
|
||||
|
||||
#include <c10/util/intrusive_ptr.h>
|
||||
|
||||
#include <torch/csrc/Export.h>
|
||||
#include <torch/csrc/autograd/autograd_not_implemented_fallback.h>
|
||||
|
||||
namespace at {
|
||||
struct Quantizer;
|
||||
};
|
||||
|
||||
namespace at_npu { namespace autograd {
|
||||
|
||||
using Variable = at::Tensor;
|
||||
using at::Context;
|
||||
using at::Device;
|
||||
using at::Dimname;
|
||||
using at::DimnameList;
|
||||
using at::Generator;
|
||||
using at::IntArrayRef;
|
||||
using at::MemoryFormat;
|
||||
using at::QScheme;
|
||||
using at::Scalar;
|
||||
using at::ScalarType;
|
||||
using at::Storage;
|
||||
using at::Tensor;
|
||||
using at::TensorList;
|
||||
using at::TensorOptions;
|
||||
using at::Quantizer;
|
||||
// This is temporary typedef to enable Quantizer in aten native function API
|
||||
// we'll remove them when we are actually exposing Quantizer class
|
||||
// to frontend
|
||||
using ConstQuantizerPtr = const c10::intrusive_ptr<Quantizer>&;
|
||||
using c10::optional;
|
||||
|
||||
namespace VariableType {
|
||||
TORCH_API std::vector<at::DeprecatedTypeProperties*> allCPUTypes();
|
||||
|
||||
at::Tensor & unpack(Tensor & t, const char * name, int pos);
|
||||
const at::Tensor & unpack(const Tensor & t, const char * name, int pos);
|
||||
at::Tensor unpack_opt(const Tensor & t, const char * name, int pos);
|
||||
std::vector<at::Tensor> unpack(at::TensorList tl, const char *name, int pos);
|
||||
|
||||
${npu_variable_type}
|
||||
};
|
||||
|
||||
}} // namespace at_npu::autograd
|
||||
@@ -0,0 +1,76 @@
|
||||
// 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.
|
||||
|
||||
#include <torch/csrc/autograd/VariableTypeUtils.h>
|
||||
|
||||
#include <ATen/RedispatchFunctions.h>
|
||||
#include <torch/library.h>
|
||||
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/VariableType.h"
|
||||
#include "torch_npu/csrc/framework/autograd/FunctionsManual.h"
|
||||
|
||||
|
||||
// ${generated_comment}
|
||||
|
||||
// NOTE [Sharded File]: on this file's split-into-shards state
|
||||
//
|
||||
// Back in the good old days, VariableType.cpp was generated as one
|
||||
// file with every function in it, and everything was great and
|
||||
// simple.
|
||||
//
|
||||
// However, this file was also very large (over 36,000 lines), and
|
||||
// compiling it was very slow, and in fact was a significant
|
||||
// bottleneck for incremental rebuilds. To address this, we now
|
||||
// generate the file split across multiple shards, named
|
||||
// VariableType_0.cpp and so on, which can be compiled in parallel.
|
||||
//
|
||||
// For ease of inspection and debugging, so that it's not necessary to
|
||||
// go rooting around in multiple files, we also generate all the
|
||||
// functions together in VariableTypeEverything.cpp. This generated
|
||||
// file is only for convenience; it's not actually used in the
|
||||
// build. If the file you're looking at now is one of the shards, you
|
||||
// may want to switch over to the Everything variant to make you
|
||||
// grepping smoother.
|
||||
|
||||
using namespace at;
|
||||
using namespace at_npu::autograd::generated;
|
||||
using namespace at_npu::autograd::generated::details;
|
||||
|
||||
namespace at_npu { namespace autograd {
|
||||
|
||||
namespace VariableType {
|
||||
namespace{
|
||||
C10_UNUSED void reset_grad_accumulator(Variable & self) {
|
||||
AutogradMeta* meta = torch::autograd::impl::get_autograd_meta(self);
|
||||
if (meta != nullptr) {
|
||||
meta->grad_accumulator_.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
${npu_method_definitions}
|
||||
} // namespace VariableType
|
||||
|
||||
namespace {
|
||||
|
||||
TORCH_LIBRARY_IMPL(aten, AutogradXLA, m) {
|
||||
${wrapper_registrations}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}} // namespace at_npu::autograd
|
||||
@@ -0,0 +1,150 @@
|
||||
// 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
|
||||
|
||||
// ${generated_comment}
|
||||
|
||||
#include <functional>
|
||||
#include <initializer_list>
|
||||
#include <utility>
|
||||
|
||||
#include <ATen/core/Tensor.h>
|
||||
#include <ATen/TracerMode.h>
|
||||
#include <ATen/core/grad_mode.h>
|
||||
#include <c10/util/ArrayRef.h>
|
||||
#include <c10/core/MemoryFormat.h>
|
||||
#include <torch/csrc/api/include/torch/detail/TensorDataContainer.h>
|
||||
#include <torch/csrc/autograd/variable.h>
|
||||
|
||||
#ifndef AT_PER_OPERATOR_HEADERS
|
||||
#include <ATen/Functions.h>
|
||||
#else
|
||||
#include <ATen/ops/from_blob.h>
|
||||
$ops_headers
|
||||
#endif
|
||||
|
||||
using namespace torch;
|
||||
|
||||
namespace at_npu {
|
||||
|
||||
/// NOTE: Currently `torch::tensor(...)` doesn't support mixed data types
|
||||
/// (i.e. `torch::tensor({{bool, 2.0}})` doesn't work). We might be able to
|
||||
/// support it in the future by iterating over all sub-lists to find
|
||||
/// the largest data type that can represent all of the elements, or by using
|
||||
/// variadic templates.
|
||||
/// NOTE: C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / `std::vector` /
|
||||
/// (nested) braced-init-list of floating-point types always produces a tensor of dtype
|
||||
/// `torch::get_default_dtype()`, matching Python `torch.tensor` behavior.
|
||||
/// NOTE: C++ `torch::tensor` with an integer type or an `at::ArrayRef` / `std::vector` /
|
||||
/// (nested) braced-init-list of integer types always produces a tensor of dtype `at::kLong`
|
||||
/// (aka. int64_t), matching Python `torch.tensor` behavior.
|
||||
/// NOTE: The following dtypes are not supported by `torch::tensor` currently:
|
||||
/// - `unsigned int`
|
||||
/// - `unsigned long int`
|
||||
/// - `unsigned long long int`
|
||||
/// - `long long int`
|
||||
inline at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const at::TensorOptions& options = {}) {
|
||||
return autograd::make_variable(
|
||||
// note: we remove the requires_grad setting from the TensorOptions because
|
||||
// it is ignored anyways (and we actually have an assertion that it isn't set
|
||||
// which would fail otherwise). We handle requires_grad explicitly here
|
||||
// instead of passing it through to the kernel.
|
||||
tensor_data_container.convert_to_tensor(options.requires_grad(c10::nullopt)),
|
||||
options.requires_grad());
|
||||
}
|
||||
|
||||
/// A generic deleter function.
|
||||
using Deleter = std::function<void(void*)>;
|
||||
using at::MemoryFormat;
|
||||
|
||||
/// Exposes the given `data` as a `Tensor` without taking ownership of the
|
||||
/// original data. `sizes` should specify the shape of the tensor, `strides` the
|
||||
/// stride in each dimension. The `deleter` function (a
|
||||
/// `std::function<void(void*)>`) will be called on the `data` when the Tensor
|
||||
/// data would normally be deallocated. The `TensorOptions` specify additional
|
||||
/// configuration options for the returned tensor, such as what type to
|
||||
/// interpret the `data` as.
|
||||
inline at::Tensor from_blob(
|
||||
void* data,
|
||||
at::IntArrayRef sizes,
|
||||
at::IntArrayRef strides,
|
||||
const Deleter& deleter,
|
||||
const at::TensorOptions& options = at::TensorOptions()) {
|
||||
at::Tensor tensor = ([&]() {
|
||||
at::AutoDispatchBelowAutograd guard;
|
||||
at::tracer::impl::NoTracerDispatchMode tracer_guard;
|
||||
return at::from_blob(data, sizes, strides, deleter, options.requires_grad(c10::nullopt));
|
||||
})();
|
||||
return autograd::make_variable(tensor, options.requires_grad());
|
||||
}
|
||||
|
||||
/// Exposes the given `data` as a `Tensor` without taking ownership of the
|
||||
/// original data. `sizes` should specify the shape of the tensor, `strides` the
|
||||
/// stride in each dimension. The `TensorOptions`
|
||||
/// specify additional configuration options for the returned tensor, such as
|
||||
/// what type to interpret the `data` as.
|
||||
inline at::Tensor from_blob(
|
||||
void* data,
|
||||
at::IntArrayRef sizes,
|
||||
at::IntArrayRef strides,
|
||||
const at::TensorOptions& options = at::TensorOptions()) {
|
||||
at::Tensor tensor = ([&]() {
|
||||
at::AutoDispatchBelowAutograd guard;
|
||||
at::tracer::impl::NoTracerDispatchMode tracer_guard;
|
||||
return at::from_blob(data, sizes, strides, options.requires_grad(c10::nullopt));
|
||||
})();
|
||||
return autograd::make_variable(tensor, options.requires_grad());
|
||||
}
|
||||
|
||||
/// Exposes the given `data` as a `Tensor` without taking ownership of the
|
||||
/// original data. `sizes` should specify the shape of the tensor. The `deleter`
|
||||
/// (a `std::function<void(void*)>`) function will be called on the `data` when
|
||||
/// the Tensor data would normally be deallocated. The `TensorOptions` specify
|
||||
/// additional configuration options for the returned tensor, such as what type
|
||||
/// to interpret the `data` as.
|
||||
inline at::Tensor from_blob(
|
||||
void* data,
|
||||
at::IntArrayRef sizes,
|
||||
const Deleter& deleter,
|
||||
const at::TensorOptions& options = at::TensorOptions()) {
|
||||
at::Tensor tensor = ([&]() {
|
||||
at::AutoDispatchBelowAutograd guard;
|
||||
at::tracer::impl::NoTracerDispatchMode tracer_guard;
|
||||
return at::from_blob(data, sizes, deleter, options.requires_grad(c10::nullopt));
|
||||
})();
|
||||
return autograd::make_variable(tensor, options.requires_grad());
|
||||
}
|
||||
|
||||
/// Exposes the given `data` as a `Tensor` without taking ownership of the
|
||||
/// original data. `sizes` should specify the shape of the tensor. The
|
||||
/// `TensorOptions` specify additional configuration options for the returned
|
||||
/// tensor, such as what type to interpret the `data` as.
|
||||
inline at::Tensor from_blob(
|
||||
void* data,
|
||||
at::IntArrayRef sizes,
|
||||
const at::TensorOptions& options = at::TensorOptions()) {
|
||||
at::Tensor tensor = ([&]() {
|
||||
at::AutoDispatchBelowAutograd guard;
|
||||
at::tracer::impl::NoTracerDispatchMode tracer_guard;
|
||||
return at::from_blob(data, sizes, options.requires_grad(c10::nullopt));
|
||||
})();
|
||||
return autograd::make_variable(tensor, options.requires_grad());
|
||||
}
|
||||
|
||||
${function_definitions}
|
||||
|
||||
} // namespace at_npu
|
||||
@@ -0,0 +1,61 @@
|
||||
# Copyright (c) 2023 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.
|
||||
|
||||
from codegen.api import cpp
|
||||
from codegen.model import NativeFunction, SchemaKind
|
||||
|
||||
'''
|
||||
Functions in this file come from gen_trace_type.py, and will be deleted once
|
||||
we have gen_trace_type.py in torch_npu.
|
||||
'''
|
||||
|
||||
# Note: we still register to dispatch key Profiler for these ops, keeping it untouched for now.
|
||||
# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp
|
||||
MANUAL_BACKEND = set([
|
||||
'options', 'data', 'set_data', 'is_leaf', 'output_nr', '_version', 'retain_grad',
|
||||
'_backward', 'requires_grad_',
|
||||
])
|
||||
|
||||
# For these ops we want to skip the codegen-ed registration to both Autograd and Tracer keys.
|
||||
# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp
|
||||
MANUAL_AUTOGRAD_AND_TRACER = set([
|
||||
'resize_', 'resize_as_', 'detach', 'detach_', 'copy_', '_fw_primal', '_make_dual',
|
||||
])
|
||||
|
||||
|
||||
def type_wrapper_name(f: NativeFunction) -> str:
|
||||
if f.func.name.overload_name:
|
||||
return f'{cpp.name(f.func)}_{f.func.name.overload_name}'
|
||||
else:
|
||||
return cpp.name(f.func)
|
||||
|
||||
|
||||
def get_return_value(f: NativeFunction) -> str:
|
||||
names = cpp.return_names(f)
|
||||
if len(f.func.returns) == 1:
|
||||
return names[0]
|
||||
if f.func.kind() == SchemaKind.out:
|
||||
return f'std::forward_as_tuple({", ".join(names)})'
|
||||
else:
|
||||
moved = ", ".join(f'std::move({name})' for name in names)
|
||||
return f'std::make_tuple({moved})'
|
||||
|
||||
|
||||
def tie_return_values(f: NativeFunction) -> str:
|
||||
if len(f.func.returns) == 1:
|
||||
return f'auto {f.func.returns[0].name or "result"}'
|
||||
names = cpp.return_names(f)
|
||||
return f'std::tie({", ".join(names)})'
|
||||
@@ -41,43 +41,23 @@ from codegen.selective_build.selector import SelectiveBuilder
|
||||
|
||||
|
||||
def gen_create_out_helper(backend_index: BackendIndex) -> List[str]:
|
||||
if backend_index.dispatch_key == DispatchKey.Meta:
|
||||
# TODO: dedupe this with below
|
||||
core = """
|
||||
if (strides.empty()) {
|
||||
return at::empty(sizes, options.device(at::kMeta));
|
||||
} else {
|
||||
return at::empty_strided(sizes, strides, options.device(at::kMeta));
|
||||
}
|
||||
"""
|
||||
else:
|
||||
expanded_topts = "optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), " \
|
||||
"options.device_opt(), options.pinned_memory_opt()"
|
||||
empty_init = ""
|
||||
if backend_index.dispatch_key == DispatchKey.CPU:
|
||||
empty_impl = "at::native::empty_cpu"
|
||||
empty_strided_impl = "at::native::empty_strided_cpu"
|
||||
elif backend_index.dispatch_key == DispatchKey.CUDA:
|
||||
empty_init = "globalContext().lazyInitCUDA();"
|
||||
empty_impl = "at::native::empty_cuda"
|
||||
empty_strided_impl = "at::native::empty_strided_cuda"
|
||||
elif backend_index.dispatch_key == DispatchKey.CompositeExplicitAutograd:
|
||||
empty_impl = "at::empty"
|
||||
empty_strided_impl = "at::empty_strided"
|
||||
else:
|
||||
return []
|
||||
core = f"""
|
||||
{empty_init}
|
||||
if (strides.empty()) {{
|
||||
return {empty_impl}(sizes, {expanded_topts}, options.memory_format_opt());
|
||||
}} else {{
|
||||
// TODO: assert options.memory_format_opt() is nullopt (debug only?)
|
||||
return {empty_strided_impl}(sizes, strides, {expanded_topts});
|
||||
}}
|
||||
"""
|
||||
if backend_index.dispatch_key != DispatchKey.CPU:
|
||||
return []
|
||||
|
||||
empty_options = "options"
|
||||
dispatch = str(backend_index.dispatch_key).lower()
|
||||
empty_impl = f"at::detail::empty_{dispatch}"
|
||||
empty_strided_impl = f"at::detail::empty_strided_{dispatch}"
|
||||
runtime_empty_supported_check = ""
|
||||
|
||||
return [f"""
|
||||
Tensor create_out(IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {{
|
||||
{core}
|
||||
{runtime_empty_supported_check}
|
||||
if (strides.empty()) {{
|
||||
return {empty_impl}(sizes, {empty_options});
|
||||
}} else {{
|
||||
return {empty_strided_impl}(sizes, strides, {empty_options});
|
||||
}}
|
||||
}}
|
||||
"""]
|
||||
|
||||
@@ -104,6 +84,7 @@ void resize_out(const Tensor &out, IntArrayRef sizes, IntArrayRef strides, const
|
||||
}
|
||||
"""]
|
||||
|
||||
|
||||
def gen_check_inplace_helper(backend_index: BackendIndex) -> List[str]:
|
||||
return ["""
|
||||
void check_inplace(const Tensor &self, IntArrayRef sizes, const TensorOptions &options) {
|
||||
@@ -157,6 +138,7 @@ class RegisterDispatchKey:
|
||||
|
||||
target: Union[
|
||||
Literal[Target.ANONYMOUS_DEFINITION],
|
||||
Literal[Target.ANONYMOUS_DEFINITION_UNSUPPORT],
|
||||
Literal[Target.NAMESPACED_DEFINITION],
|
||||
Literal[Target.NAMESPACED_DECLARATION],
|
||||
Literal[Target.REGISTRATION]
|
||||
@@ -355,6 +337,8 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
|
||||
else:
|
||||
impl_name = f"{self.cpp_namespace}::{self.class_method_name}::{metadata.kernel}"
|
||||
|
||||
op_api_impl_name = f"{self.cpp_namespace}::NPUNativeOpApiFunctions::{metadata.kernel}"
|
||||
|
||||
args_exprs_str = ', '.join(a.name for a in args)
|
||||
|
||||
device_check = ' // No device check\n'
|
||||
@@ -394,6 +378,17 @@ torch_npu::profiler::NPURecordFunction guard;
|
||||
if device_of is not None:
|
||||
device_guard = f"const OptionalDeviceGuard device_guard(device_of({device_of}));"
|
||||
|
||||
if not f.op_api:
|
||||
op_api_impl_name = impl_name
|
||||
|
||||
return_code = f"""\
|
||||
if (c10_npu::NpuRunMode::IsGraphMode() || !at_npu::native::env::CheckForbidInternalFormat()) {{
|
||||
return {impl_name}({args_exprs_str});
|
||||
}} else {{
|
||||
return {op_api_impl_name}({args_exprs_str});
|
||||
}}
|
||||
"""
|
||||
|
||||
return f"""\
|
||||
namespace {{
|
||||
|
||||
@@ -402,7 +397,18 @@ namespace {{
|
||||
|
||||
{device_guard}
|
||||
{record_func_def}
|
||||
return {impl_name}({args_exprs_str});
|
||||
{return_code}
|
||||
}}
|
||||
|
||||
}} // anonymous namespace
|
||||
"""
|
||||
|
||||
elif self.target is Target.ANONYMOUS_DEFINITION_UNSUPPORT:
|
||||
return f"""\
|
||||
namespace {{
|
||||
|
||||
{returns_type} {name}({args_str}) {{
|
||||
TORCH_CHECK(false, "{f.func.name} is unsupported!");
|
||||
}}
|
||||
|
||||
}} // anonymous namespace
|
||||
|
||||
@@ -109,7 +109,7 @@ class RegisterDispatchKeyCPU:
|
||||
# Note: We call gen_structured() if the operator is marked structured, regardless of the backend.
|
||||
# gen_structured() has special logic to handle auto-generated kernels.
|
||||
if g.structured:
|
||||
return []
|
||||
return self.gen_structured(g)
|
||||
else:
|
||||
return list(map_maybe(lambda f: self.gen_unstructured(f, g), g.functions()))
|
||||
elif isinstance(f, NativeFunction):
|
||||
@@ -524,7 +524,7 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
|
||||
metadata = self.backend_index.get_kernel(self.g)
|
||||
assert metadata is not None
|
||||
class_name = f"structured_{metadata.kernel}_{k.name}"
|
||||
parent_class = f"{self.cpp_namespace}::structured_{metadata.kernel}"
|
||||
parent_class = f"at::native::structured_{metadata.kernel}"
|
||||
|
||||
if is_cuda_dispatch_key(self.backend_index.dispatch_key):
|
||||
device_check_args = itertools.chain(
|
||||
@@ -534,23 +534,26 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
|
||||
sig_body.append(
|
||||
RegisterDispatchKeyCPU.gen_device_check(f.device_check, list(device_check_args), sig.name()))
|
||||
|
||||
trans_to_cpu_code, args_name = transfer_args_of_wrapper_func_to_cpu(sig, f)
|
||||
sig_body.append(trans_to_cpu_code)
|
||||
|
||||
if k is SchemaKind.functional:
|
||||
sig_body.append(f"{class_name} op;")
|
||||
elif k is SchemaKind.inplace:
|
||||
sig_body.append(f"{class_name} op(self);")
|
||||
sig_body.append(f"{class_name} op(self_cpu);")
|
||||
elif k is SchemaKind.out:
|
||||
out_args_str = ', '.join(a.name for a in f.func.arguments.out)
|
||||
out_args_arr = []
|
||||
for a in f.func.arguments.out:
|
||||
out_args_arr.append(f"{a.name}_cpu")
|
||||
for arg in out_args_arr:
|
||||
if arg in args_name:
|
||||
args_name.remove(arg)
|
||||
out_args_str = ', '.join(out_args_arr)
|
||||
sig_body.append(f"{class_name} op({out_args_str});")
|
||||
|
||||
# Translate the input native arguments into structured
|
||||
# arguments for the meta call
|
||||
meta_exprs = ', '.join(
|
||||
e.expr for e in translate(
|
||||
context,
|
||||
structured.meta_arguments(self.g),
|
||||
method=False
|
||||
)
|
||||
)
|
||||
meta_exprs = ', '.join(args_name)
|
||||
|
||||
if self.g.out.precomputed:
|
||||
# If this function group has precomputed elements, the meta function
|
||||
@@ -616,14 +619,17 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
|
||||
# I didn't do it for this version
|
||||
sig_body.append(f"at::{api_name}({out_exprs});")
|
||||
elif self.backend_index.dispatch_key != DispatchKey.Meta:
|
||||
impl_exprs = ', '.join(
|
||||
e.expr for e in translate(
|
||||
context,
|
||||
structured.impl_arguments(self.g),
|
||||
method=False
|
||||
)
|
||||
)
|
||||
sig_body.append(f"op.impl({impl_exprs});")
|
||||
impl_arr = [e.expr for e in translate(context,
|
||||
structured.impl_arguments(self.g),
|
||||
method=False)]
|
||||
tmp_arr = []
|
||||
for x in impl_arr:
|
||||
if '.' not in x and x not in args_name:
|
||||
tmp_arr.append(f"{x}_cpu")
|
||||
else:
|
||||
tmp_arr.append(f"{x}")
|
||||
|
||||
sig_body.append(f"op.impl({', '.join(tmp_arr)});")
|
||||
|
||||
# Destructively return the final tensors
|
||||
# TODO: Do this in translate instead
|
||||
@@ -641,7 +647,9 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
|
||||
else:
|
||||
refs = ', '.join(a.name for a in f.func.arguments.out)
|
||||
ret_expr = f"std::forward_as_tuple({refs})"
|
||||
sig_body.append(f"return {ret_expr};")
|
||||
|
||||
ret_code = transfer_ret_of_wrapper_func_to_xla(sig, ret_expr)
|
||||
sig_body.append(f"{ret_code}")
|
||||
|
||||
sig_body_str = "\n".join(sig_body)
|
||||
|
||||
|
||||
@@ -18,14 +18,14 @@ import os
|
||||
import stat
|
||||
import functools
|
||||
import hashlib
|
||||
from typing import List, Dict, Optional, Set, Callable, Any, Union, Sequence, TypeVar, Iterable
|
||||
from typing import (List, Dict, Optional, Set, Callable, Any,
|
||||
Union, Sequence, TypeVar, Iterable)
|
||||
from collections import defaultdict
|
||||
|
||||
from codegen.code_template import CodeTemplate
|
||||
from codegen.model import (FunctionSchema, NativeFunction,
|
||||
NativeFunctionsGroup, OperatorName,
|
||||
SchemaKind, assert_never)
|
||||
|
||||
from codegen.utils import concat_map
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
@@ -91,6 +91,20 @@ ParsedYaml = namedtuple('ParsedYaml', ['native_functions', 'backend_indices'])
|
||||
def parse_native_and_custom_yaml(path: str, custom_path: str) -> ParsedYaml:
|
||||
global _GLOBAL_PARSE_NATIVE_YAML_CACHE
|
||||
if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE:
|
||||
|
||||
# Filter the custom native yaml file, and extract the functions we defined.
|
||||
from io import StringIO
|
||||
f_str = StringIO()
|
||||
with open(custom_path, 'r') as f:
|
||||
for line in f:
|
||||
if ':' not in line:
|
||||
continue
|
||||
f_str.write(line)
|
||||
|
||||
f_str.seek(0)
|
||||
custom_data = yaml.safe_load(f_str)
|
||||
custom_es = custom_data['custom'] + custom_data['custom_autograd']
|
||||
|
||||
with open(path, 'r') as f:
|
||||
es = yaml.safe_load(f)
|
||||
assert isinstance(es, list)
|
||||
@@ -98,25 +112,16 @@ def parse_native_and_custom_yaml(path: str, custom_path: str) -> ParsedYaml:
|
||||
bs: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = defaultdict(dict)
|
||||
for e in es:
|
||||
funcs = e.get('func')
|
||||
if custom_data['supported']:
|
||||
for op in custom_data['supported']:
|
||||
if op['func'] == funcs.split('(')[0]:
|
||||
op['func'] = funcs
|
||||
e.update(op)
|
||||
with context(lambda: f'in {path}:\n {funcs}'):
|
||||
func, m = NativeFunction.from_yaml(e)
|
||||
rs.append(func)
|
||||
BackendIndex.grow_index(bs, m)
|
||||
|
||||
# Filter the custom native yaml file, and extract the functions we defined.
|
||||
from io import StringIO
|
||||
f_str = StringIO()
|
||||
with open(custom_path, 'r') as f:
|
||||
for line in f:
|
||||
if line.split(':')[0] in ['backend', 'cpp_namespace', 'tocpu',
|
||||
'supported', 'autograd', 'custom', 'custom_autograd']:
|
||||
continue
|
||||
if ':' not in line:
|
||||
continue
|
||||
f_str.write(line)
|
||||
|
||||
f_str.seek(0)
|
||||
custom_es = yaml.safe_load(f_str)
|
||||
for e in custom_es:
|
||||
funcs = e.get('func')
|
||||
with context(lambda: f'in {custom_path}:\n {funcs}'):
|
||||
@@ -139,7 +144,7 @@ def parse_native_and_custom_yaml(path: str, custom_path: str) -> ParsedYaml:
|
||||
# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key.
|
||||
# Returns a Tuple of (true_backend, backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping)
|
||||
ParsedExternalYaml = namedtuple('ParsedExternalYaml', [
|
||||
'true_backend', 'backend_key', 'autograd_key', 'cpp_namespace', 'backend_indices'])
|
||||
'true_backend', 'backend_key', 'autograd_key', 'unsupport_key', 'cpp_namespace', 'backend_indices'])
|
||||
def parse_backend_yaml(
|
||||
backend_yaml_path: str,
|
||||
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
|
||||
@@ -156,7 +161,8 @@ def parse_backend_yaml(
|
||||
yaml_values = yaml.safe_load(f)
|
||||
assert isinstance(yaml_values, dict)
|
||||
|
||||
valid_keys = ['backend', 'cpp_namespace', 'tocpu', 'supported', 'autograd', 'custom', 'custom_autograd']
|
||||
valid_keys = ['backend', 'cpp_namespace', 'tocpu', 'supported', 'autograd',
|
||||
'custom', 'custom_autograd', 'unsupported']
|
||||
|
||||
yaml_backend = yaml_values.pop('backend', None)
|
||||
true_backend = 'XLA' if yaml_backend=='NPU' else yaml_backend
|
||||
@@ -184,12 +190,17 @@ def parse_backend_yaml(
|
||||
supported.append(item['func'][:item['func'].index('(')])
|
||||
except ValueError:
|
||||
raise Exception(f'Wrong format for function: {item["func"]}')
|
||||
|
||||
supported = [op['func'] if isinstance(op, Dict) else op for op in supported]
|
||||
|
||||
custom_autograd = yaml_values.pop('custom_autograd', [])
|
||||
assert isinstance(custom_autograd, list), f'expected "autograd" to be a list, but got: {custom_autograd}'
|
||||
for item in custom_autograd:
|
||||
supported_autograd.append(item['func'][:item['func'].index('(')])
|
||||
|
||||
unsupported = yaml_values.pop('unsupported', [])
|
||||
assert isinstance(unsupported, list), f'expected "unsupported" to be a list, but got: {unsupported}'
|
||||
|
||||
assert len(yaml_values.keys()) == 0, \
|
||||
f'{backend_yaml_path} contains unexpected keys: {", ".join(yaml_values.keys())}. \
|
||||
Only the following keys are supported: {", ".join(valid_keys)}'
|
||||
@@ -212,10 +223,19 @@ the behavior of autograd for some operators on your backend. However "Autograd{b
|
||||
autograd_idx = create_backend_index(supported_autograd, autograd_key, native_functions_map)
|
||||
assert autograd_key not in backend_indices
|
||||
backend_indices[autograd_key] = autograd_idx
|
||||
|
||||
unsupported_key: Optional[DispatchKey] = None
|
||||
if len(unsupported) > 0:
|
||||
with context(lambda: f'"Unsupport" is not a valid DispatchKey.'):
|
||||
unsupport_key = DispatchKey.parse('Unsupport')
|
||||
|
||||
unsupported_idx = create_backend_index(unsupported, unsupported_key, native_functions_map)
|
||||
assert unsupport_key not in backend_indices
|
||||
backend_indices[unsupported_key] = unsupported_idx
|
||||
|
||||
check_op_on_cpu_kernels(supported_tocpu, backend_indices)
|
||||
check_grouped_native_functions(backend_key, autograd_key, backend_indices, grouped_native_functions)
|
||||
return ParsedExternalYaml(true_backend, backend_key, autograd_key, cpp_namespace, backend_indices)
|
||||
return ParsedExternalYaml(true_backend, backend_key, autograd_key, unsupported_key, cpp_namespace, backend_indices)
|
||||
|
||||
|
||||
def check_op_on_cpu_kernels(
|
||||
@@ -225,7 +245,7 @@ def check_op_on_cpu_kernels(
|
||||
op_names: List[OperatorName] = list(backend_indices[DispatchKey.CPU].index.keys())
|
||||
|
||||
for op_name in op_names:
|
||||
if op_name.name.base not in expected_to_cpu:
|
||||
if str(op_name) not in expected_to_cpu:
|
||||
backend_indices[DispatchKey.CPU].index.pop(op_name, None)
|
||||
|
||||
|
||||
@@ -317,6 +337,7 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
|
||||
utils.backend = true_backend
|
||||
backend_key = parsed_backend_yaml.backend_key
|
||||
autograd_key = parsed_backend_yaml.autograd_key
|
||||
unsupport_key = parsed_backend_yaml.unsupport_key
|
||||
cpp_namespace = parsed_backend_yaml.cpp_namespace
|
||||
backend_indices = parsed_backend_yaml.backend_indices
|
||||
|
||||
@@ -337,6 +358,49 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
|
||||
'generated_comment': generated_comment,
|
||||
'cpp_namespace': cpp_namespace,
|
||||
'class_name': class_name,
|
||||
'macro': '__SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__',
|
||||
'include_npu_native_functions': '',
|
||||
'static_define': '''
|
||||
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
|
||||
''',
|
||||
# Convert to a set first to remove duplicate kernel names.
|
||||
# Backends are allowed to repeat kernel names; only generate the declaration once!
|
||||
'dispatch_declarations': list(set(concat_map(
|
||||
lambda f: dest.compute_native_function_declaration(f, backend_indices[backend_dispatch_key]),
|
||||
grouped_native_functions
|
||||
))) + list(set(concat_map(
|
||||
lambda f: dest.compute_native_function_declaration(f, backend_indices[autograd_dispatch_key]),
|
||||
grouped_native_functions
|
||||
))) if autograd_dispatch_key else list(set(concat_map(
|
||||
lambda f: dest.compute_native_function_declaration(f, backend_indices[backend_dispatch_key]),
|
||||
grouped_native_functions
|
||||
))),
|
||||
})
|
||||
|
||||
fm.write_with_template(f'{backend_dispatch_key}NativeOpApiFunctions.h',
|
||||
'DispatchKeyNativeFunctions.h', lambda: {
|
||||
'generated_comment': generated_comment,
|
||||
'cpp_namespace': cpp_namespace,
|
||||
'class_name': 'NPUNativeOpApiFunctions',
|
||||
'macro': '__SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS_OPAPI__',
|
||||
'include_npu_native_functions': '''
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
''',
|
||||
'static_define': '',
|
||||
# Convert to a set first to remove duplicate kernel names.
|
||||
# Backends are allowed to repeat kernel names; only generate the declaration once!
|
||||
'dispatch_declarations': list(set(concat_map(
|
||||
@@ -355,7 +419,12 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
|
||||
if not dispatch_key:
|
||||
continue
|
||||
|
||||
native_func_header = f'#include "torch_npu/csrc/aten/NPUNativeFunctions.h"'
|
||||
native_func_header = """
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/core/npu/NPURunMode.h"
|
||||
#include "torch_npu/csrc/framework/interface/EnvVariables.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
"""
|
||||
fm.write_with_template(f'Register{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: {
|
||||
'external_backend_headers': native_func_header,
|
||||
'namespaced_headers': '',
|
||||
@@ -393,6 +462,46 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
|
||||
grouped_native_functions
|
||||
)),
|
||||
})
|
||||
|
||||
dispatch_key = backend_dispatch_key
|
||||
native_func_header = f'#include "torch_npu/csrc/aten/NPUNativeFunctions.h"'
|
||||
fm.write_with_template(f'RegisterUnsupport{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: {
|
||||
'external_backend_headers': native_func_header,
|
||||
'namespaced_headers': '',
|
||||
'DispatchKey': dispatch_key.name.replace("NPU", true_backend),
|
||||
'dispatch_namespace': dispatch_key.lower(),
|
||||
'dispatch_helpers': dest.gen_registration_helpers(backend_indices[unsupport_key]),
|
||||
'dispatch_namespaced_definitions': list(concat_map(
|
||||
dest.RegisterDispatchKey(
|
||||
backend_indices[unsupport_key],
|
||||
Target.NAMESPACED_DEFINITION,
|
||||
selector,
|
||||
rocm=False,
|
||||
cpp_namespace=cpp_namespace,
|
||||
class_method_name=f'{backend_dispatch_key}NativeFunctions'),
|
||||
grouped_native_functions
|
||||
)),
|
||||
'dispatch_anonymous_definitions': list(concat_map(
|
||||
dest.RegisterDispatchKey(
|
||||
backend_indices[unsupport_key],
|
||||
Target.ANONYMOUS_DEFINITION_UNSUPPORT,
|
||||
selector,
|
||||
rocm=False,
|
||||
cpp_namespace=cpp_namespace,
|
||||
class_method_name=f'{backend_dispatch_key}NativeFunctions'),
|
||||
grouped_native_functions
|
||||
)),
|
||||
'dispatch_registrations': list(concat_map(
|
||||
dest.RegisterDispatchKey(
|
||||
backend_indices[unsupport_key],
|
||||
Target.REGISTRATION,
|
||||
selector,
|
||||
rocm=False,
|
||||
cpp_namespace=cpp_namespace,
|
||||
class_method_name=f'{backend_dispatch_key}NativeFunctions'),
|
||||
grouped_native_functions
|
||||
)),
|
||||
})
|
||||
|
||||
if to_cpu.upper() in {'OFF', '0', 'NO', 'FALSE', 'F', 'N'}:
|
||||
return
|
||||
|
||||
@@ -47,7 +47,7 @@ from codegen.model import (BaseOperatorName, NativeFunction,
|
||||
Type, Variant, BackendIndex,
|
||||
BackendMetadata, DispatchKey, OperatorName)
|
||||
from codegen.utils import context
|
||||
|
||||
from codegen.autograd.gen_variable_type import NPU_AUTOGRAD_FUNCTION
|
||||
|
||||
# These functions require manual Python bindings or are not exposed to Python
|
||||
_SKIP_PYTHON_BINDINGS = [
|
||||
@@ -86,6 +86,7 @@ SKIP_PYTHON_BINDINGS_SIGNATURES = []
|
||||
|
||||
DONT_RECORD_TRACE = []
|
||||
|
||||
|
||||
def should_trace(f: NativeFunction) -> bool:
|
||||
# Operations involving Storage or Type are not traceable at the moment
|
||||
if any(str(arg.type) in {'Storage', 'Type', 'ConstQuantizerPtr'}
|
||||
@@ -664,9 +665,14 @@ def emit_single_dispatch(
|
||||
init_npu_device = f"//"
|
||||
|
||||
# dispatch lambda body
|
||||
is_npu_autograd = str(f.func.name) in NPU_AUTOGRAD_FUNCTION
|
||||
record_func_define = cpp_record_func(f, custom=custom)
|
||||
dispatch_callee = cpp_dispatch_target(f, custom=custom)
|
||||
dispatch_key_set = '' if not is_npu_autograd else 'auto ks_set = ' \
|
||||
'c10::DispatchKeySet().add(c10::DispatchKey::AutogradXLA).add(c10::DispatchKey::XLA);'
|
||||
dispatch_callee = cpp_dispatch_target(f, custom=custom, is_npu_autograd=is_npu_autograd)
|
||||
dispatch_args = ', '.join(cpp_dispatch_exprs(f, python_signature=ps, faithful=custom))
|
||||
if is_npu_autograd:
|
||||
dispatch_args = 'ks_set, ' + dispatch_args
|
||||
|
||||
# from arg parser outputs to dispatch lambda arguments
|
||||
parser_outputs = arg_parser_output_exprs(ps, f)
|
||||
@@ -687,6 +693,7 @@ auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{
|
||||
{init_npu_device}
|
||||
pybind11::gil_scoped_release no_gil;
|
||||
{record_func_define}
|
||||
{dispatch_key_set}
|
||||
{dispatch_callee}({dispatch_args});
|
||||
}};
|
||||
dispatch_{name}({lambda_args}){set_requires_grad};
|
||||
@@ -702,6 +709,7 @@ auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{
|
||||
{init_npu_device}
|
||||
pybind11::gil_scoped_release no_gil;
|
||||
{record_func_define}
|
||||
{dispatch_key_set}
|
||||
return {dispatch_callee}({dispatch_args});
|
||||
}};
|
||||
return wrap({namedtuple_typeref}dispatch_{name}({lambda_args}){set_requires_grad});
|
||||
|
||||
@@ -52,6 +52,15 @@ def assert_never(x: NoReturn) -> NoReturn:
|
||||
# and you're expected to populate information once during
|
||||
# construction.
|
||||
|
||||
# Represent a source location; used for better error reporting
|
||||
@dataclass(frozen=True)
|
||||
class Location:
|
||||
file: str
|
||||
line: int
|
||||
|
||||
def __str__(self) -> str:
|
||||
return "{}:{}".format(self.file, self.line)
|
||||
|
||||
# Valid values of the 'variants' field in native_functions.yaml
|
||||
Variant = Enum('Variant', ('function', 'method'))
|
||||
|
||||
@@ -95,6 +104,7 @@ class DispatchKey(Enum):
|
||||
PrivateUse3 = auto()
|
||||
EndOfBackendKeys = PrivateUse3
|
||||
|
||||
Unsupport = auto()
|
||||
ZeroTensor = auto()
|
||||
Meta = auto()
|
||||
BackendSelect = auto()
|
||||
@@ -291,6 +301,8 @@ class NativeFunction:
|
||||
# Whether or not the NativeFunction is bishengcpp kernel
|
||||
bscpp_op: bool
|
||||
|
||||
op_api: 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.
|
||||
@@ -386,6 +398,7 @@ class NativeFunction:
|
||||
|
||||
tag = parse_tag(e, structured)
|
||||
bscpp_op = e.pop("bscpp_op", False)
|
||||
op_api = e.pop("op_api", False)
|
||||
|
||||
from codegen.api import cpp
|
||||
|
||||
@@ -455,8 +468,7 @@ class NativeFunction:
|
||||
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, tag=tag,
|
||||
bscpp_op=bscpp_op), backend_metadata
|
||||
|
||||
bscpp_op=bscpp_op, op_api=op_api), backend_metadata
|
||||
|
||||
def validate_unstructured(self) -> None:
|
||||
# TODO: probably better to accumulate these errors and report them all
|
||||
@@ -505,6 +517,20 @@ class NativeFunction:
|
||||
@property
|
||||
def has_composite_kernel(self) -> bool:
|
||||
return self.has_composite_implicit_autograd_kernel or self.has_composite_explicit_autograd_kernel
|
||||
|
||||
@property
|
||||
def is_view_op(self) -> bool:
|
||||
rets = self.func.returns
|
||||
is_non_mutating_view = len(rets) > 0 and any(r.annotation is not None
|
||||
and not r.annotation.is_write for r in rets)
|
||||
is_inplace_view = self.tag is not None and self.tag is Tag.inplace_view
|
||||
is_wildcard_view = any(inp.annotation is not None and
|
||||
inp.annotation.alias_set_after != "" for inp in self.func.schema_order_arguments())
|
||||
return is_non_mutating_view or is_inplace_view or is_wildcard_view
|
||||
|
||||
@property
|
||||
def root_name(self) -> str:
|
||||
return self.func.name.name.base
|
||||
|
||||
SchemaKind = Enum('SchemaKind', ('functional', 'inplace', 'out'))
|
||||
|
||||
|
||||
@@ -15,35 +15,36 @@
|
||||
// limitations under the License.
|
||||
|
||||
#pragma once
|
||||
#ifndef __SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__
|
||||
#define __SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__
|
||||
#ifndef ${macro}
|
||||
#define ${macro}
|
||||
|
||||
|
||||
#include <ATen/Tensor.h>
|
||||
#include <ATen/ATen.h>
|
||||
#include <c10/core/Device.h>
|
||||
${include_npu_native_functions}
|
||||
|
||||
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
|
||||
${static_define}
|
||||
|
||||
// ${generated_comment}
|
||||
namespace ${cpp_namespace} {
|
||||
|
||||
struct ${class_name} {
|
||||
|
||||
static at::Tensor argmax(const at::Tensor & self, c10::optional<int64_t> dim, bool keepdim);
|
||||
static at::Tensor argmin(const at::Tensor & self, c10::optional<int64_t> dim, bool keepdim);
|
||||
static at::Tensor _embedding_bag_dense_backward(
|
||||
const at::Tensor& grad,
|
||||
const at::Tensor& indices,
|
||||
const at::Tensor& offset2bag,
|
||||
const at::Tensor& bag_size,
|
||||
const at::Tensor & maximum_indices,
|
||||
int64_t num_weights,
|
||||
bool scale_grad_by_freq,
|
||||
int64_t mode,
|
||||
const c10::optional<at::Tensor> & per_sample_weights,
|
||||
int64_t padding_idx);
|
||||
|
||||
${dispatch_declarations}
|
||||
|
||||
};
|
||||
|
||||
@@ -61,6 +61,8 @@ namespace at {
|
||||
// at namespace already.
|
||||
namespace {
|
||||
|
||||
${dispatch_helpers}
|
||||
|
||||
${dispatch_anonymous_definitions}
|
||||
|
||||
TORCH_LIBRARY_IMPL(aten, ${DispatchKey}, m) {
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/utils/LazyInit.h"
|
||||
#include "torch_npu/csrc/utils/DeviceParser.h"
|
||||
#include "torch_npu/csrc/aten/VariableType.h"
|
||||
|
||||
using at::Tensor;
|
||||
using at::Device;
|
||||
|
||||
@@ -13,13 +13,27 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import torch
|
||||
import dis
|
||||
from functools import wraps
|
||||
|
||||
import torch
|
||||
|
||||
import torch_npu
|
||||
from torch_npu.utils.device_guard import torch_device_guard
|
||||
|
||||
|
||||
def wrap_ewf_warning_func(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
if not wrapper.warned:
|
||||
print(f"Warning: torch.empty_with_format is deprecated and will be removed in future version. "
|
||||
f"Use torch_npu.empty_with_format instead.")
|
||||
wrapper.warned = True
|
||||
return func(*args, **kwargs)
|
||||
wrapper.warned = False
|
||||
return wrapper
|
||||
|
||||
|
||||
@torch_device_guard
|
||||
def _tensor(*args, **kwargs):
|
||||
return torch_npu.tensor(*args, **kwargs)
|
||||
@@ -45,6 +59,7 @@ def _arange(*args, **kwargs):
|
||||
return torch_npu.arange(*args, **kwargs)
|
||||
|
||||
|
||||
@wrap_ewf_warning_func
|
||||
@torch_device_guard
|
||||
def _empty_with_format(*args, **kwargs):
|
||||
return torch_npu.empty_with_format(*args, **kwargs)
|
||||
@@ -77,6 +92,40 @@ def _as_tensor(*args, **kwargs):
|
||||
return torch._C._VariableFunctions.as_tensor(*args, **kwargs).to(dst_device)
|
||||
|
||||
|
||||
def _eval_no_call(stmt, glob, loc):
|
||||
"""Evaluate statement as long as it does not contain any method/function calls"""
|
||||
bytecode = compile(stmt, "", mode="eval")
|
||||
for insn in dis.get_instructions(bytecode):
|
||||
if "CALL" in insn.opname:
|
||||
raise RuntimeError(f"Type annotation should not contain calls, but '{stmt}' does")
|
||||
return eval(bytecode, glob, loc)
|
||||
|
||||
|
||||
def _parse_type_line(type_line, rcb, loc):
|
||||
"""Parses a type annotation specified as a comment.
|
||||
Example inputs:
|
||||
# type: (Tensor, torch.Tensor) -> Tuple[Tensor]
|
||||
# type: (Tensor, Tuple[Tensor, Tensor]) -> Tensor
|
||||
"""
|
||||
arg_ann_str, ret_ann_str = torch.jit.annotations.split_type_line(type_line)
|
||||
|
||||
try:
|
||||
arg_ann = _eval_no_call(arg_ann_str, {}, torch.jit.annotations.EvalEnv(rcb))
|
||||
except (NameError, SyntaxError) as e:
|
||||
raise RuntimeError("Failed to parse the argument list of a type annotation") from e
|
||||
|
||||
if not isinstance(arg_ann, tuple):
|
||||
arg_ann = (arg_ann,)
|
||||
|
||||
try:
|
||||
ret_ann = _eval_no_call(ret_ann_str, {}, torch.jit.annotations.EvalEnv(rcb))
|
||||
except (NameError, SyntaxError) as e:
|
||||
raise RuntimeError("Failed to parse the return type of a type annotation") from e
|
||||
|
||||
arg_types = [torch.jit.annotations.ann_to_type(ann, loc) for ann in arg_ann]
|
||||
return arg_types, torch.jit.annotations.ann_to_type(ret_ann, loc)
|
||||
|
||||
|
||||
${device_methods_def_py_dispatch}
|
||||
|
||||
def add_torch_funcs():
|
||||
@@ -90,5 +139,6 @@ def add_torch_funcs():
|
||||
torch.jit.script = jit_script
|
||||
torch.as_tensor = _as_tensor
|
||||
torch.new_device = _new_device
|
||||
torch.jit.annotations.parse_type_line = _parse_type_line
|
||||
|
||||
${device_methods_def_py}
|
||||
${device_methods_def_py}
|
||||
|
||||
@@ -20,12 +20,30 @@ from enum import Enum
|
||||
import contextlib
|
||||
import textwrap
|
||||
|
||||
# Safely load fast C Yaml loader/dumper if they are available
|
||||
try:
|
||||
from yaml import CSafeLoader as Loader
|
||||
except ImportError:
|
||||
from yaml import SafeLoader as Loader # type: ignore[misc]
|
||||
|
||||
try:
|
||||
from yaml import CSafeDumper as Dumper
|
||||
except ImportError:
|
||||
from yaml import SafeDumper as Dumper # type: ignore[misc]
|
||||
YamlDumper = Dumper
|
||||
|
||||
# A custom loader for YAML that errors on duplicate keys.
|
||||
# This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165
|
||||
class YamlLoader(Loader):
|
||||
def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def]
|
||||
mapping = []
|
||||
for key_node, value_node in node.value:
|
||||
key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call]
|
||||
assert key not in mapping, f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}"
|
||||
mapping.append(key)
|
||||
mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call]
|
||||
return mapping
|
||||
|
||||
# Many of these functions share logic for defining both the definition
|
||||
# and declaration (for example, the function signature is the same), so
|
||||
# we organize them into one function that takes a Target to say which
|
||||
@@ -42,6 +60,7 @@ Target = Enum('Target', (
|
||||
'REGISTRATION',
|
||||
# namespace { ... }
|
||||
'ANONYMOUS_DEFINITION',
|
||||
'ANONYMOUS_DEFINITION_UNSUPPORT',
|
||||
# namespace cpu { ... }
|
||||
'NAMESPACED_DEFINITION',
|
||||
'NAMESPACED_DECLARATION',
|
||||
|
||||
|
Before Width: | Height: | Size: 580 B After Width: | Height: | Size: 580 B |
|
Before Width: | Height: | Size: 580 B After Width: | Height: | Size: 580 B |
|
Before Width: | Height: | Size: 394 B After Width: | Height: | Size: 394 B |
|
Before Width: | Height: | Size: 406 B After Width: | Height: | Size: 406 B |
|
Before Width: | Height: | Size: 253 B After Width: | Height: | Size: 253 B |
|
Before Width: | Height: | Size: 580 B After Width: | Height: | Size: 580 B |
@@ -1,4 +1,11 @@
|
||||
# FrameworkPTAdapter 3.0.0 版本说明书
|
||||
# FrameworkPTAdapter 5.0.RC1 版本说明书
|
||||
- [FrameworkPTAdapter 5.0.RC1](#FrameworkPTAdapter-5-0-RC1md)
|
||||
- [用户须知](#用户须知md)
|
||||
- [新增特性](#新增特性md)
|
||||
- [特性修改](#特性修改md)
|
||||
- [已修复问题](#已修复问题md)
|
||||
- [已知问题](#已知问题md)
|
||||
- [兼容性](#兼容性md)
|
||||
- [FrameworkPTAdapter 3.0.0](#FrameworkPTAdapter-3-0-0md)
|
||||
- [用户须知](#用户须知md)
|
||||
- [新增特性](#新增特性md)
|
||||
@@ -49,6 +56,117 @@
|
||||
- [已知问题](#已知问题-4md)
|
||||
- [兼容性](#兼容性-5md)
|
||||
|
||||
<h2 id="FrameworkPTAdapter-5-0-RC1md">FrameworkPTAdapter 5.0.RC1</h2>
|
||||
|
||||
<h3 id="用户须知md">用户须知</h3>
|
||||
|
||||
本框架基于Facebook主导的开源PyTorch进行修改,延续原生的PyTorch特性,使用NPU进行动态图训练;以算子粒度进行模型适配,代码重用性好,支持现有的网络只修改设备类型或数据类型,即可迁移到NPU上使用。
|
||||
|
||||
PyTorch1.8.1版本开始采用插件化适配方式,与原生PyTorch框架实现彻底解耦,对用户安装使用及后端算子适配开发提供较好体验。
|
||||
|
||||
<h3 id="新增特性md">新增特性</h3>
|
||||
|
||||
**表 1** PyTorch支持的版本特性列表
|
||||
|
||||
<a name="t76c34275cbb74753970f7c5a9eb594fa"></a>
|
||||
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="25.590000000000003%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>一级特性</p>
|
||||
</th>
|
||||
<th class="cellrowborder" valign="top" width="15.52%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>二级特性</p>
|
||||
</th>
|
||||
<th class="cellrowborder" valign="top" width="58.89%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>说明</p>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody><tr id="row2620183971614"><td class="cellrowborder" rowspan="3" valign="top" width="25.590000000000003%" headers="mcps1.2.4.1.1 "><p id="p0819102247"><a name="p0819102247"></a><a name="p0819102247"></a>适配NPU的PyTorch1.8.1特性</p>
|
||||
<p id="p15488161812213"><a name="p15488161812213"></a><a name="p15488161812213"></a></p>
|
||||
<p id="p17381229135615"><a name="p17381229135615"></a><a name="p17381229135615"></a></p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="15.52%" headers="mcps1.2.4.1.2 "><p id="p76365489137"><a name="p76365489137"></a><a name="p76365489137"></a>框架基础功能</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="58.89%" headers="mcps1.2.4.1.3 "><p id="p363616485131"><a name="p363616485131"></a><a name="p363616485131"></a>优化设备内存分配策略,修复少量BUG</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row945906124515"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1077934311314"><a name="p1077934311314"></a><a name="p1077934311314"></a>FX</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p3634127577"><a name="p3634127577"></a><a name="p3634127577"></a>支持模型IR图构建以及基于IR图的代码生成</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row938172915567"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p6466153955816"><a name="p6466153955816"></a><a name="p6466153955816"></a>优化器</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p20382294568"><a name="p20382294568"></a><a name="p20382294568"></a>支持npu_fused_adam等融合优化器</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row3722227133312"><td class="cellrowborder" rowspan="3" valign="top" width="25.590000000000003%" headers="mcps1.2.4.1.1 "><p id="p107221327153315"><a name="p107221327153315"></a><a name="p107221327153315"></a>适配NPU的PyTorch1.11.0特性</p>
|
||||
<p id="p7778931115613"><a name="p7778931115613"></a><a name="p7778931115613"></a></p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="15.52%" headers="mcps1.2.4.1.2 "><p id="p153563917719"><a name="p153563917719"></a><a name="p153563917719"></a>框架基础功能</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="58.89%" headers="mcps1.2.4.1.3 "><p id="p193246215619"><a name="p193246215619"></a><a name="p193246215619"></a>优化设备内存分配策略,修复少量BUG</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row6631141014305"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1416445591310"><a name="p1416445591310"></a><a name="p1416445591310"></a>FX</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1281850105718"><a name="p1281850105718"></a><a name="p1281850105718"></a>支持模型IR图构建以及基于IR图的代码生成</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row577853110564"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p546144505813"><a name="p546144505813"></a><a name="p546144505813"></a>优化器</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p47781431165614"><a name="p47781431165614"></a><a name="p47781431165614"></a>支持npu_fused_adam等融合优化器</p>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<h3 id="特性修改md">特性修改</h3>
|
||||
|
||||
不涉及
|
||||
|
||||
<h3 id="已修复问题md">已修复问题</h3>
|
||||
|
||||
不涉及
|
||||
|
||||
<h3 id="已知问题md">已知问题</h3>
|
||||
|
||||
<a name="table1969972073016"></a>
|
||||
<table><thead align="left"><tr id="row3699162017307"><th class="cellrowborder" valign="top" width="18.22%" id="mcps1.1.3.1.1"><p id="p16992020153010"><a name="p16992020153010"></a><a name="p16992020153010"></a>已知问题</p>
|
||||
</th>
|
||||
<th class="cellrowborder" valign="top" width="81.78%" id="mcps1.1.3.1.2"><p id="p269919203308"><a name="p269919203308"></a><a name="p269919203308"></a>问题描述</p>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody><tr id="row9699142003011"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p1769932017300"><a name="p1769932017300"></a><a name="p1769932017300"></a>数据类型支持</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p13699152010301"><a name="p13699152010301"></a><a name="p13699152010301"></a>NPU不支持float16类型的inf/nan数据输入输出。</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row146991520153016"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p156997200308"><a name="p156997200308"></a><a name="p156997200308"></a>数据Format</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p10699182020308"><a name="p10699182020308"></a><a name="p10699182020308"></a>出现4D以上的format时不能降维。</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row11121205610549"><td class="cellrowborder" rowspan="3" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p1647216219558"><a name="p1647216219558"></a><a name="p1647216219558"></a>集合通信约束</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p3116115695415"><a name="p3116115695415"></a><a name="p3116115695415"></a>要求一次训练任务中不同device上执行的图相同。</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row51211656105411"><td class="cellrowborder" valign="top" headers="mcps1.1.3.1.1 "><p id="p1311616560541"><a name="p1311616560541"></a><a name="p1311616560541"></a>当前只支持1/2/4/8P粒度的分配。</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row8647195765419"><td class="cellrowborder" valign="top" headers="mcps1.1.3.1.1 "><p id="p2064225716544"><a name="p2064225716544"></a><a name="p2064225716544"></a>只支持int8,int32,float16和float32数据类型。</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row4646195719548"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p4642195718541"><a name="p4642195718541"></a><a name="p4642195718541"></a>Apex功能支持</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p864205725412"><a name="p864205725412"></a><a name="p864205725412"></a>Apex当前版本的实现方式主要为python实现,不支持APEX中的自定义优化CUDA Kernel。</p>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<h3 id="兼容性md">兼容性</h3>
|
||||
|
||||
A800-9010:CentOS 7.6/Ubuntu 18.04, 2.04/BC-Linux 7.6/Debian 9.9/Debian 10/OpenEuler 20.03 LTS
|
||||
|
||||
A800-9000:CentOS 7.6/Ubuntu 18.04, 2.04/Euler 2.8, 2.10/Kylin v10/BC-Linux 7.6/OpenEuler 20.03 LTS/UOS 20 1020e
|
||||
|
||||
<h2 id="FrameworkPTAdapter-3-0-0md">FrameworkPTAdapter 3.0.0</h2>
|
||||
|
||||
<h3 id="用户须知md">用户须知</h3>
|
||||
|
Before Width: | Height: | Size: 580 B After Width: | Height: | Size: 580 B |
|
Before Width: | Height: | Size: 580 B After Width: | Height: | Size: 580 B |
|
Before Width: | Height: | Size: 394 B After Width: | Height: | Size: 394 B |
|
Before Width: | Height: | Size: 406 B After Width: | Height: | Size: 406 B |
|
Before Width: | Height: | Size: 253 B After Width: | Height: | Size: 253 B |
|
Before Width: | Height: | Size: 580 B After Width: | Height: | Size: 580 B |
@@ -1,918 +0,0 @@
|
||||
# Multi-server Multi-device Training Adaptation Guide for PyTorch Models
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Training Workflow](#training-workflow)
|
||||
- [Quick Start](#quick-start)
|
||||
- [Overview](#overview-1)
|
||||
- [Setting Up the Environment](#setting-up-the-environment)
|
||||
- [Preparing a Model](#preparing-a-model)
|
||||
- [Modifying the Model](#modifying-the-model)
|
||||
- [Starting the Training](#starting-the-training)
|
||||
- [Multi-server Multi-device Training](#multi-server-multi-device-training)
|
||||
- [Common Concepts and Parameters](#common-concepts-and-parameters)
|
||||
- [Multi-server Multi-device Training Process](#multi-server-multi-device-training-process)
|
||||
- [Setting Up the Environment](#setting-up-the-environment-1)
|
||||
- [Preparing a Model](#preparing-a-model-1)
|
||||
- [Modifying the Model](#modifying-the-model-1)
|
||||
- [Start the Training](#start-the-training)
|
||||
- [Appendix](#appendix)
|
||||
# Overview
|
||||
|
||||
Users can obtain PyTorch training models from Ascend ModelZoo, but the models do not support multi-server multi-device training. You need to modify the models based on the actual model code. This document describes how to quickly train a PyTorch model in Distributed Data Parallel (DDP) mode in multi-server multi-device scenario.
|
||||
|
||||
# Training Workflow
|
||||
|
||||
The process of training a PyTorch model in multi-server multi-device scenario includes environment setup, model preparation, model modification, and training startup.
|
||||
|
||||
1. Environment Setup
|
||||
|
||||
Prepare the software, hardware, and network environment for multi-server multi-device training, including setting up the development and operating environment, connecting the cluster network, setting the processor IP address, and setting the firewall.
|
||||
|
||||
2. Model Preparation
|
||||
|
||||
Prepare a PyTorch model, data loader, and optimizer for training. You can download them from the open source community (https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch) or prepare them by yourself.
|
||||
|
||||
3. Model Modification
|
||||
|
||||
Modify the basic model and add the code and environment variables required by DDP to enable the multi-server multi-device training.
|
||||
|
||||
4. Training Startup
|
||||
|
||||
Start model training in the multi-server multi-device scenario and view training logs.
|
||||
|
||||
|
||||
|
||||
# Quick Start
|
||||
|
||||
## Overview
|
||||
|
||||
The example presented in this document helps you quickly understand how a PyTorch model is trained in multi-server multi-device scenario. The example uses a custom model for training in two-computer eight-device scenario. The two computers are named AI Server0 and AI Server1. The eight Ascend 910 Processors on each computer are named device0 to device7.
|
||||
|
||||
## Setting Up the Environment
|
||||
|
||||
At least two computers with Ascend 910 Processors installed are required, and the NPU firmware and driver are correctly installed on each computer.
|
||||
|
||||
1. Prepare the development and operating environment on each computer.
|
||||
|
||||
- Install the CANN development and operating environment. For details, see the *CANN Software Installation Guide*. Use CANN later than 5.0.3.
|
||||
|
||||
- Install the PyTorch that adapts to NPU. For details, see the *PyTorch Installation Guide*.
|
||||
|
||||
2. Prepare the network.
|
||||
|
||||
Set up the network by directly connecting switches or optical ports. For details, see the *Ascend Data Center Solution Networking Guide* at https://support.huawei.com/enterprise/en/doc/EDOC1100221995/229cc0e4.
|
||||
|
||||
In this example, two computers with eight devices are used for training, so optical ports are used for network connection.
|
||||
|
||||
3. Configure the device IP address.
|
||||
|
||||
Configure the device IP address on AI Server0.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
Configure the device IP address on AI Server1.
|
||||
|
||||
```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. Configure the firewall.
|
||||
|
||||
- Command for disabling the firewall on Ubuntu:
|
||||
|
||||
```shell
|
||||
ufw disable
|
||||
```
|
||||
```
|
||||
|
||||
- Command for disabling the firewall on Red Hat or CentOS 7:
|
||||
|
||||
```shell
|
||||
systemctl stop firewalld
|
||||
```
|
||||
|
||||
## Preparing a Model
|
||||
|
||||
This example creates a simple model for you to quickly understand multi-server multi-device training. You can also obtain the Ascend NPU-based PyTorch training model from the open source community (https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch).
|
||||
|
||||
1. Prepare a DDP model.
|
||||
|
||||
The following is an example of main.py for multi-server multi-device training.
|
||||
|
||||
```python
|
||||
import argparse
|
||||
import os
|
||||
import torch
|
||||
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. Perform basic operations. ###
|
||||
# Build a model.
|
||||
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
|
||||
|
||||
# Obtain a dataset.
|
||||
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. Initialize the parameters, data, model, loss function, and optimizer. ####
|
||||
# Obtain local_rank and 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
|
||||
|
||||
# Set the IP address and port of the master node.
|
||||
os.environ['MASTER_ADDR'] = addr
|
||||
os.environ['MASTER_PORT'] = '29501'
|
||||
|
||||
# Initialize the DDP backend.
|
||||
loc = 'npu:{}'.format(local_rank)
|
||||
torch.npu.set_device(loc)
|
||||
dist.init_process_group(backend='hccl') # HCCL is the backend of the NPU device.
|
||||
|
||||
|
||||
# Prepare data after DDP initialization.
|
||||
trainloader = get_dataset()
|
||||
|
||||
# Instantiate the model.
|
||||
model = ToyModel().to(loc)
|
||||
|
||||
# Load the model weight. The weight needs to be loaded only on the master node before the DDP model is built.
|
||||
ckpt_path = None
|
||||
if dist.get_rank() == 0 and ckpt_path is not None:
|
||||
model.load_state_dict(torch.load(ckpt_path))
|
||||
|
||||
# Build the DDP model.
|
||||
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
|
||||
|
||||
# Initialize the optimizer. After the DDP model is built, use the model to initialize the optimizer.
|
||||
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
|
||||
|
||||
# Initialize the loss function.
|
||||
loss_func = nn.CrossEntropyLoss().to(loc)
|
||||
|
||||
### 3. Train the network.
|
||||
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. Similar to the DP mode, when you save a model, note that model.module instead of model is saved.
|
||||
# That is because the model actually refers to a DDP model, and the parameters are packaged by `model=DDP(model)`.
|
||||
# 2. You only need to save the model on process 0 once to avoid repeated saving.
|
||||
if dist.get_rank() == 0:
|
||||
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
|
||||
```
|
||||
|
||||
2. Ensure that the model is correct for training in the single-server multi-device scenario.
|
||||
|
||||
1. The Python third-party library is required if you install the model script yourself.
|
||||
|
||||
2. Configure NPU environment variables. For information about the **env_npu.sh** script, see the appendix.
|
||||
|
||||
```shell
|
||||
source env_npu.sh
|
||||
```
|
||||
|
||||
3. Execute **torch.distributed.launch** to run the following main.py command to train a model in single-server multi-device scenario.
|
||||
|
||||
```shell
|
||||
python -m torch.distributed.launch --nproc_per_node 8 main.py
|
||||
```
|
||||
|
||||
`--nproc_per_node` indicates the number of training cards.
|
||||
|
||||
After the command is run successfully, the model is trained on the eight NPUs of the device.
|
||||
|
||||
|
||||
|
||||
## Modifying the Model
|
||||
|
||||
The example provided in "Quick Start" is adapted to the multi-server multi-device training. You do not need to modify the script. For details about how to modify other models, see section "Multi-server Multi-device Training".
|
||||
|
||||
## Starting the Training
|
||||
|
||||
1. Upload main.py model script to any directory on AI Server0 and AI Server1.
|
||||
|
||||
2. Query the host IP addresses of the servers.
|
||||
|
||||
```shell
|
||||
hostname -I
|
||||
```
|
||||
|
||||
All IP addresses are displayed, and the first IP address is the host IP address of the current server.
|
||||
|
||||
For example, the host IP address of AI Server0 is **192.168.*xx*.22**, and that of AI Server1 is **192.168.*xx*.23**.
|
||||
|
||||
3. Use AI Server0 as the master node, and start the 2 x 8 cluster.
|
||||
|
||||
Startup commands for AI Server0:
|
||||
|
||||
```shell
|
||||
# Set environment variables. Obtain the env_npu.sh script content from the appendix.
|
||||
source env_npu.sh
|
||||
# Disable the trustlist of HCCL channel.
|
||||
export HCCL_WHITELIST_DISABLE=1
|
||||
# Initialize the IP address of the HCCL communication NIC, and set the IP address to the host IP address of the current server.
|
||||
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
|
||||
```
|
||||
|
||||
Startup commands for AI Server1:
|
||||
|
||||
```shell
|
||||
# Set environment variables. Obtain the env_npu.sh script content from the appendix.
|
||||
source env_npu.sh
|
||||
# Disable the trustlist of HCCL channel.
|
||||
export HCCL_WHITELIST_DISABLE=1
|
||||
# Initialize the IP address of the HCCL communication NIC, and set the IP address to the host IP address of the current server.
|
||||
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
|
||||
```
|
||||
|
||||
Parameter description:
|
||||
|
||||
--nnode: specifies the number of nodes used for distributed training scripts.
|
||||
|
||||
--node_rank: specifies the rank of the current node during multi-node distributed training.
|
||||
|
||||
--nproc_per_node: specifies the number of GPU-based training processes on the current node.
|
||||
|
||||
--master_addr: address of the master node (rank is 0). The value can be the IP address or the host name of node 0.
|
||||
|
||||
--master_port: specifies the port number used by the master node during distributed training.
|
||||
|
||||
--addr: input parameter of the main.py script, specifying the host IP address of the master node.
|
||||
|
||||
3. View the host logs.
|
||||
|
||||
Host logs are stored in the `~/ascend/log` directory. You can go to this directory to view the device logs of each host.
|
||||
|
||||
# Multi-server Multi-device Training
|
||||
|
||||
## Common Concepts and Parameters
|
||||
|
||||
Basic concepts for PyTorch distributed training
|
||||
|
||||
| Basic Concept | Description |
|
||||
| :-----------: | ------------------------------------------------------------ |
|
||||
| AI Server | Computer with an Ascend 910 Processors. Multiple computers are identified as AI Server +serial number, for example, AI Server0 and AI Server1. |
|
||||
| device | Ascend 910 Processors on the AI server. Multiple processors are represented as device 0, device 1, ..., and device 7. |
|
||||
| host | AI server host. |
|
||||
| master | Select one of multiple AI servers as the master node for data communication. |
|
||||
| group | Process group. By default, there is only one group. Use the default value. |
|
||||
| world size | Number of global parallel processes, which can be obtained by running **torch.distributed.get_world_size()**. The value is the same for different processes. |
|
||||
| rank | Sequence number of the current process, which is used for communication between processes. For example, for a 2 x 8 cluster, the **world size** is 16, and the rank in each process is [0, 1, 2, ..., 15]. |
|
||||
| local_rank | Sequence number of processes on each host, for example, there are processes 0-7 on each host. Generally, **local_rank** is used to set the GPU/NPU on which the current model runs. |
|
||||
|
||||
Parameters for executing **torch.distributed.launch** to start multi-device training
|
||||
|
||||
| Parameter | Description |
|
||||
| ------------------ | ------------------------------------------------------------ |
|
||||
| **nnodes** | Specifies the number of nodes used for distributed training scripts. |
|
||||
| **node_rank** | Specifies the rank of the current node during multi-node distributed training. |
|
||||
| **nproc_per_node** | Specifies the number of GPU-based training processes on the current node. You are advised to set this parameter to the number of GPUs on the current node. In this way, each process can independently control a GPU to achieve the highest efficiency. |
|
||||
| **master_addr** | Address of the master node (rank is 0). The value can be the IP address or the host name of node 0. For single-node multi-process training, set this parameter to **127.0.0.1**. |
|
||||
| **master_port**: | Specifies the port number used by the master node during distributed training. The port number must be different from the port numbers of other applications. |
|
||||
|
||||
## Multi-server Multi-device Training Process
|
||||
|
||||
### Setting Up the Environment
|
||||
|
||||
At least two computers with Ascend 910 Processors installed are required, and the NPU firmware and driver are correctly installed on each server.
|
||||
|
||||
1. Prepare the development and operating environment on each computer.
|
||||
|
||||
- Install the CANN development and operating environment. For details, see the *CANN Software Installation Guide*. Use CANN later than 5.0.3.
|
||||
|
||||
- Install the PyTorch that adapts to NPU. For details, see the *PyTorch Installation Guide.*
|
||||
|
||||
2. Prepare the network.
|
||||
|
||||
Cluster training is completed by multiple computers (a maximum of 128) with Ascend 910 Processors installed. The computers need to work with switches to form a fully-connected active/standby network on the data plane. The 8 x *n*-device training is supported. Two computers can be directly connected through optical ports. For details, see the *Ascend Data Center Solution Networking Guide * at https://support.huawei.com/enterprise/en/doc/EDOC1100221995/229cc0e4.
|
||||
|
||||
3. Configure the device IP address.
|
||||
|
||||
Use hccn_tool to configure the device IP address. hccn_tool is provided by CANN.
|
||||
|
||||
```shell
|
||||
hccn_tool -i 0 -ip -s address 192.168.100.111 netmask 255.255.255.0
|
||||
```
|
||||
|
||||
Observe the following rules when configuring the device IP address:
|
||||
|
||||
1. On the AI servers, devices 0/4, 1/5, 2/6, and 3/7 must be in the same network segment. But devices 0, 1, 2, and 3 must be in different network segments, and devices 4, 5, 6, and 7 must be in different network segments.
|
||||
2. In the cluster scenario, the devices corresponding to each AI server must be in the same network segment. NICs 0 and 1 of AI Server0 and AI Server1 must be in the same network segment.
|
||||
3. Each IP address must be unique. IP addresses in the same network segment must be distinguished by the last eight bits.
|
||||
|
||||
Use hccn_tool to check whether the device IP address is correct.
|
||||
|
||||
- Query the IP address of each device.
|
||||
|
||||
```shell
|
||||
hccn_tool -i 0 -ip –g
|
||||
```
|
||||
|
||||
The IP addresses are displayed:
|
||||
|
||||
> ipaddr:192.168.100.101
|
||||
>
|
||||
> netmask:255.255.255.0
|
||||
|
||||
- Use hccn_tool to ensure that the devices of the two hosts are correctly connected by performing the test for eight times from device0 to devcie7.
|
||||
|
||||
```shell
|
||||
hccn_tool -i 0 -netdetect -s address xx.xx.xx.xx
|
||||
|
||||
hccn_tool -i 0 -net_health –g
|
||||
```
|
||||
|
||||
**-i**: device ID.
|
||||
|
||||
**-s address**: ***xx.xx.xx.xx*** is the IP address of device *i* on the other host.
|
||||
|
||||
If `success` is returned, the connection is successful.
|
||||
|
||||
4. Configure the firewall.
|
||||
|
||||
During HCCL communication, the firewall may intercept the communication port, causing communication timeout. Therefore, you need to disable the firewall on the server for PyTorch cluster training.
|
||||
|
||||
- Command for disabling the firewall on Ubuntu:
|
||||
|
||||
```shell
|
||||
ufw disable
|
||||
```
|
||||
|
||||
- Command for disabling the firewall on Red Hat or CentOS 7:
|
||||
|
||||
```shell
|
||||
systemctl stop firewalld
|
||||
```
|
||||
|
||||
### Preparing a Model
|
||||
|
||||
There are two methods for preparing a model.
|
||||
|
||||
- Download a PyTorch training model from the open source community (https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch).
|
||||
|
||||
The model obtained from the open source community supports single-server multi-device training. Modify the model based on the related parameters described in section "Modifying the Model".
|
||||
|
||||
- Manually build a PyTorch training model.
|
||||
|
||||
1. Prepare a PyTorch training model and data loader.
|
||||
|
||||
Prepare a PyTorch model:
|
||||
|
||||
```python
|
||||
class ToyModel(nn.Module):
|
||||
def __init__(self):
|
||||
...
|
||||
def forward(self,x):
|
||||
...
|
||||
```
|
||||
|
||||
Prepare data:
|
||||
|
||||
```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. Instantiate the model.
|
||||
|
||||
```python
|
||||
# Instantiate the model.
|
||||
model = ToyModel().to(loc)
|
||||
|
||||
# Load the model weight
|
||||
if ckpt_path is not None:
|
||||
model.load_state_dict(torch.load(ckpt_path))
|
||||
```
|
||||
|
||||
3. Prepare the loss function and optimizer.
|
||||
|
||||
```python
|
||||
# Initialize the optimizer. After the DDP model is built, use the model to initialize the optimizer.
|
||||
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
|
||||
|
||||
# Initialize the loss function.
|
||||
loss_func = nn.CrossEntropyLoss().to(loc)
|
||||
```
|
||||
|
||||
4. Train the model.
|
||||
|
||||
```python
|
||||
### 3. Train the network.
|
||||
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)
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Modifying the Model
|
||||
|
||||
Modify the IP address and port of the master node, initialize the **distributed ** function, model DDP, data DDP, and optimizer, and modify the DDP model training method based on the initial model code.
|
||||
|
||||
1. Set the IP address and port for the master node. In the NPU distributed training, HCCL is used for communication, while in PyTorch, the HCCL communication mechanism that is detected by automatic topology is used. That is, **RANK_TABLE_FLIE** is not required, but the communication depends on the NIC on the host side. Therefore, you need to set environment variables in the code to set the communication NIC.
|
||||
|
||||
```python
|
||||
os.environ['MASTER_ADDR'] = xxx.xxx.xxx.xxx
|
||||
os.environ['MASTER_PORT'] = 'xxx'
|
||||
```
|
||||
|
||||
**MASTER_ADDR**: Set this parameter to the IP address of the master node in the cluster. (Select any host as the master node.)
|
||||
|
||||
**MASTER_PORT**: Set this parameter to the idle port of the master node.
|
||||
|
||||
In the model code, the IP address and port number of the master node are generally presented as transferred parameters. In some open-source code, the IP address and port number may be presented as **127.0.0.1**. In this case, you need to modify them.
|
||||
|
||||
The preceding variables must be declared before **torch.distributed.init_process_group()** is invoked.
|
||||
|
||||
2. Initialize **distributed**.
|
||||
|
||||
In PyTorch, `dist.init_process_group(backend='hccl', world_size=world_size, rank=rank)` is used to initialize thread groups. The parameters are described as follows:
|
||||
|
||||
`backend`: communication protocol used for distributed training. Only hccl can be used on the NPU.
|
||||
|
||||
`world_size`: total number of devices used for training.
|
||||
|
||||
`rank`: rank ID of the currently initialized device, that is, the global logical ID.
|
||||
|
||||
There are two methods to start multi-device training:
|
||||
|
||||
- **torch.distributed.launch**:
|
||||
|
||||
```python
|
||||
import torch.distributed as dist
|
||||
|
||||
dist.init_process_group(backend='hccl') # HCCL is the backend of the NPU device.
|
||||
```
|
||||
|
||||
- **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)
|
||||
```
|
||||
|
||||
In the preceding commands:
|
||||
|
||||
`pid_idx`: device ID.
|
||||
|
||||
`device_nums_per_node`: number of devices on each AI server.
|
||||
|
||||
3. Initialize the model DDP.
|
||||
|
||||
```python
|
||||
# Instantiate the model.
|
||||
model = ToyModel().to(loc)
|
||||
|
||||
# Load the model weight. It needs to be loaded only on the master node before the DDP model is built.
|
||||
if dist.get_rank() == 0 and ckpt_path is not None:
|
||||
model.load_state_dict(torch.load(ckpt_path))
|
||||
|
||||
# Build the DDP model.
|
||||
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
|
||||
```
|
||||
|
||||
4. Initialize the data 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. Initialize the loss function and optimizer.
|
||||
|
||||
```python
|
||||
# Initialize the optimizer. After the DDP model is built, use the model to initialize the optimizer.
|
||||
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
|
||||
|
||||
# Initialize the loss function.
|
||||
loss_func = nn.CrossEntropyLoss().to(loc)
|
||||
```
|
||||
|
||||
6. Train the DDP model.
|
||||
|
||||
```python
|
||||
model.train()
|
||||
iterator = range(100)
|
||||
for epoch in iterator:
|
||||
# Set 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. Similar to the DP mode, when you save a model, note that model.module instead of model is saved.
|
||||
# That is because the model actually refers to a DDP model, and the parameters are packaged by `model=DDP(model)`.
|
||||
# 2. You only need to save the model on process 0 once to avoid repeated saving.
|
||||
if dist.get_rank() == 0:
|
||||
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
|
||||
```
|
||||
|
||||
### Start the Training
|
||||
|
||||
The training can be started manually or using the shell script.
|
||||
|
||||
- Start the training manually using **torch.distributed.launch**.
|
||||
|
||||
1. Configure NPU environment variables. For details, see the **env_npu.sh** script in the appendix.
|
||||
|
||||
2. Add environment variables. For multi-server training, add the `HCCL_WHITELIST_DISABLE` and `HCCL_IF_IP` environment variables.
|
||||
|
||||
- **HCCL_WHITELIST_DISABLE**: HCCL channel trustlist. The value **1** indicates that the trustlist is disabled.
|
||||
- **HCCL_IF_IP**: initialized IP address of the HCCL communication NIC. Set it to the IP address of the host NIC IP of the current server.
|
||||
|
||||
3. Upload the modified model script to each AI server.
|
||||
|
||||
4. Install the required Python library on each AI server.
|
||||
|
||||
5. Select an AI server as the master node and query the IP address of each AI server.
|
||||
|
||||
6. Run the following commands on each 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
|
||||
```
|
||||
|
||||
In the preceding commands:
|
||||
|
||||
**--nnodes**: number of AI servers used for distributed training scripts.
|
||||
|
||||
**--node_rank**: AI server ID.
|
||||
|
||||
**--nproc_per_node**: number of devices of each AI server.
|
||||
|
||||
**--master_addr**: IP address of the AI server that functions as the master node.
|
||||
|
||||
**--master_port**: port number of the AI server that functions as the master node.
|
||||
|
||||
**main.py**: Change it to the name of the startup script.
|
||||
|
||||
**--addr**: indicates the IP address of the master node, which is a parameter transferred to the startup script.
|
||||
|
||||
- Start the training using Open MPI.
|
||||
|
||||
1. Install the PI open-source library.
|
||||
|
||||
In the multi-server multi-device scenario, distributed training deployment depends on the Open MPI open-source library, which must be installed on each server that participates in model training. Currently, Open MPI 4.0.1, 4.0.2, or 4.0.3 is required.
|
||||
Run the **mpirun --version** command to check whether Open MPI has been installed. If `mpirun (Open MPI) 4.0.2 Report bugs to http://www.open-mpi.org/community/help/` is returned, Open MPI has been installed. If it has been installed and its version is 4.0.1, 4.0.2, or 4.0.3, you do not need to install it again.
|
||||
|
||||
Otherwise, perform the following steps to install it
|
||||
|
||||
1. Visit the following link to download the Open MPI software package, for example, openmpi-4.0.2.tar.bz2.
|
||||
https://www.open-mpi.org/software/ompi/v4.0/
|
||||
|
||||
2. Log in to the installation environment as the root user.
|
||||
|
||||
3. Upload the downloaded Open MPI software package to a directory in the installation environment.
|
||||
|
||||
4. Go to the directory and run the following command to decompress the software package:
|
||||
|
||||
```shell
|
||||
tar -jxvf openmpi-4.0.2.tar.bz2
|
||||
```
|
||||
|
||||
5. Go to the directory generated after the decompression, and run the following commands to configure, compile, and install Open MPI:
|
||||
|
||||
```shell
|
||||
./configure --prefix=/usr/local/mpirun4.0.2
|
||||
make
|
||||
make install
|
||||
```
|
||||
|
||||
The **--prefix** parameter specifies the Open MPI installation path. Change it based on the site requirements.
|
||||
|
||||
6. Run the **vi ~/.bashrc** command to open the **.bashrc** file, and add the following environment variables to the end of the file:
|
||||
|
||||
```shell
|
||||
export OPENMPI=/usr/local/mpirun4.0.2
|
||||
export LD_LIBRARY_PATH=$OPENMPI/lib
|
||||
export PATH=$OPENMPI/bin:$PATH
|
||||
```
|
||||
|
||||
In the environment variables, **/usr/local/mpirun4.0.2** indicates the Open MPI installation path. Change it based on the site requirements.
|
||||
Run the **:wq!** command to save the file and exit.
|
||||
|
||||
7. Make the configuration take effect.
|
||||
|
||||
```
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
8. After the installation is complete, run the following command to check the installation version. If the required version information is displayed, the installation is successful.
|
||||
|
||||
```
|
||||
mpirun --version
|
||||
```
|
||||
|
||||
2. Configure SSH password-free login for the AI servers.
|
||||
|
||||
If Open MPI is used for distributed training deployment in the multi-server multi-device scenario, you need to configure SSH password-free login between every two servers to ensure that the servers can communicate with each other. The procedure is as follows:
|
||||
|
||||
1. Log in to each server as the root user.
|
||||
|
||||
2. Configure the reliability among hosts in the cluster.
|
||||
|
||||
Open the **/etc/ssh/ssh_config** file and add the following fields to the end of the file:
|
||||
|
||||
```
|
||||
StrictHostKeyChecking no
|
||||
UserKnownHostsFile /dev/null
|
||||
```
|
||||
|
||||
3. Open the **/etc/hosts** file on each server and add the corresponding IP address and host name of the server to the first line of the file. If the file already contains the IP address and host name, skip this step. The following is an example of the content to be added:
|
||||
|
||||
```
|
||||
xxx.xxx.xxx.111 ubuntu
|
||||
```
|
||||
|
||||
In the preceding content, **xxx.xxx.xxx.111** is the IP address of the server, and **ubuntu** is the host name.
|
||||
|
||||
4. Run the following commands on the first server to generate a public key (Assume that the IP address of the first server is **xxx.xxx.xxx.111**.):
|
||||
|
||||
```
|
||||
cd ~/.ssh/ # If the directory does not exist, run the ssh localhost command first.
|
||||
ssh-keygen -t rsa # After the key is generated, a message is displayed. Press Enter for three consecutive times.
|
||||
mv id_rsa.pub authorized_keys # Renames the generated key id_rsa.pub to authorized_keys.
|
||||
```
|
||||
|
||||
5. Generate a key on each of the other servers, and copy the keys to the **authorized_keys** file on the first server.
|
||||
|
||||
1. Run the following commands on each of the other servers to generate a key:
|
||||
|
||||
cd ~/.ssh/
|
||||
ssh-keygen -t rsa
|
||||
|
||||
2. Download the key file **id_rsa.pub** generated on each server to the local host and copy the key in the file.
|
||||
|
||||
3. On the first server, run the following command to open the authorized_keys file and copy the keys of each of other servers to the end of the public key of the first server.
|
||||
|
||||
```
|
||||
vi ~/.ssh/authorized_keys
|
||||
```
|
||||
|
||||
Run the **:wq!** command to save the file.
|
||||
|
||||
6. Run the following commands on each of the other servers to copy the public key of the first server to each of the other servers:
|
||||
|
||||
cd ~/.ssh/
|
||||
scp root@xxx.xxx.xxx.111:~/.ssh/authorized_keys ./
|
||||
|
||||
7. Run the following command on each server to test password-free login:
|
||||
|
||||
```
|
||||
ssh User name@IP address
|
||||
```
|
||||
|
||||
For example, run the **ssh root@xxx.xxx.xxx.222** command to log in to the server whose IP address is xxx.xxx.xxx.222 from the first server whose IP address is xxx.xxx.xxx.111 without a password.
|
||||
|
||||
If information similar to the following is displayed, the login without a password is successful.
|
||||
|
||||
```
|
||||
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
|
||||
```
|
||||
|
||||
You can run the **exit** command to log out of the server. If information similar to the following is displayed, the logout is successful.
|
||||
|
||||
```
|
||||
logout
|
||||
Connection to xxx.xxx.xxx.222 closed.
|
||||
```
|
||||
3. Use Open MPI to start model training.
|
||||
|
||||
1. Compile a startup script for each AI server, for example, train.sh, and move the startup script to the same path of the corresponding AI server.
|
||||
|
||||
```
|
||||
# Configure NPU environment variables. For information about the env_npu.sh script, see the appendix.
|
||||
source env_npu.sh
|
||||
#Disable the trustlist of HCCL channel.
|
||||
export HCCL_WHITELIST_DISABLE=1
|
||||
# Initialize the IP address of the HCCL communication NIC , and set the IP address to the host IP address of the current server.
|
||||
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
|
||||
```
|
||||
|
||||
For details about the script parameters, see section "Start the training manually using **torch.distributed.launch**".
|
||||
|
||||
2. Compile the startup script.
|
||||
|
||||
```
|
||||
# Configuring the mpirun environment variables.
|
||||
export PATH=$PATH:/usr/local/mpirun4.0.2/bin
|
||||
# Run the mpirun tool.
|
||||
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
|
||||
```
|
||||
|
||||
In the preceding command:
|
||||
|
||||
**-H**: IP address of each AI server and the number of started processes.
|
||||
|
||||
**--bind-to**: process-binding policy.
|
||||
|
||||
**--mca**: MCA parameter in a specific context. **arg0** is the parameter name, and **arg1** is the parameter value.
|
||||
|
||||
**--allow-run-as-root**: The root user is allowed to run this script.
|
||||
|
||||
**--prefix**: path of mpirun4.0.2.
|
||||
|
||||
**./train.sh**: path of the startup script of each AI server.
|
||||
|
||||
4. View the log information after the training succeeds.
|
||||
|
||||
|
||||
|
||||
Host logs are stored in the `~/ascend/log` directory. You can go to this directory to view the device logs of each host.
|
||||
|
||||
# Appendix
|
||||
|
||||
The following shows the NPU environment variable configuration script **env_npu.sh**, which can be used to configure the operating and development environment variables.
|
||||
|
||||
```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
|
||||
|
||||
#Output host logs to the serial port. 0: disable; 1: enable.
|
||||
export ASCEND_SLOG_PRINT_TO_STDOUT=0
|
||||
#Set the default log level. 0: debug; 1: info; 2: warning; 3: error.
|
||||
export ASCEND_GLOBAL_LOG_LEVEL=3
|
||||
#Enable or disable the event log. 0: disable; 1: enable.
|
||||
export ASCEND_GLOBAL_EVENT_ENABLE=0
|
||||
#Enable or disable taskque. 0: disable; 1: enable.
|
||||
export TASK_QUEUE_ENABLE=1
|
||||
#Enable or disable the HCCL trustlist. 1: disable; 0: enable.
|
||||
export HCCL_WHITELIST_DISABLE=1
|
||||
|
||||
#Set the device-side log to 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
|
||||
#Disable the event log on the device side.
|
||||
${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
|
||||
```
|
||||
@@ -1,475 +0,0 @@
|
||||
# PyTorch Installation Guide
|
||||
|
||||
- [Overview](#overviewa-nameoverviewa)
|
||||
|
||||
- [System Dependencies](#system-dependenciesa-namesystem-dependenciesa)
|
||||
|
||||
- [Ascend Auxiliary Software](#ascend-auxiliary-softwarea-nameascend-auxiliary-softwarea)
|
||||
|
||||
- [Installation Methods](#installation-methodsa-nameinstallation-methodsa)
|
||||
|
||||
- [Running](#runninga-namerunninga)
|
||||
- [(Optional) Installing the Mixed Precision Module](#optional-installing-the-mixed-precision-modulea-nameoptional-installing-the-mixed-precision-modulea)
|
||||
- [FAQs](#faqsa-namefaqsa)
|
||||
- [Version Descriptio](#version-descriptiona-nameversion-descriptiona)
|
||||
|
||||
# Overview<a name="Overview"></a>
|
||||
|
||||
This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch framework so that developers who use the PyTorch framework can obtain powerful compute capabilities of Ascend AI Processors. When setting up the environments for PyTorch model development and operating, developers can manually compile related modules on servers.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- The development or operating environment of CANN has been installed. For details, see the *CANN Software Installation Guide*.
|
||||
- Python 3.7.5, 3.8, and 3.9 are supported.
|
||||
|
||||
# System Dependencies<a name="System-Dependencies"></a>
|
||||
|
||||
## CentOS & EulerOS
|
||||
|
||||
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
|
||||
|
||||
yum install -y gcc==7.3.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
|
||||
|
||||
> **NOTE:**
|
||||
>If an error occurs during the installation of the GCC and CMake dependency commands, use the source code for installation. For details, see the FAQ.
|
||||
|
||||
# Ascend Auxiliary Software<a name="Ascend-Auxiliary-Software"></a>
|
||||
|
||||
| AscendPyTorch Version| CANN Version| Supported PyTorch Version| Gitee Branch|
|
||||
| :------------ | :----------- | :----------- | ------------- |
|
||||
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
|
||||
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
|
||||
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
|
||||
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
|
||||
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
|
||||
|
||||
# Installation Methods<a name="Installation-Methods"></a>
|
||||
|
||||
## Install the PyTorch environment dependencies.
|
||||
|
||||
If you install dependencies as a non-root user, add **--user** at the end of each command in this step, for example, **pip3 install pyyaml --user**.
|
||||
|
||||
```sh
|
||||
pip3 install pyyaml
|
||||
pip3 install wheel
|
||||
```
|
||||
|
||||
## Compile and install the PyTorch and Ascend plugin.
|
||||
|
||||
Install the official torch package, and then compile and install the plugin.
|
||||
|
||||
```sh
|
||||
#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.
|
||||
|
||||
#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.
|
||||
```
|
||||
|
||||
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
|
||||
cd pytorch
|
||||
# Specify the Python version packaging mode:
|
||||
bash ci/build.sh --python=3.7
|
||||
# or
|
||||
bash ci/build.sh --python=3.8
|
||||
#or
|
||||
bash ci/build.sh --python=3.9
|
||||
```
|
||||
|
||||
Install the **torch_npu** package generated in the **pytorch/dist** directory. *{arch}* indicates the architecture name.
|
||||
|
||||
```
|
||||
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
|
||||
```
|
||||
Download TorchVision.
|
||||
```
|
||||
pip3 install torchvision==0.9.1
|
||||
```
|
||||
|
||||
|
||||
# Running<a name="Running"></a>
|
||||
|
||||
## Execute environment variables.
|
||||
|
||||
Run the script for setting environment variables in the root directory of the current repository.
|
||||
|
||||
```
|
||||
source env.sh
|
||||
```
|
||||
|
||||
|
||||
## Customize environment variables.
|
||||
|
||||
The following are optional environment variables that may affect running models:
|
||||
|
||||
```
|
||||
export COMBINED_ENABLE=1 # (Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency.
|
||||
export ACL_DUMP_DATA=1 # (Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.
|
||||
```
|
||||
**Table 1** Description of environment variables
|
||||
<a name="zh-cn_topic_0000001152616261_table42017516135"></a>
|
||||
|
||||
<table><thead align="left"><tr id="zh-cn_topic_0000001152616261_row16198951191317"><th class="cellrowborder" valign="top" width="55.48%" id="mcps1.2.3.1.1"><p id="zh-cn_topic_0000001152616261_p51981251161315"><a name="zh-cn_topic_0000001152616261_p51981251161315"></a><a name="zh-cn_topic_0000001152616261_p51981251161315"></a>Environment Variable</p>
|
||||
</th>
|
||||
<th class="cellrowborder" valign="top" width="44.519999999999996%" id="mcps1.2.3.1.2"><p id="zh-cn_topic_0000001152616261_p9198135114133"><a name="zh-cn_topic_0000001152616261_p9198135114133"></a><a name="zh-cn_topic_0000001152616261_p9198135114133"></a>Description</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row78312162301"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1832171673019"><a name="p1832171673019"></a><a name="p1832171673019"></a>COMBINED_ENABLE</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency. However, the host delivery performance may deteriorate.</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr id="row183041355123411"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p730435533415"><a name="p730435533415"></a><a name="p730435533415"></a>ACL_DUMP_DATA</p>
|
||||
</td>
|
||||
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p16304105533412"><a name="p16304105533412"></a><a name="p16304105533412"></a>(Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.</p>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
|
||||
|
||||
## Run the unit test script.
|
||||
|
||||
Verify the running. The output is **OK**.
|
||||
|
||||
```shell
|
||||
cd test/test_network_ops/
|
||||
python3 test_div.py
|
||||
```
|
||||
|
||||
# (Optional) Installing the Mixed Precision Module<a name="(Optional) Installing the Mixed Precision Module"></a>
|
||||
|
||||
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.
|
||||
|
||||
- AMP
|
||||
|
||||
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
|
||||
- Tensor fusion is not supported.
|
||||
|
||||
- Apex
|
||||
|
||||
- O1 configuration mode: Conv and Matmul use the float16 precision for computing, and Softmax and BN use float32.
|
||||
- O2 configuration mode: BN uses the float32 precision for computing, and others use float16.
|
||||
- Static loss scale: Parameters are statically set to ensure the convergence of training with mixed precision.
|
||||
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
|
||||
|
||||
|
||||
# FAQs<a name="FAQs"></a>
|
||||
|
||||
## 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.
|
||||
|
||||
Download the PyTorch 1.8.1 source package.
|
||||
|
||||
```
|
||||
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
|
||||
```
|
||||
|
||||
Access the source package to obtain the passive dependency code.
|
||||
|
||||
```
|
||||
cd pytorch_v1.8.1
|
||||
git submodule sync
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
Compile and install PyTorch 1.8.1.
|
||||
|
||||
```
|
||||
python3 setup.py install
|
||||
```
|
||||
|
||||
## When PIP is set to the Huawei source, a Python environment error occurs after the typing dependency in the **requirements.txt** file is installed.
|
||||
|
||||
When PIP is set to the Huawei source, open the **requirements.txt** file, delete the typing dependency, and then run the following command:
|
||||
|
||||
```
|
||||
pip3 install -r requirments.txt
|
||||
```
|
||||
|
||||
## The error message "no module named yaml/typing_extensions." is displayed when **bash build.sh** is run during compilation.
|
||||
|
||||
PyTorch compilation depends on the YAML and typing_extensions libraries, which need to be manually installed.
|
||||
|
||||
```
|
||||
pip3 install pyyaml
|
||||
|
||||
pip3 install typing_extensions
|
||||
```
|
||||
|
||||
After the installation is successful, run **make clean** and then **bash build.sh** to perform compilation. Otherwise, an unknown compilation error may occur due to the cache.
|
||||
|
||||
## TE cannot be found during running.
|
||||
|
||||
Development state:
|
||||
|
||||
```
|
||||
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 # {arch} is the architecture name.
|
||||
|
||||
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
|
||||
|
||||
pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
```
|
||||
|
||||
User state:
|
||||
|
||||
```
|
||||
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 # {arch} is the architecture name.
|
||||
|
||||
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
|
||||
|
||||
pip3 install --upgrade te-0.4.0-py3-none-any.whl
|
||||
```
|
||||
|
||||
## During CMake installation through the CLI, an error is reported indicating that the package cannot be found. During CMake compilation, another error is reported indicating that the version is too early. In this cause, you can use the installation script or source code to compile and install CMake.
|
||||
|
||||
Method 1: Download the installation script and install CMake. (For details, see the CMake official website.)
|
||||
|
||||
x86_64 environment: cmake-3.12.0-Linux-x86_64.sh
|
||||
AArch64 environment: cmake-3.12.0-Linux-aarch64.sh
|
||||
1. Run the following command:
|
||||
|
||||
```
|
||||
./cmake-3.12.0-Linux-{arch}.sh # {arch} indicates the architecture name.
|
||||
```
|
||||
|
||||
2. Set the soft link.
|
||||
|
||||
```
|
||||
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
|
||||
```
|
||||
|
||||
3. Run the following command to check whether CMake has been installed:
|
||||
|
||||
```
|
||||
cmake --version
|
||||
```
|
||||
|
||||
If the message "cmake version 3.12.0" is displayed, the installation is successful.
|
||||
|
||||
Method 2: Use the source code to compile and install.
|
||||
|
||||
1. Obtain the CMake software package.
|
||||
|
||||
```
|
||||
wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
|
||||
```
|
||||
|
||||
2. Decompress the package and go to the software package directory.
|
||||
|
||||
```
|
||||
tar -xf cmake-3.12.0.tar.gz
|
||||
cd cmake-3.12.0/
|
||||
```
|
||||
|
||||
3. Run the configuration, compilation, and installation commands.
|
||||
|
||||
```
|
||||
./configure --prefix=/usr/local/cmake
|
||||
make && make install
|
||||
```
|
||||
|
||||
4. Set the soft link.
|
||||
|
||||
```
|
||||
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
|
||||
```
|
||||
|
||||
5. Run the following command to check whether CMake has been installed:
|
||||
|
||||
```
|
||||
cmake --version
|
||||
```
|
||||
|
||||
If the message "cmake version 3.12.0" is displayed, the installation is successful.
|
||||
|
||||
## During GCC installation through the CLI, an error is reported indicating that the package cannot be found. During GCC compilation, another error is reported.
|
||||
|
||||
When downloading GCC from some sources, you may be prompted by an error message indicating that the package cannot be found. In this case, use the source code to compile and install GCC.
|
||||
|
||||
Perform the following steps as the **root** user.
|
||||
|
||||
1. Download **gcc-7.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).
|
||||
|
||||
2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
|
||||
|
||||
```
|
||||
sudo rm -rf /tmp/*
|
||||
```
|
||||
|
||||
3. Install the dependency package. (CentOS and Ubuntu are used as examples.)
|
||||
|
||||
- For CentOS, run the following command:
|
||||
|
||||
```
|
||||
yum install bzip2
|
||||
```
|
||||
|
||||
- For Ubuntu, run the following command:
|
||||
|
||||
```
|
||||
apt-get install bzip2
|
||||
```
|
||||
|
||||
4. Compile and install GCC.
|
||||
|
||||
1. Go to the directory where the source package **gcc-7.3.0.tar.gz** is located and run the following command to decompress it:
|
||||
|
||||
```
|
||||
tar -zxvf gcc-7.3.0.tar.gz
|
||||
```
|
||||
|
||||
2. Go to the extracted directory and download the GCC dependency packages:
|
||||
|
||||
```
|
||||
cd gcc-7.3.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:
|
||||
|
||||
```
|
||||
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
|
||||
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
|
||||
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
|
||||
wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
|
||||
```
|
||||
|
||||
After the preceding dependencies are downloaded, run the following command again:
|
||||
|
||||
```
|
||||
./contrib/download_prerequisites
|
||||
```
|
||||
|
||||
If the verification fails, check whether there are duplicate dependency packages in the folder. If yes, delete duplicate ones.
|
||||
|
||||
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>Run the configuration, compilation, and installation commands.
|
||||
|
||||
```
|
||||
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.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**.
|
||||
4. Change the soft links.
|
||||
|
||||
```
|
||||
ln -s ${install_path}/bin/gcc /usr/bin/gcc
|
||||
ln -s ${install_path}/bin/g++ /usr/bin/g++
|
||||
ln -s ${install_path}/bin/c++ /usr/bin/c++
|
||||
```
|
||||
|
||||
5. Configure environment variables.
|
||||
|
||||
Training must be performed in the compilation environment with GCC upgraded. If you want to run training, configure the following environment variable in your training script:
|
||||
|
||||
```
|
||||
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
|
||||
```
|
||||
|
||||
**${install_path}** indicates the GCC 7.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/linux_gcc7.3.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)
|
||||
|
||||
## libblas.so cannot be found.
|
||||
|
||||
The OpenBLAS library is missing in the environment. You need to install it.
|
||||
|
||||
CentOS and EulerOS
|
||||
|
||||
```sh
|
||||
yum -y install openblas
|
||||
```
|
||||
|
||||
Ubuntu
|
||||
|
||||
```sh
|
||||
apt install libopenblas-dev
|
||||
```
|
||||
|
||||
## No device is mounted to the container.
|
||||
|
||||
An NPU-related error is reported when a script is run in the container. The **device** parameter is not set before container instance startup. As a result, the instance cannot be started.
|
||||
|
||||

|
||||
|
||||
Run the following command to restart the container:
|
||||
|
||||
```sh
|
||||
docker run -it --ipc=host \
|
||||
--device=/dev/davinciX \
|
||||
--device=/dev/davinci_manager \
|
||||
--device=/dev/devmm_svm \
|
||||
--device=/dev/hisi_hdc \
|
||||
-v /usr/local/Ascend/driver \
|
||||
-v /usr/local/dcmi \
|
||||
-v /usr/local/bin/npu-smi \
|
||||
${image name}:{tag} \
|
||||
/bin/bash
|
||||
```
|
||||
|
||||
Parameter description:
|
||||
|
||||
**/dev/davinci*X***: NPU device. *X* is the physical ID of the chip, for example, **davinci0**.
|
||||
|
||||
**/dev/davinci_manager**: management device
|
||||
|
||||
**/dev/devmm_svm**: management device
|
||||
|
||||
**/dev/hisi_hdc**: management device
|
||||
|
||||
**/usr/local/Ascend/driver**: driver directory
|
||||
|
||||
**/usr/local/dcmi**: DCMI directory
|
||||
|
||||
**/usr/local/bin/npu-smi**: npu-smi tool
|
||||
|
||||
**$*{image name}:{tag}***: image name and version
|
||||
|
||||
## An error is displayed during installation of -torch--whl-, indicating that -torch-1-5-0xxxx- and -torchvision- versions do not match.
|
||||
|
||||
During installation of **torch-\*.whl**, the message "ERROR: torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible" is displayed.
|
||||

|
||||
|
||||
When the PyTorch is installed, the version check is automatically triggered. The version of the torchvision installed in the environment is 0.6.0. During the check, it is found that the version of the **torch-\*.whl** is inconsistent with the required version 1.5.0. As a result, an error message is displayed, but the installation is successful.
|
||||
|
||||
This problem does not affect the actual result, and no action is required.
|
||||
|
||||
## When you run **import torch_npu**, if "_has_compatible_shallow_copy_type" is output, a warning about a repeated registration error is displayed.
|
||||
|
||||
The warning is triggered by the shallow copy operation of **Tensor.set_data**, as shown in the following figure. The main cause is that after the PyTorch plugin is decoupled, `_has_compatible_shallow_copy_type` cannot detect shallow copy of NPU tensors. You need to register `_has_compatible_shallow_copy_type` again.
|
||||
|
||||
This error can be ignored because it does not affect the model accuracy and performance.
|
||||
|
||||
It will be resolved after the NPU's device ID is incorporated into the community or the `_has_compatible_shallow_copy_type` registration mode is changed in a later PyTorch version.
|
||||
|
||||

|
||||
## An error is reported when torch_npu is referenced with Python commands in the compilation directory.
|
||||
|
||||
To verify the torch_npu reference, switch to another directory. If you perform the verification in the compilation directory, the following error message is displayed:
|
||||
|
||||
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
|
||||
|
||||
# Version Description<a name='Version Description'></a>
|
||||
|
||||
For details, see [Release Notes](https://gitee.com/ascend/pytorch/tree/master/docs/en/RELEASENOTE).
|
||||
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 29 KiB |
|
Before Width: | Height: | Size: 40 KiB |
|
Before Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 8.0 KiB |
|
Before Width: | Height: | Size: 51 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 61 KiB |
|
Before Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 9.2 KiB |
|
Before Width: | Height: | Size: 356 B |
|
Before Width: | Height: | Size: 946 B |
|
Before Width: | Height: | Size: 946 B |
|
Before Width: | Height: | Size: 356 B |
|
Before Width: | Height: | Size: 329 KiB |
|
Before Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 607 KiB |
|
Before Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 74 KiB |
|
Before Width: | Height: | Size: 51 KiB |
|
Before Width: | Height: | Size: 51 KiB |
|
Before Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 7.8 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 66 KiB |
|
Before Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 126 KiB |
|
Before Width: | Height: | Size: 56 KiB |
|
Before Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 59 KiB |
|
Before Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 140 KiB |
|
Before Width: | Height: | Size: 26 KiB |
|
Before Width: | Height: | Size: 76 KiB |
|
Before Width: | Height: | Size: 7.2 KiB |