6066 lines
220 KiB
Diff
6066 lines
220 KiB
Diff
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/CMakeLists.txt patch/CMakeLists.txt
|
|
--- pytorch-v1.8.1/CMakeLists.txt 2022-02-18 11:15:22.814637700 +0800
|
|
+++ patch/CMakeLists.txt 2022-02-18 11:05:22.671793700 +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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/CMakeLists.txt patch/aten/CMakeLists.txt
|
|
--- pytorch-v1.8.1/aten/CMakeLists.txt 2022-02-18 11:15:22.843685500 +0800
|
|
+++ patch/aten/CMakeLists.txt 2022-02-18 11:05:23.553826300 +0800
|
|
@@ -22,9 +22,11 @@
|
|
set(ATen_CPU_INCLUDE)
|
|
set(ATen_THIRD_PARTY_INCLUDE)
|
|
set(ATen_CUDA_SRCS)
|
|
+set(ATen_NPU_SRCS)
|
|
set(ATen_CUDA_SRCS_W_SORT_BY_KEY)
|
|
set(ATen_CUDA_TEST_SRCS)
|
|
set(ATen_CUDA_INCLUDE)
|
|
+set(ATen_NPU_INCLUDE)
|
|
set(ATen_NVRTC_STUB_SRCS)
|
|
set(ATen_HIP_SRCS)
|
|
set(ATen_HIP_SRCS_W_SORT_BY_KEY)
|
|
@@ -44,6 +46,10 @@
|
|
list(APPEND ATen_CUDA_INCLUDE ${CUDA_INCLUDE_DIRS})
|
|
endif()
|
|
|
|
+if(USE_NPU)
|
|
+ list(APPEND ATen_NPU_INCLUDE ${NPU_INCLUDE_DIRS})
|
|
+endif()
|
|
+
|
|
set(TH_LINK_STYLE STATIC)
|
|
add_subdirectory(src/TH)
|
|
set(TH_CPU_INCLUDE
|
|
@@ -86,6 +92,9 @@
|
|
set(AT_CUDA_ENABLED 1)
|
|
add_subdirectory(src/THC)
|
|
add_subdirectory(src/THCUNN)
|
|
+elseif(USE_NPU)
|
|
+ SET(AT_NPU_ENABLED 1)
|
|
+ add_subdirectory(src/THNPU)
|
|
else()
|
|
message("disabling CUDA because USE_CUDA is set false")
|
|
set(AT_CUDA_ENABLED 0)
|
|
@@ -110,6 +119,7 @@
|
|
# Pass source, includes, and libs to parent
|
|
set(ATen_CPU_SRCS ${ATen_CPU_SRCS} PARENT_SCOPE)
|
|
set(ATen_CUDA_SRCS ${ATen_CUDA_SRCS} PARENT_SCOPE)
|
|
+set(ATen_NPU_SRCS ${ATen_NPU_SRCS} PARENT_SCOPE)
|
|
set(ATen_CUDA_SRCS_W_SORT_BY_KEY ${ATen_CUDA_SRCS_W_SORT_BY_KEY} PARENT_SCOPE)
|
|
set(ATen_HIP_SRCS ${ATen_HIP_SRCS} PARENT_SCOPE)
|
|
set(ATen_HIP_SRCS_W_SORT_BY_KEY ${ATen_HIP_SRCS_W_SORT_BY_KEY} PARENT_SCOPE)
|
|
@@ -123,6 +133,7 @@
|
|
set(ATen_VEC256_TEST_SRCS ${ATen_VEC256_TEST_SRCS} PARENT_SCOPE)
|
|
set(ATen_CPU_INCLUDE ${ATen_CPU_INCLUDE} PARENT_SCOPE)
|
|
set(ATen_CUDA_INCLUDE ${ATen_CUDA_INCLUDE} PARENT_SCOPE)
|
|
+set(ATen_NPU_INCLUDE ${ATen_NPU_INCLUDE} PARENT_SCOPE)
|
|
set(ATen_HIP_INCLUDE ${ATen_HIP_INCLUDE} PARENT_SCOPE)
|
|
set(ATen_THIRD_PARTY_INCLUDE ${ATen_THIRD_PARTY_INCLUDE} PARENT_SCOPE)
|
|
set(ATen_CPU_DEPENDENCY_LIBS ${ATen_CPU_DEPENDENCY_LIBS} PARENT_SCOPE)
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/CMakeLists.txt patch/aten/src/ATen/CMakeLists.txt
|
|
--- pytorch-v1.8.1/aten/src/ATen/CMakeLists.txt 2022-02-18 11:15:22.843685500 +0800
|
|
+++ patch/aten/src/ATen/CMakeLists.txt 2022-02-18 11:05:23.604828500 +0800
|
|
@@ -85,6 +85,9 @@
|
|
file(GLOB native_quantized_h "native/quantized/*.h" "native/quantized/cpu/*.h")
|
|
file(GLOB native_cpu_h "native/cpu/*.h")
|
|
|
|
+file(GLOB npu_h "npu/*.h" "npu/detail/*.h")
|
|
+file(GLOB npu_cpp "npu/*.cpp" "npu/detail/*.cpp")
|
|
+
|
|
file(GLOB native_cuda_cu_sp "native/cuda/Unique.cu" "native/cuda/TensorFactories.cu")
|
|
file(GLOB native_cuda_cu "native/cuda/*.cu")
|
|
exclude(native_cuda_cu "${native_cuda_cu}" ${native_cuda_cu_sp})
|
|
@@ -388,6 +391,11 @@
|
|
list(APPEND ATen_CUDA_DEPENDENCY_LIBS ATEN_CUDA_FILES_GEN_LIB)
|
|
endif()
|
|
|
|
+# Treat npu sources directly as cpu
|
|
+if(USE_NPU)
|
|
+ set(ATen_NPU_SRCS ${ATen_NPU_SRCS} ${npu_cpp})
|
|
+endif()
|
|
+
|
|
if(USE_ROCM)
|
|
set(ATen_HIP_SRCS ${all_hip_cpp})
|
|
# caffe2_nvrtc's stubs to driver APIs are useful for HIP.
|
|
@@ -405,7 +413,7 @@
|
|
|
|
set(INSTALL_HEADERS ${base_h} ${ATen_CORE_HEADERS})
|
|
if(NOT INTERN_BUILD_MOBILE)
|
|
- list(APPEND INSTALL_HEADERS ${native_h} ${native_cpu_h} ${native_quantized_h} ${cuda_h} ${native_cuda_h} ${native_hip_h} ${cudnn_h} ${hip_h} ${miopen_h})
|
|
+ list(APPEND INSTALL_HEADERS ${native_h} ${native_cpu_h} ${native_quantized_h} ${cuda_h} ${native_cuda_h} ${native_hip_h} ${cudnn_h} ${hip_h} ${miopen_h} ${npu_h})
|
|
else()
|
|
if(USE_PYTORCH_METAL)
|
|
if(IOS)
|
|
@@ -456,6 +464,7 @@
|
|
set(ATen_CORE_SRCS ${ATen_CORE_SRCS} PARENT_SCOPE)
|
|
set(ATen_CPU_SRCS ${ATen_CPU_SRCS} PARENT_SCOPE)
|
|
set(ATen_CUDA_SRCS ${ATen_CUDA_SRCS} PARENT_SCOPE)
|
|
+set(ATen_NPU_SRCS ${ATen_NPU_SRCS} PARENT_SCOPE)
|
|
set(ATen_CUDA_SRCS_W_SORT_BY_KEY ${ATen_CUDA_SRCS_W_SORT_BY_KEY} PARENT_SCOPE)
|
|
set(ATen_NVRTC_STUB_SRCS ${ATen_NVRTC_STUB_SRCS} PARENT_SCOPE)
|
|
set(ATen_HIP_SRCS ${ATen_HIP_SRCS} PARENT_SCOPE)
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/Utils.cpp patch/aten/src/ATen/Utils.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/Utils.cpp 2022-02-18 11:15:22.874936800 +0800
|
|
+++ patch/aten/src/ATen/Utils.cpp 2022-02-18 11:05:23.881831900 +0800
|
|
@@ -8,6 +8,8 @@
|
|
#include <stdexcept>
|
|
#include <typeinfo>
|
|
|
|
+#include <ATen/detail/NPUHooksInterface.h>
|
|
+
|
|
namespace at {
|
|
|
|
int _crash_if_asan(int arg) {
|
|
@@ -34,7 +36,11 @@
|
|
bool pin_memory = pinned_memory_or_default(pin_memory_opt);
|
|
c10::Allocator* allocator;
|
|
if (pin_memory) {
|
|
- allocator = detail::getCUDAHooks().getPinnedMemoryAllocator();
|
|
+ if (detail::getNPUHooks().getNumNPUs() > 0) {
|
|
+ allocator = detail::getNPUHooks().getPinnedMemoryAllocator();
|
|
+ } else {
|
|
+ allocator = detail::getCUDAHooks().getPinnedMemoryAllocator();
|
|
+ }
|
|
} else {
|
|
allocator = at::getCPUAllocator();
|
|
}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:22.874936800 +0800
|
|
+++ patch/aten/src/ATen/autocast_mode.h 2022-02-18 11:05:23.927794200 +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=build.sh' '--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-02-18 11:15:22.890562400 +0800
|
|
+++ patch/aten/src/ATen/core/VariableFallbackKernel.cpp 2022-02-18 11:05:24.118795000 +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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/core/dispatch/Dispatcher.h patch/aten/src/ATen/core/dispatch/Dispatcher.h
|
|
--- pytorch-v1.8.1/aten/src/ATen/core/dispatch/Dispatcher.h 2022-02-18 11:15:22.906446900 +0800
|
|
+++ patch/aten/src/ATen/core/dispatch/Dispatcher.h 2022-02-18 11:05:24.245823600 +0800
|
|
@@ -417,6 +417,11 @@
|
|
}
|
|
}
|
|
}
|
|
+ if (at::DisableRecordFunction::use_npu_simple && c10::ObservedOperators::EnableNpuOp &&
|
|
+ dispatchKey == DispatchKey::NPU) {
|
|
+ auto guard_npu = at::DisableRecordFunction();
|
|
+ return kernel.template call<Return, Args...>(op, std::forward<Args>(args)...);
|
|
+ }
|
|
// keeping the guard alive while executing the kernel
|
|
return kernel.template call<Return, Args...>(op, std::forward<Args>(args)...);
|
|
}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/core/dispatch/ObservedOperators.cpp patch/aten/src/ATen/core/dispatch/ObservedOperators.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/core/dispatch/ObservedOperators.cpp 2022-02-18 11:15:22.906446900 +0800
|
|
+++ patch/aten/src/ATen/core/dispatch/ObservedOperators.cpp 2022-02-18 11:05:24.249826000 +0800
|
|
@@ -6,6 +6,7 @@
|
|
namespace c10 {
|
|
|
|
/* static */
|
|
+std::atomic<bool> ObservedOperators::EnableNpuOp{true};
|
|
bool ObservedOperators::isObserved(const OperatorName& name) {
|
|
// names of the operators that should not be observed
|
|
std::unordered_set<std::string> not_observed_ops = {
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/core/dispatch/ObservedOperators.h patch/aten/src/ATen/core/dispatch/ObservedOperators.h
|
|
--- pytorch-v1.8.1/aten/src/ATen/core/dispatch/ObservedOperators.h 2022-02-18 11:15:22.907447600 +0800
|
|
+++ patch/aten/src/ATen/core/dispatch/ObservedOperators.h 2022-02-18 11:05:24.253826700 +0800
|
|
@@ -1,12 +1,16 @@
|
|
#pragma once
|
|
|
|
#include <ATen/core/operator_name.h>
|
|
+#include <atomic>
|
|
|
|
namespace c10 {
|
|
|
|
struct TORCH_API ObservedOperators {
|
|
ObservedOperators() = delete;
|
|
|
|
+ // when EnableNpuOp is false, it will disable the profiling of operator in NPU adapter.
|
|
+ // default set it true.
|
|
+ static std::atomic<bool> EnableNpuOp;
|
|
static bool isObserved(const OperatorName& name);
|
|
};
|
|
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/detail/NPUHooksInterface.cpp patch/aten/src/ATen/detail/NPUHooksInterface.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/detail/NPUHooksInterface.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/ATen/detail/NPUHooksInterface.cpp 2022-02-18 11:05:24.750793100 +0800
|
|
@@ -0,0 +1,31 @@
|
|
+#include <ATen/detail/NPUHooksInterface.h>
|
|
+
|
|
+#include <c10/util/Exception.h>
|
|
+
|
|
+#include <cstddef>
|
|
+#include <memory>
|
|
+#include <mutex>
|
|
+
|
|
+namespace at {
|
|
+namespace detail {
|
|
+
|
|
+static NPUHooksInterface* npu_hooks = nullptr;
|
|
+
|
|
+const NPUHooksInterface& getNPUHooks() {
|
|
+ static std::once_flag once;
|
|
+ std::call_once(once, [] {
|
|
+ npu_hooks = NPUHooksRegistry()->Create("NPUHooks", NPUHooksArgs{}).release();
|
|
+ if (!npu_hooks) {
|
|
+ npu_hooks = new(std::nothrow) NPUHooksInterface();
|
|
+ if (!npu_hooks) {
|
|
+ AT_ERROR("create NPUHooksInterface failed.");
|
|
+ }
|
|
+ }
|
|
+ });
|
|
+ return *npu_hooks;
|
|
+}
|
|
+} // namespace detail
|
|
+
|
|
+C10_DEFINE_REGISTRY(NPUHooksRegistry, NPUHooksInterface, NPUHooksArgs)
|
|
+
|
|
+} // namespace at
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/detail/NPUHooksInterface.h patch/aten/src/ATen/detail/NPUHooksInterface.h
|
|
--- pytorch-v1.8.1/aten/src/ATen/detail/NPUHooksInterface.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/ATen/detail/NPUHooksInterface.h 2022-02-18 11:05:24.754827900 +0800
|
|
@@ -0,0 +1,78 @@
|
|
+#pragma once
|
|
+
|
|
+#include <c10/core/Allocator.h>
|
|
+#include <ATen/core/Generator.h>
|
|
+#include <c10/util/Exception.h>
|
|
+#include <c10/util/Optional.h>
|
|
+#include <c10/util/Registry.h>
|
|
+
|
|
+#include <cstddef>
|
|
+#include <functional>
|
|
+#include <memory>
|
|
+
|
|
+// NB: Class must live in `at` due to limitations of Registry.h.
|
|
+namespace at {
|
|
+
|
|
+constexpr const char* NPU_HELP =
|
|
+ "This error has occurred because you are trying to use some NPU functionality, "
|
|
+ "but do not build library with options USE_NPU = 1";
|
|
+
|
|
+// The CUDAHooksInterface is an omnibus interface for any NPU functionality
|
|
+// which we may want to call into from CPU code (and thus must be dynamically
|
|
+// dispatched, to allow for separate compilation of NPU code). How do I
|
|
+// decide if a function should live in this class? There are two tests:
|
|
+//
|
|
+// 1. Does the *implementation* of this function require linking against
|
|
+// NPU libraries?
|
|
+//
|
|
+// 2. Is this function *called* from non-NPU ATen code?
|
|
+//
|
|
+// (2) should filter out many ostensible use-cases, since many times a NPU
|
|
+// function provided by ATen is only really ever used by actual NPU code.
|
|
+//
|
|
+// TODO: Consider putting the stub definitions in another class, so that one
|
|
+// never forgets to implement each virtual function in the real implementation
|
|
+// in NPUHooks. This probably doesn't buy us much though.
|
|
+struct TORCH_API NPUHooksInterface {
|
|
+ // This should never actually be implemented, but it is used to
|
|
+ // squelch -Werror=non-virtual-dtor
|
|
+ virtual ~NPUHooksInterface() {}
|
|
+
|
|
+ // Initialize THCState and, transitively, the CUDA state
|
|
+ virtual void initNPU() const {
|
|
+ TORCH_CHECK(false, "Cannot initialize NPU without building library with options USE_NPU = 1.", NPU_HELP);
|
|
+ }
|
|
+
|
|
+ virtual const Generator& getDefaultNPUGenerator(DeviceIndex device_index = -1) const {
|
|
+ TORCH_CHECK(false, "Cannot get default NPU generator without ATen_cuda library. ", NPU_HELP);
|
|
+ }
|
|
+
|
|
+ virtual bool hasNPU() const {
|
|
+ return false;
|
|
+ }
|
|
+
|
|
+ virtual int64_t current_device() const {
|
|
+ return -1;
|
|
+ }
|
|
+
|
|
+ virtual Allocator* getPinnedMemoryAllocator() const {
|
|
+ TORCH_CHECK(false, "Pinned memory requires NPU. ", NPU_HELP);
|
|
+ }
|
|
+
|
|
+ virtual int getNumNPUs() const {
|
|
+ return 0;
|
|
+ }
|
|
+};
|
|
+
|
|
+// NB: dummy argument to suppress "ISO C++11 requires at least one argument
|
|
+// for the "..." in a variadic macro"
|
|
+struct TORCH_API NPUHooksArgs {};
|
|
+
|
|
+C10_DECLARE_REGISTRY(NPUHooksRegistry, NPUHooksInterface, NPUHooksArgs);
|
|
+#define REGISTER_NPU_HOOKS(clsname) \
|
|
+C10_REGISTER_CLASS(NPUHooksRegistry, clsname, clsname)
|
|
+
|
|
+namespace detail {
|
|
+ TORCH_API const NPUHooksInterface& getNPUHooks();
|
|
+} // namespace detail
|
|
+} // namespace at
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/native/Memory.cpp patch/aten/src/ATen/native/Memory.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/native/Memory.cpp 2022-02-18 11:15:22.988381600 +0800
|
|
+++ patch/aten/src/ATen/native/Memory.cpp 2022-02-18 11:05:25.161823600 +0800
|
|
@@ -6,6 +6,8 @@
|
|
#include <c10/util/Exception.h>
|
|
#include <c10/core/Storage.h>
|
|
|
|
+#include <ATen/detail/NPUHooksInterface.h>
|
|
+
|
|
namespace at {
|
|
namespace native {
|
|
|
|
@@ -20,7 +22,17 @@
|
|
if (self.is_pinned()) {
|
|
return self;
|
|
}
|
|
- auto* allocator = detail::getCUDAHooks().getPinnedMemoryAllocator();
|
|
+
|
|
+ at::Allocator* allocator = nullptr;
|
|
+ if (detail::getNPUHooks().getNumNPUs() > 0) {
|
|
+ allocator = detail::getNPUHooks().getPinnedMemoryAllocator();
|
|
+ } else {
|
|
+ allocator = detail::getCUDAHooks().getPinnedMemoryAllocator();
|
|
+ }
|
|
+
|
|
+ if(allocator == nullptr) {
|
|
+ return self;
|
|
+ }
|
|
auto storage = Storage(
|
|
Storage::use_byte_size_t(),
|
|
detail::computeStorageNbytes(
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/native/TensorFactories.cpp patch/aten/src/ATen/native/TensorFactories.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/native/TensorFactories.cpp 2022-02-18 11:15:23.004005700 +0800
|
|
+++ patch/aten/src/ATen/native/TensorFactories.cpp 2022-02-18 11:05:25.375825100 +0800
|
|
@@ -21,6 +21,8 @@
|
|
#include <cstddef>
|
|
#include <string>
|
|
|
|
+#include <ATen/detail/NPUHooksInterface.h>
|
|
+
|
|
namespace at {
|
|
namespace native {
|
|
namespace {
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/npu/Exceptions.h patch/aten/src/ATen/npu/Exceptions.h
|
|
--- pytorch-v1.8.1/aten/src/ATen/npu/Exceptions.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/ATen/npu/Exceptions.h 2022-02-18 11:05:28.827807500 +0800
|
|
@@ -0,0 +1,3 @@
|
|
+#include <c10/util/Exception.h>
|
|
+
|
|
+#define AT_NPU_CHECK(EXPR) C10_NPU_CHECK(EXPR)
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/npu/NPUGeneratorImpl.cpp patch/aten/src/ATen/npu/NPUGeneratorImpl.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/npu/NPUGeneratorImpl.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/ATen/npu/NPUGeneratorImpl.cpp 2022-02-18 11:05:28.830825900 +0800
|
|
@@ -0,0 +1,336 @@
|
|
+#include <ATen/Utils.h>
|
|
+#include <ATen/npu/NPUGeneratorImpl.h>
|
|
+#include <c10/core/StreamGuard.h>
|
|
+#include <c10/npu/NPUFunctions.h>
|
|
+#include <ATen/Utils.h>
|
|
+
|
|
+namespace at {
|
|
+namespace npu {
|
|
+namespace detail {
|
|
+
|
|
+namespace {
|
|
+
|
|
+// Ensures we only call npuGetDeviceCount only once.
|
|
+static std::once_flag num_npu_init_flag;
|
|
+
|
|
+// Total number of npus in the system.
|
|
+static int64_t num_npus;
|
|
+
|
|
+// Ensures default_gens_npu is initialized once.
|
|
+static std::deque<std::once_flag> npu_gens_init_flag;
|
|
+
|
|
+// Default, global NPU generators, one per NPU.
|
|
+static std::vector<Generator> default_gens_npu;
|
|
+
|
|
+/*
|
|
+* Populates the global variables related to NPU generators
|
|
+* Warning: this function must only be called once!
|
|
+*/
|
|
+static void initNPUGenVector(){
|
|
+ num_npus = c10::npu::device_count();
|
|
+ npu_gens_init_flag.resize(num_npus);
|
|
+ default_gens_npu.resize(num_npus);
|
|
+}
|
|
+
|
|
+} // anonymous namespace
|
|
+
|
|
+/**
|
|
+ * PyTorch maintains a collection of default generators that get
|
|
+ * initialized once. The purpose of these default generators is to
|
|
+ * maintain a global running state of the pseudo random number generation,
|
|
+ * when a user does not explicitly mention any generator.
|
|
+ * getDefaultNPUGenerator gets the default generator for a particular
|
|
+ * NPU device.
|
|
+ */
|
|
+const Generator& getDefaultNPUGenerator(DeviceIndex device_index) {
|
|
+ std::call_once(num_npu_init_flag, initNPUGenVector);
|
|
+ DeviceIndex idx = device_index;
|
|
+ if (idx == -1) {
|
|
+ idx = c10::npu::current_device();
|
|
+ } else {
|
|
+ TORCH_CHECK(idx >= 0 && idx < num_npus);
|
|
+ }
|
|
+ std::call_once(npu_gens_init_flag[idx], [&] {
|
|
+ default_gens_npu[idx] = make_generator<NPUGeneratorImpl>(idx);
|
|
+ default_gens_npu[idx].seed();
|
|
+ });
|
|
+ return default_gens_npu[idx];
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Utility to create a NPUGeneratorImpl. Returns a shared_ptr
|
|
+ */
|
|
+Generator createNPUGenerator(DeviceIndex device_index) {
|
|
+ std::call_once(num_npu_init_flag, initNPUGenVector);
|
|
+ DeviceIndex idx = device_index;
|
|
+ if (idx == -1) {
|
|
+ idx = c10::npu::current_device();
|
|
+ }
|
|
+ TORCH_CHECK(idx >= 0 && idx < num_npus, "The device_index is invalid.");
|
|
+ auto gen = make_generator<NPUGeneratorImpl>(idx);
|
|
+ auto npu_gen = check_generator<NPUGeneratorImpl>(gen);
|
|
+ npu_gen->set_current_seed(default_rng_seed_val);
|
|
+ npu_gen->set_philox_offset_per_thread(0);
|
|
+ return gen;
|
|
+}
|
|
+
|
|
+} // namespace detail
|
|
+} // namespace npu
|
|
+
|
|
+/**
|
|
+ * Note [Why enforce RNG offset % 4 == 0?]
|
|
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
+ * Curand philox does allow offsets that aren't a multiple of 4.
|
|
+ * But jit kernels don't use curand, they use a custom "Philox" class (see
|
|
+ * torch/csrc/jit/tensorexpr/npu_random.h or
|
|
+ * torch/csrc/jit/codegen/npu/runtime/random_numbers.cu).
|
|
+ * The "Philox" constructor computes offset/4 (a uint64_t division) to locate its
|
|
+ * internal start in its virtual bitstream viewed as 128-bit chunks, then, when called
|
|
+ * in a thread, returns one 32-bit chunk at a time from that start in the bitstream.
|
|
+ * In other words, if the incoming offset is not a multiple of 4, each thread
|
|
+ * might repeat some previously-generated 32-bit values in the bitstream. See
|
|
+ * https://github.com/pytorch/pytorch/pull/50169.
|
|
+ */
|
|
+
|
|
+/**
|
|
+ * NPUGeneratorImpl class implementation
|
|
+ */
|
|
+NPUGeneratorImpl::NPUGeneratorImpl(DeviceIndex device_index)
|
|
+ : c10::GeneratorImpl{Device(DeviceType::NPU, device_index),
|
|
+ DispatchKeySet(c10::DispatchKey::NPU)} {
|
|
+ //at::npu::assertNotCapturing("Cannot construct a new NPUGeneratorImpl");
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Sets the seed to be used by curandStatePhilox4_32_10
|
|
+ * Resets the philox_offset_per_thread_ to 0
|
|
+ *
|
|
+ * See Note [Acquire lock when using random generators]
|
|
+ */
|
|
+void NPUGeneratorImpl::set_current_seed(uint64_t seed) {
|
|
+ seed_ = seed;
|
|
+ philox_offset_per_thread_ = 0;
|
|
+}
|
|
+
|
|
+#define CAPTURE_DEFAULT_GENS_MSG \
|
|
+"In regions captured by NPU graphs, you may only use the default NPU RNG " \
|
|
+"generator on the device that's current when capture begins. " \
|
|
+"If you need a non-default (user-supplied) generator, or a generator on another " \
|
|
+"device, please file an issue."
|
|
+
|
|
+/**
|
|
+ * Gets the current seed of NPUGeneratorImpl.
|
|
+ */
|
|
+uint64_t NPUGeneratorImpl::current_seed() const {
|
|
+ // Debatable if current_seed() should be allowed in captured regions.
|
|
+ // Conservatively disallow it for now.
|
|
+ return seed_;
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Gets a nondeterministic random number from /dev/urandom or time,
|
|
+ * seeds the CPUGeneratorImpl with it and then returns that number.
|
|
+ *
|
|
+ * FIXME: You can move this function to Generator.cpp if the algorithm
|
|
+ * in getNonDeterministicRandom is unified for both CPU and NPU
|
|
+ */
|
|
+uint64_t NPUGeneratorImpl::seed() {
|
|
+ auto random = c10::detail::getNonDeterministicRandom(true);
|
|
+ this->set_current_seed(random);
|
|
+ return random;
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Gets the current internal state of NpuGeneratorImpl. The internal
|
|
+ * state is returned as a CPU byte tensor.
|
|
+ */
|
|
+c10::intrusive_ptr<c10::TensorImpl> NPUGeneratorImpl::get_state() const {
|
|
+ // The RNG state comprises the seed, and an offset used for Philox.
|
|
+ // The following line is just here for BC reason. sizeof curandStateMtgp32 is 4120.
|
|
+ // It used to be static const size_t states_size = MAX_NUM_BLOCKS * sizeof(curandStateMtgp32);
|
|
+ // MAX_NUM_BLOCKS was 200 and sizeof(curandStateMtgp32) is 4120. Hardcoding these numbers here
|
|
+ // because this is just host side code and we don't want to worry about linking with npu
|
|
+ static const size_t states_size = 200 * sizeof(4120);
|
|
+ static const size_t seed_size = sizeof(uint64_t);
|
|
+ static const size_t offset_size = sizeof(int64_t);
|
|
+ static const size_t total_size = states_size + seed_size + offset_size;
|
|
+
|
|
+ auto state_tensor = at::detail::empty_cpu({(int64_t)total_size}, ScalarType::Byte, c10::nullopt, c10::nullopt, c10::nullopt, c10::nullopt);
|
|
+ auto rng_state = state_tensor.data_ptr<uint8_t>();
|
|
+ // since curandStateMTGP is not used anymore, fill gen_states of THCGenerator with deterministic garbage value of -1
|
|
+ // gen_states in THCGenerator struct was an array of curandStateMtgp32s.
|
|
+ memset(rng_state, -1, states_size);
|
|
+ auto current_seed = this->current_seed();
|
|
+ auto offset = static_cast<int64_t>(this->philox_offset_per_thread()); // Note that old THCGeneratorState had offset as std::atomic<int64_t>
|
|
+ memcpy(rng_state + states_size, ¤t_seed, seed_size);
|
|
+ memcpy(rng_state + states_size + seed_size, &offset, offset_size);
|
|
+
|
|
+ return state_tensor.getIntrusivePtr();
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Sets the internal state of NPUGeneratorImpl. The new internal state
|
|
+ * must be a strided CPU byte tensor and have appropriate size. See
|
|
+ * comments of NPUGeneratorImpl::state for information about the layout
|
|
+ * and size of the internal state.
|
|
+ */
|
|
+void NPUGeneratorImpl::set_state(const c10::TensorImpl& new_state) {
|
|
+ static const size_t states_size = 200 * sizeof(4120); // this line is just here for BC reason
|
|
+ static const size_t seed_size = sizeof(uint64_t);
|
|
+ static const size_t offset_size = sizeof(int64_t);
|
|
+ static const size_t total_size = states_size + seed_size + offset_size;
|
|
+
|
|
+ detail::check_rng_state(new_state);
|
|
+
|
|
+ bool no_philox_seed = false;
|
|
+ auto new_state_size = new_state.numel();
|
|
+ if (new_state_size == total_size - offset_size) {
|
|
+ no_philox_seed = true;
|
|
+ } else {
|
|
+ TORCH_CHECK(new_state_size == total_size, "RNG state is wrong size");
|
|
+ }
|
|
+
|
|
+ uint64_t input_seed;
|
|
+ auto new_rng_state = new_state.data<uint8_t>();
|
|
+ memcpy(&input_seed, new_rng_state + states_size, seed_size);
|
|
+ this->set_current_seed(input_seed);
|
|
+ int64_t philox_offset = 0;
|
|
+ if (!no_philox_seed) {
|
|
+ memcpy(&philox_offset, new_rng_state + states_size + seed_size, offset_size);
|
|
+ }
|
|
+ this->set_philox_offset_per_thread(static_cast<uint64_t>(philox_offset));
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Sets the philox_offset_per_thread_ to be used by curandStatePhilox4_32_10
|
|
+ *
|
|
+ * See Note [Acquire lock when using random generators]
|
|
+ */
|
|
+void NPUGeneratorImpl::set_philox_offset_per_thread(uint64_t offset) {
|
|
+ // see Note [Why enforce RNG offset % 4 == 0?]
|
|
+ TORCH_CHECK(offset % 4 == 0, "offset must be a multiple of 4");
|
|
+ philox_offset_per_thread_ = offset;
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Gets the current philox_offset_per_thread_ of NpuGeneratorImpl.
|
|
+ */
|
|
+uint64_t NPUGeneratorImpl::philox_offset_per_thread() const {
|
|
+ return philox_offset_per_thread_;
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Called by NpuGraph to prepare this instance for a graph capture region.
|
|
+ * offset_extragraph is the initial offset at the start of the graphed region.
|
|
+ * offset_intragraph tracks the offset in the graphed region.
|
|
+ */
|
|
+void NPUGeneratorImpl::capture_prologue(int64_t* offset_extragraph) {
|
|
+ offset_extragraph_ = offset_extragraph;
|
|
+ offset_intragraph_ = 0;
|
|
+ graph_expects_this_gen_ = true;
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Called by NpuGraph to finalize a graph capture region for this instance.
|
|
+ */
|
|
+uint64_t NPUGeneratorImpl::capture_epilogue() {
|
|
+ graph_expects_this_gen_ = false;
|
|
+ return offset_intragraph_;
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Gets the seed and philox offset value to be used in
|
|
+ * curandStatePhilox4_32_10, in an opaque PhiloxNpuState that's safe
|
|
+ * and can be used non-divergently in callers whether NPU graph
|
|
+ * capture is underway or not. See
|
|
+ * Note [NPU Graph-safe RNG states]
|
|
+ *
|
|
+ * Each kernel using philox has to sensibly increment offset
|
|
+ * for future users of philox. So it gets the "old" value for
|
|
+ * itself (before add), and tells subsequent users which offset
|
|
+ * they should use, since only the kernel knows how many randoms
|
|
+ * it intends to generate.
|
|
+ *
|
|
+ * Increment should be at least the number of curand() random numbers used in
|
|
+ * each thread. It is the user's responsibility to make sure the increment
|
|
+ * for philox is never smaller than the number of curand() calls. Increment
|
|
+ * value > the number of curand() calls won't harm but anything less would mean
|
|
+ * that you would be reusing random values from previous calls.
|
|
+ *
|
|
+ * See Note [Acquire lock when using random generators]
|
|
+ */
|
|
+PhiloxNpuState NPUGeneratorImpl::philox_npu_state(uint64_t increment) {
|
|
+ // rounds increment up to the nearest multiple of 4
|
|
+ increment = ((increment + 3) / 4) * 4;
|
|
+ /*
|
|
+ if (at::npu::currentStreamCaptureStatus() != at::npu::CaptureStatus::None) {
|
|
+ TORCH_CHECK(graph_expects_this_gen_,
|
|
+ "philox_npu_state for an unexpected NPU generator used during capture. "
|
|
+ CAPTURE_DEFAULT_GENS_MSG);
|
|
+ // see Note [Why enforce RNG offset % 4 == 0?]
|
|
+ TORCH_INTERNAL_ASSERT(this->offset_intragraph_ % 4 == 0);
|
|
+ uint32_t offset = this->offset_intragraph_;
|
|
+ TORCH_INTERNAL_ASSERT(this->offset_intragraph_ <=
|
|
+ std::numeric_limits<uint32_t>::max() - increment);
|
|
+ this->offset_intragraph_ += increment;
|
|
+ return PhiloxNpuState(this->seed_,
|
|
+ this->offset_extragraph_,
|
|
+ offset);
|
|
+ } else {
|
|
+ TORCH_CHECK(!graph_expects_this_gen_,
|
|
+ "NPU generator expects graph capture to be underway, "
|
|
+ "but the current stream is not capturing.");
|
|
+ // see Note [Why enforce RNG offset % 4 == 0?]
|
|
+ TORCH_INTERNAL_ASSERT(this->philox_offset_per_thread_ % 4 == 0);
|
|
+ uint64_t offset = this->philox_offset_per_thread_;
|
|
+ this->philox_offset_per_thread_ += increment;
|
|
+ return PhiloxNpuState(this->seed_, offset);
|
|
+ }*/
|
|
+
|
|
+ return PhiloxNpuState(this->seed_, 0);
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Temporarily accommodates call sites that use philox_engine_inputs.
|
|
+ * Allows incremental refactor of call sites to use philox_npu_state.
|
|
+ */
|
|
+std::pair<uint64_t, uint64_t> NPUGeneratorImpl::philox_engine_inputs(uint64_t increment) {
|
|
+ // rounds increment up to the nearest multiple of 4
|
|
+ increment = ((increment + 3) / 4) * 4;
|
|
+ // see Note [Why enforce RNG offset % 4 == 0?]
|
|
+ TORCH_INTERNAL_ASSERT(this->philox_offset_per_thread_ % 4 == 0);
|
|
+ uint64_t offset = this->philox_offset_per_thread_;
|
|
+ this->philox_offset_per_thread_ += increment;
|
|
+ return std::make_pair(this->seed_, offset);
|
|
+}
|
|
+
|
|
+/*
|
|
+ * Gets the DeviceType of NPUGeneratorImpl.
|
|
+ * Used for type checking during run time.
|
|
+ */
|
|
+DeviceType NPUGeneratorImpl::device_type() {
|
|
+ return DeviceType::NPU;
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Public clone method implementation
|
|
+ *
|
|
+ * See Note [Acquire lock when using random generators]
|
|
+ */
|
|
+std::shared_ptr<NPUGeneratorImpl> NPUGeneratorImpl::clone() const {
|
|
+ return std::shared_ptr<NPUGeneratorImpl>(this->clone_impl());
|
|
+}
|
|
+
|
|
+/**
|
|
+ * Private clone method implementation
|
|
+ *
|
|
+ * See Note [Acquire lock when using random generators]
|
|
+ */
|
|
+NPUGeneratorImpl* NPUGeneratorImpl::clone_impl() const {
|
|
+ auto gen = new NPUGeneratorImpl(this->device().index());
|
|
+ gen->set_current_seed(this->seed_);
|
|
+ gen->set_philox_offset_per_thread(this->philox_offset_per_thread_);
|
|
+ return gen;
|
|
+}
|
|
+
|
|
+} // namespace at
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/npu/NPUGeneratorImpl.h patch/aten/src/ATen/npu/NPUGeneratorImpl.h
|
|
--- pytorch-v1.8.1/aten/src/ATen/npu/NPUGeneratorImpl.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/ATen/npu/NPUGeneratorImpl.h 2022-02-18 11:05:28.834825300 +0800
|
|
@@ -0,0 +1,162 @@
|
|
+#pragma once
|
|
+
|
|
+#include <c10/core/GeneratorImpl.h>
|
|
+#include <ATen/core/Generator.h>
|
|
+#include <ATen/Tensor.h>
|
|
+#include <ATen/Context.h>
|
|
+#include <limits>
|
|
+
|
|
+// TODO: this file should be in ATen/npu, not top level
|
|
+
|
|
+namespace at {
|
|
+/**
|
|
+ * Note [NPU Graph-safe RNG states]
|
|
+ * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
+ *
|
|
+ * Strategy:
|
|
+ * ~~~~~~~~~
|
|
+ * A NPU graph containing multiple RNG ops behaves like a
|
|
+ * single giant kernel from the perspective of ops external
|
|
+ * to the graph. During graph capture, logic below records
|
|
+ * the total of all offset increments that occur in the graphed
|
|
+ * region, and records the final total as the offset for the
|
|
+ * entire graph.
|
|
+ *
|
|
+ * When the graph reruns, the logic that reruns it
|
|
+ * increments this device's NPU generator's offset
|
|
+ * by that total.
|
|
+ *
|
|
+ * Meanwhile, within the graph, at capture time, instead of
|
|
+ * populating PhiloxNpuStates with the uint64_t offset pulled
|
|
+ * directly from the global state, PhiloNpuState instead
|
|
+ * holds a pointer to one-element stream-local int64_t device tensor
|
|
+ * holding an initial offset value, and a uint64_t holding an
|
|
+ * intra-graph offset. (The intra-graph offset starts from zero
|
|
+ * when capture begins.) In each consumer kernel,
|
|
+ * at::npu::philox::unpack computes the offset to use for this kernel
|
|
+ * as intra-graph offset + *initial offset.
|
|
+ *
|
|
+ * When the graph reruns, the logic that reruns it first
|
|
+ * fill_s the initial offset tensor with this device's
|
|
+ * NPU generator's current offset.
|
|
+ *
|
|
+ * The control flow above ensures graphed execution is bitwise
|
|
+ * identical to eager execution as long as RNG ops are enqueued
|
|
+ * from a single thread, even if RNG ops and graphs containing
|
|
+ * RNG ops are enqueued and run simultaneously on multiple streams.
|
|
+ *
|
|
+ * Usage:
|
|
+ * ~~~~~~
|
|
+ * PhiloxNPUState in this file, and unpack() in
|
|
+ * npu/NPUGraphsUtils.cuh allow non-divergent use of
|
|
+ * NPUGeneratorImpl whether graph capture is underway or not.
|
|
+ *
|
|
+ * Each PhiloxNpuState instance should be used for one and only one
|
|
+ * consumer kernel.
|
|
+ *
|
|
+ * Example (see e.g. native/npu/Dropout.cu):
|
|
+ *
|
|
+ * #include <ATen/NPUGeneratorImpl.h>
|
|
+ * #include <ATen/npu/NPUGraphsUtils.cuh>
|
|
+ *
|
|
+ * __global__ void kernel(..., PhiloxnpuState philox_args) {
|
|
+ * auto seeds = at::npu::philox::unpack(philox_args);
|
|
+ * IndexType idx = blockIdx.x * blockDim.x + threadIdx.x;
|
|
+ * curandStatePhilox4_32_10_t state;
|
|
+ * curand_init(std::get<0>(seeds), // seed
|
|
+ * idx, // per-thread subsequence
|
|
+ * std::get<1>(seeds), // offset in subsequence
|
|
+ * &state);
|
|
+ * ...
|
|
+ * }
|
|
+ *
|
|
+ * host_caller(...) {
|
|
+ * PhiloxnpuState rng_engine_inputs;
|
|
+ * {
|
|
+ * // See Note [Acquire lock when using random generators]
|
|
+ * std::lock_guard<std::mutex> lock(gen->mutex_);
|
|
+ *
|
|
+ * // gen could be HostState or DevState here! No divergent code needed!
|
|
+ * rng_engine_inputs = gen->philox_npu_state(offset_increment);
|
|
+ * }
|
|
+ * kernel<<<...>>>(..., rng_engine_inputs);
|
|
+ * }
|
|
+ *
|
|
+ */
|
|
+
|
|
+
|
|
+// Stores state values. Passed as a kernel argument. See "Usage:" above.
|
|
+struct PhiloxNpuState {
|
|
+ PhiloxNpuState() = default;
|
|
+ PhiloxNpuState(const PhiloxNpuState&) = default;
|
|
+ // Called if graph capture is not underway
|
|
+ PhiloxNpuState(uint64_t seed,
|
|
+ uint64_t offset) {
|
|
+ seed_ = seed;
|
|
+ offset_.val = offset;
|
|
+ }
|
|
+ // Called if graph capture is underway
|
|
+ PhiloxNpuState(uint64_t seed,
|
|
+ int64_t* offset_extragraph,
|
|
+ uint32_t offset_intragraph) {
|
|
+ seed_ = seed;
|
|
+ offset_.ptr = offset_extragraph;
|
|
+ offset_intragraph_ = offset_intragraph;
|
|
+ captured_ = true;
|
|
+ }
|
|
+
|
|
+ // Public members, directly accessible by at::Npu::philox::unpack.
|
|
+ // If we made them private with getters/setters, the getters/setters
|
|
+ // would have to be __device__, and we can't declare __device__ in ATen.
|
|
+ union Payload {
|
|
+ uint64_t val;
|
|
+ int64_t* ptr;
|
|
+ };
|
|
+
|
|
+ uint64_t seed_;
|
|
+ Payload offset_;
|
|
+ uint32_t offset_intragraph_;
|
|
+ bool captured_ = false;
|
|
+};
|
|
+
|
|
+struct C10_EXPORT NPUGeneratorImpl : public c10::GeneratorImpl {
|
|
+ // Constructors
|
|
+ NPUGeneratorImpl(DeviceIndex device_index = -1);
|
|
+ ~NPUGeneratorImpl() = default;
|
|
+
|
|
+ // NPUGeneratorImpl methods
|
|
+ std::shared_ptr<NPUGeneratorImpl> clone() const;
|
|
+ void set_current_seed(uint64_t seed) override;
|
|
+ uint64_t current_seed() const override;
|
|
+ uint64_t seed() override;
|
|
+ void set_state(const c10::TensorImpl& new_state) override;
|
|
+ c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
|
|
+ void set_philox_offset_per_thread(uint64_t offset);
|
|
+ uint64_t philox_offset_per_thread() const;
|
|
+ void capture_prologue(int64_t* offset_extragraph);
|
|
+ uint64_t capture_epilogue();
|
|
+ PhiloxNpuState philox_npu_state(uint64_t increment);
|
|
+
|
|
+ // Temporarily accommodates call sites that use philox_engine_inputs.
|
|
+ // Allows incremental refactor of call sites to use philox_npu_state.
|
|
+ std::pair<uint64_t, uint64_t> philox_engine_inputs(uint64_t increment);
|
|
+ static DeviceType device_type();
|
|
+
|
|
+private:
|
|
+ NPUGeneratorImpl* clone_impl() const override;
|
|
+ uint64_t seed_ = default_rng_seed_val;
|
|
+ uint64_t philox_offset_per_thread_ = 0;
|
|
+ int64_t* offset_extragraph_;
|
|
+ uint32_t offset_intragraph_ = 0;
|
|
+ bool graph_expects_this_gen_ = false;
|
|
+};
|
|
+
|
|
+namespace npu {
|
|
+namespace detail {
|
|
+C10_EXPORT const Generator& getDefaultNPUGenerator(
|
|
+ DeviceIndex device_index = -1);
|
|
+C10_EXPORT Generator createNPUGenerator(DeviceIndex device_index = -1);
|
|
+
|
|
+} // namespace detail
|
|
+} // namespace npu
|
|
+} // namespace at
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/npu/detail/NPUHooks.cpp patch/aten/src/ATen/npu/detail/NPUHooks.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/npu/detail/NPUHooks.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/ATen/npu/detail/NPUHooks.cpp 2022-02-18 11:05:28.838823800 +0800
|
|
@@ -0,0 +1,64 @@
|
|
+#include <ATen/npu/detail/NPUHooks.h>
|
|
+
|
|
+#include <ATen/Context.h>
|
|
+#include <ATen/DeviceGuard.h>
|
|
+#include <ATen/DynamicLibrary.h>
|
|
+#include <ATen/npu/NPUGeneratorImpl.h>
|
|
+
|
|
+#include <ATen/detail/NPUHooksInterface.h>
|
|
+#include <c10/npu/NPUException.h>
|
|
+#include <c10/npu/NPUFunctions.h>
|
|
+#include <c10/npu/sys_ctrl/npu_sys_ctrl.h>
|
|
+#include <c10/util/Exception.h>
|
|
+
|
|
+namespace at {
|
|
+namespace npu {
|
|
+namespace detail {
|
|
+
|
|
+// NB: deleter is dynamic, because we need it to live in a separate
|
|
+// compilation unit (alt is to have another method in hooks, but
|
|
+// let's not if we don't need to!)
|
|
+void NPUHooks::initNPU() const {
|
|
+ C10_LOG_API_USAGE_ONCE("aten.init.npu");
|
|
+ c10::npu::NpuSysCtrl::SysStatus status =
|
|
+ c10::npu::NpuSysCtrl::GetInstance().Initialize();
|
|
+ if (status != c10::npu::NpuSysCtrl::SysStatus::INIT_SUCC) {
|
|
+ NPU_LOGE("Npu init fail.");
|
|
+ }
|
|
+}
|
|
+
|
|
+const Generator& NPUHooks::getDefaultNPUGenerator(DeviceIndex device_index) const {
|
|
+ return at::npu::detail::getDefaultNPUGenerator(device_index);
|
|
+}
|
|
+
|
|
+bool NPUHooks::hasNPU() const {
|
|
+ return c10::npu::device_count() > 0;
|
|
+}
|
|
+
|
|
+int64_t NPUHooks::current_device() const {
|
|
+ int device = 0;
|
|
+ aclError err = aclrtGetDevice(&device);
|
|
+ if (err == ACL_ERROR_NONE) {
|
|
+ return device;
|
|
+ }
|
|
+ return -1;
|
|
+}
|
|
+
|
|
+Allocator* NPUHooks::getPinnedMemoryAllocator() const {
|
|
+ initNPU();
|
|
+ return getTHNPUCachingHostAllocator();
|
|
+}
|
|
+
|
|
+int NPUHooks::getNumNPUs() const {
|
|
+ return c10::npu::device_count();
|
|
+}
|
|
+
|
|
+// Sigh, the registry doesn't support namespaces :(
|
|
+using at::NPUHooksRegistry;
|
|
+using at::RegistererNPUHooksRegistry;
|
|
+
|
|
+REGISTER_NPU_HOOKS(NPUHooks);
|
|
+
|
|
+} // namespace detail
|
|
+} // namespace npu
|
|
+} // namespace at
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/npu/detail/NPUHooks.h patch/aten/src/ATen/npu/detail/NPUHooks.h
|
|
--- pytorch-v1.8.1/aten/src/ATen/npu/detail/NPUHooks.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/ATen/npu/detail/NPUHooks.h 2022-02-18 11:05:28.842825700 +0800
|
|
@@ -0,0 +1,24 @@
|
|
+
|
|
+#include <ATen/detail/NPUHooksInterface.h>
|
|
+
|
|
+#include <ATen/Generator.h>
|
|
+#include <THNPU/THNPUCachingHostAllocator.h>
|
|
+#include <c10/util/Optional.h>
|
|
+
|
|
+// TODO: No need to have this whole header, we can just put it all in
|
|
+// the cpp file
|
|
+
|
|
+namespace at { namespace npu { namespace detail {
|
|
+
|
|
+// The real implementation of NPUHooksInterface
|
|
+struct NPUHooks : public at::NPUHooksInterface {
|
|
+ NPUHooks(at::NPUHooksArgs) {}
|
|
+ void initNPU() const override;
|
|
+ const Generator& getDefaultNPUGenerator(DeviceIndex device_index = -1) const override;
|
|
+ bool hasNPU() const override;
|
|
+ int64_t current_device() const override;
|
|
+ Allocator* getPinnedMemoryAllocator() const override;
|
|
+ int getNumNPUs() const override;
|
|
+};
|
|
+
|
|
+}}} // at::npu::detail
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/record_function.cpp patch/aten/src/ATen/record_function.cpp
|
|
--- pytorch-v1.8.1/aten/src/ATen/record_function.cpp 2022-02-18 11:15:23.300880700 +0800
|
|
+++ patch/aten/src/ATen/record_function.cpp 2022-02-18 11:05:28.863826400 +0800
|
|
@@ -400,6 +400,9 @@
|
|
rf_tls_.tls_record_function_enabled_ = enable;
|
|
}
|
|
|
|
+/* static */
|
|
+std::atomic<bool> DisableRecordFunction::use_npu_simple{false};
|
|
+
|
|
RecordFunction::RecordFunction(RecordScope scope, bool pre_sampled) {
|
|
auto* rf_tls_ptr = &rf_tls_;
|
|
if (rf_tls_ptr->tls_record_function_enabled_) {
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/ATen/record_function.h patch/aten/src/ATen/record_function.h
|
|
--- pytorch-v1.8.1/aten/src/ATen/record_function.h 2022-02-18 11:15:23.300880700 +0800
|
|
+++ patch/aten/src/ATen/record_function.h 2022-02-18 11:05:28.868824100 +0800
|
|
@@ -2,6 +2,7 @@
|
|
|
|
#include <ATen/core/ivalue.h>
|
|
#include <ATen/core/operator_name.h>
|
|
+#include <ATen/core/dispatch/ObservedOperators.h>
|
|
#include <c10/macros/Export.h>
|
|
#include <c10/util/Optional.h>
|
|
#include <c10/util/SmallVector.h>
|
|
@@ -89,6 +90,24 @@
|
|
typedef std::vector<std::unique_ptr<ObserverContext>> ObserverContextList;
|
|
typedef uint64_t RecordFunctionHandle;
|
|
|
|
+struct TORCH_API DisableRecordFunction {
|
|
+ // use_npu_simple indicates whether to use simple mode,
|
|
+ // when set true, it will disable the profiling of some operator.
|
|
+ static std::atomic<bool> use_npu_simple;
|
|
+ // Constructor calls before callbacks
|
|
+ DisableRecordFunction() { before(); }
|
|
+ // Destructor calls end callbacks
|
|
+ ~DisableRecordFunction() { end(); }
|
|
+
|
|
+ inline void before() {
|
|
+ c10::ObservedOperators::EnableNpuOp = false;
|
|
+ }
|
|
+
|
|
+ inline void end() {
|
|
+ c10::ObservedOperators::EnableNpuOp = true;
|
|
+ }
|
|
+};
|
|
+
|
|
struct TORCH_API RecordFunction {
|
|
// Default constructor is used with before function called afterwards:
|
|
// scope - record scope that this function tracks
|
|
@@ -280,6 +299,10 @@
|
|
};
|
|
|
|
std::unique_ptr<State> state_;
|
|
+ public:
|
|
+ uint16_t local_threadId_ = 0;
|
|
+ void* local_stamp_ = nullptr;
|
|
+ uint32_t local_rangeId_ = -1;
|
|
};
|
|
|
|
//
|
|
@@ -305,8 +328,8 @@
|
|
*/
|
|
class TORCH_API RecordFunctionCallback {
|
|
public:
|
|
- using StartCallback = std::unique_ptr<ObserverContext>(*)(const RecordFunction&);
|
|
- using EndCallback = void (*)(const RecordFunction&, ObserverContext*);
|
|
+ using StartCallback = std::unique_ptr<ObserverContext>(*)(RecordFunction&);
|
|
+ using EndCallback = void (*)(RecordFunction&, ObserverContext*);
|
|
|
|
// This interface supports observers that require passing an ObserverContext
|
|
// between start and end callbacks.
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:23.300880700 +0800
|
|
+++ patch/aten/src/ATen/templates/TensorBody.h 2022-02-18 11:05:28.914825300 +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=build.sh' '--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-02-18 11:15:23.300880700 +0800
|
|
+++ patch/aten/src/ATen/templates/TensorMethods.cpp 2022-02-18 11:05:28.919824500 +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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/TH/generic/THStorage.h patch/aten/src/TH/generic/THStorage.h
|
|
--- pytorch-v1.8.1/aten/src/TH/generic/THStorage.h 2022-02-18 11:15:23.347754800 +0800
|
|
+++ patch/aten/src/TH/generic/THStorage.h 2022-02-18 11:05:29.338827100 +0800
|
|
@@ -51,6 +51,7 @@
|
|
|
|
TH_API THStorage* THStorage_(new)(void);
|
|
TH_API THStorage* THStorage_(newWithSize)(ptrdiff_t size);
|
|
+TH_API THStorage* THStorage_(newWithSizeAndDevice)(ptrdiff_t size, c10::DeviceType type);
|
|
TH_API THStorage* THStorage_(newWithSize1)(scalar_t);
|
|
TH_API THStorage* THStorage_(newWithMapping)(const char *filename, ptrdiff_t size, int flags);
|
|
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/THNPU/CMakeLists.txt patch/aten/src/THNPU/CMakeLists.txt
|
|
--- pytorch-v1.8.1/aten/src/THNPU/CMakeLists.txt 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/THNPU/CMakeLists.txt 2022-02-18 11:05:30.061825100 +0800
|
|
@@ -0,0 +1,14 @@
|
|
+set(ATen_NPU_INCLUDE ${ATen_NPU_INCLUDE}
|
|
+ "${CMAKE_CURRENT_BINARY_DIR}"
|
|
+ "${CMAKE_CURRENT_SOURCE_DIR}"
|
|
+PARENT_SCOPE)
|
|
+
|
|
+
|
|
+set(ATen_NPU_SRCS ${ATen_NPU_SRCS}
|
|
+ ${CMAKE_CURRENT_SOURCE_DIR}/THNPUCachingHostAllocator.cpp
|
|
+ PARENT_SCOPE)
|
|
+
|
|
+INSTALL(FILES
|
|
+ THNPU.h
|
|
+ THNPUCachingHostAllocator.h
|
|
+ DESTINATION "${ATEN_INSTALL_INCLUDE_SUBDIR}/THNPU")
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/THNPU/THNPU.h patch/aten/src/THNPU/THNPU.h
|
|
--- pytorch-v1.8.1/aten/src/THNPU/THNPU.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/THNPU/THNPU.h 2022-02-18 11:05:30.065827200 +0800
|
|
@@ -0,0 +1,6 @@
|
|
+#ifndef THNPU_INC
|
|
+#define THNPU_INC
|
|
+
|
|
+#include <THNPU/THNPUCachingHostAllocator.h>
|
|
+
|
|
+#endif
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/THNPU/THNPUCachingHostAllocator.cpp patch/aten/src/THNPU/THNPUCachingHostAllocator.cpp
|
|
--- pytorch-v1.8.1/aten/src/THNPU/THNPUCachingHostAllocator.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/THNPU/THNPUCachingHostAllocator.cpp 2022-02-18 11:05:30.068823400 +0800
|
|
@@ -0,0 +1,306 @@
|
|
+#include <THNPU/THNPUCachingHostAllocator.h>
|
|
+#include <c10/core/DeviceGuard.h>
|
|
+#include <c10/npu/npu_log.h>
|
|
+
|
|
+#include <Python.h>
|
|
+
|
|
+#include <cstdint>
|
|
+#include <deque>
|
|
+#include <memory>
|
|
+#include <mutex>
|
|
+#include <set>
|
|
+#include <unordered_map>
|
|
+#include <unordered_set>
|
|
+#include <utility>
|
|
+
|
|
+#include <third_party/acl/inc/acl/acl.h>
|
|
+
|
|
+namespace {
|
|
+struct BlockSize {
|
|
+ size_t size; // allocation size
|
|
+ void* ptr; // host memory pointer
|
|
+
|
|
+ explicit BlockSize(size_t size, void* ptr = nullptr) : size(size), ptr(ptr) {}
|
|
+};
|
|
+
|
|
+struct Block : public BlockSize {
|
|
+ bool allocated; // true if the block is currently allocated
|
|
+ int event_count; // number of outstanding cuda events
|
|
+ std::unordered_set<at::npu::NPUStream> streams;
|
|
+ Block(size_t size, void* ptr, bool allocated)
|
|
+ : BlockSize(size, ptr), allocated(allocated), event_count(0), streams() {}
|
|
+};
|
|
+
|
|
+static bool BlockComparator(const BlockSize& a, const BlockSize& b) {
|
|
+ // sort by size, break ties with pointer
|
|
+ if (a.size != b.size) {
|
|
+ return a.size < b.size;
|
|
+ }
|
|
+ return reinterpret_cast<uintptr_t>(a.ptr) < reinterpret_cast<uintptr_t>(b.ptr);
|
|
+}
|
|
+
|
|
+struct HostAllocator {
|
|
+ using Comparison = bool (*)(const BlockSize&, const BlockSize&);
|
|
+
|
|
+ // lock around all operations
|
|
+ std::mutex mutex;
|
|
+
|
|
+ // blocks by pointer
|
|
+ std::unordered_map<void*, Block> blocks;
|
|
+
|
|
+ // pointers that are ready to be allocated (event_count=0)
|
|
+ std::set<BlockSize, Comparison> available;
|
|
+
|
|
+ // outstanding ACL events
|
|
+ std::deque<std::pair<aclrtEvent, void*>> npu_events;
|
|
+
|
|
+ HostAllocator() : available(BlockComparator) {}
|
|
+
|
|
+ aclError malloc(void** ptr, size_t size) {
|
|
+ std::lock_guard<std::mutex> lock(mutex);
|
|
+
|
|
+ // process outstanding npu events which may have occurred
|
|
+ aclError err = processEvents();
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ return err;
|
|
+ }
|
|
+
|
|
+ // search for the smallest block which can hold this allocation
|
|
+ BlockSize search_key(size);
|
|
+ auto it = available.lower_bound(search_key);
|
|
+ if (it != available.end()) {
|
|
+ Block& block = blocks.at(it->ptr);
|
|
+ AT_ASSERT(!block.allocated && block.event_count == 0);
|
|
+ block.allocated = true;
|
|
+ *ptr = block.ptr;
|
|
+ available.erase(it);
|
|
+ return ACL_ERROR_NONE;
|
|
+ }
|
|
+
|
|
+ *ptr = nullptr;
|
|
+
|
|
+ // allocate a new block if no cached allocation is found
|
|
+ err = aclrtMallocHost(ptr, size);
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ return err;
|
|
+ }
|
|
+
|
|
+ blocks.insert({*ptr, Block(size, *ptr, true)});
|
|
+ return ACL_ERROR_NONE;
|
|
+ }
|
|
+
|
|
+ aclError free(void* ptr) {
|
|
+ std::lock_guard<std::mutex> lock(mutex);
|
|
+
|
|
+ if (!ptr) {
|
|
+ return ACL_ERROR_NONE;
|
|
+ }
|
|
+
|
|
+ // process outstanding cuda events which may have occurred
|
|
+ aclError err = processEvents();
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ return err;
|
|
+ }
|
|
+
|
|
+ auto it = blocks.find(ptr);
|
|
+ AT_ASSERT(it != blocks.end());
|
|
+
|
|
+ Block& block = it->second;
|
|
+ AT_ASSERT(block.allocated);
|
|
+
|
|
+ // free (on valid memory) shouldn't fail, so mark unallocated before
|
|
+ // we process the streams.
|
|
+ block.allocated = false;
|
|
+
|
|
+ // insert CUDA events for each stream on which this block was used. This
|
|
+ err = insertEvents(block);
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ return err;
|
|
+ }
|
|
+
|
|
+ if (block.event_count == 0) {
|
|
+ // the block can be re-used if there are no outstanding cuda events
|
|
+ available.insert(block);
|
|
+ }
|
|
+ return ACL_ERROR_NONE;
|
|
+ }
|
|
+
|
|
+ aclError recordEvent(void* ptr, at::npu::NPUStream stream) {
|
|
+ std::lock_guard<std::mutex> lock(mutex);
|
|
+
|
|
+ auto it = blocks.find(ptr);
|
|
+ if (it == blocks.end()) {
|
|
+ // Sync when host memory is allocated by malloc
|
|
+ aclError error = aclrtSynchronizeStream(stream);
|
|
+ if (error != ACL_ERROR_NONE) {
|
|
+ AT_ERROR("ACL stream synchronize failed.");
|
|
+ return error;
|
|
+ }
|
|
+ return ACL_ERROR_NONE;
|
|
+ }
|
|
+
|
|
+ Block& block = it->second;
|
|
+ AT_ASSERT(block.allocated);
|
|
+
|
|
+ block.streams.insert(stream);
|
|
+ return ACL_ERROR_NONE;
|
|
+ }
|
|
+
|
|
+ aclError processEvents() {
|
|
+ // Process outstanding cudaEvents. Events that are completed are removed
|
|
+ // from the queue, and the 'event_count' for the corresponding allocation
|
|
+ // is decremented. Stops at the first event which has not been completed.
|
|
+ // Since events on different devices or streams may occur out of order,
|
|
+ // the processing of some events may be delayed.
|
|
+ while (!npu_events.empty()) {
|
|
+ auto& e = npu_events.front();
|
|
+ aclrtEvent event = e.first;
|
|
+ aclrtEventStatus status = ACL_EVENT_STATUS_COMPLETE;
|
|
+ aclError err = aclrtQueryEvent(event, &status);
|
|
+ if (status == ACL_EVENT_STATUS_NOT_READY) {
|
|
+ break;
|
|
+ } else if (err != ACL_ERROR_NONE) {
|
|
+ return err;
|
|
+ }
|
|
+ err = aclrtDestroyEvent(event);
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ return err;
|
|
+ }
|
|
+
|
|
+ Block& block = blocks.at(e.second);
|
|
+ block.event_count--;
|
|
+ if (block.event_count == 0 && !block.allocated) {
|
|
+ available.insert(block);
|
|
+ }
|
|
+ npu_events.pop_front();
|
|
+ }
|
|
+ return ACL_ERROR_NONE;
|
|
+ }
|
|
+
|
|
+ void emptyCache() {
|
|
+ std::lock_guard<std::mutex> lock(mutex);
|
|
+
|
|
+ // remove events for freed blocks
|
|
+ for (auto it = npu_events.begin(); it != npu_events.end(); ++it) {
|
|
+ aclrtEvent event = it->first;
|
|
+ Block& block = blocks.at(it->second);
|
|
+ if (!block.allocated) {
|
|
+ if (aclrtDestroyEvent(event) != ACL_ERROR_NONE) {
|
|
+ NPU_LOGW("destory acl event fail");
|
|
+ }
|
|
+ block.event_count--;
|
|
+ }
|
|
+ }
|
|
+
|
|
+ // all cuda_events have been processed
|
|
+ npu_events.clear();
|
|
+
|
|
+ // clear list of available blocks
|
|
+ available.clear();
|
|
+
|
|
+ // free and erase non-allocated blocks
|
|
+ for (auto it = blocks.begin(); it != blocks.end();) {
|
|
+ Block& block = it->second;
|
|
+ if (aclrtFreeHost(block.ptr) != ACL_ERROR_NONE) {
|
|
+ NPU_LOGE("free host pin failed!");
|
|
+ }
|
|
+ if (!block.allocated) {
|
|
+ it = blocks.erase(it);
|
|
+ } else {
|
|
+ block.streams.clear();
|
|
+ ++it;
|
|
+ }
|
|
+ }
|
|
+ }
|
|
+
|
|
+ aclError insertEvents(Block& block) {
|
|
+ aclError err = ACL_ERROR_NONE;
|
|
+
|
|
+ int prev_device = 0;
|
|
+ err = aclrtGetDevice(&prev_device);
|
|
+ if (err != ACL_ERROR_NONE)
|
|
+ return err;
|
|
+
|
|
+ std::unordered_set<at::npu::NPUStream> streams(std::move(block.streams));
|
|
+ for (auto it = streams.begin(); it != streams.end(); ++it) {
|
|
+ int pre_device = 0;
|
|
+ aclError ret = aclrtGetDevice(&pre_device);
|
|
+ if (ret != ACL_ERROR_NONE) {
|
|
+ err = aclrtSetDevice(it->device_index());
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ break;
|
|
+ }
|
|
+ } else if (pre_device != it->device_index()) {
|
|
+ err = aclrtSetDevice(it->device_index());
|
|
+ if (err != ACL_ERROR_NONE) {
|
|
+ break;
|
|
+ }
|
|
+ }
|
|
+
|
|
+ aclrtEvent event = nullptr;
|
|
+ err = aclrtCreateEvent(&event);
|
|
+ if (err != ACL_ERROR_NONE)
|
|
+ break;
|
|
+
|
|
+ err = aclrtRecordEvent(event, it->stream());
|
|
+ if (err != ACL_ERROR_NONE)
|
|
+ break;
|
|
+
|
|
+ block.event_count++;
|
|
+ npu_events.emplace_back(event, block.ptr);
|
|
+ }
|
|
+
|
|
+ int cur_device = 0;
|
|
+ aclError ret = aclrtGetDevice(&cur_device);
|
|
+ if (ret != ACL_ERROR_NONE) {
|
|
+ aclrtSetDevice(prev_device);
|
|
+ } else if (cur_device != prev_device) {
|
|
+ aclrtSetDevice(prev_device);
|
|
+ }
|
|
+
|
|
+ return err;
|
|
+ }
|
|
+};
|
|
+} // namespace
|
|
+static HostAllocator allocator;
|
|
+
|
|
+aclError THNPUCachingHostAllocator_recordEvent(
|
|
+ void* ptr,
|
|
+ at::npu::NPUStream stream) {
|
|
+ return allocator.recordEvent(ptr, stream);
|
|
+}
|
|
+
|
|
+void THNPUCachingHostAllocator_emptyCache() {
|
|
+ allocator.emptyCache();
|
|
+}
|
|
+
|
|
+static void THNPUCachingHostDeleter(void* ptr) {
|
|
+ // check the current thread have hold GIL Lock.
|
|
+ if (PyGILState_Check()) {
|
|
+ // the current thread should not hold GIL.
|
|
+ Py_BEGIN_ALLOW_THREADS
|
|
+ allocator.free(ptr);
|
|
+ Py_END_ALLOW_THREADS
|
|
+ } else {
|
|
+ allocator.free(ptr);
|
|
+ }
|
|
+}
|
|
+
|
|
+struct THNPUCachingHostAllocator final : public at::Allocator {
|
|
+ at::DataPtr allocate(size_t size) const override {
|
|
+ AT_ASSERT(size >= 0);
|
|
+ void* ptr = nullptr;
|
|
+ if (allocator.malloc(&ptr, size) != ACL_ERROR_NONE) {
|
|
+ NPU_LOGE("allocate host pinned memory fail");
|
|
+ }
|
|
+ return {ptr, ptr, &THNPUCachingHostDeleter, at::DeviceType::CPU};
|
|
+ }
|
|
+ at::DeleterFnPtr raw_deleter() const override {
|
|
+ return &THNPUCachingHostDeleter;
|
|
+ }
|
|
+};
|
|
+
|
|
+static THNPUCachingHostAllocator thnpu_caching_host_allocator;
|
|
+at::Allocator* getTHNPUCachingHostAllocator() {
|
|
+ return &thnpu_caching_host_allocator;
|
|
+}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/aten/src/THNPU/THNPUCachingHostAllocator.h patch/aten/src/THNPU/THNPUCachingHostAllocator.h
|
|
--- pytorch-v1.8.1/aten/src/THNPU/THNPUCachingHostAllocator.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/aten/src/THNPU/THNPUCachingHostAllocator.h 2022-02-18 11:05:30.072826100 +0800
|
|
@@ -0,0 +1,11 @@
|
|
+#include <c10/core/Allocator.h>
|
|
+#include <c10/npu/NPUStream.h>
|
|
+#include <c10/util/Exception.h>
|
|
+
|
|
+C10_NPU_API c10::Allocator* getTHNPUCachingHostAllocator(void);
|
|
+
|
|
+C10_NPU_API aclError
|
|
+THNPUCachingHostAllocator_recordEvent(void* ptr, at::npu::NPUStream stream);
|
|
+
|
|
+// Releases cached pinned memory allocations via cudaHostFree
|
|
+C10_NPU_API void THNPUCachingHostAllocator_emptyCache(void);
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:23.482153900 +0800
|
|
+++ patch/c10/CMakeLists.txt 2022-02-18 11:05:30.861824600 +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=build.sh' '--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-02-18 11:15:23.483153300 +0800
|
|
+++ patch/c10/core/Backend.h 2022-02-18 11:05:30.879824800 +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");
|
|
}
|
|
@@ -99,6 +102,8 @@
|
|
return Backend::QuantizedCUDA;
|
|
case Backend::QuantizedXPU:
|
|
return Backend::QuantizedXPU;
|
|
+ case Backend::NPU:
|
|
+ return Backend::NPU;
|
|
default:
|
|
throw std::runtime_error("Unknown backend");
|
|
}
|
|
@@ -141,6 +146,8 @@
|
|
return Backend::QuantizedXPU;
|
|
} else if (t == DispatchKey::Undefined) {
|
|
return Backend::Undefined;
|
|
+ } else if (t == DispatchKey::NPU || t == DispatchKey::AutogradNPU) {
|
|
+ return Backend::NPU;
|
|
} else {
|
|
AT_ERROR("Unrecognized tensor type ID: ", t);
|
|
}
|
|
@@ -182,6 +189,8 @@
|
|
return DispatchKey::QuantizedCUDA;
|
|
case Backend::Undefined:
|
|
return DispatchKey::Undefined;
|
|
+ case Backend::NPU:
|
|
+ return DispatchKey::NPUTensorId;
|
|
default:
|
|
throw std::runtime_error("Unknown backend");
|
|
}
|
|
@@ -220,6 +229,8 @@
|
|
return DeviceType::Vulkan;
|
|
case Backend::Metal:
|
|
return DeviceType::Metal;
|
|
+ case Backend::NPU:
|
|
+ return DeviceType::NPU;
|
|
case Backend::Undefined:
|
|
AT_ERROR("Undefined backend is not a valid device type");
|
|
default:
|
|
@@ -258,6 +269,8 @@
|
|
return Backend::QuantizedCPU;
|
|
case Backend::QuantizedXPU:
|
|
return Backend::QuantizedCPU;
|
|
+ case Backend::NPU:
|
|
+ return Backend::NPU;
|
|
case Backend::Undefined:
|
|
return Backend::Undefined;
|
|
default:
|
|
@@ -374,6 +387,8 @@
|
|
return "QuantizedCUDA";
|
|
case Backend::QuantizedXPU:
|
|
return "QuantizedXPU";
|
|
+ case Backend::NPU:
|
|
+ return "NPU";
|
|
default:
|
|
return "UNKNOWN_BACKEND";
|
|
}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:23.486153400 +0800
|
|
+++ patch/c10/core/Device.cpp 2022-02-18 11:05:30.910824500 +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=build.sh' '--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-02-18 11:15:23.487153400 +0800
|
|
+++ patch/c10/core/Device.h 2022-02-18 11:05:30.914794600 +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=build.sh' '--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-02-18 11:15:23.487153400 +0800
|
|
+++ patch/c10/core/DeviceType.cpp 2022-02-18 11:05:30.922825500 +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=build.sh' '--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-02-18 11:15:23.487153400 +0800
|
|
+++ patch/c10/core/DeviceType.h 2022-02-18 11:05:30.926825300 +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=build.sh' '--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-02-18 11:15:23.488154500 +0800
|
|
+++ patch/c10/core/DispatchKey.cpp 2022-02-18 11:05:30.929825100 +0800
|
|
@@ -80,6 +80,8 @@
|
|
return "AutogradCUDA";
|
|
case DispatchKey::AutogradXLA:
|
|
return "AutogradXLA";
|
|
+ case DispatchKey::AutogradNPU:
|
|
+ return "AutogradNPU";
|
|
case DispatchKey::AutogradNestedTensor:
|
|
return "AutogradNestedTensor";
|
|
case DispatchKey::AutogradPrivateUse1:
|
|
@@ -90,6 +92,8 @@
|
|
return "AutogradPrivateUse3";
|
|
case DispatchKey::AutogradOther:
|
|
return "AutogradOther";
|
|
+ case DispatchKey::NPU:
|
|
+ return "NPU";
|
|
case DispatchKey::BackendSelect:
|
|
return "BackendSelect";
|
|
case DispatchKey::Named:
|
|
@@ -143,6 +147,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=build.sh' '--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-02-18 11:15:23.488154500 +0800
|
|
+++ patch/c10/core/DispatchKey.h 2022-02-18 11:05:30.933826900 +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=build.sh' '--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-02-18 11:15:23.488154500 +0800
|
|
+++ patch/c10/core/DispatchKeySet.cpp 2022-02-18 11:05:30.937825800 +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=build.sh' '--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-02-18 11:15:23.489154300 +0800
|
|
+++ patch/c10/core/DispatchKeySet.h 2022-02-18 11:05:30.940825000 +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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/c10/core/Storage.h patch/c10/core/Storage.h
|
|
--- pytorch-v1.8.1/c10/core/Storage.h 2022-02-18 11:15:23.491214600 +0800
|
|
+++ patch/c10/core/Storage.h 2022-02-18 11:05:30.985823500 +0800
|
|
@@ -147,6 +147,10 @@
|
|
std::move(data_ptr), capacity);
|
|
}
|
|
|
|
+ c10::NPUStorageDesc get_npu_desc() const {
|
|
+ return storage_impl_->get_npu_desc();
|
|
+ }
|
|
+
|
|
protected:
|
|
c10::intrusive_ptr<StorageImpl> storage_impl_;
|
|
};
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:23.491214600 +0800
|
|
+++ patch/c10/core/StorageImpl.h 2022-02-18 11:05:30.992825300 +0800
|
|
@@ -4,9 +4,23 @@
|
|
#include <c10/core/ScalarType.h>
|
|
|
|
#include <c10/util/intrusive_ptr.h>
|
|
+#include <third_party/acl/inc/acl/acl_base.h>
|
|
|
|
namespace c10 {
|
|
|
|
+struct NPUStorageDesc {
|
|
+public:
|
|
+ struct use_byte_size_t {};
|
|
+
|
|
+ SmallVector<int64_t,5> base_sizes_;
|
|
+ SmallVector<int64_t,5> base_strides_;
|
|
+ SmallVector<int64_t,5> storage_sizes_;
|
|
+ int64_t base_offset_ = 0; // no use
|
|
+ use_byte_size_t base_dtype_; // no use
|
|
+ aclFormat origin_format_;
|
|
+ aclFormat npu_format_ = ACL_FORMAT_ND;
|
|
+};
|
|
+
|
|
struct C10_API StorageImpl final : public c10::intrusive_ptr_target {
|
|
public:
|
|
struct use_byte_size_t {};
|
|
@@ -163,6 +177,13 @@
|
|
received_cuda_ = received_cuda;
|
|
}
|
|
|
|
+ // not private
|
|
+ NPUStorageDesc npu_desc_;
|
|
+
|
|
+ NPUStorageDesc get_npu_desc() const {
|
|
+ return npu_desc_;
|
|
+ }
|
|
+
|
|
bool received_cuda() {
|
|
return received_cuda_;
|
|
}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:23.491214600 +0800
|
|
+++ patch/c10/core/TensorImpl.h 2022-02-18 11:05:31.010826400 +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
|
|
@@ -998,7 +1002,7 @@
|
|
inline bool has_compatible_shallow_copy_type(DispatchKeySet from) {
|
|
auto is_dense = [](DispatchKeySet ts) {
|
|
return ts.has(DispatchKey::CPU) || ts.has(DispatchKey::CUDA) ||
|
|
- ts.has(DispatchKey::HIP) || ts.has(DispatchKey::XPU);
|
|
+ ts.has(DispatchKey::HIP) || ts.has(DispatchKey::XPU) || ts.has(DispatchKey::NPU);
|
|
};
|
|
auto is_sparse = [](DispatchKeySet ts) {
|
|
return ts.has(DispatchKey::SparseCPU) ||
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:23.491214600 +0800
|
|
+++ patch/c10/core/TensorOptions.h 2022-02-18 11:05:31.018826200 +0800
|
|
@@ -633,6 +633,8 @@
|
|
return DispatchKey::Vulkan;
|
|
case DeviceType::Metal:
|
|
return DispatchKey::Metal;
|
|
+ case DeviceType::NPU:
|
|
+ return DispatchKey::NPU;
|
|
default:
|
|
AT_ERROR("Unsupported device type for dense layout: ", device_.type());
|
|
}
|
|
@@ -703,6 +705,8 @@
|
|
return DeviceType::CPU;
|
|
} else if (tid == DispatchKey::XPU) {
|
|
return DeviceType::XPU;
|
|
+ } else if (tid == DispatchKey::NPU) {
|
|
+ return DeviceType::NPU;
|
|
} else if (tid == DispatchKey::SparseXPU) {
|
|
return DeviceType::XPU;
|
|
} else if (tid == DispatchKey::QuantizedXPU) {
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:05:31.177825800 +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=build.sh' '--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-02-18 11:05:31.180794800 +0800
|
|
@@ -0,0 +1,141 @@
|
|
+#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 <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::NPUEventManager::GetInstance().LazyDestroy(event_);
|
|
+ }
|
|
+ } 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;
|
|
+ }
|
|
+
|
|
+ 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(aclrtRecordEvent(event_, stream));
|
|
+ was_recorded_ = true;
|
|
+ }
|
|
+
|
|
+ void block(const NPUStream& stream) {
|
|
+ if (is_created_) {
|
|
+ NPUGuard guard(stream.device_index());
|
|
+ C10_NPU_CHECK(aclrtStreamWaitEvent(stream, event_));
|
|
+ }
|
|
+ }
|
|
+
|
|
+ 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;
|
|
+ // 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_) {
|
|
+ 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=build.sh' '--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-02-18 11:05:31.184823300 +0800
|
|
@@ -0,0 +1,44 @@
|
|
+#include "NPUEventManager.h"
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+NPUEventManager::NPUEventManager() {};
|
|
+
|
|
+NPUEventManager& NPUEventManager::GetInstance() {
|
|
+ static NPUEventManager instance;
|
|
+ return instance;
|
|
+}
|
|
+
|
|
+aclError NPUEventManager::LazyDestroy(aclrtEvent npu_event) {
|
|
+ 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) {
|
|
+ return err;
|
|
+ }
|
|
+ npu_events_.pop_front();
|
|
+ }
|
|
+ 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=build.sh' '--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-02-18 11:05:31.187825100 +0800
|
|
@@ -0,0 +1,20 @@
|
|
+#pragma once
|
|
+
|
|
+#include <c10/npu/NPUException.h>
|
|
+#include <third_party/acl/inc/acl/acl.h>
|
|
+#include <deque>
|
|
+namespace c10 {
|
|
+namespace npu {
|
|
+class C10_EXPORT NPUEventManager {
|
|
+public:
|
|
+ static NPUEventManager& GetInstance();
|
|
+ aclError LazyDestroy(aclrtEvent npu_event);
|
|
+ aclError ClearEvent();
|
|
+ ~NPUEventManager(){}
|
|
+
|
|
+private:
|
|
+ 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=build.sh' '--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-02-18 11:05:31.191825100 +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=build.sh' '--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-02-18 11:05:31.194793300 +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=build.sh' '--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-02-18 11:05:31.198824600 +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=build.sh' '--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-02-18 11:05:31.202825000 +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=build.sh' '--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-02-18 11:05:31.205823600 +0800
|
|
@@ -0,0 +1,475 @@
|
|
+#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 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, aclrtStream stream) {
|
|
+ TORCH_CHECK(this->execFunc, "Failed to find execution function.");
|
|
+ auto dstPtr = (uint8_t*)head + sizePerParams * offset;
|
|
+ return this->execFunc(dstPtr, stream);
|
|
+ }
|
|
+
|
|
+ void Copy(void* dstHead, int offset, void* src) {
|
|
+ TORCH_CHECK(this->copyFunc, "Failed to find copy function.");
|
|
+ auto dstPtr = (uint8_t*)dstHead + sizePerParams * offset;
|
|
+ return this->copyFunc(dstPtr, src);
|
|
+ }
|
|
+
|
|
+ void Release(void* head, int offset) {
|
|
+ TORCH_CHECK(this->releaseFunc, "Failed to find release function.");
|
|
+ auto ptr = (uint8_t*)head + sizePerParams * offset;
|
|
+ return this->releaseFunc(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;
|
|
+}; // class CallBackManager
|
|
+
|
|
+CallBackManager& manager() {
|
|
+ static CallBackManager instance;
|
|
+ return instance;
|
|
+}
|
|
+} // 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) {
|
|
+ manager().SetExec(execFunc);
|
|
+ manager().SetCopy(copyFunc);
|
|
+ manager().SetRelease(releaseFunc);
|
|
+ manager().SetNew(newFunc);
|
|
+ manager().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 = 1000;
|
|
+
|
|
+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) {
|
|
+ NPU_LOGE("eventfd_read failed !!");
|
|
+ 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) {
|
|
+ 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);
|
|
+ manager().Copy(datas, write_idx.idx, cur_paras);
|
|
+ __sync_synchronize();
|
|
+
|
|
+ write_idx.idx++;
|
|
+ write_idx.idx %= 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;
|
|
+ }
|
|
+
|
|
+ auto ret = manager().Call(datas, read_idx.idx, calcu_stream_);
|
|
+
|
|
+ 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);
|
|
+ read_idx.idx++;
|
|
+ read_idx.idx %= kQueueCapacity;
|
|
+ }
|
|
+ ReleaseResource();
|
|
+ std::stringstream msg;
|
|
+ msg << __func__ << ":" << __FILE__ << ":" << __LINE__;
|
|
+ TORCH_CHECK(0, msg.str());
|
|
+ }
|
|
+
|
|
+ manager().Release(datas, read_idx.idx);
|
|
+ __sync_synchronize();
|
|
+
|
|
+ read_idx.idx++;
|
|
+ read_idx.idx %= kQueueCapacity;
|
|
+ QUEUE_DEBUG("read success, now read of repo is %d", read_idx.idx);
|
|
+
|
|
+ return true;
|
|
+}
|
|
+
|
|
+void Repository::Enqueue(void* cur_paras) {
|
|
+ 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);
|
|
+ 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) {
|
|
+ NPU_LOGE("waiting queue not full failed !!");
|
|
+ return;
|
|
+ }
|
|
+ DisableInterrupt(RepoRole::WRITER);
|
|
+ QUEUE_DEBUG("waiting ok, queue isn't full now");
|
|
+ }
|
|
+ continue;
|
|
+ }
|
|
+ __sync_synchronize();
|
|
+ if (NeedNotify(RepoRole::READER)) {
|
|
+ QUEUE_DEBUG("need notify consumer");
|
|
+ s = eventfd_write(efd_read, u);
|
|
+ if (s != 0) {
|
|
+ NPU_LOGE("notify consumer failed !!");
|
|
+ return;
|
|
+ }
|
|
+ }
|
|
+ }
|
|
+ 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) {
|
|
+ NPU_LOGE("waiting queue not empty failed !!");
|
|
+ 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());
|
|
+ if (notify_empty) {
|
|
+ QUEUE_DEBUG("need notify make_sure");
|
|
+ s = eventfd_write(efd_empty, u);
|
|
+ if (s != 0) {
|
|
+ NPU_LOGE("notify make_sure failed !!");
|
|
+ return;
|
|
+ }
|
|
+ }
|
|
+ __sync_synchronize();
|
|
+ if (NeedNotify(RepoRole::WRITER)) {
|
|
+ QUEUE_DEBUG("need notify producer");
|
|
+ s = eventfd_write(efd_write, u);
|
|
+ if (s != 0) {
|
|
+ NPU_LOGE("notify producer failed !!");
|
|
+ return;
|
|
+ }
|
|
+ }
|
|
+ }
|
|
+ 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) {
|
|
+ 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, aclrtStream calcu_stream) {
|
|
+ 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);
|
|
+ }
|
|
+ if (calcu_stream == nullptr) {
|
|
+ NPU_LOGE("stream should not be null when init task queue.");
|
|
+ return;
|
|
+ }
|
|
+ calcu_stream_ = calcu_stream;
|
|
+ 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);
|
|
+}
|
|
+
|
|
+
|
|
+} // namespace npu
|
|
+} // namespace c10
|
|
\ No newline at end of file
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:05:31.209824200 +0800
|
|
@@ -0,0 +1,118 @@
|
|
+#ifndef __C10_NPU_NPUQUEUE__
|
|
+#define __C10_NPU_NPUQUEUE__
|
|
+
|
|
+#include <string>
|
|
+#include <thread>
|
|
+#include <mutex>
|
|
+#include <atomic>
|
|
+
|
|
+#include <c10/core/Device.h>
|
|
+#include "c10/npu/npu_log.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,
|
|
+};
|
|
+
|
|
+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) = 0;
|
|
+ virtual void Dequeue() = 0;
|
|
+ virtual NPUStatus MakeSureQueueEmpty() = 0;
|
|
+ virtual void InitRepo(DeviceIndex device_id, aclrtStream calcu_stream) = 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) override;
|
|
+ void Dequeue() override;
|
|
+ NPUStatus MakeSureQueueEmpty() override;
|
|
+ void InitRepo(DeviceIndex device_id, aclrtStream calcu_stream) 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);
|
|
+ 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;
|
|
+ aclrtStream calcu_stream_;
|
|
+};
|
|
+
|
|
+using ACL_EXEC_FUNC = std::function<int(void*, aclrtStream)>;
|
|
+using ACL_COPY_FUNC = std::function<void(void*, void*)>;
|
|
+using ACL_RELEASE_FUNC = std::function<void(void*)>;
|
|
+using ACL_NEW_FUNC = std::function<void*(int, int&)>;
|
|
+using ACL_DELETE_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);
|
|
+ ~NPUCallBackRegisterBuilder(){}
|
|
+};
|
|
+} // namespace register_queue_cb
|
|
+
|
|
+#define REGISTER_QUEUE_FUNC(execF, copyF, releaseF, newF, deleteF) \
|
|
+ static ::c10::npu::register_queue_cb::NPUCallBackRegisterBuilder \
|
|
+ register_queue_func_builder(execF, copyF, releaseF, newF, deleteF);
|
|
+
|
|
+} // 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=build.sh' '--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-02-18 11:05:31.213825700 +0800
|
|
@@ -0,0 +1,421 @@
|
|
+#include "NPUStream.h"
|
|
+#include "NPUQueue.h"
|
|
+#include <c10/npu/NPUFunctions.h>
|
|
+#include <c10/npu/NPUGuard.h>
|
|
+#include <c10/npu/NPUQueue.h>
|
|
+#include <c10/npu/OptionsManager.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, default_streamsi.stream);
|
|
+ }
|
|
+ // 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));
|
|
+ if (OptionsManager::CheckQueueEnable()) {
|
|
+ secondary_streamsi.repo->InitRepo(device_id, 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));
|
|
+
|
|
+ if (OptionsManager::CheckQueueEnable()) {
|
|
+ npu_streami.repo->InitRepo(device_index, 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(*this);
|
|
+ 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;
|
|
+ }
|
|
+ }
|
|
+ return 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];
|
|
+ auto& secondary_streamsi = secondary_streams[i];
|
|
+ if (default_streamsi.stream == nullptr && secondary_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;
|
|
+ }
|
|
+ }
|
|
+ if (secondary_streamsi.stream != nullptr && secondary_streamsi.repo->CheckInit()) {
|
|
+ ret = secondary_streamsi.repo->MakeSureQueueEmpty();
|
|
+ if (ret != SUCCESS) {
|
|
+ return ret;
|
|
+ }
|
|
+ }
|
|
+
|
|
+ }
|
|
+
|
|
+ for (auto i = decltype(num_npus){0}; i < num_npus; ++i) {
|
|
+ for (auto j = decltype(kStreamsPerPool){0}; j < kStreamsPerPool; ++j) {
|
|
+ auto& npu_streamj = npu_streams[i][j];
|
|
+ if (npu_streamj.stream == nullptr) {
|
|
+ continue;
|
|
+ }
|
|
+ NPUGuard device_guard{i};
|
|
+ if (npu_streamj.repo->CheckInit()) {
|
|
+ ret = npu_streamj.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,
|
|
+ DeviceIndex device_index) {
|
|
+ initNPUStreamsOnce();
|
|
+ if (device_index == -1) {
|
|
+ device_index = current_device();
|
|
+ }
|
|
+ check_npu(device_index);
|
|
+ current_streams[device_index]->repo->Enqueue(cur_paras);
|
|
+ if (current_streams[device_index]->repo->GetStatus() == RepoStatus::INIT) {
|
|
+ current_streams[device_index]->repo->MakeSureQueueEmpty();
|
|
+ current_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=build.sh' '--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-02-18 11:05:31.217828300 +0800
|
|
@@ -0,0 +1,132 @@
|
|
+#pragma once
|
|
+
|
|
+#include <cstdint>
|
|
+#include <mutex>
|
|
+
|
|
+#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 "c10/npu/npu_log.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 void npuSynchronizeDevice();
|
|
+
|
|
+TORCH_API void enCurrentNPUStream(
|
|
+ void* cur_paras,
|
|
+ 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=build.sh' '--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-02-18 11:05:31.221825700 +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=build.sh' '--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-02-18 11:05:31.224826700 +0800
|
|
@@ -0,0 +1,30 @@
|
|
+#ifndef __C10_NPU_OPTIONSMANAGER_H__
|
|
+#define __C10_NPU_OPTIONSMANAGER_H__
|
|
+
|
|
+#include <ATen/npu/Exceptions.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=build.sh' '--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-02-18 11:05:31.228823600 +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=build.sh' '--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-02-18 11:05:31.232825300 +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=build.sh' '--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-02-18 11:05:31.236823900 +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=build.sh' '--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-02-18 11:05:31.240826500 +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=build.sh' '--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-02-18 11:05:31.244794700 +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=build.sh' '--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-02-18 11:05:31.247828600 +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=build.sh' '--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-02-18 11:05:31.252825200 +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=build.sh' '--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-02-18 11:05:31.257825200 +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=build.sh' '--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-02-18 11:05:31.260793300 +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=build.sh' '--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-02-18 11:05:31.265793400 +0800
|
|
@@ -0,0 +1,87 @@
|
|
+#include "npu_sys_ctrl.h"
|
|
+#include <c10/npu/npu_log.h>
|
|
+#include <c10/npu/NPUStream.h>
|
|
+#include <c10/npu/OptionsManager.h>
|
|
+
|
|
+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");
|
|
+ }
|
|
+
|
|
+ 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(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=build.sh' '--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-02-18 11:05:31.269824300 +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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/caffe2/CMakeLists.txt patch/caffe2/CMakeLists.txt
|
|
--- pytorch-v1.8.1/caffe2/CMakeLists.txt 2022-02-18 11:15:23.553715800 +0800
|
|
+++ patch/caffe2/CMakeLists.txt 2022-02-18 11:05:31.711823600 +0800
|
|
@@ -76,6 +76,7 @@
|
|
# Add source, includes, and libs to lists
|
|
list(APPEND Caffe2_CPU_SRCS ${ATen_CPU_SRCS})
|
|
list(APPEND Caffe2_GPU_SRCS ${ATen_CUDA_SRCS})
|
|
+ list(APPEND Caffe2_NPU_SRCS ${ATen_NPU_SRCS})
|
|
list(APPEND Caffe2_GPU_SRCS_W_SORT_BY_KEY ${ATen_CUDA_SRCS_W_SORT_BY_KEY})
|
|
list(APPEND Caffe2_HIP_SRCS ${ATen_HIP_SRCS})
|
|
list(APPEND Caffe2_HIP_SRCS ${ATen_HIP_SRCS_W_SORT_BY_KEY})
|
|
@@ -86,6 +87,7 @@
|
|
list(APPEND Caffe2_VULKAN_TEST_SRCS ${ATen_VULKAN_TEST_SRCS})
|
|
list(APPEND Caffe2_CPU_INCLUDE ${ATen_CPU_INCLUDE})
|
|
list(APPEND Caffe2_GPU_INCLUDE ${ATen_CUDA_INCLUDE})
|
|
+ list(APPEND Caffe2_NPU_INCLUDE ${ATen_NPU_INCLUDE})
|
|
list(APPEND Caffe2_HIP_INCLUDE ${ATen_HIP_INCLUDE})
|
|
list(APPEND Caffe2_VULKAN_INCLUDE ${ATen_VULKAN_INCLUDE})
|
|
list(APPEND Caffe2_DEPENDENCY_LIBS ${ATen_CPU_DEPENDENCY_LIBS})
|
|
@@ -770,6 +772,14 @@
|
|
target_link_libraries(torch_hip PRIVATE __caffe2_nccl)
|
|
target_compile_definitions(torch_hip PRIVATE USE_NCCL)
|
|
endif()
|
|
+elseif(USE_NPU)
|
|
+ add_library(torch_npu ${Caffe2_NPU_SRCS})
|
|
+ torch_compile_options(torch_npu)
|
|
+ if (USE_HCCL)
|
|
+ #target_link_libraries(torch_npu PRIVATE __caffe2_hccl)
|
|
+ target_compile_definitions(torch_npu PRIVATE USE_HCCL)
|
|
+ endif()
|
|
+
|
|
elseif(USE_CUDA)
|
|
set(CUDA_LINK_LIBRARIES_KEYWORD PRIVATE)
|
|
if(CUDA_SEPARABLE_COMPILATION)
|
|
@@ -904,7 +914,12 @@
|
|
${CMAKE_CURRENT_BINARY_DIR}/../aten/src/ATen
|
|
${CMAKE_BINARY_DIR}/aten/src)
|
|
|
|
-if(USE_TBB)
|
|
+ if(USE_NPU)
|
|
+ # TODO(ascend): support TH/THGeneral.h
|
|
+ list(APPEND ATen_NPU_INCLUDE ${TH_CPU_INCLUDE})
|
|
+ endif()
|
|
+
|
|
+IF (USE_TBB)
|
|
list(APPEND ATen_CPU_INCLUDE ${TBB_ROOT_DIR}/include)
|
|
target_link_libraries(torch_cpu PUBLIC tbb)
|
|
endif()
|
|
@@ -1139,6 +1154,10 @@
|
|
# Set standard properties on the target
|
|
torch_set_target_props(torch_cpu)
|
|
|
|
+if(USE_NPU)
|
|
+ target_link_libraries(
|
|
+ torch_npu PRIVATE ${Caffe2_NPU_DEPENDENCY_LIBS})
|
|
+endif()
|
|
|
|
target_compile_options(torch_cpu PRIVATE "-DCAFFE2_BUILD_MAIN_LIB")
|
|
if(BUILD_SPLIT_CUDA)
|
|
@@ -1156,6 +1175,9 @@
|
|
elseif(USE_ROCM)
|
|
target_compile_options(torch_hip PRIVATE "-DTORCH_HIP_BUILD_MAIN_LIB")
|
|
target_compile_definitions(torch_hip PRIVATE "-DTORCH_HIP_BUILD_MAIN_LIB")
|
|
+elseif(USE_NPU)
|
|
+ target_compile_options(torch_npu PRIVATE "-DTORCH_NPU_BUILD_MAIN_LIB")
|
|
+ target_compile_definitions(torch_npu PRIVATE "-DTORCH_NPU_BUILD_MAIN_LIB")
|
|
endif()
|
|
|
|
set(EXPERIMENTAL_SINGLE_THREAD_POOL "0" CACHE STRING
|
|
@@ -1249,6 +1271,8 @@
|
|
endif()
|
|
elseif(USE_ROCM)
|
|
caffe2_interface_library(torch_hip torch_hip_library)
|
|
+elseif (USE_NPU)
|
|
+ caffe2_interface_library(torch_npu torch_npu_library)
|
|
endif()
|
|
|
|
caffe2_interface_library(torch torch_library)
|
|
@@ -1263,6 +1287,8 @@
|
|
endif()
|
|
elseif(USE_ROCM)
|
|
install(TARGETS torch_hip torch_hip_library EXPORT Caffe2Targets DESTINATION "${TORCH_INSTALL_LIB_DIR}")
|
|
+elseif (USE_NPU)
|
|
+ install(TARGETS torch_npu torch_npu_library EXPORT Caffe2Targets DESTINATION "${TORCH_INSTALL_LIB_DIR}")
|
|
endif()
|
|
install(TARGETS torch torch_library EXPORT Caffe2Targets DESTINATION "${TORCH_INSTALL_LIB_DIR}")
|
|
|
|
@@ -1288,6 +1314,8 @@
|
|
install(FILES $<TARGET_PDB_FILE:torch_cuda> DESTINATION "${TORCH_INSTALL_LIB_DIR}" OPTIONAL)
|
|
elseif(USE_ROCM)
|
|
install(FILES $<TARGET_PDB_FILE:torch_hip> DESTINATION "${TORCH_INSTALL_LIB_DIR}" OPTIONAL)
|
|
+ elseif(USE_NPU)
|
|
+ install(FILES $<TARGET_PDB_FILE:torch_npu> DESTINATION "${TORCH_INSTALL_LIB_DIR}" OPTIONAL)
|
|
endif()
|
|
endif()
|
|
|
|
@@ -1377,6 +1405,15 @@
|
|
install(TARGETS torch_global_deps DESTINATION "${TORCH_INSTALL_LIB_DIR}")
|
|
endif()
|
|
|
|
+# ---[ NPU library
|
|
+if(USE_NPU)
|
|
+ target_link_libraries(torch_npu PUBLIC c10_npu)
|
|
+ target_include_directories(
|
|
+ torch_npu PRIVATE ${ATen_NPU_INCLUDE})
|
|
+ # TODO(ascend): npu code and cpu code is tight coupling, for details: search USE_NPU in function_wrapper.py
|
|
+ target_link_libraries(torch_cpu PUBLIC torch_npu)
|
|
+endif()
|
|
+
|
|
# ---[ Caffe2 HIP sources.
|
|
if(USE_ROCM)
|
|
# Call again since Caffe2_HIP_INCLUDE is extended with ATen include dirs.
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:24.382537400 +0800
|
|
+++ patch/cmake/BuildVariables.cmake 2022-02-18 11:05:41.779593500 +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=build.sh' '--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-02-18 11:15:24.383536200 +0800
|
|
+++ patch/cmake/Codegen.cmake 2022-02-18 11:05:41.792621500 +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=build.sh' '--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-02-18 11:15:24.384536800 +0800
|
|
+++ patch/cmake/Dependencies.cmake 2022-02-18 14:21:33.769695100 +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=build.sh' '--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-02-18 11:15:24.400536700 +0800
|
|
+++ patch/cmake/Summary.cmake 2022-02-18 11:05:42.009592600 +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=build.sh' '--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-02-18 11:15:24.401537100 +0800
|
|
+++ patch/cmake/TorchConfig.cmake.in 2022-02-18 11:05:42.012591700 +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=build.sh' '--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-02-18 14:21:58.371434200 +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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/setup.py patch/setup.py
|
|
--- pytorch-v1.8.1/setup.py 2022-02-18 11:15:24.516536900 +0800
|
|
+++ patch/setup.py 2022-02-18 11:05:43.278621700 +0800
|
|
@@ -298,6 +298,7 @@
|
|
report("Did you run 'git submodule update --init --recursive'?")
|
|
sys.exit(1)
|
|
|
|
+ check_file(os.path.join(third_party_path, "acl", "CMakeLists.txt"))
|
|
check_file(os.path.join(third_party_path, "gloo", "CMakeLists.txt"))
|
|
check_file(os.path.join(third_party_path, 'cpuinfo', 'CMakeLists.txt'))
|
|
check_file(os.path.join(third_party_path, 'tbb', 'Makefile'))
|
|
@@ -881,6 +882,10 @@
|
|
'include/ATen/native/hip/*.cuh',
|
|
'include/ATen/native/quantized/*.h',
|
|
'include/ATen/native/quantized/cpu/*.h',
|
|
+ 'include/ATen/native/npu/**/*.h',
|
|
+ 'include/ATen/npu/*.h',
|
|
+ 'include/ATen/npu/detail/*.h',
|
|
+ 'include/ATen/native/npu/*/*.h',
|
|
'include/ATen/quantized/*.h',
|
|
'include/caffe2/utils/*.h',
|
|
'include/caffe2/utils/**/*.h',
|
|
@@ -898,9 +903,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 +951,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 +967,9 @@
|
|
'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',
|
|
'share/cmake/ATen/*.cmake',
|
|
'share/cmake/Caffe2/*.cmake',
|
|
'share/cmake/Caffe2/public/*.cmake',
|
|
@@ -961,6 +979,7 @@
|
|
'share/cmake/Gloo/*.cmake',
|
|
'share/cmake/Tensorpipe/*.cmake',
|
|
'share/cmake/Torch/*.cmake',
|
|
+ 'contrib/npu/*/*/*.py',
|
|
'utils/benchmark/utils/*.cpp',
|
|
'utils/benchmark/utils/valgrind_wrapper/*.cpp',
|
|
'utils/benchmark/utils/valgrind_wrapper/*.h',
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:24.799537400 +0800
|
|
+++ patch/tools/autograd/templates/python_torch_functions.cpp 2022-02-18 11:07:05.889988500 +0800
|
|
@@ -30,7 +30,7 @@
|
|
#include "torch/csrc/autograd/generated/variable_factories.h"
|
|
#include "torch/csrc/utils/structseq.h"
|
|
#include "torch/csrc/utils/cuda_lazy_init.h"
|
|
-
|
|
+#include "torch/csrc/utils/npu_lazy_init.h"
|
|
#include <ATen/ATen.h>
|
|
|
|
#include <functional>
|
|
@@ -68,6 +68,7 @@
|
|
|
|
inline Tensor dispatch_arange(Scalar end, const TensorOptions& options) {
|
|
torch::utils::maybe_initialize_cuda(options);
|
|
+ torch::utils::maybe_initialize_npu(options);
|
|
pybind11::gil_scoped_release no_gil;
|
|
return torch::arange(end, options);
|
|
}
|
|
@@ -79,6 +80,7 @@
|
|
|
|
inline Tensor dispatch_arange(Scalar start, Scalar end, Scalar step, const TensorOptions& options) {
|
|
torch::utils::maybe_initialize_cuda(options);
|
|
+ torch::utils::maybe_initialize_npu(options);
|
|
pybind11::gil_scoped_release no_gil;
|
|
return torch::arange(start, end, step, options);
|
|
}
|
|
@@ -149,6 +151,7 @@
|
|
|
|
inline Tensor dispatch_range(Scalar start, Scalar end, Scalar step, const TensorOptions& options) {
|
|
torch::utils::maybe_initialize_cuda(options);
|
|
+ torch::utils::maybe_initialize_npu(options);
|
|
pybind11::gil_scoped_release no_gil;
|
|
DeviceGuard device_guard(options.device());
|
|
return torch::range(start, end, step, options);
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:24.799537400 +0800
|
|
+++ patch/tools/autograd/templates/python_variable_methods.cpp 2022-02-18 11:07:05.905614000 +0800
|
|
@@ -21,6 +21,7 @@
|
|
#include "torch/csrc/cuda/Event.h"
|
|
#endif
|
|
#include "torch/csrc/utils/cuda_lazy_init.h"
|
|
+#include "torch/csrc/utils/npu_lazy_init.h"
|
|
#include "torch/csrc/utils/object_ptr.h"
|
|
#include "torch/csrc/utils/pycfunction_helpers.h"
|
|
#include "torch/csrc/utils/python_arg_parser.h"
|
|
@@ -531,6 +532,24 @@
|
|
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");
|
|
+ torch::utils::npu_lazy_init();
|
|
+ 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;
|
|
@@ -938,6 +957,8 @@
|
|
auto& self_ = reinterpret_cast<THPVariable*>(self)->cdata;
|
|
if (device && device->is_cuda()) {
|
|
torch::utils::cuda_lazy_init();
|
|
+ } else if (device && device->is_npu()) {
|
|
+ torch::utils::npu_lazy_init();
|
|
}
|
|
if (!device && !scalarType && !copy && !opt_memory_format.has_value()) {
|
|
Py_INCREF(self);
|
|
@@ -1019,6 +1040,8 @@
|
|
}
|
|
if (device.is_cuda()) {
|
|
torch::utils::cuda_lazy_init();
|
|
+ } else if (device.is_npu()) {
|
|
+ torch::utils::npu_lazy_init();
|
|
}
|
|
return THPVariable_Wrap(dispatch_to(self_, device, scalar_type, /*non_blocking=*/ r.toBool(1), /*copy=*/ false, opt_memory_format));
|
|
END_HANDLE_TH_ERRORS
|
|
@@ -1174,6 +1197,7 @@
|
|
{"cpu", castPyCFunctionWithKeywords(THPVariable_cpu), METH_VARARGS | METH_KEYWORDS, NULL},
|
|
{"cuda", castPyCFunctionWithKeywords(THPVariable_cuda), METH_VARARGS | METH_KEYWORDS, NULL},
|
|
{"xpu", castPyCFunctionWithKeywords(THPVariable_xpu), METH_VARARGS | METH_KEYWORDS, NULL},
|
|
+ {"npu", castPyCFunctionWithKeywords(THPVariable_npu), METH_VARARGS | METH_KEYWORDS, NULL},
|
|
{"data_ptr", THPVariable_data_ptr, METH_NOARGS, NULL},
|
|
{"dim", THPVariable_dim, METH_NOARGS, NULL},
|
|
{"has_names", THPVariable_has_names, METH_NOARGS, NULL},
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/tools/build_variables.bzl patch/tools/build_variables.bzl
|
|
--- pytorch-v1.8.1/tools/build_variables.bzl 2022-02-18 11:15:24.801537500 +0800
|
|
+++ patch/tools/build_variables.bzl 2022-02-18 11:07:05.921238600 +0800
|
|
@@ -362,6 +362,7 @@
|
|
libtorch_cuda_core_sources = [
|
|
"torch/csrc/CudaIPCTypes.cpp",
|
|
"torch/csrc/cuda/comm.cpp",
|
|
+ "torch/csrc/cuda/nccl.cpp",
|
|
"torch/csrc/jit/codegen/fuser/cuda/fused_kernel.cpp",
|
|
"torch/csrc/autograd/profiler_cuda.cpp",
|
|
"torch/csrc/autograd/functions/comm.cpp",
|
|
@@ -563,6 +564,7 @@
|
|
"torch/csrc/utils/throughput_benchmark.cpp",
|
|
"torch/csrc/utils.cpp",
|
|
"torch/csrc/utils/cuda_lazy_init.cpp",
|
|
+ "torch/csrc/utils/npu_lazy_init.cpp",
|
|
"torch/csrc/utils/invalid_arguments.cpp",
|
|
"torch/csrc/utils/object_ptr.cpp",
|
|
"torch/csrc/utils/python_arg_parser.cpp",
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:24.823538100 +0800
|
|
+++ patch/tools/generate_torch_version.py 2022-02-18 11:07:06.158945000 +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=build.sh' '--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-02-18 11:15:24.834536500 +0800
|
|
+++ patch/torch/_C/_autograd.pyi 2022-02-18 11:07:06.268320600 +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=build.sh' '--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-02-18 11:15:24.843540600 +0800
|
|
+++ patch/torch/_tensor_str.py 2022-02-18 11:48:16.196052900 +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=build.sh' '--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-02-18 11:15:24.844540200 +0800
|
|
+++ patch/torch/_utils.py 2022-02-18 11:48:11.749861100 +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
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:24.859537200 +0800
|
|
+++ patch/torch/csrc/DynamicTypes.cpp 2022-02-18 11:48:02.549949100 +0800
|
|
@@ -8,6 +8,7 @@
|
|
#include <torch/csrc/autograd/generated/VariableType.h>
|
|
#include <torch/csrc/utils/cuda_enabled.h>
|
|
#include <torch/csrc/utils/cuda_lazy_init.h>
|
|
+#include <torch/csrc/utils/npu_lazy_init.h>
|
|
#include <torch/csrc/utils/object_ptr.h>
|
|
|
|
#include <ATen/ATen.h>
|
|
@@ -61,9 +62,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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/Generator.cpp patch/torch/csrc/Generator.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/Generator.cpp 2022-02-18 11:15:24.861536600 +0800
|
|
+++ patch/torch/csrc/Generator.cpp 2022-02-18 11:47:52.036507900 +0800
|
|
@@ -18,6 +18,10 @@
|
|
#include <ATen/CUDAGeneratorImpl.h>
|
|
#endif
|
|
|
|
+#ifdef USE_NPU
|
|
+#include <ATen/npu/NPUGeneratorImpl.h>
|
|
+#endif
|
|
+
|
|
using namespace at;
|
|
using namespace torch;
|
|
|
|
@@ -59,6 +63,12 @@
|
|
self->cdata = make_generator<CPUGeneratorImpl>();
|
|
} else if (device.type() == at::kCUDA){
|
|
self->cdata = make_generator<CUDAGeneratorImpl>(device.index());
|
|
+ }
|
|
+#elif USE_NPU
|
|
+ if (device.type() == at::kCPU) {
|
|
+ self->cdata = make_generator<CPUGeneratorImpl>();
|
|
+ } else if (device.type() == at::kNPU){
|
|
+ self->cdata = make_generator<NPUGeneratorImpl>(device.index());
|
|
} else {
|
|
AT_ERROR("Device type ", c10::DeviceTypeName(device.type()),
|
|
" is not supported for torch.Generator() api.");
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:24.942536800 +0800
|
|
+++ patch/torch/csrc/autograd/engine.cpp 2022-02-18 11:47:56.387125200 +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=build.sh' '--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-02-18 11:15:24.948536800 +0800
|
|
+++ patch/torch/csrc/autograd/functions/tensor.cpp 2022-02-18 11:47:28.795845400 +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=build.sh' '--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-02-18 11:15:24.949536400 +0800
|
|
+++ patch/torch/csrc/autograd/input_buffer.cpp 2022-02-18 11:47:48.229510000 +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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/autograd/profiler_legacy.cpp patch/torch/csrc/autograd/profiler_legacy.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/autograd/profiler_legacy.cpp 2022-02-18 11:15:24.951536400 +0800
|
|
+++ patch/torch/csrc/autograd/profiler_legacy.cpp 2022-02-18 11:07:07.606514600 +0800
|
|
@@ -418,7 +418,7 @@
|
|
auto state_ptr = getProfilerTLSState();
|
|
TORCH_INTERNAL_ASSERT(state_ptr, "Expected profiler state set");
|
|
auto handle = at::addThreadLocalCallback(at::RecordFunctionCallback(
|
|
- [](const at::RecordFunction& fn) -> std::unique_ptr<at::ObserverContext> {
|
|
+ [](at::RecordFunction& fn) -> std::unique_ptr<at::ObserverContext> {
|
|
auto state_ptr = getProfilerTLSState();
|
|
if (!state_ptr || state_ptr->config().state == ProfilerState::Disabled) {
|
|
return nullptr;
|
|
@@ -439,7 +439,7 @@
|
|
|
|
return nullptr;
|
|
},
|
|
- [](const at::RecordFunction& fn, at::ObserverContext*) {
|
|
+ [](at::RecordFunction& fn, at::ObserverContext*) {
|
|
auto state_ptr = getProfilerTLSState();
|
|
if (!state_ptr || state_ptr->config().state == ProfilerState::Disabled) {
|
|
return;
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/autograd/python_variable.cpp patch/torch/csrc/autograd/python_variable.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/autograd/python_variable.cpp 2022-02-18 11:15:24.958538500 +0800
|
|
+++ patch/torch/csrc/autograd/python_variable.cpp 2022-02-18 11:47:33.741315900 +0800
|
|
@@ -20,6 +20,7 @@
|
|
#include <torch/csrc/tensor/python_tensor.h>
|
|
#include <pybind11/pybind11.h>
|
|
#include <torch/csrc/utils/cuda_lazy_init.h>
|
|
+#include <torch/csrc/utils/npu_lazy_init.h>
|
|
#include <torch/csrc/utils/pybind.h>
|
|
#include <torch/csrc/utils/pycfunction_helpers.h>
|
|
#include <torch/csrc/utils/python_strings.h>
|
|
@@ -561,6 +562,14 @@
|
|
END_HANDLE_TH_ERRORS
|
|
}
|
|
|
|
+PyObject *THPVariable_is_npu(THPVariable *self, void *unused)
|
|
+{
|
|
+ HANDLE_TH_ERRORS
|
|
+ auto& self_ = self->cdata;
|
|
+ return torch::autograd::utils::wrap(self_.is_npu());
|
|
+ END_HANDLE_TH_ERRORS
|
|
+}
|
|
+
|
|
PyObject *THPVariable_is_sparse(THPVariable *self, void *unused)
|
|
{
|
|
HANDLE_TH_ERRORS
|
|
@@ -721,6 +730,7 @@
|
|
{"name", (getter)THPVariable_get_name, nullptr, nullptr, nullptr},
|
|
{"shape", (getter)THPVariable_get_shape, nullptr, nullptr, nullptr},
|
|
{"is_cuda", (getter)THPVariable_is_cuda, nullptr, nullptr, nullptr},
|
|
+ {"is_npu", (getter)THPVariable_is_npu, nullptr, nullptr, nullptr},
|
|
{"is_xpu", (getter)THPVariable_is_xpu, nullptr, nullptr, nullptr},
|
|
{"is_sparse", (getter)THPVariable_is_sparse, nullptr, nullptr, nullptr},
|
|
{"is_mkldnn", (getter)THPVariable_is_mkldnn, nullptr, nullptr, nullptr},
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:24.959537300 +0800
|
|
+++ patch/torch/csrc/autograd/python_variable_indexing.cpp 2022-02-18 11:47:39.127862400 +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=build.sh' '--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-02-18 11:15:25.218536400 +0800
|
|
+++ patch/torch/csrc/tensor/python_tensor.cpp 2022-02-18 11:47:24.165010700 +0800
|
|
@@ -13,6 +13,7 @@
|
|
#include <torch/csrc/autograd/utils/wrap_outputs.h>
|
|
#include <torch/csrc/utils/cuda_enabled.h>
|
|
#include <torch/csrc/utils/cuda_lazy_init.h>
|
|
+#include <torch/csrc/utils/npu_lazy_init.h>
|
|
#include <torch/csrc/utils/python_strings.h>
|
|
#include <torch/csrc/utils/tensor_new.h>
|
|
#include <torch/csrc/utils/tensor_types.h>
|
|
@@ -185,6 +186,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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/utils/npu_lazy_init.cpp patch/torch/csrc/utils/npu_lazy_init.cpp
|
|
--- pytorch-v1.8.1/torch/csrc/utils/npu_lazy_init.cpp 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/torch/csrc/utils/npu_lazy_init.cpp 2022-02-18 11:47:14.369738300 +0800
|
|
@@ -0,0 +1,34 @@
|
|
+#include <torch/csrc/utils/npu_lazy_init.h>
|
|
+
|
|
+#include <torch/csrc/python_headers.h>
|
|
+#include <mutex>
|
|
+
|
|
+#include <torch/csrc/Exceptions.h>
|
|
+#include <torch/csrc/utils/object_ptr.h>
|
|
+namespace torch {
|
|
+namespace utils {
|
|
+
|
|
+static bool npu_run_yet = false;
|
|
+
|
|
+void npu_lazy_init() {
|
|
+ AutoGIL g;
|
|
+ // Protected by the GIL. We don't use call_once because under ASAN it
|
|
+ // has a buggy implementation that deadlocks if an instance throws an
|
|
+ // exception. In any case, call_once isn't necessary, because we
|
|
+ // have taken a lock.
|
|
+ if (!npu_run_yet) {
|
|
+ auto module = THPObjectPtr(PyImport_ImportModule("torch.npu"));
|
|
+ if (!module) throw python_error();
|
|
+ auto res = THPObjectPtr(PyObject_CallMethod(module.get(), "_lazy_init", ""));
|
|
+ if (!res) throw python_error();
|
|
+ npu_run_yet = true;
|
|
+ }
|
|
+}
|
|
+
|
|
+void npu_set_run_yet_variable_to_false() {
|
|
+ npu_run_yet = false;
|
|
+}
|
|
+
|
|
+}
|
|
+}
|
|
+
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/csrc/utils/npu_lazy_init.h patch/torch/csrc/utils/npu_lazy_init.h
|
|
--- pytorch-v1.8.1/torch/csrc/utils/npu_lazy_init.h 1970-01-01 08:00:00.000000000 +0800
|
|
+++ patch/torch/csrc/utils/npu_lazy_init.h 2022-02-18 11:47:19.661754600 +0800
|
|
@@ -0,0 +1,33 @@
|
|
+#pragma once
|
|
+
|
|
+#include <c10/core/TensorOptions.h>
|
|
+
|
|
+// npu_lazy_init() is always compiled, even for CPU-only builds.
|
|
+// Thus, it does not live in the npu/ folder.
|
|
+
|
|
+namespace torch {
|
|
+namespace utils {
|
|
+
|
|
+// The INVARIANT is that this function MUST be called before you attempt
|
|
+// to get a NPU Type object from ATen, in any way. Here are some common
|
|
+// ways that a Type object may be retrieved:
|
|
+//
|
|
+// - You call getNonVariableType or getNonVariableTypeOpt
|
|
+// - You call toBackend() on a Type
|
|
+//
|
|
+// It's important to do this correctly, because if you forget to add it
|
|
+// you'll get an oblique error message about "Cannot initialize NPU without
|
|
+// ATen_cuda library" if you try to use NPU functionality from a CPU-only
|
|
+// build, which is not good UX.
|
|
+//
|
|
+void npu_lazy_init();
|
|
+void npu_set_run_yet_variable_to_false();
|
|
+
|
|
+static void maybe_initialize_npu(const at::TensorOptions& options) {
|
|
+ if (options.device().is_npu()) {
|
|
+ torch::utils::npu_lazy_init();
|
|
+ }
|
|
+}
|
|
+
|
|
+}
|
|
+}
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:25.226537000 +0800
|
|
+++ patch/torch/csrc/utils/python_arg_parser.h 2022-02-18 11:47:06.244657600 +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=build.sh' '--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-02-18 11:15:25.233536800 +0800
|
|
+++ patch/torch/csrc/utils/tensor_new.cpp 2022-02-18 11:47:10.216734000 +0800
|
|
@@ -7,6 +7,7 @@
|
|
#include <torch/csrc/Size.h>
|
|
#include <torch/csrc/autograd/variable.h>
|
|
#include <torch/csrc/utils/cuda_lazy_init.h>
|
|
+#include <torch/csrc/utils/npu_lazy_init.h>
|
|
#include <torch/csrc/utils/numpy_stub.h>
|
|
#include <torch/csrc/utils/python_arg_parser.h>
|
|
#include <torch/csrc/utils/python_numbers.h>
|
|
@@ -32,6 +33,7 @@
|
|
using at::IntArrayRef;
|
|
using at::kCPU;
|
|
using at::kCUDA;
|
|
+using at::kNPU;
|
|
using at::kLong;
|
|
using at::Scalar;
|
|
using at::ScalarType;
|
|
@@ -51,6 +53,8 @@
|
|
return backendToCPU(b);
|
|
case DeviceType::CUDA:
|
|
return backendToCUDA(b);
|
|
+ case DeviceType::NPU:
|
|
+ return Backend::NPU;
|
|
case DeviceType::HIP:
|
|
return backendToHIP(b);
|
|
case DeviceType::MSNPU:
|
|
@@ -88,26 +92,42 @@
|
|
}
|
|
}
|
|
|
|
+void maybe_initialize_npu(c10::DispatchKey dispatch_key) {
|
|
+ if (backendToDeviceType(dispatchKeyToBackend(dispatch_key)) == kNPU) {
|
|
+ torch::utils::npu_lazy_init();
|
|
+ }
|
|
+}
|
|
+
|
|
+void maybe_initialize_npu(const Device device) {
|
|
+ if (device.is_npu()) {
|
|
+ torch::utils::npu_lazy_init();
|
|
+ }
|
|
+}
|
|
+
|
|
Tensor dispatch_zeros(c10::DispatchKey dispatch_key, at::ScalarType scalar_type, const optional<Device>& device, IntArrayRef sizes) {
|
|
maybe_initialize_cuda(dispatch_key);
|
|
+ maybe_initialize_npu(dispatch_key);
|
|
pybind11::gil_scoped_release no_gil;
|
|
return torch::zeros(sizes, options(dispatch_key, scalar_type, device));
|
|
}
|
|
|
|
Tensor dispatch_ones(c10::DispatchKey dispatch_key, at::ScalarType scalar_type, const optional<Device>& device, IntArrayRef sizes) {
|
|
maybe_initialize_cuda(dispatch_key);
|
|
+ maybe_initialize_npu(dispatch_key);
|
|
pybind11::gil_scoped_release no_gil;
|
|
return torch::ones(sizes, options(dispatch_key, scalar_type, device));
|
|
}
|
|
|
|
Tensor dispatch_full(c10::DispatchKey dispatch_key, at::ScalarType scalar_type, Scalar fill_value, const optional<Device>& device, IntArrayRef sizes) {
|
|
maybe_initialize_cuda(dispatch_key);
|
|
+ maybe_initialize_npu(dispatch_key);
|
|
pybind11::gil_scoped_release no_gil;
|
|
return torch::full(sizes, fill_value, options(dispatch_key, scalar_type, device));
|
|
}
|
|
|
|
Tensor new_with_sizes(c10::DispatchKey dispatch_key, at::ScalarType scalar_type, const optional<Device>& device, IntArrayRef sizes) {
|
|
maybe_initialize_cuda(dispatch_key);
|
|
+ maybe_initialize_npu(dispatch_key);
|
|
pybind11::gil_scoped_release no_gil;
|
|
return torch::empty(sizes, options(dispatch_key, scalar_type, device));
|
|
}
|
|
@@ -256,6 +276,7 @@
|
|
auto device = device_opt.has_value() ? *device_opt : var.device();
|
|
pybind11::gil_scoped_release no_gil;
|
|
maybe_initialize_cuda(device);
|
|
+ maybe_initialize_npu(device);
|
|
return var.to(device, inferred_scalar_type, /*non_blocking=*/false, /*copy=*/copy_variables);
|
|
}
|
|
|
|
@@ -267,6 +288,7 @@
|
|
auto device = device_opt.has_value() ? *device_opt : at::Device(computeDeviceType(dispatch_key));
|
|
pybind11::gil_scoped_release no_gil;
|
|
maybe_initialize_cuda(device);
|
|
+ maybe_initialize_npu(device);
|
|
return tensor.to(device, inferred_scalar_type, /*non_blocking=*/false, /*copy=*/copy_numpy);
|
|
}
|
|
|
|
@@ -277,6 +299,7 @@
|
|
auto device = device_opt.has_value() ? *device_opt : at::Device(computeDeviceType(dispatch_key));
|
|
pybind11::gil_scoped_release no_gil;
|
|
maybe_initialize_cuda(device);
|
|
+ maybe_initialize_npu(device);
|
|
return tensor.to(device, inferred_scalar_type, /*non_blocking=*/false, /*copy=*/copy_numpy);
|
|
}
|
|
#endif
|
|
@@ -298,6 +321,7 @@
|
|
auto device = device_opt.has_value() ? *device_opt : at::Device(computeDeviceType(dispatch_key));
|
|
pybind11::gil_scoped_release no_gil;
|
|
maybe_initialize_cuda(device);
|
|
+ maybe_initialize_npu(device);
|
|
// However, it is VERY important that we trace the to() call here (even
|
|
// though the reason this is important is a hack). Without *some* factory
|
|
// function call that is traced at construction time, we will consider
|
|
@@ -351,6 +375,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=build.sh' '--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-02-18 11:15:25.235539000 +0800
|
|
+++ patch/torch/csrc/utils/tensor_types.cpp 2022-02-18 11:47:01.177808700 +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=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/lib/c10d/CMakeLists.txt patch/torch/lib/c10d/CMakeLists.txt
|
|
--- pytorch-v1.8.1/torch/lib/c10d/CMakeLists.txt 2022-02-18 11:15:25.297536500 +0800
|
|
+++ patch/torch/lib/c10d/CMakeLists.txt 2022-02-18 11:07:11.626276800 +0800
|
|
@@ -127,6 +127,9 @@
|
|
copy_header(TCPStore.hpp)
|
|
copy_header(Types.hpp)
|
|
copy_header(Utils.hpp)
|
|
+copy_header(frontend.hpp)
|
|
+copy_header(default_comm_hooks.hpp)
|
|
+copy_header(comm.hpp)
|
|
if(USE_GLOO)
|
|
copy_header(ProcessGroupGloo.hpp)
|
|
copy_header(GlooDeviceFactory.hpp)
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--exclude=third_party' '--exclude=README*' -Nur pytorch-v1.8.1/torch/lib/c10d/frontend.hpp patch/torch/lib/c10d/frontend.hpp
|
|
--- pytorch-v1.8.1/torch/lib/c10d/frontend.hpp 2022-02-18 11:15:25.309538200 +0800
|
|
+++ patch/torch/lib/c10d/frontend.hpp 2022-02-18 11:07:11.769277100 +0800
|
|
@@ -2,9 +2,8 @@
|
|
|
|
#include <ATen/ATen.h>
|
|
#include <c10/util/Optional.h>
|
|
-#include <torch/lib/c10d/ProcessGroup.hpp>
|
|
-#include <torch/lib/c10d/Store.hpp>
|
|
-#include <torch/lib/c10d/Types.hpp>
|
|
+#include <c10d/ProcessGroup.hpp>
|
|
+#include <c10d/Store.hpp>
|
|
|
|
#include <chrono>
|
|
#include <memory>
|
|
diff -Nur '--exclude=.git*' '--exclude=OWNERS' '--exclude=access_control_test.py' '--exclude=build.sh' '--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-02-18 11:15:25.315537000 +0800
|
|
+++ patch/torch/lib/libshm/CMakeLists.txt 2022-02-18 11:07:11.831276800 +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=build.sh' '--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-02-18 14:29:46.034341500 +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=build.sh' '--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-02-18 11:15:25.392538400 +0800
|
|
+++ patch/torch/storage.py 2022-02-18 11:07:12.822258300 +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=build.sh' '--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-02-18 11:15:25.393537900 +0800
|
|
+++ patch/torch/tensor.py 2022-02-18 11:48:07.181584500 +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:
|
|
@@ -123,6 +125,17 @@
|
|
str(self.device),
|
|
self.requires_grad)
|
|
return (torch._utils._rebuild_xla_tensor, arg_xla)
|
|
+ if self.device.type == 'npu':
|
|
+ origin_format = self.storage().npu_format()
|
|
+ if origin_format != 2:
|
|
+ self = self.npu_format_cast(2)
|
|
+ args = (self.storage(),
|
|
+ self.storage_offset(),
|
|
+ tuple(self.size()),
|
|
+ self.stride(),
|
|
+ self.requires_grad,
|
|
+ OrderedDict())
|
|
+ return (torch._utils._rebuild_tensor_v2, args)
|
|
if self.is_quantized:
|
|
# quantizer_params can be different type based on torch attribute
|
|
quantizer_params: Union[Tuple[torch.qscheme, float, int], Tuple[Any, Tensor, Tensor, int]]
|
|
@@ -382,7 +395,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=build.sh' '--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-02-18 11:15:25.430538000 +0800
|
|
+++ patch/torch/utils/data/_utils/pin_memory.py 2022-02-18 11:46:33.377783300 +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=build.sh' '--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-02-18 11:15:25.431537600 +0800
|
|
+++ patch/torch/utils/data/dataloader.py 2022-02-18 11:46:39.219977800 +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()
|