Compare commits

..
60 Commits
Author SHA1 Message Date
i-robot 7c3acf31cf !33 同步 3cd6fe790d2af7fc618bde1f17ae347c42438c83
Merge pull request !33 from weili10/2.0.2.tr5
2021-07-29 09:33:05 +00:00
i-robot 7d7070c344 !27 文档修改命名格式归档
Merge pull request !27 from yinzijun/2.0.2.tr5
2021-07-29 09:17:03 +00:00
张昱杰 18396d4937 update scripts/mkdirs.sh. 2021-07-29 09:12:39 +00:00
weili10 7a563bcc03 同步3cd6fe790d2af7fc618bde1f17ae347c42438c83 2021-07-29 17:01:23 +08:00
ZijunYin ac4e725c80 add RELEASENOTE 2021-07-29 16:51:58 +08:00
ZijunYin 68eac297da change name of releasenote 2021-07-29 16:49:07 +08:00
i-robot 49347eadd2 !32 增加版权声明
Merge pull request !32 from weili10/2.0.2.tr5
2021-07-29 08:01:07 +00:00
weili10 36bc73fc7c 增加版权声明 2021-07-29 15:51:35 +08:00
weili10 def54c93b6 update README.zh.md. 2021-07-29 06:46:26 +00:00
i-robot 2ef2eed751 !31 解决原生pytorch中dos编码文件打patch报错问题
Merge pull request !31 from weili10/2.0.2.tr5
2021-07-29 03:27:04 +00:00
weili10 c757565613 解决原生pytorch中dos编码文件打patch报错问题 2021-07-29 10:53:20 +08:00
i-robot a933722394 !28 增加开源软件使用说明
Merge pull request !28 from weili10/2.0.2.tr5
2021-07-29 01:15:03 +00:00
weili10 a584a4e5f2 增加开源软件使用说明 2021-07-28 21:50:56 +08:00
ZijunYin 2f58ad99a0 update docs, add releasenote 2021-07-28 20:45:59 +08:00
ZijunYin 3323c4eecb update docs with new file name and icons 2021-07-27 17:03:50 +08:00
weili10 92f2f166e4 update README.zh.md. 2021-07-27 06:53:49 +00:00
weili10 98ffda59bb update README.zh.md. 2021-07-27 06:50:50 +00:00
weili10 c0989a8a1f update README.zh.md. 2021-07-27 06:50:08 +00:00
weili10 2141b0eb57 !20 同步062fd2fe1728234949b75ce9d1b07267074a8243
Merge pull request !20 from weili10/2.0.2.tr5
2021-07-17 11:46:01 +00:00
weili10 34b3fd413d 同步062fd2fe1728234949b75ce9d1b07267074a8243 2021-07-17 19:42:55 +08:00
weili10 424e4d3c91 update LICENSE. 2021-07-16 13:43:16 +00:00
weili10 982bf7a05b !18 同步c59af4f05ca3150b272cfc2bfa956cf37b7f6291
Merge pull request !18 from weili10/2.0.2.tr5
2021-07-16 13:42:18 +00:00
weili10 54606dd727 同步c59af4f05ca3150b272cfc2bfa956cf37b7f6291 2021-07-16 18:43:32 +08:00
weili10 1a0abe14d7 !15 [Task]新版本文档归档
Merge pull request !15 from fenghaolin/2.02tr5
2021-07-14 13:52:03 +00:00
fenghaolin 1f2e7c6d71 新版本资料归档 2021-07-14 21:40:06 +08:00
weili10 2f43a92d76 !12 同步 16c245707319972d9ae24d6c4e0863abdeaca6b6
Merge pull request !12 from weili10/2.0.2.tr5
2021-07-14 06:18:00 +00:00
weili10 7f158abe29 同步 16c245707319972d9ae24d6c4e0863abdeaca6b6 2021-07-14 14:13:54 +08:00
weili10 1f2771b747 update LICENSE. 2021-07-14 05:52:26 +00:00
weili10 bbdfd6c0ea update LICENSE. 2021-07-14 03:54:54 +00:00
weili10 a27e4f60c6 !11 同步44740072b1b0ea6a5b63ef7203bab73f986e2472
Merge pull request !11 from weili10/master
2021-07-13 07:55:04 +00:00
weili10 ae48832f81 同步44740072b1b0ea6a5b63ef7203bab73f986e2472 2021-07-13 15:52:09 +08:00
weili10 08403764d6 !10 优化readme中命令执行目录说明
Merge pull request !10 from weili10/master
2021-07-12 12:26:05 +00:00
weli10 998d0c88b9 优化readme中命令执行目录说明 2021-07-12 20:24:20 +08:00
张昱杰 7a0a5a6eb0 !5 [Task]添加docs文件夹中的文档
Merge pull request !5 from fenghaolin/0706
2021-07-09 09:54:27 +00:00
张昱杰 cb9b8627b9 !8 同步42f3827ef92a65a09eee3dd1a9f527de774f5da2
Merge pull request !8 from 张昱杰/master
2021-07-09 09:52:37 +00:00
ascendzyj 6b80c3e7d6 Merge branch 'master' of https://gitee.com/ascend/pytorch into master 2021-07-09 17:47:57 +08:00
weili10 b6069682fd !7 修改命名
Merge pull request !7 from 张昱杰/master
2021-07-09 09:47:39 +00:00
ascendzyj 9cb7f795df Merge branch 'master' of https://gitee.com/ascend/pytorch into master 2021-07-09 17:44:15 +08:00
ascendzyj 7024d04779 同步42f3827ef92a65a09eee3dd1a9f527de774f5da2 2021-07-09 17:43:07 +08:00
z00444290 70f0613df8 修改命名 2021-07-09 16:55:01 +08:00
z00444290 2468dd37ae 修改生成代码和编译脚本 2021-07-08 21:29:58 +08:00
张昱杰 7446763b5f !6 删除URL信息
Merge pull request !6 from 张昱杰/master
2021-07-08 02:25:23 +00:00
ascendzyj a45cb145e9 删除URL信息 2021-07-07 13:54:50 +08:00
fenghaolin 6bbc1db7d2 新增网络模型移植&训练指南 2021-07-06 11:35:16 +08:00
fenghaolin 59d9f9fe86 新增在线推理指南 2021-07-06 11:34:55 +08:00
fenghaolin c682f1e267 新增API支持清单 2021-07-06 11:34:38 +08:00
fenghaolin 1505864443 新增PyTorch适配算子清单 2021-07-06 11:34:19 +08:00
fenghaolin fdfb70af54 新增开发指南 2021-07-06 11:33:56 +08:00
fenghaolin aac3e9f237 添加算子清单 2021-07-06 11:33:16 +08:00
fenghaolin cb5937bf50 删除不需要的内容 2021-07-06 11:32:45 +08:00
fenghaolin 45a79b8865 Merge branch 'master' of https://gitee.com/ascend/pytorch 2021-07-06 11:30:14 +08:00
i-robot 18a27fad1f !4 同步f2209ee61066ae89d4efd1782a30b6235e0e0548
Merge pull request !4 from 张昱杰/master
2021-07-05 11:05:18 +00:00
ascendzyj 2ae4953208 同步f2209ee61066ae89d4efd1782a30b6235e0e0548 2021-07-05 17:14:18 +08:00
i-robot 2e90ba92b9 !3 同步739736a13b52b3203c116ea551f82c78aefe9bee
Merge pull request !3 from 张昱杰/master
2021-06-26 02:30:51 +00:00
ascendzyj dfb77c9348 同步739736a13b52b3203c116ea551f82c78aefe9bee 2021-06-26 09:52:46 +08:00
fenghaolin eca80895e7 添加CRNN文档 2021-06-26 09:11:03 +08:00
i-robot 30722c29f5 !1 [Task]补充CONTRIBUTING.zh.md文件
Merge pull request !1 from fenghaolin/master
2021-06-25 06:44:06 +00:00
fenghaolin e0003631b5 添加CONTRIBUTING.zh.md 2021-06-25 08:35:53 +08:00
ascendzyj a83ecb1f7f init repo pytorch-develop of f14e649790d60cc88e60460743b0038cc00346c9 2021-06-24 16:41:42 +08:00
张昱杰 b2b33bd531 Initial commit 2021-06-24 08:13:55 +00:00
2530 changed files with 188061 additions and 433117 deletions
-24
View File
@@ -1,24 +0,0 @@
<!-- Thanks for sending a pull request!
-->
**What type of PR is this?**
> Uncomment only one ` /kind <>` line, hit enter to put that in a new line, and remove leading whitespaces from that line:
>
> /kind bug
> /kind task
> /kind feature
**What does this PR do / why do we need it**:
**Which issue(s) this PR fixes**:
<!--
*Automatically closes linked issue when PR is merged.
Usage: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
-->
Fixes #
**Special notes for your reviewers**:
-204
View File
@@ -1,204 +0,0 @@
# READ THIS BEFORE YOU REFACTOR ME
#
# setup.py uses the list of patterns in this file to decide
# what to delete, but it's not 100% sound. So, for example,
# if you delete aten/build/ because it's redundant with build/,
# aten/build/ will stop being cleaned. So be careful when
# refactoring this file!
## PyTorch
.coverage
coverage.xml
.dmypy.json
.gradle
.hypothesis
.mypy_cache
*/*.so*
*/**/__pycache__
*/**/*.dylib*
*/**/*.pyd
*/**/*.so*
log
# Root level file used in CI to specify certain env configs.
# E.g., see .circleci/config.yaml
env
.circleci/scripts/COMMIT_MSG
# IPython notebook checkpoints
.ipynb_checkpoints
# Editor temporaries
*.swn
*.swo
*.swp
*.swm
*~
# macOS dir files
.DS_Store
# Ninja files
.ninja_deps
.ninja_log
compile_commands.json
*.egg-info/
## General
# Compiled Object files
*.slo
*.lo
*.o
*.cuo
*.obj
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Compiled protocol buffers
*.pb.h
*.pb.cc
*_pb2.py
# Compiled python
*.pyc
*.pyd
# Compiled MATLAB
*.mex*
# IPython notebook checkpoints
.ipynb_checkpoints
# Editor temporaries
*.swn
*.swo
*.swp
*~
# Sublime Text settings
*.sublime-workspace
*.sublime-project
# Eclipse Project settings
*.*project
.settings
# QtCreator files
*.user
# PyCharm files
.idea
# OSX dir files
.DS_Store
# GDB history
.gdb_history
## Caffe2
# build, distribute, and bins (+ python proto bindings)
build
build_host_protoc
build_android
build_ios
/build_*
.build_debug/*
.build_release/*
.build_profile/*
distribute/*
*.testbin
*.bin
cmake_build
.cmake_build
gen
.setuptools-cmake-build
.pytest_cache
aten/build/*
dist
# Bram
plsdontbreak
# Generated documentation
docs/_site
docs/gathered
_site
doxygen
docs/dev
# LevelDB files
*.sst
*.ldb
LOCK
CURRENT
MANIFEST-*
# generated version file
caffe2/version.py
# setup.py intermediates
.eggs
caffe2.egg-info
# Atom/Watchman required file
.watchmanconfig
# Files generated by CLion
cmake-build-debug
# BEGIN NOT-CLEAN-FILES (setup.py handles this marker. Do not change.)
#
# Below files are not deleted by "setup.py clean".
# Visual Studio Code files
.vscode
.vs
# YouCompleteMe config file
.ycm_extra_conf.py
# Files generated when a patch is rejected
*.orig
*.rej
# Files generated by ctags
CTAGS
GTAGS
GRTAGS
GSYMS
GPATH
tags
TAGS
# ccls file
.ccls-cache/
# clang-format storage location used by apply_clang_format.py
.clang-format-bin
# clangd background index
.clangd/
.cache/
# 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
torch_npu/_op_plugin_docs.py
-19
View File
@@ -1,19 +0,0 @@
[submodule "third_party/op-plugin"]
path = third_party/op-plugin
url = https://gitcode.com/ascend/op-plugin.git
ignore = dirty
[submodule "third_party/googletest"]
path = third_party/googletest
url = https://gitee.com/mirrors/googletest.git
[submodule "third_party/torchair/torchair"]
path = third_party/torchair/torchair
url = https://gitcode.com/ascend/torchair.git
[submodule "third_party/Tensorpipe"]
path = third_party/Tensorpipe
url = https://gitcode.com/ascend/Tensorpipe.git
[submodule "third_party/fmt"]
path = third_party/fmt
url = https://gitee.com/mirrors/fmt.git
[submodule "third_party/nlohmann"]
path = third_party/nlohmann
url = https://gitee.com/mirrors/nlohmann-json.git
-362
View File
@@ -1,362 +0,0 @@
cmake_minimum_required(VERSION 3.18 FATAL_ERROR)
find_program(CCACHE ccache)
if(${CCACHE} STREQUAL "CCACHE-NOTFOUND")
message(STATUS "Compile without ccache")
else()
set(CMAKE_C_COMPILER_LAUNCHER ${CCACHE} CACHE PATH "cache Compiler")
set(CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE} CACHE PATH "cache Compiler")
message(STATUS "CMAKE_C_COMPILER_LAUNCHER:${CMAKE_C_COMPILER_LAUNCHER}")
message(STATUS "CMAKE_CXX_COMPILER_LAUNCHER:${CMAKE_CXX_COMPILER_LAUNCHER}")
endif()
project(TORCHNPU CXX C)
set(LINUX TRUE)
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)
set(CMAKE_SKIP_BUILD_RPATH FALSE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH "${RPATH_VALUE}/lib/:${RPATH_VALUE}/")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${TORCHNPU_INSTALL_LIBDIR})
SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
SET(CMAKE_CXX_FLAGS_RELEASE "-O2")
SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -g")
# LTO&PGO optimization in compile option
SET(IF_APPEND FALSE)
if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
SET(APPEND_FLAGS "-fGNU-compatibility -fuse-ld=lld -Wno-non-pod-varargs")
if (DEFINED ENABLE_LTO)
SET(IF_APPEND TRUE)
SET(APPEND_FLAGS "${APPEND_FLAGS} -flto=thin")
endif()
if (DEFINED PGO_MODE)
SET(IF_APPEND TRUE)
if (PGO_MODE EQUAL 1)
SET(APPEND_FLAGS "${APPEND_FLAGS} -fprofile-generate")
elseif (PGO_MODE EQUAL 2)
SET(APPEND_FLAGS "${APPEND_FLAGS} -fprofile-use=${CMAKE_CURRENT_SOURCE_DIR}/default.profdata")
endif()
endif()
else()
if (DEFINED ENABLE_LTO)
message(FATAL_ERROR "Currently, LTO auto build is not supported in ${CMAKE_CXX_COMPILER_ID}")
endif()
if (DEFINED PGO_MODE)
message(FATAL_ERROR "Currently, PGO auto build is not supported in ${CMAKE_CXX_COMPILER_ID}")
endif()
endif()
if (IF_APPEND)
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${APPEND_FLAGS}")
endif()
# check and set CMAKE_CXX_STANDARD
string(FIND "${CMAKE_CXX_FLAGS}" "-std=c++" env_cxx_standard)
if(env_cxx_standard GREATER -1)
message(
WARNING "C++ standard version definition detected in environment variable."
"PyTorch requires -std=c++17. Please remove -std=c++ settings in your environment.")
endif()
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(TORCHNPU_ROOT "${PROJECT_SOURCE_DIR}/torch_npu/csrc")
set(TORCHNPU_THIRD_PARTY_ROOT "${PROJECT_SOURCE_DIR}/third_party")
set(Torch_DIR ${PYTORCH_INSTALL_DIR}/share/cmake/Torch)
FIND_PACKAGE(Torch REQUIRED)
set(LINUX TRUE)
set(CMAKE_INSTALL_MESSAGE NEVER)
#set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Define build type
IF(CMAKE_BUILD_TYPE MATCHES Debug)
message("Debug build.")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_DEBUG")
ELSEIF(CMAKE_BUILD_TYPE MATCHES RelWithDebInfo)
message("RelWithDebInfo build")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DNDEBUG")
ELSE()
message("Release build.")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DNDEBUG")
ENDIF()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-narrowing")
# Eigen fails to build with some versions, so convert this to a warning
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wextra")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-missing-field-initializers")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-type-limits")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-array-bounds")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-pragmas")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-sign-compare")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-function")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-result")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-strict-overflow")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-strict-aliasing")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=deprecated-declarations")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-ignored-qualifiers")
if (CMAKE_COMPILER_IS_GNUCXX AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0))
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-stringop-overflow")
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=pedantic")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=redundant-decls")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=old-style-cast")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__FILENAME__='\"$(notdir $(abspath $<))\"'")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-builtin-macro-redefined -D__FILE__='\"$(subst $(realpath ${CMAKE_SOURCE_DIR})/,,$(abspath $<))\"'")
# These flags are not available in GCC-4.8.5. Set only when using clang.
if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-invalid-partial-specialization")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-typedef-redefinition")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-warning-option")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-private-field")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-inconsistent-missing-override")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-aligned-allocation-unavailable")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-c++17-extensions")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-constexpr-not-const")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-missing-braces")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Qunused-arguments")
if (${COLORIZE_OUTPUT})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fcolor-diagnostics")
endif()
endif()
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.9)
if (${COLORIZE_OUTPUT})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color=always")
endif()
endif()
if ((APPLE AND (NOT ("${CLANG_VERSION_STRING}" VERSION_LESS "9.0")))
OR (CMAKE_COMPILER_IS_GNUCXX
AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0 AND NOT APPLE)))
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -faligned-new")
endif()
if (WERROR)
check_cxx_compiler_flag("-Werror" COMPILER_SUPPORT_WERROR)
if (NOT COMPILER_SUPPORT_WERROR)
set(WERROR FALSE)
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
endif()
endif(WERROR)
if (NOT APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-but-set-variable")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-uninitialized")
endif()
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -O0")
set(CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_STATIC_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -O0")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-math-errno")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-trapping-math")
set(CMAKE_CXX_COVERAGE $ENV{CALCULATE_CXX_COVERAGE})
if (CMAKE_BUILD_TYPE MATCHES Debug)
set(CMAKE_C_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CMAKE_CXX_FLAGS}")
set(CXXFLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CXXFLAGS}")
elseif (CMAKE_CXX_COVERAGE STREQUAL "1")
set(CMAKE_C_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fprofile-arcs -ftest-coverage -fPIE -pie ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fprofile-arcs -ftest-coverage -fPIE -pie ${CMAKE_CXX_FLAGS}")
set(CXXFLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fprofile-arcs -ftest-coverage -fPIE -pie ${CXXFLAGS}")
else()
set(CMAKE_C_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CMAKE_CXX_FLAGS}")
set(CXXFLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CXXFLAGS}")
endif()
if (NOT DEFINED GLIBCXX_USE_CXX11_ABI)
set(GLIBCXX_USE_CXX11_ABI 0)
endif()
message(STATUS "Determined _GLIBCXX_USE_CXX11_ABI=${GLIBCXX_USE_CXX11_ABI}")
set(_GLIBCXX_USE_CXX11_ABI ${GLIBCXX_USE_CXX11_ABI})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_GLIBCXX_USE_CXX11_ABI=${GLIBCXX_USE_CXX11_ABI}")
if (${GLIBCXX_USE_CXX11_ABI} EQUAL 0)
set(CMAKE_CXX_FLAGS "-fabi-version=11 ${CMAKE_CXX_FLAGS}")
else()
set(CXX_STANDARD_REQUIRED ON)
if (DEFINED ABI_VERSION)
set(CMAKE_CXX_FLAGS "-fabi-version=${ABI_VERSION} ${CMAKE_CXX_FLAGS}")
endif()
endif()
if (DEFINED BUILD_LIBTORCH)
add_compile_definitions(BUILD_LIBTORCH)
endif()
include_directories(${PROJECT_SOURCE_DIR})
include_directories(${PROJECT_SOURCE_DIR}/torch_npu/csrc/aten)
include_directories(${PROJECT_SOURCE_DIR}/third_party/hccl/inc)
include_directories(${PROJECT_SOURCE_DIR}/third_party/acl/inc)
include_directories(${PROJECT_SOURCE_DIR}/third_party/Tensorpipe)
include_directories(${PROJECT_SOURCE_DIR}/third_party/nlohmann/include)
# Set installed PyTorch dir
if(DEFINED PYTORCH_INSTALL_DIR)
include_directories(${PYTORCH_INSTALL_DIR}/include)
include_directories(${PYTORCH_INSTALL_DIR}/include/torch/csrc/api/include)
include_directories(${PYTORCH_INSTALL_DIR}/include/torch/csrc/distributed)
else()
message(FATAL_ERROR "Cannot find installed PyTorch directory")
endif()
# Set Python include dir
if(DEFINED PYTHON_INCLUDE_DIR)
include_directories(${PYTHON_INCLUDE_DIR})
else()
message(FATAL_ERROR "Cannot find installed Python head file directory")
endif()
# sources
set(ATEN_SRCS)
set(CORE_SRCS)
set(FRAMEWORK_SRCS)
set(LOGGING_SRCS)
if (NOT DEFINED BUILD_LIBTORCH)
set(DIST_SRCS)
set(FLOP_SRCS)
set(NPU_SRCS)
set(PROF_SRCS)
set(IPC_SRCS)
set(UTILS_SRCS)
set(SAN_SRCS)
set(AFD_SRCS)
endif()
if (DEFINED BUILD_LIBTORCH)
set(NPU_CPP_LIBS_SRCS)
endif()
add_subdirectory(${TORCHNPU_ROOT}/aten)
add_subdirectory(${TORCHNPU_ROOT}/core)
add_subdirectory(${TORCHNPU_ROOT}/framework)
add_subdirectory(${TORCHNPU_ROOT}/flopcount)
add_subdirectory(${TORCHNPU_ROOT}/logging)
add_subdirectory(${TORCHNPU_ROOT}/custom_dtype)
if (NOT DEFINED BUILD_LIBTORCH)
add_subdirectory(${TORCHNPU_ROOT}/distributed)
add_subdirectory(${TORCHNPU_ROOT}/npu)
add_subdirectory(${TORCHNPU_ROOT}/profiler)
add_subdirectory(${TORCHNPU_ROOT}/ipc)
add_subdirectory(${TORCHNPU_ROOT}/utils)
add_subdirectory(${TORCHNPU_ROOT}/sanitizer)
add_subdirectory(${TORCHNPU_ROOT}/afd)
endif()
if (DEFINED BUILD_LIBTORCH)
add_subdirectory(${TORCHNPU_ROOT}/libs)
endif()
set(OPS_PLUGIN_SRCS)
# Add subdirectory of op-plugin
include_directories(${PROJECT_SOURCE_DIR}/third_party/op-plugin)
add_subdirectory(${PROJECT_SOURCE_DIR}/third_party/op-plugin/op_plugin)
if (DEFINED BUILD_TENSORPIPE)
add_definitions(-DUSE_RPC_FRAMEWORK)
set(BUILD_SHARED_LIBS ON)
add_subdirectory(${PROJECT_SOURCE_DIR}/third_party/Tensorpipe)
set(BUILD_SHARED_LIBS OFF)
endif()
if (DEFINED BUILD_LIBTORCH)
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${FLOP_SRCS} ${CUS_DTYPE_SRCS} ${FRAMEWORK_SRCS} ${LOGGING_SRCS} ${NPU_CPP_LIBS_SRCS})
else()
# Compile code with pybind11
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${DIST_SRCS} ${FLOP_SRCS} ${CUS_DTYPE_SRCS} ${LOGGING_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${IPC_SRCS} ${UTILS_SRCS} ${SAN_SRCS} ${AFD_SRCS})
endif()
add_library(${PLUGIN_NAME} SHARED ${CPP_SRCS})
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag("-fvisibility=hidden" COMPILER_SUPPORTS_HIDDEN_VISIBILITY)
if(${COMPILER_SUPPORTS_HIDDEN_VISIBILITY})
target_compile_options(${PLUGIN_NAME} PRIVATE "-fvisibility=hidden")
endif()
if (DEFINED BUILD_TORCHAIR)
add_subdirectory(${TORCHNPU_THIRD_PARTY_ROOT}/torchair)
add_dependencies(${PLUGIN_NAME} copy_torchair_pyfiles)
endif()
link_directories(${PYTORCH_INSTALL_DIR}/lib)
link_directories(${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libhccl.so)
if (NOT DEFINED BUILD_LIBTORCH)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${PYTORCH_INSTALL_DIR}/lib/libtorch_python.so)
endif()
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libascendcl.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libacl_op_compiler.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libge_runner.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libgraph.so)
if (DEFINED BUILD_TENSORPIPE)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/build/packages/torch_npu/lib/libtensorpipe.so)
endif()
target_link_libraries(${PLUGIN_NAME} PUBLIC torch torch_cpu c10)
if (NOT DEFINED BUILD_LIBTORCH)
set(ATEN_THREADING "OMP" CACHE STRING "ATen parallel backend")
message(STATUS "Using ATen parallel backend: ${ATEN_THREADING}")
if ("${ATEN_THREADING}" STREQUAL "OMP")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_OPENMP=1")
elseif ("${ATEN_THREADING}" STREQUAL "NATIVE")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE=1")
elseif ("${ATEN_THREADING}" STREQUAL "TBB")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE_TBB=1")
else()
message(FATAL_ERROR "Unknown ATen parallel backend: ${ATEN_THREADING}")
endif()
include(GNUInstallDirs)
target_compile_options(${PLUGIN_NAME} PRIVATE "-DC10_BUILD_MAIN_LIB")
install(TARGETS ${PLUGIN_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()
if (NOT DEFINED BUILD_LIBTORCH)
add_subdirectory(${TORCHNPU_ROOT}/toolkit)
target_link_libraries(${PLUGIN_NAME} PUBLIC npu_profiler)
endif()
if (DEFINED BUILD_GTEST)
enable_testing()
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build/gtest)
add_subdirectory(${PROJECT_SOURCE_DIR}/third_party/googletest)
include_directories(${PROJECT_SOURCE_DIR}/third_party/googletest/googletest/include)
set(TORCH_API_TEST_SOURCES)
add_subdirectory(${PROJECT_SOURCE_DIR}/test/cpp/api)
add_executable(test_api ${TORCH_API_TEST_SOURCES})
target_link_libraries(test_api PUBLIC torch_npu)
target_link_libraries(test_api PUBLIC gtest_main gtest)
endif()
if (DEFINED BUILD_LIBTORCH)
configure_file(
${PROJECT_SOURCE_DIR}/cmake/Torch_npuConfig.cmake.in
${PROJECT_SOURCE_DIR}/build/Torch_npuConfig.cmake
@ONLY)
endif()
+19 -18
View File
@@ -16,8 +16,8 @@
<h2 id="入门.md">入门</h2>
- 在[GitCode](https://gitcode.com/ascend/pytorch)上Fork存储库。
- 阅读[README.md](#https://gitcode.com/ascend/pytorch/blob/master/README.zh.md)以获取项目信息和构建说明。
- 在[Gitee](https://gitee.com/ascend/pytorch)上Fork存储库。
- 阅读[README.md](#https://gitee.com/ascend/pytorch/blob/master/README.zh.md)以获取项目信息和构建说明。
<h2 id="开发指导.md">开发指导</h2>
@@ -40,20 +40,19 @@
1. 编写测试脚本。
以add运算为例,在“pytorch/test/test\_network\_ops“路径下编写测试脚本文件: test\_add.py。
以add运算为例,在“pytorch/test/test\_npu/test\_network\_ops“路径下编写测试脚本文件: test\_add.py。
以下示例仅为一个简单的用例实现,供用户参考。具体测试用例的实现,需要根据运算定义进行完整的覆盖才能保证功能的基本正确。
```
# 引入依赖库
import sys
sys.path.append('..')
import torch
import torch_npu
import numpy as np
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
from common_utils import TestCase, run_tests
from common_device_type import dtypes, instantiate_device_type_tests
from util_test import create_common_tensor
# 定义add测试用例类
class TestAdd(TestCase):
@@ -85,20 +84,21 @@
self.assertRtolEqual(cpu_output, npu_output)
# 定义具体add场景的测试用例,用例函数需要以test_开头
def test_add_shape_format_fp32_2d(self):
def test_add_shape_format_fp32_2d(self, device):
format_list = [0, 3, 29]
shape_format = [
[np.float32, i, [5, 256]] for i in format_list
]
self.add_result(shape_format)
instantiate_device_type_tests(TestAdd, globals(), except_for="cpu")
if __name__ == "__main__":
run_tests()
```
2. 设置环境变量。
进入"pytorch"根目录,并执行env.sh脚本。
进入“pytorh/src“路径,并执行env.sh脚本。
```
bash env.sh
@@ -119,11 +119,11 @@
- 编码指南
请在PyTorch社区使用规统一的编码分格,python建议的编码风格是[PEP 8编码样式](https://pep8.org/),C++编码所建议的风格是 [Google C++编码指南](http://google.github.io/styleguide/cppguide.html) 。可以使用[CppLint](https://github.com/cpplint/cpplint),[CppCheck](http://cppcheck.sourceforge.net/),[CMakeLint](https://github.com/cmake-lint/cmake-lint),[CodeSpell](https://github.com/codespell-project/codespell), [Lizard](http://www.lizard.ws/),[ShellCheck](https://github.com/koalaman/shellcheck)和[pylint](https://pylint.org/)检查代码的格式,建议在您的IDE中安装这些插件。
请在PyTorch社区使用规统一的编码分格,_Python__中_建议的编码风格是[PEP 8编码样式](https://pep8.org/),_C++_编码所建议的风格是 [Google C++编码指南](http://google.github.io/styleguide/cppguide.html) 。可以使用[CppLint](https://github.com/cpplint/cpplint),[CppCheck](http://cppcheck.sourceforge.net/),[CMakeLint](https://github.com/cmake-lint/cmake-lint),[CodeSpell](https://github.com/codespell-project/codespell), [Lizard](http://www.lizard.ws/),[ShellCheck](https://github.com/koalaman/shellcheck)和[pylint](https://pylint.org/)检查代码的格式,建议在您的IDE中安装这些插件。
- 单元测试指南
请在PyTorch社区使用统一的单元测试风格, Python中建议的单元测试风格是[pytest](http://www.pytest.org/en/latest/),C++单元测试所建议的风格是 [Googletest Primer](#https://github.com/google/googletest/blob/master/docs/primer.md) 。测试用例的设计意图应该通过它的注释名称来反映。
请在PyTorch社区使用统一的单元测试风格, _Python_中建议的单元测试风格是[pytest](http://www.pytest.org/en/latest/),_C++_单元测试所建议的风格是 [Googletest Primer](#https://github.com/google/googletest/blob/master/docs/primer.md) 。测试用例的设计意图应该通过它的注释名称来反映。
- 重构指南
@@ -158,14 +158,14 @@
如果要将代码下载到本地环境,git是很好的方法:
```
# For GitCode
git clone https://gitcode.com/{insert_your_forked_repo}/pytorch.git
git remote add upstream https://gitcode.com/pytorch/pytorch.git
# For Gitee
git clone https://gitee.com/{insert_your_forked_repo}/pytorch.git
git remote add upstream https://gitee.com/pytorch/pytorch.git
```
3. 本地开发代码。
为了避免多个分支之间的不一致,建议创建新的分支进行开发:
为了避免多个分支之间的不一致,建议签出到一个新的分支:
```
git checkout -b {new_branch_name} origin/master
@@ -185,7 +185,7 @@
git push origin {new_branch_name}
```
5. 向 PyTorch存储库拉取请求。
5. 向 PyTorh存储库拉取请求。
在最后一步中,您需要在新分支和“PyTorch master“分支之间拉取比较请求。完成拉取请求后,“Jenkins CI“将自动设置为构建测试。您的pull request应该尽快合并到上游 master 分支,以降低合并的风险。
@@ -212,7 +212,7 @@
<h2 id="提出PR.md">提出PR</h2>
- 在[GitCode](https://gitcode.com/ascend/pytorch/issues)上提出您的想法作为_问题_。
- 在[Gitee](https://gitee.com/ascend/pytorch/issues)上提出您的想法作为_问题_。
- 如果是需要大量设计细节的新功能,还应提交设计方案。
- 在问题讨论和设计提案审查中达成共识后,完成分叉回购的开发并提交 PR(Pull Request)。
- 在从批准者那里收到2+ LGTM(Looks Good To Me)之前,不允许任何PR 。请注意,审批人不允许在自己的 PR 上添加LGTM。
@@ -224,3 +224,4 @@
- 确保你的提交历史被排序。
- 始终将您的分支与主分支保持一致。
- 对于错误修复 PR,请确保链接所有相关问题。
+18 -66
View File
@@ -1,78 +1,30 @@
From PyTorch:
BSD 3-Clause License
Copyright (c) 2020, Huawei Technologies Co., Ltd
Copyright (c) 2016- Facebook, Inc (Adam Paszke)
Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
Copyright (c) 2011-2013 NYU (Clement Farabet)
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
From Caffe2:
Copyright (c) 2016-present, Facebook Inc. All rights reserved.
All contributions by Facebook:
Copyright (c) 2016 Facebook Inc.
All contributions by Google:
Copyright (c) 2015 Google Inc.
All rights reserved.
All contributions by Yangqing Jia:
Copyright (c) 2015 Yangqing Jia
All rights reserved.
All contributions by Kakao Brain:
Copyright 2019-2020 Kakao Brain
All contributions by Cruise LLC:
Copyright (c) 2022 Cruise LLC.
All rights reserved.
All contributions from Caffe:
Copyright(c) 2013, 2014, 2015, the respective contributors
All rights reserved.
All other contributions:
Copyright(c) 2015, 2016 the respective contributors
All rights reserved.
Caffe2 uses a copyright model similar to Caffe: each contributor holds
copyright over their contributions to Caffe2. The project versioning records
all such contribution and copyright details. If a contributor wants to further
mark their specific copyright on a particular contribution, they should
indicate their copyright solely in the commit message of the change when it is
committed.
Copyright (c) 2019, Facebook CORPORATION.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America
and IDIAP Research Institute nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+14 -50
View File
@@ -1,52 +1,16 @@
approvers:
- liwei386
- li_jing_hw
- clinglai
- aichunzheng
- yskhhh
- brightlyking
- wangjiangben_hw
- wangchao285
- AtlasAccount
- dilililiwhy
- chenhao_1209
- sunboquan
- wangchao430
- yanpengquan
- kaixin1976
reviewers:
- xiaxia3
- ascendzyj
- yskhhh
- li_jing_hw
- wangjiangben_hw
- liwei386
- clinglai
- shaoyf
- yanpengquan
- liu-jiaweikf
- xiepeng20
- brightlyking
- chenhao_1209
- wbigat
- will-devil
- ckirchhoff
- liu-tianlong
- wangchao285
- dilililiwhy
- sunjiayang
- huangyunlong2022
- misty-rain-typhoid
- du-jin-hang
- xqiangx1991
- zhan-jun
- wujianping996
- jiangpengfei712
- blian
- nalinaly
- wang-guangbin
- chuboning
- guo-guanghao
- yuhaiyan
- wangchao430
- insanecoder
- Chen_LiQing
reviewers:
- zhou_sinan
- shibo19
- Ronnie_zheng
- xiaxia3
- li_chao10
- petissue
- td__lihan
- ascendzyj
- wangyu0516
- yskhhh
- lvpeiyuan
- xchu42
-272
View File
@@ -1,272 +0,0 @@
# Ascend Extension for PyTorch
## Overview
This repository develops the **PyTorch Extension** named **torch_npu** to adapt **Ascend NPU** to **PyTorch** so that developers who use the **PyTorch** can obtain powerful compute capabilities of **Ascend AI Processors**.
Ascend is a full-stack AI computing infrastructure for industry applications and services based on Huawei Ascend processors and software. For more information about Ascend, see [Ascend Community](https://www.hiascend.com/en/).
## Installation
### From Binary
Provide users with wheel package to quickly install **torch_npu**. Before installing **torch_npu**, complete the installation of **CANN** according to [Ascend Auxiliary Software](#ascend-auxiliary-software). To obtain the **CANN** installation package, refer to the [CANN Installation](https://www.hiascend.com/en/software/cann/community).
1. **Install PyTorch**
Install **PyTorch** through pip.
**For Aarch64:**
```bash
pip3 install torch==2.1.0
```
**For x86:**
```bash
pip3 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu
```
2. **Install torch-npu dependencies**
Run the following command to install dependencies.
```bash
pip3 install pyyaml
pip3 install setuptools
```
If the installation fails, use the download link or visit the [PyTorch official website](https://pytorch.org/) to download the installation package of the corresponding version.
| OS arch | Python version | link |
|---------|----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| x86 | Python3.8 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp38-cp38-linux_x86_64.whl#sha256=9e5cfd931a65b38d222755a45dabb53b836be31bc620532bc66fee77e3ff67dc) |
| x86 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp39-cp39-linux_x86_64.whl#sha256=86cc28df491fa84738affe752f9870791026565342f69e4ab63e5b935f00a495) |
| x86 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp310-cp310-linux_x86_64.whl#sha256=5077921fc2b54e69a534f3a9c0b98493c79a5547c49d46f5e77e42da3610e011) |
| x86 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp311-cp311-linux_x86_64.whl#sha256=5954924ce74bc7e6a6c811e3fa4bdda9936d9889f6369fd068420c444bfd1cae) |
| aarch64 | Python3.8 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=761822761fffaa1c18a62c5deb13abaa780862577d3eadc428f1daa632536905) |
| aarch64 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=de7d63c6ecece118684415a3dbd4805af4a4c1ee1490cccf7405d8c240a481b4) |
| aarch64 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=a04a0296d47f28960f51c18c5489a8c3472f624ec3b5bcc8e2096314df8c3342) |
| aarch64 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=8132efb782cd181cc2dcca5e58effbe4217cdb2581206ac71466d535bf778867) |
3. **Install torch-npu**
```
pip3 install torch-npu==2.1.0.post17
```
### From Source
In some special scenarios, users may need to compile **torch-npu** by themselves.Select a branch in table [Ascend Auxiliary Software](#ascend-auxiliary-software) and a Python version in table [PyTorch and Python Version Matching Table](#pytorch-and-python-version-matching-table) first. The docker image is recommended for compiling torch-npu through the following steps(It is recommended to mount the working path only and avoid the system path to reduce security risks), the generated .whl file path is ./dist/. Note that gcc version has the following constraints if you try to compile without using docker image: we recommend the use gcc 10.2 for ARM and gcc 9.3.1 for X86.
1. **Clone torch-npu**
```
git clone https://github.com/ascend/pytorch.git -b v2.1.0-7.2.0 --depth 1
```
2. **Build Docker Image**
```
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
docker build -t manylinux-builder:v1 .
```
3. **Enter Docker Container**
```
docker run -it -v /{code_path}/pytorch:/home/pytorch manylinux-builder:v1 bash
# {code_path} is the torch_npu source code path
```
4. **Compile torch-npu**
Take **Python 3.8** as an example.
```
cd /home/pytorch
bash ci/build.sh --python=3.8
```
**Tips**
If you would like to compile with new C++ ABI, then first run this command, at this point, the recommended compilation environment is same to community torch package: glibc 2.28, gcc 8.5.0
```
export _GLIBCXX_USE_CXX11_ABI=1
```
Meanwhile, we support configuring -fabi-version using the following variables,require consistency with the community torch package
```
export _ABI_VERSION=13
```
## Getting Started
### Prerequisites
Initialize **CANN** environment variable by running the command as shown below.
```Shell
# Default path, change it if needed.
source /usr/local/Ascend/ascend-toolkit/set_env.sh
```
### Quick Verification
You can quickly experience **Ascend NPU** by the following simple examples.
```Python
import torch
import torch_npu
x = torch.randn(2, 2).npu()
y = torch.randn(2, 2).npu()
z = x.mm(y)
print(z)
```
## User Manual
Refer to [API of Ascend Extension for PyTorch](docs/api/torch_npu_apis.md) for more detailed information.
## PyTorch and Python Version Matching Table
| PyTorch Version | Python Version |
|-----------------|:----------------------------------------------------------|
| PyTorch1.11.0 | Python3.7.x(>=3.7.5),Python3.8.x,Python3.9.x,Python3.10.x |
| PyTorch2.1.0 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.2.0 | Python3.8.x,Python3.9.x,Python3.10.x |
| PyTorch2.3.1 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.4.0 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.5.1 | Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.6.0 | Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.7.1 | Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.8.0 | Python3.9.x,Python3.10.x,Python3.11.x |
## Ascend Auxiliary Software
**PyTorch Extension** versions follow the naming convention `{PyTorch version}-{Ascend version}`, where the former represents the PyTorch version compatible with the **PyTorch Extension**, and the latter is used to match the CANN version. The detailed matching is as follows:
| CANN Version | Supported PyTorch Version | Supported Extension Version | Github Branch |
|-----------------------|---------------------------|-----------------------------|-------------------|
| CANN 8.3.RC1 | 2.8.0 | 2.8.0 | v2.8.0-7.2.0 |
| | 2.7.1 | 2.7.1 | v2.7.1-7.2.0 |
| | 2.6.0 | 2.6.0.post3 | v2.6.0-7.2.0 |
| | 2.1.0 | 2.1.0.post17 | v2.1.0-7.2.0 |
| CANN 8.2.RC1 | 2.6.0 | 2.6.0 | v2.6.0-7.1.0 |
| | 2.5.1 | 2.5.1.post1 | v2.5.1-7.1.0 |
| | 2.1.0 | 2.1.0.post13 | v2.1.0-7.1.0 |
| CANN 8.1.RC1 | 2.5.1 | 2.5.1 | v2.5.1-7.0.0 |
| | 2.4.0 | 2.4.0.post4 | v2.4.0-7.0.0 |
| | 2.3.1 | 2.3.1.post6 | v2.3.1-7.0.0 |
| | 2.1.0 | 2.1.0.post12 | v2.1.0-7.0.0 |
| CANN 8.0.0 | 2.4.0 | 2.4.0.post2 | v2.4.0-6.0.0 |
| | 2.3.1 | 2.3.1.post4 | v2.3.1-6.0.0 |
| | 2.1.0 | 2.1.0.post10 | v2.1.0-6.0.0 |
| CANN 8.0.RC3 | 2.4.0 | 2.4.0 | v2.4.0-6.0.rc3 |
| | 2.3.1 | 2.3.1.post2 | v2.3.1-6.0.rc3 |
| | 2.1.0 | 2.1.0.post8 | v2.1.0-6.0.rc3 |
| CANN 8.0.RC2 | 2.3.1 | 2.3.1 | v2.3.1-6.0.rc2 |
| | 2.2.0 | 2.2.0.post2 | v2.2.0-6.0.rc2 |
| | 2.1.0 | 2.1.0.post6 | v2.1.0-6.0.rc2 |
| | 1.11.0 | 1.11.0.post14 | v1.11.0-6.0.rc2 |
| CANN 8.0.RC1 | 2.2.0 | 2.2.0 | v2.2.0-6.0.rc1 |
| | 2.1.0 | 2.1.0.post4 | v2.1.0-6.0.rc1 |
| | 1.11.0 | 1.11.0.post11 | v1.11.0-6.0.rc1 |
| CANN 7.0.0 | 2.1.0 | 2.1.0 | v2.1.0-5.0.0 |
| | 2.0.1 | 2.0.1.post1 | v2.0.1-5.0.0 |
| | 1.11.0 | 1.11.0.post8 | v1.11.0-5.0.0 |
| CANN 7.0.RC1 | 2.1.0 | 2.1.0.rc1 | v2.1.0-5.0.rc3 |
| | 2.0.1 | 2.0.1 | v2.0.1-5.0.rc3 |
| | 1.11.0 | 1.11.0.post4 | v1.11.0-5.0.rc3 |
| CANN 6.3.RC3.1 | 1.11.0 | 1.11.0.post3 | v1.11.0-5.0.rc2.2 |
| CANN 6.3.RC3 | 1.11.0 | 1.11.0.post2 | v1.11.0-5.0.rc2.1 |
| CANN 6.3.RC2 | 2.0.1 | 2.0.1.rc1 | v2.0.1-5.0.rc2 |
| | 1.11.0 | 1.11.0.post1 | v1.11.0-5.0.rc2 |
| | 1.8.1 | 1.8.1.post2 | v1.8.1-5.0.rc2 |
| CANN 6.3.RC1 | 1.11.0 | 1.11.0 | v1.11.0-5.0.rc1 |
| | 1.8.1 | 1.8.1.post1 | v1.8.1-5.0.rc1 |
| CANN 6.0.1 | 1.5.0 | 1.5.0.post8 | v1.5.0-3.0.0 |
| | 1.8.1 | 1.8.1 | v1.8.1-3.0.0 |
| | 1.11.0 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 |
| CANN 6.0.RC1 | 1.5.0 | 1.5.0.post7 | v1.5.0-3.0.rc3 |
| | 1.8.1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 |
| | 1.11.0 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 |
| CANN 5.1.RC2 | 1.5.0 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
| | 1.8.1 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
| CANN 5.1.RC1 | 1.5.0 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| | 1.8.1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
| CANN 5.0.4 | 1.5.0 | 1.5.0.post4 | 2.0.4.tr5 |
| CANN 5.0.3 | 1.8.1 | 1.5.0.post3 | 2.0.3.tr5 |
| CANN 5.0.2 | 1.5.0 | 1.5.0.post2 | 2.0.2.tr5 |
## Hardware support
The Ascend training device includes the following models, all of which can be used as training environments for PyTorch models
| Product series | Product model |
|-----------------------|----------------------------------|
| Atlas Training series products | Atlas 800(model: 9000) |
| | Atlas 800(model:9010) |
| | Atlas 900 PoD(model:9000) |
| | Atlas 300T(model:9000) |
| | Atlas 300T Pro(model:9000) |
| Atlas A2 Training series products | Atlas 800T A2 |
| | Atlas 900 A2 PoD |
| | Atlas 200T A2 Box16 |
| | Atlas 300T A2 |
The Ascend inference device includes the following models, all of which can be used as inference environments for large models
| Product series | Product model |
|-----------------------|----------------------------------|
| Atlas 800I A2 Inference product | Atlas 800I A2 |
## Suggestions and Communication
Everyone is welcome to contribute to the community. If you have any questions or suggestions, you can submit [Github Issues](https://github.com/Ascend/pytorch/issues). We will reply to you as soon as possible. Thank you very much.
## Branch Maintenance Policies
The version branches of AscendPyTorch have the following maintenance phases:
| **Status** | **Duration** | **Description** |
|-------------------|--------------|--------------------------------------------------------------------------------------------------------------------------------|
| Planning | 1-3 months | Plan features. |
| Development | 6-12 months | Develop new features and fix issues, regularly release new versions. Different strategies are adopted for different versions of PyTorch, with a regular branch development cycle of 6 months and a long-term support branch development cycle of 12 months. |
| Maintained | 1 year/3.5 years | Regular Release branch for 1 year, Long Term Support branch maintenance for 3.5 years. Fix major issues, do not incorporate new features, and release patch versions based on the impact of fixed bugs. |
| End Of Life (EOL) | N/A | Do not accept any modification to a branch. |
## PyTorch Maintenance Policies
| **PyTorch** | **Maintenance Policies** | **Status** | **Launch Date** | **Subsequent Status** | **EOL Date** |
|-------------|--------------------------|-------------|-----------------|-------------------------------------------------------------------|--------------|
| 2.8.0 | Regular Release | Development | 2025/10/15 | Expected to enter maintenance status from March 15, 2026 | - |
| 2.7.1 | Long Term Support | Development | 2025/10/15 | Expected to enter maintenance status from September 15, 2026 | |
| 2.6.0 | Regular Release | Development | 2025/07/25 | Expected to enter maintenance status from January 15, 2026 | - |
| 2.5.1 | Regular Release | Maintained | 2024/11/08 | Expected to enter maintenance free status from August 8, 2026 | |
| 2.4.0 | Regular Release | Maintained | 2024/10/15 | Expected to enter maintenance free status from June 15, 2026 | |
| 2.3.1 | Regular Release | Maintained | 2024/06/06 | Expected to enter maintenance free status from June 7, 2026 | |
| 2.2.0 | Regular Release | Maintained | 2024/04/01 | Expected to enter maintenance free status from September 10, 2025 | |
| 2.1.0 | Long Term Support | Development | 2023/10/15 | Expected to enter maintenance status from September 15, 2025 | |
| 2.0.1 | Regular Release | EOL | 2023/7/19 | | 2024/3/14 |
| 1.11.0 | Long Term Support | Maintained | 2023/4/19 | Expected to enter maintenance free status from September 10, 2025 | |
| 1.8.1 | Long Term Support | EOL | 2022/4/10 | | 2023/4/10 |
| 1.5.0 | Long Term Support | EOL | 2021/7/29 | | 2022/7/29 |
## Reference Documents
For more detailed information on installation guides, model migration, training/inference tutorials, and API lists, please refer to the [PyTorch Ascend Adapter on the HiAI Community](https://www.hiascend.com/software/ai-frameworks?framework=pytorch).
| Document Name | Document Link |
|------------------------------------------|-------------------------------------------------------------------------------------------------------------------------|
| Installation Guide | [link](https://www.hiascend.com/document/detail/zh/Pytorch/720/configandinstg/instg/insg_0001.html) |
| Network Model Migration and Training | [link](https://www.hiascend.com/document/detail/zh/Pytorch/720/ptmoddevg/trainingmigrguide/PT_LMTMOG_0003.html) |
| Operator Adaptation | [link](https://www.hiascend.com/document/detail/zh/canncommercial/81RC1/operatordev/tbeaicpudevg/atlasopdev_10_0086.html) |
| API List (PyTorch and Custom Interfaces) | [link](https://www.hiascend.com/document/detail/zh/Pytorch/720/apiref/apilist/ptaoplist_000002.html) |
## License
Ascend Extension for Pytorch has a BSD-style license, as found in the [LICENSE](LICENSE) file.
+170 -259
View File
@@ -1,307 +1,218 @@
# Ascend Extension for PyTorch插件
# AscendPyTorch
## 简介
# 项目简介
本项目开发了PyTorch Adapter插件,用于昇腾适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。
本项目开发了名为**torch_npu**的**Ascend Extension for PyTorch**插件,使昇腾NPU可以适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。
# 编译/执行约束
昇腾为基于华为昇腾处理器和软件的行业应用及服务提供全栈AI计算基础设施。您可以通过访问[昇腾社区](https://www.hiascend.com/zh/),了解关于昇腾的更多信息。
gcc版本: 7.3.0(只在编译场景要求)
## 版本说明
cmake版本:3.12.0以上版本(只在编译场景要求)
### PyTorch与Python版本配套表
| PyTorch版本 | Python版本 |
|---------------|:-------------------------------------------------------------|
| PyTorch1.11.0 | Python3.7.x(>=3.7.5), Python3.8.x, Python3.9.x, Python3.10.x |
| PyTorch2.1.0 | Python3.8.x, Python3.9.x, Python3.10.x, Python 3.11.x |
| PyTorch2.2.0 | Python3.8.x, Python3.9.x, Python3.10.x |
| PyTorch2.3.1 | Python3.8.x, Python3.9.x, Python3.10.x, Python 3.11.x |
| PyTorch2.4.0 | Python3.8.x, Python3.9.x, Python3.10.x, Python 3.11.x |
| PyTorch2.5.1 | Python3.9.x, Python3.10.x, Python 3.11.x |
| PyTorch2.6.0 | Python3.9.x, Python3.10.x, Python 3.11.x |
| PyTorch2.7.1 | Python3.9.x, Python3.10.x, Python 3.11.x |
| PyTorch2.8.0 | Python3.9.x, Python3.10.x, Python 3.11.x |
python版本:3.7.x
### 昇腾辅助软件
# 系统依赖库
**Ascend Extension for PyTorch**的分支名称采用`{PyTorch版本}-{昇腾版本}`命名规则,前者为**Ascend Extension for PyTorch**匹配的PyTorch版本,后者为**Ascend Extension for PyTorch**版本号,详细匹配如下:
## CentOS & EulerOS
| CANN版本 | 支持的PyTorch版本 | 支持的Extension版本 | GitCode分支 |
|-----------------------|--------------|------------------|-------------------|
| CANN 8.3.RC1 | 2.8.0 | 2.8.0 | v2.8.0-7.2.0 |
| | 2.7.1 | 2.7.1 | v2.7.1-7.2.0 |
| | 2.6.0 | 2.6.0.post3 | v2.6.0-7.2.0 |
| | 2.1.0 | 2.1.0.post17 | v2.1.0-7.2.0 |
| CANN 8.2.RC1 | 2.6.0 | 2.6.0 | v2.6.0-7.1.0 |
| | 2.5.1 | 2.5.1.post1 | v2.5.1-7.1.0 |
| | 2.1.0 | 2.1.0.post13 | v2.1.0-7.1.0 |
| CANN 8.1.RC1 | 2.5.1 | 2.5.1 | v2.5.1-7.0.0 |
| | 2.4.0 | 2.4.0.post4 | v2.4.0-7.0.0 |
| | 2.3.1 | 2.3.1.post6 | v2.3.1-7.0.0 |
| | 2.1.0 | 2.1.0.post12 | v2.1.0-7.0.0 |
| CANN 8.0.0 | 2.4.0 | 2.4.0.post2 | v2.4.0-6.0.0 |
| | 2.3.1 | 2.3.1.post4 | v2.3.1-6.0.0 |
| | 2.1.0 | 2.1.0.post10 | v2.1.0-6.0.0 |
| CANN 8.0.RC3 | 2.4.0 | 2.4.0 | v2.4.0-6.0.rc3 |
| | 2.3.1 | 2.3.1.post2 | v2.3.1-6.0.rc3 |
| | 2.1.0 | 2.1.0.post8 | v2.1.0-6.0.rc3 |
| CANN 8.0.RC2 | 2.3.1 | 2.3.1 | v2.3.1-6.0.rc2 |
| | 2.2.0 | 2.2.0.post2 | v2.2.0-6.0.rc2 |
| | 2.1.0 | 2.1.0.post6 | v2.1.0-6.0.rc2 |
| | 1.11.0 | 1.11.0.post14 | v1.11.0-6.0.rc2 |
| CANN 8.0.RC1 | 2.2.0 | 2.2.0 | v2.2.0-6.0.rc1 |
| | 2.1.0 | 2.1.0.post4 | v2.1.0-6.0.rc1 |
| | 1.11.0 | 1.11.0.post11 | v1.11.0-6.0.rc1 |
| CANN 7.0.0 | 2.1.0 | 2.1.0 | v2.1.0-5.0.0 |
| | 2.0.1 | 2.0.1.post1 | v2.0.1-5.0.0 |
| | 1.11.0 | 1.11.0.post8 | v1.11.0-5.0.0 |
| CANN 7.0.RC1 | 2.1.0 | 2.1.0.rc1 | v2.1.0-5.0.rc3 |
| | 2.0.1 | 2.0.1 | v2.0.1-5.0.rc3 |
| | 1.11.0 | 1.11.0.post4 | v1.11.0-5.0.rc3 |
| CANN 6.3.RC3.1 | 1.11.0 | 1.11.0.post3 | v1.11.0-5.0.rc2.2 |
| CANN 6.3.RC3 | 1.11.0 | 1.11.0.post2 | v1.11.0-5.0.rc2.1 |
| CANN 6.3.RC2 | 2.0.1 | 2.0.1.rc1 | v2.0.1-5.0.rc2 |
| | 1.11.0 | 1.11.0.post1 | v1.11.0-5.0.rc2 |
| | 1.8.1 | 1.8.1.post2 | v1.8.1-5.0.rc2 |
| CANN 6.3.RC1 | 1.11.0 | 1.11.0 | v1.11.0-5.0.rc1 |
| | 1.8.1 | 1.8.1.post1 | v1.8.1-5.0.rc1 |
| CANN 6.0.1 | 1.5.0 | 1.5.0.post8 | v1.5.0-3.0.0 |
| | 1.8.1 | 1.8.1 | v1.8.1-3.0.0 |
| | 1.11.0 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 |
| CANN 6.0.RC1 | 1.5.0 | 1.5.0.post7 | v1.5.0-3.0.rc3 |
| | 1.8.1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 |
| | 1.11.0 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 |
| CANN 5.1.RC2 | 1.5.0 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
| | 1.8.1 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
| CANN 5.1.RC1 | 1.5.0 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| | 1.8.1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
| CANN 5.0.4 | 1.5.0 | 1.5.0.post4 | 2.0.4.tr5 |
| CANN 5.0.3 | 1.8.1 | 1.5.0.post3 | 2.0.3.tr5 |
| CANN 5.0.2 | 1.5.0 | 1.5.0.post2 | 2.0.2.tr5 |
yum install -y cmake zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas
## Ubuntu
apt-get install -y gcc 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 cmake dos2unix libopenblas-dev
## 快速入门
# python依赖库
基于CNN模型识别手写数字的脚本,对在GPU上训练的该脚本代码进行修改,使其可以迁移到昇腾NPU上进行训练。具体操作请参见[Ascend Extension for PyTorch 快速入门](https://www.hiascend.com/document/detail/zh/Pytorch/710/fastexperience/fastexperience_0001.html)。
## 环境部署
依赖库安装:
### 使用二进制文件进行安装
我们为用户提供可以快速安装**torch_npu**的whl安装包。在安装**torch_npu**之前,您需要先安装**CANN**软件。[昇腾辅助软件](#昇腾辅助软件)中有更多关于CANN的版本信息。请参考[CANN安装指南](https://www.hiascend.com/zh/software/cann/community)获取**CANN**安装包。
1. **安装PyTorch**
通过 pip 安装 PyTorch。
**aarch64:**
```bash
pip3 install torch==2.1.0
```
**x86:**
```bash
pip3 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu
```
若使用pip命令安装失败,请使用下载链接或进入[PyTorch官方网站](https://pytorch.org/)进行查询下载对应版本。
| 架构 | Python版本 | 下载链接 |
|---------|------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| x86 | Python3.8 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp38-cp38-linux_x86_64.whl#sha256=9e5cfd931a65b38d222755a45dabb53b836be31bc620532bc66fee77e3ff67dc) |
| x86 | Python3.9 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp39-cp39-linux_x86_64.whl#sha256=86cc28df491fa84738affe752f9870791026565342f69e4ab63e5b935f00a495) |
| x86 | Python3.10 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp310-cp310-linux_x86_64.whl#sha256=5077921fc2b54e69a534f3a9c0b98493c79a5547c49d46f5e77e42da3610e011) |
| x86 | Python3.11 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0%2Bcpu-cp311-cp311-linux_x86_64.whl#sha256=5954924ce74bc7e6a6c811e3fa4bdda9936d9889f6369fd068420c444bfd1cae) |
| aarch64 | Python3.8 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=761822761fffaa1c18a62c5deb13abaa780862577d3eadc428f1daa632536905) |
| aarch64 | Python3.9 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=de7d63c6ecece118684415a3dbd4805af4a4c1ee1490cccf7405d8c240a481b4) |
| aarch64 | Python3.10 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=a04a0296d47f28960f51c18c5489a8c3472f624ec3b5bcc8e2096314df8c3342) |
| aarch64 | Python3.11 | [下载链接](https://download.pytorch.org/whl/cpu/torch-2.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl#sha256=8132efb782cd181cc2dcca5e58effbe4217cdb2581206ac71466d535bf778867) |
2. **安装torch_npu依赖**
运行以下命令安装依赖。
```bash
pip3 install pyyaml
pip3 install setuptools
```
3. **安装torch_npu**
```bash
pip3 install torch-npu==2.1.0.post17
```
如需要保存安装日志,可在pip3 install命令后面加上参数 `--log <PATH>`,并对您指定的目录`<PATH>`做好权限管控。
### 使用源代码进行安装
某些特殊场景下,用户可能需要自行编译**torch_npu**。可以根据[昇腾辅助软件表](#昇腾辅助软件)和[PyTorch与Python版本配套表](#pytorch与python版本配套表)选择合适的分支。
推荐使用Docker镜像编译**torch_npu**,可以通过以下步骤获取(建议只挂载工作路径,并避开系统路径,以降低安全风险), 生成的.whl文件路径为./dist/。
>**须知:**<br>
>如果不使用镜像,编译时请注意gcc版本遵循如下约束。
> - ARM架构下推荐使用gcc 10.2版本
> - X86架构下推荐使用gcc 9.3.1
1. **克隆torch_npu代码仓**
```
git clone https://gitcode.com/ascend/pytorch.git -b v2.1.0-7.2.0 --depth 1
```
2. **构建镜像**
```
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
docker build -t manylinux-builder:v1 .
```
3. **进入Docker容器**
```
docker run -it -v /{code_path}/pytorch:/home/pytorch manylinux-builder:v1 bash
# {code_path} is the torch_npu source code path
```
4. **编译torch_npu**
以**Python 3.8** 为例。
```
cd /home/pytorch
bash ci/build.sh --python=3.8
```
**提示**
如果想使用新的C++ ABI编译,请首先运行如下命令,此时推荐和社区torch包相同的编译环境:glibc 2.28, gcc 8.5.0。
```
export _GLIBCXX_USE_CXX11_ABI=1
```
同时,我们支持使用如下变量配置-fabi-version,要求和社区torch包ABI版本一致。
```
export _ABI_VERSION=13
```
### 安装后验证
#### 前提
运行以下命令初始化**CANN**环境变量。
```Shell
# Default path, change it if needed.
source /usr/local/Ascend/ascend-toolkit/set_env.sh
```python3
pip3 install -r requirements.txt
```
#### 快速验证
可以通过以下样例快速体验**昇腾NPU**。
# 使用方式 --生成全量代码并编译
```diff
import torch
- import torch_npu # torch_npu2.5.1及以后版本可以不用手动导包
## 获取原生PyTorch源代码和third_party代码
x = torch.randn(2, 2).npu()
y = torch.randn(2, 2).npu()
z = x.mm(y)
在当前仓库根目录pytorch/下获取原生PyTorch的源代码
print(z)
```sh
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
```
## 卸载
Pytorch框架训练环境的卸载可以参考[昇腾官方文档](https://www.hiascend.com/document/detail/zh/ModelZoo/pytorchframework/ptes/ptes_00032.html)。
进入到pytorch/pytorch/目录下, 获取PyTorch被动依赖代码(获取时间较长,请耐心等待)。
torch_npu的卸载只需执行命令:
```sh
git submodule sync
git submodule update --init --recursive
```
```bash
pip3 uninstall torch_npu
```
完成且没有报错之后就生成了PyTorch及其依赖的三方代码
如需要保存卸载日志,可在pip3 uninstall命令后面加上参数 `--log <PATH>`,并对您指定的目录`<PATH>`做好权限管控。
## 生成适配昇腾AI处理器的PyTorch代码。
进入到pytorch/scripts目录,执行
```sh
bash gen.sh
```
会在pytorch/pytorch/目录中生成npu适配全量代码
## 编译torch的二进制包
进入到pytorch/pytorch/目录,执行
```sh
bash build.sh
```
生成的二进制包在pytorch/pytorch/dist/目录下
# 安装
**x86_64:**
torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl (实际可能附带小版本号例如torch-1.5.0.post2+ascend-cp37-cp37m-linux_x86_64.whl)
```python
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl
```
**arm:**
torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl (实际可能附带小版本号例如torch-1.5.0.post2+ascend-cp37-cp37m-linux_aarch64.whl)
```python
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl
```
# 运行
## 运行环境变量
在当前仓库根目录中执行设置环境变量脚本
```
source src/env.sh
```
## 自定义环境变量
以下环境变量为NPU场景下使用的功能类或可以提升性能的环境变量:
```
export TASK_QUEUE_ENABLE=1 # 使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1
export PTCOPY_ENABLE=1 # 使用PTCopy算子模式,加速转连续及copy等过程,建议默认开启,开启设置为1
```
可选的环境变量可能会对运行的模型产生影响:
```
export DYNAMIC_COMPILE_ENABLE=1 # 动态shape特性功能,针对shape变化场景,可选,开启设置为1
export COMBINED_ENABLE=1 # 非连续两个算子组合类场景优化,可选,开启设置为1
export TRI_COMBINED_ENABLE=1 # 非连续三个算子组合类场景优化,可选,开启设置为1
export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
export DYNAMIC_OP="ADD#MUL" # 算子实现,ADD和MUL算子在不同场景下有不同的性能表现。可选
```
## 执行单元测试脚本
验证运行, 输出结果OK
```python
python3 test/test_npu/test_div.py
```
# 路标
以下将展示AscendPyTorch近期的计划,我们会根据用户的反馈诉求,持续调整计划的优先级。
总体而言,我们会努力在以下几个方面不断改进。
1、pytorch AICPU多核能力补齐
2、pytorch单算子模式const节点输入
3、pytorch场景支持算子非连续输入
4、pytorch单算子模式支持动态shape
5、NLP网络格式转化方案完善
6、pytorch的基线格式调整
7、reshapeType总体方案梳理优化
8、AICPU针对pytorch方案梳理优化
热忱希望各位在用户社区加入讨论,并贡献您的建议。
## 硬件配套
# FAQ
昇腾训练设备包含以下型号,都可作为PyTorch模型的训练环境。
| 产品系列 | 产品型号 |
|-----------------------|----------------------------------|
| Atlas 训练系列产品 | Atlas 800 训练服务器(型号:9000) |
| | Atlas 800 训练服务器(型号:9010) |
| | Atlas 900 PoD(型号:9000) |
| | Atlas 300T 训练卡(型号:9000) |
| | Atlas 300T Pro 训练卡(型号:9000)|
| Atlas A2 训练系列产品 | Atlas 800T A2 训练服务器 |
| | Atlas 900 A2 PoD 集群基础单元 |
| | Atlas 200T A2 Box16 异构子框 |
| Atlas A3 训练系列产品 | Atlas 800T A3 训练服务器 |
| | Atlas 900 A3 SuperPoD 超节点 |
## 运行遇到找不到te问题
昇腾推理设备包含以下型号,都可作为大模型的推理环境。
| 产品系列 | 产品型号 |
|-----------------------|----------------------------------|
| Atlas 800I A2推理产品 | Atlas 800I A2 推理服务器 |
开发态:
## 建议与交流
cd /urs/local/ascend-toolkit/latest/fwkacllib/lib64
欢迎大家为社区做贡献。如果有任何疑问或建议,请提交[GitCode Issues](https://gitcode.com/Ascend/pytorch/issues),我们会尽快回复。感谢您的支持。
用户态:
## 分支维护策略
cd /urs/local/nnae/latest/fwkacllib/lib64
Ascend Extension for PyTorch版本分支的维护阶段如下:
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
| **状态** | **时间** | **说明** |
| ------------------- | -------- | ------------------------------------------------ |
| 计划 | 1—3 个月 | 计划特性 |
| 开发 | 6—12 个月 | 开发新特性并修复问题,定期发布新版本。针对不同的PyTorch版本采取不同的策略,常规分支的开发周期分别为6个月,长期支持分支的开发周期为12个月 |
| 维护 | 1年/3.5年 | 常规分支维护1年,长期支持分支维护3.5年。对重大BUG进行修复,不合入新特性,并视BUG的影响发布补丁版本 |
| 生命周期终止(EOL) | N/A | 分支不再接受任何修改 |
## PyTorch版本维护策略
## 编译cmake报错版本过低
| **PyTorch版本** | **维护策略** | **当前状态** | **发布时间** | **后续状态** | **EOL日期** |
|---------------|----------|----------|------------|----------------------|-----------|
| 2.8.0 | 常规分支 | 开发 | 2025/10/15| 预计2026/03/15起进入维护状态 | - |
| 2.7.1 | 长期分支 | 开发 | 2025/10/15| 预计2026/10/15起进入维护状态 | - |
| 2.6.0 | 常规分支 | 开发 | 2025/07/25 | 预计2026/01/25起进入维护状态 | - |
| 2.5.1 | 常规分支 | 维护 | 2024/11/08 | 预计2026/08/08起进入无维护状态 | - |
| 2.4.0 | 常规分支 | 维护 | 2024/10/15 | 预计2026/06/15起进入无维护状态 | - |
| 2.3.1 | 常规分支 | 维护 | 2024/06/06 | 预计2026/06/07起进入无维护状态 | |
| 2.2.0 | 常规分支 | EOL | 2024/04/01 | | 2025/10/14 |
| 2.1.0 | 长期支持 | 开发 | 2023/10/15 | 预计2025/09/15起进入维护状态 | |
| 2.0.1 | 常规分支 | EOL | 2023/7/19 | | 2024/3/14 |
| 1.11.0 | 长期支持 | 维护 | 2023/4/19 | 预计2025/09/10起进入无维护状态 | |
| 1.8.1 | 长期支持 | EOL | 2022/4/10 | | 2023/4/10 |
| 1.5.0 | 长期支持 | EOL | 2021/7/29 | | 2022/7/29 |
cmake官网下载linux版本安装(当前3.18.0)
## 安全声明
1. 使用yum命令安装: yum install -y cmake==3.18.0
[Ascend Extension for PyTorch插件 安全声明](./SECURITYNOTE.md)
2. 下载cmake sh脚本安装:(参考cmake官网)
## 参考文档
X86_64环境推荐脚本安装: cmake-3.18.2-Linux-x86_64.sh
有关安装指南、模型迁移和训练/推理教程和API列表等更多详细信息,请参考[昇腾社区Ascend Extension for PyTorch](https://www.hiascend.com/software/ai-frameworks?framework=pytorch)。
| 文档名称 | 文档链接 |
| -------------------------- | ------------------------------------------------------------ |
| 软件安装指南 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/configandinstg/instg/insg_0001.html) |
| 网络模型迁移和训练 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/ptmoddevg/trainingmigrguide/PT_LMTMOG_0002.html) |
| 算子适配 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/ptmoddevg/Frameworkfeatures/featuresguide_00021.html) |
| PyTorch原生接口清单 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/apiref/PyTorchNativeapi/ptaoplist_000003.html) |
| Ascend Extension for PyTorch自定义API参考 | [参考链接](https://www.hiascend.com/document/detail/zh/Pytorch/720/apiref/torchnpuCustomsapi/context/%E6%A6%82%E8%BF%B0.md) |
## GCC版本问题切换问题
目前存在测试环境从GCC4.8.5 切换到 GCC7.3.0。这个过程容易出现错误导致pytorch编译不过,以下是需要软连接的库
gcc, g++,c++(--version 必须是7.3.0)
libstdc++->libstdc++.so.6.0.24(7.3.0)
## 许可证
Ascend Extension for PyTorch插件使用BSD许可证。详见[LICENSE](LICENSE)文件。
## 找不到libblas.so问题
环境缺少openblas库,需要安装openblas库
Centos,EulerOS环境
```sh
yum -y install openblas
```
Ubuntu环境
```sh
apt install libopenblas-dev
```
-323
View File
@@ -1,323 +0,0 @@
# Ascend Extension for PyTorch插件 安全声明
## 系统安全加固
建议用户在系统中配置开启ASLR(级别2 ),又称**全随机地址空间布局随机化**,可参考以下方式进行配置:
echo 2 > /proc/sys/kernel/randomize_va_space
## 运行用户建议
出于安全性及权限最小化角度考虑,不建议使用root等管理员类型账户使用torch_npu。
## 文件权限控制
1. 建议用户对训练所需文件、训练过程中保存的文件、用户个人的隐私数据、商业资产等敏感文件做好权限控制等安全措施,例如多用户共享数据集场景下的数据集文件写权限控制、profiler等场景产生数据文件权限控制等,设定的权限建议参见[文件权限参考](#文件权限参考)进行设置。
2. torch_npu中profiler工具会生成性能记录文件,生成的文件权限为640,文件夹权限为750,用户可根据需要自行对生成后的相关文件进行权限控制。
3. 用户安装和使用过程需要做好权限控制,建议参见[文件权限参考](#文件权限参考)进行设置。如需要保存安装/卸载日志,可在安装/卸载命令后面加上参数--log <FILE>, 注意对<FILE>文件及目录做好权限管控。
4. PyTorch框架运行中所生成的文件权限依赖系统设定,如torch.save接口保存的文件。建议当前执行脚本的用户根据自身需要,对生成文件做好权限控制,设定的权限可参见[文件权限参考](#文件权限参考) 。可使用umask控制默认权限,降低提权等安全风险,建议用户将主机(包括宿主机)和容器中的umask设置为0027及其以上,提高安全性。
##### 文件权限参考
| 类型 | Linux权限参考最大值 |
|----------------------------------- |-----------------------|
| 用户主目录 | 750(rwxr-x---) |
| 程序文件(含脚本文件、库文件等) | 550(r-xr-x---) |
| 程序文件目录 | 550(r-xr-x---) |
| 配置文件 | 640(rw-r-----) |
| 配置文件目录 | 750(rwxr-x---) |
| 日志文件(记录完毕或者已经归档) | 440(r--r-----) |
| 日志文件(正在记录) | 640(rw-r-----) |
| 日志文件目录 | 750(rwxr-x---) |
| Debug文件 | 640(rw-r-----) |
| Debug文件目录 | 750(rwxr-x---) |
| 临时文件目录 | 750(rwxr-x---) |
| 维护升级文件目录 | 770(rwxrwx---) |
| 业务数据文件 | 640(rw-r-----) |
| 业务数据文件目录 | 750(rwxr-x---) |
| 密钥组件、私钥、证书、密文文件目录 | 700(rwx------) |
| 密钥组件、私钥、证书、加密密文 | 600(rw-------) |
| 加解密接口、加解密脚本 | 500(r-x------) |
## 调试工具声明
torch_npu内集成性能分析工具profiler:
- 集成原因:对标PyTorch原生支持能力,提供NPU PyTorch框架开发性能分析能力,加速性能分析调试过程。
- 使用场景:默认不采集,如用户需要进行性能分析时,可在模型训练脚本中添加Ascend Extension for PyTorch Profiler接口,执行训练的同时采集性能数据,完成训练后直接输出可视化的性能数据文件。
- 风险提示:使用该功能会在本地生成性能数据,用户需加强对相关性能数据的保护,请在需要模型性能分析时使用,分析完成后及时关闭。Profiler工具具体细节请参考[《PyTorch 性能分析工具介绍》](https://www.hiascend.com/document/detail/zh/Pytorch/710/ptmoddevg/trainingmigrguide/performance_tuning_0014.html)。
## 数据安全声明
1. PyTorch使用过程中需要加载和保存数据,部分接口使用风险模块pickle,可能存在数据风险,如torch.load、torch.jit.load、torch.distributed.scatter_object_list等接口,可参考[torch.load](https://pytorch.org/docs/2.1/generated/torch.load.html#torch.load)、[collective-functions](https://pytorch.org/docs/2.1/distributed.html#collective-functions)了解具体风险。
2. Ascend Extension for PyTorch依赖CANN的基础能力实现AOE性能调优、算子dump、日志记录等功能,用户需要关注上述功能生成文件的权限控制,加强对相关数据的保护。
## 构建安全声明
torch_npu支持源码编译安装,在编译时会下载依赖第三方库并执行构建shell脚本,在编译过程中会产生临时程序文件和编译目录。用户可根据需要自行对源代码目录内的文件进行权限管控降低安全风险。
## 运行安全声明
1. 建议用户结合运行环境资源状况编写对应训练脚本。若训练脚本与资源状况不匹配,如数据集加载内存大小超出内存容量限制、训练脚本在本地生成数据超过磁盘空间大小等情况,可能引发错误并导致进程意外退出。
2. PyTorch和torch_npu在运行异常时会退出进程并打印报错信息,属于正常现象。建议用户根据报错提示定位具体错误原因,包括设定算子同步执行、查看CANN日志、解析生成的Core Dump文件等方式。
3. PyTorch和torch_npu的分布式特性仅适用于内部通信。出于性能考虑,这些分布式特性不包含任何授权协议,并且会发送未加密的消息。关于PyTorch分布式特性的详细说明及安全注意事项,可参考[using-distributed-features](https://github.com/pytorch/pytorch/security#using-distributed-features)。
## 公网地址声明
在torch_npu的配置文件和脚本中存在[公网地址](#公网地址)
##### 公网地址
| 类型 | 开源代码地址 | 文件名 | 公网IP地址/公网URL地址/域名/邮箱地址 | 用途说明 |
|------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------|--------------------------------------------------------------------------------|--------------------------------|
| 自研 | 不涉及 | .gitmodules | https://gitcode.com/ascend/op-plugin.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/googletest.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/ascend/torchair.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitcode.com/ascend/Tensorpipe.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/fmt.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/nlohmann-json.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://mirrors.huaweicloud.com/repository/pypi/simple | docker配置文件,用于配置pip源 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://download.pytorch.org/whl/cpu | docker配置源,用于配置torch下载连接 |
| 自研 | 不涉及 | ci\docker\ARM\Dockerfile | https://mirrors.huaweicloud.com/repository/pypi/simple | docker配置文件,用于配置pip源 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo | docker配置文件,用于配置yum源 |
| 自研 | 不涉及 | ci\docker\ARM\Dockerfile | https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo | docker配置文件,用于配置yum源 |
| 自研 | 不涉及 | setup.cfg | https://gitcode.com/ascend/pytorch | 用于打包whl的url入参 |
| 自研 | 不涉及 | setup.cfg | https://gitcode.com/ascend/pytorch/tags | 用于打包whl的download_url入参 |
| 自研 | 不涉及 | third_party\op-plugin\ci\build.sh | https://gitcode.com/ascend/pytorch.git | 编译脚本根据torch_npu仓库地址拉取代码进行编译 |
| 自研 | 不涉及 | third_party\op-plugin\ci\exec_ut.sh | https://gitcode.com/ascend/pytorch.git | UT脚本根据torch_npu仓库地址拉取代码进行UT测试 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/test/nn/test_convolution.py <br> https://github.com/pytorch/pytorch/blob/v2.1.0/test/test_mps.py <br> https://github.com/pytorch/pytorch/blob/v2.1.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/legacy_conv2d.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/legacy_serialized.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/gpu_tensors.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/test/onnx/test_utility_funs.py | test\url.ini | https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml | issue的链接 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/test/test_nn.py <br> https://github.com/pytorch/pytorch/blob/v2.1.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/linear.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/torch/csrc/profiler/unwind/eh_frame_hdr.h | torch_npu\csrc\profiler\unwind\eh_frame_hdr.h | https://refspecs.linuxfoundation.org/LSB_1.3.0/gLSB/gLSB/ehframehdr.html | c++调用栈实现相关注解网址 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/torch/csrc/profiler/unwind/fde.h | torch_npu\csrc\profiler\unwind\fde.h | https://www.airs.com/blog/archives/460 | c++调用栈实现相关注解网址 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/torch/csrc/profiler/unwind/fde.h | torch_npu\csrc\profiler\unwind\fde.h | https://web.archive.org/web/20221129184704/https://dwarfstd.org/doc/DWARF4.doc | c++调用栈实现相关注解网址 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/torch/csrc/profiler/unwind/fde.h | torch_npu\csrc\profiler\unwind\fde.h | https://dl.acm.org/doi/pdf/10.1145/3360572 | c++调用栈实现相关注解网址 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.1.0/torch/csrc/profiler/unwind/fde.h | torch_npu\csrc\profiler\unwind\fde.h | https://github.com/mstange/framehop/ | c++调用栈实现相关注解网址 |
| 自研 | 不涉及 | test\requirements-x86.txt | https://download.pytorch.org/whl/cpu | 下载链接,用于下载torch-cpu版本 |
| 自研 | 不涉及 | test\requirements-x86.txt | https://data.pyg.org/whl/torch-2.1.0+cpu.html | 下载链接,用于下载torch-scatter的cpu版本 |
| 自研 | 不涉及 | test\requirements-x86.txt | https://download.pytorch.org/whl/test/cpu | 下载链接,用于下载torchvision的cpu版本 |
| 自研 | 不涉及 | test\get_synchronized_files.sh | https://github.com/pytorch/pytorch.git | 下载链接,用于下载PyTorch测试用例 |
## 公开接口声明
Ascend Extension for PyTorch是PyTorch适配插件,支持用户使用PyTorch在昇腾设备上进行训练和推理。Ascend Extension for PyTorch适配后支持用户使用PyTorch原生接口。除了原生PyTorch接口外,Ascend Extension for PyTorch提供了部分自定义接口,包括自定义算子、亲和库和其他接口,支持PyTorch接口和自定义接口连接,具体可参见[《Ascend Extension for PyTorch自定义API参考》](https://www.hiascend.com/document/detail/zh/Pytorch/710/apiref/torchnpuCustomsapi/context/%E6%A6%82%E8%BF%B0.md)以及[《PyTorch原生接口清单》](https://www.hiascend.com/document/detail/zh/Pytorch/710/apiref/PyTorchNativeapi/ptaoplist_000003.html)。
参考[PyTorch社区公开接口规范](https://github.com/pytorch/pytorch/wiki/Public-API-definition-and-documentation),Ascend Extension for PyTorch提供了对外的自定义接口。如果一个函数看起来符合公开接口的标准且在文档中有展示,则该接口是公开接口。否则,使用该功能前可以在社区询问该功能是否确实是公开的或意外暴露的接口,因为这些未暴露接口将来可能会被修改或者删除。
Ascend Extension for PyTorch项目采用C++和Python联合开发,当前除Libtorch场景外正式接口只提供Python接口,在torch_npu的二进制包中动态库不直接提供服务,暴露的接口为内部使用,不建议用户使用。
## 通信安全加固
PyTorch分布式训练服务需要在设备间进行通信,通信开启的端口默认为全0侦听,为了降低安全风险,建议用户针对此场景进行安全加固,如使用iptables配置防火墙,在运行分布式训练开始前限制外部对分布式训练使用端口的访问,在运行分布式训练结束后清理防火墙规则。
1. 防火墙规则设定和移除参考脚本模板
- 防火墙规则设定,可参考如下脚本:
```
#!/bin/bash
set -x
# 要限制的端口号
port={端口号}
# 清除旧规则
iptables -D INPUT -p tcp -j {规则名}
iptables -F {规则名}
iptables -X {规则名}
# 创建新的规则链
iptables -t filter -N {规则名}
# 在多机场景下设定白名单,允许其他节点访问主节点的侦听端口
# 在规则链中添加允许特定IP地址范围的规则
iptables -t filter -A {规则名} -i eno1 -p tcp --dport $port -s {允许外部访问的IP} -j ACCEPT
# 屏蔽外部地址访问分布式训练端口
# 在PORT-LIMIT-RULE规则链中添加拒绝其他IP地址的规则
iptables -t filter -A {规则名} -i {要限制的网卡名} -p tcp --dport $port -j DROP
# 将流量传递给规则链
iptables -I INPUT -p tcp -j {规则名}
```
- 防火墙规则移除,可参考如下脚本:
```
#!/bin/bash
set -x
# 清除规则
iptables -D INPUT -p tcp -j {规则名}
iptables -F {规则名}
iptables -X {规则名}
```
2. 防火墙规则设定和移除参考脚本示例
1. 针对特定端口设定防火墙,脚本中端口号为要限制的端口,在PyTorch分布式训练中端口号请参考[通信矩阵信息](#通信矩阵信息);要限制的网卡名为服务器用于分布式通信使用的网卡,允许的外部访问的IP为分布式训练服务器的IP地址。网卡和服务器IP可以通过ifconfig查看,如下文回显的eth0为网卡名,192.168.1.1为服务器IP地址:
```
# ifconfig
eth0
inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::230:64ee:ef1a:c1a/64 Scope:Link
```
2. 假定服务器主节点地址192.168.1.1,另一台需要进行分布式训练的服务器为192.168.1.2,训练端口为29510。
- 防火墙规则设定,可参考如下脚本:
```
#!/bin/bash
set -x
# 设定侦听的端口
port=29510
# 清除旧规则
iptables -D INPUT -p tcp -j PORT-LIMIT-RULE
iptables -F PORT-LIMIT-RULE
iptables -X PORT-LIMIT-RULE
# 创建新的PORT-LIMIT-RULE规则链
iptables -t filter -N PORT-LIMIT-RULE
# 在多机场景下设定白名单,允许192.168.1.2访问主节点
# 在PORT-LIMIT-RULE规则链中添加允许特定IP地址范围的规则
iptables -t filter -A PORT-LIMIT-RULE -i eno1 -p tcp --dport $port -s 192.168.1.2 -j ACCEPT
# 屏蔽外部地址访问分布式训练端口
# 在PORT-LIMIT-RULE规则链中添加拒绝其他IP地址的规则
iptables -t filter -A PORT-LIMIT-RULE -i eth0 -p tcp --dport $port -j DROP
# 将流量传递给PORT-LIMIT-RULE规则链
iptables -I INPUT -p tcp -j PORT-LIMIT-RULE
```
- 防火墙规则移除,可参考如下脚本:
```
#!/bin/bash
set -x
# 清除规则
iptables -D INPUT -p tcp -j PORT-LIMIT-RULE
iptables -F PORT-LIMIT-RULE
iptables -X PORT-LIMIT-RULE
```
## 通信矩阵
PyTorch提供分布式训练能力,支持在单机和多机场景下进行训练,需要进行网络通信。其中PyTorch需要使用TCP进行通信,torch_npu使用CANN中HCCL在NPU设备间通信,通信端口见[通信矩阵信息](#通信矩阵信息)。用户需要注意并保障节点间通信网络安全,可以使用iptables等方式消减安全风险,可参考[通信安全加固](#通信安全加固)进行网络安全加固。
##### 通信矩阵信息
| 组件 | PyTorch | HCCL |
| --------------------- | ------------------------------------ | ------------------------------------ |
| 源设备 | 运行torch_npu进程的服务器 | 运行torch_npu进程的服务器 |
| 源IP | 设备地址IP | 设备地址IP |
| 源端口 | 操作系统自动分配,分配范围由操作系统的自身配置决定 | 默认值为60000,取值范围[1024,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
| 目的设备 | 运行torch_npu进程的服务器 | 运行torch_npu进程的服务器 |
| 目的IP | 设备地址IP | 设备地址IP |
| 目的端口 (侦听) | 默认29500/29400,用户可以设定端口号 | 默认值为60000,取值范围[1024,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
| 协议 | TCP | TCP |
| 端口说明 | 分布式场景下 <br> 1. torchrun/torch.distributed.launch <br> (1) backend为static时(默认该backend),目的端口(默认29500)用于接收和发送数据,源端口用于接收和发送数据。使用master-addr指定地址,master-port指定端口 <br> (2) backend为c10d时,目的端口(默认29400)用于接收和发送数据,源端口用于接收和发送数据。使用rdzv_endpoint指定地址和端口号,格式为"地址:端口号" <br> 2. torch_npu_run:目的端口(默认29500)用于接收和发送数据,源端口用于接收和发送数据。使用master-addr指定地址,master-port指定端口 | 默认值为60000,取值范围[1024,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
| 侦听端口是否可更改 | 是 | 是 |
| 认证方式 | 无认证方式 | 无认证方式 |
| 加密方式 | 无 | 无 |
| 所属平面 | 不涉及 | 不涉及 |
| 版本 | 所有版本 | 所有版本 |
| 特殊场景 | 无 | 无 |
| 备注 | 该通信过程由开源软件PyTorch控制,配置为PyTorch原生设置,可参考[PyTorch文档](https://pytorch.org/docs/stable/distributed.html#launch-utility)。源端口由操作系统自动分配,分配范围由操作系统的配置决定,例如ubuntu:采用/proc/sys/net/ipv4/ipv4_local_port_range文件指定,可通过cat /proc/sys/net/ipv4/ipv4_local_port_range或sysctl net.ipv4.ip_local_port_range查看 | 该通信过程由CANN中HCCL组件控制,torch_npu不进行控制,端口范围可参考[《环境变量参考》](https://www.hiascend.com/document/detail/zh/canncommercial/82RC1/maintenref/envvar/envref_07_0001.html)的“执行相关 > 集合通信 >HCCL_IF_BASE_PORT” |
## 漏洞机制说明
Ascend Extension for PyTorch 社区非常重视社区版本的安全性,专门设置了漏洞管理专员负责处理漏洞相关的事务,同时为了构建更安全的AI全流程工具链,我们也欢迎您一起参与。
### 漏洞处理流程
对于每一个安全漏洞,Ascend Extension for PyTorch 社区会安排人员进行跟踪和处理,漏洞处理的端到端流程如下图所示。
![漏洞处理流程](./figures/cve.png)
下面将重点解释漏洞上报、漏洞评估、漏洞披露的流程。
### 漏洞上报
您可以通过提交issue的方式联系 Ascend Extension for PyTorch 社区团队,我们将会第一时间安排安全漏洞专项人员向您联系。
注意,为了确保安全性,请不要在issue中描述涉及安全隐私的具体信息。
#### 上报响应
1. Ascend Extension for PyTorch 社区会在3个工作日内确认、分析、上报安全漏洞问题,同时启动安全处理流程。
2. Ascend Extension for PyTorch 安全团队在确认安全漏洞问题后,会对问题进行分发和跟进。
3. 在安全漏洞问题从分类、确定、修复和发布的过程中,我们会及时更新报告。
### 漏洞评估
业界普遍使用 CVSS 标准评估漏洞的严重性,Ascend Extension for PyTorch 在使用 CVSS v3.1 进行漏洞评估时,需要设定漏洞攻击场景,基于在该攻击场景下的实际影响进行评估。漏洞严重等级评估是指针对漏洞利用难易程度,以及利用后对机密性、完整性、可用性的影响进行评估,并生成一个评分值。
#### 漏洞评估标准
Ascend Extension for PyTorch 通过以下向量评估一个漏洞的严重等级:
- 攻击向量(AV):表示攻击的“远程性”以及如何利用此漏洞。
- 攻击复杂性(AC):讲述攻击执行的难度以及成功进行攻击需要哪些因素。
- 用户交互(UI):确定攻击是否需要用户参与。
- 所需的权限(PR):记录成功进行攻击所需的用户身份验证级别。
- 范围(S):确定攻击者是否可以影响具有不同权限级别的组件。
- 机密性(C):衡量信息泄露给非授权方后导致的影响程度。
- 完整性(I):衡量信息被篡改后导致的影响程度。
- 可用性(A):衡量用户在需要访问数据或服务时受影响的程度。
#### 评估原则
- 评估漏洞的严重等级,不是评估风险。
- 评估时必须基于攻击场景,且保证在该场景下,攻击者成功攻击后能对系统造成机密性、完整性、可用性影响。
- 当安全漏洞有多个攻击场景时,应以造成最大的影响,即 CVSS 评分最高的攻击场景为依据。
- 被嵌入调用的库存在漏洞,要根据该库在产品中的使用方式,确定漏洞的攻击场景后进行评估。
- 安全缺陷不能被触发或不影响 CIA(机密性、完整性、可用性),CVSS 评分为 0 分。
#### 评估步骤
评估漏洞严重等级时,可根据下述步骤进行操作:
1. 设定可能的攻击场景,基于攻击场景评分。
2. 确定漏洞组件(Vulnerable Component)和受影响组件(Impact Component)。
3. 选择基础指标的值。
- 可利用指标(攻击向量、攻击复杂度、所需权限、用户交互、范围)根据漏洞组件选择指标值。
- 影响指标(机密性、完整性、可用性)要么反映对漏洞组件的影响,要么反映对受影响组件影响,以结果最严重的为准。
#### 严重等级划分
| **严重等级(Severity Rating)** | **CVSS评分(Score)** | **漏洞修复时长** |
| ------------------------------- | --------------------- | ---------------- |
| 致命(Critical) | 9.0~10.0 | 7天 |
| 高(High) | 7.0~8.9 | 14天 |
| 中(Medium) | 4.0~6.9 | 30天 |
| 低(Low) | 0.1~3.9 | 30天 |
### 漏洞披露
安全漏洞修复后 Ascend Extension for PyTorch 社区会发布安全公告 (SA)以及安全说明(SN) ,安全公告内容包括该漏洞的技术细节、类型、上报人、CVE ID 以及受到该漏洞影响的版本和修复版本等信息。
为了保护 Ascend Extension for PyTorch 用户的安全,在进行调查、修复和发布安全公告之前, Ascend Extension for PyTorch 社区不会公开披露、讨论或确认 Ascend Extension for PyTorch 产品的安全问题。
### 附录
#### 安全公告(SA)
目前在维护版本,无安全漏洞
#### 安全说明(SN)
涉及第三方的开源组件部分漏洞说明:
PyTorch 2.2.0以下版本存在CVE-2024-31583漏洞,该漏洞在torch/csrc/jit/mobile/interpreter.cpp组件中存在use-after-free问题(内存释放后程序继续使用该内存)。 如需要使用jit相关功能,建议用户使用2.2.0及以上的修复版本。
PyTorch 2.2.0以下版本存在CVE-2024-31580漏洞,该漏洞在torch/csrc/jit/runtime/vararg_functions.cpp组件中存在buffer-overflow问题(缓冲区溢出)。 如需要使用jit相关功能,建议用户使用2.2.0及以上的修复版本。
PyTorch 2.2.0以下版本存在CVE-2024-31584漏洞,该漏洞在torch/csrc/jit/mobile/flatbuffer_loader.cpp组件中存在越界读取问题。 如需要使用jit相关功能,建议用户使用2.2.0及以上的修复版本。
PyTorch 2.6.0以下版本存在CVE-2025-32434漏洞,该漏洞因torch/serialization.py组件兼容性处理导致潜在的远程代码执行(RCE)风险。 torch_npu已参考[LINK](https://github.com/pytorch/pytorch/pull/145020)进行修复。
+85 -190
View File
@@ -1,190 +1,85 @@
OPEN SOURCE SOFTWARE NOTICE
Please note we provide an open source software notice along with this product and/or this product firmware (in the following just "this product"). The open source software licenses are granted by the respective right holders. And the open source licenses prevail all other license information with regard to the respective open source software contained in the product, including but not limited to End User Software Licensing Agreement. This notice is provided on behalf of Huawei Technologies Co. Ltd. and any of its local subsidiaries which may have provided this product to you in your local country.
Warranty Disclaimer
THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
Copyright Notice and License Texts
Software: pytorch v2.6.0
Copyright notice:
Copyright (c) Advanced Micro Devices, Inc.
Copyright (c) Microsoft Corporation
Copyright (c) Bjorn Fahller
Copyright (c) 2001-2014 Python Software Foundation All Rights Reserved
Copyright (c) 2011-2013 NYU
Copyright (c) 1995-2011 by Fredrik Lundh
Copyright (c) Edward Z. Yang ezyang@mit.edu
Copyright (c) 2014- Facebook, Inc
Copyright (c) 2017 The Android Open Source Project
Copyright Python Software Foundation
Copyright (c) 2012 Massachusetts Institute of Technology
Copyright (c) 2018 Alex Rogozhnikov
Copyright (c) 2007-2009 Scientific Computing and Imaging Institute, University of Utah
Copyright (c) 2006 Idiap Research Institute
Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved
Copyright (c) 2015 Yangqing Jia All rights reserved
Copyright (c) Meta Platforms, Inc.
Copyright 2023-present Facebook. All Rights Reserved
Copyright (c) 2022 Apple Inc.
Copyright (c) 2005-2017, NumPy Developers. All rights reserved
Copyright (c) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved
Copyright (c) 2014, The Regents
Copyright (c) 2005-2010 ActiveState Software Inc.
Copyright Malte Skarupke 2017
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
Copyright 2005, Google Inc. All rights reserved
Copyright (c) Meta Platforms, Inc. and affiliates
Copyright (c) 2023, Advanced Micro Devices, Inc.
Copyright (c) 2022, Tri Dao
Copyright (c) 2005-2023 NVIDIA Corporation Built
Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers. All rights reserved
Copyright 2008 Google Inc. All rights reserved
Copyright (c) 2021, 2023-2024 Arm Limited
Copyright (c) 2003-2017 Josef Weidendorfer. All rights reserved
Copyright (c) 1997-2011 by Secret Labs AB
Copyright (c) 2016- Facebook, Inc
Copyright (c) 2014 Matthew Rocklin
Copyright (c) 2005-2022 NVIDIA Corporation Built
Copyright (c) Facebook, Inc.
Copyright 2019-2020 Kakao Brain
Copyright (c) 2000-2017 Julian Seward. All rights reserved
Copyright (c) 2005-2020 Rich Felker
Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
Copyright (c) 2016 Facebook Inc.
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC All Rights Reserved
Copyright (c) 2012-2014 Deepmind Technologies
Copyright (c) 2012 Giovanni Garberoglio Interdisciplinary Laboratory
Copyright (c) 2024, Tri Dao
Copyright (c) Donald Stufft and individual contributors. All rights reserved
Copyright (c) 2018, Steven Moshier All rights reserved
Copyright (c) 2015 Google Inc. All rights reserved
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved
Copyright (c) 2010-2022 by Alex Clark and contributors
Copyright 2015 Google Inc. All Rights Reserved
Copyright (c) 2017 - 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved
Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved
Copyright (c) 2016 manylinux
Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
Copyright 2013-2014 RAD Game
Copyright (c) 2011-2019 Stephan Brumme. All rights reserved
Copyright (c) 2018 MathInf GmbH, Thomas Viehmann
Copyright (c) 2013 Eddy Petrisor
Copyright (c) 2023-2024 The ggml
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation All Rights Reserved
Copyright 2004-present Facebook. All Rights Reserved
Copyright (c) 2010 ActiveState Software Inc.
Copyright (c) 2006 The Android Open Source Project
(c) Meta Platforms, Inc. and affiliates. All rights reserved
Copyright (c) 2023 Apple Inc.
Copyright (c) Microsoft Corporation. All rights reserved
Copyright 2015 The TensorFlow Authors. All Rights Reserved
Copyright (c) 2023, Tri Dao
Copyright 2022 Cruise LLC
Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved
Copyright (c) 2022 Cruise LLC. All rights reserved
Copyright (c) 2016-present, Facebook, Inc.
(c) Copyright John Maddock 2006
Copyright (c) 2011-2014 Idiap Research Institute
Copyright (c) 2014 Indiana University All rights reserved
copyright 2019 The TensorFlow Authors
Copyright (c) 2016-present, Facebook Inc. All rights reserved
License: BSD 3-Clause License
Copyright (c) ,
All rights reserved.
1. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
OPEN SOURCE SOFTWARE NOTICE
Please note we provide an open source software notice along with this product and/or this product firmware (in the following just “this product”). The open source software licenses are granted by the respective right holders. And the open source licenses prevail all other license information with regard to the respective open source software contained in the product, including but not limited to End User Software Licensing Agreement. This notice is provided on behalf of Huawei Technologies Co. Ltd. and any of its local subsidiaries which may have provided this product to you in your local country.
Warranty Disclaimer
THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
Copyright Notice and License Texts
Software: pytorch 1.5.0
Copyright notice:
Copyright (c) 2016-present, Facebook, Inc.
Copyright (c) Facebook, Inc. and its affiliates.
Copyright 2006, Google Inc.
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
2017-2018 Advanced Micro Devices, Inc. and Facebook Inc. All rights reserved.
Copyright 2004-present Facebook. All Rights Reserved.
Copyright (c) 2018 MathInf GmbH, Thomas Viehmann
Copyright (c) 2014 Indiana University
Copyright (c) 2016, NVIDIA CORPORATION, All rights reserved
Copyright (C) 2012 Giovanni Garberoglio
Copyright 2015 Google Inc. All Rights Reserved.
Copyright (c) Facebook Inc. and Microsoft Corporation.
Copyright © 2001-2014 Python Software Foundation
All Rights Reserved
Copyright (c) 2014-2015 The Khronos Group Inc.
Copyright (c) 2006, Laurent Montel, montel@kde.org
Copyright 2013 Conrad Steenberg conrad.steenberg@gmail.com
Copyright (C) 2017 The Android Open Source Project
Copyright (c) 2010-2017 Benjamin Peterson
Copyright 2013-2014 RAD Game Tools and Valve Software
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved.
Copyright (c) 2007-2009 Scientific Computing and Imaging Institute, University of Utah
(c) Facebook, Inc. and its affiliates. Confidential and proprietary.
Copyright (c) 2017 by Contributors
Copyright 2016 Facebook
Copyright (C) 2018 Marat Dukhan
Copyright (c) 2017-2018 Facebook Inc.
Copyright (c) 2017 Georgia Institute of Technology
Copyright (c) 2016 Microsoft
Copyright (c) 2014, 2015, The Regents of the University of California
Copyright (c) 2014, 2015, the respective contributors
Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
Copyright (c) 2011-2013 NYU (Clement Farabet)
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert,Leon Bottou, Iain Melvin, Jason Weston)
Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert,Samy Bengio, Johnny Mariethoz)
Copyright (c) 2016-2017, ARM Limited and Contributors
Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
Copyright (C) 2007-2017 Free Software Foundation, Inc.
Copyright Malte Skarupke 2017.
Copyright (C) 2011 - 2012 Andrzej Krzemienski.
Copyright (C) 2001-2019 Free Software Foundation, Inc.
Copyright (c) 1994 Hewlett-Packard Company
Copyright (c) 1996-1998 Silicon Graphics Computer Systems, Inc.
Copyright Michael Park, 2015-2017
Copyright (c) 2008 - 2012 The Khronos Group Inc.
Copyright (c) 2008-2013 The Khronos Group Inc.
Copyright (c) 2008-2012 The Khronos Group Inc.
Copyright (C) 2006 The Android Open Source Project
Copyright (c) 2016- Facebook, Inc (Adam Paszke)
Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
Copyright (c) 2011-2013 NYU (Clement Farabet)
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
Copyright (c) 2016-present, Facebook Inc. All rights reserved.
Copyright (c) 2016 Facebook Inc.
Copyright (c) 2015 Google Inc.
Copyright (c) 2015 Yangqing Jia
Copyright(c) 2013, 2014, 2015, the respective contributors
Copyright(c) 2015, 2016 the respective contributors
Copyright (c) 2014, The Regents of the University of California (Regents)
Copyright (c) 2014, the respective contributors
Copyright (c) 2008-2015 The Khronos Group Inc.
Copyright (c) 2014-2017 The Regents of the University of California (Regents)
Copyright (c) 2014-2017, the respective contributors
Copyright (c) 2017 Microsoft
Copyright (c) 2017-present, Facebook, Inc.
Copyright (c) 2018-present, Facebook, Inc.
License: BSD 3-Clause License
Please see above.
+190
View File
@@ -0,0 +1,190 @@
# -*- coding: UTF-8 -*-
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import sys
import subprocess
from abc import ABCMeta, abstractmethod
DEFAULT_UT_FILE = 'test/test_npu/test_add.py'
class AccurateTest(metaclass=ABCMeta):
@abstractmethod
def identify(self, modify_files):
"""
该接口提供代码对应的UT的路径信息
"""
raise Exception("abstract method.")
def find_ut_by_regex(self, regex):
ut_files = []
cmd = "find {} -name {}".format('test/test_npu', regex)
status, output = subprocess.getstatusoutput(cmd)
if status:
pass # 对于找不到的暂时不作处理
else:
if output:
files = output.split('\n')
for ut_file in files:
if ut_file.endswith(".py"):
ut_files.append(ut_file)
return ut_files
class OpStrategy(AccurateTest):
"""
通过对适配层的代码的识别
"""
def identify(self, modify_file):
"""
通过对于算子实现文件的文件名解析获取其单元测试的名字,比如:
BinaryCrossEntropyWithLogitsBackwardKernelNpu.cpp
针对这个文件,先识别关键字BinaryCrossEntropyWithLogitsBackward
然后,获取其正则表达式*binary*cross*entropy*with*logits*backward*识别到符合要求的测试用例
具体方法:通过大写字母切分关键字,再识别包含所有这些关键字的测试文件名。
"""
filename = os.path.basename(modify_file)
if filename.find('KernelNpu') >= 0:
feature_line = filename.split('KernelNpu')[0]
features = re.findall('[A-Z][^A-Z]*', feature_line)
regex = '*' + '*'.join(["%s" % feature.lower() for feature in features]) + '*'
return self.find_ut_by_regex(regex)
return []
class DirectoryStrategy(AccurateTest):
"""
通过识别测试文件的目录确认需要进行UT的文件
"""
def identify(self, modify_file):
second_dir = modify_file.split("/")[0]
if second_dir == 'test':
return [modify_file]
return []
class CopyOptStrategy(AccurateTest):
"""
通过识别非连续转连续的测试用例
"""
def identify(self, modify_file):
if modify_file.find('contiguous') > 0:
regex = '*contiguous*'
return self.find_ut_by_regex(regex)
return []
class TestMgr():
def __init__(self):
self.modify_files = []
self.ut_files = []
def load(self, modify_files):
with open(modify_files) as f:
for line in f:
line = line.strip()
self.modify_files.append(line)
def analyze(self):
for modify_file in self.modify_files:
self.ut_files += DirectoryStrategy().identify(modify_file)
self.ut_files += OpStrategy().identify(modify_file)
self.ut_files += CopyOptStrategy().identify(modify_file)
unique_files = set(self.ut_files)
exist_ut_file = []
for changed_file in unique_files:
if os.path.exists(changed_file):
exist_ut_file.append(changed_file)
self.ut_files = exist_ut_file
if len(self.ut_files) == 0:
self.ut_files.append(DEFAULT_UT_FILE)
def get_ut_files(self):
return self.ut_files
def print_modify_files(self):
print("modify files:")
for modify_file in self.modify_files:
print(modify_file)
def print_ut_files(self):
print("ut files:")
for ut_file in ut_files:
print(ut_file)
def exec_ut(ut_files):
"""
执行单元测试文件,其中存在失败,则标识异常并打印相关信息
"""
def change_dir_and_exec(ut_path):
ut_dir = os.path.dirname(ut_path)
ut_file = os.path.basename(ut_path)
os.chdir(ut_dir)
cmd = "python3 {}".format(ut_file)
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
try:
msg = p.communicate(timeout=300)
ret = p.poll()
if ret:
print(msg)
except subprocess.TimeoutExpired:
p.kill()
p.terminate()
ret = 1
print("Timeout: Command '" + cmd + "' timed out after 300 seconds")
except Exception as err:
ret = 1
print(err)
return ret
ret_status = 0
cur_dir = os.path.abspath(os.path.dirname(__file__))
exec_infos = []
for ut_file in ut_files:
os.chdir(cur_dir)
ret = change_dir_and_exec(ut_file)
if ret:
ret_status = ret
exec_infos.append("exec ut {} failed.".format(ut_file))
else:
exec_infos.append("exec ut {} success.".format(ut_file))
print("***** Total result:")
for exec_info in exec_infos:
print(exec_info)
return ret_status
if __name__ == "__main__":
cur_dir = os.path.abspath(os.path.dirname(__file__))
modify_files = os.path.join(cur_dir, 'modify_files.txt')
test_mgr = TestMgr()
test_mgr.load(modify_files)
test_mgr.analyze()
ut_files = test_mgr.get_ut_files()
test_mgr.print_modify_files()
test_mgr.print_ut_files()
ret = exec_ut(ut_files)
sys.exit(ret)
-275
View File
@@ -1,275 +0,0 @@
import multiprocessing
import glob
import os
import re
import shutil
import subprocess
import sys
import traceback
import platform
from pathlib import Path
from sysconfig import get_paths
from distutils.version import LooseVersion
from distutils import file_util
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
VERSION = '2.1.0'
def which(thefile):
path = os.environ.get("PATH", os.defpath).split(os.pathsep)
for d in path:
fname = os.path.join(d, thefile)
fnames = [fname]
if sys.platform == 'win32':
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
fnames += [fname + ext for ext in exts]
for name in fnames:
if os.access(name, os.F_OK | os.X_OK) and not os.path.isdir(name):
return name
return None
def get_cmake_command():
def _get_version(cmd):
for line in subprocess.check_output([cmd, '--version']).decode('utf-8').split('\n'):
if 'version' in line:
return LooseVersion(line.strip().split(' ')[2])
raise RuntimeError('no version found')
"Returns cmake command."
cmake_command = 'cmake'
if platform.system() == 'Windows':
return cmake_command
cmake3 = which('cmake3')
cmake = which('cmake')
if cmake3 is not None and _get_version(cmake3) >= LooseVersion("3.18.0"):
cmake_command = 'cmake3'
return cmake_command
elif cmake is not None and _get_version(cmake) >= LooseVersion("3.18.0"):
return cmake_command
else:
raise RuntimeError('no cmake or cmake3 with version >= 3.18.0 found')
def get_build_type():
build_type = 'Release'
if os.getenv('DEBUG', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
build_type = 'Debug'
if os.getenv('REL_WITH_DEB_INFO', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
build_type = 'RelWithDebInfo'
return build_type
def get_pytorch_dir():
try:
import torch
return os.path.dirname(os.path.abspath(torch.__file__))
except Exception:
_, _, exc_traceback = sys.exc_info()
frame_summary = traceback.extract_tb(exc_traceback)[-1]
return os.path.dirname(frame_summary.filename)
def generate_bindings_code(base_dir):
python_execute = sys.executable
generate_code_cmd = ["bash", os.path.join(base_dir, 'generate_code.sh'), python_execute, VERSION]
if subprocess.call(generate_code_cmd) != 0:
print(
'Failed to generate ATEN bindings: {}'.format(generate_code_cmd),
file=sys.stderr)
sys.exit(1)
def build_stub(base_dir):
build_stub_cmd = ["sh", os.path.join(base_dir, 'third_party/acl/libs/build_stub.sh')]
if subprocess.call(build_stub_cmd) != 0:
print(
'Failed to build stub: {}'.format(build_stub_cmd),
file=sys.stderr)
sys.exit(1)
def clean_generated_files():
f_ignore = open(os.path.join(BASE_DIR, '.gitignore'), 'r')
ignores = f_ignore.read()
pat = re.compile(r'^#( BEGIN NOT-CLEAN-FILES )?')
for wildcard in filter(None, ignores.split('\n')):
match = pat.match(wildcard)
if match:
if match.group(1):
# Marker is found and stop reading .gitignore.
break
# Ignore lines which begin with '#'.
else:
for filename in glob.glob(wildcard):
shutil.rmtree(filename, ignore_errors=True)
f_ignore.close()
clean_files = ['torch_npu/csrc/aten/RegisterCPU.cpp', 'torch_npu/csrc/aten/RegisterNPU.cpp',
'torch_npu/csrc/aten/RegisterAutogradNPU.cpp', 'torch_npu/csrc/aten/NPUNativeFunctions.h']
for file in clean_files:
if os.path.exists(os.path.join(BASE_DIR, file)):
os.remove(os.path.join(BASE_DIR, file))
if os.path.exists(os.path.join(BASE_DIR, "libtorch")):
shutil.rmtree(os.path.join(BASE_DIR, "libtorch"))
def check_gtest_valid(base_dir):
# validation of GoogleTest path.
gtest_path = os.path.join(base_dir, 'third_party/googletest/CMakeLists.txt')
return os.path.exists(gtest_path)
def generate_dbg_files_and_strip():
library_dir = Path(BASE_DIR).joinpath("build/packages/torch_npu")
dbg_dir = Path(BASE_DIR).joinpath("build/dbg_libtorch")
os.makedirs(dbg_dir, exist_ok=True)
library_files = [Path(i) for i in library_dir.rglob('*.so')]
for library_file in library_files:
subprocess.check_call(["eu-strip", library_file, "-f",
str(dbg_dir.joinpath(library_file.name)) + ".debug"], cwd=BASE_DIR) # Compliant
def run_cmake():
cmake = get_cmake_command()
if cmake is None:
raise RuntimeError(
"CMake must be installed to build the following extensions: ")
build_dir = os.path.join(BASE_DIR, "build")
build_type_dir = os.path.join(build_dir)
output_lib_path = os.path.join(build_type_dir, "packages/torch_npu/lib")
os.makedirs(build_type_dir, exist_ok=True)
os.makedirs(output_lib_path, exist_ok=True)
cmake_args = [
'-DCMAKE_BUILD_TYPE=' + get_build_type(),
'-DCMAKE_INSTALL_PREFIX=' + os.path.abspath(output_lib_path),
'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + os.path.abspath(output_lib_path),
'-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=' + os.path.abspath(output_lib_path),
'-DTORCHNPU_INSTALL_LIBDIR=' + os.path.abspath(output_lib_path),
'-DPYTHON_INCLUDE_DIR=' + get_paths().get('include'),
'-DPYTORCH_INSTALL_DIR=' + get_pytorch_dir(),
'-DTORCH_VERSION=' + VERSION,
'-DBUILD_LIBTORCH=' + "ON"]
if check_opplugin_valid(BASE_DIR):
cmake_args.append('-DBUILD_OPPLUGIN=on')
cmake_args.append('-DBUILD_NEW_HEADER=on')
if check_tensorpipe_valid(BASE_DIR):
cmake_args.append('-DBUILD_TENSORPIPE=on')
if os.getenv('_GLIBCXX_USE_CXX11_ABI') is not None:
cmake_args.append('-DGLIBCXX_USE_CXX11_ABI=' + os.getenv('_GLIBCXX_USE_CXX11_ABI'))
if os.getenv('_ABI_VERSION') is not None:
cmake_args.append('-DABI_VERSION=' + os.getenv('_ABI_VERSION'))
build_args = ['-j', str(multiprocessing.cpu_count())]
subprocess.check_call([cmake, BASE_DIR] + cmake_args, cwd=build_type_dir, env=os.environ)
subprocess.check_call(['make'] + build_args, cwd=build_type_dir, env=os.environ)
if which('eu-strip') is not None:
generate_dbg_files_and_strip()
def check_opplugin_valid(base_dir):
# build with submodule of op_plugin, if path of op-plugin is valid
op_plugin_path = os.path.join(base_dir, 'third_party/op-plugin/op_plugin')
return os.path.exists(op_plugin_path)
def check_tensorpipe_valid(base_dir):
tensorpipe_path = os.path.join(base_dir, 'third_party/Tensorpipe/tensorpipe')
return os.path.exists(tensorpipe_path)
def copy_file(infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1):
"""Copy a file respecting verbose, dry-run and force flags. (The
former two default to whatever is in the Distribution object, and
the latter defaults to false for commands that don't define it.)
"""
return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, True, link)
def move_special_hpp(ret):
hpp_name = "torch_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():
ret = []
header_files = [
"torch_npu/csrc/aten/*.h",
"torch_npu/csrc/aten/*/*.h",
"torch_npu/csrc/aten/*/*/*.h",
"torch_npu/csrc/core/*.h",
"torch_npu/csrc/core/*/*.h",
"torch_npu/csrc/core/*/*/*.h",
"torch_npu/csrc/framework/*.h",
"torch_npu/csrc/framework/*/*.h",
"torch_npu/csrc/framework/*/*/*.h",
"torch_npu/csrc/libs/*.h"
]
glob_header_files = []
for regex_pattern in header_files:
glob_header_files += glob.glob(os.path.join(BASE_DIR, regex_pattern), recursive=True)
for src in glob_header_files:
dst = os.path.join(
os.path.join(BASE_DIR, "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))
return ret
ret = get_src_py_and_dst()
for src, dst in ret:
copy_file(src, dst)
move_special_hpp(ret)
def copy_lib():
lib_file = ["build/packages/torch_npu/lib/*.*"]
glob_lib_files = []
for regex_pattern in lib_file:
glob_lib_files += glob.glob(os.path.join(BASE_DIR, regex_pattern), recursive=True)
dst_path = os.path.join(BASE_DIR, "libtorch_npu/lib")
os.makedirs(dst_path, exist_ok=True)
for src in glob_lib_files:
_, src_file_name = os.path.split(src)
copy_file(src, os.path.join(dst_path, src_file_name))
def copy_cmake():
cmake_file = os.path.join(BASE_DIR, "build/Torch_npuConfig.cmake")
dst_path = os.path.join(BASE_DIR, "libtorch_npu/share/cmake/Torch_npu")
os.makedirs(dst_path, exist_ok=True)
copy_file(cmake_file, dst_path)
def build_libtorch_npu():
clean_generated_files()
generate_bindings_code(BASE_DIR)
if Path(BASE_DIR).joinpath("third_party/Tensorpipe/third_party/acl/libs").exists():
build_stub(Path(BASE_DIR).joinpath("third_party/Tensorpipe"))
build_stub(BASE_DIR)
run_cmake()
copy_hpp()
copy_lib()
copy_cmake()
if __name__ == "__main__":
build_libtorch_npu()
-5
View File
@@ -1,5 +0,0 @@
from .constants import (
BASE_DIR, TEST_DIR, NETWORK_OPS_DIR,
SLOW_TEST_BLOCKLIST, NOT_RUN_DIRECTLY, INCLUDE_FILES, EXEC_TIMEOUT
)
from .test_manager import TestMgr
-36
View File
@@ -1,36 +0,0 @@
import os
from pathlib import Path
BASE_DIR = Path(__file__).absolute().parent.parent.parent
TEST_DIR = BASE_DIR / 'test'
NETWORK_OPS_DIR = BASE_DIR / 'third_party/op-plugin/test'
# Add slow test cases here (first element must be test_ops)
SLOW_TEST_BLOCKLIST = [
'test_ops',
'test_modules',
'test_binary_ufuncs',
'test_ops_fwd_gradients',
'test_ops_gradients',
'test_reductions',
'test_unary_ufuncs',
'test_ops_jit',
'test_jit_fuser_te',
'onnx/test_op_consistency',
'test_foreach',
'onnx/test_pytorch_onnx_onnxruntime'
]
# exclude some not run directly test files
NOT_RUN_DIRECTLY = {
"jit": "test_jit.py",
}
# include some files
INCLUDE_FILES = [
'jit/test_complexity.py',
]
# default ut cmd execution timeout is 2000s
EXEC_TIMEOUT = os.getenv("PTA_UT_EXEC_TIMEOUT", "2000")
EXEC_TIMEOUT = int(EXEC_TIMEOUT) if EXEC_TIMEOUT.isdigit() else 2000
-5
View File
@@ -1,5 +0,0 @@
from .copy_opt import CopyOptStrategy
from .core import CoreTestStrategy
from .directory_mapping import DirectoryMappingStrategy
from .op import OpStrategy
from .test_file import TestFileStrategy
-30
View File
@@ -1,30 +0,0 @@
import os
import subprocess
from abc import ABCMeta, abstractmethod
from ..constants import BASE_DIR
class AccurateTest(metaclass=ABCMeta):
base_dir = BASE_DIR
test_dir = base_dir / 'test'
@abstractmethod
def identify(self, modify_file):
"""
该接口提供代码对应的UT的路径信息
"""
raise Exception("abstract method. Subclasses should implement it.")
@classmethod
def find_ut_by_regex(cls, regex):
ut_files = []
cmd = "find {} -name {}".format(str(cls.test_dir), regex)
status, output = subprocess.getstatusoutput(cmd)
# 对于找不到的暂不作处理
if not(status or not output):
files = output.split('\n')
for ut_file in files:
ut_file_basename = os.path.basename(ut_file)
if ut_file_basename.startswith("test") and ut_file.endswith(".py"):
ut_files.append(ut_file)
return ut_files
-13
View File
@@ -1,13 +0,0 @@
from .base import AccurateTest
class CopyOptStrategy(AccurateTest):
"""
通过识别非连续转连续的测试用例
"""
def identify(self, modify_file):
if modify_file.find('contiguous') > 0:
regex = '*contiguous*'
return AccurateTest.find_ut_by_regex(regex)
return []
-18
View File
@@ -1,18 +0,0 @@
from pathlib import Path
from .base import AccurateTest
class CoreTestStrategy(AccurateTest):
"""
Determine whether the core tests should be runned
"""
def __init__(self):
super().__init__()
self.block_list = ['test', 'docs']
self.core_test_cases = [str(i) for i in (self.base_dir / 'test/npu').rglob('test_*.py')]
def identify(self, modify_file):
modified_module = str(Path(modify_file).parts[0])
if modified_module not in self.block_list:
return self.core_test_cases
return []
@@ -1,55 +0,0 @@
from pathlib import Path
from .base import AccurateTest
class DirectoryMappingStrategy(AccurateTest):
"""
Map the modified files to the corresponding test cases
"""
mapping_list = {
'contrib': 'test/contrib',
'cpp_extension': 'test/cpp_extensions',
'distributed': 'test/distributed',
'fx': 'test/test_fx.py',
'optim': 'test/optim',
'profiler': 'test/profiler',
'onnx': 'test/onnx',
'utils': 'test/test_utils.py',
'testing': 'test/test_testing.py',
'jit': 'test/test_jit.py',
'rpc': 'test/distributed/rpc',
'dynamo': 'test/dynamo',
'checkpoint': 'test/distributed/checkpoint',
}
@staticmethod
def get_module_name(modify_file):
module_name = str(Path(modify_file).parts[1])
if module_name == 'csrc':
module_name = str(Path(modify_file).parts[2])
for part in Path(modify_file).parts:
if part == 'rpc' or part == 'checkpoint':
module_name = part
if module_name == 'utils' and Path(modify_file).parts[2] == 'cpp_extension.py':
module_name = 'cpp_extension'
if module_name == 'utils' and 'dynamo' in Path(modify_file).parts[2]:
module_name = 'dynamo'
return module_name
def identify(self, modify_file):
current_all_ut_path = []
if str(Path(modify_file).parts[0]) == 'torch_npu':
mapped_ut_path = []
module_name = self.get_module_name(modify_file)
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(self.base_dir.joinpath(mapped_path)):
current_all_ut_path.append(str(self.base_dir.joinpath(mapped_path)))
else:
current_all_ut_path += [str(i) for i in (self.base_dir.joinpath(mapped_path)).glob('test_*.py')]
return current_all_ut_path
-25
View File
@@ -1,25 +0,0 @@
import re
from pathlib import Path
from .base import AccurateTest
class OpStrategy(AccurateTest):
"""
通过对适配层的代码的识别
"""
def identify(self, modify_file):
"""
通过对于算子实现文件的文件名解析获取其单元测试的名字,比如:
BinaryCrossEntropyWithLogitsBackwardKernelNpu.cpp
针对这个文件,先识别关键字BinaryCrossEntropyWithLogitsBackward
然后,获取其正则表达式*binary*cross*entropy*with*logits*backward*识别到符合要求的测试用例
具体方法:通过大写字母切分关键字,再识别包含所有这些关键字的测试文件名。
"""
filename = Path(modify_file).name
if filename.find('KernelNpu') >= 0:
feature_line = filename.split('KernelNpu')[0]
features = re.findall('[A-Z][^A-Z]*', feature_line)
regex = '*' + '*'.join([f"{feature.lower()}" for feature in features]) + '*'
return AccurateTest.find_ut_by_regex(regex)
return []
-14
View File
@@ -1,14 +0,0 @@
import re
from pathlib import Path
from .base import AccurateTest
class TestFileStrategy(AccurateTest):
"""
Determine whether the modified files are test cases
"""
def identify(self, modify_file):
is_test_file = str(Path(modify_file).parts[0]) == "test" \
and re.match("test_(.+).py", Path(modify_file).name)
return [(str(self.base_dir.joinpath(modify_file)))] if is_test_file else []
-159
View File
@@ -1,159 +0,0 @@
import os
import re
from pathlib import Path
import torch_npu
from .strategy import (
TestFileStrategy,
CopyOptStrategy,
OpStrategy,
DirectoryMappingStrategy,
CoreTestStrategy
)
from .constants import (
BASE_DIR, TEST_DIR, SLOW_TEST_BLOCKLIST, INCLUDE_FILES
)
def get_test_torch_version_path():
torch_npu_version = torch_npu.__version__
version_list = torch_npu_version.split('.')
if len(version_list) > 2:
return f'test_v{version_list[0]}r{version_list[1]}_ops'
else:
raise RuntimeError("Invalid torch_npu version.")
class TestMgr:
def __init__(self):
self.modify_files = []
self.test_files = {
'ut_files': [],
'op_ut_files': []
}
def load(self, modify_files, world_size):
with open(modify_files) as f:
for line in f:
if world_size != 0 and "test/distributed/" in line:
continue
line = line.strip()
self.modify_files.append(line)
def analyze(self):
for modify_file in self.modify_files:
self.test_files['ut_files'] += TestFileStrategy().identify(modify_file)
self.test_files['ut_files'] += CopyOptStrategy().identify(modify_file)
self.test_files['ut_files'] += OpStrategy().identify(modify_file)
self.test_files['ut_files'] += DirectoryMappingStrategy().identify(modify_file)
self.test_files['op_ut_files'] += OpStrategy().identify(modify_file)
self.test_files['ut_files'] += CoreTestStrategy().identify(modify_file)
unique_files = sorted(set(self.test_files['ut_files']))
exist_ut_file = [
changed_file
for changed_file in unique_files
if Path(changed_file).exists()
]
self.test_files['ut_files'] = exist_ut_file
self.exclude_test_files(slow_files=SLOW_TEST_BLOCKLIST)
def load_core_ut(self):
self.test_files['ut_files'] += [str(i) for i in (BASE_DIR / 'test/npu').rglob('test_*.py')]
def load_distributed_ut(self):
self.test_files['ut_files'] += [str(i) for i in (BASE_DIR / 'test/distributed').rglob('test_*.py')]
def load_op_plugin_ut(self):
version_path = get_test_torch_version_path()
file_hash = {}
for file_path in (BASE_DIR / 'third_party/op-plugin/test').rglob('test_*.py'):
if str(file_path.parts[-2]) in [version_path, "test_custom_ops", "test_base_ops"]:
file_name = str(file_path.name)
if file_name in file_hash:
if str(file_path.parts[-2]) == version_path:
self.test_files['ut_files'].remove(file_hash[file_name])
file_hash[file_name] = str(file_path)
self.test_files['ut_files'].append(str(file_path))
else:
file_hash[file_name] = str(file_path)
self.test_files['ut_files'].append(str(file_path))
def load_all_ut(self, include_distributed_case=False, include_op_plugin_case=False):
all_files = [str(i) for i in (BASE_DIR / 'test').rglob('test_*.py') if 'distributed' not in str(i)]
self.test_files['ut_files'] = all_files
if include_distributed_case:
self.load_distributed_ut()
if include_op_plugin_case:
if os.path.exists(BASE_DIR / 'third_party/op-plugin/test'):
self.load_op_plugin_ut()
else:
raise Exception("The path of op-plugin did not exist, check whether it had been pulled.")
def split_test_files(self, rank, world_size):
if rank > world_size:
raise Exception(f'rank {rank} is greater than world_size {world_size}')
def ordered_split(files, start, step):
return sorted(files)[start::step] if files else []
# node rank starts from 1
self.test_files['ut_files'] = ordered_split(self.test_files['ut_files'], rank - 1, world_size)
self.test_files['op_ut_files'] = ordered_split(self.test_files['op_ut_files'], rank - 1, world_size)
def exclude_test_files(self, slow_files=None, not_run_files=None, mode="slow_test"):
"""
Args:
slow_files: slow test files.
not_run_files: not_run_directly test files.
mode: "slow_test" or "not_run_directly". Default: "slow_test".
Returns:
"""
def remove_test_files(key):
block_list = not_run_files.keys() if mode == "not_run_directly" else slow_files
for test_name in block_list:
test_files_copy = self.test_files.get(key, [])[:]
for test_file in test_files_copy:
is_remove = False
if mode == "slow_test" and test_name + ".py" in test_file:
print(f'Excluding slow test: {test_name}')
is_remove = True
if mode == "not_run_directly":
# remove not run directly files
is_folder_in = not test_name.endswith(".py") and "/" + test_name + "/" in test_file
is_file_in = test_name.endswith(".py") and test_name in test_file
if is_folder_in or is_file_in:
if test_name in ["jit"] and re.search("|".join(INCLUDE_FILES), test_file):
continue
is_remove = True
# add instead file
instead_files.add(str(TEST_DIR.joinpath(not_run_files[test_name])))
if is_remove:
test_files = self.test_files.get(key, [])
if test_file in test_files:
test_files.remove(test_file)
for test_files_key in self.test_files.keys():
instead_files = set()
remove_test_files(test_files_key)
for instead_file in instead_files:
if instead_file not in self.test_files[test_files_key]:
self.test_files[test_files_key].append(instead_file)
def get_test_files(self):
return self.test_files
def print_modify_files(self):
print("modify files:")
for modify_file in self.modify_files:
print(modify_file)
def print_ut_files(self):
print("ut files:")
for ut_file in self.test_files.get('ut_files', []):
print(ut_file)
def print_op_ut_files(self):
print("op ut files:")
for op_ut_file in self.test_files.get('op_ut_files', []):
print(op_ut_file)
-149
View File
@@ -1,149 +0,0 @@
# -*- coding: UTF-8 -*-
import os
import sys
import subprocess
import threading
import queue
import argparse
from pathlib import Path
import random
import psutil
from access_control import (
TestMgr,
BASE_DIR, TEST_DIR, SLOW_TEST_BLOCKLIST, NOT_RUN_DIRECTLY, EXEC_TIMEOUT, NETWORK_OPS_DIR
)
def exec_ut(files):
"""
执行单元测试文件,其中存在失败,则标识异常并打印相关信息
"""
def get_op_name(ut_file):
op_name = str(ut_file.split('/')[-1].split('.')[0])
return op_name[5:] if op_name.startswith("test_") else op_name
def get_ut_name(ut_file):
if 'op-plugin' in str(Path(ut_file)):
return str(Path(ut_file).relative_to(NETWORK_OPS_DIR))[:-3]
return str(Path(ut_file).relative_to(TEST_DIR))[:-3]
def get_ut_cmd(ut_type, ut_file):
cmd = [sys.executable, "run_test.py", "-v"]
if ut_type == "op_ut_files":
# do not skip ops related test entries
return cmd + ["-e"] + SLOW_TEST_BLOCKLIST[1:] + ["-i", "test_ops", "--", "-k", "_" + get_op_name(ut_file)]
if 'op-plugin' in str(Path(ut_file)):
cmd = [sys.executable, NETWORK_OPS_DIR / "run_test.py", "-v"]
return cmd + ["-i", get_ut_name(ut_file)]
def wait_thread(process, event_timer):
process.wait()
event_timer.set()
def enqueue_output(out, log_queue):
for line in iter(out.readline, b''):
log_queue.put(line.decode('utf-8', errors='ignore'))
out.close()
return
def start_thread(fn, *args):
stdout_t = threading.Thread(target=fn, args=args)
stdout_t.daemon = True
stdout_t.start()
def print_subprocess_log(log_queue):
while not log_queue.empty():
print((log_queue.get()).strip())
def run_cmd_with_timeout(cmd):
os.chdir(str(TEST_DIR))
stdout_queue = queue.Queue()
event_timer = threading.Event()
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
start_thread(wait_thread, p, event_timer)
start_thread(enqueue_output, p.stdout, stdout_queue)
try:
event_timer.wait(EXEC_TIMEOUT)
ret = p.poll()
if ret:
print_subprocess_log(stdout_queue)
if not event_timer.is_set():
ret = 1
parent_process = psutil.Process(p.pid)
for children_process in parent_process.children(recursive=True):
children_process.kill()
p.kill()
p.terminate()
print("Timeout: Command '{}' timed out after {} seconds".format(" ".join(cmd), EXEC_TIMEOUT))
print_subprocess_log(stdout_queue)
except Exception as err:
ret = 1
print(err)
return ret
def run_tests(test_files):
test_infos = []
has_failed = 0
init_method = random.randint(1, 2)
for ut_type, ut_files in test_files.items():
for ut_file in ut_files:
cmd = get_ut_cmd(ut_type, ut_file)
ut_info = str(cmd[-1])
if ut_type == "op_ut_files":
ut_info = "test_ops " + ut_info
else:
cmd = cmd if 'op-plugin' in str(Path(ut_file)) else cmd + ["--init_method={}".format(init_method)]
ret = run_cmd_with_timeout(cmd)
if ret:
has_failed = ret
test_infos.append("exec ut {} failed.".format(ut_info))
else:
test_infos.append("exec ut {} success.".format(ut_info))
init_method = 2 if init_method == 1 else 1
return has_failed, test_infos
ret_status, exec_infos = run_tests(files)
print("***** Total result:")
for exec_info in exec_infos:
print(exec_info)
return ret_status
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Control needed ut cases')
parser.add_argument('--all', action="store_true", help='Run all testcases')
parser.add_argument('--distributed', action="store_true", help='Run distributed testcases')
parser.add_argument('--rank', default=0, type=int, help='Index of current ut nodes')
parser.add_argument('--world_size', default=0, type=int, help='Number of ut nodes')
parser.add_argument('--network_ops', action="store_true", help='Run network_ops testcases in the op-plugin repo')
options = parser.parse_args()
print(f"options: {options}")
cur_modify_files = str(BASE_DIR / 'modify_files.txt')
test_mgr = TestMgr()
if options.all:
test_mgr.load_all_ut(options.distributed, options.network_ops)
elif options.distributed:
test_mgr.load_distributed_ut()
elif os.path.exists(cur_modify_files):
test_mgr.load(cur_modify_files, world_size=options.world_size)
test_mgr.analyze()
else:
test_mgr.load_core_ut()
test_mgr.exclude_test_files(not_run_files=NOT_RUN_DIRECTLY, mode="not_run_directly")
if options.rank > 0 and options.world_size > 0:
test_mgr.split_test_files(options.rank, options.world_size)
cur_test_files = test_mgr.get_test_files()
test_mgr.print_modify_files()
test_mgr.print_ut_files()
test_mgr.print_op_ut_files()
ret_ut = exec_ut(cur_test_files)
sys.exit(ret_ut)
-114
View File
@@ -1,114 +0,0 @@
#!/bin/bash
set -e
CUR_DIR=$(dirname $(readlink -f $0))
SUPPORTED_PY_VERSION=(3.8 3.9 3.10 3.11)
PY_VERSION='3.8' # Default supported python version is 3.8
# Parse arguments inside script
function parse_script_args() {
local args_num=0
if [[ "x${1}" = "x" ]]; then
# default: bash build.sh (python3.8)
return 0
fi
args_num=$#
while true; do
case "${1}" in
--python=*)
PY_VERSION=$(echo "${1}"|cut -d"=" -f2)
args_num=$((args_num-1))
shift
;;
--disable_torchair)
export DISABLE_INSTALL_TORCHAIR=TRUE
args_num=$((args_num-1))
shift
;;
--disable_rpc)
export DISABLE_RPC_FRAMEWORK=TRUE
args_num=$((args_num-1))
shift
;;
--enable_lto)
export ENABLE_LTO=TRUE
args_num=$((args_num-1))
shift
;;
--enable_pgo=*)
pgo_mode=$(echo "${1}"|cut -d"=" -f2)
case $pgo_mode in
1)
export PGO_MODE=1
args_num=$((args_num-1))
;;
2)
export PGO_MODE=2
args_num=$((args_num-1))
;;
*)
echo "ERROR Unsupported parameters: ${1}"
return 1
;;
esac
shift
;;
-*)
echo "ERROR Unsupported parameters: ${1}"
return 1
;;
*)
if [ "x${1}" != "x" ]; then
echo "ERROR Unsupported parameters: ${1}"
return 1
fi
break
;;
esac
done
# if some "--param=value" are not parsed correctly, throw an error.
if [[ ${args_num} -ne 0 ]]; then
return 1
fi
}
function check_python_version() {
matched_py_version='false'
for ver in ${SUPPORTED_PY_VERSION[*]}; do
if [ "${PY_VERSION}" = "${ver}" ]; then
matched_py_version='true'
return 0
fi
done
if [ "${matched_py_version}" = 'false' ]; then
echo "${PY_VERSION} is an unsupported python version, we suggest ${SUPPORTED_PY_VERSION[*]}"
exit 1
fi
}
function main()
{
if ! parse_script_args "$@"; then
echo "Failed to parse script args. Please check your inputs."
exit 1
fi
check_python_version
cd ${CUR_DIR}/..
# if you add or delete file/files in the project, you need to remove the following comment
# make clean
python"${PY_VERSION}" setup.py build bdist_wheel
if [ $? != 0 ]; then
echo "Failed to compile the wheel file. Please check the source code by yourself."
exit 1
fi
exit 0
}
main "$@"
-54
View File
@@ -1,54 +0,0 @@
FROM quay.io/pypa/manylinux2014_aarch64:2023-10-07-c1e05d1
# Set pip
RUN cd /usr/local/bin \
&& ln -s /opt/_internal/cpython-3.7.17/bin/pip3.7 pip3.7 \
&& ln -s /opt/_internal/cpython-3.8.18/bin/pip3.8 pip3.8 \
&& ln -s /opt/_internal/cpython-3.9.18/bin/pip3.9 pip3.9 \
&& ln -s /opt/_internal/cpython-3.10.13/bin/pip3.10 pip3.10 \
&& ln -s /opt/_internal/cpython-3.11.6/bin/pip3.11 pip3.11 \
&& ln -s python3.8 python3
# Set pip source
RUN mkdir /root/.pip \
&& echo "[global]" > /root/.pip/pip.conf \
&& echo "index-url=https://mirrors.huaweicloud.com/repository/pypi/simple" >> /root/.pip/pip.conf \
&& echo "trusted-host=repo.huaweicloud.com" >> /root/.pip/pip.conf \
&& echo "timeout=120" >> /root/.pip/pip.conf
ARG CONFIG_FOR_LCOV=0
RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
mkdir -p /etc/yum.repos.d/backup && \
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ && \
curl -o /etc/yum.repos.d/Centos7-aliyun.repo https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo -k && \
yum clean all && \
yum makecache; \
fi
RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
yum install -y perl-Module-Load-Conditional && \
yum install -y perl-Digest-MD5 && \
yum install -y "perl(DateTime)" && \
yum install -y perl-CPAN*; \
fi
# Install pip package(build)
RUN pip3.8 install pyyaml \
&& pip3.8 install torch==2.1.0 \
&& pip3.8 install numpy==1.21.3
RUN pip3.9 install pyyaml \
&& pip3.9 install torch==2.1.0 \
&& pip3.9 install numpy==1.21.3
RUN pip3.10 install pyyaml \
&& pip3.10 install torch==2.1.0 \
&& pip3.10 install numpy==1.21.3
RUN pip3.11 install pyyaml \
&& pip3.11 install torch==2.1.0 \
&& pip3.11 install numpy==1.23.2
WORKDIR /home
-37
View File
@@ -1,37 +0,0 @@
## Ascend Pytorch Dockerfile Repository
This folder hosts the `Dockerfile` to build docker images with various platforms.
### Build torch_npu from Docker container
**Clone torch-npu**
```Shell
git clone https://gitcode.com/ascend/pytorch.git --depth 1
```
**Build docker image**
```Shell
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
docker build -t manylinux-builder:v1 .
```
If you want to configure the environment of LCOV, please build docker image like this:
```Shell
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
docker build -t manylinux-builder:v1 --build-arg CONFIG_FOR_LCOV=1 .
```
**Enter docker Container**
```Shell
docker run -it -v /{code_path}/pytorch:/home/pytorch manylinux-builder:v1 bash
# {code_path} is the torch_npu source code path
```
**Compile torch_npu**
Take Python 3.8 as an example
```Shell
cd /home/pytorch
bash ci/build.sh --python=3.8
```
-60
View File
@@ -1,60 +0,0 @@
FROM pytorch/manylinux-builder:cpu-2.1
# Install python
RUN cd /usr/local/bin \
&& ln -s /opt/_internal/cpython-3.7.5/bin/pip3.7 pip3.7 \
&& ln -s /opt/_internal/cpython-3.8.1/bin/pip3.8 pip3.8 \
&& ln -s /opt/_internal/cpython-3.9.0/bin/pip3.9 pip3.9 \
&& ln -s /opt/_internal/cpython-3.10.1/bin/pip3.10 pip3.10 \
&& ln -s /opt/_internal/cpython-3.11.0/bin/pip3.11 pip3.11 \
&& ln -s /opt/_internal/cpython-3.7.5/bin/python3.7 python3.7 \
&& ln -s /opt/_internal/cpython-3.8.1/bin/python3.8 python3.8 \
&& ln -s /opt/_internal/cpython-3.9.0/bin/python3.9 python3.9 \
&& ln -s /opt/_internal/cpython-3.10.1/bin/python3.10 python3.10 \
&& ln -s /opt/_internal/cpython-3.11.0/bin/python3.11 python3.11 \
&& ln -s python3.8 python3
# Set pip source
RUN mkdir /root/.pip \
&& echo "[global]" > /root/.pip/pip.conf \
&& echo "index-url=https://mirrors.huaweicloud.com/repository/pypi/simple" >> /root/.pip/pip.conf \
&& echo "trusted-host=repo.huaweicloud.com" >> /root/.pip/pip.conf \
&& echo "timeout=120" >> /root/.pip/pip.conf
ARG CONFIG_FOR_LCOV=0
RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
mkdir -p /etc/yum.repos.d/backup && \
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ && \
curl -o /etc/yum.repos.d/Centos7-aliyun.repo https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo -k && \
yum clean all && \
yum makecache; \
fi
RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
yum install -y perl-Module-Load-Conditional && \
yum install -y perl-Digest-MD5 && \
yum install -y "perl(DateTime)" && \
yum install -y perl-CPAN*; \
fi
# Install pip package(build)
RUN pip3.8 install pyyaml \
&& pip3.8 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.8 install numpy==1.21.3
RUN pip3.9 install pyyaml \
&& pip3.9 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.9 install numpy==1.21.3
RUN pip3.10 install pyyaml \
&& pip3.10 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.10 install numpy==1.21.3
RUN pip3.11 install pyyaml \
&& pip3.11 install torch==2.1.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.11 install numpy==1.23.2
WORKDIR /home
-33
View File
@@ -1,33 +0,0 @@
#!/bin/bash
py_execute=${1-python3}
CUR_DIR=$(dirname $(readlink -f $0))
cd ${CUR_DIR}/../examples/libtorch_resnet
if [ -f ./resnet_model.pt ]; then
rm ./resnet_model.pt
fi
$py_execute 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=`$py_execute -c 'import torch;print(torch.utils.cmake_prefix_path)'` .. && \
make && ./libtorch_resnet ../resnet_model.pt > out.log
if grep -q "resnet_model run success!" out.log; then
echo "Success."
exit 0
else
echo "Failed."
exit 1
fi
-31
View File
@@ -1,31 +0,0 @@
include(FindPackageHandleStandardArgs)
if(DEFINED ENV{TORCH_NPU_INSTALL_PREFIX})
set(TORCH_NPU_INSTALL_PREFIX $ENV{TORCH_NPU_INSTALL_PREFIX})
else()
# Assume we are in <install-prefix>/share/cmake/Torch_npu/Torch_npuConfig.cmake
get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
get_filename_component(TORCH_NPU_INSTALL_PREFIX "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)
endif()
# Include directories.
if(EXISTS "${TORCH_NPU_INSTALL_PREFIX}/include")
set(TORCH_NPU_INCLUDE_DIRS
${TORCH_NPU_INSTALL_PREFIX}/include)
else()
set(TORCH_NPU_INCLUDE_DIRS
${TORCH_NPU_INSTALL_PREFIX}/include)
endif()
# Library dependencies.
find_library(TORCH_NPU_LIBRARY torch_npu PATHS "${TORCH_NPU_INSTALL_PREFIX}/lib")
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
set(TORCH_NPU_CXX_FALGS "-D_GLIBCXX_USE_CXX11_ABI=@GLIBCXX_USE_CXX11_ABI@")
endif()
include_directories(${TORCH_NPU_INCLUDE_DIRS})
set(TORCH_NPU_LIBRARIES ${TORCH_NPU_LIBRARY})
find_package_handle_standard_args(Torch_npu DEFAULT_MSG TORCH_NPU_LIBRARY TORCH_NPU_INCLUDE_DIRS)
-27
View File
@@ -1,27 +0,0 @@
import os
import stat
import torchgen.gen
from codegen.utils import PathManager
def _write_if_changed_security(self, filename: str, contents: str) -> None:
old_contents: Optional[str]
filepath = os.path.realpath(filename)
try:
with open(filepath, 'r') as f:
old_contents = f.read()
except IOError:
old_contents = None
if contents != old_contents:
PathManager.remove_path_safety(filepath)
with os.fdopen(os.open(filepath, os.O_RDWR | os.O_CREAT, stat.S_IWUSR | stat.S_IRUSR), "w") as f:
f.write(contents)
os.chmod(filepath, stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)
def apply_codegen_patches():
torchgen.gen.FileManager._write_if_changed = _write_if_changed_security
apply_codegen_patches()
-47
View File
@@ -1,47 +0,0 @@
import re
from typing import List, Dict
import torchgen.gen
from torchgen.code_template import CodeTemplate
from torchgen.api.autograd import NativeFunctionWithDifferentiabilityInfo, DifferentiabilityInfo
from torchgen.packaged.autograd.gen_inplace_or_view_type import gen_inplace_or_view_type_env
from torchgen.packaged.autograd.gen_autograd_functions import process_function
from codegen.gen_backend_stubs import parse_native_and_custom_yaml
from codegen.utils import CUSTOM_YAML_NAME
def parse_native_and_custom_yaml_(*args, **kwargs):
return parse_native_and_custom_yaml(*args, **kwargs, custom_path=f'./torch_npu/csrc/aten/{CUSTOM_YAML_NAME}')
def gen_inplace_or_view_type_env_for_npu(
fn: NativeFunctionWithDifferentiabilityInfo,
) -> Dict[str, List[str]]:
gen_code = gen_inplace_or_view_type_env(fn)
if len(gen_code['inplace_or_view_method_definitions']):
gen_code['ops_headers'] = []
method_definitions = re.sub(pattern=r"at::_ops::(\w+)::redispatch",
repl=r'at_npu::redispatch::\1',
string=gen_code['inplace_or_view_method_definitions'][0])
gen_code['inplace_or_view_method_definitions'] = [method_definitions]
return gen_code
# A temporary solution, due to op coupling, temporarily removing symint
def process_function_(info: DifferentiabilityInfo, template: CodeTemplate) -> str:
function_codegen = process_function(info, template)
if '_symint' in function_codegen:
function_codegen = function_codegen.replace('_symint', '')
return function_codegen
def apply_autograd_patches():
torchgen.gen.parse_native_yaml = parse_native_and_custom_yaml_
torchgen.packaged.autograd.gen_inplace_or_view_type.gen_inplace_or_view_type_env = \
gen_inplace_or_view_type_env_for_npu
torchgen.packaged.autograd.gen_autograd_functions.process_function = process_function_
apply_autograd_patches()
-93
View File
@@ -1,93 +0,0 @@
"""
To run this file by hand from the root of the PyTorch
repository, run:
python -m codegen.autograd.gen_autograd \
--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_variable_type.py: generates VariableType.h which contains all tensor methods
import argparse
import os
from torchgen.packaged.autograd.gen_inplace_or_view_type import gen_inplace_or_view_type
from torchgen.packaged.autograd.gen_autograd_functions import gen_autograd_functions_lib
from codegen.utils import get_torchgen_dir, gen_custom_yaml_path
from .gen_variable_type import (
gen_variable_type, gen_variable_type_head
)
from .gen_variable_factories import gen_variable_factories
from .gen_autograd_functions import gen_autograd_functions_python
from .utils import parse_derivatives, filt_npu_autograd_functions
def gen_autograd(
native_functions_path: str,
tags_path: str,
out: str,
autograd_dir: str,
npu_native_functions_path: str
) -> None:
npu_native_functions_path = gen_custom_yaml_path(npu_native_functions_path)
differentiability_infos, native_funcs, funcs_with_diff_infos =\
parse_derivatives(native_functions_path, tags_path, autograd_dir, npu_native_functions_path)
npu_funcs_with_diff_infos, _ = filt_npu_autograd_functions(native_functions_path, funcs_with_diff_infos)
template_path = os.path.join(autograd_dir, 'templates')
torch_template_path = os.path.join(get_torchgen_dir(), 'packaged/autograd/templates')
# Generate VariableType.cpp
gen_variable_type(out, funcs_with_diff_infos, template_path)
# Generate VariableType.h
gen_variable_type_head(out, funcs_with_diff_infos, template_path)
# Generate ADInplaceOrViewType.cpp
gen_inplace_or_view_type(out, native_functions_path, tags_path, npu_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, torch_template_path, native_funcs)
# Generate python_functions.h/cpp
gen_autograd_functions_python(out, differentiability_infos, template_path)
def main() -> None:
parser = argparse.ArgumentParser(
description='Generate autograd C++ files script')
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()
torchgen_path = get_torchgen_dir()
tags_yaml_path = os.path.join(torchgen_path, 'packaged/ATen/native/tags.yaml')
native_yaml_path = os.path.join(torchgen_path, 'packaged/ATen/native/native_functions.yaml')
gen_autograd(native_yaml_path,
tags_yaml_path,
args.out_dir,
args.autograd_dir,
args.npu_native_function_dir)
if __name__ == '__main__':
main()
@@ -1,63 +0,0 @@
# Generates C++ autograd functions for the derivatives of ATen operations
#
# This writes two files:
# python_functions.h/cpp: Python bindings for subclasses of autograd::Node
from typing import Dict
from torchgen.api.autograd import DifferentiabilityInfo
from torchgen.model import FunctionSchema
from torchgen.utils import FileManager
from torchgen.gen import FileManager
from torchgen.packaged.autograd.gen_autograd_functions import (
process_function,
get_infos_with_derivatives_list,
PY_FUNCTION_DEFINITION,
PY_FUNCTION_PROPS_AND_GETTERS
)
def gen_autograd_functions_python(
out: str,
differentiability_infos: Dict[FunctionSchema, Dict[str, DifferentiabilityInfo]],
template_path: str,
) -> None:
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
num_shards = 2
fm.write(
"python_functions.h",
lambda: {
"generated_comment":
f"@ generated from {fm.template_dir_for_comments()}/python_functions.h",
"shard_forward_declare": [
f"void initialize_autogenerated_functions_{i}(PyObject* module);"
for i in range(num_shards)
],
"shard_call": [
f"initialize_autogenerated_functions_{i}(module);"
for i in range(num_shards)
],
},
)
# get a 1D list of diffinfos, we do not need them to be per FunctionSchema/DispatchKey here
# infos with the diff dispatchkeys but the same name will still be in the same shard.
infos = get_infos_with_derivatives_list(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_for_comments()}/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"},
)
@@ -1,27 +0,0 @@
# Generates C++ functions that wrap ATen tensor factory methods to turn them into Variables.
#
# This writes one file: variable_factories.h
from torchgen.gen import FileManager
from torchgen.utils import mapMaybe
from torchgen.packaged.autograd.gen_variable_factories import (
process_function,
is_factory_function,
)
from .utils import NPU_AUTOGRAD_FUNCTION
def gen_variable_factories(
out: str,
template_path: str,
native_functions: list
) -> None:
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(mapMaybe(process_function, factory_functions)),
})
-137
View File
@@ -1,137 +0,0 @@
# Generates VariableType.h/cpp
#
#If you need any guidance, please refer to the comments in derivatives.yaml in PyTorch.
#
import re
from typing import List
from torchgen.api.autograd import NativeFunctionWithDifferentiabilityInfo
from torchgen.api import cpp
from torchgen.code_template import CodeTemplate
from torchgen.context import native_function_manager
from torchgen.gen import FileManager
from torchgen.packaged.autograd.gen_inplace_or_view_type import (
use_derived, METHOD_DEFINITION, gen_formals,
)
from torchgen.packaged.autograd.gen_trace_type import type_wrapper_name
from torchgen.packaged.autograd.gen_variable_type import (
emit_body, gen_wrapper_registration, GRADIENT_IMPLEMENTED_FOR_COMPLEX
)
from .utils import NPU_AUTOGRAD_FUNCTION
GRADIENT_IMPLEMENTED_FOR_COMPLEX.update((
"stft",
"npu_dtype_cast",
"_npu_dtype_cast",
))
NPU_NATIVEFUNCTIONS = {'npu_format_cast', '_npu_format_cast'}
try_jit_decomposition_pattern = (r'if \(\(.*?\)\) \{.*?static c10::OperatorName full_name\("aten::.*?", .*?\);\n.*?'
r'return impl::run_jit_decomposition_with_args_for_jvp<.*?>'
r'\(".*?", \*opt_op, ks, .*?\);\n\s*\} '
r'else \{\n\s*(.*?)\n\s*\}')
use_count_pattern = (r'if \(\S+\.has_storage\(\) && !at::impl::dispatch_mode_enabled\(\) && '
r'!at::impl::tensor_has_dispatch\(\S+\)\) {\s+TORCH_INTERNAL_ASSERT\('
r'\S+\.storage\(\)\.use_count\(\) == 1, "function: \S+"\);\s+}')
METHOD_HEADER_DEFINITION = CodeTemplate("""\
${return_type} ${type_wrapper_name}(${formals});
""")
def gen_variable_type(
out: str,
fns_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo],
template_path: str,
) -> None:
"""Generate VariableType.cpp body
Generate variable type definition for torch and npu method here.
"""
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
fm.write_sharded(
'VariableType.cpp',
[fn for fn in fns_with_diff_infos if use_derived(fn)],
key_fn=lambda fn: cpp.name(fn.func.func),
base_env={
'generated_comment':
"@" f'generated from {template_path}/VariableType.cpp',
},
env_callable=gen_variable_type_func,
num_shards=1,
sharded_keys={'type_derived_method_definitions', 'wrapper_registrations_aten', 'wrapper_registrations_npu'}
)
def gen_variable_type_head(
out: str,
fns_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo],
template_path: str,
) -> None:
"""Generate VariableType.h body
"""
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
fm.write_with_template('VariableType.h', 'VariableType.h', lambda: {
'generated_comment': "@" f'generated from {template_path}/VariableType.h',
'npu_variable_type': gen_variable_type_header(fns_with_diff_infos)
})
def gen_variable_type_header(
fns_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo]
) -> List[str]:
variable_type_header: List[str] = []
for fn in fns_with_diff_infos:
f = fn.func
with native_function_manager(f):
formals = gen_formals(f)
wrapper_name = type_wrapper_name(f)
name = str(fn.func.func.name)
if name in NPU_AUTOGRAD_FUNCTION:
type_header_definition = METHOD_HEADER_DEFINITION.substitute(
return_type=cpp.returns_type(f.func.returns).cpp_type(),
type_wrapper_name=wrapper_name,
formals=formals,
)
variable_type_header.append(type_header_definition)
return variable_type_header
def gen_variable_type_func(
fn: NativeFunctionWithDifferentiabilityInfo
) -> str:
f = fn.func
result = {}
with native_function_manager(f):
formals = gen_formals(f)
type_definition = METHOD_DEFINITION.substitute(
return_type=cpp.returns_type(f.func.returns).cpp_type(),
type_wrapper_name=type_wrapper_name(f),
type_definition_body=emit_body(fn, "Default"),
formals=formals,
)
type_definition = re.sub(try_jit_decomposition_pattern, r"\1", type_definition, flags=re.DOTALL)
type_definition = re.sub(use_count_pattern, "", type_definition, flags=re.DOTALL)
if str(f.func.name) in NPU_AUTOGRAD_FUNCTION:
if f.func.is_out_fn():
type_definition = re.sub(r'at::redispatch::(\w+)_outf', r'at_npu::redispatch::\1_out', type_definition)
else:
type_definition = type_definition.replace('at::redispatch', 'at_npu::redispatch')
type_definition = type_definition.replace('_symint', '')
wrapper_registration = gen_wrapper_registration(f, "Default")
result[f"type_derived_method_definitions"] = [type_definition]
if str(f.func.name) in NPU_AUTOGRAD_FUNCTION:
result[f"wrapper_registrations_aten"] = []
result[f"wrapper_registrations_npu"] = [wrapper_registration]
else:
result[f"wrapper_registrations_aten"] = [wrapper_registration]
result[f"wrapper_registrations_npu"] = []
return result
@@ -1,31 +0,0 @@
#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
#include "torch/csrc/autograd/VariableTypeUtils.h"
#include <torch/library.h>
#include "torch_npu/csrc/aten/CustomRedispatch.h"
// ${generated_comment}
$ops_headers
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(npu, ADInplaceOrView, m) {
${inplace_or_view_wrapper_registrations};
}
} // namespace
} // namespace at_npu
-24
View File
@@ -1,24 +0,0 @@
#include <torch/csrc/dynamo/compiled_autograd.h>
#include "torch_npu/csrc/framework/autograd/FunctionsManual.h"
#include "torch_npu/csrc/aten/CustomFunctions.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 namespace at_npu::native::custom_ops;
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
-67
View File
@@ -1,67 +0,0 @@
#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>
#include <c10/core/SymIntArrayRef.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, std::shared_ptr<Node> saved_for = nullptr)
{
// 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, [&saved_for](const SavedVariable& x) {
return static_cast<Tensor>(x.unpack(saved_for));
});
}
inline c10::List<c10::optional<Tensor>> unpack_opt_list(at::ArrayRef<SavedVariable> xs, std::shared_ptr<Node> saved_for = nullptr)
{
torch::List<c10::optional<Tensor>> result;
result.reserve(xs.size());
for (const SavedVariable& v : xs) {
auto var = v.unpack(saved_for);
result.push_back(var.defined() ? c10::optional<Tensor>(var) : c10::nullopt);
}
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
@@ -1,69 +0,0 @@
#include <torch/csrc/autograd/VariableTypeUtils.h>
#include <c10/core/impl/TorchDispatchModeTLS.h>
#include <ATen/core/TorchDispatchUtils.h>
#include <ATen/SparseCsrTensorUtils.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"
#include "torch_npu/csrc/aten/CustomRedispatch.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();
}
}
}
${type_derived_method_definitions}
} // namespace VariableType
namespace {
TORCH_LIBRARY_IMPL(aten, AutogradPrivateUse1, m) {
${wrapper_registrations_aten}
}
TORCH_LIBRARY_IMPL(npu, AutogradPrivateUse1, m) {
${wrapper_registrations_npu}
}
}
}} // namespace at_npu::autograd
-58
View File
@@ -1,58 +0,0 @@
#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
@@ -1,46 +0,0 @@
#ifndef BUILD_LIBTORCH
#include <torch/csrc/autograd/generated/python_functions.h>
// ${generated_comment}
#include <Python.h>
#include <ATen/ATen.h>
#include <c10/core/SymNodeImpl.h>
#include <torch/csrc/autograd/generated/Functions.h>
#include <torch/csrc/autograd/python_cpp_function.h>
#include <torch/csrc/autograd/python_variable.h>
#include <torch/csrc/autograd/saved_variable.h>
#include <torch/csrc/utils/pybind.h>
#include <pybind11/pybind11.h>
#include <torch/csrc/utils/pybind.h>
#include "torch_npu/csrc/aten/Functions.h"
// NOTE: See [Sharded File] comment in VariableType
namespace at_npu {
namespace autograd {
namespace generated {
template <typename C>
static void addClass(PyObject *module, PyTypeObject &type, const char *name,
PyGetSetDef *function_properties = NULL,
PyMethodDef *function_methods = NULL)
{
_initFunctionPyTypeObject(type, name, function_properties, function_methods);
Py_INCREF(&type);
PyModule_AddObject(module, name, (PyObject *)&type);
registerCppFunction(typeid(C), &type);
}
${py_function_props_and_getters}
void initialize_autogenerated_functions${shard_id}(PyObject *module)
{
${py_function_initializers}
}
}
}
} // namespace at_npu::autograd::generated
#endif
@@ -1,24 +0,0 @@
#ifndef BUILD_LIBTORCH
#pragma once
#include <Python.h>
// ${generated_comment}
// Python bindings for automatically generated autograd functions
namespace at_npu {
namespace autograd {
namespace generated {
${shard_forward_declare}
inline void initialize_autogenerated_functions(PyObject *module)
{
${shard_call}
}
}
}
} // namespace at_npu::autograd::generated
#endif
-92
View File
@@ -1,92 +0,0 @@
from pathlib import Path
from typing import List, Dict
import yaml
import torch
from torchgen.model import NativeFunction, FunctionSchema
from torchgen.api.autograd import (
match_differentiability_info, NativeFunctionWithDifferentiabilityInfo,
DifferentiabilityInfo
)
from torchgen.packaged.autograd.load_derivatives import load_derivatives
from codegen.utils import get_torchgen_dir, CUSTOM_YAML_NAME, PathManager
from codegen.gen_backend_stubs import parse_native_and_custom_yaml
AUTOGRAD_BLACK_LIST = {'npu_format_cast.Tensor', 'npu_format_cast_', 'npu_format_cast_.acl_format'}
VERSION_PART = torch.__version__.split('.')
def parse_derivatives(
native_functions_path: str,
tags_path: str,
autograd_dir: str,
npu_native_functions_path: str
):
derivatives_path = str(Path(autograd_dir).parents[1].joinpath(
f'third_party/op-plugin/op_plugin/config/v{VERSION_PART[0]}r{VERSION_PART[1]}/derivatives.yaml'
))
differentiability_infos, _ = load_derivatives(
derivatives_path, native_functions_path, tags_path)
native_funcs = parse_native_and_custom_yaml(native_functions_path,
tags_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)
filt_funcs_with_diff_infos = [f for f in funcs_with_diff_infos if str(f.func.func.name) not in AUTOGRAD_BLACK_LIST]
return (differentiability_infos, native_funcs, filt_funcs_with_diff_infos)
def filt_npu_autograd_functions(
native_functions_path: str,
funcs_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo]
):
npu_funcs_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo] = []
torch_functions = set()
PathManager.check_directory_path_readable(native_functions_path)
with open(native_functions_path, 'r') as f:
es = yaml.safe_load(f)
for e in es:
torch_functions.add(e.get('func').split('(')[0])
npu_autograd_functions = set()
for f in funcs_with_diff_infos:
name = str(f.func.func.name)
# f.info is differentiabilityinfo. Existence of variants ops with a differentiabilityinfo of none.
if f.info and name not in torch_functions:
npu_funcs_with_diff_infos.append(f)
npu_autograd_functions.add(name)
return npu_funcs_with_diff_infos, npu_autograd_functions
def filte_out_native_autograd_function(
native_funcs: List[NativeFunction],
differentiability_infos: Dict[FunctionSchema, Dict[str, DifferentiabilityInfo]],
):
result: List[NativeFunction] = []
derivatives_name_list: List[str] = []
for diffinfo_dict in differentiability_infos.values():
for info in diffinfo_dict.values():
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
NPU_AUTOGRAD_FUNCTION = filt_npu_autograd_functions(
str(Path(get_torchgen_dir()).joinpath('packaged/ATen/native/native_functions.yaml')),
parse_derivatives(
str(Path(get_torchgen_dir()).joinpath('packaged/ATen/native/native_functions.yaml')),
str(Path(get_torchgen_dir()).joinpath('packaged/ATen/native/tags.yaml')),
str(Path(__file__).parent),
str(Path(__file__).parents[2].joinpath(f'torch_npu/csrc/aten/{CUSTOM_YAML_NAME}')))[-1]
)[-1]
-106
View File
@@ -1,106 +0,0 @@
"""
This file is mainly used to transform failed test names into DecorateInfo Object.
"""
from pathlib import Path
import os
import yaml
from torchgen.code_template import CodeTemplate
from torchgen.gen import FileManager
from codegen.autograd.utils import VERSION_PART
from codegen.utils import PathManager
project_path = Path(os.path.dirname(__file__)).parent
op_plugin_info_path = os.path.realpath(os.path.join(
project_path,
f'third_party/op-plugin/test/test_v{VERSION_PART[0]}r{VERSION_PART[1]}_ops',
"unsupported_ops_info.yaml"))
torch_npu_info_path = os.path.realpath(os.path.join(project_path, "test", "unsupported_ops_info.yaml"))
unsupported_dict_path = op_plugin_info_path if os.path.exists(op_plugin_info_path) else torch_npu_info_path
PathManager.check_directory_path_readable(unsupported_dict_path)
with open(unsupported_dict_path, "r") as f:
unsupported_summary_dict = yaml.safe_load(f)
skip_list = dict()
#class2test is a mapping from test class to test names. As is shown in test_ops.py.
class2test = {
"TestCommon":[
"test_compare_cpu",
"test_dtypes",
"test_errors",
"test_multiple_devices",
"test_non_standard_bool_values",
"test_noncontiguous_samples",
"test_numpy_ref",
"test_out",
"test_out_integral_dtype",
"test_out_warning",
"test_pointwise_tag_coverage",
"test_variant_consistency_eager",
"test_complex_half_reference_testing"
],
"TestCompositeCompliance":[
"test_backward",
"test_forward_ad",
"test_operator",
],
"TestMathBits":[
"test_conj_view",
"test_neg_conj_view",
"test_neg_view",
],
"TestFakeTensor":[
"test_fake",
"test_fake_autocast",
"test_fake_crossref_backward_amp",
"test_fake_crossref_backward_no_amp",
"test_pointwise_ops",
],
"TestTags":["test_tags"]
}
def get_class_name(func_name):
for key, value in class2test.items():
if func_name in value:
return key
raise RuntimeError("Can't find corresponding class name of test: {}".format(func_name))
#There are two kinds of templates. One is with Dtype Info, the other is without.
def update_skip_list(class_name, op_name, func_name, dtype):
skip_reason = "npu test skipped!"
template = f"""\nDecorateInfo(unittest.skip("{skip_reason}"), \'{class_name}\', \'{func_name}\', dtypes=(torch.{dtype},))"""
template_ = f"""\nDecorateInfo(unittest.skip("{skip_reason}"), \'{class_name}\', \'{func_name}\')"""
if dtype:
if op_name not in skip_list:
skip_list[op_name] = [template]
else:
skip_list[op_name].append(template)
else:
if op_name not in skip_list:
skip_list[op_name] = [template_]
else:
skip_list[op_name].append(template_)
def gen_ops_info(summary_dict):
for op_name in summary_dict:
for func_name in summary_dict[op_name]:
for dtype in summary_dict[op_name][func_name]:
update_skip_list(get_class_name(func_name), op_name, func_name, dtype)
skip_template = CodeTemplate(
"""\n'${op_name}': [${decorators}]"""
)
fm = FileManager(os.path.join("torch_npu", "testing"), os.path.join("codegen", "templates"), False)
fm.write_with_template(f"_npu_testing_utils.py", "npu_testing_utils.py", lambda:{
"skip_detail": [skip_template.substitute(op_name=op, decorators=doc) for op, doc in skip_list.items()]
})
if __name__ == "__main__":
gen_ops_info(unsupported_summary_dict)
-346
View File
@@ -1,346 +0,0 @@
import re
import itertools
from collections import namedtuple, defaultdict
from typing import List, Dict, Sequence
import yaml
from torchgen.code_template import CodeTemplate
from torchgen.gen import (parse_tags_yaml, FileManager, cpp_string, error_check_native_functions)
from torchgen.model import (BackendIndex, DispatchKey, Variant,
NativeFunction, OperatorName, BackendMetadata, TensorOptionsArguments, OptionalType)
from torchgen.utils import concatMap
from torchgen.context import with_native_function, native_function_manager, with_native_function_and_index
from torchgen.api.types import DispatcherSignature
from torchgen.api import cpp
from torchgen.dest.register_dispatch_key import RegisterDispatchKey
from codegen.utils import (enable_opplugin, is_op_valid, field_tag, get_opplugin_wrap_name, parse_npu_yaml,
gen_op_hook_post_code)
# Parse native_functions.yaml into a sequence of NativeFunctions and Backend Indices.
ParsedYaml = namedtuple('ParsedYaml', ['native_functions', 'backend_indices'])
CUSTOM_FUNCTIONS_DECLARATION = CodeTemplate("""\
${return_type} ${func_name}(${args_str});
""")
CUSTOM_FUNCTIONS_DEFINITION = CodeTemplate("""\
${return_type} ${func_name}(${args_str}) {
static auto op = c10::Dispatcher::singleton().findSchemaOrThrow("npu::${base_name}", "${overload}").typed<${schema}>();
return op.${func_type}(${args_exprs_str});
}
""")
SKIP_PYTHON_BINDINGS_SIGNATURES = []
@with_native_function
def should_generate_ops_patch(f: NativeFunction) -> bool:
func_signature = str(f.func)
for pattern in SKIP_PYTHON_BINDINGS_SIGNATURES:
if pattern == func_signature:
return False
return True
def parse_custom_yaml(custom_path: str, tag_path: str) -> ParsedYaml:
valid_tags = parse_tags_yaml(tag_path)
rs: List[NativeFunction] = []
bs: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = defaultdict(dict)
# Filter the custom native yaml file, and extract the functions we defined.
source_es = parse_npu_yaml(custom_path)
custom_es = source_es.get('custom', []) + source_es.get('custom_autograd', [])
custom_es = field_tag(custom_es)
for e_with_vars in custom_es:
func, m = NativeFunction.from_yaml(e_with_vars, "Location", valid_tags)
func.variants.discard(Variant.method)
rs.append(func)
BackendIndex.grow_index(bs, m)
error_check_native_functions(rs)
# Default dict is to prevent the codegen from barfing when we have a dispatch key that has no kernels yet.
indices: Dict[DispatchKey, BackendIndex] = defaultdict(lambda: BackendIndex(
dispatch_key=DispatchKey.Undefined, use_out_as_primary=True, external=False, device_guard=False, index={}))
for k, v in bs.items():
# All structured in-tree operators are implemented in terms of their out operator.
indices[k] = BackendIndex(dispatch_key=k,
use_out_as_primary=True,
external=False,
device_guard=False,
index=v)
return ParsedYaml(rs, indices)
METHOD_DEFINITION = CodeTemplate("""\
${return_type} ${name}(${args_str}) {
${unpack_out}
${unsafe_tensor_check}
${device_check}
${device_guard}
${type_definition_body}
}
""")
TRACE_DISPATCH = CodeTemplate("""\
${op_hook_check}
return ${impl_name}(${args_exprs_str});""")
@with_native_function
def compute_op_definition(f: NativeFunction):
out_num = len(f.func.arguments.out)
sig = DispatcherSignature.from_schema(f.func, prefix=f'wrapper_{f.func.name.overload_name}_')
name = sig.name()
args = sig.arguments()
args_str = ', '.join(a.defn() for a in args)
args_exprs_str = ', '.join(a.name for a in args)
impl_name = f"at_npu::native::NPUNativeFunctions::{cpp.name(f.func)}"
if enable_opplugin() and is_op_valid(str(f.func.name)):
impl_name = f"op_plugin::{get_opplugin_wrap_name(f)}"
check_out = [f'TORCH_CHECK(out.size() == {out_num}, "expected tuple of {out_num} elements but got ", out.size(), '
f'OPS_ERROR(ErrCode::PARAM));']
unpack_out = check_out + [f'at::Tensor {args[-out_num + i].name} = out[{i}];' for i in range(out_num)] \
if out_num > 1 else ''
out_return_type = '::std::tuple<{}>'.format(', '.join(['at::Tensor'] * out_num))
has_tensor_options = any(
isinstance(a, TensorOptionsArguments)
for a in f.func.arguments.non_out
)
# There is precedence for which argument we use to do
# device guard. This describes the precedence order.
self_arg = (
[f.func.arguments.self_arg.argument]
if f.func.arguments.self_arg is not None
else []
)
candidate_args = itertools.chain(
self_arg,
f.func.arguments.out,
f.func.arguments.flat_positional,
)
candidate_tensor_args = []
candidate_tensor_args_without_optional = []
for a in candidate_args:
if a.type.is_tensor_like():
candidate_tensor_args.append(f"{a.name}")
pos = 0
for a in f.func.arguments.flat_positional:
if a.type.is_tensor_like() and not isinstance(a.type, OptionalType):
candidate_tensor_args_without_optional.append([f"{a.name}", pos])
pos += 1
unsafe_tensor_check = """ // No unsafe tensor check"""
if len(candidate_tensor_args) > 0:
unsafe_tensor_check = """"""
for tensor_arg in candidate_tensor_args_without_optional:
unsafe_tensor_check += \
f"""at_npu::autograd::VariableType::unpack({tensor_arg[0]}, "{tensor_arg[0]}", {tensor_arg[1]});
"""
unsafe_tensor_check += \
"""
if (c10_npu::get_npu_data_unsafe_flag()) {"""
for tensor_arg in candidate_tensor_args:
unsafe_tensor_check = unsafe_tensor_check + f"""
c10_npu::check_npu_tensor_is_safe({tensor_arg});"""
unsafe_tensor_check = unsafe_tensor_check + """
}
"""
candidate_args = itertools.chain(
f.func.arguments.out,
f.func.arguments.flat_positional,
f.func.arguments.flat_kwarg_only,
)
device_check = RegisterDispatchKey.gen_device_check(
f.device_check, list(candidate_args), name
)
candidate_args = itertools.chain(
self_arg,
f.func.arguments.out,
f.func.arguments.flat_positional,
)
# Only tensor like arguments are eligible
device_of = next(
(
f"{a.name}"
for a in candidate_args
if a.type.is_tensor_like()
),
None,
)
device_guard = ""
if has_tensor_options and device_of is not None:
device_guard = f"""
c10::OptionalDeviceGuard device_guard(device_of({device_of}));
if (device.has_value()) {{
device_guard.reset_device(device_or_default(device));
}}
"""
elif has_tensor_options:
# kernel is creating a tensor
device_guard = """
const c10::DeviceGuard device_guard(device_or_default(device));"""
elif device_of is not None:
# kernel is operating on existing tensors
device_guard = f"const c10::OptionalDeviceGuard device_guard(device_of({device_of}));"
# for op_hook_check
res_of_op_hook_post_code, return_of_op_hook_post_code = gen_op_hook_post_code(sig)
op_key = str(f.func.name)
op_hook_check = f"""\
if (C10_UNLIKELY(at_npu::native::env::CheckOpHookEnable())) {{
at_npu::native::OpHook::GetInstance().PreHook(\"{op_key}\", {args_exprs_str});
{res_of_op_hook_post_code}{impl_name}({args_exprs_str});
{return_of_op_hook_post_code}
}}
"""
return [METHOD_DEFINITION.substitute(
return_type=out_return_type if out_num > 1 else cpp.returns_type(f.func.returns).cpp_type(),
name=name,
args_str=','.join(a.defn() for a in args[:-out_num]) + ', at::TensorList out' if out_num > 1 else args_str,
unpack_out=unpack_out,
unsafe_tensor_check=unsafe_tensor_check,
device_check=device_check,
device_guard=device_guard,
type_definition_body=[TRACE_DISPATCH.substitute(impl_name=impl_name, args_exprs_str=args_exprs_str,
op_hook_check=op_hook_check)]
)]
@with_native_function
def compute_register_symbol(f: NativeFunction):
out_num = len(f.func.arguments.out)
if out_num > 1:
decl = re.compile(r"(?P<name>[^\(]+)\((?P<args>.*)\) -> (?P<returns>.*)").findall(str(f.func))[0]
func_schema = decl[0] + '(' + ','.join(decl[1].split(',')[:-out_num]) + ', Tensor[] out) -> (' + ', '.join(
['Tensor'] * out_num) + ')'
else:
func_schema = str(f.func)
pattern = r'\bself\b(?=[,\)])'
func_schema = re.sub(pattern, 'input', func_schema)
if f.has_composite_explicit_autograd_kernel:
name = DispatcherSignature.from_schema(f.func, prefix=f'wrapper_{f.func.name.overload_name}_').name()
return [f'm.def({cpp_string(func_schema)}, TORCH_FN(at_npu::native::{name}));\n']
else:
return [f'm.def({cpp_string(func_schema)});\n']
@with_native_function_and_index
def compute_register_impl(f: NativeFunction, backend_index):
if (backend_index is not None) and (backend_index.get_kernel(f) is None):
return []
if f.has_composite_explicit_autograd_kernel:
return []
else:
name = DispatcherSignature.from_schema(f.func, prefix=f'wrapper_{f.func.name.overload_name}_').name()
return [f'm.impl("{f.func.name}", TORCH_FN(at_npu::native::{name}));\n']
def gen_custom_trace(fm: FileManager, custom_trace_functions: Sequence[NativeFunction], custom_backend_indices):
fm.write_with_template(f'CustomRegisterSchema.cpp', 'CustomRegisterSchema.cpp', lambda: {
'custom_op_definitions': list(concatMap(
lambda f: compute_op_definition(f),
custom_trace_functions
)),
'custom_schema_registrations': list(concatMap(
lambda f: compute_register_symbol(f),
custom_trace_functions
)),
'custom_impl_registrations': list(concatMap(
lambda f: compute_register_impl(f, None),
custom_trace_functions
)),
'custom_autograd_impl_registrations': list(concatMap(
lambda f: compute_register_impl(f, custom_backend_indices[DispatchKey.AutogradPrivateUse1]),
custom_trace_functions
)),
})
def gen_custom_ops_patch(fm: FileManager, custom_trace_functions: Sequence[NativeFunction]):
valid_native_functions = list(filter(should_generate_ops_patch, custom_trace_functions))
fm.write_with_template(f'custom_ops.py', 'custom_ops.py', lambda: {
'custom_ops': [f'torch_npu.{ops} = torch.ops.npu.{ops}'
for ops in set([f.func.name.name for f in valid_native_functions])],
})
def compute_custom_functions_declaration(f: NativeFunction, func_type: str):
with native_function_manager(f):
sig = DispatcherSignature.from_schema(f.func)
name = sig.name()
args = sig.arguments()
if func_type == 'call':
args_str = ', '.join(a.decl() for a in args)
if func_type == 'redispatch':
args_str = 'c10::DispatchKeySet dispatchKeySet, ' + ', '.join(a.decl() for a in args)
return [CUSTOM_FUNCTIONS_DECLARATION.substitute(
return_type=cpp.returns_type(f.func.returns).cpp_type(),
func_name=name,
args_str=args_str,)]
def compute_custom_functions_definition(f: NativeFunction, func_type: str):
with native_function_manager(f):
sig = DispatcherSignature.from_schema(f.func)
name = sig.name()
args = sig.arguments()
if func_type == 'call':
args_str = ', '.join(a.defn() for a in args)
args_exprs_str = ', '.join(a.name for a in args)
if func_type == 'redispatch':
args_str = 'c10::DispatchKeySet dispatchKeySet, ' + ', '.join(a.defn() for a in args)
args_exprs_str = 'dispatchKeySet, ' + ', '.join(a.name for a in args)
return [CUSTOM_FUNCTIONS_DEFINITION.substitute(
return_type=cpp.returns_type(f.func.returns).cpp_type(),
base_name=f.func.name.name,
func_name=name,
overload=f.func.name.overload_name,
args_str=args_str,
func_type=func_type,
schema=sig.type(),
args_exprs_str=args_exprs_str,)]
def gen_custom_functions_dispatch(
fm: FileManager,
custom_functions: Sequence[NativeFunction]
) -> None:
func_type_list = ['call', 'redispatch']
file_name_list = ['CustomFunctions', 'CustomRedispatch']
for func_type, file_name in zip(func_type_list, file_name_list):
fm.write_with_template(
f'{file_name}.h', f'{file_name}.h', lambda:{
'custom_function_declarations':list(concatMap(
lambda f: compute_custom_functions_declaration(f, func_type),
custom_functions
))}
)
fm.write_with_template(
f'{file_name}.cpp', f'{file_name}.cpp', lambda:{
'custom_function_definitions':list(concatMap(
lambda f: compute_custom_functions_definition(f, func_type),
custom_functions
))}
)
-724
View File
@@ -1,724 +0,0 @@
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# Copyright (c) 2019, Facebook CORPORATION.
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pathlib
import argparse
import os
import stat
import re
from collections import namedtuple, Counter, defaultdict
from typing import List, Dict, Union, Sequence, Optional, Set, Callable
import yaml
import torchgen
from torchgen.code_template import CodeTemplate
from torchgen.gen import (parse_tags_yaml, FileManager, parse_native_yaml,
get_grouped_native_functions, error_check_native_functions)
from torchgen.model import (BackendIndex, DispatchKey,
NativeFunction, NativeFunctionsGroup, OperatorName,
BackendMetadata, is_cuda_dispatch_key)
from torchgen.native_function_generation import add_generated_native_functions
from torchgen.selective_build.selector import SelectiveBuilder
from torchgen.utils import Target, concatMap, context, NamespaceHelper
import torchgen.dest as dest
import torchgen.api.dispatcher as dispatcher
import torchgen.api.native as native
from torchgen.api.cpp import JIT_TO_CPP_DEFAULT
from torchgen.gen_backend_stubs import gen_dispatchkey_nativefunc_headers
from codegen.gen_functionalization_type import gen_functionalization_definition, gen_functionalization_registration
from codegen.utils import (get_torchgen_dir, rename_privateuse1_dispatch_key, gen_unstructured, add_header_to_template_file,
get_grouped_native_functions_optional_out, parse_npu_yaml, get_opplugin_wrap_name,
get_target_functions, merge_custom_yaml, field_tag, gen_custom_yaml_path,
update_opapi_info, is_opapi, update_internal_format_opapi_info, PathManager, filt_exposed_api, get_target_native_registration,
NativeFunctionsGroupOptionalOut, gen_device_check, DEVICE_NOCHECK_SET)
from codegen.custom_functions import (parse_custom_yaml, gen_custom_trace, gen_custom_ops_patch,
gen_custom_functions_dispatch)
torchgen.model.dispatch_keys.append(torchgen.model.DispatchKey.AutogradPrivateUse1)
# Create backend_indices map for func retrieval with the key of each func we supported.
def create_backend_index(backend_ops: List[str],
symint_ops: Set[str],
dispatch_key: DispatchKey,
native_funcs_map: Dict[OperatorName, NativeFunction],
cpp_namespace: str,
) -> BackendIndex:
metadata: Dict[OperatorName, BackendMetadata] = {}
for op in backend_ops:
op_name = OperatorName.parse(op)
if op_name not in native_funcs_map:
raise KeyError(f"Found an invalid operator name: {op_name}")
# See Note [External Backends Follow Dispatcher API]
kernel_name = dispatcher.name(native_funcs_map[op_name].func)
if op in symint_ops:
kernel_name += "_symint"
m = BackendMetadata(kernel=kernel_name, structured=False, cpp_namespace=cpp_namespace)
metadata[op_name] = m
return BackendIndex(
dispatch_key=dispatch_key,
use_out_as_primary=False,
external=True,
device_guard=True,
index=metadata)
# Check whether the function is placed at the wrong place.
def check_grouped_native_functions(
backend_key: DispatchKey,
autograd_key: DispatchKey,
backend_indices: Dict[DispatchKey, BackendIndex],
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]]):
for g in grouped_native_functions:
if isinstance(g, NativeFunction):
forward_kernels = [] if backend_key is None else \
[m for m in [backend_indices[backend_key].get_kernel(g)] if m is not None]
backward_kernels = [] if autograd_key is None else \
[m for m in [backend_indices[autograd_key].get_kernel(g)] if m is not None]
else:
if backend_key is None:
forward_kernels = []
else:
forward_kernels = []
for f in g.functions():
kernel = backend_indices[backend_key].get_kernel(f)
if kernel is not None:
forward_kernels.append(kernel)
if autograd_key is None:
backward_kernels = []
else:
backward_kernels = []
for f in g.functions():
kernel = backend_indices[autograd_key].get_kernel(f)
if kernel is not None:
backward_kernels.append(kernel)
forward_kernels = [f for f in forward_kernels if f is not None]
backward_kernels = [f for f in backward_kernels if f is not None]
if len(forward_kernels) != 0 and len(backward_kernels) != 0:
raise ValueError(f'Currently, all variants of an op must either be registered to a backend key, \
or to a backend\'s autograd key. They cannot be mix and matched. If this is \
something you need, feel free to create an issue! {forward_kernels[0].kernel} \
is listed under "supported", but {backward_kernels[0].kernel} is listed under "autograd".')
_GLOBAL_PARSE_NATIVE_YAML_CACHE = {}
# Parse native_functions.yaml into a sequence of NativeFunctions and Backend Indices.
ParsedYaml = namedtuple('ParsedYaml', ['native_functions', 'backend_indices'])
def modify_func_in_native_yaml(func: str) -> str:
# func_to_modify: {old_value: new_value}
func_to_modify = {"matmul_backward(Tensor grad, Tensor self, Tensor other, bool[2] mask) -> (Tensor, Tensor)":
"matmul_backward(Tensor grad_out, Tensor self, Tensor other, bool[2] mask) -> (Tensor, Tensor)"}
if func in func_to_modify:
return func_to_modify[func]
return func
def parse_native_and_custom_yaml(path: str, tag_path: str, custom_path: str) -> ParsedYaml:
global _GLOBAL_PARSE_NATIVE_YAML_CACHE
if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE:
valid_tags = parse_tags_yaml(tag_path)
PathManager.check_directory_path_readable(path)
with open(path, 'r') as f:
es = yaml.safe_load(f)
if not isinstance(es, list):
raise TypeError("es is not list")
rs: List[NativeFunction] = []
bs: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = defaultdict(dict)
for e in es:
e["func"] = modify_func_in_native_yaml(e["func"])
func, m = NativeFunction.from_yaml(e, "Location", valid_tags)
rs.append(func)
BackendIndex.grow_index(bs, m)
source_es = parse_npu_yaml(custom_path)
custom_es = source_es.get('custom', []) + source_es.get('custom_autograd', [])
supported_es = source_es.get('supported', []) + source_es.get('autograd', []) + custom_es
for es in supported_es:
update_opapi_info(es)
update_internal_format_opapi_info(es)
custom_es = field_tag(custom_es)
for e in custom_es:
func, m = NativeFunction.from_yaml(e, "Location", valid_tags)
rs.append(func)
BackendIndex.grow_index(bs, m)
error_check_native_functions(rs)
# Default dict is to prevent the codegen from barfing when we have a dispatch key that has no kernels yet.
indices: Dict[DispatchKey, BackendIndex] = defaultdict(lambda: BackendIndex(
dispatch_key=DispatchKey.Undefined,
use_out_as_primary=True,
device_guard=True,
external=False,
index={}))
add_generated_native_functions(rs, bs)
for k, v in bs.items():
# All structured in-tree operators are implemented in terms of their out operator.
indices[k] = BackendIndex(dispatch_key=k,
use_out_as_primary=True,
external=False,
device_guard=is_cuda_dispatch_key(k),
index=v)
_GLOBAL_PARSE_NATIVE_YAML_CACHE[path] = ParsedYaml(rs, indices)
return _GLOBAL_PARSE_NATIVE_YAML_CACHE[path]
# Different implements of ops from origin torch.
# Native ops with dispatchkey CompositeImplicitAutograd but implemented as a kernel op in pta
COMPOSITEIMPLICITAUTOGRAD_INCLUDE_LIST = [
'to.device',
'to.dtype',
]
# 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'])
def parse_backend_yaml(
backend_yaml_path: str,
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
backend_indices: Dict[DispatchKey, BackendIndex]
) -> ParsedExternalYaml:
native_functions_map = {}
for f in grouped_native_functions:
if isinstance(f, NativeFunction):
native_functions_map[f.func.name] = f
else:
for func in f.functions():
native_functions_map[func.func.name] = func
PathManager.check_directory_path_readable(backend_yaml_path)
with open(backend_yaml_path, 'r') as f:
yaml_values = yaml.safe_load(f)
if not isinstance(yaml_values, dict):
raise TypeError("yaml_values is not dict")
valid_keys = ['backend', 'cpp_namespace', 'supported', 'autograd', 'custom', 'custom_autograd', 'symint']
yaml_backend = yaml_values.pop('backend', None)
true_backend = 'PrivateUse1' if yaml_backend == 'NPU' else yaml_backend
if true_backend is None:
raise ValueError("You must provide a value for 'backend'")
backend = "NPU"
cpp_namespace = yaml_values.pop('cpp_namespace', None)
if cpp_namespace is None:
raise ValueError("You must provide a value for 'cpp_namespace'")
supported = yaml_values.pop('supported', [])
if supported is None:
supported = [] # Allow an empty list of supported ops
if not isinstance(supported, list):
raise TypeError(f'expected "supported" to be a list, but got type {type(supported)}')
symint = yaml_values.pop("symint", [])
if symint is None:
symint = []
if not (isinstance(symint, list)):
raise RuntimeError(f'expected "symint" to be a list, but got: {supported} (of type {type(supported)})')
symint = [op['func'].split("(")[0] if isinstance(op, Dict) else op for op in symint]
symint_set = set(symint)
supported_autograd = yaml_values.pop('autograd', [])
if not isinstance(supported_autograd, list):
raise TypeError(f'expected "autograd" to be a list, but got: {supported_autograd}')
supported_list = []
for op in supported:
if isinstance(op, Dict) and op.get('device_check', None) == 'NoCheck':
DEVICE_NOCHECK_SET.add(op['func'].split("(")[0])
if isinstance(op, Dict) and ({"impl_ns", "op_api", "device_check"} & set(op.keys())):
supported_list.append(op['func'].split("(")[0])
elif not isinstance(op, Dict):
supported_list.append(op)
supported = supported_list
supported_autograd = [op['func'].split("(")[0] if isinstance(op, Dict) else op for op in supported_autograd]
supported_autograd += COMPOSITEIMPLICITAUTOGRAD_INCLUDE_LIST
custom = yaml_values.pop('custom', [])
if not isinstance(custom, list):
raise TypeError(f'expected "autograd" to be a list, but got: {custom}')
for item in custom:
try:
supported.append(item['func'][:item['func'].index('(')])
except ValueError as e:
raise Exception(f'Wrong format for function: {item["func"]}') from e
custom_autograd = yaml_values.pop('custom_autograd', [])
if not isinstance(custom_autograd, list):
raise TypeError(f'expected "autograd" to be a list, but got: {custom_autograd}')
for item in custom_autograd:
supported_autograd.append(item['func'][:item['func'].index('(')])
# custom_supported is only supported for filt expose api, and is not useful here.
yaml_values.pop('custom_supported', [])
if (len(yaml_values.keys()) > 0):
raise KeyError(f'{backend_yaml_path} contains unexpected keys: {", ".join(yaml_values.keys())}. \
Only the following keys are supported: {", ".join(valid_keys)}')
backend_key: Optional[DispatchKey] = None
opapi_key = "OpApi"
if len(supported) > 0:
with context(lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.'):
backend_key = DispatchKey.parse(backend)
backend_idx = create_backend_index(supported, symint_set, backend_key, native_functions_map, cpp_namespace)
opapi_backend_idx = create_backend_index([op for op in supported if is_opapi(op)],
symint_set, backend_key, native_functions_map, cpp_namespace)
if backend_key in backend_indices:
raise KeyError("backend_key should not be in backend_indices.")
backend_indices[backend_key] = backend_idx
backend_indices[str(backend_key) + opapi_key] = opapi_backend_idx
autograd_key: Optional[DispatchKey] = None
if len(supported_autograd) > 0:
with context(lambda: f'The "autograd" key was specified, which indicates that you would like to override \
the behavior of autograd for some operators on your backend. However "Autograd{backend}" is not a valid DispatchKey.'):
autograd_key = DispatchKey.parse(f'Autograd{backend}')
autograd_idx = create_backend_index(supported_autograd, symint_set,
autograd_key, native_functions_map, cpp_namespace)
opapi_autograd_idx = create_backend_index([op for op in supported_autograd if is_opapi(op)],
symint_set, autograd_key, native_functions_map, cpp_namespace)
backend_indices[autograd_key] = autograd_idx
backend_indices[str(autograd_key) + opapi_key] = opapi_autograd_idx
return ParsedExternalYaml(true_backend, backend_key, autograd_key, cpp_namespace, backend_indices)
def op_plugin_kernel_conut(op_plugin_ops_dir: str):
actual_backend_kernel_name_counts = Counter()
file_path = os.path.join(op_plugin_ops_dir, "OpInterface.h")
PathManager.check_directory_path_readable(file_path)
try:
with open(file_path, 'r') as f:
backend_defns = f.read()
except IOError as e:
raise AssertionError(f'Unable to read from the specified impl_path file: {file_path}') from e
kernel_defn_regex = rf'\w+(?=\()'
actual_backend_kernel_name_counts += Counter(re.findall(kernel_defn_regex, backend_defns))
return actual_backend_kernel_name_counts
def pta_kernel_conut(class_name: str, pta_op_dir: str):
actual_backend_kernel_name_counts = Counter()
for cur_dir, _, filenames in os.walk(pta_op_dir):
for filename in filenames:
if not filename.endswith('.cpp'):
continue
file_path = os.path.join(cur_dir, filename)
PathManager.check_directory_path_readable(file_path)
try:
with open(file_path, 'r') as f:
backend_defns = f.read()
except IOError:
raise AssertionError(f'Unable to read from the specified impl_path file: {file_path}')
kernel_defn_regex = rf'{class_name}::([\w\d]*)\([^\)]*\)\s*{{'
actual_backend_kernel_name_counts += Counter(re.findall(kernel_defn_regex, backend_defns))
return actual_backend_kernel_name_counts
def check_op_plugin_kernels(
native_functions: Sequence[NativeFunction],
expected_kernel_counts: Dict[str, List[NativeFunction]],
actual_kernel_counts: Dict[str, List[NativeFunction]]):
for f in native_functions:
wrap_name = get_opplugin_wrap_name(f)
expect_op_plugin_kernel_count = len(expected_kernel_counts[wrap_name])
if expect_op_plugin_kernel_count > actual_kernel_counts[wrap_name]:
return False
return True
def main() -> None:
parser = argparse.ArgumentParser(description='Generate backend stub files')
parser.add_argument(
'-s',
'--source_yaml',
help='path to source yaml file containing operator external definitions')
parser.add_argument(
'-o', '--output_dir', help='output directory')
parser.add_argument(
'--dry_run', type=bool, default=False, help='output directory')
parser.add_argument(
'--impl_path', type=str, default=None, help='path to the source C++ file containing kernel definitions')
parser.add_argument(
'--op_plugin_impl_path', type=str, default=None,
help='path to the source C++ file containing kernel definitions in op_plugin')
parser.add_argument(
'--op_plugin_yaml_path', type=str, default=None,
help='path to the source yaml file containing kernel definitions in op_plugin')
options = parser.parse_args()
run(options.source_yaml, options.output_dir, options.dry_run,
options.impl_path, options.op_plugin_impl_path, options.op_plugin_yaml_path)
def gen_dispatcher_registrations(
fm: FileManager,
class_name: str,
backend_indices: Dict[DispatchKey, BackendIndex],
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
backend_dispatch_key: DispatchKey,
dispatch_key: DispatchKey,
selector: "SelectiveBuilder",
dispatch_key_name: str,
register_dispatch_key_func: Callable,
native_function_registrations: str = '',
):
backend_index = backend_indices[backend_dispatch_key]
ns_helper = NamespaceHelper(namespace_str="at")
native_func_header = """\
#include "torch_npu/csrc/core/npu/NPURecovery.h"
#include "torch_npu/csrc/core/npu/NpuVariables.h"
#include "torch_npu/csrc/core/npu/NPUException.h"
#ifndef BUILD_LIBTORCH
#include "torch_npu/csrc/profiler/utils.h"
#endif
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/framework/interface/EnvVariables.h"
#include "torch_npu/csrc/aten/NPUOpApiNativeFunctions.h"
#include "torch_npu/csrc/framework/FormatHelper.h"
#include "torch_npu/csrc/framework/utils/ForceAclnnList.h"
#include "torch_npu/csrc/framework/OpHook.h"
#include "op_plugin/OpInterface.h"
"""
static_template = CodeTemplate(
"""\
TORCH_LIBRARY_IMPL(aten, $dispatch_key, m) {
$dispatch_registrations_body
};"""
)
static_init_dispatch_registrations = static_template.substitute(
dispatch_key=dispatch_key_name,
dispatch_registrations_body=list(
concatMap(
register_dispatch_key_func(
backend_index,
Target.REGISTRATION,
selector,
rocm=False,
symint=True,
class_method_name=f"{class_name}",
skip_dispatcher_op_registration=False,
),
grouped_native_functions,
)
),
)
fm.write_with_template(f'Register{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: {
'extra_cuda_headers': '',
'external_backend_headers': native_func_header,
'namespaced_headers': '',
'DispatchKey': dispatch_key,
'dispatch_headers': dest.gen_registration_headers(
backend_index, per_operator_headers=False, rocm=False
),
'ops_headers': '',
'dispatch_definitions': fm.substitute_with_template(
'RegisterDispatchDefinitions.ini',
lambda: {
'ns_prologue': ns_helper.prologue,
'ns_epilogue': ns_helper.epilogue,
'static_init_dispatch_registrations': static_init_dispatch_registrations,
'deferred_dispatch_registrations': '',
'dispatch_helpers': dest.gen_registration_helpers(backend_index),
'dispatch_namespace': dispatch_key.lower(),
'dispatch_namespaced_definitions': native_function_registrations,
'dispatch_anonymous_definitions': list(
concatMap(
register_dispatch_key_func(
backend_index,
Target.ANONYMOUS_DEFINITION,
selector,
rocm=False,
symint=True,
class_method_name=f'{class_name}',
skip_dispatcher_op_registration=False,
),
grouped_native_functions,
)
),
},
).split('\n'),
})
def get_supported_grouped_native_functions(
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
backend_index: BackendIndex,
) -> Sequence[Union[NativeFunction, NativeFunctionsGroup]]:
supported_grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]] = []
for funcs in grouped_native_functions:
if isinstance(funcs, NativeFunctionsGroup) and not backend_index.has_kernel(funcs.out):
for f in funcs.functions():
if backend_index.has_kernel(f):
supported_grouped_native_functions.append(f)
continue
supported_grouped_native_functions.append(funcs)
return supported_grouped_native_functions
def gen_foreach_register(
fm: FileManager,
tags_yaml_path: str,
native_yaml_path: str,
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
backend_indices: BackendIndex,
):
cpu_backend_indices = parse_native_yaml(native_yaml_path, tags_yaml_path).backend_indices[DispatchKey.CPU]
foreach_dict: Dict[str, str] = {}
header_set = set()
def get_foreach_kernel(func: NativeFunction):
schema = func.func.name
if not str(schema).startswith("_foreach"):
return
if schema in cpu_backend_indices.index and schema not in backend_indices.index:
foreach_dict[str(schema)] = cpu_backend_indices.index[schema].kernel
for f in grouped_native_functions:
if isinstance(f, NativeFunctionsGroup):
header_set.add(str(f.signature().name.name.base))
for func in f.functions():
get_foreach_kernel(func)
else:
header_set.add(str(f.func.name.name.base))
get_foreach_kernel(f)
kernel_template = CodeTemplate(
"""\
m.impl("${schema}", TORCH_FN(at::native::${kernel}));"""
)
header_template = CodeTemplate(
"""\
#include <ATen/ops/${function}_native.h>"""
)
fm.write_with_template(f'ForeachRegister.cpp', 'ForeachRegister.cpp', lambda: {
'include_headers': [header_template.substitute(function=h) for h in header_set if h.startswith("_foreach")],
'foreach_kernel': [kernel_template.substitute(schema=kv[0], kernel=kv[1]) for kv in foreach_dict.items()]
})
def gen_functionalization(fm: FileManager,
selector: "SelectiveBuilder",
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroupOptionalOut]],
):
def key_func(
fn: Union[NativeFunction, NativeFunctionsGroupOptionalOut]
) -> str:
return fn.root_name
def functionalization_env_callable(g):
definition = gen_functionalization_definition(selector, g)
register = gen_functionalization_registration(selector, g)
return {
"func_definitions": definition,
"func_registrations": register,
}
fm.write_sharded(
"RegisterFunctionalization.cpp",
grouped_native_functions,
key_fn=key_func,
env_callable=functionalization_env_callable,
num_shards=2,
sharded_keys={
"func_definitions",
"func_registrations",
},
)
return
def gen_target_registration(
target_op_type: str,
dispatch_key: DispatchKey,
backend_indices: Dict[DispatchKey, BackendIndex],
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
op_plugin_yaml_path: str,
fm: FileManager,
selector: "SelectiveBuilder",
native_functions: List[NativeFunction] = None,
):
target_ops = get_target_functions(op_plugin_yaml_path, target_op_type=target_op_type)
target_native_functions = []
for f in grouped_native_functions:
if isinstance(f, NativeFunctionsGroup):
for func in f.functions():
if func.func in target_ops:
target_native_functions.append(func)
elif f.func in target_ops:
target_native_functions.append(f)
metadata: Dict[OperatorName, BackendMetadata] = {}
for op in target_ops:
kernel_name = dispatcher.name(op)
metadata[op.name] = BackendMetadata(kernel=kernel_name, structured=False, cpp_namespace=target_op_type)
backend_indices[dispatch_key] = BackendIndex(
dispatch_key=dispatch_key,
use_out_as_primary=False,
external=True,
device_guard=True,
index=metadata)
native_registration = get_target_native_registration(dispatch_key, backend_indices, metadata, native_functions)
gen_dispatcher_registrations(
fm,
backend_indices[dispatch_key].native_function_class_name(),
backend_indices,
target_native_functions,
dispatch_key,
dispatch_key,
selector,
dispatch_key_name=dispatch_key.name,
register_dispatch_key_func=dest.RegisterDispatchKey,
native_function_registrations=native_registration,
)
def run(source_yaml: str, output_dir: str, dry_run: bool,
impl_path: Optional[str], op_plugin_impl_path: Optional[str], op_plugin_yaml_path: Optional[str]) -> None:
rename_privateuse1_dispatch_key()
torchgen_path = get_torchgen_dir()
template_dir = os.path.join(torchgen_path, "packaged/ATen/templates")
def make_file_manager(install_dir: str) -> FileManager:
return FileManager(install_dir=install_dir, template_dir=template_dir, dry_run=dry_run)
fm = make_file_manager(output_dir)
merge_custom_yaml(source_yaml, op_plugin_yaml_path)
source_yaml = gen_custom_yaml_path(source_yaml)
tags_yaml_path = os.path.join(torchgen_path, 'packaged/ATen/native/tags.yaml')
native_yaml_path = os.path.join(torchgen_path, 'packaged/ATen/native/native_functions.yaml')
parsed_yaml = parse_native_and_custom_yaml(native_yaml_path, tags_yaml_path, source_yaml)
get_target_functions(op_plugin_yaml_path)
native_functions, backend_indices = parsed_yaml.native_functions, parsed_yaml.backend_indices
grouped_native_functions = get_grouped_native_functions(native_functions)
parsed_backend_yaml = parse_backend_yaml(source_yaml, grouped_native_functions, backend_indices)
true_backend = parsed_backend_yaml.true_backend
backend_key = parsed_backend_yaml.backend_key
autograd_key = parsed_backend_yaml.autograd_key
cpp_namespace = parsed_backend_yaml.cpp_namespace
backend_indices = parsed_backend_yaml.backend_indices
selector = SelectiveBuilder.get_nop_selector()
if backend_key is not None:
backend_dispatch_key: DispatchKey = backend_key
autograd_dispatch_key: DispatchKey = autograd_key
class_name = backend_indices[backend_dispatch_key].native_function_class_name()
gen_dispatchkey_nativefunc_headers(
fm,
class_name,
cpp_namespace,
backend_indices,
grouped_native_functions,
backend_key,
None,
)
gen_dispatchkey_nativefunc_headers(
fm,
"NPUNativeOpApiFunctions",
cpp_namespace,
backend_indices,
grouped_native_functions,
str(backend_key) + "OpApi",
None,
)
for dispatch_key in [backend_dispatch_key, autograd_dispatch_key]:
if not dispatch_key:
continue
gen_dispatcher_registrations(
fm,
class_name,
backend_indices,
get_supported_grouped_native_functions(grouped_native_functions, backend_indices[dispatch_key]),
dispatch_key,
dispatch_key,
selector,
dispatch_key_name=dispatch_key.name.replace("NPU", true_backend),
register_dispatch_key_func=dest.RegisterDispatchKey,
)
custom_functions, custom_backend_indices = parse_custom_yaml(source_yaml, tags_yaml_path)
pta_template_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "templates")
fm = FileManager(install_dir=output_dir, template_dir=pta_template_dir, dry_run=dry_run)
grouped_custom_functions = get_grouped_native_functions_optional_out(custom_functions)
gen_functionalization(fm, selector, grouped_custom_functions)
gen_custom_trace(fm, custom_functions, custom_backend_indices)
gen_custom_functions_dispatch(fm, custom_functions)
gen_foreach_register(fm,
tags_yaml_path,
native_yaml_path,
grouped_native_functions,
backend_indices[backend_dispatch_key])
custom_ops_patch_dir = os.path.join(output_dir, "../../utils/")
fm = FileManager(install_dir=custom_ops_patch_dir, template_dir=pta_template_dir, dry_run=dry_run)
gen_custom_ops_patch(fm, custom_functions)
filt_exposed_list = filt_exposed_api(source_yaml)
exposed_path = pathlib.Path(__file__).parents[1].joinpath('torch_npu/utils/exposed_api.py')
PathManager.remove_path_safety(exposed_path)
with os.fdopen(os.open(exposed_path, os.O_RDWR | os.O_CREAT, stat.S_IWUSR | stat.S_IRUSR), 'w') as f:
f.write(f'public_npu_functions = {filt_exposed_list}')
os.chmod(exposed_path, stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)
fm = make_file_manager(output_dir)
gen_target_registration(
"sparse",
DispatchKey.SparsePrivateUse1,
backend_indices,
grouped_native_functions,
op_plugin_yaml_path,
fm,
selector,
native_functions
)
def apply_torchgen_patch():
dest.RegisterDispatchKey.gen_unstructured = gen_unstructured
dest.RegisterDispatchKey.gen_device_check = gen_device_check
# generate default arguments
JIT_TO_CPP_DEFAULT["contiguous_format"] = "c10::MemoryFormat::Contiguous"
add_header_to_template_file()
dispatcher.arguments = native.arguments
if __name__ == '__main__':
apply_torchgen_patch()
main()
-258
View File
@@ -1,258 +0,0 @@
from typing import List, Union
from torchgen.api import dispatcher
from torchgen.api.translate import translate
from torchgen.api.types import (
DispatcherSignature,
)
from torchgen.context import (
with_native_function,
with_native_function_and,
)
from torchgen.model import (
BaseTy,
BaseType,
NativeFunction,
NativeFunctionsGroup,
SchemaKind
)
from torchgen.selective_build.selector import SelectiveBuilder
from torchgen.gen_functionalization_type import (
wrapper_name,
modifies_arguments,
unwrap_tensor_args,
convert_to_meta_tensors,
get_mutable_redispatch_return_names,
return_str,
maybe_create_output,
return_from_mutable_noop_redispatch,
)
from .utils import NativeFunctionsGroupOptionalOut
def wrap_propagate_mutations_and_return(
f: NativeFunction, functional_op: NativeFunction, inner_return_var: str
) -> str:
mutable_arg_names = f.func.arguments.mutable_arg_names()
(
aliased_outer_rets,
non_aliased_outer_rets,
) = get_mutable_redispatch_return_names(f, inner_return_var)
_, non_aliased_inner_rets = get_mutable_redispatch_return_names(
functional_op, inner_return_var
)
# The outer function may have a mix of aliased and non-aliased outputs,
# But the inner functional op that we're transforming to should only have non-aliased outputs
if len(mutable_arg_names) + len(non_aliased_outer_rets) != len(non_aliased_inner_rets):
raise RuntimeError("The sum of the lengths of mutable_arg_names and non_aliased_outer_rets "
"does not equal the length of non_aliased_inner_rets.")
# First, take all of the newly created outputs from the inner call and wrap them into functional tensors
updates = []
non_aliased_wrapped_ret_names = []
for i, inner_ret in enumerate(
non_aliased_inner_rets[: len(non_aliased_outer_rets)]
):
ret_name = f"output_{i}"
updates.append(
f"""\
auto output_{i} = at::functionalization::impl::to_functional_tensor({inner_ret});"""
)
non_aliased_wrapped_ret_names.append(ret_name)
# Next, take all of the mutated outputs from the inner call corresponding to mutated inputs,
# and propagate the mutations
for outer_arg, inner_ret in zip(
mutable_arg_names, non_aliased_inner_rets[len(non_aliased_outer_rets) :]
):
updates.append(
f"""\
at::functionalization::impl::replace_({outer_arg}, {inner_ret});
at::functionalization::impl::commit_update({outer_arg});
at::functionalization::impl::sync({outer_arg});"""
)
# Finally, we return:
# - Any mutable arguments that also returns
# - Any immutable returns that were created wrapping the output from the inner call
returns_str = return_str(
f.func.returns, aliased_outer_rets + non_aliased_wrapped_ret_names
)
updates_str = "\n".join(updates)
return f"""\
{updates_str}
{returns_str}"""
# Generates the Functionalization kernel for:
# - mutation ops (inplace and out= ops)
@with_native_function_and
def emit_inplace_functionalization_body(
f: NativeFunction, g: NativeFunctionsGroup
) -> str:
# mutation case
if not modifies_arguments(f):
raise RuntimeError(f"The function {f.func.name} does not modify its arguments.")
dispatcher_sig = DispatcherSignature.from_schema(f.func)
dispatcher_sig_func = DispatcherSignature.from_schema(g.functional.func)
unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args(
dispatcher_sig, is_view_op=False
)
mutated_names = [
a.name
for a in f.func.arguments.flat_all
if a.type.is_tensor_like() and a.annotation is not None
]
non_mutated_names = [
a.name
for a in f.func.arguments.flat_all
if a.type.is_tensor_like() and a.annotation is None
]
# all mutable inputs must be functional tensors in order to participate in functionalization
check_all_mutated_args_are_functional = " && ".join(
["true"]
+ [
f"at::functionalization::impl::isFunctionalTensor({a})"
for a in mutated_names
]
)
check_any_non_mutated_args_are_functional = " || ".join(
["false"]
+ [
f"at::functionalization::impl::isFunctionalTensor({a})"
for a in non_mutated_names
]
)
# These are used in the cases where we don't functionalize and redispatch to the inplace op
# case 1: we hit an inplace op that doesn't have an out-of-place equivalent
# case 2: we hit an inplace ops but our inputs are not functional tensors (in which case our kernel just no-ops)
inplace_exprs = [
e.expr
for e in translate(unwrapped_args_ctx, dispatcher_sig.arguments(), method=False)
]
# call the out-of-place variant of the op
return_type = (
dispatcher.returns_type(g.functional.func.returns).remove_const_ref().cpp_type()
)
functional_sig = DispatcherSignature.from_schema(g.functional.func)
functional_exprs = [
e.expr
for e in translate(unwrapped_args_ctx, functional_sig.arguments(), method=False)
]
meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig)
# We don't want to run the inplace meta func for ops like .set_(), because:
# (1) they're unnecessary: inplace meta checks are only useful for ops like add_(),
# where broadcasting will work for the out-of-place case but should fail on the inplace call
# (2) They'll also fail without adding extra infra: we'd need to convert the input storage argument
# into a meta storage
any_storage_args = any(
a.type == BaseType(BaseTy.Storage) for a in f.func.arguments.flat_all
)
return f"""
{dispatcher_sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{
if ({str(not any_storage_args and f.func.kind() == SchemaKind.inplace).lower()}) {{
// Before converting the mutable op to its functional variant, run meta tensors through the original op.
// This will help us catch shape errors that apply to inplace ops that wouldn't apply to their functional variants.
// (We can only do this for inplace ops today though, because they technicaly all support meta tensors).
{meta_conversion_str}
at::AutoDispatchSkipFunctionalize func_guard;
c10::impl::ExcludeDispatchKeyGuard guard(exclude_keys_for_meta_dispatch);
at_npu::native::custom_ops::{dispatcher_sig.name()}({', '.join(a.name for a in meta_call_ctx)});
}}
{unwrap_tensor_args_str}
if (!({check_all_mutated_args_are_functional})) {{
if ({check_any_non_mutated_args_are_functional}) {{
// case 1: trying to mutate a non functional tensor with a functional tensor is an error
TORCH_INTERNAL_ASSERT(false,
"mutating a non-functional tensor with a functional tensor is not allowed.",
" Please ensure that all of your inputs are wrapped inside of a functionalize() call.", PTA_ERROR(ErrCode::PARAM));
}} else {{
// case 2: arguments are not functional tensors, so we no-op and redispatch.
at::AutoDispatchSkipFunctionalize guard;
{maybe_create_output(f, 'tmp_output')}at_npu::native::custom_ops::{dispatcher_sig.name()}({', '.join(inplace_exprs)});
{return_from_mutable_noop_redispatch(f, 'tmp_output')}
}}
}} else {{
{return_type} tmp_output;
{{
at::AutoDispatchSkipFunctionalize guard;
tmp_output = at_npu::native::custom_ops::{dispatcher_sig_func.name()}({', '.join(functional_exprs)});
}}
{wrap_propagate_mutations_and_return(f, g.functional, 'tmp_output')}
}}
}}"""
def gen_functionalization_registration(
selector: SelectiveBuilder,
g: Union[NativeFunction, NativeFunctionsGroupOptionalOut],
) -> List[str]:
@with_native_function
def emit_registration_helper(f: NativeFunction) -> str:
registration_str = f"TORCH_FN(functionalization::{wrapper_name(f.func)})"
return f'm.impl("{f.func.name}", {registration_str});'
# Don't generate kernels in mobile build
if not selector.include_all_operators:
return []
if isinstance(g, NativeFunctionsGroupOptionalOut):
fns = list(g.functions())
else :
fns = []
registrations = []
for f in fns:
if len(f.func.arguments.out) > 1:
return []
if str(f.func.name) == "lift":
# See Note [Functionalization <> torch.Tensor constructor]
return []
if str(f.func.name) == "resize_":
# See Note [resize_ in Functionalization]
return []
if f.is_view_op:
raise RuntimeError(f"The {f.func.name} func is a view op.")
# functionalization needs to generate and register kernals for inplace ops.
# We *also* need to directly register CompositeImplicitAUtograd kernels
# so that they decompose properly before functioanlization.
if modifies_arguments(f):
registrations.append(emit_registration_helper(f))
return registrations
def gen_functionalization_definition(
selector: SelectiveBuilder,
# Note: Ideally this code should never have to look at NativeFunction
# (and instead only need to operate on grouped NativeFunctions).
# The only reason currently is because we need to emit direct dispatch registrations
# For CompositeImplicitAutograd operators, which are potentially ungrouped.
g: Union[NativeFunction, NativeFunctionsGroupOptionalOut],
) -> List[str]:
# Don't generate kernels in mobile build
if not selector.include_all_operators:
return []
if isinstance(g, NativeFunction):
return []
else:
# Case 2: emit inplace -> out-of-place kernels for the functionalization.
mutation_defs = []
if g.out is not None:
if len(g.out.func.arguments.out) > 1:
return []
mutation_defs.append(emit_inplace_functionalization_body(g.out, g))
if g.inplace is not None:
mutation_defs.append(emit_inplace_functionalization_body(g.inplace, g))
if g.mutable is not None:
mutation_defs.append(emit_inplace_functionalization_body(g.mutable, g))
return mutation_defs
return []
-14
View File
@@ -1,14 +0,0 @@
#include <ATen/core/dispatch/Dispatcher.h>
#include "torch_npu/csrc/aten/CustomFunctions.h"
namespace at_npu {
namespace native {
namespace custom_ops {
${custom_function_definitions}
} // namespace custom_ops
} // namespace native
} // namespace at_npu
-16
View File
@@ -1,16 +0,0 @@
#ifndef TORCH_NPU_CSRC_ATEN_CUSTOM_FUNCTIONS
#define TORCH_NPU_CSRC_ATEN_CUSTOM_FUNCTIONS
#include <ATen/ATen.h>
namespace at_npu {
namespace native {
namespace custom_ops {
${custom_function_declarations}
} // namespace custom_ops
} // namespace native
} // namespace at_npu
#endif
-12
View File
@@ -1,12 +0,0 @@
#include <ATen/core/dispatch/Dispatcher.h>
#include "torch_npu/csrc/aten/CustomRedispatch.h"
namespace at_npu {
namespace redispatch {
${custom_function_definitions}
} // namespace redispatch
} // namespace at_npu
-14
View File
@@ -1,14 +0,0 @@
#ifndef TORCH_NPU_CSRC_ATEN_CUSTOM_REDISPATCH
#define TORCH_NPU_CSRC_ATEN_CUSTOM_REDISPATCH
#include <ATen/ATen.h>
namespace at_npu {
namespace redispatch {
${custom_function_declarations}
} // namespace redispatch
} // namespace at_npu
#endif
@@ -1,71 +0,0 @@
#include <c10/core/TensorImpl.h>
#include <c10/core/Allocator.h>
#include <ATen/DeviceGuard.h>
#include <ATen/NativeFunctions.h>
#include <ATen/MetaFunctions.h>
#include <ATen/NamedTensorUtils.h>
#include <ATen/Utils.h>
#include <ATen/WrapDimUtils.h>
#include <ATen/Dispatch.h>
#include <c10/util/Half.h>
#include <c10/core/UndefinedTensorImpl.h>
#include <c10/util/Optional.h>
#include <ATen/Tensor.h>
#include <ATen/Functions.h>
#include <ATen/native/Resize.h>
#include <ATen/core/op_registration/adaption.h>
#include <cstddef>
#include <functional>
#include <memory>
#include <utility>
#include <ATen/Config.h>
#include <torch/library.h>
#include <torch/csrc/autograd/function.h>
#include <torch/csrc/jit/frontend/tracer.h>
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/aten/VariableType.h"
#include "torch_npu/csrc/core/npu/NPUException.h"
#include "torch_npu/csrc/core/npu/NPURecovery.h"
#include "torch_npu/csrc/framework/interface/EnvVariables.h"
#include "torch_npu/csrc/framework/OpHook.h"
#include "op_plugin/OpInterface.h"
namespace at_npu {
namespace native {
${custom_op_definitions}
namespace {
TORCH_LIBRARY(npu, m) {
${custom_schema_registrations}
}
} // anonymous namespace
namespace {
TORCH_LIBRARY_IMPL(npu, PrivateUse1, m) {
${custom_impl_registrations}
}
} // anonymous namespace
namespace {
TORCH_LIBRARY_IMPL(npu, AutogradPrivateUse1, m) {
${custom_autograd_impl_registrations}
}
} // anonymous namespace
} // namespace native
} // namespace at_npu
-16
View File
@@ -1,16 +0,0 @@
#include <torch/library.h>
${include_headers}
namespace {
// Register fallthrough for Autograd backends dispatch keys
// NB: But not the private use ones; maybe the extension wants
// to override it themselves!
// (Ascend) TORCH_LIBRARY_IMPL
TORCH_LIBRARY_IMPL(aten, PrivateUse1, m) {
${foreach_kernel}
}
}
@@ -1,108 +0,0 @@
// ${generated_comment}
#include <ATen/core/LegacyTypeDispatch.h>
#include <ATen/EmptyTensor.h>
#include <ATen/FunctionalTensorWrapper.h>
#include <ATen/MemoryOverlap.h>
#include <torch/library.h>
#include <ATen/Operators.h>
#include <ATen/NativeFunctions.h>
#include "torch_npu/csrc/aten/CustomFunctions.h"
#include "torch_npu/csrc/core/npu/NPUException.h"
namespace at_npu {
namespace functionalization {
// This keyset is used by functionalization when it calls into meta kernels
// to accurately propagate stride metadata.
// Exclude any modes: the purpose of calling into meta kernels is only as an implementation
// detail to perform shape inference, and we don't want any modal keys to run.
// Specifically, we want to prevent functionalization and Python modes from running.
constexpr auto exclude_keys_for_meta_dispatch =
c10::functorch_transforms_ks |
c10::DispatchKeySet({
c10::DispatchKey::FuncTorchDynamicLayerBackMode,
c10::DispatchKey::FuncTorchDynamicLayerFrontMode,
c10::DispatchKey::Python
});
// Helper around at::has_internal_overlap.
// The ATen util is used in hot-path eager mode: it's always fast,
// but might return TOO_HARD sometimes.
// During functionalization, we're ok taking a bit longer
// to detect memory overlap.
inline bool has_internal_overlap_helper(const at::Tensor t)
{
auto has_overlap = at::has_internal_overlap(t);
if (has_overlap == at::MemOverlap::Yes) {
return true;
}
if (has_overlap == at::MemOverlap::No) {
return false;
}
return false;
}
inline at::Tensor to_meta(const at::Tensor& t)
{
if (!t.defined()) return t;
return at::native::empty_strided_meta_symint(t.sym_sizes(), t.sym_strides(),
c10::make_optional(t.scalar_type()) /* dtype */, c10::make_optional(t.layout() /* layout */),
c10::make_optional(c10::Device(at::kMeta)) /* device */, c10::nullopt /* pin_memory */);
}
inline c10::optional<at::Tensor> to_meta(const c10::optional<at::Tensor>& t)
{
if (t.has_value()) {
return c10::make_optional<at::Tensor>(to_meta(*t));
}
return c10::nullopt;
}
inline std::vector<at::Tensor> to_meta(at::ITensorListRef t_list)
{
std::vector<at::Tensor> outputs;
outputs.reserve(t_list.size());
for (const auto& tensor : t_list) {
outputs.push_back(to_meta(tensor));
}
return outputs;
}
inline c10::List<at::Tensor> to_meta(const c10::List<at::Tensor>& t_list)
{
c10::List<at::Tensor> outputs;
outputs.reserve(t_list.size());
for (const auto i : c10::irange(t_list.size())) {
outputs.push_back(to_meta(t_list[i]));
}
return outputs;
}
inline c10::List<c10::optional<at::Tensor>> to_meta(const c10::List<c10::optional<at::Tensor>>& t_list)
{
c10::List<c10::optional<at::Tensor>> outputs;
outputs.reserve(t_list.size());
for (const auto i : c10::irange(t_list.size())) {
outputs.push_back(to_meta(t_list[i]));
}
return outputs;
}
${func_definitions}
} // namespace functionalization
namespace {
TORCH_LIBRARY_IMPL(npu, Functionalize, m) {
${func_registrations};
}
} // namespace
} // namespace at_npu
-6
View File
@@ -1,6 +0,0 @@
import warnings
import torch
import torch_npu
${custom_ops}
-48
View File
@@ -1,48 +0,0 @@
import unittest
from collections import defaultdict
import torch
from torch.testing._internal.common_methods_invocations import op_db, python_ref_db
from torch.testing._internal.opinfo.core import DecorateInfo
"""
strategy: Due to the restriction of NPU operators.
patch the data classes to avoid unsupported cases.
"""
skip_list = {${skip_detail}}
def update_skip_list():
for item in op_db:
op_name = item.name
if op_name in skip_list:
if isinstance(item.skips, tuple):
new_skips = tuple(skip_list[op_name]) + item.skips
elif isinstance(item.skips, list):
new_skips = skip_list[op_name] + item.skips
else:
new_skips = tuple(skip_list[op_name])
item.skips = new_skips
for item in python_ref_db:
op_name = item.name
if op_name in skip_list:
if isinstance(item.skips, tuple):
new_skips = tuple(skip_list[op_name]) + item.skips
elif isinstance(item.skips, list):
new_skips = skip_list[op_name] + item.skips
else:
new_skips = tuple(skip_list[op_name])
item.skips = new_skips
def get_decorators(self, test_class, test_name, device, dtype, param_kwargs):
self.decorators = (*self.decorators, *self.skips)
result = []
for decorator in self.decorators:
if isinstance(decorator, DecorateInfo):
if decorator.is_active(test_class, test_name, device, dtype, param_kwargs):
result.extend(decorator.decorators)
else:
result.append(decorator)
return result
-813
View File
@@ -1,813 +0,0 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import stat
import traceback
import warnings
import itertools
from typing import List, Optional, Set, Dict, Union, Sequence, Iterator, Tuple
from collections import defaultdict
from dataclasses import dataclass
import yaml
from torchgen.api.types.signatures import NativeSignature, DispatcherSignature
from torchgen.context import native_function_manager
from torchgen.code_template import CodeTemplate
from torchgen.model import (
Arguments,
BackendIndex,
BackendMetadata,
DispatchKey,
is_cuda_dispatch_key,
NativeFunction,
NativeFunctionsGroup,
FunctionSchema,
OperatorName,
TensorOptionsArguments,
SchemaKind,
DeviceCheckType,
Argument,
)
from torchgen.native_function_generation import pre_group_native_functions
from torchgen.utils import concatMap
from torchgen.api import cpp
from torchgen.api.translate import translate
from torchgen.api.types import Binding, CppSignatureGroup, kernel_signature
from torchgen.utils import Target
from torchgen.dest.register_dispatch_key import RegisterDispatchKey
GLOBAL_STRUCTURED_OP_INFO_CACHE = defaultdict(str)
GLOBAL_OPAPI_INFO_CACHE = set()
GLOBAL_INTERNAL_FORMAT_OPAPI_INFO_CACHE = set()
CUSTOM_YAML_NAME = "npu_native_functions_by_codegen.yaml"
FIELDS_TO_USE = ["func", "tags", "dispatch", "device_check"]
DEVICE_NOCHECK_SET = set()
DEVICE_CHECK_NOTSUPPORT_TYPE = {"Tensor[]?"}
class PathManager:
@classmethod
def check_path_owner_consistent(cls, path: str):
"""
Function Description:
check whether the path belong to process owner
Parameter:
path: the path to check
Exception Description:
when invalid path, prompt the user
"""
if not os.path.exists(path):
msg = f"The path does not exist: {path}"
raise RuntimeError(msg)
if os.stat(path).st_uid != os.getuid():
warnings.warn(f"Warning: The {path} owner does not match the current user.")
@classmethod
def check_directory_path_readable(cls, path):
"""
Function Description:
check whether the path is writable
Parameter:
path: the path to check
Exception Description:
when invalid data throw exception
"""
cls.check_path_owner_consistent(path)
if os.path.islink(path):
msg = f"Invalid path is a soft chain: {path}"
raise RuntimeError(msg)
if not os.access(path, os.R_OK):
msg = f"The path permission check failed: {path}"
raise RuntimeError(msg)
@classmethod
def remove_path_safety(cls, path: str):
if os.path.islink(path):
raise RuntimeError(f"Invalid path is a soft chain: {path}")
if os.path.exists(path):
os.remove(path)
def parse_npu_yaml(custom_path: str) -> Dict:
if not os.path.exists(custom_path):
return {}
from io import StringIO
f_str = StringIO()
PathManager.check_directory_path_readable(custom_path)
with open(custom_path, 'r') as f:
for line in f:
if ':' not in line:
continue
f_str.write(line)
f_str.seek(0)
source_es = yaml.safe_load(f_str)
return source_es
def merge_yaml(base_data, additional_data):
"""Merge two YAML data structures. If there's a conflict, the base data will take precedence."""
map_dict = {"official": "supported"}
def key_map(x):
if x in map_dict:
return map_dict[x]
else:
return x
if isinstance(base_data, dict):
for key, value in additional_data.items():
if key_map(key) not in base_data:
base_data[key_map(key)] = value
else:
base_data[key_map(key)] = merge_yaml(base_data[key_map(key)], value)
elif isinstance(base_data, list):
for item in additional_data:
if item not in base_data:
base_data.append(item)
return base_data
def merge_custom_yaml(pta_path, op_plugin_path):
PathManager.check_directory_path_readable(pta_path)
with open(pta_path, 'r') as pta_file:
pta_es = yaml.safe_load(pta_file)
PathManager.check_directory_path_readable(op_plugin_path)
with open(op_plugin_path, 'r') as op_plugin_file:
op_es = yaml.safe_load(op_plugin_file)
merged_yaml = merge_yaml(pta_es, op_es)
merged_yaml_path = gen_custom_yaml_path(pta_path)
PathManager.remove_path_safety(merged_yaml_path)
with os.fdopen(os.open(merged_yaml_path, os.O_RDWR | os.O_CREAT, stat.S_IWUSR | stat.S_IRUSR), "w") as outfile:
yaml.dump(merged_yaml, outfile, default_flow_style=False, width=float("inf"))
os.chmod(merged_yaml_path, stat.S_IRUSR | stat.S_IEXEC | stat.S_IRGRP | stat.S_IXGRP)
return merged_yaml
def field_tag(custom_es):
for i, es in enumerate(custom_es):
if not isinstance(es, dict):
continue
custom_es[i] = {key: custom_es[i][key] for key in FIELDS_TO_USE if key in custom_es[i]}
return custom_es
def filt_exposed_api(custom_path: str):
source_es = parse_npu_yaml(custom_path)
custom_es = source_es.get('custom', []) + source_es.get('custom_autograd', [])
exposed_set = set()
for es in custom_es:
if es.get('exposed', False):
exposed_set.add(es.get('func').split('(')[0].split('.')[0])
return list(exposed_set)
def rename_privateuse1_dispatch_key():
# rename DispatcherKey about PrivateUse1
custom_backend = "NPU"
def PrivateUse1Str(self):
return self.name.replace("PrivateUse1", custom_backend)
@staticmethod
def parse(value: str) -> "DispatchKey":
for k, v in DispatchKey.__members__.items():
if k == value.replace(custom_backend, "PrivateUse1"):
return v
raise AssertionError(f"unknown dispatch key {value}")
DispatchKey.__str__ = PrivateUse1Str
DispatchKey.parse = parse
def get_torchgen_dir():
# get path of torchgen, then get tags.yaml and native_functions.yaml
try:
import torchgen
return os.path.dirname(os.path.realpath(torchgen.__file__))
except Exception:
_, _, exc_traceback = sys.exc_info()
frame_summary = traceback.extract_tb(exc_traceback)[-1]
return os.path.dirname(frame_summary.filename)
def gen_op_hook_post_code(sig: Union[NativeSignature, DispatcherSignature]) -> Tuple[str, str]:
res_code: str = None
return_code: str = None
if sig.returns_type().cpp_type() == "void":
res_code = ""
return_code = f"""at_npu::native::OpHook::GetInstance().PostHook();
return;"""
else:
res_code = f"""{sig.returns_type().cpp_type()} res = """
return_code = f"""at_npu::native::OpHook::GetInstance().PostHook(res);
return res;"""
return res_code, return_code
# This function is to add profiler information for each operator, which is later extended in the official
def gen_unstructured(
self, f: NativeFunction, g: Optional[NativeFunctionsGroup] = None
) -> Optional[str]:
with native_function_manager(f):
inplace_meta = False
gets_out_inplace_wrapper = False
if not self.backend_index.has_kernel(f):
return None
if f.manual_kernel_registration:
return None
if (
self.target is Target.REGISTRATION
and not self.selector.is_native_function_selected(f)
):
return None
sig = self.wrapper_kernel_sig(f)
name = sig.name()
returns_type = sig.returns_type().cpp_type()
args = sig.arguments()
args_str = ", ".join(a.defn() for a in args)
op_name = str(f.func.name.name)
force_aclnn = f"at_npu::native::ForceAclnn::GetInstance().IsForceAclnnOp(\"{op_name}\")"
# See Note [Direct dispatch bindings]
cpp_sig_group = CppSignatureGroup.from_native_function(
f, method=False, fallback_binding=False
)
if self.target is Target.NAMESPACED_DECLARATION:
result = ""
for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
result += f"TORCH_API {cpp_sig.decl()};\n"
return result
elif self.target is Target.NAMESPACED_DEFINITION:
def generate_defn(cpp_sig: CppSignature) -> str:
return f"""
{cpp_sig.defn()} {{
return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), sig.arguments()))});
}}
"""
result = ""
for cpp_sig in cpp_sig_group.signatures(symint=self.symint):
result += generate_defn(cpp_sig)
return result
elif self.target is Target.ANONYMOUS_DEFINITION:
# short circuit for inplace_meta
if inplace_meta:
if f.func.arguments.self_arg is None:
raise ValueError("f.func.arguments.self_arg is None")
self_arg_name = f.func.arguments.self_arg.argument.name
return f"""
{returns_type} {name}({args_str}) {{
TORCH_CHECK_NOT_IMPLEMENTED({self_arg_name}.is_meta(),
"Cannot inplace into non-meta tensor with meta tensor argument", OPS_ERROR(ErrCode::NOT_SUPPORT));
return {self_arg_name};
}}
"""
# short circuit for generated inplace/out wrappers
if gets_out_inplace_wrapper:
return self.gen_out_inplace_wrapper(f, g)
metadata = self.backend_index.get_kernel(f)
if metadata is None:
return None
if self.class_method_name is None:
impl_name = f"{metadata.cpp_namespace}::{metadata.kernel}"
else:
impl_name = f"{metadata.cpp_namespace}::{self.class_method_name}::{metadata.kernel}"
kernel_sig = kernel_signature(f, self.backend_index)
args_exprs_str = ", ".join(
e.expr
for e in translate(
sig.arguments(), kernel_sig.arguments(), method=False
)
)
device_check = " // No device check\n"
# Backends that require device guards presumably also require device checks.
if self.backend_index.device_guard and str(f.func.name) not in DEVICE_NOCHECK_SET:
device_check_args = itertools.chain(
f.func.arguments.out, f.func.arguments.flat_positional
)
device_check = RegisterDispatchKey.gen_device_check(
f.device_check, list(device_check_args), name
)
device_guard = "// DeviceGuard omitted" # default
record_func_def = """
#ifndef BUILD_LIBTORCH
torch_npu::profiler::NPURecordFunction guard;
#endif
"""
unsafe_tensor_check = """ // No data check"""
if self.backend_index.device_guard:
has_tensor_options = any(
isinstance(a, TensorOptionsArguments)
for a in f.func.arguments.non_out
)
# There is precedence for which argument we use to do
# device guard. This describes the precedence order.
self_arg = (
[f.func.arguments.self_arg.argument]
if f.func.arguments.self_arg is not None
else []
)
candidate_args = itertools.chain(
self_arg,
f.func.arguments.out,
f.func.arguments.flat_positional,
)
candidate_tensor_args = []
for a in candidate_args:
if a.type.is_tensor_like():
candidate_tensor_args.append(f"{a.name}")
candidate_tensor_args = list(set(candidate_tensor_args))
unsafe_tensor_check = """// No data check."""
if len(candidate_tensor_args) > 0:
unsafe_tensor_check = """
if (c10_npu::get_npu_data_unsafe_flag()) {"""
if name in ["wrapper_NPU__copy_", "wrapper_NPU___foreach_copy_"]:
tensor_arg = candidate_tensor_args[0] + ", " +\
candidate_tensor_args[1]
unsafe_tensor_check = unsafe_tensor_check + f"""
c10_npu::check_and_update_npu_tensor_for_copy(self, src);"""
else:
for tensor_arg in candidate_tensor_args:
unsafe_tensor_check = unsafe_tensor_check + f"""
c10_npu::check_npu_tensor_is_safe({tensor_arg});"""
if len(candidate_tensor_args) > 0:
unsafe_tensor_check = unsafe_tensor_check + """
}
"""
candidate_args = itertools.chain(
self_arg,
f.func.arguments.out,
f.func.arguments.flat_positional,
)
# Only tensor like arguments are eligible
device_of = next(
(
f"{a.name}"
for a in candidate_args
if a.type.is_tensor_like()
),
None,
)
if has_tensor_options and device_of is not None:
device_guard = f"""
OptionalDeviceGuard device_guard(device_of({device_of}));
if (device.has_value()) {{
device_guard.reset_device(device_or_default(device));
}}
"""
elif has_tensor_options:
# kernel is creating a tensor
device_guard = """
const DeviceGuard device_guard(device_or_default(device));"""
elif device_of is not None:
# kernel is operating on existing tensors
device_guard = f"const OptionalDeviceGuard device_guard(device_of({device_of}));"
op_key = str(f.func.name)
is_aclnn_only = "c10_npu::IsAclnnOnly()"
if enable_opplugin():
if op_key in GLOBAL_STRUCTURED_OP_INFO_CACHE:
impl_name = f"op_plugin::{GLOBAL_STRUCTURED_OP_INFO_CACHE[op_key]}"
# for op_hook_check
res_of_op_hook_post_code, return_of_op_hook_post_code = gen_op_hook_post_code(sig)
args_exprs_str_list = [
e.expr
for e in translate(
sig.arguments(), kernel_sig.arguments(), method=False
)
]
lvalue_ref_list = ["C10_AS_INTARRAYREF_SLOW", "expect_int", "guard_int"]
auto_lvalue = ""
for idx, args_expr in enumerate(args_exprs_str_list):
if any(lvalue_ref in args_expr for lvalue_ref in lvalue_ref_list):
auto_lvalue += f"""
auto {kernel_sig.arguments()[idx].name}_tmp = {args_expr};"""
args_exprs_str_list[idx] = f"""{kernel_sig.arguments()[idx].name}_tmp"""
args_exprs_str_for_op_hook = ", ".join(e for e in args_exprs_str_list)
op_hook_blacklist = ["is_pinned", "_pin_memory"]
op_hook_check = ""
if is_opapi(op_key) and not is_op_valid(op_key):
op_api_impl_name = f"{metadata.cpp_namespace}::NPUNativeOpApiFunctions::{metadata.kernel}"
tensor_check_str = ""
tensor_check_list = []
for a in args:
if a.argument.type.is_tensor_like():
tensor_check_list.append(f"at_npu::native::FormatHelper::IsOpInputBaseFormat({a.name})")
if tensor_check_list:
tensor_check_str = f" && {' && '.join(tensor_check_list)}"
if self.backend_index.dispatch_key is DispatchKey.PrivateUse1:
if op_key not in op_hook_blacklist:
if not is_opapi_support_internal_format(op_key):
op_hook_check += f"""\
if (C10_UNLIKELY(at_npu::native::env::CheckOpHookEnable())) {{
{auto_lvalue}
at_npu::native::OpHook::GetInstance().PreHook(\"{op_key}\", {args_exprs_str_for_op_hook});
if (({force_aclnn} || at_npu::native::env::CheckJitDisable()){tensor_check_str}) {{
{res_of_op_hook_post_code}{op_api_impl_name}({args_exprs_str_for_op_hook});
{return_of_op_hook_post_code}
}} else {{
{res_of_op_hook_post_code}{impl_name}({args_exprs_str_for_op_hook});
{return_of_op_hook_post_code}
}}
}}
"""
else:
op_hook_check += f"""\
if (C10_UNLIKELY(at_npu::native::env::CheckOpHookEnable())) {{
{auto_lvalue}
at_npu::native::OpHook::GetInstance().PreHook(\"{op_key}\", {args_exprs_str_for_op_hook});
if (({force_aclnn} || at_npu::native::env::CheckJitDisable())) {{
{res_of_op_hook_post_code}{op_api_impl_name}({args_exprs_str_for_op_hook});
{return_of_op_hook_post_code}
}} else {{
{res_of_op_hook_post_code}{impl_name}({args_exprs_str_for_op_hook});
{return_of_op_hook_post_code}
}}
}}
"""
if not is_opapi_support_internal_format(op_key):
return_code = f"""\
if (({force_aclnn} || at_npu::native::env::CheckJitDisable()){tensor_check_str}) {{
return {op_api_impl_name}({args_exprs_str});
}} else {{
if ({is_aclnn_only}) {{
TORCH_CHECK(false,
"Current device only support aclnn operator, and current operator {impl_name} do not support internal format.",
PTA_ERROR(ErrCode::NOT_SUPPORT));
}}
return {impl_name}({args_exprs_str});
}}
"""
else:
return_code = f"""\
if (({force_aclnn} || at_npu::native::env::CheckJitDisable())) {{
return {op_api_impl_name}({args_exprs_str});
}} else {{
return {impl_name}({args_exprs_str});
}}
"""
else:
if self.backend_index.dispatch_key is DispatchKey.PrivateUse1:
if op_key not in op_hook_blacklist:
op_hook_check += f"""\
if (C10_UNLIKELY(at_npu::native::env::CheckOpHookEnable())) {{
{auto_lvalue}
at_npu::native::OpHook::GetInstance().PreHook(\"{op_key}\", {args_exprs_str_for_op_hook});
{res_of_op_hook_post_code}{impl_name}({args_exprs_str_for_op_hook});
{return_of_op_hook_post_code}
}}
"""
return_code = f"""\
return {impl_name}({args_exprs_str});
"""
return f"""\
namespace {{
{returns_type} {name}({args_str}) {{
{device_check}
{unsafe_tensor_check}
{device_guard}
{record_func_def}
{op_hook_check}
{return_code}
}}
}} // anonymous namespace
"""
elif self.target is Target.REGISTRATION:
if f.manual_kernel_registration or self.skip_dispatcher_op_registration:
return None
else:
payload = f"TORCH_FN({name})"
return f'm.impl("{f.func.name}",\n{payload});\n'
else:
assert_never(self.target)
def gen_device_check(
type: DeviceCheckType, args: List[Argument], method_name: str
) -> str:
if type == DeviceCheckType.NoCheck:
return " // No device check\n"
device_check = "c10::optional<at::Device> common_device = at::nullopt;\n"
device_check += "(void)common_device; // Suppress unused variable warning\n"
for arg in args:
# Only tensor like arguments are eligible
if arg.type.is_tensor_like() and str(arg.type) not in DEVICE_CHECK_NOTSUPPORT_TYPE:
device_check += \
f"""c10::impl::check_and_update_common_device(common_device, {arg.name}, "{method_name}", "{arg.name}");\n"""
return device_check
def arguments(
arguments: Arguments,
*,
faithful: bool,
symint: bool = False,
method: bool,
cpp_no_default_args: Set[str],
) -> List[Binding]:
args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
args.extend(arguments.non_out)
args.extend(arguments.out)
result = []
for a in args:
for r in cpp.argument(
a,
faithful=faithful,
symint=symint,
method=method,
has_tensor_options=arguments.tensor_options is not None,
cpp_no_default_args=cpp_no_default_args,
):
if faithful:
result.append(r.no_default())
else:
result.append(r)
return result
def add_header_to_template_file():
torchgen_path = get_torchgen_dir()
template_dir = os.path.join(torchgen_path, "packaged/ATen/templates/DispatchKeyNativeFunctions.h")
PathManager.check_directory_path_readable(template_dir)
with open(template_dir, "r") as file:
template_content = file.read()
if "#include <ATen/ATen.h>" not in template_content:
template_content = template_content.replace("#include <ATen/Tensor.h>",
"#include <ATen/Tensor.h>\n#include <ATen/ATen.h>")
with os.fdopen(os.open(template_dir, os.O_WRONLY, stat.S_IWUSR | stat.S_IRUSR), "w") as file:
file.write(template_content)
def enable_opplugin() -> bool:
# enable op_plugin, if path of third_party/op-plugin is valid.
base_dir = os.path.dirname(os.path.realpath(__file__))
op_plugin_path = os.path.join(base_dir, '../third_party/op-plugin/op_plugin')
return os.path.exists(op_plugin_path)
def is_op_valid(op_key: str) -> bool:
return True if op_key in GLOBAL_STRUCTURED_OP_INFO_CACHE else False
def get_opplugin_wrap_name(func) -> str:
op_key = str(func.func.name) if type(func) is NativeFunction else func
return GLOBAL_STRUCTURED_OP_INFO_CACHE.get(op_key, None)
def gen_custom_yaml_path(original_path, codegen_yaml_filename=CUSTOM_YAML_NAME):
new_path = os.path.join(os.path.dirname(original_path), codegen_yaml_filename)
return new_path
def update_opapi_info(op_info):
global GLOBAL_OPAPI_INFO_CACHE
if isinstance(op_info, str):
return
elif isinstance(op_info, dict):
if op_info.get("op_api", False):
GLOBAL_OPAPI_INFO_CACHE.add(op_info.get("func").split("(")[0])
else:
print(f"Warning: Unsupported parameter types, only str and dict is supported, but input is {type(op_info)}")
def is_opapi(op_key):
global GLOBAL_OPAPI_INFO_CACHE
return op_key in GLOBAL_OPAPI_INFO_CACHE
def update_internal_format_opapi_info(op_info):
global GLOBAL_INTERNAL_FORMAT_OPAPI_INFO_CACHE
if isinstance(op_info, str):
return
elif isinstance(op_info, dict):
if op_info.get("internal_format_opapi", False):
GLOBAL_INTERNAL_FORMAT_OPAPI_INFO_CACHE.add(op_info.get("func").split("(")[0])
else:
print(f"Warning: Unsupported parameter types, only str and dict is supported, but input is {type(op_info)}")
def is_opapi_support_internal_format(op_key):
global GLOBAL_INTERNAL_FORMAT_OPAPI_INFO_CACHE
return op_key in GLOBAL_INTERNAL_FORMAT_OPAPI_INFO_CACHE
def get_target_functions(yaml_path: str, target_op_type: str = None) -> List:
source_es = parse_npu_yaml(yaml_path)
custom = source_es.pop('custom', [])
if custom is None:
custom = [] # Allow an empty list of supported ops
official = source_es.pop('official', [])
if official is None:
official = [] # Allow an empty list of supported ops
support_ops = custom + official
symint = source_es.pop("symint", [])
if symint is None:
symint = []
symint = [op['func'] if isinstance(op, Dict) else op for op in symint]
symint_set = set([str(FunctionSchema.parse(op).name) for op in symint])
global GLOBAL_STRUCTURED_OP_INFO_CACHE
GLOBAL_STRUCTURED_OP_INFO_CACHE.clear()
target_funcs = []
for op in support_ops:
funcs = op.get("func", None)
if not isinstance(funcs, str):
raise TypeError(f'not a str : {funcs}')
func = FunctionSchema.parse(funcs)
wrap_name = cpp.name(func)
op_key = str(func.name)
if op_key in symint_set:
wrap_name += "_symint"
if target_op_type is not None:
if target_op_type not in op.keys():
continue
wrap_name += "_" + target_op_type
cur_wrap_name = GLOBAL_STRUCTURED_OP_INFO_CACHE.get(op_key, "")
if cur_wrap_name and cur_wrap_name != wrap_name:
print(f"Find different wrap_name for {cur_wrap_name} and {wrap_name} between pta and opplugin, ",
f"with {wrap_name} being used as the actual wrap_name")
GLOBAL_STRUCTURED_OP_INFO_CACHE[op_key] = wrap_name
target_funcs.append(func)
return target_funcs
def get_target_native_registration(
dispatch_key: DispatchKey,
backend_indices: Dict[DispatchKey, BackendIndex],
metadata: Dict[OperatorName, BackendMetadata],
native_functions: List[NativeFunction],
):
if native_functions is None:
return ""
cpu_dispatch_key = DispatchKey.parse(dispatch_key.name.replace("PrivateUse1", "CPU"))
cpu_backend_indices = backend_indices[cpu_dispatch_key]
cuda_dispatch_key = DispatchKey.parse(dispatch_key.name.replace("PrivateUse1", "CUDA"))
cuda_backend_indices = backend_indices[cuda_dispatch_key]
target_native_functions_kernels = {}
for op_name in cpu_backend_indices.index.keys():
if cpu_backend_indices.index[op_name].kernel == cuda_backend_indices.index[op_name].kernel \
and op_name not in metadata.keys():
target_native_functions_kernels[op_name] = cpu_backend_indices.index[op_name].kernel
target_native_functions = []
for f in native_functions:
if f.func.name in target_native_functions_kernels.keys():
target_native_functions.append(f)
native_functions_registration_template = CodeTemplate(
"""\
namespace {
${dispatch_helpers}
TORCH_LIBRARY_IMPL(aten, ${dispatch_key}, m) {
${native_kernels}
}
}
""")
def wrap_native_function(f):
kernel_name = target_native_functions_kernels[f.func.name]
wrap_func_name = f"wrap_{dispatch_key}_{str(f.func.name.name)}_{f.func.name.overload_name}"
with native_function_manager(f):
sig = NativeSignature(f.func, prefix='', symint=kernel_name.endswith('symint'))
args_exprs_str = ', '.join(a.name for a in sig.arguments())
return f"""{sig.decl(name=wrap_func_name)} {{
return at::native::{kernel_name}({args_exprs_str});
}}
"""
def register_wrap_native_function(f):
wrap_func_name = f"wrap_{dispatch_key}_{str(f.func.name.name)}_{f.func.name.overload_name}"
return f"m.impl(\"{f.func.name}\", TORCH_FN({wrap_func_name}));"
return native_functions_registration_template.substitute(
dispatch_helpers=[wrap_native_function(f) for f in target_native_functions],
dispatch_key=dispatch_key.name,
native_kernels=[register_wrap_native_function(f) for f in target_native_functions]
)
# A structured kernel is guaranteed to have a functional, optionally out variant and
# optionally an inplace variant.
@dataclass(frozen=True)
class NativeFunctionsGroupOptionalOut:
functional: NativeFunction
inplace: Optional[NativeFunction]
mutable: Optional[NativeFunction]
out: Optional[NativeFunction]
@property
def root_name(self) -> str:
return self.functional.root_name
def functions(self) -> Iterator[NativeFunction]:
yield self.functional
if self.out is not None:
yield self.out
if self.inplace is not None:
yield self.inplace
if self.mutable is not None:
yield self.mutable
@staticmethod
def from_dict(
d: Dict[SchemaKind, NativeFunction]
) -> Optional["NativeFunctionsGroupOptionalOut"]:
if len(d) == 0:
raise RuntimeError('The variable d is empty')
if len(d) == 1:
return None
d = dict(d) # non-destructive updates please
functional = d.pop(SchemaKind.functional, None)
inplace = d.pop(SchemaKind.inplace, None)
mutable = d.pop(SchemaKind.mutable, None)
out = d.pop(SchemaKind.out, None)
if len(d) != 0:
raise RuntimeError('The variable d is not empty after popping keys')
if functional is None:
raise RuntimeError('The variable functional is None')
return NativeFunctionsGroupOptionalOut(
functional=functional,
inplace=inplace,
mutable=mutable,
out=out,
)
def get_grouped_native_functions_optional_out(
native_functions: Sequence[NativeFunction],
) -> Sequence[Union[NativeFunction, NativeFunctionsGroupOptionalOut]]:
def flatten_pre_group(
d: Dict[SchemaKind, NativeFunction]
) -> Sequence[Union[NativeFunction, NativeFunctionsGroupOptionalOut]]:
r = NativeFunctionsGroupOptionalOut.from_dict(d)
if r is None:
# Invariant: any NativeFunctions that are code-generated
# should have been grouped into NativeFunctionsGroupOptionalOut objects
if any("generated" in f.tags for f in d.values()):
raise RuntimeError("The variable d contains 'generated' in function tags")
return list(d.values())
else:
return [r]
pre_grouped_native_functions = pre_group_native_functions(native_functions)
return list(
concatMap(flatten_pre_group, list(pre_grouped_native_functions.values()))
)
-728
View File
@@ -1,728 +0,0 @@
# FrameworkPTAdapter 3.0.RC2 Release Notes
- [FrameworkPTAdapter 3.0.RC2 Release Notes](#frameworkptadapter-30rc2-release-notes)
- [FrameworkPTAdapter 3.0.RC2](#frameworkptadapter-30rc2)
- [Before You Start](#before-you-start)
- [New Features](#new-features)
- [Modified Features](#modified-features)
- [Resolved Issues](#resolved-issues)
- [Known Issues](#known-issues)
- [Compatibility](#compatibility)
- [FrameworkPTAdapter 3.0.RC1](#frameworkptadapter-30rc1)
- [Before You Start](#before-you-start-1)
- [New Features](#new-features-1)
- [Modified Features](#modified-features-1)
- [Resolved Issues](#resolved-issues-1)
- [Known Issues](#known-issues-1)
- [Compatibility](#compatibility-1)
- [FrameworkPTAdapter 2.0.4](#frameworkptadapter-204)
- [Before You Start](#before-you-start-2)
- [New Features](#new-features-2)
- [Modified Features](#modified-features-2)
- [Resolved Issues](#resolved-issues-2)
- [Known Issues](#known-issues-2)
- [Compatibility](#compatibility-2)
- [FrameworkPTAdapter 2.0.3](#frameworkptadapter-203)
- [Before You Start](#before-you-start-3)
- [New Features](#new-features-3)
- [Modified Features](#modified-features-3)
- [Resolved Issues](#resolved-issues-3)
- [Known Issues](#known-issues-3)
- [Compatibility](#compatibility-3)
- [FrameworkPTAdapter 2.0.2](#frameworkptadapter-202)
- [Before You Start](#before-you-start-4)
- [New Features](#new-features-4)
- [Modified Features](#modified-features-4)
- [Resolved Issues](#resolved-issues-4)
- [Known Issues](#known-issues-4)
- [Compatibility](#compatibility-4)
## FrameworkPTAdapter 3.0.RC2
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 and 1.8.1 developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
PyTorch 1.8.1 uses plug-in adaptation and is completely decoupled from the native PyTorch framework. The current functions and performance of PyTorch 1.8.1 are basically the same as those of PyTorch 1.5.0, providing good development experience for backend operator adaptation.
AOE-based tuning is supported.
### New Features
**Table 1** Features supported by PyTorch
<a name="t76c34275cbb74753970f7c5a9eb594fa"></a>
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.5.0 features adapted to NPUs</p>
</td>
</tr>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> Fixed a few bugs.</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="3" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.8.1 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Decoupled as plugins</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Decoupled the torch_npu plugin from the native PyTorch framework completely.</p>
</td>
<tr>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Performance optimization</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Optimized the single-operator delivery and collective communication functions.</p>
</td>
</tr>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>API satisfaction</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Added more APIs. (For details, see the API list.)</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Description</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization of CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04/2.04, BC-Linux 7.6, Debian 9.9, Debian 10, openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6, Ubuntu 18.04/2.04, EulerOS 2.8/2.10, Kylin V10, BC-Linux 7.6, openEuler 20.03 LTS, UOS 20 1020e
## FrameworkPTAdapter 3.0.RC1
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 and 1.8.1 developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
PyTorch 1.8.1 adopts the plugin adaptation mode and inherits the features of PyTorch 1.5.0. Their functions are basically the same, but PyTorch 1.8.1 provides better development experience for backend operator adaptation. It supports AOE-based tuning.
### New Features
**Table 1** Features supported by PyTorch
<a name="t76c34275cbb74753970f7c5a9eb594fa"></a>
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.5.0 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>AOE-based tuning</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported the AOE auto tuning tool to improve the model performance.</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> Added the function of adapted operator development. For details, see the API list.</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="3" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.8.1 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Plugin decoupling</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Decoupled the NPU-adapted code and ported it to the **torch_npu** plugin to decouple the Ascend-adapted code from the native PyTorch code.</p>
</td>
<tr>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>AOE-based tuning</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported the AOE auto tuning tool to improve the model performance.</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>Improvement of framework API satisfaction</p>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Supported APIs that have been adapted to Ascend PyTorch 1.5.0. For details, see the API list.</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Symptom</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type.</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization of CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04/2.04, BC-Linux 7.6, Debian 9.9, Debian 10, openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6, Ubuntu 18.04/2.04, EulerOS 2.8/2.10, Kylin V10, BC-Linux 7.6, openEuler 20.03 LTS, UOS 20 1020e
## FrameworkPTAdapter 2.0.4
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 and 1.8.1 developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
PyTorch 1.8.1 inherits the features of PyTorch 1.5.0. Their functions are basically the same, but PyTorch 1.8.1 provides better development experience for backend operator adaptation. Currently, PyTorch 1.8.1 supports only the ResNet-50 network model.
### New Features
**Table 1** Features supported by PyTorch
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row7979351559"><td class="cellrowborder" rowspan="3" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.5.0 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Optimization of Model Accuracy Analyzer</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported mapping between IR and TBE operators and enabled the NPU dump data to be loaded to the GPU side for comparison.</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>E2E prof</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Integrated the profile data obtained by the native PyTorch Profiling tool and CANN prof tool to implement end-to-end model and operator performance analysis.</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>Added the function of adapted operator development. For details, see the operator list.</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.8.1 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>AMP</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported the native training with automatic mixed precision (AMP) of PyTorch.</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>Profiling</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Supported the native profiling function of PyTorch.</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>OS compatibility</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>OS compatibility</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported Ubuntu 20.04 (x86 and ARM) and EulerOS 2.10 (ARM).</p>
</td>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Python version compatibility</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>Supported compilation and use of Python 3.9 (only in PyTorch 1.8.1).</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Description</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type.</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization of CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04/2.04, BC-Linux 7.6, Debian 9.9, Debian 10, openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6, Ubuntu 18.04/2.04, EulerOS 2.8/2.10, Kylin V10, BC-Linux 7.6, openEuler 20.03 LTS, UOS 20 1020e
## FrameworkPTAdapter 2.0.3
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
PyTorch 1.8.1 is supported by this version and later, and this version inherits the features of PyTorch 1.5.0 and provides the same functions, except for the Profiling tool. In addition, it optimizes the backend operator adaptation. Currently, PyTorch 1.8.1 supports only the ResNet-50 network model.
### New Features
**Table 1** Features supported by PyTorch
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row7979351559"><td class="cellrowborder" rowspan="5" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>PyTorch 1.8.1</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Added PyTorch 1.8.1. Currently, only the ResNet-50 network is supported, including the training scenario for distributed data parallel (DDP).</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>Python 3.8</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Supported compilation and use of Python 3.8.</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Operator overflow/underflow detection tool</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>Supported IR-level operator overflow/underflow detection in the PyTorch framework. When an AI Core operator overflow/underflow occurs, the IR information is displayed.</p>
</td>
</tr>
<tr id="row185381431133610"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p953883153611"><a name="p953883153611"></a><a name="p953883153611"></a>OS compatibility</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p13538203153618"><a name="p13538203153618"></a><a name="p13538203153618"></a>Supported UOS 20 1020e ARM.</p>
</td>
</tr>
<tr id="row91681125173610"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p2168172519364"><a name="p2168172519364"></a><a name="p2168172519364"></a>Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1416815259367"><a name="p1416815259367"></a><a name="p1416815259367"></a>Added the function of adapted operator development. For details, see the operator list.</p>
</td>
</tr>
<tr id="row11970351050"><td class="cellrowborder" rowspan="26" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p298314333514"><a name="p298314333514"></a><a name="p298314333514"></a>Model training</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p19984193312511"><a name="p19984193312511"></a><a name="p19984193312511"></a>CenterFace</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p7517351258"><a name="p7517351258"></a><a name="p7517351258"></a>-</p>
</td>
</tr>
<tr id="row9965351254"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1984033458"><a name="p1984033458"></a><a name="p1984033458"></a>PCBU</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p298411338513"><a name="p298411338513"></a><a name="p298411338513"></a>-</p>
</td>
</tr>
<tr id="row14966351959"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p198414331957"><a name="p198414331957"></a><a name="p198414331957"></a>Net++</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1798413331756"><a name="p1798413331756"></a><a name="p1798413331756"></a>-</p>
</td>
</tr>
<tr id="row20966351454"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p4984183317518"><a name="p4984183317518"></a><a name="p4984183317518"></a>FCN8S</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1698453311519"><a name="p1698453311519"></a><a name="p1698453311519"></a>-</p>
</td>
</tr>
<tr id="row19653517518"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1298483319512"><a name="p1298483319512"></a><a name="p1298483319512"></a>OSNetRetinaFace</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1798423312519"><a name="p1798423312519"></a><a name="p1798423312519"></a>-</p>
</td>
</tr>
<tr id="row39619351751"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1298414331513"><a name="p1298414331513"></a><a name="p1298414331513"></a>PSPnet</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p10984633254"><a name="p10984633254"></a><a name="p10984633254"></a>-</p>
</td>
</tr>
<tr id="row496335654"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p19984433351"><a name="p19984433351"></a><a name="p19984433351"></a>EDSR</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p898473314517"><a name="p898473314517"></a><a name="p898473314517"></a>-</p>
</td>
</tr>
<tr id="row17953357517"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p14984123312515"><a name="p14984123312515"></a><a name="p14984123312515"></a>Tsm</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p159841033855"><a name="p159841033855"></a><a name="p159841033855"></a>-</p>
</td>
</tr>
<tr id="row16951435551"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p19984933457"><a name="p19984933457"></a><a name="p19984933457"></a>pnasnet5large</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p89846335512"><a name="p89846335512"></a><a name="p89846335512"></a>-</p>
</td>
</tr>
<tr id="row2095113520514"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1798416331952"><a name="p1798416331952"></a><a name="p1798416331952"></a>Gaitset</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p098417336516"><a name="p098417336516"></a><a name="p098417336516"></a>-</p>
</td>
</tr>
<tr id="row89516351511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p11985153312516"><a name="p11985153312516"></a><a name="p11985153312516"></a>fcn</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p169858331155"><a name="p169858331155"></a><a name="p169858331155"></a>-</p>
</td>
</tr>
<tr id="row5953353513"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18985103311514"><a name="p18985103311514"></a><a name="p18985103311514"></a>Albert</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p2098513334519"><a name="p2098513334519"></a><a name="p2098513334519"></a>-</p>
</td>
</tr>
<tr id="row119533516513"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p598511336511"><a name="p598511336511"></a><a name="p598511336511"></a>AdvancedEast</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p119850331513"><a name="p119850331513"></a><a name="p119850331513"></a>-</p>
</td>
</tr>
<tr id="row39511356512"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p698553311512"><a name="p698553311512"></a><a name="p698553311512"></a>ReidStrongBaseline</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1198514331659"><a name="p1198514331659"></a><a name="p1198514331659"></a>-</p>
</td>
</tr>
<tr id="row129463518517"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p99851633158"><a name="p99851633158"></a><a name="p99851633158"></a>Fast-scnn</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1298514331359"><a name="p1298514331359"></a><a name="p1298514331359"></a>-</p>
</td>
</tr>
<tr id="row9942035757"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p109854331151"><a name="p109854331151"></a><a name="p109854331151"></a>RDN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1198583317511"><a name="p1198583317511"></a><a name="p1198583317511"></a>-</p>
</td>
</tr>
<tr id="row79415357517"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p6985833351"><a name="p6985833351"></a><a name="p6985833351"></a>SRFlow</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p29851033350"><a name="p29851033350"></a><a name="p29851033350"></a>-</p>
</td>
</tr>
<tr id="row12947357514"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p149859334518"><a name="p149859334518"></a><a name="p149859334518"></a>MGN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p19851833850"><a name="p19851833850"></a><a name="p19851833850"></a>-</p>
</td>
</tr>
<tr id="row3941735855"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p898533316518"><a name="p898533316518"></a><a name="p898533316518"></a>Roberta</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p998553318518"><a name="p998553318518"></a><a name="p998553318518"></a>-</p>
</td>
</tr>
<tr id="row1093335856"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1985533451"><a name="p1985533451"></a><a name="p1985533451"></a>RegNetY</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p59851033355"><a name="p59851033355"></a><a name="p59851033355"></a>-</p>
</td>
</tr>
<tr id="row49373518516"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p19986173311512"><a name="p19986173311512"></a><a name="p19986173311512"></a>VoVNet-39</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p798683310515"><a name="p798683310515"></a><a name="p798683310515"></a>-</p>
</td>
</tr>
<tr id="row5930351357"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p189862336515"><a name="p189862336515"></a><a name="p189862336515"></a>RegNetX</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1398618331651"><a name="p1398618331651"></a><a name="p1398618331651"></a>-</p>
</td>
</tr>
<tr id="row169312351655"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p149863337513"><a name="p149863337513"></a><a name="p149863337513"></a>RefineNet</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p2098615331959"><a name="p2098615331959"></a><a name="p2098615331959"></a>-</p>
</td>
</tr>
<tr id="row11931235957"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1198616331657"><a name="p1198616331657"></a><a name="p1198616331657"></a>RefineDet</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1698611332518"><a name="p1698611332518"></a><a name="p1698611332518"></a>-</p>
</td>
</tr>
<tr id="row189215359511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p16986183319512"><a name="p16986183319512"></a><a name="p16986183319512"></a>AlignedReID</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1898715331055"><a name="p1898715331055"></a><a name="p1898715331055"></a>-</p>
</td>
</tr>
<tr id="row89213351858"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p119878330511"><a name="p119878330511"></a><a name="p119878330511"></a>FaceBoxes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p129878331158"><a name="p129878331158"></a><a name="p129878331158"></a>-</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Description</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type.</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization of CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04, BC-Linux 7.6, Debian 9.9, Debian 10, openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6, Euler 2.8, Kylin v10, BC-Linux 7.6, openEuler 20.03 LTS, UOS 20 1020e
## FrameworkPTAdapter 2.0.2
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 primarily developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
### New Features
**Table 1** Features supported by PyTorch
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.489999999999998%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.3%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.21%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row171322953713"><td class="cellrowborder" rowspan="7" valign="top" width="10.489999999999998%" headers="mcps1.2.4.1.1 "><p id="p10237517181"><a name="p10237517181"></a><a name="p10237517181"></a>Adapted training models</p>
</td>
<td class="cellrowborder" valign="top" width="26.3%" headers="mcps1.2.4.1.2 "><p id="p6134294377"><a name="p6134294377"></a><a name="p6134294377"></a>YOLOv4</p>
</td>
<td class="cellrowborder" valign="top" width="63.21%" headers="mcps1.2.4.1.3 "><p id="p314533811397"><a name="p314533811397"></a><a name="p314533811397"></a>-</p>
</td>
</tr>
<tr id="row15990182233714"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p399019224374"><a name="p399019224374"></a><a name="p399019224374"></a>YOLOv3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1714553816396"><a name="p1714553816396"></a><a name="p1714553816396"></a>-</p>
</td>
</tr>
<tr id="row5301255373"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1530325123719"><a name="p1530325123719"></a><a name="p1530325123719"></a>DB</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p5146193819390"><a name="p5146193819390"></a><a name="p5146193819390"></a>-</p>
</td>
</tr>
<tr id="row274203413712"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p197423343379"><a name="p197423343379"></a><a name="p197423343379"></a>RFCN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p15828941153919"><a name="p15828941153919"></a><a name="p15828941153919"></a>-</p>
</td>
</tr>
<tr id="row78671918163714"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p188671318183713"><a name="p188671318183713"></a><a name="p188671318183713"></a>CRNN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p10828241123917"><a name="p10828241123917"></a><a name="p10828241123917"></a>-</p>
</td>
</tr>
<tr id="row16912221171"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p6913132676"><a name="p6913132676"></a><a name="p6913132676"></a>Densenset161</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p209131221474"><a name="p209131221474"></a><a name="p209131221474"></a>-</p>
</td>
</tr>
<tr id="row1016073314719"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p3160153320717"><a name="p3160153320717"></a><a name="p3160153320717"></a>Densenset191</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1516012331173"><a name="p1516012331173"></a><a name="p1516012331173"></a>-</p>
</td>
</tr>
<tr id="row9627165910386"><td class="cellrowborder" rowspan="4" valign="top" width="10.489999999999998%" headers="mcps1.2.4.1.1 "><p id="p1561535993811"><a name="p1561535993811"></a><a name="p1561535993811"></a>PyTorch features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.3%" headers="mcps1.2.4.1.2 "><p id="p136151659163819"><a name="p136151659163819"></a><a name="p136151659163819"></a>Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" width="63.21%" headers="mcps1.2.4.1.3 "><p id="p1661535983813"><a name="p1661535983813"></a><a name="p1661535983813"></a>Added the function of adapted operator development. For details, see the operator list.</p>
</td>
</tr>
<tr id="row7627155917380"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1561525916383"><a name="p1561525916383"></a><a name="p1561525916383"></a>Model Accuracy Analyzer</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p19616115953816"><a name="p19616115953816"></a><a name="p19616115953816"></a>Added the Model Accuracy Analyzer and supported training accuracy demarcation.</p>
</td>
</tr>
<tr id="row46269593383"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p0616559163819"><a name="p0616559163819"></a><a name="p0616559163819"></a>Ascend 710 AI Processor</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p186161459193813"><a name="p186161459193813"></a><a name="p186161459193813"></a>Supported the online inference on Ascend 710 AI Processors.</p>
</td>
</tr>
<tr id="row76261059153817"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p11616175953812"><a name="p11616175953812"></a><a name="p11616175953812"></a>OS compatibility</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p8935115971714"><a name="p8935115971714"></a><a name="p8935115971714"></a>Supported Ubuntu 18.04.5 and openEuler 20.03 LTS.</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Description</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type.</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6/Ubuntu 18.04/BC-Linux 7.6/Debian 9.9/Debian 10/openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6/EulerOS 2.8/Kylin v10/BC-Linux 7.6/openEuler 20.03 LTS
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

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

@@ -0,0 +1,600 @@
# PyTorch在线推理指南
- [使用场景](#使用场景.md)
- [基本使用流程](#基本使用流程.md)
- [前提条件](#前提条件.md)
- [在线推理流程](#在线推理流程.md)
- [环境变量配置](#环境变量配置.md)
- [样例参考](#样例参考.md)
- [专题](#专题.md)
- [混合精度](#混合精度.md)
- [安装7.3.0版本gcc](#安装7-3-0版本gcc.md)
<h2 id="使用场景.md">使用场景</h2>
在线推理是在AI框架内执行推理的场景,例如在PyTorch框架上,加载模型后,通过“model.eval\(\)“将模型切换为推理模式。
相比于离线推理场景,使用在线推理可以方便将原来基于PyTorch框架做推理的应用快速迁移到昇腾AI处理器,适用于数据中心推理场景。
## 支持的芯片型号<a name="section15598658104219"></a>
昇腾910 AI处理器
昇腾710 AI处理器
<h2 id="基本使用流程.md">基本使用流程</h2>
- **[前提条件](#前提条件.md)**
- **[在线推理流程](#在线推理流程.md)**
- **[环境变量配置](#环境变量配置.md)**
- **[样例参考](#样例参考.md)**
<h2 id="前提条件.md">前提条件</h2>
已完成PyTorch框架及混合精度模块的安装,详情请参见《PyTorch安装指南》进行PyTorch相关运行环境搭建。
<h2 id="在线推理流程.md">在线推理流程</h2>
在线推理流程如[图1](#fig13802941161818)所示。
**图 1** 在线推理流程图<a name="fig13802941161818"></a>
![](figures/在线推理流程图.png "在线推理流程图")
<h2 id="环境变量配置.md">环境变量配置</h2>
PyTorch在线推理进程启动所依赖的环境变量:
```
# 请依据实际在下列场景中选择其一,进行在线推理依赖包安装路径的环境变量设置。具体如下(以HwHiAiUser用户安装,安装路径为默认路径为例):
# 场景一:昇腾设备安装部署开发套件包Ascend-cann-toolkit(此时开发环境可进行推理任务)。
. /home/HwHiAiUser/Ascend/ascend-toolkit/set_env.sh
# 场景二:昇腾设备安装部署软件包Ascend-cann-nnae。
. /home/HwHiAiUser/Ascend/nnae/set_env.sh
# 若运行环境中存在多个python3版本时,需要在环境变量中配置python3.7.5的安装路径。
export PATH=/usr/local/python3.7.5/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/python3.7.5/lib:$LD_LIBRARY_PATH
# 指定芯片的逻辑ID
export ASCEND_DEVICE_ID=0
# 输出日志信息,可根据实际修改
export ASCEND_SLOG_PRINT_TO_STDOUT=1
export ASCEND_GLOBAL_LOG_LEVEL=0
# TASK多线程下发
export TASK_QUEUE_ENABLE=0
```
**表 1** 环境变量说明
<a name="table2072027194819"></a>
<table><thead align="left"><tr id="row1173527114812"><th class="cellrowborder" valign="top" width="35.51355135513551%" id="mcps1.2.4.1.1"><p id="p073027114816"><a name="p073027114816"></a><a name="p073027114816"></a>配置项</p>
</th>
<th class="cellrowborder" valign="top" width="54.42544254425443%" id="mcps1.2.4.1.2"><p id="p157362712480"><a name="p157362712480"></a><a name="p157362712480"></a>说明</p>
</th>
<th class="cellrowborder" valign="top" width="10.061006100610062%" id="mcps1.2.4.1.3"><p id="p187392714485"><a name="p187392714485"></a><a name="p187392714485"></a>必选/可选</p>
</th>
</tr>
</thead>
<tbody><tr id="row2732273481"><td class="cellrowborder" valign="top" width="35.51355135513551%" headers="mcps1.2.4.1.1 "><p id="p57382719481"><a name="p57382719481"></a><a name="p57382719481"></a>LD_LIBRARY_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="54.42544254425443%" headers="mcps1.2.4.1.2 "><p id="p07319271480"><a name="p07319271480"></a><a name="p07319271480"></a>动态库的查找路径,参考上述举例配置。</p>
<div class="note" id="note119943144912"><a name="note119943144912"></a><a name="note119943144912"></a><span class="notetitle"> 说明: </span><div class="notebody"><p id="p49933104915"><a name="p49933104915"></a><a name="p49933104915"></a>若系统环境安装了gcc7.3.0(例如CentOS7.6、Debian和BClinux系统),需要配置gcc相关环境变量,详情请参见<a href="#安装7-3-0版本gcc.md#zh-cn_topic_0000001146754749_zh-cn_topic_0000001072593337_l5e5c9395407d46439788b12f0e6342bc">5</a>。</p>
</div></div>
</td>
<td class="cellrowborder" valign="top" width="10.061006100610062%" headers="mcps1.2.4.1.3 "><p id="p187352744817"><a name="p187352744817"></a><a name="p187352744817"></a>必选</p>
</td>
</tr>
<tr id="row17342744812"><td class="cellrowborder" valign="top" width="35.51355135513551%" headers="mcps1.2.4.1.1 "><p id="p4731227184818"><a name="p4731227184818"></a><a name="p4731227184818"></a>PATH</p>
</td>
<td class="cellrowborder" valign="top" width="54.42544254425443%" headers="mcps1.2.4.1.2 "><p id="p97310276484"><a name="p97310276484"></a><a name="p97310276484"></a>可执行程序的查找路径,参考上述举例配置。</p>
</td>
<td class="cellrowborder" valign="top" width="10.061006100610062%" headers="mcps1.2.4.1.3 "><p id="p1573142711483"><a name="p1573142711483"></a><a name="p1573142711483"></a>必选</p>
</td>
</tr>
<tr id="row95241840165613"><td class="cellrowborder" valign="top" width="35.51355135513551%" headers="mcps1.2.4.1.1 "><p id="p15242404566"><a name="p15242404566"></a><a name="p15242404566"></a>ASCEND_DEVICE_ID</p>
</td>
<td class="cellrowborder" valign="top" width="54.42544254425443%" headers="mcps1.2.4.1.2 "><p id="p688447526"><a name="p688447526"></a><a name="p688447526"></a>指定芯片的逻辑ID。</p>
<p id="p178824712212"><a name="p178824712212"></a><a name="p178824712212"></a>取值范围[0,N-1],默认为0。其中N为当前物理机/虚拟机/容器内的设备总数。</p>
</td>
<td class="cellrowborder" valign="top" width="10.061006100610062%" headers="mcps1.2.4.1.3 "><p id="p105245400562"><a name="p105245400562"></a><a name="p105245400562"></a>可选</p>
</td>
</tr>
<tr id="row203705529819"><td class="cellrowborder" valign="top" width="35.51355135513551%" headers="mcps1.2.4.1.1 "><p id="p53705522810"><a name="p53705522810"></a><a name="p53705522810"></a>ASCEND_SLOG_PRINT_TO_STDOUT</p>
</td>
<td class="cellrowborder" valign="top" width="54.42544254425443%" headers="mcps1.2.4.1.2 "><p id="zh-cn_topic_0000001073203258_p763102116322"><a name="zh-cn_topic_0000001073203258_p763102116322"></a><a name="zh-cn_topic_0000001073203258_p763102116322"></a>是否开启日志打屏。取值:</p>
<a name="zh-cn_topic_0000001073203258_ul95291245104113"></a><a name="zh-cn_topic_0000001073203258_ul95291245104113"></a><ul id="zh-cn_topic_0000001073203258_ul95291245104113"><li>0或不配置:关闭日志打屏</li><li>1:开启日志打屏</li></ul>
</td>
<td class="cellrowborder" valign="top" width="10.061006100610062%" headers="mcps1.2.4.1.3 "><p id="p6370125217818"><a name="p6370125217818"></a><a name="p6370125217818"></a>可选</p>
</td>
</tr>
<tr id="row188405280914"><td class="cellrowborder" valign="top" width="35.51355135513551%" headers="mcps1.2.4.1.1 "><p id="p5840928594"><a name="p5840928594"></a><a name="p5840928594"></a>ASCEND_GLOBAL_LOG_LEVEL</p>
</td>
<td class="cellrowborder" valign="top" width="54.42544254425443%" headers="mcps1.2.4.1.2 "><p id="zh-cn_topic_0000001073521184_p763102116322"><a name="zh-cn_topic_0000001073521184_p763102116322"></a><a name="zh-cn_topic_0000001073521184_p763102116322"></a>设置日志的全局日志级别。取值:</p>
<a name="zh-cn_topic_0000001073521184_u4d735da6e0494e55abbf5eb6aefe988d"></a><a name="zh-cn_topic_0000001073521184_u4d735da6e0494e55abbf5eb6aefe988d"></a><ul id="zh-cn_topic_0000001073521184_u4d735da6e0494e55abbf5eb6aefe988d"><li>0:对应DEBUG级别。</li><li>1:对应INFO级别。</li><li>2:对应WARNING级别。</li><li>3:对应ERROR级别。</li><li>4:对应NULL级别,不输出日志。</li><li>其他值为非法值。</li></ul>
</td>
<td class="cellrowborder" valign="top" width="10.061006100610062%" headers="mcps1.2.4.1.3 "><p id="p6841928598"><a name="p6841928598"></a><a name="p6841928598"></a>可选</p>
</td>
</tr>
<tr id="row17638114219104"><td class="cellrowborder" valign="top" width="35.51355135513551%" headers="mcps1.2.4.1.1 "><p id="p20638342191018"><a name="p20638342191018"></a><a name="p20638342191018"></a>TASK_QUEUE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="54.42544254425443%" headers="mcps1.2.4.1.2 "><p id="p126381842151019"><a name="p126381842151019"></a><a name="p126381842151019"></a>是否开启TASK多线程下发,绝大多数情况下,打开该功能会进一步提升整网训练性能。取值:</p>
<a name="ul6194152711118"></a><a name="ul6194152711118"></a><ul id="ul6194152711118"><li>0或不配置:关闭TASK多线程下发。</li><li>1:开启TASK多线程下发。</li></ul>
</td>
<td class="cellrowborder" valign="top" width="10.061006100610062%" headers="mcps1.2.4.1.3 "><p id="p86386423103"><a name="p86386423103"></a><a name="p86386423103"></a>可选</p>
</td>
</tr>
</tbody>
</table>
>![](public_sys-resources/icon-note.gif) **说明:**
>更多日志信息,请参见《CANN 日志参考》。
<h2 id="样例参考.md">样例参考</h2>
## 样例代码<a name="section2017032418274"></a>
在进行推理应用时,应尽量保证应用在生命周期内不频繁初始化。推理模式通过模型model.eval\(\)进行设置,并且推理过程要在“with torch.no\_grad\(\):”代码分支下运行。
本例中,我们将使用Resnet50网络的python代码进行说明。
样例代码 resnet50\_infer\_for\_pytorch.py:
```
import argparse
import os
import time
import torch
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models
import torch.npu
from apex import amp
model_names = sorted(name for name in models.__dict__
if name.islower() and not name.startswith("__")
and callable(models.__dict__[name]))
def parse_args():
""" 用户自定义数据集路径、模型路径 """
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('--data', metavar='DIR', default="/data/imagenet",
help='path to dataset')
parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet50',
choices=model_names,
help='model architecture: ' +
' | '.join(model_names) +
' (default: resnet18)')
parser.add_argument('--epochs', default=100, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('-b', '--batch_size', default=512, type=int,
metavar='N',
help='mini-batch size (default: 256), this is the total '
'batch size of all GPUs on the current node when '
'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('--npu', default=None, type=int,
help='NPU id to use.')
parser.add_argument('-j', '--workers', default=32, type=int, metavar='N',
help='number of data loading workers (default: 8)')
parser.add_argument('--lr', '--learning_rate', default=0.1, type=float,
metavar='LR', help='initial learning rate', dest='lr')
parser.add_argument('--wd', '--weight_decay', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)',
dest='weight_decay')
args, unknown_args = parser.parse_known_args()
if len(unknown_args) > 0:
for bad_arg in unknown_args:
print("ERROR: Unknown command line arg: %s" % bad_arg)
raise ValueError("Invalid command line arg(s)")
return args
# =========================================================================
# 主函数入口
# =========================================================================
def main():
args = parse_args()
if args.npu is None:
args.npu = 0
global CALCULATE_DEVICE
CALCULATE_DEVICE = "npu:{}".format(args.npu)
torch.npu.set_device(CALCULATE_DEVICE)
print("use ", CALCULATE_DEVICE)
main_worker(args.npu, args)
def main_worker(npu, args):
global best_acc1
args.npu = npu
# =========================================================================
# 创建模型
# =========================================================================
print("=> creating model '{}'".format(args.arch))
model = models.__dict__[args.arch](zero_init_residual=True)
# 将模型数据复制到昇腾AI处理器中
model = model.to(CALCULATE_DEVICE)
optimizer = torch.optim.SGD([
{'params': [param for name, param in model.named_parameters() if name[-4:] == 'bias'], 'weight_decay': 0.0},
{'params': [param for name, param in model.named_parameters() if name[-4:] != 'bias'],
'weight_decay': args.weight_decay}],
args.lr)
# =========================================================================
# 初始化混合精度模型,使用后可加速运算,但结果的准确率可能会轻微降低。可根据实际场景选择使用
# =========================================================================
model, optimizer = amp.initialize(model, optimizer, opt_level="O2", loss_scale=1024, verbosity=1)
# =========================================================================
# 加载训练好的模型参数
# =========================================================================
# 从模型文件中恢复模型参数
if os.path.isfile(args.resume):
print("=> loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(args.resume)
best_acc1 = checkpoint['best_acc1']
best_acc1 = best_acc1.to("npu:{}".format(args.npu))
model.load_state_dict(checkpoint['state_dict'])
print("=> loaded checkpoint '{}' (epoch {})".format(args.resume, checkpoint['epoch']))
else:
print("=> no checkpoint found at '{}'".format(args.resume))
# =========================================================================
# 初始化数据集
# =========================================================================
# 图像数据加载与预处理
valdir = os.path.join(args.data, 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=args.batch_size, shuffle=True,
num_workers=args.workers, pin_memory=True)
# =========================================================================
# 运行validate
# =========================================================================
validate(val_loader, model, args)
# =========================================================================
# 在线推理样例接口实现
# =========================================================================
def validate(val_loader, model, args):
batch_time = AverageMeter('Time', ':6.3f')
top1 = AverageMeter('Acc@1', ':6.2f')
top5 = AverageMeter('Acc@5', ':6.2f')
progress = ProgressMeter(
len(val_loader),
[batch_time, top1, top5],
prefix='Test: ')
# =========================================================================
# 切换到推理模式
# =========================================================================
model.eval()
# =========================================================================
# 在 torch.no_grad():分支下执行模型正向计算
# =========================================================================
with torch.no_grad():
end = time.time()
for i, (images, target) in enumerate(val_loader):
# 将图像数据置于NPU中
images = images.to(CALCULATE_DEVICE, non_blocking=True)
target = target.to(torch.int32).to(CALCULATE_DEVICE, non_blocking=True)
# 计算输出
output = model(images)
# 统计结果精度
acc1, acc5 = accuracy(output, target, topk=(1, 5))
top1.update(acc1[0], images.size(0))
top5.update(acc5[0], images.size(0))
# 测量运行时间
batch_time.update(time.time() - end)
end = time.time()
# 打印推理运算过程日志
progress.display(i)
print(' * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}'.format(top1=top1, top5=top5))
return top1.avg
class AverageMeter(object):
"""计算并存储平均值和当前值"""
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
self.start_count_index = 10
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
if self.count == 0:
self.batchsize = n
self.val = val
self.count += n
if self.count > (self.start_count_index * self.batchsize):
self.sum += val * n
self.avg = self.sum / (self.count - self.start_count_index * self.batchsize)
def __str__(self):
fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
return fmtstr.format(**self.__dict__)
class ProgressMeter(object):
"""记录模型运算过程信息"""
def __init__(self, num_batches, meters, prefix=""):
self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
self.meters = meters
self.prefix = prefix
def display(self, batch):
entries = [self.prefix + self.batch_fmtstr.format(batch)]
entries += [str(meter) for meter in self.meters]
print('\t'.join(entries))
def _get_batch_fmtstr(self, num_batches):
num_digits = len(str(num_batches // 1))
fmt = '{:' + str(num_digits) + 'd}'
return '[' + fmt + '/' + fmt.format(num_batches) + ']'
def accuracy(output, target, topk=(1,)):
"""根据指定值k,计算k个顶部预测的精度"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
if __name__ == '__main__':
main()
```
## 样例执行<a name="section340764716270"></a>
以ResNet50模型为例,执行在线推理样例。
1. 下载预训练模型。
打开ModelZoo中[ResNet50详情页](https://ascend.huawei.com/zh/#/software/modelzoo/detail/C/cf20ab8b8bea4032a6b056ab503112e4),单击该页面的“下载模型“下载已训练好的模型文件。
2. 编辑推理脚本。
创建“resnet50\_infer\_for\_pytorch.py“模型脚本文件,并参考[样例代码]()写入相关代码。
3. 执行推理。
参考[环境变量配置](#环境变量配置.md)设置环境变量,并执行命令:
```
python3 pytorch-resnet50-apex.py --data /data/imagenet \
--npu 7 \
--epochs 90 \
--resume ./checkpoint.pth.tar # ./checkpoint.pth.tar为示例预训练模型文件路径
```
>![](public_sys-resources/icon-note.gif) **说明:**
>上述为样例输入,用户可根据实际修改传入参数。
<h2 id="专题.md">专题</h2>
- **[混合精度](#混合精度.md)**
<h2 id="混合精度.md">混合精度</h2>
## 概述<a name="section14734122962615"></a>
基于NPU芯片的架构特性,模型运算会涉及到混合精度,即混合使用float16和float32数据类型的应用场景。使用float16代替float32有如下好处:
- 对于中间变量的内存占用更少,节省内存的使用。
- 因内存使用会减少,所以数据传出的时间也会减少。
- float16的计算单元可以提供更快的计算性能。
但是,混合精度训练受限于float16表达的精度范围,单纯将float32转换成float16会影响训练收敛情况,为了保证部分计算使用float16来进行加速的同时能保证训练收敛,这里采用混合精度模块Apex来达到以上效果。混合精度模块Apex是一个集优化性能、精度收敛于一身的综合优化库。
## 特性支持<a name="section175201458521"></a>
混合精度模块功能和优化描述如[表1](#zh-cn_topic_0278765773_table10717173813332)所示。
**表 1** 混合精度模块功能
<a name="zh-cn_topic_0278765773_table10717173813332"></a>
<table><thead align="left"><tr id="zh-cn_topic_0278765773_row371716385333"><th class="cellrowborder" valign="top" width="32.269999999999996%" id="mcps1.2.3.1.1"><p id="zh-cn_topic_0278765773_p13717163815333"><a name="zh-cn_topic_0278765773_p13717163815333"></a><a name="zh-cn_topic_0278765773_p13717163815333"></a>功能</p>
</th>
<th class="cellrowborder" valign="top" width="67.73%" id="mcps1.2.3.1.2"><p id="zh-cn_topic_0278765773_p14400173910345"><a name="zh-cn_topic_0278765773_p14400173910345"></a><a name="zh-cn_topic_0278765773_p14400173910345"></a>描述</p>
</th>
</tr>
</thead>
<tbody><tr id="zh-cn_topic_0278765773_row1571763813334"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0278765773_p4502732153412"><a name="zh-cn_topic_0278765773_p4502732153412"></a><a name="zh-cn_topic_0278765773_p4502732153412"></a>O1配置模式</p>
</td>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0278765773_p640053920348"><a name="zh-cn_topic_0278765773_p640053920348"></a><a name="zh-cn_topic_0278765773_p640053920348"></a>Conv, Matmul等使用<span>float16</span>计算,其他如Softmax、BN使用<span>float32</span>。</p>
</td>
</tr>
<tr id="zh-cn_topic_0278765773_row3717173817336"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0278765773_p11503103210344"><a name="zh-cn_topic_0278765773_p11503103210344"></a><a name="zh-cn_topic_0278765773_p11503103210344"></a>O2配置模式</p>
</td>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0278765773_p164001639143419"><a name="zh-cn_topic_0278765773_p164001639143419"></a><a name="zh-cn_topic_0278765773_p164001639143419"></a>BN使用<span>float32</span>,其他绝大部分使用<span>float16</span>。</p>
</td>
</tr>
<tr id="zh-cn_topic_0278765773_row14717193815334"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0278765773_p1950318328349"><a name="zh-cn_topic_0278765773_p1950318328349"></a><a name="zh-cn_topic_0278765773_p1950318328349"></a>静态Loss Scale功能</p>
</td>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0278765773_p1440033983418"><a name="zh-cn_topic_0278765773_p1440033983418"></a><a name="zh-cn_topic_0278765773_p1440033983418"></a>静态设置参数确保混合精度训练收敛。</p>
</td>
</tr>
<tr id="zh-cn_topic_0278765773_row871733813317"><td class="cellrowborder" valign="top" width="32.269999999999996%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0278765773_p1550303243417"><a name="zh-cn_topic_0278765773_p1550303243417"></a><a name="zh-cn_topic_0278765773_p1550303243417"></a>动态Loss Scale功能</p>
</td>
<td class="cellrowborder" valign="top" width="67.73%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0278765773_p15400143963412"><a name="zh-cn_topic_0278765773_p15400143963412"></a><a name="zh-cn_topic_0278765773_p15400143963412"></a>动态计算Loss Scale值并判读是否溢出。</p>
</td>
</tr>
</tbody>
</table>
>![](public_sys-resources/icon-note.gif) **说明:**
>当前版本的实现方式主要为python实现,不支持AscendCL或者CUDA优化。
## 混合精度模型初始化<a name="section18178125518268"></a>
1. 使用apex混合精度模块需要首先从apex库中导入amp,代码如下:
```
from apex import amp
```
2. 导入amp模块后,需要初始化amp,使其能对模型、优化器以及PyTorch内部函数进行必要的改动,初始化代码如下:
```
model, optimizer = amp.initialize(model, optimizer)
```
也可参考[样例代码](#样例参考.md)中的“初始化混合精度模型”:
```
model, optimizer = amp.initialize(model, optimizer, opt_level="O2", loss_scale=1024, verbosity=1)
```
## 混合精度推理<a name="section818071513288"></a>
按混合精度模型初始化后,正常执行模型正向计算即可。
参考代码:可参考[样例代码](#样例参考.md)实现。
<h2 id="安装7-3-0版本gcc.md">安装7.3.0版本gcc</h2>
以下步骤请在root用户下执行。
1. 下载gcc-7.3.0.tar.gz,下载地址为[https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz)。
2. 安装gcc时候会占用大量临时空间,请先执行下面的命令清空/tmp目录:
```
sudo rm -rf /tmp/*
```
3. 安装依赖(以CentOS和Ubuntu系统为例)。
- CentOS执行如下命令安装。
```
yum install bzip2
```
- Ubuntu执行如下命令安装。
```
apt-get install bzip2
```
4. 编译安装gcc。
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
```
tar -zxvf gcc-7.3.0.tar.gz
```
2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
如果执行上述命令报错,需要执行如下命令在“gcc-7.3.0/“文件夹下下载依赖包:
```
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
```
下载好上述依赖包后,重新执行以下命令:
```
./contrib/download_prerequisites
```
如果上述命令校验失败,需要确保依赖包为一次性下载成功,无重复下载现象。
3. <a name="zh-cn_topic_0000001146754749_zh-cn_topic_0000001072593337_l75d31a2874534a2092e80a5f865b46f0"></a>执行配置、编译和安装命令:
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
make -j15 # 通过grep -w processor /proc/cpuinfo|wc -l查看cpu数,示例为15,用户可自行设置相应参数。
make install
```
>![](public_sys-resources/icon-notice.gif) **须知:**
>其中“--prefix“参数用于指定linux\_gcc7.3.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.3.0“。
5. 配置环境变量。
当用户执行训练时,需要用到gcc升级后的编译环境,因此要在训练脚本中配置环境变量,通过如下命令配置。
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001146754749_zh-cn_topic_0000001072593337_l75d31a2874534a2092e80a5f865b46f0)中配置的gcc7.3.0安装路径,本示例为“/usr/local/linux\_gcc7.3.0/“。
>![](public_sys-resources/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

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

@@ -0,0 +1,573 @@
# PyTorch安装指南
- [简介](#简介.md)
- [手动编译安装](#手动编译安装.md)
- [前提条件](#前提条件.md)
- [安装PyTorch框架](#安装PyTorch框架.md)
- [配置环境变量](#配置环境变量.md)
- [安装混合精度模块](#安装混合精度模块.md)
- [使用Ascend Hub镜像](#使用Ascend-Hub镜像.md)
- [Ascend Hub获取PyTorch镜像](#Ascend-Hub获取PyTorch镜像.md)
- [配置环境变量](#配置环境变量-0.md)
- [参考信息](#参考信息.md)
- [CMake安装方法](#CMake安装方法.md)
- [安装7.3.0版本gcc](#安装7-3-0版本gcc.md)
- [安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配.md)
<h2 id="简介.md">简介</h2>
用户在准备相关环境进行PyTorch模型的移植及训练时,可以选择在训练服务器中手动编译安装PyTorch框架相关模块,或直接获取Ascend Hub镜像中心提供的基础镜像(镜像中已安装PyTorch模块和混合精度模块),进行模型的移植与训练。
**图 1** 环境准备流程图<a name="zh-cn_topic_0000001119176876_fig1938918396117"></a>
![](figures/环境准备流程图.png "环境准备流程图")
<h2 id="手动编译安装.md">手动编译安装</h2>
- **[前提条件](#前提条件.md)**
- **[安装PyTorch框架](#安装PyTorch框架.md)**
- **[配置环境变量](#配置环境变量.md)**
- **[安装混合精度模块](#安装混合精度模块.md)**
<h2 id="前提条件.md">前提条件</h2>
## 前提条件<a name="zh-cn_topic_0000001105856382_zh-cn_topic_0275872734_section108914373254"></a>
- 需完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
- 需安装3.12.0以上版本的CMake,安装方法请参考[CMake安装方法](#CMake安装方法.md)。
- 需确保已安装7.3.0以上版本的gcc,7.3.0版本gcc具体安装及使用方式请参考[安装7.3.0版本gcc](#安装7-3-0版本gcc.md)。
- 需确保环境中已安装patch、git工具,以Ubuntu和CentOS系统为例,命令如下:
- Ubuntu系统
```
apt-get install patch
apt-get install git
```
- CentOS系统
```
yum install patch
yum install git
```
<h2 id="安装PyTorch框架.md">安装PyTorch框架</h2>
## 安装流程<a name="zh-cn_topic_0000001152776301_section1611810384557"></a>
1. 以root或非root用户登录服务器。
2. 依次执行如下命令安装PyTorch依赖环境。
如果使用非root用户安装Python及其依赖,用户需要在本步骤中的每句命令结尾加上**--user**,命令示例为:**pip3.7 install pyyaml --user**
```
pip3 install pyyaml
pip3 install wheel
```
3. 获取PyTorch源代码。
1. 运行如下命令,获取适配昇腾AI处理器的PyTorch源代码。
```
git clone https://gitee.com/ascend/pytorch.git
```
下载的源码主要目录结构如下所示:
```
pytorch
│ ├─patch # 昇腾AI处理器适配补丁目录
│ ├─npu.patch
│ ├─scripts # 编译构建目录
│ ├─gen.sh
│ ├─src # 源码目录
│ ├─test # 测试用例存放目录
│ ├─README.md
```
2. 运行如下命令,进入“pytorch“目录,并获取原生PyTorch源代码。
```
cd pytorch
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
```
下载原生pytorch源码后,代码主要目录结构如下所示:
```
pytorch
│ ├─patch # 昇腾AI处理器适配补丁目录
│ ├─npu.patch
│ ├─pytorch # 原生pytorch代码目录
│ ├─scripts # 编译构建目录
│ ├─gen.sh
│ ├─src # 源码目录
│ ├─test # 测试用例存放目录
│ ├─README.md
```
3. 运行如下命令,进入原生pytorch代码目录“pytorch“,并获取PyTorch被动依赖代码。
```
cd pytorch
git submodule sync
git submodule update --init --recursive
```
>![](public_sys-resources/icon-note.gif) **说明:**
>受网络波动影响,源码获取时间可能较长,下载过程中请耐心等待。 下载完成之后若没有报错,即生成了PyTorch及其依赖的第三方代码。
4. 编译生成适配昇腾AI处理器的PyTorch安装包。
1. 进入“pytorch/scripts“文件夹,执行转换脚本,生成适配昇腾AI处理器的全量代码。
```
cd ../scripts
bash gen.sh
```
将在"pytorch/pytorch"目录中生成适配昇腾AI处理器的全量代码。
2. 进入适配后的全量代码目录,即“pytorch/pytorch“目录,编译生成pytorch的二进制安装包。
```
cd ../pytorch
bash build.sh
```
生成的二进制包在当前的dist目录下,即“pytorch/pytorch/dist”文件夹目录下。
5. <a name="zh-cn_topic_0000001152776301_li49671667141"></a>安装PyTorch。
进入“pytorch/pytorch/dist“文件夹目录,执行如下命令安装。
```
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_{arch}.whl
```
**\{arch\}**表示架构信息,为aarch64或x86\_64。
>![](public_sys-resources/icon-note.gif) **说明:**
>若对环境中的PyTorch进行升级时,需要先卸载环境中已安装的PyTorch软件包再执行[5. 安装PyTorch。](#zh-cn_topic_0000001152776301_li49671667141)可以通过执行如下命令查询环境上是否已安装PyTorch。
>**pip3 list | grep torch**
<h2 id="配置环境变量.md">配置环境变量</h2>
安装完软件包后,需要配置环境变量才能正常使用昇腾PyTorch。建议构建启动脚本,例如构建set\_env.sh脚本,使用source set\_env.sh配置当前窗口的环境变量。set\_env.sh脚本内容如下(以root用户安装,安装路径为默认路径为例)。
```
cpu_type=$(echo $HOSTTYPE)
if [ x"${cpu_type}" == x"x86_64" ];then
cpu_type=x86_64-linux
else
cpu_type=arm64-linux
fi
if [ -d /usr/local/Ascend/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/:/usr/local/Ascend/nnae/latest/fwkacllib/lib64/:/usr/local/Ascend/driver/lib64/common/:/usr/local/Ascend/driver/lib64/driver/:/usr/local/Ascend/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
export PATH=$PATH:/usr/local/Ascend/nnae/latest/fwkacllib/ccec_compiler/bin/:/usr/local/Ascend/nnae/latest/toolkit/tools/ide_daemon/bin/
export ASCEND_OPP_PATH=/usr/local/Ascend/nnae/latest/opp/
export OPTION_EXEC_EXTERN_PLUGIN_PATH=/usr/local/Ascend/nnae/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:/usr/local/Ascend/nnae/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:/usr/local/Ascend/nnae/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
export PYTHONPATH=/usr/local/Ascend/nnae/latest/fwkacllib/python/site-packages/:/usr/local/Ascend/nnae/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:/usr/local/Ascend/nnae/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
export ASCEND_AICPU_PATH=/usr/local/Ascend/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:/usr/local/Ascend/ascend-toolkit/latest/fwkacllib/lib64/:/usr/local/Ascend/driver/lib64/common/:/usr/local/Ascend/driver/lib64/driver/:/usr/local/Ascend/add-ons/:/usr/lib/aarch64-linux-gnu:$LD_LIBRARY_PATH
export PATH=$PATH:/usr/local/Ascend/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin/:/usr/local/Ascend/ascend-toolkit/latest/toolkit/tools/ide_daemon/bin/
export ASCEND_OPP_PATH=/usr/local/Ascend/ascend-toolkit/latest/opp/
export OPTION_EXEC_EXTERN_PLUGIN_PATH=/usr/local/Ascend/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:/usr/local/Ascend/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:/usr/local/Ascend/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
export PYTHONPATH=/usr/local/Ascend/ascend-toolkit/latest/fwkacllib/python/site-packages/:/usr/local/Ascend/ascend-toolkit/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:/usr/local/Ascend/ascend-toolkit/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
export ASCEND_AICPU_PATH=/usr/local/Ascend/ascend-toolkit/latest/${cpu_type}
fi
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)"""
)
export LD_LIBRARY_PATH=/usr/local/python3.7.5/lib/:${path_lib}:$LD_LIBRARY_PATH
export TASK_QUEUE_ENABLE=1
# (可选)当系统为openeuler时,需设置此命令,取消CPU绑核。
# unset GOMP_CPU_AFFINITY
# 请依据实际,在下列场景中选择合适的HCCL初始化方式,并配置相应环境变量。具体如下:
# 场景一:单机场景
export HCCL_WHITELIST_DISABLE=1 # 关闭HCCL通信白名单
# 场景二:多机场景。
export HCCL_WHITELIST_DISABLE=1 # 关闭HCCL通信白名单
export HCCL_IF_IP="1.1.1.1" # “1.1.1.1”为示例使用的host网卡IP,请根据实际修改。需要保证使用的网卡IP在集群内是互通的。
```
相关参数介绍参见[表1](#zh-cn_topic_0000001152616261_table42017516135)。
**表 1** 环境变量说明
<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>配置项</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>说明</p>
</th>
</tr>
</thead>
<tbody><tr id="zh-cn_topic_0000001152616261_row6882121917329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p688241953218"><a name="zh-cn_topic_0000001152616261_p688241953218"></a><a name="zh-cn_topic_0000001152616261_p688241953218"></a>LD_LIBRARY_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1888291915322"><a name="zh-cn_topic_0000001152616261_p1888291915322"></a><a name="zh-cn_topic_0000001152616261_p1888291915322"></a>动态库的查找路径,参考上述举例配置。</p>
<p id="p1292181892120"><a name="p1292181892120"></a><a name="p1292181892120"></a>若训练所在系统环境需要升级gcc(例如CentOS、Debian和BClinux系统),则<span class="parmname" id="parmname795020446318"><a name="parmname795020446318"></a><a name="parmname795020446318"></a>“LD_LIBRARY_PATH”</span>配置项处动态库查找路径需要添加<span class="filepath" id="zh-cn_topic_0256062644_filepath115819811512"><a name="zh-cn_topic_0256062644_filepath115819811512"></a><a name="zh-cn_topic_0256062644_filepath115819811512"></a>“${install_path}/lib64”</span>,其中<span class="filepath" id="zh-cn_topic_0256062644_filepath195951574421"><a name="zh-cn_topic_0256062644_filepath195951574421"></a><a name="zh-cn_topic_0256062644_filepath195951574421"></a>“{install_path}”</span>为gcc升级安装路径。请参见<a href="#安装7-3-0版本gcc.md#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li9745165315131">5</a>。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row16194175523010"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p16195185523019"><a name="zh-cn_topic_0000001152616261_p16195185523019"></a><a name="zh-cn_topic_0000001152616261_p16195185523019"></a>PYTHONPATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p19637083322"><a name="zh-cn_topic_0000001152616261_p19637083322"></a><a name="zh-cn_topic_0000001152616261_p19637083322"></a>Python搜索路径,参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row2954102119329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p195452113218"><a name="zh-cn_topic_0000001152616261_p195452113218"></a><a name="zh-cn_topic_0000001152616261_p195452113218"></a>PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p964914893211"><a name="zh-cn_topic_0000001152616261_p964914893211"></a><a name="zh-cn_topic_0000001152616261_p964914893211"></a>可执行程序的查找路径,参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row58592816294"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p1886016892913"><a name="zh-cn_topic_0000001152616261_p1886016892913"></a><a name="zh-cn_topic_0000001152616261_p1886016892913"></a>ASCEND_OPP_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p28608892915"><a name="zh-cn_topic_0000001152616261_p28608892915"></a><a name="zh-cn_topic_0000001152616261_p28608892915"></a>算子根目录,参考上述举例配置。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row144592037903"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p104601373014"><a name="zh-cn_topic_0000001152616261_p104601373014"></a><a name="zh-cn_topic_0000001152616261_p104601373014"></a>OPTION_EXEC_EXTERN_PLUGIN_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1046013716017"><a name="zh-cn_topic_0000001152616261_p1046013716017"></a><a name="zh-cn_topic_0000001152616261_p1046013716017"></a>算子信息库路径。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row16184379493"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p131851873492"><a name="zh-cn_topic_0000001152616261_p131851873492"></a><a name="zh-cn_topic_0000001152616261_p131851873492"></a>ASCEND_AICPU_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p181851575497"><a name="zh-cn_topic_0000001152616261_p181851575497"></a><a name="zh-cn_topic_0000001152616261_p181851575497"></a>aicpu算子包路径。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row234714854615"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p2034724894619"><a name="zh-cn_topic_0000001152616261_p2034724894619"></a><a name="zh-cn_topic_0000001152616261_p2034724894619"></a>TASK_QUEUE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p53477489462"><a name="zh-cn_topic_0000001152616261_p53477489462"></a><a name="zh-cn_topic_0000001152616261_p53477489462"></a>使用异步任务下发,异步调用acl接口。建议开启,开启设置为1。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row1680820246202"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p4809112415207"><a name="zh-cn_topic_0000001152616261_p4809112415207"></a><a name="zh-cn_topic_0000001152616261_p4809112415207"></a>HCCL_WHITELIST_DISABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p952814428206"><a name="zh-cn_topic_0000001152616261_p952814428206"></a><a name="zh-cn_topic_0000001152616261_p952814428206"></a>配置在使用HCCL时是否开启通信白名单。</p>
<a name="ul928845132310"></a><a name="ul928845132310"></a><ul id="ul928845132310"><li>0:开启白名单,无需校验HCCL通信白名单。</li><li>1:关闭白名单,需校验HCCL通信白名单。</li></ul>
<p id="zh-cn_topic_0000001152616261_p5809162416201"><a name="zh-cn_topic_0000001152616261_p5809162416201"></a><a name="zh-cn_topic_0000001152616261_p5809162416201"></a>缺省值为0,默认开启白名单。</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row0671137162115"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p4671203792114"><a name="zh-cn_topic_0000001152616261_p4671203792114"></a><a name="zh-cn_topic_0000001152616261_p4671203792114"></a>HCCL_IF_IP</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p1822165982114"><a name="zh-cn_topic_0000001152616261_p1822165982114"></a><a name="zh-cn_topic_0000001152616261_p1822165982114"></a>配置HCCL的初始化通信网卡IP。</p>
<a name="ul2676102292415"></a><a name="ul2676102292415"></a><ul id="ul2676102292415"><li>ip格式为点分十进制。</li><li>暂只支持host网卡。</li></ul>
<p id="zh-cn_topic_0000001152616261_p1167163719217"><a name="zh-cn_topic_0000001152616261_p1167163719217"></a><a name="zh-cn_topic_0000001152616261_p1167163719217"></a>缺省时,按照以下优先级选定host通信网卡名:docker/local以外网卡(网卡名字字典序升序排列)&gt;docker 网卡 &gt; local网卡</p>
</td>
</tr>
<tr id="zh-cn_topic_0000001152616261_row1371356152313"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="zh-cn_topic_0000001152616261_p16711563237"><a name="zh-cn_topic_0000001152616261_p16711563237"></a><a name="zh-cn_topic_0000001152616261_p16711563237"></a>unset GOMP_CPU_AFFINITY</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="zh-cn_topic_0000001152616261_p0711356152317"><a name="zh-cn_topic_0000001152616261_p0711356152317"></a><a name="zh-cn_topic_0000001152616261_p0711356152317"></a>(可选)当系统为openeuler时,需设置此命令,取消CPU绑核。</p>
</td>
</tr>
</tbody>
</table>
<h2 id="安装混合精度模块.md">安装混合精度模块</h2>
## 前提条件<a name="zh-cn_topic_0000001106176190_section3225481020"></a>
1. 请确保运行环境中适配昇腾AI处理器的PyTorch框架能正常使用。
2. 编译安装Apex前,需参见[配置环境变量](#配置环境变量.md)配置好编译过程依赖的环境变量。
## 安装流程<a name="zh-cn_topic_0000001106176190_section11880164819567"></a>
1. 以root或非root用户登录服务器。
2. 获取apex源代码。
1. 运行如下命令,获取适配昇腾AI处理器的apex源代码。
```
git clone https://gitee.com/ascend/apex.git
```
下载的源码主要目录结构如下所示:
```
apex
│ ├─patch # 昇腾AI处理器适配补丁目录
│ ├─npu.patch
│ ├─scripts # 编译构建目录
│ ├─gen.sh
│ ├─src # 源码目录
│ ├─tests # 测试用例存放目录
│ ├─README.md
```
2. 运行如下命令,进入“apex“目录,并获取原生apex源代码。
```
cd apex
git clone https://github.com/NVIDIA/apex.git
```
下载原生apex源码后,代码主要目录结构如下所示:
```
apex
│ ├─apex # 原生apex代码目录
│ ├─patch # 昇腾AI处理器适配补丁目录
│ ├─npu.patch
│ ├─scripts # 编译构建目录
│ ├─gen.sh
│ ├─src # 源码目录
│ ├─tests # 测试用例存放目录
│ ├─README.md
```
3. 进入原生apex代码目录,即“apex/apex“目录。切换至commitid为4ef930c1c884fdca5f472ab2ce7cb9b505d26c1a的代码分支。
```
cd apex
git checkout 4ef930c1c884fdca5f472ab2ce7cb9b505d26c1a
cd ..
```
>![](public_sys-resources/icon-note.gif) **说明:**
>受网络波动影响,源码获取时间可能较长,下载过程中请耐心等待。
3. 编译生成适配昇腾AI处理器的apex安装包。
1. 进入“apex/scripts“文件夹,执行转换脚本,生成适配昇腾AI处理器的全量代码。
```
cd ../scripts
bash gen.sh
```
将在"apex/apex"目录中生成适配昇腾AI处理器的全量代码。
2. 进入适配后的全量代码目录,即“apex/apex“目录,编译生成apex的二进制安装包。
```
cd ../apex
python3 setup.py --cpp_ext --npu_float_status bdist_wheel
```
生成的二进制包在当前的dist目录下,即“apex/apex/dist”文件夹目录下。
4. <a name="zh-cn_topic_0000001106176190_li425495374416"></a>安装apex。
进入“apex/apex/dist“文件夹目录,执行如下命令安装。
```
pip3.7 install --upgrade apex-0.1+ascend-cp37-cp37m-linux_{arch}.whl
```
**\{arch\}**表示架构信息,为aarch64或x86\_64。
>![](public_sys-resources/icon-note.gif) **说明:**
>若对环境中的Apex进行升级时,需要先卸载环境中已安装的PyTorch软件包再执行[4. 安装apex。](#zh-cn_topic_0000001106176190_li425495374416)可以通过执行如下命令查询环境上是否已安装PyTorch。
>**pip3 list | grep apex**
<h2 id="使用Ascend-Hub镜像.md">使用Ascend Hub镜像</h2>
- **[Ascend Hub获取PyTorch镜像](#Ascend-Hub获取PyTorch镜像.md)**
- **[配置环境变量](#配置环境变量-0.md)**
<h2 id="Ascend-Hub获取PyTorch镜像.md">Ascend Hub获取PyTorch镜像</h2>
## 前提条件<a name="zh-cn_topic_0000001118701830_zh-cn_topic_0275872734_section108914373254"></a>
- 已完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
- 宿主机上已安装Docker。
## 获取并使用镜像<a name="zh-cn_topic_0000001118701830_section108941734162613"></a>
用户可登录[Ascend Hub](https://ascendhub.huawei.com/#/home)获取相应镜像(首次申请需要激活账号)。
当前支持的镜像列表如[表1](#zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_table1519011227314)所示。用户可根据实际选择所需的镜像进行下载并使用。
**表 1** 镜像列表
<a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_table1519011227314"></a>
<table><thead align="left"><tr id="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_row0190152218319"><th class="cellrowborder" valign="top" width="55.00000000000001%" id="mcps1.2.4.1.1"><p id="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p1419132211315"><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p1419132211315"></a><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p1419132211315"></a>镜像名称</p>
</th>
<th class="cellrowborder" valign="top" width="20%" id="mcps1.2.4.1.2"><p id="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p75071327115313"><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p75071327115313"></a><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p75071327115313"></a>镜像版本</p>
</th>
<th class="cellrowborder" valign="top" width="25%" id="mcps1.2.4.1.3"><p id="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p1024411406234"><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p1024411406234"></a><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p1024411406234"></a>配套CANN版本</p>
</th>
</tr>
</thead>
<tbody><tr id="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_row71915221134"><td class="cellrowborder" valign="top" width="55.00000000000001%" headers="mcps1.2.4.1.1 "><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_ul81691515131910"></a><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_ul81691515131910"></a><ul id="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_ul81691515131910"><li>ARM架构:<a href="https://ascendhub.huawei.com/#/detail?name=ascend-pytorch-arm" target="_blank" rel="noopener noreferrer">ascend-pytorch-arm</a></li><li>x86架构:<a href="https://ascendhub.huawei.com/#/detail?name=ascend-pytorch-x86" target="_blank" rel="noopener noreferrer">ascend-pytorch-x86</a></li></ul>
</td>
<td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.4.1.2 "><p id="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p14648161414516"><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p14648161414516"></a><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p14648161414516"></a>21.0.2</p>
</td>
<td class="cellrowborder" valign="top" width="25%" headers="mcps1.2.4.1.3 "><p id="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p1264815147514"><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p1264815147514"></a><a name="zh-cn_topic_0000001118701830_zh-cn_topic_0000001074498056_p1264815147514"></a><a href="https://support.huawei.com/enterprise/zh/ascend-computing/cann-pid-251168373" target="_blank" rel="noopener noreferrer">5.0.2</a></p>
</td>
</tr>
</tbody>
</table>
<h2 id="配置环境变量-0.md">配置环境变量</h2>
启动并进入镜像容器后,请参见[配置环境变量](#配置环境变量.md)配置模型训练依赖的环境变量。
<h2 id="参考信息.md">参考信息</h2>
- **[CMake安装方法](#CMake安装方法.md)**
- **[安装7.3.0版本gcc](#安装7-3-0版本gcc.md)**
- **[安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配](#安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配.md)**
<h2 id="CMake安装方法.md">CMake安装方法</h2>
CMake版本升级为3.12.1的方法
1. 获取Cmake软件包。
```
wget https://cmake.org/files/v3.12/cmake-3.12.1.tar.gz --no-check-certificate
```
2. 解压并进入软件包目录。
```
tar -xf cmake-3.12.1.tar.gz
cd cmake-3.12.1/
```
3. 执行配置、编译和安装命令。
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. 设置软连接。
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. 执行如下命令验证是否安装成功。
```
cmake --version
```
如显示“cmake version 3.12.1”则表示安装成功。
<h2 id="安装7-3-0版本gcc.md">安装7.3.0版本gcc</h2>
以下步骤请在root用户下执行。
1. 下载gcc-7.3.0.tar.gz,下载地址为[https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz)。
2. 安装gcc时候会占用大量临时空间,所以先执行下面的命令清空/tmp目录:
```
sudo rm -rf /tmp/*
```
3. 安装依赖(以CentOS和Ubuntu系统为例)。
- CentOS执行如下命令安装。
```
yum install bzip2
```
- Ubuntu执行如下命令安装。
```
apt-get install bzip2
```
4. 编译安装gcc。
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
```
tar -zxvf gcc-7.3.0.tar.gz
```
2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
```
cd gcc-7.3.0
./contrib/download_prerequisites
```
如果执行上述命令报错,需要执行如下命令在“gcc-7.3.0/“文件夹下下载依赖包:
```
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
```
下载好上述依赖包后,重新执行以下命令:
```
./contrib/download_prerequisites
```
如果上述命令校验失败,需要确保依赖包为一次性下载成功,无重复下载现象。
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>执行配置、编译和安装命令:
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
make -j15 # 通过grep -w processor /proc/cpuinfo|wc -l查看cpu数,示例为15,用户可自行设置相应参数。
make install
```
>![](public_sys-resources/icon-notice.gif) **须知:**
>其中“--prefix“参数用于指定linux\_gcc7.3.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.3.0“。
5. 配置环境变量。
当用户执行训练时,需要用到gcc升级后的编译环境,因此要在训练脚本中配置环境变量,通过如下命令配置。
```
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.3.0安装路径,本示例为“/usr/local/gcc7.3.0/“。
>![](public_sys-resources/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
<h2 id="安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配.md">安装“torch-\*.whl ”提示“torch 1.5.0xxxx”与“torchvision”所依赖的版本不匹配</h2>
## 现象描述<a name="zh-cn_topic_0000001105856364_zh-cn_topic_0175549220_section197270431505"></a>
安装“torch-\*.whl”时,提示"ERROR:torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible"。
![](figures/zh-cn_image_0000001180656411.png)
## 可能原因<a name="zh-cn_topic_0000001105856364_zh-cn_topic_0175549220_section169499490501"></a>
安装torch时,会自动触发torchvision进行依赖版本检查,环境中安装的torchvision版本为0.6.0,检查时发现我们安装的torch-\*.whl的版本号与要求的1.5.0不一致,所以提示报错,但实际安装成功 。
## 处理方法<a name="zh-cn_topic_0000001105856364_section108142031907"></a>
对实际结果无影响,无需处理。
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

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

File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Some files were not shown because too many files have changed in this diff Show More