jasonfan commited on
Commit
d7fe2a7
·
verified ·
1 Parent(s): b22bd2d

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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/metrics/RpcMetricsHandler.h +45 -0
  2. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/remote_profiler_manager.h +60 -0
  3. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/server_process_global_profiler.h +134 -0
  4. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h +72 -0
  5. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h +59 -0
  6. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h +27 -0
  7. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h +498 -0
  8. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h +124 -0
  9. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h +109 -0
  10. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/testing.h +14 -0
  11. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h +42 -0
  12. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/types.h +75 -0
  13. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h +43 -0
  14. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h +38 -0
  15. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h +91 -0
  16. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cache_entry.h +100 -0
  17. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/compiled_autograd.h +1566 -0
  18. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpp_shim.h +20 -0
  19. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_defs.h +45 -0
  20. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_includes.h +76 -0
  21. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/debug_macros.h +107 -0
  22. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame.h +65 -0
  23. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame_cpp.h +34 -0
  24. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/extra_state.h +213 -0
  25. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/framelocals_mapping.h +97 -0
  26. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/guards.h +119 -0
  27. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/init.h +16 -0
  28. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/python_compiled_autograd.h +12 -0
  29. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/stackref_bridge.h +23 -0
  30. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/utils.h +23 -0
  31. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/example_upgraders.h +20 -0
  32. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pt2_archive_constants.h +76 -0
  33. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pybind.h +12 -0
  34. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/upgrader.h +124 -0
  35. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functionalization/Module.h +41 -0
  36. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functorch/init.h +12 -0
  37. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/fx/node.h +11 -0
  38. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_holder.h +117 -0
  39. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_meta_info.h +147 -0
  40. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/array_ref.h +12 -0
  41. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/common.h +21 -0
  42. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cpu.h +9 -0
  43. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cuda.h +9 -0
  44. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/mps.h +9 -0
  45. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/xpu.h +9 -0
  46. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/model_package_loader.h +64 -0
  47. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/pybind.h +12 -0
  48. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h +145 -0
  49. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h +23 -0
  50. miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h +40 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/metrics/RpcMetricsHandler.h ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/util/Registry.h>
4
+ #include <string>
5
+
6
+ namespace torch::distributed::rpc {
7
+ // All metrics are prefixed with the following key.
8
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays)
9
+ constexpr char kRpcMetricsKeyPrefix[] = "torch.distributed.rpc.";
10
+ // APIs for logging time-series metrics for RPC-based distributed
11
+ // training. Implementations of this class should provide thread safety so that
12
+ // metrics can be logged from multiple threads without the user needing to
13
+ // coordinate serialization.
14
+ class RpcMetricsHandler {
15
+ public:
16
+ // Accumulates the metric value specified by the name for purposes of
17
+ // computing aggregate statistics over time.
18
+ virtual void accumulateMetric(const std::string& name, double value) = 0;
19
+ // Increment a count for the metric given by the name.
20
+ virtual void incrementMetric(const std::string& name) = 0;
21
+ virtual ~RpcMetricsHandler() = default;
22
+ };
23
+
24
+ // Configuration struct for metrics handling.
25
+ struct RpcMetricsConfig {
26
+ explicit RpcMetricsConfig(std::string handlerName, bool enabled)
27
+ : handlerName_(std::move(handlerName)), enabled_(enabled) {}
28
+
29
+ // Handler name
30
+ std::string handlerName_;
31
+ // Whether metrics exporting should be enabled or not.
32
+ bool enabled_;
33
+ };
34
+
35
+ // A registry for different implementations of RpcMetricsHandler. Classes
36
+ // implementing the above interface should use this to register implementations.
37
+ TORCH_DECLARE_REGISTRY(
38
+ RpcMetricsHandlerRegistry,
39
+ torch::distributed::rpc::RpcMetricsHandler);
40
+
41
+ } // namespace torch::distributed::rpc
42
+
43
+ #else
44
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
45
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/remote_profiler_manager.h ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <torch/csrc/Export.h>
4
+ #include <torch/csrc/distributed/rpc/types.h>
5
+ #include <mutex>
6
+ #include <optional>
7
+ #include <unordered_map>
8
+
9
+ namespace torch::distributed::rpc {
10
+ extern const std::string REMOTE_PROFILING_KEY_PREFIX;
11
+
12
+ class TORCH_API RemoteProfilerManager {
13
+ public:
14
+ // Retrieves the lazily-initialized RemoteProfilerManager singleton instance.
15
+ static RemoteProfilerManager& getInstance();
16
+ // Sets the current, thread-local profiling key.
17
+ void setCurrentKey(std::string key);
18
+ // Returns whether the current profiling key is set.
19
+ bool isCurrentKeySet() const;
20
+ // Unsets the current, thread-local profiling key to allow other RPCs to reset
21
+ // it.
22
+ void unsetCurrentKey();
23
+ // inserts a pair (globallyUniqueId, key) to an in-memory map. The
24
+ // corresponding ID is used in RPC deserialization to prefix remotely profiled
25
+ // events with the right key.
26
+ void saveRPCKey(
27
+ ProfilingId globallyUniqueId,
28
+ const std::string& rpcProfilingKey);
29
+ // Retrieves the profiling key corresponding to the given globallyUniqueId.
30
+ // Throws if it is not found.
31
+ std::string retrieveRPCProfilingKey(const ProfilingId& globallyUniqueId);
32
+ // Generates the next globally unique ID for profiling.
33
+ ProfilingId getNextProfilerId();
34
+ // Retrieves the currently set thread-local profiling key. Throws if it is not
35
+ // set.
36
+ std::string& getCurrentProfilingKey();
37
+ // erases the globallyUniqueId from the map. This can help save memory in the
38
+ // case that many RPCs are being profiled.
39
+ void eraseKey(const ProfilingId& globallyUniqueId);
40
+
41
+ RemoteProfilerManager(const RemoteProfilerManager& other) = delete;
42
+ RemoteProfilerManager operator=(const RemoteProfilerManager& other) = delete;
43
+ RemoteProfilerManager(RemoteProfilerManager&&) = delete;
44
+ RemoteProfilerManager& operator=(RemoteProfilerManager&&) = delete;
45
+
46
+ private:
47
+ RemoteProfilerManager();
48
+ ~RemoteProfilerManager() = default;
49
+ local_id_t getNextLocalId();
50
+ std::unordered_map<ProfilingId, std::string, ProfilingId::Hash>
51
+ profiledRpcKeys_;
52
+ static thread_local std::optional<std::string> currentThreadLocalKey_;
53
+ std::mutex mutex_;
54
+ local_id_t currentLocalId_;
55
+ };
56
+ } // namespace torch::distributed::rpc
57
+
58
+ #else
59
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
60
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/profiler/server_process_global_profiler.h ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <shared_mutex>
5
+ #include <utility>
6
+
7
+ #include <torch/csrc/autograd/profiler.h>
8
+
9
+ namespace torch::distributed::rpc::profiler::processglobal {
10
+
11
+ using namespace torch::autograd::profiler;
12
+
13
+ // Process global profiler state.
14
+ //
15
+ // This class holds information about a profiling range, from "enable" to
16
+ // "disable".
17
+ // An instance of this ``State`` will be
18
+ // pushed into a global stack, so nested profiling range is supported.
19
+ //
20
+ // It has 2 members.
21
+ // One is ``autograd::profiler::ProfilerConfig``. It's set by user and
22
+ // will be copied to thread-local profiler state of RPC threads.
23
+ // The other is a container that aggregates recorded
24
+ // ``autograd::profiler::Event``s from all thread-local profilers on RPC
25
+ // threads.
26
+ class State {
27
+ public:
28
+ explicit State(ProfilerConfig config) : config_(std::move(config)) {}
29
+ ~State() = default;
30
+
31
+ const ProfilerConfig& config() const {
32
+ return config_;
33
+ }
34
+
35
+ void pushResult(thread_event_lists result) {
36
+ std::unique_lock<std::mutex> lock(resultsMutex_);
37
+
38
+ // NB: When a thread wants to push an entry into the this container,
39
+ // main control logic might have exited the process-global profile range.
40
+ results_.emplace_back(std::move(result));
41
+ }
42
+
43
+ std::vector<thread_event_lists> results();
44
+
45
+ private:
46
+ // Each result comes from a profile range. In each profile range, there is a
47
+ // "__profiler_start" marker event that all following events calculate time
48
+ // relative to it, so it's required to call
49
+ // parse_cpu_trace(result) for results of all profile range.
50
+ std::mutex resultsMutex_;
51
+ std::vector<thread_event_lists> results_;
52
+ const ProfilerConfig config_ = ProfilerConfig(ProfilerState::Disabled);
53
+ };
54
+
55
+ class StateStackEntry;
56
+
57
+ #if defined(__MACH__)
58
+ // Compiler error: 'shared_timed_mutex' is unavailable: introduced in
59
+ // macOS 10.12
60
+ using mutexType = std::mutex;
61
+ // Compiler error: 'shared_lock' is unavailable: introduced in
62
+ // macOS 10.12
63
+ using rLockType = std::unique_lock<std::mutex>;
64
+ using wLockType = std::unique_lock<std::mutex>;
65
+ #else
66
+ using mutexType = std::shared_timed_mutex;
67
+ using rLockType = std::shared_lock<std::shared_timed_mutex>;
68
+ using wLockType = std::unique_lock<std::shared_timed_mutex>;
69
+ #endif
70
+
71
+ // This is the global stack of ``State``s.
72
+ TORCH_API extern std::shared_ptr<StateStackEntry> currentStateStackEntryPtr;
73
+ TORCH_API extern mutexType currentStateStackEntryMutex;
74
+
75
+ // This class is used to implement a stack of ``State``s.
76
+ // It has 2 members.
77
+ // One is `prevPtr`, a shared_ptr pointing to previous element in the
78
+ // stack.
79
+ // The other is ``statePtr``, a shared_ptr pointing to ``State``.
80
+ class StateStackEntry {
81
+ public:
82
+ StateStackEntry(
83
+ std::shared_ptr<StateStackEntry> prevPtr,
84
+ std::shared_ptr<State> statePtr)
85
+ : prevPtr_(std::move(prevPtr)), statePtr_(std::move(statePtr)) {}
86
+
87
+ static void pushRange(std::shared_ptr<State> profilerProcessGlobalStatePtr);
88
+ static std::shared_ptr<State> popRange();
89
+
90
+ static std::shared_ptr<StateStackEntry> current() {
91
+ rLockType rlock(currentStateStackEntryMutex);
92
+
93
+ return currentStateStackEntryPtr;
94
+ }
95
+
96
+ std::shared_ptr<StateStackEntry> prevPtr() const {
97
+ return prevPtr_;
98
+ }
99
+
100
+ std::shared_ptr<State> statePtr() const {
101
+ return statePtr_;
102
+ }
103
+
104
+ private:
105
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
106
+ const std::shared_ptr<StateStackEntry> prevPtr_{nullptr};
107
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
108
+ const std::shared_ptr<State> statePtr_{nullptr};
109
+ };
110
+
111
+ // Push the result to ``State``s of current profile range and recursively outer
112
+ // profile ranges.
113
+ TORCH_API void pushResultRecursive(
114
+ std::shared_ptr<StateStackEntry> stateStackEntryPtr,
115
+ const thread_event_lists& result);
116
+
117
+ // User-facing API.
118
+ //
119
+ // Enter a server-side process-global profiling range.
120
+ // Profiling range can be neste, so it's ok to call this API for multiple
121
+ // times. This enables all RPC threads running server-side request callbacks.
122
+ TORCH_API void enableServer(const ProfilerConfig& new_config);
123
+ //
124
+ // Exit a server-side process-global profiling range.
125
+ // Profiling range can be neste, so it's possible that profiler is still on
126
+ // after calling this API.
127
+ // This enables all RPC threads running server-side request callbacks.
128
+ TORCH_API std::vector<thread_event_lists> disableServer();
129
+
130
+ } // namespace torch::distributed::rpc::profiler::processglobal
131
+
132
+ #else
133
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
134
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/distributed/rpc/message.h>
5
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
6
+ #include <torch/csrc/jit/runtime/operator.h>
7
+ #include <optional>
8
+ #include <vector>
9
+
10
+ namespace torch::distributed::rpc {
11
+
12
+ using torch::jit::Operator;
13
+
14
+ // A ScriptCall instance represents an invocation of a builtin operator for a
15
+ // TorchScript function. If it is a builtin operator, it
16
+ // contains a shared ptr to the `Operator` and a list of arguments.
17
+ // If it is a TorchScript function, it contains a non empty qualifiedName string
18
+ // to the TorchScript function schema name and a list of arguments.
19
+ class TORCH_API ScriptCall : public RpcCommandBase {
20
+ public:
21
+ // Constructor for builtin operator call.
22
+ ScriptCall(std::shared_ptr<Operator> op, std::vector<at::IValue>&& stack);
23
+ // Constructor for TorchScript function call.
24
+ ScriptCall(
25
+ const c10::QualifiedName& qualifiedName,
26
+ std::vector<at::IValue>&& stack,
27
+ const bool isAsyncExecution = false);
28
+
29
+ bool hasOp() const;
30
+ std::shared_ptr<Operator> op() const;
31
+ bool hasQualifiedName() const;
32
+ const c10::QualifiedName& qualifiedName() const;
33
+ // return the argument stack of this builtin operator
34
+ const std::vector<at::IValue>& stack() const;
35
+ std::vector<at::IValue>& stackRef();
36
+ inline bool isAsyncExecution() const {
37
+ return isAsyncExecution_;
38
+ }
39
+
40
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
41
+ static std::unique_ptr<ScriptCall> fromMessage(const Message& message);
42
+
43
+ ~ScriptCall() override = default;
44
+
45
+ protected:
46
+ virtual void toIValues(std::vector<at::IValue>& ivalues) const;
47
+ static std::unique_ptr<ScriptCall> fromIValues(
48
+ std::vector<at::IValue>& ivalues);
49
+
50
+ private:
51
+ // Given an operator symbol and a string schema, return the matched operator.
52
+ static std::shared_ptr<Operator> matchOperator(const std::string& str_schema);
53
+
54
+ static const std::string BUILTIN_OP_NAMESPACE_;
55
+ static const std::string ATEN_PREFIX_;
56
+
57
+ // This field has value if this ScriptCall represents invocation of a builtin
58
+ // operator.
59
+ std::optional<std::shared_ptr<Operator>> op_;
60
+ // This field has non empty string if this ScriptCall represents invocation of
61
+ // an annotated torchscript function defined by users.
62
+ std::optional<const c10::QualifiedName> qualifiedName_;
63
+ std::vector<at::IValue> stack_;
64
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
65
+ const bool isAsyncExecution_;
66
+ };
67
+
68
+ } // namespace torch::distributed::rpc
69
+
70
+ #else
71
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
72
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/distributed/rpc/script_call.h>
5
+ #include <torch/csrc/distributed/rpc/types.h>
6
+ #include <torch/csrc/jit/runtime/operator.h>
7
+ #include <vector>
8
+
9
+ namespace torch::distributed::rpc {
10
+
11
+ using torch::jit::Operator;
12
+
13
+ // A ScriptRemoteCall instance represents an invocation of `dist.remote` on a
14
+ // builtin operator. Currently, it does not support using RRef as arguments yet.
15
+ // Besides the operator and a vector of arguments, ScriptRemoteCall also
16
+ // contains the RRefId and the ForkId of the return value RRef.
17
+ class TORCH_API ScriptRemoteCall final : public ScriptCall {
18
+ public:
19
+ // Constructor for builtin operator call.
20
+ ScriptRemoteCall(
21
+ std::shared_ptr<Operator> op,
22
+ std::vector<at::IValue>&& stack,
23
+ const RRefId& retRRefId,
24
+ const ForkId& retForkId);
25
+
26
+ // Constructor for TorchScript function call.
27
+ ScriptRemoteCall(
28
+ const c10::QualifiedName& qualifiedName,
29
+ std::vector<at::IValue>&& stack,
30
+ const RRefId& retRRefId,
31
+ const ForkId& retForkId,
32
+ const bool isAsyncExecution);
33
+
34
+ inline const RRefId& retRRefId() const {
35
+ return retRRefId_;
36
+ }
37
+
38
+ inline const ForkId& retForkId() const {
39
+ return retForkId_;
40
+ }
41
+
42
+ static std::unique_ptr<ScriptRemoteCall> fromIValues(
43
+ std::vector<at::IValue>& ivalues);
44
+
45
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
46
+ static std::unique_ptr<ScriptRemoteCall> fromMessage(const Message& message);
47
+
48
+ private:
49
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
50
+ const RRefId retRRefId_;
51
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
52
+ const ForkId retForkId_;
53
+ };
54
+
55
+ } // namespace torch::distributed::rpc
56
+
57
+ #else
58
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
59
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/distributed/rpc/message.h>
5
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
6
+
7
+ namespace torch::distributed::rpc {
8
+
9
+ // Return value of a builtin operator or a TorchScript function.
10
+ class TORCH_API ScriptResp final : public RpcCommandBase {
11
+ public:
12
+ explicit ScriptResp(at::IValue&& values);
13
+
14
+ const at::IValue& value();
15
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
16
+ static std::unique_ptr<ScriptResp> fromMessage(const Message& message);
17
+
18
+ private:
19
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
20
+ const at::IValue value_;
21
+ };
22
+
23
+ } // namespace torch::distributed::rpc
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #ifdef USE_TENSORPIPE
5
+
6
+ #include <atomic>
7
+ #include <thread>
8
+
9
+ #include <c10/core/thread_pool.h>
10
+ #include <torch/csrc/distributed/c10d/PrefixStore.hpp>
11
+ #include <torch/csrc/distributed/c10d/Store.hpp>
12
+ #include <torch/csrc/distributed/rpc/rpc_agent.h>
13
+ #include <utility>
14
+
15
+ // Forward-declare the TensorPipe classes we need, to avoid including its
16
+ // headers in PyTorch's ones and thus have it become a public dependency.
17
+
18
+ namespace tensorpipe {
19
+
20
+ class Context;
21
+ class Error;
22
+ class Listener;
23
+ class Message;
24
+ class Pipe;
25
+
26
+ namespace transport {
27
+ class Context;
28
+ } // namespace transport
29
+
30
+ namespace channel {
31
+ class Context;
32
+ } // namespace channel
33
+
34
+ } // namespace tensorpipe
35
+
36
+ namespace torch::distributed::rpc {
37
+
38
+ // These priorities instruct TensorPipe on which transport/channel to pick
39
+ // during handshake. Higher priorities will take precedence over lower ones.
40
+ // The transport with lowest priority will be the one used to bootstrap pipes.
41
+
42
+ constexpr int64_t kShmTransportPriority = 200;
43
+ constexpr int64_t kIbvTransportPriority = 100;
44
+ // The UV transport just uses TCP and should work everywhere, thus keep it last.
45
+ constexpr int64_t kUvTransportPriority = 0;
46
+
47
+ constexpr int64_t kCmaChannelPriority = 1200;
48
+ constexpr int64_t kMultiplexedUvChannelPriority = 1100;
49
+ // The basic channel reuses a transport as a channel, and is thus our fallback.
50
+ constexpr int64_t kBasicChannelPriority = 1000;
51
+
52
+ // CPU channel have higher priority than CUDA channels, since the latter might
53
+ // handle CPU-to-CPU transfers, but will always be less efficient than their
54
+ // CPU-only counterparts.
55
+ constexpr int64_t kCudaIpcChannelPriority = 300;
56
+ constexpr int64_t kCudaGdrChannelPriority = 200;
57
+ constexpr int64_t kCudaXthChannelPriority = 400;
58
+ constexpr int64_t kCudaBasicChannelPriority = 0;
59
+
60
+ using steady_clock_time_point =
61
+ std::chrono::time_point<std::chrono::steady_clock>;
62
+
63
+ struct TORCH_API TransportRegistration {
64
+ std::shared_ptr<tensorpipe::transport::Context> transport;
65
+ int64_t priority;
66
+ std::string address;
67
+ };
68
+
69
+ TORCH_DECLARE_REGISTRY(TensorPipeTransportRegistry, TransportRegistration);
70
+
71
+ struct TORCH_API ChannelRegistration {
72
+ std::shared_ptr<tensorpipe::channel::Context> channel;
73
+ int64_t priority;
74
+ };
75
+
76
+ TORCH_DECLARE_REGISTRY(TensorPipeChannelRegistry, ChannelRegistration);
77
+
78
+ struct TORCH_API TensorPipeRpcBackendOptions : public RpcBackendOptions {
79
+ TensorPipeRpcBackendOptions(
80
+ int numWorkerThreads,
81
+ std::optional<std::vector<std::string>> transports,
82
+ std::optional<std::vector<std::string>> channels,
83
+ float rpc_timeout,
84
+ std::string init_method,
85
+ std::unordered_map<std::string, DeviceMap> device_maps = {},
86
+ std::vector<c10::Device> devices = {})
87
+ : RpcBackendOptions(rpc_timeout, std::move(init_method)),
88
+ numWorkerThreads(numWorkerThreads),
89
+ transports(std::move(transports)),
90
+ channels(std::move(channels)),
91
+ deviceMaps(std::move(device_maps)),
92
+ devices(std::move(devices)) {
93
+ TORCH_CHECK(
94
+ numWorkerThreads > 0,
95
+ "num_worker_threads must be positive, got ",
96
+ numWorkerThreads);
97
+
98
+ if (this->transports.has_value()) {
99
+ for (const std::string& transportName : this->transports.value()) {
100
+ TORCH_CHECK(
101
+ TensorPipeTransportRegistry()->Has(transportName),
102
+ "Unknown transport: ",
103
+ transportName);
104
+ }
105
+ }
106
+
107
+ if (this->channels.has_value()) {
108
+ for (const std::string& channelName : this->channels.value()) {
109
+ TORCH_CHECK(
110
+ TensorPipeChannelRegistry()->Has(channelName),
111
+ "Unknown channel: ",
112
+ channelName);
113
+ }
114
+ }
115
+ }
116
+
117
+ void setDeviceMap(const std::string& workerName, const DeviceMap& deviceMap) {
118
+ auto iter = deviceMaps.find(workerName);
119
+ if (iter == deviceMaps.end()) {
120
+ deviceMaps[workerName] = deviceMap;
121
+ } else {
122
+ for (auto& entry : deviceMap) {
123
+ // c10::Device has no default constructor, hence map[device] doesn't
124
+ // work In C++-17 we can use insert_or_assign.
125
+ auto entryIter = iter->second.find(entry.first);
126
+ if (entryIter == iter->second.end()) {
127
+ iter->second.emplace(entry.first, entry.second);
128
+ } else {
129
+ entryIter->second = entry.second;
130
+ }
131
+ }
132
+ }
133
+ }
134
+
135
+ int numWorkerThreads;
136
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
137
+ const std::optional<std::vector<std::string>> transports;
138
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
139
+ const std::optional<std::vector<std::string>> channels;
140
+ std::unordered_map<std::string, DeviceMap> deviceMaps;
141
+ std::vector<c10::Device> devices;
142
+ };
143
+
144
+ // Struct to track the network source metrics
145
+ struct TORCH_API NetworkSourceInfo {
146
+ worker_id_t srcRank;
147
+ std::vector<uint8_t> srcMachineAddr;
148
+ };
149
+
150
+ // Struct to track aggregated network metrics
151
+ struct TORCH_API AggregatedNetworkData {
152
+ uint64_t numCalls{0};
153
+ uint64_t totalSentBytes{0};
154
+ uint64_t totalRecvBytes{0};
155
+ uint64_t totalErrors{0};
156
+ };
157
+
158
+ // TensorPipeAgent leverages TensorPipe (https://github.com/pytorch/tensorpipe)
159
+ // to transparently move tensors and payloads through the fastest available
160
+ // transport or channel. It acts like a hybrid RPC transport, providing shared
161
+ // memory (linux) and TCP (linux & mac) support. CUDA support is in progress.
162
+ class TORCH_API TensorPipeAgent : public RpcAgent {
163
+ public:
164
+ TensorPipeAgent(
165
+ const c10::intrusive_ptr<::c10d::Store>& store,
166
+ std::string selfName,
167
+ worker_id_t selfId,
168
+ std::optional<int> worldSize,
169
+ TensorPipeRpcBackendOptions opts,
170
+ std::unordered_map<std::string, DeviceMap> reverseDeviceMaps,
171
+ std::vector<c10::Device> devices,
172
+ std::unique_ptr<RequestCallback> cb);
173
+
174
+ TensorPipeAgent(const TensorPipeAgent&) = delete;
175
+ TensorPipeAgent& operator=(const TensorPipeAgent&) = delete;
176
+
177
+ c10::intrusive_ptr<JitFuture> send(
178
+ const WorkerInfo& to,
179
+ c10::intrusive_ptr<Message> message,
180
+ const float rpcTimeoutSeconds = kUnsetRpcTimeout,
181
+ const DeviceMap& deviceMap = {}) override;
182
+
183
+ // join() and sync() would be deprecated -
184
+ // https://github.com/pytorch/pytorch/issues/27647
185
+ void join(bool shutdown = false, float timeout = 0) override;
186
+ void sync() override {}
187
+ void startImpl() override;
188
+ void shutdownImpl() override;
189
+
190
+ ~TensorPipeAgent() override;
191
+
192
+ const WorkerInfo& getWorkerInfo(const std::string& workerName) const override;
193
+ const WorkerInfo& getWorkerInfo(worker_id_t workerId) const override;
194
+ std::vector<WorkerInfo> getWorkerInfos() const override;
195
+ void updateGroupMembership(
196
+ const WorkerInfo& workerInfo,
197
+ const std::vector<c10::Device>& devices,
198
+ const std::unordered_map<std::string, DeviceMap>& reverseDeviceMaps,
199
+ bool isJoin);
200
+
201
+ std::unordered_map<std::string, std::string> getMetrics() override;
202
+
203
+ void addGilWaitTime(const std::chrono::microseconds gilWaitTime) override;
204
+
205
+ TensorPipeRpcBackendOptions getBackendOptions() const;
206
+
207
+ const c10::intrusive_ptr<::c10d::Store> getStore() const;
208
+
209
+ DeviceMap getDeviceMap(const WorkerInfo& dest) const override;
210
+
211
+ const std::vector<c10::Device>& getDevices() const override;
212
+
213
+ using NetworkDataDict =
214
+ std::unordered_map<std::string, AggregatedNetworkData>;
215
+
216
+ // Returns metrics tracked by the NetworkDataDict
217
+ NetworkDataDict getNetworkData();
218
+ // Returns NetworkSourceInfo struct
219
+ NetworkSourceInfo getNetworkSourceInfo();
220
+
221
+ static const std::string& guessAddress();
222
+
223
+ // For testing purposes.
224
+ size_t timeoutMapSize();
225
+ size_t numPendingResponses();
226
+ size_t messageIdToTimeoutMapSize();
227
+
228
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
229
+ const bool isStaticGroup_;
230
+
231
+ protected:
232
+ // TensorPipe write function that could be used to write response
233
+ // messages by server, and write request messages by client. This
234
+ // is a protected method since it is overwritten by FaultyTensorPipeAgent
235
+ virtual void pipeWrite(
236
+ const std::shared_ptr<tensorpipe::Pipe>& /*pipe*/,
237
+ const c10::intrusive_ptr<Message>& message,
238
+ std::vector<c10::Device>&& devices,
239
+ std::vector<c10::Stream> streams,
240
+ std::function<void(const tensorpipe::Error&)> /*fn*/) noexcept;
241
+
242
+ private:
243
+ // Removes the given messageId with the given expirationTime from the
244
+ // timeoutMap_.
245
+ void removeFromTimeoutMap(uint64_t messageId);
246
+
247
+ // Populates workerIdToInfo_ and workerNameToInfo_ using addressStore_
248
+ void prepareNames(bool isStaticGroup);
249
+
250
+ // Check the static group attribute with the value set in store
251
+ void checkAndSetStaticGroup(const c10::intrusive_ptr<::c10d::Store>& store);
252
+
253
+ const std::string& findWorkerURL(const WorkerInfo& worker) const;
254
+
255
+ // Only use for Dynamic RPC groups, method to have worker leave group
256
+ void leaveGroup();
257
+
258
+ // TensorPipe read function that could be used to read response messages
259
+ // by client, and read request messages by server.
260
+ void pipeRead(
261
+ const std::shared_ptr<tensorpipe::Pipe>& /*pipe*/,
262
+ std::function<void(
263
+ const tensorpipe::Error&,
264
+ c10::intrusive_ptr<Message>,
265
+ std::vector<c10::Stream>)> /*fn*/) noexcept;
266
+
267
+ // Callback of listener accept()
268
+ void onListenerAccepted(
269
+ const tensorpipe::Error& error,
270
+ std::shared_ptr<tensorpipe::Pipe>& pipe);
271
+
272
+ // Respond to a call from a peer
273
+ void respond(std::shared_ptr<tensorpipe::Pipe>& pipe);
274
+
275
+ void sendCompletedResponseMessage(
276
+ std::shared_ptr<tensorpipe::Pipe>& pipe,
277
+ JitFuture& futureResponseMessage,
278
+ uint64_t messageId,
279
+ std::vector<c10::Stream> stream);
280
+
281
+ // Collects metrics from successful RPC calls
282
+ void trackNetworkData(
283
+ uint64_t requestSize,
284
+ uint64_t responseSize,
285
+ const std::string& destWorkerName);
286
+
287
+ // Collects metrics from failed RPC calls
288
+ void trackNetworkError(
289
+ uint64_t requestSize,
290
+ const std::string& destWorkerName);
291
+
292
+ inline std::vector<c10::Device> getDevicesForRemote(
293
+ const std::string& remoteName,
294
+ const Message& message) const;
295
+
296
+ // When a request+response completes, we need to mark the future message as
297
+ // complete. However, if its timeout has already expired, it already has an
298
+ // error set. There is no atomic "test-and-set" way to mark a future complete
299
+ // only if it isn't yet. It does exist for errors (setErrorIfNeeded) but, even
300
+ // then, it ends up printing a log message, which may worry the user. To solve
301
+ // both issues we use a separate atomic flag to know the status of the future.
302
+ struct AtomicJitFuture {
303
+ explicit AtomicJitFuture(const std::vector<c10::Device>& devices) {
304
+ jitFuture = c10::make_intrusive<at::ivalue::Future>(
305
+ at::AnyClassType::get(), devices);
306
+ }
307
+
308
+ std::atomic_flag isComplete = ATOMIC_FLAG_INIT;
309
+ c10::intrusive_ptr<JitFuture> jitFuture;
310
+ };
311
+
312
+ // Maintains state per client pipe to track pending response messages and
313
+ // error states. pendingResponseMessage_ should be protected by a mutex since
314
+ // it can be raced with user send() call.
315
+ // TODO: To achieve better performance we can have a pipe pool per
316
+ // client that can be configured using RpcBackendOptions.
317
+ struct ClientPipe {
318
+ explicit ClientPipe(std::shared_ptr<tensorpipe::Pipe> pipe)
319
+ : pipe_(std::move(pipe)) {}
320
+ std::shared_ptr<tensorpipe::Pipe> pipe_;
321
+ mutable std::mutex mutex_;
322
+ bool inError_{false};
323
+ // Map from Message Request ID's to corresponding futures.
324
+ std::unordered_map<uint64_t, std::shared_ptr<AtomicJitFuture>>
325
+ pendingResponseMessage_;
326
+ };
327
+
328
+ const c10::intrusive_ptr<::c10d::Store> store_;
329
+
330
+ const TensorPipeRpcBackendOptions opts_;
331
+ // For dynamic RPC, the reverse device maps are updated whenever a new rank
332
+ // joins or leaves the group
333
+ std::unordered_map<std::string, DeviceMap> reverseDeviceMaps_;
334
+ // Local devices used by this agent. If application didn't specify this
335
+ // field, it will be initialized using corresponding local devices in
336
+ // opts_.deviceMaps and reverseDeviceMaps_;
337
+ std::vector<c10::Device> devices_;
338
+
339
+ ThreadPool threadPool_;
340
+ std::shared_ptr<tensorpipe::Context> context_;
341
+ std::shared_ptr<tensorpipe::Listener> listener_;
342
+
343
+ mutable std::mutex connectedPipesMutex_;
344
+ std::unordered_map<worker_id_t, ClientPipe> connectedPipes_;
345
+
346
+ // Maps keyed on name and id for easy WorkerInfo lookup.
347
+ std::unordered_map<worker_id_t, WorkerInfo> workerIdToInfo_;
348
+ std::unordered_map<std::string, WorkerInfo> workerNameToInfo_;
349
+ std::unordered_map<std::string, std::string> workerNameToURL_;
350
+
351
+ ::c10d::PrefixStore rankToNameStore_;
352
+ ::c10d::PrefixStore nameToAddressStore_;
353
+ // Store keys that will used to count joined processes and active calls during
354
+ // the shutdown process
355
+ ::c10d::PrefixStore shutdownStore_;
356
+ int worldSize_ = 0;
357
+ std::atomic<uint64_t> nextMessageID_{0};
358
+
359
+ // Metadata used for tracking of whether certain RPCs have timed out or not.
360
+ struct TimeoutMessageMetadata {
361
+ TimeoutMessageMetadata(
362
+ uint64_t messageId_,
363
+ std::shared_ptr<AtomicJitFuture> responseFuture_,
364
+ std::chrono::milliseconds timeout_)
365
+ : messageId(messageId_),
366
+ responseFuture(std::move(responseFuture_)),
367
+ timeout(timeout_) {}
368
+ uint64_t messageId;
369
+ std::shared_ptr<AtomicJitFuture> responseFuture;
370
+ std::chrono::milliseconds timeout;
371
+ };
372
+
373
+ // Map to store the expiration times for each message.
374
+ std::map<steady_clock_time_point, std::vector<TimeoutMessageMetadata>>
375
+ timeoutMap_;
376
+
377
+ // Map to store the messageId to expiry time.
378
+ std::unordered_map<uint64_t, steady_clock_time_point> messageIdToTimeout_;
379
+
380
+ // Thread that will poll the timeoutMap_ for timed out messages and mark them
381
+ // with an error accordingly
382
+ std::thread timeoutThread_;
383
+
384
+ // Function run by the timeoutThread_ to check for timed out RPCs
385
+ void pollTimeoutRpcs();
386
+
387
+ // Mutex to guard the timeoutMap_
388
+ std::mutex timeoutMapMutex_;
389
+
390
+ // Condition Variable to signal population of the timeoutMap_
391
+ std::condition_variable timeoutThreadCV_;
392
+
393
+ // Returns the expiration time for an RPC by adding the current time to the
394
+ // passed in timeout.
395
+ inline steady_clock_time_point computeRpcMessageExpiryTime(
396
+ std::chrono::milliseconds timeout) const {
397
+ return std::chrono::time_point_cast<std::chrono::milliseconds>(
398
+ std::chrono::steady_clock::now() + timeout);
399
+ }
400
+
401
+ // Handle error on an outgoing pipe
402
+ void handleClientError(
403
+ ClientPipe& clientPipe,
404
+ const tensorpipe::Error& error);
405
+
406
+ // This is a generic struct for capturing Time-Series Metrics. It keeps a
407
+ // running sum and count of data points (observations), and can return an
408
+ // average of the data points seen so far. This is currently only used for
409
+ // tracking the GIL Wait Time in RPC Agents, but can be used for other metrics
410
+ // as well.
411
+ struct TimeSeriesMetricsTracker {
412
+ // Running sum of the data points seen so far
413
+ uint64_t currentSum_;
414
+ // Running count of the data points seen so far
415
+ uint64_t currentCount_;
416
+
417
+ explicit TimeSeriesMetricsTracker(
418
+ uint64_t currentSum = 0,
419
+ uint64_t currentCount = 0);
420
+
421
+ // Adds a data point (which is basically one observation for the metric
422
+ // being tracked) to the running sum and count.
423
+ void addData(uint64_t dataPoint);
424
+ // Returns the average of all the data points seen so far.
425
+ float computeAverage() const;
426
+ };
427
+
428
+ // Map of Time-Series metrics tracked by the RPC Agent
429
+ std::unordered_map<std::string, TimeSeriesMetricsTracker> timeSeriesMetrics_;
430
+ // Mutex to guard timeSeriesMetrics_
431
+ std::mutex metricsMutex_;
432
+
433
+ // Custom lock guard used to check if the RPC group is dynamic and lock the
434
+ // mutex if so
435
+ struct GroupMembershipLockGuard {
436
+ GroupMembershipLockGuard(std::mutex& mutex, bool isStaticGroup)
437
+ : ref_(mutex), isStaticGroup_(isStaticGroup) {
438
+ if (isStaticGroup_) {
439
+ ref_.lock();
440
+ }
441
+ }
442
+
443
+ ~GroupMembershipLockGuard() {
444
+ if (isStaticGroup_) {
445
+ ref_.unlock();
446
+ }
447
+ }
448
+
449
+ GroupMembershipLockGuard(const GroupMembershipLockGuard&) = delete;
450
+
451
+ private:
452
+ std::mutex& ref_;
453
+ bool isStaticGroup_;
454
+ };
455
+ // Mutex to guard access to group membership data
456
+ // e.g. updates to (workerIdToInfo_, workerNameToInfo_, workerNameToURL_)
457
+ mutable std::mutex groupMembershipMutex_;
458
+
459
+ // Map to Track Network Data
460
+ NetworkDataDict networkData_;
461
+ // Mutex to guard networkData_
462
+ std::mutex networkDataMutex_;
463
+
464
+ // A mutex and a cv to guard access to the call counts and watch for changes.
465
+ std::mutex callCountMutex_;
466
+ std::condition_variable callCountCV_;
467
+ // Running total of un-processed, un-errored RPC calls sent
468
+ int32_t clientActiveCalls_{0};
469
+ // Running total of un-processed RPC requests received
470
+ int32_t serverActiveCalls_{0};
471
+ // Running total of RPC requests that will be completed asynchronously
472
+ int32_t serverActiveAsyncCalls_{0};
473
+
474
+ // Whether a global graceful shutdown has begun, in which case we'll silence
475
+ // error messages due to remote workers closing their pipes.
476
+ std::atomic<bool> shuttingDown_{false};
477
+
478
+ // Helpers to modify the counts while correctly dealing with the mutex and cv.
479
+ void increaseCallCount(int32_t& count);
480
+ void decreaseCallCount(int32_t& count);
481
+
482
+ // Helpers to set the state of the requests.
483
+ void markFutureAsComplete(
484
+ std::shared_ptr<AtomicJitFuture> atomicFuture,
485
+ c10::intrusive_ptr<Message> message,
486
+ std::vector<c10::Stream> streams);
487
+ void markFutureWithError(
488
+ std::shared_ptr<AtomicJitFuture> atomicFuture,
489
+ std::string errorMsg);
490
+ };
491
+
492
+ } // namespace torch::distributed::rpc
493
+
494
+ #endif // USE_TENSORPIPE
495
+
496
+ #else
497
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
498
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #ifdef USE_TENSORPIPE
5
+
6
+ #include <torch/csrc/distributed/rpc/utils.h>
7
+
8
+ namespace tensorpipe {
9
+ class Message;
10
+ class Allocation;
11
+ class Descriptor;
12
+ } // namespace tensorpipe
13
+
14
+ namespace torch::distributed::rpc {
15
+
16
+ TORCH_API const c10::Stream& getStreamForDevice(
17
+ const std::vector<c10::Stream>& streams,
18
+ const c10::Device& device);
19
+
20
+ // Inspired by c10/core/impl/DeviceGuardImplInterface.h.
21
+
22
+ class TensorpipeDeviceTypeConverter {
23
+ public:
24
+ // Ideally we'd want this to also return a tensorpipe::Message::Tensor object
25
+ // but we cannot forward-declare that class (because it's nested), and we
26
+ // cannot include the TensorPipe headers because it's a private dependency.
27
+ // Thus we bend over backwards and entrust this method with appending that
28
+ // object to the `tensors` field of the tensorpipe::Message object we pass.
29
+ virtual std::optional<std::vector<char>> prepareTensorForSending(
30
+ const c10::Storage& storage,
31
+ const std::vector<c10::Stream>& streams,
32
+ tensorpipe::Message& message) const = 0;
33
+
34
+ // Same as above: this method cannot return a tensorpipe::Allocation::Tensor,
35
+ // thus it appends it to the `tensors` field of the tensorpipe::Allocation.
36
+ virtual at::DataPtr allocateTensorForReceiving(
37
+ c10::DeviceIndex deviceIndex,
38
+ size_t length,
39
+ const std::vector<c10::Stream>& streams,
40
+ tensorpipe::Allocation& allocation) const = 0;
41
+
42
+ virtual ~TensorpipeDeviceTypeConverter() = default;
43
+ };
44
+
45
+ extern TORCH_API std::array<
46
+ std::atomic<const TensorpipeDeviceTypeConverter*>,
47
+ static_cast<size_t>(DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES)>
48
+ device_type_converter_registry;
49
+
50
+ class TORCH_API TensorpipeDeviceTypeConverterRegistrar {
51
+ public:
52
+ TensorpipeDeviceTypeConverterRegistrar(
53
+ DeviceType /*type*/,
54
+ const TensorpipeDeviceTypeConverter* /*impl*/);
55
+ };
56
+
57
+ #define C10_REGISTER_TENSORPIPE_DEVICE_TYPE_CONVERTER( \
58
+ DevType, TensorpipeDeviceTypeConverter) \
59
+ static ::torch::distributed::rpc::TensorpipeDeviceTypeConverterRegistrar \
60
+ C10_ANONYMOUS_VARIABLE(g_##DeviceType)( \
61
+ ::c10::DeviceType::DevType, new TensorpipeDeviceTypeConverter());
62
+
63
+ inline const TensorpipeDeviceTypeConverter* getDeviceTypeConverter(
64
+ DeviceType type) {
65
+ return device_type_converter_registry[static_cast<size_t>(type)].load();
66
+ }
67
+
68
+ // A struct that holds pointers that keep alive all the memory that will be
69
+ // accessed by TensorPipe during a write operation.
70
+ struct TensorpipeWriteBuffers {
71
+ // Allocate on heap so pointers stay valid as we move the holder.
72
+ std::unique_ptr<MessageType> type;
73
+ std::unique_ptr<int64_t> id;
74
+ std::vector<char> payload;
75
+ std::vector<char> pickle;
76
+ // This contains the original tensors and the clones of the sparse tensors.
77
+ std::vector<torch::Tensor> tensors;
78
+ // This contains the copies of the data of the tensors that didn't own their
79
+ // memory, e.g., the ones created from torch::from_blob() with no deleter.
80
+ std::vector<std::vector<char>> copiedTensors;
81
+ };
82
+
83
+ // A struct that holds pointers that keep alive all the memory that will be
84
+ // accessed by TensorPipe during a read operation.
85
+ struct TensorpipeReadBuffers {
86
+ // Allocate on heap so pointers stay valid as we move the holder.
87
+ std::unique_ptr<MessageType> type;
88
+ std::unique_ptr<int64_t> id;
89
+ std::vector<char> payload;
90
+ std::vector<char> pickle;
91
+ std::vector<c10::DataPtr> tensors;
92
+ };
93
+
94
+ // Convert an RPC message into a TensorPipe message, plus a holder to all the
95
+ // data that must be kept alive while the write is performed asynchronously.
96
+ TORCH_API std::tuple<tensorpipe::Message, TensorpipeWriteBuffers>
97
+ tensorpipeSerialize(
98
+ const c10::intrusive_ptr<Message>& rpcMessage,
99
+ std::vector<c10::Device> devices,
100
+ const std::vector<c10::Stream>& streams);
101
+
102
+ // Allocate the buffers that will hold the incoming data. They will be managed
103
+ // by the returned holder, which must be kept alive until the asynchronous read
104
+ // has finished. Pointers to these buffers will be stored in the returned
105
+ // tensorpipe::Allocation struct.
106
+ TORCH_API std::pair<tensorpipe::Allocation, TensorpipeReadBuffers>
107
+ tensorpipeAllocate(
108
+ const tensorpipe::Descriptor& tpDescriptor,
109
+ const std::vector<c10::Stream>& streams);
110
+
111
+ // Convert a TensorPipe message back into an RPC message. This requires the data
112
+ // to be available and can thus only be performed once the asynchronous read has
113
+ // completed. The holder can be destroyed once this function returns.
114
+ TORCH_API c10::intrusive_ptr<Message> tensorpipeDeserialize(
115
+ const tensorpipe::Descriptor& tpDescriptor,
116
+ TensorpipeReadBuffers&& holder);
117
+
118
+ } // namespace torch::distributed::rpc
119
+
120
+ #endif // USE_TENSORPIPE
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/faulty_tensorpipe_agent.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #ifdef USE_TENSORPIPE
5
+
6
+ #include <torch/csrc/distributed/rpc/message.h>
7
+ #include <torch/csrc/distributed/rpc/tensorpipe_agent.h>
8
+
9
+ namespace torch::distributed::rpc {
10
+
11
+ struct TORCH_API FaultyTensorPipeRpcBackendOptions
12
+ : public TensorPipeRpcBackendOptions {
13
+ FaultyTensorPipeRpcBackendOptions(
14
+ int num_worker_threads,
15
+ float rpc_timeout,
16
+ std::string init_method,
17
+ std::vector<std::string> messages_to_fail,
18
+ std::unordered_map<std::string, float> messages_to_delay,
19
+ int num_fail_sends = 0)
20
+ : TensorPipeRpcBackendOptions(
21
+ num_worker_threads,
22
+ std::optional<std::vector<std::string>>(),
23
+ std::optional<std::vector<std::string>>(),
24
+ rpc_timeout,
25
+ std::move(init_method)),
26
+ messagesToFail(std::move(messages_to_fail)),
27
+ messagesToDelay(std::move(messages_to_delay)),
28
+ numFailSends(num_fail_sends) {
29
+ TORCH_CHECK(numFailSends >= 0, "numFailSends should be non-negative");
30
+ }
31
+
32
+ std::vector<std::string> messagesToFail;
33
+ std::unordered_map<std::string, float> messagesToDelay;
34
+ int numFailSends;
35
+ };
36
+
37
+ class TORCH_API FaultyTensorPipeAgent : public TensorPipeAgent {
38
+ public:
39
+ FaultyTensorPipeAgent(
40
+ const c10::intrusive_ptr<::c10d::Store>& store,
41
+ std::string selfName,
42
+ worker_id_t selfId,
43
+ int worldSize,
44
+ FaultyTensorPipeRpcBackendOptions opts,
45
+ std::unordered_map<std::string, DeviceMap> reverseDeviceMaps,
46
+ std::vector<c10::Device> devices,
47
+ std::unique_ptr<RequestCallback> callback);
48
+
49
+ // Faulty send function for this class.
50
+ c10::intrusive_ptr<JitFuture> send(
51
+ const WorkerInfo& to,
52
+ c10::intrusive_ptr<Message> message,
53
+ const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout,
54
+ const DeviceMap& deviceMap = {}) override;
55
+
56
+ // Add delay to writes
57
+ void pipeWrite(
58
+ const std::shared_ptr<tensorpipe::Pipe>& pipe,
59
+ const c10::intrusive_ptr<Message>& rpcMessage,
60
+ std::vector<c10::Device>&& devices,
61
+ std::vector<c10::Stream> streams,
62
+ std::function<void(const tensorpipe::Error&)> fn) noexcept override;
63
+
64
+ protected:
65
+ // This function checks the messageTypesToFail_ to determine whether to use
66
+ // the faulty send or not.
67
+ bool shouldFailMessage(MessageType type) const;
68
+
69
+ private:
70
+ // This function parses the list of strings passed in by the python tests and
71
+ // resolves the Message Types that must use the faulty send.
72
+ std::vector<MessageType> parseMessagesToFailInput(
73
+ const std::vector<std::string>& messagesToFail) const;
74
+
75
+ // Returns amount of time in seconds to delay sending of the given message
76
+ // type.
77
+ float getDelayForMessage(MessageType type) const;
78
+
79
+ // Parse message types that we should inject arbitrary delays for.
80
+ std::unordered_map<MessageType, float, std::hash<int>> parseMessagesToDelay(
81
+ const std::unordered_map<std::string, float>& messageTypesToDelay) const;
82
+
83
+ // Number of sends to intentionally fail before allowing one to succeed.
84
+ const int numFailSends_;
85
+
86
+ // Vector of the MessageTypes that we must use the faulty send for. This is
87
+ // parsed based on a list of strings passed in by the python tests.
88
+ const std::vector<MessageType> messageTypesToFail_;
89
+
90
+ // Mapping of message types to amount we should delay send for in the ::send()
91
+ // function.
92
+ std::unordered_map<MessageType, float, std::hash<int>> messageTypesToDelay_;
93
+
94
+ // Map to track the number of sends we've failed for each RPC.
95
+ std::unordered_map<std::string, int> failMessageCountMap_;
96
+
97
+ // Mutex to guard failMessageCountMap_
98
+ std::mutex failMapMutex_;
99
+
100
+ MessageType messageStringToType(const std::string& messageString) const;
101
+ };
102
+
103
+ } // namespace torch::distributed::rpc
104
+
105
+ #endif // USE_TENSORPIPE
106
+
107
+ #else
108
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
109
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/testing/testing.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/python_headers.h>
5
+
6
+ namespace torch::distributed::rpc::testing {
7
+
8
+ PyMethodDef* python_functions();
9
+
10
+ } // namespace torch::distributed::rpc::testing
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/ivalue.h>
5
+ #include <torch/csrc/autograd/profiler.h>
6
+ #include <torch/csrc/distributed/autograd/utils.h>
7
+ #include <torch/csrc/distributed/rpc/rref_context.h>
8
+ #include <torch/csrc/distributed/rpc/script_remote_call.h>
9
+
10
+ namespace torch::distributed::rpc {
11
+
12
+ // This function sends an rpc call to run torchscript function, currently the
13
+ // torchscript function could only be a user defined python function with
14
+ // "@torch.jit.script" annotation. The torchscript function could not be
15
+ // a class constructor, class method, instance method or a script module.
16
+ // dst: destination worker name
17
+ // qualifiedName: torchscript function qualified name string like
18
+ // "moduleName::torchscriptFunctionName", e.g,
19
+ // "dist_autograd_test::my_py_add"
20
+ // stack: a bag of IValue args passed to torchscriptFunctionName
21
+ // It returns c10::intrusive_ptr<ivalue::Future>
22
+ c10::intrusive_ptr<c10::ivalue::Future> TORCH_API rpcTorchscript(
23
+ const std::string& dstWorkerName,
24
+ const c10::QualifiedName& qualifiedName,
25
+ const c10::FunctionSchema& functionSchema,
26
+ std::vector<c10::IValue> stack,
27
+ const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout,
28
+ const bool isAsyncExecution = false);
29
+
30
+ c10::intrusive_ptr<RRef> TORCH_API remoteTorchscript(
31
+ const std::string& dstWorkerName,
32
+ const c10::QualifiedName& qualifiedName,
33
+ const c10::FunctionSchema& functionSchema,
34
+ std::vector<c10::IValue>& stack,
35
+ const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout,
36
+ const bool isAsyncExecution = false);
37
+
38
+ } // namespace torch::distributed::rpc
39
+
40
+ #else
41
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
42
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/types.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/core/ivalue.h>
5
+
6
+ namespace torch::distributed::rpc {
7
+
8
+ using worker_id_t = int16_t;
9
+ using local_id_t = int64_t;
10
+
11
+ bool getAllowJitRRefPickle();
12
+ TORCH_API void enableJitRRefPickle();
13
+ TORCH_API void disableJitRRefPickle();
14
+
15
+ struct TORCH_API JitRRefPickleGuard {
16
+ JitRRefPickleGuard();
17
+ JitRRefPickleGuard(JitRRefPickleGuard&& other) = delete;
18
+ JitRRefPickleGuard(const JitRRefPickleGuard&) = delete;
19
+ JitRRefPickleGuard& operator=(const JitRRefPickleGuard&) = delete;
20
+ JitRRefPickleGuard& operator=(JitRRefPickleGuard&&) = delete;
21
+ ~JitRRefPickleGuard();
22
+ };
23
+
24
+ struct TORCH_API GloballyUniqueId final {
25
+ GloballyUniqueId(worker_id_t createdOn, local_id_t localId);
26
+ GloballyUniqueId(const GloballyUniqueId& other) = default;
27
+ GloballyUniqueId& operator=(const GloballyUniqueId& other) = delete;
28
+ GloballyUniqueId(GloballyUniqueId&& other) = default;
29
+ GloballyUniqueId& operator=(GloballyUniqueId&& other) = delete;
30
+ ~GloballyUniqueId() = default;
31
+
32
+ bool operator==(const GloballyUniqueId& other) const;
33
+ bool operator!=(const GloballyUniqueId& other) const;
34
+
35
+ at::IValue toIValue() const;
36
+ static GloballyUniqueId fromIValue(const at::IValue& /*ivalue*/);
37
+
38
+ struct Hash {
39
+ size_t operator()(const GloballyUniqueId& key) const {
40
+ return (uint64_t(key.createdOn_) << kLocalIdBits) | key.localId_;
41
+ }
42
+ };
43
+
44
+ static constexpr int kLocalIdBits = 48;
45
+
46
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
47
+ const worker_id_t createdOn_;
48
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
49
+ const local_id_t localId_;
50
+ };
51
+
52
+ TORCH_API std::ostream& operator<<(
53
+ std::ostream& os,
54
+ const GloballyUniqueId& globalId);
55
+
56
+ using RRefId = GloballyUniqueId;
57
+ using ForkId = GloballyUniqueId;
58
+ using ProfilingId = GloballyUniqueId;
59
+
60
+ struct TORCH_API SerializedPyObj final {
61
+ SerializedPyObj(std::string&& payload, std::vector<at::Tensor>&& tensors)
62
+ : payload_(std::move(payload)), tensors_(std::move(tensors)) {}
63
+
64
+ std::vector<at::IValue> toIValues() &&;
65
+ static SerializedPyObj fromIValues(std::vector<at::IValue> value);
66
+
67
+ std::string payload_;
68
+ std::vector<at::Tensor> tensors_;
69
+ };
70
+
71
+ } // namespace torch::distributed::rpc
72
+
73
+ #else
74
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
75
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
5
+ #include <torch/csrc/distributed/rpc/types.h>
6
+ #include <torch/csrc/utils/pybind.h>
7
+
8
+ namespace torch::distributed::rpc {
9
+
10
+ // This class converts the content in a PythonCall into py::object. This is a
11
+ // helper class to make sure that all arguments deserialization is done before
12
+ // entering RequestCallbackImpl::processRpc(...), so that the deserialization
13
+ // related logic can be carried out in one spot instead of scattered in multiple
14
+ // places for different message types.
15
+ // NB: The reason for not consolidating class into PythonCall is because
16
+ // PythonCall is a libtorch type which should not depend on Python types.
17
+ class TORCH_API UnpickledPythonCall : public RpcCommandBase {
18
+ public:
19
+ UnpickledPythonCall(
20
+ const SerializedPyObj& serializedPyObj,
21
+ bool isAsyncExecution);
22
+ ~UnpickledPythonCall() override;
23
+
24
+ // toMessage() method is not implemented, as objects of this class should
25
+ // never be directly converted into a Message object.
26
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
27
+ const py::object& pythonUdf() const;
28
+
29
+ inline bool isAsyncExecution() const {
30
+ return isAsyncExecution_;
31
+ }
32
+
33
+ private:
34
+ py::object pythonUdf_;
35
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
36
+ const bool isAsyncExecution_;
37
+ };
38
+
39
+ } // namespace torch::distributed::rpc
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
5
+ #include <torch/csrc/distributed/rpc/types.h>
6
+ #include <torch/csrc/distributed/rpc/unpickled_python_call.h>
7
+ #include <torch/csrc/utils/pybind.h>
8
+
9
+ namespace torch::distributed::rpc {
10
+
11
+ // This class converts the content in a PythonRemoteCall into py::object. This
12
+ // is a helper class to make sure that all arguments deserialization is done
13
+ // before entering RequestCallbackImpl::processRpc(...), so that the
14
+ // deserialization related logic can be carried out in one spot instead of
15
+ // scattered in multiple places for different message types.
16
+ // NB: The reason for not consolidating class into PythonRemoteCall is because
17
+ // PythonRemoteCall is a libtorch type which should not depend on Python types.
18
+ class TORCH_API UnpickledPythonRemoteCall final : public UnpickledPythonCall {
19
+ public:
20
+ explicit UnpickledPythonRemoteCall(
21
+ const SerializedPyObj& serializedPyObj,
22
+ const at::IValue& retRRefId,
23
+ const at::IValue& retForkId,
24
+ const bool isAsyncExecution);
25
+
26
+ const RRefId& rrefId() const;
27
+ const ForkId& forkId() const;
28
+
29
+ private:
30
+ RRefId rrefId_;
31
+ ForkId forkId_;
32
+ };
33
+
34
+ } // namespace torch::distributed::rpc
35
+
36
+ #else
37
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
38
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <c10/core/Device.h>
5
+ #include <c10/core/Event.h>
6
+ #include <c10/core/Stream.h>
7
+ #include <torch/csrc/autograd/profiler.h>
8
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
9
+ #include <torch/csrc/jit/serialization/pickle.h>
10
+ #include <torch/csrc/utils/byte_order.h>
11
+
12
+ namespace torch::distributed::rpc {
13
+
14
+ // Parse error message and return RPCErrorType based on the message.
15
+ TORCH_API RPCErrorType getRPCErrorType(const JitFuture& jitFuture);
16
+ // Create an error string given the error description and error type
17
+ TORCH_API std::string makeRPCError(
18
+ const std::string& rpcErrorStr,
19
+ RPCErrorType errorType);
20
+
21
+ // Given an RPC message received as a request over the wire, deserialize it into
22
+ // the appropriate 'RpcCommandBase' type.
23
+ TORCH_API std::unique_ptr<RpcCommandBase> deserializeRequest(
24
+ const Message& request);
25
+
26
+ // Given an RPC message received as a response over the wire, deserialize it
27
+ // into the appropriate 'RpcCommandBase' type, if the response is
28
+ // FORWARD_AUTOGRAD_RESP type, unwrap it, attach recvBackward() functions
29
+ // to received tensors and set the wrappedMsgType to its wrapped message type.
30
+ TORCH_API std::unique_ptr<RpcCommandBase> deserializeResponse(
31
+ const Message& response,
32
+ MessageType& wrappedMsgType);
33
+
34
+ // Given an RPC message received as a response over the wire, deserialize it
35
+ // into the valid IValue if the message is for a script rpc result,
36
+ // otherwise deserialize it into dummy none ivalue that will never be used.
37
+ // In this deserialization, we also attach recv rpc backward functions if
38
+ // needed.
39
+ IValue deserializeResptoIValueInternal(
40
+ RpcCommandBase& rpc,
41
+ MessageType messageType);
42
+ TORCH_API IValue deserializeRespToIValue(const Message& message);
43
+
44
+ // Note: format is subject to change and intended for RPCs.
45
+ // For saving persistently to disk, use torch::save().
46
+ TORCH_API std::string wireSerialize(
47
+ const std::vector<char>& payload,
48
+ const std::vector<at::Tensor>& tensors);
49
+
50
+ TORCH_API std::pair<std::vector<char>, std::vector<at::Tensor>> wireDeserialize(
51
+ const void* data,
52
+ size_t data_size);
53
+
54
+ // We use vector<char> as the type of blobs because it's what rpc::Message uses
55
+ // for its payload, even though it has the disadvantage that it cannot be
56
+ // allocated with uninitialized memory: it is always zeroed out.
57
+
58
+ // Some Tensors are effectively views of larger Tensors, where only a small
59
+ // subset of the Storage data is referenced. This normally is good and avoids
60
+ // copies when kept locally, but if we naively push the whole Storage over the
61
+ // wire, we'll end up with excess network traffic. This change clones tensors if
62
+ // we'd save at least half the data, and over a minimum hurdle.
63
+ TORCH_API c10::List<at::Tensor> cloneSparseTensors(
64
+ const std::vector<at::Tensor>& tensors);
65
+
66
+ // Combines an original payload and wrapped payload into the original payload.
67
+ // Used to generate the overall payload for the wrapped RPC.
68
+ TORCH_API void writeWrappedPayload(
69
+ std::vector<char>& originalPayload,
70
+ std::vector<char>& additionalPayload);
71
+
72
+ // Reads the additional, wrapped payload from a wrapped RPC off of the input
73
+ // payload. After this, payload will contain the payload of the original,
74
+ // un-wrapped RPC.
75
+ TORCH_API std::vector<at::IValue> readWrappedPayload(
76
+ std::vector<char>& payload,
77
+ const rpc::Message& message);
78
+
79
+ // Takes a list of events from autograd profiler and populates them into
80
+ // profiledEvents to be carried over RPC.
81
+ TORCH_API void populateRemoteProfiledEvents(
82
+ std::vector<torch::autograd::profiler::LegacyEvent>& profiledEvents,
83
+ const torch::autograd::profiler::ProfilerConfig& profilerConfig,
84
+ const std::vector<std::vector<torch::autograd::profiler::LegacyEvent>>&
85
+ eventLists);
86
+
87
+ } // namespace torch::distributed::rpc
88
+
89
+ #else
90
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
91
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cache_entry.h ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <Python.h>
5
+
6
+ #ifdef __cplusplus
7
+
8
+ #include <torch/csrc/dynamo/utils.h>
9
+ #include <torch/csrc/utils/pybind.h>
10
+ #include <list>
11
+
12
+ extern "C" {
13
+
14
+ #endif
15
+
16
+ /*
17
+ Our cache resides on the extra scratch space of the code object. The structure
18
+ of the cache is as follows:
19
+
20
+ -> ExtraState
21
+ -> CacheEntry (list)
22
+ -> guard_manager (a wrapper that contains the actual guard manager at its
23
+ attr named root)
24
+ -> code
25
+ -> FrameState
26
+
27
+ CacheEntry is a linked list node containing the guard_manager for guards
28
+ and the optimized code.
29
+
30
+ The FrameState is a PyDict that enables sharing between different frames. This
31
+ is used to detect dynamism in automatic dynamic shapes.
32
+
33
+ These two are encapsulated into a ExtraState.
34
+ */
35
+
36
+ typedef struct CacheEntry CacheEntry;
37
+ typedef struct ExtraState ExtraState;
38
+
39
+ #ifdef __cplusplus
40
+
41
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED(
42
+ "-Wdeprecated-copy-with-user-provided-dtor")
43
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wdeprecated-copy-dtor")
44
+ // NOLINTNEXTLINE(cppcoreguidelines-special-member-functions)
45
+ typedef struct VISIBILITY_HIDDEN CacheEntry {
46
+ // check the guards: lambda: <locals of user function>: bool
47
+ py::object guard_manager;
48
+ // modified user bytecode (protected by guard_manager's guards)
49
+ py::object code;
50
+ // CompileId corresponding to this compilation
51
+ py::object compile_id;
52
+ // root guard manager if exists
53
+ void* root_mgr{nullptr};
54
+ // diff guard root guard manager if exists
55
+ void* diff_guard_root_mgr{nullptr};
56
+ // backend used to create this cache entry
57
+ py::object backend;
58
+ // Reference to owning ExtraState
59
+ ExtraState* _owner{nullptr};
60
+ // Reference to this CacheEntry's location in owner's linked list
61
+ std::list<CacheEntry>::iterator _owner_loc;
62
+ // Reference to string representation of the CompileContext
63
+ std::string trace_annotation;
64
+
65
+ CacheEntry(const py::handle& guarded_code, PyObject* backend);
66
+ CacheEntry(const CacheEntry&) = default;
67
+ CacheEntry(CacheEntry&&) = default;
68
+ CacheEntry& operator=(const CacheEntry&) = default;
69
+ CacheEntry& operator=(CacheEntry&&) = default;
70
+ ~CacheEntry();
71
+
72
+ // Warning: returns a reference whose lifetime is controlled by C++
73
+ py::object next();
74
+
75
+ void invalidate(py::object deleted_guard_manager);
76
+ // Called from the python side to update the diff guard root manager
77
+ void update_diff_guard_root_manager();
78
+ } CacheEntry;
79
+ C10_DIAGNOSTIC_POP()
80
+ C10_DIAGNOSTIC_POP()
81
+
82
+ #endif
83
+
84
+ // Returns borrowed reference
85
+ PyCodeObject* CacheEntry_get_code(CacheEntry* e);
86
+
87
+ // Returns borrowed string representation of CompileContext
88
+ const char* CacheEntry_get_trace_annotation(CacheEntry* e);
89
+
90
+ // Returns a borrowed reference to CacheEntry as a PyObject
91
+ // Warning: lifetime is controlled by C++
92
+ PyObject* CacheEntry_to_obj(CacheEntry* e);
93
+
94
+ #ifdef __cplusplus
95
+ } // extern "C"
96
+ #endif
97
+
98
+ #else
99
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
100
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/compiled_autograd.h ADDED
@@ -0,0 +1,1566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <ATen/TensorGeometry.h>
4
+ #include <ATen/core/ivalue.h>
5
+ #include <c10/core/impl/TorchDispatchModeTLS.h>
6
+ #include <c10/util/flat_hash_map.h>
7
+ #include <torch/csrc/autograd/function.h>
8
+ #include <torch/csrc/autograd/input_metadata.h>
9
+ #include <torch/csrc/autograd/saved_variable.h>
10
+ #include <torch/csrc/autograd/variable_info.h>
11
+ #include <torch/csrc/utils/python_stub.h>
12
+ #include <torch/csrc/utils/torch_dispatch_mode.h>
13
+ #include <typeindex>
14
+ #include <vector>
15
+
16
+ // see [Note: Compiled Autograd]
17
+
18
+ namespace torch::dynamo::autograd {
19
+ using namespace torch::autograd;
20
+
21
+ // This is a layer of indirection for calling methods on the Python
22
+ // AutogradCompilerInstance (referred to as the "py_compiler") from
23
+ // libtorch_cpu (where Python is not available).
24
+ // A PyCompilerInterfaceImpl in libtorch_python subclasses it and
25
+ // overrides the methods to do the actual calls back to Python.
26
+ struct TORCH_API PyCompilerInterface {
27
+ PyCompilerInterface() = default;
28
+ PyCompilerInterface(const PyCompilerInterface&) = delete;
29
+ PyCompilerInterface& operator=(const PyCompilerInterface&) = delete;
30
+ PyCompilerInterface(PyCompilerInterface&&) = delete;
31
+ PyCompilerInterface& operator=(PyCompilerInterface&&) = delete;
32
+ virtual ~PyCompilerInterface() = default;
33
+
34
+ // Invokes py_compiler.bind_function
35
+ virtual std::string bind_function(
36
+ PyObject* py_compiler,
37
+ const std::string& fn_name,
38
+ // NOLINTNEXTLINE(performance-unnecessary-value-param)
39
+ functional_apply_t fn,
40
+ // NOLINTNEXTLINE(performance-unnecessary-value-param)
41
+ std::vector<at::TypePtr> packed_args_schema,
42
+ bool is_custom_function = false,
43
+ bool is_traceable = true) const {
44
+ TORCH_INTERNAL_ASSERT(false, "Needs to be overridden");
45
+ }
46
+
47
+ // Invokes py_compiler.method_name(fn_name, inputs, packed_args,
48
+ // output_metadata)
49
+ virtual variable_list call_function(
50
+ PyObject* py_compiler,
51
+ const char* method_name,
52
+ const std::string& fn_name,
53
+ const variable_list& inputs,
54
+ const ivalue_list& packed_args,
55
+ const c10::IValue& output_metadata) const {
56
+ TORCH_INTERNAL_ASSERT(false, "Needs to be overridden");
57
+ }
58
+ virtual variable_list call_copy_slices_prologue(
59
+ PyObject* py_compiler,
60
+ const variable_list& inputs,
61
+ const at::TensorGeometry& base,
62
+ const at::TensorGeometry& view) const {
63
+ TORCH_INTERNAL_ASSERT(false, "Needs to be overridden");
64
+ }
65
+ virtual variable_list call_copy_slices_epilogue(
66
+ PyObject* py_compiler,
67
+ const std::vector<bool>& needs_input_grad,
68
+ const at::Tensor& result,
69
+ const variable_list& res,
70
+ const at::Tensor& grad_slice) const {
71
+ TORCH_INTERNAL_ASSERT(false, "Needs to be overridden");
72
+ }
73
+ virtual at::Tensor call_unpack(
74
+ PyObject* py_compiler,
75
+ std::optional<size_t> hook_id,
76
+ size_t hook_input_id) const {
77
+ TORCH_INTERNAL_ASSERT(false, "Needs to be overridden");
78
+ }
79
+ virtual void call_accumulate_grad(
80
+ PyObject* py_compiler,
81
+ const at::Tensor& variable,
82
+ const at::Tensor& grad,
83
+ bool has_post_hooks) const {
84
+ TORCH_INTERNAL_ASSERT(false, "Needs to be overridden");
85
+ }
86
+ };
87
+
88
+ TORCH_API const std::unique_ptr<PyCompilerInterface>& getPyCompilerInterface();
89
+ struct TORCH_API PyCompilerGuard {
90
+ explicit PyCompilerGuard(std::unique_ptr<PyCompilerInterface>&& impl);
91
+ PyCompilerGuard(const PyCompilerGuard&) = delete;
92
+ PyCompilerGuard& operator=(const PyCompilerGuard&) = delete;
93
+ PyCompilerGuard(PyCompilerGuard&&) = delete;
94
+ PyCompilerGuard& operator=(PyCompilerGuard&&) = delete;
95
+
96
+ ~PyCompilerGuard();
97
+ };
98
+
99
+ // including torch/csrc/autograd/engine.h breaks BC by somehow introducing
100
+ // symbol resolution issues. Instead requiring downstream users to include
101
+ // engine.h to access collect_input_metadata, we provide it here (with a
102
+ // different name to avoid ambiguous symbols...)
103
+ TORCH_API std::vector<std::optional<InputMetadata>> get_input_metadata(
104
+ const edge_list& edges);
105
+
106
+ struct SizeInput {
107
+ // Note: int value is still needed when dynamic to pass as an arg
108
+ enum DynType : uint8_t { STATIC = 0, DYNAMIC = 1 };
109
+ SizeInput(DynType dt, int64_t v) : dyn_type(dt), value(v) {}
110
+ DynType dyn_type;
111
+ int64_t value;
112
+ };
113
+
114
+ struct CacheKeyBuffer {
115
+ CacheKeyBuffer(const uint8_t* key, uint16_t len) : data(new uint8_t[len]) {
116
+ std::memcpy(data.get(), key, len);
117
+ }
118
+ const uint8_t* get() const {
119
+ return data.get();
120
+ }
121
+
122
+ private:
123
+ // NOLINTNEXTLINE(*c-array*)
124
+ std::unique_ptr<uint8_t[]> data;
125
+ };
126
+
127
+ struct CacheKey {
128
+ // Key to find the next node in the shadow graph. We use C++ RTTI for the
129
+ // type of the node (ntype), then a key generated with a visitor pattern.
130
+ CacheKey(const std::type_index& ntype, const uint8_t* key, uint16_t len)
131
+ : node_type(ntype), key_size(len), key(key) {}
132
+
133
+ bool operator<(const CacheKey& other) const {
134
+ if (node_type != other.node_type) {
135
+ return node_type < other.node_type;
136
+ }
137
+ if (key_size != other.key_size) {
138
+ return key_size < other.key_size;
139
+ }
140
+ return std::memcmp(key, other.key, key_size) < 0;
141
+ }
142
+
143
+ bool operator==(const CacheKey& other) const {
144
+ return node_type == other.node_type && key_size == other.key_size &&
145
+ std::memcmp(key, other.key, key_size) == 0;
146
+ }
147
+
148
+ size_t hash() const {
149
+ // don't bother hashing the key data, common case 1 cache entry per node
150
+ return std::hash<std::type_index>()(node_type) ^ key_size;
151
+ }
152
+
153
+ std::type_index node_type;
154
+ uint16_t key_size;
155
+ const uint8_t* key;
156
+ };
157
+
158
+ struct NodeCall {
159
+ NodeCall(uint32_t id_, std::shared_ptr<Node> node_)
160
+ : id(id_), node(std::move(node_)) {}
161
+
162
+ void mark_output(int input_nr, int output_idx) {
163
+ graph_output.emplace_back(input_nr, output_idx);
164
+ }
165
+
166
+ uint32_t id;
167
+ std::shared_ptr<Node> node;
168
+ std::vector<std::pair<int, int>> tensor_pre_hooks;
169
+ std::vector<std::pair<int, int>> cpp_tensor_pre_hooks;
170
+ std::vector<int> pre_hooks;
171
+ std::vector<int> post_hooks;
172
+ std::vector<int> post_acc_grad_hooks;
173
+ std::vector<std::pair<int, int>> graph_output;
174
+ bool needed = true;
175
+ };
176
+
177
+ struct NodeCalls : public std::unordered_map<Node*, NodeCall> {
178
+ NodeCall& lookup(const std::shared_ptr<Node>& function) {
179
+ auto it = find(function.get());
180
+ if (it == end()) {
181
+ it = emplace(function.get(), NodeCall(_next_id++, function)).first;
182
+ nodes.emplace_back(function.get());
183
+ }
184
+ return it->second;
185
+ }
186
+
187
+ const NodeCall& lookup(uint32_t id) const {
188
+ TORCH_INTERNAL_ASSERT(id < nodes.size());
189
+ auto it = find(nodes[id]);
190
+ TORCH_INTERNAL_ASSERT(it != end());
191
+ return it->second;
192
+ }
193
+
194
+ void clear() {
195
+ _next_id = 0;
196
+ std::unordered_map<Node*, NodeCall>::clear();
197
+ nodes.clear();
198
+ }
199
+
200
+ private:
201
+ uint32_t _next_id = 0;
202
+ std::vector<Node*> nodes;
203
+ };
204
+
205
+ struct TensorArg {
206
+ // Represents a de-duplicated tensor that will be passed into the graph
207
+ TensorArg(uint32_t i = 0) : id(i) {}
208
+ uint32_t index() const {
209
+ TORCH_INTERNAL_ASSERT(defined());
210
+ return id - 1;
211
+ }
212
+ bool defined() const {
213
+ return id != 0;
214
+ }
215
+ uint32_t id;
216
+ at::Tensor proxy_tensor;
217
+ };
218
+
219
+ struct TensorArgs {
220
+ // Manages a collection of TensorArgs and mappings from Tensors/SavedVariables
221
+ // to them. This also allows us to unpack SavedVariable exactly once and
222
+ // store the unpacked Tensor.
223
+ TensorArgs(const std::optional<size_t>& active_node_call_idx)
224
+ : active_node_call_idx(active_node_call_idx) {}
225
+
226
+ TensorArg& lookup(const at::Tensor& tensor, bool create = false) {
227
+ if (!tensor.defined()) {
228
+ return _undefined;
229
+ }
230
+ auto impl = tensor.unsafeGetTensorImpl();
231
+ auto it = _args.find(impl);
232
+ if (it == _args.end()) {
233
+ TORCH_INTERNAL_ASSERT(create && inputs.size() == _next_id - 1);
234
+ it = _args.emplace(impl, TensorArg(_next_id++)).first;
235
+ inputs.emplace_back(tensor);
236
+ if (active_node_call_idx.has_value()) {
237
+ input_origins.emplace_back(active_node_call_idx.value());
238
+ }
239
+ }
240
+ return it->second;
241
+ }
242
+
243
+ TensorArg& lookup(const SavedVariable& sv) {
244
+ if (auto it = _saved_variables.find(&sv); it != _saved_variables.end()) {
245
+ // unpacked before graph
246
+ return *it->second;
247
+ }
248
+ // unpacked in graph
249
+ auto it2 = _saved_variables_proxies.find(&sv);
250
+ TORCH_INTERNAL_ASSERT(it2 != _saved_variables_proxies.end());
251
+ return *it2->second;
252
+ }
253
+
254
+ TensorArg& add(const at::Tensor& tensor) {
255
+ return lookup(tensor, true);
256
+ }
257
+
258
+ TensorArg& add(const SavedVariable& sv, const std::shared_ptr<Node>& node) {
259
+ // no unpack hooks in this codepath
260
+ at::Tensor tensor = sv.unpack(node);
261
+ TensorArg& arg = add(tensor);
262
+ _saved_variables.emplace(&sv, &arg);
263
+ return arg;
264
+ }
265
+
266
+ // the concrete tensors that will get passed into the graph as inputs
267
+ std::vector<at::Tensor> inputs;
268
+ // NodeCall id of each input, only when verbose logging is enabled
269
+ std::vector<uint32_t> input_origins;
270
+
271
+ private:
272
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
273
+ const std::optional<size_t>& active_node_call_idx;
274
+ std::unordered_map<const c10::TensorImpl*, TensorArg> _args;
275
+ // Every TensorArg from this is actually owned by _args (or _undefined) and
276
+ // that's why we have an un-owned pointer here.
277
+ std::unordered_map<const SavedVariable*, TensorArg*> _saved_variables;
278
+ std::unordered_map<const SavedVariable*, TensorArg*> _saved_variables_proxies;
279
+ TensorArg _undefined;
280
+ uint32_t _next_id = 1; // id=0 used by _undefined
281
+ };
282
+
283
+ struct LiftedIValueArg {
284
+ LiftedIValueArg() = delete;
285
+ LiftedIValueArg(const at::IValue* ptr)
286
+ : actual_ptr(ptr), proxy(at::IValue::uninitialized()) {}
287
+
288
+ const at::IValue* actual_ptr; // lifetime handled by autograd node
289
+ at::IValue proxy;
290
+ };
291
+
292
+ struct LiftedIValueArgs {
293
+ LiftedIValueArgs(const std::optional<size_t>& active_node_call_idx)
294
+ : active_node_call_idx(active_node_call_idx) {}
295
+
296
+ at::IValue& next_proxy(const at::IValue* actual_ptr) {
297
+ TORCH_INTERNAL_ASSERT(next < args.size());
298
+ auto& iv_arg = args.at(next++);
299
+ TORCH_INTERNAL_ASSERT(iv_arg.actual_ptr == actual_ptr);
300
+ return iv_arg.proxy;
301
+ }
302
+
303
+ void add(const at::IValue* iv) {
304
+ args.emplace_back(iv);
305
+ if (active_node_call_idx.has_value()) {
306
+ args_origins.emplace_back(active_node_call_idx.value());
307
+ }
308
+ }
309
+
310
+ std::vector<LiftedIValueArg> args;
311
+ size_t next = 0;
312
+ // NodeCall id of each arg, only when verbose logging is enabled
313
+ std::vector<uint32_t> args_origins;
314
+
315
+ private:
316
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
317
+ const std::optional<size_t>& active_node_call_idx;
318
+ };
319
+
320
+ struct AutogradCompilerCall {
321
+ AutogradCompilerCall(SizeInput::DynType default_dyn_type)
322
+ : active_node_call_idx(std::nullopt),
323
+ tensor_args(active_node_call_idx),
324
+ lifted_ivalue_args(active_node_call_idx),
325
+ default_dyn_type(default_dyn_type) {}
326
+ void add_size_input(const c10::SymInt& s) {
327
+ all_size_inputs.emplace_back(
328
+ default_dyn_type, s.guard_int(__FILE__, __LINE__));
329
+ if (active_node_call_idx.has_value()) {
330
+ size_input_origins.emplace_back(active_node_call_idx.value());
331
+ }
332
+ }
333
+
334
+ size_t emplace_hook(c10::SafePyObject&& fn) {
335
+ hooks.emplace_back(std::move(fn));
336
+ return hooks.size() - 1;
337
+ }
338
+
339
+ size_t emplace_cpp_tensor_pre_hook(
340
+ std::function<at::TensorBase(const at::TensorBase&)>&& fn) {
341
+ cpp_tensor_pre_hooks.emplace_back(std::move(fn));
342
+ return cpp_tensor_pre_hooks.size() - 1;
343
+ }
344
+
345
+ size_t emplace_packed_input(c10::SafePyObject&& input) {
346
+ packed_inputs.emplace_back(std::move(input));
347
+ return packed_inputs.size() - 1;
348
+ }
349
+
350
+ void set_active_node_call_idx(size_t node_call_idx) {
351
+ active_node_call_idx = node_call_idx;
352
+ }
353
+
354
+ std::optional<size_t> active_node_call_idx;
355
+ TensorArgs tensor_args;
356
+ std::vector<SizeInput> all_size_inputs;
357
+ LiftedIValueArgs lifted_ivalue_args;
358
+ std::vector<int64_t> dyn_size_inputs;
359
+ std::vector<c10::SafePyObject> hooks;
360
+ std::vector<std::function<at::TensorBase(const at::TensorBase&)>>
361
+ cpp_tensor_pre_hooks;
362
+ std::vector<c10::SafePyObject> packed_inputs;
363
+ NodeCalls node_calls;
364
+ SizeInput::DynType default_dyn_type;
365
+ // NodeCall id of each size, only when verbose logging is enabled
366
+ std::vector<uint32_t> size_input_origins;
367
+ std::unordered_map<const SavedVariable*, std::pair<size_t, size_t>>
368
+ sv_to_hooks;
369
+ // pynode -> backward and backward state idx
370
+ std::unordered_map<const Node*, std::pair<size_t, std::optional<size_t>>>
371
+ pynode_objs;
372
+ };
373
+
374
+ class CompiledNodeArgs {
375
+ // CompiledNodeArgs builds a representation of the constant values found
376
+ // across all the nodes in the compiled graph, via 'collect' overloads. The
377
+ // collected constants are specialized on by concatenation into a cache key.
378
+ // Tensor, symint arguments (which are lifted to become graph inputs rather
379
+ // than specialized on) are forwarded to the compiler and not included in the
380
+ // key.
381
+ public:
382
+ void collect(const TensorArg& t) {
383
+ collect_size(t.id);
384
+ if (t.defined()) {
385
+ const at::Tensor& tensor = _compiler.tensor_args.inputs[t.index()];
386
+ // including these in the cache key means dynamo-level tensor guards can
387
+ // be skipped
388
+ collect(tensor.device());
389
+ collect(tensor.dtype());
390
+ collect(tensor.requires_grad());
391
+ }
392
+ }
393
+
394
+ void collect(const at::Tensor& t) {
395
+ collect(_compiler.tensor_args.add(t));
396
+ }
397
+ void collect(const SavedVariable& sv, bool is_output) {
398
+ if (auto hook_data = sv.retrieve_unpack_hook_data();
399
+ hook_data.has_value()) {
400
+ // hooks, unpack in graph
401
+ auto& [hook, packed_input] = hook_data.value();
402
+ size_t hook_id = _compiler.emplace_hook(std::move(hook));
403
+ // rely on dynamo to dedup packed tensors from unpacked tensors
404
+ size_t input_id = _compiler.emplace_packed_input(std::move(packed_input));
405
+ _compiler.sv_to_hooks.emplace(&sv, std::make_pair(hook_id, input_id));
406
+ } else {
407
+ // no hooks, unpack now
408
+ collect(
409
+ _compiler.tensor_args.add(sv, is_output ? _node_call.node : nullptr));
410
+ }
411
+ }
412
+ void collect(const c10::SymInt& t) {
413
+ _compiler.add_size_input(t);
414
+ }
415
+ void collect(const std::vector<SavedVariable>& t, bool is_output) {
416
+ collect_size(t.size());
417
+ for (const SavedVariable& i : t) {
418
+ collect(i, is_output);
419
+ }
420
+ }
421
+ template <typename T>
422
+ void collect(const std::vector<T>& t) {
423
+ collect_size(t.size());
424
+ for (const T& i : t) {
425
+ collect(i);
426
+ }
427
+ }
428
+ void collect(const c10::ArrayRef<SavedVariable>& t, bool is_output) {
429
+ collect_size(t.size());
430
+ for (const SavedVariable& i : t) {
431
+ collect(i, is_output);
432
+ }
433
+ }
434
+ template <typename T>
435
+ void collect(const c10::ArrayRef<T>& t) {
436
+ collect_size(t.size());
437
+ for (const T& i : t) {
438
+ collect(i);
439
+ }
440
+ }
441
+ template <typename T>
442
+ void collect(const c10::OptionalArray<T>& t) {
443
+ collect(t.list);
444
+ }
445
+ template <typename T>
446
+ void collect(const std::optional<T>& t) {
447
+ if (cond(t.has_value())) {
448
+ // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
449
+ collect(*t);
450
+ }
451
+ }
452
+ template <typename A, typename B>
453
+ void collect(const std::pair<A, B>& t) {
454
+ collect(t.first);
455
+ collect(t.second);
456
+ }
457
+ template <typename V>
458
+ void collect(const ska::flat_hash_map<std::string, V>& m) {
459
+ collect_size(m.size());
460
+
461
+ std::vector<std::string> keys;
462
+ keys.reserve(m.size());
463
+ std::transform(
464
+ m.begin(), m.end(), std::back_inserter(keys), [](const auto& entry) {
465
+ return entry.first;
466
+ });
467
+ std::sort(keys.begin(), keys.end());
468
+ for (const auto& k : keys) {
469
+ collect(k);
470
+ collect(m.at(k));
471
+ }
472
+ }
473
+ void collect(const at::IValue& iv, bool nested = false) {
474
+ // used by AutogradContext::saved_data from CppNode
475
+ if (iv.isList()) {
476
+ c10::List<at::IValue> list = iv.toList();
477
+ collect_size(list.size());
478
+ for (auto&& value : list) {
479
+ collect(value, true);
480
+ }
481
+ } else if (iv.isGenericDict()) {
482
+ c10::Dict<at::IValue, at::IValue> ordered_dict = iv.toGenericDict();
483
+ collect_size(ordered_dict.size());
484
+ // NOLINTNEXTLINE(modernize-loop-convert)
485
+ for (auto it = ordered_dict.begin(); it != ordered_dict.end(); it++) {
486
+ collect(it->key());
487
+ collect(it->value(), true);
488
+ }
489
+ } else if (iv.isTensor()) {
490
+ collect(iv.toTensor());
491
+ } else if (
492
+ !nested &&
493
+ (iv.isInt() || iv.isSymInt() || iv.isDouble() || iv.isSymFloat())) {
494
+ // can't lift ivalues nested in collections
495
+ _compiler.lifted_ivalue_args.add(&iv);
496
+ } else {
497
+ try {
498
+ collect(static_cast<uint64_t>(at::IValue::hash(iv)));
499
+ } catch (const std::runtime_error& e) {
500
+ std::string msg =
501
+ "Compiled autograd can not trace unhashable IValues, error: " +
502
+ std::string(e.what());
503
+ TORCH_CHECK_NOT_IMPLEMENTED(false, msg);
504
+ }
505
+ }
506
+ }
507
+ void collect(const c10::Scalar& t) {
508
+ auto type = t.type();
509
+ specialize_on_bytes(type);
510
+ if (type == c10::ScalarType::Double) {
511
+ collect(t.toDouble());
512
+ } else if (type == c10::ScalarType::Long) {
513
+ collect(t.toLong());
514
+ } else if (type == c10::ScalarType::Bool) {
515
+ collect(t.toBool());
516
+ } else if (type == c10::ScalarType::ComplexDouble) {
517
+ auto c = t.toComplexDouble();
518
+ collect(c.real());
519
+ collect(c.imag());
520
+ } else {
521
+ TORCH_INTERNAL_ASSERT(false);
522
+ }
523
+ }
524
+ void collect(const c10::TensorOptions& t) {
525
+ collect(t.device());
526
+ collect(t.dtype());
527
+ collect(t.layout());
528
+ collect(t.requires_grad());
529
+ collect(t.pinned_memory());
530
+ collect(t.memory_format_opt());
531
+ }
532
+ void collect(const at::TensorGeometry& t) {
533
+ collect(t.sym_sizes());
534
+ collect(t.sym_strides());
535
+ collect(t.sym_storage_offset());
536
+ }
537
+ void collect(const torch::autograd::TypeAndSize& t) {
538
+ collect(t.sym_sizes);
539
+ collect(t.options);
540
+ }
541
+ void collect(const c10::Device& t) {
542
+ collect(t.type());
543
+ collect(t.index());
544
+ }
545
+ void collect(const std::string& t) {
546
+ collect_size(t.size());
547
+ for (char c : t) {
548
+ collect(c);
549
+ }
550
+ }
551
+ void collect(const caffe2::TypeMeta& t) {
552
+ specialize_on_bytes(t.id());
553
+ }
554
+ void collect(const std::shared_ptr<Node>& t) {
555
+ // Note: this is only capturing the ID of the node not everything
556
+ // contained inside it. This is used for tracking connections between
557
+ // nodes and the actual details of the node itself must be handled by
558
+ // a separate call to `node->compiled_args()`.
559
+ if (cond((bool)t)) {
560
+ collect(_compiler.node_calls.lookup(t));
561
+ }
562
+ }
563
+ void collect(const NodeCall& t) {
564
+ collect_size(t.id);
565
+ collect(t.graph_output);
566
+ collect_hooks_from(t.node.get());
567
+ }
568
+ void collect(const Edge& t) {
569
+ if (cond(t.is_valid())) {
570
+ collect_size(_compiler.node_calls.lookup(t.function).id);
571
+ collect_size(t.input_nr);
572
+ collect(t.function->input_metadata(t.input_nr)); // for validate_outputs
573
+ }
574
+ }
575
+ void collect(const InputMetadata& t) {
576
+ TORCH_CHECK_NOT_IMPLEMENTED(
577
+ !t.is_nested_tensor(), "NestedTensor support not implemented. ");
578
+ collect(t.options());
579
+ collect(t.is_tensor_subclass());
580
+ collect(t.shape_as_dim_vector());
581
+ }
582
+ void collect(const VariableInfo& t) {
583
+ collect(t.layout);
584
+ collect(t.device);
585
+ collect(t.scalar_type);
586
+ collect(t.size);
587
+ collect(t.requires_grad);
588
+ collect(t.is_empty);
589
+ }
590
+ bool cond(bool cond) {
591
+ collect(cond);
592
+ return cond;
593
+ }
594
+
595
+ #define COLLECT_AS_BYTES(T) \
596
+ void collect(T t) { \
597
+ specialize_on_bytes(t); \
598
+ }
599
+ COLLECT_AS_BYTES(c10::ScalarType)
600
+ COLLECT_AS_BYTES(c10::DeviceType)
601
+ COLLECT_AS_BYTES(c10::Layout)
602
+ COLLECT_AS_BYTES(c10::MemoryFormat)
603
+ COLLECT_AS_BYTES(int8_t)
604
+ COLLECT_AS_BYTES(int16_t)
605
+ COLLECT_AS_BYTES(int32_t)
606
+ COLLECT_AS_BYTES(int64_t)
607
+ COLLECT_AS_BYTES(uint8_t)
608
+ COLLECT_AS_BYTES(uint16_t)
609
+ COLLECT_AS_BYTES(uint32_t)
610
+ COLLECT_AS_BYTES(uint64_t)
611
+ COLLECT_AS_BYTES(bool)
612
+ COLLECT_AS_BYTES(float)
613
+ COLLECT_AS_BYTES(double)
614
+ #undef COLLECT_AS_BYTES
615
+
616
+ void collect_hooks_from(Node* fn) {
617
+ for (auto& i : fn->tensor_pre_hooks()) {
618
+ i->compiled_args(*this);
619
+ }
620
+ for (auto& [_, i] : fn->retains_grad_hooks()) {
621
+ i->compiled_args(*this);
622
+ }
623
+ for (auto& i : fn->pre_hooks()) {
624
+ i->compiled_args(*this);
625
+ }
626
+ for (auto& i : fn->post_hooks()) {
627
+ i->compiled_args(*this);
628
+ }
629
+ collect_size(_node_call.tensor_pre_hooks.size());
630
+ collect_size(_node_call.pre_hooks.size());
631
+ collect_size(_node_call.post_hooks.size());
632
+ for (const auto& h : _node_call.tensor_pre_hooks) {
633
+ collect_size(static_cast<size_t>(h.second));
634
+ }
635
+ }
636
+
637
+ CacheKey key() const {
638
+ Node* node = _node_call.node.get();
639
+ return CacheKey(
640
+ typeid(*node), _specialization_key, _specialization_key_size);
641
+ }
642
+
643
+ void collect_pynode_objs(
644
+ const Node* pynode,
645
+ c10::SafePyObject&& bwd,
646
+ std::optional<c10::SafePyObject>&& bwd_state) {
647
+ size_t bwd_idx = _compiler.emplace_hook(std::move(bwd));
648
+ std::optional<size_t> bwd_state_idx;
649
+ if (auto state = std::move(bwd_state); state.has_value()) {
650
+ bwd_state_idx = _compiler.emplace_hook(std::move(state.value()));
651
+ }
652
+ _compiler.pynode_objs.emplace(
653
+ pynode, std::make_pair(bwd_idx, bwd_state_idx));
654
+ }
655
+
656
+ void add_tensor_pre_hook(c10::SafePyObject&& obj, int index) {
657
+ auto fn_id = _compiler.emplace_hook(std::move(obj));
658
+ collect_size(fn_id);
659
+ _node_call.tensor_pre_hooks.emplace_back(fn_id, index);
660
+ }
661
+
662
+ void add_cpp_single_tensor_pre_hook(
663
+ const std::function<at::TensorBase(const at::TensorBase&)>& hook,
664
+ size_t idx) {
665
+ auto wrapper = [hook](const at::TensorBase& grad) {
666
+ // handle when hook returns nothing
667
+ auto out = hook(grad);
668
+ if (!out.defined()) {
669
+ return grad;
670
+ }
671
+ return out;
672
+ };
673
+
674
+ auto hook_id = _compiler.emplace_cpp_tensor_pre_hook(std::move(wrapper));
675
+ collect_size(hook_id);
676
+ _node_call.cpp_tensor_pre_hooks.emplace_back(hook_id, idx);
677
+ }
678
+
679
+ void add_pre_hook(c10::SafePyObject&& obj) {
680
+ auto fn_id = _compiler.emplace_hook(std::move(obj));
681
+ collect_size(fn_id);
682
+ _node_call.pre_hooks.emplace_back(fn_id);
683
+ }
684
+
685
+ void add_post_hook(c10::SafePyObject&& obj) {
686
+ auto fn_id = _compiler.emplace_hook(std::move(obj));
687
+ collect_size(fn_id);
688
+ _node_call.post_hooks.emplace_back(fn_id);
689
+ }
690
+
691
+ void add_post_acc_grad_hook(c10::SafePyObject&& obj) {
692
+ auto fn_id = _compiler.emplace_hook(std::move(obj));
693
+ collect_size(fn_id);
694
+ _node_call.post_acc_grad_hooks.emplace_back(fn_id);
695
+ }
696
+
697
+ // Need to template the size_t to silence internal 32-bit build errors due to
698
+ // a mix of -Werror, -Wtautological-type-limit-compare and
699
+ // -Wunknown-pragmas
700
+ template <typename T>
701
+ std::enable_if_t<std::is_unsigned_v<T>, void> collect_size(T s) {
702
+ // we expect sizes to be small, so try to cram them into a single byte
703
+ constexpr uint8_t encode_as_u64 = std::numeric_limits<uint8_t>::max();
704
+ constexpr uint8_t encode_as_u32 = encode_as_u64 - 1;
705
+ constexpr uint8_t encode_as_u16 = encode_as_u64 - 2;
706
+ if (C10_UNLIKELY(s >= encode_as_u16)) {
707
+ // first write a byte indicating the path we followed, then the data
708
+ if (s <= std::numeric_limits<uint16_t>::max()) {
709
+ // 3 bytes
710
+ specialize_on_bytes(encode_as_u16);
711
+ specialize_on_bytes(static_cast<uint16_t>(s));
712
+ } else if (s <= std::numeric_limits<uint32_t>::max()) {
713
+ // 5 bytes
714
+ specialize_on_bytes(encode_as_u32);
715
+ specialize_on_bytes(static_cast<uint32_t>(s));
716
+ } else {
717
+ // 9 bytes
718
+ specialize_on_bytes(encode_as_u64);
719
+ specialize_on_bytes(s);
720
+ }
721
+ } else {
722
+ // happy case, 1 byte
723
+ specialize_on_bytes(static_cast<uint8_t>(s));
724
+ }
725
+ }
726
+
727
+ SizeInput::DynType set_default_dyn_type(SizeInput::DynType default_dyn_type) {
728
+ return std::exchange(_compiler.default_dyn_type, default_dyn_type);
729
+ }
730
+
731
+ CompiledNodeArgs(AutogradCompilerCall& compiler, NodeCall& node_call)
732
+ : _compiler(compiler),
733
+ _node_call(node_call),
734
+ _specialization_key(
735
+ // NOLINTNEXTLINE(cppcoreguidelines-no-malloc)
736
+ (uint8_t*)std::malloc(_specialization_key_storage)) {}
737
+ CompiledNodeArgs(const CompiledNodeArgs&) = delete;
738
+ CompiledNodeArgs(CompiledNodeArgs&&) = delete;
739
+ CompiledNodeArgs& operator=(const CompiledNodeArgs&) = delete;
740
+ CompiledNodeArgs& operator=(CompiledNodeArgs&&) = delete;
741
+ ~CompiledNodeArgs() {
742
+ // NOLINTNEXTLINE(cppcoreguidelines-no-malloc)
743
+ std::free(_specialization_key);
744
+ }
745
+
746
+ private:
747
+ template <typename T>
748
+ void specialize_on_bytes(const T& t) {
749
+ while (C10_UNLIKELY(
750
+ _specialization_key_size + sizeof(T) > _specialization_key_storage)) {
751
+ _specialization_key_storage *= 2;
752
+ // NOLINTNEXTLINE(cppcoreguidelines-no-malloc)
753
+ _specialization_key = (uint8_t*)std::realloc(
754
+ _specialization_key, _specialization_key_storage);
755
+ }
756
+ std::memcpy(_specialization_key + _specialization_key_size, &t, sizeof(T));
757
+ _specialization_key_size += sizeof(T);
758
+ }
759
+
760
+ AutogradCompilerCall& _compiler;
761
+ NodeCall& _node_call;
762
+ size_t _specialization_key_size{0};
763
+ size_t _specialization_key_storage{1024};
764
+ uint8_t* _specialization_key;
765
+ };
766
+
767
+ struct TraceState {
768
+ TraceState(std::vector<std::optional<c10::SymInt>>&& ss, size_t num_outputs)
769
+ : sym_sizes(std::move(ss)), outputs(num_outputs) {}
770
+
771
+ void debug_asserts() {
772
+ TORCH_INTERNAL_ASSERT(sym_sizes_index == sym_sizes.size());
773
+ }
774
+ std::optional<c10::SymInt> next_sym_size() {
775
+ TORCH_INTERNAL_ASSERT(sym_sizes_index < sym_sizes.size());
776
+ return sym_sizes[sym_sizes_index++];
777
+ }
778
+
779
+ size_t sym_sizes_index{0};
780
+ std::vector<std::optional<c10::SymInt>> sym_sizes;
781
+ variable_list outputs;
782
+ };
783
+
784
+ class SwapSavedVariables {
785
+ // SwapSavedVariables is used during the tracing/compilation phase after a
786
+ // cache-miss. It swaps any 'lifted' inputs (tensors, symints) to proxy nodes,
787
+ // allows tracing to happen, then swaps them back afterwards.
788
+ public:
789
+ std::pair<size_t, std::optional<size_t>> retrieve_pynode_objs(
790
+ Node* pynode) const {
791
+ auto it = compiler.pynode_objs.find(pynode);
792
+ TORCH_INTERNAL_ASSERT(it != compiler.pynode_objs.end());
793
+ return it->second;
794
+ }
795
+
796
+ void before(at::Tensor& t) {
797
+ TensorArg& arg = compiler.tensor_args.lookup(t);
798
+ stashed_tensors.save(&t, std::move(t));
799
+ if (arg.defined()) {
800
+ TORCH_INTERNAL_ASSERT(arg.proxy_tensor.defined());
801
+ t = arg.proxy_tensor;
802
+ }
803
+ }
804
+ void after(at::Tensor& t) {
805
+ stashed_tensors.restore(&t);
806
+ }
807
+
808
+ void before(SavedVariable& t) {
809
+ if (auto it = compiler.sv_to_hooks.find(&t);
810
+ it != compiler.sv_to_hooks.end()) {
811
+ const auto& pyinterface =
812
+ torch::dynamo::autograd::getPyCompilerInterface();
813
+ auto proxy_tensor = pyinterface->call_unpack(
814
+ get_py_compiler(), it->second.first, it->second.second);
815
+ stashed_variables.save(&t, std::move(t));
816
+ bool prior = at::SavedTensorDefaultHooks::set_tracing(true);
817
+ t = SavedVariable(proxy_tensor, false);
818
+ at::SavedTensorDefaultHooks::set_tracing(prior);
819
+ } else {
820
+ // no hooks, was already unpacked
821
+ TensorArg& arg = compiler.tensor_args.lookup(t);
822
+ stashed_variables.save(&t, std::move(t));
823
+ if (arg.defined()) {
824
+ bool prior = at::SavedTensorDefaultHooks::set_tracing(true);
825
+ TORCH_INTERNAL_ASSERT(arg.proxy_tensor.defined());
826
+ t = SavedVariable(arg.proxy_tensor, false);
827
+ at::SavedTensorDefaultHooks::set_tracing(prior);
828
+ }
829
+ }
830
+ }
831
+ void after(SavedVariable& t) {
832
+ stashed_variables.restore(&t);
833
+ }
834
+
835
+ void before(c10::SymInt& t) {
836
+ stashed_symints.save(&t, c10::SymInt(t));
837
+ auto opt_value = state.next_sym_size();
838
+ if (opt_value.has_value()) {
839
+ t = *opt_value; // dynamic shape
840
+ }
841
+ }
842
+ void after(c10::SymInt& t) {
843
+ stashed_symints.restore(&t);
844
+ }
845
+
846
+ void before(at::IValue& iv) {
847
+ if (iv.isTensor()) {
848
+ before(iv.toTensor());
849
+ } else {
850
+ stashed_ivalues.save(&iv, at::IValue(iv));
851
+ if (iv.isInt() || iv.isSymInt() || iv.isDouble() || iv.isSymFloat()) {
852
+ iv = compiler.lifted_ivalue_args.next_proxy(&iv);
853
+ }
854
+ }
855
+ }
856
+
857
+ void after(at::IValue& t) {
858
+ if (t.isTensor()) {
859
+ after(t.toTensor());
860
+ } else {
861
+ stashed_ivalues.restore(&t);
862
+ }
863
+ }
864
+
865
+ void before(Edge& t) {
866
+ if (t.is_valid()) {
867
+ // need for symints used by validate_outputs
868
+ before(t.function->mutable_input_metadata(t.input_nr));
869
+ }
870
+ }
871
+ void after(Edge& t) {
872
+ if (t.is_valid()) {
873
+ after(t.function->mutable_input_metadata(t.input_nr));
874
+ }
875
+ }
876
+ void before(InputMetadata& t) {
877
+ before(t.mutable_shape_as_dim_vector());
878
+ }
879
+ void after(InputMetadata& t) {
880
+ after(t.mutable_shape_as_dim_vector());
881
+ }
882
+ void before(at::TensorGeometry& t) {
883
+ before(t.mutable_sizes());
884
+ before(t.mutable_strides());
885
+ before(t.mutable_storage_offset());
886
+ t.recompute();
887
+ }
888
+ void after(at::TensorGeometry& t) {
889
+ after(t.mutable_sizes());
890
+ after(t.mutable_strides());
891
+ after(t.mutable_storage_offset());
892
+ t.recompute();
893
+ }
894
+ void before(torch::autograd::TypeAndSize& t) {
895
+ before(t.sym_sizes);
896
+ before(t.options);
897
+ }
898
+ void after(torch::autograd::TypeAndSize& t) {
899
+ after(t.sym_sizes);
900
+ after(t.options);
901
+ }
902
+ void before(VariableInfo& t) {
903
+ before(t.size);
904
+ }
905
+ void after(VariableInfo& t) {
906
+ after(t.size);
907
+ }
908
+
909
+ template <typename T>
910
+ void before(std::vector<T>& t) {
911
+ for (T& i : t) {
912
+ before(i);
913
+ }
914
+ }
915
+ template <typename T>
916
+ void after(std::vector<T>& t) {
917
+ for (T& i : t) {
918
+ after(i);
919
+ }
920
+ }
921
+ template <typename T, unsigned N>
922
+ void before(c10::SmallVector<T, N>& t) {
923
+ for (T& i : t) {
924
+ before(i);
925
+ }
926
+ }
927
+ template <typename T, unsigned N>
928
+ void after(c10::SmallVector<T, N>& t) {
929
+ for (T& i : t) {
930
+ after(i);
931
+ }
932
+ }
933
+
934
+ template <typename T>
935
+ void before(c10::OptionalArray<T>& t) {
936
+ before(t.list);
937
+ }
938
+ template <typename T>
939
+ void after(c10::OptionalArray<T>& t) {
940
+ after(t.list);
941
+ }
942
+
943
+ template <typename T>
944
+ void before(std::optional<T>& t) {
945
+ if (t.has_value()) {
946
+ before(*t);
947
+ }
948
+ }
949
+ template <typename T>
950
+ void after(std::optional<T>& t) {
951
+ if (t.has_value()) {
952
+ after(*t);
953
+ }
954
+ }
955
+
956
+ template <typename V>
957
+ void before(ska::flat_hash_map<std::string, V>& m) {
958
+ std::vector<std::string> keys;
959
+ keys.reserve(m.size());
960
+ std::transform(
961
+ m.begin(), m.end(), std::back_inserter(keys), [](const auto& entry) {
962
+ return entry.first;
963
+ });
964
+ std::sort(keys.begin(), keys.end());
965
+ for (auto& k : keys) {
966
+ before(m.at(k));
967
+ }
968
+ }
969
+
970
+ template <typename V>
971
+ void after(ska::flat_hash_map<std::string, V>& m) {
972
+ for (auto& [_, v] : m) {
973
+ after(v);
974
+ }
975
+ }
976
+
977
+ #define NO_OP_VISIT(T) \
978
+ void before(const T&) {} \
979
+ void after(const T&) {}
980
+ NO_OP_VISIT(caffe2::TypeMeta)
981
+ NO_OP_VISIT(c10::Device)
982
+ NO_OP_VISIT(c10::DeviceType)
983
+ NO_OP_VISIT(c10::Layout)
984
+ NO_OP_VISIT(c10::MemoryFormat)
985
+ NO_OP_VISIT(c10::ScalarType)
986
+ NO_OP_VISIT(c10::Scalar)
987
+ NO_OP_VISIT(c10::TensorOptions)
988
+ NO_OP_VISIT(std::string)
989
+ NO_OP_VISIT(int64_t)
990
+ NO_OP_VISIT(bool)
991
+ NO_OP_VISIT(double)
992
+ #undef NO_OP_VISIT
993
+
994
+ SwapSavedVariables(
995
+ AutogradCompilerCall& c,
996
+ TraceState& s,
997
+ PyObject* p,
998
+ const NodeCall& n)
999
+ : compiler(c), state(s), py_compiler(p), curr_node_call(n) {}
1000
+
1001
+ PyObject* get_py_compiler() const {
1002
+ return py_compiler;
1003
+ }
1004
+
1005
+ const NodeCall& get_curr_node_call() {
1006
+ return curr_node_call;
1007
+ }
1008
+
1009
+ void debug_asserts() {
1010
+ stashed_variables.debug_assert();
1011
+ stashed_tensors.debug_assert();
1012
+ stashed_symints.debug_assert();
1013
+ }
1014
+
1015
+ private:
1016
+ template <typename T>
1017
+ struct Stashed {
1018
+ Stashed(T&& v) : prior_value(std::move(v)) {}
1019
+ T prior_value;
1020
+ // Note: we need count here to support duplicate calls to before()
1021
+ // which happen when we have multiple autograd::Edge objects pointing
1022
+ // to the same autograd::Node
1023
+ int count = 1;
1024
+ };
1025
+
1026
+ template <typename T>
1027
+ struct StashedVars : public std::unordered_map<const T*, Stashed<T>> {
1028
+ void save(const T* key, T&& value) {
1029
+ auto [it, inserted] = this->try_emplace(key, std::move(value));
1030
+ if (!inserted) {
1031
+ // keep the value from the prior save()
1032
+ it->second.count++;
1033
+ }
1034
+ }
1035
+ void restore(T* var) {
1036
+ auto it = this->find(var);
1037
+ TORCH_INTERNAL_ASSERT(it != this->end(), "missing before())");
1038
+ if (--it->second.count == 0) {
1039
+ // restore the value on the last restore()
1040
+ *var = std::move(it->second.prior_value);
1041
+ this->erase(it);
1042
+ }
1043
+ }
1044
+ void debug_assert() {
1045
+ TORCH_INTERNAL_ASSERT(this->empty(), "missing call to after()");
1046
+ }
1047
+ };
1048
+
1049
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
1050
+ AutogradCompilerCall& compiler;
1051
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
1052
+ TraceState& state;
1053
+ // This is a borrowed reference, we do not increment ownership, or lower it,
1054
+ // it's lifecycle is entirely longer than this objects.
1055
+ PyObject* py_compiler;
1056
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
1057
+ const NodeCall& curr_node_call;
1058
+
1059
+ // These mappings are used to save the prior values when we overwrite things
1060
+ // in before(). In after(), we use these to cleanup after ourselves.
1061
+ StashedVars<SavedVariable> stashed_variables;
1062
+ StashedVars<at::Tensor> stashed_tensors;
1063
+ StashedVars<c10::SymInt> stashed_symints;
1064
+ StashedVars<at::IValue> stashed_ivalues;
1065
+ };
1066
+
1067
+ // NOTE: [Compiled Autograd and backward functions]
1068
+ // Built-in autograd nodes have functional apply variants
1069
+ // (e.g. MulBackward0_apply_functional). Compiled Autograd's initial graph
1070
+ // capture wants to take a variant of this function and proxy it into the graph.
1071
+ // Every autograd node defines an apply_with_saved function, that when invoked,
1072
+ // proxies a call to a function into the Compiled Autograd graph.
1073
+ //
1074
+ // Some requirements that we have are:
1075
+ // - The proxy'ed function must have inputs that are FX-graphable types.
1076
+ // - Windows has a DLL symbol limit of 65536.
1077
+ // - Node::apply_with_saved is in libtorch_cpu which does not have direct access
1078
+ // to Python
1079
+ //
1080
+ // There were multiple ways to skin the cat, but what we end up doing is:
1081
+ // - for e.g. MulBackward0_apply_functional, we create a new C++ function
1082
+ // MulBackward0_apply_functional_ivalue that accepts vector<IValue>.
1083
+ // - We define how to pack and unpack arbitrary C++ types into IValues.
1084
+ // - apply_with_saved passes MulBackward0_apply_functional_ivalue and
1085
+ // the IValue arguments to Python via an indirection.
1086
+ // In Python, these get proxy'ed into a graph.
1087
+
1088
+ // Helper struct for packing/unpacking an arbitrary C++ type into a single
1089
+ // IValue. There are various full and partial specializations for IValuePacker
1090
+ // to handle packing specific types (like TensorOptions) into an IValue.
1091
+ template <typename T>
1092
+ struct IValuePacker {
1093
+ // Defines how to pack T into an IValue.
1094
+ static at::IValue pack(const T& t) {
1095
+ return t;
1096
+ }
1097
+ // Defines how to unpack an IValue into T.
1098
+ static T unpack(const at::IValue& t) {
1099
+ return t.to<T>();
1100
+ }
1101
+ // Returns the TypePtr for the IValue (this is like the "type" of the IValue).
1102
+ // We use this when passing the packed IValue from Python to C++.
1103
+ // In Python, the IValue is just a PyObject* with the native type.
1104
+ // For example, it may be a Python int, a Python List[int], etc.
1105
+ // When passing this PyObject* into C++, we need to know how to parse it
1106
+ // into a C++ type that then gets put into an IValue.
1107
+ // That's what the TypePtr is for: it contains the information to do the
1108
+ // parsing. See torch::jit::toIValue for more information.
1109
+ static at::TypePtr packed_type() {
1110
+ // On windows CPU is support compiled autograd.
1111
+ #if defined(_WIN32) && (defined(USE_CUDA) || defined(USE_ROCM))
1112
+ // NB: the if-constexpr usage triggers compilation errors on Windows
1113
+ // with certain compiler settings
1114
+ // (see https://github.com/pytorch/pytorch/pull/144707 for examples).
1115
+ // It's not clear what the problem is, so we're going to ignore it for now.
1116
+ TORCH_CHECK_NOT_IMPLEMENTED(
1117
+ false, "torch.compile not supported on Windows");
1118
+ #else
1119
+ if constexpr (::std::is_same_v<T, at::Tensor>) {
1120
+ return at::TensorType::get();
1121
+ } else if constexpr (::std::is_same_v<T, int64_t>) {
1122
+ return at::IntType::get();
1123
+ } else if constexpr (::std::is_same_v<T, c10::SymInt>) {
1124
+ return at::SymIntType::get();
1125
+ } else if constexpr (::std::is_same_v<T, bool>) {
1126
+ return at::BoolType::get();
1127
+ } else if constexpr (::std::is_same_v<T, double>) {
1128
+ return at::FloatType::get();
1129
+ } else if constexpr (::std::is_same_v<T, c10::SymFloat>) {
1130
+ return at::SymFloatType::get();
1131
+ } else if constexpr (::std::is_same_v<T, c10::SymBool>) {
1132
+ return at::SymBoolType::get();
1133
+ } else if constexpr (::std::is_same_v<T, c10::Layout>) {
1134
+ return at::LayoutType::get();
1135
+ } else if constexpr (::std::is_same_v<T, ::std::string>) {
1136
+ return at::StringType::get();
1137
+ } else if constexpr (::std::is_same_v<T, at::Device>) {
1138
+ return at::DeviceObjType::get();
1139
+ } else if constexpr (::std::is_same_v<T, at::Scalar>) {
1140
+ return at::NumberType::get();
1141
+ } else if constexpr (::std::is_same_v<T, at::MemoryFormat>) {
1142
+ return at::MemoryFormatType::get();
1143
+ } else if constexpr (::std::is_same_v<T, at::ScalarType>) {
1144
+ return at::ScalarTypeType::get();
1145
+ } else {
1146
+ // If you got here, you have probably added a member of a new type
1147
+ // to a built-in C++ autograd node.
1148
+ // Unfortunately, we don't know how to handle this type yet.
1149
+ // To get this new type to work with Compiled Autograd, please
1150
+ // either change it to be an IValue-constructible type, or
1151
+ // define how to pack and unpack an object of this time into an IValue
1152
+ // by creating a specialization of IValuePacker for this type.
1153
+ // See NOTE: [Compiled Autograd and backward functions] for context.
1154
+ TORCH_CHECK_NOT_IMPLEMENTED(
1155
+ false, "IValuePacker not implemented for type");
1156
+ return at::NoneType::get();
1157
+ }
1158
+ #endif
1159
+ }
1160
+ };
1161
+
1162
+ template <>
1163
+ struct IValuePacker<size_t> {
1164
+ static at::IValue pack(const size_t& t) {
1165
+ // We generally use size_t as the size of a list of Tensors or number of
1166
+ // dimensions. The number of dimensions generally do not exceed 64
1167
+ // (TensorIterator has that limitation), and lists of Tensors generally do
1168
+ // not exceed the int64_t max (you'd probably run out of RAM or run into
1169
+ // significant Tensor overhead). If you run into this limitation the fix is
1170
+ // to figure out how to pack size_t into int64_t. Note that size_t has some
1171
+ // weird behavior on Mac OS.
1172
+ uint64_t maximum_value = std::numeric_limits<int64_t>::max();
1173
+ TORCH_INTERNAL_ASSERT(
1174
+ static_cast<uint64_t>(t) <= maximum_value,
1175
+ "size_t too large to pack into IValue");
1176
+ return static_cast<int64_t>(t); // pack as int64_t
1177
+ }
1178
+ static size_t unpack(const at::IValue& t) {
1179
+ return static_cast<size_t>(t.toInt());
1180
+ }
1181
+ static at::TypePtr packed_type() {
1182
+ return IValuePacker<int64_t>::packed_type();
1183
+ }
1184
+ };
1185
+
1186
+ template <>
1187
+ struct IValuePacker<std::vector<at::SymInt>> {
1188
+ static at::IValue pack(const std::vector<at::SymInt>& t) {
1189
+ return t;
1190
+ }
1191
+ static std::vector<at::SymInt> unpack(const at::IValue& t) {
1192
+ // We need this because there's no t.to<std::vector<at::SymInt>>() override?
1193
+ return t.toSymIntVector();
1194
+ }
1195
+ static at::TypePtr packed_type() {
1196
+ return at::ListType::create(at::SymIntType::get());
1197
+ }
1198
+ };
1199
+
1200
+ template <>
1201
+ struct IValuePacker<VariableInfo> {
1202
+ static at::IValue pack(const VariableInfo& t) {
1203
+ auto tuple = std::make_tuple(
1204
+ t.layout, t.device, t.scalar_type, t.size, t.requires_grad, t.is_empty);
1205
+ return tuple;
1206
+ }
1207
+ static VariableInfo unpack(const at::IValue& t) {
1208
+ auto tuple = t.toTuple();
1209
+ const auto& tuple_elements = tuple->elements();
1210
+ const auto elements = tuple_elements.asArrayRef();
1211
+ TORCH_INTERNAL_ASSERT(elements.size() == 6);
1212
+ VariableInfo v;
1213
+ v.layout = elements[0].toLayout();
1214
+ v.device = elements[1].toDevice();
1215
+ v.scalar_type = elements[2].toScalarType();
1216
+ v.size = elements[3].toSymIntVector();
1217
+ v.requires_grad = elements[4].toBool();
1218
+ v.is_empty = elements[5].toBool();
1219
+ return v;
1220
+ }
1221
+ static at::TypePtr packed_type() {
1222
+ return at::TupleType::create({
1223
+ at::LayoutType::get(),
1224
+ at::DeviceObjType::get(),
1225
+ at::ScalarTypeType::get(),
1226
+ at::ListType::create(at::SymIntType::get()),
1227
+ at::BoolType::get(),
1228
+ at::BoolType::get(),
1229
+ });
1230
+ }
1231
+ };
1232
+
1233
+ template <>
1234
+ struct IValuePacker<caffe2::TypeMeta> {
1235
+ static at::IValue pack(const caffe2::TypeMeta& t) {
1236
+ return at::typeMetaToScalarType(t); // pack as at::ScalarType
1237
+ }
1238
+ static caffe2::TypeMeta unpack(const at::IValue& t) {
1239
+ return caffe2::TypeMeta::fromScalarType(t.to<at::ScalarType>());
1240
+ }
1241
+ static at::TypePtr packed_type() {
1242
+ return IValuePacker<at::ScalarType>::packed_type();
1243
+ }
1244
+ };
1245
+
1246
+ inline std::optional<at::ScalarType> optTypeMetaToScalarType(
1247
+ const std::optional<caffe2::TypeMeta>& t) {
1248
+ if (t.has_value()) {
1249
+ return at::typeMetaToScalarType(t.value());
1250
+ } else {
1251
+ return std::nullopt;
1252
+ }
1253
+ }
1254
+
1255
+ using packed_tensoroptions_t = std::tuple<
1256
+ std::optional<bool>,
1257
+ std::optional<at::MemoryFormat>,
1258
+ std::optional<at::Device>,
1259
+ std::optional<at::ScalarType>,
1260
+ std::optional<at::Layout>,
1261
+ std::optional<bool>>;
1262
+
1263
+ inline packed_tensoroptions_t pack_TensorOptions(const at::TensorOptions& t) {
1264
+ auto tuple = std::make_tuple(
1265
+ t.requires_grad_opt(),
1266
+ t.memory_format_opt(),
1267
+ t.device_opt(),
1268
+ optTypeMetaToScalarType(t.dtype_opt()),
1269
+ t.layout_opt(),
1270
+ t.pinned_memory_opt());
1271
+ return tuple;
1272
+ }
1273
+ inline at::TensorOptions unpack_TensorOptions(
1274
+ const packed_tensoroptions_t& tuple) {
1275
+ at::TensorOptions result;
1276
+ auto maybe_requires_grad = std::get<0>(tuple);
1277
+ if (maybe_requires_grad.has_value()) {
1278
+ result = result.requires_grad(maybe_requires_grad);
1279
+ }
1280
+ auto maybe_memory_format = std::get<1>(tuple);
1281
+ if (maybe_memory_format.has_value()) {
1282
+ result = result.memory_format(maybe_memory_format);
1283
+ }
1284
+ auto maybe_device = std::get<2>(tuple);
1285
+ if (maybe_device.has_value()) {
1286
+ result = result.device(maybe_device.value());
1287
+ }
1288
+ auto maybe_dtype = std::get<3>(tuple);
1289
+ if (maybe_dtype.has_value()) {
1290
+ result =
1291
+ result.dtype(caffe2::TypeMeta::fromScalarType(maybe_dtype.value()));
1292
+ }
1293
+ auto maybe_layout = std::get<4>(tuple);
1294
+ if (maybe_layout.has_value()) {
1295
+ result = result.layout(maybe_layout);
1296
+ }
1297
+ auto maybe_pinned_memory = std::get<5>(tuple);
1298
+ if (maybe_pinned_memory.has_value()) {
1299
+ result = result.pinned_memory(maybe_pinned_memory);
1300
+ }
1301
+ return result;
1302
+ }
1303
+
1304
+ template <>
1305
+ struct IValuePacker<at::TensorOptions> {
1306
+ static at::IValue pack(const at::TensorOptions& t) {
1307
+ return pack_TensorOptions(t);
1308
+ }
1309
+ static at::TensorOptions unpack(const at::IValue& t) {
1310
+ auto tuple = t.to<packed_tensoroptions_t>();
1311
+ return unpack_TensorOptions(tuple);
1312
+ }
1313
+ static at::TypePtr packed_type() {
1314
+ return at::TupleType::create(
1315
+ {at::OptionalType::create(at::BoolType::get()),
1316
+ at::OptionalType::create(at::MemoryFormatType::get()),
1317
+ at::OptionalType::create(at::DeviceObjType::get()),
1318
+ at::OptionalType::create(at::ScalarTypeType::get()),
1319
+ at::OptionalType::create(at::LayoutType::get()),
1320
+ at::OptionalType::create(at::BoolType::get())});
1321
+ }
1322
+ };
1323
+
1324
+ template <>
1325
+ struct IValuePacker<TypeAndSize> {
1326
+ static at::IValue pack(const TypeAndSize& t) {
1327
+ auto tuple = std::make_tuple(t.sym_sizes, pack_TensorOptions(t.options));
1328
+ return tuple;
1329
+ }
1330
+ static TypeAndSize unpack(const at::IValue& t) {
1331
+ auto tuple =
1332
+ t.to<std::tuple<std::vector<at::SymInt>, packed_tensoroptions_t>>();
1333
+ TypeAndSize result;
1334
+ result.sym_sizes = std::get<0>(tuple);
1335
+ result.options = unpack_TensorOptions(std::get<1>(tuple));
1336
+ return result;
1337
+ }
1338
+ static at::TypePtr packed_type() {
1339
+ return at::TupleType::create(
1340
+ {IValuePacker<std::vector<at::SymInt>>::packed_type(),
1341
+ IValuePacker<at::TensorOptions>::packed_type()});
1342
+ }
1343
+ };
1344
+
1345
+ template <typename T>
1346
+ struct IValuePacker<std::optional<T>> {
1347
+ static at::IValue pack(const std::optional<T>& t) {
1348
+ if (t.has_value()) {
1349
+ return IValuePacker<T>::pack(t.value());
1350
+ } else {
1351
+ return std::nullopt;
1352
+ }
1353
+ }
1354
+ static std::optional<T> unpack(const at::IValue& t) {
1355
+ if (t.isNone()) {
1356
+ return std::nullopt;
1357
+ } else {
1358
+ return IValuePacker<T>::unpack(t);
1359
+ }
1360
+ }
1361
+ static at::TypePtr packed_type() {
1362
+ return at::OptionalType::create(IValuePacker<T>::packed_type());
1363
+ }
1364
+ };
1365
+
1366
+ template <typename T>
1367
+ struct IValuePacker<std::vector<T>> {
1368
+ static at::IValue pack(const std::vector<T>& t) {
1369
+ if constexpr (::std::is_constructible_v<at::IValue, T>) {
1370
+ return t;
1371
+ }
1372
+ if (t.empty()) {
1373
+ auto lst = c10::impl::GenericList(at::AnyType::get());
1374
+ return lst;
1375
+ }
1376
+ auto type_ptr = IValuePacker<T>::pack(t[0]).type();
1377
+ auto lst = c10::impl::GenericList(type_ptr);
1378
+ for (const auto& elt : t) {
1379
+ lst.emplace_back(IValuePacker<T>::pack(elt));
1380
+ }
1381
+ return lst;
1382
+ }
1383
+ static std::vector<T> unpack(const at::IValue& t) {
1384
+ if constexpr (::std::is_constructible_v<at::IValue, T>) {
1385
+ return t.to<::std::vector<T>>();
1386
+ }
1387
+ std::vector<T> result;
1388
+ auto lst = t.toList();
1389
+ for (size_t i = 0; i < lst.size(); ++i) {
1390
+ const at::IValue& elt = lst.get(i);
1391
+ result.emplace_back(IValuePacker<T>::unpack(elt));
1392
+ }
1393
+ return result;
1394
+ }
1395
+ static at::TypePtr packed_type() {
1396
+ return at::ListType::create(IValuePacker<T>::packed_type());
1397
+ }
1398
+ };
1399
+
1400
+ template <typename T>
1401
+ struct IValuePacker<c10::List<T>> {
1402
+ static at::IValue pack(const c10::List<T>& t) {
1403
+ return IValuePacker<std::vector<T>>::pack(t.vec());
1404
+ }
1405
+ static c10::List<T> unpack(const at::IValue& t) {
1406
+ return c10::List<T>(IValuePacker<std::vector<T>>::unpack(t));
1407
+ }
1408
+ static at::TypePtr packed_type() {
1409
+ return IValuePacker<std::vector<T>>::packed_type();
1410
+ }
1411
+ };
1412
+
1413
+ template <size_t N>
1414
+ struct IValuePacker<std::array<bool, N>> {
1415
+ static at::IValue pack(const std::array<bool, N>& t) {
1416
+ std::vector<bool> result(t.begin(), t.end());
1417
+ return IValuePacker<std::vector<bool>>::pack(result);
1418
+ }
1419
+ static std::array<bool, N> unpack(const at::IValue& t) {
1420
+ std::array<bool, N> result;
1421
+ auto packed = IValuePacker<std::vector<bool>>::unpack(t);
1422
+ for (size_t i = 0; i < packed.size(); i++) {
1423
+ result[i] = packed[i];
1424
+ }
1425
+ return result;
1426
+ }
1427
+ static at::TypePtr packed_type() {
1428
+ return IValuePacker<std::vector<bool>>::packed_type();
1429
+ }
1430
+ };
1431
+
1432
+ template <>
1433
+ struct IValuePacker<at::TensorGeometry> {
1434
+ static at::IValue pack(const at::TensorGeometry& t) {
1435
+ auto tuple = std::make_tuple(
1436
+ t.sym_sizes().vec(), t.sym_strides().vec(), t.sym_storage_offset());
1437
+ return tuple;
1438
+ }
1439
+ static at::TensorGeometry unpack(const at::IValue& t) {
1440
+ auto tuple = t.to<std::tuple<
1441
+ std::vector<at::SymInt>,
1442
+ std::vector<at::SymInt>,
1443
+ at::SymInt>>();
1444
+ return at::TensorGeometry(
1445
+ std::get<0>(tuple), std::get<1>(tuple), std::get<2>(tuple));
1446
+ }
1447
+ static at::TypePtr packed_type() {
1448
+ return at::TupleType::create(
1449
+ {IValuePacker<std::vector<at::SymInt>>::packed_type(),
1450
+ IValuePacker<std::vector<at::SymInt>>::packed_type(),
1451
+ at::SymIntType::get()});
1452
+ }
1453
+ };
1454
+
1455
+ template <>
1456
+ struct IValuePacker<InputMetadata> {
1457
+ static at::IValue pack(const InputMetadata& t) {
1458
+ TORCH_INTERNAL_ASSERT(!t.is_nested_tensor());
1459
+ auto tuple = std::make_tuple(
1460
+ pack_TensorOptions(t.options()),
1461
+ t.shape_as_dim_vector().vec(),
1462
+ t.is_tensor_subclass(),
1463
+ t.grad_dtype());
1464
+ return tuple;
1465
+ }
1466
+ static InputMetadata unpack(const at::IValue& t) {
1467
+ auto tuple = t.to<std::tuple<
1468
+ packed_tensoroptions_t,
1469
+ std::vector<at::SymInt>,
1470
+ bool,
1471
+ std::optional<c10::ScalarType>>>();
1472
+
1473
+ return InputMetadata(
1474
+ unpack_TensorOptions(std::get<0>(tuple)),
1475
+ SymIntSmallVec(std::get<1>(tuple)),
1476
+ std::get<2>(tuple),
1477
+ false,
1478
+ std::get<3>(tuple));
1479
+ }
1480
+ static at::TypePtr packed_type() {
1481
+ return at::TupleType::create(
1482
+ {IValuePacker<at::TensorOptions>::packed_type(),
1483
+ IValuePacker<std::vector<at::SymInt>>::packed_type(),
1484
+ at::BoolType::get(),
1485
+ IValuePacker<std::optional<at::ScalarType>>::packed_type()});
1486
+ }
1487
+ };
1488
+
1489
+ template <typename T>
1490
+ struct IValuePacker<at::OptionalArray<T>> {
1491
+ static at::IValue pack(const at::OptionalArray<T>& t) {
1492
+ return IValuePacker<std::optional<std::vector<T>>>::pack(t.list);
1493
+ }
1494
+ static at::OptionalArray<T> unpack(const at::IValue& t) {
1495
+ auto result = IValuePacker<std::optional<std::vector<T>>>::unpack(t);
1496
+ if (result.has_value()) {
1497
+ return {result.value()};
1498
+ } else {
1499
+ return {};
1500
+ }
1501
+ }
1502
+ static at::TypePtr packed_type() {
1503
+ return IValuePacker<std::optional<std::vector<T>>>::packed_type();
1504
+ }
1505
+ };
1506
+
1507
+ // This is a helper struct for packing and unpacking multiple arguments into
1508
+ // an ivalue_list. It leverages IValuePacker<T>.
1509
+ struct PackedArgs {
1510
+ PackedArgs() = default;
1511
+
1512
+ explicit PackedArgs(std::vector<at::IValue> stack_)
1513
+ : stack(std::move(stack_)) {}
1514
+
1515
+ const std::vector<at::IValue>& vec() const {
1516
+ return stack;
1517
+ }
1518
+
1519
+ template <typename T>
1520
+ void pack(const T& t) {
1521
+ stack.emplace_back(IValuePacker<T>::pack(t));
1522
+ }
1523
+ template <typename T>
1524
+ T unpack() {
1525
+ return IValuePacker<T>::unpack(std::move(stack[idx++]));
1526
+ }
1527
+
1528
+ void pack_saved_data(const ska::flat_hash_map<std::string, at::IValue>& dct) {
1529
+ std::vector<std::string> keys;
1530
+ std::vector<at::IValue> values;
1531
+ for (const auto& [key, value] : dct) {
1532
+ keys.emplace_back(key);
1533
+ values.emplace_back(value);
1534
+ }
1535
+ pack(keys);
1536
+ for (const auto& value : values) {
1537
+ pack(value);
1538
+ }
1539
+ }
1540
+
1541
+ ska::flat_hash_map<std::string, at::IValue> unpack_saved_data() {
1542
+ ska::flat_hash_map<std::string, at::IValue> dct;
1543
+ auto keys = unpack<std::vector<std::string>>();
1544
+ for (const auto& key : keys) {
1545
+ dct.insert({key, std::move(stack[idx++])});
1546
+ }
1547
+ return dct;
1548
+ }
1549
+
1550
+ private:
1551
+ std::vector<at::IValue> stack;
1552
+ int64_t idx = 0;
1553
+ };
1554
+
1555
+ } // namespace torch::dynamo::autograd
1556
+
1557
+ template <>
1558
+ struct std::hash<torch::dynamo::autograd::CacheKey> {
1559
+ size_t operator()(const torch::dynamo::autograd::CacheKey& k) const {
1560
+ return k.hash();
1561
+ }
1562
+ };
1563
+
1564
+ #else
1565
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
1566
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpp_shim.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #ifdef __cplusplus
5
+ extern "C" {
6
+ #endif
7
+
8
+ struct _PytorchRecordFunctionState;
9
+ typedef struct _PytorchRecordFunctionState _PytorchRecordFunctionState;
10
+
11
+ _PytorchRecordFunctionState* _pytorch_record_function_enter(const char* name);
12
+ void _pytorch_record_function_exit(_PytorchRecordFunctionState* state);
13
+
14
+ #ifdef __cplusplus
15
+ } // extern "C"
16
+ #endif
17
+
18
+ #else
19
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
20
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_defs.h ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/utils/python_compat.h>
5
+
6
+ // Functions that need to be copied from the CPython source
7
+ // should go in cpython_defs.c. Copying is required when, e.g.,
8
+ // we need to call internal CPython functions that are not exposed.
9
+
10
+ #if IS_PYTHON_3_11_PLUS
11
+
12
+ typedef struct _PyInterpreterFrame _PyInterpreterFrame;
13
+
14
+ PyFunctionObject* _PyFunction_CopyWithNewCode(
15
+ PyFunctionObject* o,
16
+ PyCodeObject* code);
17
+
18
+ void THP_PyFrame_Clear(_PyInterpreterFrame* frame);
19
+
20
+ _PyInterpreterFrame* THP_PyThreadState_BumpFramePointerSlow(
21
+ PyThreadState* tstate,
22
+ size_t size);
23
+
24
+ void THP_PyThreadState_PopFrame(
25
+ PyThreadState* tstate,
26
+ _PyInterpreterFrame* frame);
27
+
28
+ #endif
29
+
30
+ // pointers to _PyOpcode_Caches for C++
31
+ #ifdef __cplusplus
32
+ extern "C" {
33
+ #endif
34
+
35
+ extern const uint8_t* THP_PyOpcode_Caches;
36
+ extern int THP_PyOpcode_Caches_size;
37
+ void init_THPCaches();
38
+
39
+ #ifdef __cplusplus
40
+ } // extern "C"
41
+ #endif
42
+
43
+ #else
44
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
45
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/cpython_includes.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/utils/python_compat.h>
5
+
6
+ // Problem in CPython includes when mixing core and non-core build
7
+ // The fix was not backported to 3.12 so this is needed here
8
+ // https://github.com/python/cpython/issues/105268
9
+ #if IS_PYTHON_3_12_PLUS
10
+ #undef _PyGC_FINALIZED
11
+ #endif
12
+
13
+ // see https://bugs.python.org/issue35886
14
+ #define Py_BUILD_CORE
15
+
16
+ #ifndef __cplusplus
17
+ // C-only headers
18
+ #include <internal/pycore_pystate.h>
19
+
20
+ #endif // __cplusplus
21
+
22
+ #if IS_PYTHON_3_11_PLUS
23
+ #include <internal/pycore_frame.h>
24
+
25
+ #include <torch/csrc/dynamo/stackref_bridge.h>
26
+ #if IS_PYTHON_3_14_PLUS && !defined(_WIN32)
27
+ #include <internal/pycore_code.h>
28
+ #include <internal/pycore_genobject.h>
29
+ #include <internal/pycore_interpframe.h>
30
+ #include <internal/pycore_stackref.h>
31
+ #elif IS_PYTHON_3_14_PLUS && defined(_WIN32)
32
+ #include <internal/pycore_interpframe_structs.h> // _PyInterpreterFrame
33
+ #endif
34
+
35
+ #endif
36
+
37
+ #undef Py_BUILD_CORE
38
+
39
+ #ifdef __cplusplus
40
+ extern "C" {
41
+ #endif
42
+
43
+ #if IS_PYTHON_3_14_PLUS
44
+
45
+ #define F_CODE(x) \
46
+ ((PyCodeObject*)THP_PyStackRef_AsPyObjectBorrow(&(x)->f_executable))
47
+ #define PREV_INSTR(x) (x)->instr_ptr
48
+
49
+ #else
50
+
51
+ #if IS_PYTHON_3_13_PLUS
52
+ #define F_CODE(x) ((PyCodeObject*)(x)->f_executable)
53
+ #define PREV_INSTR(x) (x)->instr_ptr
54
+ #else
55
+ #define F_CODE(x) ((PyCodeObject*)(x)->f_code)
56
+ #define PREV_INSTR(x) (x)->prev_instr
57
+ #endif // IS_PYTHON_3_13_PLUS
58
+
59
+ #endif // IS_PYTHON_3_14_PLUS
60
+
61
+ #if IS_PYTHON_3_14_PLUS
62
+ #define FUNC(x) \
63
+ ((PyFunctionObject*)THP_PyStackRef_AsPyObjectBorrow(&(x)->f_funcobj))
64
+ #elif IS_PYTHON_3_12_PLUS
65
+ #define FUNC(x) ((PyFunctionObject*)(x)->f_funcobj)
66
+ #else
67
+ #define FUNC(x) ((PyFunctionObject*)(x)->f_func)
68
+ #endif
69
+
70
+ #ifdef __cplusplus
71
+ } // extern "C"
72
+ #endif
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/debug_macros.h ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/utils/python_compat.h>
5
+
6
+ #ifdef __cplusplus
7
+ #include <cstdio>
8
+ #else
9
+ #include <stdio.h>
10
+ #endif
11
+
12
+ #ifdef __cplusplus
13
+ extern "C" {
14
+ #endif
15
+
16
+ #ifdef _WIN32
17
+ #define unlikely(x) (x)
18
+ #else
19
+ #define unlikely(x) __builtin_expect((x), 0)
20
+ #endif
21
+
22
+ #define NULL_CHECK(val) \
23
+ if (unlikely((val) == NULL)) { \
24
+ fprintf(stderr, "NULL ERROR: %s:%d\n", __FILE__, __LINE__); \
25
+ PyErr_Print(); \
26
+ abort(); \
27
+ } else { \
28
+ }
29
+
30
+ // CHECK might be previously declared
31
+ #undef CHECK
32
+ #define CHECK(cond) \
33
+ if (unlikely(!(cond))) { \
34
+ fprintf(stderr, "DEBUG CHECK FAILED: %s:%d\n", __FILE__, __LINE__); \
35
+ abort(); \
36
+ } else { \
37
+ }
38
+
39
+ // Uncomment next line to print debug message
40
+ // #define TORCHDYNAMO_DEBUG 1
41
+ #ifdef TORCHDYNAMO_DEBUG
42
+
43
+ #define DEBUG_CHECK(cond) CHECK(cond)
44
+ #define DEBUG_NULL_CHECK(val) NULL_CHECK(val)
45
+ #define DEBUG_TRACE(msg, ...) \
46
+ fprintf(stderr, "TRACE[%s:%d] " msg "\n", __func__, __LINE__, __VA_ARGS__)
47
+ #define DEBUG_TRACE0(msg) \
48
+ fprintf(stderr, "TRACE[%s:%d] " msg "\n", __func__, __LINE__)
49
+
50
+ #else
51
+
52
+ #define DEBUG_CHECK(cond)
53
+ #define DEBUG_NULL_CHECK(val)
54
+ #define DEBUG_TRACE(msg, ...)
55
+ #define DEBUG_TRACE0(msg)
56
+
57
+ #endif
58
+
59
+ inline _PyFrameEvalFunction _debug_set_eval_frame(
60
+ PyThreadState* tstate,
61
+ _PyFrameEvalFunction eval_frame) {
62
+ _PyFrameEvalFunction prev =
63
+ _PyInterpreterState_GetEvalFrameFunc(tstate->interp);
64
+ _PyInterpreterState_SetEvalFrameFunc(tstate->interp, eval_frame);
65
+ return prev;
66
+ }
67
+
68
+ // Inspect PyObject*'s from C/C++ at the Python level, in pdb.
69
+ // e.g.
70
+ //
71
+ // PyObject* obj1 = PyList_New(...);
72
+ // PyObject* obj2 = PyObject_CallFunction(...);
73
+ // INSPECT(obj1, obj2);
74
+ // (pdb) p args[0]
75
+ // # list
76
+ // (pdb) p args[1]
77
+ // # some object
78
+ // (pdb) p args[1].some_attr
79
+ // # etc.
80
+ //
81
+ // Implementation: set eval frame callback to default, call
82
+ // torch._dynamo.utils._breakpoint_for_c_dynamo, reset eval frame callback.
83
+ #define INSPECT(...) \
84
+ { \
85
+ PyThreadState* cur_tstate = PyThreadState_Get(); \
86
+ _PyFrameEvalFunction prev_eval_frame = \
87
+ _debug_set_eval_frame(cur_tstate, &_PyEval_EvalFrameDefault); \
88
+ PyObject* torch__dynamo_utils_module = \
89
+ PyImport_ImportModule("torch._dynamo.utils"); \
90
+ NULL_CHECK(torch__dynamo_utils_module); \
91
+ PyObject* breakpoint_for_c_dynamo_fn = PyObject_GetAttrString( \
92
+ torch__dynamo_utils_module, "_breakpoint_for_c_dynamo"); \
93
+ NULL_CHECK(breakpoint_for_c_dynamo_fn); \
94
+ PyObject_CallFunctionObjArgs( \
95
+ breakpoint_for_c_dynamo_fn, __VA_ARGS__, NULL); \
96
+ _debug_set_eval_frame(cur_tstate, prev_eval_frame); \
97
+ Py_DECREF(breakpoint_for_c_dynamo_fn); \
98
+ Py_DECREF(torch__dynamo_utils_module); \
99
+ }
100
+
101
+ #ifdef __cplusplus
102
+ } // extern "C"
103
+ #endif
104
+
105
+ #else
106
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
107
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <stdbool.h>
4
+
5
+ #include <torch/csrc/dynamo/extra_state.h>
6
+ #include <torch/csrc/utils/python_compat.h>
7
+ #ifdef __cplusplus
8
+
9
+ extern "C" {
10
+
11
+ PyObject* torch_c_dynamo_eval_frame_init(void);
12
+
13
+ #endif
14
+
15
+ // All the eval APIs change in 3.11 so we need to decide which one to use on the
16
+ // fly https://docs.python.org/3/c-api/init.html#c._PyFrameEvalFunction
17
+ #if IS_PYTHON_3_11_PLUS
18
+ #define THP_EVAL_API_FRAME_OBJECT _PyInterpreterFrame
19
+ #else
20
+ #define THP_EVAL_API_FRAME_OBJECT PyFrameObject
21
+ #endif // IS_PYTHON_3_11_PLUS
22
+
23
+ // We need to be able to return the _PyInterpreterFrame to python so create
24
+ // a python binding for it
25
+
26
+ typedef struct THPPyInterpreterFrame {
27
+ PyObject_HEAD
28
+ THP_EVAL_API_FRAME_OBJECT* frame; // Borrowed reference
29
+ PyObject* locals;
30
+ } THPPyInterpreterFrame;
31
+
32
+ THPPyInterpreterFrame* THPPyInterpreterFrame_New(
33
+ THP_EVAL_API_FRAME_OBJECT* frame);
34
+
35
+ extern bool is_skip_guard_eval_unsafe;
36
+
37
+ void clear_old_frame_if_python_312_plus(
38
+ PyThreadState* tstate,
39
+ THP_EVAL_API_FRAME_OBJECT* frame);
40
+
41
+ void eval_frame_callback_set(PyObject* obj);
42
+
43
+ const char* get_frame_name(THP_EVAL_API_FRAME_OBJECT* frame);
44
+
45
+ PyObject* dynamo_eval_frame_default(
46
+ PyThreadState* tstate,
47
+ THP_EVAL_API_FRAME_OBJECT* frame,
48
+ int throw_flag);
49
+
50
+ PyObject* dynamo_eval_custom_code(
51
+ PyThreadState* tstate,
52
+ THP_EVAL_API_FRAME_OBJECT* frame,
53
+ PyCodeObject* code,
54
+ const char* trace_annotation,
55
+ int throw_flag);
56
+
57
+ #ifdef __cplusplus
58
+
59
+ } // extern "C"
60
+
61
+ #endif
62
+
63
+ #else
64
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
65
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/eval_frame_cpp.h ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <Python.h>
4
+
5
+ #include <torch/csrc/dynamo/eval_frame.h>
6
+ #include <torch/csrc/dynamo/extra_state.h>
7
+ #include <torch/csrc/dynamo/framelocals_mapping.h>
8
+ #ifdef __cplusplus
9
+
10
+ extern "C" {
11
+
12
+ #endif
13
+
14
+ PyObject* dynamo__custom_eval_frame(
15
+ PyThreadState* tstate,
16
+ THP_EVAL_API_FRAME_OBJECT* frame,
17
+ int throw_flag,
18
+ PyObject* callback);
19
+
20
+ PyObject* dynamo_set_code_exec_strategy(PyObject* dummy, PyObject* obj);
21
+ void dynamo_skip_code_recursive(PyCodeObject* code);
22
+
23
+ void dynamo_set_c_recursion_limit(int32_t limit);
24
+ int32_t dynamo_get_c_recursion_limit();
25
+
26
+ #ifdef __cplusplus
27
+
28
+ } // extern "C"
29
+
30
+ #endif
31
+
32
+ #else
33
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
34
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/extra_state.h ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <Python.h>
5
+
6
+ #include <torch/csrc/dynamo/framelocals_mapping.h>
7
+
8
+ #ifdef __cplusplus
9
+
10
+ #include <torch/csrc/dynamo/utils.h>
11
+ #include <torch/csrc/utils/pybind.h>
12
+ #include <list>
13
+
14
+ namespace py = pybind11;
15
+
16
+ extern "C" {
17
+
18
+ #else
19
+
20
+ #include <stdbool.h>
21
+
22
+ #endif
23
+
24
+ enum FrameAction {
25
+ DEFAULT, // look through the cache, compile if not found
26
+ SKIP, // eager
27
+ RUN_ONLY, // look through the cache, run eager if not found
28
+ };
29
+
30
+ typedef struct FrameExecStrategy {
31
+ enum FrameAction cur_action; // action to take for current frame
32
+ enum FrameAction recursive_action; // action to take for recursive frames
33
+ } FrameExecStrategy;
34
+
35
+ // Points to the extra scratch space on the code object
36
+ extern Py_ssize_t extra_index;
37
+
38
+ // function to call when cache lookup errors
39
+ extern PyObject* guard_error_hook;
40
+
41
+ typedef PyObject FrameState;
42
+ typedef struct CacheEntry CacheEntry;
43
+
44
+ // ExtraState encasulates CacheEntry and FrameState. ExtraState is the highest
45
+ // level of abstraction of what is stored on the extra code object. Previously,
46
+ // we saved different parts on different extra indexes. We prefer this way
47
+ // because of cleaner abstraction and faster SetExtra access.
48
+
49
+ #ifdef __cplusplus
50
+
51
+ typedef struct VISIBILITY_HIDDEN PrecompileEntry {
52
+ py::object guard_manager;
53
+ py::object code;
54
+ void* root_mgr;
55
+
56
+ PrecompileEntry(py::object gm, py::object c);
57
+ } PrecompileEntry;
58
+
59
+ typedef struct VISIBILITY_HIDDEN ExtraState {
60
+ // A pointer to the orig_code object to prevent race conditions in invalidate
61
+ // function.
62
+ PyCodeObject* orig_code;
63
+ std::list<PrecompileEntry> precompile_entries;
64
+ // List of cache entries for compiled code objects
65
+ std::list<CacheEntry> cache_entry_list;
66
+ // Frame state to detect dynamic shape dims
67
+ py::dict frame_state;
68
+ // Actions to apply to all frames with this code object
69
+ FrameExecStrategy strategy{DEFAULT, DEFAULT};
70
+
71
+ ExtraState(PyCodeObject* orig_code_arg);
72
+ CacheEntry* get_first_entry();
73
+ void move_to_front(CacheEntry* cache_entry);
74
+ void move_to_back(CacheEntry* cache_entry);
75
+ void invalidate(CacheEntry* cache_entry, py::object deleted_guard_manager);
76
+ } ExtraState;
77
+
78
+ #else
79
+
80
+ typedef struct ExtraState ExtraState;
81
+ typedef struct PrecompileEntry PrecompileEntry;
82
+
83
+ #endif
84
+
85
+ // Helper to extra the cache_entry from the extra state.
86
+ // Ownership contract
87
+ // args
88
+ // - extra_state: Borrowed
89
+ // return
90
+ // - CacheEntry: Borrowed.
91
+ CacheEntry* extract_cache_entry(ExtraState* extra_state);
92
+
93
+ // Returns either the previously stored frame state or an empty dict.
94
+ // Ownership contract
95
+ // args
96
+ // - extra_state: Borrowed
97
+ // return
98
+ // - extra_state->frame_state: Borrowed.
99
+ FrameState* extract_frame_state(ExtraState* extra_state);
100
+
101
+ // Returns the FrameExecStrategy stored in extra_state.
102
+ // Ownership contract
103
+ // args
104
+ // - extra_state: Borrowed
105
+ FrameExecStrategy extra_state_get_exec_strategy(ExtraState* extra_state);
106
+
107
+ // Set the FrameExecStrategy to be done to all frames with code object
108
+ // corresponding to this extra_state. Ownership contract
109
+ // - extra_state: Borrowed
110
+ void extra_state_set_exec_strategy(
111
+ ExtraState* extra_state,
112
+ FrameExecStrategy strategy);
113
+
114
+ // Ownership contract
115
+ // args
116
+ // - code: Borrowed
117
+ // return
118
+ // - extra_state: Borrowed.
119
+ ExtraState* get_extra_state(PyCodeObject* code);
120
+
121
+ // This is passed as freefunc to _PyEval_RequestCodeExtraIndex. This acts as a
122
+ // deleter for the object on extra scratch space. This function is called
123
+ // internally in _PyCode_SetExtra and also during the code deallocation.
124
+
125
+ // Destroys the extra state by deleting cache_entry, frame state and finally
126
+ // freeing the constructed extra state.
127
+
128
+ // Developer note - You should not call this function directly. This is called
129
+ // directly inside set_extra_state. If you are in a situation trying to call
130
+ // this function, consider if set_extra_state should be called.
131
+ void destroy_extra_state(void* obj);
132
+
133
+ // Clears the existing object sitting on the extra scratch spance and sets it
134
+ // up with the new state. Note that _PyCode_SetExtra calls the
135
+ // destroy_extra_state deleter internally, and therefore we don't call it
136
+ // explicitly here.
137
+
138
+ // Ownership contract
139
+ // args
140
+ // - extra_state: Stolen
141
+ // return
142
+ // - there is no return, but the extra_state is stolen, so it becomes
143
+ // set_extra_state responsibility to clean it up. It will be deleted during
144
+ // the reset_code, when the set_extra_state is called with NULL.
145
+
146
+ // Invariant - Dont set the extra state for the extra state that is already on
147
+ // the code object. Otherwise, we will first free up the old extra state
148
+ // (which is also the new extra state) and write something invalid on the
149
+ // scratch space.
150
+ void set_extra_state(PyCodeObject* code, ExtraState* extra_state);
151
+
152
+ // Creates a new extra state and put it on the extra scratch space of the code
153
+ // object.
154
+
155
+ // Ownership contract
156
+ // args
157
+ // - code: Borrowed
158
+ // return:
159
+ // - extra_state: New reference.
160
+ // These references are then further passed to set_extra_state which becomes
161
+ // the final owner of these references.
162
+ ExtraState* init_and_set_extra_state(PyCodeObject* code);
163
+
164
+ // Lookup the cache held by extra_state.
165
+ // Ownership contract
166
+ // args
167
+ // - extra_state: Borrowed
168
+ // return:
169
+ // - Py_None or PyCodeObject: Borrowed reference.
170
+ // - Py_None or PyObject: Trace id of the compiled code.
171
+ void lookup(
172
+ ExtraState* extra_state,
173
+ FrameLocalsMapping* f_locals,
174
+ PyObject* backend,
175
+ PyObject** maybe_cached_code,
176
+ const char** trace_annotation,
177
+ bool is_skip_guard_eval_unsafe);
178
+
179
+ // Create a new cache entry at extra_state holding on to guarded_code.
180
+ // Ownership contract
181
+ // args
182
+ // - extra_state: Borrowed
183
+ // - guarded_code: Borrowed
184
+ // return:
185
+ // - cache_entry: Borrowed reference
186
+ CacheEntry* create_cache_entry(
187
+ ExtraState* extra_state,
188
+ PyObject* guraded_code,
189
+ PyObject* callback);
190
+
191
+ // Extracts the backend fn from the callback.
192
+ PyObject* get_backend(PyObject* callback);
193
+
194
+ #ifdef __cplusplus
195
+
196
+ } // extern "C"
197
+
198
+ // Returns the list of CacheEntry corresponding to code_obj.
199
+ // Warning: returns references whose lifetimes are controlled by C++
200
+ py::list _debug_get_cache_entry_list(const py::handle& code_obj);
201
+ void _reset_precompile_entries(const py::handle& code_obj);
202
+ void _load_precompile_entry(
203
+ const py::handle& code_obj,
204
+ py::object guard_manager,
205
+ py::object dynamo_code);
206
+ py::list _debug_get_precompile_entries(const py::handle& code_obj);
207
+ void _set_lru_cache(py::object boolean);
208
+
209
+ #endif
210
+
211
+ #else
212
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
213
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/framelocals_mapping.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/utils/python_compat.h>
5
+
6
+ #ifdef __cplusplus
7
+
8
+ #include <string>
9
+ #include <unordered_map>
10
+
11
+ #include <torch/csrc/dynamo/utils.h>
12
+ #include <torch/csrc/utils/pybind.h>
13
+
14
+ extern "C" {
15
+
16
+ #if IS_PYTHON_3_11_PLUS
17
+ using FrameLocalsFrameType = _PyInterpreterFrame;
18
+ #else
19
+ using FrameLocalsFrameType = PyFrameObject;
20
+ #endif // IS_PYTHON_3_11_PLUS
21
+
22
+ /**
23
+ * Utility to view a frame's localsplus (locals + cells + freevars)
24
+ * in C/C++ and Python, without changing the state of the frame.
25
+ *
26
+ * Notes on usage:
27
+ * - C/C++ can directly read the frame's localsplus using an index.
28
+ * - Cell/free variables are unboxed.
29
+ * - Can be converted into a dict for use in Python.
30
+ * The dict is constructed once per FrameLocalsMapping, lazily.
31
+ * - Lifetime should not exceed the lifetime of the frame
32
+ *
33
+ * How do guards use FrameLocalsMapping?
34
+ * - When a guard accesses a frame's localsplus, we find the index of the
35
+ * variable name in the frame's code object and create a
36
+ * FrameLocalsGuardAccessor.
37
+ * - We create a FrameLocalsMapping for the frame that we pass on to guard eval.
38
+ * - LeafGuards/GuardManagers/GuardAccessors now need to define how they
39
+ * handle FrameLocalsMapping. By default, the FrameLocalsMapping is converted
40
+ * to a Python dict and the guard check is performed on the resulting dict.
41
+ * - Some guard checks don't actually depend on the input arguments, e.g. they
42
+ * only check global state. In this case, no dict conversion of
43
+ * FrameLocalsMapping is done.
44
+ * - FrameLocalsGuardAccessor is like DictGetItemGuardAccessor, except it knows
45
+ * how to handle FrameLocalsMapping - by using the framelocals variable name
46
+ * index that it was given when it was built.
47
+ */
48
+ typedef struct VISIBILITY_HIDDEN FrameLocalsMapping {
49
+ private:
50
+ py::object _code_obj;
51
+ // can't use localsplus directly due to closure variables:
52
+ // - in 3.11+, the closure vars in the frame's closure object and
53
+ // the corresponding localsplus entry is nullptr
54
+ // - regardless of Python version, we need to unbox the cell variable
55
+ std::vector<py::handle> _framelocals;
56
+
57
+ py::object _dict{py::none()};
58
+
59
+ void _realize_dict();
60
+
61
+ public:
62
+ explicit FrameLocalsMapping(FrameLocalsFrameType* frame);
63
+
64
+ PyObject* get(int idx);
65
+
66
+ bool dict_realized() const {
67
+ return _dict.is_none();
68
+ }
69
+
70
+ // Borrowed reference
71
+ PyDictObject* to_dict() {
72
+ if (this->dict_realized()) {
73
+ _realize_dict();
74
+ }
75
+ return (PyDictObject*)_dict.ptr();
76
+ }
77
+ } FrameLocalsMapping;
78
+
79
+ #else
80
+
81
+ // opaque type for C
82
+ typedef struct FrameLocalsMapping FrameLocalsMapping;
83
+
84
+ #endif
85
+
86
+ // Borrowed reference
87
+ PyDictObject* framelocals_mapping_to_dict(FrameLocalsMapping* map);
88
+
89
+ #ifdef __cplusplus
90
+ } // extern "C"
91
+
92
+ py::tuple code_framelocals_names(py::handle code);
93
+ #endif
94
+
95
+ #else
96
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
97
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/guards.h ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/core/GradMode.h>
4
+ #include <torch/csrc/dynamo/framelocals_mapping.h>
5
+ #include <torch/csrc/python_headers.h>
6
+ #include <torch/csrc/utils/pybind.h>
7
+
8
+ namespace torch::dynamo {
9
+
10
+ PyObject* torch_c_dynamo_guards_init();
11
+
12
+ // interfaces for extra_state and eval_frame.c because RootGuardManager class is
13
+ // not visible there.
14
+ void* convert_to_root_guard_manager(py::object root);
15
+ bool run_root_guard_manager(void* root, FrameLocalsMapping* f_locals);
16
+
17
+ extern thread_local bool tls_is_in_mode_without_ignore_compile_internals;
18
+
19
+ void set_is_in_mode_without_ignore_compile_internals(bool value);
20
+
21
+ // If we're in a mode with ignore_compile_internals=False, we WON'T mask
22
+ // Python keys from guard checking (they should be visible, so eager fallback is
23
+ // possible). Otherwise (invisible mode or no mode), we WILL mask Python keys to
24
+ // avoid guard failures on the dispatch keyset at runtime.
25
+ bool get_is_in_mode_without_ignore_compile_internals();
26
+
27
+ struct LocalState {
28
+ // TLS state that changes operators
29
+ c10::impl::LocalDispatchKeySet dispatch_modifier;
30
+ c10::DispatchKeySet override_dispatch_key_set;
31
+ bool grad_mode_enabled;
32
+ bool should_mask_python_keys;
33
+
34
+ at::DispatchKeySet apply(at::DispatchKeySet ks) const {
35
+ if (override_dispatch_key_set.empty()) {
36
+ auto result =
37
+ (ks | dispatch_modifier.included_) - dispatch_modifier.excluded_;
38
+
39
+ if (should_mask_python_keys) {
40
+ result = result -
41
+ c10::DispatchKeySet(
42
+ {c10::DispatchKey::Python,
43
+ c10::DispatchKey::PythonTLSSnapshot});
44
+ }
45
+
46
+ return result;
47
+ } else {
48
+ return override_dispatch_key_set;
49
+ }
50
+ }
51
+
52
+ LocalState()
53
+ : dispatch_modifier(c10::impl::tls_local_dispatch_key_set()),
54
+ override_dispatch_key_set(c10::BackendComponent::InvalidBit),
55
+ grad_mode_enabled(at::GradMode::is_enabled()),
56
+ should_mask_python_keys(
57
+ !get_is_in_mode_without_ignore_compile_internals()) {}
58
+
59
+ void overrideDispatchKeySet(c10::DispatchKeySet ks) {
60
+ override_dispatch_key_set = ks;
61
+ }
62
+ };
63
+
64
+ class TensorCheck {
65
+ public:
66
+ TensorCheck(
67
+ const LocalState& state,
68
+ PyTypeObject* pt,
69
+ const at::Tensor& v,
70
+ c10::DispatchKeySet dispatch_key_set,
71
+ std::vector<std::optional<c10::SymInt>> dynamic_dims_sizes,
72
+ std::vector<std::optional<c10::SymInt>> dynamic_dims_strides);
73
+
74
+ TensorCheck(
75
+ const LocalState& state,
76
+ PyTypeObject* pt,
77
+ c10::DispatchKeySet dispatch_key_set,
78
+ at::ScalarType dtype,
79
+ at::DeviceIndex device_index,
80
+ bool requires_grad,
81
+ std::vector<std::optional<c10::SymInt>> dynamic_dims_sizes,
82
+ std::vector<std::optional<c10::SymInt>> dynamic_dims_strides);
83
+
84
+ bool check(const LocalState& state, const at::Tensor& v);
85
+ bool check(
86
+ const LocalState& state,
87
+ const c10::DispatchKeySet& dispatch_key_set,
88
+ const at::ScalarType& dtype,
89
+ const c10::Device& device,
90
+ const c10::SymIntArrayRef& dynamic_dims_sizes,
91
+ const c10::SymIntArrayRef& dynamic_dims_strides,
92
+ const bool& requires_grad);
93
+ std::string check_verbose(
94
+ const LocalState& state,
95
+ const at::Tensor& v,
96
+ const std::string& tensor_name);
97
+
98
+ PyTypeObject* pytype;
99
+
100
+ private:
101
+ uint64_t dispatch_key_; // DispatchKeySet includes device/layout
102
+ at::ScalarType dtype_;
103
+ // Note(voz): While dispatch_key_ is sufficiently representative of a device
104
+ // In that keys are more granular AND device specific - they do not
105
+ // necessarily capture device indices correctly.
106
+ at::DeviceIndex device_index_;
107
+ bool requires_grad_;
108
+ // NB: These are unset if dynamic shapes is enabled.
109
+ std::vector<std::optional<c10::SymInt>> sizes_;
110
+ std::vector<std::optional<c10::SymInt>> strides_;
111
+ // Not strictly required for dense tensors, but nested tensors need it.
112
+ int64_t dim_;
113
+ };
114
+
115
+ } // namespace torch::dynamo
116
+
117
+ #else
118
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
119
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/init.h ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ // C2039 MSVC
5
+ #include <pybind11/complex.h>
6
+ #include <torch/csrc/utils/pybind.h>
7
+
8
+ #include <Python.h>
9
+
10
+ namespace torch::dynamo {
11
+ void initDynamoBindings(PyObject* torch);
12
+ }
13
+
14
+ #else
15
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
16
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/python_compiled_autograd.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <torch/csrc/utils/python_stub.h>
4
+
5
+ // see [Note: Compiled Autograd]
6
+ namespace torch::dynamo::autograd {
7
+ PyObject* torch_c_dynamo_compiled_autograd_init();
8
+ } // namespace torch::dynamo::autograd
9
+
10
+ #else
11
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
12
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/stackref_bridge.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/utils/python_compat.h>
5
+
6
+ #if IS_PYTHON_3_14_PLUS
7
+
8
+ #ifdef __cplusplus
9
+ extern "C" {
10
+ #endif // __cplusplus
11
+
12
+ // Use a void* to avoid exposing the internal _PyStackRef union on this
13
+ // translation unit
14
+ PyObject* THP_PyStackRef_AsPyObjectBorrow(void* stackref);
15
+
16
+ #ifdef __cplusplus
17
+ }
18
+ #endif // __cplusplus
19
+ #endif // IS_PYTHON_3_14_PLUS
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/dynamo/utils.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <torch/csrc/python_headers.h>
4
+ // C2039 MSVC
5
+ #include <pybind11/complex.h>
6
+ #include <torch/csrc/utils/pybind.h>
7
+
8
+ #include <Python.h>
9
+ // The visibility attribute is to avoid a warning about storing a field in the
10
+ // struct that has a different visibility (from pybind) than the struct.
11
+ #ifdef _WIN32
12
+ #define VISIBILITY_HIDDEN
13
+ #else
14
+ #define VISIBILITY_HIDDEN __attribute__((visibility("hidden")))
15
+ #endif
16
+
17
+ namespace torch::dynamo {
18
+ PyObject* torch_c_dynamo_utils_init();
19
+ } // namespace torch::dynamo
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/example_upgraders.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace torch::_export {
5
+
6
+ /// Register example upgraders for the upgrader system for testing.
7
+ /// This function demonstrates common upgrade patterns and is primarily
8
+ /// used for testing and demonstration purposes.
9
+ void registerExampleUpgraders();
10
+
11
+ /// Deregister example upgraders for the upgrader system for testing.
12
+ /// This function cleans up the example upgraders that were registered
13
+ /// by registerExampleUpgraders().
14
+ void deregisterExampleUpgraders();
15
+
16
+ } // namespace torch::_export
17
+
18
+ #else
19
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
20
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pt2_archive_constants.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <array>
5
+ #include <string_view>
6
+
7
+ namespace torch::_export::archive_spec {
8
+
9
+ #define FORALL_CONSTANTS(DO) \
10
+ DO(ARCHIVE_ROOT_NAME, "package") \
11
+ /* Archive format */ \
12
+ DO(ARCHIVE_FORMAT_PATH, "archive_format") \
13
+ DO(ARCHIVE_FORMAT_VALUE, "pt2") \
14
+ /* Archive version */ \
15
+ DO(ARCHIVE_VERSION_PATH, "archive_version") \
16
+ DO(ARCHIVE_VERSION_VALUE, "0") /* Sep.4.2024: This is the initial version of \
17
+ the PT2 Archive Spec */ \
18
+ /* \
19
+ * ######## Note on updating ARCHIVE_VERSION_VALUE ######## \
20
+ * When there is a BC breaking change to the PT2 Archive Spec, \
21
+ * e.g. deleting a folder, or changing the naming convention of the \
22
+ * following fields it would require bumping the ARCHIVE_VERSION_VALUE \
23
+ * Archive reader would need corresponding changes to support loading both \
24
+ * the current and older versions of the PT2 Archive. \
25
+ */ \
26
+ /* Model definitions */ \
27
+ DO(MODELS_DIR, "models/") \
28
+ DO(MODELS_FILENAME_FORMAT, "models/{}.json") /* {model_name} */ \
29
+ /* AOTInductor artifacts */ \
30
+ DO(AOTINDUCTOR_DIR, "data/aotinductor/") \
31
+ /* MTIA artifacts */ \
32
+ DO(MTIA_DIR, "data/mtia") \
33
+ /* weights, including parameters and buffers */ \
34
+ DO(WEIGHTS_DIR, "data/weights/") \
35
+ DO(WEIGHT_FILENAME_PREFIX, "weight_") \
36
+ DO(WEIGHTS_PARAM_CONFIG_FORMAT, "data/weights/{}_model_param_config.json") \
37
+ DO(WEIGHTS_CONFIG_FILENAME_FORMAT, "data/weights/{}_weights_config.json") \
38
+ /* constants, including tensor_constants, non-persistent buffers and script \
39
+ * objects */ \
40
+ DO(CONSTANTS_DIR, "data/constants/") \
41
+ DO(CONSTANTS_PARAM_CONFIG_FORMAT, \
42
+ "data/constants/{}_model_constants_config.json") \
43
+ DO(CONSTANTS_CONFIG_FILENAME_FORMAT, \
44
+ "data/constants/{}_constants_config.json") \
45
+ DO(TENSOR_CONSTANT_FILENAME_PREFIX, "tensor_") \
46
+ DO(CUSTOM_OBJ_FILENAME_PREFIX, "custom_obj_") \
47
+ /* example inputs */ \
48
+ DO(SAMPLE_INPUTS_DIR, "data/sample_inputs/") \
49
+ DO(SAMPLE_INPUTS_FILENAME_FORMAT, \
50
+ "data/sample_inputs/{}.pt") /* {model_name} */ \
51
+ /* ExecuTorch artifacts, including PTE files */ \
52
+ DO(EXECUTORCH_DIR, "data/executorch/") \
53
+ /* extra folder */ \
54
+ DO(EXTRA_DIR, "extra/") \
55
+ DO(MODULE_INFO_PATH, "extra/module_info.json") \
56
+ /* xl_model_weights, this folder is used for storing per-feature-weights for \
57
+ * remote net data in this folder is consume by Predictor, and is not \
58
+ * intended to be used by Sigmoid */ \
59
+ DO(XL_MODEL_WEIGHTS_DIR, "xl_model_weights/") \
60
+ DO(XL_MODEL_WEIGHTS_PARAM_CONFIG_PATH, "xl_model_weights/model_param_config")
61
+
62
+ #define DEFINE_GLOBAL(NAME, VALUE) \
63
+ inline constexpr std::string_view NAME = VALUE;
64
+ FORALL_CONSTANTS(DEFINE_GLOBAL)
65
+ #undef DEFINE_GLOBAL
66
+
67
+ #define DEFINE_ENTRY(NAME, VALUE) std::pair(#NAME, VALUE),
68
+ inline constexpr std::array kAllConstants{FORALL_CONSTANTS(DEFINE_ENTRY)};
69
+ #undef DEFINE_ENTRY
70
+
71
+ #undef FORALL_CONSTANTS
72
+ } // namespace torch::_export::archive_spec
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/pybind.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #include <torch/csrc/python_headers.h>
3
+
4
+ namespace torch::_export {
5
+
6
+ void initExportBindings(PyObject* module);
7
+
8
+ } // namespace torch::_export
9
+
10
+ #else
11
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
12
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/export/upgrader.h ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <nlohmann/json.hpp>
5
+ #include <functional>
6
+ #include <string>
7
+ #include <vector>
8
+
9
+ namespace torch::_export {
10
+
11
+ /// Function type for upgrading JSON fields during schema version migration.
12
+ /// Takes a JSON field and returns the upgraded version of that field.
13
+ using UpgraderFunction = std::function<nlohmann::json(const nlohmann::json&)>;
14
+
15
+ /// Structure containing upgrader information for a specific keypath.
16
+ /// The version is stored as the map key in the registry, so it's not
17
+ /// duplicated here.
18
+ struct Upgrader {
19
+ /// Path to the field that should be upgraded (e.g., {"graph_module", "graph",
20
+ /// "nodes"}) Assuming top-level is a JSON object that represents
21
+ /// ExportedProgram
22
+ std::vector<std::string> keypath;
23
+
24
+ /// Function that performs the actual upgrade transformation
25
+ UpgraderFunction upgrade_func;
26
+
27
+ /// Constructor for creating an upgrader with keypath and function
28
+ Upgrader(std::vector<std::string> kp, UpgraderFunction func);
29
+
30
+ /// Comparator for maintaining bottom-up ordering in the registry.
31
+ /// Deeper keypaths are processed first to ensure safe upgrade application
32
+ /// without conflicts between parent and child field modifications.
33
+ bool operator<(const Upgrader& other) const;
34
+ };
35
+
36
+ /// Register an upgrader function for a specific schema version and keypath.
37
+ ///
38
+ /// This function allows registration of custom upgrade logic that will be
39
+ /// applied when upgrading artifacts from the specified version. Upgraders
40
+ /// are applied in bottom-up order (deeper keypaths first) to prevent
41
+ /// conflicts between parent and child field modifications.
42
+ ///
43
+ /// @param version The schema version this upgrader applies to
44
+ /// @param keypath The key path to the field that should be upgraded
45
+ /// @param upgrade_func Function that performs the upgrade transformation
46
+ void registerUpgrader(
47
+ int version,
48
+ const std::vector<std::string>& keypath,
49
+ const UpgraderFunction& upgrade_func);
50
+
51
+ /// Register an upgrader function using dot-separated keypath notation.
52
+ ///
53
+ /// Convenience overload that accepts dot-separated keypath strings for
54
+ /// simpler syntax. For example: "graph_module.graph.nodes" instead of
55
+ /// {"graph_module", "graph", "nodes"}.
56
+ ///
57
+ /// @param version The schema version this upgrader applies to
58
+ /// @param dot_keypath Dot-separated keypath string (e.g., "graph.nodes")
59
+ /// @param upgrade_func Function that performs the upgrade transformation
60
+ void registerUpgrader(
61
+ int version,
62
+ const std::string& dot_keypath,
63
+ const UpgraderFunction& upgrade_func);
64
+
65
+ /// Deregister an upgrader function for a specific schema version and keypath.
66
+ ///
67
+ /// This function allows removal of previously registered upgrade logic for
68
+ /// the specified version and keypath. This is useful for testing scenarios
69
+ /// where you need to clean up registered upgraders or modify upgrader
70
+ /// behavior dynamically.
71
+ ///
72
+ /// @param version The schema version to deregister the upgrader from
73
+ /// @param keypath The key path to the field that should be deregistered
74
+ /// @return true if an upgrader was found and removed, false otherwise
75
+ bool deregisterUpgrader(int version, const std::vector<std::string>& keypath);
76
+
77
+ /// Deregister an upgrader function using dot-separated keypath notation.
78
+ ///
79
+ /// Convenience overload that accepts dot-separated keypath strings for
80
+ /// simpler syntax. For example: "graph_module.graph.nodes" instead of
81
+ /// {"graph_module", "graph", "nodes"}.
82
+ ///
83
+ /// @param version The schema version to deregister the upgrader from
84
+ /// @param dot_keypath Dot-separated keypath string (e.g., "graph.nodes")
85
+ /// @return true if an upgrader was found and removed, false otherwise
86
+ bool deregisterUpgrader(int version, const std::string& dot_keypath);
87
+
88
+ /// Utility function for throwing consistent upgrader errors.
89
+ ///
90
+ /// This function formats error messages in a standardized way for upgrader
91
+ /// failures, including version information and optional problematic object
92
+ /// details for debugging.
93
+ ///
94
+ /// @param upgrader_name Name of the upgrader that failed
95
+ /// @param from_version Source schema version being upgraded from
96
+ /// @param error_message Descriptive error message
97
+ /// @param problematic_object Optional JSON object that caused the error
98
+ /// @throws std::runtime_error Always throws with formatted error message
99
+ void throwUpgraderError(
100
+ const std::string& upgrader_name,
101
+ int from_version,
102
+ const std::string& error_message,
103
+ const nlohmann::json& problematic_object = nlohmann::json::object());
104
+
105
+ /// Upgrade a JSON artifact to a specific target version with available
106
+ /// upgraders until a target version is reached.
107
+ ///
108
+ /// This handles major version upgrade only. For minor version upgrade,
109
+ /// e.g. adding a new field with default value, it's automatically handled by
110
+ /// the default constructor in generated_serialization_types.h.
111
+ ///
112
+ /// @param artifact The JSON artifact to upgrade(passed by value: function
113
+ /// operates on a local copy, original remains unmodified)
114
+ /// @param target_version The target schema version to upgrade to
115
+ /// @return The upgraded JSON artifact with updated schema version
116
+ /// @throws std::runtime_error if artifact is missing schema_version field
117
+ /// @throws std::runtime_error if final version doesn't match target version
118
+ nlohmann::json upgrade(nlohmann::json artifact, int target_version);
119
+
120
+ } // namespace torch::_export
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functionalization/Module.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/FunctionalStorageImpl.h>
5
+
6
+ #include <torch/csrc/python_headers.h>
7
+ #include <torch/csrc/utils/pybind.h>
8
+
9
+ namespace torch::functionalization {
10
+
11
+ // Creates the default bindings for `ViewMeta` specializations.
12
+ //
13
+ // Defines a constructor using the types in `SerializableTuple`, as well
14
+ // as pickle methods.
15
+ template <class T>
16
+ void create_binding_with_pickle(py::module m) {
17
+ py::class_<T, std::shared_ptr<T>, at::functionalization::ViewMeta>(
18
+ m, T::name())
19
+ .def(py::init<typename T::SerializableTuple>())
20
+ .def(
21
+ "as_tuple",
22
+ [](const std::shared_ptr<T>& meta) {
23
+ return meta->to_serializable_tuple();
24
+ })
25
+ .def(py::pickle(
26
+ [](const std::shared_ptr<T>& meta) {
27
+ return meta->to_serializable_tuple();
28
+ },
29
+ [](const typename T::SerializableTuple& tpl) {
30
+ return std::make_shared<T>(tpl);
31
+ }));
32
+ }
33
+
34
+ void initModule(PyObject* module);
35
+ void initGenerated(PyObject* module);
36
+
37
+ } // namespace torch::functionalization
38
+
39
+ #else
40
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
41
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/functorch/init.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #include <Python.h>
3
+
4
+ namespace torch::functorch::impl {
5
+
6
+ void initFuncTorchBindings(PyObject* module);
7
+
8
+ }
9
+
10
+ #else
11
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
12
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/fx/node.h ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/python_headers.h>
5
+
6
+ bool NodeBase_init(PyObject* module);
7
+ bool NodeIter_init(PyObject* module);
8
+
9
+ #else
10
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
11
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_holder.h ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #if !defined(C10_MOBILE) && !defined(ANDROID)
3
+ #pragma once
4
+
5
+ #include <ATen/ATen.h>
6
+ #include <ATen/core/boxing/KernelFunction.h>
7
+ #include <ATen/core/function_schema.h>
8
+
9
+ #include <torch/csrc/dynamo/guards.h>
10
+ #include <torch/csrc/inductor/aoti_eager/kernel_meta_info.h>
11
+ #include <torch/csrc/inductor/aoti_runner/model_container_runner.h>
12
+ #include <torch/csrc/utils/pybind.h>
13
+
14
+ #include <string>
15
+
16
+ namespace torch::inductor {
17
+
18
+ // Represent AOTI kernel. It contains all the parameter metadata of the kernel
19
+ // and the AOTI model runner.
20
+ struct AOTIKernelMetadata {
21
+ // Represent all the parameters of AOTI kernel
22
+ std::vector<ParameterMetadata> parameter_metadata_list_;
23
+ // AOTI model runner to run the AOTI kernel
24
+ std::shared_ptr<AOTIModelContainerRunner> kernel_runner_;
25
+ AOTIKernelMetadata() : kernel_runner_(nullptr) {}
26
+
27
+ // Check whether the given parameter metadata list is the same as the
28
+ // parameter metadata list of the AOTI kernel.
29
+ bool check(
30
+ const std::vector<ParameterMetadata>& parameter_metadata_list) const {
31
+ if (parameter_metadata_list_.size() != parameter_metadata_list.size()) {
32
+ return false;
33
+ }
34
+
35
+ for (size_t i = 0; i < parameter_metadata_list_.size(); ++i) {
36
+ if (parameter_metadata_list_[i] == parameter_metadata_list[i]) {
37
+ continue;
38
+ } else {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ return true;
44
+ }
45
+ };
46
+
47
+ // The AOTIPythonKernelHolder class uses the AOT Inductor to generate a kernel
48
+ // for a specified operation. To speed up this process, the generated kernel
49
+ // library is cached on disk. Detailed information from the input tensors is
50
+ // used as the key for caching the kernel library. On subsequent runs, these
51
+ // input tensors are used to search the cache. If a cache hit occurs, the cached
52
+ // kernel library is loaded and executed. If a cache miss occurs, the AOT
53
+ // Inductor is called again to generate the kernel library.
54
+ class AOTIPythonKernelHolder : public c10::OperatorKernel {
55
+ // A DispatchKey object that represents the dispatch key for the kernel.
56
+ c10::DispatchKey dispatch_key_;
57
+ // Namespace of the kernel.
58
+ std::string ns_;
59
+ // Name of the operation the kernel performs.
60
+ std::string op_name_with_overload_;
61
+ // The device on which the kernel is to be executed.
62
+ c10::Device device_;
63
+ // The Python interpreter to get OpOverload object with the given op_name and
64
+ // op_overload_name.
65
+ c10::impl::PyInterpreter* pyinterpreter_;
66
+ // Cache the produced kernels by AOTI and its metadata
67
+ std::vector<AOTIKernelMetadata> aoti_kernel_cache_;
68
+
69
+ public:
70
+ AOTIPythonKernelHolder(
71
+ c10::DispatchKey dispatch_key,
72
+ std::string_view ns,
73
+ std::string_view op_name_with_overload);
74
+
75
+ void operator()(
76
+ const c10::OperatorHandle& op,
77
+ c10::DispatchKeySet keyset,
78
+ torch::jit::Stack* stack);
79
+
80
+ private:
81
+ bool cache_lookup(
82
+ const c10::OperatorHandle& op,
83
+ const c10::DispatchKeySet& keyset,
84
+ const torch::jit::Stack* stack,
85
+ AOTIKernelMetadata& aoti_kernel_metadata);
86
+ void cache_miss(
87
+ const c10::OperatorHandle& op,
88
+ const c10::DispatchKeySet& keyset,
89
+ torch::jit::Stack* stack);
90
+ void cache_hit(
91
+ const AOTIKernelMetadata& aoti_kernel_metadata,
92
+ const c10::OperatorHandle& op,
93
+ const c10::DispatchKeySet& keyset,
94
+ torch::jit::Stack* stack);
95
+ // Invoke python utility function on the Inductor side to produce AOTI kernel
96
+ // for the given operation.
97
+ // Inductor utility function -
98
+ // torch._inductor.utils.aoti_compile_with_persistent_cache
99
+ std::string produce_aoti_kernel_lib(
100
+ const c10::OperatorHandle& op,
101
+ const c10::DispatchKeySet& keyset,
102
+ const torch::jit::Stack* stack);
103
+ // Invoke python utility function on the Inductor side to load AOTI kernel for
104
+ // the given operation.
105
+ // Inductor utility function - torch._inductor.utils.load_aoti_eager_cache
106
+ void init_aoti_kernel_cache();
107
+ // Load the AOTIModelContainerRunner object from the given file path.
108
+ std::shared_ptr<AOTIModelContainerRunner> load_aoti_model_runner(
109
+ const std::string& /*so_path*/);
110
+ };
111
+
112
+ } // namespace torch::inductor
113
+ #endif
114
+
115
+ #else
116
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
117
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_eager/kernel_meta_info.h ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #if !defined(C10_MOBILE) && !defined(ANDROID)
3
+ #pragma once
4
+
5
+ #include <ATen/ATen.h>
6
+ #include <c10/core/SymIntArrayRef.h>
7
+ #include <torch/csrc/dynamo/guards.h>
8
+
9
+ #include <string>
10
+
11
+ namespace torch::inductor {
12
+
13
+ // Regarding a aten operation implemented by AOTI, the metadata of the input
14
+ // tensors will be cached on the disk to accelerate next run. TensorMetada
15
+ // structure is to represent the metadata of each input tensor. It includes
16
+ // whether the tensor is symbolic, the dtype, the device, the sizes and the
17
+ // strides of the tensor. When the metadata of the input tensors is the same as
18
+ // the cached metadata, the cached kernel library will be loaded and executed.
19
+ // Otherwise, the AOT Inductor will be called again to generate the kernel
20
+ // library.
21
+ // Beyond the TensorMetadata, we build guard/TensorCheck for each input tensor
22
+ // as well to support symbolic shape. We intend to utilize TensorCheck to find
23
+ // out the proper kernel rather than TensorMetada comparison. Suppose an
24
+ // operation with a single input tensor and two kernels:
25
+ // kernel1: TensorMetadata(is_symbolic=false, dtype=Float, device=CPU,
26
+ // sizes=[s0, s1, s2], strides=[s1 * s2, s2, 1]) kernel2:
27
+ // TensorMetadata(is_symbolic=false, dtype=Float, device=CPU, sizes=[3, s1,
28
+ // s2], strides=[s1 * s2, s2, 1])
29
+ // If a tensor with sizes=[3, 4, 5] is passed to the operation, both kernel1 and
30
+ // kernel2 support the tensor shape. In this case, we need to use TensorCheck
31
+ // plus some heruistic rules to find out the proper kernel.
32
+ struct TensorMetadata {
33
+ // Indicate whether the tensor is symbolic and it may be concluded by sizes_
34
+ // and strides_ in the future.
35
+ bool is_symbolic_;
36
+ // Dtype of a tensor(For scalar, we will wrap it as a scalar tensor)
37
+ c10::ScalarType dtype_ = c10::ScalarType::Undefined;
38
+ // Device of a tensor.
39
+ c10::Device device_;
40
+ // Dispatch key set of a tensor
41
+ c10::DispatchKeySet dispatch_key_set_;
42
+ // Sizes of a tensor. Currently, we only support static shape and use int64_t
43
+ // to represent the sizes. In the future, we will create symbolic size and use
44
+ // SymInt to represent it to support symbolic shape.
45
+ std::vector<int64_t> sizes_;
46
+ // Strides of a tensor. For symbolic shape support, it is the same as sizes_
47
+ std::vector<int64_t> strides_;
48
+ // requires grad
49
+ bool requires_grad_ = false;
50
+ // TensorCheck for the tensor
51
+ std::optional<dynamo::TensorCheck> tensor_check_;
52
+
53
+ TensorMetadata()
54
+ : is_symbolic_(false),
55
+ device_(c10::DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES),
56
+ sizes_({}),
57
+ strides_({}) {}
58
+ TensorMetadata(const at::Tensor& src_tensor);
59
+ TensorMetadata(
60
+ bool is_symbolic,
61
+ c10::ScalarType dtype,
62
+ c10::Device device,
63
+ c10::DispatchKeySet dispatch_key_set,
64
+ std::vector<int64_t> sizes,
65
+ std::vector<int64_t> strides,
66
+ bool requires_grad = false);
67
+
68
+ // Build TensorCheck for the tensor by using the data fields in TensorMetadata
69
+ void build_guard(const dynamo::LocalState& local_state);
70
+
71
+ // Compare two TensorMetadata objects
72
+ bool operator==(const TensorMetadata& other) const;
73
+ };
74
+
75
+ // ParameterTag is to represent the type of the input parameters of a aten
76
+ // operation. Currently, we support the following types:
77
+ // 1. TENSOR: a single tensor
78
+ // 2. TENSOR_OPTIONAL: a single optional tensor
79
+ // 3. TENSOR_LIST: a list of tensors
80
+ // 4. TENSOR_LIST_OPTIONAL: a list of optional tensors
81
+ // 5. SCALAR: a scalar value
82
+ // If we need to support more types in the future, we will add more types in the
83
+ // ParameterTag enum. For example, we will extend the enum to support string,
84
+ // Dimname and so on to support more types of input parameters of aten
85
+ // operations.
86
+ enum ParameterTag {
87
+ TENSOR,
88
+ TENSOR_OPTIONAL,
89
+ TENSOR_LIST,
90
+ TENSOR_LIST_OPTIONAL,
91
+ SCALAR,
92
+ STRING,
93
+ DEVICE,
94
+ INVALID,
95
+ };
96
+
97
+ // ParameterMetadataValue is to represent the value of the input parameters of a
98
+ // aten operation.
99
+ using ParameterMetadataValue = std::variant<
100
+ TensorMetadata,
101
+ std::vector<TensorMetadata>,
102
+ c10::Scalar,
103
+ std::string,
104
+ c10::Device>;
105
+
106
+ // ParameterMetadata is to represent the metadata of the input parameters of a
107
+ // aten operation. It includes the tag of the parameter, the value of the
108
+ // parameter and the order of the parameter.
109
+ struct ParameterMetadata {
110
+ // The tag of the parameter. It indicates the type of the parameter.
111
+ ParameterTag tag_;
112
+ // The value of the parameter. It can be a tensor, a list of tensors or a
113
+ // scalar.
114
+ ParameterMetadataValue value_;
115
+ // The order of the parameter is used to distinguish the parameters with the
116
+ // same tag. For example, an operation with two input tensors, the first
117
+ // tensor is a optional tensor and the second tensor is a tensor. The first
118
+ // tensor will have the order 0 and the second tensor will have the order 1.
119
+ uint64_t order_{};
120
+
121
+ ParameterMetadata() : tag_(INVALID) {}
122
+ ParameterMetadata(TensorMetadata tensor_metadata, uint64_t input_order);
123
+ ParameterMetadata(const at::Tensor& tensor, uint64_t input_order);
124
+ ParameterMetadata(
125
+ const std::vector<at::Tensor>& tensor_list,
126
+ uint64_t input_order);
127
+ ParameterMetadata(
128
+ const std::vector<TensorMetadata>& tensor_metadata_list,
129
+ uint64_t input_order);
130
+ ParameterMetadata(const c10::Scalar& scalar, uint64_t input_order);
131
+ ParameterMetadata(const std::string& string_value, uint64_t input_order);
132
+ ParameterMetadata(const c10::Device& device, uint64_t input_order);
133
+
134
+ bool operator==(const ParameterMetadata& other) const;
135
+
136
+ private:
137
+ // Helper function to compare two ParameterMetadata objects with the same
138
+ // SCALAR tag.
139
+ bool equal_to(const c10::Scalar& scalar) const;
140
+ };
141
+
142
+ } // namespace torch::inductor
143
+ #endif
144
+
145
+ #else
146
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
147
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/array_ref.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/inductor/aoti_include/common.h>
5
+ #include <torch/csrc/inductor/aoti_runtime/arrayref_tensor.h>
6
+ #include <torch/csrc/inductor/aoti_runtime/thread_local.h>
7
+ #include <torch/csrc/inductor/array_ref_impl.h>
8
+ #include <torch/csrc/inductor/cpp_wrapper/device_internal/cpu.h>
9
+
10
+ #else
11
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
12
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/common.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <array>
5
+ #include <filesystem>
6
+ #include <optional>
7
+
8
+ #include <torch/csrc/inductor/aoti_runtime/interface.h>
9
+ #include <torch/csrc/inductor/aoti_runtime/model.h>
10
+
11
+ #include <c10/util/generic_math.h>
12
+ #include <torch/csrc/inductor/aoti_runtime/scalar_to_tensor.h>
13
+
14
+ // Round up to the nearest multiple of 64
15
+ [[maybe_unused]] inline int64_t align(int64_t nbytes) {
16
+ return (nbytes + 64 - 1) & -64;
17
+ }
18
+
19
+ #else
20
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
21
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cpu.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/inductor/aoti_include/common.h>
5
+ #include <torch/csrc/inductor/cpp_wrapper/device_internal/cpu.h>
6
+
7
+ #else
8
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
9
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/cuda.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/inductor/aoti_include/common.h>
5
+ #include <torch/csrc/inductor/cpp_wrapper/device_internal/cuda.h>
6
+
7
+ #else
8
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
9
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/mps.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/inductor/aoti_include/common.h>
5
+ #include <torch/csrc/inductor/cpp_wrapper/device_internal/mps.h>
6
+
7
+ #else
8
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
9
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_include/xpu.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/inductor/aoti_include/common.h>
5
+ #include <torch/csrc/inductor/cpp_wrapper/device_internal/xpu.h>
6
+
7
+ #else
8
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
9
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/model_package_loader.h ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #if !defined(C10_MOBILE) && !defined(ANDROID)
3
+ #pragma once
4
+
5
+ #include <ATen/Tensor.h>
6
+ #include <c10/core/Device.h>
7
+ #include <torch/csrc/inductor/aoti_runner/model_container_runner.h>
8
+
9
+ namespace torch::inductor {
10
+ class TORCH_API AOTIModelPackageLoader {
11
+ public:
12
+ AOTIModelPackageLoader(
13
+ const std::string& model_package_path,
14
+ const std::string& model_name = "model",
15
+ const bool run_single_threaded = false,
16
+ const size_t num_runners = 1,
17
+ const c10::DeviceIndex device_index = -1);
18
+ ~AOTIModelPackageLoader();
19
+
20
+ AOTIModelContainerRunner* get_runner();
21
+ std::unordered_map<std::string, std::string> get_metadata();
22
+
23
+ std::vector<at::Tensor> run(
24
+ const std::vector<at::Tensor>& inputs,
25
+ void* stream_handle = nullptr);
26
+
27
+ // boxed_run will steal the ownership of the input tensors
28
+ std::vector<at::Tensor> boxed_run(
29
+ std::vector<at::Tensor>&& inputs,
30
+ void* stream_handle = nullptr);
31
+
32
+ std::vector<std::string> get_call_spec();
33
+ void load_constants(
34
+ std::unordered_map<std::string, at::Tensor>& constants_map,
35
+ bool use_inactive,
36
+ bool check_full_update,
37
+ bool user_managed = false);
38
+ std::vector<std::string> get_constant_fqns();
39
+
40
+ void update_constant_buffer(
41
+ std::unordered_map<std::string, at::Tensor>& tensor_map,
42
+ bool use_inactive,
43
+ bool validate_full_updates,
44
+ bool user_managed = false);
45
+
46
+ // Static function to load metadata directly from a model package
47
+ static std::unordered_map<std::string, std::string> load_metadata_from_package(
48
+ const std::string& model_package_path,
49
+ const std::string& model_name);
50
+
51
+ private:
52
+ std::string temp_dir_;
53
+ std::unique_ptr<AOTIModelContainerRunner> runner_;
54
+ std::unordered_map<std::string, std::string> metadata_;
55
+
56
+ void load_metadata(const std::string& cpp_filename);
57
+ };
58
+
59
+ } // namespace torch::inductor
60
+ #endif
61
+
62
+ #else
63
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
64
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_package/pybind.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #include <torch/csrc/python_headers.h>
3
+
4
+ namespace torch::inductor {
5
+
6
+ void initAOTIPackageBindings(PyObject* module);
7
+
8
+ } // namespace torch::inductor
9
+
10
+ #else
11
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
12
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner.h ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #if !defined(C10_MOBILE) && !defined(ANDROID)
3
+ #pragma once
4
+
5
+ #include <ATen/Tensor.h>
6
+ #include <torch/csrc/inductor/aoti_runtime/interface.h>
7
+ #include <torch/csrc/inductor/aoti_torch/proxy_executor.h>
8
+
9
+ // Forward declare DynamicLibrary
10
+ namespace at {
11
+ struct DynamicLibrary;
12
+ }
13
+
14
+ namespace torch::inductor {
15
+ using TensorConstantMap = std::unordered_map<std::string, at::Tensor*>;
16
+
17
+ class TORCH_API AOTIModelContainerRunner {
18
+ public:
19
+ AOTIModelContainerRunner() = delete;
20
+ AOTIModelContainerRunner(const AOTIModelContainerRunner& other) = delete;
21
+ AOTIModelContainerRunner(AOTIModelContainerRunner&& other) = delete;
22
+ AOTIModelContainerRunner& operator=(const AOTIModelContainerRunner& other) =
23
+ delete;
24
+ AOTIModelContainerRunner& operator=(AOTIModelContainerRunner&& other) =
25
+ delete;
26
+ virtual ~AOTIModelContainerRunner();
27
+
28
+ std::vector<at::Tensor> run(
29
+ const std::vector<at::Tensor>& inputs,
30
+ void* stream_handle = nullptr);
31
+
32
+ // boxed_run will steal the ownership of the input tensors
33
+ std::vector<at::Tensor> boxed_run(
34
+ std::vector<at::Tensor>&& inputs,
35
+ void* stream_handle = nullptr);
36
+
37
+ std::unordered_map<std::string, std::string> getConstantNamesToOriginalFQNs()
38
+ const;
39
+ std::unordered_map<std::string, int32_t> getConstantNamesToDtypes() const;
40
+
41
+ const std::unordered_map<std::string, at::Tensor> extract_constants_map(
42
+ bool use_inactive) const;
43
+ void update_inactive_constant_buffer(const TensorConstantMap& const_map);
44
+ void update_constant_buffer(
45
+ std::unordered_map<std::string, at::Tensor>& tensor_map,
46
+ bool use_inactive,
47
+ bool validate_full_updates,
48
+ bool user_managed = false);
49
+ void update_constant_buffer(
50
+ const TensorConstantMap& const_map,
51
+ bool use_inactive,
52
+ bool validate_full_updates,
53
+ bool user_managed = false);
54
+ void run_const_fold(
55
+ bool use_inactive,
56
+ AOTInductorStreamHandle cuda_stream_handle = nullptr);
57
+ void swap_constant_buffer();
58
+ void free_inactive_constant_buffer();
59
+ void update_constant_buffer_from_blob(const std::string& weights_path);
60
+
61
+ std::vector<std::string> get_call_spec();
62
+
63
+ protected:
64
+ AOTIModelContainerRunner(
65
+ const std::string& model_so_path,
66
+ size_t num_models,
67
+ const std::string& device_str,
68
+ const std::string& cubin_dir,
69
+ const bool run_single_threaded);
70
+
71
+ virtual std::vector<at::Tensor> run_impl(
72
+ std::vector<AtenTensorHandle>& input_handles,
73
+ void* stream_handle);
74
+
75
+ std::unique_ptr<at::DynamicLibrary> model_so_;
76
+ decltype(&AOTInductorModelContainerCreateWithDevice) create_func_{nullptr};
77
+ decltype(&AOTInductorModelContainerDelete) delete_func_{nullptr};
78
+ decltype(&AOTInductorModelContainerGetNumOutputs) get_num_outputs_func_{
79
+ nullptr};
80
+ decltype(&AOTInductorModelContainerRun) run_func_{nullptr};
81
+ decltype(&AOTInductorModelContainerGetNumConstants) get_num_constants_func_{
82
+ nullptr};
83
+ decltype(&AOTInductorModelContainerGetConstantName) get_constant_name_func_{
84
+ nullptr};
85
+ decltype(&AOTInductorModelContainerGetConstantOriginalFQN)
86
+ get_constant_original_fqn_func_{nullptr};
87
+ decltype(&AOTInductorModelContainerGetConstantDtype) get_constant_dtype_func_{
88
+ nullptr};
89
+ decltype(&AOTInductorModelContainerExtractConstantsMap)
90
+ extract_constants_map_func_{nullptr};
91
+ decltype(&AOTInductorModelContainerUpdateUserManagedConstantBuffer)
92
+ update_user_managed_constant_buffer_func_{nullptr};
93
+ decltype(&AOTInductorModelContainerUpdateConstantBuffer)
94
+ update_constant_buffer_func_{nullptr};
95
+ decltype(&AOTInductorModelContainerUpdateInactiveConstantBuffer)
96
+ update_inactive_constant_buffer_func_{nullptr};
97
+ decltype(&AOTInductorModelContainerRunConstantFolding) run_const_fold_func_{
98
+ nullptr};
99
+ decltype(&AOTInductorModelContainerSwapConstantBuffer)
100
+ swap_constant_buffer_func_{nullptr};
101
+ decltype(&AOTInductorModelContainerFreeInactiveConstantBuffer)
102
+ free_inactive_constant_buffer_func_{nullptr};
103
+ decltype(&AOTInductorModelContainerGetCallSpec) get_call_spec_func_{nullptr};
104
+ decltype(&AOTInductorModelContainerGetConstantsBlobSize)
105
+ get_constants_blob_size_func_{nullptr};
106
+ decltype(&AOTInductorModelUpdateConstantsFromBlob)
107
+ update_constants_from_blob_func_{nullptr};
108
+
109
+ AOTInductorModelContainerHandle container_handle_ = nullptr;
110
+
111
+ AOTIProxyExecutorHandle proxy_executor_handle_;
112
+
113
+ private:
114
+ std::unique_ptr<torch::aot_inductor::ProxyExecutor> proxy_executor_;
115
+ };
116
+
117
+ using CreateAOTIModelRunnerFunc = std::unique_ptr<AOTIModelContainerRunner> (*)(
118
+ const std::string& model_so_path,
119
+ size_t num_models,
120
+ const std::string& device_str,
121
+ const std::string& bin_dir,
122
+ const bool run_single_threaded);
123
+
124
+ // Return a global map "device name" -> "aoti model runner create function" for
125
+ // all registered in AOTI external backends
126
+ TORCH_API std::unordered_map<std::string, CreateAOTIModelRunnerFunc>&
127
+ getAOTIModelRunnerRegistry();
128
+
129
+ // To register a new external backend in AOTI one needs to create an instance of
130
+ // this struct. It is not thread-safe. Because it is expected to be called
131
+ // during the initialization of the program.
132
+ struct TORCH_API RegisterAOTIModelRunner{RegisterAOTIModelRunner(
133
+ const std::string& name,
134
+ CreateAOTIModelRunnerFunc create_aoti_model_runner_fn){
135
+ getAOTIModelRunnerRegistry()[name] = create_aoti_model_runner_fn;
136
+ } // namespace torch::inductor
137
+ }
138
+ ;
139
+
140
+ } // namespace torch::inductor
141
+ #endif
142
+
143
+ #else
144
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
145
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cpu.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #if !defined(C10_MOBILE) && !defined(ANDROID)
3
+ #pragma once
4
+
5
+ #include <torch/csrc/inductor/aoti_runner/model_container_runner.h>
6
+
7
+ namespace torch::inductor {
8
+ class TORCH_API AOTIModelContainerRunnerCpu : public AOTIModelContainerRunner {
9
+ public:
10
+ AOTIModelContainerRunnerCpu(
11
+ const std::string& model_so_path,
12
+ size_t num_models = 1,
13
+ const bool run_single_threaded = false);
14
+
15
+ ~AOTIModelContainerRunnerCpu() override;
16
+ };
17
+
18
+ } // namespace torch::inductor
19
+ #endif
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/ladir/lib/python3.10/site-packages/torch/include/torch/csrc/inductor/aoti_runner/model_container_runner_cuda.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #if !defined(C10_MOBILE) && !defined(ANDROID)
3
+ #pragma once
4
+
5
+ #include <c10/cuda/CUDAStream.h>
6
+ #include <torch/csrc/inductor/aoti_runner/model_container_runner.h>
7
+
8
+ namespace torch::inductor {
9
+
10
+ // NOTICE: Following APIs are subject to change due to active development
11
+ // We provide NO BC guarantee for these APIs
12
+ // NOLINTNEXTLINE(cppcoreguidelines-special-member-functions)
13
+ class TORCH_CUDA_CPP_API AOTIModelContainerRunnerCuda
14
+ : public AOTIModelContainerRunner {
15
+ public:
16
+ // @param device_str: cuda device string, e.g. "cuda", "cuda:0"
17
+ AOTIModelContainerRunnerCuda(
18
+ const std::string& model_so_path,
19
+ size_t num_models = 1,
20
+ const std::string& device_str = "cuda",
21
+ const std::string& cubin_dir = "",
22
+ const bool run_single_threaded = false);
23
+
24
+ ~AOTIModelContainerRunnerCuda() override;
25
+
26
+ std::vector<at::Tensor> run_impl(
27
+ std::vector<AtenTensorHandle>& input_handles,
28
+ void* stream_handle) override;
29
+
30
+ std::vector<at::Tensor> run_with_cuda_stream(
31
+ const std::vector<at::Tensor>& inputs,
32
+ const at::cuda::CUDAStream& cuda_stream);
33
+ };
34
+
35
+ } // namespace torch::inductor
36
+ #endif
37
+
38
+ #else
39
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
40
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)