4919 lines
171 KiB
Diff
4919 lines
171 KiB
Diff
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/autocast_mode.h patch/aten/src/ATen/autocast_mode.h
|
|
--- pytorch-v1.8.1/aten/src/ATen/autocast_mode.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/aten/src/ATen/autocast_mode.h 2022-03-07 18:32:02.084336916 +0800
|
|
@@ -5,7 +5,7 @@
|
|
|
|
namespace {
|
|
bool is_autocast_eligible(const Tensor& tensor) {
|
|
- return (tensor.is_cuda() || tensor.is_xla()) && tensor.is_floating_point();
|
|
+ return (tensor.is_cuda() || tensor.is_xla() || tensor.is_npu()) && tensor.is_floating_point();
|
|
}
|
|
} // namespace
|
|
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/core/VariableFallbackKernel.cpp patch/aten/src/ATen/core/VariableFallbackKernel.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/core/VariableFallbackKernel.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/aten/src/ATen/core/VariableFallbackKernel.cpp 2022-03-07 18:32:02.084336916 +0800
|
|
@@ -48,4 +48,8 @@
|
|
m.fallback(torch::CppFunction::makeFallthrough());
|
|
}
|
|
|
|
+TORCH_LIBRARY_IMPL(_, AutogradNPU, m) {
|
|
+ m.fallback(torch::CppFunction::makeFallthrough());
|
|
+}
|
|
+
|
|
}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/templates/TensorBody.h patch/aten/src/ATen/templates/TensorBody.h
|
|
--- pytorch-v1.8.1/aten/src/ATen/templates/TensorBody.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/aten/src/ATen/templates/TensorBody.h 2022-03-07 18:32:02.192337599 +0800
|
|
@@ -342,6 +342,9 @@
|
|
|
|
/// Returns if a `Tensor` has CUDA backend.
|
|
bool is_cuda() const;
|
|
+
|
|
+ /// Returns if a `Tensor` has NPU backend.
|
|
+ bool is_npu() const;
|
|
|
|
/// Returns if a `Tensor` has XPU backend.
|
|
bool is_xpu() const;
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/templates/TensorMethods.cpp patch/aten/src/ATen/templates/TensorMethods.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/templates/TensorMethods.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/aten/src/ATen/templates/TensorMethods.cpp 2022-03-07 18:32:02.192337599 +0800
|
|
@@ -81,6 +81,10 @@
|
|
return impl_->is_cuda();
|
|
}
|
|
|
|
+bool Tensor::is_npu() const {
|
|
+ return impl_->is_npu();
|
|
+}
|
|
+
|
|
bool Tensor::is_xpu() const {
|
|
// NB: this is not a native function to avoid dispatching overhead.
|
|
return impl_->is_xpu();
|
|
@@ -116,6 +120,10 @@
|
|
return self.is_cuda();
|
|
}
|
|
|
|
+bool is_npu(Tensor self) {
|
|
+ return self.is_npu();
|
|
+}
|
|
+
|
|
bool is_xla(Tensor self) {
|
|
return self.is_xla();
|
|
}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/build.sh patch/build.sh
|
|
--- pytorch-v1.8.1/build.sh 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/build.sh 2022-05-05 14:32:51.351071624 +0800
|
|
@@ -0,0 +1,127 @@
|
|
+CUR_DIR=$(dirname $(readlink -f $0))
|
|
+SUPPORTED_PY_VERSION=(3.7 3.8 3.9)
|
|
+PY_VERSION='3.7' # Default supported python version is 3.7
|
|
+DEFAULT_SCRIPT_ARGS_NUM=1 # Default supported input parameters
|
|
+
|
|
+# Parse arguments inside script
|
|
+function parse_script_args() {
|
|
+ local args_num=0
|
|
+ if [[ "x${1}" = "x" ]]; then
|
|
+ # default: bash build.sh (python3.7)
|
|
+ return 0
|
|
+ fi
|
|
+
|
|
+ while true; do
|
|
+ if [[ "x${1}" = "x" ]]; then
|
|
+ break
|
|
+ fi
|
|
+ if [[ "$(echo "${1}"|cut -b1-|cut -b-2)" == "--" ]]; then
|
|
+ args_num=$((args_num+1))
|
|
+ fi
|
|
+ if [[ ${args_num} -eq ${DEFAULT_SCRIPT_ARGS_NUM} ]]; then
|
|
+ break
|
|
+ fi
|
|
+ shift
|
|
+ done
|
|
+
|
|
+ # if num of args are not fully parsed, throw an error.
|
|
+ if [[ ${args_num} -lt ${DEFAULT_SCRIPT_ARGS_NUM} ]]; then
|
|
+ return 1
|
|
+ fi
|
|
+
|
|
+ while true; do
|
|
+ case "${1}" in
|
|
+ --python=*)
|
|
+ PY_VERSION=$(echo "${1}"|cut -d"=" -f2)
|
|
+ args_num=$((args_num-1))
|
|
+ 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
|
|
+
|
|
+ # Find matched dependent Python libraries to current Python version in HCCL compiling
|
|
+ hccl_file1=${CUR_DIR}/cmake/public/npu.cmake
|
|
+ hccl_file2=${CUR_DIR}/third_party/acl/libs/build_stub.sh
|
|
+ if [[ ${PY_VERSION} = '3.7' ]]; then
|
|
+ dst_py_ver='3.7m'
|
|
+ else
|
|
+ dst_py_ver=${PY_VERSION}
|
|
+ fi
|
|
+ for src_py_ver in ${SUPPORTED_PY_VERSION[*]}; do
|
|
+ if [[ ${src_py_ver} = '3.7' ]]; then
|
|
+ src_py_ver='3.7m'
|
|
+ fi
|
|
+ if [[ $(grep -c "${src_py_ver}" ${hccl_file1}) -ne 0 && ${src_py_ver} != ${dst_py_ver} ]]; then
|
|
+ sed -i "s/python${src_py_ver}/python${dst_py_ver}/g" ${hccl_file1}
|
|
+ fi
|
|
+ if [[ $(grep -c "${src_py_ver}" ${hccl_file2}) -ne 0 && ${src_py_ver} != ${dst_py_ver} ]]; then
|
|
+ sed -i "s/libpython${src_py_ver}/libpython${dst_py_ver}/g" ${hccl_file2}
|
|
+ fi
|
|
+ done
|
|
+
|
|
+ cd ${CUR_DIR}/third_party/acl/libs
|
|
+ # stub
|
|
+ dos2unix build_stub.sh
|
|
+ chmod +x build_stub.sh
|
|
+ ./build_stub.sh
|
|
+
|
|
+ cd ${CUR_DIR}
|
|
+ # if you add or delete file/files in the project, you need to remove the following comment
|
|
+ # make clean
|
|
+ export TORCH_PACKAGE_NAME=torch
|
|
+ export PYTORCH_BUILD_VERSION='1.8.1+ascend'
|
|
+ export PYTORCH_BUILD_NUMBER=2
|
|
+
|
|
+ USE_FBGEMM=0 DEBUG=0 USE_DISTRIBUTED=1 USE_QNNPACK=0 USE_HCCL=1 USE_MKLDNN=0 USE_CUDA=0 USE_NPU=1 BUILD_TEST=0 USE_NNPACK=0 USE_XNNPACK=0 python"${PY_VERSION}" setup.py build bdist_wheel
|
|
+ if [ $? != 0 ]; then
|
|
+ USE_FBGEMM=0 DEBUG=0 USE_DISTRIBUTED=1 USE_QNNPACK=0 USE_HCCL=1 USE_MKLDNN=0 USE_CUDA=0 USE_NPU=1 BUILD_TEST=0 USE_NNPACK=0 USE_XNNPACK=0 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
|
|
+ fi
|
|
+
|
|
+ exit 0
|
|
+}
|
|
+
|
|
+main "$@"
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/CMakeLists.txt patch/c10/CMakeLists.txt
|
|
--- pytorch-v1.8.1/c10/CMakeLists.txt 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/CMakeLists.txt 2022-03-07 18:32:02.216337752 +0800
|
|
@@ -79,6 +79,14 @@
|
|
message(STATUS "don't use NUMA")
|
|
endif()
|
|
|
|
+if (USE_NPU)
|
|
+ message(STATUS "NPU paths:")
|
|
+ message(STATUS ${NPU_INCLUDE_DIRS})
|
|
+ message(STATUS ${NPU_LIBRARIES})
|
|
+ include_directories(SYSTEM ${NPU_INCLUDE_DIRS})
|
|
+ target_link_libraries(c10 PRIVATE ${NPU_LIBRARIES})
|
|
+endif()
|
|
+
|
|
if(ANDROID)
|
|
target_link_libraries(c10 PRIVATE log)
|
|
endif()
|
|
@@ -96,6 +104,10 @@
|
|
add_subdirectory(cuda)
|
|
endif()
|
|
|
|
+if(USE_NPU)
|
|
+ add_subdirectory(npu)
|
|
+endif()
|
|
+
|
|
if(USE_ROCM)
|
|
# NB: This directory is generated by the HIPIFY script; it's
|
|
# not checked in
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/Backend.h patch/c10/core/Backend.h
|
|
--- pytorch-v1.8.1/c10/core/Backend.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/Backend.h 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -45,6 +45,7 @@
|
|
QuantizedXPU,
|
|
Undefined,
|
|
MkldnnCPU,
|
|
+ NPU,
|
|
NumOptions
|
|
};
|
|
|
|
@@ -64,6 +65,8 @@
|
|
return Backend::SparseCUDA;
|
|
case Backend::SparseHIP:
|
|
return Backend::SparseHIP;
|
|
+ case Backend::NPU:
|
|
+ throw std::runtime_error("NPU is not support sparse tensor");
|
|
default:
|
|
throw std::runtime_error("Unknown backend");
|
|
}
|
|
@@ -71,6 +74,8 @@
|
|
|
|
static inline Backend toDense(Backend b) {
|
|
switch (b) {
|
|
+ case Backend::NPU:
|
|
+ return Backend::NPU;
|
|
case Backend::CPU:
|
|
return Backend::CPU;
|
|
case Backend::CUDA:
|
|
@@ -105,7 +110,9 @@
|
|
}
|
|
|
|
static inline Backend dispatchKeyToBackend(DispatchKey t) {
|
|
- if (t == DispatchKey::CPU || t == DispatchKey::AutogradCPU) {
|
|
+ if (t == DispatchKey::NPU || t == DispatchKey::AutogradNPU) {
|
|
+ return Backend::NPU;
|
|
+ } else if (t == DispatchKey::CPU || t == DispatchKey::AutogradCPU) {
|
|
return Backend::CPU;
|
|
} else if (t == DispatchKey::CUDA || t == DispatchKey::AutogradCUDA) {
|
|
return Backend::CUDA;
|
|
@@ -148,6 +155,8 @@
|
|
|
|
static inline DispatchKey backendToDispatchKey(Backend b) {
|
|
switch (b) {
|
|
+ case Backend::NPU:
|
|
+ return DispatchKey::NPUTensorId;
|
|
case Backend::CPU:
|
|
return DispatchKey::CPU;
|
|
case Backend::CUDA:
|
|
@@ -189,6 +198,8 @@
|
|
|
|
static inline DeviceType backendToDeviceType(Backend b) {
|
|
switch (b) {
|
|
+ case Backend::NPU:
|
|
+ return DeviceType::NPU;
|
|
case Backend::CPU:
|
|
return DeviceType::CPU;
|
|
case Backend::CUDA:
|
|
@@ -229,6 +240,8 @@
|
|
|
|
static inline Backend backendToCPU(Backend b) {
|
|
switch (b) {
|
|
+ case Backend::NPU:
|
|
+ return Backend::NPU;
|
|
case Backend::CPU:
|
|
return Backend::CPU;
|
|
case Backend::CUDA:
|
|
@@ -340,6 +353,8 @@
|
|
// TODO: This probably shouldn't actually be static inline
|
|
static inline const char* toString(Backend b) {
|
|
switch (b) {
|
|
+ case Backend::NPU:
|
|
+ return "NPU";
|
|
case Backend::CPU:
|
|
return "CPU";
|
|
case Backend::CUDA:
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/Device.cpp patch/c10/core/Device.cpp
|
|
--- pytorch-v1.8.1/c10/core/Device.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/Device.cpp 2022-03-07 18:32:02.216337752 +0800
|
|
@@ -46,6 +46,7 @@
|
|
{"msnpu", DeviceType::MSNPU},
|
|
{"xla", DeviceType::XLA},
|
|
{"vulkan", DeviceType::Vulkan},
|
|
+ {"npu", DeviceType::NPU},
|
|
}};
|
|
auto device = std::find_if(
|
|
types.begin(),
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/Device.h patch/c10/core/Device.h
|
|
--- pytorch-v1.8.1/c10/core/Device.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/Device.h 2022-03-07 18:32:02.216337752 +0800
|
|
@@ -85,6 +85,11 @@
|
|
bool is_xpu() const noexcept {
|
|
return type_ == DeviceType::XPU;
|
|
}
|
|
+
|
|
+ /// Return true if the device is of NPU type.
|
|
+ bool is_npu() const noexcept {
|
|
+ return type_ == DeviceType::NPU;
|
|
+ }
|
|
|
|
/// Return true if the device is of CPU type.
|
|
bool is_cpu() const noexcept {
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/DeviceType.cpp patch/c10/core/DeviceType.cpp
|
|
--- pytorch-v1.8.1/c10/core/DeviceType.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/DeviceType.cpp 2022-03-07 18:32:02.216337752 +0800
|
|
@@ -33,6 +33,8 @@
|
|
return lower_case ? "metal" : "METAL";
|
|
case DeviceType::XPU:
|
|
return lower_case ? "xpu" : "XPU";
|
|
+ case DeviceType::NPU:
|
|
+ return lower_case ? "npu" : "NPU";
|
|
default:
|
|
AT_ERROR(
|
|
"Unknown device: ",
|
|
@@ -68,6 +70,7 @@
|
|
case DeviceType::Vulkan:
|
|
case DeviceType::Metal:
|
|
case DeviceType::XPU:
|
|
+ case DeviceType::NPU:
|
|
return true;
|
|
default:
|
|
return false;
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/DeviceType.h patch/c10/core/DeviceType.h
|
|
--- pytorch-v1.8.1/c10/core/DeviceType.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/DeviceType.h 2022-03-07 18:32:02.216337752 +0800
|
|
@@ -26,15 +26,17 @@
|
|
Vulkan = 10, // Vulkan
|
|
Metal = 11, // Metal
|
|
XPU = 12, // XPU
|
|
+ NPU = 13, // NPU
|
|
// NB: If you add more devices:
|
|
// - Change the implementations of DeviceTypeName and isValidDeviceType
|
|
// in DeviceType.cpp
|
|
// - Change the number below
|
|
- COMPILE_TIME_MAX_DEVICE_TYPES = 13,
|
|
+ COMPILE_TIME_MAX_DEVICE_TYPES = 14,
|
|
};
|
|
|
|
constexpr DeviceType kCPU = DeviceType::CPU;
|
|
constexpr DeviceType kCUDA = DeviceType::CUDA;
|
|
+constexpr DeviceType kNPU = DeviceType::NPU;
|
|
constexpr DeviceType kHIP = DeviceType::HIP;
|
|
constexpr DeviceType kFPGA = DeviceType::FPGA;
|
|
constexpr DeviceType kMSNPU = DeviceType::MSNPU;
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/DispatchKey.cpp patch/c10/core/DispatchKey.cpp
|
|
--- pytorch-v1.8.1/c10/core/DispatchKey.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/DispatchKey.cpp 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -6,7 +6,8 @@
|
|
switch (t) {
|
|
case DispatchKey::Undefined:
|
|
return "Undefined";
|
|
-
|
|
+ case DispatchKey::NPU:
|
|
+ return "NPU";
|
|
case DispatchKey::CPU:
|
|
return "CPU";
|
|
case DispatchKey::CUDA:
|
|
@@ -80,6 +81,8 @@
|
|
return "AutogradCUDA";
|
|
case DispatchKey::AutogradXLA:
|
|
return "AutogradXLA";
|
|
+ case DispatchKey::AutogradNPU:
|
|
+ return "AutogradNPU";
|
|
case DispatchKey::AutogradNestedTensor:
|
|
return "AutogradNestedTensor";
|
|
case DispatchKey::AutogradPrivateUse1:
|
|
@@ -143,6 +146,8 @@
|
|
return DispatchKey::AutogradCUDA;
|
|
case DispatchKey::XLA:
|
|
return DispatchKey::AutogradXLA;
|
|
+ case DispatchKey::NPU:
|
|
+ return DispatchKey::AutogradNPU;
|
|
case DispatchKey::NestedTensor:
|
|
return DispatchKey::AutogradNestedTensor;
|
|
case DispatchKey::PrivateUse1:
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/DispatchKey.h patch/c10/core/DispatchKey.h
|
|
--- pytorch-v1.8.1/c10/core/DispatchKey.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/DispatchKey.h 2022-03-07 18:32:02.216337752 +0800
|
|
@@ -114,6 +114,7 @@
|
|
// Here are reserved backends for user-defined backends, see Note [Private use
|
|
// DispatchKey]
|
|
// To see some example about how to use this, check out MSNPU
|
|
+ NPU,
|
|
PrivateUse1,
|
|
PrivateUse2,
|
|
PrivateUse3,
|
|
@@ -224,6 +225,7 @@
|
|
AutogradCPU,
|
|
AutogradCUDA,
|
|
AutogradXLA,
|
|
+ AutogradNPU,
|
|
AutogradNestedTensor, // lives out of tree at
|
|
// https://github.com/pytorch/nestedtensor
|
|
AutogradXPU,
|
|
@@ -297,6 +299,7 @@
|
|
// be used
|
|
CPUTensorId = CPU,
|
|
CUDATensorId = CUDA,
|
|
+ NPUTensorId = NPU,
|
|
PrivateUse1_PreAutograd = AutogradPrivateUse1,
|
|
PrivateUse2_PreAutograd = AutogradPrivateUse2,
|
|
PrivateUse3_PreAutograd = AutogradPrivateUse3,
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/DispatchKeySet.cpp patch/c10/core/DispatchKeySet.cpp
|
|
--- pytorch-v1.8.1/c10/core/DispatchKeySet.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/DispatchKeySet.cpp 2022-03-07 18:32:02.216337752 +0800
|
|
@@ -11,6 +11,7 @@
|
|
DispatchKey::XLA,
|
|
DispatchKey::NestedTensor,
|
|
DispatchKey::XPU,
|
|
+ DispatchKey::NPU,
|
|
DispatchKey::PrivateUse1,
|
|
DispatchKey::PrivateUse2,
|
|
DispatchKey::PrivateUse3,
|
|
@@ -48,6 +49,8 @@
|
|
return DispatchKeySet(DispatchKey::CUDA);
|
|
case DispatchKey::AutogradXLA:
|
|
return DispatchKeySet(DispatchKey::XLA);
|
|
+ case DispatchKey::AutogradNPU:
|
|
+ return DispatchKeySet(DispatchKey::NPU);
|
|
case DispatchKey::AutogradNestedTensor:
|
|
return DispatchKeySet(DispatchKey::NestedTensor);
|
|
case DispatchKey::AutogradXPU:
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/DispatchKeySet.h patch/c10/core/DispatchKeySet.h
|
|
--- pytorch-v1.8.1/c10/core/DispatchKeySet.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/DispatchKeySet.h 2022-03-07 18:32:02.216337752 +0800
|
|
@@ -193,6 +193,7 @@
|
|
DispatchKey::AutogradCPU,
|
|
DispatchKey::AutogradCUDA,
|
|
DispatchKey::AutogradXLA,
|
|
+ DispatchKey::AutogradNPU,
|
|
DispatchKey::AutogradNestedTensor,
|
|
DispatchKey::AutogradXPU,
|
|
DispatchKey::AutogradPrivateUse1,
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/StorageImpl.h patch/c10/core/StorageImpl.h
|
|
--- pytorch-v1.8.1/c10/core/StorageImpl.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/StorageImpl.h 2022-04-28 18:51:47.202663489 +0800
|
|
@@ -7,7 +7,7 @@
|
|
|
|
namespace c10 {
|
|
|
|
-struct C10_API StorageImpl final : public c10::intrusive_ptr_target {
|
|
+struct C10_API StorageImpl : public c10::intrusive_ptr_target {
|
|
public:
|
|
struct use_byte_size_t {};
|
|
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/TensorImpl.h patch/c10/core/TensorImpl.h
|
|
--- pytorch-v1.8.1/c10/core/TensorImpl.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/TensorImpl.h 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -508,6 +508,10 @@
|
|
key_set_.has(DispatchKey::SparseCUDA) ||
|
|
key_set_.has(DispatchKey::QuantizedCUDA);
|
|
}
|
|
+
|
|
+ bool is_npu() const {
|
|
+ return key_set_.has(DispatchKey::NPU);
|
|
+ }
|
|
|
|
bool is_xpu() const {
|
|
// NB: This method is not virtual and avoid dispatches for performance
|
|
@@ -997,7 +1001,7 @@
|
|
*/
|
|
inline bool has_compatible_shallow_copy_type(DispatchKeySet from) {
|
|
auto is_dense = [](DispatchKeySet ts) {
|
|
- return ts.has(DispatchKey::CPU) || ts.has(DispatchKey::CUDA) ||
|
|
+ return ts.has(DispatchKey::NPU) || ts.has(DispatchKey::CPU) || ts.has(DispatchKey::CUDA) ||
|
|
ts.has(DispatchKey::HIP) || ts.has(DispatchKey::XPU);
|
|
};
|
|
auto is_sparse = [](DispatchKeySet ts) {
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/TensorOptions.h patch/c10/core/TensorOptions.h
|
|
--- pytorch-v1.8.1/c10/core/TensorOptions.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/core/TensorOptions.h 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -595,6 +595,8 @@
|
|
case Layout::Strided: {
|
|
const auto dtype_ = dtype_or_default(dtype);
|
|
switch (device_.type()) {
|
|
+ case DeviceType::NPU:
|
|
+ return DispatchKey::NPU;
|
|
case DeviceType::CPU: {
|
|
if (isQIntType(dtype_)) {
|
|
return DispatchKey::QuantizedCPU;
|
|
@@ -665,7 +667,9 @@
|
|
// We deliberately ignore handling AutogradCPU/CUDA/XLA... keys to
|
|
// avoid adding asymmetry in device <--> Autograd dispatch key mapping.
|
|
inline DeviceType computeDeviceType(DispatchKey tid) {
|
|
- if (tid == DispatchKey::CPU) {
|
|
+ if (tid == DispatchKey::NPU) {
|
|
+ return DeviceType::NPU;
|
|
+ } else if (tid == DispatchKey::CPU) {
|
|
return DeviceType::CPU;
|
|
} else if (tid == DispatchKey::CUDA) {
|
|
return DeviceType::CUDA;
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/cuda/CMakeLists.txt patch/c10/cuda/CMakeLists.txt
|
|
--- pytorch-v1.8.1/c10/cuda/CMakeLists.txt 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/c10/cuda/CMakeLists.txt 2022-03-07 18:32:02.220337776 +0800
|
|
@@ -36,6 +36,8 @@
|
|
CUDAFunctions.h
|
|
impl/CUDAGuardImpl.h
|
|
impl/CUDATest.h
|
|
+ # need to remove
|
|
+ ../npu/NPUGraphContextManager.cpp
|
|
)
|
|
set(CUDA_LINK_LIBRARIES_KEYWORD PRIVATE)
|
|
torch_cuda_based_add_library(c10_cuda ${C10_CUDA_SRCS} ${C10_CUDA_HEADERS})
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/CMakeLists.txt patch/c10/npu/CMakeLists.txt
|
|
--- pytorch-v1.8.1/c10/npu/CMakeLists.txt 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/CMakeLists.txt 2022-03-07 18:31:59.236318895 +0800
|
|
@@ -0,0 +1,18 @@
|
|
+#Build file for C10 NPU
|
|
+#
|
|
+#C10 NPU is a minimal library, but it does depend on NPU.
|
|
+
|
|
+file(GLOB C10_NPU_SYS_CTRL_SRCS sys_ctrl/*.cpp *.cpp impl/*.cpp register/*.cpp interface/*.cpp)
|
|
+
|
|
+add_library(c10_npu ${C10_NPU_SYS_CTRL_SRCS})
|
|
+
|
|
+target_link_libraries(c10_npu PUBLIC c10)
|
|
+
|
|
+if(USE_NPU)
|
|
+ target_link_libraries(
|
|
+ c10_npu PRIVATE ${Caffe2_NPU_DEPENDENCY_LIBS})
|
|
+
|
|
+endif()
|
|
+
|
|
+install(TARGETS c10_npu EXPORT Caffe2Targets DESTINATION lib)
|
|
+
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/impl/NPUGuardImpl.cpp patch/c10/npu/impl/NPUGuardImpl.cpp
|
|
--- pytorch-v1.8.1/c10/npu/impl/NPUGuardImpl.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/impl/NPUGuardImpl.cpp 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,13 @@
|
|
+#include <c10/npu/impl/NPUGuardImpl.h>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+namespace impl {
|
|
+
|
|
+constexpr DeviceType NPUGuardImpl::static_type;
|
|
+
|
|
+C10_REGISTER_GUARD_IMPL(NPU, NPUGuardImpl);
|
|
+
|
|
+} // namespace impl
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/impl/NPUGuardImpl.h patch/c10/npu/impl/NPUGuardImpl.h
|
|
--- pytorch-v1.8.1/c10/npu/impl/NPUGuardImpl.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/impl/NPUGuardImpl.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,165 @@
|
|
+#pragma once
|
|
+
|
|
+#include <c10/core/impl/DeviceGuardImplInterface.h>
|
|
+#include <c10/macros/Macros.h>
|
|
+#include <c10/util/Exception.h>
|
|
+
|
|
+#include <c10/npu/NPUException.h>
|
|
+#include <c10/npu/NPUFunctions.h>
|
|
+#include <c10/npu/NPUStream.h>
|
|
+#include <c10/npu/sys_ctrl/npu_sys_ctrl.h>
|
|
+#include <third_party/acl/inc/acl/acl.h>
|
|
+#include <third_party/acl/inc/acl/acl_base.h>
|
|
+#include <third_party/acl/inc/acl/acl_rt.h>
|
|
+#include <cassert>
|
|
+
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+namespace impl {
|
|
+
|
|
+struct NPUGuardImpl final : public c10::impl::DeviceGuardImplInterface {
|
|
+ static constexpr DeviceType static_type = DeviceType::NPU;
|
|
+
|
|
+ NPUGuardImpl() {}
|
|
+ explicit NPUGuardImpl(DeviceType t) {
|
|
+ TORCH_INTERNAL_ASSERT(t == DeviceType::NPU);
|
|
+ }
|
|
+ DeviceType type() const override {
|
|
+ return DeviceType::NPU;
|
|
+ }
|
|
+ Device exchangeDevice(Device d) const override {
|
|
+ TORCH_INTERNAL_ASSERT(d.type() == DeviceType::NPU);
|
|
+ Device old_device = getDevice();
|
|
+ if (old_device.index() != d.index()) {
|
|
+ C10_NPU_CHECK(aclrtSetDevice(d.index()));
|
|
+ }
|
|
+ return old_device;
|
|
+ }
|
|
+ Device getDevice() const override {
|
|
+ int device = 0;
|
|
+ C10_NPU_CHECK(aclrtGetDevice(&device));
|
|
+ return Device(DeviceType::NPU, device);
|
|
+ }
|
|
+ void setDevice(Device d) const override {
|
|
+ TORCH_INTERNAL_ASSERT(d.type() == DeviceType::NPU);
|
|
+ Device old_device = getDevice();
|
|
+ if (old_device.index() != d.index()) {
|
|
+ C10_NPU_CHECK(aclrtSetDevice(d.index()));
|
|
+ }
|
|
+ }
|
|
+ void uncheckedSetDevice(Device d) const noexcept override {
|
|
+ int old_device = 0;
|
|
+ aclError ret = aclrtGetDevice(&old_device);
|
|
+ if (ret != ACL_ERROR_NONE){
|
|
+ C10_NPU_CHECK_WARN(aclrtSetDevice(d.index()));
|
|
+ }else if(old_device != d.index()){
|
|
+ C10_NPU_CHECK_WARN(aclrtSetDevice(d.index()));
|
|
+ }
|
|
+ }
|
|
+ Stream getStream(Device d) const noexcept override {
|
|
+ return getCurrentNPUStream(d.index()).unwrap();
|
|
+ }
|
|
+ Stream getDefaultStream(Device d) const override {
|
|
+ return getDefaultNPUStream(d.index());
|
|
+ }
|
|
+ // NB: These do NOT set the current device
|
|
+ Stream exchangeStream(Stream s) const noexcept override {
|
|
+ NPUStream cs(s);
|
|
+ auto old_stream = getCurrentNPUStream(s.device().index());
|
|
+ setCurrentNPUStream(cs);
|
|
+ return old_stream.unwrap();
|
|
+ }
|
|
+ DeviceIndex deviceCount() const noexcept override {
|
|
+ return c10::npu::device_count();
|
|
+ }
|
|
+
|
|
+ // Event-related functions
|
|
+ void createEvent(aclrtEvent* acl_event, const EventFlag flag) const {
|
|
+ /*
|
|
+ // Maps PyTorch's Event::Flag to NPU flag
|
|
+ auto cuda_flag = cudaEventDefault;
|
|
+ switch (flag) {
|
|
+ case EventFlag::PYTORCH_DEFAULT:
|
|
+ case EventFlag::NPU_EVENT_DISABLE_TIMING:
|
|
+ cuda_flag = cudaEventDisableTiming;
|
|
+ break;
|
|
+ case EventFlag::BACKEND_DEFAULT:
|
|
+ case EventFlag::NPU_EVENT_DEFAULT:
|
|
+ cuda_flag = cudaEventDefault;
|
|
+ break;
|
|
+ default:
|
|
+ TORCH_CHECK(false, "NPU event received unknown flag");
|
|
+ }*/
|
|
+
|
|
+ C10_NPU_CHECK(aclrtCreateEvent(acl_event));
|
|
+ }
|
|
+
|
|
+ void destroyEvent(void* event, const DeviceIndex device_index)
|
|
+ const noexcept override {
|
|
+ if (!event)
|
|
+ return;
|
|
+ auto acl_event = static_cast<aclrtEvent>(event);
|
|
+ int orig_device;
|
|
+ C10_NPU_CHECK_WARN(aclrtDestroyEvent(acl_event));
|
|
+ }
|
|
+
|
|
+ void record(
|
|
+ void** event,
|
|
+ const Stream& stream,
|
|
+ const DeviceIndex device_index,
|
|
+ const EventFlag flag) const override {
|
|
+ TORCH_CHECK(
|
|
+ device_index == -1 || device_index == stream.device_index(),
|
|
+ "Event device index ",
|
|
+ device_index,
|
|
+ " does not match recording stream's device index ",
|
|
+ stream.device_index(),
|
|
+ ".");
|
|
+
|
|
+ aclrtEvent npu_event = static_cast<aclrtEvent>(*event);
|
|
+ NPUStream npu_stream{stream};
|
|
+
|
|
+ // Moves to stream's device to record
|
|
+ const auto orig_device = getDevice();
|
|
+ setDevice(stream.device());
|
|
+
|
|
+ // Creates the event (lazily)
|
|
+ if (!npu_event)
|
|
+ aclrtCreateEvent(&npu_event);
|
|
+ C10_NPU_CHECK(aclrtRecordEvent(npu_event, npu_stream));
|
|
+ // Makes the void* point to the (possibly just allocated) NPU event
|
|
+ *event = npu_event;
|
|
+
|
|
+ // Resets device
|
|
+ setDevice(orig_device);
|
|
+ }
|
|
+
|
|
+ void block(void* event, const Stream& stream) const override {
|
|
+ if (!event)
|
|
+ return;
|
|
+ aclrtEvent npu_event = static_cast<aclrtEvent>(event);
|
|
+ NPUStream npu_stream{stream};
|
|
+ const auto orig_device = getDevice();
|
|
+ setDevice(stream.device());
|
|
+ C10_NPU_CHECK(aclrtStreamWaitEvent(npu_stream, npu_event));
|
|
+ setDevice(orig_device);
|
|
+ }
|
|
+
|
|
+ // May be called from any device
|
|
+ bool queryEvent(void* event) const override {
|
|
+ if (!event)
|
|
+ return true;
|
|
+ aclrtEvent npu_event = static_cast<aclrtEvent>(event);
|
|
+ aclrtEventStatus status;
|
|
+ const aclError err = aclrtQueryEvent(npu_event, &status);
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ C10_NPU_CHECK(err);
|
|
+ }
|
|
+ return (status == ACL_EVENT_STATUS_COMPLETE);
|
|
+ }
|
|
+};
|
|
+
|
|
+} // namespace impl
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/interface/AclInterface.cpp patch/c10/npu/interface/AclInterface.cpp
|
|
--- pytorch-v1.8.1/c10/npu/interface/AclInterface.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/interface/AclInterface.cpp 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,178 @@
|
|
+#include "AclInterface.h"
|
|
+#include "c10/npu/register/FunctionLoader.h"
|
|
+#include "c10/util/Exception.h"
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+namespace acl {
|
|
+#undef LOAD_FUNCTION
|
|
+#define LOAD_FUNCTION(funcName) \
|
|
+ REGISTER_FUNCTION(libascendcl, funcName)
|
|
+#undef GET_FUNC
|
|
+#define GET_FUNC(funcName) \
|
|
+ GET_FUNCTION(libascendcl, funcName)
|
|
+
|
|
+REGISTER_LIBRARY(libascendcl)
|
|
+LOAD_FUNCTION(aclGetRecentErrMsg)
|
|
+LOAD_FUNCTION(aclrtCreateEventWithFlag)
|
|
+LOAD_FUNCTION(aclrtQueryEventWaitStatus)
|
|
+LOAD_FUNCTION(aclprofCreateStepInfo)
|
|
+LOAD_FUNCTION(aclprofGetStepTimestamp)
|
|
+LOAD_FUNCTION(aclprofDestroyStepInfo)
|
|
+LOAD_FUNCTION(aclprofInit)
|
|
+LOAD_FUNCTION(aclprofStart)
|
|
+LOAD_FUNCTION(aclprofStop)
|
|
+LOAD_FUNCTION(aclprofFinalize)
|
|
+LOAD_FUNCTION(aclprofCreateConfig)
|
|
+LOAD_FUNCTION(aclprofDestroyConfig)
|
|
+
|
|
+aclprofStepInfoPtr init_stepinfo(){
|
|
+ typedef aclprofStepInfoPtr(*npdInitFunc)();
|
|
+ static npdInitFunc func = nullptr;
|
|
+ if(func == nullptr){
|
|
+ func = (npdInitFunc)GET_FUNC(aclprofCreateStepInfo);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofCreateStepInfo");
|
|
+ auto ret = func();
|
|
+ return ret;
|
|
+}
|
|
+
|
|
+NpdStatus destroy_stepinfo(aclprofStepInfoPtr stepInfo){
|
|
+ typedef NpdStatus(*npdDestroyFunc)(aclprofStepInfoPtr);
|
|
+ static npdDestroyFunc func = nullptr;
|
|
+ if(func == nullptr){
|
|
+ func = (npdDestroyFunc)GET_FUNC(aclprofDestroyStepInfo);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofDestroyStepInfo");
|
|
+ auto ret = func(stepInfo);
|
|
+ return ret;
|
|
+}
|
|
+
|
|
+NpdStatus start_deliver_op(aclprofStepInfoPtr stepInfo, aclprofStepTag stepTag, aclrtStream stream){
|
|
+ typedef NpdStatus(*npdStartProfiling)(aclprofStepInfoPtr, aclprofStepTag, aclrtStream);
|
|
+ static npdStartProfiling func = nullptr;
|
|
+ if(func == nullptr){
|
|
+ func = (npdStartProfiling)GET_FUNC(aclprofGetStepTimestamp);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofGetStepTimestamp");
|
|
+ auto ret = func(stepInfo, stepTag, stream);
|
|
+ return ret;
|
|
+}
|
|
+
|
|
+NpdStatus stop_deliver_op(aclprofStepInfoPtr stepInfo, aclprofStepTag stepTag, aclrtStream stream){
|
|
+ typedef NpdStatus(*npdStopProfiling)(aclprofStepInfoPtr, aclprofStepTag, aclrtStream);
|
|
+ static npdStopProfiling func = nullptr;
|
|
+ if(func == nullptr){
|
|
+ func = (npdStopProfiling)GET_FUNC(aclprofGetStepTimestamp);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofGetStepTimestamp");
|
|
+ auto ret = func(stepInfo, stepTag, stream);
|
|
+ return ret;
|
|
+}
|
|
+
|
|
+const char *AclGetErrMsg()
|
|
+{
|
|
+ typedef const char *(*aclGetErrMsg)();
|
|
+ static aclGetErrMsg func = nullptr;
|
|
+ if (func == nullptr) {
|
|
+ func = (aclGetErrMsg)GET_FUNC(aclGetRecentErrMsg);
|
|
+ }
|
|
+ if (func != nullptr) {
|
|
+ return func();
|
|
+ }
|
|
+ return "";
|
|
+}
|
|
+
|
|
+aclError AclrtCreateEventWithFlag(aclrtEvent *event, uint32_t flag) {
|
|
+ typedef aclError(*AclrtCreateEventWithFlagFunc)(aclrtEvent*, uint32_t);
|
|
+ static AclrtCreateEventWithFlagFunc func = nullptr;
|
|
+ if (func == nullptr) {
|
|
+ func = (AclrtCreateEventWithFlagFunc)GET_FUNC(aclrtCreateEventWithFlag);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclrtCreateEventWithFlag");
|
|
+ return func(event, flag);
|
|
+}
|
|
+
|
|
+aclError AclQueryEventStatus(aclrtEvent event, aclrtEventWaitStatus *waitStatus, aclrtEventStatus *recordStatus)
|
|
+{
|
|
+ typedef aclError (*aclQueryEventWaitStatus)(aclrtEvent event, aclrtEventWaitStatus *status);
|
|
+ static aclQueryEventWaitStatus func = nullptr;
|
|
+ if (func == nullptr) {
|
|
+ func = (aclQueryEventWaitStatus)GET_FUNC(aclrtQueryEventWaitStatus);
|
|
+ }
|
|
+ if (func != nullptr) {
|
|
+ return func(event, waitStatus);
|
|
+ } else {
|
|
+ return aclrtQueryEvent(event, recordStatus);
|
|
+ }
|
|
+}
|
|
+
|
|
+aclError AclProfilingInit(const char *profilerResultPath, size_t length) {
|
|
+ typedef aclError (*AclProfInitFunc) (const char *, size_t);
|
|
+ static AclProfInitFunc func = nullptr;
|
|
+ if (func == nullptr) {
|
|
+ func = (AclProfInitFunc)GET_FUNC(aclprofInit);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofInit");
|
|
+ return func(profilerResultPath, length);
|
|
+}
|
|
+
|
|
+aclError AclProfilingStart(const aclprofConfig *profilerConfig) {
|
|
+ typedef aclError (*AclProfStartFunc) (const aclprofConfig *);
|
|
+ static AclProfStartFunc func = nullptr;
|
|
+ if (func == nullptr) {
|
|
+ func = (AclProfStartFunc)GET_FUNC(aclprofStart);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofStart");
|
|
+ return func(profilerConfig);
|
|
+}
|
|
+
|
|
+aclError AclProfilingStop(const aclprofConfig *profilerConfig) {
|
|
+ typedef aclError (*AclProfStopFunc) (const aclprofConfig*);
|
|
+ static AclProfStopFunc func = nullptr;
|
|
+ if (func == nullptr) {
|
|
+ func = (AclProfStopFunc)GET_FUNC(aclprofStop);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofStop");
|
|
+ return func(profilerConfig);
|
|
+}
|
|
+
|
|
+aclError AclProfilingFinalize() {
|
|
+ typedef aclError (*AclProfFinalizeFunc) ();
|
|
+ static AclProfFinalizeFunc func = nullptr;
|
|
+ if (func == nullptr) {
|
|
+ func = (AclProfFinalizeFunc)GET_FUNC(aclprofFinalize);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofFinalize");
|
|
+ return func();
|
|
+}
|
|
+
|
|
+aclprofConfig *AclProfilingCreateConfig(
|
|
+ uint32_t *deviceIdList,
|
|
+ uint32_t deviceNums,
|
|
+ aclprofAicoreMetrics aicoreMetrics,
|
|
+ aclprofAicoreEvents *aicoreEvents,
|
|
+ uint64_t dataTypeConfig) {
|
|
+ typedef aclprofConfig *(*AclProfCreateConfigFunc) \
|
|
+ (uint32_t *, uint32_t, aclprofAicoreMetrics, aclprofAicoreEvents *, uint64_t);
|
|
+ static AclProfCreateConfigFunc func = nullptr;
|
|
+ if (func == nullptr) {
|
|
+ func = (AclProfCreateConfigFunc)GET_FUNC(aclprofCreateConfig);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofCreateConfig");
|
|
+ return func(deviceIdList, deviceNums, aicoreMetrics, aicoreEvents, dataTypeConfig);
|
|
+}
|
|
+
|
|
+aclError AclProfilingDestroyConfig(const aclprofConfig *profilerConfig) {
|
|
+ typedef aclError (*AclProfDestroyConfigFunc) (const aclprofConfig *);
|
|
+ static AclProfDestroyConfigFunc func = nullptr;
|
|
+ if (func == nullptr) {
|
|
+ func = (AclProfDestroyConfigFunc)GET_FUNC(aclprofDestroyConfig);
|
|
+ }
|
|
+ TORCH_CHECK(func, "Failed to find function ", "aclprofDestroyConfig");
|
|
+ return func(profilerConfig);
|
|
+}
|
|
+
|
|
+} // namespace acl
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/interface/AclInterface.h patch/c10/npu/interface/AclInterface.h
|
|
--- pytorch-v1.8.1/c10/npu/interface/AclInterface.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/interface/AclInterface.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,80 @@
|
|
+#ifndef __C10_NPU_INTERFACE_ACLINTERFACE__
|
|
+#define __C10_NPU_INTERFACE_ACLINTERFACE__
|
|
+
|
|
+#include "third_party/acl/inc/acl/acl_rt.h"
|
|
+#include <third_party/acl/inc/acl/acl_base.h>
|
|
+#include <third_party/acl/inc/acl/acl_prof.h>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+namespace acl {
|
|
+typedef enum aclrtEventWaitStatus {
|
|
+ ACL_EVENT_WAIT_STATUS_COMPLETE = 0,
|
|
+ ACL_EVENT_WAIT_STATUS_NOT_READY = 1,
|
|
+ ACL_EVENT_WAIT_STATUS_RESERVED = 0xffff,
|
|
+} aclrtEventWaitStatus;
|
|
+
|
|
+/**
|
|
+ aclprofStepInfo is provide by acl, it used to be store dispatch op info.
|
|
+ */
|
|
+using aclprofStepInfoPtr = aclprofStepInfo *;
|
|
+/**
|
|
+ NpdStatus is provide by acl, it used to store the return value.
|
|
+ */
|
|
+using NpdStatus = int;
|
|
+
|
|
+/**
|
|
+ This Api is used to init npd, it need to be called once at process.
|
|
+ */
|
|
+aclprofStepInfoPtr init_stepinfo();
|
|
+/**
|
|
+ This Api is used to destroy npd, it need to be called once at process.
|
|
+ */
|
|
+NpdStatus destroy_stepinfo(aclprofStepInfoPtr stepInfo);
|
|
+/**
|
|
+ This Api is used to start dispatch op, this operation should be called after init.
|
|
+ */
|
|
+NpdStatus start_deliver_op(aclprofStepInfoPtr stepInfo, aclprofStepTag stepTag, aclrtStream stream);
|
|
+/**
|
|
+ This Api is used to stop dispatch op, this operation should be called after start dispatch op.
|
|
+ */
|
|
+NpdStatus stop_deliver_op(aclprofStepInfoPtr stepInfo, aclprofStepTag stepTag, aclrtStream stream);
|
|
+
|
|
+/**
|
|
+ This API is used to get error msg
|
|
+ */
|
|
+const char *AclGetErrMsg();
|
|
+
|
|
+/**
|
|
+ * @ingroup AscendCL
|
|
+ * @brief create event instance
|
|
+ *
|
|
+ * @param event [OUT] created event
|
|
+ * @param flag [IN] event flag
|
|
+ * @retval ACL_ERROR_NONE The function is successfully executed.
|
|
+ * @retval OtherValues Failure
|
|
+ */
|
|
+aclError AclrtCreateEventWithFlag(aclrtEvent *event, uint32_t flag);
|
|
+
|
|
+/**
|
|
+ This API is used to query status of event task
|
|
+ */
|
|
+aclError AclQueryEventStatus(aclrtEvent event, aclrtEventWaitStatus *waitStatus, aclrtEventStatus *recordStatus);
|
|
+
|
|
+aclError AclProfilingInit(const char *profilerResultPath, size_t length);
|
|
+aclError AclProfilingStart(const aclprofConfig *profilerConfig);
|
|
+aclError AclProfilingStop(const aclprofConfig *profilerConfig);
|
|
+aclError AclProfilingFinalize();
|
|
+aclprofConfig * AclProfilingCreateConfig(
|
|
+ uint32_t *deviceIdList,
|
|
+ uint32_t deviceNums,
|
|
+ aclprofAicoreMetrics aicoreMetrics,
|
|
+ aclprofAicoreEvents *aicoreEvents,
|
|
+ uint64_t dataTypeConfig);
|
|
+aclError AclProfilingDestroyConfig(const aclprofConfig *profilerConfig);
|
|
+
|
|
+} // namespace acl
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
+
|
|
+#endif // __C10_NPU_INTERFACE_ACLINTERFACE__
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/interface/AsyncTaskQueueInterface.cpp patch/c10/npu/interface/AsyncTaskQueueInterface.cpp
|
|
--- pytorch-v1.8.1/c10/npu/interface/AsyncTaskQueueInterface.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/interface/AsyncTaskQueueInterface.cpp 2022-04-02 16:30:53.433581347 +0800
|
|
@@ -0,0 +1,229 @@
|
|
+#include "AsyncTaskQueueInterface.h"
|
|
+#include "c10/npu/NPUEventManager.h"
|
|
+#include "c10/npu/OptionsManager.h"
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+namespace queue {
|
|
+void CopyParas::Copy(CopyParas& other) {
|
|
+ this->dst = other.dst;
|
|
+ this->dstLen = other.dstLen;
|
|
+ this->src = other.src;
|
|
+ this->srcLen = other.srcLen;
|
|
+ this->kind = other.kind;
|
|
+ if (!other.pinMem.empty()) {
|
|
+ this->pinMem = other.pinMem;
|
|
+ }
|
|
+}
|
|
+
|
|
+void EventParas::Copy(EventParas& other) {
|
|
+ this->event = other.event;
|
|
+ this->eventAllocatorType = other.eventAllocatorType;
|
|
+}
|
|
+
|
|
+class AsyncCopyTask {
|
|
+ public:
|
|
+ AsyncCopyTask(
|
|
+ void* dst,
|
|
+ size_t dstLen,
|
|
+ void* src,
|
|
+ size_t srcLen,
|
|
+ aclrtMemcpyKind kind);
|
|
+ AsyncCopyTask(
|
|
+ void* dst,
|
|
+ size_t dstLen,
|
|
+ void* src,
|
|
+ size_t srcLen,
|
|
+ aclrtMemcpyKind kind,
|
|
+ Storage& st);
|
|
+ ~AsyncCopyTask() = default;
|
|
+ void LaunchCopyTask();
|
|
+ void LaunchCopyTask(bool isPinnedMem);
|
|
+
|
|
+ private:
|
|
+ CopyParas copyParam_;
|
|
+};
|
|
+
|
|
+class EventTask {
|
|
+ public:
|
|
+ explicit EventTask(
|
|
+ aclrtEvent event,
|
|
+ EventAllocatorType allocatorType = RESERVED)
|
|
+ : eventParam_(event, allocatorType){};
|
|
+ ~EventTask() = default;
|
|
+ void LaunchRecordTask(
|
|
+ at::npu::NPUStream npuStream,
|
|
+ SmallVector<Storage, N>& needClearVec);
|
|
+ void LaunchWaitTask(at::npu::NPUStream npuStream);
|
|
+ void LaunchLazyDestroyTask();
|
|
+
|
|
+ private:
|
|
+ EventParas eventParam_;
|
|
+};
|
|
+
|
|
+AsyncCopyTask::AsyncCopyTask(
|
|
+ void* dst,
|
|
+ size_t dstLen,
|
|
+ void* src,
|
|
+ size_t srcLen,
|
|
+ aclrtMemcpyKind kind) {
|
|
+ copyParam_.dst = dst;
|
|
+ copyParam_.dstLen = dstLen;
|
|
+ copyParam_.src = src;
|
|
+ copyParam_.srcLen = srcLen;
|
|
+ copyParam_.kind = kind;
|
|
+}
|
|
+
|
|
+AsyncCopyTask::AsyncCopyTask(
|
|
+ void* dst,
|
|
+ size_t dstLen,
|
|
+ void* src,
|
|
+ size_t srcLen,
|
|
+ aclrtMemcpyKind kind,
|
|
+ Storage& st) {
|
|
+ copyParam_.dst = dst;
|
|
+ copyParam_.dstLen = dstLen;
|
|
+ copyParam_.src = src;
|
|
+ copyParam_.srcLen = srcLen;
|
|
+ copyParam_.kind = kind;
|
|
+ copyParam_.pinMem.emplace_back(st);
|
|
+}
|
|
+
|
|
+void AsyncCopyTask::LaunchCopyTask() {
|
|
+ if (c10::npu::OptionsManager::CheckQueueEnable()) {
|
|
+ QueueParas params(ASYNC_MEMCPY, sizeof(CopyParas), ©Param_);
|
|
+ SmallVector<Storage, N> needClearVec;
|
|
+ c10::npu::enCurrentNPUStream(¶ms, needClearVec);
|
|
+ // free pin memory
|
|
+ needClearVec.clear();
|
|
+ } else {
|
|
+ c10::npu::NPUStream stream = c10::npu::getCurrentNPUStream();
|
|
+ C10_NPU_CHECK(aclrtMemcpyAsync(
|
|
+ copyParam_.dst,
|
|
+ copyParam_.dstLen,
|
|
+ copyParam_.src,
|
|
+ copyParam_.srcLen,
|
|
+ copyParam_.kind,
|
|
+ stream));
|
|
+ }
|
|
+}
|
|
+
|
|
+void AsyncCopyTask::LaunchCopyTask(bool isPinnedMem) {
|
|
+ if (c10::npu::OptionsManager::CheckQueueEnable() && isPinnedMem) {
|
|
+ QueueParas params(ASYNC_MEMCPY_EX, sizeof(CopyParas), ©Param_);
|
|
+ SmallVector<Storage, N> needClearVec;
|
|
+ c10::npu::enCurrentNPUStream(¶ms, needClearVec);
|
|
+ // free pin memory
|
|
+ needClearVec.clear();
|
|
+ } else {
|
|
+ c10::npu::NPUStream stream = c10::npu::getCurrentNPUStream();
|
|
+ C10_NPU_CHECK(aclrtMemcpyAsync(
|
|
+ copyParam_.dst,
|
|
+ copyParam_.dstLen,
|
|
+ copyParam_.src,
|
|
+ copyParam_.srcLen,
|
|
+ copyParam_.kind,
|
|
+ stream));
|
|
+ }
|
|
+}
|
|
+
|
|
+aclError LaunchAsyncCopyTask(
|
|
+ void* dst,
|
|
+ size_t dstLen,
|
|
+ void* src,
|
|
+ size_t srcLen,
|
|
+ aclrtMemcpyKind kind) {
|
|
+ AsyncCopyTask copyTask(dst, dstLen, src, srcLen, kind);
|
|
+ copyTask.LaunchCopyTask();
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+
|
|
+aclError LaunchAsyncCopyTask(
|
|
+ void* dst,
|
|
+ size_t dstLen,
|
|
+ void* src,
|
|
+ size_t srcLen,
|
|
+ aclrtMemcpyKind kind,
|
|
+ Storage& st,
|
|
+ bool isPinMem) {
|
|
+ AsyncCopyTask copyTask(dst, dstLen, src, srcLen, kind, st);
|
|
+ copyTask.LaunchCopyTask(isPinMem);
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+
|
|
+void EventTask::LaunchRecordTask(
|
|
+ at::npu::NPUStream npuStream,
|
|
+ SmallVector<Storage, N>& needClearVec) {
|
|
+ if (c10::npu::OptionsManager::CheckQueueEnable()) {
|
|
+ at::npu::NPUStream currentStream = c10::npu::getCurrentNPUStream();
|
|
+ c10::npu::setCurrentNPUStream(npuStream);
|
|
+ QueueParas params(RECORD_EVENT, sizeof(EventParas), &eventParam_);
|
|
+ c10::npu::enCurrentNPUStream(¶ms, needClearVec);
|
|
+ c10::npu::setCurrentNPUStream(currentStream);
|
|
+ } else {
|
|
+ C10_NPU_CHECK(aclrtRecordEvent(eventParam_.event, npuStream));
|
|
+ }
|
|
+}
|
|
+
|
|
+aclError HostAllocatorLaunchRecordEventTask(
|
|
+ aclrtEvent event,
|
|
+ at::npu::NPUStream npuStream,
|
|
+ SmallVector<Storage, N>& needClearVec) {
|
|
+ EventTask recordTask(event, HOST_ALLOCATOR_EVENT);
|
|
+ recordTask.LaunchRecordTask(npuStream, needClearVec);
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+
|
|
+aclError NpuAllocatorLaunchRecordEventTask(
|
|
+ aclrtEvent event,
|
|
+ at::npu::NPUStream npuStream) {
|
|
+ EventTask recordTask(event, NPU_ALLOCATOR_EVENT);
|
|
+ SmallVector<Storage, N> needClearVec;
|
|
+ recordTask.LaunchRecordTask(npuStream, needClearVec);
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+
|
|
+aclError LaunchRecordEventTask(aclrtEvent event, at::npu::NPUStream npuStream) {
|
|
+ EventTask recordTask(event);
|
|
+ SmallVector<Storage, N> needClearVec;
|
|
+ recordTask.LaunchRecordTask(npuStream, needClearVec);
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+
|
|
+void EventTask::LaunchWaitTask(at::npu::NPUStream npuStream) {
|
|
+ if (c10::npu::OptionsManager::CheckQueueEnable()) {
|
|
+ at::npu::NPUStream currentStream = c10::npu::getCurrentNPUStream();
|
|
+ c10::npu::setCurrentNPUStream(npuStream);
|
|
+ QueueParas params(WAIT_EVENT, sizeof(EventParas), &eventParam_);
|
|
+ SmallVector<Storage, N> needClearVec;
|
|
+ c10::npu::enCurrentNPUStream(¶ms, needClearVec);
|
|
+ c10::npu::setCurrentNPUStream(currentStream);
|
|
+ } else {
|
|
+ C10_NPU_CHECK(aclrtStreamWaitEvent(npuStream, eventParam_.event));
|
|
+ }
|
|
+}
|
|
+
|
|
+aclError LaunchWaitEventTask(aclrtEvent event, at::npu::NPUStream npuStream) {
|
|
+ EventTask waitTask(event);
|
|
+ waitTask.LaunchWaitTask(npuStream);
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+
|
|
+void EventTask::LaunchLazyDestroyTask() {
|
|
+ if (c10::npu::OptionsManager::CheckQueueEnable()) {
|
|
+ QueueParas params(LAZY_DESTROY_EVENT, sizeof(EventParas), &eventParam_);
|
|
+ SmallVector<Storage, N> needClearVec;
|
|
+ c10::npu::enCurrentNPUStream(¶ms, needClearVec);
|
|
+ } else {
|
|
+ C10_NPU_CHECK(c10::npu::NPUEventManager::GetInstance().LazyDestroy(
|
|
+ eventParam_.event));
|
|
+ }
|
|
+}
|
|
+
|
|
+aclError LaunchLazyDestroyEventTask(aclrtEvent event) {
|
|
+ EventTask lazyDestroyTask(event);
|
|
+ lazyDestroyTask.LaunchLazyDestroyTask();
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+} // namespace queue
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/interface/AsyncTaskQueueInterface.h patch/c10/npu/interface/AsyncTaskQueueInterface.h
|
|
--- pytorch-v1.8.1/c10/npu/interface/AsyncTaskQueueInterface.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/interface/AsyncTaskQueueInterface.h 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -0,0 +1,73 @@
|
|
+#ifndef __C10_NPU_INTERFACE_ASYNCTASKQUEUEINTERFACE__
|
|
+#define __C10_NPU_INTERFACE_ASYNCTASKQUEUEINTERFACE__
|
|
+
|
|
+#include "c10/core/Storage.h"
|
|
+#include "c10/npu/NPUStream.h"
|
|
+#include "third_party/acl/inc/acl/acl_rt.h"
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+namespace queue {
|
|
+struct CopyParas {
|
|
+ void *dst = nullptr;
|
|
+ size_t dstLen = 0;
|
|
+ void *src = nullptr;
|
|
+ size_t srcLen = 0;
|
|
+ aclrtMemcpyKind kind = ACL_MEMCPY_HOST_TO_HOST;
|
|
+ SmallVector<Storage, 1> pinMem;
|
|
+ void Copy(CopyParas& other);
|
|
+};
|
|
+
|
|
+enum EventAllocatorType {
|
|
+ HOST_ALLOCATOR_EVENT = 1,
|
|
+ NPU_ALLOCATOR_EVENT = 2,
|
|
+ RESERVED = -1,
|
|
+};
|
|
+
|
|
+struct EventParas {
|
|
+ explicit EventParas(aclrtEvent aclEvent, EventAllocatorType allocatorType) :
|
|
+ event(aclEvent), eventAllocatorType(allocatorType) {}
|
|
+ aclrtEvent event = nullptr;
|
|
+ void Copy(EventParas& other);
|
|
+ EventAllocatorType eventAllocatorType = RESERVED;
|
|
+};
|
|
+
|
|
+enum QueueParamType {
|
|
+ COMPILE_AND_EXECUTE = 1,
|
|
+ ASYNC_MEMCPY = 2,
|
|
+ ASYNC_MEMCPY_EX = 3,
|
|
+ RECORD_EVENT = 4,
|
|
+ WAIT_EVENT = 5,
|
|
+ LAZY_DESTROY_EVENT = 6,
|
|
+};
|
|
+
|
|
+struct QueueParas {
|
|
+ QueueParas(QueueParamType type, size_t len, void *val) : paramType(type), paramLen(len), paramVal(val) {}
|
|
+ aclrtStream paramStream = nullptr;
|
|
+ QueueParamType paramType = COMPILE_AND_EXECUTE;
|
|
+ size_t paramLen = 0;
|
|
+ void* paramVal = nullptr;
|
|
+};
|
|
+
|
|
+aclError LaunchAsyncCopyTask(void* dst, size_t dstLen, void* src, size_t srcLen, aclrtMemcpyKind kind);
|
|
+
|
|
+aclError LaunchAsyncCopyTask(void* dst, size_t dstLen, void* src, size_t srcLen, aclrtMemcpyKind kind,
|
|
+ Storage& st, bool isPinMem);
|
|
+
|
|
+aclError HostAllocatorLaunchRecordEventTask(aclrtEvent event,
|
|
+ at::npu::NPUStream npuStream,
|
|
+ SmallVector<Storage, N>& needClearVec);
|
|
+
|
|
+aclError NpuAllocatorLaunchRecordEventTask(aclrtEvent event,
|
|
+ at::npu::NPUStream npuStream);
|
|
+
|
|
+aclError LaunchRecordEventTask(aclrtEvent event, at::npu::NPUStream npuStream);
|
|
+
|
|
+aclError LaunchWaitEventTask(aclrtEvent event, at::npu::NPUStream npuStream);
|
|
+
|
|
+aclError LaunchLazyDestroyEventTask(aclrtEvent event);
|
|
+} // namespace queue
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
+
|
|
+#endif // __C10_NPU_INTERFACE_ASYNCTASKQUEUEINTERFACE__
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUEvent.h patch/c10/npu/NPUEvent.h
|
|
--- pytorch-v1.8.1/c10/npu/NPUEvent.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUEvent.h 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -0,0 +1,157 @@
|
|
+#pragma once
|
|
+
|
|
+#include <c10/npu/NPUStream.h>
|
|
+#include <c10/npu/NPUGuard.h>
|
|
+#include <third_party/acl/inc/acl/acl.h>
|
|
+#include <c10/npu/NPUException.h>
|
|
+#include <c10/npu/NPUEventManager.h>
|
|
+#include <c10/npu/interface/AsyncTaskQueueInterface.h>
|
|
+#include <cstdint>
|
|
+#include <utility>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+using namespace c10::npu;
|
|
+/*
|
|
+* NPUEvents are movable not copyable wrappers around NPU's events.
|
|
+* NPUEvents are constructed lazily when first recorded.
|
|
+*/
|
|
+struct C10_EXPORT NPUEvent {
|
|
+ // Constructors
|
|
+ // Default value for `flags` is specified below
|
|
+ NPUEvent() {}
|
|
+
|
|
+ // flags is an useless parameter for npu
|
|
+ // NPUEvent(unsigned int flags) : flags_{flags} {}
|
|
+
|
|
+ // npu do not support IpcEventHandle until now
|
|
+
|
|
+ ~NPUEvent() {
|
|
+ try {
|
|
+ if (is_created_) {
|
|
+ C10_NPU_CHECK(c10::npu::queue::LaunchLazyDestroyEventTask(event_));
|
|
+ C10_NPU_CHECK(c10::npu::NPUEventManager::GetInstance().QueryAndDestroyEvent());
|
|
+ }
|
|
+ } catch (...) {} /* No throw */
|
|
+ }
|
|
+
|
|
+ NPUEvent(const NPUEvent&) = delete;
|
|
+ NPUEvent& operator=(const NPUEvent&) = delete;
|
|
+
|
|
+ NPUEvent(NPUEvent&& other) { moveHelper(std::move(other)); }
|
|
+ NPUEvent& operator=(NPUEvent&& other) {
|
|
+ moveHelper(std::move(other));
|
|
+ return *this;
|
|
+ }
|
|
+
|
|
+ operator aclrtEvent() const { return event(); }
|
|
+
|
|
+ // aclrtEvent do not support Less than operator until now
|
|
+
|
|
+ optional<at::Device> device() const {
|
|
+ if (is_created_) {
|
|
+ return at::Device(at::kNPU, device_index_);
|
|
+ } else {
|
|
+ return {};
|
|
+ }
|
|
+ }
|
|
+
|
|
+ bool isCreated() const { return is_created_; }
|
|
+ DeviceIndex device_index() const {return device_index_;}
|
|
+ aclrtEvent event() const { return event_; }
|
|
+
|
|
+ bool query() const {
|
|
+ if (!is_created_) {
|
|
+ return true;
|
|
+ }
|
|
+ NPUStatus ret = c10::npu::emptyAllNPUStream();
|
|
+ if (ret != SUCCESS) {
|
|
+ NPU_LOGE("MakeSureQueueEmpty fail, ret: %s", ret.c_str());
|
|
+ }
|
|
+ aclrtEventStatus currStatus = ACL_EVENT_STATUS_COMPLETE;
|
|
+ C10_NPU_CHECK(aclrtQueryEvent(event_, &currStatus));
|
|
+
|
|
+ if (currStatus == ACL_EVENT_STATUS_COMPLETE) {
|
|
+ return true;
|
|
+ }
|
|
+ return false;
|
|
+ }
|
|
+
|
|
+ void record() { record(getCurrentNPUStream()); }
|
|
+
|
|
+ void recordOnce(const NPUStream& stream) {
|
|
+ if (!was_recorded_) record(stream);
|
|
+ }
|
|
+
|
|
+ void record(const NPUStream& stream) {
|
|
+ if (!is_created_) {
|
|
+ createEvent(stream.device_index());
|
|
+ }
|
|
+
|
|
+ TORCH_CHECK(device_index_ == stream.device_index(), "Event device ", device_index_,
|
|
+ " does not match recording stream's device ", stream.device_index(), ".");
|
|
+ NPUGuard guard(device_index_);
|
|
+ C10_NPU_CHECK(c10::npu::queue::LaunchRecordEventTask(event_, stream));
|
|
+ was_recorded_ = true;
|
|
+ }
|
|
+
|
|
+ void block(const NPUStream& stream) {
|
|
+ if (is_created_) {
|
|
+ NPUGuard guard(stream.device_index());
|
|
+ C10_NPU_CHECK(c10::npu::queue::LaunchWaitEventTask(event_, stream));
|
|
+ }
|
|
+ }
|
|
+
|
|
+ float elapsed_time(const NPUEvent& other) const {
|
|
+ TORCH_CHECK(is_created_ && other.isCreated(),
|
|
+ "Both events must be recorded before calculating elapsed time.");
|
|
+ float time_ms = 0;
|
|
+ NPUStatus ret = c10::npu::emptyAllNPUStream();
|
|
+ if (ret != SUCCESS) {
|
|
+ NPU_LOGE("MakeSureQueueEmpty fail, ret: %s", ret.c_str());
|
|
+ }
|
|
+
|
|
+ C10_NPU_CHECK(aclrtSynchronizeEvent(event_));
|
|
+ C10_NPU_CHECK(aclrtSynchronizeEvent(other.event_));
|
|
+ // raise error if either event is recorded but not yet completed
|
|
+ C10_NPU_CHECK(aclrtEventElapsedTime(&time_ms, event_, other.event_));
|
|
+ return time_ms;
|
|
+ }
|
|
+
|
|
+ void synchronize() const {
|
|
+ if (is_created_) {
|
|
+ NPUStatus ret = c10::npu::emptyAllNPUStream();
|
|
+ if (ret != SUCCESS) {
|
|
+ NPU_LOGE("MakeSureQueueEmpty fail, ret: %s", ret.c_str());
|
|
+ }
|
|
+ C10_NPU_CHECK(aclrtSynchronizeEvent(event_));
|
|
+ }
|
|
+ }
|
|
+
|
|
+ // npu do not support IpcEventHandle until now
|
|
+
|
|
+private:
|
|
+ bool is_created_ = false;
|
|
+ bool was_recorded_ = false;
|
|
+ DeviceIndex device_index_ = -1;
|
|
+ aclrtEvent event_ = nullptr;
|
|
+
|
|
+ void createEvent(DeviceIndex device_index) {
|
|
+ device_index_ = device_index;
|
|
+ NPUGuard guard(device_index_);
|
|
+ C10_NPU_CHECK(aclrtCreateEvent(&event_));
|
|
+ is_created_ = true;
|
|
+ }
|
|
+
|
|
+ void moveHelper(NPUEvent&& other) {
|
|
+ std::swap(is_created_, other.is_created_);
|
|
+ std::swap(was_recorded_, other.was_recorded_);
|
|
+ std::swap(device_index_, other.device_index_);
|
|
+ std::swap(event_, other.event_);
|
|
+ }
|
|
+};
|
|
+
|
|
+} // namespace NPU
|
|
+} // namespace at
|
|
+
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUEventManager.cpp patch/c10/npu/NPUEventManager.cpp
|
|
--- pytorch-v1.8.1/c10/npu/NPUEventManager.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUEventManager.cpp 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -0,0 +1,51 @@
|
|
+#include "NPUEventManager.h"
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+NPUEventManager::NPUEventManager() {};
|
|
+
|
|
+NPUEventManager& NPUEventManager::GetInstance() {
|
|
+ static NPUEventManager instance;
|
|
+ return instance;
|
|
+}
|
|
+
|
|
+aclError NPUEventManager::QueryAndDestroyEvent() {
|
|
+ std::lock_guard<std::mutex> guard(event_queue_mutex_);
|
|
+ while (!npu_events_.empty())
|
|
+ {
|
|
+ aclrtEvent event = npu_events_.front();
|
|
+ acl::aclrtEventWaitStatus waitStatus = acl::ACL_EVENT_WAIT_STATUS_RESERVED;
|
|
+ aclrtEventStatus recordStatus = ACL_EVENT_STATUS_RESERVED;
|
|
+ aclError err = acl::AclQueryEventStatus(event, &waitStatus, &recordStatus);
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ return err;
|
|
+ }
|
|
+ if ((waitStatus != acl::ACL_EVENT_WAIT_STATUS_COMPLETE) &&
|
|
+ (recordStatus != ACL_EVENT_STATUS_COMPLETE)) {
|
|
+ break;
|
|
+ }
|
|
+ err = aclrtDestroyEvent(event);
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ C10_NPU_SHOW_ERR_MSG();
|
|
+ return err;
|
|
+ }
|
|
+ npu_events_.pop_front();
|
|
+ }
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+
|
|
+aclError NPUEventManager::LazyDestroy(aclrtEvent npu_event) {
|
|
+ std::lock_guard<std::mutex> guard(event_queue_mutex_);
|
|
+ npu_events_.push_back(npu_event);
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+
|
|
+aclError NPUEventManager::ClearEvent() {
|
|
+ while(!npu_events_.empty()) {
|
|
+ aclrtEvent event = npu_events_.front();
|
|
+ C10_NPU_CHECK(aclrtDestroyEvent(event));
|
|
+ npu_events_.pop_front();
|
|
+ }
|
|
+ return ACL_ERROR_NONE;
|
|
+}
|
|
+} // namespace NPU
|
|
+} // namespace c10
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUEventManager.h patch/c10/npu/NPUEventManager.h
|
|
--- pytorch-v1.8.1/c10/npu/NPUEventManager.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUEventManager.h 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -0,0 +1,23 @@
|
|
+#pragma once
|
|
+
|
|
+#include <c10/npu/NPUException.h>
|
|
+#include <third_party/acl/inc/acl/acl.h>
|
|
+#include <deque>
|
|
+#include <mutex>
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+class C10_EXPORT NPUEventManager {
|
|
+public:
|
|
+ static NPUEventManager& GetInstance();
|
|
+ aclError QueryAndDestroyEvent();
|
|
+ aclError LazyDestroy(aclrtEvent npu_event);
|
|
+ aclError ClearEvent();
|
|
+ ~NPUEventManager(){}
|
|
+
|
|
+private:
|
|
+ std::mutex event_queue_mutex_;
|
|
+ NPUEventManager();
|
|
+ std::deque<aclrtEvent> npu_events_;
|
|
+};
|
|
+} // namespace NPU
|
|
+} // namespace c10
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUException.h patch/c10/npu/NPUException.h
|
|
--- pytorch-v1.8.1/c10/npu/NPUException.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUException.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,35 @@
|
|
+#pragma once
|
|
+
|
|
+#include <iostream>
|
|
+#include <c10/macros/Macros.h>
|
|
+#include <c10/util/Exception.h>
|
|
+#include <third_party/acl/inc/acl/acl_base.h>
|
|
+#include <c10/npu/interface/AclInterface.h>
|
|
+
|
|
+#define C10_NPU_SHOW_ERR_MSG() \
|
|
+do { \
|
|
+ std::cout<<c10::npu::acl::AclGetErrMsg()<<std::endl; \
|
|
+} while (0)
|
|
+
|
|
+#define C10_NPU_CHECK(Error) \
|
|
+ do { \
|
|
+ if ((Error) != ACL_ERROR_NONE) { \
|
|
+ TORCH_CHECK( \
|
|
+ false, \
|
|
+ __func__, \
|
|
+ ":", \
|
|
+ __FILE__, \
|
|
+ ":", \
|
|
+ __LINE__, \
|
|
+ " NPU error, error code is ", Error, \
|
|
+ "\n", c10::npu::acl::AclGetErrMsg()); \
|
|
+ } \
|
|
+ } while (0)
|
|
+
|
|
+#define C10_NPU_CHECK_WARN(Error) \
|
|
+ do { \
|
|
+ if ((Error) != ACL_ERROR_NONE) { \
|
|
+ TORCH_WARN("NPU warning, error code is ", Error, \
|
|
+ "\n", c10::npu::acl::AclGetErrMsg()); \
|
|
+ } \
|
|
+ } while (0)
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUFunctions.h patch/c10/npu/NPUFunctions.h
|
|
--- pytorch-v1.8.1/c10/npu/NPUFunctions.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUFunctions.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,49 @@
|
|
+#pragma once
|
|
+
|
|
+// This header provides C++ wrappers around commonly used CUDA API functions.
|
|
+// The benefit of using C++ here is that we can raise an exception in the
|
|
+// event of an error, rather than explicitly pass around error codes. This
|
|
+// leads to more natural APIs.
|
|
+//
|
|
+// The naming convention used here matches the naming convention of torch.cuda
|
|
+
|
|
+#include <c10/core/Device.h>
|
|
+#include <c10/macros/Macros.h>
|
|
+#include <c10/npu/NPUException.h>
|
|
+#include <c10/npu/npu_log.h>
|
|
+#include <third_party/acl/inc/acl/acl.h>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+inline DeviceIndex device_count() noexcept {
|
|
+ unsigned int count = 1;
|
|
+ // NB: In the past, we were inconsistent about whether or not this reported
|
|
+ // an error if there were driver problems are not. Based on experience
|
|
+ // interacting with users, it seems that people basically ~never want this
|
|
+ // function to fail; it should just return zero if things are not working.
|
|
+ // Oblige them.
|
|
+ aclError error = aclrtGetDeviceCount(&count);
|
|
+ if (error != ACL_ERROR_NONE) {
|
|
+ // Clear out the error state, so we don't spuriously trigger someone else.
|
|
+ // (This shouldn't really matter, since we won't be running very much CUDA
|
|
+ // code in this regime.)
|
|
+ // npuError_t last_err = npuGetLastError();
|
|
+ // (void)last_err;
|
|
+ NPU_LOGE("get device count of NPU failed");
|
|
+ return 0;
|
|
+ }
|
|
+ return static_cast<DeviceIndex>(count);
|
|
+}
|
|
+
|
|
+inline DeviceIndex current_device() {
|
|
+ int cur_device = 0;
|
|
+ C10_NPU_CHECK(aclrtGetDevice(&cur_device));
|
|
+ return static_cast<DeviceIndex>(cur_device);
|
|
+}
|
|
+
|
|
+inline void set_device(DeviceIndex device) {
|
|
+ // C10_NPU_CHECK(npuSetDevice(static_cast<int>(device)));
|
|
+}
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUGuard.h patch/c10/npu/NPUGuard.h
|
|
--- pytorch-v1.8.1/c10/npu/NPUGuard.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUGuard.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,274 @@
|
|
+#pragma once
|
|
+
|
|
+#include <c10/core/DeviceType.h>
|
|
+#include <c10/core/impl/InlineDeviceGuard.h>
|
|
+#include <c10/core/impl/InlineStreamGuard.h>
|
|
+#include <c10/npu/NPUMacros.h>
|
|
+#include <c10/npu/impl/NPUGuardImpl.h>
|
|
+
|
|
+#include <cstddef>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+// This code is kind of boilerplatey. See Note [Whither the DeviceGuard
|
|
+// boilerplate]
|
|
+
|
|
+/// A variant of DeviceGuard that is specialized for NPU. It accepts
|
|
+/// integer indices (interpreting them as NPU devices) and is a little
|
|
+/// more efficient than DeviceGuard (it compiles to straight line
|
|
+/// NPUSetDevice/NPUGetDevice calls); however, it can only be used
|
|
+/// from code that links against NPU directly.
|
|
+struct NPUGuard {
|
|
+ /// No default constructor; see Note [Omitted default constructor from RAII]
|
|
+ explicit NPUGuard() = delete;
|
|
+
|
|
+ /// Set the current NPU device to the passed device index.
|
|
+ explicit NPUGuard(DeviceIndex device_index) : guard_(device_index) {}
|
|
+
|
|
+ /// Sets the current NPU device to the passed device. Errors if the passed
|
|
+ /// device is not a NPU device.
|
|
+ explicit NPUGuard(Device device) : guard_(device) {}
|
|
+
|
|
+ // Copy is not allowed
|
|
+ NPUGuard(const NPUGuard&) = delete;
|
|
+ NPUGuard& operator=(const NPUGuard&) = delete;
|
|
+
|
|
+ // Move is not allowed (there is no uninitialized state)
|
|
+ NPUGuard(NPUGuard&& other) = delete;
|
|
+ NPUGuard& operator=(NPUGuard&& other) = delete;
|
|
+
|
|
+ /// Sets the NPU device to the given device. Errors if the given device
|
|
+ /// is not a NPU device.
|
|
+ void set_device(Device device) {
|
|
+ guard_.set_device(device);
|
|
+ }
|
|
+
|
|
+ /// Sets the NPU device to the given device. Errors if the given device
|
|
+ /// is not a NPU device. (This method is provided for uniformity with
|
|
+ /// DeviceGuard).
|
|
+ void reset_device(Device device) {
|
|
+ guard_.reset_device(device);
|
|
+ }
|
|
+
|
|
+ /// Sets the NPU device to the given device index.
|
|
+ void set_index(DeviceIndex device_index) {
|
|
+ guard_.set_index(device_index);
|
|
+ }
|
|
+
|
|
+ /// Returns the device that was set upon construction of the guard
|
|
+ Device original_device() const {
|
|
+ return guard_.original_device();
|
|
+ }
|
|
+
|
|
+ /// Returns the last device that was set via `set_device`, if any, otherwise
|
|
+ /// the device passed during construction.
|
|
+ Device current_device() const {
|
|
+ return guard_.current_device();
|
|
+ }
|
|
+
|
|
+ private:
|
|
+ /// The guard for the current device.
|
|
+ c10::impl::InlineDeviceGuard<impl::NPUGuardImpl> guard_;
|
|
+};
|
|
+
|
|
+/// A variant of OptionalDeviceGuard that is specialized for NPU. See
|
|
+/// NPUGuard for when you can use this.
|
|
+struct OptionalNPUGuard {
|
|
+ /// Create an uninitialized OptionalNPUGuard.
|
|
+ explicit OptionalNPUGuard() : guard_() {}
|
|
+
|
|
+ /// Set the current NPU device to the passed Device, if it is not nullopt.
|
|
+ explicit OptionalNPUGuard(optional<Device> device_opt) : guard_(device_opt) {}
|
|
+
|
|
+ /// Set the current NPU device to the passed device index, if it is not
|
|
+ /// nullopt
|
|
+ explicit OptionalNPUGuard(optional<DeviceIndex> device_index_opt)
|
|
+ : guard_(device_index_opt) {}
|
|
+
|
|
+ // Copy is not allowed
|
|
+ OptionalNPUGuard(const OptionalNPUGuard&) = delete;
|
|
+ OptionalNPUGuard& operator=(const OptionalNPUGuard&) = delete;
|
|
+
|
|
+ // See Note [Move construction for RAII guards is tricky]
|
|
+ OptionalNPUGuard(OptionalNPUGuard&& other) = delete;
|
|
+
|
|
+ // See Note [Move assignment for RAII guards is tricky]
|
|
+ OptionalNPUGuard& operator=(OptionalNPUGuard&& other) = delete;
|
|
+
|
|
+ /// Sets the NPU device to the given device, initializing the guard if it
|
|
+ /// is not already initialized. Errors if the given device is not a NPU
|
|
+ /// device.
|
|
+ void set_device(Device device) {
|
|
+ guard_.set_device(device);
|
|
+ }
|
|
+
|
|
+ /// Sets the NPU device to the given device, initializing the guard if it is
|
|
+ /// not already initialized. Errors if the given device is not a NPU device.
|
|
+ /// (This method is provided for uniformity with OptionalDeviceGuard).
|
|
+ void reset_device(Device device) {
|
|
+ guard_.reset_device(device);
|
|
+ }
|
|
+
|
|
+ /// Sets the NPU device to the given device index, initializing the guard if
|
|
+ /// it is not already initialized.
|
|
+ void set_index(DeviceIndex device_index) {
|
|
+ guard_.set_index(device_index);
|
|
+ }
|
|
+
|
|
+ /// Returns the device that was set immediately prior to initialization of the
|
|
+ /// guard, or nullopt if the guard is uninitialized.
|
|
+ optional<Device> original_device() const {
|
|
+ return guard_.original_device();
|
|
+ }
|
|
+
|
|
+ /// Returns the most recent device that was set using this device guard,
|
|
+ /// either from construction, or via set_device, if the guard is initialized,
|
|
+ /// or nullopt if the guard is uninitialized.
|
|
+ optional<Device> current_device() const {
|
|
+ return guard_.current_device();
|
|
+ }
|
|
+
|
|
+ /// Restore the original NPU device, resetting this guard to uninitialized
|
|
+ /// state.
|
|
+ void reset() {
|
|
+ guard_.reset();
|
|
+ }
|
|
+
|
|
+ private:
|
|
+ c10::impl::InlineOptionalDeviceGuard<impl::NPUGuardImpl> guard_;
|
|
+};
|
|
+
|
|
+/// A variant of StreamGuard that is specialized for NPU. See NPUGuard
|
|
+/// for when you can use this.
|
|
+struct NPUStreamGuard {
|
|
+ /// No default constructor, see Note [Omitted default constructor from RAII]
|
|
+ explicit NPUStreamGuard() = delete;
|
|
+
|
|
+ /// Set the current NPU device to the device associated with the passed
|
|
+ /// stream, and set the current NPU stream on that device to the passed
|
|
+ /// stream. Errors if the Stream is not a NPU stream.
|
|
+ explicit NPUStreamGuard(Stream stream) : guard_(stream) {}
|
|
+
|
|
+ /// Copy is disallowed
|
|
+ NPUStreamGuard(const NPUStreamGuard&) = delete;
|
|
+ NPUStreamGuard& operator=(const NPUStreamGuard&) = delete;
|
|
+
|
|
+ /// Move is disallowed, as NPUStreamGuard does not have an uninitialized
|
|
+ /// state, which is required for moves on types with nontrivial destructors.
|
|
+ NPUStreamGuard(NPUStreamGuard&& other) = delete;
|
|
+ NPUStreamGuard& operator=(NPUStreamGuard&& other) = delete;
|
|
+
|
|
+ /// Resets the currently set stream to the original stream and
|
|
+ /// the currently set device to the original device. Then,
|
|
+ /// set the current device to the device associated with the passed stream,
|
|
+ /// and set the current stream on that device to the passed stream.
|
|
+ /// Errors if the stream passed is not a NPU stream.
|
|
+ ///
|
|
+ /// NOTE: this implementation may skip some stream/device setting if
|
|
+ /// it can prove that it is unnecessary.
|
|
+ ///
|
|
+ /// WARNING: reset_stream does NOT preserve previously set streams on
|
|
+ /// different devices. If you need to set streams on multiple devices
|
|
+ /// on NPU, use NPUMultiStreamGuard instead.
|
|
+ void reset_stream(Stream stream) {
|
|
+ guard_.reset_stream(stream);
|
|
+ }
|
|
+
|
|
+ /// Returns the NPU stream that was set at the time the guard was constructed.
|
|
+ NPUStream original_stream() const {
|
|
+ return NPUStream(NPUStream::UNCHECKED, guard_.original_stream());
|
|
+ }
|
|
+
|
|
+ /// Returns the most recent NPU stream that was set using this device guard,
|
|
+ /// either from construction, or via set_stream.
|
|
+ NPUStream current_stream() const {
|
|
+ return NPUStream(NPUStream::UNCHECKED, guard_.current_stream());
|
|
+ }
|
|
+
|
|
+ /// Returns the most recent NPU device that was set using this device guard,
|
|
+ /// either from construction, or via set_device/reset_device/set_index.
|
|
+ Device current_device() const {
|
|
+ return guard_.current_device();
|
|
+ }
|
|
+
|
|
+ /// Returns the NPU device that was set at the most recent reset_stream(),
|
|
+ /// or otherwise the device at construction time.
|
|
+ Device original_device() const {
|
|
+ return guard_.original_device();
|
|
+ }
|
|
+
|
|
+ private:
|
|
+ c10::impl::InlineStreamGuard<impl::NPUGuardImpl> guard_;
|
|
+};
|
|
+
|
|
+/// A variant of OptionalStreamGuard that is specialized for NPU. See NPUGuard
|
|
+/// for when you can use this.
|
|
+struct OptionalNPUStreamGuard {
|
|
+ /// Create an uninitialized guard.
|
|
+ explicit OptionalNPUStreamGuard() : guard_() {}
|
|
+
|
|
+ /// Set the current NPU device to the device associated with the passed
|
|
+ /// stream, and set the current NPU stream on that device to the passed
|
|
+ /// stream. Errors if the Stream is not a NPU stream.
|
|
+ explicit OptionalNPUStreamGuard(Stream stream) : guard_(stream) {}
|
|
+
|
|
+ /// Set the current device to the device associated with the passed stream,
|
|
+ /// and set the current stream on that device to the passed stream,
|
|
+ /// if the passed stream is not nullopt.
|
|
+ explicit OptionalNPUStreamGuard(optional<Stream> stream_opt)
|
|
+ : guard_(stream_opt) {}
|
|
+
|
|
+ /// Copy is disallowed
|
|
+ OptionalNPUStreamGuard(const OptionalNPUStreamGuard&) = delete;
|
|
+ OptionalNPUStreamGuard& operator=(const OptionalNPUStreamGuard&) = delete;
|
|
+
|
|
+ // See Note [Move construction for RAII guards is tricky]
|
|
+ OptionalNPUStreamGuard(OptionalNPUStreamGuard&& other) = delete;
|
|
+
|
|
+ // See Note [Move assignment for RAII guards is tricky]
|
|
+ OptionalNPUStreamGuard& operator=(OptionalNPUStreamGuard&& other) = delete;
|
|
+
|
|
+ /// Resets the currently set NPU stream to the original stream and
|
|
+ /// the currently set device to the original device. Then,
|
|
+ /// set the current device to the device associated with the passed stream,
|
|
+ /// and set the current stream on that device to the passed stream.
|
|
+ /// Initializes the guard if it was not previously initialized.
|
|
+ void reset_stream(Stream stream) {
|
|
+ guard_.reset_stream(stream);
|
|
+ }
|
|
+
|
|
+ /// Returns the NPU stream that was set at the time the guard was most
|
|
+ /// recently initialized, or nullopt if the guard is uninitialized.
|
|
+ optional<NPUStream> original_stream() const {
|
|
+ auto r = guard_.original_stream();
|
|
+ if (r.has_value()) {
|
|
+ return make_optional(NPUStream(NPUStream::UNCHECKED, r.value()));
|
|
+ } else {
|
|
+ return nullopt;
|
|
+ }
|
|
+ }
|
|
+
|
|
+ /// Returns the most recent NPU stream that was set using this stream guard,
|
|
+ /// either from construction, or via reset_stream, if the guard is
|
|
+ /// initialized, or nullopt if the guard is uninitialized.
|
|
+ optional<NPUStream> current_stream() const {
|
|
+ auto r = guard_.current_stream();
|
|
+ if (r.has_value()) {
|
|
+ return make_optional(NPUStream(NPUStream::UNCHECKED, r.value()));
|
|
+ } else {
|
|
+ return nullopt;
|
|
+ }
|
|
+ }
|
|
+
|
|
+ /// Restore the original NPU device and stream, resetting this guard to
|
|
+ /// uninitialized state.
|
|
+ void reset() {
|
|
+ guard_.reset();
|
|
+ }
|
|
+
|
|
+ private:
|
|
+ c10::impl::InlineOptionalStreamGuard<impl::NPUGuardImpl> guard_;
|
|
+};
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/npu_log.h patch/c10/npu/npu_log.h
|
|
--- pytorch-v1.8.1/c10/npu/npu_log.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/npu_log.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,46 @@
|
|
+#ifndef __C10_NPU_NPU_LOG___
|
|
+#define __C10_NPU_NPU_LOG___
|
|
+#include <iostream>
|
|
+#include <string>
|
|
+
|
|
+#define NPUStatus std::string
|
|
+#define SUCCESS "SUCCESS"
|
|
+#define INTERNEL_ERROR "INTERNEL_ERROR"
|
|
+#define PARAM_ERROR "PARAM_ERROR"
|
|
+#define ALLOC_ERROR "ALLOC_ERROR"
|
|
+#define FAILED "FAILED"
|
|
+
|
|
+#define NPU_LOGE(fmt, ...) \
|
|
+ printf( \
|
|
+ "[ERROR]%s,%s:%u:" #fmt "\n", \
|
|
+ __FUNCTION__, \
|
|
+ __FILE__, \
|
|
+ __LINE__, \
|
|
+ ##__VA_ARGS__)
|
|
+#define NPU_LOGW(fmt, ...) \
|
|
+ printf( \
|
|
+ "[WARN]%s,%s:%u:" #fmt "\n", \
|
|
+ __FUNCTION__, \
|
|
+ __FILE__, \
|
|
+ __LINE__, \
|
|
+ ##__VA_ARGS__)
|
|
+#define NPU_LOGI(fmt, ...) \
|
|
+ printf( \
|
|
+ "[INFO]%s,%s:%u:" #fmt "\n", \
|
|
+ __FUNCTION__, \
|
|
+ __FILE__, \
|
|
+ __LINE__, \
|
|
+ ##__VA_ARGS__)
|
|
+#endif
|
|
+
|
|
+#ifdef USE_NPU_LOG
|
|
+#define NPU_LOGD(fmt, ...) \
|
|
+ printf( \
|
|
+ "[INFO]%s,%s:%u:" #fmt "\n", \
|
|
+ __FUNCTION__, \
|
|
+ __FILE__, \
|
|
+ __LINE__, \
|
|
+ ##__VA_ARGS__)
|
|
+#else
|
|
+#define NPU_LOGD(fmt, ...)
|
|
+#endif
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUMacros.h patch/c10/npu/NPUMacros.h
|
|
--- pytorch-v1.8.1/c10/npu/NPUMacros.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUMacros.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,30 @@
|
|
+#pragma once
|
|
+// See c10/macros/Export.h for a detailed explanation of what the function
|
|
+// of these macros are. We need one set of macros for every separate library
|
|
+// we build.
|
|
+
|
|
+#ifdef _WIN32
|
|
+#if defined(C10_NPU_BUILD_SHARED_LIBS)
|
|
+#define C10_NPU_EXPORT __declspec(dllexport)
|
|
+#define C10_NPU_IMPORT __declspec(dllimport)
|
|
+#else
|
|
+#define C10_NPU_EXPORT
|
|
+#define C10_NPU_IMPORT
|
|
+#endif
|
|
+#else // _WIN32
|
|
+#if defined(__GNUC__)
|
|
+#define C10_NPU_EXPORT __attribute__((__visibility__("default")))
|
|
+#else // defined(__GNUC__)
|
|
+#define C10_NPU_EXPORT
|
|
+#endif // defined(__GNUC__)
|
|
+#define C10_NPU_IMPORT C10_NPU_EXPORT
|
|
+#endif // _WIN32
|
|
+
|
|
+// This one is being used by libc10_cuda.so
|
|
+#ifdef C10_NPU_BUILD_MAIN_LIB
|
|
+#define C10_NPU_API C10_NPU_EXPORT
|
|
+#else
|
|
+#define C10_NPU_API C10_NPU_IMPORT
|
|
+#endif
|
|
+
|
|
+#define C10_COMPILE_TIME_MAX_NPUS 16
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUQueue.cpp patch/c10/npu/NPUQueue.cpp
|
|
--- pytorch-v1.8.1/c10/npu/NPUQueue.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUQueue.cpp 2022-04-06 22:55:25.877661658 +0800
|
|
@@ -0,0 +1,659 @@
|
|
+#include "c10/npu/NPUQueue.h"
|
|
+#include "c10/npu/NPUStream.h"
|
|
+#include "c10/npu/npu_log.h"
|
|
+
|
|
+#include <Python.h>
|
|
+
|
|
+#include <sys/eventfd.h>
|
|
+#include <sys/prctl.h>
|
|
+#include <third_party/acl/inc/acl/acl_rt.h>
|
|
+
|
|
+#ifdef OPEN_QUEUE_DEBUG
|
|
+#define QUEUE_DEBUG(fmt, ...) \
|
|
+ do { \
|
|
+ printf("[%s:%d]" fmt "\n", __func__, __LINE__, ##__VA_ARGS__); \
|
|
+ } while (0)
|
|
+#else
|
|
+#define QUEUE_DEBUG(fmt, ...)
|
|
+#endif
|
|
+
|
|
+#ifdef OPEN_QUEUE_COUT
|
|
+#define QUEUE_COUT(fmt, ...) \
|
|
+ do { \
|
|
+ printf("[%s:%d]" fmt "\n", __func__, __LINE__, ##__VA_ARGS__); \
|
|
+ } while (0)
|
|
+#else
|
|
+#define QUEUE_COUT(fmt, ...)
|
|
+#endif
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+namespace {
|
|
+
|
|
+class CallBackManager {
|
|
+public:
|
|
+ CallBackManager() {}
|
|
+ ~CallBackManager() {}
|
|
+ void SetExec(const ACL_EXEC_FUNC& func) {
|
|
+ this->execFunc = func;
|
|
+ }
|
|
+
|
|
+ void SetCopy(const ACL_COPY_FUNC& func) {
|
|
+ this->copyFunc = func;
|
|
+ }
|
|
+
|
|
+ void SetRelease(const ACL_RELEASE_FUNC& func) {
|
|
+ this->releaseFunc = func;
|
|
+ }
|
|
+
|
|
+ void SetCopyReleaseParam(const ACL_COPY_RELEASE_PARM_FUNC& func) {
|
|
+ this->copyReleaseParamFunc = func;
|
|
+ }
|
|
+
|
|
+ void SetReleaseParam(const ACL_RELEASE_PARAM_FUNC& func) {
|
|
+ this->releaseParamFunc = func;
|
|
+ }
|
|
+
|
|
+ void SetNew(const ACL_NEW_FUNC& func) {
|
|
+ this->newFunc = func;
|
|
+ }
|
|
+
|
|
+ void SetDelete(const ACL_DELETE_FUNC& func) {
|
|
+ this->deleteFunc = func;
|
|
+ }
|
|
+
|
|
+ int Call(void* head, int offset, uint32_t queueLen) {
|
|
+ TORCH_CHECK(this->execFunc, "Failed to find execution function.");
|
|
+ auto dstPtr = (uint8_t*)head + sizePerParams * offset;
|
|
+ return this->execFunc(dstPtr, queueLen);
|
|
+ }
|
|
+
|
|
+ void Copy(void* dstHead, int offset, void* src, SmallVector<Storage, N>& needClearVec, uint32_t queueLen) {
|
|
+ TORCH_CHECK(this->copyFunc, "Failed to find copy function.");
|
|
+ auto dstPtr = (uint8_t*)dstHead + sizePerParams * offset;
|
|
+ return this->copyFunc(dstPtr, src, needClearVec, queueLen);
|
|
+ }
|
|
+
|
|
+ void Release(void* head, int offset, ReleaseQueue& releaseQueue) {
|
|
+ TORCH_CHECK(this->releaseFunc, "Failed to find release function.");
|
|
+ auto ptr = (uint8_t*)head + sizePerParams * offset;
|
|
+ return this->releaseFunc(ptr, releaseQueue);
|
|
+ }
|
|
+
|
|
+ void CopyRealseParam(void* dstHead, int offset, void* src) {
|
|
+ TORCH_CHECK(this->copyReleaseParamFunc, "Failed to find copy release params function.");
|
|
+ auto dstPtr = (uint8_t*)dstHead + sizePerParams * offset;
|
|
+ return this->copyReleaseParamFunc(dstPtr, src);
|
|
+ }
|
|
+
|
|
+ void ReleaseParam(void* head, int offset) {
|
|
+ TORCH_CHECK(this->releaseParamFunc, "Failed to find release params function.");
|
|
+ auto ptr = (uint8_t*)head + sizePerParams * offset;
|
|
+ return this->releaseParamFunc(ptr);
|
|
+ }
|
|
+
|
|
+ void* Init(int capacity) {
|
|
+ TORCH_CHECK(this->newFunc, "Failed to find new function.");
|
|
+ void* ptr = this->newFunc(capacity, sizePerParams); // not check as CUDA
|
|
+ return ptr;
|
|
+ }
|
|
+
|
|
+ void DeInit(void* ptr) {
|
|
+ if (ptr != nullptr) {
|
|
+ TORCH_CHECK(this->deleteFunc, "Failed to find delete function.");
|
|
+ this->deleteFunc(ptr);
|
|
+ ptr = nullptr;
|
|
+ }
|
|
+ }
|
|
+private:
|
|
+ int sizePerParams = 0;
|
|
+ ACL_EXEC_FUNC execFunc = nullptr;
|
|
+ ACL_COPY_FUNC copyFunc = nullptr;
|
|
+ ACL_RELEASE_FUNC releaseFunc = nullptr;
|
|
+ ACL_NEW_FUNC newFunc = nullptr;
|
|
+ ACL_DELETE_FUNC deleteFunc = nullptr;
|
|
+ ACL_COPY_RELEASE_PARM_FUNC copyReleaseParamFunc = nullptr;
|
|
+ ACL_RELEASE_PARAM_FUNC releaseParamFunc = nullptr;
|
|
+}; // class CallBackManager
|
|
+
|
|
+CallBackManager& manager() {
|
|
+ static CallBackManager instance;
|
|
+ return instance;
|
|
+}
|
|
+
|
|
+CallBackManager& releaseManager() {
|
|
+ static CallBackManager releaseinstance;
|
|
+ return releaseinstance;
|
|
+}
|
|
+} // namespace
|
|
+
|
|
+namespace register_queue_cb {
|
|
+NPUCallBackRegisterBuilder::NPUCallBackRegisterBuilder(const ACL_EXEC_FUNC& execFunc,
|
|
+ const ACL_COPY_FUNC& copyFunc, const ACL_RELEASE_FUNC& releaseFunc,
|
|
+ const ACL_NEW_FUNC& newFunc, const ACL_DELETE_FUNC& deleteFunc,
|
|
+ const ACL_COPY_RELEASE_PARM_FUNC& copyReleaseParamF, const ACL_RELEASE_PARAM_FUNC& releaseParamF) {
|
|
+ manager().SetExec(execFunc);
|
|
+ manager().SetCopy(copyFunc);
|
|
+ manager().SetRelease(releaseFunc);
|
|
+ manager().SetNew(newFunc);
|
|
+ manager().SetDelete(deleteFunc);
|
|
+ releaseManager().SetCopyReleaseParam(copyReleaseParamF);
|
|
+ releaseManager().SetReleaseParam(releaseParamF);
|
|
+ releaseManager().SetNew(newFunc);
|
|
+ releaseManager().SetDelete(deleteFunc);
|
|
+}
|
|
+} // namespace register_queue_cb
|
|
+
|
|
+
|
|
+// If the capacity is too large, when the queue is full,
|
|
+// a large amount of device memory is occupied at the same time;
|
|
+// if the capacity is too small, and the main thread is fast enough,
|
|
+// it does not make full use of concurrent design capabilities.
|
|
+static constexpr size_t kQueueCapacity = 4096;
|
|
+
|
|
+RepoStatus Repository::GetStatus() const {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE("Task queue is not initialized, shouldn't call GetStatus(). !!");
|
|
+ }
|
|
+
|
|
+ return repo_status.load();
|
|
+}
|
|
+
|
|
+void Repository::SetStatus(RepoStatus desired) {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE("Task queue is not initialized, shouldn't call SetStatus(). !!");
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ repo_status = desired;
|
|
+}
|
|
+
|
|
+void Repository::ChangeStatus(RepoStatus expected, RepoStatus desired) {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE(
|
|
+ "Task queue is not initialized, shouldn't call ChangeStatus(). !!");
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ repo_status.compare_exchange_strong(expected, desired);
|
|
+}
|
|
+
|
|
+NPUStatus Repository::MakeSureQueueEmpty() {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE(
|
|
+ "Task queue is not initialized, shouldn't call MakeSureQueueEmpty(). !!");
|
|
+ return FAILED;
|
|
+ }
|
|
+
|
|
+ if (consumer.joinable()) {
|
|
+ ssize_t s;
|
|
+ uint64_t u = 1;
|
|
+ while (!IsEmptyQueue()) {
|
|
+ std::lock_guard<std::mutex> lock(mu_empty);
|
|
+ need_empty = true;
|
|
+ __sync_synchronize();
|
|
+ if (!IsEmptyQueue()) { // double-check, very important idea
|
|
+ // While waiting for ACL thread to launch tasks,
|
|
+ // the current thread should not hold GIL.
|
|
+ // When the operator compilation is triggered in the ACL thread,
|
|
+ // the TE module attempts to obtain the GIL.
|
|
+ // If the current thread does not release the GIL, a deadlock will
|
|
+ // occur.
|
|
+ if (PyGILState_Check()) {
|
|
+ Py_BEGIN_ALLOW_THREADS s = eventfd_read(efd_empty, &u);
|
|
+ Py_END_ALLOW_THREADS
|
|
+ } else {
|
|
+ s = eventfd_read(efd_empty, &u);
|
|
+ }
|
|
+ if (s != 0) {
|
|
+ if (errno == EINTR) {
|
|
+ QUEUE_DEBUG("EINTR occurs on the eventfd_read");
|
|
+ continue;
|
|
+ }
|
|
+ NPU_LOGE("eventfd_read failed. s=%zd, errno=%s.", s, strerror(errno));
|
|
+ return INTERNEL_ERROR;
|
|
+ }
|
|
+ QUEUE_DEBUG("waiting ok, queue is empty now");
|
|
+ }
|
|
+ }
|
|
+ need_empty = false;
|
|
+ QUEUE_DEBUG(
|
|
+ "MakeSureQueueEmpty success, now write_idx=%d, read_idx=%d",
|
|
+ write_idx.idx,
|
|
+ read_idx.idx);
|
|
+ }
|
|
+ return SUCCESS;
|
|
+}
|
|
+
|
|
+void Repository::EnableInterrupt(RepoRole role) {
|
|
+ if (role == RepoRole::READER) {
|
|
+ read_idx.working = false;
|
|
+ } else {
|
|
+ write_idx.working = false;
|
|
+ }
|
|
+}
|
|
+
|
|
+void Repository::DisableInterrupt(RepoRole role) {
|
|
+ if (role == RepoRole::READER) {
|
|
+ read_idx.working = true;
|
|
+ } else {
|
|
+ write_idx.working = true;
|
|
+ }
|
|
+}
|
|
+
|
|
+bool Repository::NeedNotify(RepoRole role) const {
|
|
+ bool working =
|
|
+ (role == RepoRole::READER) ? read_idx.working : write_idx.working;
|
|
+ return !working;
|
|
+}
|
|
+
|
|
+bool Repository::WriteQueue(void* cur_paras, SmallVector<Storage, N>& needClearVec) {
|
|
+ QUEUE_DEBUG("write_idx=%d, read_idx=%d", write_idx.idx, read_idx.idx);
|
|
+ if (IsFullQueue()) {
|
|
+ QUEUE_DEBUG("queue is full");
|
|
+ return false;
|
|
+ }
|
|
+
|
|
+ std::lock_guard<std::mutex> lock(mu_enqueue);
|
|
+ uint32_t queueLen = (write_idx.idx - read_idx.idx + kQueueCapacity) % kQueueCapacity;
|
|
+ manager().Copy(datas, write_idx.idx, cur_paras, needClearVec, queueLen);
|
|
+ __sync_synchronize();
|
|
+
|
|
+ write_idx.idx = (write_idx.idx + 1) % kQueueCapacity;
|
|
+ return true;
|
|
+}
|
|
+
|
|
+bool Repository::ReadQueue() {
|
|
+ QUEUE_DEBUG("write_idx=%d, read_idx=%d", write_idx.idx, read_idx.idx);
|
|
+ if (IsEmptyQueue()) {
|
|
+ QUEUE_DEBUG("queue is empty");
|
|
+ return false;
|
|
+ }
|
|
+
|
|
+ uint32_t queueLen = (write_idx.idx - read_idx.idx + kQueueCapacity) % kQueueCapacity;
|
|
+ auto ret = manager().Call(datas, read_idx.idx, queueLen);
|
|
+
|
|
+ if (ret != 0) {
|
|
+ while (!IsEmptyQueue()) { // ignore other tasks
|
|
+ std::cout << "---Thread---" << std::this_thread::get_id()
|
|
+ << ": device=" << device_idx << ", write_idx=" << write_idx.idx
|
|
+ << ", read_idx=" << read_idx.idx << ", status=" << GetStatus()
|
|
+ << ", ret = " << ret << std::endl;
|
|
+ manager().Release(datas, read_idx.idx, releaseQueue);
|
|
+ read_idx.idx = (read_idx.idx + 1) % kQueueCapacity;
|
|
+ }
|
|
+ ReleaseResource();
|
|
+ std::stringstream msg;
|
|
+ msg << __func__ << ":" << __FILE__ << ":" << __LINE__;
|
|
+ TORCH_CHECK(0, msg.str());
|
|
+ }
|
|
+
|
|
+ manager().Release(datas, read_idx.idx, releaseQueue);
|
|
+ __sync_synchronize();
|
|
+
|
|
+ read_idx.idx = (read_idx.idx + 1) % kQueueCapacity;
|
|
+ QUEUE_DEBUG("read success, now read of repo is %d", read_idx.idx);
|
|
+
|
|
+ return true;
|
|
+}
|
|
+
|
|
+void Repository::Enqueue(void* cur_paras, SmallVector<Storage, N>& needClearVec) {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE("Task queue is not initialized, shouldn't call Enqueue(). !!");
|
|
+ return;
|
|
+ }
|
|
+ if (GetStatus() != RUN && GetStatus() != INIT) {
|
|
+ NPU_LOGE("Task queue thread is exit, cann't call Enqueue(). !!");
|
|
+ return;
|
|
+ }
|
|
+ bool ret = false;
|
|
+ ssize_t s;
|
|
+ uint64_t u = 1;
|
|
+
|
|
+ DisableInterrupt(RepoRole::WRITER);
|
|
+ while (ret == false) {
|
|
+ ret = WriteQueue(cur_paras, needClearVec);
|
|
+ if (ret == false) {
|
|
+ EnableInterrupt(RepoRole::WRITER);
|
|
+ __sync_synchronize();
|
|
+ if (IsFullQueue()) {
|
|
+ // double check the current thread hold a Gil lock
|
|
+ if (PyGILState_Check()) {
|
|
+ Py_BEGIN_ALLOW_THREADS s = eventfd_read(efd_write, &u);
|
|
+ Py_END_ALLOW_THREADS
|
|
+ } else {
|
|
+ s = eventfd_read(efd_write, &u);
|
|
+ }
|
|
+ if (s != 0) {
|
|
+ if (errno == EINTR) {
|
|
+ QUEUE_DEBUG("EINTR occurs on the eventfd_read");
|
|
+ continue;
|
|
+ }
|
|
+ NPU_LOGE("waiting queue not full failed. s=%zd, errno=%s.", s, strerror(errno));
|
|
+ return;
|
|
+ }
|
|
+ DisableInterrupt(RepoRole::WRITER);
|
|
+ QUEUE_DEBUG("waiting ok, queue isn't full now");
|
|
+ }
|
|
+ continue;
|
|
+ }
|
|
+ __sync_synchronize();
|
|
+ while (NeedNotify(RepoRole::READER)) {
|
|
+ QUEUE_DEBUG("need notify consumer");
|
|
+ s = eventfd_write(efd_read, u);
|
|
+ if (s != 0) {
|
|
+ if (errno == EINTR) {
|
|
+ QUEUE_DEBUG("EINTR occurs on the eventfd_write");
|
|
+ continue;
|
|
+ }
|
|
+ NPU_LOGE("notify consumer failed!! s=%zd, errno=%s", s, strerror(errno));
|
|
+ return;
|
|
+ }
|
|
+ break;
|
|
+ }
|
|
+ }
|
|
+ EnableInterrupt(RepoRole::WRITER);
|
|
+}
|
|
+
|
|
+void Repository::Dequeue() {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE("Task queue is not initialized, shouldn't call Dequeue(). !!");
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ bool ret = false;
|
|
+ bool notify_empty = false;
|
|
+ ssize_t s;
|
|
+ uint64_t u = 1;
|
|
+
|
|
+ DisableInterrupt(RepoRole::READER);
|
|
+ while (ret == false && GetStatus() != RepoStatus::CAN_EXIT) {
|
|
+ ret = ReadQueue();
|
|
+ if (ret == false) {
|
|
+ if (GetStatus() == RepoStatus::NEED_EXIT) {
|
|
+ ChangeStatus(NEED_EXIT, CAN_EXIT);
|
|
+ break;
|
|
+ }
|
|
+ EnableInterrupt(RepoRole::READER);
|
|
+ __sync_synchronize();
|
|
+ if (IsEmptyQueue()) {
|
|
+ s = eventfd_read(efd_read, &u);
|
|
+ if (s != 0) {
|
|
+ if (errno == EINTR) {
|
|
+ QUEUE_DEBUG("EINTR occurs on the eventfd_read");
|
|
+ continue;
|
|
+ }
|
|
+ NPU_LOGE("waiting queue not empty failed. s=%zd, errno=%s.", s, strerror(errno));
|
|
+ return;
|
|
+ }
|
|
+ DisableInterrupt(RepoRole::READER);
|
|
+ QUEUE_DEBUG("waiting ok, queue isn't empty now");
|
|
+ }
|
|
+ continue;
|
|
+ }
|
|
+ __sync_synchronize();
|
|
+ notify_empty = need_empty &&
|
|
+ IsEmptyQueue(); // need_empty && (ret == false || IsEmptyQueue());
|
|
+ while (notify_empty) {
|
|
+ QUEUE_DEBUG("need notify make_sure");
|
|
+ s = eventfd_write(efd_empty, u);
|
|
+ if (s != 0) {
|
|
+ if (errno == EINTR) {
|
|
+ QUEUE_DEBUG("EINTR occurs on the eventfd_write");
|
|
+ continue;
|
|
+ }
|
|
+ NPU_LOGE("notify make_sure failed. s=%zd, errno=%s.", s, strerror(errno));
|
|
+ return;
|
|
+ }
|
|
+ break;
|
|
+ }
|
|
+ __sync_synchronize();
|
|
+ while (NeedNotify(RepoRole::WRITER)) {
|
|
+ QUEUE_DEBUG("need notify producer");
|
|
+ s = eventfd_write(efd_write, u);
|
|
+ if (s != 0) {
|
|
+ if (errno == EINTR) {
|
|
+ QUEUE_DEBUG("EINTR occurs on the eventfd_write");
|
|
+ continue;
|
|
+ }
|
|
+ NPU_LOGE("notify producer failed. s=%zd, errno=%s.", s, strerror(errno));
|
|
+ return;
|
|
+ }
|
|
+ break;
|
|
+ }
|
|
+ }
|
|
+ EnableInterrupt(RepoRole::READER);
|
|
+}
|
|
+
|
|
+void Repository::ReleaseResource() {
|
|
+ manager().DeInit(datas);
|
|
+ if (efd_read > 0) {
|
|
+ close(efd_read);
|
|
+ efd_read = -1;
|
|
+ }
|
|
+ if (efd_write > 0) {
|
|
+ close(efd_write);
|
|
+ efd_write = -1;
|
|
+ }
|
|
+ if (efd_empty > 0) {
|
|
+ close(efd_empty);
|
|
+ efd_empty = -1;
|
|
+ }
|
|
+}
|
|
+
|
|
+Repository::~Repository() {
|
|
+ if (initialized) {
|
|
+ struct timeval tv;
|
|
+ gettimeofday(&tv, NULL);
|
|
+ QUEUE_COUT(
|
|
+ "%ds %dms %dus <-- device %d FinishRepo start.",
|
|
+ (int)(tv.tv_sec),
|
|
+ (int)(tv.tv_usec / 1000),
|
|
+ (int)(tv.tv_usec % 1000),
|
|
+ (int)device_idx);
|
|
+ if (consumer.joinable()) {
|
|
+ SetStatus(NEED_EXIT);
|
|
+ (void)eventfd_write(efd_read, 1); // escape wait
|
|
+ QUEUE_DEBUG("acl escape wait.");
|
|
+ consumer.join();
|
|
+ QUEUE_DEBUG("acl end, now we destruct.");
|
|
+ }
|
|
+ gettimeofday(&tv, NULL);
|
|
+ QUEUE_COUT(
|
|
+ "%ds %dms %dus <-- device %d FinishRepo start.",
|
|
+ (int)(tv.tv_sec),
|
|
+ (int)(tv.tv_usec / 1000),
|
|
+ (int)(tv.tv_usec % 1000),
|
|
+ (int)device_idx);
|
|
+ eventfd_write(efd_empty, 1);
|
|
+ ReleaseResource();
|
|
+ }
|
|
+}
|
|
+
|
|
+bool Repository::IsEmptyQueue() const {
|
|
+ return read_idx.idx == write_idx.idx;
|
|
+}
|
|
+
|
|
+bool Repository::IsFullQueue() const {
|
|
+ return ((write_idx.idx + 1) % kQueueCapacity) == read_idx.idx;
|
|
+}
|
|
+
|
|
+bool Repository::CheckInit() const {
|
|
+ return initialized;
|
|
+}
|
|
+
|
|
+void StartConsume(Repository* repo, DeviceIndex device_id) {
|
|
+ if (prctl(PR_SET_NAME, ("ACL_thread")) != 0) {
|
|
+ std::cout << "set thread name failed!" << std::endl;
|
|
+ }
|
|
+
|
|
+ aclError ret = aclrtSetDevice(device_id);
|
|
+ if (ret != 0) {
|
|
+ C10_NPU_SHOW_ERR_MSG();
|
|
+ std::cout << "***Thread*" << std::this_thread::get_id() << ": set device ("
|
|
+ << device_id << "): ret = " << ret << std::endl;
|
|
+ }
|
|
+
|
|
+ while (repo->GetStatus() != RepoStatus::CAN_EXIT) {
|
|
+ repo->Dequeue();
|
|
+ }
|
|
+ return;
|
|
+}
|
|
+
|
|
+void Repository::InitRepo(DeviceIndex device_id) {
|
|
+ struct timeval tv;
|
|
+ gettimeofday(&tv, NULL);
|
|
+ QUEUE_COUT(
|
|
+ "%ds %dms %dus <--InitRepo start.",
|
|
+ (int)(tv.tv_sec),
|
|
+ (int)(tv.tv_usec / 1000),
|
|
+ (int)(tv.tv_usec % 1000));
|
|
+
|
|
+ if (datas == nullptr) {
|
|
+ datas = manager().Init(kQueueCapacity);
|
|
+ }
|
|
+
|
|
+ efd_read = eventfd(0, 0);
|
|
+ efd_write = eventfd(0, 0);
|
|
+ efd_empty = eventfd(0, 0);
|
|
+
|
|
+ initialized = true;
|
|
+ SetStatus(INIT);
|
|
+ device_idx = device_id;
|
|
+ std::thread cur_consumer(StartConsume, this, device_id);
|
|
+ consumer = std::move(cur_consumer);
|
|
+
|
|
+ releaseQueue.InitReleaseQueue();
|
|
+}
|
|
+
|
|
+static constexpr size_t kReleaseQueueCapacity = 8192;
|
|
+bool ReleaseQueue::WriteToReleaseQueue(void* cur_paras)
|
|
+{
|
|
+ if (IsFullQueue()) {
|
|
+ QUEUE_DEBUG("Release queue is full");
|
|
+ return false;
|
|
+ }
|
|
+
|
|
+ releaseManager().CopyRealseParam(datas, write_idx.idx, cur_paras);
|
|
+
|
|
+ __sync_synchronize();
|
|
+ write_idx.idx = (write_idx.idx + 1) % kReleaseQueueCapacity;
|
|
+ return true;
|
|
+}
|
|
+
|
|
+void ReleaseQueue::PushToReleaseQueue(void* cur_paras) {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE("Release queue is not initialized, shouldn't call PushToReleaseQueue(). !!");
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ bool ret = false;
|
|
+ while (ret == false) {
|
|
+ ret = WriteToReleaseQueue(cur_paras);
|
|
+ if (ret == true) {
|
|
+ break;
|
|
+ }
|
|
+ }
|
|
+}
|
|
+
|
|
+bool ReleaseQueue::ReadFromReleaseQueue() {
|
|
+ if (IsEmptyQueue()) {
|
|
+ QUEUE_DEBUG("Release queue is empty");
|
|
+ return false;
|
|
+ }
|
|
+
|
|
+ releaseManager().ReleaseParam(datas, read_idx.idx);
|
|
+
|
|
+ __sync_synchronize();
|
|
+ read_idx.idx = (read_idx.idx + 1) % kReleaseQueueCapacity;
|
|
+
|
|
+ return true;
|
|
+}
|
|
+
|
|
+void ReleaseQueue::PopFromReleaseQueue() {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE("Release queue is not initialized, shouldn't call PopFromReleaseQueue(). !!");
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ bool ret = false;
|
|
+ while ((ret == false) && (GetStatus() != RepoStatus::CAN_EXIT)) {
|
|
+ ret = ReadFromReleaseQueue();
|
|
+ if (ret == false) {
|
|
+ if (GetStatus() == RepoStatus::NEED_EXIT) {
|
|
+ ChangeStatus(NEED_EXIT, CAN_EXIT);
|
|
+ break;
|
|
+ }
|
|
+ usleep(2);
|
|
+ }
|
|
+ }
|
|
+}
|
|
+
|
|
+void StartRelease(ReleaseQueue* releaseQue) {
|
|
+ if (prctl(PR_SET_NAME, ("Release_thread")) != 0) {
|
|
+ std::cout << "set thread name failed!" << std::endl;
|
|
+ }
|
|
+
|
|
+ while (releaseQue->GetStatus() != RepoStatus::CAN_EXIT) {
|
|
+ releaseQue->PopFromReleaseQueue();
|
|
+ }
|
|
+ return;
|
|
+}
|
|
+
|
|
+void ReleaseQueue::InitReleaseQueue() {
|
|
+ if (datas == nullptr) {
|
|
+ datas = releaseManager().Init(kReleaseQueueCapacity);
|
|
+ }
|
|
+
|
|
+ initialized = true;
|
|
+ SetStatus(INIT);
|
|
+ std::thread cur_releaser(StartRelease, this);
|
|
+ releaser = std::move(cur_releaser);
|
|
+}
|
|
+
|
|
+ReleaseQueue::~ReleaseQueue() {
|
|
+ if (initialized) {
|
|
+ if (releaser.joinable()) {
|
|
+ SetStatus(NEED_EXIT);
|
|
+ releaser.join();
|
|
+ }
|
|
+ }
|
|
+ releaseManager().DeInit(datas);
|
|
+}
|
|
+
|
|
+bool ReleaseQueue::IsEmptyQueue() const {
|
|
+ return read_idx.idx == write_idx.idx;
|
|
+}
|
|
+
|
|
+bool ReleaseQueue::IsFullQueue() const {
|
|
+ return ((write_idx.idx + 1) % kReleaseQueueCapacity) == read_idx.idx;
|
|
+}
|
|
+
|
|
+RepoStatus ReleaseQueue::GetStatus() const {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE("Release queue is not initialized, shouldn't call GetStatus(). !!");
|
|
+ }
|
|
+
|
|
+ return repo_status.load();
|
|
+}
|
|
+
|
|
+void ReleaseQueue::SetStatus(RepoStatus desired) {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE("Release queue is not initialized, shouldn't call SetStatus(). !!");
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ repo_status = desired;
|
|
+}
|
|
+
|
|
+void ReleaseQueue::ChangeStatus(RepoStatus expected, RepoStatus desired) {
|
|
+ if (initialized == false) {
|
|
+ NPU_LOGE("Release queue is not initialized, shouldn't call ChangeStatus(). !!");
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ repo_status.compare_exchange_strong(expected, desired);
|
|
+}
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUQueue.h patch/c10/npu/NPUQueue.h
|
|
--- pytorch-v1.8.1/c10/npu/NPUQueue.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUQueue.h 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -0,0 +1,155 @@
|
|
+#ifndef __C10_NPU_NPUQUEUE__
|
|
+#define __C10_NPU_NPUQUEUE__
|
|
+
|
|
+#include <string>
|
|
+#include <thread>
|
|
+#include <mutex>
|
|
+#include <atomic>
|
|
+
|
|
+#include "c10/core/Storage.h"
|
|
+#include "c10/core/Device.h"
|
|
+#include "c10/npu/npu_log.h"
|
|
+#include "c10/util/SmallVector.h"
|
|
+#include <third_party/acl/inc/acl/acl_op.h>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+struct sring_idx {
|
|
+ bool working = false;
|
|
+ volatile unsigned int idx = 0;
|
|
+};
|
|
+
|
|
+enum RepoRole {
|
|
+ WRITER = 0,
|
|
+ READER = 1,
|
|
+};
|
|
+
|
|
+enum RepoStatus {
|
|
+ INIT = 0,
|
|
+ RUN = 1,
|
|
+ NEED_EXIT = 2,
|
|
+ CAN_EXIT = 3,
|
|
+};
|
|
+
|
|
+// smallvector max size
|
|
+const int N = 32;
|
|
+
|
|
+class ReleaseQueue {
|
|
+ public:
|
|
+ ReleaseQueue() = default;
|
|
+ ~ReleaseQueue();
|
|
+ void PushToReleaseQueue(void* cur_paras);
|
|
+ void PopFromReleaseQueue();
|
|
+ void InitReleaseQueue();
|
|
+ RepoStatus GetStatus() const;
|
|
+
|
|
+ private:
|
|
+ bool IsEmptyQueue() const;
|
|
+ bool IsFullQueue() const;
|
|
+ bool WriteToReleaseQueue(void* cur_paras);
|
|
+ bool ReadFromReleaseQueue();
|
|
+ void SetStatus(RepoStatus desired);
|
|
+ void ChangeStatus(RepoStatus expected, RepoStatus desired);
|
|
+
|
|
+ private:
|
|
+ void* datas = nullptr;
|
|
+ std::thread releaser;
|
|
+
|
|
+ private:
|
|
+ sring_idx read_idx;
|
|
+ sring_idx write_idx;
|
|
+ std::atomic<RepoStatus> repo_status;
|
|
+ bool initialized = false;
|
|
+};
|
|
+
|
|
+class NPUQueueBase {
|
|
+ public:
|
|
+ virtual ~NPUQueueBase() {}
|
|
+ virtual RepoStatus GetStatus() const = 0;
|
|
+ virtual void SetStatus(RepoStatus desired) = 0;
|
|
+ virtual void ChangeStatus(RepoStatus expected, RepoStatus desired) = 0;
|
|
+ virtual void Enqueue(void* cur_paras, SmallVector<Storage, N>& needClearVec) = 0;
|
|
+ virtual void Dequeue() = 0;
|
|
+ virtual NPUStatus MakeSureQueueEmpty() = 0;
|
|
+ virtual void InitRepo(DeviceIndex device_id) = 0;
|
|
+ virtual bool CheckInit() const = 0;
|
|
+};
|
|
+
|
|
+class NPUQueueFactoryBase {
|
|
+public:
|
|
+ virtual NPUQueueBase* create() = 0;
|
|
+ virtual ~NPUQueueFactoryBase() {}
|
|
+};
|
|
+
|
|
+class Repository : public NPUQueueBase {
|
|
+ public:
|
|
+ Repository() = default;
|
|
+ ~Repository() override;
|
|
+ RepoStatus GetStatus() const override;
|
|
+ void SetStatus(RepoStatus desired) override;
|
|
+ void ChangeStatus(RepoStatus expected, RepoStatus desired) override;
|
|
+ void Enqueue(void* cur_paras, SmallVector<Storage, N>& needClearVec) override;
|
|
+ void Dequeue() override;
|
|
+ NPUStatus MakeSureQueueEmpty() override;
|
|
+ void InitRepo(DeviceIndex device_id) override;
|
|
+ bool CheckInit() const override;
|
|
+
|
|
+ private:
|
|
+ void ReleaseResource();
|
|
+ bool IsEmptyQueue() const;
|
|
+ bool IsFullQueue() const;
|
|
+ void EnableInterrupt(RepoRole role);
|
|
+ void DisableInterrupt(RepoRole role);
|
|
+ bool NeedNotify(RepoRole role) const;
|
|
+ bool WriteQueue(void* cur_paras, SmallVector<Storage, N>& needClearVec);
|
|
+ bool ReadQueue();
|
|
+
|
|
+ private:
|
|
+ void* datas = nullptr;
|
|
+ std::thread consumer;
|
|
+ int efd_read;
|
|
+ int efd_write;
|
|
+ int efd_empty;
|
|
+ DeviceIndex device_idx;
|
|
+
|
|
+ private:
|
|
+ sring_idx read_idx;
|
|
+ sring_idx write_idx;
|
|
+ std::atomic<RepoStatus> repo_status;
|
|
+ bool need_empty = false;
|
|
+ bool initialized = false;
|
|
+ std::mutex mu_empty;
|
|
+ // In theory, this is not necessary.
|
|
+ // The logic is ensured by original pytorch, but this is added here just in
|
|
+ // case.
|
|
+ std::mutex mu_enqueue;
|
|
+ ReleaseQueue releaseQueue;
|
|
+};
|
|
+
|
|
+using ACL_EXEC_FUNC = std::function<int(void*, uint32_t)>;
|
|
+using ACL_COPY_FUNC = std::function<void(void*, void*, SmallVector<Storage, N>&, uint32_t)>;
|
|
+using ACL_RELEASE_FUNC = std::function<void(void*, ReleaseQueue&)>;
|
|
+using ACL_NEW_FUNC = std::function<void*(int, int&)>;
|
|
+using ACL_DELETE_FUNC = std::function<void(void*)>;
|
|
+using ACL_COPY_RELEASE_PARM_FUNC = std::function<void(void*, void*)>;
|
|
+using ACL_RELEASE_PARAM_FUNC = std::function<void(void*)>;
|
|
+
|
|
+namespace register_queue_cb {
|
|
+class NPUCallBackRegisterBuilder {
|
|
+public:
|
|
+ NPUCallBackRegisterBuilder(const ACL_EXEC_FUNC& execF, const ACL_COPY_FUNC& copyF,
|
|
+ const ACL_RELEASE_FUNC& releaseF, const ACL_NEW_FUNC& newF, const ACL_DELETE_FUNC& deleteF,
|
|
+ const ACL_COPY_RELEASE_PARM_FUNC& copyReleaseParamF, const ACL_RELEASE_PARAM_FUNC& releaseParamF);
|
|
+ ~NPUCallBackRegisterBuilder(){}
|
|
+};
|
|
+} // namespace register_queue_cb
|
|
+
|
|
+#define REGISTER_QUEUE_FUNC(execF, copyF, releaseF, newF, deleteF, copyReleaseParamF, releaseParamF) \
|
|
+ static ::c10::npu::register_queue_cb::NPUCallBackRegisterBuilder \
|
|
+ register_queue_func_builder(execF, copyF, releaseF, newF, deleteF, copyReleaseParamF, releaseParamF);
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
+
|
|
+#endif // __C10_NPU_NPUQUEUE__
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUStream.cpp patch/c10/npu/NPUStream.cpp
|
|
--- pytorch-v1.8.1/c10/npu/NPUStream.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUStream.cpp 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -0,0 +1,394 @@
|
|
+#include "NPUStream.h"
|
|
+#include <c10/npu/NPUFunctions.h>
|
|
+#include <c10/npu/NPUGuard.h>
|
|
+#include <c10/npu/NPUQueue.h>
|
|
+#include <c10/npu/OptionsManager.h>
|
|
+#include <c10/npu/interface/AsyncTaskQueueInterface.h>
|
|
+#include <c10/util/Exception.h>
|
|
+
|
|
+#include <Python.h>
|
|
+#include <array>
|
|
+#include <atomic>
|
|
+#include <cstdint>
|
|
+#include <cstring>
|
|
+#include <vector>
|
|
+
|
|
+#include <sys/time.h>
|
|
+#include <unistd.h>
|
|
+#include <iostream>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+namespace {
|
|
+struct LeakyStreamInternals {
|
|
+ LeakyStreamInternals() {
|
|
+ repo = ::std::make_unique<Repository>();
|
|
+ }
|
|
+ C10_DISABLE_COPY_AND_ASSIGN(LeakyStreamInternals);
|
|
+
|
|
+ ~LeakyStreamInternals() {
|
|
+ // NB: this code is invoked only in the destruction of global variables
|
|
+ // (since we never shrink the corresponding vectors). At this point the NPU
|
|
+ // runtime might be already destroyed and invoking npuStreamDestroy leads
|
|
+ // to a crash. It's likely an issue in NPU, but to be safe - let's just
|
|
+ // "forget" the destruction.
|
|
+
|
|
+ // if (stream) npuStreamDestroy(stream);
|
|
+
|
|
+ }
|
|
+
|
|
+ DeviceIndex device_index = -1;
|
|
+ int32_t stream_id = -1;
|
|
+ aclrtStream stream = nullptr;
|
|
+ ::std::unique_ptr<NPUQueueBase> repo = nullptr;
|
|
+};
|
|
+
|
|
+// Global stream state and constants
|
|
+static DeviceIndex num_npus = -1;
|
|
+static constexpr int kStreamsPerPoolBits = 3;
|
|
+static constexpr int kStreamsPerPool = 1 << kStreamsPerPoolBits;
|
|
+// static constexpr unsigned int kDefaultFlags = npuStreamNonBlocking;
|
|
+
|
|
+// Default streams
|
|
+static std::once_flag init_flag;
|
|
+static LeakyStreamInternals default_streams[C10_COMPILE_TIME_MAX_NPUS];
|
|
+
|
|
+// In a specific scenario, the two operators have no value dependence
|
|
+// and different execution hardware, so they can be executed in parallel
|
|
+// on the default stream and the secondary stream respectively.
|
|
+static LeakyStreamInternals secondary_streams[C10_COMPILE_TIME_MAX_NPUS];
|
|
+
|
|
+static std::once_flag device_flags[C10_COMPILE_TIME_MAX_NPUS];
|
|
+static std::atomic<uint32_t> npu_counters[C10_COMPILE_TIME_MAX_NPUS];
|
|
+
|
|
+static std::array<LeakyStreamInternals, kStreamsPerPool>
|
|
+ npu_streams[C10_COMPILE_TIME_MAX_NPUS];
|
|
+
|
|
+enum class StreamIdType : uint8_t {
|
|
+ DEFAULT = 0x0,
|
|
+ HCCL = 0x1,
|
|
+ SECONDARY = 0x2,
|
|
+};
|
|
+
|
|
+std::ostream& operator<<(std::ostream& stream, StreamIdType s) {
|
|
+ switch (s) {
|
|
+ case StreamIdType::DEFAULT:
|
|
+ stream << "DEFAULT";
|
|
+ break;
|
|
+ case StreamIdType::HCCL:
|
|
+ stream << "HCCL";
|
|
+ break;
|
|
+ case StreamIdType::SECONDARY:
|
|
+ stream << "SECONDARY";
|
|
+ break;
|
|
+ default:
|
|
+ stream << static_cast<uint8_t>(s);
|
|
+ break;
|
|
+ }
|
|
+ return stream;
|
|
+}
|
|
+
|
|
+static inline StreamIdType streamIdType(StreamId s) {
|
|
+ return static_cast<StreamIdType>((uint32_t)s >> kStreamsPerPoolBits);
|
|
+}
|
|
+
|
|
+static inline size_t streamIdIndex(StreamId s) {
|
|
+ return static_cast<size_t>((uint32_t)s & ((1 << kStreamsPerPoolBits) - 1));
|
|
+}
|
|
+
|
|
+StreamId makeStreamId(StreamIdType st, size_t si) {
|
|
+ return ((uint32_t)static_cast<StreamId>(st) << kStreamsPerPoolBits) |
|
|
+ static_cast<StreamId>(si);
|
|
+}
|
|
+
|
|
+template <typename T, typename A>
|
|
+static bool pointer_within(const T* ptr, const A& arr) {
|
|
+ return std::greater_equal<const T*>()(ptr, arr.data()) &&
|
|
+ std::less<const T*>()(ptr, arr.data() + arr.size());
|
|
+}
|
|
+
|
|
+static StreamId NPUStream_getStreamId(const LeakyStreamInternals* ptr) {
|
|
+ DeviceIndex device_index = ptr->device_index;
|
|
+ if (ptr == &default_streams[device_index]) {
|
|
+ return makeStreamId(StreamIdType::DEFAULT, 0);
|
|
+ }
|
|
+ if (pointer_within<LeakyStreamInternals>(ptr, npu_streams[device_index])) {
|
|
+ return makeStreamId(
|
|
+ StreamIdType::HCCL, ptr - npu_streams[device_index].data());
|
|
+ }
|
|
+ if (ptr == &secondary_streams[device_index]) {
|
|
+ return makeStreamId(StreamIdType::SECONDARY, 0);
|
|
+ }
|
|
+ AT_ASSERTM(
|
|
+ 0,
|
|
+ "Could not compute stream ID for ",
|
|
+ ptr,
|
|
+ " on device ",
|
|
+ device_index,
|
|
+ " (something has gone horribly wrong!)");
|
|
+}
|
|
+
|
|
+static thread_local LeakyStreamInternals** current_streams = nullptr;
|
|
+
|
|
+static void initGlobalStreamState() {
|
|
+ // TODO device_count(), set to 1 temporarily.
|
|
+ num_npus = c10::npu::device_count();
|
|
+ // Check if the number of GPUs matches the expected compile-time max number
|
|
+ // of GPUs.
|
|
+ AT_ASSERTM(
|
|
+ num_npus <= C10_COMPILE_TIME_MAX_NPUS,
|
|
+ "Number of NPU devices on the machine is larger than the compiled "
|
|
+ "max number of npus expected (",
|
|
+ C10_COMPILE_TIME_MAX_NPUS,
|
|
+ "). Increase that and recompile.");
|
|
+
|
|
+ int device_id = 0;
|
|
+ auto ret = aclrtGetDevice(&device_id);
|
|
+ if (ret != ACL_ERROR_NONE) {
|
|
+ NPU_LOGE("Device has not been set");
|
|
+ }
|
|
+ // Initializes default streams
|
|
+ default_streams[device_id].device_index = device_id;
|
|
+ npu_counters[device_id] = 0;
|
|
+ auto& default_streamsi = default_streams[device_id];
|
|
+ C10_NPU_CHECK(aclrtCreateStream(&default_streamsi.stream));
|
|
+ if (OptionsManager::CheckQueueEnable()) {
|
|
+ default_streamsi.repo->InitRepo(device_id);
|
|
+ }
|
|
+ // Initializes secondary streams
|
|
+ secondary_streams[device_id].device_index = device_id;
|
|
+ auto& secondary_streamsi = secondary_streams[device_id];
|
|
+ C10_NPU_CHECK(aclrtCreateStream(&secondary_streamsi.stream));
|
|
+}
|
|
+
|
|
+static void initDeviceStreamState(DeviceIndex device_index) {
|
|
+ // Switches to the requested device so streams are properly associated
|
|
+ // with it.
|
|
+ NPUGuard device_guard{device_index};
|
|
+ for (auto i = decltype(kStreamsPerPool){0}; i < kStreamsPerPool; ++i) {
|
|
+ auto& npu_streami = npu_streams[device_index][i];
|
|
+
|
|
+ npu_streami.device_index = device_index;
|
|
+
|
|
+ C10_NPU_CHECK(aclrtCreateStream(&npu_streami.stream));
|
|
+ }
|
|
+}
|
|
+
|
|
+static void initNPUStreamsOnce() {
|
|
+ // Inits default and secondary streams (once, globally)
|
|
+ std::call_once(init_flag, initGlobalStreamState);
|
|
+
|
|
+ if (current_streams) {
|
|
+ return;
|
|
+ }
|
|
+
|
|
+ // Inits current streams (thread local) to default streams
|
|
+ current_streams =
|
|
+ (LeakyStreamInternals**)malloc(num_npus * sizeof(LeakyStreamInternals*));
|
|
+ if (current_streams == NULL){
|
|
+ NPU_LOGE("current_streams malloc failed.");
|
|
+ return;
|
|
+ }
|
|
+ for (auto i = decltype(num_npus){0}; i < num_npus; ++i) {
|
|
+ current_streams[i] = &default_streams[i];
|
|
+ }
|
|
+}
|
|
+
|
|
+static inline void check_npu(DeviceIndex device_index) {
|
|
+ AT_ASSERT(device_index >= 0 && device_index < num_npus);
|
|
+}
|
|
+
|
|
+static uint32_t get_idx(std::atomic<uint32_t>& counter) {
|
|
+ auto raw_idx = counter++;
|
|
+ return raw_idx % kStreamsPerPool;
|
|
+}
|
|
+
|
|
+LeakyStreamInternals* NPUStream_internals(NPUStream s) {
|
|
+ c10::DeviceIndex device_index = s.device_index();
|
|
+ StreamIdType st = streamIdType(s.unwrap().id());
|
|
+ size_t si = streamIdIndex(s.unwrap().id());
|
|
+ switch (st) {
|
|
+ case StreamIdType::DEFAULT:
|
|
+ AT_ASSERTM(
|
|
+ si == 0,
|
|
+ "Unrecognized stream ",
|
|
+ s.unwrap(),
|
|
+ " (I think this should be the default stream, but I got a non-zero index ",
|
|
+ si,
|
|
+ ").",
|
|
+ " Did you manufacture the StreamId yourself? Don't do that; use the",
|
|
+ " official API like c10::cuda::getStreamFromPool() to get a new stream.");
|
|
+ return &default_streams[device_index];
|
|
+ case StreamIdType::HCCL:
|
|
+ return &npu_streams[device_index][si];
|
|
+ case StreamIdType::SECONDARY:
|
|
+ return &secondary_streams[device_index];
|
|
+ default:
|
|
+ AT_ASSERTM(
|
|
+ 0,
|
|
+ "Unrecognized stream ",
|
|
+ s.unwrap(),
|
|
+ " (I didn't recognize the stream type, ",
|
|
+ st,
|
|
+ ")");
|
|
+ }
|
|
+}
|
|
+
|
|
+NPUStream NPUStream_fromInternals(const LeakyStreamInternals* ptr) {
|
|
+ return NPUStream(
|
|
+ NPUStream::UNCHECKED,
|
|
+ Stream(
|
|
+ Stream::UNSAFE,
|
|
+ c10::Device(DeviceType::NPU, ptr->device_index),
|
|
+ NPUStream_getStreamId(ptr)));
|
|
+}
|
|
+} // namespace
|
|
+
|
|
+C10_API aclrtStream NPUStream::stream() const {
|
|
+ auto ptr = NPUStream_internals(getDefaultNPUStream());
|
|
+ AT_ASSERT(ptr);
|
|
+ if (ptr->repo->CheckInit()) {
|
|
+ NPUStatus ret = ptr->repo->MakeSureQueueEmpty();
|
|
+ if (ret != SUCCESS) {
|
|
+ NPU_LOGE("MakeSureQueueEmpty fail, ret: %s", ret.c_str());
|
|
+ return nullptr;
|
|
+ }
|
|
+ }
|
|
+ auto cur_ptr = NPUStream_internals(*this);
|
|
+ AT_ASSERT(cur_ptr);
|
|
+ return cur_ptr->stream;
|
|
+}
|
|
+
|
|
+NPUStream getNPUStreamFromPool(DeviceIndex device_index) {
|
|
+ initNPUStreamsOnce();
|
|
+ if (device_index == -1)
|
|
+ device_index = current_device();
|
|
+ check_npu(device_index);
|
|
+
|
|
+ // Initializes the stream pools (once)
|
|
+ std::call_once(
|
|
+ device_flags[device_index], initDeviceStreamState, device_index);
|
|
+
|
|
+ const auto idx = get_idx(npu_counters[device_index]);
|
|
+ return NPUStream_fromInternals(&npu_streams[device_index][idx]);
|
|
+}
|
|
+
|
|
+NPUStream getStreamFromPool(
|
|
+ const bool isHighPriority,
|
|
+ DeviceIndex device_index) {
|
|
+ initNPUStreamsOnce();
|
|
+ if (device_index == -1)
|
|
+ device_index = current_device();
|
|
+ check_npu(device_index);
|
|
+
|
|
+ // Initializes the stream pools (once)
|
|
+ std::call_once(
|
|
+ device_flags[device_index], initDeviceStreamState, device_index);
|
|
+
|
|
+ if (isHighPriority) {
|
|
+ const auto idx = get_idx(npu_counters[device_index]);
|
|
+ return NPUStream_fromInternals(&npu_streams[device_index][idx]);
|
|
+ }
|
|
+
|
|
+ const auto idx = get_idx(npu_counters[device_index]);
|
|
+ return NPUStream_fromInternals(&npu_streams[device_index][idx]);
|
|
+}
|
|
+
|
|
+NPUStream getDefaultNPUStream(DeviceIndex device_index) {
|
|
+ initNPUStreamsOnce();
|
|
+ if (device_index == -1) {
|
|
+ device_index = current_device();
|
|
+ }
|
|
+ return NPUStream_fromInternals(&default_streams[device_index]);
|
|
+}
|
|
+
|
|
+NPUStream getCurrentNPUStream(DeviceIndex device_index) {
|
|
+ initNPUStreamsOnce();
|
|
+ if (device_index == -1) {
|
|
+ device_index = current_device();
|
|
+ }
|
|
+ check_npu(device_index);
|
|
+ return NPUStream_fromInternals(current_streams[device_index]);
|
|
+}
|
|
+
|
|
+NPUStream getCurrentSecondaryStream(DeviceIndex device_index) {
|
|
+ initNPUStreamsOnce();
|
|
+ if (device_index == -1) {
|
|
+ device_index = current_device();
|
|
+ }
|
|
+ check_npu(device_index);
|
|
+ return NPUStream_fromInternals(&secondary_streams[device_index]);
|
|
+}
|
|
+
|
|
+aclrtStream getCurrentNPUStreamNoWait(DeviceIndex device_index) {
|
|
+ initNPUStreamsOnce();
|
|
+ if (device_index == -1) {
|
|
+ device_index = current_device();
|
|
+ }
|
|
+ check_npu(device_index);
|
|
+ LeakyStreamInternals* ptr = current_streams[device_index];
|
|
+ return ptr->stream;
|
|
+}
|
|
+
|
|
+NPUStatus emptyAllNPUStream() {
|
|
+ initNPUStreamsOnce();
|
|
+ NPUStatus ret;
|
|
+ for (auto i = decltype(num_npus){0}; i < num_npus; ++i) {
|
|
+ auto& default_streamsi = default_streams[i];
|
|
+ if (default_streamsi.stream == nullptr) {
|
|
+ continue;
|
|
+ }
|
|
+ NPUGuard device_guard{i};
|
|
+ if (default_streamsi.stream != nullptr && default_streamsi.repo->CheckInit()) {
|
|
+ ret = default_streamsi.repo->MakeSureQueueEmpty();
|
|
+ if (ret != SUCCESS) {
|
|
+ return ret;
|
|
+ }
|
|
+ }
|
|
+ }
|
|
+ return SUCCESS;
|
|
+}
|
|
+
|
|
+void npuSynchronizeDevice() {
|
|
+ if (OptionsManager::CheckQueueEnable()) {
|
|
+ NPUStatus ret = c10::npu::emptyAllNPUStream();
|
|
+ if (ret != SUCCESS) {
|
|
+ NPU_LOGE("MakeSureQueueEmpty fail, ret: %s", ret.c_str());
|
|
+ return;
|
|
+ }
|
|
+ }
|
|
+ C10_NPU_CHECK(aclrtSynchronizeDevice());
|
|
+}
|
|
+
|
|
+void enCurrentNPUStream(
|
|
+ void* cur_paras,
|
|
+ SmallVector<Storage, N>& needClearVec,
|
|
+ DeviceIndex device_index) {
|
|
+ initNPUStreamsOnce();
|
|
+ if (device_index == -1) {
|
|
+ device_index = current_device();
|
|
+ }
|
|
+ check_npu(device_index);
|
|
+ c10::npu::queue::QueueParas* queueParam = static_cast<c10::npu::queue::QueueParas* >(cur_paras);
|
|
+ queueParam->paramStream = current_streams[device_index]->stream;
|
|
+ default_streams[device_index].repo->Enqueue(cur_paras, needClearVec);
|
|
+ if (default_streams[device_index].repo->GetStatus() == RepoStatus::INIT) {
|
|
+ default_streams[device_index].repo->MakeSureQueueEmpty();
|
|
+ default_streams[device_index].repo->ChangeStatus(RepoStatus::INIT, RepoStatus::RUN);
|
|
+ }
|
|
+}
|
|
+
|
|
+void setCurrentNPUStream(NPUStream stream) {
|
|
+ initNPUStreamsOnce();
|
|
+ auto ptr = NPUStream_internals(stream);
|
|
+ AT_ASSERT(ptr);
|
|
+ current_streams[ptr->device_index] = ptr;
|
|
+}
|
|
+
|
|
+std::ostream& operator<<(std::ostream& stream, const NPUStream& s) {
|
|
+ return stream << s.unwrap();
|
|
+}
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/NPUStream.h patch/c10/npu/NPUStream.h
|
|
--- pytorch-v1.8.1/c10/npu/NPUStream.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/NPUStream.h 2022-03-08 15:25:36.520231820 +0800
|
|
@@ -0,0 +1,133 @@
|
|
+#pragma once
|
|
+
|
|
+#include <cstdint>
|
|
+#include <mutex>
|
|
+#include "NPUQueue.h"
|
|
+#include <c10/core/DeviceGuard.h>
|
|
+#include <c10/core/Stream.h>
|
|
+#include <c10/npu/NPUException.h>
|
|
+#include <c10/npu/NPUMacros.h>
|
|
+#include <c10/npu/npu_log.h>
|
|
+#include <c10/util/Exception.h>
|
|
+#include <third_party/acl/inc/acl/acl_op.h>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+class C10_NPU_API NPUStream {
|
|
+ public:
|
|
+ enum Unchecked { UNCHECKED };
|
|
+
|
|
+ explicit NPUStream(Stream stream) : stream_(stream) {
|
|
+ TORCH_CHECK(stream_.device_type() == DeviceType::NPU);
|
|
+ }
|
|
+
|
|
+ explicit NPUStream(Unchecked, Stream stream) : stream_(stream) {}
|
|
+
|
|
+ ~NPUStream(){}
|
|
+
|
|
+ bool operator==(const NPUStream& other) const noexcept {
|
|
+ return unwrap() == other.unwrap();
|
|
+ }
|
|
+
|
|
+ bool operator!=(const NPUStream& other) const noexcept {
|
|
+ return unwrap() != other.unwrap();
|
|
+ }
|
|
+
|
|
+ /// Implicit conversion to rtStream_t.
|
|
+ operator aclrtStream() const {
|
|
+ return stream();
|
|
+ }
|
|
+
|
|
+ /// Implicit conversion to pytorch Stream.
|
|
+ operator Stream() const {
|
|
+ return unwrap();
|
|
+ }
|
|
+
|
|
+ /// Get the NPU device index that this stream is associated with.
|
|
+ DeviceIndex device_index() const {
|
|
+ return stream_.device_index();
|
|
+ }
|
|
+
|
|
+ /// Get the full Device that this stream is associated with. The Device
|
|
+ /// is guaranteed to be a NPU device.
|
|
+ Device device() const {
|
|
+ return Device(DeviceType::NPU, device_index());
|
|
+ }
|
|
+
|
|
+ StreamId id() const {
|
|
+ return stream_.id();
|
|
+ }
|
|
+
|
|
+ /*
|
|
+ bool query() const {
|
|
+ DeviceGuard guard{stream_.device()};
|
|
+ aclError err = aclrtQueryStream(stream());
|
|
+
|
|
+ if (err == ACL_ERROR_NONE) {
|
|
+ return true;
|
|
+ } else if (err != ACL_ERROR_NOT_READY) {
|
|
+ C10_NPU_CHECK(err);
|
|
+ }
|
|
+
|
|
+ return false;
|
|
+ } */
|
|
+
|
|
+ void synchronize() const {
|
|
+ DeviceGuard guard{stream_.device()};
|
|
+ C10_NPU_CHECK(aclrtSynchronizeStream(stream()));
|
|
+ }
|
|
+
|
|
+ /// Explicit conversion to rtStream_t.
|
|
+ C10_API aclrtStream stream() const;
|
|
+
|
|
+ /// Explicit conversion to Stream.
|
|
+ Stream unwrap() const {
|
|
+ return stream_;
|
|
+ }
|
|
+
|
|
+ uint64_t pack() const noexcept {
|
|
+ return stream_.pack();
|
|
+ }
|
|
+
|
|
+ static NPUStream unpack(uint64_t bits) {
|
|
+ return NPUStream(Stream::unpack(bits));
|
|
+ }
|
|
+
|
|
+ private:
|
|
+ Stream stream_;
|
|
+};
|
|
+
|
|
+TORCH_API NPUStream getNPUStreamFromPool(DeviceIndex device = -1);
|
|
+
|
|
+TORCH_API NPUStream getDefaultNPUStream(DeviceIndex device_index = -1);
|
|
+
|
|
+TORCH_API NPUStream getCurrentNPUStream(DeviceIndex device_index = -1);
|
|
+
|
|
+TORCH_API NPUStream getCurrentSecondaryStream(DeviceIndex device_index = -1);
|
|
+
|
|
+TORCH_API aclrtStream getCurrentNPUStreamNoWait(DeviceIndex device_index = -1);
|
|
+
|
|
+TORCH_API NPUStatus emptyAllNPUStream();
|
|
+TORCH_API void npuSynchronizeDevice();
|
|
+
|
|
+TORCH_API void enCurrentNPUStream(
|
|
+ void* cur_paras,
|
|
+ SmallVector<Storage, N>& needClearVec,
|
|
+ DeviceIndex device_index = -1);
|
|
+
|
|
+TORCH_API void setCurrentNPUStream(NPUStream stream);
|
|
+
|
|
+C10_API std::ostream& operator<<(std::ostream& stream, const NPUStream& s);
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
+
|
|
+namespace std {
|
|
+template <>
|
|
+struct hash<c10::npu::NPUStream> {
|
|
+ size_t operator()(c10::npu::NPUStream s) const noexcept {
|
|
+ return std::hash<c10::Stream>{}(s.unwrap());
|
|
+ }
|
|
+};
|
|
+} // namespace std
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/OptionsManager.cpp patch/c10/npu/OptionsManager.cpp
|
|
--- pytorch-v1.8.1/c10/npu/OptionsManager.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/OptionsManager.cpp 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,108 @@
|
|
+#include "c10/npu/OptionsManager.h"
|
|
+#include <string>
|
|
+#include "c10/npu/register/OptionRegister.h"
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+using namespace std;
|
|
+
|
|
+bool OptionsManager::CheckQueueEnable() {
|
|
+ static int32_t queue_enable = -1;
|
|
+ if (queue_enable == -1) {
|
|
+ queue_enable = GetBoolTypeOption("TASK_QUEUE_ENABLE");
|
|
+ }
|
|
+ return (queue_enable == 1);
|
|
+}
|
|
+
|
|
+bool OptionsManager::CheckPTcopy_Enable() {
|
|
+ static int32_t PTcopy__enable = -1;
|
|
+ if (PTcopy__enable == -1) {
|
|
+ PTcopy__enable = GetBoolTypeOption("PTCOPY_ENABLE");
|
|
+ }
|
|
+ return (PTcopy__enable == 1);
|
|
+}
|
|
+
|
|
+bool OptionsManager::CheckCombinedOptimizerEnable() {
|
|
+ static int32_t combined_optimize = -1;
|
|
+ if (combined_optimize == -1) {
|
|
+ combined_optimize = GetBoolTypeOption("COMBINED_ENABLE");
|
|
+ }
|
|
+ return (combined_optimize == 1);
|
|
+}
|
|
+
|
|
+bool OptionsManager::CheckTriCombinedOptimizerEnable() {
|
|
+ static int32_t tri_combined_optimize = -1;
|
|
+ if (tri_combined_optimize == -1) {
|
|
+ tri_combined_optimize = GetBoolTypeOption("TRI_COMBINED_ENABLE");
|
|
+ }
|
|
+ return (tri_combined_optimize == 1);
|
|
+}
|
|
+
|
|
+
|
|
+bool OptionsManager::CheckAclDumpDateEnable() {
|
|
+ static int aclDumpDataEnable = -1;
|
|
+ if (aclDumpDataEnable == -1) {
|
|
+ aclDumpDataEnable = GetBoolTypeOption("ACL_DUMP_DATA");
|
|
+ }
|
|
+ return (aclDumpDataEnable == 1);
|
|
+}
|
|
+
|
|
+bool OptionsManager::CheckSwitchMMOutputEnable() {
|
|
+ static int switchMMOutputEnable = -1;
|
|
+ if (switchMMOutputEnable == -1) {
|
|
+ switchMMOutputEnable = GetBoolTypeOption("SWITCH_MM_OUTPUT_ENABLE");
|
|
+ }
|
|
+ return (switchMMOutputEnable == 1);
|
|
+}
|
|
+
|
|
+int OptionsManager::GetBoolTypeOption(const char* env_str) {
|
|
+ char* env_val = std::getenv(env_str);
|
|
+ int64_t envFlag = (env_val != nullptr) ? strtol(env_val, nullptr, 10) : 0;
|
|
+ return (envFlag != 0) ? 1 : 0;
|
|
+}
|
|
+
|
|
+bool OptionsManager::CheckUseNpuLogEnable() {
|
|
+ static int useNpuLog = -1;
|
|
+ if (useNpuLog == -1) {
|
|
+ useNpuLog = GetBoolTypeOption("NPU_LOG_ENABLE");
|
|
+ }
|
|
+
|
|
+ return (useNpuLog == 1);
|
|
+}
|
|
+
|
|
+bool OptionsManager::CheckDynamicOptimizer(const char* op) {
|
|
+ static int isGetOps = 0;
|
|
+ static std::map<std::string, bool> op_map = {{"ADD", false}, {"MUL", false}};
|
|
+ if (isGetOps == 0) {
|
|
+ char* dynamicOptimizerEnv = std::getenv("DYNAMIC_OP");
|
|
+ if (dynamicOptimizerEnv != nullptr) {
|
|
+ std::string dynamicOptimizerEnvStr = dynamicOptimizerEnv;
|
|
+ const std::string separator = "#";
|
|
+ std::string::size_type pos1 = 0;
|
|
+ std::string::size_type pos2 = dynamicOptimizerEnvStr.find(separator);
|
|
+ std::string substr;
|
|
+ while (pos2 != std::string::npos) {
|
|
+ substr = dynamicOptimizerEnvStr.substr(pos1, pos2 - pos1);
|
|
+ if (op_map.find(substr) != op_map.end()) {
|
|
+ op_map[substr] = true;
|
|
+ }
|
|
+ pos1 = pos2 + separator.size();
|
|
+ pos2 = dynamicOptimizerEnvStr.find(separator, pos1);
|
|
+ }
|
|
+ if (pos1 != dynamicOptimizerEnvStr.size()) {
|
|
+ substr = dynamicOptimizerEnvStr.substr(pos1);
|
|
+ if (op_map.find(substr) != op_map.end()) {
|
|
+ op_map[substr] = true;
|
|
+ }
|
|
+ }
|
|
+ }
|
|
+ isGetOps = 1;
|
|
+ }
|
|
+ TORCH_CHECK(
|
|
+ op_map.find(op) != op_map.end(), "This op is not currently optimized.");
|
|
+ return op_map[op];
|
|
+}
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/OptionsManager.h patch/c10/npu/OptionsManager.h
|
|
--- pytorch-v1.8.1/c10/npu/OptionsManager.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/OptionsManager.h 2022-04-02 16:30:53.433581347 +0800
|
|
@@ -0,0 +1,30 @@
|
|
+#ifndef __C10_NPU_OPTIONSMANAGER_H__
|
|
+#define __C10_NPU_OPTIONSMANAGER_H__
|
|
+
|
|
+#include <c10/util/Exception.h>
|
|
+#include <map>
|
|
+#include <string>
|
|
+#include <unordered_map>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+class OptionsManager {
|
|
+ public:
|
|
+ static bool CheckQueueEnable();
|
|
+ static bool CheckPTcopy_Enable();
|
|
+ static bool CheckCombinedOptimizerEnable();
|
|
+ static bool CheckTriCombinedOptimizerEnable();
|
|
+ static bool CheckAclDumpDateEnable();
|
|
+ static bool CheckSwitchMMOutputEnable();
|
|
+ static bool CheckDynamicOptimizer(const char* op);
|
|
+ static bool CheckUseNpuLogEnable();
|
|
+ static std::string CheckDisableDynamicPath();
|
|
+ private:
|
|
+ static int GetBoolTypeOption(const char* env_str);
|
|
+};
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
+
|
|
+#endif //
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/register/FunctionLoader.cpp patch/c10/npu/register/FunctionLoader.cpp
|
|
--- pytorch-v1.8.1/c10/npu/register/FunctionLoader.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/register/FunctionLoader.cpp 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,87 @@
|
|
+#include "FunctionLoader.h"
|
|
+#include <dlfcn.h>
|
|
+#include "c10/util/Exception.h"
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+FunctionLoader::FunctionLoader(const std::string& name) {
|
|
+ this->fileName = name + ".so";
|
|
+}
|
|
+
|
|
+FunctionLoader::~FunctionLoader() {
|
|
+ if (this->handle != nullptr) {
|
|
+ dlclose(this->handle);
|
|
+ }
|
|
+}
|
|
+
|
|
+void FunctionLoader::Set(const std::string& name) {
|
|
+ this->registry[name] = nullptr;
|
|
+}
|
|
+
|
|
+void* FunctionLoader::Get(const std::string& name) {
|
|
+ if (this->handle == nullptr) {
|
|
+ auto handle = dlopen(this->fileName.c_str(), RTLD_LAZY);
|
|
+ if (handle == nullptr) {
|
|
+ AT_ERROR(dlerror());
|
|
+ return nullptr;
|
|
+ }
|
|
+ this->handle = handle;
|
|
+ }
|
|
+
|
|
+ auto itr = registry.find(name);
|
|
+ if (itr == registry.end()) {
|
|
+ AT_ERROR("function(", name, ") is not registered.");
|
|
+ return nullptr;
|
|
+ }
|
|
+
|
|
+ if (itr->second != nullptr) {
|
|
+ return itr->second;
|
|
+ }
|
|
+
|
|
+ auto func = dlsym(this->handle, name.c_str());
|
|
+ if (func == nullptr) {
|
|
+ return nullptr;
|
|
+ }
|
|
+ this->registry[name] = func;
|
|
+ return func;
|
|
+}
|
|
+
|
|
+namespace register_function {
|
|
+ FunctionRegister* FunctionRegister::GetInstance() {
|
|
+ static FunctionRegister instance;
|
|
+ return &instance;
|
|
+ }
|
|
+ void FunctionRegister::Register(const std::string& name, ::std::unique_ptr<FunctionLoader>& ptr) {
|
|
+ std::lock_guard<std::mutex> lock(mu_);
|
|
+ registry.emplace(name, std::move(ptr));
|
|
+ }
|
|
+
|
|
+ void FunctionRegister::Register(const std::string& name, const std::string& funcName) {
|
|
+ auto itr = registry.find(name);
|
|
+ if (itr == registry.end()) {
|
|
+ AT_ERROR(name, " library should register first.");
|
|
+ return;
|
|
+ }
|
|
+ itr->second->Set(funcName);
|
|
+ }
|
|
+
|
|
+ void* FunctionRegister::Get(const std::string& soName, const std::string& funcName) {
|
|
+ auto itr = registry.find(soName);
|
|
+ if (itr != registry.end()) {
|
|
+ return itr->second->Get(funcName);
|
|
+ }
|
|
+ return nullptr;
|
|
+ }
|
|
+
|
|
+ FunctionRegisterBuilder::FunctionRegisterBuilder(const std::string& name, ::std::unique_ptr<FunctionLoader>& ptr) {
|
|
+ FunctionRegister::GetInstance()->Register(name, ptr);
|
|
+ }
|
|
+ FunctionRegisterBuilder::FunctionRegisterBuilder(const std::string& soName, const std::string& funcName) {
|
|
+ FunctionRegister::GetInstance()->Register(soName, funcName);
|
|
+ }
|
|
+} // namespace register_function
|
|
+
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace at
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/register/FunctionLoader.h patch/c10/npu/register/FunctionLoader.h
|
|
--- pytorch-v1.8.1/c10/npu/register/FunctionLoader.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/register/FunctionLoader.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,98 @@
|
|
+#include <mutex>
|
|
+#include <memory>
|
|
+#include <string>
|
|
+#include <unordered_map>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+/**
|
|
+ FunctionLoader is used to store function address in the process.
|
|
+ */
|
|
+class FunctionLoader {
|
|
+public:
|
|
+ /**
|
|
+ ctr
|
|
+ */
|
|
+ explicit FunctionLoader(const std::string& filename);
|
|
+ /**
|
|
+ dectr
|
|
+ */
|
|
+ ~FunctionLoader();
|
|
+ /**
|
|
+ set function name
|
|
+ */
|
|
+ void Set(const std::string& name);
|
|
+ /**
|
|
+ get function address by function name.
|
|
+ */
|
|
+ void* Get(const std::string& name);
|
|
+private:
|
|
+ mutable std::mutex mu_;
|
|
+ std::string fileName;
|
|
+ void* handle = nullptr;
|
|
+ mutable std::unordered_map<std::string, void*> registry;
|
|
+}; // class FunctionLoader
|
|
+
|
|
+
|
|
+namespace register_function {
|
|
+/**
|
|
+ this class is used to register
|
|
+ */
|
|
+class FunctionRegister {
|
|
+public:
|
|
+ /**
|
|
+ Singleton
|
|
+ */
|
|
+ static FunctionRegister* GetInstance();
|
|
+ /**
|
|
+ this API is used to store FunctionLoader class
|
|
+ */
|
|
+ void Register(const std::string& name, ::std::unique_ptr<FunctionLoader>& ptr);
|
|
+ /**
|
|
+ this API is used to associate library name and function name.
|
|
+ */
|
|
+ void Register(const std::string& name, const std::string& funcName);
|
|
+ /**
|
|
+ this API is used to get the function address by library and function name.
|
|
+ */
|
|
+ void* Get(const std::string& soName, const std::string& funcName);
|
|
+
|
|
+private:
|
|
+ FunctionRegister() = default;
|
|
+ mutable std::mutex mu_;
|
|
+ mutable std::unordered_map<std::string, ::std::unique_ptr<FunctionLoader>> registry;
|
|
+}; // class FunctionRegister
|
|
+
|
|
+/**
|
|
+ FunctionRegisterBuilder is the helper of FunctionRegister.
|
|
+ */
|
|
+class FunctionRegisterBuilder {
|
|
+public:
|
|
+ /**
|
|
+ ctr
|
|
+ */
|
|
+ FunctionRegisterBuilder(const std::string& name, ::std::unique_ptr<FunctionLoader>& ptr);
|
|
+ /**
|
|
+ ctr
|
|
+ */
|
|
+ FunctionRegisterBuilder(const std::string& soName, const std::string& funcName);
|
|
+}; // class FunctionRegisterBuilder
|
|
+
|
|
+} // namespace register_function
|
|
+
|
|
+#define REGISTER_LIBRARY(soName) \
|
|
+ auto library_##soName = \
|
|
+ ::std::unique_ptr<c10::npu::FunctionLoader>(new c10::npu::FunctionLoader(#soName)); \
|
|
+ static c10::npu::register_function::FunctionRegisterBuilder \
|
|
+ register_library_##soName(#soName, library_##soName);
|
|
+
|
|
+#define REGISTER_FUNCTION(soName, funcName) \
|
|
+ static c10::npu::register_function::FunctionRegisterBuilder \
|
|
+ register_function_##funcName(#soName, #funcName);
|
|
+
|
|
+#define GET_FUNCTION(soName, funcName) \
|
|
+ c10::npu::register_function::FunctionRegister::GetInstance()->Get(#soName, #funcName);
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/register/OptionRegister.cpp patch/c10/npu/register/OptionRegister.cpp
|
|
--- pytorch-v1.8.1/c10/npu/register/OptionRegister.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/register/OptionRegister.cpp 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,87 @@
|
|
+#include <algorithm>
|
|
+#include "OptionRegister.h"
|
|
+#include "c10/util/Exception.h"
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+OptionInterface::OptionInterface(OptionCallBack callback) {
|
|
+ this->callback = callback;
|
|
+}
|
|
+
|
|
+void OptionInterface::Set(const std::string& in) {
|
|
+ this->val = in;
|
|
+ if (this->callback != nullptr) {
|
|
+ this->callback(in);
|
|
+ }
|
|
+}
|
|
+
|
|
+std::string OptionInterface::Get() {
|
|
+ return val;
|
|
+}
|
|
+
|
|
+
|
|
+namespace register_options {
|
|
+OptionRegister* OptionRegister::GetInstance() {
|
|
+ static OptionRegister instance;
|
|
+ return &instance;
|
|
+}
|
|
+
|
|
+void OptionRegister::Register(const std::string& name,
|
|
+ ::std::unique_ptr<OptionInterface>& ptr) {
|
|
+ std::lock_guard<std::mutex> lock(mu_);
|
|
+ registry.emplace(name, std::move(ptr));
|
|
+}
|
|
+
|
|
+void OptionRegister::Set(const std::string& name, const std::string& val) {
|
|
+ auto itr = registry.find(name);
|
|
+ if (itr != registry.end()) {
|
|
+ itr->second->Set(val);
|
|
+ } else {
|
|
+ AT_ERROR("invalid npu option name:", name);
|
|
+ }
|
|
+}
|
|
+
|
|
+c10::optional<std::string> OptionRegister::Get(const std::string& name) {
|
|
+ auto itr = registry.find(name);
|
|
+ if (itr != registry.end()) {
|
|
+ return itr->second->Get();
|
|
+ }
|
|
+ return c10::nullopt; // default value
|
|
+}
|
|
+
|
|
+OptionInterfaceBuilder::OptionInterfaceBuilder(
|
|
+ const std::string& name,
|
|
+ ::std::unique_ptr<OptionInterface>& ptr,
|
|
+ const std::string& type) {
|
|
+ OptionRegister::GetInstance()->Register(name, ptr);
|
|
+
|
|
+ // init the value if env variable.
|
|
+ if (type == "env") {
|
|
+ std::string env_name = name;
|
|
+ std::transform(env_name.begin(), env_name.end(), env_name.begin(), ::toupper);
|
|
+ char* env_val = std::getenv(env_name.c_str());
|
|
+ if (env_val != nullptr) {
|
|
+ std::string val(env_val);
|
|
+ OptionRegister::GetInstance()->Set(name, val);
|
|
+ }
|
|
+ }
|
|
+}
|
|
+} // namespace register_options
|
|
+
|
|
+void SetOption(const std::string& key, const std::string& val) {
|
|
+ register_options::OptionRegister::GetInstance()->Set(key, val);
|
|
+}
|
|
+
|
|
+void SetOption(const std::map<std::string, std::string>& options) {
|
|
+ for (auto item : options) {
|
|
+ SetOption(item.first, item.second);
|
|
+ }
|
|
+}
|
|
+
|
|
+c10::optional<std::string> GetOption(const std::string& key) {
|
|
+ return register_options::OptionRegister::GetInstance()->Get(key);
|
|
+}
|
|
+
|
|
+} // namespace c10
|
|
+} // namespace npu
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/register/OptionRegister.h patch/c10/npu/register/OptionRegister.h
|
|
--- pytorch-v1.8.1/c10/npu/register/OptionRegister.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/register/OptionRegister.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,130 @@
|
|
+#ifndef __C10_NPU_OPTION_REGISTER_H__
|
|
+#define __C10_NPU_OPTION_REGISTER_H__
|
|
+
|
|
+#include <map>
|
|
+#include <memory>
|
|
+#include <mutex>
|
|
+#include <string>
|
|
+#include <unordered_map>
|
|
+#include <c10/util/Optional.h>
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+typedef void(*OptionCallBack) (const std::string&);
|
|
+/**
|
|
+ This class is used to storage env value, and provide Set and Get to
|
|
+ */
|
|
+class OptionInterface {
|
|
+ public:
|
|
+ /**
|
|
+ dctr
|
|
+ */
|
|
+ OptionInterface(OptionCallBack callback=nullptr);
|
|
+ /**
|
|
+ This API is used to store value.
|
|
+ */
|
|
+ void Set(const std::string& in);
|
|
+ /**
|
|
+ This API is used to load value.
|
|
+ */
|
|
+ std::string Get();
|
|
+ private:
|
|
+/**
|
|
+ Its used to store hook.
|
|
+ */
|
|
+ OptionCallBack callback = nullptr;
|
|
+ std::string val;
|
|
+};
|
|
+
|
|
+namespace register_options {
|
|
+
|
|
+/**
|
|
+ This class is used to register OptionInterface
|
|
+ */
|
|
+class OptionRegister {
|
|
+ public:
|
|
+ /**
|
|
+ dctr
|
|
+ */
|
|
+ ~OptionRegister() = default;
|
|
+ /**
|
|
+ singleton
|
|
+ */
|
|
+ static OptionRegister* GetInstance();
|
|
+ /**
|
|
+ register
|
|
+ */
|
|
+ void Register(const std::string& name, ::std::unique_ptr<OptionInterface>& ptr);
|
|
+ /**
|
|
+ This API is used to store value to special key.
|
|
+ */
|
|
+ void Set(const std::string& name, const std::string& val);
|
|
+ /**
|
|
+ This API is used to load value from special key.
|
|
+ */
|
|
+ c10::optional<std::string> Get(const std::string& name);
|
|
+ private:
|
|
+ OptionRegister() {}
|
|
+ mutable std::mutex mu_;
|
|
+ mutable std::unordered_map<std::string, ::std::unique_ptr<OptionInterface>> registry;
|
|
+};
|
|
+
|
|
+/**
|
|
+ This class is the helper to construct class OptionRegister
|
|
+ */
|
|
+class OptionInterfaceBuilder {
|
|
+ public:
|
|
+ OptionInterfaceBuilder(const std::string& name, ::std::unique_ptr<OptionInterface>& ptr, const std::string& type = "cli");
|
|
+};
|
|
+
|
|
+} // namespace register_options
|
|
+
|
|
+/**
|
|
+ This API is used to store key-value pairs
|
|
+ */
|
|
+void SetOption(const std::map<std::string, std::string>& options);
|
|
+/**
|
|
+ This API is used to store key-value pair
|
|
+ */
|
|
+void SetOption(const std::string& key, const std::string& val);
|
|
+/**
|
|
+ This API is used to load value by key
|
|
+ */
|
|
+c10::optional<std::string> GetOption(const std::string& key);
|
|
+
|
|
+#define REGISTER_OPTION(name) \
|
|
+ REGISTER_OPTION_UNIQ(name, name, cli)
|
|
+
|
|
+#define REGISTER_OPTION_INIT_BY_ENV(name) \
|
|
+ REGISTER_OPTION_UNIQ(name, name, env)
|
|
+
|
|
+#define REGISTER_OPTION_UNIQ(id, name, type) \
|
|
+ auto options_interface_##id = \
|
|
+ ::std::unique_ptr<c10::npu::OptionInterface>(new c10::npu::OptionInterface()); \
|
|
+ static c10::npu::register_options::OptionInterfaceBuilder \
|
|
+ register_options_interface_##id(#name, options_interface_##id, #type);
|
|
+
|
|
+#define REGISTER_OPTION_HOOK(name, ...) \
|
|
+ REGISTER_OPTION_HOOK_UNIQ(name, name, __VA_ARGS__)
|
|
+
|
|
+#define REGISTER_OPTION_HOOK_UNIQ(id, name, ...) \
|
|
+ auto options_interface_##id = \
|
|
+ ::std::unique_ptr<c10::npu::OptionInterface>( \
|
|
+ new c10::npu::OptionInterface(c10::npu::OptionCallBack(__VA_ARGS__))); \
|
|
+ static c10::npu::register_options::OptionInterfaceBuilder \
|
|
+ register_options_interface_##id(#name, options_interface_##id);
|
|
+
|
|
+#define REGISTER_OPTION_BOOL_FUNCTION(func, key, defaultVal, trueVal) \
|
|
+ bool func() { \
|
|
+ auto val = c10::npu::GetOption(#key); \
|
|
+ if (val.value_or(defaultVal) == (trueVal)) { \
|
|
+ return true; \
|
|
+ } \
|
|
+ return false; \
|
|
+ }
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
+
|
|
+#endif // __C10_NPU_OPTION_REGISTER_H__
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/sys_ctrl/npu_sys_ctrl.cpp patch/c10/npu/sys_ctrl/npu_sys_ctrl.cpp
|
|
--- pytorch-v1.8.1/c10/npu/sys_ctrl/npu_sys_ctrl.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/sys_ctrl/npu_sys_ctrl.cpp 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,183 @@
|
|
+#include "npu_sys_ctrl.h"
|
|
+#include <Python.h>
|
|
+#include <c10/npu/npu_log.h>
|
|
+#include <c10/npu/interface/AclInterface.h>
|
|
+#include <c10/npu/NPUStream.h>
|
|
+#include <c10/npu/OptionsManager.h>
|
|
+#include <c10/npu/register/OptionRegister.h>
|
|
+#ifdef SUCCESS
|
|
+#undef SUCCESS
|
|
+#endif
|
|
+#ifdef FAILED
|
|
+#undef FAILED
|
|
+#endif
|
|
+#include <third_party/acl/inc/ge/ge_api.h>
|
|
+
|
|
+#if defined(_MSC_VER)
|
|
+#include <direct.h>
|
|
+#define GetCurrentDirPath _getcwd
|
|
+#define Mkdir(path, mode) _mkdir(path)
|
|
+#elif defined(__unix__)
|
|
+#include <unistd.h>
|
|
+#include <sys/stat.h>
|
|
+#include <sys/types.h>
|
|
+#define GetCurrentDirPath getcwd
|
|
+#define Mkdir(path, mode) mkdir(path, mode)
|
|
+#else
|
|
+#endif
|
|
+
|
|
+namespace {
|
|
+const size_t kMaxPathLen = 4096U;
|
|
+std::string GetCurDirPath() {
|
|
+ char buff[kMaxPathLen] = {'\0'};
|
|
+ GetCurrentDirPath(buff, kMaxPathLen);
|
|
+ return std::string(buff);
|
|
+}
|
|
+
|
|
+void MakeCompileCacheDirAndSetOption() {
|
|
+ auto compile_cache_dir = GetCurDirPath() + "/cache";
|
|
+ // mode : 750
|
|
+ auto ret = Mkdir(compile_cache_dir.c_str(), S_IRWXU | S_IRGRP | S_IXGRP);
|
|
+ if (ret == -1) {
|
|
+ if (errno != EEXIST) {
|
|
+ TORCH_WARN("make compile cache directory error: ", strerror(errno));
|
|
+ return;
|
|
+ }
|
|
+ }
|
|
+ c10::npu::register_options::OptionRegister::GetInstance()->Set("ACL_OP_COMPILER_CACHE_MODE", "enable");
|
|
+ c10::npu::register_options::OptionRegister::GetInstance()->Set("ACL_OP_COMPILER_CACHE_DIR", compile_cache_dir);
|
|
+}
|
|
+} // namespace
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+NpuSysCtrl::NpuSysCtrl() : init_flag_(false), device_id_(0) {}
|
|
+
|
|
+// Get NpuSysCtrl singleton instance
|
|
+C10_API NpuSysCtrl& NpuSysCtrl::GetInstance() {
|
|
+ static NpuSysCtrl instance;
|
|
+ return instance;
|
|
+}
|
|
+
|
|
+// GE Environment Initialize, return Status: SUCCESS, FAILED
|
|
+C10_API NpuSysCtrl::SysStatus NpuSysCtrl::Initialize(int device_id) {
|
|
+
|
|
+ if (init_flag_) {
|
|
+ return INIT_SUCC;
|
|
+ }
|
|
+ C10_NPU_CHECK(aclInit(nullptr));
|
|
+
|
|
+ if (c10::npu::OptionsManager::CheckAclDumpDateEnable()){
|
|
+ C10_NPU_CHECK(aclmdlInitDump());
|
|
+ NPU_LOGD("dump init success");
|
|
+ }
|
|
+
|
|
+ auto ret = aclrtGetDevice(&device_id_);
|
|
+ if (ret != ACL_ERROR_NONE) {
|
|
+ device_id_ = (device_id == -1) ? 0 : device_id;
|
|
+ C10_NPU_CHECK(aclrtSetDevice(device_id_));
|
|
+ }else{
|
|
+ NPU_LOGE("Npu device %d has been set before global init.", device_id_);
|
|
+ }
|
|
+
|
|
+ init_flag_ = true;
|
|
+ NPU_LOGD("Npu sys ctrl initialize successfully.");
|
|
+
|
|
+ if (c10::npu::OptionsManager::CheckAclDumpDateEnable()) {
|
|
+ const char *aclConfigPath = "acl.json";
|
|
+ C10_NPU_CHECK(aclmdlSetDump(aclConfigPath));
|
|
+ NPU_LOGD("set dump config success");
|
|
+ }
|
|
+
|
|
+ auto npu_device_id = std::to_string(device_id_);
|
|
+ std::map<ge::AscendString, ge::AscendString> config = {
|
|
+ {ge::AscendString(ge::OPTION_EXEC_DEVICE_ID),
|
|
+ ge::AscendString(npu_device_id.data())},
|
|
+ {ge::AscendString(ge::OPTION_GRAPH_RUN_MODE), "0"},
|
|
+ {ge::AscendString(ge::PRECISION_MODE.data()), "allow_fp32_to_fp16"},
|
|
+ {ge::AscendString(ge::VARIABLE_MEMORY_MAX_SIZE), "1048576"},
|
|
+ {ge::AscendString(ge::OP_SELECT_IMPL_MODE.data()), "high_precision"}
|
|
+ };
|
|
+
|
|
+ config["ge.session_device_id"] = ge::AscendString(npu_device_id.data());
|
|
+ config["ge.exec.reuseZeroCopyMemory"] = ge::AscendString("1");
|
|
+
|
|
+ static std::map<const std::string, const std::string>
|
|
+ STRING_TO_COMPILE_OPT_MAP = {
|
|
+ {"ACL_OP_DEBUG_LEVEL", ge::OP_DEBUG_LEVEL},
|
|
+ {"ACL_DEBUG_DIR", ge::DEBUG_DIR},
|
|
+ {"ACL_OP_COMPILER_CACHE_MODE", ge::OP_COMPILER_CACHE_MODE},
|
|
+ {"ACL_OP_COMPILER_CACHE_DIR", ge::OP_COMPILER_CACHE_DIR},
|
|
+ {"ACL_OP_SELECT_IMPL_MODE", ge::OP_SELECT_IMPL_MODE},
|
|
+ {"ACL_OPTYPELIST_FOR_IMPLMODE", ge::OPTYPELIST_FOR_IMPLMODE}
|
|
+ };
|
|
+
|
|
+ for (const auto& iter : STRING_TO_COMPILE_OPT_MAP) {
|
|
+ auto val = c10::npu::GetOption(iter.first);
|
|
+ if (val.has_value() && (!val.value().empty())) {
|
|
+ config.emplace(iter.second.data(), val.value().data());
|
|
+ }
|
|
+ }
|
|
+
|
|
+// auto soc_name = c10::npu::acl::AclGetSocName();
|
|
+// if (soc_name != nullptr) {
|
|
+// config.emplace(ge::AscendString(ge::SOC_VERSION.data()), soc_name);
|
|
+// }
|
|
+
|
|
+// if (c10::npu::acl::IsExistQueryEventRecordedStatus()) {
|
|
+// static const std::string HCOM_OPTIONS = "ge.exec.isUseHcom";
|
|
+// config.emplace(HCOM_OPTIONS.data(), "1");
|
|
+// }
|
|
+
|
|
+ auto ge_ret = ge::GEInitialize(config);
|
|
+ if (ge_ret != ge::SUCCESS) {
|
|
+ AT_ERROR("GE init failed!");
|
|
+ }
|
|
+
|
|
+ // set default compile cache mode and dir for users to improve op compile time
|
|
+ // set option has been moved to plugin, wait to be decoupled
|
|
+ // MakeCompileCacheDirAndSetOption();
|
|
+
|
|
+ return INIT_SUCC;
|
|
+}
|
|
+
|
|
+C10_API NpuSysCtrl::SysStatus NpuSysCtrl::ExchangeDevice(int pre_device, int device) {
|
|
+ C10_NPU_CHECK(aclrtResetDevice(pre_device));
|
|
+ C10_NPU_CHECK(aclrtSetDevice(device));
|
|
+ device_id_= device;
|
|
+ return INIT_SUCC;
|
|
+}
|
|
+
|
|
+C10_API NpuSysCtrl::SysStatus NpuSysCtrl::BackwardsInit() {
|
|
+ C10_NPU_CHECK(aclrtSetDevice(device_id_));
|
|
+ return INIT_SUCC;
|
|
+}
|
|
+
|
|
+// GE Environment Finalize, return SysStatus
|
|
+C10_API NpuSysCtrl::SysStatus NpuSysCtrl::Finalize() {
|
|
+ if (!init_flag_) {
|
|
+ return FINALIZE_SUCC;
|
|
+ }
|
|
+ c10::npu::NPUEventManager::GetInstance().ClearEvent();
|
|
+ auto stream = c10::npu::getCurrentNPUStream();
|
|
+ (void)aclrtDestroyStream(stream);
|
|
+ C10_NPU_CHECK(ge::GEFinalize());
|
|
+ C10_NPU_CHECK(aclrtResetDevice(device_id_));
|
|
+ C10_NPU_CHECK(aclFinalize());
|
|
+ init_flag_ = false;
|
|
+
|
|
+ if (c10::npu::OptionsManager::CheckAclDumpDateEnable()) {
|
|
+ C10_NPU_CHECK(aclmdlFinalizeDump());
|
|
+ }
|
|
+
|
|
+ NPU_LOGD("Npu sys ctrl finalize successfully.");
|
|
+ return FINALIZE_SUCC;
|
|
+}
|
|
+
|
|
+C10_API bool NpuSysCtrl::GetInitFlag() {
|
|
+ return init_flag_;
|
|
+}
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/npu/sys_ctrl/npu_sys_ctrl.h patch/c10/npu/sys_ctrl/npu_sys_ctrl.h
|
|
--- pytorch-v1.8.1/c10/npu/sys_ctrl/npu_sys_ctrl.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/c10/npu/sys_ctrl/npu_sys_ctrl.h 2022-03-07 18:32:02.224337802 +0800
|
|
@@ -0,0 +1,61 @@
|
|
+#ifndef __C10_NPU_SYS_CTRL___
|
|
+#define __C10_NPU_SYS_CTRL___
|
|
+
|
|
+#include <third_party/acl/inc/acl/acl.h>
|
|
+#include <map>
|
|
+#include <string>
|
|
+#include <vector>
|
|
+#include "c10/macros/Export.h"
|
|
+#include <c10/npu/NPUEventManager.h>
|
|
+#define NpuSysStatus c10::npu::NpuSysCtrl::SysStatus
|
|
+
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+
|
|
+class NpuSysCtrl {
|
|
+public:
|
|
+ ~NpuSysCtrl() = default;
|
|
+
|
|
+ enum SysStatus {
|
|
+ INIT_SUCC = 0,
|
|
+ INIT_ALREADY,
|
|
+ INIT_FAILED,
|
|
+ CREATE_SESS_SUCC,
|
|
+ CREATE_SESS_FAILED,
|
|
+ ADD_GRAPH_SUCC,
|
|
+ ADD_GRAPH_FAILED,
|
|
+ RUN_GRAPH_SUCC,
|
|
+ RUN_GRAPH_FAILED,
|
|
+ FINALIZE_SUCC,
|
|
+ FINALIZE_FAILED,
|
|
+ };
|
|
+
|
|
+ // Get NpuSysCtrl singleton instance
|
|
+ C10_API static NpuSysCtrl& GetInstance();
|
|
+
|
|
+ // GE Environment Initialize, return SysStatus
|
|
+ C10_API SysStatus Initialize(int device_id = -1);
|
|
+
|
|
+ // Change current device from pre_device to device
|
|
+ C10_API SysStatus ExchangeDevice(int pre_device, int device);
|
|
+
|
|
+ // Init backwards thread
|
|
+ C10_API SysStatus BackwardsInit();
|
|
+
|
|
+ // GE Environment Finalize, return SysStatus
|
|
+ C10_API SysStatus Finalize();
|
|
+
|
|
+ // Get Init_flag
|
|
+ C10_API bool GetInitFlag();
|
|
+private:
|
|
+ NpuSysCtrl();
|
|
+
|
|
+private:
|
|
+ bool init_flag_;
|
|
+ int device_id_;
|
|
+};
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
+
|
|
+#endif
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/cmake/BuildVariables.cmake patch/cmake/BuildVariables.cmake
|
|
--- pytorch-v1.8.1/cmake/BuildVariables.cmake 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/cmake/BuildVariables.cmake 2022-03-07 18:32:02.340338536 +0800
|
|
@@ -11,6 +11,7 @@
|
|
# CMakeLists.txt files under each folder respectively.
|
|
set(Caffe2_CPU_SRCS)
|
|
set(Caffe2_GPU_SRCS)
|
|
+set(Caffe2_NPU_SRCS)
|
|
|
|
# Caffe2_{CPU,GPU}_TEST_SRCS is the list that will have all the related source
|
|
# files for CPU and GPU tests respectively.
|
|
@@ -21,10 +22,12 @@
|
|
# directories for CPU and GPU respectively.
|
|
set(Caffe2_CPU_INCLUDE)
|
|
set(Caffe2_GPU_INCLUDE)
|
|
+set(Caffe2_NPU_INCLUDE)
|
|
|
|
# Lists for Caffe2 dependency libraries, for CPU and CUDA respectively.
|
|
set(Caffe2_DEPENDENCY_LIBS "")
|
|
set(Caffe2_CUDA_DEPENDENCY_LIBS "")
|
|
+set(Caffe2_NPU_DEPENDENCY_LIBS "")
|
|
# This variable contains dependency libraries of Caffe2 which requires whole
|
|
# symbol linkage. One example is the onnx lib where we need all its schema
|
|
# symbols. However, if the lib is whole linked in caffe2 lib, we don't want
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/cmake/Codegen.cmake patch/cmake/Codegen.cmake
|
|
--- pytorch-v1.8.1/cmake/Codegen.cmake 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/cmake/Codegen.cmake 2022-03-07 18:32:02.340338536 +0800
|
|
@@ -214,7 +214,7 @@
|
|
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/aten/src/ATen)
|
|
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/aten/src/ATen/core)
|
|
|
|
- add_custom_command(OUTPUT ${generated_cpp} ${cuda_generated_cpp} ${core_generated_cpp}
|
|
+ add_custom_command(OUTPUT ${generated_cpp} ${cuda_generated_cpp} ${core_generated_cpp} ${npu_generated_cpp}
|
|
COMMAND ${GEN_COMMAND}
|
|
DEPENDS ${all_python} ${all_templates}
|
|
${CMAKE_CURRENT_LIST_DIR}/../aten/src/ATen/native/native_functions.yaml
|
|
@@ -226,10 +226,13 @@
|
|
# on building the generated ATen files to workaround.
|
|
add_custom_target(ATEN_CPU_FILES_GEN_TARGET DEPENDS ${generated_cpp} ${core_generated_cpp})
|
|
add_custom_target(ATEN_CUDA_FILES_GEN_TARGET DEPENDS ${cuda_generated_cpp})
|
|
+ add_custom_target(ATEN_NPU_FILES_GEN_TARGET DEPENDS ${npu_generated_cpp})
|
|
add_library(ATEN_CPU_FILES_GEN_LIB INTERFACE)
|
|
add_library(ATEN_CUDA_FILES_GEN_LIB INTERFACE)
|
|
+ add_library(ATEN_NPU_FILES_GEN_LIB INTERFACE)
|
|
add_dependencies(ATEN_CPU_FILES_GEN_LIB ATEN_CPU_FILES_GEN_TARGET)
|
|
add_dependencies(ATEN_CUDA_FILES_GEN_LIB ATEN_CUDA_FILES_GEN_TARGET)
|
|
+ add_dependencies(ATEN_NPU_FILES_GEN_LIB ATEN_NPU_FILES_GEN_TARGET)
|
|
endif()
|
|
|
|
function(append_filelist name outputvar)
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/cmake/Dependencies.cmake patch/cmake/Dependencies.cmake
|
|
--- pytorch-v1.8.1/cmake/Dependencies.cmake 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/cmake/Dependencies.cmake 2022-03-07 18:32:02.340338536 +0800
|
|
@@ -1771,6 +1771,13 @@
|
|
endif(NOT C_HAS_THREAD)
|
|
endif()
|
|
|
|
+# ---[ NPU
|
|
+if(USE_NPU)
|
|
+ include(${CMAKE_CURRENT_LIST_DIR}/public/npu.cmake)
|
|
+ set(Caffe2_NPU_DEPENDENCY_LIBS npu_interface)
|
|
+ add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/../third_party/acl)
|
|
+endif()
|
|
+
|
|
#
|
|
# End ATen checks
|
|
#
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/cmake/public/npu.cmake patch/cmake/public/npu.cmake
|
|
--- pytorch-v1.8.1/cmake/public/npu.cmake 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/cmake/public/npu.cmake 2022-03-07 18:32:02.344338561 +0800
|
|
@@ -0,0 +1,30 @@
|
|
+if(NOT TARGET npu_interface)
|
|
+ add_library(npu_interface INTERFACE)
|
|
+endif()
|
|
+
|
|
+set(NPU_BASE_DIRS "${CMAKE_BINARY_DIR}/../third_party/acl")
|
|
+# Npu headers
|
|
+set(NPU_INCLUDE_DIRS "${NPU_BASE_DIRS}/inc")
|
|
+list(APPEND NPU_INCLUDE_DIRS "${NPU_BASE_DIRS}/inc/acl")
|
|
+
|
|
+link_directories("${NPU_BASE_DIRS}/libs")
|
|
+link_directories("$ENV{ACL_HOME}/lib64")
|
|
+link_directories("$ENV{ASCEND_DRIVER_HOME}")
|
|
+
|
|
+if(${CMAKE_VERSION} VERSION_LESS "3.12.0")
|
|
+message(FATAL_ERROR "Please consider switch to CMake 3.12.0 or above")
|
|
+endif()
|
|
+
|
|
+if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.12.0")
|
|
+ find_package (Python3 COMPONENTS Interpreter Development REQUIRED)
|
|
+ message("Python3 RUNTIME LIBRAY DIRS: " ${Python3_RUNTIME_LIBRARY_DIRS})
|
|
+ link_directories(${Python3_RUNTIME_LIBRARY_DIRS})
|
|
+endif()
|
|
+
|
|
+target_include_directories(npu_interface INTERFACE ${NPU_INCLUDE_DIRS})
|
|
+
|
|
+if(USE_HCCL)
|
|
+ target_link_libraries(npu_interface INTERFACE acl_op_compiler ascendcl hccl python3.7m graph ge_runner)
|
|
+else()
|
|
+ target_link_libraries(npu_interface INTERFACE acl_op_compiler ascendcl python3.7m graph ge_runner)
|
|
+endif()
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/cmake/Summary.cmake patch/cmake/Summary.cmake
|
|
--- pytorch-v1.8.1/cmake/Summary.cmake 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/cmake/Summary.cmake 2022-03-07 18:32:02.344338561 +0800
|
|
@@ -127,6 +127,7 @@
|
|
message(STATUS " USE_MKLDNN_CBLAS : ${USE_MKLDNN_CBLAS}")
|
|
endif()
|
|
message(STATUS " USE_NCCL : ${USE_NCCL}")
|
|
+ message(STATUS " USE_HCCL : ${USE_HCCL}")
|
|
if(${USE_NCCL})
|
|
message(STATUS " USE_SYSTEM_NCCL : ${USE_SYSTEM_NCCL}")
|
|
endif()
|
|
@@ -162,6 +163,7 @@
|
|
if(NOT "${SELECTED_OP_LIST}" STREQUAL "")
|
|
message(STATUS " SELECTED_OP_LIST : ${SELECTED_OP_LIST}")
|
|
endif()
|
|
+ message(STATUS " USE_NPU : ${USE_NPU}")
|
|
message(STATUS " USE_DEPLOY : ${USE_DEPLOY}")
|
|
message(STATUS " Public Dependencies : ${Caffe2_PUBLIC_DEPENDENCY_LIBS}")
|
|
message(STATUS " Private Dependencies : ${Caffe2_DEPENDENCY_LIBS}")
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/cmake/TorchConfig.cmake.in patch/cmake/TorchConfig.cmake.in
|
|
--- pytorch-v1.8.1/cmake/TorchConfig.cmake.in 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/cmake/TorchConfig.cmake.in 2022-03-07 18:32:02.344338561 +0800
|
|
@@ -158,6 +158,11 @@
|
|
list(APPEND TORCH_LIBRARIES ${TORCH_CUDA_LIBRARIES})
|
|
endif()
|
|
|
|
+if (@USE_NPU@)
|
|
+ find_library(C10_NPU_LIBRARY c10_npu PATHS "${TORCH_INSTALL_PREFIX}/lib")
|
|
+ list(APPEND TORCH_LIBRARIES ${C10_NPU_LIBRARY})
|
|
+endif()
|
|
+
|
|
# When we build libtorch with the old GCC ABI, dependent libraries must too.
|
|
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
|
|
set(TORCH_CXX_FLAGS "-D_GLIBCXX_USE_CXX11_ABI=@GLIBCXX_USE_CXX11_ABI@")
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/CMakeLists.txt patch/CMakeLists.txt
|
|
--- pytorch-v1.8.1/CMakeLists.txt 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/CMakeLists.txt 2022-03-07 18:32:02.068336815 +0800
|
|
@@ -261,6 +261,10 @@
|
|
"USE_DISTRIBUTED" OFF)
|
|
option(USE_TBB "Use TBB" OFF)
|
|
option(ONNX_ML "Enable traditional ONNX ML API." ON)
|
|
+# TODO: need to add options to disable NPU on other platforms
|
|
+option(USE_NPU "Use NPU" ON)
|
|
+option(USE_HCCL "Use HCCL" ON)
|
|
+
|
|
option(HAVE_SOVERSION "Whether to add SOVERSION to the shared objects" OFF)
|
|
cmake_dependent_option(
|
|
USE_DEPLOY "Build embedded torch::deploy interpreter" OFF
|
|
@@ -748,7 +752,29 @@
|
|
else()
|
|
message(ERROR "Code coverage for compiler ${CMAKE_CXX_COMPILER_ID} is unsupported")
|
|
endif()
|
|
+endif()
|
|
+
|
|
+if (USE_NPU)
|
|
+ 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}")
|
|
+ else()
|
|
+ set (CMAKE_C_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-s,-z,noexecstack -fPIE -pie ${CMAKE_C_FLAGS}")
|
|
+ set (CMAKE_CXX_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-s,-z,noexecstack -fPIE -pie ${CMAKE_CXX_FLAGS}")
|
|
+ set (CXXFLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-s,-z,noexecstack -fPIE -pie ${CXXFLAGS}")
|
|
+ endif()
|
|
+ set (CMAKE_SKIP_RPATH TRUE)
|
|
+ add_definitions(-DUSE_NPU=1)
|
|
+endif()
|
|
+
|
|
+if (USE_HCCL)
|
|
+ link_directories(${CMAKE_BINARY_DIR}/../third_party/acl/libs)
|
|
+ add_definitions(-DUSE_HCCL=1)
|
|
+endif()
|
|
|
|
+if ($ENV{NPU_LOG_ENABLE})
|
|
+ add_definitions(-NPU_LOG_ENABLE=1)
|
|
endif()
|
|
|
|
if(APPLE)
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/setup.py patch/setup.py
|
|
--- pytorch-v1.8.1/setup.py 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/setup.py 2022-04-16 12:30:03.012363284 +0800
|
|
@@ -898,9 +898,15 @@
|
|
'include/c10/hip/*.h',
|
|
'include/c10/hip/impl/*.h',
|
|
'include/c10d/*.hpp',
|
|
+ 'include/c10/npu/*.h',
|
|
+ 'include/c10/npu/interface/*.h',
|
|
+ 'include/c10/npu/impl/*.h',
|
|
+ 'include/c10/npu/sys_ctrl/*.h',
|
|
+ 'include/c10/npu/register/*.h',
|
|
'include/caffe2/**/*.h',
|
|
'include/torch/*.h',
|
|
'include/torch/csrc/*.h',
|
|
+ 'include/torch/csrc/generic/*.h',
|
|
'include/torch/csrc/api/include/torch/*.h',
|
|
'include/torch/csrc/api/include/torch/data/*.h',
|
|
'include/torch/csrc/api/include/torch/data/dataloader/*.h',
|
|
@@ -940,6 +946,10 @@
|
|
'include/torch/csrc/jit/tensorexpr/*.h',
|
|
'include/torch/csrc/onnx/*.h',
|
|
'include/torch/csrc/utils/*.h',
|
|
+ 'include/torch/csrc/tensor/*.h',
|
|
+ 'include/torch/csrc/distributed/c10d/*.h',
|
|
+ 'include/torch/csrc/distributed/rpc/*.h',
|
|
+ 'include/torch/csrc/distributed/autograd/**/*.h',
|
|
'include/pybind11/*.h',
|
|
'include/pybind11/detail/*.h',
|
|
'include/TH/*.h*',
|
|
@@ -952,6 +962,12 @@
|
|
'include/THH/*.cuh',
|
|
'include/THH/*.h*',
|
|
'include/THH/generic/*.h',
|
|
+ # TODO(ascend): the following two acl directories should be removed after the NPU API is enhanced.
|
|
+ 'include/third_party/acl/inc/acl/*.h',
|
|
+ 'include/third_party/acl/inc/acl/ops/*.h',
|
|
+ 'include/third_party/acl/inc/ge/*.h',
|
|
+ 'include/third_party/acl/inc/graph/*.h',
|
|
+ 'include/third_party/acl/inc/op_proto/*.h',
|
|
'share/cmake/ATen/*.cmake',
|
|
'share/cmake/Caffe2/*.cmake',
|
|
'share/cmake/Caffe2/public/*.cmake',
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/tools/autograd/templates/python_torch_functions.cpp patch/tools/autograd/templates/python_torch_functions.cpp
|
|
--- pytorch-v1.8.1/tools/autograd/templates/python_torch_functions.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/tools/autograd/templates/python_torch_functions.cpp 2022-05-05 14:32:51.351071624 +0800
|
|
@@ -30,7 +30,6 @@
|
|
#include "torch/csrc/autograd/generated/variable_factories.h"
|
|
#include "torch/csrc/utils/structseq.h"
|
|
#include "torch/csrc/utils/cuda_lazy_init.h"
|
|
-
|
|
#include <ATen/ATen.h>
|
|
|
|
#include <functional>
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/tools/autograd/templates/python_variable_methods.cpp patch/tools/autograd/templates/python_variable_methods.cpp
|
|
--- pytorch-v1.8.1/tools/autograd/templates/python_variable_methods.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/tools/autograd/templates/python_variable_methods.cpp 2022-05-05 14:32:51.351071624 +0800
|
|
@@ -531,6 +531,23 @@
|
|
END_HANDLE_TH_ERRORS
|
|
}
|
|
|
|
+static PyObject * THPVariable_npu(PyObject* self, PyObject* args, PyObject* kwargs)
|
|
+{
|
|
+ HANDLE_TH_ERRORS
|
|
+ static PythonArgParser parser({
|
|
+ "npu(Device? device=None, bool non_blocking=False, *, MemoryFormat? memory_format=None)",
|
|
+ "npu(Device? device=None, bool async=False, *, MemoryFormat? memory_format=None)|deprecated"
|
|
+ });
|
|
+ auto& self_ = reinterpret_cast<THPVariable*>(self)->cdata;
|
|
+ ParsedArgs<3> parsed_args;
|
|
+ auto r = parser.parse(args, kwargs, parsed_args);
|
|
+ auto device = r.isNone(0) ? at::Device(at::DeviceType::NPU) : r.device(0);
|
|
+ auto opt_memory_format = r.memoryformatOptional(2);
|
|
+ TORCH_CHECK(device.is_npu(), "Invalid device, must be npu device");
|
|
+ return THPVariable_Wrap(dispatch_to(self_, device, r.toBool(1), false, opt_memory_format));
|
|
+ END_HANDLE_TH_ERRORS
|
|
+}
|
|
+
|
|
static PyObject * THPVariable_to_type(PyObject* self, ScalarType scalarType, c10::optional<c10::MemoryFormat> optional_memory_format) {
|
|
HANDLE_TH_ERRORS
|
|
auto& self_ = reinterpret_cast<THPVariable*>(self)->cdata;
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/tools/generate_torch_version.py patch/tools/generate_torch_version.py
|
|
--- pytorch-v1.8.1/tools/generate_torch_version.py 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/tools/generate_torch_version.py 2022-03-07 18:32:03.076343192 +0800
|
|
@@ -17,10 +17,10 @@
|
|
|
|
if os.getenv('PYTORCH_BUILD_VERSION'):
|
|
assert os.getenv('PYTORCH_BUILD_NUMBER') is not None
|
|
- build_number = int(os.getenv('PYTORCH_BUILD_NUMBER', ""))
|
|
+ build_number = int(os.getenv('PYTORCH_BUILD_NUMBER', "0"))
|
|
version = os.getenv('PYTORCH_BUILD_VERSION', "")
|
|
- if build_number > 1:
|
|
- version += '.post' + str(build_number)
|
|
+ if build_number > 0:
|
|
+ version += '.rc' + str(build_number)
|
|
elif sha != 'Unknown':
|
|
if sha is None:
|
|
sha = get_sha(pytorch_root)
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/_C/_autograd.pyi patch/torch/_C/_autograd.pyi
|
|
--- pytorch-v1.8.1/torch/_C/_autograd.pyi 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/_C/_autograd.pyi 2022-03-07 18:32:03.080343218 +0800
|
|
@@ -9,14 +9,17 @@
|
|
CUDA = ...
|
|
NVTX = ...
|
|
KINETO = ...
|
|
+ NPU = ...
|
|
|
|
class ProfilerActivity(Enum):
|
|
CPU = ...
|
|
CUDA = ...
|
|
+ NPU = ...
|
|
|
|
class DeviceType(Enum):
|
|
CPU = ...
|
|
CUDA = ...
|
|
+ NPU = ...
|
|
...
|
|
|
|
class ProfilerConfig:
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/autograd/engine.cpp patch/torch/csrc/autograd/engine.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/autograd/engine.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/csrc/autograd/engine.cpp 2022-03-07 18:32:03.100343345 +0800
|
|
@@ -34,6 +34,11 @@
|
|
#include <queue>
|
|
#include <TH/TH.h>
|
|
|
|
+#ifdef USE_NPU
|
|
+#include <third_party/acl/inc/acl/acl.h>
|
|
+#include <c10/npu/NPUFunctions.h>
|
|
+#include <c10/npu/sys_ctrl/npu_sys_ctrl.h>
|
|
+#endif
|
|
namespace torch { namespace autograd {
|
|
|
|
namespace {
|
|
@@ -499,10 +504,22 @@
|
|
cb_lock.lock();
|
|
}
|
|
|
|
+ at::DeviceType device_type;
|
|
+ at::DeviceType cuda_type = c10::DeviceType::CUDA;
|
|
+#ifdef USE_NPU
|
|
+ at::DeviceType npu_type = c10::DeviceType::NPU;
|
|
+ if (c10::npu::device_count() > 0) {
|
|
+ device_type = npu_type;
|
|
+ } else {
|
|
+ device_type = cuda_type;
|
|
+ }
|
|
+#else
|
|
+ device_type = cuda_type;
|
|
+#endif
|
|
// Syncs leaf streams with default streams (if necessary)
|
|
// See note "Streaming backwards"
|
|
for (const auto& leaf_stream : leaf_streams) {
|
|
- const auto guard = c10::impl::VirtualGuardImpl{c10::DeviceType::CUDA};
|
|
+ const auto guard = c10::impl::VirtualGuardImpl{device_type};
|
|
const auto default_stream = guard.getDefaultStream(leaf_stream.device());
|
|
if (leaf_stream != default_stream) {
|
|
auto event = c10::Event{c10::DeviceType::CUDA};
|
|
@@ -558,6 +575,9 @@
|
|
//
|
|
// Don't use DeviceGuard here because its destructor may be called before the
|
|
// device is reset. This is fine because the device is thread local.
|
|
+#ifdef USE_NPU
|
|
+ c10::npu::NpuSysCtrl::GetInstance().BackwardsInit();
|
|
+#else
|
|
if (device != CPU_DEVICE) {
|
|
for (size_t i = 0; i < static_cast<size_t>(c10::DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES); i++) {
|
|
auto* impl = c10::impl::device_guard_impl_registry[i].load();
|
|
@@ -566,7 +586,9 @@
|
|
}
|
|
}
|
|
}
|
|
+#endif
|
|
worker_device = device;
|
|
+
|
|
}
|
|
|
|
void validate_outputs(
|
|
@@ -716,7 +738,16 @@
|
|
}
|
|
|
|
// Switches to a function's CUDA stream (if applicable) before calling it
|
|
- const auto opt_parent_stream = (*func).stream(c10::DeviceType::CUDA);
|
|
+ const auto opt_stream_gpu = (*func).stream(c10::DeviceType::CUDA);
|
|
+#ifdef USE_NPU
|
|
+ const auto opt_stream_npu = (*func).stream(c10::DeviceType::NPU);
|
|
+
|
|
+ const auto opt_parent_stream = (opt_stream_npu != c10::nullopt) ? opt_stream_npu : opt_stream_gpu;
|
|
+ auto stream_device = (opt_stream_npu != c10::nullopt) ? c10::DeviceType::NPU : c10::DeviceType::CUDA;
|
|
+#else
|
|
+ const auto opt_parent_stream = opt_stream_gpu;
|
|
+ auto stream_device = c10::DeviceType::CUDA;
|
|
+#endif
|
|
c10::OptionalStreamGuard parent_stream_guard{opt_parent_stream};
|
|
|
|
auto outputs = call_function(graph_task, func, inputs);
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/autograd/functions/tensor.cpp patch/torch/csrc/autograd/functions/tensor.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/autograd/functions/tensor.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/csrc/autograd/functions/tensor.cpp 2022-03-07 18:32:03.104343370 +0800
|
|
@@ -26,7 +26,7 @@
|
|
at::DeviceGuard device_guard(src_device);
|
|
// TODO: What if !grad.is_cuda(), but src_device is CUDA?
|
|
// This code is kind of weirdly asymmetric.
|
|
- if (grad.is_cuda() && grad.device() != src_device) {
|
|
+ if ((grad.is_cuda() || grad.is_npu()) && grad.device() != src_device) {
|
|
grad_inputs[1] = grad.to(
|
|
src_options,
|
|
/*non_blocking=*/false,
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/autograd/input_buffer.cpp patch/torch/csrc/autograd/input_buffer.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/autograd/input_buffer.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/csrc/autograd/input_buffer.cpp 2022-03-07 18:32:03.104343370 +0800
|
|
@@ -100,6 +100,28 @@
|
|
opt_accumulate_stream->wait(event);
|
|
}
|
|
}
|
|
+ } else if (device_of(var)->is_npu()) {
|
|
+ const auto on_producer = opt_producer_stream
|
|
+ && device_of(var) == opt_producer_stream->device();
|
|
+ const auto on_consumer = opt_consumer_stream
|
|
+ && device_of(var) == opt_consumer_stream->device();
|
|
+ if (on_producer && on_consumer) {
|
|
+ // (2) NPU variable with producer and consumer sharing a device
|
|
+ // Accumulation happens on consumer's stream
|
|
+ opt_accumulate_stream = opt_consumer_stream;
|
|
+ if (opt_producer_stream != opt_consumer_stream) {
|
|
+ // (2a) Syncs consumer with producer
|
|
+ auto event = c10::Event{c10::DeviceType::NPU};
|
|
+ event.record(*opt_producer_stream);
|
|
+ opt_consumer_stream->wait(event);
|
|
+ }
|
|
+ } else {
|
|
+ // (3) NPU variable with multiple devices
|
|
+ // Accumulation happens on variable's device's default stream
|
|
+ const auto guard = c10::impl::VirtualGuardImpl{c10::DeviceType::NPU};
|
|
+ const auto default_stream = guard.getDefaultStream(*device_of(var));
|
|
+ opt_accumulate_stream = default_stream;
|
|
+ }
|
|
}
|
|
|
|
auto& old_var = buffer[pos];
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/autograd/python_variable_indexing.cpp patch/torch/csrc/autograd/python_variable_indexing.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/autograd/python_variable_indexing.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/csrc/autograd/python_variable_indexing.cpp 2022-03-07 18:32:03.104343370 +0800
|
|
@@ -368,6 +368,9 @@
|
|
// TODO: This qint special case looks very suspicious...
|
|
if (isQIntType(self_.scalar_type())) {
|
|
value = valueToTensor(device(kCPU).dtype(kFloat), py_value, at::Device(kCPU));
|
|
+ } else if (self_device.type() == DeviceType::NPU) {
|
|
+ value = valueToTensor(self_.options().device(kCPU), py_value, at::Device(kCPU));
|
|
+ value = value.to("npu");
|
|
} else {
|
|
value = valueToTensor(self_.options(), py_value, self_device);
|
|
}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/DynamicTypes.cpp patch/torch/csrc/DynamicTypes.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/DynamicTypes.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/csrc/DynamicTypes.cpp 2022-05-05 14:32:51.351071624 +0800
|
|
@@ -61,9 +61,14 @@
|
|
const at::Storage& storage,
|
|
const caffe2::TypeMeta dtype) {
|
|
at::ScalarType scalarType = at::typeMetaToScalarType(dtype);
|
|
- auto attype = &at::getDeprecatedTypeProperties(
|
|
- at::dispatchKeyToBackend(c10::computeDispatchKey(scalarType, c10::nullopt, storage.device_type())),
|
|
- scalarType);
|
|
+ auto backend = at::dispatchKeyToBackend(c10::computeDispatchKey(scalarType, c10::nullopt, storage.device_type()));
|
|
+
|
|
+#ifdef USE_NPU
|
|
+ if (backend == c10::Backend::NPU) {
|
|
+ backend = c10::Backend::CPU;
|
|
+ }
|
|
+#endif
|
|
+ auto attype = &at::getDeprecatedTypeProperties(backend, scalarType);
|
|
auto it = attype_to_py_storage_type.find(attype);
|
|
if (it != attype_to_py_storage_type.end()) {
|
|
return it->second;
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/tensor/python_tensor.cpp patch/torch/csrc/tensor/python_tensor.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/tensor/python_tensor.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/csrc/tensor/python_tensor.cpp 2022-05-05 14:32:51.351071624 +0800
|
|
@@ -185,6 +185,7 @@
|
|
case Backend::CUDA: return "torch.cuda";
|
|
case Backend::SparseCPU: return "torch.sparse";
|
|
case Backend::SparseCUDA: return "torch.cuda.sparse";
|
|
+ case Backend::NPU: return "torch.npu";
|
|
default: AT_ERROR("invalid backend: ", toString(backend));
|
|
}
|
|
}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/utils/python_arg_parser.h patch/torch/csrc/utils/python_arg_parser.h
|
|
--- pytorch-v1.8.1/torch/csrc/utils/python_arg_parser.h 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/csrc/utils/python_arg_parser.h 2022-03-07 18:32:03.176343826 +0800
|
|
@@ -495,7 +495,11 @@
|
|
if (THPUtils_checkLong(args[i])) {
|
|
const auto device_index = THPUtils_unpackLong(args[i]);
|
|
TORCH_CHECK(device_index >= 0, "Device index must not be negative");
|
|
+#ifdef USE_NPU
|
|
+ return at::Device(DeviceType::NPU, device_index);
|
|
+#else
|
|
return at::Device(DeviceType::CUDA, device_index);
|
|
+#endif
|
|
}
|
|
const std::string &device_str = THPUtils_unpackString(args[i]);
|
|
return at::Device(device_str);
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/utils/tensor_new.cpp patch/torch/csrc/utils/tensor_new.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/utils/tensor_new.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/csrc/utils/tensor_new.cpp 2022-05-05 14:32:51.351071624 +0800
|
|
@@ -32,6 +32,7 @@
|
|
using at::IntArrayRef;
|
|
using at::kCPU;
|
|
using at::kCUDA;
|
|
+using at::kNPU;
|
|
using at::kLong;
|
|
using at::Scalar;
|
|
using at::ScalarType;
|
|
@@ -47,6 +48,8 @@
|
|
|
|
Backend backendToBackendOfDeviceType(Backend b, DeviceType d) {
|
|
switch (d) {
|
|
+ case DeviceType::NPU:
|
|
+ return Backend::NPU;
|
|
case DeviceType::CPU:
|
|
return backendToCPU(b);
|
|
case DeviceType::CUDA:
|
|
@@ -341,6 +344,7 @@
|
|
dispatch_key == c10::DispatchKey::CUDA ||
|
|
dispatch_key == c10::DispatchKey::HIP ||
|
|
dispatch_key == c10::DispatchKey::XLA ||
|
|
+ dispatch_key == c10::DispatchKey::NPU ||
|
|
dispatch_key == c10::DispatchKey::XPU,
|
|
"new(): expected DispatchKey: ",
|
|
c10::DispatchKey::CPU,
|
|
@@ -351,6 +355,8 @@
|
|
" or ",
|
|
c10::DispatchKey::XLA,
|
|
" or ",
|
|
+ c10::DispatchKey::NPU,
|
|
+ " or ",
|
|
c10::DispatchKey::XPU,
|
|
" but got: ",
|
|
dispatch_key);
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/utils/tensor_types.cpp patch/torch/csrc/utils/tensor_types.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/utils/tensor_types.cpp 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/csrc/utils/tensor_types.cpp 2022-03-07 18:32:03.176343826 +0800
|
|
@@ -19,6 +19,7 @@
|
|
switch (backend) {
|
|
case at::Backend::CPU: return "torch";
|
|
case at::Backend::CUDA: return "torch.cuda";
|
|
+ case at::Backend::NPU: return "torch.npu";
|
|
case at::Backend::XPU: return "torch.xpu";
|
|
case at::Backend::SparseCPU: return "torch.sparse";
|
|
case at::Backend::SparseCUDA: return "torch.cuda.sparse";
|
|
@@ -82,7 +83,7 @@
|
|
std::vector<std::pair<Backend, ScalarType>> all_declared_types() {
|
|
std::vector<std::pair<Backend, ScalarType>> ret;
|
|
// can't easily iterate over enum classes
|
|
- std::vector<Backend> backends = { Backend::CPU, Backend::CUDA, Backend::SparseCPU, Backend::SparseCUDA };
|
|
+ std::vector<Backend> backends = { Backend::CPU, Backend::CUDA, Backend::SparseCPU, Backend::SparseCUDA, Backend::NPU };
|
|
std::vector<ScalarType> scalar_types = { ScalarType::Byte, ScalarType::Char, ScalarType::Double, ScalarType::Float,
|
|
ScalarType::Int, ScalarType::Long, ScalarType::Short, ScalarType::Half,
|
|
ScalarType::Bool, ScalarType::BFloat16};
|
|
@@ -92,6 +93,9 @@
|
|
if (scalar_type == ScalarType::Bool && (backend == Backend::SparseCUDA || backend == Backend::SparseCPU)) {
|
|
continue;
|
|
}
|
|
+ if (scalar_type == ScalarType::BFloat16 && backend == Backend::NPU) {
|
|
+ continue;
|
|
+ }
|
|
ret.emplace_back(std::make_pair(backend, scalar_type));
|
|
}
|
|
}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/lib/libshm/CMakeLists.txt patch/torch/lib/libshm/CMakeLists.txt
|
|
--- pytorch-v1.8.1/torch/lib/libshm/CMakeLists.txt 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/lib/libshm/CMakeLists.txt 2022-03-07 18:32:03.200343977 +0800
|
|
@@ -41,8 +41,11 @@
|
|
set_target_properties(shm PROPERTIES
|
|
PREFIX "lib"
|
|
IMPORT_PREFIX "lib")
|
|
+if(USE_NPU)
|
|
+target_link_libraries(shm torch c10 c10_npu npu_interface)
|
|
+else()
|
|
target_link_libraries(shm torch c10)
|
|
-
|
|
+endif ()
|
|
if(UNIX AND NOT APPLE)
|
|
include(CheckLibraryExists)
|
|
# https://github.com/libgit2/libgit2/issues/2128#issuecomment-35649830
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/npu/__init__.py patch/torch/npu/__init__.py
|
|
--- pytorch-v1.8.1/torch/npu/__init__.py 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/torch/npu/__init__.py 2022-03-07 18:32:03.212344053 +0800
|
|
@@ -0,0 +1 @@
|
|
+# Empty Module for Npu-type Tensors.
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/storage.py patch/torch/storage.py
|
|
--- pytorch-v1.8.1/torch/storage.py 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/storage.py 2022-03-07 18:32:03.224344129 +0800
|
|
@@ -8,6 +8,7 @@
|
|
class _StorageBase(object):
|
|
_cdata: Any
|
|
is_cuda: bool = False
|
|
+ is_npu = False
|
|
is_sparse: bool = False
|
|
|
|
def __init__(self, *args, **kwargs): ... # noqa: E704
|
|
@@ -139,6 +140,8 @@
|
|
from torch.multiprocessing import get_sharing_strategy
|
|
if self.is_cuda:
|
|
pass # CUDA doesn't use POSIX shared memory
|
|
+ elif self.is_npu:
|
|
+ pass
|
|
elif get_sharing_strategy() == 'file_system':
|
|
self._share_filename_()
|
|
else:
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/tensor.py patch/torch/tensor.py
|
|
--- pytorch-v1.8.1/torch/tensor.py 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/tensor.py 2022-03-07 18:32:03.224344129 +0800
|
|
@@ -59,6 +59,8 @@
|
|
with torch.no_grad():
|
|
if self.is_sparse or self.device.type == 'xla':
|
|
new_tensor = self.clone()
|
|
+ elif self.device.type == 'npu':
|
|
+ new_tensor = self.clone().detach().requires_grad_(self.requires_grad)
|
|
else:
|
|
new_storage = self.storage().__deepcopy__(memo)
|
|
if self.is_quantized:
|
|
@@ -382,7 +384,11 @@
|
|
"""
|
|
if has_torch_function_unary(self):
|
|
return handle_torch_function(Tensor.share_memory_, (self,), self)
|
|
- self.storage().share_memory_()
|
|
+
|
|
+ if self.device.type == 'npu':
|
|
+ self.storage()
|
|
+ else:
|
|
+ self.storage().share_memory_()
|
|
return self
|
|
|
|
def __reversed__(self):
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/_tensor_str.py patch/torch/_tensor_str.py
|
|
--- pytorch-v1.8.1/torch/_tensor_str.py 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/_tensor_str.py 2022-03-07 18:32:03.084343243 +0800
|
|
@@ -77,7 +77,9 @@
|
|
self.int_mode = True
|
|
self.sci_mode = False
|
|
self.max_width = 1
|
|
-
|
|
+ device = tensor.device
|
|
+ if device.type == "npu":
|
|
+ tensor = tensor.to("cpu")
|
|
with torch.no_grad():
|
|
tensor_view = tensor.reshape(-1)
|
|
|
|
@@ -293,7 +295,8 @@
|
|
# In other cases, we don't have a way to set them as default yet,
|
|
# and we should always print out device for them.
|
|
if self.device.type != torch._C._get_default_device()\
|
|
- or (self.device.type == 'cuda' and torch.cuda.current_device() != self.device.index):
|
|
+ or (self.device.type == 'cuda' and torch.cuda.current_device() != self.device.index)\
|
|
+ or (self.device.type == 'npu' and torch.npu.current_device() != self.device.index):
|
|
suffixes.append('device=\'' + str(self.device) + '\'')
|
|
|
|
# TODO: add an API to map real -> complex dtypes
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/utils/data/dataloader.py patch/torch/utils/data/dataloader.py
|
|
--- pytorch-v1.8.1/torch/utils/data/dataloader.py 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/utils/data/dataloader.py 2022-03-07 18:32:03.236344205 +0800
|
|
@@ -16,6 +16,7 @@
|
|
import torch.multiprocessing as multiprocessing
|
|
from torch._utils import ExceptionWrapper
|
|
from torch._six import queue, string_classes
|
|
+import torch.npu
|
|
|
|
from . import IterableDataset, Sampler, SequentialSampler, RandomSampler, BatchSampler, Dataset
|
|
from . import _utils
|
|
@@ -487,7 +488,7 @@
|
|
self._index_sampler = loader._index_sampler
|
|
self._num_workers = loader.num_workers
|
|
self._prefetch_factor = loader.prefetch_factor
|
|
- self._pin_memory = loader.pin_memory and torch.cuda.is_available()
|
|
+ self._pin_memory = loader.pin_memory and (torch.cuda.is_available() or torch.npu.is_available())
|
|
self._timeout = loader.timeout
|
|
self._collate_fn = loader.collate_fn
|
|
self._sampler_iter = iter(self._index_sampler)
|
|
@@ -916,6 +917,11 @@
|
|
self._workers.append(w)
|
|
|
|
if self._pin_memory:
|
|
+ train_device_id = 0
|
|
+ if torch.npu.is_available():
|
|
+ train_device_id = torch.npu.current_device()
|
|
+ else:
|
|
+ train_device_id = torch.cuda.current_device()
|
|
self._pin_memory_thread_done_event = threading.Event()
|
|
|
|
# Queue is not type-annotated
|
|
@@ -923,7 +929,7 @@
|
|
pin_memory_thread = threading.Thread(
|
|
target=_utils.pin_memory._pin_memory_loop,
|
|
args=(self._worker_result_queue, self._data_queue,
|
|
- torch.cuda.current_device(),
|
|
+ train_device_id,
|
|
self._pin_memory_thread_done_event))
|
|
pin_memory_thread.daemon = True
|
|
pin_memory_thread.start()
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/utils/data/_utils/pin_memory.py patch/torch/utils/data/_utils/pin_memory.py
|
|
--- pytorch-v1.8.1/torch/utils/data/_utils/pin_memory.py 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/utils/data/_utils/pin_memory.py 2022-03-07 18:32:03.236344205 +0800
|
|
@@ -6,6 +6,7 @@
|
|
"""
|
|
|
|
import torch
|
|
+import torch.npu
|
|
from torch._six import queue, container_abcs, string_classes
|
|
from . import MP_STATUS_CHECK_INTERVAL
|
|
from torch._utils import ExceptionWrapper
|
|
@@ -14,9 +15,12 @@
|
|
def _pin_memory_loop(in_queue, out_queue, device_id, done_event):
|
|
# This setting is thread local, and prevents the copy in pin_memory from
|
|
# consuming all CPU cores.
|
|
- torch.set_num_threads(1)
|
|
|
|
- torch.cuda.set_device(device_id)
|
|
+ torch.set_num_threads(1)
|
|
+ if torch.npu.is_available():
|
|
+ torch.npu.set_device(device_id)
|
|
+ else:
|
|
+ torch.cuda.set_device(device_id)
|
|
|
|
# See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the
|
|
# logic of this function.
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/_utils.py patch/torch/_utils.py
|
|
--- pytorch-v1.8.1/torch/_utils.py 2022-03-05 10:10:10.000000000 +0800
|
|
+++ patch/torch/_utils.py 2022-03-07 18:32:03.084343243 +0800
|
|
@@ -133,9 +133,15 @@
|
|
t = torch.tensor([], dtype=storage.dtype, device=storage.device)
|
|
return t.set_(storage, storage_offset, size, stride)
|
|
|
|
+def _rebuild_npu_tensor(storage, npu_format, storage_offset, size, stride):
|
|
+ t = torch.tensor([0], dtype=storage.dtype).to(storage.device)
|
|
+ return t.npu_set_(storage, storage_offset, npu_format, size, stride)
|
|
|
|
-def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):
|
|
- tensor = _rebuild_tensor(storage, storage_offset, size, stride)
|
|
+def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks, npu_format=2):
|
|
+ if storage.device.type == 'npu':
|
|
+ tensor = _rebuild_npu_tensor(storage, npu_format, storage_offset, size, stride)
|
|
+ else:
|
|
+ tensor = _rebuild_tensor(storage, storage_offset, size, stride)
|
|
tensor.requires_grad = requires_grad
|
|
# NB: This line exists only for backwards compatibility; the
|
|
# general expectation is that backward_hooks is an empty
|