jasonfan commited on
Commit
8fa975c
·
verified ·
1 Parent(s): 8ccd33f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/HPUHooksInterface.h +62 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/IPUHooksInterface.h +48 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/MAIAHooksInterface.h +47 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/MPSHooksInterface.h +130 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/MTIAHooksInterface.h +218 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/PrivateUse1HooksInterface.h +94 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/XLAHooksInterface.h +84 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/XPUHooksInterface.h +89 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/ADInterpreters.h +43 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchRulesHelper.h +486 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchedFallback.h +86 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchedTensorImpl.h +181 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchingMetaprogramming.h +131 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/DynamicLayer.h +129 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/FunctionalizeInterpreter.h +27 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/Interpreter.h +358 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/LegacyVmapTransforms.h +192 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/Macros.h +8 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/PlumbingHelper.h +68 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/TensorWrapper.h +108 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/VmapInterpreter.h +30 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h +248 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h +203 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h +388 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h +140 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/metal/Context.h +37 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Descriptors.h +210 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Exceptions.h +46 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Handle.h +14 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Types.h +18 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Utils.h +23 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/miopen-wrapper.h +26 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/EmptyTensor.h +33 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/IndexKernels.h +225 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocator.h +442 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocatorInterface.h +73 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSDevice.h +90 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSEvent.h +110 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGeneratorImpl.h +66 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGuardImpl.h +187 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSHooks.h +76 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSProfiler.h +472 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSStream.h +171 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/Activation.h +78 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/AdaptivePooling.h +54 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/AmpKernels.h +33 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h +337 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h +124 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/BucketizationUtils.h +178 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/CPUBlas.h +319 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/HPUHooksInterface.h ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Generator.h>
5
+ #include <ATen/detail/AcceleratorHooksInterface.h>
6
+
7
+ #include <c10/core/Allocator.h>
8
+ #include <c10/core/Device.h>
9
+ #include <c10/util/Registry.h>
10
+
11
+ namespace at {
12
+
13
+ struct TORCH_API HPUHooksInterface : AcceleratorHooksInterface {
14
+ ~HPUHooksInterface() override = default;
15
+
16
+ void init() const override {
17
+ TORCH_CHECK(false, "Cannot initialize HPU without HPU backend");
18
+ }
19
+
20
+ virtual bool hasHPU() const {
21
+ return false;
22
+ }
23
+
24
+ Device getDeviceFromPtr(void* /*data*/) const override {
25
+ TORCH_CHECK(
26
+ false, "Cannot get device of pointer on HPU without HPU backend");
27
+ }
28
+
29
+ bool isPinnedPtr(const void* /*data*/) const override {
30
+ return false;
31
+ }
32
+
33
+ Allocator* getPinnedMemoryAllocator() const override {
34
+ TORCH_CHECK(
35
+ false,
36
+ "You should register `HPUHooksInterface` for HPU before call `getPinnedMemoryAllocator`.");
37
+ }
38
+
39
+ bool hasPrimaryContext(
40
+ [[maybe_unused]] DeviceIndex device_index) const override {
41
+ TORCH_CHECK(
42
+ false,
43
+ "You should register `HPUHooksInterface` for HPU before call `hasPrimaryContext`.");
44
+ }
45
+ };
46
+
47
+ struct TORCH_API HPUHooksArgs {};
48
+
49
+ TORCH_DECLARE_REGISTRY(HPUHooksRegistry, HPUHooksInterface, HPUHooksArgs);
50
+ #define REGISTER_HPU_HOOKS(clsname) \
51
+ C10_REGISTER_CLASS(HPUHooksRegistry, clsname, clsname)
52
+
53
+ namespace detail {
54
+
55
+ TORCH_API const at::HPUHooksInterface& getHPUHooks();
56
+
57
+ } // namespace detail
58
+ } // namespace at
59
+
60
+ #else
61
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
62
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/IPUHooksInterface.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/detail/AcceleratorHooksInterface.h>
5
+
6
+ #include <c10/core/Allocator.h>
7
+ #include <c10/util/Exception.h>
8
+ #include <c10/util/Registry.h>
9
+
10
+ namespace at {
11
+
12
+ struct TORCH_API IPUHooksInterface : AcceleratorHooksInterface {
13
+ ~IPUHooksInterface() override = default;
14
+
15
+ void init() const override {
16
+ TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library.");
17
+ }
18
+
19
+ bool hasPrimaryContext(DeviceIndex /*device_index*/) const override {
20
+ TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library.");
21
+ return false;
22
+ }
23
+
24
+ const Generator& getDefaultGenerator(
25
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
26
+ TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library.");
27
+ }
28
+
29
+ Generator getNewGenerator(
30
+ DeviceIndex /*device_index*/ = -1) const override {
31
+ TORCH_CHECK(false, "Cannot initialize IPU without ATen_ipu library.");
32
+ }
33
+ };
34
+
35
+ struct TORCH_API IPUHooksArgs {};
36
+
37
+ TORCH_DECLARE_REGISTRY(IPUHooksRegistry, IPUHooksInterface, IPUHooksArgs);
38
+ #define REGISTER_IPU_HOOKS(clsname) \
39
+ C10_REGISTER_CLASS(IPUHooksRegistry, clsname, clsname)
40
+
41
+ namespace detail {
42
+ TORCH_API const IPUHooksInterface& getIPUHooks();
43
+ } // namespace detail
44
+ } // namespace at
45
+
46
+ #else
47
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
48
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/MAIAHooksInterface.h ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/util/Exception.h>
5
+ #include <c10/util/Registry.h>
6
+
7
+ #include <ATen/detail/AcceleratorHooksInterface.h>
8
+
9
+ // NB: Class must live in `at` due to limitations of Registry.h.
10
+ namespace at {
11
+
12
+ struct TORCH_API MAIAHooksInterface : AcceleratorHooksInterface {
13
+ // This should never actually be implemented, but it is used to
14
+ // squelch -Werror=non-virtual-dtor
15
+ ~MAIAHooksInterface() override = default;
16
+
17
+ void init() const override {
18
+ TORCH_CHECK(false, "Cannot initialize MAIA without ATen_maia library.");
19
+ }
20
+
21
+ bool hasPrimaryContext(DeviceIndex /*device_index*/) const override {
22
+ TORCH_CHECK(false, "Cannot initialize MAIA without ATen_maia library.");
23
+ return false;
24
+ }
25
+
26
+ virtual std::string showConfig() const {
27
+ TORCH_CHECK(false, "Cannot query detailed MAIA version information.");
28
+ }
29
+ };
30
+
31
+ // NB: dummy argument to suppress "ISO C++11 requires at least one argument
32
+ // for the "..." in a variadic macro"
33
+ struct TORCH_API MAIAHooksArgs {};
34
+
35
+ TORCH_DECLARE_REGISTRY(MAIAHooksRegistry, MAIAHooksInterface, MAIAHooksArgs);
36
+ #define REGISTER_MAIA_HOOKS(clsname) \
37
+ C10_REGISTER_CLASS(MAIAHooksRegistry, clsname, clsname)
38
+
39
+ namespace detail {
40
+ TORCH_API const MAIAHooksInterface& getMAIAHooks();
41
+ } // namespace detail
42
+
43
+ } // namespace at
44
+
45
+ #else
46
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
47
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/MPSHooksInterface.h ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/detail/AcceleratorHooksInterface.h>
7
+
8
+ #include <c10/core/Allocator.h>
9
+ #include <c10/util/Exception.h>
10
+ #include <c10/util/Registry.h>
11
+
12
+ #include <cstddef>
13
+
14
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter")
15
+ namespace at {
16
+
17
+ struct TORCH_API MPSHooksInterface : AcceleratorHooksInterface {
18
+ // this fails the implementation if MPSHooks functions are called, but
19
+ // MPS backend is not present.
20
+ #define FAIL_MPSHOOKS_FUNC(func) \
21
+ TORCH_CHECK(false, "Cannot execute ", func, "() without MPS backend.");
22
+
23
+ ~MPSHooksInterface() override = default;
24
+
25
+ // Initialize the MPS library state
26
+ void init() const override {
27
+ FAIL_MPSHOOKS_FUNC(__func__);
28
+ }
29
+ virtual bool hasMPS() const {
30
+ return false;
31
+ }
32
+ virtual bool isOnMacOSorNewer(unsigned major = 13, unsigned minor = 0) const {
33
+ FAIL_MPSHOOKS_FUNC(__func__);
34
+ }
35
+ const Generator& getDefaultGenerator(
36
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
37
+ FAIL_MPSHOOKS_FUNC(__func__);
38
+ }
39
+ Generator getNewGenerator(
40
+ [[maybe_unused]] DeviceIndex device_index) const override {
41
+ FAIL_MPSHOOKS_FUNC(__func__);
42
+ }
43
+ virtual Allocator* getMPSDeviceAllocator() const {
44
+ FAIL_MPSHOOKS_FUNC(__func__);
45
+ }
46
+ virtual void deviceSynchronize() const {
47
+ FAIL_MPSHOOKS_FUNC(__func__);
48
+ }
49
+ virtual void commitStream() const {
50
+ FAIL_MPSHOOKS_FUNC(__func__);
51
+ }
52
+ virtual void* getCommandBuffer() const {
53
+ FAIL_MPSHOOKS_FUNC(__func__);
54
+ }
55
+ virtual void* getDispatchQueue() const {
56
+ FAIL_MPSHOOKS_FUNC(__func__);
57
+ }
58
+ virtual void emptyCache() const {
59
+ FAIL_MPSHOOKS_FUNC(__func__);
60
+ }
61
+ virtual size_t getCurrentAllocatedMemory() const {
62
+ FAIL_MPSHOOKS_FUNC(__func__);
63
+ }
64
+ virtual size_t getDriverAllocatedMemory() const {
65
+ FAIL_MPSHOOKS_FUNC(__func__);
66
+ }
67
+ virtual size_t getRecommendedMaxMemory() const {
68
+ FAIL_MPSHOOKS_FUNC(__func__);
69
+ }
70
+ virtual void setMemoryFraction(double /*ratio*/) const {
71
+ FAIL_MPSHOOKS_FUNC(__func__);
72
+ }
73
+ virtual void profilerStartTrace(const std::string& mode, bool waitUntilCompleted) const {
74
+ FAIL_MPSHOOKS_FUNC(__func__);
75
+ }
76
+ virtual void profilerStopTrace() const {
77
+ FAIL_MPSHOOKS_FUNC(__func__);
78
+ }
79
+ virtual uint32_t acquireEvent(bool enable_timing) const {
80
+ FAIL_MPSHOOKS_FUNC(__func__);
81
+ }
82
+ Device getDeviceFromPtr(void* data) const override {
83
+ TORCH_CHECK(false, "Cannot get device of pointer on MPS without ATen_mps library. ");
84
+ }
85
+ virtual void releaseEvent(uint32_t event_id) const {
86
+ FAIL_MPSHOOKS_FUNC(__func__);
87
+ }
88
+ virtual void recordEvent(uint32_t event_id) const {
89
+ FAIL_MPSHOOKS_FUNC(__func__);
90
+ }
91
+ virtual void waitForEvent(uint32_t event_id) const {
92
+ FAIL_MPSHOOKS_FUNC(__func__);
93
+ }
94
+ virtual void synchronizeEvent(uint32_t event_id) const {
95
+ FAIL_MPSHOOKS_FUNC(__func__);
96
+ }
97
+ virtual bool queryEvent(uint32_t event_id) const {
98
+ FAIL_MPSHOOKS_FUNC(__func__);
99
+ }
100
+ virtual double elapsedTimeOfEvents(uint32_t start_event_id, uint32_t end_event_id) const {
101
+ FAIL_MPSHOOKS_FUNC(__func__);
102
+ }
103
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
104
+ FAIL_MPSHOOKS_FUNC(__func__);
105
+ }
106
+ bool isPinnedPtr(const void* data) const override {
107
+ return false;
108
+ }
109
+ Allocator* getPinnedMemoryAllocator() const override {
110
+ FAIL_MPSHOOKS_FUNC(__func__);
111
+ }
112
+ #undef FAIL_MPSHOOKS_FUNC
113
+ };
114
+
115
+ struct TORCH_API MPSHooksArgs {};
116
+
117
+ TORCH_DECLARE_REGISTRY(MPSHooksRegistry, MPSHooksInterface, MPSHooksArgs);
118
+ #define REGISTER_MPS_HOOKS(clsname) \
119
+ C10_REGISTER_CLASS(MPSHooksRegistry, clsname, clsname)
120
+
121
+ namespace detail {
122
+ TORCH_API const MPSHooksInterface& getMPSHooks();
123
+
124
+ } // namespace detail
125
+ } // namespace at
126
+ C10_DIAGNOSTIC_POP()
127
+
128
+ #else
129
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
130
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/MTIAHooksInterface.h ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/core/CachingDeviceAllocator.h>
5
+ #include <c10/core/Device.h>
6
+ #include <c10/util/Exception.h>
7
+
8
+ #include <c10/core/Stream.h>
9
+ #include <c10/util/Registry.h>
10
+
11
+ #include <c10/core/Allocator.h>
12
+
13
+ #include <ATen/detail/AcceleratorHooksInterface.h>
14
+ #include <c10/util/python_stub.h>
15
+
16
+ #include <string>
17
+ namespace at {
18
+ class Context;
19
+ }
20
+
21
+ namespace at {
22
+ constexpr const char* MTIA_HELP =
23
+ "The MTIA backend requires MTIA extension for PyTorch;"
24
+ "this error has occurred because you are trying "
25
+ "to use some MTIA's functionality without MTIA extension included.";
26
+
27
+ struct TORCH_API MTIAHooksInterface : AcceleratorHooksInterface {
28
+ // this fails the implementation if MTIAHooks functions are called, but
29
+ // MTIA backend is not present.
30
+ #define FAIL_MTIAHOOKS_FUNC(func) TORCH_CHECK(false, "Cannot execute ", func, "() without MTIA backend.");
31
+
32
+ ~MTIAHooksInterface() override = default;
33
+
34
+ void init() const override {
35
+ // Avoid logging here, since MTIA needs init devices first then it will know
36
+ // how many devices are available. Make it as no-op if mtia extension is not
37
+ // dynamically loaded.
38
+ return;
39
+ }
40
+
41
+ virtual bool hasMTIA() const {
42
+ return false;
43
+ }
44
+
45
+ DeviceIndex deviceCount() const override {
46
+ return 0;
47
+ }
48
+
49
+ virtual void deviceSynchronize(c10::DeviceIndex /*device_index*/) const {
50
+ FAIL_MTIAHOOKS_FUNC(__func__);
51
+ }
52
+
53
+ virtual std::string showConfig() const {
54
+ FAIL_MTIAHOOKS_FUNC(__func__);
55
+ }
56
+
57
+ bool hasPrimaryContext(DeviceIndex /*device_index*/) const override {
58
+ return false;
59
+ }
60
+
61
+ void setCurrentDevice(DeviceIndex /*device*/) const override {
62
+ FAIL_MTIAHOOKS_FUNC(__func__);
63
+ }
64
+
65
+ DeviceIndex getCurrentDevice() const override {
66
+ FAIL_MTIAHOOKS_FUNC(__func__);
67
+ return -1;
68
+ }
69
+
70
+ DeviceIndex exchangeDevice(DeviceIndex /*device*/) const override {
71
+ FAIL_MTIAHOOKS_FUNC(__func__);
72
+ return -1;
73
+ }
74
+
75
+ DeviceIndex maybeExchangeDevice(DeviceIndex /*device*/) const override {
76
+ FAIL_MTIAHOOKS_FUNC(__func__);
77
+ return -1;
78
+ }
79
+
80
+ virtual c10::Stream getCurrentStream(DeviceIndex /*device*/) const {
81
+ FAIL_MTIAHOOKS_FUNC(__func__);
82
+ return c10::Stream::unpack3(-1, 0, c10::DeviceType::MTIA);
83
+ }
84
+
85
+ virtual int64_t getCurrentRawStream(DeviceIndex /*device*/) const {
86
+ FAIL_MTIAHOOKS_FUNC(__func__);
87
+ return -1;
88
+ }
89
+
90
+ virtual c10::Stream getDefaultStream(DeviceIndex /*device*/) const {
91
+ FAIL_MTIAHOOKS_FUNC(__func__);
92
+ return c10::Stream::unpack3(-1, 0, c10::DeviceType::MTIA);
93
+ }
94
+
95
+ virtual void setCurrentStream(const c10::Stream& /*stream*/) const {
96
+ FAIL_MTIAHOOKS_FUNC(__func__);
97
+ }
98
+
99
+ bool isPinnedPtr(const void* /*data*/) const override {
100
+ return false;
101
+ }
102
+
103
+ Allocator* getPinnedMemoryAllocator() const override {
104
+ FAIL_MTIAHOOKS_FUNC(__func__);
105
+ return nullptr;
106
+ }
107
+
108
+ virtual PyObject* memoryStats(DeviceIndex /*device*/) const {
109
+ FAIL_MTIAHOOKS_FUNC(__func__);
110
+ return nullptr;
111
+ }
112
+
113
+ virtual PyObject* getDeviceCapability(DeviceIndex /*device*/) const {
114
+ FAIL_MTIAHOOKS_FUNC(__func__);
115
+ return nullptr;
116
+ }
117
+
118
+ virtual PyObject* getDeviceProperties(DeviceIndex device) const {
119
+ FAIL_MTIAHOOKS_FUNC(__func__);
120
+ return nullptr;
121
+ }
122
+
123
+ virtual void emptyCache() const {
124
+ FAIL_MTIAHOOKS_FUNC(__func__);
125
+ }
126
+
127
+ virtual void recordMemoryHistory(const std::optional<std::string>& /*enabled*/,
128
+ const std::string& /*stacks*/,
129
+ size_t /*max_entries*/) const {
130
+ FAIL_MTIAHOOKS_FUNC(__func__);
131
+ }
132
+
133
+ virtual PyObject* memorySnapshot(const std::optional<std::string>& local_path) const {
134
+ FAIL_MTIAHOOKS_FUNC(__func__);
135
+ return nullptr;
136
+ }
137
+
138
+ virtual DeviceIndex getDeviceCount() const {
139
+ FAIL_MTIAHOOKS_FUNC(__func__);
140
+ return 0;
141
+ }
142
+
143
+ virtual void resetPeakMemoryStats(DeviceIndex /*device*/) const {
144
+ FAIL_MTIAHOOKS_FUNC(__func__);
145
+ }
146
+
147
+ virtual void attachOutOfMemoryObserver(PyObject* observer) const {
148
+ FAIL_MTIAHOOKS_FUNC(__func__);
149
+ return;
150
+ }
151
+
152
+ virtual bool isAvailable() const override;
153
+
154
+ /* MTIAGraph related APIs */
155
+ virtual int64_t mtiagraphCreate(bool keep_graph = false) const {
156
+ FAIL_MTIAHOOKS_FUNC(__func__);
157
+ return -1;
158
+ }
159
+
160
+ virtual void mtiagraphDestroy(int64_t handle) const {
161
+ FAIL_MTIAHOOKS_FUNC(__func__);
162
+ }
163
+
164
+ virtual void mtiagraphCaptureBegin(int64_t handle, MempoolId_t pool) const {
165
+ FAIL_MTIAHOOKS_FUNC(__func__);
166
+ }
167
+
168
+ virtual void mtiagraphCaptureEnd(int64_t handle) const {
169
+ FAIL_MTIAHOOKS_FUNC(__func__);
170
+ }
171
+
172
+ virtual void mtiagraphInstantiate(int64_t handle) const {
173
+ FAIL_MTIAHOOKS_FUNC(__func__);
174
+ }
175
+
176
+ virtual void mtiagraphReplay(int64_t handle) const {
177
+ FAIL_MTIAHOOKS_FUNC(__func__);
178
+ }
179
+
180
+ virtual void mtiagraphReset(int64_t handle) const {
181
+ FAIL_MTIAHOOKS_FUNC(__func__);
182
+ }
183
+
184
+ virtual MempoolId_t mtiagraphPool(int64_t handle) const {
185
+ FAIL_MTIAHOOKS_FUNC(__func__);
186
+ }
187
+
188
+ virtual MempoolId_t graphPoolHandle() const {
189
+ FAIL_MTIAHOOKS_FUNC(__func__);
190
+ }
191
+
192
+ virtual const Generator& getDefaultGenerator(DeviceIndex) const override {
193
+ FAIL_MTIAHOOKS_FUNC(__func__);
194
+ static Generator dummy_generator;
195
+ return dummy_generator;
196
+ }
197
+
198
+ virtual Generator getNewGenerator(DeviceIndex) const override {
199
+ FAIL_MTIAHOOKS_FUNC(__func__);
200
+ static Generator dummy_generator;
201
+ return dummy_generator;
202
+ }
203
+ };
204
+
205
+ struct TORCH_API MTIAHooksArgs {};
206
+
207
+ TORCH_DECLARE_REGISTRY(MTIAHooksRegistry, MTIAHooksInterface, MTIAHooksArgs);
208
+ #define REGISTER_MTIA_HOOKS(clsname) C10_REGISTER_CLASS(MTIAHooksRegistry, clsname, clsname)
209
+
210
+ namespace detail {
211
+ TORCH_API const MTIAHooksInterface& getMTIAHooks();
212
+ TORCH_API bool isMTIAHooksBuilt();
213
+ } // namespace detail
214
+ } // namespace at
215
+
216
+ #else
217
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
218
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/PrivateUse1HooksInterface.h ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/GeneratorForPrivateuseone.h>
5
+ #include <ATen/detail/AcceleratorHooksInterface.h>
6
+
7
+ #include <c10/core/Allocator.h>
8
+ #include <c10/core/Device.h>
9
+ #include <c10/core/Storage.h>
10
+ #include <c10/util/Exception.h>
11
+
12
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter")
13
+
14
+ namespace at {
15
+
16
+ struct TORCH_API PrivateUse1HooksInterface : AcceleratorHooksInterface {
17
+ #define FAIL_PRIVATEUSE1HOOKS_FUNC(func) \
18
+ TORCH_CHECK_NOT_IMPLEMENTED( \
19
+ false, \
20
+ "You should register `PrivateUse1HooksInterface`", \
21
+ "by `RegisterPrivateUse1HooksInterface` and implement `", \
22
+ func, \
23
+ "` at the same time for PrivateUse1.");
24
+
25
+ ~PrivateUse1HooksInterface() override = default;
26
+
27
+ bool isBuilt() const override {
28
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
29
+ }
30
+
31
+ bool isAvailable() const override {
32
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
33
+ }
34
+
35
+ const at::Generator& getDefaultGenerator(
36
+ c10::DeviceIndex device_index) const override {
37
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
38
+ }
39
+
40
+ Generator getNewGenerator(
41
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
42
+ // TODO(FFFrog): Preserved for BC and will be removed in the future.
43
+ if (at::GetGeneratorPrivate().has_value())
44
+ return at::GetGeneratorForPrivateuse1(device_index);
45
+
46
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
47
+ }
48
+
49
+ at::Device getDeviceFromPtr(void* data) const override {
50
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
51
+ }
52
+
53
+ bool isPinnedPtr(const void* data) const override {
54
+ return false;
55
+ }
56
+
57
+ Allocator* getPinnedMemoryAllocator() const override {
58
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
59
+ }
60
+
61
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
62
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
63
+ }
64
+
65
+ void init() const override {}
66
+ virtual void resizePrivateUse1Bytes(
67
+ const c10::Storage& storage,
68
+ size_t newsize) const {
69
+ FAIL_PRIVATEUSE1HOOKS_FUNC(__func__);
70
+ }
71
+
72
+ #undef FAIL_PRIVATEUSE1HOOKS_FUNC
73
+ };
74
+
75
+ struct TORCH_API PrivateUse1HooksArgs {};
76
+
77
+ TORCH_API void RegisterPrivateUse1HooksInterface(
78
+ at::PrivateUse1HooksInterface* hook_);
79
+
80
+ TORCH_API bool isPrivateUse1HooksRegistered();
81
+
82
+ namespace detail {
83
+
84
+ TORCH_API const at::PrivateUse1HooksInterface& getPrivateUse1Hooks();
85
+
86
+ } // namespace detail
87
+
88
+ } // namespace at
89
+
90
+ C10_DIAGNOSTIC_POP()
91
+
92
+ #else
93
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
94
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/XLAHooksInterface.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/core/Device.h>
5
+ #include <c10/util/Exception.h>
6
+ #include <c10/util/Registry.h>
7
+
8
+ #include <ATen/detail/AcceleratorHooksInterface.h>
9
+
10
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter")
11
+
12
+ namespace at {
13
+
14
+ constexpr const char* XLA_HELP =
15
+ "This error has occurred because you are trying "
16
+ "to use some XLA functionality, but the XLA library has not been "
17
+ "loaded by the dynamic linker. You must load xla libraries by `import torch_xla`";
18
+
19
+ struct TORCH_API XLAHooksInterface : AcceleratorHooksInterface {
20
+ ~XLAHooksInterface() override = default;
21
+
22
+ void init() const override {
23
+ TORCH_CHECK(false, "Cannot initialize XLA without torch_xla library. ", XLA_HELP);
24
+ }
25
+
26
+ virtual bool hasXLA() const {
27
+ return false;
28
+ }
29
+
30
+ virtual std::string showConfig() const {
31
+ TORCH_CHECK(
32
+ false,
33
+ "Cannot query detailed XLA version without torch_xla library. ",
34
+ XLA_HELP);
35
+ }
36
+
37
+ const Generator& getDefaultGenerator(
38
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
39
+ TORCH_CHECK(
40
+ false, "Cannot get default XLA generator without torch_xla library. ", XLA_HELP);
41
+ }
42
+
43
+ Generator getNewGenerator(
44
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
45
+ TORCH_CHECK(false, "Cannot get XLA generator without torch_xla library. ", XLA_HELP);
46
+ }
47
+
48
+ virtual DeviceIndex getCurrentDevice() const override {
49
+ TORCH_CHECK(false, "Cannot get current XLA device without torch_xla library. ", XLA_HELP);
50
+ }
51
+
52
+ Device getDeviceFromPtr(void* /*data*/) const override {
53
+ TORCH_CHECK(false, "Cannot get device of pointer on XLA without torch_xla library. ", XLA_HELP);
54
+ }
55
+
56
+ Allocator* getPinnedMemoryAllocator() const override {
57
+ TORCH_CHECK(false, "Cannot get XLA pinned memory allocator without torch_xla library. ", XLA_HELP);
58
+ }
59
+
60
+ bool isPinnedPtr(const void* data) const override {
61
+ return false;
62
+ }
63
+
64
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
65
+ TORCH_CHECK(false, "Cannot query primary context without torch_xla library. ", XLA_HELP);
66
+ }
67
+
68
+ };
69
+
70
+ struct TORCH_API XLAHooksArgs {};
71
+
72
+ TORCH_DECLARE_REGISTRY(XLAHooksRegistry, XLAHooksInterface, XLAHooksArgs);
73
+ #define REGISTER_XLA_HOOKS(clsname) \
74
+ C10_REGISTER_CLASS(XLAHooksRegistry, clsname, clsname)
75
+
76
+ namespace detail {
77
+ TORCH_API const XLAHooksInterface& getXLAHooks();
78
+ } // namespace detail
79
+ } // namespace at
80
+ C10_DIAGNOSTIC_POP()
81
+
82
+ #else
83
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
84
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/detail/XPUHooksInterface.h ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/core/Device.h>
5
+ #include <c10/util/Exception.h>
6
+ #include <c10/util/Registry.h>
7
+
8
+ #include <ATen/detail/AcceleratorHooksInterface.h>
9
+
10
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter")
11
+
12
+ namespace at {
13
+
14
+ struct TORCH_API XPUHooksInterface : AcceleratorHooksInterface{
15
+ ~XPUHooksInterface() override = default;
16
+
17
+ void init() const override {
18
+ TORCH_CHECK(false, "Cannot initialize XPU without ATen_xpu library.");
19
+ }
20
+
21
+ virtual bool hasXPU() const {
22
+ return false;
23
+ }
24
+
25
+ virtual std::string showConfig() const {
26
+ TORCH_CHECK(
27
+ false,
28
+ "Cannot query detailed XPU version without ATen_xpu library.");
29
+ }
30
+
31
+ virtual int32_t getGlobalIdxFromDevice(const Device& device) const {
32
+ TORCH_CHECK(false, "Cannot get XPU global device index without ATen_xpu library.");
33
+ }
34
+
35
+ const Generator& getDefaultGenerator(
36
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
37
+ TORCH_CHECK(
38
+ false, "Cannot get default XPU generator without ATen_xpu library.");
39
+ }
40
+
41
+ Generator getNewGenerator(
42
+ [[maybe_unused]] DeviceIndex device_index = -1) const override {
43
+ TORCH_CHECK(false, "Cannot get XPU generator without ATen_xpu library.");
44
+ }
45
+
46
+ virtual DeviceIndex getNumGPUs() const {
47
+ return 0;
48
+ }
49
+
50
+ virtual DeviceIndex current_device() const {
51
+ TORCH_CHECK(false, "Cannot get current device on XPU without ATen_xpu library.");
52
+ }
53
+
54
+ Device getDeviceFromPtr(void* /*data*/) const override {
55
+ TORCH_CHECK(false, "Cannot get device of pointer on XPU without ATen_xpu library.");
56
+ }
57
+
58
+ virtual void deviceSynchronize(DeviceIndex /*device_index*/) const {
59
+ TORCH_CHECK(false, "Cannot synchronize XPU device without ATen_xpu library.");
60
+ }
61
+
62
+ Allocator* getPinnedMemoryAllocator() const override {
63
+ TORCH_CHECK(false, "Cannot get XPU pinned memory allocator without ATen_xpu library.");
64
+ }
65
+
66
+ bool isPinnedPtr(const void* data) const override {
67
+ return false;
68
+ }
69
+
70
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
71
+ TORCH_CHECK(false, "Cannot query primary context without ATen_xpu library.");
72
+ }
73
+ };
74
+
75
+ struct TORCH_API XPUHooksArgs {};
76
+
77
+ TORCH_DECLARE_REGISTRY(XPUHooksRegistry, XPUHooksInterface, XPUHooksArgs);
78
+ #define REGISTER_XPU_HOOKS(clsname) \
79
+ C10_REGISTER_CLASS(XPUHooksRegistry, clsname, clsname)
80
+
81
+ namespace detail {
82
+ TORCH_API const XPUHooksInterface& getXPUHooks();
83
+ } // namespace detail
84
+ } // namespace at
85
+ C10_DIAGNOSTIC_POP()
86
+
87
+ #else
88
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
89
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/ADInterpreters.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/functorch/Interpreter.h>
4
+
5
+ namespace at::functorch {
6
+
7
+ // These are the interpreters for our AD transforms
8
+ // (grad, vjp and jvp).
9
+ // See NOTE: [functorch interpreter stack] for more details.
10
+
11
+ struct TORCH_API GradInterpreterPtr {
12
+ explicit GradInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Grad); }
13
+ TransformType key() const { return base_->key(); }
14
+ int64_t level() const { return base_->level(); }
15
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
16
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
17
+ bool prevGradMode() const {
18
+ return std::get<GradInterpreterMeta>(base_->meta()).prevGradMode_;
19
+ }
20
+ Tensor lift(const Tensor& tensor) const;
21
+ private:
22
+ const Interpreter* base_;
23
+ };
24
+
25
+ struct TORCH_API JvpInterpreterPtr {
26
+ explicit JvpInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Jvp); }
27
+ TransformType key() const { return base_->key(); }
28
+ int64_t level() const { return base_->level(); }
29
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
30
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
31
+ bool prevFwdGradMode() const {
32
+ return std::get<JvpInterpreterMeta>(base_->meta()).prevFwdGradMode_;
33
+ }
34
+ Tensor lift(const Tensor& tensor) const;
35
+ private:
36
+ const Interpreter* base_;
37
+ };
38
+
39
+ } // namespace at::functorch
40
+
41
+ #else
42
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
43
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchRulesHelper.h ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright (c) Facebook, Inc. and its affiliates.
3
+ // All rights reserved.
4
+ //
5
+ // This source code is licensed under the BSD-style license found in the
6
+ // LICENSE file in the root directory of this source tree.
7
+ #pragma once
8
+
9
+ #include <c10/util/TypeList.h>
10
+
11
+ #include <ATen/ATen.h>
12
+ #include <ATen/Operators.h>
13
+
14
+ #include <ATen/functorch/DynamicLayer.h>
15
+ #include <ATen/functorch/TensorWrapper.h>
16
+ #include <ATen/functorch/BatchingMetaprogramming.h>
17
+ #include <ATen/functorch/LegacyVmapTransforms.h>
18
+ #include <ATen/functorch/BatchedFallback.h>
19
+ #include <ATen/functorch/PlumbingHelper.h>
20
+ #include <ATen/core/dispatch/Dispatcher.h>
21
+ #include <ATen/VmapGeneratedPlumbing.h>
22
+
23
+ #include <utility>
24
+
25
+ // This file contains helper functions for batching rules.
26
+
27
+ namespace at::functorch {
28
+
29
+ TORCH_API Tensor reshape_dim_into(int64_t src, int64_t dst, const Tensor& x);
30
+ TORCH_API Tensor reshape_dim_outof(int64_t src, int64_t size1, const Tensor& x);
31
+
32
+ TORCH_API Tensor reshape_dim_outof_symint(int64_t src, const c10::SymInt& size1, const Tensor& x);
33
+
34
+ Tensor moveBatchDimToFront(Tensor tensor, std::optional<int64_t> maybe_batch_dim);
35
+ int64_t rankWithoutBatchDim(const Tensor& tensor, std::optional<int64_t> maybe_batch_dim);
36
+ int64_t numelWithoutBatchDim(const Tensor& tensor, std::optional<int64_t> maybe_batch_dim);
37
+ std::optional<int64_t> valIfNonempty(std::optional<int64_t> maybe_empty, int64_t new_val);
38
+ int64_t getPhysicalDim(const Tensor& tensor, bool has_batch_dim, int64_t logical_dim);
39
+ VmapDimVector getPhysicalDims(const Tensor& tensor, bool has_batch_dim, IntArrayRef logical_dims);
40
+
41
+ void vmapIncompatibleInplaceError(const char* schema_name);
42
+
43
+ Tensor maybePadToLogicalRank(const Tensor& tensor, std::optional<int64_t> has_bdim, int64_t logical_rank);
44
+
45
+ void check_randomness(RandomnessType randomness);
46
+ void check_randomness(RandomnessType randomness, bool any_tensor_bdim);
47
+
48
+ inline Tensor ensure_has_bdim(const Tensor& tensor, bool has_bdim, c10::SymInt batch_size) {
49
+ if (has_bdim) {
50
+ return tensor;
51
+ }
52
+ const auto sizes = tensor.sym_sizes();
53
+ SymDimVector expanded_shape;
54
+ expanded_shape.reserve(sizes.size());
55
+ expanded_shape.emplace_back(std::move(batch_size));
56
+ expanded_shape.insert(expanded_shape.end(), sizes.begin(), sizes.end());
57
+ return tensor.expand_symint(expanded_shape);
58
+ }
59
+
60
+ #define VMAP_SUPPORT(op, batch_rule) \
61
+ m.impl(#op, op ## _generated_plumbing<decltype(&batch_rule), &batch_rule>);
62
+
63
+ #define VMAP_SUPPORT2(op, overload, batch_rule) \
64
+ m.impl(#op "." #overload, op ## _ ## overload ## _generated_plumbing<decltype(&batch_rule), &batch_rule>);
65
+
66
+ #define OP_DECOMPOSE(op) m.impl(#op, static_cast<decltype(&ATEN_FN(op))>(native::op));
67
+ #define OP_DECOMPOSE2(op, overload) m.impl(#op"."#overload, static_cast<decltype(&ATEN_FN2(op, overload))>(native::op));
68
+
69
+ // DO NOT USE ME DIRECTLY! Use BASIC_UNARY_BATCH_RULE to save yourself some pain
70
+ template <typename A, A a, typename C>
71
+ struct BasicUnaryBatchRuleHelper;
72
+
73
+ template <typename F, F Func, typename A, typename... T>
74
+ struct BasicUnaryBatchRuleHelper<F, Func, c10::guts::typelist::typelist<A, T...>> {
75
+ static std::tuple<Tensor, std::optional<int64_t>> apply(
76
+ const Tensor& tensor,
77
+ std::optional<int64_t> batch_dim,
78
+ T... extra_args) {
79
+ return std::make_tuple(Func(tensor, std::forward<T>(extra_args)...), batch_dim);
80
+ }
81
+ };
82
+
83
+ // USAGE: BASIC_UNARY_BATCH_RULE(at::sin)
84
+ // INCORRECT USAGE: BASIC_UNARY_BATCH_RULE(&at::sin)
85
+ // It is important that this macro is not passed a function pointer!!
86
+ #define BASIC_UNARY_BATCH_RULE(fn) SINGLE_ARG(\
87
+ BasicUnaryBatchRuleHelper<\
88
+ decltype(&fn),\
89
+ &fn,\
90
+ c10::guts::function_traits<decltype(fn)>::parameter_types>::apply)
91
+
92
+ #define UNARY_POINTWISE(op) \
93
+ VMAP_SUPPORT(op, BASIC_UNARY_BATCH_RULE(ATEN_FN(op)));
94
+
95
+ template <typename A, A a, typename C>
96
+ struct VariadicBdimsBatchRuleHelper;
97
+
98
+ template <typename F, F Func, typename A, typename... T>
99
+ struct VariadicBdimsBatchRuleHelper<F, Func, c10::guts::typelist::typelist<A, T...>> {
100
+ static std::tuple<Tensor, std::optional<int64_t>> apply(
101
+ const Tensor& tensor,
102
+ std::optional<int64_t> batch_dim,
103
+ T... extra_args) {
104
+ auto tensor_ = moveBatchDimToFront(tensor, batch_dim);
105
+ return std::make_tuple(Func(tensor_, std::forward<T>(extra_args)...), 0);
106
+ }
107
+ };
108
+
109
+ // USAGE: VARIADIC_BDIMS_BATCH_RULE(at::cholesky_inverse)
110
+ // INCORRECT USAGE: VARIADIC_BDIMS_BATCH_RULE(&at::cholesky_inverse)
111
+ // It is important that this macro is not passed a function pointer!!
112
+ #define VARIADIC_BDIMS_BATCH_RULE(fn) SINGLE_ARG(\
113
+ VariadicBdimsBatchRuleHelper<\
114
+ decltype(&fn),\
115
+ &fn,\
116
+ c10::guts::function_traits<decltype(fn)>::parameter_types>::apply)
117
+
118
+ #define VARIADIC_BDIMS(op) \
119
+ VMAP_SUPPORT(op, VARIADIC_BDIMS_BATCH_RULE(ATEN_FN(op)));
120
+
121
+ #define VARIADIC_BDIMS2(op, overload) \
122
+ VMAP_SUPPORT2(op, overload, VARIADIC_BDIMS_BATCH_RULE(ATEN_FN2(op, overload)));
123
+
124
+ template<class F, F Func>
125
+ void boxed_tensor_inputs_batch_rule(const c10::OperatorHandle& op, torch::jit::Stack* stack) {
126
+ const auto& schema = op.schema();
127
+ const auto num_returns = schema.returns().size();
128
+ const auto num_arguments = schema.arguments().size();
129
+
130
+ c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched);
131
+ auto maybe_layer = maybeCurrentDynamicLayer();
132
+ vmap_check_escaped(maybe_layer, "boxed_tensor_inputs_batch_rule");
133
+
134
+ int64_t cur_level = maybe_layer->layerId();
135
+
136
+ auto orig_arguments = torch::jit::last(*stack, num_arguments);
137
+ if (std::none_of(orig_arguments.begin(), orig_arguments.end(), ivalueParticipatesInCurrentLevel)) {
138
+ op.callBoxed(stack);
139
+ return;
140
+ }
141
+
142
+ auto arguments = torch::jit::pop(*stack, num_arguments);
143
+ std::vector<std::pair<Tensor, std::optional<int64_t>>> tensor_inputs;
144
+ std::vector<int64_t> tensor_pos;
145
+ for (const auto idx : c10::irange(0, num_arguments)) {
146
+ const auto& ivalue = arguments[idx];
147
+ if (ivalue.isTensor()) {
148
+ auto [tensor_value, tensor_bdim] = unwrapTensorAtLevel(ivalue.toTensor(), cur_level);
149
+ tensor_inputs.emplace_back(std::move(tensor_value), tensor_bdim);
150
+ tensor_pos.push_back(static_cast<int64_t>(idx));
151
+ }
152
+ }
153
+ Func(tensor_inputs);
154
+
155
+ size_t tensor_idx = 0;
156
+ TORCH_INTERNAL_ASSERT(!tensor_pos.empty());
157
+ for (const auto arg_idx : c10::irange(0, num_arguments)) {
158
+ if (tensor_idx >= tensor_pos.size() || (int64_t)arg_idx != tensor_pos[tensor_idx]) {
159
+ torch::jit::push(stack, arguments[arg_idx]);
160
+ } else {
161
+ TORCH_INTERNAL_ASSERT(tensor_idx < tensor_inputs.size());
162
+ torch::jit::push(stack, tensor_inputs[tensor_idx].first);
163
+ tensor_idx++;
164
+ }
165
+ }
166
+
167
+ op.callBoxed(stack);
168
+ const auto returns = torch::jit::pop(*stack, num_returns);
169
+ for (const auto& ret : returns) {
170
+ if (ret.isTensor()) {
171
+ torch::jit::push(stack, makeBatched(ret.toTensor(), 0, cur_level));
172
+ } else {
173
+ TORCH_INTERNAL_ASSERT(false, "This boxed batching rule does not currently support ops that return non-tensor values");
174
+ }
175
+ }
176
+ }
177
+
178
+ inline void handle_pointwise_ops(std::vector<std::pair<Tensor, std::optional<int64_t>>> &tensor_inputs) {
179
+ int64_t out_logical_rank = 0;
180
+ for (auto& tensor_input : tensor_inputs) {
181
+ int64_t cur_logical_rank = rankWithoutBatchDim(tensor_input.first, tensor_input.second);
182
+ out_logical_rank = std::max(out_logical_rank, cur_logical_rank);
183
+ }
184
+ for (auto& tensor_input: tensor_inputs) {
185
+ tensor_input.first = moveBatchDimToFront(tensor_input.first, tensor_input.second);
186
+ tensor_input.first = maybePadToLogicalRank(tensor_input.first, tensor_input.second, out_logical_rank);
187
+ }
188
+ }
189
+
190
+ #define POINTWISE_BOXED(op) \
191
+ m.impl(#op, torch::CppFunction::makeFromBoxedFunction<boxed_tensor_inputs_batch_rule<decltype(&handle_pointwise_ops), &handle_pointwise_ops>>());
192
+
193
+ #define POINTWISE_BOXED2(op, overload) \
194
+ m.impl(#op "." #overload, torch::CppFunction::makeFromBoxedFunction<boxed_tensor_inputs_batch_rule<decltype(&handle_pointwise_ops), &handle_pointwise_ops>>());
195
+
196
+ inline void handle_variadic_bdims(std::vector<std::pair<Tensor, std::optional<int64_t>>> &tensor_inputs) {
197
+ for (auto & tensor_input : tensor_inputs) {
198
+ tensor_input.first = moveBatchDimToFront(tensor_input.first, tensor_input.second);
199
+ }
200
+ }
201
+
202
+ #define VARIADIC_BDIMS_BOXED(op) \
203
+ m.impl(#op, torch::CppFunction::makeFromBoxedFunction<boxed_tensor_inputs_batch_rule<decltype(&handle_variadic_bdims), &handle_variadic_bdims>>());
204
+
205
+ using UnpackedBatchedTensor = std::tuple<Tensor, std::optional<int64_t>>;
206
+
207
+ inline void find_and_unpack_tensors(
208
+ const torch::jit::Stack* stack,
209
+ int64_t num_args,
210
+ int64_t cur_level,
211
+ SmallVector<UnpackedBatchedTensor, 5>* tensors,
212
+ SmallVector<int64_t, 5>* tensors_pos,
213
+ int64_t* batch_size) {
214
+
215
+ int64_t computed_batch_size = -1;
216
+ int64_t args_begin = static_cast<int64_t>(stack->size()) - num_args;
217
+
218
+ for (const auto idx : c10::irange(0, num_args)) {
219
+ const auto& ivalue = (*stack)[args_begin + idx];
220
+ if (!ivalue.isTensor()) {
221
+ continue;
222
+ }
223
+ auto unpacked = unwrapTensorAtLevel(ivalue.toTensor(), cur_level);
224
+ const auto& [tensor_value, tensor_bdim] = unpacked;
225
+ if (tensor_bdim.has_value()) {
226
+ auto candidate_batch_size = tensor_value.size(*tensor_bdim);
227
+ if (computed_batch_size == -1) {
228
+ computed_batch_size = candidate_batch_size;
229
+ }
230
+ TORCH_INTERNAL_ASSERT(candidate_batch_size == computed_batch_size);
231
+ }
232
+
233
+ tensors->push_back(std::move(unpacked));
234
+ tensors_pos->push_back(idx);
235
+ }
236
+ TORCH_INTERNAL_ASSERT(computed_batch_size > -1);
237
+ *batch_size = computed_batch_size;
238
+ }
239
+
240
+ inline void boxed_existing_bdim_all_batch_rule(
241
+ const c10::OperatorHandle& op, torch::jit::Stack* stack) {
242
+ const auto& schema = op.schema();
243
+ const auto num_returns = schema.returns().size();
244
+ const auto num_arguments = static_cast<int64_t>(schema.arguments().size());
245
+
246
+ c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched);
247
+ const auto maybe_layer = maybeCurrentDynamicLayer();
248
+ vmap_check_escaped(maybe_layer, "boxed_existing_bdim_all_batch_rule");
249
+
250
+ const auto arguments = torch::jit::last(stack, num_arguments);
251
+ if (std::none_of(arguments.begin(), arguments.end(), ivalueParticipatesInCurrentLevel)) {
252
+ op.callBoxed(stack);
253
+ return;
254
+ }
255
+
256
+ int64_t args_begin = static_cast<int64_t>(stack->size()) - num_arguments;
257
+ SmallVector<UnpackedBatchedTensor, 5> tensor_inputs;
258
+ SmallVector<int64_t, 5> tensor_pos;
259
+ int64_t batch_size = 0;
260
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
261
+ int64_t cur_level = maybe_layer->layerId();
262
+
263
+ find_and_unpack_tensors(
264
+ stack, num_arguments, cur_level,
265
+ &tensor_inputs, &tensor_pos, &batch_size);
266
+
267
+ // for each tensor, ensure it has a bdim and reshape it.
268
+ for (const auto tensor_idx : c10::irange(0, tensor_inputs.size())) {
269
+ const auto& [value, bdim] = tensor_inputs[tensor_idx];
270
+ auto value_ = ensure_has_bdim(value, bdim.has_value(), batch_size);
271
+ (*stack)[args_begin + tensor_pos[tensor_idx]] = reshape_dim_into(bdim.value_or(0), 0, value_);
272
+ }
273
+
274
+ op.callBoxed(stack);
275
+
276
+ for (const auto idx : c10::irange(args_begin, args_begin + num_returns)) {
277
+ const auto& ret = (*stack)[idx];
278
+ TORCH_INTERNAL_ASSERT(ret.isTensor(),
279
+ "This boxed batching rule does not currently support ops that return non-tensor values");
280
+ (*stack)[idx] = makeBatched(reshape_dim_outof(0, batch_size, ret.toTensor()), 0, cur_level);
281
+ }
282
+ }
283
+
284
+ // Use when all tensors arguments accept one (normal) batch dim.
285
+ // This batching rule expands the batch dim on all Tensors, reshapes it into
286
+ // dim 0, calls the op, and then reshapes the batch dim out of dim 0.
287
+ // This is not the most efficient thing; if there are alternatives, please try
288
+ // to use them. Use this only as a last resort.
289
+ #define EXISTING_BDIM_ALL_BOXED(op) \
290
+ m.impl(#op, torch::CppFunction::makeFromBoxedFunction<boxed_existing_bdim_all_batch_rule>());
291
+
292
+ template <int64_t feature_rank, int64_t contig_tensor_index=-1>
293
+ inline void boxed_all_tensors_have_optional_bdim(
294
+ const c10::OperatorHandle& op, torch::jit::Stack* stack) {
295
+ const auto& schema = op.schema();
296
+ const auto num_returns = schema.returns().size();
297
+ const auto num_arguments = schema.arguments().size();
298
+
299
+ c10::impl::ExcludeDispatchKeyGuard guard(DispatchKey::FuncTorchBatched);
300
+ auto maybe_layer = maybeCurrentDynamicLayer();
301
+ vmap_check_escaped(maybe_layer, "boxed_all_tensors_have_optional_bdim");
302
+ int64_t cur_level = maybe_layer->layerId();
303
+
304
+ const auto arguments = torch::jit::last(stack, num_arguments);
305
+ if (std::none_of(arguments.begin(), arguments.end(), ivalueParticipatesInCurrentLevel)) {
306
+ op.callBoxed(stack);
307
+ return;
308
+ }
309
+
310
+ int64_t args_begin = static_cast<int64_t>(stack->size() - num_arguments);
311
+ SmallVector<UnpackedBatchedTensor, 5> tensor_inputs;
312
+ SmallVector<int64_t, 5> tensor_pos;
313
+ int64_t batch_size = 0;
314
+
315
+ find_and_unpack_tensors(
316
+ stack, static_cast<int64_t>(num_arguments), cur_level,
317
+ &tensor_inputs, &tensor_pos, &batch_size);
318
+
319
+ std::optional<bool> is_no_batch_dim_case;
320
+
321
+ for (const auto tensor_idx : c10::irange(0, tensor_inputs.size())) {
322
+ const auto& value = std::get<0>(tensor_inputs[tensor_idx]);
323
+ auto bdim = std::get<1>(tensor_inputs[tensor_idx]);
324
+ const auto logical_rank = rankWithoutBatchDim(value, bdim);
325
+
326
+ if (!is_no_batch_dim_case.has_value()) {
327
+ is_no_batch_dim_case = (logical_rank == feature_rank);
328
+ }
329
+ auto value_ = ensure_has_bdim(value, bdim.has_value(), batch_size);
330
+ if (!bdim.has_value()) {
331
+ bdim = 0;
332
+ }
333
+ if (*is_no_batch_dim_case) {
334
+ TORCH_INTERNAL_ASSERT(logical_rank == feature_rank);
335
+ value_ = moveBatchDimToFront(value_, bdim);
336
+ if (tensor_idx == contig_tensor_index) {
337
+ value_ = value_.contiguous();
338
+ }
339
+ (*stack)[args_begin + tensor_pos[tensor_idx]] = std::move(value_);
340
+ continue;
341
+ }
342
+ TORCH_INTERNAL_ASSERT(logical_rank == feature_rank + 1);
343
+ value_ = reshape_dim_into(*bdim, 0, value_);
344
+ if (tensor_idx == contig_tensor_index) {
345
+ value_ = value_.contiguous();
346
+ }
347
+ (*stack)[args_begin + tensor_pos[tensor_idx]] = std::move(value_);
348
+ }
349
+
350
+ op.callBoxed(stack);
351
+
352
+ for (const auto idx : c10::irange(args_begin, args_begin + num_returns)) {
353
+ const auto& ret = (*stack)[idx];
354
+ TORCH_INTERNAL_ASSERT(ret.isTensor(),
355
+ "This boxed batching rule does not currently support ops that return non-tensor values");
356
+ if (*is_no_batch_dim_case) {
357
+ (*stack)[idx] = makeBatched(ret.toTensor(), 0, cur_level);
358
+ } else {
359
+ (*stack)[idx] = makeBatched(reshape_dim_outof(0, batch_size, ret.toTensor()), 0, cur_level);
360
+ }
361
+ }
362
+ }
363
+
364
+ // Useful for many NN operators.
365
+ // The operator must satisfy the following:
366
+ // - All arguments must accept an optional batch dim.
367
+ // - All arguments must be the same rank
368
+ #define ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED(feature_rank, op) \
369
+ m.impl(#op, torch::CppFunction::makeFromBoxedFunction<boxed_all_tensors_have_optional_bdim<feature_rank>>());
370
+
371
+ #define ALL_TENSORS_HAVE_OPTIONAL_BDIM_BOXED_CONTIG1(feature_rank, op, contig_tensor_index) \
372
+ m.impl(#op, \
373
+ torch::CppFunction::makeFromBoxedFunction<\
374
+ boxed_all_tensors_have_optional_bdim<\
375
+ feature_rank, \
376
+ contig_tensor_index>\
377
+ >());
378
+
379
+ template <typename A, A a, typename C>
380
+ struct ExistingBdimBatchRuleHelper;
381
+
382
+ template <typename F, F Func, typename A, typename... T>
383
+ struct ExistingBdimBatchRuleHelper<F, Func, c10::guts::typelist::typelist<A, T...>> {
384
+ static std::tuple<Tensor, std::optional<int64_t>> apply(
385
+ const Tensor& self,
386
+ std::optional<int64_t> self_bdim,
387
+ T... extra_args) {
388
+ auto self_ = reshape_dim_into(*self_bdim, 0, self);
389
+ auto out = Func(self_, std::forward<T>(extra_args)...);
390
+ return std::make_tuple(reshape_dim_outof_symint(0, self.sym_sizes()[*self_bdim], out), 0);
391
+ }
392
+ };
393
+
394
+ // USAGE: EXISTING_BDIM_BATCH_RULE(at::cholesky_inverse)
395
+ // INCORRECT USAGE: EXISTING_BDIM_BATCH_RULE(&at::cholesky_inverse)
396
+ // It is important that this macro is not passed a function pointer!!
397
+ #define EXISTING_BDIM_BATCH_RULE(fn) SINGLE_ARG(\
398
+ ExistingBdimBatchRuleHelper<\
399
+ decltype(&fn),\
400
+ &fn,\
401
+ c10::guts::function_traits<decltype(fn)>::parameter_types>::apply)
402
+
403
+
404
+ #define EXISTING_BDIM(op) \
405
+ VMAP_SUPPORT(op, EXISTING_BDIM_BATCH_RULE(ATEN_FN(op)));
406
+
407
+ #define EXISTING_BDIM2(op, overload) \
408
+ VMAP_SUPPORT2(op, overload, EXISTING_BDIM_BATCH_RULE(ATEN_FN2(op, overload)));
409
+
410
+ #define INVOKE(object,ptrToMember) ((object).*(ptrToMember))
411
+
412
+
413
+ template <typename F, F Method, typename... ExtraArgs>
414
+ Tensor& unary_inplace_batch_rule(Tensor& self, std::optional<int64_t> /*unused*/, ExtraArgs... extra_args) {
415
+ INVOKE(self, Method)(std::forward<ExtraArgs>(extra_args)...);
416
+ return self;
417
+ }
418
+
419
+ inline int64_t get_bdim_size4(
420
+ const Tensor& a_value, std::optional<int64_t> a_bdim,
421
+ const Tensor& b_value, std::optional<int64_t> b_bdim,
422
+ const Tensor& c_value, std::optional<int64_t> c_bdim,
423
+ const Tensor& d_value, std::optional<int64_t> d_bdim) {
424
+ if (a_bdim)
425
+ return a_value.size(*a_bdim);
426
+ if (b_bdim)
427
+ return b_value.size(*b_bdim);
428
+ if (c_bdim)
429
+ return c_value.size(*c_bdim);
430
+ if (d_bdim)
431
+ return d_value.size(*d_bdim);
432
+ TORCH_INTERNAL_ASSERT(false);
433
+ }
434
+
435
+ inline int64_t get_bdim_size3(
436
+ const Tensor& a_value, std::optional<int64_t> a_bdim,
437
+ const Tensor& b_value, std::optional<int64_t> b_bdim,
438
+ const Tensor& c_value, std::optional<int64_t> c_bdim) {
439
+ if (a_bdim)
440
+ return a_value.size(*a_bdim);
441
+ if (b_bdim)
442
+ return b_value.size(*b_bdim);
443
+ if (c_bdim)
444
+ return c_value.size(*c_bdim);
445
+ TORCH_INTERNAL_ASSERT(false);
446
+ }
447
+
448
+ inline int64_t get_bdim_size2(
449
+ const Tensor& a_value, std::optional<int64_t> a_bdim,
450
+ const Tensor& b_value, std::optional<int64_t> b_bdim) {
451
+ if (a_bdim)
452
+ return a_value.size(*a_bdim);
453
+ if (b_bdim)
454
+ return b_value.size(*b_bdim);
455
+ TORCH_INTERNAL_ASSERT(false);
456
+ }
457
+
458
+ inline c10::SymInt get_bdim_size2_symint(
459
+ const Tensor& a_value, std::optional<int64_t> a_bdim,
460
+ const Tensor& b_value, std::optional<int64_t> b_bdim) {
461
+ if (a_bdim)
462
+ return a_value.sym_size(*a_bdim);
463
+ if (b_bdim)
464
+ return b_value.sym_size(*b_bdim);
465
+ TORCH_INTERNAL_ASSERT(false);
466
+ }
467
+
468
+ // [start, start + 1, ..., stop - 1]
469
+ inline VmapDimVector range(int64_t start, int64_t stop) {
470
+ TORCH_INTERNAL_ASSERT(stop >= start);
471
+ VmapDimVector dims;
472
+ dims.reserve(stop - start);
473
+ for (int64_t i = start; i < stop; i++) {
474
+ dims.emplace_back(i);
475
+ }
476
+ return dims;
477
+ }
478
+ std::tuple<Tensor, Tensor> _binary_pointwise_helper(
479
+ const Tensor& tensor, std::optional<int64_t> tensor_batch_dim, const Tensor& other, std::optional<int64_t> other_batch_dim,
480
+ bool do_type_promotion=true);
481
+
482
+ } // namespace at::functorch
483
+
484
+ #else
485
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
486
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchedFallback.h ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright (c) Facebook, Inc. and its affiliates.
3
+ // All rights reserved.
4
+ //
5
+ // This source code is licensed under the BSD-style license found in the
6
+ // LICENSE file in the root directory of this source tree.
7
+
8
+ #pragma once
9
+ #include <ATen/ATen.h>
10
+ #include <ATen/core/op_registration/op_registration.h>
11
+ #include <torch/library.h>
12
+
13
+ namespace at::functorch {
14
+
15
+ // This file contains code for the vmap fallback (also known as the
16
+ // BatchedTensor fallback or the Batched fallback). This code runs
17
+ // when an operation doesn't have a batching rule implemented.
18
+
19
+ // If an operator doesn't have a batching rule implemented then we fallback
20
+ // to this implementation. The fallback doesn't work on out= variants or
21
+ // view operations; that is, it works for out-of-place operations and
22
+ // in-place non-view operations.
23
+ //
24
+ // For out-of-place operations, the fallback effectively takes all of the
25
+ // BatchedTensors in `stack`, slices them, and runs `op` on all of the
26
+ // corresponding slices to produce slices of the outputs. The output slices
27
+ // then get `torch.stack`ed to create the
28
+ // final returns.
29
+ //
30
+ // The performance of the fallback is not very good because it introduces an
31
+ // extra copy from stacking the sliced outputs. Because of this, we prefer to
32
+ // write batching rules for operators whenever possible.
33
+ void batchedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
34
+ void batchedNestedTensorForLoopFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
35
+
36
+ void vmapErrorFallback(const c10::OperatorHandle& op, torch::jit::Stack* stack);
37
+
38
+ // The vmap fallback emits a warning by default, but it may be disabled if
39
+ // the user finds it to be too annoying.
40
+ TORCH_API bool isVmapFallbackWarningEnabled();
41
+ TORCH_API void setVmapFallbackWarningEnabled(bool enabled);
42
+
43
+ // Used for testing. The vmap fallback is enabled by default. When it is disabled,
44
+ // it raises an error.
45
+ TORCH_API bool isVmapFallbackEnabled();
46
+ TORCH_API void setVmapFallbackEnabled(bool enabled);
47
+
48
+ template <typename A> A vector_to_result(const std::vector<IValue>& buffer) {
49
+ return buffer[0].to<A>();
50
+ }
51
+ template <typename A, typename B> std::tuple<A, B> vector_to_result(const std::vector<IValue>& buffer) {
52
+ return std::make_tuple(buffer[0].to<A>(), buffer[1].to<B>());
53
+ }
54
+ template <typename A, typename B, typename C> std::tuple<A, B, C> vector_to_result(const std::vector<IValue>& buffer) {
55
+ return std::make_tuple(buffer[0].to<A>(), buffer[1].to<B>(), buffer[2].to<B>());
56
+ }
57
+
58
+ // slow_fallback is a way to call the vmap fallback inside some boxed kernel.
59
+ // There is probably some better way to metaprogram this.
60
+ template <typename Ret>
61
+ Ret slow_fallback(const c10::OperatorHandle& op, ArrayRef<IValue> args) {
62
+ std::vector<IValue> stack(args.begin(), args.end());
63
+ batchedTensorForLoopFallback(op, &stack);
64
+ return vector_to_result<Ret>(stack);
65
+ }
66
+
67
+ template <typename A, typename B>
68
+ std::tuple<A, B> slow_fallback(const c10::OperatorHandle& op, ArrayRef<IValue> args) {
69
+ std::vector<IValue> stack(args.begin(), args.end());
70
+ batchedTensorForLoopFallback(op, &stack);
71
+ return vector_to_result<A, B>(stack);
72
+ }
73
+
74
+ template <typename A, typename B, typename C>
75
+ std::tuple<A, B, C> slow_fallback(const c10::OperatorHandle& op, ArrayRef<IValue> args) {
76
+ std::vector<IValue> stack(args.begin(), args.end());
77
+ batchedTensorForLoopFallback(op, &stack);
78
+ return vector_to_result<A, B, C>(stack);
79
+ }
80
+
81
+
82
+ } // namespace at::functorch
83
+
84
+ #else
85
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
86
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchedTensorImpl.h ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright (c) Facebook, Inc. and its affiliates.
3
+ // All rights reserved.
4
+ //
5
+ // This source code is licensed under the BSD-style license found in the
6
+ // LICENSE file in the root directory of this source tree.
7
+
8
+ #pragma once
9
+
10
+ #include <bitset>
11
+
12
+ #include <ATen/ArrayRef.h>
13
+ #include <ATen/SmallVector.h>
14
+ #include <ATen/Tensor.h>
15
+
16
+ namespace at::functorch {
17
+
18
+ using Tensor = at::Tensor;
19
+
20
+ // We assume this in a few other places in the codebase,
21
+ // but there isn't a centralized definition.
22
+ constexpr int64_t kVmapMaxTensorDims = 64;
23
+
24
+ // The valid vmap levels range from [0, 64). This effectively means that we
25
+ // support a maximum of 64 nested vmaps.
26
+ constexpr int64_t kVmapNumLevels = 64;
27
+
28
+ // Store this number of elements of BatchDims on the stack. Most people will
29
+ // probably use <= 5 nested vmaps, but adjust this number as necessary.
30
+ constexpr int64_t kBatchDimsStackSize = 5;
31
+
32
+ // A BatchedTensorImpl holds an underlying Tensor and a single batch dim
33
+ // NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a
34
+ // BatchedTensorImpl.
35
+ //
36
+ // The batch dimensions are treated as being "private"; they are not user-visible.
37
+ // For example, in the following Tensor,
38
+ // bt = BatchedTensorImpl(ones(2, 3, 5, 7), lvl=1, dim=0)
39
+ // dimension 0 is batch dimension.
40
+ //
41
+ // bt.sizes() returns (5, 7); bt.sum(0) performs a reduction over the (public)
42
+ // dim 0, which is equivalent to dim 3 in the underlying ones(2, 3, 5, 7) tensor.
43
+ struct TORCH_API BatchedTensorImpl : public c10::TensorImpl {
44
+ explicit BatchedTensorImpl(at::DispatchKeySet key_set, Tensor value, int64_t dim, int64_t level);
45
+
46
+ // Returns batch dimension of this tensor
47
+ int64_t bdim() const { return bdim_; }
48
+
49
+ // Returns batch dimension of this tensor
50
+ int64_t level() const { return level_; }
51
+
52
+ // BatchedTensorImpl wraps a Tensor
53
+ const Tensor& value() const { return value_; }
54
+
55
+ // Given a public dimension index, return the dimension index in the underlying
56
+ // value() tensor.
57
+ // For example, if we have
58
+ // bt = BatchedTensorImpl(ones(2, 3, 5, 7), lvl=1, dim=0)
59
+ // bt.actualDim(0) -> 1
60
+ // bt.actualDim(1) -> 2
61
+ // bt.actualDim(2) -> 3
62
+ // bt.actualDim(3) -> Error
63
+ int64_t actualDim(int64_t dim, bool wrap_dim = true) const;
64
+
65
+ IntArrayRef sizes_custom() const override;
66
+ SymIntArrayRef sym_sizes_custom() const override;
67
+ int64_t size_custom(int64_t d) const override;
68
+ c10::SymInt sym_size_custom(int64_t d) const override;
69
+ // We have to override this because we opted into CustomStrides
70
+ IntArrayRef strides_custom() const override;
71
+ SymIntArrayRef sym_strides_custom() const override;
72
+ // Override a bunch of methods inherited from TensorImpl to return error messages.
73
+ c10::SymBool sym_is_contiguous_custom(at::MemoryFormat memory_format) const override;
74
+ void set_size(int64_t dim, int64_t new_size) override;
75
+ void set_stride(int64_t dim, int64_t new_stride) override;
76
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
77
+ const c10::VariableVersion& version_counter,
78
+ bool allow_tensor_metadata_change) const override;
79
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
80
+ c10::VariableVersion&& version_counter,
81
+ bool allow_tensor_metadata_change) const override;
82
+ void shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) override;
83
+ #ifdef DEBUG
84
+ bool has_storage() const override;
85
+ #endif
86
+
87
+ void refreshTensorMetadata();
88
+
89
+ // Used in torchdim. torchdim uses non-lexical BatchedTensor; the way it
90
+ // accomplishes this is a hack where it is able to modify the levels of
91
+ // BatchedTensor to match the level of the current vmap transform.
92
+ void _unsafe_set_level(int64_t level) {
93
+ level_ = level;
94
+ }
95
+
96
+ // Used in batching rule for in-place view operations that can change
97
+ // the index of the bdim (think squeeze_, unsqueeze_)
98
+ void unsafe_set_bdim(int64_t bdim) {
99
+ // NB: you MUST call refreshTensorMetadata after doing this.
100
+ bdim_ = bdim;
101
+ }
102
+ private:
103
+ // see NOTE: [BatchedTensorImpl levels invariant]
104
+ void checkInvariants() const;
105
+ const char* tensorimpl_type_name() const override;
106
+
107
+ Tensor value_;
108
+
109
+ int64_t level_;
110
+ int64_t bdim_;
111
+ };
112
+
113
+ // NB: We use the term "BatchedTensor" to mean a Tensor that is backed with a
114
+ // BatchedTensorImpl.
115
+ inline bool isBatchedTensor(const Tensor& tensor) {
116
+ return tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::FuncTorchBatched) ||
117
+ tensor.unsafeGetTensorImpl()->key_set().has(DispatchKey::BatchedNestedTensor);
118
+ }
119
+
120
+ // It is unsafe to call this on a Tensor that is not backed by a
121
+ // BatchedTensorImpl. Please use `maybeGetBatchedImpl` whenever possible.
122
+ inline BatchedTensorImpl* unsafeGetBatchedImpl(const Tensor& tensor) {
123
+ return static_cast<BatchedTensorImpl*>(tensor.unsafeGetTensorImpl());
124
+ }
125
+
126
+ inline BatchedTensorImpl* maybeGetBatchedImpl(const Tensor& tensor) {
127
+ if (!isBatchedTensor(tensor)) {
128
+ return nullptr;
129
+ }
130
+ return unsafeGetBatchedImpl(tensor);
131
+ }
132
+
133
+ // Returns a bitset. If bit i is set, then that means dim i is a batchdim.
134
+ inline std::bitset<kVmapMaxTensorDims> createBatchDimBitset(int64_t dim) {
135
+ std::bitset<kVmapMaxTensorDims> is_bdim;
136
+ is_bdim.set(dim);
137
+ return is_bdim;
138
+ }
139
+
140
+ // Creates a bitset for the given level
141
+ inline std::bitset<kVmapNumLevels> createVmapLevelsBitset(int64_t level) {
142
+ std::bitset<kVmapNumLevels> result;
143
+ result.set(level);
144
+ return result;
145
+ }
146
+
147
+ // Use this to construct a BatchedTensor from a regular Tensor
148
+ TORCH_API Tensor makeBatched(Tensor tensor, int64_t dim, int64_t level);
149
+
150
+ // Adds a batch dim to `tensor`, returning a BatchedTensor
151
+ TORCH_API Tensor addBatchDim(Tensor tensor, int64_t dim, int64_t level);
152
+
153
+ // Certain dispatch keys must be propagated to the BatchedTensor (or, in general,
154
+ // any wrapper Tensor subclasses). This is because there are methods on Tensor
155
+ // that skip dispatch and check for the presence of a dispatch key (e.g. is_cpu()).
156
+ // TODO: should probably contain more (or all?) backend keys
157
+ constexpr DispatchKeySet kKeysToPropagateToWrapper({
158
+ DispatchKey::Negative,
159
+ DispatchKey::Conjugate,
160
+ DispatchKey::XLA,
161
+ DispatchKey::XPU,
162
+ DispatchKey::HPU,
163
+ DispatchKey::CUDA,
164
+ DispatchKey::CPU,
165
+ DispatchKey::PrivateUse1,
166
+ DispatchKey::SparseCPU,
167
+ DispatchKey::SparseCUDA,
168
+ DispatchKey::SparseCsrCPU,
169
+ DispatchKey::SparseCsrCUDA,
170
+ });
171
+
172
+ inline DispatchKeySet getKeysToPropagateToWrapper(const Tensor& tensor, DispatchKeySet to_propagate=kKeysToPropagateToWrapper) {
173
+ auto key_set = tensor.unsafeGetTensorImpl()->key_set();
174
+ return key_set & kKeysToPropagateToWrapper;
175
+ }
176
+
177
+ } // namespace at::functorch
178
+
179
+ #else
180
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
181
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/BatchingMetaprogramming.h ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright (c) Facebook, Inc. and its affiliates.
3
+ // All rights reserved.
4
+ //
5
+ // This source code is licensed under the BSD-style license found in the
6
+ // LICENSE file in the root directory of this source tree.
7
+
8
+ #pragma once
9
+ #include <ATen/Tensor.h>
10
+ #include <ATen/VmapGeneratedPlumbing.h>
11
+
12
+ // This file contains template metaprogramming things that are used for our
13
+ // batching rules.
14
+ //
15
+ // See NOTE: [vmap plumbing] for more details on why this is necessary.
16
+ // The plumbing has a bunch of metaprogramming hacks for determining the signature
17
+ // of a batching rule from the signature of the operator, many of which use the
18
+ // helper functions in this file.
19
+
20
+ namespace at::functorch {
21
+
22
+ // Metaprogramming things
23
+ template <class... Items> using typelist = c10::guts::typelist::typelist<Items...>;
24
+ template <class TypeList> using head_t = c10::guts::typelist::head_t<TypeList>;
25
+ template <class TL1, class TL2> using concat_t = c10::guts::typelist::concat_t<TL1, TL2>;
26
+ template <typename T> class debug_t;
27
+
28
+ // tail operation
29
+ template<class TypeList>
30
+ struct tail final {
31
+ static_assert(c10::guts::false_t<TypeList>::value,
32
+ "In typelist::tail<T>, the T argument must be typelist<...>.");
33
+ };
34
+ template<class Head, class... Tail>
35
+ struct tail<typelist<Head, Tail...>> final {
36
+ using type = typelist<Tail...>;
37
+ };
38
+ template<class TypeList> using tail_t = typename tail<TypeList>::type;
39
+
40
+ template <class First, class Second, class Next, class Tail>
41
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext {
42
+ using type = Next;
43
+ };
44
+ template <class Next, class Tail>
45
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<Tensor, std::optional<int64_t>, Next, Tail> {
46
+ using type = Tail;
47
+ };
48
+ template <class Next, class Tail>
49
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<const Tensor&, std::optional<int64_t>, Next, Tail> {
50
+ using type = Tail;
51
+ };
52
+ template <class Next, class Tail>
53
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<Tensor&, std::optional<int64_t>, Next, Tail> {
54
+ using type = Tail;
55
+ };
56
+ template <class Next, class Tail>
57
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<std::optional<Tensor>, std::optional<int64_t>, Next, Tail> {
58
+ using type = Tail;
59
+ };
60
+ template <class Next, class Tail>
61
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<const std::optional<Tensor>&, std::optional<int64_t>, Next, Tail> {
62
+ using type = Tail;
63
+ };
64
+ template <class Next, class Tail>
65
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<std::optional<Tensor>&, std::optional<int64_t>, Next, Tail> {
66
+ using type = Tail;
67
+ };
68
+ template <class Next, class Tail>
69
+ struct IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<std::vector<Tensor>, std::optional<int64_t>, Next, Tail> {
70
+ using type = Tail;
71
+ };
72
+ template <class TypeList> struct RemoveBatchDimAfterTensor {
73
+ using first = head_t<TypeList>;
74
+ using next = tail_t<TypeList>;
75
+ using second = head_t<next>;
76
+ using tail = tail_t<next>;
77
+
78
+ using type = concat_t<
79
+ typelist<first>,
80
+ typename RemoveBatchDimAfterTensor<
81
+ typename IfFirstIsTensorAndSecondisBatchDimThenTailElseNext<first, second, next, tail>::type
82
+ >::type
83
+ >;
84
+ };
85
+ template <class Type> struct RemoveBatchDimAfterTensor<typelist<Type>> {
86
+ using type = typelist<Type>;
87
+ };
88
+ template <> struct RemoveBatchDimAfterTensor<typelist<>> {
89
+ using type = typelist<>;
90
+ };
91
+ template<class TypeList> using remove_batch_dim_after_tensor_t = typename RemoveBatchDimAfterTensor<TypeList>::type;
92
+
93
+ template <typename T> struct UnpackSingleItemTuple {
94
+ using type = T;
95
+ };
96
+ template <typename T> struct UnpackSingleItemTuple<std::tuple<T>> {
97
+ using type = T;
98
+ };
99
+ template <typename T> using unpack_single_item_tuple_t = typename UnpackSingleItemTuple<T>::type;
100
+
101
+ template <typename Return, typename TupleArgs> struct BuildFunctionHelper;
102
+ template <typename Return, typename... Args> struct BuildFunctionHelper<Return, std::tuple<Args...>> {
103
+ using type = Return(Args...);
104
+ };
105
+ template <typename Return, typename TL>
106
+ struct BuildFunction {
107
+ using type = typename BuildFunctionHelper<Return, c10::guts::typelist::to_tuple_t<TL>>::type;
108
+ };
109
+ template <typename Return, typename TL> using build_function_t = typename BuildFunction<Return, TL>::type;
110
+
111
+
112
+ template <typename batch_rule_t> struct ToOperatorType {
113
+ using batch_rule_return_type = typename c10::guts::function_traits<batch_rule_t>::return_type;
114
+ using batch_rule_parameter_types = typename c10::guts::function_traits<batch_rule_t>::parameter_types;
115
+
116
+ using operator_parameter_types = remove_batch_dim_after_tensor_t<batch_rule_parameter_types>;
117
+ using operator_return_type =
118
+ unpack_single_item_tuple_t<
119
+ c10::guts::typelist::to_tuple_t<
120
+ remove_batch_dim_after_tensor_t<
121
+ c10::guts::typelist::from_tuple_t<batch_rule_return_type>>>>;
122
+
123
+ using type = build_function_t<operator_return_type, operator_parameter_types>;
124
+ };
125
+ template <typename batch_rule_t> using to_operator_t = typename ToOperatorType<batch_rule_t>::type;
126
+
127
+ } // namespace at::functorch
128
+
129
+ #else
130
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
131
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/DynamicLayer.h ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright (c) Facebook, Inc. and its affiliates.
3
+ // All rights reserved.
4
+ //
5
+ // This source code is licensed under the BSD-style license found in the
6
+ // LICENSE file in the root directory of this source tree.
7
+
8
+ #pragma once
9
+ #include <ATen/functorch/Macros.h>
10
+ #include <c10/core/DispatchKey.h>
11
+ #include <ATen/core/function_schema.h>
12
+ #include <optional>
13
+ #include <c10/core/impl/LocalDispatchKeySet.h>
14
+ #include <ATen/functorch/Interpreter.h>
15
+ #include <ATen/functorch/VmapInterpreter.h>
16
+ #include <ATen/functorch/ADInterpreters.h>
17
+ #include <ATen/functorch/FunctionalizeInterpreter.h>
18
+
19
+ // Forward declared
20
+ namespace c10 { struct AutogradMetaInterface; }
21
+
22
+ namespace at::functorch {
23
+
24
+ // This file contains the implementation of functorch's interpreter stack.
25
+ // See NOTE: [functorch interpreter stack] first before reading on.
26
+ //
27
+ // NB: the functorch interpreter stack is also referred to as:
28
+ // - the "dynamic layer stack" -- an older name for "interpreter" was
29
+ // "dynamic layer".
30
+ // - the "functorch mode stack". You can think of each functorch transform as a
31
+ // "mode" (in the same sense as torch_dispatch mode or torch_function mode),
32
+ // and functorch being an implementation of a "mode stack" where the modes
33
+ // may be arbitrary composed.
34
+
35
+ // DynamicLayer is basically the same thing as an Interpreter.
36
+ // It represents a functorch transform and it holds an Interpreter,
37
+ // which contains metadata related to the transform and instructions on
38
+ // how to perform the transform.
39
+ //
40
+ // TODO: we can excise DynamicLayer in favor of Interpreter,
41
+ // But I am going to leave it for now as a compatibility shim to avoid
42
+ // needing to refactor a lot of callsites...
43
+ struct TORCH_API DynamicLayer {
44
+ explicit DynamicLayer(
45
+ TransformType transform_type,
46
+ int64_t layerId,
47
+ std::optional<c10::SymInt> batchSize = std::nullopt,
48
+ std::optional<RandomnessType> randomness = std::nullopt,
49
+ std::optional<bool> prev_grad_mode = std::nullopt,
50
+ std::optional<bool> pre_fwd_grad_mode = std::nullopt,
51
+ std::optional<bool> functionalize_add_back_views = std::nullopt);
52
+
53
+ TransformType key() const;
54
+ int64_t layerId() const;
55
+
56
+ const Interpreter& interpreter() const { return interpreter_; }
57
+ Interpreter& interpreter() { return interpreter_; }
58
+
59
+ // Only valid for vmap
60
+ c10::SymInt batchSize() const;
61
+ RandomnessType randomness() const;
62
+
63
+ private:
64
+ Interpreter interpreter_;
65
+ };
66
+
67
+ TORCH_API int64_t initAndPushDynamicLayer(
68
+ TransformType transform_type,
69
+ std::optional<c10::SymInt> batch_size = std::nullopt,
70
+ std::optional<RandomnessType> randomness = std::nullopt,
71
+ std::optional<bool> prev_grad_mode = std::nullopt,
72
+ std::optional<bool> prev_fwd_grad_mode = std::nullopt,
73
+ std::optional<bool> functionalize_add_back_views = std::nullopt);
74
+ TORCH_API DynamicLayer popDynamicLayerAndDeleteMetadata();
75
+ TORCH_API std::optional<DynamicLayer> maybeCurrentDynamicLayer();
76
+ TORCH_API const std::vector<DynamicLayer>& getDynamicLayerStack();
77
+ TORCH_API void setDynamicLayerStack(const std::vector<DynamicLayer>& stack);
78
+ TORCH_API void setDynamicLayerFrontBackKeysIncluded(bool included);
79
+
80
+ // NOTE: [Life handles and lexically scoped transforms]
81
+ // functorch transforms are lexically scoped.
82
+ // Given a level, we store a "life handle" that is a boolean that tells us if the
83
+ // transform with that level is active or not.
84
+ //
85
+ // functorch's TensorWrapper (for grad transforms) stores a life handle.
86
+ // If a TensorWrapper escapes from the scope of the transform, then somehow
87
+ // it must know it escaped; it can tell by querying the life handle.
88
+ TORCH_API const std::shared_ptr<bool>& getLifeHandleForLevel(int64_t level);
89
+
90
+ // Returns if an operator is in-place. An operator is inplace if:
91
+ // 1. The first argument is a Tensor and it is being written to
92
+ // 2. The first argument is being returned
93
+ // 3. No other arguments are aliased
94
+ // Here is an example of an in-place operator:
95
+ // add_(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!)
96
+ TORCH_API bool isInplaceOp(const c10::FunctionSchema& schema);
97
+
98
+ // Given the indices of unwrapped inputs and the schema, this returns the indices of any outputs that should remain unwrapped
99
+ TORCH_API std::optional<size_t> findAliasedOutput(const FunctionSchema& schema, const int64_t immutable_input);
100
+
101
+ TORCH_API Tensor unwrapIfDead(const Tensor& tensor);
102
+ TORCH_API bool isDeadTensorWrapper(const Tensor& tensor);
103
+
104
+ // Pretty printers
105
+ TORCH_API std::ostream& operator<<(std::ostream& os, const DynamicLayer& layer);
106
+ TORCH_API std::ostream& operator<<(std::ostream& os, const std::vector<DynamicLayer>& dynamicLayerStack);
107
+
108
+ // While a functorch transform is active, torch.autograd.function._SingleLevelFunction
109
+ // is disabled by default. The following two APIs are APIs for enabling
110
+ // it. These are not user-facing APIs. We can delete this in the future, but
111
+ // it is useful for debugging when something goes wrong with the
112
+ // autograd.Function <> functorch interaction, which uses _SingleLevelFunction,
113
+ // because it leads to loud errors if something is incorrect.
114
+ TORCH_API void setSingleLevelAutogradFunctionAllowed(bool allowed);
115
+ TORCH_API bool getSingleLevelAutogradFunctionAllowed();
116
+
117
+ // While a functorch grad transform is active, Tensor.requires_grad_() gets
118
+ // disabled. These two functions are the mechanism to controlling that.
119
+ TORCH_API void setInplaceRequiresGradAllowed(bool allowed);
120
+ TORCH_API bool getInplaceRequiresGradAllowed();
121
+
122
+ TORCH_API DynamicLayer popDynamicLayer();
123
+ TORCH_API int64_t pushDynamicLayer(DynamicLayer&& layer);
124
+
125
+ } // namespace at::functorch
126
+
127
+ #else
128
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
129
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/FunctionalizeInterpreter.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/functorch/Interpreter.h>
4
+
5
+ namespace at::functorch {
6
+
7
+ // This is the interpreter that handles the functionalize() transform.
8
+ // See NOTE: [functorch interpreter stack] for more details.
9
+
10
+ struct FunctionalizeInterpreterPtr {
11
+ explicit FunctionalizeInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Functionalize); }
12
+ TransformType key() const { return base_->key(); }
13
+ int64_t level() const { return base_->level(); }
14
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
15
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
16
+ bool functionalizeAddBackViews() const {
17
+ return std::get<FunctionalizeInterpreterMeta>(base_->meta()).functionalizeAddBackViews_;
18
+ }
19
+ private:
20
+ const Interpreter* base_;
21
+ };
22
+
23
+ } // namespace at::functorch
24
+
25
+ #else
26
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
27
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/Interpreter.h ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/functorch/Macros.h>
5
+ #include <ATen/core/dispatch/Dispatcher.h>
6
+ #include <c10/core/impl/LocalDispatchKeySet.h>
7
+ #include <c10/util/Exception.h>
8
+ #include <optional>
9
+ #include <bitset>
10
+ #include <utility>
11
+ #include <variant>
12
+
13
+ #include <nlohmann/json.hpp>
14
+
15
+ namespace at::functorch {
16
+
17
+ // NOTE: [functorch interpreter stack]
18
+ //
19
+ // functorch's dispatching system uses a stack of interpreters.
20
+ // Historically we've referred to this as the "DynamicLayerStack".
21
+ //
22
+ // An interpreter is something that reads in the code it is passed
23
+ // and then executes it. We have a different interpreter per-transform:
24
+ // the "VmapInterpreter" is responsible for reading in operators (like aten::mv)
25
+ // and executing the batched version of it (the batching rule for aten::mv).
26
+ //
27
+ // Concretely, each interpreter is responsible for two things:
28
+ //
29
+ // 1) process(ophandle, stack)
30
+ // Given an operator handle and a stack of arguments, the interpreter is
31
+ // responsible for figuring out how to execute the operation under the semantics
32
+ // of the interpreter. For e.g. VmapInterpreter, this is figuring out how to call
33
+ // the batching rule.
34
+ //
35
+ // The batching rules are stored as kernels on the FuncTorchBatched key, so the way
36
+ // VmapInterpreter calls the batching rule is roughly: (A) exclude all
37
+ // dispatch keys aside from the Batched key, (B) redispatch so we get to the
38
+ // Batched key.
39
+ //
40
+ // 2) sendToNextInterpreter(ophandle, stack)
41
+ // The VmapInterpreter, when it sees aten::mv, will process it into a call to
42
+ // aten::mm. It then needs to send the call to aten::mm to the next interpreter
43
+ // in the interpreter stack.
44
+ //
45
+ // The VmapInterpreter just does this via a call to ophandle.callBoxed(stack)
46
+ // and most Interpreters will implement it this way.
47
+
48
+ enum class RandomnessType {
49
+ Error, // always errors when calling a random function
50
+ Same, // randomness appears the same across batches
51
+ Different, // randomness appears different across batches
52
+ END
53
+ };
54
+
55
+ enum class TransformType {
56
+ Torch, // Unused
57
+ Vmap,
58
+ Grad, // reverse-mode AD, aka vjp
59
+ Jvp, // forward-mode AD
60
+ Functionalize,
61
+ };
62
+
63
+ std::ostream& operator<<(std::ostream& os, const TransformType& t);
64
+
65
+ // NOTE: [Interpreter "subclassing" design]
66
+ //
67
+ // How are various Interpreters for different transforms (vmap, grad, ...)
68
+ // implemented?
69
+ //
70
+ // Accessing interpreters is in the hot-path of functorch so we have a constraint
71
+ // that this code must be as fast as possible.
72
+ //
73
+ // As a result, we stay away from virtual methods and this causes our code
74
+ // to look a little funny.
75
+ //
76
+ // `Interpreter` is the struct for Interpreters. It holds ALL of the
77
+ // relevant information (what type of interpreter it is and the metadata).
78
+ // Metadata for each interpreter is represented as a Union (std::variant)
79
+ // of all possible metadata (VmapInterpreterMeta, GradInterpreterMeta, ...).
80
+ //
81
+ // Given an Interpreter, how do I get a "VmapInterpreter"? You may wish to do this
82
+ // if you want to access the metadata fields (like batchSize and randomness).
83
+ //
84
+ // Each type of interpreter (e.g. Vmap) has a convenience struct
85
+ // (e.g. VmapInterpreterPtr) associated with it.
86
+ //
87
+ // Construct the convenience struct with VmapInterpreterPtr(Interpreter*),
88
+ // and then one can access methods on VmapInterpreterPtr like so:
89
+ // >>> VmapInterpreterPtr(&interpreter).batchSize()
90
+ //
91
+ // Finally, Interpreter::process switches on the type of the interpreter
92
+ // and calls one of {Transform}Interpreter::processImpl under the hood.
93
+ // Same for Interpreter::sendToNextInterpreter :)
94
+
95
+ struct VmapInterpreterMeta {
96
+ explicit VmapInterpreterMeta(c10::SymInt batchSize, RandomnessType randomness) :
97
+ batchSize_(std::move(batchSize)), randomness_(randomness) {}
98
+
99
+ c10::SymInt batchSize_;
100
+ RandomnessType randomness_;
101
+
102
+ VmapInterpreterMeta() = default;
103
+ VmapInterpreterMeta(const VmapInterpreterMeta&) = default;
104
+ VmapInterpreterMeta(VmapInterpreterMeta&&) = default;
105
+ VmapInterpreterMeta& operator=(const VmapInterpreterMeta&) = default;
106
+ VmapInterpreterMeta& operator=(VmapInterpreterMeta&&) = default;
107
+ ~VmapInterpreterMeta() = default;
108
+
109
+ template <typename T>
110
+ friend void to_json(T& json_j, const VmapInterpreterMeta& json_t) {
111
+ TORCH_CHECK(
112
+ !json_t.batchSize_.is_heap_allocated(),
113
+ "Serialization for heap-allocated SymInt is not implemented yet"
114
+ );
115
+ json_j["batchSize"] = json_t.batchSize_.as_int_unchecked();
116
+ json_j["randomness"] = static_cast<int64_t>(json_t.randomness_);
117
+ }
118
+
119
+ template <typename T>
120
+ friend void from_json(const T& json_j, VmapInterpreterMeta& json_t) {
121
+ json_t.batchSize_ = c10::SymInt(SymInt::Unchecked::UNCHECKED, json_j["batchSize"]);
122
+ json_t.randomness_ = static_cast<RandomnessType>(json_j["randomness"]);
123
+ }
124
+ };
125
+
126
+ struct GradInterpreterMeta {
127
+ explicit GradInterpreterMeta(bool prevGradMode): prevGradMode_(prevGradMode) {}
128
+ GradInterpreterMeta() = default;
129
+ GradInterpreterMeta(const GradInterpreterMeta&) = default;
130
+ GradInterpreterMeta(GradInterpreterMeta&&) = default;
131
+ GradInterpreterMeta& operator=(const GradInterpreterMeta&) = default;
132
+ GradInterpreterMeta& operator=(GradInterpreterMeta&&) = default;
133
+ ~GradInterpreterMeta() = default;
134
+
135
+ bool prevGradMode_;
136
+ template <typename T>
137
+ friend void to_json(T& json_j, const GradInterpreterMeta& json_t) {
138
+ json_j["prevGradMode"] = json_t.prevGradMode_;
139
+ }
140
+
141
+ template <typename T>
142
+ friend void from_json(const T& json_j, GradInterpreterMeta& json_t) {
143
+ json_t.prevGradMode_ = json_j["prevGradMode"];
144
+ }
145
+ };
146
+
147
+ struct JvpInterpreterMeta {
148
+ explicit JvpInterpreterMeta(bool prevFwdGradMode) : prevFwdGradMode_(prevFwdGradMode) {}
149
+ JvpInterpreterMeta() = default;
150
+ JvpInterpreterMeta(const JvpInterpreterMeta&) = default;
151
+ JvpInterpreterMeta(JvpInterpreterMeta&&) = default;
152
+ JvpInterpreterMeta& operator=(const JvpInterpreterMeta&) = default;
153
+ JvpInterpreterMeta& operator=(JvpInterpreterMeta&&) = default;
154
+ ~JvpInterpreterMeta() = default;
155
+
156
+ bool prevFwdGradMode_;
157
+ template <typename T>
158
+ friend void to_json(T& json_j, const JvpInterpreterMeta& json_t) {
159
+ json_j["prevFwdGradMode"] = json_t.prevFwdGradMode_;
160
+ }
161
+
162
+ template <typename T>
163
+ friend void from_json(const T& json_j, JvpInterpreterMeta& json_t) {
164
+ json_t.prevFwdGradMode_ = json_j["prevFwdGradMode"];
165
+ }
166
+ };
167
+
168
+ struct FunctionalizeInterpreterMeta {
169
+ explicit FunctionalizeInterpreterMeta(bool functionalizeAddBackViews) :
170
+ functionalizeAddBackViews_(functionalizeAddBackViews) {}
171
+ FunctionalizeInterpreterMeta() = default;
172
+ FunctionalizeInterpreterMeta(const FunctionalizeInterpreterMeta&) = default;
173
+ FunctionalizeInterpreterMeta(FunctionalizeInterpreterMeta&&) = default;
174
+ FunctionalizeInterpreterMeta& operator=(const FunctionalizeInterpreterMeta&) = default;
175
+ FunctionalizeInterpreterMeta& operator=(FunctionalizeInterpreterMeta&&) = default;
176
+ ~FunctionalizeInterpreterMeta() = default;
177
+
178
+ bool functionalizeAddBackViews_;
179
+ template <typename T>
180
+ friend void to_json(T& json_j, const FunctionalizeInterpreterMeta& json_t) {
181
+ json_j["functionalizeAddBackViews"] = json_t.functionalizeAddBackViews_;
182
+ }
183
+
184
+ template <typename T>
185
+ friend void from_json(const T& json_j, FunctionalizeInterpreterMeta& json_t) {
186
+ json_t.functionalizeAddBackViews_ = json_j["functionalizeAddBackViews"];
187
+ }
188
+ };
189
+
190
+ typedef std::variant<
191
+ int64_t,
192
+ GradInterpreterMeta,
193
+ JvpInterpreterMeta,
194
+ VmapInterpreterMeta,
195
+ FunctionalizeInterpreterMeta
196
+ > InterpreterMeta;
197
+
198
+
199
+ struct Interpreter {
200
+ // factory functions
201
+ static Interpreter Vmap(int64_t level, c10::SymInt batchSize, RandomnessType randomness) {
202
+ return Interpreter(TransformType::Vmap, level, VmapInterpreterMeta(std::move(batchSize), randomness));
203
+ }
204
+ static Interpreter Grad(int64_t level, bool prevGradMode) {
205
+ return Interpreter(TransformType::Grad, level, GradInterpreterMeta(prevGradMode));
206
+ }
207
+ static Interpreter Jvp(int64_t level, bool prevFwdGradMode) {
208
+ return Interpreter(TransformType::Jvp, level, JvpInterpreterMeta(prevFwdGradMode));
209
+ }
210
+ static Interpreter Functionalize(int64_t level, bool functionalizeAddBackViews) {
211
+ return Interpreter(TransformType::Functionalize, level, FunctionalizeInterpreterMeta(functionalizeAddBackViews));
212
+ }
213
+
214
+ // methods
215
+ TransformType key() const { return type_; }
216
+ int64_t level() const { return level_; }
217
+ const InterpreterMeta& meta() const { return meta_; }
218
+
219
+ void process(const c10::OperatorHandle& op, torch::jit::Stack* stack);
220
+ void sendToNextInterpreter(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
221
+
222
+ void saveLocalDispatchKeySet(c10::impl::LocalDispatchKeySet keyset) {
223
+ TORCH_INTERNAL_ASSERT(!savedLocalDispatchKeySet_.has_value());
224
+ savedLocalDispatchKeySet_ = keyset;
225
+ }
226
+ void clearSavedLocalDispatchKeySet() {
227
+ TORCH_INTERNAL_ASSERT(savedLocalDispatchKeySet_.has_value());
228
+ savedLocalDispatchKeySet_ = std::nullopt;
229
+ }
230
+ c10::impl::LocalDispatchKeySet getSavedLocalDispatchKeySet() const {
231
+ TORCH_INTERNAL_ASSERT(savedLocalDispatchKeySet_.has_value());
232
+ return *savedLocalDispatchKeySet_;
233
+ }
234
+
235
+ // An Interpreter is alive if we are currently inside the ongoing transform
236
+ // for the interpreter. For example, vmap(f)(x); inside of f, the vmap's
237
+ // corresponding Interpreter is alive, even when it is not on the DynamicLayerStack.
238
+ bool is_alive() const {
239
+ return *is_alive_;
240
+ }
241
+ const std::shared_ptr<bool>& is_alive_ptr() const {
242
+ return is_alive_;
243
+ }
244
+ void set_is_alive(bool alive) {
245
+ *is_alive_ = alive;
246
+ }
247
+
248
+ // Please don't use this
249
+ explicit Interpreter() = default;
250
+
251
+ template <typename T>
252
+ friend void to_json(T& json_j, const Interpreter& json_t) {
253
+ json_j["type"] = static_cast<int64_t>(json_t.type_);
254
+ json_j["level"] = json_t.level_;
255
+ if (json_t.savedLocalDispatchKeySet_) {
256
+ json_j["savedLocalDispatchKeySet"] = {
257
+ {"included", json_t.savedLocalDispatchKeySet_->included_.raw_repr()},
258
+ {"excluded", json_t.savedLocalDispatchKeySet_->excluded_.raw_repr()}
259
+ };
260
+ } else {
261
+ json_j["savedLocalDispatchKeySet"] = nlohmann::json();
262
+ }
263
+ json_j["is_alive"] = *json_t.is_alive_;
264
+ std::visit([&](auto&& arg) {
265
+ using V = std::decay_t<decltype(arg)>;
266
+ if constexpr (std::is_same_v<V, int64_t>) {
267
+ json_j["meta"] = {{"Torch", arg}};
268
+ } else if constexpr (std::is_same_v<V, GradInterpreterMeta>) {
269
+ json_j["meta"] = {{"Grad", arg}};
270
+ } else if constexpr (std::is_same_v<V, JvpInterpreterMeta>) {
271
+ json_j["meta"] = {{"Jvp", arg}};
272
+ } else if constexpr (std::is_same_v<V, VmapInterpreterMeta>) {
273
+ json_j["meta"] = {{"Vmap", arg}};
274
+ } else if constexpr (std::is_same_v<V, FunctionalizeInterpreterMeta>) {
275
+ json_j["meta"] = {{"Functionalize", arg}};
276
+ } else {
277
+ static_assert(false && sizeof(V), "unknown variant case");
278
+ }
279
+ }, json_t.meta_);
280
+ }
281
+
282
+ template <typename T>
283
+ friend void from_json(const T& json_j, Interpreter& json_t) {
284
+ json_t.type_ = static_cast<TransformType>(json_j["type"]);
285
+ json_t.level_ = json_j["level"];
286
+ auto savedLocalDispatchKeySet = json_j["savedLocalDispatchKeySet"];
287
+ if (savedLocalDispatchKeySet.is_null()) {
288
+ json_t.savedLocalDispatchKeySet_ = std::nullopt;
289
+ } else {
290
+ c10::impl::PODLocalDispatchKeySet pod;
291
+ pod.set_included(DispatchKeySet::from_raw_repr(savedLocalDispatchKeySet["included"].template get<uint64_t>()));
292
+ pod.set_excluded(DispatchKeySet::from_raw_repr(savedLocalDispatchKeySet["excluded"].template get<uint64_t>()));
293
+ json_t.savedLocalDispatchKeySet_ = c10::impl::LocalDispatchKeySet(pod);
294
+ }
295
+ json_t.is_alive_ = std::make_shared<bool>(json_j["is_alive"]);
296
+ auto meta = json_j["meta"];
297
+ if (meta.contains("Torch")) {
298
+ json_t.meta_.emplace<int64_t>(meta["Torch"].template get<int64_t>());
299
+ } else if (meta.contains("Grad")) {
300
+ json_t.meta_.emplace<GradInterpreterMeta>(meta["Grad"].template get<GradInterpreterMeta>());
301
+ } else if (meta.contains("Jvp")) {
302
+ json_t.meta_.emplace<JvpInterpreterMeta>(meta["Jvp"].template get<JvpInterpreterMeta>());
303
+ } else if (meta.contains("Vmap")) {
304
+ json_t.meta_.emplace<VmapInterpreterMeta>(meta["Vmap"].template get<VmapInterpreterMeta>());
305
+ } else if (meta.contains("Functionalize")) {
306
+ json_t.meta_.emplace<FunctionalizeInterpreterMeta>(meta["Functionalize"].template get<FunctionalizeInterpreterMeta>());
307
+ } else {
308
+ TORCH_CHECK(false, "unknown interpreter metadata type");
309
+ }
310
+ }
311
+
312
+ std::string serialize() const {
313
+ return nlohmann::json(*this).dump();
314
+ }
315
+
316
+ static Interpreter deserialize(const std::string& serialized) {
317
+ return nlohmann::json::parse(serialized).get<Interpreter>();
318
+ }
319
+
320
+ private:
321
+ explicit Interpreter(TransformType type, int64_t level, InterpreterMeta meta):
322
+ type_(type), level_(level), is_alive_(std::make_shared<bool>(false)), meta_(std::move(meta)) {}
323
+
324
+ // fields
325
+ TransformType type_{};
326
+ int64_t level_{};
327
+ std::optional<c10::impl::LocalDispatchKeySet> savedLocalDispatchKeySet_;
328
+ std::shared_ptr<bool> is_alive_;
329
+ InterpreterMeta meta_;
330
+ };
331
+
332
+ // Applies the following for-loop:
333
+ // for i in range(begin, end):
334
+ // args[i] = func(args[i])
335
+ void foreachTensorInplace(std::vector<IValue>& args, int64_t begin, int64_t end,
336
+ std::function<Tensor(const Tensor&)> func);
337
+
338
+ // Applies the following for-loop:
339
+ // for i in range(begin, end):
340
+ // if use_flag_relative[i] == 1: <-- treats use_flag_relative as a bitset
341
+ // args[i] = func(args[i], i - begin, true)
342
+ // args[i] = func(args[i], i - begin)
343
+ void foreachTensorInplaceWithFlag(std::vector<IValue>& args, int64_t begin, int64_t end,
344
+ const std::bitset<64> use_flag_relative, const std::function<Tensor(const Tensor&, bool)>& func);
345
+
346
+ std::vector<int64_t> findUnwrappedInputs(std::vector<IValue>& args, int64_t begin, int64_t end);
347
+
348
+ DispatchKeySet keysToExcludeWhenEnteringDynamicLayer(TransformType key);
349
+
350
+ void setup_dispatch_key_tls(TransformType key, DispatchKeySet include);
351
+
352
+ void sanityCheckStack(const c10::OperatorHandle& op, torch::jit::Stack* stack);
353
+
354
+ } // namespace at::functorch
355
+
356
+ #else
357
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
358
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/LegacyVmapTransforms.h ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright (c) Facebook, Inc. and its affiliates.
3
+ // All rights reserved.
4
+ //
5
+ // This source code is licensed under the BSD-style license found in the
6
+ // LICENSE file in the root directory of this source tree.
7
+
8
+ #pragma once
9
+
10
+ #include <ATen/functorch/Macros.h>
11
+ #include <ATen/functorch/BatchedTensorImpl.h>
12
+
13
+ namespace at::functorch {
14
+
15
+ // This files contains the legacy (now-deprecated) batching rule API.
16
+ // Please try to use the new-style batching rule API (see writing_batch_rules.md)
17
+
18
+ // This file contains abstractions used for transforming *logical* vmap arguments
19
+ // into *physical* arguments. (Keep reading for definitions of these terms).
20
+
21
+ // NOTE: [Logical vs physical args]
22
+ // Consider the following vmap.
23
+ // vmap(vmap(func, in_dims=(2,)), in_dims=(0,))(torch.ones(2, 3, 4))
24
+ // This would produce a BatchedTensor wrapping a Tensor of size [2, 3, 4],
25
+ // with batch dims 0 and 2:
26
+ // BatchedTensor(ones(2, 3, 4), bdims=[(lvl=1,dim=0),(lvl=2,dim=2)])
27
+ //
28
+ // We say the *logical* view of the tensor has size [3] -- tensors inside
29
+ // `func` appear to have size [3].
30
+ // However, the *physical* underlying tensor (the one passed to vmap) has size
31
+ // [2, 3, 4].
32
+ //
33
+ // This notion of logical vs physical also extends to non-tensor arguments.
34
+ // Consider the previous tensor; let's assume the user called
35
+ // `torch.sum(tensor, dim=0)` inside of `func`. Then the logical
36
+ // dimension they are reducing over is dim 0 but the physical dim is dim 1
37
+ // (the first non-batch dimension)
38
+
39
+ // Forward declared; see NOTE: [What is a VmapPhysicalView?]
40
+ struct VmapPhysicalView;
41
+
42
+ // Most PyTorch operators take 4 or fewer inputs.
43
+ constexpr int64_t kVmapTransformStaticInputSize = 4;
44
+ using VmapPhysicalViewVec = SmallVector<VmapPhysicalView, kVmapTransformStaticInputSize>;
45
+
46
+ // Pytorch generally advertises good performance for <= 5 dims.
47
+ // (see ATen/core/DimVector.h). We add a few extra dims (~3) for vmap
48
+ // dimensions to get 8. Adjust this number as necessary
49
+ constexpr int64_t kVmapStaticDimVecSize = 8;
50
+ using VmapDimVector = SmallVector<int64_t, kVmapStaticDimVecSize>;
51
+ using VmapSymDimVector = SmallVector<c10::SymInt, kVmapStaticDimVecSize>;
52
+
53
+ // NOTE: [What is an VmapTransform?]
54
+ // An *VmapTransform* converts logical views of tensors to physical views.
55
+ //
56
+ // Batching rules use VmapTransforms to convert logical arguments to
57
+ // physical arguments, then call one or more at:: operator that handles the
58
+ // physical arguments, and then converts the physical result back to a logical
59
+ // argument.
60
+
61
+ // VmapTransform for operators that take tensors with multiple batch dims.
62
+ // Given one or more logical views on Tensors, `logicalToPhysical`
63
+ // permutes all of the batch dims to the front of the tensor, aligns
64
+ // and expands the batch dims to match each other (according to their `level`),
65
+ // and returns a VmapPhysicalView on the tensor(s).
66
+ struct TORCH_API MultiBatchVmapTransform {
67
+ static VmapPhysicalView logicalToPhysical(const Tensor& logical_tensor);
68
+ static VmapPhysicalViewVec logicalToPhysical(ITensorListRef logical_tensors);
69
+ };
70
+
71
+ // VmapTransform for operators that broadcast all inputs.
72
+ // Given some logical views on Tensors, `logicalToPhysical`:
73
+ // - permutes all of the batch dims to the front of the tensors
74
+ // - aligns all the batch dims to the collective levels of all of the tensors.
75
+ // If a tensor does not have a batch dim for a vmap level, then it receives
76
+ // a size-one dimension for said level.
77
+ // - aligns the non-batch dims to have the same dimensionality, adding extra
78
+ // size-1 dimensions in between the batch dimensions and the non-batch dimensions
79
+ // so that the batch dimensions are lined up from the right.
80
+ //
81
+ // For example: given inputs of size (B, 2) and (B, 3, 2) where B is the batch
82
+ // dimension, BroadcastingVmapTransform returns VmapPhysicalViews that wrap tensors
83
+ // of size (B, 1, 2) and (B, 3, 2).
84
+ //
85
+ // Given inputs of size (B, 2) and (2,), BroadcastingVmapTransform returns
86
+ // VmapPhysicalViews wrapping tensors of size (B, 2) and (1, 2). We don't
87
+ // actually *need* to return a tensor of size (1, 2) for the second tensor
88
+ // because the broadcasting operation takes care of that for us, but we do
89
+ // it anyways to keep things simple.
90
+ struct TORCH_API BroadcastingVmapTransform {
91
+ static VmapPhysicalViewVec logicalToPhysical(TensorList logical_tensors);
92
+ };
93
+
94
+ // Forward declared, if you're reading this file head to toe, don't worry about
95
+ // it yet.
96
+ struct VmapPhysicalToLogicalMap;
97
+
98
+ // NOTE: [What is a VmapPhysicalView?]
99
+ // VmapPhysicalView represents a physical view on a Tensor.
100
+ //
101
+ // One can use it to further convert logical dimension indices, logical shapes,
102
+ // and more to their physical variants, or convert a new (physical) tensor into
103
+ // a logical BatchedTensor. (TODO(rzou): some of these are not yet implemented).
104
+ //
105
+ // VmapPhysicalView stores a physical tensor with all of its batch dimensions at
106
+ // the front and some levels that correspond to said batch dimensions.
107
+ //
108
+ // The levels bitset specifies which vmap levels correspond to the batch
109
+ // dimensions at the front of the tensor. In particular, the number of set bits
110
+ // corresponds to the number of batch dimensions on `tensor` and the rightmost
111
+ // bit of `levels` specifies the maximum number of nested vmaps we are in at
112
+ // this point in time.
113
+ // For example, given:
114
+ // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5, 6), levels={1, 3})
115
+ //
116
+ // Rightmost bit of `levels` is 3 indicating the number of nested vmaps less
117
+ // than or equal to 3.
118
+ // bitset: 010100
119
+ // ^
120
+ // |
121
+ // levels: 012345
122
+ struct TORCH_API VmapPhysicalView {
123
+ VmapPhysicalView(Tensor&& tensor, std::bitset<kVmapNumLevels> levels)
124
+ : levels_(levels), tensor_(std::move(tensor)) {
125
+ // TORCH_INTERNAL_ASSERT(!isBatchedTensor(tensor));
126
+ }
127
+
128
+ Tensor& tensor() { return tensor_; }
129
+ const Tensor& tensor() const { return tensor_; }
130
+
131
+ // Maps logical dim indices to physical dim indices. Also does dim wrapping.
132
+ //
133
+ // For example, given:
134
+ // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5), levels={1, 3})
135
+ //
136
+ // Then physical_view.getPhysicalDims({0, 1}) returns {2, 3}.
137
+ // This is because the size of levels tell us that the first two dimensions
138
+ // of `tensor_` are batch dimensions, so a logical dim of `n` is actually
139
+ // a physical dim of `n + 2`.
140
+ VmapDimVector getPhysicalDims(IntArrayRef logical_dims) const;
141
+ int64_t getPhysicalDim(int64_t logical_dim) const;
142
+
143
+ // Returns a VmapPhysicalToLogicalMap object. This can be used for
144
+ // mapping a physical tensor to a new logical tensor (BatchedTensor)
145
+ VmapPhysicalToLogicalMap getPhysicalToLogicalMap() const;
146
+
147
+ // Maps a logical shape to a physical shape by prepending the batch
148
+ // sizes to the logical shape.
149
+ VmapDimVector getPhysicalShape(IntArrayRef logical_shape) const;
150
+ SymDimVector getPhysicalShape(c10::SymIntArrayRef logical_shape) const;
151
+
152
+ int64_t numBatchDims() const;
153
+
154
+ private:
155
+ int64_t numLogicalDims() const;
156
+
157
+ std::bitset<kVmapNumLevels> levels_;
158
+ Tensor tensor_;
159
+ };
160
+
161
+ // Convenience struct used for mapping a physical tensor (a non-BatchedTensor)
162
+ // to a logical one (BatchedTensor). It holds some levels that are used to do the
163
+ // mapping and assumes that the batch dimensions in the physical tensor all
164
+ // occur at the front of the tensor.
165
+ struct TORCH_API VmapPhysicalToLogicalMap {
166
+ VmapPhysicalToLogicalMap(std::bitset<kVmapNumLevels> levels): levels_(levels) {}
167
+
168
+ // Maps a physical tensor to a new logical tensor (BatchedTensor).
169
+ // Assumes that all of the "batch dimensions" are at the front
170
+ // of the physical tensor. For example, given:
171
+ // - x = rank-4 Tensor with size 2, 3, 5, 7
172
+ // - levels = (2, 4)
173
+ // Returns:
174
+ // - BatchedTensor(x, bdims=[(dim=0,lvl=2), (dim=1, lvl=4)])
175
+ Tensor apply(const Tensor& physical_tensor) const;
176
+
177
+ // Given a vector of physical tensors,
178
+ // 1. maps each tensor to a new logical tensor. Assumes that all of the
179
+ // "batch dimensions" are at the front of the physical tensors.
180
+ // 2. stores the new logical tensors back into the passed-in vector. This is
181
+ // to avoid additional dynamic allocations.
182
+ void applyInplace(std::vector<Tensor>& physical_tensors) const;
183
+
184
+ std::bitset<kVmapNumLevels> levels_;
185
+ };
186
+
187
+
188
+ } // namespace at::functorch
189
+
190
+ #else
191
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
192
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/Macros.h ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #define SINGLE_ARG(...) __VA_ARGS__
5
+
6
+ #else
7
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
8
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/PlumbingHelper.h ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright (c) Facebook, Inc. and its affiliates.
3
+ // All rights reserved.
4
+ //
5
+ // This source code is licensed under the BSD-style license found in the
6
+ // LICENSE file in the root directory of this source tree.
7
+ #pragma once
8
+ #include <ATen/Tensor.h>
9
+ #include <ATen/functorch/BatchedTensorImpl.h>
10
+ #include <ATen/functorch/DynamicLayer.h>
11
+
12
+ // NOTE: [vmap plumbing]
13
+ //
14
+ // Here's how "batching rules" work.
15
+ // - we register kernels to the Batched key
16
+ // - these kernels have the same signatures as the original operators.
17
+ // For example, at::sin(Tensor self) accepts a Tensor, and the batched kernel
18
+ // must also accept a Tensor
19
+ // - However, it is more natural for users to write a batching rule like the
20
+ // following: sin_batch_rule(Tensor self, std::optional<int> self_bdim)
21
+ // - There is some codegenerated layer (the "plumbing") that wraps the user
22
+ // defined batching rule (e.g. sin_batch_rule) in a kernel that can be
23
+ // registered to the Batched key.
24
+ //
25
+ // The plumbing is responsible for wrapping a batching rule into a form that may
26
+ // be registered as the kernel for the batched key.
27
+
28
+ namespace at::functorch {
29
+
30
+ void vmap_check_escaped(const std::optional<DynamicLayer> &layer, const char* what);
31
+
32
+ // Create a BatchedTensor given a tensor, bdim, and level
33
+ TORCH_API Tensor makeBatched(Tensor tensor, std::optional<int64_t> bdim, int64_t level);
34
+
35
+ // Given a Tensor that may or may not be a BatchedTensor, unwrap it.
36
+ // If `tensor` is not a BatchedTensor, or is a BatchedTensor but the level
37
+ // doesn't match, then this returns (tensor, std::nullopt).
38
+ // Otherwise, it returns (unwrap(tensor), bdim).
39
+ TORCH_API std::tuple<Tensor, std::optional<int64_t>> unwrapTensorAtLevel(const Tensor& tensor, int64_t level);
40
+
41
+ // Creates a vector of BatchedTensor
42
+ TORCH_API std::vector<Tensor> makeBatchedVector(std::vector<Tensor> tensors, std::optional<int64_t> bdim, int64_t level);
43
+
44
+ // Returns True if ANY tensor in tensors is batched at level
45
+ TORCH_API bool isBatchedAtLevel(ITensorListRef tensors, int64_t level);
46
+ TORCH_API bool isBatchedAtLevel(const c10::List<std::optional<Tensor>>& maybe_tensors, int64_t level);
47
+ TORCH_API bool isBatchedAtLevel(const Tensor& tensor, int64_t level);
48
+ TORCH_API bool isBatchedAtLevel(const std::optional<Tensor>& maybe_tensor, int64_t level);
49
+
50
+ // Convenience helper. Returns true if any tensor is batched at level
51
+ TORCH_API bool areAnyBatchedAtLevel(ArrayRef<std::optional<Tensor>> maybe_tensors, int64_t level);
52
+
53
+ inline bool ivalueParticipatesInCurrentLevel(const IValue& ivalue) {
54
+ if (ivalue.isTensor()) {
55
+ auto maybe_level = maybeCurrentDynamicLayer();
56
+ TORCH_INTERNAL_ASSERT(maybe_level.has_value());
57
+ auto current_level = maybe_level->layerId();
58
+ return isBatchedAtLevel(ivalue.toTensor(), current_level);
59
+ }
60
+ // TODO: should really check this
61
+ return false;
62
+ }
63
+
64
+ } // namespace at::functorch
65
+
66
+ #else
67
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
68
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/TensorWrapper.h ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright (c) Facebook, Inc. and its affiliates.
3
+ // All rights reserved.
4
+ //
5
+ // This source code is licensed under the BSD-style license found in the
6
+ // LICENSE file in the root directory of this source tree.
7
+
8
+ #pragma once
9
+
10
+ #include <ATen/functorch/Macros.h>
11
+ #include <ATen/Tensor.h>
12
+ #include <ATen/functorch/Interpreter.h>
13
+
14
+ namespace at::functorch {
15
+
16
+ // NOTE: [functorch's TensorWrapper]
17
+ //
18
+ // Taking better suggestions for a name. TensorWrapper is the wrapper Tensor
19
+ // Subclass for functorch's grad-based transforms (grad, vjp, jvp). It is
20
+ // analogous to how vmap uses BatchedTensor as the wrapper Tensor subclass.
21
+ //
22
+ // If you're familiar with the Tensor-Variable merge, TensorWrapper is effectively
23
+ // another Variable.
24
+ //
25
+ // Consider grad(grad(torch.sin))(x). This wraps `x` as TensorWrapper(TensorWrapper(x)).
26
+ // The reason why is so that each TensorWrapper can hold its own AutogradMeta and
27
+ // participate in a **separate** autograd graph.
28
+ //
29
+ // There are alternative designs we could have chosen (e.g. each grad transform
30
+ // stores a weak map of Tensor -> AutogradMeta); the benefit of the TensorWrapper
31
+ // design is that we can reuse existing VariableType kernels (i.e. Autograd kernels)
32
+ // without much modification. Since a TensorWrapper looks like a regular Tensor,
33
+ // the VariableType kernel can pull out the AutogradMeta struct from where it
34
+ // expects and extend the autograd graph
35
+
36
+ struct TORCH_API TensorWrapper : public c10::TensorImpl {
37
+ explicit TensorWrapper(
38
+ c10::DispatchKeySet key_set,
39
+ Tensor value,
40
+ int64_t level,
41
+ std::shared_ptr<bool> is_alive,
42
+ bool is_immutable = false, // if true, this came from an operation that aliases an immutable tensor
43
+ bool use_value_sizes_strides = true);
44
+
45
+ void refreshMetadata();
46
+
47
+ const Tensor& value() const {
48
+ return value_;
49
+ }
50
+ std::optional<int64_t> level() const {
51
+ if (is_alive()) {
52
+ return level_;
53
+ }
54
+ return {};
55
+ }
56
+ bool is_immutable() const {
57
+ return is_immutable_;
58
+ }
59
+ bool is_alive() const;
60
+
61
+ // Overrides necessary for autograd
62
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
63
+ const c10::VariableVersion& version_counter,
64
+ bool allow_tensor_metadata_change) const override;
65
+ c10::intrusive_ptr<TensorImpl> shallow_copy_and_detach(
66
+ c10::VariableVersion&& version_counter,
67
+ bool allow_tensor_metadata_change) const override;
68
+ void shallow_copy_from(const c10::intrusive_ptr<TensorImpl>& impl) override;
69
+
70
+ private:
71
+ const char* tensorimpl_type_name() const override;
72
+ Tensor value_;
73
+ int64_t level_;
74
+ bool is_immutable_;
75
+
76
+ // TensorWrapper receives a boolean flag on whether or not the Grad Interpreter
77
+ // that created it is still alive or not.
78
+ // If the Grad Interpreter is no longer alive then it attempts to behave like
79
+ // a regular Tensor.
80
+ //
81
+ // When we exit the level, this wrapper may be marked as "not alive".
82
+ // Wrappers that are not alive:
83
+ // 1) May still have autograd metadata on them
84
+ // 2) Forward dispatches to the underlying value()
85
+ std::shared_ptr<bool> is_alive_;
86
+ };
87
+
88
+ // There are two variants of makeTensorWrapper: one that accepts a level
89
+ // and one that accepts an Interpreter.
90
+ //
91
+ // The one that accepts a level tries to automatically get the life handle from the
92
+ // interpreter on the DynamicLayerStack.
93
+ // It needs to be used with caution: if the interpreter is not on the
94
+ // DynamicLayerStack, then we won't be able to find the life handle.
95
+ //
96
+ // In practice this isn't a problem: when we're constructing TensorWrapper in
97
+ // Python, the corresponding interpreter is on the stack.
98
+ TORCH_API Tensor makeTensorWrapper(const Tensor& tensor, int64_t level, bool is_immutable=false);
99
+ TORCH_API Tensor makeTensorWrapper(const Tensor& tensor, const Interpreter& interpreter, bool is_immutable=false);
100
+ TORCH_API TensorWrapper* maybeGetTensorWrapper(const Tensor& tensor);
101
+ TORCH_API void dumpTensor(std::ostream & ss, const Tensor& tensor);
102
+ TORCH_API void dumpTensorCout(const Tensor& tensor);
103
+
104
+ } // namespace at::functorch
105
+
106
+ #else
107
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
108
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/functorch/VmapInterpreter.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/functorch/Interpreter.h>
4
+
5
+ namespace at::functorch {
6
+
7
+ // This is the interpreter that handles the functionalize() transform.
8
+ // See NOTE: [functorch interpreter stack] for more details.
9
+
10
+ struct VmapInterpreterPtr {
11
+ explicit VmapInterpreterPtr(const Interpreter* base): base_(base) { TORCH_INTERNAL_ASSERT(base->key() == TransformType::Vmap); }
12
+ TransformType key() const { return base_->key(); }
13
+ int64_t level() const { return base_->level(); }
14
+ void processImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack);
15
+ void sendToNextInterpreterImpl(const c10::OperatorHandle& op, torch::jit::Stack* stack, bool grad_special_case);
16
+ c10::SymInt batchSize() const {
17
+ return std::get<VmapInterpreterMeta>(base_->meta()).batchSize_;
18
+ }
19
+ RandomnessType randomness() const {
20
+ return std::get<VmapInterpreterMeta>(base_->meta()).randomness_;
21
+ }
22
+ private:
23
+ const Interpreter* base_;
24
+ };
25
+
26
+ } // namespace at::functorch
27
+
28
+ #else
29
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
30
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/hip/HIPCachingAllocator.h>
5
+
6
+ // Use of c10::hip namespace here makes hipification easier, because
7
+ // I don't have to also fix namespaces. Sorry!
8
+ namespace c10::hip {
9
+
10
+ // Takes a valid HIPAllocator (of any sort) and turns it into
11
+ // an allocator pretending to be a CUDA allocator. See
12
+ // Note [Masquerading as CUDA]
13
+ class HIPAllocatorMasqueradingAsCUDA final : public HIPCachingAllocator::HIPAllocator {
14
+ HIPCachingAllocator::HIPAllocator* allocator_;
15
+ public:
16
+ explicit HIPAllocatorMasqueradingAsCUDA(HIPCachingAllocator::HIPAllocator* allocator)
17
+ : allocator_(allocator) {}
18
+
19
+ virtual ~HIPAllocatorMasqueradingAsCUDA() = default;
20
+
21
+ // From c10::Allocator
22
+
23
+ DataPtr allocate(size_t size) override {
24
+ DataPtr r = allocator_->allocate(size);
25
+ r.unsafe_set_device(Device(c10::DeviceType::CUDA, r.device().index()));
26
+ return r;
27
+ }
28
+
29
+ bool is_simple_data_ptr(const DataPtr& data_ptr) const override {
30
+ return allocator_->is_simple_data_ptr(data_ptr);
31
+ }
32
+
33
+ DeleterFnPtr raw_deleter() const override {
34
+ return allocator_->raw_deleter();
35
+ }
36
+
37
+ void copy_data(void* dest, const void* src, std::size_t count) const final {
38
+ allocator_->copy_data(dest, src, count);
39
+ }
40
+
41
+ // From DeviceAllocator
42
+
43
+ bool initialized() override {
44
+ return allocator_->initialized();
45
+ }
46
+
47
+ void emptyCache(MempoolId_t mempool_id = {0, 0}) override {
48
+ allocator_->emptyCache(mempool_id);
49
+ }
50
+
51
+ void recordStream(const DataPtr& ptr, c10::Stream stream) override {
52
+ HIPStream hip_stream = HIPStream(stream);
53
+ recordStream(ptr, hip_stream);
54
+ }
55
+
56
+ CachingDeviceAllocator::DeviceStats getDeviceStats(c10::DeviceIndex device) override {
57
+ return allocator_->getDeviceStats(device);
58
+ }
59
+
60
+ void resetAccumulatedStats(c10::DeviceIndex device) override {
61
+ allocator_->resetAccumulatedStats(device);
62
+ }
63
+
64
+ void resetPeakStats(c10::DeviceIndex device) override {
65
+ allocator_->resetPeakStats(device);
66
+ }
67
+
68
+ // From CUDAAllocator
69
+
70
+ void* raw_alloc(size_t nbytes) override {
71
+ return allocator_->raw_alloc(nbytes);
72
+ }
73
+
74
+ void* raw_alloc_with_stream(size_t nbytes, hipStream_t stream) override {
75
+ return allocator_->raw_alloc_with_stream(nbytes, stream);
76
+ }
77
+
78
+ void raw_delete(void* ptr) override {
79
+ allocator_->raw_delete(ptr);
80
+ }
81
+
82
+ void init(int device_count) override {
83
+ allocator_->init(device_count);
84
+ }
85
+
86
+ double getMemoryFraction(c10::DeviceIndex device) override {
87
+ return allocator_->getMemoryFraction(device);
88
+ }
89
+
90
+ void setMemoryFraction(double fraction, c10::DeviceIndex device) override {
91
+ allocator_->setMemoryFraction(fraction, device);
92
+ }
93
+
94
+ std::vector<HIPCachingAllocator::StreamSegmentSize> getExpandableSegmentSizes(c10::DeviceIndex device) override {
95
+ return allocator_->getExpandableSegmentSizes(device);
96
+ }
97
+
98
+ void enable(bool value) override {
99
+ allocator_->enable(value);
100
+ }
101
+
102
+ bool isEnabled() const override {
103
+ return allocator_->isEnabled();
104
+ }
105
+
106
+ void cacheInfo(c10::DeviceIndex device, size_t* largestBlock) override {
107
+ allocator_->cacheInfo(device, largestBlock);
108
+ }
109
+
110
+ void* getBaseAllocation(void* ptr, size_t* size) override {
111
+ return allocator_->getBaseAllocation(ptr, size);
112
+ }
113
+
114
+ void recordStream(const DataPtr& ptr, HIPStream stream) override {
115
+ allocator_->recordStream(ptr, stream);
116
+ }
117
+
118
+ HIPCachingAllocator::SnapshotInfo snapshot(MempoolId_t mempool_id = {0, 0}) override {
119
+ return allocator_->snapshot(mempool_id);
120
+ }
121
+
122
+ void beginAllocateToPool(
123
+ c10::DeviceIndex device,
124
+ MempoolId_t mempool_id,
125
+ std::function<bool(hipStream_t)> filter) override {
126
+ allocator_->beginAllocateToPool(device, mempool_id, filter);
127
+ }
128
+
129
+ void endAllocateToPool(
130
+ c10::DeviceIndex device,
131
+ MempoolId_t mempool_id) override {
132
+ allocator_->endAllocateToPool(device, mempool_id);
133
+ }
134
+
135
+ void releasePool(c10::DeviceIndex device, MempoolId_t mempool_id) override {
136
+ allocator_->releasePool(device, mempool_id);
137
+ }
138
+
139
+ int getPoolUseCount(c10::DeviceIndex device, MempoolId_t mempool_id) override {
140
+ return allocator_->getPoolUseCount(device, mempool_id);
141
+ }
142
+
143
+ void createOrIncrefPool(
144
+ c10::DeviceIndex device,
145
+ MempoolId_t mempool_id,
146
+ HIPAllocator* allocator = nullptr) override {
147
+ allocator_->createOrIncrefPool(device, mempool_id, allocator);
148
+ }
149
+
150
+ void setUseOnOOM(c10::DeviceIndex device, MempoolId_t mempool_id) override {
151
+ allocator_->setUseOnOOM(device, mempool_id);
152
+ }
153
+
154
+ void setNoSplit(c10::DeviceIndex device, MempoolId_t mempool_id) override {
155
+ allocator_->setNoSplit(device, mempool_id);
156
+ }
157
+
158
+ bool checkPoolLiveAllocations(
159
+ c10::DeviceIndex device,
160
+ MempoolId_t mempool_id,
161
+ const std::unordered_set<void*>& expected_live_allocations) override {
162
+ return allocator_->checkPoolLiveAllocations(device, mempool_id, expected_live_allocations);
163
+ }
164
+
165
+ HIPCachingAllocator::ShareableHandle shareIpcHandle(void* ptr) override {
166
+ return allocator_->shareIpcHandle(ptr);
167
+ }
168
+
169
+ std::shared_ptr<void> getIpcDevPtr(std::string handle) override {
170
+ return allocator_->getIpcDevPtr(handle);
171
+ }
172
+
173
+ bool isHistoryEnabled() override {
174
+ return allocator_->isHistoryEnabled();
175
+ }
176
+
177
+ void recordHistory(
178
+ bool enabled,
179
+ HIPCachingAllocator::CreateContextFn context_recorder,
180
+ size_t alloc_trace_max_entries,
181
+ HIPCachingAllocator::RecordContext when,
182
+ bool clearHistory) override {
183
+ allocator_->recordHistory(enabled, context_recorder, alloc_trace_max_entries, when, clearHistory);
184
+ }
185
+
186
+ void recordAnnotation(
187
+ const std::vector<std::pair<std::string, std::string>>& md) override {
188
+ allocator_->recordAnnotation(md);
189
+ }
190
+
191
+ void pushCompileContext(std::string& md) override {
192
+ allocator_->pushCompileContext(md);
193
+ }
194
+
195
+ void popCompileContext() override {
196
+ allocator_->popCompileContext();
197
+ }
198
+
199
+ void attachOutOfMemoryObserver(HIPCachingAllocator::OutOfMemoryObserver observer) override {
200
+ allocator_->attachOutOfMemoryObserver(observer);
201
+ }
202
+
203
+ void attachAllocatorTraceTracker(HIPCachingAllocator::AllocatorTraceTracker tracker) override {
204
+ allocator_->attachAllocatorTraceTracker(tracker);
205
+ }
206
+
207
+ void enablePeerAccess(c10::DeviceIndex dev, c10::DeviceIndex dev_to_access) override {
208
+ allocator_->enablePeerAccess(dev, dev_to_access);
209
+ }
210
+
211
+ hipError_t memcpyAsync(
212
+ void* dst,
213
+ int dstDevice,
214
+ const void* src,
215
+ int srcDevice,
216
+ size_t count,
217
+ hipStream_t stream,
218
+ bool p2p_enabled) override {
219
+ return allocator_->memcpyAsync(dst, dstDevice, src, srcDevice, count, stream, p2p_enabled);
220
+ }
221
+
222
+ std::shared_ptr<HIPCachingAllocator::AllocatorState> getCheckpointState(
223
+ c10::DeviceIndex device,
224
+ MempoolId_t id) override {
225
+ return allocator_->getCheckpointState(device, id);
226
+ }
227
+
228
+ HIPCachingAllocator::CheckpointDelta setCheckpointPoolState(
229
+ c10::DeviceIndex device,
230
+ std::shared_ptr<HIPCachingAllocator::AllocatorState> pps) override {
231
+ auto cpd = allocator_->setCheckpointPoolState(device, pps);
232
+ for (auto& ptr : cpd.dataptrs_allocd) {
233
+ ptr.unsafe_set_device(Device(c10::DeviceType::CUDA, ptr.device().index()));
234
+ }
235
+ return cpd;
236
+ }
237
+
238
+ std::string name() override {
239
+ return allocator_->name();
240
+ }
241
+
242
+ };
243
+
244
+ } // namespace c10::hip
245
+
246
+ #else
247
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
248
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/hip/HIPCachingAllocator.h>
5
+ #include <ATen/hip/impl/HIPAllocatorMasqueradingAsCUDA.h>
6
+ #include <ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h>
7
+
8
+ namespace c10 {
9
+ // forward declaration
10
+ class DataPtr;
11
+ namespace hip {
12
+ namespace HIPCachingAllocatorMasqueradingAsCUDA {
13
+
14
+ C10_HIP_API HIPCachingAllocator::HIPAllocator* get();
15
+ C10_HIP_API void recordStreamMasqueradingAsCUDA(const DataPtr& ptr, HIPStreamMasqueradingAsCUDA stream);
16
+
17
+ inline void* raw_alloc(size_t nbytes) {
18
+ return get()->raw_alloc(nbytes);
19
+ }
20
+
21
+ inline void* raw_alloc_with_stream(size_t nbytes, hipStream_t stream) {
22
+ return get()->raw_alloc_with_stream(nbytes, stream);
23
+ }
24
+
25
+ inline void raw_delete(void* ptr) {
26
+ return get()->raw_delete(ptr);
27
+ }
28
+
29
+ inline void init(int device_count) {
30
+ return get()->init(device_count);
31
+ }
32
+
33
+ inline double getMemoryFraction(c10::DeviceIndex device) {
34
+ return get()->getMemoryFraction(device);
35
+ }
36
+
37
+ inline void setMemoryFraction(double fraction, c10::DeviceIndex device) {
38
+ return get()->setMemoryFraction(fraction, device);
39
+ }
40
+
41
+ inline void emptyCache(MempoolId_t mempool_id = {0, 0}) {
42
+ return get()->emptyCache(mempool_id);
43
+ }
44
+
45
+ inline void enable(bool value) {
46
+ return get()->enable(value);
47
+ }
48
+
49
+ inline bool isEnabled() {
50
+ return get()->isEnabled();
51
+ }
52
+
53
+ inline void cacheInfo(c10::DeviceIndex device, size_t* largestBlock) {
54
+ return get()->cacheInfo(device, largestBlock);
55
+ }
56
+
57
+ inline void* getBaseAllocation(void* ptr, size_t* size) {
58
+ return get()->getBaseAllocation(ptr, size);
59
+ }
60
+
61
+ inline c10::CachingDeviceAllocator::DeviceStats getDeviceStats(
62
+ c10::DeviceIndex device) {
63
+ return get()->getDeviceStats(device);
64
+ }
65
+
66
+ inline void resetAccumulatedStats(c10::DeviceIndex device) {
67
+ return get()->resetAccumulatedStats(device);
68
+ }
69
+
70
+ inline void resetPeakStats(c10::DeviceIndex device) {
71
+ return get()->resetPeakStats(device);
72
+ }
73
+
74
+ inline HIPCachingAllocator::SnapshotInfo snapshot(MempoolId_t mempool_id = {0, 0}) {
75
+ return get()->snapshot(mempool_id);
76
+ }
77
+
78
+ inline std::shared_ptr<HIPCachingAllocator::AllocatorState> getCheckpointState(
79
+ c10::DeviceIndex device,
80
+ MempoolId_t id) {
81
+ return get()->getCheckpointState(device, id);
82
+ }
83
+
84
+ inline HIPCachingAllocator::CheckpointDelta setCheckpointPoolState(
85
+ c10::DeviceIndex device,
86
+ std::shared_ptr<HIPCachingAllocator::AllocatorState> pps) {
87
+ return get()->setCheckpointPoolState(device, std::move(pps));
88
+ }
89
+
90
+ inline void beginAllocateToPool(
91
+ c10::DeviceIndex device,
92
+ MempoolId_t mempool_id,
93
+ std::function<bool(hipStream_t)> filter) {
94
+ get()->beginAllocateToPool(device, mempool_id, std::move(filter));
95
+ }
96
+
97
+ inline void endAllocateToPool(c10::DeviceIndex device, MempoolId_t mempool_id) {
98
+ get()->endAllocateToPool(device, mempool_id);
99
+ }
100
+
101
+ inline void recordHistory(
102
+ bool enabled,
103
+ HIPCachingAllocator::CreateContextFn context_recorder,
104
+ size_t alloc_trace_max_entries,
105
+ HIPCachingAllocator::RecordContext when,
106
+ bool clearHistory) {
107
+ return get()->recordHistory(
108
+ enabled, context_recorder, alloc_trace_max_entries, when, clearHistory);
109
+ }
110
+
111
+ inline void recordAnnotation(
112
+ const std::vector<std::pair<std::string, std::string>>& md) {
113
+ return get()->recordAnnotation(md);
114
+ }
115
+
116
+ inline void pushCompileContext(std::string& md) {
117
+ return get()->pushCompileContext(md);
118
+ }
119
+
120
+ inline void popCompileContext() {
121
+ return get()->popCompileContext();
122
+ }
123
+
124
+ inline bool isHistoryEnabled() {
125
+ return get()->isHistoryEnabled();
126
+ }
127
+
128
+ inline bool checkPoolLiveAllocations(
129
+ c10::DeviceIndex device,
130
+ MempoolId_t mempool_id,
131
+ const std::unordered_set<void*>& expected_live_allocations) {
132
+ return get()->checkPoolLiveAllocations(
133
+ device, mempool_id, expected_live_allocations);
134
+ }
135
+
136
+ inline void attachOutOfMemoryObserver(HIPCachingAllocator::OutOfMemoryObserver observer) {
137
+ return get()->attachOutOfMemoryObserver(std::move(observer));
138
+ }
139
+
140
+ inline void attachAllocatorTraceTracker(HIPCachingAllocator::AllocatorTraceTracker tracker) {
141
+ return get()->attachAllocatorTraceTracker(std::move(tracker));
142
+ }
143
+
144
+ inline void releasePool(c10::DeviceIndex device, MempoolId_t mempool_id) {
145
+ return get()->releasePool(device, mempool_id);
146
+ }
147
+
148
+ inline void createOrIncrefPool(
149
+ c10::DeviceIndex device,
150
+ MempoolId_t mempool_id,
151
+ HIPCachingAllocator::HIPAllocator* allocator_ptr = nullptr) {
152
+ get()->createOrIncrefPool(device, mempool_id, allocator_ptr);
153
+ }
154
+
155
+ inline void setUseOnOOM(c10::DeviceIndex device, MempoolId_t mempool_id) {
156
+ get()->setUseOnOOM(device, mempool_id);
157
+ }
158
+
159
+ inline void setNoSplit(c10::DeviceIndex device, MempoolId_t mempool_id) {
160
+ get()->setNoSplit(device, mempool_id);
161
+ }
162
+
163
+ inline int getPoolUseCount(c10::DeviceIndex device, MempoolId_t mempool_id) {
164
+ return get()->getPoolUseCount(device, mempool_id);
165
+ }
166
+
167
+ inline std::shared_ptr<void> getIpcDevPtr(std::string handle) {
168
+ return get()->getIpcDevPtr(std::move(handle));
169
+ }
170
+
171
+ inline HIPCachingAllocator::ShareableHandle shareIpcHandle(void* ptr) {
172
+ return get()->shareIpcHandle(ptr);
173
+ }
174
+
175
+ inline std::string name() {
176
+ return get()->name();
177
+ }
178
+
179
+ inline hipError_t memcpyAsync(
180
+ void* dst,
181
+ int dstDevice,
182
+ const void* src,
183
+ int srcDevice,
184
+ size_t count,
185
+ hipStream_t stream,
186
+ bool p2p_enabled) {
187
+ return get()->memcpyAsync(
188
+ dst, dstDevice, src, srcDevice, count, stream, p2p_enabled);
189
+ }
190
+
191
+ inline void enablePeerAccess(
192
+ c10::DeviceIndex dev,
193
+ c10::DeviceIndex dev_to_access) {
194
+ return get()->enablePeerAccess(dev, dev_to_access);
195
+ }
196
+
197
+ } // namespace HIPCachingAllocatorMasqueradingAsCUDA
198
+ } // namespace hip
199
+ } // namespace c10
200
+
201
+ #else
202
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
203
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/hip/HIPConfig.h>
5
+
6
+ // The includes of HIPGuard.h
7
+ #include <c10/hip/impl/HIPGuardImpl.h>
8
+ #include <c10/hip/HIPMacros.h>
9
+ #include <c10/core/DeviceType.h>
10
+ #include <c10/core/impl/InlineDeviceGuard.h>
11
+ #include <c10/core/impl/InlineStreamGuard.h>
12
+ #include <c10/util/Exception.h>
13
+
14
+ #include <c10/hip/impl/HIPGuardImpl.h>
15
+
16
+ #include <ATen/hip/impl/HIPCachingAllocatorMasqueradingAsCUDA.h>
17
+ #include <ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h>
18
+
19
+ // Use of c10::hip namespace here makes hipification easier, because
20
+ // I don't have to also fix namespaces. Sorry!
21
+ namespace c10 { namespace hip {
22
+
23
+ // Note [Masquerading as CUDA]
24
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~
25
+ // c10_hip is very easy to understand: it is HIPified from c10_cuda,
26
+ // and anywhere you said CUDA, the source code now says HIP. HIPified
27
+ // PyTorch is much harder to understand: it is HIPified from regular
28
+ // PyTorch, yes, but NO source-to-source translation from CUDA to
29
+ // HIP occurs; instead, anywhere we see "CUDA", it actually means "HIP".
30
+ // For example, when you use HIPified PyTorch, you say x.cuda() to
31
+ // move a tensor onto ROCm device. We call this situation "HIP
32
+ // masquerading as CUDA".
33
+ //
34
+ // This leads to a very awkward situation when we want to call c10_hip
35
+ // code from PyTorch, since c10_hip is expecting things to be called
36
+ // HIP, but PyTorch is calling them CUDA (masquerading as HIP). To
37
+ // fix this impedance mismatch, we have MasqueradingAsCUDA variants
38
+ // for all c10_hip classes. These translate between the "HIP" and "CUDA
39
+ // masquerading as HIP" worlds. For example,
40
+ // HIPGuardImplMasqueradingAsCUDA (this file) provides something like a
41
+ // HIPGuardImpl, but it reports its DeviceType as CUDA (e.g., type()
42
+ // returns CUDA, getDevice() reports the current HIP device as a CUDA
43
+ // device.)
44
+ //
45
+ // We should be able to delete all of these classes entirely once
46
+ // we switch PyTorch to calling a HIP a HIP.
47
+ //
48
+ // When you add a new MasqueradingAsCUDA class/function, you need to
49
+ // also update the rewrite rules in torch/utils/hipify/cuda_to_hip_mappings.py
50
+ //
51
+ //
52
+ //
53
+ // By the way, note that the cpp file associated with this also
54
+ // *overwrites* the entry in the DeviceGuardImpl registry for CUDA with
55
+ // this HIP implementation.
56
+
57
+ struct HIPGuardImplMasqueradingAsCUDA final : public c10::impl::DeviceGuardImplInterface {
58
+ static constexpr c10::DeviceType static_type = c10::DeviceType::CUDA;
59
+ HIPGuardImplMasqueradingAsCUDA() {}
60
+ HIPGuardImplMasqueradingAsCUDA(c10::DeviceType t) {
61
+ TORCH_INTERNAL_ASSERT(t == c10::DeviceType::CUDA);
62
+ }
63
+ c10::DeviceType type() const override {
64
+ return c10::DeviceType::CUDA;
65
+ }
66
+ Device exchangeDevice(Device d) const override {
67
+ TORCH_INTERNAL_ASSERT(d.is_cuda());
68
+ Device old_device = getDevice();
69
+ if (old_device.index() != d.index()) {
70
+ C10_HIP_CHECK(hipSetDevice(d.index()));
71
+ }
72
+ return old_device;
73
+ }
74
+ Device getDevice() const override {
75
+ int device;
76
+ C10_HIP_CHECK(hipGetDevice(&device));
77
+ return Device(c10::DeviceType::CUDA, device);
78
+ }
79
+ void setDevice(Device d) const override {
80
+ TORCH_INTERNAL_ASSERT(d.is_cuda());
81
+ C10_HIP_CHECK(hipSetDevice(d.index()));
82
+ }
83
+ void uncheckedSetDevice(Device d) const noexcept override {
84
+ C10_HIP_CHECK_WARN(hipSetDevice(d.index()));
85
+ }
86
+ Stream getStream(Device d) const override {
87
+ return getCurrentHIPStreamMasqueradingAsCUDA(d.index()).unwrap();
88
+ }
89
+ Stream getDefaultStream(Device d) const override {
90
+ return getDefaultHIPStreamMasqueradingAsCUDA(d.index());
91
+ }
92
+ Stream getNewStream(Device d, int priority = 0) const override {
93
+ return getStreamFromPoolMasqueradingAsCUDA(priority, d.index());
94
+ }
95
+ Stream getStreamFromGlobalPool(Device d, bool isHighPriority = false) const override {
96
+ return getStreamFromPoolMasqueradingAsCUDA(isHighPriority, d.index());
97
+ }
98
+ Stream exchangeStream(Stream s) const override {
99
+ HIPStreamMasqueradingAsCUDA cs(s);
100
+ auto old_stream = getCurrentHIPStreamMasqueradingAsCUDA(s.device().index());
101
+ setCurrentHIPStreamMasqueradingAsCUDA(cs);
102
+ return old_stream.unwrap();
103
+ }
104
+ DeviceIndex deviceCount() const noexcept override {
105
+ int deviceCnt;
106
+ hipError_t _err;
107
+ _err = hipGetDeviceCount(&deviceCnt);
108
+ if(_err != hipErrorNoDevice && _err != hipSuccess)
109
+ C10_HIP_CHECK(_err);
110
+ return deviceCnt;
111
+ }
112
+
113
+ // Event-related functions
114
+ // Note: hipEventCreateWithFlags should be called on the same device as
115
+ // the recording stream's device.
116
+ void createEvent(
117
+ hipEvent_t* hip_event,
118
+ const EventFlag flag) const {
119
+ // Maps PyTorch's Event::Flag to HIP flag
120
+ auto hip_flag = hipEventDefault;
121
+ switch (flag) {
122
+ case EventFlag::PYTORCH_DEFAULT:
123
+ hip_flag = hipEventDisableTiming;
124
+ break;
125
+ case EventFlag::BACKEND_DEFAULT:
126
+ hip_flag = hipEventDefault;
127
+ break;
128
+ default:
129
+ TORCH_CHECK(false, "HIP event received unknown flag");
130
+ }
131
+
132
+ C10_HIP_CHECK(hipEventCreateWithFlags(hip_event, hip_flag));
133
+ }
134
+
135
+ void destroyEvent(
136
+ void* event,
137
+ const DeviceIndex device_index) const noexcept override {
138
+ if (!event) return;
139
+ auto hip_event = static_cast<hipEvent_t>(event);
140
+ int orig_device;
141
+ C10_HIP_CHECK_WARN(hipGetDevice(&orig_device));
142
+ C10_HIP_CHECK_WARN(hipSetDevice(device_index));
143
+ C10_HIP_CHECK_WARN(hipEventDestroy(hip_event));
144
+ C10_HIP_CHECK_WARN(hipSetDevice(orig_device));
145
+ }
146
+
147
+ void record(void** event,
148
+ const Stream& stream,
149
+ const DeviceIndex device_index,
150
+ const EventFlag flag) const override {
151
+ TORCH_CHECK(device_index == -1 || device_index == stream.device_index(),
152
+ "Event device index ",
153
+ device_index,
154
+ " does not match recording stream's device index ",
155
+ stream.device_index(),
156
+ ".");
157
+
158
+ hipEvent_t hip_event = static_cast<hipEvent_t>(*event);
159
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
160
+
161
+ // Moves to stream's device to record
162
+ const auto orig_device = getDevice();
163
+ setDevice(stream.device());
164
+
165
+ // Creates the event (lazily)
166
+ if (!hip_event) createEvent(&hip_event, flag);
167
+ C10_HIP_CHECK(hipEventRecord(hip_event, hip_stream));
168
+ // Makes the void* point to the (possibly just allocated) HIP event
169
+ *event = hip_event;
170
+
171
+ // Resets device
172
+ setDevice(orig_device);
173
+ }
174
+
175
+ void block(
176
+ void* event,
177
+ const Stream& stream) const override {
178
+ if (!event) return;
179
+ hipEvent_t hip_event = static_cast<hipEvent_t>(event);
180
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
181
+ const auto orig_device = getDevice();
182
+ setDevice(stream.device());
183
+ C10_HIP_CHECK(hipStreamWaitEvent(
184
+ hip_stream,
185
+ hip_event,
186
+ /*flags (must be zero)=*/ 0));
187
+ setDevice(orig_device);
188
+ }
189
+
190
+ bool queryEvent(void* event) const override {
191
+ if (!event) return true;
192
+ hipEvent_t hip_event = static_cast<hipEvent_t>(event);
193
+ const hipError_t err = hipEventQuery(hip_event);
194
+ if (err != hipErrorNotReady) C10_HIP_CHECK(err);
195
+ else {
196
+ // ignore and clear the error if not ready
197
+ (void)hipGetLastError();
198
+ }
199
+ return (err == hipSuccess);
200
+ }
201
+
202
+ // Stream-related functions
203
+ bool queryStream(const Stream& stream) const override {
204
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
205
+ return hip_stream.query();
206
+ }
207
+
208
+ void synchronizeStream(const Stream& stream) const override {
209
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
210
+ hip_stream.synchronize();
211
+ }
212
+
213
+ void synchronizeEvent(void* event) const override {
214
+ if (!event)
215
+ return;
216
+ hipEvent_t hip_event = static_cast<hipEvent_t>(event);
217
+ C10_HIP_CHECK(hipEventSynchronize(hip_event));
218
+ }
219
+
220
+ // Note: synchronizeDevice can be safely called from any device
221
+ void synchronizeDevice(const c10::DeviceIndex device_index) const override {
222
+ int orig_device{-1};
223
+ C10_HIP_CHECK(hipGetDevice(&orig_device));
224
+ C10_HIP_CHECK(hipSetDevice(device_index));
225
+ C10_HIP_CHECK(hipDeviceSynchronize());
226
+ C10_HIP_CHECK(hipSetDevice(orig_device));
227
+ }
228
+
229
+ void recordDataPtrOnStream(
230
+ const c10::DataPtr& data_ptr,
231
+ const Stream& stream) const override {
232
+ HIPStreamMasqueradingAsCUDA hip_stream{stream};
233
+ HIPCachingAllocatorMasqueradingAsCUDA::recordStreamMasqueradingAsCUDA(data_ptr, hip_stream);
234
+ }
235
+
236
+ double elapsedTime(void* event1, void* event2, const DeviceIndex device_index)
237
+ const override {
238
+ TORCH_CHECK(
239
+ event1 && event2,
240
+ "Both events must be recorded before calculating elapsed time.");
241
+ int orig_device;
242
+ C10_HIP_CHECK(hipGetDevice(&orig_device));
243
+ C10_HIP_CHECK(hipSetDevice(device_index));
244
+ hipEvent_t hip_event1 = static_cast<hipEvent_t>(event1);
245
+ hipEvent_t hip_event2 = static_cast<hipEvent_t>(event2);
246
+ float time_ms = 0;
247
+ // raise hipErrorNotReady if either event is recorded but not yet completed
248
+ C10_HIP_CHECK(hipEventElapsedTime(&time_ms, hip_event1, hip_event2));
249
+ C10_HIP_CHECK(hipSetDevice(orig_device));
250
+ return static_cast<double>(time_ms);
251
+ }
252
+ };
253
+
254
+ // All of the guards which have HIPGuardImpl burned in need to also have
255
+ // variants using HIPGuardImplMasqueradingAsCUDA.
256
+
257
+ /// This code is all a direct copy from c10/cuda/HIPGuardMasqueradingAsCUDA.h, but with
258
+ /// the correct InlineDeviceGuard burned in. Sorry about the
259
+ /// copy-pasting.
260
+
261
+ struct HIPGuardMasqueradingAsCUDA {
262
+ explicit HIPGuardMasqueradingAsCUDA() = delete;
263
+ explicit HIPGuardMasqueradingAsCUDA(DeviceIndex device_index) : guard_(device_index) {}
264
+ explicit HIPGuardMasqueradingAsCUDA(Device device) : guard_(device) {}
265
+
266
+ HIPGuardMasqueradingAsCUDA(const HIPGuardMasqueradingAsCUDA&) = delete;
267
+ HIPGuardMasqueradingAsCUDA& operator=(const HIPGuardMasqueradingAsCUDA&) = delete;
268
+ HIPGuardMasqueradingAsCUDA(HIPGuardMasqueradingAsCUDA&& other) = delete;
269
+ HIPGuardMasqueradingAsCUDA& operator=(HIPGuardMasqueradingAsCUDA&& other) = delete;
270
+
271
+ void set_device(Device device) { guard_.set_device(device); }
272
+ void reset_device(Device device) { guard_.reset_device(device); }
273
+ void set_index(DeviceIndex device_index) { guard_.set_index(device_index); }
274
+ Device original_device() const { return guard_.original_device(); }
275
+ Device current_device() const { return guard_.current_device(); }
276
+
277
+ private:
278
+ c10::impl::InlineDeviceGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
279
+ };
280
+
281
+ struct OptionalHIPGuardMasqueradingAsCUDA {
282
+ explicit OptionalHIPGuardMasqueradingAsCUDA() : guard_() {}
283
+ explicit OptionalHIPGuardMasqueradingAsCUDA(std::optional<Device> device_opt) : guard_(device_opt) {}
284
+ explicit OptionalHIPGuardMasqueradingAsCUDA(std::optional<DeviceIndex> device_index_opt) : guard_(device_index_opt) {}
285
+
286
+ OptionalHIPGuardMasqueradingAsCUDA(const OptionalHIPGuardMasqueradingAsCUDA&) = delete;
287
+ OptionalHIPGuardMasqueradingAsCUDA& operator=(const OptionalHIPGuardMasqueradingAsCUDA&) = delete;
288
+ OptionalHIPGuardMasqueradingAsCUDA(OptionalHIPGuardMasqueradingAsCUDA&& other) = delete;
289
+ OptionalHIPGuardMasqueradingAsCUDA& operator=(OptionalHIPGuardMasqueradingAsCUDA&& other) = delete;
290
+
291
+ void set_device(Device device) { guard_.set_device(device); }
292
+ void reset_device(Device device) { guard_.reset_device(device); }
293
+ void set_index(DeviceIndex device_index) { guard_.set_index(device_index); }
294
+ std::optional<Device> original_device() const { return guard_.original_device(); }
295
+ std::optional<Device> current_device() const { return guard_.current_device(); }
296
+ void reset() { guard_.reset(); }
297
+
298
+ private:
299
+ c10::impl::InlineOptionalDeviceGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
300
+ };
301
+
302
+ struct HIPStreamGuardMasqueradingAsCUDA {
303
+ explicit HIPStreamGuardMasqueradingAsCUDA() = delete;
304
+ explicit HIPStreamGuardMasqueradingAsCUDA(Stream stream) : guard_(stream) {}
305
+ HIPStreamGuardMasqueradingAsCUDA(const HIPStreamGuardMasqueradingAsCUDA&) = delete;
306
+ HIPStreamGuardMasqueradingAsCUDA& operator=(const HIPStreamGuardMasqueradingAsCUDA&) = delete;
307
+ HIPStreamGuardMasqueradingAsCUDA(HIPStreamGuardMasqueradingAsCUDA&& other) = delete;
308
+ HIPStreamGuardMasqueradingAsCUDA& operator=(HIPStreamGuardMasqueradingAsCUDA&& other) = delete;
309
+
310
+ void reset_stream(Stream stream) { guard_.reset_stream(stream); }
311
+
312
+ HIPStreamMasqueradingAsCUDA original_stream() const {
313
+ return HIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA::UNCHECKED, guard_.original_stream());
314
+ }
315
+ HIPStreamMasqueradingAsCUDA current_stream() const {
316
+ return HIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA::UNCHECKED, guard_.current_stream());
317
+ }
318
+
319
+ Device current_device() const { return guard_.current_device(); }
320
+ Device original_device() const { return guard_.original_device(); }
321
+
322
+ private:
323
+ c10::impl::InlineStreamGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
324
+ };
325
+
326
+ struct OptionalHIPStreamGuardMasqueradingAsCUDA {
327
+ explicit OptionalHIPStreamGuardMasqueradingAsCUDA() : guard_() {}
328
+ explicit OptionalHIPStreamGuardMasqueradingAsCUDA(Stream stream) : guard_(stream) {}
329
+ explicit OptionalHIPStreamGuardMasqueradingAsCUDA(std::optional<Stream> stream_opt) : guard_(stream_opt) {}
330
+
331
+ OptionalHIPStreamGuardMasqueradingAsCUDA(const OptionalHIPStreamGuardMasqueradingAsCUDA&) = delete;
332
+ OptionalHIPStreamGuardMasqueradingAsCUDA& operator=(const OptionalHIPStreamGuardMasqueradingAsCUDA&) = delete;
333
+ OptionalHIPStreamGuardMasqueradingAsCUDA(OptionalHIPStreamGuardMasqueradingAsCUDA&& other) = delete;
334
+ OptionalHIPStreamGuardMasqueradingAsCUDA& operator=(OptionalHIPStreamGuardMasqueradingAsCUDA&& other) = delete;
335
+
336
+ void reset_stream(Stream stream) { guard_.reset_stream(stream); }
337
+
338
+ std::optional<HIPStreamMasqueradingAsCUDA> original_stream() const {
339
+ auto r = guard_.original_stream();
340
+ if (r.has_value()) {
341
+ return HIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA::UNCHECKED, r.value());
342
+ } else {
343
+ return std::nullopt;
344
+ }
345
+ }
346
+
347
+ std::optional<HIPStreamMasqueradingAsCUDA> current_stream() const {
348
+ auto r = guard_.current_stream();
349
+ if (r.has_value()) {
350
+ return HIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA::UNCHECKED, r.value());
351
+ } else {
352
+ return std::nullopt;
353
+ }
354
+ }
355
+
356
+ void reset() { guard_.reset(); }
357
+
358
+ private:
359
+ c10::impl::InlineOptionalStreamGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
360
+ };
361
+
362
+ struct HIPMultiStreamGuardMasqueradingAsCUDA {
363
+ explicit HIPMultiStreamGuardMasqueradingAsCUDA(ArrayRef<HIPStreamMasqueradingAsCUDA> streams)
364
+ : guard_(unwrapStreams(streams)) {}
365
+
366
+ HIPMultiStreamGuardMasqueradingAsCUDA(const HIPMultiStreamGuardMasqueradingAsCUDA&) = delete;
367
+ HIPMultiStreamGuardMasqueradingAsCUDA& operator=(const HIPMultiStreamGuardMasqueradingAsCUDA&) = delete;
368
+ HIPMultiStreamGuardMasqueradingAsCUDA(HIPMultiStreamGuardMasqueradingAsCUDA&& other) = delete;
369
+ HIPMultiStreamGuardMasqueradingAsCUDA& operator=(HIPMultiStreamGuardMasqueradingAsCUDA&& other) = delete;
370
+
371
+ private:
372
+ c10::impl::InlineMultiStreamGuard<HIPGuardImplMasqueradingAsCUDA> guard_;
373
+
374
+ static std::vector<Stream> unwrapStreams(ArrayRef<HIPStreamMasqueradingAsCUDA> hipStreams) {
375
+ std::vector<Stream> streams;
376
+ streams.reserve(hipStreams.size());
377
+ for (const HIPStreamMasqueradingAsCUDA& hipStream : hipStreams) {
378
+ streams.push_back(hipStream);
379
+ }
380
+ return streams;
381
+ }
382
+ };
383
+
384
+ }} // namespace c10::hip
385
+
386
+ #else
387
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
388
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/hip/impl/HIPStreamMasqueradingAsCUDA.h ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/hip/HIPStream.h>
5
+
6
+ // Use of c10::hip namespace here makes hipification easier, because
7
+ // I don't have to also fix namespaces. Sorry!
8
+ namespace c10 { namespace hip {
9
+
10
+ // See Note [Masquerading as CUDA] for motivation
11
+
12
+ class HIPStreamMasqueradingAsCUDA {
13
+ public:
14
+
15
+ enum Unchecked { UNCHECKED };
16
+
17
+ explicit HIPStreamMasqueradingAsCUDA(Stream stream)
18
+ : HIPStreamMasqueradingAsCUDA(UNCHECKED, stream) {
19
+ // We did the coercion unchecked; check that it was right.
20
+ TORCH_CHECK(stream.device().is_cuda() /* !!! */);
21
+ }
22
+
23
+ explicit HIPStreamMasqueradingAsCUDA(Unchecked, Stream stream)
24
+ // Unsafely coerce the "CUDA" stream into a HIP stream
25
+ : stream_(
26
+ HIPStream(
27
+ Stream(
28
+ Stream::UNSAFE,
29
+ Device(c10::DeviceType::HIP, stream.device_index()),
30
+ stream.id())
31
+ )
32
+ ) {}
33
+
34
+ // New constructor, just for this. Does NOT coerce.
35
+ explicit HIPStreamMasqueradingAsCUDA(HIPStream stream) : stream_(stream) {}
36
+
37
+ bool operator==(const HIPStreamMasqueradingAsCUDA& other) const noexcept {
38
+ return stream_ == other.stream_;
39
+ }
40
+
41
+ bool operator!=(const HIPStreamMasqueradingAsCUDA& other) const noexcept {
42
+ return stream_ != other.stream_;
43
+ }
44
+
45
+ operator hipStream_t() const { return stream_.stream(); }
46
+
47
+ operator Stream() const {
48
+ // Unsafely coerce HIP stream into a "CUDA" stream
49
+ return Stream(Stream::UNSAFE, device(), id());
50
+ }
51
+
52
+ DeviceIndex device_index() const { return stream_.device_index(); }
53
+
54
+ // Unsafely coerce HIP device into CUDA device
55
+ c10::DeviceType device_type() const { return c10::DeviceType::CUDA; }
56
+
57
+ Device device() const {
58
+ // Unsafely coerce HIP device into CUDA device
59
+ return Device(c10::DeviceType::CUDA, stream_.device_index());
60
+ }
61
+
62
+ StreamId id() const { return stream_.id(); }
63
+ bool query() const { return stream_.query(); }
64
+ void synchronize() const { stream_.synchronize(); }
65
+ int priority() const { return stream_.priority(); }
66
+ hipStream_t stream() const { return stream_.stream(); }
67
+
68
+ Stream unwrap() const {
69
+ // Unsafely coerce HIP stream into "CUDA" stream
70
+ return Stream(Stream::UNSAFE, device(), id());
71
+ }
72
+
73
+ c10::StreamData3 pack3() const noexcept {
74
+ // Unsafely coerce HIP stream into "CUDA" stream before packing
75
+ return unwrap().pack3();
76
+ }
77
+
78
+ static HIPStreamMasqueradingAsCUDA unpack3(StreamId stream_id,
79
+ DeviceIndex device_index,
80
+ c10::DeviceType device_type) {
81
+ // NB: constructor manages CUDA->HIP translation for us
82
+ return HIPStreamMasqueradingAsCUDA(Stream::unpack3(
83
+ stream_id, device_index, device_type));
84
+ }
85
+
86
+ static std::tuple<int, int> priority_range() { return HIPStream::priority_range(); }
87
+
88
+ // New method, gets the underlying HIPStream
89
+ HIPStream hip_stream() const { return stream_; }
90
+
91
+ private:
92
+ HIPStream stream_;
93
+ };
94
+
95
+ HIPStreamMasqueradingAsCUDA
96
+ inline getStreamFromPoolMasqueradingAsCUDA(const bool isHighPriority = false, DeviceIndex device = -1) {
97
+ return HIPStreamMasqueradingAsCUDA(getStreamFromPool(isHighPriority, device));
98
+ }
99
+
100
+ HIPStreamMasqueradingAsCUDA
101
+ inline getStreamFromPoolMasqueradingAsCUDA(const int priority, DeviceIndex device = -1) {
102
+ return HIPStreamMasqueradingAsCUDA(getStreamFromPool(priority, device));
103
+ }
104
+
105
+ HIPStreamMasqueradingAsCUDA
106
+ inline getStreamFromExternalMasqueradingAsCUDA(hipStream_t ext_stream, DeviceIndex device) {
107
+ return HIPStreamMasqueradingAsCUDA(getStreamFromExternal(ext_stream, device));
108
+ }
109
+
110
+ inline HIPStreamMasqueradingAsCUDA getDefaultHIPStreamMasqueradingAsCUDA(DeviceIndex device_index = -1) {
111
+ return HIPStreamMasqueradingAsCUDA(getDefaultHIPStream(device_index));
112
+ }
113
+
114
+ inline HIPStreamMasqueradingAsCUDA getCurrentHIPStreamMasqueradingAsCUDA(DeviceIndex device_index = -1) {
115
+ return HIPStreamMasqueradingAsCUDA(getCurrentHIPStream(device_index));
116
+ }
117
+
118
+ inline void setCurrentHIPStreamMasqueradingAsCUDA(HIPStreamMasqueradingAsCUDA stream) {
119
+ setCurrentHIPStream(stream.hip_stream());
120
+ }
121
+
122
+ inline std::ostream& operator<<(std::ostream& stream, const HIPStreamMasqueradingAsCUDA& s) {
123
+ stream << s.hip_stream() << " (masquerading as CUDA)";
124
+ return stream;
125
+ }
126
+
127
+ }} // namespace c10::hip
128
+
129
+ namespace std {
130
+ template <>
131
+ struct hash<c10::hip::HIPStreamMasqueradingAsCUDA> {
132
+ size_t operator()(c10::hip::HIPStreamMasqueradingAsCUDA s) const noexcept {
133
+ return std::hash<c10::Stream>{}(s.unwrap());
134
+ }
135
+ };
136
+ } // namespace std
137
+
138
+ #else
139
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
140
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/metal/Context.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #ifndef MetalContext_h
3
+ #define MetalContext_h
4
+
5
+ #include <atomic>
6
+
7
+ #include <ATen/Tensor.h>
8
+
9
+ namespace at::metal {
10
+
11
+ struct MetalInterface {
12
+ virtual ~MetalInterface() = default;
13
+ virtual bool is_metal_available() const = 0;
14
+ virtual at::Tensor& metal_copy_(at::Tensor& self, const at::Tensor& src)
15
+ const = 0;
16
+ };
17
+
18
+ extern std::atomic<const MetalInterface*> g_metal_impl_registry;
19
+
20
+ class MetalImplRegistrar {
21
+ public:
22
+ explicit MetalImplRegistrar(MetalInterface* /*impl*/);
23
+ };
24
+
25
+ at::Tensor& metal_copy_(at::Tensor& self, const at::Tensor& src);
26
+
27
+ } // namespace at::metal
28
+
29
+ namespace at::native {
30
+ bool is_metal_available();
31
+ } // namespace at::native
32
+
33
+ #endif /* MetalContext_h */
34
+
35
+ #else
36
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
37
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Descriptors.h ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/miopen/Exceptions.h>
5
+
6
+ #include <ATen/miopen/miopen-wrapper.h>
7
+ #include <ATen/core/Tensor.h>
8
+ #include <ATen/TensorUtils.h>
9
+ #include <c10/macros/Export.h>
10
+
11
+ namespace at { namespace native {
12
+
13
+ std::string miopenTypeToString(miopenDataType_t dtype);
14
+
15
+ inline int dataSize(miopenDataType_t dataType)
16
+ {
17
+ switch (dataType) {
18
+ case miopenHalf: return 2;
19
+ case miopenFloat: return 4;
20
+ case miopenBFloat16: return 2;
21
+ default: return 8;
22
+ }
23
+ }
24
+
25
+ // See NOTE [ cudnn fixSizeOneDimStride ] in aten/src/ATen/cudnn/Descriptors.h
26
+ template <typename T>
27
+ static inline void fixSizeOneDimStride(int dim, const T *size, T *stride, bool nhwc) {
28
+ int64_t z = 1;
29
+ int index = 0;
30
+ std::vector<int> permutation(dim);
31
+
32
+ if (nhwc) {
33
+ permutation[index++] = 1;
34
+ }
35
+ for (int d = dim-1; d > 1; d--) {
36
+ permutation[index++] = d;
37
+ }
38
+ if (!nhwc) {
39
+ permutation[index++] = 1;
40
+ }
41
+ permutation[index++] = 0;
42
+ for (int d : permutation) {
43
+ if (size[d] == 1) {
44
+ stride[d] = z;
45
+ } else {
46
+ z *= size[d];
47
+ }
48
+ }
49
+ }
50
+
51
+ template <typename T, miopenStatus_t (*dtor)(T*)>
52
+ struct DescriptorDeleter {
53
+ void operator()(T* x) {
54
+ if (x != nullptr) {
55
+ MIOPEN_CHECK(dtor(x));
56
+ }
57
+ }
58
+ };
59
+
60
+ // A generic class for wrapping MIOpen descriptor types. All you need
61
+ // is to give the underlying type the Descriptor_t points to (usually,
62
+ // if it's miopenTensorDescriptor_t it points to miopenTensorStruct),
63
+ // the constructor and the destructor. Subclasses are responsible
64
+ // for defining a set() function to actually set the descriptor.
65
+ //
66
+ // Descriptors default construct to a nullptr, and have a descriptor
67
+ // initialized the first time you call set() or any other initializing
68
+ // function.
69
+ template <typename T, miopenStatus_t (*ctor)(T**), miopenStatus_t (*dtor)(T*)>
70
+ // NOLINTNEXTLINE(bugprone-exception-escape)
71
+ class TORCH_HIP_CPP_API Descriptor {
72
+ public:
73
+ // Use desc() to access the underlying descriptor pointer in
74
+ // a read-only fashion. Most client code should use this.
75
+ // If the descriptor was never initialized, this will return
76
+ // nullptr.
77
+ T* desc() const { return desc_.get(); }
78
+ T* desc() { return desc_.get(); }
79
+
80
+ // Use mut_desc() to access the underlying descriptor pointer
81
+ // if you intend to modify what it points to (e.g., using
82
+ // miopenSetFooDescriptor). This will ensure that the descriptor
83
+ // is initialized. Code in this file will use this function.
84
+ T* mut_desc() { init(); return desc_.get(); }
85
+ protected:
86
+ void init() {
87
+ if (desc_ == nullptr) {
88
+ T* raw_desc = nullptr;
89
+ MIOPEN_CHECK(ctor(&raw_desc));
90
+ desc_.reset(raw_desc);
91
+ }
92
+ }
93
+ private:
94
+ std::unique_ptr<T, DescriptorDeleter<T, dtor>> desc_;
95
+ };
96
+
97
+ class TORCH_HIP_CPP_API TensorDescriptor : public Descriptor<
98
+ miopenTensorDescriptor,
99
+ &miopenCreateTensorDescriptor,
100
+ &miopenDestroyTensorDescriptor> {
101
+ public:
102
+ TensorDescriptor() = default;
103
+ explicit TensorDescriptor(const at::Tensor &t, size_t pad = 0) {
104
+ set(t, pad);
105
+ }
106
+
107
+ // See Note [CuDNN broadcast padding]
108
+ void set(const at::Tensor &t, size_t pad = 0);
109
+ void set(const at::Tensor &t, at::MemoryFormat memory_format, size_t pad = 0);
110
+ void set(miopenDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad = 0);
111
+
112
+ void print();
113
+
114
+ private:
115
+ void set(miopenDataType_t dataType, IntArrayRef sizes, IntArrayRef strides, size_t pad, bool nhwc);
116
+
117
+ void set(miopenDataType_t dataType, int dim, int* size, int* stride, bool nhwc) {
118
+ std::vector<int> strides_copy(stride, stride + dim);
119
+ fixSizeOneDimStride<int>(dim, size, strides_copy.data(), nhwc);
120
+ MIOPEN_CHECK(miopenSetTensorDescriptor(mut_desc(), dataType, dim, size, strides_copy.data()));
121
+ }
122
+ };
123
+
124
+ std::ostream& operator<<(std::ostream & out, const TensorDescriptor& d);
125
+
126
+ class TORCH_HIP_CPP_API FilterDescriptor : public Descriptor<
127
+ miopenTensorDescriptor,
128
+ &miopenCreateTensorDescriptor,
129
+ &miopenDestroyTensorDescriptor> {
130
+ public:
131
+ void set(const at::Tensor &t, int64_t pad = 0) {
132
+ set(t, at::MemoryFormat::Contiguous, pad);
133
+ }
134
+
135
+ void set(const at::Tensor &t, const at::MemoryFormat memory_format, int64_t pad = 0);
136
+
137
+ private:
138
+ void set(miopenDataType_t dataType, int dim, int* size, int* stride, bool nhwc) {
139
+ std::vector<int> strides_copy(stride, stride + dim);
140
+ fixSizeOneDimStride<int>(dim, size, strides_copy.data(), nhwc);
141
+ MIOPEN_CHECK(miopenSetTensorDescriptor(mut_desc(), dataType, dim, size, strides_copy.data()));
142
+ }
143
+ };
144
+
145
+ struct TORCH_HIP_CPP_API ConvolutionDescriptor
146
+ : public Descriptor<
147
+ miopenConvolutionDescriptor,
148
+ &miopenCreateConvolutionDescriptor,
149
+ &miopenDestroyConvolutionDescriptor> {
150
+ void set(miopenDataType_t dataType, miopenConvolutionMode_t c_mode, int dim, int* pad, int* stride, int * upscale /* aka dilation */, int groups, bool benchmark, bool deterministic) {
151
+ MIOPEN_CHECK(miopenInitConvolutionNdDescriptor(mut_desc(), dim, pad, stride, upscale, c_mode));
152
+ MIOPEN_CHECK(miopenSetConvolutionGroupCount(mut_desc(), groups));
153
+ MIOPEN_CHECK(miopenSetConvolutionAttribute(mut_desc(), MIOPEN_CONVOLUTION_ATTRIB_DETERMINISTIC, deterministic ? 1 : 0));
154
+ if (benchmark) {
155
+ MIOPEN_CHECK(miopenSetConvolutionFindMode(mut_desc(), miopenConvolutionFindModeNormal));
156
+ }
157
+ }
158
+ };
159
+
160
+ // NOLINTNEXTLINE(bugprone-exception-escape)
161
+ struct TORCH_HIP_CPP_API DropoutDescriptor
162
+ : public Descriptor<
163
+ miopenDropoutDescriptor,
164
+ &miopenCreateDropoutDescriptor,
165
+ &miopenDestroyDropoutDescriptor> {
166
+ void set(miopenHandle_t handle, float dropout, void* states, size_t stateSizeInBytes,
167
+ unsigned long long seed, bool use_mask, bool state_evo, miopenRNGType_t rng_mode) {
168
+ MIOPEN_CHECK(miopenSetDropoutDescriptor(mut_desc(), handle, dropout, states, stateSizeInBytes, seed, use_mask, state_evo, rng_mode));
169
+ }
170
+
171
+ void restore(miopenHandle_t handle, float dropout, void* states, size_t stateSizeInBytes,
172
+ unsigned long long seed, bool use_mask, bool state_evo, miopenRNGType_t rng_mode) {
173
+ MIOPEN_CHECK(miopenRestoreDropoutDescriptor(mut_desc(), handle, dropout, states, stateSizeInBytes, seed, use_mask, state_evo, rng_mode));
174
+ }
175
+ };
176
+
177
+ struct TORCH_HIP_CPP_API RNNDescriptor
178
+ : public Descriptor<miopenRNNDescriptor,
179
+ &miopenCreateRNNDescriptor,
180
+ &miopenDestroyRNNDescriptor>
181
+ {
182
+ void set(int64_t hidden_size, int64_t num_layers, miopenRNNInputMode_t input_mode, miopenRNNDirectionMode_t direction, miopenRNNMode_t rnn_mode,
183
+ miopenRNNBiasMode_t bias_mode, miopenRNNAlgo_t algorithm, miopenDataType_t datatype) {
184
+ MIOPEN_CHECK(miopenSetRNNDescriptor(mut_desc(), hidden_size, num_layers, input_mode, direction, rnn_mode, bias_mode, algorithm, datatype));
185
+ }
186
+
187
+ void setWithDropout(DropoutDescriptor& dropout_desc, int64_t hidden_size, int64_t num_layers, miopenRNNInputMode_t input_mode, miopenRNNDirectionMode_t direction,
188
+ miopenRNNMode_t rnn_mode, miopenRNNBiasMode_t bias_mode, miopenRNNAlgo_t algorithm, miopenDataType_t datatype) {
189
+ MIOPEN_CHECK(miopenSetRNNDescriptor_V2(mut_desc(), hidden_size, num_layers, dropout_desc.mut_desc(), input_mode, direction, rnn_mode, bias_mode, algorithm, datatype));
190
+ }
191
+ };
192
+
193
+ union Constant
194
+ {
195
+ float f;
196
+ double d;
197
+ Constant(miopenDataType_t dataType, double value) {
198
+ if (dataType == miopenHalf || dataType == miopenFloat || dataType == miopenBFloat16) {
199
+ f = static_cast<float>(value);
200
+ } else {
201
+ d = value;
202
+ }
203
+ }
204
+ };
205
+
206
+ }} // namespace
207
+
208
+ #else
209
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
210
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Exceptions.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/miopen/miopen-wrapper.h>
5
+ #include <string>
6
+ #include <stdexcept>
7
+ #include <sstream>
8
+
9
+ namespace at { namespace native {
10
+
11
+ class miopen_exception : public std::runtime_error {
12
+ public:
13
+ miopenStatus_t status;
14
+ miopen_exception(miopenStatus_t status, const char* msg)
15
+ : std::runtime_error(msg)
16
+ , status(status) {}
17
+ miopen_exception(miopenStatus_t status, const std::string& msg)
18
+ : std::runtime_error(msg)
19
+ , status(status) {}
20
+ };
21
+
22
+ inline void MIOPEN_CHECK(miopenStatus_t status)
23
+ {
24
+ if (status != miopenStatusSuccess) {
25
+ if (status == miopenStatusNotImplemented) {
26
+ throw miopen_exception(status, std::string(miopenGetErrorString(status)) +
27
+ ". This error may appear if you passed in a non-contiguous input.");
28
+ }
29
+ throw miopen_exception(status, miopenGetErrorString(status));
30
+ }
31
+ }
32
+
33
+ inline void HIP_CHECK(hipError_t error)
34
+ {
35
+ if (error != hipSuccess) {
36
+ std::string msg("HIP error: ");
37
+ msg += hipGetErrorString(error);
38
+ throw std::runtime_error(msg);
39
+ }
40
+ }
41
+
42
+ }} // namespace at::native
43
+
44
+ #else
45
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
46
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Handle.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/miopen/miopen-wrapper.h>
5
+ #include <c10/macros/Export.h>
6
+
7
+ namespace at::native {
8
+
9
+ TORCH_HIP_CPP_API miopenHandle_t getMiopenHandle();
10
+ } // namespace at::native
11
+
12
+ #else
13
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
14
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Types.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Tensor.h>
5
+ #include <ATen/miopen/miopen-wrapper.h>
6
+ #include <c10/macros/Export.h>
7
+
8
+ namespace at::native {
9
+
10
+ TORCH_HIP_CPP_API miopenDataType_t getMiopenDataType(const at::Tensor& tensor);
11
+
12
+ int64_t miopen_version();
13
+
14
+ } // namespace at::native
15
+
16
+ #else
17
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
18
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/Utils.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/miopen/miopen-wrapper.h>
6
+ #include <ATen/miopen/Handle.h>
7
+
8
+ namespace at { namespace native {
9
+
10
+ // This function makes tensors which have zero stride contiguous, by
11
+ // setting the strides to 1.
12
+ inline Tensor contiguousIfZeroInStrides(const Tensor& t) {
13
+ for (auto s : t.strides()) {
14
+ if (s == 0) return t.contiguous();
15
+ }
16
+ return t;
17
+ }
18
+
19
+ }}
20
+
21
+ #else
22
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
23
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/miopen/miopen-wrapper.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <miopen/miopen.h>
5
+ #include <miopen/version.h>
6
+
7
+ #if MIOPEN_VERSION_MAJOR > 3 || (MIOPEN_VERSION_MAJOR == 3 && MIOPEN_VERSION_MINOR >= 4)
8
+ // miopen 3.4 moved find mode from private header to public header
9
+ #else
10
+ // from miopen_internal.h
11
+ extern "C" {
12
+
13
+ typedef enum
14
+ {
15
+ miopenConvolutionFindModeNormal = 1, /*!< Normal mode */
16
+ } miopenConvolutionFindMode_t;
17
+
18
+ miopenStatus_t miopenSetConvolutionFindMode(
19
+ miopenConvolutionDescriptor_t convDesc,
20
+ miopenConvolutionFindMode_t findMode);
21
+ }
22
+ #endif
23
+
24
+ #else
25
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
26
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/EmptyTensor.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+ #include <ATen/core/TensorBase.h>
6
+
7
+ namespace at::detail {
8
+
9
+ C10_EXPORT TensorBase empty_mps(
10
+ IntArrayRef size,
11
+ std::optional<ScalarType> dtype_opt,
12
+ std::optional<Layout> layout_opt,
13
+ std::optional<Device> device_opt,
14
+ std::optional<bool> pin_memory_opt,
15
+ std::optional<c10::MemoryFormat> memory_format_opt);
16
+ C10_EXPORT TensorBase empty_mps(IntArrayRef size, const TensorOptions& options);
17
+
18
+ C10_EXPORT TensorBase empty_strided_mps(
19
+ IntArrayRef size,
20
+ IntArrayRef stride,
21
+ ScalarType dtype,
22
+ std::optional<Device> device_opt);
23
+
24
+ C10_EXPORT TensorBase empty_strided_mps(
25
+ IntArrayRef size,
26
+ IntArrayRef stride,
27
+ const TensorOptions& options);
28
+
29
+ } // namespace at::detail
30
+
31
+ #else
32
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
33
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/IndexKernels.h ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace at::mps {
5
+
6
+ static const char* SCATTER_OPS_TEMPLATE = R"METAL_SCATTER(
7
+ template<typename Y, typename X>
8
+ Y cast(const X x);
9
+
10
+ template<>
11
+ {1} cast<{1}, {0}>(const {0} x) {{
12
+ return {2};
13
+ }}
14
+
15
+ kernel void scatter_kernel_n(uint linear_index [[thread_position_in_grid]],
16
+ constant void * src_ [[buffer(0)]],
17
+ device void * dst_ [[buffer(1)]],
18
+ constant uint32_t * size [[buffer(2)]],
19
+ constant uint32_t * stride [[buffer(3)]],
20
+ constant uint32_t & numel [[buffer(4)]],
21
+ constant int32_t & ndim [[buffer(5)]]) {{
22
+ if (linear_index >= numel) return;
23
+
24
+ constant {0} * src = (constant {0} *)src_;
25
+ device {1} * dst = (device {1} *)dst_;
26
+
27
+ uint64_t dst_offs = 0;
28
+ auto dst_idx = linear_index;
29
+ for(int dim = ndim - 1; dim >= 0; --dim) {{
30
+ dst_offs += stride[dim] * (dst_idx % size[dim]);
31
+ dst_idx /= size[dim];
32
+ }}
33
+
34
+ dst[dst_offs] = cast<{1}>(src[linear_index]);
35
+ }}
36
+
37
+ kernel void scatter_kernel_4(uint linear_index [[thread_position_in_grid]],
38
+ constant void * src_ [[buffer(0)]],
39
+ device void * dst_ [[buffer(1)]],
40
+ constant packed_uint4 & size [[buffer(2)]],
41
+ constant packed_uint4 & stride [[buffer(3)]],
42
+ constant uint32_t & numel [[buffer(4)]]) {{
43
+ if (linear_index >= numel) return;
44
+
45
+ constant {0} * src = (constant {0} *)src_;
46
+ device {1} * dst = (device {1} *)dst_;
47
+
48
+ packed_uint4 local_index;
49
+ local_index.x = linear_index / (size[3] * size[2] * size[1]) % size[0];
50
+ local_index.y = linear_index / (size[3] * size[2]) % size[1];
51
+ local_index.z = linear_index / size[3] % size[2];
52
+ local_index.w = linear_index % size[3];
53
+
54
+ const packed_uint4 strided_index = local_index * stride;
55
+ dst[strided_index.x + strided_index.y + strided_index.z + strided_index.w] = cast<{1}>(src[linear_index]);
56
+ }}
57
+
58
+ kernel void scatter_kernel_3(uint linear_index [[thread_position_in_grid]],
59
+ constant void * src_ [[buffer(0)]],
60
+ device void * dst_ [[buffer(1)]],
61
+ constant packed_uint3 & size [[buffer(2)]],
62
+ constant packed_uint3 & stride [[buffer(3)]],
63
+ constant uint32_t & numel [[buffer(4)]]) {{
64
+ if (linear_index >= numel) return;
65
+
66
+ constant {0} * src = (constant {0} *)src_;
67
+ device {1} * dst = (device {1} *)dst_;
68
+
69
+ packed_uint3 local_index;
70
+ local_index.x = linear_index / (size[2] * size[1]) % size[0];
71
+ local_index.y = linear_index / size[2] % size[1];
72
+ local_index.z = linear_index % size[2];
73
+
74
+ const packed_uint3 strided_index = local_index * stride;
75
+ dst[strided_index.x + strided_index.y + strided_index.z] = cast<{1}>(src[linear_index]);
76
+ }}
77
+
78
+ kernel void scatter_kernel_2(uint linear_index [[thread_position_in_grid]],
79
+ constant void * src_ [[buffer(0)]],
80
+ device void * dst_ [[buffer(1)]],
81
+ constant packed_uint2 & size [[buffer(2)]],
82
+ constant packed_uint2 & stride [[buffer(3)]],
83
+ constant uint32_t & numel [[buffer(4)]]) {{
84
+ if (linear_index >= numel) return;
85
+
86
+ constant {0} * src = (constant {0} *)src_;
87
+ device {1} * dst = (device {1} *)dst_;
88
+
89
+ packed_uint2 local_index;
90
+ local_index.x = linear_index / size[1] % size[0];
91
+ local_index.y = linear_index % size[1];
92
+
93
+ const packed_uint2 strided_index = local_index * stride;
94
+ dst[strided_index.x + strided_index.y] = cast<{1}>(src[linear_index]);
95
+ }}
96
+
97
+ kernel void scatter_kernel_1(uint linear_index [[thread_position_in_grid]],
98
+ constant void * src_ [[buffer(0)]],
99
+ device void * dst_ [[buffer(1)]],
100
+ constant int & size [[buffer(2)]],
101
+ constant int & stride [[buffer(3)]],
102
+ constant uint32_t & numel [[buffer(4)]]) {{
103
+ if (linear_index >= numel) return;
104
+
105
+ constant {0} * src = (constant {0} *)src_;
106
+ device {1} * dst = (device {1} *)dst_;
107
+
108
+ const int local_index = linear_index % size;
109
+ const int strided_index = local_index * stride;
110
+ dst[strided_index] = cast<{1}>(src[linear_index]);
111
+ }}
112
+ )METAL_SCATTER";
113
+
114
+ static const char* GATHER_OPS_TEMPLATE = R"METAL_GATHER(
115
+ template<typename Y, typename X>
116
+ Y cast(const X x);
117
+
118
+ template<>
119
+ {1} cast<{1}, {0}>(const {0} x) {{
120
+ return {2};
121
+ }}
122
+
123
+ kernel void gather_kernel_n(uint linear_index [[thread_position_in_grid]],
124
+ constant void * src_ [[buffer(0)]],
125
+ device void * dst_ [[buffer(1)]],
126
+ constant uint32_t * size [[buffer(2)]],
127
+ constant uint32_t * stride [[buffer(3)]],
128
+ constant uint32_t & numel [[buffer(4)]],
129
+ constant int32_t & ndim [[buffer(5)]]) {{
130
+ if (linear_index >= numel) return;
131
+
132
+ constant {0} * src = (constant {0} *)src_;
133
+ device {1} * dst = (device {1} *)dst_;
134
+
135
+ uint64_t src_offs = 0;
136
+ auto src_idx = linear_index;
137
+ for(int dim = ndim - 1; dim >= 0; --dim) {{
138
+ src_offs += stride[dim] * (src_idx % size[dim]);
139
+ src_idx /= size[dim];
140
+ }}
141
+
142
+ dst[linear_index] = cast<{1}>(src[src_offs]);
143
+ }}
144
+
145
+ kernel void gather_kernel_4(uint linear_index [[thread_position_in_grid]],
146
+ constant void * src_ [[buffer(0)]],
147
+ device void * dst_ [[buffer(1)]],
148
+ constant packed_uint4 & size [[buffer(2)]],
149
+ constant packed_uint4 & stride [[buffer(3)]],
150
+ constant uint32_t & numel [[buffer(4)]]) {{
151
+ if (linear_index >= numel) return;
152
+
153
+ constant {0} * src = (constant {0} *)src_;
154
+ device {1} * dst = (device {1} *)dst_;
155
+
156
+ packed_uint4 local_index;
157
+ local_index.x = linear_index / (size[3] * size[2] * size[1]) % size[0];
158
+ local_index.y = linear_index / (size[3] * size[2]) % size[1];
159
+ local_index.z = linear_index / size[3] % size[2];
160
+ local_index.w = linear_index % size[3];
161
+
162
+ const packed_uint4 strided_index = local_index * stride;
163
+ dst[linear_index] = cast<{1}>(src[strided_index.x + strided_index.y + strided_index.z + strided_index.w]);
164
+ }}
165
+
166
+ kernel void gather_kernel_3(uint linear_index [[thread_position_in_grid]],
167
+ constant void * src_ [[buffer(0)]],
168
+ device void * dst_ [[buffer(1)]],
169
+ constant packed_uint3 & size [[buffer(2)]],
170
+ constant packed_uint3 & stride [[buffer(3)]],
171
+ constant uint32_t & numel [[buffer(4)]]) {{
172
+ if (linear_index >= numel) return;
173
+
174
+ constant {0} * src = (constant {0} *)src_;
175
+ device {1} * dst = (device {1} *)dst_;
176
+
177
+ packed_uint3 local_index;
178
+ local_index.x = linear_index / (size[2] * size[1]) % size[0];
179
+ local_index.y = linear_index / size[2] % size[1];
180
+ local_index.z = linear_index % size[2];
181
+
182
+ const packed_uint3 strided_index = local_index * stride;
183
+ dst[linear_index] = cast<{1}>(src[strided_index.x + strided_index.y + strided_index.z]);
184
+ }}
185
+
186
+ kernel void gather_kernel_2(uint linear_index [[thread_position_in_grid]],
187
+ constant void * src_ [[buffer(0)]],
188
+ device void * dst_ [[buffer(1)]],
189
+ constant packed_uint2 & size [[buffer(2)]],
190
+ constant packed_uint2 & stride [[buffer(3)]],
191
+ constant uint32_t & numel [[buffer(4)]]) {{
192
+ if (linear_index >= numel) return;
193
+
194
+ constant {0} * src = (constant {0} *)src_;
195
+ device {1} * dst = (device {1} *)dst_;
196
+
197
+ packed_uint2 local_index;
198
+ local_index.x = linear_index / size[1] % size[0];
199
+ local_index.y = linear_index % size[1];
200
+
201
+ const packed_uint2 strided_index = local_index * stride;
202
+ dst[linear_index] = cast<{1}>(src[strided_index.x + strided_index.y]);
203
+ }}
204
+
205
+ kernel void gather_kernel_1(uint linear_index [[thread_position_in_grid]],
206
+ constant void * src_ [[buffer(0)]],
207
+ device void * dst_ [[buffer(1)]],
208
+ constant int & size [[buffer(2)]],
209
+ constant int & stride [[buffer(3)]],
210
+ constant uint32_t & numel [[buffer(4)]]) {{
211
+ if (linear_index >= numel) return;
212
+
213
+ constant {0} * src = (constant {0} *)src_;
214
+ device {1} * dst = (device {1} *)dst_;
215
+
216
+ const int local_index = linear_index % size;
217
+ const int strided_index = local_index * stride;
218
+ dst[linear_index] = cast<{1}>(src[strided_index]);
219
+ }}
220
+ )METAL_GATHER";
221
+ } // namespace at::mps
222
+
223
+ #else
224
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
225
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocator.h ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/mps/MPSAllocatorInterface.h>
7
+ #include <ATen/mps/MPSEvent.h>
8
+ #include <ATen/mps/MPSStream.h>
9
+
10
+ #include <c10/util/flat_hash_map.h>
11
+ #include <mach/vm_page_size.h>
12
+ #include <cstdio>
13
+ #include <mutex>
14
+ #include <set>
15
+ #include <unordered_set>
16
+
17
+ // this implementation is based on CUDACachingAllocator.
18
+ // It utilizes Metal Heaps to improve the performance with buffer allocation.
19
+ // Do not include this header. Use MPSAllocatorInterface.h instead.
20
+ // TODO: Unify the logic with CUDACachingAllocator and remove redundant code.
21
+ namespace at::mps::HeapAllocator {
22
+
23
+ static const size_t kMaxSmallAlloc = MB(1); // largest "small" allocation is 1 MiB
24
+ static const size_t kMinLargeAlloc = MB(10); // allocations between 1 and 10 MiB may use kLargeHeap
25
+ static const size_t kRoundLarge = MB(2); // round up large allocations to 2 MiB
26
+ static const size_t kSmallHeap = MB(8); // "small" allocations are packed in 8 MiB heaps
27
+ static const size_t kLargeHeap = MB(32); // "large" allocations may be packed in 32 MiB heaps
28
+ static const size_t kXLargeHeapD =
29
+ MB(128); // "extra large" allocations on Discrete devices may be packed in 128 MiB heaps
30
+ static const size_t kXLargeHeapU =
31
+ MB(1024); // "extra large" allocations on Unified devices may be packed in 1 GiB heaps
32
+ static const size_t kMaxScalarAlloc = (sizeof(int64_t)); // largest "scalar" allocation
33
+
34
+ // buffer pools could be customized with a combination of usage flags
35
+ enum UsageFlags : uint32_t {
36
+ PRIVATE = 0,
37
+ SMALL = (1 << 0), // small heaps have sizes of kSmallHeap, and large ones kLargeHeap
38
+ SHARED = (1 << 1), // shared pools allocated on devices with unified memory; otherwise, private between host/device
39
+ MANAGED = (1 << 2), // managed storage mode
40
+ HAZARD = (1 << 3), // enables Automatic Hazard Tracking for the resources allocated on the pool
41
+ SCALAR = (1 << 4), // used to import CPU scalar values to GPU and use them in MPS Stream
42
+ };
43
+ // debug verbosity flags
44
+ enum DebugVerbosity : uint32_t {
45
+ SILENT = 0,
46
+ PROFILING = (1 << 0), // print generic profiling data for total system memory usage
47
+ ALLOCATIONS = (1 << 1), // print buffer allocations
48
+ RECYCLES = (1 << 2), // print buffer recycling
49
+ RELEASES = (1 << 3), // print buffer releases
50
+ LARGE_ONLY = (1 << 4), // only log large buffer pool transactions
51
+ };
52
+
53
+ struct HeapBlock;
54
+
55
+ struct BufferBlock {
56
+ id<MTLBuffer> buffer;
57
+ void* cpu_ptr = nullptr; // stores the pointer to CPU mapping of a Shared MTLBuffer
58
+ size_t size; // size after alignment
59
+ size_t requested_size; // requested size (before alignment)
60
+ // buffer shape is used for retrieving base of views in cached graphs
61
+ std::vector<int64_t> shape;
62
+ bool in_use = false;
63
+ HeapBlock* heap;
64
+ id_t buf_id;
65
+ // counter to candidate least recently used buffers for garbage collection
66
+ uint32_t gc_count = 0;
67
+ uint32_t use_count = 0;
68
+ // counter to assign unique ids to buffer blocks
69
+ static uint64_t buffer_counter;
70
+ // Metal events used to sync GPU/CPU operations on the shared-storage buffers
71
+ MPSEventPtr event;
72
+
73
+ BufferBlock(size_t Size, size_t RequestedSize = 0, const id<MTLBuffer> Buffer = nullptr, HeapBlock* Heap = nullptr)
74
+ : buffer(Buffer), size(Size), requested_size(RequestedSize), heap(Heap), buf_id(Buffer ? ++buffer_counter : 0) {}
75
+
76
+ static bool Comparator(const BufferBlock* a, const BufferBlock* b) {
77
+ return (a->size != b->size) ? a->size < b->size : (uintptr_t)a->buffer < (uintptr_t)b->buffer;
78
+ }
79
+ static size_t alignUp(size_t Size, size_t Alignment) {
80
+ assert(((Alignment - 1) & Alignment) == 0);
81
+ return ((Size + Alignment - 1) & ~(Alignment - 1));
82
+ }
83
+ uint32_t retainCount() const {
84
+ return [buffer retainCount];
85
+ }
86
+ };
87
+ typedef bool (*BufferComparison)(const BufferBlock*, const BufferBlock*);
88
+
89
+ struct BufferPool;
90
+ struct AllocParams {
91
+ AllocParams(size_t Alloc_Size, size_t Requested_Size, BufferPool* Pool)
92
+ : search_key(Alloc_Size), pool(Pool), requested_size(Requested_Size) {}
93
+ size_t size() const {
94
+ return search_key.size;
95
+ }
96
+
97
+ BufferBlock search_key;
98
+ BufferPool* pool;
99
+ BufferBlock* buffer_block = nullptr;
100
+ size_t requested_size;
101
+ // true if we exceed the low watermark limit. In this case
102
+ // we apply strategies to relieve the pressure before allocation.
103
+ bool has_memory_pressure = false;
104
+ // true if we're allocating on a unified memory device
105
+ bool has_unified_memory = true;
106
+ };
107
+
108
+ struct HeapBlock {
109
+ id<MTLHeap> heap;
110
+ struct {
111
+ size_t total, available;
112
+ } size;
113
+ BufferPool* pool;
114
+ unsigned int n_buffers = 0;
115
+ id_t heap_id;
116
+ // indicates if we split this heap to sub-allocate 'several' buffers (otherwise single buffer)
117
+ bool is_split;
118
+ // counter to assign unique ids to heap blocks
119
+ static uint64_t heap_counter;
120
+
121
+ HeapBlock(size_t Size, const id<MTLHeap> Heap = nullptr, BufferPool* Pool = nullptr)
122
+ : heap(Heap),
123
+ size({.total = Size, .available = Size}),
124
+ pool(Pool),
125
+ heap_id(Heap ? ++heap_counter : 0),
126
+ is_split(true) {}
127
+
128
+ static MTLResourceOptions getOptions(uint32_t usage) {
129
+ // TODO: check the caching performance of write-combined mode
130
+ MTLResourceOptions options = MTLResourceCPUCacheModeDefaultCache;
131
+
132
+ if (usage & UsageFlags::MANAGED)
133
+ options |= MTLResourceStorageModeManaged;
134
+ else if (usage & UsageFlags::SHARED)
135
+ options |= MTLResourceStorageModeShared;
136
+ else
137
+ options |= MTLResourceStorageModePrivate;
138
+
139
+ options |=
140
+ (usage & UsageFlags::HAZARD) ? MTLResourceHazardTrackingModeTracked : MTLResourceHazardTrackingModeUntracked;
141
+
142
+ return options;
143
+ }
144
+
145
+ static HeapBlock* createHeapBlock(AllocParams& params, id<MTLDevice> device, uint32_t usage) {
146
+ HeapBlock* heapBlock = nullptr;
147
+ bool is_split = true;
148
+ const size_t size = params.size();
149
+ MTLHeapDescriptor* d = [MTLHeapDescriptor new];
150
+ if (d) {
151
+ const size_t kXLargeHeap = params.has_unified_memory ? kXLargeHeapU : kXLargeHeapD;
152
+ if (size <= kMaxSmallAlloc) {
153
+ d.size = kSmallHeap;
154
+ } else if (size < kMinLargeAlloc) {
155
+ d.size = kLargeHeap;
156
+ } else if (size < kXLargeHeap / 2 && !params.has_memory_pressure) {
157
+ d.size = kXLargeHeap;
158
+ } else {
159
+ d.size = kRoundLarge * ((size + kRoundLarge - 1) / kRoundLarge);
160
+ is_split = false;
161
+ }
162
+ d.storageMode = (usage & UsageFlags::SHARED) ? MTLStorageModeShared : MTLStorageModePrivate;
163
+ d.cpuCacheMode = MTLCPUCacheModeDefaultCache;
164
+ // this automatically handles Metal buffer access synchronizations at the
165
+ // cost of slightly lower performance.
166
+ d.hazardTrackingMode =
167
+ (usage & UsageFlags::HAZARD) ? MTLHazardTrackingModeTracked : MTLHazardTrackingModeUntracked;
168
+ d.resourceOptions = getOptions(usage);
169
+ d.type = MTLHeapTypeAutomatic;
170
+ id<MTLHeap> heap = [device newHeapWithDescriptor:d];
171
+ if (heap) {
172
+ [heap setPurgeableState:MTLPurgeableStateNonVolatile];
173
+ const size_t heap_size = heapAvailableSize(heap);
174
+ heapBlock = new HeapBlock(heap_size, heap, params.pool);
175
+ if (heapBlock) {
176
+ heapBlock->is_split = is_split;
177
+ }
178
+ }
179
+ [d release];
180
+ }
181
+ return heapBlock;
182
+ }
183
+ static bool Comparator(const HeapBlock* a, const HeapBlock* b) {
184
+ return (a->size.available != b->size.available) ? a->size.available < b->size.available
185
+ : (uintptr_t)a->heap < (uintptr_t)b->heap;
186
+ }
187
+ static NSUInteger heapAvailableSize(id<MTLHeap> heap, size_t Alignment = vm_page_size) {
188
+ return [heap maxAvailableSizeWithAlignment:Alignment];
189
+ }
190
+ NSUInteger Size() {
191
+ return [heap size];
192
+ }
193
+ id<MTLBuffer> newMTLBuffer(size_t length, uint32_t usage) {
194
+ id<MTLBuffer> buf = [heap newBufferWithLength:length options:getOptions(usage)];
195
+ if (buf) {
196
+ updateAvailableSize();
197
+ n_buffers++;
198
+ }
199
+ return buf;
200
+ }
201
+ // returns the retainCount before releasing the buffer
202
+ uint32_t releaseMTLBuffer(id<MTLBuffer>& buffer) {
203
+ const uint32_t retainCount = [buffer retainCount];
204
+ [buffer release];
205
+ buffer = nil;
206
+ updateAvailableSize();
207
+ n_buffers--;
208
+ return retainCount;
209
+ }
210
+ // returns the retainCount before releasing the heap
211
+ uint32_t releaseMTLHeap() {
212
+ const uint32_t retainCount = [heap retainCount];
213
+ TORCH_INTERNAL_ASSERT(!n_buffers); // assert if heap isn't empty
214
+ [heap setPurgeableState:MTLPurgeableStateEmpty];
215
+ [heap release];
216
+ heap = nil;
217
+ size.available = 0;
218
+ return retainCount;
219
+ }
220
+ uint32_t retainCount() const {
221
+ return [heap retainCount];
222
+ }
223
+ void updateAvailableSize() {
224
+ size.available = heapAvailableSize(heap);
225
+ }
226
+ };
227
+ typedef bool (*HeapComparison)(const HeapBlock*, const HeapBlock*);
228
+
229
+ struct BufferPool {
230
+ enum class Kind {
231
+ PRIVATE_SMALL,
232
+ PRIVATE_LARGE,
233
+ SHARED_SMALL,
234
+ SHARED_LARGE,
235
+ SCALAR,
236
+ };
237
+
238
+ BufferPool(const id<MTLDevice> Device, uint32_t Usage)
239
+ : device(Device), usage(Usage), heaps(HeapBlock::Comparator), available_buffers(BufferBlock::Comparator) {}
240
+
241
+ const id<MTLDevice> device;
242
+ // usage flags to customize the pool for various purposes (see UsageFlags enum)
243
+ const uint32_t usage;
244
+ // total number of buffers in the pool
245
+ uint32_t n_buffers = 0;
246
+ // total allocations size on this pool
247
+ size_t allocated_size = 0;
248
+ // total memory available in the pool
249
+ size_t available_size = 0;
250
+ // list of heaps ordered by their "available" (not total) memory size
251
+ std::set<HeapBlock*, HeapComparison> heaps;
252
+ // list of only "available" buffers in the pool (i.e., buffers not in-use)
253
+ std::set<BufferBlock*, BufferComparison> available_buffers;
254
+ // list of buffers that are in a state of "limbo" where they've already been freed
255
+ // from PyTorch-side, but were not returned to pool due to still being
256
+ // in-use by command buffers with retainCount > 1. In this state, the buffer is
257
+ // neither ready to be recycled, nor could be returned to pool as available.
258
+ // These buffers will be returned to pool once the command buffer's
259
+ // completionHandler callbacks are called.
260
+ std::unordered_set<BufferBlock*> buffers_pending_free;
261
+ // list of heaps pending size update
262
+ std::unordered_set<HeapBlock*> heaps_pending_update;
263
+ };
264
+
265
+ class MPSHeapAllocatorImpl {
266
+ public:
267
+ explicit MPSHeapAllocatorImpl()
268
+ : m_device(at::mps::MPSDevice::getInstance()->device()),
269
+ m_max_buffer_size([m_device maxBufferLength]),
270
+ m_stream(getDefaultMPSStream()),
271
+ m_event_pool(getMPSEventPool()) {
272
+ init_allocator();
273
+ }
274
+ ~MPSHeapAllocatorImpl() {
275
+ emptyCache();
276
+ }
277
+ // interface exposed to at::Allocator
278
+ id<MTLBuffer> malloc(size_t size, uint32_t usage);
279
+ // frees a buffer and returns it into buffer pool
280
+ void free(void* ptr);
281
+ // releases all the cached buffers and their associated heaps
282
+ void emptyCache();
283
+ // free inactive buffers that are pending to be freed
284
+ void freeInactiveBuffers();
285
+ // returns true if buffer was allocated from the shared pool
286
+ bool isSharedBuffer(const void* ptr);
287
+ // get the requested unaligned size of an MTLBuffer
288
+ ssize_t getUnalignedBufferSize(const void* ptr);
289
+ // set the shape of a base tensor from a view tensor
290
+ void setBufferShape(const void* ptr, const IntArrayRef& shape);
291
+ // retrieve the shape of a base tensor from a view tensor
292
+ IntArrayRef getBufferShape(const void* ptr);
293
+ // get the unique ID of the buffer
294
+ id_t getBufferId(const void* ptr);
295
+ // allocate a buffer from a specialized pool to import CPU scalars into GPU
296
+ id<MTLBuffer> allocScalarBufferWithValue(void* value, size_t size);
297
+ // returns a CPU-mapping of the input buffer and its retainCount,
298
+ // if only it has Shared storage-mode and allocated on MPSAllocator
299
+ std::pair<const void*, uint32_t> getSharedBufferPtr(const void* buffer);
300
+ // records events for a list of MTLBuffers (list is used to lock the mutex once)
301
+ // returns true if records any event (given if passed buffers exist and are shared-storage)
302
+ bool recordEvents(c10::ArrayRef<const void*> buffers);
303
+ // waits for the event to signal the completion of GPU execution
304
+ // on the passed shared buffers (list is used to lock the mutex once)
305
+ // returns true if actually waited on any event
306
+ bool waitForEvents(c10::ArrayRef<const void*> buffers);
307
+ // this indicates how far (in Megabytes) the current total allocations are from the
308
+ // low watermark limit which is used to detect if we're under memory pressure
309
+ // This returns zero if we've reached the low watermark limit
310
+ ssize_t getLowWatermarkValue();
311
+ // (see m_low_watermark_ratio for description)
312
+ void setLowWatermarkRatio(double ratio);
313
+ // (see m_high_watermark_ratio for description)
314
+ void setHighWatermarkRatio(double ratio);
315
+ // (see m_low_watermark_limit for description)
316
+ size_t getLowWatermarkLimit() const {
317
+ return m_low_watermark_limit;
318
+ }
319
+ // (see m_max_total_allowed_size for description)
320
+ size_t getHighWatermarkLimit() const {
321
+ return m_max_total_allowed_size;
322
+ }
323
+ // (see m_total_allocated_memory for description)
324
+ size_t getTotalAllocatedMemory() const {
325
+ return m_total_allocated_memory;
326
+ }
327
+ // (see m_current_allocated_memory for description)
328
+ size_t getCurrentAllocatedMemory() const {
329
+ return m_current_allocated_memory;
330
+ }
331
+ // total GPU memory allocated in the process by Metal driver; including
332
+ // implicit allocations from MPS/MPSGraph frameworks and MPSHeapAllocatorImpl.
333
+ size_t getDriverAllocatedMemory() const {
334
+ return current_allocated_size();
335
+ }
336
+ // recommended Max memory for Metal
337
+ size_t getRecommendedMaxMemory() const {
338
+ return max_device_size();
339
+ }
340
+ // (see enum DebugVerbosity for description)
341
+ uint32_t getDebugVerbosity() const {
342
+ return m_debug_verbosity;
343
+ }
344
+ // returns the device that we allocate from
345
+ inline id<MTLDevice> Device() const {
346
+ return m_device;
347
+ }
348
+
349
+ inline std::string format_size(uint64_t size) const;
350
+
351
+ private:
352
+ // (see m_high_watermark_ratio for description)
353
+ constexpr static double default_high_watermark_ratio = 1.7;
354
+ // we set the allowed upper bound to twice the size of recommendedMaxWorkingSetSize.
355
+ constexpr static double default_high_watermark_upper_bound = 2.0;
356
+ // (see m_low_watermark_ratio for description)
357
+ // on unified memory, we could allocate beyond the recommendedMaxWorkingSetSize
358
+ constexpr static double default_low_watermark_ratio_unified = 1.4;
359
+ constexpr static double default_low_watermark_ratio_discrete = 1.0;
360
+
361
+ const id<MTLDevice> m_device;
362
+ std::recursive_mutex m_mutex;
363
+ // allocated buffers by device pointer
364
+ ska::flat_hash_map<const void*, BufferBlock*> m_allocated_buffers;
365
+ // using a container for pools to simplify iterating them
366
+ ska::flat_hash_map<BufferPool::Kind, std::unique_ptr<BufferPool>> m_pools;
367
+ // total memory allocated by HeapAllocator (including blocks in pools)
368
+ size_t m_total_allocated_memory = 0;
369
+ // currently active memory allocations in use (i.e., blocks not in pools)
370
+ size_t m_current_allocated_memory = 0;
371
+ // max buffer size allowed by Metal
372
+ size_t m_max_buffer_size = 0;
373
+ // maximum total size allowed to be allocated
374
+ size_t m_max_total_allowed_size = 0;
375
+ // high watermark ratio is a hard limit for the total allowed allocations
376
+ // 0. : disables high watermark limit (may cause system failure if system-wide OOM occurs)
377
+ // 1. : recommended maximum allocation size (i.e., device.recommendedMaxWorkingSetSize)
378
+ // >1.: allows limits beyond the device.recommendedMaxWorkingSetSize
379
+ // e.g., value 0.95 means we allocate up to 95% of recommended maximum
380
+ // allocation size; beyond that, the allocations would fail with OOM error.
381
+ double m_high_watermark_ratio;
382
+ // low watermark ratio is a soft limit to attempt limiting memory allocations up to the lower watermark
383
+ // level by garbage collection or committing command buffers more frequently (a.k.a, adaptive commit).
384
+ // Value between 0 to m_high_watermark_ratio (setting 0.0 disables adaptive commit and garbage collection)
385
+ // e.g., value 0.9 means we 'attempt' to limit allocations up to 90% of recommended maximum
386
+ // allocation size.
387
+ double m_low_watermark_ratio;
388
+ // low watermark size limit (in Bytes) at the time we initialize the allocator
389
+ size_t m_low_watermark_limit;
390
+ // use "PYTORCH_DEBUG_MPS_ALLOCATOR" env-var to set debug verbosity
391
+ uint32_t m_debug_verbosity;
392
+ // default MPS stream
393
+ MPSStream* m_stream;
394
+ // we hold a reference to MPSEventPool so it could get destroyed after MPSAllocator
395
+ std::shared_ptr<MPSEventPool> m_event_pool;
396
+
397
+ void init_allocator();
398
+ void init_buffer_pools();
399
+ HeapBlock* get_free_heap(AllocParams& params);
400
+ bool get_free_buffer(AllocParams& params);
401
+ BufferBlock* get_allocated_buffer_block(const void* ptr);
402
+ BufferBlock* alloc_buffer_block(size_t size, uint32_t usage);
403
+ bool alloc_buffer(AllocParams& params);
404
+ void free_buffer(BufferBlock* buffer_block);
405
+ // returns true if the container heap is also released
406
+ bool release_buffer(BufferBlock* buffer_block, bool remove_empty_heap = true);
407
+ void release_buffers(BufferPool& pool);
408
+ bool release_available_cached_buffers(AllocParams& params);
409
+ bool release_cached_buffers();
410
+ // free unused cached blocks to reclaim GPU memory if memory pressure is high
411
+ void garbage_collect_cached_buffers(AllocParams& params);
412
+ // returns the suitable buffer pool type for the usage or
413
+ // requested/allocated sizes
414
+ BufferPool& get_pool(size_t requested_size, size_t aligned_size, uint32_t usage);
415
+ // returns the aligned allocation size that is optimized
416
+ // for the buffers to get reused frequently
417
+ size_t get_allocation_size(size_t size, uint32_t usage) const;
418
+ // maximum size of device memory available for allocation in current process
419
+ // Note: the recommendedMaxWorkingSetSize is typically 75% of the total system memory.
420
+ size_t max_device_size() const {
421
+ return [m_device recommendedMaxWorkingSetSize];
422
+ }
423
+ // there are implicit allocations from MPS backend, so we need to query the 'device' for
424
+ // total allocated size instead of manually tracking in MPSAllocator
425
+ size_t current_allocated_size() const {
426
+ return [m_device currentAllocatedSize];
427
+ }
428
+
429
+ bool trigger_memory_callbacks(BufferBlock* buffer_block, IMpsAllocatorCallback::EventType event) const {
430
+ for (const auto& name : MPSAllocatorCallbacksRegistry()->Keys()) {
431
+ MPSAllocatorCallbacksRegistry()->Create(name)->executeMPSAllocatorCallback(
432
+ buffer_block ? buffer_block->buffer : nullptr, event);
433
+ }
434
+ return true;
435
+ }
436
+ };
437
+
438
+ } // namespace at::mps::HeapAllocator
439
+
440
+ #else
441
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
442
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSAllocatorInterface.h ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2023 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/core/ATen_fwd.h>
7
+ #include <c10/core/Allocator.h>
8
+ #include <c10/util/Registry.h>
9
+
10
+ #define MB(x) (x * 1048576UL)
11
+
12
+ namespace at::mps {
13
+
14
+ // this is a public interface to access MPSAllocator.
15
+ // Do not declare methods that would depend on MPS or Metal frameworks.
16
+ class IMPSAllocator : public c10::Allocator {
17
+ public:
18
+ // see the comments in MPSAllocator.h for the description of these methods.
19
+ virtual void emptyCache() const = 0;
20
+ virtual void freeInactiveBuffers() const = 0;
21
+ virtual ssize_t getUnalignedBufferSize(const void* ptr) const = 0;
22
+ virtual IntArrayRef getBufferShape(const void* ptr) const = 0;
23
+ virtual id_t getBufferId(const void* ptr) const = 0;
24
+ virtual void setBufferShape(const void* ptr, const IntArrayRef& shape)
25
+ const = 0;
26
+ virtual bool isSharedBuffer(const void* ptr) const = 0;
27
+ virtual bool isSharedStorageSupported() const = 0;
28
+ virtual c10::DataPtr allocScalarBufferWithValue(void* value, size_t size)
29
+ const = 0;
30
+ virtual std::string formatSize(size_t size) const = 0;
31
+ virtual void setLowWatermarkRatio(double ratio) const = 0;
32
+ virtual void setHighWatermarkRatio(double ratio) const = 0;
33
+ virtual ssize_t getLowWatermarkValue() const = 0;
34
+ virtual size_t getLowWatermarkLimit() const = 0;
35
+ virtual size_t getHighWatermarkLimit() const = 0;
36
+ virtual size_t getTotalAllocatedMemory() const = 0;
37
+ virtual size_t getCurrentAllocatedMemory() const = 0;
38
+ virtual size_t getDriverAllocatedMemory() const = 0;
39
+ virtual size_t getRecommendedMaxMemory() const = 0;
40
+ virtual std::pair<const void*, uint32_t> getSharedBufferPtr(
41
+ const void* ptr) const = 0;
42
+ virtual bool recordEvents(c10::ArrayRef<const void*> buffers) const = 0;
43
+ virtual bool waitForEvents(c10::ArrayRef<const void*> buffers) const = 0;
44
+ };
45
+
46
+ class IMpsAllocatorCallback {
47
+ public:
48
+ enum class EventType {
49
+ ALLOCATED, // buffer got allocated to be used immediately
50
+ RECYCLED, // buffer pulled from free list to be reused
51
+ FREED, // buffer put to free list for future recycling
52
+ RELEASED, // buffer memory released
53
+ ALLOCATION_FAILED // buffer allocation failed
54
+ };
55
+ virtual ~IMpsAllocatorCallback() = default;
56
+ virtual void executeMPSAllocatorCallback(void* ptr, EventType event) = 0;
57
+ };
58
+
59
+ // MPS allocator will execute every registered callback when a block of memory
60
+ // is freed.
61
+ TORCH_DECLARE_REGISTRY(MPSAllocatorCallbacksRegistry, IMpsAllocatorCallback);
62
+ #define REGISTER_MPS_ALLOCATOR_CALLBACK(name, ...) \
63
+ C10_REGISTER_CLASS(MPSAllocatorCallbacksRegistry, name, __VA_ARGS__)
64
+
65
+ IMPSAllocator* getIMPSAllocator(bool sharedAllocator = false);
66
+
67
+ bool isMPSPinnedPtr(const void* data);
68
+
69
+ } // namespace at::mps
70
+
71
+ #else
72
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
73
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSDevice.h ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+ #include <ATen/Device.h>
6
+ #include <c10/core/Allocator.h>
7
+ #include <c10/macros/Macros.h>
8
+ #include <c10/util/Exception.h>
9
+
10
+ #ifdef __OBJC__
11
+ #include <Foundation/Foundation.h>
12
+ #include <Metal/Metal.h>
13
+ typedef id<MTLDevice> MTLDevice_t;
14
+ #else
15
+ typedef void* MTLDevice_t;
16
+ #endif
17
+
18
+ namespace at::mps {
19
+
20
+ // Helper enum to check if a MPSGraph op is supported in a given macOS version
21
+ enum class MacOSVersion : uint32_t {
22
+ MACOS_VER_14_4_PLUS = 0,
23
+ MACOS_VER_15_0_PLUS,
24
+ MACOS_VER_15_1_PLUS,
25
+ MACOS_VER_15_2_PLUS,
26
+ };
27
+
28
+ //-----------------------------------------------------------------
29
+ // MPSDevice
30
+ //
31
+ // MPSDevice is a singleton class that returns the default device
32
+ //-----------------------------------------------------------------
33
+
34
+ class TORCH_API MPSDevice {
35
+ public:
36
+ /**
37
+ * MPSDevice should not be cloneable.
38
+ */
39
+ MPSDevice(MPSDevice& other) = delete;
40
+ /**
41
+ * MPSDevice should not be assignable.
42
+ */
43
+ void operator=(const MPSDevice&) = delete;
44
+ /**
45
+ * Gets single instance of the Device.
46
+ */
47
+ static MPSDevice* getInstance();
48
+ /**
49
+ * Returns the single device.
50
+ */
51
+ MTLDevice_t device() {
52
+ return _mtl_device;
53
+ }
54
+ /**
55
+ * Returns whether running on Ventura or newer
56
+ */
57
+ bool isMacOS13Plus(MacOSVersion version) const;
58
+
59
+ /**
60
+ * Returns device name
61
+ */
62
+ std::string getName() const;
63
+
64
+ /**
65
+ * Returns number of GPU cores.
66
+ * 1 Core = 16 ExecutionUnit x 8 ALU x 24 threads
67
+ */
68
+ unsigned getCoreCount() const;
69
+
70
+ ~MPSDevice();
71
+
72
+ private:
73
+ static MPSDevice* _device;
74
+ MTLDevice_t _mtl_device;
75
+ MPSDevice();
76
+ };
77
+
78
+ TORCH_API bool is_available();
79
+ TORCH_API bool is_macos_13_or_newer(MacOSVersion version);
80
+ TORCH_API at::Allocator* GetMPSAllocator(bool useSharedAllocator = false);
81
+
82
+ inline Device getDeviceFromPtr(void* ptr) {
83
+ return {c10::DeviceType::MPS, 0};
84
+ }
85
+
86
+ } // namespace at::mps
87
+
88
+ #else
89
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
90
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSEvent.h ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2023 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/mps/MPSStream.h>
7
+ #include <ctime>
8
+ #include <stack>
9
+
10
+ namespace at::mps {
11
+
12
+ // NOTE: don't create instances of this class directly.
13
+ // Use MPSEventPool to acquire instances of MPSEvent.
14
+ class MPSEvent {
15
+ public:
16
+ explicit MPSEvent(id_t ID, MPSStream* stream, bool enable_timing);
17
+ ~MPSEvent();
18
+
19
+ // records an event on the stream
20
+ void record(bool needsLock, bool syncEvent = false);
21
+ // makes all future work submitted to the stream wait for this event.
22
+ bool wait(bool needsLock, bool syncEvent = false);
23
+ // schedules a notifyListener callback for the event.
24
+ bool notify(bool needsLock, MTLSharedEventNotificationBlock block);
25
+ // checks if events are already signaled.
26
+ bool query() const;
27
+ // blocks the CPU thread until all the GPU work that were scheduled
28
+ // prior to recording this event are completed.
29
+ bool synchronize();
30
+ // resets this event with new parameters in case it gets reused from the event
31
+ // pool
32
+ void reset(MPSStream* stream, bool enable_timing);
33
+ // returns the unique ID of the event instance
34
+ id_t getID() const {
35
+ return m_id;
36
+ }
37
+ // returns the completion timestamp of the event
38
+ uint64_t getCompletionTime() const {
39
+ return m_completion_time;
40
+ }
41
+ // if already recorded, waits for cpu_sync_cv to be signaled
42
+ void waitForCpuSync();
43
+
44
+ private:
45
+ id_t m_id;
46
+ // enables measuring the completion time of the notifyListener of this event
47
+ bool m_enable_timing;
48
+ uint64_t m_signalCounter = 0;
49
+ MPSStream* m_stream = nullptr;
50
+ MTLSharedEvent_t m_event = nullptr;
51
+ MTLSharedEventListener* m_listener = nullptr;
52
+ // used to sync the events created on this Stream with CPU
53
+ std::mutex m_cpu_sync_mutex{};
54
+ std::condition_variable m_cpu_sync_cv{};
55
+ // CondVar predicate to sync the events created on this Stream with CPU
56
+ bool m_cpu_sync_completed = false;
57
+ // used to compute elapsed time
58
+ uint64_t m_completion_time = 0;
59
+
60
+ void recordLocked(bool syncEvent);
61
+ bool waitLocked(bool syncEvent);
62
+ bool notifyLocked(MTLSharedEventNotificationBlock block);
63
+ void notifyCpuSync();
64
+ static uint64_t getTime() {
65
+ return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
66
+ }
67
+ };
68
+
69
+ typedef std::unique_ptr<MPSEvent, std::function<void(MPSEvent*)>> MPSEventPtr;
70
+
71
+ class MPSEventPool {
72
+ public:
73
+ explicit MPSEventPool(MPSStream* default_stream);
74
+ ~MPSEventPool();
75
+
76
+ MPSEventPtr acquireEvent(bool enable_timing, MPSStream* stream);
77
+ void emptyCache();
78
+
79
+ // these are mainly used for MPSHooks and torch.mps.Event() bindings
80
+ id_t acquireEvent(bool enable_timing);
81
+ void releaseEvent(id_t event_id);
82
+ void recordEvent(id_t event_id, bool syncEvent);
83
+ void waitForEvent(id_t event_id, bool syncEvent);
84
+ void synchronizeEvent(id_t event_id);
85
+ bool queryEvent(id_t event_id);
86
+ // returns elapsed time between two recorded events in milliseconds
87
+ double elapsedTime(id_t start_event_id, id_t end_event_id);
88
+
89
+ private:
90
+ MPSStream* m_default_stream = nullptr;
91
+ std::recursive_mutex m_mutex;
92
+ std::stack<std::unique_ptr<MPSEvent>> m_pool{};
93
+ // dictionary to associate event IDs with event objects
94
+ // used to retain in-use events out of the pool
95
+ // for torch.mps.Event() bindings.
96
+ std::unordered_map<id_t, MPSEventPtr> m_in_use_events{};
97
+ uint64_t m_event_counter = 0;
98
+ std::function<void(MPSEvent*)> m_default_deleter;
99
+
100
+ MPSEvent* getInUseEvent(id_t event_id, bool locked = true);
101
+ };
102
+
103
+ // shared_ptr is used to get MPSEventPool destroyed after dependent instances
104
+ std::shared_ptr<MPSEventPool> getMPSEventPool();
105
+
106
+ } // namespace at::mps
107
+
108
+ #else
109
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
110
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGeneratorImpl.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/core/Generator.h>
7
+ #include <ATen/core/PhiloxRNGEngine.h>
8
+ #include <c10/core/GeneratorImpl.h>
9
+ #include <optional>
10
+
11
+ namespace at {
12
+ namespace mps::detail {
13
+
14
+ constexpr uint32_t PHILOX_STATE_N = 7;
15
+ struct rng_data_pod {
16
+ std::array<uint32_t, PHILOX_STATE_N> state{1};
17
+ uint64_t seed = default_rng_seed_val;
18
+ };
19
+
20
+ TORCH_API const Generator& getDefaultMPSGenerator();
21
+ TORCH_API Generator
22
+ createMPSGenerator(uint64_t seed_val = default_rng_seed_val);
23
+
24
+ } // namespace mps::detail
25
+
26
+ struct TORCH_API MPSGeneratorImpl : public c10::GeneratorImpl {
27
+ // Constructors
28
+ MPSGeneratorImpl(uint64_t seed_in = default_rng_seed_val);
29
+ ~MPSGeneratorImpl() override = default;
30
+
31
+ // MPSGeneratorImpl methods
32
+ std::shared_ptr<MPSGeneratorImpl> clone() const;
33
+ void set_current_seed(uint64_t seed) override;
34
+ void set_offset(uint64_t offset) override;
35
+ uint64_t get_offset() const override;
36
+ uint64_t current_seed() const override;
37
+ uint64_t seed() override;
38
+ void set_state(const c10::TensorImpl& new_state) override;
39
+ c10::intrusive_ptr<c10::TensorImpl> get_state() const override;
40
+ void update_philox_counters();
41
+
42
+ void set_engine(at::Philox4_32 engine) {
43
+ engine_ = engine;
44
+ }
45
+ at::Philox4_32 engine() {
46
+ return engine_;
47
+ }
48
+ uint32_t* state_data() {
49
+ return data_.state.data();
50
+ }
51
+ static DeviceType device_type() {
52
+ return DeviceType::MPS;
53
+ }
54
+
55
+ private:
56
+ mps::detail::rng_data_pod data_;
57
+ at::Philox4_32 engine_;
58
+
59
+ MPSGeneratorImpl* clone_impl() const override;
60
+ };
61
+
62
+ } // namespace at
63
+
64
+ #else
65
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
66
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSGuardImpl.h ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+ #include <ATen/Context.h>
6
+ #include <ATen/mps/MPSEvent.h>
7
+ #include <ATen/mps/MPSStream.h>
8
+ #include <c10/core/impl/DeviceGuardImplInterface.h>
9
+ #include <c10/macros/Macros.h>
10
+ #include <c10/util/Exception.h>
11
+
12
+ #ifdef __OBJC__
13
+ #include <Foundation/Foundation.h>
14
+ #include <Metal/Metal.h>
15
+ #include <MetalPerformanceShaders/MetalPerformanceShaders.h>
16
+ #endif
17
+
18
+ #include <ATen/Tensor.h>
19
+ #include <c10/core/MemoryFormat.h>
20
+ #include <c10/core/Storage.h>
21
+ #include <c10/core/TensorImpl.h>
22
+ #include <c10/core/UndefinedTensorImpl.h>
23
+ #include <c10/util/intrusive_ptr.h>
24
+ #include <sys/_types/_size_t.h>
25
+ #include <memory>
26
+
27
+ namespace at::mps {
28
+
29
+ typedef MPSEvent* mpsEvent_t;
30
+
31
+ // TODO: Move the MPSGuardImpl to inherit from NoOpDeviceGuardImpl
32
+ // https://github.com/pytorch/pytorch/issues/77170
33
+ struct TORCH_API MPSGuardImpl final
34
+ : public c10::impl::DeviceGuardImplInterface {
35
+ static constexpr c10::DeviceType static_type = c10::DeviceType::MPS;
36
+
37
+ // constructor
38
+ MPSGuardImpl() {}
39
+ explicit MPSGuardImpl(c10::DeviceType t) {
40
+ TORCH_CHECK(
41
+ t == DeviceType::MPS,
42
+ "MPSGuardImpl initialized with non-MPS DeviceType: ",
43
+ t);
44
+ }
45
+
46
+ // returns the type
47
+ c10::DeviceType type() const override {
48
+ return c10::DeviceType::MPS;
49
+ }
50
+
51
+ Device exchangeDevice(Device d) const override {
52
+ return Device(c10::DeviceType::MPS, 0);
53
+ }
54
+
55
+ Device getDevice() const override {
56
+ return Device(c10::DeviceType::MPS, 0);
57
+ }
58
+
59
+ std::optional<Device> uncheckedGetDevice() const noexcept {
60
+ return Device(c10::DeviceType::MPS, 0);
61
+ }
62
+
63
+ void setDevice(Device d) const override {
64
+ TORCH_CHECK(d.is_mps(), "Expected a MPS device, but got ", d);
65
+ }
66
+
67
+ void uncheckedSetDevice(Device d) const noexcept override {
68
+ // TODO: Currently setting only device 0
69
+ }
70
+
71
+ Stream getStream(Device d) const override {
72
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
73
+ }
74
+
75
+ Stream getNewStream(Device, int priority = 0) const override {
76
+ (void)priority;
77
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
78
+ }
79
+
80
+ Stream getDefaultStream(Device d) const override {
81
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
82
+ }
83
+
84
+ // NB: These do NOT set the current device
85
+ Stream exchangeStream(Stream s) const override {
86
+ return Stream(Stream::DEFAULT, Device(c10::DeviceType::MPS, 0));
87
+ }
88
+ DeviceIndex deviceCount() const noexcept override {
89
+ if (at::hasMPS()) {
90
+ // TODO: extend it for multi-device case
91
+ return 1;
92
+ } else {
93
+ return 0;
94
+ }
95
+ }
96
+
97
+ // Event-related functions
98
+ void createEvent(mpsEvent_t* event, const EventFlag flag) const;
99
+
100
+ void destroyEvent(void* event, const DeviceIndex device_index)
101
+ const noexcept override;
102
+
103
+ void record(
104
+ void** event,
105
+ const Stream& stream,
106
+ const DeviceIndex device_index,
107
+ const EventFlag flag) const override;
108
+
109
+ void block(void* event, const Stream& stream) const override;
110
+
111
+ bool queryEvent(void* event) const override;
112
+
113
+ void synchronizeEvent(void* event) const override;
114
+
115
+ double elapsedTime(void* event1, void* event2, const DeviceIndex device_index)
116
+ const override;
117
+
118
+ void synchronizeDevice(const DeviceIndex device_index) const override;
119
+ };
120
+
121
+ /// A variant of OptionalDeviceGuard that is specialized for MPS.
122
+ struct OptionalMPSGuard {
123
+ explicit OptionalMPSGuard() : guard_() {}
124
+
125
+ explicit OptionalMPSGuard(std::optional<Device> device_opt)
126
+ : guard_(device_opt) {}
127
+
128
+ /// Set the current MPS device to the passed device index, if it is not
129
+ /// nullopt
130
+ explicit OptionalMPSGuard(std::optional<DeviceIndex> device_index_opt)
131
+ : guard_(device_index_opt) {}
132
+
133
+ // Copy is not allowed
134
+ OptionalMPSGuard(const OptionalMPSGuard&) = delete;
135
+ OptionalMPSGuard& operator=(const OptionalMPSGuard&) = delete;
136
+ OptionalMPSGuard(OptionalMPSGuard&& other) = delete;
137
+ OptionalMPSGuard& operator=(OptionalMPSGuard&& other) = delete;
138
+
139
+ /// Sets the MPS device to the given device, initializing the guard if it
140
+ /// is not already initialized. Errors if the given device is not a MPS
141
+ /// device.
142
+ void set_device(Device device) {
143
+ guard_.set_device(device);
144
+ }
145
+
146
+ /// Sets the MPS device to the given device, initializing the guard if it is
147
+ /// not already initialized. Errors if the given device is not a MPS device.
148
+ void reset_device(Device device) {
149
+ guard_.reset_device(device);
150
+ }
151
+
152
+ /// Sets the MPS device to the given device index, initializing the guard if
153
+ /// it is not already initialized.
154
+ void set_index(DeviceIndex device_index) {
155
+ guard_.set_index(device_index);
156
+ }
157
+
158
+ /// Returns the device that was set immediately prior to initialization of the
159
+ /// guard, or nullopt if the guard is uninitialized.
160
+ std::optional<Device> original_device() const {
161
+ return guard_.original_device();
162
+ }
163
+
164
+ /// Returns the most recent device that was set using this device guard,
165
+ /// either from construction, or via set_device, if the guard is initialized,
166
+ /// or nullopt if the guard is uninitialized.
167
+ std::optional<Device> current_device() const {
168
+ return guard_.current_device();
169
+ }
170
+
171
+ /// Restore the original MPS device, resetting this guard to uninitialized
172
+ /// state.
173
+ void reset() {
174
+ guard_.reset();
175
+ }
176
+
177
+ private:
178
+ c10::impl::InlineOptionalDeviceGuard<MPSGuardImpl> guard_;
179
+ };
180
+
181
+ C10_REGISTER_GUARD_IMPL(MPS, MPSGuardImpl)
182
+
183
+ } // namespace at::mps
184
+
185
+ #else
186
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
187
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSHooks.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/Generator.h>
7
+ #include <ATen/detail/MPSHooksInterface.h>
8
+ #include <ATen/mps/MPSEvent.h>
9
+ #include <optional>
10
+
11
+ namespace at::mps {
12
+
13
+ // The real implementation of MPSHooksInterface
14
+ struct MPSHooks : public at::MPSHooksInterface {
15
+ MPSHooks(at::MPSHooksArgs) {}
16
+ void init() const override;
17
+
18
+ // MPSDevice interface
19
+ bool hasMPS() const override;
20
+ bool isOnMacOSorNewer(unsigned major, unsigned minor) const override;
21
+
22
+ Device getDeviceFromPtr(void* data) const override;
23
+
24
+ // MPSGeneratorImpl interface
25
+ const Generator& getDefaultGenerator(
26
+ DeviceIndex device_index = -1) const override;
27
+ Generator getNewGenerator(DeviceIndex device_index = -1) const override;
28
+
29
+ // MPSStream interface
30
+ void deviceSynchronize() const override;
31
+ void commitStream() const override;
32
+ void* getCommandBuffer() const override;
33
+ void* getDispatchQueue() const override;
34
+
35
+ // MPSAllocator interface
36
+ Allocator* getMPSDeviceAllocator() const override;
37
+ void emptyCache() const override;
38
+ size_t getCurrentAllocatedMemory() const override;
39
+ size_t getDriverAllocatedMemory() const override;
40
+ size_t getRecommendedMaxMemory() const override;
41
+ void setMemoryFraction(double ratio) const override;
42
+ bool isPinnedPtr(const void* data) const override;
43
+ Allocator* getPinnedMemoryAllocator() const override;
44
+
45
+ // MPSProfiler interface
46
+ void profilerStartTrace(const std::string& mode, bool waitUntilCompleted)
47
+ const override;
48
+ void profilerStopTrace() const override;
49
+
50
+ // MPSEvent interface
51
+ uint32_t acquireEvent(bool enable_timing) const override;
52
+ void releaseEvent(uint32_t event_id) const override;
53
+ void recordEvent(uint32_t event_id) const override;
54
+ void waitForEvent(uint32_t event_id) const override;
55
+ void synchronizeEvent(uint32_t event_id) const override;
56
+ bool queryEvent(uint32_t event_id) const override;
57
+ double elapsedTimeOfEvents(uint32_t start_event_id, uint32_t end_event_id)
58
+ const override;
59
+
60
+ bool isBuilt() const override {
61
+ return true;
62
+ }
63
+ bool isAvailable() const override {
64
+ return hasMPS();
65
+ }
66
+ bool hasPrimaryContext(DeviceIndex device_index) const override {
67
+ // When MPS is available, it is always in use for the one device.
68
+ return true;
69
+ }
70
+ };
71
+
72
+ } // namespace at::mps
73
+
74
+ #else
75
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
76
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSProfiler.h ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <ATen/Tensor.h>
7
+ #include <ATen/mps/MPSAllocatorInterface.h>
8
+ #include <ATen/mps/MPSStream.h>
9
+
10
+ #include <os/log.h>
11
+ #include <os/signpost.h>
12
+
13
+ #include <atomic>
14
+ #include <ctime>
15
+ #include <sstream>
16
+ #include <string>
17
+ #include <unordered_map>
18
+ #include <utility>
19
+
20
+ #ifndef __OBJC__
21
+ typedef void* MTLCaptureManager;
22
+ #endif
23
+
24
+ namespace at::mps {
25
+
26
+ namespace Profiler {
27
+
28
+ struct BaseInfo {
29
+ // profiling info types
30
+ enum class Type {
31
+ GRAPH,
32
+ KERNEL,
33
+ COPY,
34
+ CPU_FALLBACK,
35
+ };
36
+
37
+ BaseInfo(Type infoType, uint64_t Id, const uintptr_t Handle)
38
+ : type(infoType), profileId(Id), handle(Handle) {}
39
+ virtual ~BaseInfo() = default;
40
+
41
+ // type of profiling info
42
+ Type type;
43
+ // unique profile ID for execution instances of operations or copies
44
+ uint64_t profileId;
45
+ // ID generated by os_signpost
46
+ // since it's possible to use event and interval-based signposts at the
47
+ // same time, we need separate IDs for each.
48
+ os_signpost_id_t eventSignpostId = 0, intervalSignpostId = 0;
49
+ // accumulated GPU time in ms (obtained from CompletionHandler's "GPUEndTime -
50
+ // GPUStartTime")
51
+ std::atomic<double> totalGpuTime{0.0};
52
+ // accumulated Scheduling time in ms (obtained from CompletionHandler's
53
+ // "KernelEndTime - KernelStartTime")
54
+ std::atomic<double> totalSchedulingTime{0.0};
55
+ // indicates if the operation or copy execution has completed
56
+ std::atomic_bool completed{false};
57
+ // handle used to identify the profile info's instance (usually the pointer)
58
+ const uintptr_t handle;
59
+
60
+ virtual const std::string toString(
61
+ double gpuTime = 0,
62
+ double schedulingTime = 0) const;
63
+ // builds a string for a tensor (format: Device:ScalarType[tensor.sizes()])
64
+ static std::string buildTensorString(
65
+ const Tensor& tensor,
66
+ bool includeBufferId = false);
67
+ static uint64_t getTime() {
68
+ return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW);
69
+ }
70
+ };
71
+
72
+ struct OperationInfo : BaseInfo {
73
+ OperationInfo(
74
+ const void* Handle,
75
+ bool IsGraph,
76
+ uint64_t Id,
77
+ const std::string& StrKey)
78
+ : BaseInfo(IsGraph ? Type::GRAPH : Type::KERNEL, Id, uintptr_t(Handle)),
79
+ strKey(StrKey) {}
80
+
81
+ uint64_t runCount = 0;
82
+ std::string strKey;
83
+
84
+ const std::string toString(double gpuTime = 0, double schedulingTime = 0)
85
+ const override;
86
+
87
+ // builds a string for a kernel
88
+ static std::string buildKernelString(
89
+ const std::string& kernelName,
90
+ const TensorList& tensors,
91
+ bool includeBufferId = false) {
92
+ std::stringstream kernelStr;
93
+ kernelStr << kernelName;
94
+ for (const Tensor& tensor : tensors) {
95
+ kernelStr << ':' << BaseInfo::buildTensorString(tensor, includeBufferId);
96
+ }
97
+ return kernelStr.str();
98
+ }
99
+ };
100
+
101
+ struct CpuFbInfo : BaseInfo {
102
+ CpuFbInfo(uint64_t Id, const std::string& OpName)
103
+ : BaseInfo(Type::CPU_FALLBACK, Id, 0), opName(OpName) {}
104
+
105
+ uint64_t runCount = 0;
106
+ // the current and total overhead of copies in bytes required to convert the
107
+ // Op's input tensors from MPS to CPU and then output from CPU back to MPS
108
+ size_t currentCopyOverhead = 0;
109
+ size_t totalCopyOverhead = 0;
110
+ std::string opName;
111
+ std::string strKey;
112
+ uint64_t startTime = 0;
113
+
114
+ const std::string toString(double gpuTime = 0, double schedulingTime = 0)
115
+ const override;
116
+
117
+ void updateCopyOverhead(const TensorList& tensors) {
118
+ currentCopyOverhead = 0;
119
+ for (const Tensor& tensor : tensors) {
120
+ if (tensor.defined()) {
121
+ currentCopyOverhead += tensor.nbytes();
122
+ }
123
+ }
124
+ totalCopyOverhead += currentCopyOverhead;
125
+ }
126
+ };
127
+
128
+ struct CopyInfo : BaseInfo {
129
+ enum class Kind {
130
+ MPS_TO_MPS,
131
+ MPS_TO_CPU,
132
+ CPU_TO_MPS,
133
+ };
134
+
135
+ CopyInfo(
136
+ const void* Handle,
137
+ size_t Length,
138
+ uint64_t Id,
139
+ bool IsNonBlocking,
140
+ bool UsesBlitter)
141
+ : BaseInfo(Type::COPY, Id, uintptr_t(Handle)),
142
+ kind(Kind::MPS_TO_MPS),
143
+ length(Length),
144
+ isNonBlocking(IsNonBlocking),
145
+ usesBlitter(UsesBlitter) {}
146
+
147
+ Kind kind;
148
+ size_t length;
149
+ bool isNonBlocking;
150
+ bool usesBlitter;
151
+ std::string srcStrKey;
152
+ std::string dstStrKey;
153
+ // for copies that don't use blitters, we measure CPU time
154
+ uint64_t startTime = 0;
155
+
156
+ const std::string toString(double gpuTime = 0, double schedulingTime = 0)
157
+ const override;
158
+
159
+ static std::string buildTensorString(
160
+ const void* buffer,
161
+ const OptionalTensorRef tensor,
162
+ bool includeBufferId = false);
163
+
164
+ static bool isStorageOnMPS(
165
+ const void* buffer,
166
+ const OptionalTensorRef tensor) {
167
+ if (tensor.has_value()) {
168
+ return tensor->device().type() == at::kMPS;
169
+ }
170
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(buffer);
171
+ // getUnalignedBufferSize() returns -1 if input buffer is not on MPS device
172
+ return getIMPSAllocator()->getUnalignedBufferSize(buffer) >= 0;
173
+ }
174
+
175
+ static Kind getCopyKind(
176
+ const void* srcBuffer,
177
+ const void* dstBuffer,
178
+ const OptionalTensorRef srcTensor,
179
+ const OptionalTensorRef dstTensor) {
180
+ const bool isSrcOnMPS = isStorageOnMPS(srcBuffer, srcTensor);
181
+ const bool isDstOnMPS = isStorageOnMPS(dstBuffer, dstTensor);
182
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(isSrcOnMPS || isDstOnMPS);
183
+ if (isSrcOnMPS && !isDstOnMPS) {
184
+ return Kind::MPS_TO_CPU;
185
+ } else if (!isSrcOnMPS && isDstOnMPS) {
186
+ return Kind::CPU_TO_MPS;
187
+ }
188
+ return Kind::MPS_TO_MPS;
189
+ }
190
+ };
191
+
192
+ struct CopyStat : CopyInfo {
193
+ explicit CopyStat(std::string CopyKindStr)
194
+ : CopyInfo(nullptr, 0, 0, false, false),
195
+ kindStr(std::move(CopyKindStr)) {}
196
+ // total number of copies
197
+ size_t totalCount = 0;
198
+ // number of Scalar copies (i.e., less than sizeof(int64))
199
+ size_t scalarsCount = 0;
200
+ // number of blocking copies (i.e., require syncing to GPU)
201
+ size_t blockingCount = 0;
202
+ // number of copies that used memcpy(), instead of Metal Blit Encoder
203
+ size_t memcpyCount = 0;
204
+ // accumulated GPU time in ms for the scalar copies
205
+ std::atomic<double> scalarsGpuTime{0.0};
206
+ // copy kind in string type
207
+ std::string kindStr;
208
+ };
209
+
210
+ class MPSProfiler {
211
+ public:
212
+ // lower 16 bits used for profiler options
213
+ enum ProfileOptions : uint32_t {
214
+ OPTIONS_NONE = 0,
215
+ // ALL_* means, all signpost types (RUN_OPERATION|BLIT_COPY|CPU_FALLBACK,
216
+ // etc.) (used for convenience to not compute bit flags by OR-ing manually)
217
+ // trace all signpost types using events
218
+ ALL_SIGNPOST_EVENTS = (1 << 0),
219
+ // trace all signpost types using intervals
220
+ ALL_SIGNPOST_INTERVALS = (1 << 1),
221
+ // always wait for command buffer to finish executing after each commit
222
+ WAIT_UNTIL_COMPLETED = (1 << 2),
223
+ // for interval-based signposts, include the scheduling portion of
224
+ // Graph/Kernel/Copy executions as well.
225
+ // if flag is disable, only "GPU run time" is included in interval,
226
+ // and not schedule time.
227
+ INCLUDE_SCHEDULE_INTERVAL = (1 << 3),
228
+
229
+ // use these if you need to trace signposts types individually (rarely
230
+ // required) trace signpost using intervals
231
+ USE_INTERVALS = (1 << 4),
232
+ // trace signpost by emitting events
233
+ USE_EVENTS = (1 << 5),
234
+ // used for sanity check (Change this when new option added)
235
+ OPTIONS_COUNT = (USE_EVENTS << 1) - 1,
236
+ };
237
+
238
+ // when adding new types, #define the type string in MPSProfiler.mm as well.
239
+ // upper 16 bits used for event types
240
+ enum SignpostTypes : uint32_t {
241
+ SIGNPOST_NONE = 0,
242
+ // trace signposts for PyTorch operation executions
243
+ RUN_OPERATION = (1 << 16),
244
+ // trace signposts for blitter copies
245
+ BLIT_COPY = (1 << 17),
246
+ // trace signposts for ops that fall back on CPU
247
+ CPU_FALLBACK = (1 << 18),
248
+ // used for sanity check (Change this when new type added)
249
+ SIGNPOST_COUNT = (CPU_FALLBACK << 1) - 1,
250
+ };
251
+
252
+ enum LogOptions : uint32_t {
253
+ LOG_NONE = 0,
254
+
255
+ // Info logging options during execution
256
+ // -------------------------------------
257
+ // prints operation info (id/key/run_count) during execution
258
+ OPERATION_INFO = (1 << 0),
259
+ // prints copy info (src/dst tensors/buffers, size, etc.) during execution
260
+ COPY_INFO = (1 << 1),
261
+ // prints CPU Fallback info (id/runCount/opName/copyOverhead) during
262
+ // execution
263
+ CPU_FALLBACK_INFO = (1 << 2),
264
+
265
+ // Profiling Statistics logging options when process terminates
266
+ // ------------------------------------------------------------
267
+ // prints all stats (OPERATION_STATS, COPY_STATS, CPU_FALLBACK_STATS) before
268
+ // process terminates this is convenient to not combine following stats bit
269
+ // flags manually
270
+ ALL_STATS = (1 << 3),
271
+ // prints operation stats (GPU times, run count, etc.) before process
272
+ // terminates
273
+ OPERATION_STATS = (1 << 4),
274
+ // prints copies stats (GPU times, copy kinds, sizes, etc.) before process
275
+ // terminates
276
+ COPY_STATS = (1 << 5),
277
+ // prints CPU Fallback stats (CPU times, run times, size of MPS<->CPU copies
278
+ // for tensors, etc.) before process terminates
279
+ CPU_FALLBACK_STATS = (1 << 6),
280
+
281
+ // Metadata format options when logging the info
282
+ // ---------------------------------------------
283
+ // if enabled, includes GPU run time in metadata (i.e.,
284
+ // GPUEndTime-GPUStartTime from Metal Command Buffers) (e.g., [GPU=0.324
285
+ // ms])
286
+ INCLUDE_GPU_TIME = (1 << 7),
287
+ // if enabled, includes GPU scheduling time in metadata separately
288
+ // (i.e., KernelEndTime-KernelStartTime from Metal Command Buffers)
289
+ // e.g., [GPU=0.324 ms, KRNL=0.036 ms]
290
+ INCLUDE_KERNEL_TIME = (1 << 8),
291
+ // if enabled, includes the unique buffer ID in metadata for the storage
292
+ // of a tensor that was allocated on MPSAllocator. This is useful (along
293
+ // with the EV "PYTORCH_DEBUG_MPS_ALLOCATOR") to identify buffers that are
294
+ // involved with various operations.
295
+ INCLUDE_BUFFER_ID = (1 << 9),
296
+
297
+ // used for sanity check (Change this when new option added)
298
+ LOG_COUNT = (INCLUDE_BUFFER_ID << 1) - 1,
299
+ };
300
+
301
+ explicit MPSProfiler();
302
+ ~MPSProfiler();
303
+
304
+ // the handle is either "MPSGraph*" or "id<MTLComputePipelineState>" for Metal
305
+ // Kernels the beginProfile*() functions return a profileId which is unique
306
+ // per graph/kernel/copy
307
+ uint64_t beginProfileKernel(
308
+ const void* handle,
309
+ const std::string& strKey,
310
+ bool isGraph);
311
+ uint64_t beginProfileKernel(
312
+ const void* handle,
313
+ const std::string& kernelName,
314
+ const TensorList& tensors);
315
+ uint64_t beginProfileCopy(
316
+ const void* srcBuffer,
317
+ const void* dstBuffer,
318
+ const OptionalTensorRef srcTensor,
319
+ const OptionalTensorRef dstTensor,
320
+ size_t length,
321
+ bool isNonBlocking,
322
+ bool usesBlitter = true);
323
+ uint64_t beginProfileCPUFallback(
324
+ const std::string& opName,
325
+ const TensorList& tensors);
326
+ void beginProfileGPUInterval(const void* handle);
327
+
328
+ void endProfileCopy(uint64_t profileId, SyncType syncType);
329
+ void endProfileKernel(const void* handle, SyncType syncType = SyncType::NONE);
330
+ void endProfileCPUFallback(const std::string& opName);
331
+
332
+ // these are used to hook into Python bindings for torch.mps.profiler module.
333
+ // this enables generating OS Signpost traces from MPSProfiler on-demand
334
+ // during runtime (instead of environment variables).
335
+ // The "mode" could be either "interval", "event", or both "interval,event"
336
+ // for interval-based and/or event-based signpost tracing.
337
+ void StartTrace(const std::string& mode, bool waitUntilCompleted);
338
+ void StopTrace();
339
+
340
+ // Abstractions for GPU trace capturing
341
+ bool isCaptureEnabled() const;
342
+ bool isCapturing() const;
343
+ void startCapture(const std::string& name, MPSStream* stream = nullptr);
344
+ void stopCapture(MPSStream* stream = nullptr);
345
+
346
+ // convenience functions to indicate whether signpost tracing or
347
+ // logging are enabled for the SignpostTypes
348
+ bool isOperationProfilingEnabled() const {
349
+ return (m_signpost_types & SignpostTypes::RUN_OPERATION) ||
350
+ (m_log_options &
351
+ (LogOptions::OPERATION_INFO | LogOptions::OPERATION_STATS));
352
+ }
353
+ bool isCopyProfilingEnabled() const {
354
+ return (m_signpost_types & SignpostTypes::BLIT_COPY) ||
355
+ (m_log_options & (LogOptions::COPY_INFO | LogOptions::COPY_STATS));
356
+ }
357
+ bool isCPUFallbackProfilingEnabled() const {
358
+ return (m_signpost_types & SignpostTypes::CPU_FALLBACK) ||
359
+ (m_log_options &
360
+ (LogOptions::CPU_FALLBACK_INFO | LogOptions::CPU_FALLBACK_STATS));
361
+ }
362
+ bool isSignpostTracingEnabled() const {
363
+ return (m_signpost_types != SignpostTypes::SIGNPOST_NONE);
364
+ }
365
+
366
+ private:
367
+ // indicates what type of signpost types are enabled and traced by MPS
368
+ // profiler.
369
+ uint32_t m_signpost_types = 0;
370
+ uint32_t m_profile_options = 0;
371
+ uint32_t m_log_options = 0;
372
+ uint64_t m_kernel_counter = 0;
373
+ uint64_t m_graph_counter = 0;
374
+ uint64_t m_cpu_fb_counter = 0;
375
+ uint64_t m_copy_counter = 0;
376
+ // technically, it's possible to trace both events and intervals at the same
377
+ // time so we use separate os_log categories for them
378
+ os_log_t m_os_log_events;
379
+ os_log_t m_os_log_intervals;
380
+ // stats logging could run either from destructor or signal handler
381
+ // so this is used to check if logging has already started.
382
+ std::atomic_bool hasLoggedStats{false};
383
+ // indicates there are pending completionHandler callbacks that haven't been
384
+ // called yet.
385
+ std::atomic_bool hasPendingCompletionHandlers{false};
386
+ // used to capture sigint signal to log profiling stats
387
+ static struct sigaction currentSigint, previousSigint;
388
+
389
+ // We use the following lists for two reasons:
390
+ // 1- for interval-based signposts the "begin" point won't be in same function
391
+ // as the "end" point where we need to be able to retrieve signpost's info
392
+ // 2- if Operations info need to be logged when process ends using
393
+ // LogOptions::OPERATION_INFO.
394
+
395
+ // the pointer key for this map is either "MPSGraph*" or
396
+ // "id<MTLComputePipelineState>" for Metal Kernels this list is retained and
397
+ // could be logged along with aggregate profiling numbers when the process
398
+ // ends.
399
+ std::unordered_map<uintptr_t, std::unique_ptr<OperationInfo>>
400
+ m_op_info_list{};
401
+ // the string key for this map is the op name that we fall back to execute on
402
+ // CPU this list is retained and could be logged along with aggregate
403
+ // profiling numbers when the process ends.
404
+ std::unordered_map<std::string, std::unique_ptr<CpuFbInfo>>
405
+ m_cpu_fb_info_list{};
406
+ // this list contains the info for copies, and its key is the unique profileId
407
+ // which is generated from m_copy_counter
408
+ // The copyInfo list is not retained.
409
+ std::unordered_map<uint64_t, std::unique_ptr<CopyInfo>> m_copy_info_list{};
410
+ // a short list that contains copy stats
411
+ std::unordered_map<CopyInfo::Kind, std::unique_ptr<CopyStat>>
412
+ m_copy_stat_list{};
413
+
414
+ mutable MTLCaptureManager* captureManager = nil;
415
+ unsigned captureCount = 0;
416
+
417
+ void initialize();
418
+ void beginProfileExecution(BaseInfo& info, bool cpuExecution = false);
419
+ void endProfileExecution(
420
+ BaseInfo& info,
421
+ os_signpost_id_t event_signpost_id,
422
+ os_signpost_id_t interval_signpost_id,
423
+ double gpuTime,
424
+ double schedulingTime);
425
+ void addProfilerScheduledHandler(BaseInfo& info);
426
+ void addProfilerCompletedHandler(BaseInfo& info, SyncType syncType);
427
+ void emitSignpostEvent(
428
+ SignpostTypes signpost_type,
429
+ os_signpost_id_t signpost_id,
430
+ const std::string& msg) const;
431
+ void beginSignpostInterval(
432
+ SignpostTypes signpost_type,
433
+ os_signpost_id_t signpost_id,
434
+ const std::string& msg) const;
435
+ void endSignpostInterval(
436
+ SignpostTypes signpost_type,
437
+ os_signpost_id_t signpost_id) const;
438
+
439
+ void updateCopyStats(
440
+ const CopyInfo& copyInfo,
441
+ double gpuTime,
442
+ double schedulingTime);
443
+ // returns true if logging the profiling info "during the execution" is
444
+ // enabled
445
+ bool isProfileInfoLoggingEnabled(
446
+ BaseInfo::Type infoType,
447
+ bool isExecutionEnded);
448
+ // logs all the profiling stats that are enabled
449
+ void logProfilingStats();
450
+ // logs kernel profiling stats when the process ends.
451
+ void logOperationsProfilingStats(std::FILE* f) const;
452
+ // logs CPU Fallback profiling stats when the process ends.
453
+ void logCPUFallbackProfilingStats(std::FILE* f) const;
454
+ // logs copy profiling stats when the process ends.
455
+ void logCopyProfilingStats(std::FILE* f) const;
456
+
457
+ os_signpost_id_t generateSignpostId(
458
+ os_signpost_type_t signpostType,
459
+ const void* ptr = nullptr);
460
+ static SignpostTypes getSignpostType(BaseInfo::Type infoType);
461
+ static void handleIntSignal(int signal);
462
+ };
463
+
464
+ } // namespace Profiler
465
+
466
+ Profiler::MPSProfiler& getMPSProfiler();
467
+
468
+ } // namespace at::mps
469
+
470
+ #else
471
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
472
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/mps/MPSStream.h ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // Copyright © 2022 Apple Inc.
3
+
4
+ #pragma once
5
+
6
+ #include <cstdint>
7
+ #include <utility>
8
+
9
+ #include <ATen/mps/MPSDevice.h>
10
+ #include <c10/core/DeviceGuard.h>
11
+ #include <c10/core/Stream.h>
12
+ #include <c10/util/Exception.h>
13
+
14
+ #ifdef __OBJC__
15
+ #include <Foundation/Foundation.h>
16
+ #include <Metal/Metal.h>
17
+ #include <MetalPerformanceShaders/MetalPerformanceShaders.h>
18
+ #include <MetalPerformanceShadersGraph/MetalPerformanceShadersGraph.h>
19
+ typedef MPSCommandBuffer* MPSCommandBuffer_t;
20
+ typedef id<MTLCommandQueue> MTLCommandQueue_t;
21
+ typedef id<MTLComputeCommandEncoder> MTLComputeCommandEncoder_t;
22
+ typedef id<MTLSharedEvent> MTLSharedEvent_t;
23
+ typedef id<MTLDevice> MTLDevice_t;
24
+ typedef id<MTLBuffer> MTLBuffer_t;
25
+ #else
26
+ #include <dispatch/dispatch.h>
27
+ typedef void* MPSCommandBuffer_t;
28
+ typedef void* MPSGraph;
29
+ typedef void* MPSGraphExecutionDescriptor;
30
+ typedef void* MPSGraphCompilationDescriptor;
31
+ typedef void* MTLCommandQueue_t;
32
+ typedef void* MTLComputeCommandEncoder_t;
33
+ typedef void* MTLSharedEvent_t;
34
+ typedef void* MTLDevice_t;
35
+ typedef void* MTLBuffer_t;
36
+ typedef void* MTLCommandBufferHandler;
37
+ typedef void* NSDictionary;
38
+ #define nil NULL
39
+ #endif
40
+
41
+ namespace at::mps {
42
+
43
+ //-----------------------------------------------------------------
44
+ // MPSStream
45
+ //-----------------------------------------------------------------
46
+
47
+ enum class SyncType {
48
+ NONE, // no commit to command buffer
49
+ COMMIT, // commit and flush the command buffer
50
+ COMMIT_AND_WAIT, // flush and wait for command buffer execution to finish
51
+ COMMIT_AND_CONTINUE, // commit and continue with a new underlying command buffer
52
+ COMMIT_ADAPTIVE, // commit adaptively based on available memory
53
+ };
54
+
55
+ class TORCH_API MPSStream {
56
+ public:
57
+ enum Unchecked { UNCHECKED };
58
+
59
+ /// Construct a MPSStream from a Stream. This construction is checked,
60
+ /// and will raise an error if the Stream is not, in fact, a MPS stream.
61
+ explicit MPSStream(Stream stream);
62
+
63
+ ~MPSStream();
64
+
65
+ MTLCommandQueue_t commandQueue() const {
66
+ return _commandQueue;
67
+ }
68
+
69
+ dispatch_queue_t queue() const {
70
+ return _serialQueue;
71
+ }
72
+
73
+ MPSCommandBuffer_t commandBuffer();
74
+ MTLComputeCommandEncoder_t commandEncoder();
75
+ void endKernelCoalescing();
76
+ void synchronize(SyncType syncType);
77
+ void fill(MTLBuffer_t buffer, uint8_t value, size_t length, size_t offset, SyncType syncType = SyncType::NONE);
78
+ void copy(MTLBuffer_t srcBuffer,
79
+ MTLBuffer_t dstBuffer,
80
+ size_t length,
81
+ size_t srcOffset,
82
+ size_t dstOffset,
83
+ uint64_t profileId,
84
+ SyncType syncType = SyncType::NONE);
85
+ void copy_and_sync(MTLBuffer_t srcBuffer,
86
+ MTLBuffer_t dstBuffer,
87
+ size_t length,
88
+ size_t srcOffset,
89
+ size_t dstOffset,
90
+ bool non_blocking,
91
+ uint64_t profileId);
92
+ void executeMPSGraph(MPSGraph* mpsGraph,
93
+ NSDictionary* feeds,
94
+ NSDictionary* results,
95
+ SyncType syncType = SyncType::NONE);
96
+ void addCompletedHandler(MTLCommandBufferHandler block);
97
+
98
+ /// Get the MPS device index that this stream is associated with.
99
+ c10::DeviceIndex device_index() const {
100
+ return _stream.device_index();
101
+ }
102
+
103
+ MTLCommandQueue_t stream() const {
104
+ return _commandQueue;
105
+ }
106
+
107
+ MTLDevice_t device() const;
108
+
109
+ /// Explicit conversion to Stream.
110
+ Stream unwrap() const {
111
+ return _stream;
112
+ }
113
+
114
+ MTLBuffer_t getErrorBuffer();
115
+ void checkLastError();
116
+
117
+ private:
118
+ Stream _stream;
119
+ MTLCommandQueue_t _commandQueue = nil;
120
+ MPSCommandBuffer_t _commandBuffer = nil;
121
+ MPSCommandBuffer_t _prevCommandBuffer = nil;
122
+ MTLComputeCommandEncoder_t _commandEncoder = nil;
123
+ MPSGraphExecutionDescriptor* _executionDescriptor = nil;
124
+ MPSGraphCompilationDescriptor* _compilationDescriptor = nil;
125
+ dispatch_queue_t _serialQueue = nullptr;
126
+ // CommitAndContinue is enabled by default
127
+ bool _enableCommitAndContinue = true;
128
+ // Buffer that contains last raised error
129
+ MTLBuffer_t _errorBuffer = nil;
130
+
131
+ // use synchronize() to access any of these commit functions outside MPSStream
132
+ void commit();
133
+ void commitAndWait();
134
+ void commitAndContinue();
135
+ void flush();
136
+ };
137
+
138
+ /**
139
+ * Get the current MPS stream
140
+ */
141
+ TORCH_API MPSStream* getCurrentMPSStream();
142
+
143
+ /**
144
+ * Get the default MPS stream
145
+ */
146
+ TORCH_API MPSStream* getDefaultMPSStream();
147
+
148
+ //-----------------------------------------------------------------
149
+ // MPSStreamImpl
150
+ //-----------------------------------------------------------------
151
+
152
+ class TORCH_API MPSStreamImpl {
153
+ public:
154
+ /**
155
+ * Gets single instance of the MPSStream.
156
+ */
157
+ static MPSStream* getInstance();
158
+
159
+ private:
160
+ static MPSStream* _stream;
161
+ MPSStreamImpl();
162
+ };
163
+
164
+ #ifdef __OBJC__
165
+ void dispatch_sync_with_rethrow(dispatch_queue_t queue, void (^block)());
166
+ #endif
167
+ } // namespace at::mps
168
+
169
+ #else
170
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
171
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/Activation.h ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <ATen/native/Gelu.h>
6
+ #include <c10/util/Exception.h>
7
+
8
+ namespace c10 {
9
+ class Scalar;
10
+ }
11
+
12
+ namespace at {
13
+ struct TensorIterator;
14
+ struct TensorIteratorBase;
15
+ class TensorBase;
16
+ }
17
+
18
+ namespace at::native {
19
+
20
+ using structured_activation_fn = void (*)(TensorIteratorBase&);
21
+ using structured_activation_backward_fn = void (*)(TensorIteratorBase&);
22
+
23
+ using activation_fn = void (*)(TensorIterator&);
24
+ using activation_backward_fn = void (*)(TensorIterator&);
25
+ using softplus_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
26
+ using softplus_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
27
+ using threshold_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&);
28
+ using hardtanh_backward_fn = void (*)(TensorIterator&, const c10::Scalar&, const c10::Scalar&);
29
+ using hardsigmoid_fn = void(*)(TensorIteratorBase&);
30
+ using hardsigmoid_backward_fn = void(*)(TensorIteratorBase&);
31
+ using hardswish_fn = void(*)(TensorIterator&);
32
+ using hardswish_backward_fn = void(*)(TensorIterator&);
33
+ using shrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
34
+ using softshrink_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
35
+ using shrink_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
36
+ using elu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&);
37
+ using elu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&, const c10::Scalar&, const c10::Scalar&, bool);
38
+ using leaky_relu_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
39
+ using leaky_relu_backward_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
40
+ using log_sigmoid_cpu_fn = void (*)(TensorBase&, TensorBase&, const TensorBase&);
41
+ using gelu_fn = void (*)(TensorIteratorBase&, GeluType);
42
+ using gelu_backward_fn = void (*)(TensorIteratorBase&, GeluType);
43
+ using glu_jvp_fn = void (*)(TensorIteratorBase&);
44
+
45
+ DECLARE_DISPATCH(elu_fn, elu_stub)
46
+ DECLARE_DISPATCH(elu_backward_fn, elu_backward_stub)
47
+ DECLARE_DISPATCH(softplus_fn, softplus_stub)
48
+ DECLARE_DISPATCH(softplus_backward_fn, softplus_backward_stub)
49
+ DECLARE_DISPATCH(log_sigmoid_cpu_fn, log_sigmoid_cpu_stub)
50
+ DECLARE_DISPATCH(activation_backward_fn, log_sigmoid_backward_stub)
51
+ DECLARE_DISPATCH(threshold_fn, threshold_stub)
52
+ DECLARE_DISPATCH(gelu_fn, GeluKernel)
53
+ DECLARE_DISPATCH(gelu_backward_fn, GeluBackwardKernel)
54
+ DECLARE_DISPATCH(hardtanh_backward_fn, hardtanh_backward_stub)
55
+ DECLARE_DISPATCH(hardsigmoid_fn, hardsigmoid_stub)
56
+ DECLARE_DISPATCH(hardsigmoid_backward_fn, hardsigmoid_backward_stub)
57
+ DECLARE_DISPATCH(hardswish_fn, hardswish_stub)
58
+ DECLARE_DISPATCH(hardswish_backward_fn, hardswish_backward_stub)
59
+ DECLARE_DISPATCH(shrink_fn, hardshrink_stub)
60
+ DECLARE_DISPATCH(softshrink_fn, softshrink_stub)
61
+ DECLARE_DISPATCH(shrink_backward_fn, shrink_backward_stub)
62
+ DECLARE_DISPATCH(leaky_relu_fn, leaky_relu_stub)
63
+ DECLARE_DISPATCH(leaky_relu_backward_fn, leaky_relu_backward_stub)
64
+ DECLARE_DISPATCH(structured_activation_fn, glu_stub)
65
+ DECLARE_DISPATCH(activation_backward_fn, glu_backward_stub)
66
+ DECLARE_DISPATCH(glu_jvp_fn, glu_jvp_stub)
67
+ DECLARE_DISPATCH(structured_activation_fn, silu_stub)
68
+ DECLARE_DISPATCH(structured_activation_backward_fn, silu_backward_stub)
69
+ DECLARE_DISPATCH(structured_activation_fn, mish_stub)
70
+ DECLARE_DISPATCH(activation_backward_fn, mish_backward_stub)
71
+ DECLARE_DISPATCH(activation_fn, prelu_stub)
72
+ DECLARE_DISPATCH(activation_backward_fn, prelu_backward_stub)
73
+
74
+ } // namespace at::native
75
+
76
+ #else
77
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
78
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/AdaptivePooling.h ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <c10/util/ArrayRef.h>
7
+ #include <c10/util/irange.h>
8
+ #include <cmath>
9
+
10
+ namespace at::native {
11
+
12
+ using adaptive_avg_pooling2d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size);
13
+ using adaptive_avg_pooling2d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output);
14
+ DECLARE_DISPATCH(adaptive_avg_pooling2d_fn, adaptive_avg_pool2d_kernel)
15
+ DECLARE_DISPATCH(adaptive_avg_pooling2d_backward_fn, adaptive_avg_pool2d_backward_kernel)
16
+
17
+ using adaptive_max_pooling2d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size);
18
+ using adaptive_max_pooling2d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
19
+ DECLARE_DISPATCH(adaptive_max_pooling2d_fn, adaptive_max_pool2d_kernel)
20
+ DECLARE_DISPATCH(adaptive_max_pooling2d_backward_fn, adaptive_max_pool2d_backward_kernel)
21
+
22
+ using adaptive_avg_pooling3d_fn = void(*)(Tensor& output, const Tensor& input, IntArrayRef output_size);
23
+ using adaptive_avg_pooling3d_backward_fn = void(*)(Tensor& grad_input, const Tensor& grad_output);
24
+ DECLARE_DISPATCH(adaptive_avg_pooling3d_fn, adaptive_avg_pool3d_kernel)
25
+ DECLARE_DISPATCH(adaptive_avg_pooling3d_backward_fn, adaptive_avg_pool3d_backward_kernel)
26
+
27
+ using adaptive_max_pooling3d_fn = void(*)(const Tensor& output, const Tensor& indices, const Tensor& input, IntArrayRef output_size);
28
+ using adaptive_max_pooling3d_backward_fn = void(*)(const Tensor& grad_input, const Tensor& grad_output, const Tensor& indices);
29
+ DECLARE_DISPATCH(adaptive_max_pooling3d_fn, adaptive_max_pool3d_kernel)
30
+ DECLARE_DISPATCH(adaptive_max_pooling3d_backward_fn, adaptive_max_pool3d_backward_kernel)
31
+
32
+ inline int64_t start_index(int64_t a, int64_t b, int64_t c) {
33
+ return (a / b) * c + ((a % b) * c) / b;
34
+ }
35
+
36
+ inline int64_t end_index(int64_t a, int64_t b, int64_t c) {
37
+ return 1 + ((a + 1) * c - 1) / b;
38
+ }
39
+
40
+ inline void adaptive_pool_empty_output_check(const Tensor& gradOutput_, const char* arg_name) {
41
+ int64_t ndim = gradOutput_.ndimension();
42
+ for (const auto i : c10::irange(1, ndim)) {
43
+ TORCH_CHECK(gradOutput_.size(i) > 0,
44
+ arg_name, "(): Expected grad_output to have non-zero size for non-batch dimensions, "
45
+ "but grad_output has sizes ", gradOutput_.sizes(), " with dimension ", i,
46
+ " being empty");
47
+ }
48
+ }
49
+
50
+ } // namespace at::native
51
+
52
+ #else
53
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
54
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/AmpKernels.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <ATen/core/ATen_fwd.h>
6
+
7
+ namespace at {
8
+ class Tensor;
9
+
10
+ namespace native {
11
+
12
+ using _amp_foreach_non_finite_check_and_unscale_cpu__fn = void (*)(
13
+ TensorList,
14
+ Tensor&,
15
+ const Tensor&);
16
+
17
+ using _amp_update_scale_cpu__fn = Tensor& (*)(
18
+ Tensor&,
19
+ Tensor&,
20
+ const Tensor&,
21
+ double,
22
+ double,
23
+ int64_t);
24
+
25
+ DECLARE_DISPATCH(_amp_foreach_non_finite_check_and_unscale_cpu__fn, _amp_foreach_non_finite_check_and_unscale_cpu_stub)
26
+ DECLARE_DISPATCH(_amp_update_scale_cpu__fn, _amp_update_scale_cpu_stub)
27
+
28
+ } // namespace native
29
+ } // namespace at
30
+
31
+ #else
32
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
33
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/BatchLinearAlgebra.h ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <optional>
5
+ #include <string_view>
6
+ #include <ATen/Config.h>
7
+ #include <ATen/native/DispatchStub.h>
8
+
9
+ // Forward declare TI
10
+ namespace at {
11
+ class Tensor;
12
+ struct TensorIterator;
13
+
14
+ namespace native {
15
+ enum class TransposeType;
16
+ }
17
+
18
+ }
19
+
20
+ namespace at::native {
21
+
22
+ enum class LapackLstsqDriverType : int64_t { Gels, Gelsd, Gelsy, Gelss};
23
+
24
+ #if AT_BUILD_WITH_LAPACK()
25
+ // Define per-batch functions to be used in the implementation of batched
26
+ // linear algebra operations
27
+
28
+ template <class scalar_t>
29
+ void lapackCholesky(char uplo, int n, scalar_t *a, int lda, int *info);
30
+
31
+ template <class scalar_t>
32
+ void lapackCholeskyInverse(char uplo, int n, scalar_t *a, int lda, int *info);
33
+
34
+ template <class scalar_t, class value_t=scalar_t>
35
+ void lapackEig(char jobvl, char jobvr, int n, scalar_t *a, int lda, scalar_t *w, scalar_t* vl, int ldvl, scalar_t *vr, int ldvr, scalar_t *work, int lwork, value_t *rwork, int *info);
36
+
37
+ template <class scalar_t>
38
+ void lapackGeqrf(int m, int n, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
39
+
40
+ template <class scalar_t>
41
+ void lapackOrgqr(int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *work, int lwork, int *info);
42
+
43
+ template <class scalar_t>
44
+ void lapackOrmqr(char side, char trans, int m, int n, int k, scalar_t *a, int lda, scalar_t *tau, scalar_t *c, int ldc, scalar_t *work, int lwork, int *info);
45
+
46
+ template <class scalar_t, class value_t = scalar_t>
47
+ void lapackSyevd(char jobz, char uplo, int n, scalar_t* a, int lda, value_t* w, scalar_t* work, int lwork, value_t* rwork, int lrwork, int* iwork, int liwork, int* info);
48
+
49
+ template <class scalar_t>
50
+ void lapackGels(char trans, int m, int n, int nrhs,
51
+ scalar_t *a, int lda, scalar_t *b, int ldb,
52
+ scalar_t *work, int lwork, int *info);
53
+
54
+ template <class scalar_t, class value_t = scalar_t>
55
+ void lapackGelsd(int m, int n, int nrhs,
56
+ scalar_t *a, int lda, scalar_t *b, int ldb,
57
+ value_t *s, value_t rcond, int *rank,
58
+ scalar_t* work, int lwork,
59
+ value_t *rwork, int* iwork, int *info);
60
+
61
+ template <class scalar_t, class value_t = scalar_t>
62
+ void lapackGelsy(int m, int n, int nrhs,
63
+ scalar_t *a, int lda, scalar_t *b, int ldb,
64
+ int *jpvt, value_t rcond, int *rank,
65
+ scalar_t *work, int lwork, value_t* rwork, int *info);
66
+
67
+ template <class scalar_t, class value_t = scalar_t>
68
+ void lapackGelss(int m, int n, int nrhs,
69
+ scalar_t *a, int lda, scalar_t *b, int ldb,
70
+ value_t *s, value_t rcond, int *rank,
71
+ scalar_t *work, int lwork,
72
+ value_t *rwork, int *info);
73
+
74
+ template <LapackLstsqDriverType, class scalar_t, class value_t = scalar_t>
75
+ struct lapackLstsq_impl;
76
+
77
+ template <class scalar_t, class value_t>
78
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gels, scalar_t, value_t> {
79
+ static void call(
80
+ char trans, int m, int n, int nrhs,
81
+ scalar_t *a, int lda, scalar_t *b, int ldb,
82
+ scalar_t *work, int lwork, int *info, // Gels flavor
83
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
84
+ value_t *s, // Gelss flavor
85
+ int *iwork // Gelsd flavor
86
+ ) {
87
+ lapackGels<scalar_t>(
88
+ trans, m, n, nrhs,
89
+ a, lda, b, ldb,
90
+ work, lwork, info);
91
+ }
92
+ };
93
+
94
+ template <class scalar_t, class value_t>
95
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelsy, scalar_t, value_t> {
96
+ static void call(
97
+ char trans, int m, int n, int nrhs,
98
+ scalar_t *a, int lda, scalar_t *b, int ldb,
99
+ scalar_t *work, int lwork, int *info, // Gels flavor
100
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
101
+ value_t *s, // Gelss flavor
102
+ int *iwork // Gelsd flavor
103
+ ) {
104
+ lapackGelsy<scalar_t, value_t>(
105
+ m, n, nrhs,
106
+ a, lda, b, ldb,
107
+ jpvt, rcond, rank,
108
+ work, lwork, rwork, info);
109
+ }
110
+ };
111
+
112
+ template <class scalar_t, class value_t>
113
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelsd, scalar_t, value_t> {
114
+ static void call(
115
+ char trans, int m, int n, int nrhs,
116
+ scalar_t *a, int lda, scalar_t *b, int ldb,
117
+ scalar_t *work, int lwork, int *info, // Gels flavor
118
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
119
+ value_t *s, // Gelss flavor
120
+ int *iwork // Gelsd flavor
121
+ ) {
122
+ lapackGelsd<scalar_t, value_t>(
123
+ m, n, nrhs,
124
+ a, lda, b, ldb,
125
+ s, rcond, rank,
126
+ work, lwork,
127
+ rwork, iwork, info);
128
+ }
129
+ };
130
+
131
+ template <class scalar_t, class value_t>
132
+ struct lapackLstsq_impl<LapackLstsqDriverType::Gelss, scalar_t, value_t> {
133
+ static void call(
134
+ char trans, int m, int n, int nrhs,
135
+ scalar_t *a, int lda, scalar_t *b, int ldb,
136
+ scalar_t *work, int lwork, int *info, // Gels flavor
137
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
138
+ value_t *s, // Gelss flavor
139
+ int *iwork // Gelsd flavor
140
+ ) {
141
+ lapackGelss<scalar_t, value_t>(
142
+ m, n, nrhs,
143
+ a, lda, b, ldb,
144
+ s, rcond, rank,
145
+ work, lwork,
146
+ rwork, info);
147
+ }
148
+ };
149
+
150
+ template <LapackLstsqDriverType driver_type, class scalar_t, class value_t = scalar_t>
151
+ void lapackLstsq(
152
+ char trans, int m, int n, int nrhs,
153
+ scalar_t *a, int lda, scalar_t *b, int ldb,
154
+ scalar_t *work, int lwork, int *info, // Gels flavor
155
+ int *jpvt, value_t rcond, int *rank, value_t* rwork, // Gelsy flavor
156
+ value_t *s, // Gelss flavor
157
+ int *iwork // Gelsd flavor
158
+ ) {
159
+ lapackLstsq_impl<driver_type, scalar_t, value_t>::call(
160
+ trans, m, n, nrhs,
161
+ a, lda, b, ldb,
162
+ work, lwork, info,
163
+ jpvt, rcond, rank, rwork,
164
+ s,
165
+ iwork);
166
+ }
167
+
168
+ template <class scalar_t>
169
+ void lapackLuSolve(char trans, int n, int nrhs, scalar_t *a, int lda, int *ipiv, scalar_t *b, int ldb, int *info);
170
+
171
+ template <class scalar_t>
172
+ void lapackLu(int m, int n, scalar_t *a, int lda, int *ipiv, int *info);
173
+
174
+ template <class scalar_t>
175
+ void lapackLdlHermitian(
176
+ char uplo,
177
+ int n,
178
+ scalar_t* a,
179
+ int lda,
180
+ int* ipiv,
181
+ scalar_t* work,
182
+ int lwork,
183
+ int* info);
184
+
185
+ template <class scalar_t>
186
+ void lapackLdlSymmetric(
187
+ char uplo,
188
+ int n,
189
+ scalar_t* a,
190
+ int lda,
191
+ int* ipiv,
192
+ scalar_t* work,
193
+ int lwork,
194
+ int* info);
195
+
196
+ template <class scalar_t>
197
+ void lapackLdlSolveHermitian(
198
+ char uplo,
199
+ int n,
200
+ int nrhs,
201
+ scalar_t* a,
202
+ int lda,
203
+ int* ipiv,
204
+ scalar_t* b,
205
+ int ldb,
206
+ int* info);
207
+
208
+ template <class scalar_t>
209
+ void lapackLdlSolveSymmetric(
210
+ char uplo,
211
+ int n,
212
+ int nrhs,
213
+ scalar_t* a,
214
+ int lda,
215
+ int* ipiv,
216
+ scalar_t* b,
217
+ int ldb,
218
+ int* info);
219
+
220
+ template<class scalar_t, class value_t=scalar_t>
221
+ void lapackSvd(char jobz, int m, int n, scalar_t *a, int lda, value_t *s, scalar_t *u, int ldu, scalar_t *vt, int ldvt, scalar_t *work, int lwork, value_t *rwork, int *iwork, int *info);
222
+ #endif
223
+
224
+ #if AT_BUILD_WITH_BLAS()
225
+ template <class scalar_t>
226
+ void blasTriangularSolve(char side, char uplo, char trans, char diag, int n, int nrhs, scalar_t* a, int lda, scalar_t* b, int ldb);
227
+ #endif
228
+
229
+ using cholesky_fn = void (*)(const Tensor& /*input*/, const Tensor& /*info*/, bool /*upper*/);
230
+ DECLARE_DISPATCH(cholesky_fn, cholesky_stub)
231
+
232
+ using cholesky_inverse_fn = Tensor& (*)(Tensor& /*result*/, Tensor& /*infos*/, bool /*upper*/);
233
+
234
+ DECLARE_DISPATCH(cholesky_inverse_fn, cholesky_inverse_stub)
235
+
236
+ using linalg_eig_fn = void (*)(Tensor& /*eigenvalues*/, Tensor& /*eigenvectors*/, Tensor& /*infos*/, const Tensor& /*input*/, bool /*compute_eigenvectors*/);
237
+
238
+ DECLARE_DISPATCH(linalg_eig_fn, linalg_eig_stub)
239
+
240
+ // Converts LAPACK's real-valued eigenvector encoding to complex eigenvectors
241
+ TORCH_API void linalg_eig_make_complex_eigenvectors(
242
+ const Tensor& complex_vectors,
243
+ const Tensor& complex_values,
244
+ const Tensor& real_vectors);
245
+
246
+ DECLARE_DISPATCH(
247
+ void(*)(const Tensor&, const Tensor&, const Tensor&),
248
+ linalg_eig_make_complex_eigenvectors_stub)
249
+
250
+
251
+ using geqrf_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/);
252
+ DECLARE_DISPATCH(geqrf_fn, geqrf_stub)
253
+
254
+ using orgqr_fn = Tensor& (*)(Tensor& /*result*/, const Tensor& /*tau*/);
255
+ DECLARE_DISPATCH(orgqr_fn, orgqr_stub)
256
+
257
+ using ormqr_fn = void (*)(const Tensor& /*input*/, const Tensor& /*tau*/, const Tensor& /*other*/, bool /*left*/, bool /*transpose*/);
258
+ DECLARE_DISPATCH(ormqr_fn, ormqr_stub)
259
+
260
+ using linalg_eigh_fn = void (*)(
261
+ const Tensor& /*eigenvalues*/,
262
+ const Tensor& /*eigenvectors*/,
263
+ const Tensor& /*infos*/,
264
+ bool /*upper*/,
265
+ bool /*compute_eigenvectors*/);
266
+ DECLARE_DISPATCH(linalg_eigh_fn, linalg_eigh_stub)
267
+
268
+ using lstsq_fn = void (*)(
269
+ const Tensor& /*a*/,
270
+ Tensor& /*b*/,
271
+ Tensor& /*rank*/,
272
+ Tensor& /*singular_values*/,
273
+ Tensor& /*infos*/,
274
+ double /*rcond*/,
275
+ std::string /*driver_name*/);
276
+ DECLARE_DISPATCH(lstsq_fn, lstsq_stub)
277
+
278
+ using triangular_solve_fn = void (*)(
279
+ const Tensor& /*A*/,
280
+ const Tensor& /*B*/,
281
+ bool /*left*/,
282
+ bool /*upper*/,
283
+ TransposeType /*transpose*/,
284
+ bool /*unitriangular*/);
285
+ DECLARE_DISPATCH(triangular_solve_fn, triangular_solve_stub)
286
+
287
+ using lu_factor_fn = void (*)(
288
+ const Tensor& /*input*/,
289
+ const Tensor& /*pivots*/,
290
+ const Tensor& /*infos*/,
291
+ bool /*compute_pivots*/);
292
+ DECLARE_DISPATCH(lu_factor_fn, lu_factor_stub)
293
+
294
+ using unpack_pivots_fn = void(*)(
295
+ TensorIterator& iter,
296
+ const int64_t dim_size,
297
+ const int64_t max_pivot);
298
+ DECLARE_DISPATCH(unpack_pivots_fn, unpack_pivots_stub)
299
+
300
+ using lu_solve_fn = void (*)(
301
+ const Tensor& /*LU*/,
302
+ const Tensor& /*pivots*/,
303
+ const Tensor& /*B*/,
304
+ TransposeType /*trans*/);
305
+ DECLARE_DISPATCH(lu_solve_fn, lu_solve_stub)
306
+
307
+ using ldl_factor_fn = void (*)(
308
+ const Tensor& /*LD*/,
309
+ const Tensor& /*pivots*/,
310
+ const Tensor& /*info*/,
311
+ bool /*upper*/,
312
+ bool /*hermitian*/);
313
+ DECLARE_DISPATCH(ldl_factor_fn, ldl_factor_stub)
314
+
315
+ using svd_fn = void (*)(
316
+ const Tensor& /*A*/,
317
+ const bool /*full_matrices*/,
318
+ const bool /*compute_uv*/,
319
+ const std::optional<std::string_view>& /*driver*/,
320
+ const Tensor& /*U*/,
321
+ const Tensor& /*S*/,
322
+ const Tensor& /*Vh*/,
323
+ const Tensor& /*info*/);
324
+ DECLARE_DISPATCH(svd_fn, svd_stub)
325
+
326
+ using ldl_solve_fn = void (*)(
327
+ const Tensor& /*LD*/,
328
+ const Tensor& /*pivots*/,
329
+ const Tensor& /*result*/,
330
+ bool /*upper*/,
331
+ bool /*hermitian*/);
332
+ DECLARE_DISPATCH(ldl_solve_fn, ldl_solve_stub)
333
+ } // namespace at::native
334
+
335
+ #else
336
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
337
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/TensorBase.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <c10/core/Scalar.h>
7
+ #include <c10/util/TypeSafeSignMath.h>
8
+
9
+
10
+ namespace at {
11
+ struct TensorIterator;
12
+ struct TensorIteratorBase;
13
+ }
14
+
15
+ namespace at::native {
16
+
17
+ inline void alpha_check(const ScalarType dtype, const Scalar& alpha) {
18
+ TORCH_CHECK(! alpha.isBoolean() || dtype == ScalarType::Bool,
19
+ "Boolean alpha only supported for Boolean results.");
20
+ TORCH_CHECK(isFloatingType(dtype) || isComplexType(dtype)
21
+ || alpha.isIntegral(true),
22
+ "For integral input tensors, argument alpha must not be a floating point number.");
23
+ TORCH_CHECK(isComplexType(dtype) || !alpha.isComplex(),
24
+ "For non-complex input tensors, argument alpha must not be a complex number.")
25
+ }
26
+
27
+ // Basic checking for all sub functions.
28
+ inline void sub_check(const TensorBase& self, const TensorBase& other) {
29
+ TORCH_CHECK(self.scalar_type() != kBool || other.scalar_type() != kBool,
30
+ "Subtraction, the `-` operator, with two bool tensors is not supported. "
31
+ "Use the `^` or `logical_xor()` operator instead.")
32
+ TORCH_CHECK(self.scalar_type() != kBool && other.scalar_type() != kBool,
33
+ "Subtraction, the `-` operator, with a bool tensor is not supported. "
34
+ "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
35
+ }
36
+
37
+ inline void sub_check(const TensorBase& self, const Scalar& scalar) {
38
+ TORCH_CHECK(self.scalar_type() != kBool || !scalar.isBoolean(),
39
+ "Subtraction, the `-` operator, with two bool tensors is not supported. "
40
+ "Use the `^` or `logical_xor()` operator instead.")
41
+ TORCH_CHECK(self.scalar_type() != kBool && !scalar.isBoolean(),
42
+ "Subtraction, the `-` operator, with a bool tensor is not supported. "
43
+ "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
44
+ }
45
+
46
+ using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
47
+ using structured_binary_fn_double = void(*)(TensorIteratorBase&, double);
48
+ using structured_binary_fn = void(*)(TensorIteratorBase&);
49
+
50
+ using binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
51
+ using binary_fn_double = void(*)(TensorIterator&, double);
52
+ using binary_fn = void(*)(TensorIterator&);
53
+ using binary_clamp_fn_alpha =
54
+ void(*)(TensorIterator&, const Scalar& alpha, const Scalar& min_val, const Scalar& max_val);
55
+
56
+ // NB: codegenned
57
+ DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub)
58
+
59
+ DECLARE_DISPATCH(binary_clamp_fn_alpha, add_clamp_stub)
60
+ DECLARE_DISPATCH(structured_binary_fn_alpha, sub_stub)
61
+ DECLARE_DISPATCH(structured_binary_fn, mul_stub)
62
+ DECLARE_DISPATCH(structured_binary_fn, div_true_stub)
63
+ DECLARE_DISPATCH(structured_binary_fn, div_floor_stub)
64
+ DECLARE_DISPATCH(structured_binary_fn, div_trunc_stub)
65
+ DECLARE_DISPATCH(structured_binary_fn, atan2_stub)
66
+ DECLARE_DISPATCH(structured_binary_fn, remainder_stub)
67
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_and_stub)
68
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_or_stub)
69
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_xor_stub)
70
+ DECLARE_DISPATCH(structured_binary_fn, lshift_stub)
71
+ DECLARE_DISPATCH(structured_binary_fn, rshift_stub)
72
+ DECLARE_DISPATCH(binary_fn, logical_xor_stub)
73
+ DECLARE_DISPATCH(binary_fn, logical_and_stub)
74
+ DECLARE_DISPATCH(binary_fn, logical_or_stub)
75
+ DECLARE_DISPATCH(structured_binary_fn, lt_stub)
76
+ DECLARE_DISPATCH(structured_binary_fn, le_stub)
77
+ DECLARE_DISPATCH(structured_binary_fn, gt_stub)
78
+ DECLARE_DISPATCH(structured_binary_fn, ge_stub)
79
+ DECLARE_DISPATCH(structured_binary_fn, eq_stub)
80
+ DECLARE_DISPATCH(structured_binary_fn, ne_stub)
81
+ DECLARE_DISPATCH(binary_fn, max_elementwise_stub)
82
+ DECLARE_DISPATCH(binary_fn, min_elementwise_stub)
83
+ DECLARE_DISPATCH(structured_binary_fn, maximum_stub)
84
+ DECLARE_DISPATCH(structured_binary_fn, minimum_stub)
85
+ DECLARE_DISPATCH(structured_binary_fn, fmax_stub)
86
+ DECLARE_DISPATCH(structured_binary_fn, fmin_stub)
87
+ DECLARE_DISPATCH(structured_binary_fn_double, smooth_l1_stub)
88
+ DECLARE_DISPATCH(binary_fn_double, huber_stub)
89
+ DECLARE_DISPATCH(structured_binary_fn, sigmoid_backward_stub)
90
+ DECLARE_DISPATCH(binary_fn_alpha, logit_backward_stub)
91
+ DECLARE_DISPATCH(structured_binary_fn, tanh_backward_stub)
92
+ DECLARE_DISPATCH(structured_binary_fn, mse_stub)
93
+ DECLARE_DISPATCH(structured_binary_fn, fmod_stub)
94
+ DECLARE_DISPATCH(structured_binary_fn, logaddexp_stub)
95
+ DECLARE_DISPATCH(structured_binary_fn, logaddexp2_stub)
96
+ DECLARE_DISPATCH(structured_binary_fn, gcd_stub)
97
+ DECLARE_DISPATCH(structured_binary_fn, lcm_stub)
98
+ DECLARE_DISPATCH(structured_binary_fn, hypot_stub)
99
+ DECLARE_DISPATCH(structured_binary_fn, igamma_stub)
100
+ DECLARE_DISPATCH(structured_binary_fn, igammac_stub)
101
+ DECLARE_DISPATCH(structured_binary_fn, nextafter_stub)
102
+ DECLARE_DISPATCH(structured_binary_fn, heaviside_stub)
103
+ DECLARE_DISPATCH(structured_binary_fn, copysign_stub)
104
+ DECLARE_DISPATCH(structured_binary_fn, xlogy_stub)
105
+ DECLARE_DISPATCH(structured_binary_fn, xlog1py_stub)
106
+ DECLARE_DISPATCH(structured_binary_fn, zeta_stub)
107
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_t_stub)
108
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_u_stub)
109
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_v_stub)
110
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_w_stub)
111
+ DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_h_stub)
112
+ DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_he_stub)
113
+ DECLARE_DISPATCH(structured_binary_fn, laguerre_polynomial_l_stub)
114
+ DECLARE_DISPATCH(structured_binary_fn, legendre_polynomial_p_stub)
115
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_t_stub)
116
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_u_stub)
117
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_v_stub)
118
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_w_stub)
119
+
120
+ } // namespace at::native
121
+
122
+ #else
123
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
124
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/BucketizationUtils.h ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/Tensor.h>
5
+ #include <ATen/native/TypeProperties.h>
6
+ #include <ATen/ScalarOps.h>
7
+
8
+ #ifndef AT_PER_OPERATOR_HEADERS
9
+ #include <ATen/NativeFunctions.h>
10
+ #else
11
+ #include <ATen/ops/result_type.h>
12
+ #endif
13
+
14
+ namespace at::native {
15
+
16
+ // original values given by raw_*. If an original value is not contiguous, will make a contiguous copy to
17
+ // the corresponding trimmed_* value. Additionally, if the dtypes of the boundary and input tensor do not
18
+ // match, will change them to be a common super type so comparisons are done between the same types.
19
+ // For any trimmed_* tensor, if its outgoing value matches what it was incoming (typically null), then the
20
+ // corresponding raw_* version should be used since it was already contiguous of the right type.
21
+ inline void searchsorted_maybe_trim_input_tensors(
22
+ Tensor& trimmed_input,
23
+ Tensor& trimmed_boundaries,
24
+ Tensor& trimmed_sorter,
25
+ const Tensor& raw_input,
26
+ const Tensor& raw_boundaries,
27
+ const Tensor& raw_sorter) {
28
+ bool in_is_contiguous = raw_input.is_contiguous();
29
+ bool bd_is_contiguous = raw_boundaries.is_contiguous();
30
+ bool sort_is_contiguous = raw_sorter.is_contiguous();
31
+
32
+ if (!in_is_contiguous) {
33
+ TORCH_WARN_ONCE("torch.searchsorted(): input value tensor is non-contiguous, this will lower the performance due "
34
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous input value "
35
+ "tensor if possible. This message will only appear once per program.");
36
+ trimmed_input = raw_input.contiguous();
37
+ }
38
+ if (!bd_is_contiguous) {
39
+ TORCH_WARN_ONCE("torch.searchsorted(): boundary tensor is non-contiguous, this will lower the performance due "
40
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous boundary "
41
+ "tensor if possible. This message will only appear once per program.");
42
+ trimmed_boundaries = raw_boundaries.contiguous();
43
+ }
44
+ if (!sort_is_contiguous) {
45
+ TORCH_WARN_ONCE("torch.searchsorted(): sorter tensor is non-contiguous, this will lower the performance due "
46
+ "to extra data copy when converting non-contiguous tensor to contiguous, please use contiguous sorter "
47
+ "tensor if possible. This message will only appear once per program.");
48
+ trimmed_sorter = raw_sorter.contiguous();
49
+ }
50
+ if (raw_input.dtype() != raw_boundaries.dtype()) {
51
+ at::native::ResultTypeState state = {};
52
+ state = at::native::update_result_type_state(raw_boundaries, state);
53
+ state = at::native::update_result_type_state(raw_input, state);
54
+ ScalarType common_stype = at::native::result_type(state);
55
+
56
+ TORCH_INTERNAL_ASSERT(common_stype != ScalarType::Undefined);
57
+ if (common_stype != raw_input.scalar_type()) {
58
+ trimmed_input = in_is_contiguous ? raw_input.to(common_stype) : trimmed_input.to(common_stype);
59
+ }
60
+ if (common_stype != raw_boundaries.scalar_type()) {
61
+ trimmed_boundaries = bd_is_contiguous ? raw_boundaries.to(common_stype) : trimmed_boundaries.to(common_stype);
62
+ }
63
+ }
64
+ }
65
+
66
+ /* unused but needed for internal jagged tensor class */
67
+ inline void searchsorted_maybe_trim_input_tensors(
68
+ Tensor& trimmed_input,
69
+ Tensor& trimmed_boundaries,
70
+ const Tensor& raw_input,
71
+ const Tensor& raw_boundaries) {
72
+ Tensor trimmed_sorter;
73
+ Tensor raw_sorter;
74
+ searchsorted_maybe_trim_input_tensors(
75
+ trimmed_input,
76
+ trimmed_boundaries,
77
+ trimmed_sorter,
78
+ raw_input,
79
+ raw_boundaries,
80
+ raw_sorter);
81
+ }
82
+
83
+ inline bool searchsorted_dims_matched_before_last_dim(const Tensor& boundaries, const Tensor& input) {
84
+ if (boundaries.dim() != input.dim()) {
85
+ return false;
86
+ }
87
+ const auto& dims_bd = boundaries.sizes();
88
+ const auto& dims_in = input.sizes();
89
+ for (int64_t dim = 0; dim + 1 < boundaries.dim(); ++dim) {
90
+ if (dims_bd[dim] != dims_in[dim]) {
91
+ return false;
92
+ }
93
+ }
94
+ return true;
95
+ }
96
+
97
+ inline Tensor searchsorted_scalar_tensor(const Scalar& scalar, const c10::Device& device) {
98
+ auto tensor = c10::scalar_to_tensor(scalar, device);
99
+ // This is to adopt the scalar promotion rules defined in native/TypeProperties.h
100
+ // So we have the same type promotion rules as binary operations.
101
+ tensor.unsafeGetTensorImpl()->set_wrapped_number(true);
102
+ return tensor;
103
+ }
104
+
105
+ inline void searchsorted_pre_check(
106
+ const Tensor& boundaries,
107
+ const Tensor& input,
108
+ const Tensor& output,
109
+ const bool out_int32,
110
+ const bool right,
111
+ const std::optional<std::string_view> side_opt,
112
+ const Tensor& sorter) {
113
+ if (side_opt) {
114
+ const std::string_view side = *side_opt;
115
+ TORCH_CHECK(side == "left" || side == "right", "torch.searchsorted(): side can only be 'left' or 'right' but ",
116
+ "got ", side);
117
+
118
+ // assume the user has not explicitly set (right=False, side="right")
119
+ TORCH_CHECK(!right || side == "right", "torch.searchsorted(): side and right can't be set to opposites, got side "
120
+ "of ", side, " while right was True");
121
+ }
122
+
123
+ TORCH_CHECK(boundaries.device() == input.device(), "torch.searchsorted(): boundaries and input value tensors ",
124
+ "should have same device type, but got boundaries tensor device type ", boundaries.device(), " and input value ",
125
+ "tensor device type ", input.device());
126
+
127
+ if (sorter.defined()) {
128
+ TORCH_CHECK(sorter.device() == boundaries.device(), "torch.searchsorted(): sorter and boundary tensors should ",
129
+ "have same device type, but got sorter tensor device type ", sorter.device(), " and input value tensor ",
130
+ "device type ", boundaries.device());
131
+
132
+ TORCH_CHECK(sorter.sizes() == boundaries.sizes(), "torch.searchsorted(): boundary and sorter must have the same "
133
+ "size, but got boundary tensor ", boundaries.sizes(), "and got sorter tensor ", sorter.sizes());
134
+
135
+ TORCH_CHECK(sorter.scalar_type() == ScalarType::Long, "torch.searchsorted(): sorter must be a tensor of long ",
136
+ "dtype but got dtype ", sorter.scalar_type());
137
+
138
+ if (sorter.numel() > 0) {
139
+ auto minmax = sorter.aminmax();
140
+ int64_t vmin = std::get<0>(minmax).item().toLong();
141
+ int64_t vmax = std::get<1>(minmax).item().toLong();
142
+ TORCH_CHECK(vmin >= 0 && vmax < sorter.sizes().back(), "torch.searchsorted(): sorter index out of range");
143
+ }
144
+ }
145
+
146
+ TORCH_CHECK(input.dim() > 0 || (input.dim() == 0 && input.numel() == 1 && boundaries.dim() == 1),
147
+ "torch.searchsorted(): input value can be a scalar only when boundaries tensor dimension is 1, but we got ",
148
+ "boundaries tensor dim(", boundaries.dim(), ") and input value's dim(", input.dim(), ") numel(",
149
+ input.numel(), ")");
150
+
151
+ TORCH_CHECK(boundaries.dim() != 0, "torch.searchsorted(): boundaries tensor should have positive dimension, but ",
152
+ "got 0 dimension");
153
+
154
+ TORCH_CHECK(boundaries.dim() == 1 || searchsorted_dims_matched_before_last_dim(boundaries, input),
155
+ "torch.searchsorted(): boundaries tensor should be 1 dimension or the first N-1 dimensions of boundaries tensor ",
156
+ "and input value tensor must match, but we got boundaries tensor ", boundaries.sizes(), " and input value tensor ",
157
+ input.sizes());
158
+
159
+ ScalarType output_dtype = output.scalar_type();
160
+ TORCH_CHECK(
161
+ (output_dtype == ScalarType::Long && !out_int32) ||
162
+ (output_dtype == ScalarType::Int && out_int32),
163
+ "torch.searchsorted(): output tensor's dtype is wrong, it can only be Int(int32) or Long(int64) depending on ",
164
+ "whether out_int32 flag is True, but we got output tensor's dtype ", output_dtype,
165
+ " and out_int32 flag is ", (out_int32 ? "True" : "False"));
166
+
167
+ if (out_int32) {
168
+ TORCH_CHECK(boundaries.sizes().back() < INT_MAX,
169
+ "torch.searchsorted(): the size of boundaries' last dimension should be less than ", INT_MAX, ", but we got ",
170
+ boundaries.sizes().back());
171
+ }
172
+ }
173
+
174
+ } // namespace at::native
175
+
176
+ #else
177
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
178
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/ATen/native/CPUBlas.h ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/OpMathType.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <ATen/native/TransposeType.h>
7
+ #include <c10/util/complex.h>
8
+ #include <c10/core/ScalarType.h>
9
+ #include <c10/core/Scalar.h>
10
+
11
+
12
+ namespace at::native::cpublas {
13
+
14
+ namespace internal {
15
+ void normalize_last_dims(
16
+ TransposeType transa, TransposeType transb,
17
+ int64_t m, int64_t n, int64_t k,
18
+ int64_t *lda, int64_t *ldb, int64_t *ldc);
19
+ } // namespace internal
20
+
21
+ using gemm_fn = void(*)(
22
+ at::ScalarType type,
23
+ TransposeType transa, TransposeType transb,
24
+ int64_t m, int64_t n, int64_t k,
25
+ const Scalar& alpha,
26
+ const void *a, int64_t lda,
27
+ const void *b, int64_t ldb,
28
+ const Scalar& beta,
29
+ void *c, int64_t ldc);
30
+
31
+ DECLARE_DISPATCH(gemm_fn, gemm_stub)
32
+
33
+ using gemm_no_downcast_fn = void(*)(
34
+ at::ScalarType type,
35
+ TransposeType transa, TransposeType transb,
36
+ int64_t m, int64_t n, int64_t k,
37
+ const Scalar& alpha,
38
+ const void *a, int64_t lda,
39
+ const void *b, int64_t ldb,
40
+ const Scalar& beta,
41
+ void *c, int64_t ldc);
42
+
43
+ DECLARE_DISPATCH(gemm_no_downcast_fn, gemm_no_downcast_stub)
44
+
45
+ template <typename scalar_t>
46
+ void gemm(
47
+ TransposeType transa, TransposeType transb,
48
+ int64_t m, int64_t n, int64_t k,
49
+ at::opmath_type<scalar_t> alpha,
50
+ const scalar_t *a, int64_t lda,
51
+ const scalar_t *b, int64_t ldb,
52
+ at::opmath_type<scalar_t> beta,
53
+ scalar_t *c, int64_t ldc) {
54
+ internal::normalize_last_dims(transa, transb, m, n, k, &lda, &ldb, &ldc);
55
+ gemm_stub(
56
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
57
+ transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc);
58
+ }
59
+
60
+ void gemm(
61
+ TransposeType transa, TransposeType transb,
62
+ int64_t m, int64_t n, int64_t k,
63
+ double alpha,
64
+ const double *a, int64_t lda,
65
+ const double *b, int64_t ldb,
66
+ double beta,
67
+ double *c, int64_t ldc);
68
+
69
+ void gemm(
70
+ TransposeType transa, TransposeType transb,
71
+ int64_t m, int64_t n, int64_t k,
72
+ float alpha,
73
+ const float *a, int64_t lda,
74
+ const float *b, int64_t ldb,
75
+ float beta,
76
+ float *c, int64_t ldc);
77
+
78
+ void gemm(
79
+ TransposeType transa, TransposeType transb,
80
+ int64_t m, int64_t n, int64_t k,
81
+ float alpha,
82
+ const at::BFloat16 *a, int64_t lda,
83
+ const at::BFloat16 *b, int64_t ldb,
84
+ float beta,
85
+ at::BFloat16 *c, int64_t ldc);
86
+
87
+ void gemm(
88
+ TransposeType transa, TransposeType transb,
89
+ int64_t m, int64_t n, int64_t k,
90
+ const float alpha,
91
+ const at::BFloat16 *a, int64_t lda,
92
+ const at::BFloat16 *b, int64_t ldb,
93
+ const float beta,
94
+ float *c, int64_t ldc);
95
+
96
+ void gemm(
97
+ TransposeType transa, TransposeType transb,
98
+ int64_t m, int64_t n, int64_t k,
99
+ float alpha,
100
+ const at::Half *a, int64_t lda,
101
+ const at::Half *b, int64_t ldb,
102
+ float beta,
103
+ at::Half *c, int64_t ldc);
104
+
105
+ void gemm(
106
+ TransposeType transa, TransposeType transb,
107
+ int64_t m, int64_t n, int64_t k,
108
+ const float alpha,
109
+ const at::Half *a, int64_t lda,
110
+ const at::Half *b, int64_t ldb,
111
+ const float beta,
112
+ float *c, int64_t ldc);
113
+
114
+ void gemm(
115
+ TransposeType transa, TransposeType transb,
116
+ int64_t m, int64_t n, int64_t k,
117
+ c10::complex<double> alpha,
118
+ const c10::complex<double> *a, int64_t lda,
119
+ const c10::complex<double> *b, int64_t ldb,
120
+ c10::complex<double> beta,
121
+ c10::complex<double> *c, int64_t ldc);
122
+
123
+ void gemm(
124
+ TransposeType transa, TransposeType transb,
125
+ int64_t m, int64_t n, int64_t k,
126
+ c10::complex<float> alpha,
127
+ const c10::complex<float> *a, int64_t lda,
128
+ const c10::complex<float> *b, int64_t ldb,
129
+ c10::complex<float> beta,
130
+ c10::complex<float> *c, int64_t ldc);
131
+
132
+ void gemm(
133
+ TransposeType transa, TransposeType transb,
134
+ int64_t m, int64_t n, int64_t k,
135
+ int64_t alpha,
136
+ const int64_t *a, int64_t lda,
137
+ const int64_t *b, int64_t ldb,
138
+ int64_t beta,
139
+ int64_t *c, int64_t ldc);
140
+
141
+ template <typename scalar_t>
142
+ void gemm_batched(
143
+ TransposeType transa, TransposeType transb,
144
+ int64_t batch_size, int64_t m, int64_t n, int64_t k,
145
+ scalar_t alpha,
146
+ const scalar_t * const *a, int64_t lda,
147
+ const scalar_t * const *b, int64_t ldb,
148
+ const scalar_t beta,
149
+ scalar_t * const *c, int64_t ldc);
150
+
151
+ template <typename scalar_t>
152
+ void gemm_batched_with_stride(
153
+ TransposeType transa, TransposeType transb,
154
+ int64_t batch_size, int64_t m, int64_t n, int64_t k,
155
+ scalar_t alpha,
156
+ const scalar_t *a, int64_t lda, int64_t batch_stride_a,
157
+ const scalar_t *b, int64_t ldb, int64_t batch_stride_b,
158
+ scalar_t beta,
159
+ scalar_t *c, int64_t ldc, int64_t batch_stride_c);
160
+
161
+ using axpy_fn = void(*)(at::ScalarType type, int64_t n, const Scalar& a, const void *x, int64_t incx, void *y, int64_t incy);
162
+
163
+ DECLARE_DISPATCH(axpy_fn, axpy_stub)
164
+
165
+ template<typename scalar_t>
166
+ void axpy(int64_t n, scalar_t a, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy){
167
+ if(n == 1)
168
+ {
169
+ incx = 1;
170
+ incy = 1;
171
+ }
172
+ axpy_stub(
173
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
174
+ n, a, x, incx, y, incy);
175
+ }
176
+
177
+ void axpy(int64_t n, double a, const double *x, int64_t incx, double *y, int64_t incy);
178
+ void axpy(int64_t n, float a, const float *x, int64_t incx, float *y, int64_t incy);
179
+ void axpy(int64_t n, c10::complex<double> a, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
180
+ void axpy(int64_t n, c10::complex<float> a, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
181
+
182
+ using copy_fn = void(*)(at::ScalarType type, int64_t n, const void *x, int64_t incx, void *y, int64_t incy);
183
+
184
+ DECLARE_DISPATCH(copy_fn, copy_stub)
185
+
186
+ template<typename scalar_t>
187
+ void copy(int64_t n, const scalar_t *x, int64_t incx, scalar_t *y, int64_t incy) {
188
+ if(n == 1)
189
+ {
190
+ incx = 1;
191
+ incy = 1;
192
+ }
193
+ copy_stub(
194
+ kCPU, c10::CppTypeToScalarType<scalar_t>::value,
195
+ n, x, incx, y, incy);
196
+ }
197
+
198
+ void copy(int64_t n, const double *x, int64_t incx, double *y, int64_t incy);
199
+ void copy(int64_t n, const float *x, int64_t incx, float *y, int64_t incy);
200
+ void copy(int64_t n, const c10::complex<double> *x, int64_t incx, c10::complex<double> *y, int64_t incy);
201
+ void copy(int64_t n, const c10::complex<float> *x, int64_t incx, c10::complex<float> *y, int64_t incy);
202
+
203
+ // Batch-reduce GEMM
204
+ // Operates by the following formula:
205
+ // C = SUM(A[i] x B[i]) + C if add_C is true, i = 0 to batch size
206
+ // A Base pointer to a tensor A.
207
+ // B Base pointer to a tensor B.
208
+ // C Pointer to a tensor C (accumulation buffer).
209
+ // Note only batch size 1 is used currently
210
+
211
+ // Define macros for available brgemm APIs
212
+ // so that callers can determine which APIs are available
213
+ #define CPUBLAS_BRGEMM_F16F16F32 // half * half -> float
214
+ #define CPUBLAS_BRGEMM_BF16BF16F32 // bfloat16 * bfloat16 -> float
215
+ #define CPUBLAS_BRGEMM_F32F32F32 // float * float -> float
216
+ #define CPUBLAS_BRGEMM_U8U8I32 // unsigned char * unsigned char -> int32
217
+ #define CPUBLAS_BRGEMM_U8I8I32 // unsigned char * signed char -> int32
218
+ #define CPUBLAS_BRGEMM_I8I8I32 // signed char * signed char -> int32
219
+
220
+ TORCH_API void brgemm(
221
+ int64_t M,
222
+ int64_t N,
223
+ int64_t K,
224
+ int64_t ld_a,
225
+ int64_t ld_b,
226
+ int64_t ld_c,
227
+ const bool add_C,
228
+ const at::Half* A,
229
+ const at::Half* B,
230
+ float* C,
231
+ bool is_vnni = true);
232
+
233
+ TORCH_API void brgemm(
234
+ int64_t M,
235
+ int64_t N,
236
+ int64_t K,
237
+ int64_t ld_a,
238
+ int64_t ld_b,
239
+ int64_t ld_c,
240
+ const bool add_C,
241
+ const at::BFloat16* A,
242
+ const at::BFloat16* B,
243
+ float* C,
244
+ bool is_vnni = true);
245
+
246
+ TORCH_API void brgemm(
247
+ int64_t M,
248
+ int64_t N,
249
+ int64_t K,
250
+ int64_t ld_a,
251
+ int64_t ld_b,
252
+ int64_t ld_c,
253
+ const bool add_C,
254
+ const float* A,
255
+ const float* B,
256
+ float* C,
257
+ bool is_vnni = false);
258
+
259
+ TORCH_API void brgemm(
260
+ int64_t M,
261
+ int64_t N,
262
+ int64_t K,
263
+ int64_t ld_a,
264
+ int64_t ld_b,
265
+ int64_t ld_c,
266
+ const bool add_C,
267
+ const unsigned char* A,
268
+ const unsigned char* B,
269
+ int32_t* C,
270
+ bool is_vnni = true);
271
+
272
+ TORCH_API void brgemm(
273
+ int64_t M,
274
+ int64_t N,
275
+ int64_t K,
276
+ int64_t ld_a,
277
+ int64_t ld_b,
278
+ int64_t ld_c,
279
+ const bool add_C,
280
+ const unsigned char* A,
281
+ const signed char* B,
282
+ int32_t* C,
283
+ bool is_vnni = true);
284
+
285
+ TORCH_API void brgemm(
286
+ int64_t M,
287
+ int64_t N,
288
+ int64_t K,
289
+ int64_t ld_a,
290
+ int64_t ld_b,
291
+ int64_t ld_c,
292
+ const bool add_C,
293
+ const signed char* A,
294
+ const signed char* B,
295
+ int32_t* C,
296
+ bool is_vnni = true);
297
+
298
+ // Release brgemm hardware context
299
+ TORCH_API void brgemm_release(bool is_vnni = true);
300
+
301
+ // Pack B matrix to get better performance if needed
302
+ TORCH_API void pack(
303
+ int64_t K,
304
+ int64_t N,
305
+ int64_t ld_in,
306
+ int64_t ld_out,
307
+ ScalarType dt_in,
308
+ ScalarType dt_out,
309
+ const void* in,
310
+ void* out);
311
+
312
+ // Whether pack is supported in the platform.
313
+ TORCH_API bool could_pack(ScalarType dt_in);
314
+
315
+ } // namespace at::native::cpublas
316
+
317
+ #else
318
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
319
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)