ZTWHHH commited on
Commit
80fc073
·
verified ·
1 Parent(s): 5ca824a

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. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory-inl.h +256 -0
  2. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory.hpp +115 -0
  3. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp +140 -0
  4. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/RankLocal.hpp +73 -0
  5. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/SymmetricMemory.hpp +161 -0
  6. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStore.hpp +141 -0
  7. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Types.hpp +177 -0
  8. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCUtils.hpp +187 -0
  9. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp +25 -0
  10. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Work.hpp +165 -0
  11. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/c10d.h +13 -0
  12. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/comm.hpp +141 -0
  13. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/exception.h +33 -0
  14. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/intra_node_comm.hpp +152 -0
  15. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/sequence_num.hpp +66 -0
  16. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket.h +109 -0
  17. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/agent_utils.h +46 -0
  18. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/message.h +193 -0
  19. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_call.h +28 -0
  20. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_functions.h +66 -0
  21. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_remote_call.h +45 -0
  22. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_resp.h +23 -0
  23. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h +129 -0
  24. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback.h +32 -0
  25. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_impl.h +61 -0
  26. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h +115 -0
  27. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc.h +9 -0
  28. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_agent.h +337 -0
  29. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_command_base.h +23 -0
  30. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_context.h +335 -0
  31. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_impl.h +416 -0
  32. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_proto.h +160 -0
  33. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h +71 -0
  34. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h +57 -0
  35. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h +26 -0
  36. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h +492 -0
  37. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h +119 -0
  38. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h +37 -0
  39. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h +38 -0
  40. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h +33 -0
  41. janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h +90 -0
  42. janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cpp_stacktraces.h +9 -0
  43. janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cuda_enabled.h +13 -0
  44. janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/device_lazy_init.h +50 -0
  45. janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/init.h +9 -0
  46. janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/invalid_arguments.h +15 -0
  47. janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/numpy_stub.h +21 -0
  48. janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/object_ptr.h +67 -0
  49. janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/out_types.h +15 -0
  50. janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pybind.h +418 -0
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory-inl.h ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ >= 900) && CUDART_VERSION >= 12010
4
+ #define NVCC_SUPPORTS_MULTICAST 1
5
+ #endif
6
+
7
+ #include <ATen/ATen.h>
8
+
9
+ namespace c10d::symmetric_memory {
10
+
11
+ constexpr size_t max_num_threads_per_block = 1024;
12
+ constexpr size_t max_num_blocks = 8;
13
+
14
+ template <typename T>
15
+ size_t get_alignment(T ptr_or_size) {
16
+ auto val = reinterpret_cast<uintptr_t>(ptr_or_size);
17
+ if (val % 16 == 0) {
18
+ return 16;
19
+ } else if (val % 8 == 0) {
20
+ return 8;
21
+ } else if (val % 4 == 0) {
22
+ return 4;
23
+ } else if (val % 2 == 0) {
24
+ return 2;
25
+ } else {
26
+ return 1;
27
+ }
28
+ }
29
+
30
+ template <>
31
+ size_t get_alignment<size_t>(size_t size) {
32
+ return get_alignment(reinterpret_cast<void*>(size));
33
+ }
34
+
35
+ __device__ __forceinline__ uint32_t
36
+ cas_sys(uint32_t* addr, uint32_t compare, uint32_t val) {
37
+ #if defined(USE_ROCM) || (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800))
38
+ CUDA_KERNEL_ASSERT(false);
39
+ #else
40
+ uint32_t old_val;
41
+ asm volatile("atom.global.sys.cas.b32 %0, [%1], %2, %3;"
42
+ : "=r"(old_val)
43
+ : "l"(addr), "r"(compare), "r"(val)
44
+ : "memory");
45
+ return old_val;
46
+ #endif
47
+ }
48
+
49
+ __device__ __forceinline__ uint32_t
50
+ cas_release_sys(uint32_t* addr, uint32_t compare, uint32_t val) {
51
+ #if defined(USE_ROCM) || (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800))
52
+ CUDA_KERNEL_ASSERT(false);
53
+ #else
54
+ uint32_t old_val;
55
+ asm volatile("atom.global.release.sys.cas.b32 %0, [%1], %2, %3;"
56
+ : "=r"(old_val)
57
+ : "l"(addr), "r"(compare), "r"(val)
58
+ : "memory");
59
+ return old_val;
60
+ #endif
61
+ }
62
+
63
+ __device__ __forceinline__ void release_signal(uint32_t* addr) {
64
+ while (cas_release_sys(addr, 0, 1) != 0)
65
+ ;
66
+ }
67
+
68
+ __device__ __forceinline__ void wait_signal(uint32_t* addr) {
69
+ while (cas_sys(addr, 1, 0) != 1)
70
+ ;
71
+ }
72
+
73
+ __device__ __forceinline__ uint32_t acquire_signal(uint32_t* addr) {
74
+ #if defined(USE_ROCM) || (defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 800))
75
+ CUDA_KERNEL_ASSERT(false);
76
+ #else
77
+ uint32_t val;
78
+ asm volatile("ld.acquire.sys.global.u32 %0, [%1];"
79
+ : "=r"(val)
80
+ : "l"(addr)
81
+ : "memory");
82
+ return val;
83
+ #endif
84
+ }
85
+
86
+ // Perform a barrier to establish observation order between memory operations
87
+ // issued before and after the barrier.
88
+ __device__ __forceinline__ void barrier(
89
+ uint32_t** signal_pads,
90
+ size_t rank,
91
+ size_t world_size) {
92
+ if (threadIdx.x < world_size) {
93
+ auto target_rank = threadIdx.x;
94
+ release_signal(signal_pads[target_rank] + blockIdx.x * world_size + rank);
95
+ wait_signal(signal_pads[rank] + blockIdx.x * world_size + target_rank);
96
+ }
97
+ __syncthreads();
98
+ }
99
+
100
+ // Perform a barrier and establish causality order between memory operations
101
+ // issued before the calling kernel on all devices and memory operations
102
+ // issued after this function by all thread in the calling kernel.
103
+ //
104
+ // NOTE: this function does NOT ensure that memory operations issues in the
105
+ // current kernel are visible to all threads in the current kernel.
106
+ //
107
+ // | mem ops (guaranteed to be visible by all threads at point T)
108
+ // | kernel K
109
+ // | +- mem ops (not guaranteed to be visible all threads at point T)
110
+ // | +- barrier_and_acquire_previous_kernel_writes()
111
+ // | +- point T
112
+ // v
113
+ __device__ __forceinline__ void barrier_and_acquire_previous_kernel_writes(
114
+ uint32_t** signal_pads,
115
+ size_t rank,
116
+ size_t world_size) {
117
+ if (threadIdx.x < world_size) {
118
+ auto target_rank = threadIdx.x;
119
+ release_signal(signal_pads[target_rank] + blockIdx.x * world_size + rank);
120
+ wait_signal(signal_pads[rank] + blockIdx.x * world_size + target_rank);
121
+ }
122
+ __syncthreads();
123
+ // At this point, we established observation order between memory operations
124
+ // issued before and after the barrier. Now we convert the observation order
125
+ // into causality order by having every thread acquire the signals released
126
+ // by threads on peer devices. Due to the implicit synchronizes-with
127
+ // relationships at task/kernel boundaries, acquiring the signal released by
128
+ // thread T in kernel K transitively acquires memory operations issued prior
129
+ // to kernel K.
130
+ //
131
+ // https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#memory-fence-interference
132
+ for (size_t target_rank = 0; target_rank < world_size; ++target_rank) {
133
+ acquire_signal(signal_pads[rank] + blockIdx.x * world_size + target_rank);
134
+ }
135
+ }
136
+
137
+ template <bool Value, class... Args>
138
+ inline constexpr bool dependent_bool_value = Value;
139
+
140
+ template <class... Args>
141
+ inline constexpr bool dependent_false = dependent_bool_value<false, Args...>;
142
+
143
+ template <int Size>
144
+ union Vec;
145
+
146
+ template <>
147
+ union Vec<4> {
148
+ uint16_t u16[2];
149
+ uint32_t u32, as_scalar;
150
+ };
151
+
152
+ template <>
153
+ union Vec<8> {
154
+ uint16_t u16[4];
155
+ uint32_t u32[2];
156
+ uint64_t u64, as_scalar;
157
+ };
158
+
159
+ template <>
160
+ union alignas(16) Vec<16> {
161
+ uint16_t u16[8];
162
+ uint32_t u32[4];
163
+ uint64_t u64[2];
164
+ uint4 u128, as_scalar;
165
+ };
166
+
167
+ template <typename T>
168
+ struct MultimemLdReduce {
169
+ template <int Alignment>
170
+ __device__ __inline__ Vec<Alignment> operator()(T* mc_ptr) {
171
+ static_assert(dependent_false<T>);
172
+ }
173
+ };
174
+
175
+ template <int Alignment, typename T>
176
+ __device__ __inline__ Vec<Alignment> multimem_ld_reduce_add(T* mc_ptr) {
177
+ MultimemLdReduce<T> functor;
178
+ return functor.template operator()<Alignment>(mc_ptr);
179
+ }
180
+
181
+ #if defined(USE_ROCM) || !defined(NVCC_SUPPORTS_MULTICAST)
182
+ #define SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(type, asm_type) \
183
+ template <> \
184
+ struct MultimemLdReduce<type> { \
185
+ template <int Alignment> \
186
+ __device__ __inline__ Vec<Alignment> operator()(type* mc_ptr) { \
187
+ CUDA_KERNEL_ASSERT(false); \
188
+ } \
189
+ };
190
+ #else
191
+ #define SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(type, asm_type) \
192
+ template <> \
193
+ struct MultimemLdReduce<type> { \
194
+ template <int Alignment> \
195
+ __device__ __inline__ Vec<Alignment> operator()(type* mc_ptr) { \
196
+ Vec<Alignment> vec; \
197
+ if constexpr (Alignment == 16) { \
198
+ asm("multimem.ld_reduce.relaxed.sys.global.add.v4." asm_type \
199
+ " {%0,%1,%2,%3}, [%4];" \
200
+ : "=r"(vec.u32[0]), \
201
+ "=r"(vec.u32[1]), \
202
+ "=r"(vec.u32[2]), \
203
+ "=r"(vec.u32[3]) \
204
+ : "l"(mc_ptr) \
205
+ : "memory"); \
206
+ } else if constexpr (Alignment == 8) { \
207
+ asm("multimem.ld_reduce.relaxed.sys.global.add.v2." asm_type \
208
+ " {%0,%1}, [%2];" \
209
+ : "=r"(vec.u32[0]), "=r"(vec.u32[1]) \
210
+ : "l"(mc_ptr) \
211
+ : "memory"); \
212
+ } else if constexpr (Alignment == 4) { \
213
+ asm("multimem.ld_reduce.relaxed.sys.global.add." asm_type " %0, [%1];" \
214
+ : "=r"(vec.u32) \
215
+ : "l"(mc_ptr) \
216
+ : "memory"); \
217
+ } \
218
+ return vec; \
219
+ } \
220
+ };
221
+ #endif
222
+
223
+ SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(at::BFloat16, "bf16x2");
224
+ SPECIALIZE_MULTIMEM_LD_REDUCE_VEC_32(float, "f32");
225
+
226
+ template <int Alignment, typename T>
227
+ __device__ __inline__ void multimem_st(T* mc_ptr, Vec<Alignment>& vec) {
228
+ #if defined(USE_ROCM) || !defined(NVCC_SUPPORTS_MULTICAST)
229
+ CUDA_KERNEL_ASSERT(false);
230
+ #else
231
+ if constexpr (Alignment == 16) {
232
+ asm("multimem.st.relaxed.sys.global.v4.f32 [%0], {%1,%2,%3,%4};"
233
+ :
234
+ : "l"(mc_ptr),
235
+ "r"(vec.u32[0]),
236
+ "r"(vec.u32[1]),
237
+ "r"(vec.u32[2]),
238
+ "r"(vec.u32[3])
239
+ : "memory");
240
+ } else if constexpr (Alignment == 8) {
241
+ asm("multimem.st.relaxed.sys.global.v2.f32 [%0], {%1,%2};"
242
+ :
243
+ : "l"(mc_ptr), "r"(vec.u32[0]), "r"(vec.u32[1])
244
+ : "memory");
245
+ } else if constexpr (Alignment == 4) {
246
+ asm("multimem.st.relaxed.sys.global.f32 [%0], %1;"
247
+ :
248
+ : "l"(mc_ptr), "r"(vec.u32)
249
+ : "memory");
250
+ } else {
251
+ static_assert(dependent_false<T>);
252
+ }
253
+ #endif
254
+ }
255
+
256
+ } // namespace c10d::symmetric_memory
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/CUDASymmetricMemory.hpp ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/ATen.h>
4
+ #include <torch/csrc/distributed/c10d/Store.hpp>
5
+ #include <torch/csrc/distributed/c10d/SymmetricMemory.hpp>
6
+
7
+ namespace c10d {
8
+ namespace symmetric_memory {
9
+
10
+ #if !defined(USE_ROCM) && defined(PYTORCH_C10_DRIVER_API_SUPPORTED)
11
+ using HandleType = CUmemGenericAllocationHandle;
12
+ #else
13
+ using HandleType = void*;
14
+ #endif
15
+
16
+ class CUDASymmetricMemory : public SymmetricMemory {
17
+ public:
18
+ CUDASymmetricMemory(
19
+ std::vector<HandleType> handles,
20
+ size_t block_size,
21
+ std::vector<void*> buffers,
22
+ std::vector<void*> signal_pads,
23
+ HandleType mc_handle,
24
+ void* mc_addr,
25
+ size_t buffer_size,
26
+ int local_device_idx,
27
+ int rank,
28
+ int world_size);
29
+
30
+ ~CUDASymmetricMemory() override;
31
+
32
+ std::vector<void*> get_buffer_ptrs() override;
33
+ std::vector<void*> get_signal_pad_ptrs() override;
34
+ void** get_buffer_ptrs_dev() override;
35
+ void** get_signal_pad_ptrs_dev() override;
36
+ size_t get_buffer_size() override;
37
+ size_t get_signal_pad_size() override;
38
+
39
+ bool has_multicast_support() override;
40
+ void* get_multicast_ptr() override;
41
+
42
+ at::Tensor get_buffer(
43
+ int rank,
44
+ c10::IntArrayRef sizes,
45
+ c10::ScalarType dtype,
46
+ int64_t storage_offset) override;
47
+
48
+ void barrier(int channel) override;
49
+ void put_signal(int dst_rank, int channel) override;
50
+ void wait_signal(int src_rank, int channel) override;
51
+
52
+ int get_rank() override;
53
+ int get_world_size() override;
54
+
55
+ private:
56
+ std::vector<HandleType> handles_;
57
+ size_t block_size_;
58
+ std::vector<void*> buffers_;
59
+ std::vector<void*> signal_pads_;
60
+ HandleType mc_handle_;
61
+ void* mc_addr_;
62
+ size_t buffer_size_;
63
+ int local_device_idx_;
64
+ int rank_;
65
+ int world_size_;
66
+ void** buffers_dev_;
67
+ void** signal_pads_dev_;
68
+ std::optional<std::function<void(void)>> finalizer_;
69
+ };
70
+
71
+ struct Block : public c10::intrusive_ptr_target {
72
+ HandleType handle;
73
+ int device_idx;
74
+ size_t block_size;
75
+ size_t buffer_size;
76
+ size_t signal_pad_offset;
77
+ std::string group_name;
78
+ c10::intrusive_ptr<CUDASymmetricMemory> symm_mem = nullptr;
79
+
80
+ Block(
81
+ HandleType handle,
82
+ int device_idx,
83
+ size_t block_size,
84
+ size_t buffer_size,
85
+ size_t signal_pad_offset,
86
+ const std::string& group_name)
87
+ : handle(handle),
88
+ device_idx(device_idx),
89
+ block_size(block_size),
90
+ buffer_size(buffer_size),
91
+ signal_pad_offset(signal_pad_offset),
92
+ group_name(group_name),
93
+ symm_mem(nullptr) {}
94
+ };
95
+
96
+ class CUDASymmetricMemoryAllocator : public SymmetricMemoryAllocator {
97
+ public:
98
+ void* alloc(size_t size, int device_idx, const std::string& group_name)
99
+ override;
100
+
101
+ void free(void* ptr) override;
102
+ size_t get_alloc_size(void* ptr) override;
103
+ c10::intrusive_ptr<SymmetricMemory> rendezvous(void* ptr) override;
104
+ bool is_rendezvous_completed(void* ptr) override;
105
+ bool has_multicast_support(int device_idx) override;
106
+
107
+ private:
108
+ c10::intrusive_ptr<Block> find_block(void* ptr);
109
+
110
+ std::shared_mutex mutex_;
111
+ std::unordered_map<void*, c10::intrusive_ptr<Block>> ptr_to_block_;
112
+ };
113
+
114
+ } // namespace symmetric_memory
115
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/ProcessGroupWrapper.hpp ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #ifdef USE_C10D_GLOO
4
+
5
+ #include <torch/csrc/distributed/c10d/ProcessGroupGloo.hpp>
6
+ #include <torch/csrc/distributed/c10d/Types.hpp>
7
+ #include <torch/csrc/distributed/c10d/Utils.hpp>
8
+
9
+ namespace c10d {
10
+
11
+ class TORCH_API ProcessGroupWrapper : public Backend {
12
+ public:
13
+ explicit ProcessGroupWrapper(
14
+ const c10::intrusive_ptr<Backend>& backend,
15
+ c10::intrusive_ptr<Backend> glooBackend);
16
+
17
+ const std::string getBackendName() const override;
18
+
19
+ c10::intrusive_ptr<Work> broadcast(
20
+ std::vector<at::Tensor>& data,
21
+ const BroadcastOptions& opts = BroadcastOptions()) override;
22
+
23
+ c10::intrusive_ptr<Work> allreduce(
24
+ std::vector<at::Tensor>& data,
25
+ const AllreduceOptions& opts = AllreduceOptions()) override;
26
+
27
+ c10::intrusive_ptr<Work> allreduce_coalesced(
28
+ std::vector<at::Tensor>& tensors,
29
+ const AllreduceCoalescedOptions& opts =
30
+ AllreduceCoalescedOptions()) override;
31
+
32
+ c10::intrusive_ptr<Work> reduce(
33
+ std::vector<at::Tensor>& tensors,
34
+ const ReduceOptions& opts = ReduceOptions()) override;
35
+
36
+ c10::intrusive_ptr<Work> allgather(
37
+ std::vector<std::vector<at::Tensor>>& outputTensors,
38
+ std::vector<at::Tensor>& inputTensors,
39
+ const AllgatherOptions& opts = AllgatherOptions()) override;
40
+
41
+ c10::intrusive_ptr<Work> _allgather_base(
42
+ at::Tensor& outputBuffer,
43
+ at::Tensor& inputBuffer,
44
+ const AllgatherOptions& opts = AllgatherOptions()) override;
45
+
46
+ // This function is deprecated and will be moved out of ProcessGroup to comms:
47
+ // * do not add dependencies on this function,
48
+ // * do not implement it in your ProcessGroup, implement _allgather_base
49
+ // instead.
50
+ c10::intrusive_ptr<Work> allgather_coalesced(
51
+ std::vector<std::vector<at::Tensor>>& outputTensorLists,
52
+ std::vector<at::Tensor>& inputTensors,
53
+ const AllgatherOptions& opts = AllgatherOptions()) override;
54
+
55
+ c10::intrusive_ptr<Work> gather(
56
+ std::vector<std::vector<at::Tensor>>& outputTensors,
57
+ std::vector<at::Tensor>& inputTensors,
58
+ const GatherOptions& opts = GatherOptions()) override;
59
+
60
+ c10::intrusive_ptr<Work> scatter(
61
+ std::vector<at::Tensor>& outputTensors,
62
+ std::vector<std::vector<at::Tensor>>& inputTensors,
63
+ const ScatterOptions& opts = ScatterOptions()) override;
64
+
65
+ c10::intrusive_ptr<Work> reduce_scatter(
66
+ std::vector<at::Tensor>& outputTensors,
67
+ std::vector<std::vector<at::Tensor>>& inputTensors,
68
+ const ReduceScatterOptions& opts = ReduceScatterOptions()) override;
69
+
70
+ c10::intrusive_ptr<Work> alltoall_base(
71
+ at::Tensor& outputTensor,
72
+ at::Tensor& inputTensor,
73
+ std::vector<int64_t>& outputSplitSizes,
74
+ std::vector<int64_t>& inputSplitSizes,
75
+ const AllToAllOptions& opts = AllToAllOptions()) override;
76
+
77
+ c10::intrusive_ptr<Work> alltoall(
78
+ std::vector<at::Tensor>& outputTensors,
79
+ std::vector<at::Tensor>& inputTensors,
80
+ const AllToAllOptions& opts = AllToAllOptions()) override;
81
+
82
+ void monitoredBarrier(const BarrierOptions& opts, bool waitAllRanks = false)
83
+ override;
84
+
85
+ // Agrees on an initial sequence number for the whole group by having rank 0
86
+ // create it and broadcast it to other ranks using the store. Only implemented
87
+ // for GLOO and NCCL backends currently.
88
+ // dont implement this
89
+ void setSequenceNumberForGroup() override;
90
+
91
+ // Retrieves the current sequence number for the whole group, which should be
92
+ // in sync. If the returned number is not consistent across the group, it
93
+ // may indicate that there is some sort of collective desynchronization.
94
+ uint64_t getSequenceNumberForGroup() override; // just call underlying
95
+
96
+ c10::intrusive_ptr<Work> send(
97
+ std::vector<at::Tensor>& tensors,
98
+ int dstRank,
99
+ int tag) override;
100
+
101
+ c10::intrusive_ptr<Work> recv(
102
+ std::vector<at::Tensor>& tensors,
103
+ int srcRank,
104
+ int tag) override;
105
+
106
+ c10::intrusive_ptr<Work> recvAnysource(
107
+ std::vector<at::Tensor>& tensors,
108
+ int tag) override;
109
+
110
+ c10::intrusive_ptr<Work> barrier(
111
+ const BarrierOptions& opts = BarrierOptions()) override;
112
+
113
+ c10::intrusive_ptr<Work> _reduce_scatter_base(
114
+ at::Tensor& outputBuffer,
115
+ at::Tensor& inputBuffer,
116
+ const ReduceScatterOptions& opts) override;
117
+
118
+ void startCoalescing() override;
119
+
120
+ c10::intrusive_ptr<Work> endCoalescing() override;
121
+
122
+ c10::intrusive_ptr<Backend> getWrappedPg() const;
123
+
124
+ private:
125
+ // Underlying process group that actual application collectives will be
126
+ // dispatched to
127
+ c10::intrusive_ptr<Backend> backend_;
128
+ // Gloo process group responsible for internal coordination such as monitored
129
+ // barrier, sequence number checking, collective fingerprint collecting.
130
+ c10::intrusive_ptr<Backend> glooBackend_;
131
+ // Conducts several checks to ensure that the underlying collective is well
132
+ // formed with the goal of notifying the user about incorrect collective use
133
+ // in the application.
134
+ void runCollectiveChecks(
135
+ OpType op_type,
136
+ const std::vector<at::Tensor>& tensors);
137
+ };
138
+ } // namespace c10d
139
+
140
+ #endif // USE_C10D_GLOO
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/RankLocal.hpp ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ #pragma once
3
+
4
+ #include <shared_mutex>
5
+
6
+ #include <torch/csrc/autograd/function.h>
7
+
8
+ namespace c10d {
9
+
10
+ // `RankLocal` maintains a unique instance of T for each non-autograd thread.
11
+ // For non-autograd threads, `RankLocal<T>::get()` functions similar to
12
+ // thread_local. For autograd threads, `RankLocal<T>::get()` returns the
13
+ // instance of T corresponding to the enqueuing non-autograd thread. The
14
+ // mechanism allows for rank-specific context shared between forward and
15
+ // backward. It works for both the one-rank-per-process and one-rank-per-thread
16
+ // scenarios.
17
+ //
18
+ // NOTE: RankLocal doesn't make the underlying objects thread-safe.
19
+ template <typename T>
20
+ class RankLocal {
21
+ public:
22
+ RankLocal(const RankLocal&) = delete;
23
+ RankLocal& operator=(const RankLocal&) = delete;
24
+
25
+ static T& get() {
26
+ // Fast path: non-autograd threads can simply return
27
+ // the object reference cached in TLS.
28
+ if (cached_ != nullptr) {
29
+ return *cached_;
30
+ }
31
+ const auto node = torch::autograd::get_current_node();
32
+ auto fwd_thread_id = node == nullptr ? at::RecordFunction::currentThreadId()
33
+ : node->thread_id();
34
+ // Optimistically acquire the read lock first, since most likely we are in
35
+ // an autograd thread and the object has already been constructed.
36
+ {
37
+ std::shared_lock read_lock(lock_);
38
+ auto it = thread_id_to_rank_local_.find(fwd_thread_id);
39
+ if (it != thread_id_to_rank_local_.end()) {
40
+ // Cache for non-autograd threads
41
+ if (node == nullptr) {
42
+ cached_ = &it->second;
43
+ }
44
+ return it->second;
45
+ }
46
+ }
47
+
48
+ std::unique_lock write_lock(lock_);
49
+ auto [it, _] = thread_id_to_rank_local_.try_emplace(fwd_thread_id);
50
+ // Cache for non-autograd threads
51
+ if (node == nullptr) {
52
+ cached_ = &it->second;
53
+ }
54
+ return it->second;
55
+ }
56
+
57
+ private:
58
+ RankLocal(){};
59
+ thread_local static T* cached_;
60
+ static std::unordered_map<uint64_t, T> thread_id_to_rank_local_;
61
+ static std::shared_mutex lock_;
62
+ };
63
+
64
+ template <typename T>
65
+ thread_local T* RankLocal<T>::cached_ = nullptr;
66
+
67
+ template <typename T>
68
+ std::unordered_map<uint64_t, T> RankLocal<T>::thread_id_to_rank_local_;
69
+
70
+ template <typename T>
71
+ std::shared_mutex RankLocal<T>::lock_;
72
+
73
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/SymmetricMemory.hpp ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/ATen.h>
4
+ #include <torch/csrc/distributed/c10d/Store.hpp>
5
+
6
+ namespace c10d {
7
+ namespace symmetric_memory {
8
+
9
+ // SymmetricMemory represents symmetric allocations across a group of devices.
10
+ // The allocations represented by a SymmetricMemory object are accessible by
11
+ // all devices in the group. The class can be used for op-level custom
12
+ // communication patterns (via the get_buffer APIs and the synchronization
13
+ // primitives), as well as custom communication kernels (via the buffer and
14
+ // signal_pad device pointers).
15
+ //
16
+ // To acquire a SymmetricMemory object, each rank first allocates
17
+ // identical-sized memory via SymmetricMemoryAllocator::alloc(), then invokes
18
+ // SymmetricMemoryAllocator::rendezvous() on the memory to establish the
19
+ // association across peer buffers. The rendezvous is a one-time process, and
20
+ // the mapping between a local memory memory and the associated SymmetricMemory
21
+ // object is unique.
22
+ //
23
+ // NOTE [symmetric memory signal pad]
24
+ // Signal pads are P2P-accessible memory regions designated for
25
+ // synchronization. SymmetricMemory offers built-in synchronization primitives
26
+ // such as barriers, put_signal, and wait_signal, which are all based on signal
27
+ // pads. Users may utilize signal pads for their own synchronization logic,
28
+ // provided that the signal pads remain zero-filled following successful
29
+ // synchronization.
30
+ //
31
+ // NOTE [symmetric memory synchronization channel]
32
+ // Synchronization channels allow users to use a single SymmetricMemory object
33
+ // to perform isolated synchronizations on different streams. For example,
34
+ // consider the case in which two barriers are issued on two streams for
35
+ // different purposes. Without the concept of channels, we cannot guarantee the
36
+ // correctness of the barriers since signals issued from barrier on stream A
37
+ // can be received by the barrier on stream B. By specifying different channels
38
+ // for these two barriers, they can operate correctly in parallel.
39
+ class TORCH_API SymmetricMemory : public c10::intrusive_ptr_target {
40
+ public:
41
+ virtual ~SymmetricMemory() {}
42
+
43
+ virtual std::vector<void*> get_buffer_ptrs() = 0;
44
+ virtual std::vector<void*> get_signal_pad_ptrs() = 0;
45
+
46
+ // get_buffer_ptrs_dev() and get_signal_pad_ptrs_dev() each return a pointer
47
+ // to a device array of size world_size, containing buffer pointers and
48
+ // signal pad pointers, respectively.
49
+ virtual void** get_buffer_ptrs_dev() = 0;
50
+ virtual void** get_signal_pad_ptrs_dev() = 0;
51
+ virtual size_t get_buffer_size() = 0;
52
+ virtual size_t get_signal_pad_size() = 0;
53
+
54
+ virtual bool has_multicast_support() = 0;
55
+ virtual void* get_multicast_ptr() = 0;
56
+
57
+ virtual at::Tensor get_buffer(
58
+ int rank,
59
+ c10::IntArrayRef sizes,
60
+ c10::ScalarType dtype,
61
+ int64_t storage_offset) = 0;
62
+
63
+ virtual void barrier(int channel) = 0;
64
+ virtual void put_signal(int dst_rank, int channel) = 0;
65
+ virtual void wait_signal(int src_rank, int channel) = 0;
66
+
67
+ virtual int get_rank() = 0;
68
+ virtual int get_world_size() = 0;
69
+ };
70
+
71
+ class SymmetricMemoryAllocator : public c10::intrusive_ptr_target {
72
+ public:
73
+ virtual ~SymmetricMemoryAllocator(){};
74
+
75
+ virtual void* alloc(
76
+ size_t size,
77
+ int device_idx,
78
+ const std::string& group_name) = 0;
79
+
80
+ virtual void free(void* ptr) = 0;
81
+ virtual size_t get_alloc_size(void* ptr) = 0;
82
+ virtual c10::intrusive_ptr<SymmetricMemory> rendezvous(void* ptr) = 0;
83
+ virtual bool is_rendezvous_completed(void* ptr) = 0;
84
+ virtual bool has_multicast_support(int device_idx) = 0;
85
+ };
86
+
87
+ C10_EXPORT bool is_finalizing();
88
+
89
+ C10_EXPORT void register_allocator(
90
+ c10::DeviceType device_type,
91
+ c10::intrusive_ptr<SymmetricMemoryAllocator> allocator);
92
+
93
+ C10_EXPORT c10::intrusive_ptr<SymmetricMemoryAllocator> get_allocator(
94
+ c10::DeviceType device_type);
95
+
96
+ // Set a store for rendezvousing symmetric allocations on a group of devices
97
+ // identified by `group_name`. The concept of groups is logical; users can
98
+ // utilize predefined groups (e.g., a group of device identified by a
99
+ // ProcessGroup) or create custom ones. Note that a SymmetricMemoryAllocator
100
+ // backends might employ a more efficient communication channel for the actual
101
+ // rendezvous process and only use the store for bootstrapping purposes.
102
+ TORCH_API void set_group_info(
103
+ const std::string& group_name,
104
+ int rank,
105
+ int world_size,
106
+ c10::intrusive_ptr<Store> store);
107
+
108
+ struct GroupInfo {
109
+ int rank;
110
+ int world_size;
111
+ c10::intrusive_ptr<c10d::Store> store;
112
+ };
113
+
114
+ C10_EXPORT const GroupInfo& get_group_info(const std::string& group_name);
115
+
116
+ // Identical to empty_strided, but allows symmetric memory access to be
117
+ // established for the allocated tensor via SymmetricMemory::rendezvous(). This
118
+ // function itself is not a collective operation. It invokes
119
+ // SymmetricMemoryAllocator::alloc() for the requested device under the hood.
120
+ //
121
+ // NOTE [symmetric memory persistent allocation]
122
+ // If an `alloc_id` is supplied, empty_strided_p2p will perform persistent
123
+ // allocation. This makes the function cache allocated memory and ensure that
124
+ // invocations with the same `alloc_id` receive tensors backed by the same
125
+ // memory address. For safety, if a previous persistent allocation is still
126
+ // active (i.e., the storage of the returned tensor is still alive), persistent
127
+ // allocations with the same `alloc_id` will fail. This determinism coupled
128
+ // with memory planning of communication buffers (e.g., by Inductor) allows
129
+ // communication algorithms to reliably reuse previously established remote
130
+ // memory access.
131
+ TORCH_API at::Tensor empty_strided_p2p(
132
+ c10::IntArrayRef size,
133
+ c10::IntArrayRef stride,
134
+ c10::ScalarType dtype,
135
+ c10::Device device,
136
+ const std::string& group_name,
137
+ std::optional<uint64_t> alloc_id);
138
+
139
+ // Establishes symmetric memory access on tensors allocated via
140
+ // empty_strided_p2p() and empty_strided_p2p_persistent(). rendezvous() is a
141
+ // one-time process, and the mapping between a local memory region and the
142
+ // associated SymmetricMemory object is unique. Subsequent calls to
143
+ // rendezvous() with the same tensor, or tensors allocated with
144
+ // empty_strided_p2p_persistent() using the same alloc_id, will receive the
145
+ // cached SymmetricMemory object.
146
+ //
147
+ // The function has a collective semantic and must be invoked simultaneously
148
+ // from all rendezvous participants.
149
+ TORCH_API c10::intrusive_ptr<SymmetricMemory> rendezvous(
150
+ const at::Tensor& tensor);
151
+
152
+ // Returns the SymmetricMemory object associated with the tensor. It can only
153
+ // be invoked after rendezvous() but does not need to be invoked collectively.
154
+ TORCH_API c10::intrusive_ptr<SymmetricMemory> get_symmetric_memory(
155
+ const at::Tensor& tensor);
156
+
157
+ TORCH_API bool has_multicast_support(
158
+ c10::DeviceType device_type,
159
+ int device_idx);
160
+ } // namespace symmetric_memory
161
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/TCPStore.hpp ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <cstddef>
4
+ #include <cstdint>
5
+ #include <memory>
6
+
7
+ #include <torch/csrc/distributed/c10d/Store.hpp>
8
+
9
+ namespace c10d {
10
+ namespace detail {
11
+
12
+ class TCPServer;
13
+
14
+ class TCPClient;
15
+
16
+ struct SocketAddress {
17
+ std::string host{};
18
+ std::uint16_t port{};
19
+ };
20
+
21
+ } // namespace detail
22
+
23
+ struct TCPStoreOptions {
24
+ static constexpr std::uint16_t kDefaultPort = 29500;
25
+
26
+ std::uint16_t port = kDefaultPort;
27
+ bool isServer = false;
28
+ std::optional<std::size_t> numWorkers = std::nullopt;
29
+ bool waitWorkers = true;
30
+ std::chrono::milliseconds timeout = Store::kDefaultTimeout;
31
+
32
+ // A boolean value indicating whether multiple store instances can be
33
+ // initialized with the same host:port pair.
34
+ bool multiTenant = false;
35
+
36
+ // If specified, and if isServer is true, the underlying TCPServer will take
37
+ // over the bound socket associated to this fd. This option is useful to avoid
38
+ // port assignment races in certain scenarios.
39
+ std::optional<int> masterListenFd = std::nullopt;
40
+
41
+ // A boolean value indicating whether to use the experimental libUV backend.
42
+ bool useLibUV = true;
43
+ };
44
+
45
+ class TORCH_API TCPStore : public Store {
46
+ public:
47
+ static constexpr std::chrono::milliseconds kConnectRetryDelay{1000};
48
+
49
+ explicit TCPStore(std::string host, const TCPStoreOptions& opts = {});
50
+
51
+ [[deprecated("Use TCPStore(host, opts) instead.")]] explicit TCPStore(
52
+ const std::string& masterAddr,
53
+ std::uint16_t masterPort,
54
+ std::optional<int> numWorkers = std::nullopt,
55
+ bool isServer = false,
56
+ const std::chrono::milliseconds& timeout = kDefaultTimeout,
57
+ bool waitWorkers = true);
58
+
59
+ ~TCPStore() override;
60
+
61
+ void set(const std::string& key, const std::vector<uint8_t>& value) override;
62
+
63
+ std::vector<uint8_t> compareSet(
64
+ const std::string& key,
65
+ const std::vector<uint8_t>& expectedValue,
66
+ const std::vector<uint8_t>& desiredValue) override;
67
+
68
+ std::vector<uint8_t> get(const std::string& key) override;
69
+
70
+ int64_t add(const std::string& key, int64_t value) override;
71
+
72
+ bool deleteKey(const std::string& key) override;
73
+
74
+ bool check(const std::vector<std::string>& keys) override;
75
+
76
+ int64_t getNumKeys() override;
77
+
78
+ void wait(const std::vector<std::string>& keys) override;
79
+
80
+ void wait(
81
+ const std::vector<std::string>& keys,
82
+ const std::chrono::milliseconds& timeout) override;
83
+
84
+ void append(const std::string& key, const std::vector<uint8_t>& value)
85
+ override;
86
+
87
+ std::vector<std::vector<uint8_t>> multiGet(
88
+ const std::vector<std::string>& keys) override;
89
+
90
+ void multiSet(
91
+ const std::vector<std::string>& keys,
92
+ const std::vector<std::vector<uint8_t>>& values) override;
93
+
94
+ bool hasExtendedApi() const override;
95
+
96
+ // Waits for all workers to join.
97
+ void waitForWorkers();
98
+
99
+ // Returns the hostname used by the TCPStore.
100
+ const std::string& getHost() const noexcept {
101
+ return addr_.host;
102
+ }
103
+
104
+ // Returns the port used by the TCPStore.
105
+ std::uint16_t getPort() const noexcept {
106
+ return addr_.port;
107
+ }
108
+
109
+ bool isLibUvBackend() const noexcept {
110
+ return usingLibUv_;
111
+ }
112
+
113
+ // note(xilunwu): this function is only for internal testing
114
+ void _splitSet(const std::string& key, const std::vector<uint8_t>& data);
115
+
116
+ std::string repr() const;
117
+
118
+ private:
119
+ int64_t incrementValueBy(const std::string& key, int64_t delta);
120
+
121
+ void ping();
122
+ void validate();
123
+
124
+ std::vector<uint8_t> doGet(const std::string& key);
125
+
126
+ void doWait(
127
+ c10::ArrayRef<std::string> keys,
128
+ std::chrono::milliseconds timeout);
129
+
130
+ detail::SocketAddress addr_;
131
+ std::shared_ptr<detail::TCPServer> server_;
132
+ std::unique_ptr<detail::TCPClient> client_;
133
+ std::optional<std::size_t> numWorkers_;
134
+
135
+ const std::string initKey_ = "init/";
136
+ const std::string keyPrefix_ = "/";
137
+ std::mutex activeOpLock_;
138
+ bool usingLibUv_ = true;
139
+ };
140
+
141
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Types.hpp ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/c10d/Store.hpp>
4
+
5
+ #include <chrono>
6
+ #include <cstdint>
7
+
8
+ #include <ATen/core/Tensor.h>
9
+ #include <ATen/core/ivalue.h>
10
+
11
+ #include <c10/macros/Macros.h>
12
+ #include <c10/util/intrusive_ptr.h>
13
+
14
+ namespace c10d {
15
+
16
+ // Base class for supplementary data potentially needed by ReduceOps
17
+ struct TORCH_API _SupplementBase : torch::CustomClassHolder {
18
+ ~_SupplementBase() override = default;
19
+ };
20
+
21
+ // Supplementary data specific to NCCL PREMUL_SUM
22
+ // The point of use in ProcessGroupNCCL knows how to unpack it.
23
+ struct NCCLPreMulSumSupplement : _SupplementBase {
24
+ double double_factor{0.0};
25
+ at::Tensor tensor_factor;
26
+ NCCLPreMulSumSupplement(double f) : double_factor{f} {}
27
+ NCCLPreMulSumSupplement(at::Tensor t) : tensor_factor{std::move(t)} {
28
+ TORCH_CHECK_EQ(tensor_factor.numel(), 1);
29
+ }
30
+ };
31
+
32
+ // Other ReduceOps that need different supplementary data can also
33
+ // derive from _SupplementBase.
34
+ struct TORCH_API ReduceOp : torch::CustomClassHolder {
35
+ // note(crcrpar): RedOpType could be defined outside of `ReduceOp`
36
+ enum RedOpType : uint8_t {
37
+ SUM = 0,
38
+ AVG = 1,
39
+ PRODUCT = 2,
40
+ MIN = 3,
41
+ MAX = 4,
42
+ BAND = 5, // Bitwise AND
43
+ BOR = 6, // Bitwise OR
44
+ BXOR = 7, // Bitwise XOR
45
+ PREMUL_SUM = 8, // Multiply by a user-supplied constant before summing.
46
+ UNUSED = 9
47
+ };
48
+
49
+ ReduceOp() = default;
50
+
51
+ ReduceOp(RedOpType op) : op_(op) {
52
+ TORCH_INTERNAL_ASSERT(
53
+ op_ != PREMUL_SUM,
54
+ "Use `torch.distributed._make_nccl_premul_sum` to create an instance of ReduceOp with PREMUL_SUM");
55
+ }
56
+
57
+ ReduceOp(
58
+ RedOpType op,
59
+ const c10::intrusive_ptr<_SupplementBase>& optional_supplement) {
60
+ if (optional_supplement) {
61
+ op_ = op;
62
+ } else {
63
+ supplement_ = optional_supplement;
64
+ }
65
+ }
66
+
67
+ // The heap resource supplement_, if it exists, is managed by a
68
+ // c10::intrusive_ptr, so constructors and operator= can be simple
69
+ ReduceOp(const ReduceOp& other) = default;
70
+ ReduceOp& operator=(const ReduceOp& other) = default;
71
+
72
+ ReduceOp(ReduceOp&& other) = default;
73
+ ReduceOp& operator=(ReduceOp&& other) = default;
74
+
75
+ operator RedOpType() const {
76
+ return op_;
77
+ }
78
+
79
+ bool operator==(const std::uint8_t other) {
80
+ TORCH_INTERNAL_ASSERT(other < 9, "Invalid other op value");
81
+ return other == op_;
82
+ }
83
+
84
+ bool operator==(const ReduceOp::RedOpType other) {
85
+ return *this == static_cast<std::uint8_t>(other);
86
+ }
87
+
88
+ // todo(crcrpar): Handle `RedOpType::PREMUL_SUM` with its scaling factor.
89
+ bool operator==(const ReduceOp& other) {
90
+ return *this == other.op_;
91
+ }
92
+
93
+ RedOpType op_ = SUM;
94
+ // supplement_ is "type-erased" storage for optional supplementary
95
+ // data the op might need.
96
+ // The point of use will know the derived type supplement_ really is,
97
+ // and downcast its pointer to extract the data as the needed type(s).
98
+ // Right now, only PREMUL_SUM needs supplementary data, but the same
99
+ // mechanism could extend to support other nontrivial reduce ops with
100
+ // different supplementary payloads.
101
+ c10::intrusive_ptr<_SupplementBase> supplement_;
102
+ };
103
+
104
+ template <typename T>
105
+ ReduceOp makeNCCLPreMulSum(const T& factor) {
106
+ ReduceOp rop;
107
+ rop.op_ = ReduceOp::PREMUL_SUM;
108
+ rop.supplement_ = c10::make_intrusive<NCCLPreMulSumSupplement>(factor);
109
+ return rop;
110
+ }
111
+
112
+ constexpr auto kUnsetTimeout = std::chrono::milliseconds(-1);
113
+
114
+ struct BroadcastOptions {
115
+ int64_t rootRank = 0;
116
+ int64_t rootTensor = 0;
117
+ std::chrono::milliseconds timeout = kUnsetTimeout;
118
+ bool asyncOp = true;
119
+ };
120
+
121
+ struct AllreduceOptions {
122
+ ReduceOp reduceOp = ReduceOp::SUM;
123
+ std::chrono::milliseconds timeout = kUnsetTimeout;
124
+ std::optional<at::Tensor> sparseIndices = std::nullopt;
125
+ };
126
+
127
+ struct AllreduceCoalescedOptions : AllreduceOptions {};
128
+
129
+ struct ReduceOptions {
130
+ ReduceOp reduceOp = ReduceOp::SUM;
131
+ int64_t rootRank = 0;
132
+ int64_t rootTensor = 0;
133
+ std::chrono::milliseconds timeout = kUnsetTimeout;
134
+ };
135
+
136
+ struct AllgatherOptions {
137
+ std::chrono::milliseconds timeout = kUnsetTimeout;
138
+ bool asyncOp = true;
139
+ };
140
+
141
+ struct GatherOptions {
142
+ int64_t rootRank = 0;
143
+ std::chrono::milliseconds timeout = kUnsetTimeout;
144
+ };
145
+
146
+ struct ScatterOptions {
147
+ int64_t rootRank = 0;
148
+ std::chrono::milliseconds timeout = kUnsetTimeout;
149
+ bool asyncOp = true;
150
+ };
151
+
152
+ struct ReduceScatterOptions {
153
+ ReduceOp reduceOp = ReduceOp::SUM;
154
+ std::chrono::milliseconds timeout = kUnsetTimeout;
155
+ bool asyncOp = true;
156
+ };
157
+
158
+ struct AllToAllOptions {
159
+ std::chrono::milliseconds timeout = kUnsetTimeout;
160
+ };
161
+
162
+ struct BarrierOptions {
163
+ std::vector<int64_t> device_ids;
164
+ std::chrono::milliseconds timeout = kUnsetTimeout;
165
+ std::optional<at::Device> device;
166
+ };
167
+
168
+ struct DistributedBackendOptions {
169
+ c10::intrusive_ptr<::c10d::Store> store;
170
+ int group_rank;
171
+ int group_size;
172
+ std::chrono::duration<float> timeout;
173
+ std::string group_id;
174
+ std::vector<int64_t> global_ranks_in_group;
175
+ };
176
+
177
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/UCCUtils.hpp ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #ifdef USE_C10D_UCC
4
+
5
+ #include <torch/csrc/distributed/c10d/ProcessGroup.hpp>
6
+ #include <torch/csrc/distributed/c10d/Store.hpp>
7
+ #include <ucc/api/ucc.h>
8
+
9
+ namespace c10d {
10
+
11
+ // Macro to generate the error message on a non-successful UCC return value.
12
+ #define TORCH_UCC_GET_ERROR_MSG(_err, _error_msg, _result) \
13
+ do { \
14
+ _err = c10::str( \
15
+ "[", \
16
+ std::string(__FILE__), \
17
+ ":", \
18
+ std::to_string(__LINE__), \
19
+ "] ", \
20
+ logger->getLogPrefix(), \
21
+ _error_msg, \
22
+ ", error code ", \
23
+ _result, \
24
+ ": ", \
25
+ ucc_status_string(_result), \
26
+ ", system error code ", \
27
+ errno); \
28
+ } while (0)
29
+
30
+ // Macro to throw on a non-successful UCC return value.
31
+ #define TORCH_UCC_CHECK(_cmd, _error_msg) \
32
+ do { \
33
+ ucc_status_t result = _cmd; \
34
+ if (result != UCC_OK) { \
35
+ std::string err; \
36
+ TORCH_UCC_GET_ERROR_MSG(err, _error_msg, result); \
37
+ TORCH_CHECK(false, err); \
38
+ } \
39
+ } while (0)
40
+
41
+ // Macro and throw on a non-successful UCC return value and free its request.
42
+ #define TORCH_UCC_CHECK_REQUEST(_request, _cmd, _error_msg) \
43
+ do { \
44
+ ucc_status_t result = _cmd; \
45
+ if (result != UCC_OK) { \
46
+ std::string err; \
47
+ TORCH_UCC_GET_ERROR_MSG(err, _error_msg, result); \
48
+ if (_request != nullptr) { \
49
+ ucc_collective_finalize(_request); \
50
+ } \
51
+ TORCH_CHECK(false, err); \
52
+ } \
53
+ } while (0)
54
+
55
+ // Macros to print logs with unified format
56
+ #define TORCH_UCC_LOG_ERROR(_phase, _msg) \
57
+ LOG(ERROR) << logger->getLogPrefix(_phase) << "[ERROR] " << _msg;
58
+ #define TORCH_UCC_LOG_INFO(_phase, _msg) \
59
+ LOG(INFO) << logger->getLogPrefix(_phase) << "[INFO] " << _msg;
60
+ #define TORCH_UCC_LOG_DEBUG(_phase, _msg) \
61
+ VLOG(1) << logger->getLogPrefix(_phase) << "[DEBUG] " << _msg;
62
+
63
+ enum torch_ucc_phase_t {
64
+ TORCH_UCC_UNKNOWN = -1,
65
+ TORCH_UCC_INIT,
66
+ TORCH_UCC_HEALTH_CHECK,
67
+ TORCH_UCC_READY,
68
+ TORCH_UCC_COLL_POST,
69
+ TORCH_UCC_COLL_PROGRESS,
70
+ TORCH_UCC_FINALIZE,
71
+ };
72
+
73
+ const std::map<torch_ucc_phase_t, std::string> ucc_phase_map = {
74
+ {TORCH_UCC_UNKNOWN, "UNKNOWN"},
75
+ {TORCH_UCC_INIT, "INIT"},
76
+ {TORCH_UCC_HEALTH_CHECK, "HEALTH_CHECK"},
77
+ {TORCH_UCC_READY, "READY"},
78
+ {TORCH_UCC_COLL_POST, "COLL_POST"},
79
+ {TORCH_UCC_COLL_PROGRESS, "COLL_PROGRESS"},
80
+ {TORCH_UCC_FINALIZE, "FINALIZE"},
81
+ };
82
+
83
+ class CommTraceLogger;
84
+
85
+ class TORCH_API ProcessGroupUCCLogger : public torch::CustomClassHolder {
86
+ public:
87
+ ProcessGroupUCCLogger();
88
+ ProcessGroupUCCLogger(std::string log_prefix, torch_ucc_phase_t phase);
89
+
90
+ std::string getLogPrefix(torch_ucc_phase_t phase = TORCH_UCC_UNKNOWN);
91
+ void setLogPrefix(std::string log_prefix);
92
+ inline void setPhase(torch_ucc_phase_t phase) {
93
+ local_phase = phase;
94
+ }
95
+
96
+ void initCommsTracer();
97
+ void flushComms(int rank, int world_size);
98
+ std::shared_ptr<CommTraceLogger> trace_generator = nullptr;
99
+
100
+ protected:
101
+ std::string log_prefix;
102
+ torch_ucc_phase_t local_phase = TORCH_UCC_UNKNOWN;
103
+ bool initialized_CommTraceLogger = false;
104
+ };
105
+
106
+ struct torch_ucc_oob_coll_info_t {
107
+ c10::intrusive_ptr<Store> store;
108
+ uint32_t comm_id;
109
+ int rank;
110
+ int size;
111
+ void* rbuf;
112
+ size_t msglen;
113
+ std::string getKey(std::string key) {
114
+ return std::to_string(comm_id) + key;
115
+ }
116
+ };
117
+
118
+ class CommBase {
119
+ public:
120
+ CommBase(const c10::intrusive_ptr<ProcessGroupUCCLogger>& logger_)
121
+ : logger(logger_) {}
122
+ virtual void progress() = 0;
123
+ virtual void free_request(ucc_coll_req_h request) = 0;
124
+ virtual ~CommBase() {}
125
+ c10::intrusive_ptr<ProcessGroupUCCLogger> logger;
126
+ };
127
+ class CommUCC : public CommBase {
128
+ public:
129
+ ucc_lib_h lib{nullptr};
130
+ ucc_context_h context{nullptr};
131
+
132
+ public:
133
+ void progress() override;
134
+ CommUCC(
135
+ std::shared_ptr<torch_ucc_oob_coll_info_t> oob,
136
+ const c10::intrusive_ptr<ProcessGroupUCCLogger>& logger);
137
+ void free_request(ucc_coll_req_h request) override;
138
+ ~CommUCC();
139
+ };
140
+
141
+ ucc_status_t oob_allgather(
142
+ void* sbuf,
143
+ void* rbuf,
144
+ size_t msglen,
145
+ void* coll_info,
146
+ void** req);
147
+
148
+ ucc_status_t oob_allgather_test(void* req);
149
+
150
+ ucc_status_t oob_allgather_free(void* req);
151
+
152
+ // trim: remove spaces before and after the string view
153
+ // implementation borrowed from https://stackoverflow.com/a/17976541
154
+ inline c10::string_view trim(c10::string_view s) {
155
+ auto wsfront = std::find_if_not(
156
+ s.begin(), s.end(), [](int c) { return std::isspace(c); });
157
+ auto wsback = std::find_if_not(s.rbegin(), s.rend(), [](int c) {
158
+ return std::isspace(c);
159
+ }).base();
160
+ return (
161
+ wsback <= wsfront ? "" : s.substr(wsfront - s.begin(), wsback - wsfront));
162
+ }
163
+
164
+ inline std::string tolower(c10::string_view s) {
165
+ std::string result;
166
+ result.reserve(s.size());
167
+ for (auto c : s) {
168
+ result.push_back(std::tolower(c));
169
+ }
170
+ return result;
171
+ }
172
+
173
+ inline std::vector<std::string> parse_list(std::string list) {
174
+ std::vector<std::string> result;
175
+ list = tolower(trim(list));
176
+ while (!list.empty()) {
177
+ const auto end_pos = list.find_first_of(',');
178
+ const auto token = trim(list.substr(0, end_pos));
179
+ result.push_back(std::string(token));
180
+ list = (end_pos != c10::string_view::npos) ? list.substr(end_pos + 1) : "";
181
+ }
182
+ return result;
183
+ }
184
+
185
+ } // namespace c10d
186
+
187
+ #endif // USE_C10D_UCC
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/WinSockUtils.hpp ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/c10d/Utils.hpp>
4
+
5
+ namespace c10d::tcputil {
6
+
7
+ #define CONNECT_SOCKET_OFFSET 1
8
+
9
+ inline int poll(struct pollfd* fdArray, unsigned long fds, int timeout) {
10
+ return WSAPoll(fdArray, fds, timeout);
11
+ }
12
+
13
+ inline void addPollfd(
14
+ std::vector<struct pollfd>& fds,
15
+ int socket,
16
+ short events) {
17
+ fds.push_back({(SOCKET)socket, events});
18
+ }
19
+
20
+ inline struct ::pollfd getPollfd(int socket, short events) {
21
+ struct ::pollfd res = {(SOCKET)socket, events};
22
+ return res;
23
+ }
24
+
25
+ } // namespace c10d::tcputil
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/Work.hpp ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/ATen.h>
4
+ #include <chrono>
5
+ #include <mutex>
6
+ #include <vector>
7
+
8
+ constexpr auto kNoTimeout = std::chrono::milliseconds(0);
9
+
10
+ namespace c10d {
11
+
12
+ constexpr const char* const kSeqNumStoreKey = "SEQ_NUM_STORE_KEY";
13
+
14
+ enum class OpType : std::uint8_t {
15
+ BROADCAST = 0,
16
+ ALLREDUCE = 1,
17
+ ALLREDUCE_COALESCED = 2,
18
+ REDUCE = 3,
19
+ ALLGATHER = 4,
20
+ _ALLGATHER_BASE = 5,
21
+ ALLGATHER_COALESCED = 6,
22
+ GATHER = 7,
23
+ SCATTER = 8,
24
+ REDUCE_SCATTER = 9,
25
+ ALLTOALL_BASE = 10,
26
+ ALLTOALL = 11,
27
+ SEND = 12,
28
+ RECV = 13,
29
+ RECVANYSOURCE = 14,
30
+ BARRIER = 15,
31
+ _REDUCE_SCATTER_BASE = 16,
32
+ COALESCED = 17,
33
+ _ALLREDUCE_SPARSE = 18,
34
+ UNKNOWN = 100,
35
+ };
36
+
37
+ // Converts OpType to human readable string.
38
+ TORCH_API std::string opTypeToString(OpType opType);
39
+
40
+ // Whether or not an OP is an p2p op (SEND, RECV, RECVANYSOURCE)
41
+ TORCH_API bool isP2POp(OpType opType, bool batchP2P = false);
42
+
43
+ // Please do not use Work API, it is going away, to be
44
+ // replaced by ivalue::Future.
45
+ // Python binding for this class might change, please do not assume
46
+ // this will be bound using pybind.
47
+ class TORCH_API Work : public torch::CustomClassHolder {
48
+ public:
49
+ Work(
50
+ int rank = -1,
51
+ OpType opType = OpType::UNKNOWN,
52
+ const char* profilingTitle = nullptr,
53
+ const std::optional<std::vector<at::Tensor>>& inputTensors =
54
+ std::nullopt);
55
+
56
+ ~Work() override;
57
+
58
+ // Checks if request has completed. Non-blocking operation.
59
+ virtual bool isCompleted();
60
+
61
+ // Returns if the work completed successfully.
62
+ // If false, the exception function can be called to get details.
63
+ virtual bool isSuccess() const;
64
+
65
+ // Returns exception if isSuccess() returned false.
66
+ virtual std::exception_ptr exception() const;
67
+
68
+ // Returns source rank if this objects represents a recv-from-any.
69
+ virtual int sourceRank() const;
70
+
71
+ // Returns result tensors, if applicable.
72
+ // If work is not supposed to have result, we return empty list.
73
+ virtual std::vector<at::Tensor> result();
74
+
75
+ // Ensures that operations on the output tensors that are invoked
76
+ // after this function returns are correctly sequenced after the
77
+ // asynchronous completion of this work.
78
+ //
79
+ // For CUDA tensors, it inserts stream synchronization such that
80
+ // the streams of the caller wait for completion of the
81
+ // asynchronous operations on the destination tensors.
82
+ //
83
+ // For CPU tensors, it is currently a nop.
84
+ //
85
+ // This function should only be used if the caller polls for
86
+ // completion through the `isCompleted` function, it has returned
87
+ // true, and the `isSuccess` function also has returned true.
88
+ //
89
+ virtual void synchronize();
90
+
91
+ // Waits until request completes. Blocking operation.
92
+ // Throws if the work completed with an exception.
93
+ // Returns false if the work is aborted.
94
+ // Otherwise, it always returns true, indicating the work is completed.
95
+ //
96
+ // Functionally equivalent to:
97
+ //
98
+ // while (!isCompleted()) { /* nop */ }
99
+ // auto success = isSuccess();
100
+ // if (!success) { std::rethrow_exception(exception()); }
101
+ // return success;
102
+ //
103
+ virtual bool wait(std::chrono::milliseconds timeout = kNoTimeout);
104
+
105
+ virtual void abort();
106
+
107
+ // Returns a Future object that will be associated with the completion of
108
+ // work. Only NCCL backend is currently supported.
109
+ virtual c10::intrusive_ptr<c10::ivalue::Future> getFuture();
110
+
111
+ virtual float getDuration() const;
112
+
113
+ virtual uint64_t getSequencenumber() const;
114
+
115
+ OpType retrieveOpType() const;
116
+
117
+ static c10::intrusive_ptr<Work> create_from_future(
118
+ const c10::intrusive_ptr<c10::ivalue::Future>&);
119
+
120
+ protected:
121
+ // Completes the work object and optionally sets the exception in a
122
+ // thread-safe manner. Notifies all waiting condition variables as well.
123
+ void finish(std::exception_ptr exception = nullptr);
124
+
125
+ // Similar to finish, but throws an exception if one is already set or
126
+ // provided by the user.
127
+ void finishAndThrow(std::exception_ptr exception);
128
+
129
+ mutable std::mutex mutex_;
130
+ std::condition_variable cv_;
131
+ bool completed_ = false;
132
+ std::exception_ptr exception_;
133
+
134
+ // Current rank of the node.
135
+ const int rank_;
136
+
137
+ // Operation type that this work object refers to.
138
+ OpType opType_;
139
+
140
+ // When profiling, the callback to record end of operation event. This
141
+ // callback needs to be called when collective operation is complete.
142
+ std::function<void()> recordFunctionEndCallback_;
143
+ };
144
+
145
+ struct TORCH_API WorkInfo {
146
+ WorkInfo(
147
+ const OpType& opType,
148
+ const uint64_t seq,
149
+ const std::chrono::time_point<std::chrono::system_clock>& timeStarted,
150
+ const std::chrono::time_point<std::chrono::system_clock>& timeFinished,
151
+ const std::chrono::duration<float>& activeDuration)
152
+ : opType(opType),
153
+ seq(seq),
154
+ timeStarted(timeStarted),
155
+ timeFinished(timeFinished),
156
+ activeDuration(activeDuration) {}
157
+
158
+ OpType opType;
159
+ uint64_t seq;
160
+ std::chrono::time_point<std::chrono::system_clock> timeStarted;
161
+ std::chrono::time_point<std::chrono::system_clock> timeFinished;
162
+ std::chrono::duration<float> activeDuration;
163
+ };
164
+
165
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/c10d.h ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/python_headers.h>
4
+
5
+ namespace torch {
6
+ namespace distributed {
7
+ namespace c10d {
8
+
9
+ PyMethodDef* python_functions();
10
+
11
+ } // namespace c10d
12
+ } // namespace distributed
13
+ } // namespace torch
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/comm.hpp ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/ATen.h>
4
+ #include <ATen/core/ivalue.h>
5
+ #include <torch/csrc/Export.h>
6
+ #include <torch/csrc/distributed/c10d/ProcessGroup.hpp>
7
+ #include <utility>
8
+
9
+ namespace c10d {
10
+
11
+ // Broadcast many tensors to all processes in the process group.
12
+ TORCH_API void broadcast_coalesced(
13
+ const c10::intrusive_ptr<c10d::ProcessGroup>& process_group,
14
+ at::TensorList tensors,
15
+ size_t buffer_size,
16
+ int rank = 0);
17
+
18
+ // This class passes bucket contents tensor to DDP communication hook.
19
+ class TORCH_API GradBucket {
20
+ public:
21
+ explicit GradBucket(
22
+ size_t index,
23
+ size_t bucket_count,
24
+ at::Tensor tensor,
25
+ std::vector<size_t> offsets,
26
+ std::vector<size_t> lengths,
27
+ std::vector<c10::IntArrayRef> sizes_vec,
28
+ std::vector<at::Tensor> parameters,
29
+ std::optional<at::Tensor> sparse_grad_indices)
30
+ : index_(index),
31
+ bucket_count_(bucket_count),
32
+ buffer_(std::move(tensor)),
33
+ offsets_(std::move(offsets)),
34
+ lengths_(std::move(lengths)),
35
+ sizes_vec_(std::move(sizes_vec)),
36
+ parameters_(std::move(parameters)),
37
+ sparse_grad_indices_(std::move(sparse_grad_indices)) {}
38
+
39
+ // Returns the index of the bucket, which is unique across all the buckets.
40
+ size_t getIndex() const {
41
+ return index_;
42
+ }
43
+
44
+ const at::Tensor& getBuffer() const {
45
+ return buffer_;
46
+ }
47
+
48
+ // Returns a mutable buffer compared with the above method.
49
+ at::Tensor& getBufferRef() {
50
+ return buffer_;
51
+ }
52
+
53
+ // Overwrites the buffer at a specific index.
54
+ void setBuffer(at::Tensor& buffer) {
55
+ buffer_ = buffer;
56
+ }
57
+
58
+ // Each tensor in the list that getGradients corresponds to a
59
+ // parameter.
60
+ std::vector<at::Tensor> getGradients() const;
61
+
62
+ // Returns model parameters belonging to this bucket. They are returned in the
63
+ // same order as gradient tensors via getGradients(). For example,
64
+ // getParameters[i] will have its gradient stored in
65
+ // getGradients[i]
66
+ const std::vector<at::Tensor> getParameters() const {
67
+ return parameters_;
68
+ }
69
+
70
+ // Returns whther this bucket is the last bucket to allreduce in an iteration.
71
+ bool isLast() const {
72
+ return index_ == bucket_count_ - 1;
73
+ }
74
+
75
+ std::optional<at::Tensor>& getSparseGradIndices() {
76
+ return sparse_grad_indices_;
77
+ }
78
+
79
+ private:
80
+ size_t index_;
81
+ size_t bucket_count_;
82
+ at::Tensor buffer_;
83
+
84
+ // Per-variable info in buffer_.
85
+ std::vector<size_t> offsets_;
86
+ std::vector<size_t> lengths_;
87
+ std::vector<c10::IntArrayRef> sizes_vec_;
88
+
89
+ // Model parameters for this bucket.
90
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
91
+ const std::vector<at::Tensor> parameters_;
92
+
93
+ // Predefined sparse indices for this bucket (only used for sparse tensors).
94
+ // The gradients will be updated to have indices with these tensor values
95
+ std::optional<at::Tensor> sparse_grad_indices_;
96
+ };
97
+
98
+ // Base class of both `PythonCommHook` and `CppCommHook`.
99
+ // Requires implementing 1) `runHook` method that communicates gradients
100
+ // asynchronously, and 2) `parseHookResult` method that converts the hook
101
+ // result into a tensor.
102
+ class TORCH_API CommHookInterface {
103
+ public:
104
+ virtual ~CommHookInterface() = default;
105
+
106
+ // Passes the input grad bucket to the registered communication hook.
107
+ // Once the tensor in the bucket are ready, kicks off the hook asynchronously
108
+ // and returns a future that holds the communication results.
109
+ virtual c10::intrusive_ptr<c10::ivalue::Future> runHook(
110
+ GradBucket& bucket) = 0;
111
+
112
+ // Returns the resulting tensor once the communication hook result is
113
+ // ready. The resulting tensor will then be copied to the grads of
114
+ // individual parameters.
115
+ virtual at::Tensor parseHookResult(const c10::IValue& result) = 0;
116
+ };
117
+
118
+ namespace detail {
119
+ // This helper function is called both by CppCommHookInterface below and inside
120
+ // reducer.
121
+ TORCH_API at::Tensor parseCppCommHookResult(const c10::IValue& result);
122
+ } // namespace detail
123
+
124
+ // This CppCommHook interface only requires implementing runHook method that
125
+ // potentially uses a state.
126
+ template <typename T>
127
+ class CppCommHookInterface : public CommHookInterface {
128
+ public:
129
+ explicit CppCommHookInterface(T state) : state_(std::move(state)) {}
130
+
131
+ ~CppCommHookInterface() override = default;
132
+
133
+ at::Tensor parseHookResult(const c10::IValue& result) override {
134
+ return detail::parseCppCommHookResult(result);
135
+ }
136
+
137
+ protected:
138
+ T state_;
139
+ };
140
+
141
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/exception.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <stdexcept>
10
+
11
+ #include <c10/macros/Macros.h>
12
+ #include <c10/util/Exception.h>
13
+
14
+ // Utility macro similar to C10_THROW_ERROR, the major difference is that this
15
+ // macro handles exception types defined in the c10d namespace, whereas
16
+ // C10_THROW_ERROR requires an exception to be defined in the c10 namespace.
17
+ #define C10D_THROW_ERROR(err_type, msg) \
18
+ throw ::c10d::err_type( \
19
+ {__func__, __FILE__, static_cast<uint32_t>(__LINE__)}, msg)
20
+
21
+ namespace c10d {
22
+
23
+ using c10::DistNetworkError;
24
+
25
+ class TORCH_API SocketError : public DistNetworkError {
26
+ using DistNetworkError::DistNetworkError;
27
+ };
28
+
29
+ class TORCH_API TimeoutError : public DistNetworkError {
30
+ using DistNetworkError::DistNetworkError;
31
+ };
32
+
33
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/intra_node_comm.hpp ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/ATen.h>
4
+ #include <ATen/cuda/CUDAEvent.h>
5
+ #include <c10/cuda/CUDAStream.h>
6
+ #include <torch/csrc/distributed/c10d/Store.hpp>
7
+ #include <torch/csrc/distributed/c10d/SymmetricMemory.hpp>
8
+ #include <torch/csrc/distributed/c10d/Work.hpp>
9
+
10
+ namespace c10d::intra_node_comm {
11
+
12
+ using namespace c10d::symmetric_memory;
13
+
14
+ constexpr size_t kMaxDevices = 8;
15
+ constexpr size_t kDefaultBufferSize = 10ull * 1024 * 1024;
16
+ constexpr size_t kP2pStateSize = 2048;
17
+
18
+ using NvlMesh = std::array<std::array<size_t, kMaxDevices>, kMaxDevices>;
19
+ using HybridCubeMesh = std::array<std::array<int, 4>, kMaxDevices>;
20
+
21
+ enum class Topology : uint8_t {
22
+ UNKNOWN = 0,
23
+ FULLY_CONNECTED = 1,
24
+ HYBRID_CUBE_MESH = 2
25
+ };
26
+
27
+ enum class AllReduceAlgo : uint8_t {
28
+ NONE = 0,
29
+ ONE_SHOT = 1,
30
+ TWO_SHOT = 2,
31
+ HCM = 3
32
+ };
33
+
34
+ // NOTE: this class will be be removed soon in favor of SymmetricMemory
35
+ class TORCH_API IntraNodeComm : public c10::intrusive_ptr_target {
36
+ public:
37
+ IntraNodeComm(
38
+ c10::intrusive_ptr<c10d::Store> store,
39
+ size_t rank,
40
+ size_t worldSize,
41
+ std::optional<size_t> bufferSize = std::nullopt);
42
+
43
+ ~IntraNodeComm() override;
44
+
45
+ static bool isEnabled();
46
+
47
+ /**
48
+ * Performs rendezvous.
49
+ * If rendezvous fails, the IntraNodeComm object will be in an invalid
50
+ * state and it is the caller's responsibility to dispose it.
51
+ */
52
+ bool rendezvous();
53
+
54
+ Topology getTopology() {
55
+ return topology_;
56
+ }
57
+
58
+ size_t getBufferSize() {
59
+ return bufferSize_;
60
+ }
61
+
62
+ /**
63
+ * Selects a AllReduceAlgo that we think will outperform nccl.
64
+ * Returns AllReduceAlgo::NONE if we don't think we can outperform nccl.
65
+ */
66
+ AllReduceAlgo selectAllReduceAlgo(const at::Tensor& input);
67
+
68
+ at::Tensor allReduce(const at::Tensor& input, AllReduceAlgo algo);
69
+
70
+ /**
71
+ * Perform a barrier among the specified ranks.
72
+ */
73
+ void barrier(std::optional<std::vector<int64_t>> ranks = std::nullopt);
74
+
75
+ at::Tensor getBuffer(
76
+ size_t rank,
77
+ const std::vector<int64_t>& sizes,
78
+ c10::ScalarType dtype,
79
+ int64_t storageOffset);
80
+
81
+ private:
82
+ at::Tensor oneShotAllReduce(
83
+ const at::Tensor& input,
84
+ at::cuda::CUDAStream& stream);
85
+
86
+ at::Tensor twoShotAllReduce(
87
+ const at::Tensor& input,
88
+ at::cuda::CUDAStream& stream);
89
+
90
+ at::Tensor hybridCubeMeshAllReduce(
91
+ const at::Tensor& input,
92
+ at::cuda::CUDAStream& stream);
93
+
94
+ c10::intrusive_ptr<Store> store_;
95
+ size_t rank_;
96
+ size_t worldSize_;
97
+ size_t bufferSize_;
98
+ at::cuda::CUDAEvent barrierReady_;
99
+
100
+ /**
101
+ * Members initialized after rendezvous
102
+ */
103
+ bool isInitialized_ = false;
104
+ int deviceIdx_;
105
+ Topology topology_ = Topology::UNKNOWN;
106
+ void* symmetricMemoryPtr_ = nullptr;
107
+ c10::intrusive_ptr<SymmetricMemory> symmetricMemory_ = nullptr;
108
+ void* p2pStatesDev_{};
109
+ void* buffersDev_{};
110
+ void* topoInfo_{};
111
+ };
112
+
113
+ /**
114
+ * NOTE [IntraNodeComm Stream Semantics]
115
+ *
116
+ * ProcessGroupNCCL launches kernels differently from the conventional PyTorch
117
+ * CUDA semantics: it always launches collective kernels onto a dedicated
118
+ * communication stream. Therefore, it needs to:
119
+ *
120
+ * - Synchronize the calling stream and the comm stream.
121
+ * - Ensure the memory safety of the operands (via record_stream or stashing).
122
+ * - Synchronize the waiting stream with the comm stream.
123
+ *
124
+ * Unconditionally performing these tasks makes sense when we expect most of the
125
+ * communication to benefit from compute/comm overlap. However, IntraNodeComm
126
+ * primarily aims to optimize small, latency-sensitive, blocking communication,
127
+ * in which the overhead incurred by the above steps can be quite pronounced.
128
+ *
129
+ * Thus, IntraNodeComm follows the conventional PyTorch CUDA semantics and
130
+ * launches kernels onto the stream specified by the user. Although the user
131
+ * can perform neccessary synchronization via wait_stream, to provide a UX
132
+ * consistent to that of ProcessGroupNCCL, the neccessary stream
133
+ * synchronization can also be performed via IntraNodeWork::wait().
134
+ */
135
+ class IntraNodeCommWork : public c10d::Work {
136
+ public:
137
+ IntraNodeCommWork() : c10d::Work() {
138
+ event_.record();
139
+ }
140
+
141
+ bool wait(std::chrono::milliseconds timeout = kNoTimeout) override {
142
+ event_.block(at::cuda::getCurrentCUDAStream());
143
+ return true;
144
+ }
145
+
146
+ private:
147
+ at::cuda::CUDAEvent event_;
148
+ };
149
+
150
+ TORCH_API int64_t getIntraNodeCommUsageCounter();
151
+
152
+ } // namespace c10d::intra_node_comm
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/sequence_num.hpp ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/macros/Macros.h>
4
+ #include <c10/util/irange.h>
5
+ #include <mutex>
6
+ #include <optional>
7
+ #include <vector>
8
+
9
+ namespace c10d {
10
+ const int kUnsetSeqNum = 0;
11
+
12
+ namespace {
13
+ constexpr int kByteOffset = 8;
14
+ }
15
+
16
+ // Converts from int to char vec to write in store
17
+ template <typename T>
18
+ inline std::vector<T> toVec(uint64_t num, int numBytes) {
19
+ std::vector<T> values;
20
+ // Read off bytes from right to left, pushing them into
21
+ // char array.
22
+ for (const auto i : c10::irange(numBytes)) {
23
+ uint8_t x = (num >> (kByteOffset * i)) & 0xff;
24
+ values.push_back(static_cast<T>(x));
25
+ }
26
+ return values;
27
+ }
28
+
29
+ // Converts from char vec (such as from store read) to int.
30
+ template <typename T>
31
+ inline uint64_t fromVec(const std::vector<T>& values) {
32
+ uint64_t num = 0;
33
+ // Set each byte at the correct location on num
34
+ for (const auto i : c10::irange(values.size())) {
35
+ uint8_t x = static_cast<uint8_t>(values[i]);
36
+ num |= (static_cast<int64_t>(x) << (kByteOffset * i));
37
+ }
38
+ return num;
39
+ }
40
+
41
+ class TORCH_API SequenceNum {
42
+ public:
43
+ SequenceNum();
44
+ explicit SequenceNum(const uint64_t num);
45
+ // Retrieve num_. Will throw if not set.
46
+ uint64_t get() const;
47
+ // Increment num_. Will throw if not set.
48
+ void increment();
49
+ // Increment num_ and return the old value. Will throw if not set.
50
+ uint64_t getAndIncrement();
51
+ // Sets num_
52
+ void set(const uint64_t num);
53
+ // Returns true if this SequenceNum is properly initialized with a value, else
54
+ // false.
55
+ bool isSet() const;
56
+
57
+ SequenceNum& operator=(const SequenceNum& other);
58
+
59
+ SequenceNum(const SequenceNum& other);
60
+
61
+ private:
62
+ std::optional<uint64_t> num_;
63
+ mutable std::mutex lock_;
64
+ };
65
+
66
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/c10d/socket.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and its affiliates.
2
+ // All rights reserved.
3
+ //
4
+ // This source code is licensed under the BSD-style license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ #pragma once
8
+
9
+ #include <chrono>
10
+ #include <cstdint>
11
+ #include <memory>
12
+ #include <string>
13
+
14
+ #include <c10/macros/Macros.h>
15
+ #include <c10/util/Exception.h>
16
+ #include <torch/csrc/distributed/c10d/Backoff.hpp>
17
+ #include <torch/csrc/distributed/c10d/exception.h>
18
+
19
+ namespace c10d {
20
+ namespace detail {
21
+
22
+ class SocketOptions {
23
+ public:
24
+ SocketOptions& prefer_ipv6(bool value) noexcept {
25
+ prefer_ipv6_ = value;
26
+
27
+ return *this;
28
+ }
29
+
30
+ bool prefer_ipv6() const noexcept {
31
+ return prefer_ipv6_;
32
+ }
33
+
34
+ SocketOptions& connect_timeout(std::chrono::milliseconds value) noexcept {
35
+ connect_timeout_ = value;
36
+
37
+ return *this;
38
+ }
39
+
40
+ std::chrono::milliseconds connect_timeout() const noexcept {
41
+ return connect_timeout_;
42
+ }
43
+
44
+ // Sets the backoff policy to use for socket connect ops.
45
+ SocketOptions& connect_backoff(std::shared_ptr<Backoff> value) noexcept {
46
+ connect_backoff_ = std::move(value);
47
+
48
+ return *this;
49
+ }
50
+
51
+ const std::shared_ptr<Backoff>& connect_backoff() const noexcept {
52
+ return connect_backoff_;
53
+ }
54
+
55
+ private:
56
+ bool prefer_ipv6_ = true;
57
+ std::chrono::milliseconds connect_timeout_{std::chrono::seconds{30}};
58
+ std::shared_ptr<Backoff> connect_backoff_{
59
+ std::make_shared<FixedBackoff>(std::chrono::milliseconds(1000))};
60
+ };
61
+
62
+ class SocketImpl;
63
+
64
+ class Socket {
65
+ public:
66
+ // This function initializes the underlying socket library and must be called
67
+ // before any other socket function.
68
+ static void initialize();
69
+
70
+ static Socket listen(std::uint16_t port, const SocketOptions& opts = {});
71
+
72
+ static Socket listenFromFd(int fd, std::uint16_t expected_port);
73
+
74
+ static Socket connect(
75
+ const std::string& host,
76
+ std::uint16_t port,
77
+ const SocketOptions& opts = {});
78
+
79
+ Socket() noexcept = default;
80
+
81
+ Socket(const Socket& other) = delete;
82
+
83
+ Socket& operator=(const Socket& other) = delete;
84
+
85
+ Socket(Socket&& other) noexcept;
86
+
87
+ Socket& operator=(Socket&& other) noexcept;
88
+
89
+ ~Socket();
90
+
91
+ Socket accept() const;
92
+
93
+ int handle() const noexcept;
94
+
95
+ std::uint16_t port() const;
96
+
97
+ bool waitForInput(std::chrono::milliseconds timeout);
98
+
99
+ std::string repr() const;
100
+
101
+ private:
102
+ explicit Socket(std::unique_ptr<SocketImpl>&& impl) noexcept;
103
+
104
+ std::unique_ptr<SocketImpl> impl_;
105
+ };
106
+
107
+ } // namespace detail
108
+
109
+ } // namespace c10d
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/agent_utils.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/c10d/PrefixStore.hpp>
4
+ #include <torch/csrc/distributed/rpc/utils.h>
5
+
6
+ namespace torch {
7
+ namespace distributed {
8
+ namespace rpc {
9
+
10
+ // All RPC peers should call into this function at the same time. Each peer
11
+ // provides its own id and name, and this function uses the given Store to
12
+ // gather global name-to-id mapping on all peers.
13
+ TORCH_API std::unordered_map<std::string, worker_id_t> collectNames(
14
+ ::c10d::PrefixStore store,
15
+ const worker_id_t selfId,
16
+ const std::string& selfName,
17
+ const int worldSize);
18
+
19
+ // Ranks in dynamic RPC groups will initially call into this to establish the
20
+ // name-to-id mapping for the current peers in the group. The current rank will
21
+ // put its own worker info in the store and discover all the ranks that came
22
+ // before it. NOTE: This needs to be called with the Dynamic RPC group
23
+ // membership management token held.
24
+ TORCH_API std::unordered_map<std::string, worker_id_t> collectCurrentNames(
25
+ ::c10d::PrefixStore store,
26
+ const worker_id_t selfId,
27
+ const std::string& selfName);
28
+
29
+ // Remove name frmo Store, used in dynamic RPC groups.
30
+ // NOTE: This needs to be called with the Dynamic RPC group
31
+ // membership management token held.
32
+ TORCH_API void removeCurrentName(
33
+ ::c10d::PrefixStore store,
34
+ const worker_id_t selfId,
35
+ const std::string& selfName);
36
+
37
+ // This performs a synchronization of all call counts by using store.
38
+ // All RPC peers wait for others to join to exit at the same time.
39
+ TORCH_API int syncCallCount(
40
+ ::c10d::PrefixStore store,
41
+ const int worldSize,
42
+ int activeCalls = 0);
43
+
44
+ } // namespace rpc
45
+ } // namespace distributed
46
+ } // namespace torch
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/message.h ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/types.h>
4
+ #include <vector>
5
+
6
+ namespace torch {
7
+ namespace distributed {
8
+ namespace rpc {
9
+
10
+ // An enum denoting common RPC errors to allow specific error handling for them.
11
+ enum RPCErrorType {
12
+ UNKNOWN_ERROR = 0, /* Indicates that error type could not be parsed */
13
+ TIMEOUT = 1, /* Indicates that the RPC has timed out */
14
+ INTENTIONAL_FAILURE = 2 /* Deliberate failure, such as those injected by
15
+ FaultyAgent for testing */
16
+ };
17
+
18
+ // The enum values are bitwise ORed with MessageType
19
+ // They are bit flags starting from 0x100 and should have
20
+ // value such as 0x100, 0x200, 0x400, 0x800, 0xF00, etc.
21
+ enum MessageTypeFlags {
22
+ REQUEST_TYPE = 0x100,
23
+ RESPONSE_TYPE = 0x200,
24
+ };
25
+
26
+ // Message types must have values between 0x00 to 0xff
27
+ enum MessageType {
28
+ // messages for dist.rpc on builtin operators
29
+ SCRIPT_CALL = 0x00 | MessageTypeFlags::REQUEST_TYPE,
30
+ SCRIPT_RET = 0x01 | MessageTypeFlags::RESPONSE_TYPE,
31
+
32
+ // messages for dist.rpc on Python UDF
33
+ PYTHON_CALL = 0x02 | MessageTypeFlags::REQUEST_TYPE,
34
+ PYTHON_RET = 0x03 | MessageTypeFlags::RESPONSE_TYPE,
35
+
36
+ // messages for dist.remote on builtin operators and Python UDF
37
+ SCRIPT_REMOTE_CALL = 0x04 |
38
+ MessageTypeFlags::REQUEST_TYPE, // A remote call on a builtin operator
39
+ PYTHON_REMOTE_CALL =
40
+ 0x05 | MessageTypeFlags::REQUEST_TYPE, // A remote call on a Python UDF
41
+ REMOTE_RET =
42
+ 0x06 | MessageTypeFlags::RESPONSE_TYPE, // Response for remote calls for
43
+ // UDF, builtin, or script
44
+
45
+ // RRef related internal messages
46
+ SCRIPT_RREF_FETCH_CALL =
47
+ 0x07 | MessageTypeFlags::REQUEST_TYPE, // A UserRRef<IValue> fetches value
48
+ // from owner
49
+ PYTHON_RREF_FETCH_CALL =
50
+ 0x08 | MessageTypeFlags::REQUEST_TYPE, // A UserRRef<py::object> fetches
51
+ // value from owner
52
+ SCRIPT_RREF_FETCH_RET = 0x09 |
53
+ MessageTypeFlags::RESPONSE_TYPE, // An OwnerRRef sends ivalue to user
54
+ PYTHON_RREF_FETCH_RET = 0x0a |
55
+ MessageTypeFlags::RESPONSE_TYPE, // An OwnerRRef sends py::object to user
56
+ RREF_USER_DELETE = 0x0b |
57
+ MessageTypeFlags::REQUEST_TYPE, // A UserRRef tells the owner to deref
58
+ RREF_FORK_REQUEST =
59
+ 0x0c | MessageTypeFlags::REQUEST_TYPE, // A child UserRRef tells the owner
60
+ // about itself
61
+ RREF_CHILD_ACCEPT =
62
+ 0x0d | MessageTypeFlags::REQUEST_TYPE, // A child UserRRef tells parent
63
+ // that owner knows it
64
+ RREF_ACK =
65
+ 0x0e | MessageTypeFlags::RESPONSE_TYPE, // ACK to internal RRef messages
66
+
67
+ // Messages with autograd info
68
+ FORWARD_AUTOGRAD_REQ = 0x0f | MessageTypeFlags::REQUEST_TYPE,
69
+ FORWARD_AUTOGRAD_RESP = 0x10 | MessageTypeFlags::RESPONSE_TYPE,
70
+
71
+ // Messages to propagate gradients on the backward pass.
72
+ BACKWARD_AUTOGRAD_REQ = 0x11 | MessageTypeFlags::REQUEST_TYPE,
73
+ BACKWARD_AUTOGRAD_RESP = 0x12 | MessageTypeFlags::RESPONSE_TYPE,
74
+
75
+ // Messages to tell workers to clean up their autograd context.
76
+ CLEANUP_AUTOGRAD_CONTEXT_REQ = 0x13 | MessageTypeFlags::REQUEST_TYPE,
77
+ CLEANUP_AUTOGRAD_CONTEXT_RESP = 0x14 | MessageTypeFlags::RESPONSE_TYPE,
78
+
79
+ // Messages that tell workers to run requests with profiling enabled.
80
+ RUN_WITH_PROFILING_REQ = 0x15 | MessageTypeFlags::REQUEST_TYPE,
81
+ RUN_WITH_PROFILING_RESP = 0x16 | MessageTypeFlags::RESPONSE_TYPE,
82
+
83
+ // Messages to support RRef.backward().
84
+ RREF_BACKWARD_REQ = 0x17 | MessageTypeFlags::REQUEST_TYPE,
85
+ RREF_BACKWARD_RESP = 0x18 | MessageTypeFlags::RESPONSE_TYPE,
86
+
87
+ // Other internal message types
88
+ EXCEPTION = 0x37 | MessageTypeFlags::RESPONSE_TYPE,
89
+ UNKNOWN = 0x3c
90
+ };
91
+
92
+ // A message to be sent/received by an RpcAgent.
93
+ //
94
+ // A Message object contains 4 fields:
95
+ // payload (std::vector<char>): a binary chunk of data.
96
+ // tensors (std::vector<torch::Tensor>): all tensors. Tensor data are not
97
+ // included in the payload, and it is up to the RpcAgent implementation
98
+ // to determine how to serialize them. This design is helpful for
99
+ // communicating super large tensors where serializing all the data at
100
+ // once leads to excessively large memory footprint. An implementation
101
+ // can then serialize and send tensors chunk-by-chunk, in the streaming
102
+ // fashion.
103
+ // type (MessageType): type of the message.
104
+ // id (int64_t): message id, this is used to match request and response.
105
+ // Other implementation can ignore it if they have their own
106
+ // ways to do matching.
107
+ //
108
+ // Layers above ``RpcAgent`` only converts ScriptCall, ScriptResp, PythonCall,
109
+ // and PythonResp into a Message, and it is up to the RpcAgent
110
+ // implementation to determine how to serialize a message.
111
+ class TORCH_API Message final : public torch::CustomClassHolder {
112
+ private:
113
+ // Keep these private in order to force users to go through make_intrusive and
114
+ // thus prevent creating a Message that's not held by an intrusive_ptr.
115
+ Message();
116
+
117
+ Message(
118
+ std::vector<char>&& payload,
119
+ std::vector<torch::Tensor>&& tensors,
120
+ MessageType type);
121
+
122
+ Message(
123
+ std::vector<char>&& payload,
124
+ std::vector<torch::Tensor>&& tensors,
125
+ MessageType type,
126
+ int64_t id);
127
+
128
+ friend c10::intrusive_ptr<Message>;
129
+
130
+ public:
131
+ Message(const Message& other) = delete;
132
+ Message(Message&& other) = delete;
133
+ Message& operator=(Message const& rhs) = delete;
134
+ Message& operator=(Message&& rhs) = delete;
135
+
136
+ // Destructively retrieves the payload.
137
+ std::vector<char>&& movePayload() &&;
138
+ std::vector<torch::Tensor>&& moveTensors() &&;
139
+
140
+ std::vector<char>& payload();
141
+ const std::vector<char>& payload() const;
142
+ std::vector<torch::Tensor>& tensors();
143
+ const std::vector<torch::Tensor>& tensors() const;
144
+ MessageType type() const;
145
+
146
+ bool isRequest() const;
147
+ bool isResponse() const;
148
+ bool isShutdown() const;
149
+
150
+ // id is an optional field to match request/response. If an RpcAgent
151
+ // implementation is able to do the matching without using this id, it can be
152
+ // dropped during message serialization.
153
+ int64_t id() const;
154
+ void setId(int64_t id);
155
+
156
+ std::vector<c10::weak_intrusive_ptr<c10::StorageImpl>> getStorages() const;
157
+
158
+ private:
159
+ std::vector<char> payload_;
160
+ std::vector<torch::Tensor> tensors_;
161
+ MessageType type_ = MessageType::UNKNOWN;
162
+ int64_t id_ = -1;
163
+ };
164
+
165
+ // Create a response Message of type Exception.
166
+ // The exception string representation will be used as the message's payload.
167
+ // A message ID corresponding to the request that resulted in this response can
168
+ // be provided for matching requests/responses.
169
+ TORCH_API c10::intrusive_ptr<Message> createExceptionResponse(
170
+ const std::exception& e,
171
+ int64_t id);
172
+
173
+ // Create a response Message of type Exception.
174
+ // The passed in string representation will be used as the message's payload.
175
+ // A message ID corresponding to the request that resulted in this response can
176
+ // be provided for matching requests/responses.
177
+ TORCH_API c10::intrusive_ptr<Message> createExceptionResponse(
178
+ const std::string& exceptionStr,
179
+ int64_t id);
180
+
181
+ inline std::tuple<
182
+ c10::intrusive_ptr<Message>,
183
+ std::vector<c10::weak_intrusive_ptr<c10::StorageImpl>>>
184
+ withStorages(c10::intrusive_ptr<Message> message) {
185
+ auto storages = message->getStorages();
186
+ return std::make_tuple(std::move(message), std::move(storages));
187
+ }
188
+
189
+ using JitFuture = c10::ivalue::Future;
190
+
191
+ } // namespace rpc
192
+ } // namespace distributed
193
+ } // namespace torch
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_call.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
4
+ #include <torch/csrc/distributed/rpc/types.h>
5
+
6
+ namespace torch::distributed::rpc {
7
+
8
+ // RPC call representing calling a Python function over RPC.
9
+ class TORCH_API PythonCall final : public RpcCommandBase {
10
+ public:
11
+ PythonCall(SerializedPyObj&& serializedPyObj, bool isAsyncExecution);
12
+
13
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
14
+
15
+ static std::unique_ptr<PythonCall> fromMessage(const Message& message);
16
+
17
+ const SerializedPyObj& serializedPyObj() const;
18
+
19
+ inline bool isAsyncExecution() const {
20
+ return isAsyncExecution_;
21
+ }
22
+
23
+ private:
24
+ SerializedPyObj serializedPyObj_;
25
+ const bool isAsyncExecution_;
26
+ };
27
+
28
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_functions.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/py_rref.h>
4
+ #include <torch/csrc/distributed/rpc/rpc_agent.h>
5
+ #include <torch/csrc/jit/python/pybind_utils.h>
6
+ #include <torch/csrc/utils/pybind.h>
7
+
8
+ namespace torch::distributed::rpc {
9
+
10
+ // Converts an internal ivalue::Future of Message into a user-facing
11
+ // ivalue::Future of py::object type by creating a new ivalue::Future and call
12
+ // its markCompleted as a callback in the given ivalue::Future.
13
+ // If hasValue is true, the Message will be converted into a py::object and then
14
+ // wrap it with an IValue. If hasValue is false, this ivalue::Future is only
15
+ // used for signaling and launching callbacks. In this case, the message will be
16
+ // discarded and then set the ivalue::Future using an empty IValue or the given
17
+ // FutureError if there is an error.
18
+ c10::intrusive_ptr<JitFuture> toPyJitFuture(
19
+ const c10::intrusive_ptr<JitFuture>& messageJitFuture,
20
+ bool hasValue = true);
21
+
22
+ c10::intrusive_ptr<JitFuture> pyRpcBuiltin(
23
+ const WorkerInfo& dst,
24
+ const std::string& opName,
25
+ const py::args& args,
26
+ const py::kwargs& kwargs,
27
+ const float rpcTimeoutSeconds);
28
+
29
+ c10::intrusive_ptr<JitFuture> pyRpcPythonUdf(
30
+ const WorkerInfo& dst,
31
+ std::string& pickledPythonUDF,
32
+ std::vector<torch::Tensor>& tensors,
33
+ const float rpcTimeoutSeconds,
34
+ const bool isAsyncExecution);
35
+
36
+ c10::intrusive_ptr<JitFuture> pyRpcTorchscript(
37
+ const std::string& dstWorkerName,
38
+ const std::string& qualifiedNameStr,
39
+ const py::tuple& argsTuple,
40
+ const py::dict& kwargsDict,
41
+ const float rpcTimeoutSeconds,
42
+ const bool isAsyncExecution);
43
+
44
+ PyRRef pyRemoteBuiltin(
45
+ const WorkerInfo& dst,
46
+ const std::string& opName,
47
+ const float rpcTimeoutSeconds,
48
+ const py::args& args,
49
+ const py::kwargs& kwargs);
50
+
51
+ PyRRef pyRemotePythonUdf(
52
+ const WorkerInfo& dst,
53
+ std::string& pickledPythonUDF,
54
+ std::vector<torch::Tensor>& tensors,
55
+ const float rpcTimeoutSeconds,
56
+ const bool isAsyncExecution);
57
+
58
+ PyRRef pyRemoteTorchscript(
59
+ const std::string& dstWorkerName,
60
+ const std::string& qualifiedNameStr,
61
+ const float rpcTimeoutSeconds,
62
+ const bool isAsyncExecution,
63
+ const py::args& args,
64
+ const py::kwargs& kwargs);
65
+
66
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_remote_call.h ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
5
+ #include <torch/csrc/distributed/rpc/types.h>
6
+ #include <torch/csrc/jit/serialization/pickler.h>
7
+ #include <vector>
8
+
9
+ namespace torch::distributed::rpc {
10
+
11
+ class TORCH_API PythonRemoteCall : public RpcCommandBase {
12
+ public:
13
+ PythonRemoteCall(
14
+ SerializedPyObj&& serializedPyObj,
15
+ at::IValue retRRefId,
16
+ at::IValue retForkId,
17
+ const bool isAsyncExecution);
18
+
19
+ inline const SerializedPyObj& serializedPyObj() const {
20
+ return serializedPyObj_;
21
+ }
22
+
23
+ inline const at::IValue& retRRefId() const {
24
+ return retRRefId_;
25
+ }
26
+
27
+ inline const at::IValue& retForkId() const {
28
+ return retForkId_;
29
+ }
30
+
31
+ inline bool isAsyncExecution() const {
32
+ return isAsyncExecution_;
33
+ }
34
+
35
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
36
+ static std::unique_ptr<PythonRemoteCall> fromMessage(const Message& message);
37
+
38
+ private:
39
+ SerializedPyObj serializedPyObj_;
40
+ const at::IValue retRRefId_;
41
+ const at::IValue retForkId_;
42
+ const bool isAsyncExecution_;
43
+ };
44
+
45
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_resp.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
4
+ #include <torch/csrc/distributed/rpc/types.h>
5
+
6
+ namespace torch::distributed::rpc {
7
+
8
+ // RPC call representing the response of a Python UDF over RPC.
9
+ class TORCH_API PythonResp final : public RpcCommandBase {
10
+ public:
11
+ explicit PythonResp(SerializedPyObj&& serializedPyObj);
12
+
13
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
14
+
15
+ static std::unique_ptr<PythonResp> fromMessage(const Message& message);
16
+
17
+ const SerializedPyObj& serializedPyObj() const;
18
+
19
+ private:
20
+ SerializedPyObj serializedPyObj_;
21
+ };
22
+
23
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/python_rpc_handler.h ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/types.h>
5
+ #include <torch/csrc/jit/frontend/script_type_parser.h>
6
+ #include <torch/csrc/utils/pybind.h>
7
+
8
+ namespace torch::distributed::rpc {
9
+
10
+ // Singleton class provides interface to execute python UDF remote call
11
+ // and deserialize the returned results by running python function
12
+ // in internal_rpc_utilities.
13
+ // The singleton object is constructed at first when RPC agent is
14
+ // constructed, where the python function in
15
+ // torch/distributed/internal_rpc_utils.py are imported only once.
16
+ class PYBIND11_EXPORT PythonRpcHandler {
17
+ public:
18
+ struct RRefProxyFunctions {
19
+ py::object rrefProxyCtor_;
20
+ py::object rpcSync_;
21
+ py::object rpcAsync_;
22
+ py::object remote_;
23
+ };
24
+
25
+ struct RRefTypeFunctions {
26
+ py::object onOwner_;
27
+ py::object onUser_;
28
+ };
29
+
30
+ static PythonRpcHandler& getInstance();
31
+
32
+ // Run a pickled Python UDF and return the result py::object
33
+ py::object runPythonUdf(const py::object& pythonUdf);
34
+
35
+ // Serialized a py::object into a string
36
+ SerializedPyObj serialize(const py::object& obj);
37
+
38
+ // Deserialize a string into a py::object
39
+ py::object deserialize(const SerializedPyObj& serializedObj);
40
+
41
+ // Check if obj is RemoteException, then throw it
42
+ void handleException(const py::object& obj);
43
+ // Alternative if the caller is already holding the GIL.
44
+ void handleExceptionGILHeld(const py::object& obj);
45
+ // Check if obj is an RemoteException instance.
46
+ bool isRemoteException(const py::object& obj);
47
+
48
+ // Explicitly clean up py::objects to avoid segment faults when
49
+ // py::objects with CPython are cleaned up later at program exit
50
+ // See similar issues reported https://github.com/pybind/pybind11/issues/1598
51
+ // and https://github.com/pybind/pybind11/issues/1493
52
+ // Our local tests also caught this segment faults if py::objects are cleaned
53
+ // up at program exit. The explanation is: CPython cleans up most critical
54
+ // utilities before cleaning up PythonRpcHandler singleton, so when
55
+ // PythonRpcHandler singleton cleans up py::objects and call dec_ref(), it
56
+ // will crash.
57
+ // The solution is to clean up py::objects earlier when Rpc agent join().
58
+ // Be note that py::objects can not be cleaned up when Rpc agent is destroyed
59
+ // as well, as Rpc agent is global variable and it will have same issue as
60
+ // PythonRpcHandler.
61
+ void cleanup();
62
+
63
+ std::shared_ptr<torch::jit::CompilationUnit> jitCompilationUnit();
64
+
65
+ // Parse the string to recover the jit_type, this is used for RRef python
66
+ // pickling/unpickling type recovery. The type string inference rule is as
67
+ // follows:
68
+ // 1. first try to parse if this is primitive types.
69
+ // i.e. TensorType, IntType, PyObjectType, etc.
70
+ // 2. if not primitive type, we query the python_cu to see if it is a
71
+ // class type or interface type registered in python
72
+ // We use a ScriptTypeParser instance with custom PythonTypeResolver
73
+ // to resolve types according to the above rules.
74
+ TypePtr parseTypeFromStr(const std::string& typeStr);
75
+
76
+ // Return a set of Python functions for RRef helpers.
77
+ const RRefProxyFunctions& getRRefProxyFunctions() const;
78
+
79
+ // Return a set of Python functions to retrieve the type of the object
80
+ // referenced by a given RRef.
81
+ const RRefTypeFunctions& getRRefTypeFunctions() const;
82
+
83
+ PythonRpcHandler(const PythonRpcHandler&) = delete;
84
+ PythonRpcHandler& operator=(const PythonRpcHandler&) = delete;
85
+ PythonRpcHandler(PythonRpcHandler&&) = delete;
86
+ PythonRpcHandler& operator=(PythonRpcHandler&&) = delete;
87
+
88
+ private:
89
+ void init();
90
+ PythonRpcHandler();
91
+ ~PythonRpcHandler() = default;
92
+
93
+ // Ref to `torch.distributed.rpc.internal._run_function`.
94
+ py::object pyRunFunction_;
95
+
96
+ // Ref to `torch.distributed.rpc.internal.serialize`.
97
+ py::object pySerialize_;
98
+
99
+ // Ref to `torch.distributed.rpc.internal.deserialize`.
100
+ py::object pyDeserialize_;
101
+
102
+ // Ref to 'torch.distributed.rpc.internal._handle_exception'
103
+ py::object pyHandleException_;
104
+
105
+ // Python functions for RRef proxy
106
+ RRefProxyFunctions rrefProxyFunctions_;
107
+
108
+ // Ref to 'torch.distributed.rpc.api._rref_typeof_on_'
109
+ RRefTypeFunctions rrefTypeFunctions_;
110
+
111
+ // Shared ptr to python compilation unit in jit, it is constructed in python
112
+ // side (see _python_cu = torch._C.CompilationUnit() in jit/__init__.py)
113
+ // and imported in C++ (see get_python_cu() in
114
+ // csrc/jit/python/pybind_utils.h). We import the compilation unit here only
115
+ // once for less cost and thread safety.
116
+ std::shared_ptr<torch::jit::CompilationUnit> jitCompilationUnit_;
117
+
118
+ // jit type parser to parse type_str back to TypePtr for RRef type
119
+ // recovery when pickling and unpickling RRef
120
+ std::shared_ptr<jit::ScriptTypeParser> typeParser_;
121
+
122
+ // Indicates whether or not we have properly initialized the handler.
123
+ bool initialized_;
124
+
125
+ // Lock to protect initialization.
126
+ std::mutex init_lock_;
127
+ };
128
+
129
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback.h ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+
5
+ namespace torch::distributed::rpc {
6
+
7
+ // Functor which is invoked to process an RPC message. This is an abstract class
8
+ // with some common functionality across all request handlers. Users need to
9
+ // implement this interface to perform the actual business logic.
10
+ class TORCH_API RequestCallback {
11
+ public:
12
+ // Invoke the callback.
13
+ c10::intrusive_ptr<JitFuture> operator()(
14
+ Message& request,
15
+ std::vector<c10::Stream> streams) const;
16
+
17
+ virtual ~RequestCallback() = default;
18
+
19
+ protected:
20
+ // RpcAgent implementation should invoke ``RequestCallback`` to process
21
+ // received requests. There is no restriction on the implementation's
22
+ // threading model. This function takes an rvalue reference of the Message
23
+ // object. It is expected to return the future to a response message or
24
+ // message containing an exception. Different rpc agent implementations are
25
+ // expected to ensure delivery of the response/exception based on their
26
+ // implementation specific mechanisms.
27
+ virtual c10::intrusive_ptr<JitFuture> processMessage(
28
+ Message& request,
29
+ std::vector<c10::Stream> streams) const = 0;
30
+ };
31
+
32
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_impl.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/request_callback_no_python.h>
5
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
6
+ #include <torch/csrc/jit/python/pybind.h>
7
+
8
+ namespace torch::distributed::rpc {
9
+
10
+ class TORCH_API RequestCallbackImpl : public RequestCallbackNoPython {
11
+ public:
12
+ std::unique_ptr<RpcCommandBase> deserializePythonRpcCommand(
13
+ std::unique_ptr<RpcCommandBase> rpc,
14
+ const MessageType& messageType) const override;
15
+
16
+ c10::intrusive_ptr<JitFuture> processPythonCall(
17
+ RpcCommandBase& rpc,
18
+ const std::vector<c10::Stream>& streams) const override;
19
+
20
+ c10::intrusive_ptr<JitFuture> processScriptCall(
21
+ RpcCommandBase& rpc,
22
+ const std::vector<c10::Stream>& streams) const override;
23
+
24
+ c10::intrusive_ptr<JitFuture> processScriptRemoteCall(
25
+ RpcCommandBase& rpc,
26
+ const std::vector<c10::Stream>& streams) const override;
27
+
28
+ c10::intrusive_ptr<JitFuture> processPythonRemoteCall(
29
+ RpcCommandBase& rpc,
30
+ const std::vector<c10::Stream>& streams) const override;
31
+
32
+ c10::intrusive_ptr<JitFuture> processPythonRRefFetchCall(
33
+ RpcCommandBase& rpc) const override;
34
+
35
+ void handleRRefDelete(c10::intrusive_ptr<RRef>& rref) const override;
36
+
37
+ c10::intrusive_ptr<JitFuture> processRpcWithErrors(
38
+ RpcCommandBase& rpc,
39
+ const MessageType& messageType,
40
+ const std::vector<c10::Stream>& streams) const override;
41
+
42
+ bool cudaAvailable() const override;
43
+
44
+ c10::intrusive_ptr<JitFuture> processRRefBackward(
45
+ RpcCommandBase& rpc) const override;
46
+
47
+ // Helpers to run user-defined functions, operators and other computations.
48
+
49
+ c10::intrusive_ptr<JitFuture> runJitFunction(
50
+ const c10::QualifiedName& name,
51
+ std::vector<at::IValue>& stack,
52
+ const std::vector<c10::Stream>& streams,
53
+ bool isAsyncExecution) const;
54
+
55
+ c10::intrusive_ptr<JitFuture> runPythonFunction(
56
+ const py::object& function,
57
+ const std::vector<c10::Stream>& streams,
58
+ bool isAsyncExecution) const;
59
+ };
60
+
61
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/request_callback_no_python.h ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/request_callback.h>
5
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
6
+ #include <torch/csrc/distributed/rpc/rref_impl.h>
7
+ #include <torch/csrc/distributed/rpc/script_call.h>
8
+ #include <torch/csrc/distributed/rpc/script_remote_call.h>
9
+
10
+ namespace torch::distributed::rpc {
11
+
12
+ // RequestCallback implementation with no Python dependencies.
13
+ class TORCH_API RequestCallbackNoPython : public RequestCallback {
14
+ public:
15
+ c10::intrusive_ptr<JitFuture> processMessage(
16
+ Message& request,
17
+ std::vector<c10::Stream> streams) const override;
18
+
19
+ protected:
20
+ virtual std::unique_ptr<RpcCommandBase> deserializePythonRpcCommand(
21
+ std::unique_ptr<RpcCommandBase> rpc,
22
+ const MessageType& messageType) const;
23
+
24
+ virtual c10::intrusive_ptr<JitFuture> processScriptCall(
25
+ RpcCommandBase& rpc,
26
+ const std::vector<c10::Stream>& streams) const;
27
+
28
+ virtual c10::intrusive_ptr<JitFuture> processPythonCall(
29
+ RpcCommandBase& rpc,
30
+ const std::vector<c10::Stream>& streams) const;
31
+
32
+ c10::intrusive_ptr<JitFuture> assignOwnerRRef(
33
+ const RRefId& rrefId,
34
+ const RRefId& forkId,
35
+ const c10::intrusive_ptr<JitFuture>& valueFuture) const;
36
+
37
+ virtual c10::intrusive_ptr<JitFuture> processScriptRemoteCall(
38
+ RpcCommandBase& rpc,
39
+ const std::vector<c10::Stream>& streams) const;
40
+
41
+ virtual c10::intrusive_ptr<JitFuture> processPythonRemoteCall(
42
+ RpcCommandBase& rpc,
43
+ const std::vector<c10::Stream>& streams) const;
44
+
45
+ c10::intrusive_ptr<JitFuture> retrieveOwnerRRef(const RRefId& rrefId) const;
46
+
47
+ c10::intrusive_ptr<JitFuture> processScriptRRefFetchCall(
48
+ RpcCommandBase& rpc) const;
49
+
50
+ virtual c10::intrusive_ptr<JitFuture> processPythonRRefFetchCall(
51
+ RpcCommandBase& rpc) const;
52
+
53
+ c10::intrusive_ptr<JitFuture> processRRefUserDelete(
54
+ RpcCommandBase& rpc) const;
55
+
56
+ c10::intrusive_ptr<JitFuture> processRRefChildAccept(
57
+ RpcCommandBase& rpc) const;
58
+
59
+ c10::intrusive_ptr<JitFuture> processRRefForkRequest(
60
+ RpcCommandBase& rpc) const;
61
+
62
+ c10::intrusive_ptr<JitFuture> processForwardAutogradReq(
63
+ RpcCommandBase& rpc,
64
+ const std::vector<c10::Stream>& streams) const;
65
+
66
+ c10::intrusive_ptr<JitFuture> processBackwardAutogradReq(
67
+ RpcCommandBase& rpc,
68
+ const std::vector<c10::Stream>& streams) const;
69
+
70
+ c10::intrusive_ptr<JitFuture> processCleanupAutogradContextReq(
71
+ RpcCommandBase& rpc) const;
72
+
73
+ c10::intrusive_ptr<JitFuture> processRunWithProfilingReq(
74
+ RpcCommandBase& rpc) const;
75
+
76
+ virtual void handleRRefDelete(c10::intrusive_ptr<RRef>& rref) const;
77
+
78
+ c10::intrusive_ptr<JitFuture> processRpc(
79
+ RpcCommandBase& rpc,
80
+ const MessageType& messageType,
81
+ const std::vector<c10::Stream>& streams) const;
82
+
83
+ virtual c10::intrusive_ptr<JitFuture> processRpcWithErrors(
84
+ RpcCommandBase& rpc,
85
+ const MessageType& messageType,
86
+ const std::vector<c10::Stream>& streams) const;
87
+
88
+ c10::intrusive_ptr<Message> handleError(
89
+ const std::exception& e,
90
+ const MessageType messageType,
91
+ int64_t messageId) const;
92
+
93
+ virtual bool cudaAvailable() const;
94
+
95
+ virtual c10::intrusive_ptr<JitFuture> processRRefBackward(
96
+ RpcCommandBase& rpc) const;
97
+
98
+ // Helpers to run user-defined functions, operators and other computations.
99
+
100
+ c10::intrusive_ptr<JitFuture> runJitOperator(
101
+ const jit::Operator& op,
102
+ std::vector<at::IValue>& stack,
103
+ const std::vector<c10::Stream>& streams) const;
104
+
105
+ // Helpers to convert various kinds of objects into already-completed futures.
106
+
107
+ c10::intrusive_ptr<JitFuture> asFuture(IValue value, TypePtr type) const;
108
+
109
+ c10::intrusive_ptr<JitFuture> asFuture(
110
+ c10::intrusive_ptr<Message> message) const;
111
+
112
+ c10::intrusive_ptr<JitFuture> asFuture(std::exception_ptr err) const;
113
+ };
114
+
115
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/python_headers.h>
4
+
5
+ namespace torch::distributed::rpc {
6
+
7
+ PyMethodDef* python_functions();
8
+
9
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_agent.h ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/request_callback.h>
5
+ #include <torch/csrc/distributed/rpc/types.h>
6
+
7
+ #include <algorithm>
8
+ #include <cctype>
9
+ #include <chrono>
10
+ #include <condition_variable>
11
+ #include <mutex>
12
+ #include <thread>
13
+
14
+ namespace torch::distributed::rpc {
15
+
16
+ using DeviceMap = std::unordered_map<c10::Device, c10::Device>;
17
+
18
+ // Default RPC timeout
19
+ constexpr float kDefaultRpcTimeoutSeconds = 60;
20
+ // Unset RPC timeout. This is the value agent::send() will have if user does not
21
+ // pass in a specific timeout, and indicates that we must use the default
22
+ // timeout for RPCs.
23
+ constexpr float kUnsetRpcTimeout = -1;
24
+ constexpr auto kDefaultInitMethod = "env://";
25
+ constexpr float kSecToMsConversion = 1000;
26
+ constexpr auto kRpcTimeoutErrorStr =
27
+ "RPC ran for more than set timeout ({} ms) and will now be marked with an error";
28
+
29
+ using steady_clock_time_point =
30
+ std::chrono::time_point<std::chrono::steady_clock>;
31
+ // Input is qualified name string, output is JIT StrongTypePtr
32
+ // Same as jit::TypeResolver, did not import jit::TypeResolver to here
33
+ // because it could introduce cyclic dependencies.
34
+ using TypeResolver =
35
+ std::function<c10::StrongTypePtr(const c10::QualifiedName&)>;
36
+
37
+ struct TORCH_API RpcBackendOptions {
38
+ RpcBackendOptions()
39
+ : RpcBackendOptions(kDefaultRpcTimeoutSeconds, kDefaultInitMethod) {}
40
+
41
+ RpcBackendOptions(float rpcTimeoutSeconds, std::string initMethod)
42
+ : rpcTimeoutSeconds(rpcTimeoutSeconds),
43
+ initMethod(std::move(initMethod)) {
44
+ TORCH_CHECK(rpcTimeoutSeconds >= 0, "RPC Timeout must be non-negative");
45
+ }
46
+
47
+ float rpcTimeoutSeconds;
48
+ std::string initMethod;
49
+ };
50
+
51
+ // A globally unique ID to identify an RpcAgent
52
+ struct TORCH_API WorkerInfo : torch::CustomClassHolder {
53
+ WorkerInfo(std::string name, int64_t id);
54
+
55
+ WorkerInfo(std::string name, worker_id_t id);
56
+
57
+ bool operator==(const WorkerInfo& rhs) {
58
+ return (id_ == rhs.id_) && (name_ == rhs.name_);
59
+ }
60
+
61
+ static constexpr size_t MAX_NAME_LEN = 128;
62
+
63
+ const std::string name_;
64
+ const worker_id_t id_;
65
+ };
66
+
67
+ struct TORCH_API RegisterWorkerInfoOnce {
68
+ RegisterWorkerInfoOnce();
69
+ };
70
+
71
+ TORCH_API std::ostream& operator<<(
72
+ std::ostream& os,
73
+ const WorkerInfo& workerInfo);
74
+
75
+ // Struct for options to configure the RPC Retry protocol.
76
+ struct TORCH_API RpcRetryOptions {
77
+ // Using a default constructor like all other Options structs in the RPC
78
+ // codebase. TORCH_CHECKs for input validation are done in the
79
+ // sendWithRetries function.
80
+ RpcRetryOptions() = default;
81
+ // Maximum number of times we will retry the RPC
82
+ int maxRetries{5};
83
+ // Initial duration between consecutive RPC send attempts
84
+ std::chrono::milliseconds rpcRetryDuration{std::chrono::milliseconds(1000)};
85
+ // Constant for exponential backoff used while calculating future wait
86
+ // durations
87
+ float retryBackoff{1.5};
88
+ };
89
+
90
+ // Struct that stores all the metadata needed to retry a given RPC.
91
+ struct TORCH_API RpcRetryInfo {
92
+ RpcRetryInfo(
93
+ const WorkerInfo& to,
94
+ c10::intrusive_ptr<Message> message,
95
+ c10::intrusive_ptr<JitFuture> originalFuture,
96
+ int retryCount,
97
+ RpcRetryOptions options)
98
+ : to_(to),
99
+ message_(std::move(message)),
100
+ originalFuture_(std::move(originalFuture)),
101
+ retryCount_(retryCount),
102
+ options_(options) {}
103
+
104
+ const WorkerInfo& to_;
105
+ c10::intrusive_ptr<Message> message_;
106
+ // Future that is returned to the caller of sendWithRetries().
107
+ c10::intrusive_ptr<JitFuture> originalFuture_;
108
+ // Number of send attempts completed so far.
109
+ int retryCount_;
110
+ RpcRetryOptions options_;
111
+ };
112
+
113
+ // ``RpcAgent`` is the base class for sending and receiving RPC messages. It
114
+ // provides a unified ``send`` API for both request and response messages, and
115
+ // will invoke the given ``RequestCallback`` to process received requests. It
116
+ // should immediately become ready to serve request and accept response after
117
+ // construction.
118
+ class TORCH_API RpcAgent {
119
+ public:
120
+ // `WorkerInfo` is the globally unique identifier for this RpcAgent instance.
121
+ // It contains a ``name_`` field and an ``id_`` field. ``name_`` is the
122
+ // globally unique name for this ``RpcAgent``. It is up to the ``RpcAgent``
123
+ // implementation to determine how to resolve names. ``id_`` is the globally
124
+ // unique ID for this ``RpcAgent``. This should be determined by the
125
+ // ``RpcAgent`` implementation.
126
+ // The ``RequestCallback`` will be invoked to handle received requests. This
127
+ // ``RpcAgent`` base class makes no assumption on the thread-safeness of the
128
+ // ``RequestCallback``. ``RpcAgent`` implementations need to make sure that
129
+ // its threading model conform to ``RequestCallback``'s requirement.
130
+ // NB: RpcAgent implementations should not start serving requests until
131
+ // ``start()`` is called, as there could be other contexts that have not been
132
+ // initialized yet at this time.
133
+ RpcAgent(
134
+ WorkerInfo id,
135
+ std::unique_ptr<RequestCallback> cb,
136
+ std::chrono::milliseconds rpcTimeout);
137
+
138
+ virtual ~RpcAgent();
139
+
140
+ // Send a message to the ``RpcAgent`` of id ``to`` and returns a
141
+ // ``JitFuture`` ptr. The implementation must be asynchronous, i.e., it
142
+ // cannot block until it receives the response.
143
+ //
144
+ // If ``message.isRequest()`` is true, the ``JitFuture`` will be
145
+ // completed when the response arrives. For other message types, the Future
146
+ // should be ignored by the caller.
147
+ virtual c10::intrusive_ptr<JitFuture> send(
148
+ const WorkerInfo& to,
149
+ c10::intrusive_ptr<Message> message,
150
+ const float rpcTimeoutSeconds = kUnsetRpcTimeout,
151
+ const DeviceMap& deviceMap = {}) = 0;
152
+
153
+ // Retries sending the message up to maxRetries times until an ACK is
154
+ // received. The duration between consecutive sends is increased over
155
+ // time using an exponential backoff algorithm.
156
+ //
157
+ // Sends ``message`` to the ``RpcAgent`` of id ``to`` and returns a
158
+ // ``JitFuture`` ptr, just like send(). Caller can specify the maximum
159
+ // number of retries for this RPC (default is 5), initial duration between
160
+ // sends (default is 1000ms), and backoff constant (default is 1.5) by
161
+ // passing in the RpcRetryOptions struct. This API might end up
162
+ // executing a method twice on the remote end (it does not guarantee
163
+ // exactly-once semantics). Therefore, the user must ensure their requests
164
+ // are idempotent.
165
+ c10::intrusive_ptr<JitFuture> sendWithRetries(
166
+ const WorkerInfo& to,
167
+ c10::intrusive_ptr<Message> message,
168
+ RpcRetryOptions retryOptions = RpcRetryOptions());
169
+
170
+ // Return a reference to the ``WorkerInfo`` of this RpcAgent.
171
+ // NB: not using ``std::optional<const std::string&>`` here because we might
172
+ // need to create a separate RPC API lib and avoid forcing all ``RpcAgent``
173
+ // implementations to depend on libtorch.
174
+ const WorkerInfo& getWorkerInfo() const;
175
+
176
+ // Return a reference to the ``WorkerInfo`` of the given ``workerName``.
177
+ virtual const WorkerInfo& getWorkerInfo(
178
+ const std::string& workerName) const = 0;
179
+
180
+ virtual const WorkerInfo& getWorkerInfo(worker_id_t id) const = 0;
181
+
182
+ virtual std::vector<WorkerInfo> getWorkerInfos() const = 0;
183
+
184
+ // Retrieve the timeout for all RPCs.
185
+ inline std::chrono::milliseconds getRpcTimeout() const {
186
+ return rpcTimeout_.load();
187
+ }
188
+
189
+ // Set the timeout for all RPCs
190
+ inline void setRpcTimeout(const std::chrono::milliseconds& rpcTimeout) {
191
+ rpcTimeout_.store(rpcTimeout);
192
+ }
193
+
194
+ // Call sync and join all internal threads. This method should be called
195
+ // before every RPC process exits.
196
+ virtual void join(bool shutdown = false, float timeout = 0) = 0;
197
+
198
+ // Synchronize the this process with other ``RpcAgent`` processes. Block until
199
+ // all ``RpcAgent``s reach this method and send all pending messages.
200
+ virtual void sync() = 0;
201
+
202
+ // Sets up backend-agnostic state for accepting requests. Currently, this
203
+ // entails setting rpcAgentRunning_ to true, creating the retry thread, and
204
+ // calling the backend's startImpl.
205
+ void start();
206
+
207
+ // Derived classes must override this function to start accepting requests.
208
+ // This is used to initialize any backend-specific state. Users must call
209
+ // start, not startImpl, to initialize the RPC Agent.
210
+ virtual void startImpl() = 0;
211
+
212
+ // Stop accepting requests and shutdown the RPC framework as soon as possible
213
+ // by terminating all RPC threads.
214
+ void shutdown();
215
+
216
+ // Derived classes must override this function to start accepting requests.
217
+ // THis is used to clean up any backend-specific state. Users must call
218
+ // shutdown, not shutdownImpl, to shutdown the RPC Agent.
219
+ virtual void shutdownImpl() = 0;
220
+
221
+ // Check if current RPC agent is set.
222
+ static bool isCurrentRpcAgentSet();
223
+
224
+ // Retrieve the valid current RPC agent.
225
+ static std::shared_ptr<RpcAgent> getCurrentRpcAgent();
226
+
227
+ // Set the current RPC agent.
228
+ static void setCurrentRpcAgent(std::shared_ptr<RpcAgent> rpcAgent);
229
+
230
+ // Retrieve metrics as KV map
231
+ virtual std::unordered_map<std::string, std::string> getMetrics() = 0;
232
+
233
+ // Retrieve debug info in addition to metrics as KV map
234
+ virtual std::unordered_map<std::string, std::string> getDebugInfo();
235
+
236
+ // Flag to control whether GIL wait times
237
+ // should be profiled or not.
238
+ void enableGILProfiling(bool flag);
239
+
240
+ // Retrieve wheher we should profile GIL wait times or not.
241
+ bool isGILProfilingEnabled();
242
+
243
+ // Set type resolver that will be passed to JIT pickler to resolver type Ptr
244
+ // based on type str.
245
+ void setTypeResolver(std::shared_ptr<TypeResolver> typeResolver);
246
+
247
+ // Get the type resolver
248
+ std::shared_ptr<TypeResolver> getTypeResolver();
249
+
250
+ // Retrieves the device map for the provided destination worker.
251
+ virtual DeviceMap getDeviceMap(const WorkerInfo& dst) const;
252
+
253
+ // Retrieve the (non-CPU) devices that are supported by the agent.
254
+ virtual const std::vector<c10::Device>& getDevices() const;
255
+
256
+ protected:
257
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
258
+ const WorkerInfo workerInfo_;
259
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
260
+ const std::unique_ptr<RequestCallback> cb_;
261
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
262
+ std::atomic<std::chrono::milliseconds> rpcTimeout_;
263
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
264
+ std::atomic<bool> profilingEnabled_;
265
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
266
+ std::shared_ptr<TypeResolver> typeResolver_;
267
+ // Atomic boolean indicating whether this agent is running. It controls
268
+ // whether several background threads should be running. It is set in
269
+ // RpcAgent::start() and unset in the derived class shutdown().
270
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
271
+ std::atomic<bool> rpcAgentRunning_;
272
+
273
+ private:
274
+ static std::shared_ptr<RpcAgent> currentRpcAgent_;
275
+ // Add GIL wait time data point to metrics
276
+ virtual void addGilWaitTime(const std::chrono::microseconds gilWaitTime) = 0;
277
+ friend class PythonRpcHandler;
278
+
279
+ // Map that stores metadata for RPC's that may need to be re-tried as well as
280
+ // the timepoint at which we should re-try them.
281
+ std::map<
282
+ steady_clock_time_point,
283
+ std::unordered_set<std::shared_ptr<RpcRetryInfo>>>
284
+ rpcRetryMap_;
285
+
286
+ // Thread that checks for retryable RPC's in the rpcRetryMap_ and sleeps until
287
+ // the next unACKed RPC's timeout has expired.
288
+ std::thread rpcRetryThread_;
289
+
290
+ // Function that rpcRetryThread_ calls in a loop as long as RpcAgent is
291
+ // running.
292
+ void retryExpiredRpcs();
293
+
294
+ // This is the callback attached to futures corresponding to send retries.
295
+ // This handles 3 cases: 1). send was completed, 2). send failed with an
296
+ // error and we've done maxRetries failed send attempts, and 3). send
297
+ // failed with an error and we have more retries to go. In case 1, we mark
298
+ // the original future as complete. In case 2, we mark the future with an
299
+ // error and do not retry again. In case 3, we move the RpcRetryInfo struct
300
+ // to another time point in the map to schedule the RPC for a future send.
301
+ void rpcRetryCallback(
302
+ JitFuture& message,
303
+ steady_clock_time_point newTime,
304
+ std::shared_ptr<RpcRetryInfo> earliestRpc);
305
+
306
+ // Function that uses the exponential backoff algorithm to compute the next
307
+ // time point to retry a given RPC.
308
+ inline steady_clock_time_point computeNewRpcRetryTime(
309
+ RpcRetryOptions& options,
310
+ int retryCount) {
311
+ // The exponential backoff algorithm being used here is:
312
+ // newTime = timeNow + (retryDuration * (backoffConstant ^ retryCount)).
313
+ std::chrono::milliseconds timedelta =
314
+ std::chrono::duration_cast<std::chrono::milliseconds>(
315
+ options.rpcRetryDuration * pow(options.retryBackoff, retryCount));
316
+ return std::chrono::time_point_cast<std::chrono::milliseconds>(
317
+ std::chrono::steady_clock::now() + timedelta);
318
+ }
319
+
320
+ // Condition Variable to signal when the rpcRetryMap_ has been populated.
321
+ std::condition_variable rpcRetryMapCV_;
322
+
323
+ // Mutex to protect RpcRetryMap_.
324
+ std::mutex rpcRetryMutex_;
325
+ };
326
+
327
+ } // namespace torch::distributed::rpc
328
+
329
+ namespace std {
330
+ template <>
331
+ struct hash<torch::distributed::rpc::WorkerInfo> {
332
+ std::size_t operator()(
333
+ const torch::distributed::rpc::WorkerInfo& worker_info) const noexcept {
334
+ return worker_info.id_;
335
+ }
336
+ };
337
+ } // namespace std
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rpc_command_base.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/types.h>
5
+
6
+ namespace torch::distributed::rpc {
7
+
8
+ // Base class for all RPC request and responses.
9
+ class RpcCommandBase {
10
+ public:
11
+ // Need to override this to serialize the RPC. This should destructively
12
+ // create a message for the RPC (Hence the &&).
13
+ c10::intrusive_ptr<Message> toMessage() && {
14
+ JitRRefPickleGuard jitPickleGuard;
15
+ return std::move(*this).toMessageImpl();
16
+ }
17
+ virtual c10::intrusive_ptr<Message> toMessageImpl() && = 0;
18
+ virtual ~RpcCommandBase() = 0;
19
+ };
20
+
21
+ inline RpcCommandBase::~RpcCommandBase() = default;
22
+
23
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_context.h ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/rpc_agent.h>
5
+ #include <torch/csrc/distributed/rpc/rref_impl.h>
6
+ #include <torch/csrc/distributed/rpc/types.h>
7
+ #include <torch/csrc/distributed/rpc/utils.h>
8
+
9
+ #include <atomic>
10
+ #include <optional>
11
+
12
+ namespace torch::distributed::rpc {
13
+
14
+ namespace callback {
15
+ // It's the callback for RemoteCall.
16
+ void TORCH_API
17
+ confirmPendingUser(const JitFuture& jitFuture, const ForkId& expectedForkId);
18
+
19
+ // It's the callback for finishing creating owner rref, it returned deletedRRef,
20
+ // so that the deletedRRef can be handled under GIL in python_functions.cpp if
21
+ // deletedRRef contains python object.
22
+ c10::intrusive_ptr<RRef> TORCH_API
23
+ finishCreatingOwnerRRef(const JitFuture& jitFuture, const RRefId& rrefId);
24
+ } // namespace callback
25
+
26
+ // Manages RRef lifetime and keeps track of RRef forks.
27
+ class TORCH_API RRefContext {
28
+ public:
29
+ static RRefContext& getInstance();
30
+ // NB: This method must be called before destructing RRefContext singleton.
31
+ // Similar to delForkOfOwner, this method returns a vector of OwnerRRefs that
32
+ // hold py::object. The call-site is also responsible for resetting those
33
+ // shared_ptr objects with a GIL. See comments at delForkOfOwner() for more
34
+ // details.
35
+ static std::vector<c10::intrusive_ptr<RRef>> destroyInstance(
36
+ bool ignoreRRefLeak = true);
37
+
38
+ static void handleException(const JitFuture& jitFuture);
39
+
40
+ // handle exception without throw ::c10::Error again
41
+ static void handleExceptionSilent(const JitFuture& jitFuture);
42
+
43
+ RRefContext(const RRefContext&) = delete;
44
+ RRefContext(RRefContext&& other) = delete;
45
+ void operator=(const RRefContext&) = delete;
46
+ RRefContext& operator=(RRefContext&& other) = delete;
47
+
48
+ ~RRefContext();
49
+
50
+ // get the worker id of the current worker
51
+ inline worker_id_t getWorkerId() const {
52
+ return agent_->getWorkerInfo().id_;
53
+ }
54
+
55
+ // get the worker name of the current worker
56
+ inline const std::string& getWorkerName() const {
57
+ return agent_->getWorkerInfo().name_;
58
+ }
59
+
60
+ // generate a globally unique ID
61
+ inline GloballyUniqueId genGloballyUniqueId() {
62
+ return GloballyUniqueId(getWorkerId(), nextLocalId_++);
63
+ }
64
+
65
+ inline const std::shared_ptr<RpcAgent>& agent() const {
66
+ return agent_;
67
+ }
68
+
69
+ // create a ``UserRRef`` owned by the worker ``ownerId``
70
+ c10::intrusive_ptr<UserRRef> createUserRRef(
71
+ worker_id_t ownerId,
72
+ const TypePtr& type);
73
+
74
+ // Convert an RRefForkData into an RRef. This RRef could be user or owner.
75
+ // This RRef could have already existed before, or could be created in this
76
+ // method, we pass type here to validate or help the rref creation.
77
+ c10::intrusive_ptr<RRef> getOrCreateRRef(
78
+ const RRefForkData& rfd,
79
+ const TypePtr& type);
80
+
81
+ // Get the ``OwnerRRef`` of id ``rrefId``. If it does not exist, create a new
82
+ // one. This function is called in two places:
83
+ // 1. when processing ``rpc.remote()``, i.e., ``SCRIPT_REMOTE_CALL``
84
+ // ``PYTHON_REMOTE_CALL``.
85
+ // 2. when unpickling ``OwnerRRef``.
86
+ // What's common in these two cases are, 1) the RRefId is already generated
87
+ // 2) the TypePtr is presented. So it can always create the ``OwnerRRef`` if
88
+ // it is not yet available.
89
+ c10::intrusive_ptr<OwnerRRef> getOrCreateOwnerRRef(
90
+ const RRefId& rrefId,
91
+ const TypePtr& type);
92
+
93
+ // Create an empty owner rref of type.
94
+ // This method is called to first time generate an ``OwnerRRef``, e.g.,
95
+ // 1) ``rpc.RRef(obj)``
96
+ // 2) create the ``OwnerRRef`` on `rpc.remote()` caller side.
97
+ // What's common in these two cases are, 1) the RRefId hasn't been generated
98
+ // 2) the TypePtr is presented.
99
+ c10::intrusive_ptr<OwnerRRef> createOwnerRRef(const TypePtr& type);
100
+
101
+ // Returns a Future of the OwnerRRef, which will be marked completed when
102
+ // ``OwnerRRef`` is created. This method is used when the TypePtr is not
103
+ // available, e.g., when processing to_here(). The forceCreated flag can be
104
+ // used to ensure that the rref is created on the owner, otherwise throw in
105
+ // cases where the user of this API expects this to return a completed future.
106
+ // Note that the return value is a intrusive_ptr to a c10::ivalue::Future that
107
+ // holds the RRef.
108
+ c10::intrusive_ptr<JitFuture> getOwnerRRef(
109
+ const RRefId& rrefId,
110
+ bool forceCreated = false);
111
+
112
+ // Adding the RRefId of an OwnerRRef into the forks_ map. This is useful when
113
+ // making a remote call to self, which as for now, still goes through serde
114
+ // and invokes request callback. In this case, the OwnerRRef has already been
115
+ // created on the send side, and we need to pass it to the receive side,
116
+ // instead of creating a new OwnerRRef. This is done by adding the OwnerRRef
117
+ // into owners_. However, that alone is not enough, as it could be deleted
118
+ // when all UserRRef die, which would then remove the OwnerRRef from owners_
119
+ // and this could happen before the self remote call finishes. To prevent
120
+ // that, this API adds the RRefId as a ForkId, which will then delete the
121
+ // ForkId when the self remote is done.
122
+ void addSelfAsFork(c10::intrusive_ptr<OwnerRRef>& rref);
123
+
124
+ // Register a fork of the ``OwnerRRef``, and inserts a intrusive_ptr of the
125
+ // ``OwnerRRef`` in a map to keep it alive.
126
+ void addForkOfOwner(const RRefId& rrefId, const ForkId& forkId);
127
+ // Performs the same function as addForkOfOwner but ignores duplicate
128
+ // requests. This idempotent function is used with RREF_FORK_REQUEST calls,
129
+ // whereas all other message types use the non-idempotent variant.
130
+ void addForkOfOwnerIfNotPresent(const RRefId& rrefId, const ForkId& forkId);
131
+ // Delete a fork of the ``OwnerRRef``. NB: this could trigger deletion on the
132
+ // IValue or py::object. For the later, this method will acquire GIL.
133
+ // NB: If this fork deletion triggered deleting OwnerRRef, this method will
134
+ // return a shared_ptr to the OwnerRRef, which is likely to be the last
135
+ // shared_ptr instance for it. Therefore, deleting this shared_ptr<OwnerRRef>
136
+ // will also trigger deleting the object it points to. If OwnerRRef holds a
137
+ // py::object, deleting it require GIL. The call site should guarded it with
138
+ // a GIL and reset the shared_ptr. The GIL-guarded deletion is intentionally
139
+ // left out of this function to avoid creating dependency on pybind.
140
+ c10::intrusive_ptr<RRef> delForkOfOwner(
141
+ const RRefId& rrefId,
142
+ const ForkId& forkId);
143
+
144
+ // Invoked when pickling an RRef to setup child/fork properly
145
+ RRefForkData prepareChildFork(const c10::intrusive_ptr<RRef>& rref);
146
+ // Invoked when unpickling an RRef to send RREF_FORK_REQUEST to owner and
147
+ // send RREF_CHILD_ACCEPT to the parent.
148
+ // NB: forkId is necessary here as the rref could be an OwnerRRef
149
+ void notifyOwnerAndParentOfFork(
150
+ const ForkId& forkId,
151
+ worker_id_t parent,
152
+ const c10::intrusive_ptr<RRef>& rref);
153
+
154
+ // When a UserRRef is forked to another worker (user or owner), it is added
155
+ // into pendingChildren_ to be held alive until it receives RREF_CHILD_ACCEPT
156
+ // from the child.
157
+ // NB: This is necessary for both user and owner child. As we do not have FIFO
158
+ // communication between workers, we need this strategy to make sure that all
159
+ // previously submitted rpc/remote calls are acked before sending out the
160
+ // RREF_USER_DELETE message. Otherwise, the OwnerRRef could be deleted too
161
+ // soon.
162
+ void addPendingChild(
163
+ const ForkId& forkId,
164
+ const c10::intrusive_ptr<RRef>& rref);
165
+ void delPendingChild(const ForkId& forkId);
166
+
167
+ // When a UserRRef is created, it is added into pendingUsers_ to be held alive
168
+ // until it receives RREF_USER_ACCEPT from the owner.
169
+ void addPendingUser(
170
+ const ForkId& forkId,
171
+ const c10::intrusive_ptr<RRef>& rref);
172
+ void delPendingUser(const ForkId& forkId);
173
+ void addConfirmedUser(
174
+ const ForkId& forkId,
175
+ const c10::intrusive_ptr<RRef>& rref);
176
+
177
+ // Retrieve a pending user given the fork ID. Throws if the user has already
178
+ // been confirmed (i.e. is no longer in the pendingUsers_ map).
179
+ c10::intrusive_ptr<RRef> getPendingUser(const ForkId& forkId);
180
+
181
+ // Start recording new pending UserRRefs. All pending UserRRefs introduced
182
+ // after this point will be put into the thread_local userTable_, which will
183
+ // then be consumed and cleared in waitForThreadLocalPendingRRefs().
184
+ void recordThreadLocalPendingRRefs();
185
+ // End recording new pending UserRRefs, and clear the thread_local userTable_.
186
+ // Returns a Future which will be marked as completed when all pending
187
+ // UserRRefs in the current userTable_ are confirmed by their owners. The bool
188
+ // value in the Future is unused.
189
+ // This method is useful to make sure RRefs in user function arguments are
190
+ // confirmed before launching user code.
191
+ // NB: Callers of this method does not need to keep the returned Future alive,
192
+ // because this Future is already captured in callbacks of the
193
+ // PendingUserState. If there is no pending UserRRefs, this method returns a
194
+ // completed future.
195
+ c10::intrusive_ptr<JitFuture> waitForThreadLocalPendingRRefs();
196
+ // Only call this function when there are errors during a recording session,
197
+ // and it is likely that waitForThreadLocalPendingRRefs() cannot be invoked
198
+ // properly.
199
+ // TODO: make this a context guard
200
+ void clearRecordedPendingRRefsOnError();
201
+
202
+ void delUser(
203
+ const worker_id_t owner,
204
+ const RRefId& rrefId,
205
+ const ForkId& forkId);
206
+ void delAllUsersAndUnforkedOwners(std::chrono::milliseconds timeoutMillis);
207
+
208
+ std::unordered_map<std::string, std::string> getDebugInfo();
209
+
210
+ private:
211
+ struct PendingUserState {
212
+ PendingUserState(c10::intrusive_ptr<RRef> rref)
213
+ : rref_(std::move(rref)),
214
+ confirmationFuture_(c10::make_intrusive<JitFuture>(BoolType::get())) {
215
+ }
216
+
217
+ inline void confirm() {
218
+ c10::static_intrusive_pointer_cast<UserRRef>(rref_)->confirm();
219
+ confirmationFuture_->markCompleted();
220
+ }
221
+
222
+ c10::intrusive_ptr<RRef> rref_;
223
+ // Use Future.wait() and Future.markCompleted() to block and unblock user
224
+ // functions. The bool value wrapped by the future_ is not used.
225
+ c10::intrusive_ptr<JitFuture> confirmationFuture_;
226
+ };
227
+
228
+ RRefContext(std::shared_ptr<RpcAgent>);
229
+
230
+ c10::intrusive_ptr<UserRRef> createUserRRef(
231
+ worker_id_t ownerId,
232
+ const RRefId& rrefId,
233
+ const ForkId& forkId,
234
+ const TypePtr& type);
235
+
236
+ void finishForkRequest(const ForkId& forkId, worker_id_t parent);
237
+
238
+ // If there is any leak on any RRef, this method will throw an error.
239
+ void checkRRefLeaks(bool ignoreRRefLeak);
240
+
241
+ static std::atomic<local_id_t> nextLocalId_;
242
+
243
+ const std::shared_ptr<RpcAgent> agent_;
244
+ mutable std::mutex mutex_;
245
+ // Keep OwnerRRefs alive until there is no living UserRRefs.
246
+ std::unordered_map<RRefId, c10::intrusive_ptr<RRef>, RRefId::Hash> owners_;
247
+ // A map to track OwnerRRefs that are requested but not yet created. This can
248
+ // happen if the to_here() message is processed on the owner before the
249
+ // corresponding creator rpc.remote() message. If this happens, instead of
250
+ // to_here() RPC thread to block waiting for the OwnerRRef creation, the
251
+ // RRefContext returns a Future, so that the RPC request processing logic can
252
+ // attach subsequent code as a callback to that Future.
253
+ // NB: the OwnerRRefs in this map must be cleared when the corresponding
254
+ // OwnerRRef is created. Note that the values in this map are intrusive_ptrs
255
+ // to c10::ivalue::Future that will be marked completed with the owner RRef.
256
+ std::unordered_map<RRefId, c10::intrusive_ptr<JitFuture>, RRefId::Hash>
257
+ pendingOwners_;
258
+ // Tracks known living UserRRefs of an OwnerRRef
259
+ std::unordered_map<
260
+ RRefId,
261
+ std::unordered_set<ForkId, ForkId::Hash>,
262
+ RRefId::Hash>
263
+ forks_;
264
+
265
+ // This cond var is used by deleteAllUsers(), a event notification is sent if
266
+ // number of pending UserRRef or UserRRef children is reduced, or
267
+ // number of owned OwnerRRef is reduced.
268
+ std::condition_variable deleteAllUsersCV_;
269
+ // The follow 3 maps keep UserRRefs alive by holding a intrusive_ptr to the
270
+ // RRef instances. A UserRRef must be added into this map if any of the
271
+ // following two conditions is true:
272
+ //
273
+ // (1) A UserRRef has not been accepted by owner yet.
274
+ //
275
+ // It can be used or shared, but cannot be deleted, and hence kept alive
276
+ // in this map. A message of type RREF_USER_ACCEPT will move the
277
+ // corresponding RRef from pendingUsers_ map to confirmedUsers_ map.
278
+ std::unordered_map<ForkId, std::shared_ptr<PendingUserState>, ForkId::Hash>
279
+ pendingUsers_;
280
+ // UserRRefs are added into this map when it is confirmed by the owner.
281
+ // When destroying RRefContext this map helps to find local UserRRefs
282
+ // and send delete messages if they are still not deleted by Python
283
+ // garbage collection.
284
+ std::unordered_map<ForkId, c10::weak_intrusive_ptr<RRef>, ForkId::Hash>
285
+ confirmedUsers_;
286
+
287
+ // (2) A UserRRef has forked a child UserRRef which has not been accepted by
288
+ // the owner yet.
289
+ //
290
+ // In this case, this UserRRef cannot send out RREF_USER_DELETE message,
291
+ // as it could potentially trigger the OwnerRRef been deleted before the
292
+ // owner learns about the forked child.
293
+ std::unordered_map<ForkId, c10::intrusive_ptr<RRef>, ForkId::Hash>
294
+ pendingChildren_;
295
+
296
+ // The RRef context performs its operations through async RPC requests, in
297
+ // order to not block the user code. Therefore the RRef context's state may be
298
+ // lagging a bit behind what it is intended to be, while it waits for these
299
+ // requests to complete. To allow syncing when needed, we store the count of
300
+ // these pending requests, so that users can wait for it to reach zero.
301
+ std::atomic<int64_t> numPendingFutures_{0};
302
+
303
+ std::mutex destroyedMutex_;
304
+ bool destroyed_{false};
305
+
306
+ // Thread local states to keep UserRRefs deserialized from user function
307
+ // arguments.
308
+ static thread_local std::vector<std::shared_ptr<PendingUserState>> userTable_;
309
+ // A flag indicating whether subsequently created UserRRefs should be added to
310
+ // the thread_local userTable_. The flag is set to true before serializing
311
+ // RPC arguments and then set to false before running the corresponding
312
+ // user code. See addPendingUser and delPendingUser for more details.
313
+ // NB: The reason for having this flag is because addPendingUser are called in
314
+ // two cases, and we only want to track the 2nd case.
315
+ // (1) RRef as the return value: when calling rpc.remote, the UserRRef on the
316
+ // caller side is added to the context using addPendingUser.
317
+ // (2) RRef as an argument: When running an RPC using RRefs as arguments, the
318
+ // RRef is forwarded to the callee as new UserRRefs (if the callee is not
319
+ // the owner). In this case, we block running the user function until all
320
+ // UserRRefs are confirmed by the owner.
321
+ // This contract gurantees that no UserRRefs can be used remotely without
322
+ // confirmation. Note that, however, the UserRRef created by rpc.remote can
323
+ // still be passed to local functions as arguments and used there. This is by
324
+ // design, because this feature is especially useful when, say a master node
325
+ // creates multiple UserRRefs in a loop and then shares them with other nodes.
326
+ // Blocking every iteration in the loop until RRefs are confirmed will slow
327
+ // this down. This nuance on UserRRef can be interpreted as we only make
328
+ // exceptions for UserRRef creators. And using the UserRRef on its creator
329
+ // without confirmation is OK, because the creator would either call to_here
330
+ // or forward the UserRRef, and both would then require confirmations from the
331
+ // owner.
332
+ static thread_local bool recording_;
333
+ };
334
+
335
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_impl.h ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/jit_type.h>
4
+ #include <ATen/core/rref_interface.h>
5
+ #include <c10/core/Event.h>
6
+ #include <torch/csrc/distributed/rpc/message.h>
7
+ #include <torch/csrc/distributed/rpc/rpc_agent.h>
8
+ #include <torch/csrc/distributed/rpc/types.h>
9
+ #include <optional>
10
+
11
+ #include <atomic>
12
+
13
+ namespace torch::distributed::rpc {
14
+
15
+ class RRef;
16
+ class RRefContext;
17
+ class UserRRef;
18
+
19
+ constexpr int OWNER_IDX = 0; // index of ownerId in the tuple
20
+ constexpr int RREFID_ON_IDX = 1; // index of RRefId.createdOn_ in the tuple
21
+ constexpr int RREFID_ID_IDX = 2; // index of RRefId.localId_ in the tuple
22
+ constexpr int FORKID_ON_IDX = 3; // index of ForkId.createdOn_ in the tuple
23
+ constexpr int FORKID_ID_IDX = 4; // index of ForkId.localId_ in the tuple
24
+ constexpr int PARENT_IDX = 5; // index of parent in the tuple
25
+ constexpr int TYPE_IDX = 6; // index of parent in the tuple
26
+
27
+ // NB: if more fields are added, make sure this field is also bumped
28
+ constexpr int RFD_TUPLE_SIZE = 7; // number of RRefForkData fields in py::tuple
29
+
30
+ // Represents fork of an RRef to be sent over the wire.
31
+ struct TORCH_API RRefForkData {
32
+ const worker_id_t ownerId_;
33
+ const RRefId rrefId_;
34
+ const ForkId forkId_;
35
+ const worker_id_t parent_;
36
+ const std::string typeStr_;
37
+
38
+ RRefForkData(
39
+ worker_id_t ownerId,
40
+ const RRefId& rrefId,
41
+ const ForkId& forkId,
42
+ worker_id_t parent,
43
+ std::string typeStr);
44
+ };
45
+
46
+ // Note [RRef Protocol]
47
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~
48
+ //
49
+ // [Background]
50
+ //
51
+ // RRef stands for Remote REFerence. Each RRef is owned by a single worker
52
+ // (i.e., owner) and can be used by multiple users. The owner stores the real
53
+ // data referenced by its RRefs. RRef needs to support fast and scalable RPC.
54
+ // Hence, in the design, we avoid using a single global master to keep RRef
55
+ // states, instead owners will keep track of the global reference counts
56
+ // for its RRefs. Every RRef can be uniquely identified by a global RRefId,
57
+ // which is assigned at the time it is first created either on a user or on the
58
+ // owner.
59
+ //
60
+ // On the owner worker, there is only one OwnerRRef instance, which contains the
61
+ // real data, while on user workers, there can be as many UserRRefs as
62
+ // necessary, and UserRRef does not hold the data. All usage on the OwnerRRef
63
+ // should retrieve the unique OwnerRRef instance using the globally unique
64
+ // RRefId. //A UserRRef will be created when it is used as an argument or return
65
+ // value in dist.rpc or dist.remote call, but RRef forking and reference
66
+ // counting (RC) are completely transparent to applications. Every UserRRef will
67
+ // also have its globally unique ForkId.
68
+ //
69
+ // [Assumptions]
70
+ //
71
+ // 1. Transient Network Failures
72
+ //
73
+ // TODO: current RRef implementation does not tolerate failures
74
+ //
75
+ // The RRef design handles transient network failures by retrying
76
+ // messages. Node crashes or permanent network partition is beyond the scope.
77
+ // When those incidents occur, the application may take down all workers, revert
78
+ // to the previous checkpoint, and resume training.
79
+ //
80
+ // 2. Non-idempotent UDFs
81
+ //
82
+ // We assume UDFs are not idempotent and therefore cannot be retried. However,
83
+ // internal RRef control messages are idempotent and retried upon message
84
+ // failure.
85
+ //
86
+ // TODO: RRef internal messages are not yet idempotent
87
+ //
88
+ // 3. Out of Order Message Delivery
89
+ //
90
+ // We do not assume message delivery order between any pair of nodes, because
91
+ // both sender and receiver are using multiple threads. There is no guarantee on
92
+ // which message will be processed first.
93
+ //
94
+ // [RRef Lifetime]
95
+ //
96
+ // The goal of the protocol is to delete an OwnerRRef at an appropriate time.
97
+ // The right time to delete an OwnerRRef is when there are no living UserRRefs
98
+ // and Python GC also agrees to delete the OwnerRRef instance on the owner. The
99
+ // tricky part is to determine if there are any living UserRRefs.
100
+ //
101
+ // A user can get a UserRRef in three situations:
102
+ //
103
+ // (1). Receiving a UserRRef from the owner.
104
+ // (2). Receiving a UserRRef from another user.
105
+ // (3). Creating a new UserRRef owned by another worker.
106
+ //
107
+ // (1) is the simplest case where the owner initiates the fork, and hence it can
108
+ // easily increment local RC. The only requirement is that any UserRRef must
109
+ // notify the owner before destruction. Hence, we need the first guarantee:
110
+ //
111
+ // G1. The owner will be notified when any UserRRef is deleted.
112
+ //
113
+ // As messages might come delayed or out-of-order, we need more one guarantee to
114
+ // make sure the delete message is not sent out too soon. Let us first introduce
115
+ // a new concept. If A sends an RPC to B that involves an RRef, we call the RRef
116
+ // on A the parent RRef and the RRef on B the child RRef.
117
+ //
118
+ // G2. Parent RRef cannot be deleted until the child RRef is confirmed by the
119
+ // owner.
120
+ //
121
+ // Under (1), where the caller is UserRRef and callee is OwnerRRef, it simply
122
+ // means that the user will not send out the delete message until all previous
123
+ // messages are ACKed. Note that ACKed does not mean the owner finishes
124
+ // executing the function, instead, it only means the owner has retrieved its
125
+ // local OwnerRRef and about to pass it to the function, which is sufficient to
126
+ // keep the OwnerRRef alive even if the delete message from the user arrives at
127
+ // the owner before the function finishes execution.
128
+ //
129
+ // With (2) and (3), it is possible that the owner only partially knows the RRef
130
+ // fork graph or not even knowing it at all. For example, the RRef could be
131
+ // constructed on a user, and before the owner receives the RPC call, the
132
+ // creator user might have already shared the RRef with other users, and those
133
+ // users could further share the RRef. One invariant is that the fork graph of
134
+ // any RRef is always a tree rooted at the owner, because forking an RRef always
135
+ // creates a new RRef instance, and hence every RRef has a single parent. One
136
+ // nasty detail is that when an RRef is created on a user, technically the owner
137
+ // is not its parent but we still consider it that way and it does not break the
138
+ // argument below.
139
+ //
140
+ // The owner's view on any node (fork) in the tree has three stages:
141
+ //
142
+ // 1) unknown -> 2) known -> 3) deleted.
143
+ //
144
+ // The owner's view on the entire tree keeps changing. The owner deletes its
145
+ // OwnerRRef instance when it thinks there are no living UserRRefs, i.e., when
146
+ // OwnerRRef is deleted, all UserRRefs could be either indeed deleted or
147
+ // unknown. The dangerous case is when some forks are unknown and others are
148
+ // deleted.
149
+ //
150
+ // G2 trivially guarantees that no parent UserRRef Y can be deleted before the
151
+ // owner knows all of Y's children UserRRefs.
152
+ //
153
+ // However, it is possible that the child UserRRef Z may be deleted before the
154
+ // owner knows its parent Y. More specifically, this can happen when all of Z's
155
+ // messages are processed by the owner before all messages from Y, including the
156
+ // delete message. Nevertheless, this does not cause any problem. Because, at
157
+ // least one of Y's ancestor will be alive, and it will prevent the owner from
158
+ // deleting the OwnerRRef. Consider the following example: (NB: this scenario
159
+ // will no longer relevant when we block UDF until all RRefs are confirmed by
160
+ // the owner)
161
+ //
162
+ // OwnerRRef -> A -> Y -> Z
163
+ //
164
+ // OwnerRRef forks to A, then A forks to Y, and Y forks to Z. Z can be deleted
165
+ // without OwnerRRef knowing Y. However, the OwnerRRef will at least know A, as
166
+ // the owner directly forks the RRef to A. A won't die before the owner knows Y.
167
+ //
168
+ // Things get a little trickier if the RRef is created on a user:
169
+ //
170
+ // OwnerRRef
171
+ // ^
172
+ // |
173
+ // A -> Y -> Z
174
+ //
175
+ // If Z calls to_here on the UserRRef, the owner at least knows A when Z is
176
+ // deleted, because otherwise to_here wouldn't finish. If Z does not call
177
+ // to_here, it is possible that the owner receives all messages from Z before
178
+ // any message from A and Y. In this case, as the real data of the OwnerRRef has
179
+ // not been created yet, there is nothing to be deleted either. It is the same
180
+ // as Z does not exist at all Hence, it's still OK.
181
+ //
182
+ // See #26759 for more details and discussions.
183
+ //
184
+ // TODO: make RRef an IValue, and edit createStackForSchema accordingly
185
+ // TODO: make RRef system messages idempotent and retry on failures.
186
+ //
187
+ // ``RRef`` is the base type for both ``UserRRef`` and ``OwnerRRef``.
188
+ // Each ``RRef`` has a globally unique ``RRefId``.
189
+ class TORCH_API RRef : public RRefInterface {
190
+ public:
191
+ // RRef is made NOT copyable NOT movable to prevent messing up reference
192
+ // counting.
193
+ explicit RRef(const RRef& other) = delete;
194
+ explicit RRef(RRef&& other) = delete;
195
+ RRef& operator=(RRef&& other) = delete;
196
+
197
+ ~RRef() override = default;
198
+
199
+ // returns the worker id of the owner
200
+ inline worker_id_t owner() const override {
201
+ return ownerId_;
202
+ }
203
+
204
+ // returns the worker name of the owner
205
+ inline std::string ownerName() const override {
206
+ return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_).name_;
207
+ }
208
+
209
+ // returns the worker info of the owner
210
+ inline WorkerInfo ownerWorkerInfo() const {
211
+ return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_);
212
+ }
213
+
214
+ // Returns the globally unique RRefId of this RRef
215
+ inline const RRefId& rrefId() const {
216
+ return rrefId_;
217
+ }
218
+
219
+ inline bool isPyObj() const {
220
+ return type_ == PyObjectType::get();
221
+ }
222
+ inline const TypePtr type() const override {
223
+ return type_;
224
+ }
225
+
226
+ // Save the future corresponding to the creation of this RRef on a remote
227
+ // node. Note that this is only set when processing requests invoked with
228
+ // rpc.remote. This is only used to get the future corresponding to the rref
229
+ // for profiling use cases.
230
+ inline void registerOwnerCreationFuture(c10::intrusive_ptr<JitFuture> fut) {
231
+ ownerCreationFuture_ = std::move(fut);
232
+ }
233
+
234
+ // Get the future corresponding to the creation of this rref.
235
+ inline c10::intrusive_ptr<JitFuture> getOwnerCreationFuture() const {
236
+ return ownerCreationFuture_;
237
+ }
238
+
239
+ // Check if creation of this RRef on owner node has timed out.
240
+ inline bool getTimedOut() const {
241
+ return timedOut_.load();
242
+ }
243
+
244
+ // Dispatches an error to the correct handler based on its RPCErrorType.
245
+ void handleError(RPCErrorType errorType, const JitFuture& JitFuture);
246
+
247
+ // Send delete UserRRef request to Owner,
248
+ // if the request hasn't been sent yet.
249
+ // There are 2 cases to call it,
250
+ // 1, Python GC decides end of UserRRef lifetime, calling destructor.
251
+ // 2, RPC module graceful shutdown calls it on all UserRRefs tracked
252
+ // in the RRefContext.
253
+ virtual void tryDel() {}
254
+
255
+ protected:
256
+ // Indicates that the creation of this RRef on owner node has timed out.
257
+ inline void setTimedOut() {
258
+ timedOut_ = true;
259
+ }
260
+ friend class RRefContext;
261
+
262
+ RRef(worker_id_t ownerId, const RRefId& rrefId, TypePtr type);
263
+
264
+ virtual RRefForkData fork() const;
265
+
266
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
267
+ const worker_id_t ownerId_;
268
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
269
+ const RRefId rrefId_;
270
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
271
+ std::atomic<bool> timedOut_{false};
272
+
273
+ // type field to denote the type of the element that the RRef is holding
274
+ // it could be any TypePtr that JIT support, including PyObjectType
275
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
276
+ const TypePtr type_;
277
+ // Future corresponding to request to create RRef on remote node.
278
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
279
+ c10::intrusive_ptr<JitFuture> ownerCreationFuture_;
280
+ };
281
+
282
+ // ``UserRRef`` represents a user of an RRef. Besides the ``RRefId``, each user
283
+ // also has a globally unique ``ForkId`` to identify this user. ``UserRRef``
284
+ // never owns the real value, the only way to get the value of the ``RRef`` is
285
+ // to call ``to_here()`` and get a copy..
286
+ class TORCH_API UserRRef final : public RRef {
287
+ public:
288
+ UserRRef(const UserRRef& other) = delete;
289
+ UserRRef(UserRRef&& other) = delete;
290
+ UserRRef& operator=(const UserRRef& other) = delete;
291
+ UserRRef& operator=(UserRRef&& other) = delete;
292
+
293
+ UserRRef(
294
+ worker_id_t ownerId,
295
+ const RRefId& rrefId,
296
+ const ForkId& forkId,
297
+ TypePtr type);
298
+
299
+ inline bool isOwner() const override {
300
+ return false;
301
+ }
302
+
303
+ inline bool confirmedByOwner() const override {
304
+ return confirmedByOwner_;
305
+ }
306
+
307
+ // Returns the globally unique ForkId of this RRef
308
+ const ForkId& forkId() const;
309
+
310
+ // Get of copy of the value from the ``OwnerRRef``. If the value is not ready
311
+ // yet, this call will block.
312
+ IValue toHere(
313
+ const float timeoutSeconds =
314
+ torch::distributed::rpc::kUnsetRpcTimeout) const;
315
+
316
+ void tryDel() override;
317
+
318
+ // Will be called when refcount reaches 0.
319
+ // Upon destruction, this ``UserRRef`` will tell the owner to deref.
320
+ void release_resources() override;
321
+
322
+ // Will be called when both refcount and weakcount reach 0. See
323
+ // https://github.com/pytorch/pytorch/blob/9116f02bebf3a5260feef5732d36c54ecb3b4033/c10/util/intrusive_ptr.h#L204
324
+ // This is called on destructing the wrapping intrusive_ptr_target instance
325
+ // and it's data members.
326
+ ~UserRRef() override;
327
+
328
+ private:
329
+ friend class RRefContext;
330
+
331
+ RRefForkData fork() const override;
332
+ inline void confirm() {
333
+ confirmedByOwner_ = true;
334
+ }
335
+
336
+ const ForkId forkId_;
337
+
338
+ // Indicates if this user has sent delete message to it's owner.
339
+ // Note, thread safety is needed because delete message could be sent by
340
+ // either the destructor called by Python garbage collection or RRefContext
341
+ // proactive cleanup on RPC graceful shutdown.
342
+ std::mutex deletedOnOwnerMutex_;
343
+ bool deletedOnOwner_{false};
344
+ // Indicating whether this UserRRef has been confirmed by its owner.
345
+ std::atomic<bool> confirmedByOwner_;
346
+ };
347
+
348
+ // Keep the template only on the derived class because ``RRefContext`` needs to
349
+ // erase the type on ``RRef`` and keep them in one map.
350
+ class TORCH_API OwnerRRef final : public RRef {
351
+ public:
352
+ OwnerRRef(const OwnerRRef& other) = delete;
353
+ OwnerRRef(OwnerRRef&& other) = delete;
354
+ OwnerRRef& operator=(const OwnerRRef& other) = delete;
355
+ OwnerRRef& operator=(OwnerRRef&& other) = delete;
356
+
357
+ OwnerRRef(
358
+ worker_id_t ownerId,
359
+ const RRefId& rrefId,
360
+ TypePtr type,
361
+ std::vector<c10::Device> devices);
362
+
363
+ OwnerRRef(
364
+ worker_id_t ownerId,
365
+ const RRefId& rrefId,
366
+ TypePtr type,
367
+ std::optional<IValue> value,
368
+ std::vector<c10::Device> devices);
369
+
370
+ inline bool isOwner() const override {
371
+ return true;
372
+ }
373
+
374
+ // OwnerRRef is always confirmed, while UserRRef is only confirmed when the
375
+ // owner knows about it.
376
+ inline bool confirmedByOwner() const override {
377
+ return true;
378
+ }
379
+
380
+ // Get a constant reference of the real value. This method will block if the
381
+ // value is not ready. This method does not need GIL as it does not create
382
+ // any new py::object. It will throw if there is an error.
383
+ const IValue& getValue() const;
384
+
385
+ // Set the value of this ``OwnerRRef``. This method does not need GIL as it
386
+ // does not create any new py::object.
387
+ void setValue(IValue&& value);
388
+ // Sets the value of this ``OwnerRRef`` to contain an exception.
389
+ void setError(std::exception_ptr eptr);
390
+
391
+ // Has a value or error been set?
392
+ bool hasValue() const;
393
+ // Gets a future that is satisfied when the value or error is set.
394
+ c10::intrusive_ptr<JitFuture> getFuture();
395
+
396
+ private:
397
+ friend class RRefContext;
398
+
399
+ c10::intrusive_ptr<JitFuture> future_;
400
+ };
401
+
402
+ TORCH_API std::ostream& operator<<(std::ostream& os, const RRef& rref);
403
+
404
+ // Helper function that casts from c10::RRefInterface to OwnerRRef
405
+ inline TORCH_API c10::intrusive_ptr<OwnerRRef> fromRRefInterface(
406
+ const c10::intrusive_ptr<c10::RRefInterface>& rrefInterface) {
407
+ return c10::static_intrusive_pointer_cast<OwnerRRef>(rrefInterface);
408
+ }
409
+
410
+ // Helper function that casts from OwnerRRef to c10::RRefInterface
411
+ inline TORCH_API c10::intrusive_ptr<c10::RRefInterface> fromOwnerRRef(
412
+ const c10::intrusive_ptr<RRef>& ownerRRef) {
413
+ return c10::static_intrusive_pointer_cast<c10::RRefInterface>(ownerRRef);
414
+ }
415
+
416
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/rref_proto.h ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
5
+ #include <torch/csrc/distributed/rpc/types.h>
6
+ #include <torch/csrc/jit/runtime/operator.h>
7
+ #include <torch/csrc/jit/serialization/pickler.h>
8
+ #include <vector>
9
+
10
+ namespace torch::distributed::rpc {
11
+
12
+ // Temporary solution of RRef operations.
13
+ // TODO: Remove all these messages and use rpc + registered functions instead.
14
+ class TORCH_API RRefMessageBase : public RpcCommandBase {
15
+ public:
16
+ RRefMessageBase(const RRefId& rrefId, MessageType type)
17
+ : rrefId_(rrefId), type_(type) {}
18
+
19
+ const RRefId& rrefId();
20
+
21
+ protected:
22
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
23
+ const RRefId rrefId_;
24
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
25
+ const MessageType type_;
26
+ };
27
+
28
+ class TORCH_API ForkMessageBase : public RRefMessageBase {
29
+ public:
30
+ ForkMessageBase(const RRefId& rrefId, const ForkId& forkId, MessageType type)
31
+ : RRefMessageBase(rrefId, type), forkId_(forkId) {}
32
+
33
+ const ForkId& forkId();
34
+
35
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
36
+ static std::pair<RRefId, ForkId> fromMessage(
37
+ const Message& message,
38
+ MessageType type);
39
+
40
+ protected:
41
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
42
+ const ForkId forkId_;
43
+ };
44
+
45
+ // UserRRef uses this message to fetch the remote RRef value from the owner.
46
+ class TORCH_API ScriptRRefFetchCall final : public RRefMessageBase {
47
+ public:
48
+ ScriptRRefFetchCall(worker_id_t fromWorkerId, const RRefId& rrefId)
49
+ : RRefMessageBase(rrefId, MessageType::SCRIPT_RREF_FETCH_CALL),
50
+ fromWorkerId_(fromWorkerId) {}
51
+
52
+ inline worker_id_t fromWorkerId() const {
53
+ return fromWorkerId_;
54
+ }
55
+
56
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
57
+ static std::unique_ptr<ScriptRRefFetchCall> fromMessage(
58
+ const Message& message);
59
+
60
+ private:
61
+ const worker_id_t fromWorkerId_;
62
+ };
63
+
64
+ class TORCH_API PythonRRefFetchCall final : public RRefMessageBase {
65
+ public:
66
+ PythonRRefFetchCall(worker_id_t fromWorkerId, const RRefId& rrefId)
67
+ : RRefMessageBase(rrefId, MessageType::PYTHON_RREF_FETCH_CALL),
68
+ fromWorkerId_(fromWorkerId) {}
69
+
70
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
71
+ static std::unique_ptr<PythonRRefFetchCall> fromMessage(
72
+ const Message& message);
73
+
74
+ private:
75
+ const worker_id_t fromWorkerId_;
76
+ };
77
+
78
+ // OwnerRRef uses this message to send the RRef value to a remote UserRRef
79
+ class TORCH_API RRefFetchRet : public RpcCommandBase {
80
+ public:
81
+ RRefFetchRet(std::vector<at::IValue> values, MessageType type)
82
+ : values_(std::move(values)), type_(type) {}
83
+
84
+ const std::vector<at::IValue>& values();
85
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
86
+
87
+ private:
88
+ std::vector<at::IValue> values_;
89
+ const MessageType type_;
90
+ };
91
+
92
+ class TORCH_API ScriptRRefFetchRet final : public RRefFetchRet {
93
+ public:
94
+ explicit ScriptRRefFetchRet(std::vector<at::IValue> values)
95
+ : RRefFetchRet(std::move(values), MessageType::SCRIPT_RREF_FETCH_RET) {}
96
+
97
+ static std::unique_ptr<ScriptRRefFetchRet> fromMessage(
98
+ const Message& message);
99
+ };
100
+
101
+ class TORCH_API PythonRRefFetchRet final : public RRefFetchRet {
102
+ public:
103
+ explicit PythonRRefFetchRet(std::vector<at::IValue> values)
104
+ : RRefFetchRet(std::move(values), MessageType::PYTHON_RREF_FETCH_RET) {}
105
+
106
+ static std::unique_ptr<PythonRRefFetchRet> fromMessage(
107
+ const Message& message);
108
+ };
109
+
110
+ // UserRRef (regardless it's the creator or not) uses this message to notify
111
+ // OwnerRRef on delete.
112
+ class TORCH_API RRefUserDelete final : public ForkMessageBase {
113
+ public:
114
+ RRefUserDelete(const RRefId& rrefId, const ForkId& forkId)
115
+ : ForkMessageBase(rrefId, forkId, MessageType::RREF_USER_DELETE) {}
116
+
117
+ static std::unique_ptr<RRefUserDelete> fromMessage(const Message& message);
118
+ };
119
+
120
+ class TORCH_API RemoteRet final : public ForkMessageBase {
121
+ public:
122
+ RemoteRet(const RRefId& rrefId, const ForkId& forkId)
123
+ : ForkMessageBase(rrefId, forkId, MessageType::REMOTE_RET) {}
124
+
125
+ static std::unique_ptr<RemoteRet> fromMessage(const Message& message);
126
+ };
127
+
128
+ // A child RRef uses this message to notify its parent that the child has been
129
+ // confirmed by the owner.
130
+ class TORCH_API RRefChildAccept final : public RpcCommandBase {
131
+ public:
132
+ explicit RRefChildAccept(const ForkId& forkId) : forkId_(forkId) {}
133
+
134
+ const ForkId& forkId() const;
135
+
136
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
137
+ static std::unique_ptr<RRefChildAccept> fromMessage(const Message& message);
138
+
139
+ private:
140
+ const ForkId forkId_;
141
+ };
142
+
143
+ // A child RRef uses this message to send a fork request to the owner.
144
+ class TORCH_API RRefForkRequest final : public ForkMessageBase {
145
+ public:
146
+ RRefForkRequest(const RRefId& rrefId, const ForkId& forkId)
147
+ : ForkMessageBase(rrefId, forkId, MessageType::RREF_FORK_REQUEST) {}
148
+
149
+ static std::unique_ptr<RRefForkRequest> fromMessage(const Message& message);
150
+ };
151
+
152
+ class TORCH_API RRefAck final : public RpcCommandBase {
153
+ public:
154
+ RRefAck() = default;
155
+
156
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
157
+ static std::unique_ptr<RRefAck> fromMessage(const Message& message);
158
+ };
159
+
160
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_call.h ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
5
+ #include <torch/csrc/jit/runtime/operator.h>
6
+ #include <torch/csrc/jit/serialization/pickler.h>
7
+ #include <optional>
8
+ #include <vector>
9
+
10
+ namespace torch {
11
+ namespace distributed {
12
+ namespace rpc {
13
+
14
+ using torch::jit::Operator;
15
+
16
+ // A ScriptCall instance represents an invocation of a builtin operator for a
17
+ // TorchScript function. If it is a builtin operator, it
18
+ // contains a shared ptr to the `Operator` and a list of arguments.
19
+ // If it is a TorchScript function, it contains a non empty qualifiedName string
20
+ // to the TorchScript function schema name and a list of arguments.
21
+ class TORCH_API ScriptCall : public RpcCommandBase {
22
+ public:
23
+ // Constructor for builitin operator call.
24
+ ScriptCall(std::shared_ptr<Operator> op, std::vector<at::IValue>&& stack);
25
+ // Constructor for TorchScript function call.
26
+ ScriptCall(
27
+ const c10::QualifiedName& qualifiedName,
28
+ std::vector<at::IValue>&& stack,
29
+ const bool isAsyncExecution = false);
30
+
31
+ bool hasOp() const;
32
+ std::shared_ptr<Operator> op() const;
33
+ bool hasQualifiedName() const;
34
+ const c10::QualifiedName& qualifiedName() const;
35
+ // return the argument stack of this builtin operator
36
+ const std::vector<at::IValue>& stack() const;
37
+ std::vector<at::IValue>& stackRef();
38
+ inline bool isAsyncExecution() const {
39
+ return isAsyncExecution_;
40
+ }
41
+
42
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
43
+ static std::unique_ptr<ScriptCall> fromMessage(const Message& message);
44
+
45
+ ~ScriptCall() override = default;
46
+
47
+ protected:
48
+ virtual void toIValues(std::vector<at::IValue>& ivalues) const;
49
+ static std::unique_ptr<ScriptCall> fromIValues(
50
+ std::vector<at::IValue>& ivalues);
51
+
52
+ private:
53
+ // Given an operator symbol and a string schema, return the matched operator.
54
+ static std::shared_ptr<Operator> matchOperator(const std::string& str_schema);
55
+
56
+ static const std::string BUILTIN_OP_NAMESPACE_;
57
+ static const std::string ATEN_PREFIX_;
58
+
59
+ // This field has value if this ScriptCall represents invocation of a builtin
60
+ // operator.
61
+ std::optional<std::shared_ptr<Operator>> op_;
62
+ // This field has non empty string if this ScriptCall represents invocation of
63
+ // an annotated torchscript function defined by users.
64
+ std::optional<const c10::QualifiedName> qualifiedName_;
65
+ std::vector<at::IValue> stack_;
66
+ const bool isAsyncExecution_;
67
+ };
68
+
69
+ } // namespace rpc
70
+ } // namespace distributed
71
+ } // namespace torch
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_remote_call.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/script_call.h>
4
+ #include <torch/csrc/distributed/rpc/types.h>
5
+ #include <torch/csrc/jit/runtime/operator.h>
6
+ #include <torch/csrc/jit/serialization/pickler.h>
7
+ #include <vector>
8
+
9
+ namespace torch {
10
+ namespace distributed {
11
+ namespace rpc {
12
+
13
+ using torch::jit::Operator;
14
+
15
+ // A ScriptRemoteCall instance represents an invocation of `dist.remote` on a
16
+ // builtin operator. Currently, it does not support using RRef as arguments yet.
17
+ // Besides the operator and a vector of arguments, ScriptRemoteCall also
18
+ // contains the RRefId and the ForkId of the return value RRef.
19
+ class TORCH_API ScriptRemoteCall final : public ScriptCall {
20
+ public:
21
+ // Constructor for builitin operator call.
22
+ ScriptRemoteCall(
23
+ std::shared_ptr<Operator> op,
24
+ std::vector<at::IValue>&& stack,
25
+ const RRefId& retRRefId,
26
+ const ForkId& retForkId);
27
+
28
+ // Constructor for TorchScript function call.
29
+ ScriptRemoteCall(
30
+ const c10::QualifiedName& qualifiedName,
31
+ std::vector<at::IValue>&& stack,
32
+ const RRefId& retRRefId,
33
+ const ForkId& retForkId,
34
+ const bool isAsyncExecution);
35
+
36
+ inline const RRefId& retRRefId() const {
37
+ return retRRefId_;
38
+ }
39
+
40
+ inline const ForkId& retForkId() const {
41
+ return retForkId_;
42
+ }
43
+
44
+ static std::unique_ptr<ScriptRemoteCall> fromIValues(
45
+ std::vector<at::IValue>& ivalues);
46
+
47
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
48
+ static std::unique_ptr<ScriptRemoteCall> fromMessage(const Message& message);
49
+
50
+ private:
51
+ const RRefId retRRefId_;
52
+ const ForkId retForkId_;
53
+ };
54
+
55
+ } // namespace rpc
56
+ } // namespace distributed
57
+ } // namespace torch
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/script_resp.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/message.h>
4
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
5
+ #include <torch/csrc/jit/serialization/pickler.h>
6
+
7
+ namespace torch {
8
+ namespace distributed {
9
+ namespace rpc {
10
+
11
+ // Return value of a builtin operator or a TorchScript function.
12
+ class TORCH_API ScriptResp final : public RpcCommandBase {
13
+ public:
14
+ explicit ScriptResp(at::IValue&& values);
15
+
16
+ const at::IValue& value();
17
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
18
+ static std::unique_ptr<ScriptResp> fromMessage(const Message& message);
19
+
20
+ private:
21
+ const at::IValue value_;
22
+ };
23
+
24
+ } // namespace rpc
25
+ } // namespace distributed
26
+ } // namespace torch
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_agent.h ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #ifdef USE_TENSORPIPE
4
+
5
+ #include <atomic>
6
+ #include <thread>
7
+
8
+ #include <c10/core/thread_pool.h>
9
+ #include <torch/csrc/distributed/c10d/PrefixStore.hpp>
10
+ #include <torch/csrc/distributed/c10d/Store.hpp>
11
+ #include <torch/csrc/distributed/rpc/rpc_agent.h>
12
+ #include <utility>
13
+
14
+ // Forward-declare the TensorPipe classes we need, to avoid including its
15
+ // headers in PyTorch's ones and thus have it become a public dependency.
16
+
17
+ namespace tensorpipe {
18
+
19
+ class Context;
20
+ class Error;
21
+ class Listener;
22
+ class Message;
23
+ class Pipe;
24
+
25
+ namespace transport {
26
+ class Context;
27
+ } // namespace transport
28
+
29
+ namespace channel {
30
+ class Context;
31
+ } // namespace channel
32
+
33
+ } // namespace tensorpipe
34
+
35
+ namespace torch::distributed::rpc {
36
+
37
+ // These priorities instruct TensorPipe on which transport/channel to pick
38
+ // during handshake. Higher priorities will take precedence over lower ones.
39
+ // The transport with lowest priority will be the one used to bootstrap pipes.
40
+
41
+ constexpr int64_t kShmTransportPriority = 200;
42
+ constexpr int64_t kIbvTransportPriority = 100;
43
+ // The UV transport just uses TCP and should work everywhere, thus keep it last.
44
+ constexpr int64_t kUvTransportPriority = 0;
45
+
46
+ constexpr int64_t kCmaChannelPriority = 1200;
47
+ constexpr int64_t kMultiplexedUvChannelPriority = 1100;
48
+ // The basic channel reuses a transport as a channel, and is thus our fallback.
49
+ constexpr int64_t kBasicChannelPriority = 1000;
50
+
51
+ // CPU channel have higher priority than CUDA channels, since the latter might
52
+ // handle CPU-to-CPU transfers, but will always be less efficient than their
53
+ // CPU-only counterparts.
54
+ constexpr int64_t kCudaIpcChannelPriority = 300;
55
+ constexpr int64_t kCudaGdrChannelPriority = 200;
56
+ constexpr int64_t kCudaXthChannelPriority = 400;
57
+ constexpr int64_t kCudaBasicChannelPriority = 0;
58
+
59
+ using steady_clock_time_point =
60
+ std::chrono::time_point<std::chrono::steady_clock>;
61
+
62
+ struct TORCH_API TransportRegistration {
63
+ std::shared_ptr<tensorpipe::transport::Context> transport;
64
+ int64_t priority;
65
+ std::string address;
66
+ };
67
+
68
+ C10_DECLARE_REGISTRY(TensorPipeTransportRegistry, TransportRegistration);
69
+
70
+ struct TORCH_API ChannelRegistration {
71
+ std::shared_ptr<tensorpipe::channel::Context> channel;
72
+ int64_t priority;
73
+ };
74
+
75
+ C10_DECLARE_REGISTRY(TensorPipeChannelRegistry, ChannelRegistration);
76
+
77
+ constexpr auto kDefaultNumWorkerThreads = 16;
78
+
79
+ struct TORCH_API TensorPipeRpcBackendOptions : public RpcBackendOptions {
80
+ TensorPipeRpcBackendOptions(
81
+ int numWorkerThreads,
82
+ std::optional<std::vector<std::string>> transports,
83
+ std::optional<std::vector<std::string>> channels,
84
+ float rpc_timeout,
85
+ std::string init_method,
86
+ std::unordered_map<std::string, DeviceMap> device_maps = {},
87
+ std::vector<c10::Device> devices = {})
88
+ : RpcBackendOptions(rpc_timeout, std::move(init_method)),
89
+ numWorkerThreads(numWorkerThreads),
90
+ transports(std::move(transports)),
91
+ channels(std::move(channels)),
92
+ deviceMaps(std::move(device_maps)),
93
+ devices(std::move(devices)) {
94
+ TORCH_CHECK(
95
+ numWorkerThreads > 0,
96
+ "num_worker_threads must be positive, got ",
97
+ numWorkerThreads);
98
+
99
+ if (this->transports.has_value()) {
100
+ for (const std::string& transportName : this->transports.value()) {
101
+ TORCH_CHECK(
102
+ TensorPipeTransportRegistry()->Has(transportName),
103
+ "Unknown transport: ",
104
+ transportName);
105
+ }
106
+ }
107
+
108
+ if (this->channels.has_value()) {
109
+ for (const std::string& channelName : this->channels.value()) {
110
+ TORCH_CHECK(
111
+ TensorPipeChannelRegistry()->Has(channelName),
112
+ "Unknown channel: ",
113
+ channelName);
114
+ }
115
+ }
116
+ }
117
+
118
+ void setDeviceMap(const std::string& workerName, const DeviceMap& deviceMap) {
119
+ auto iter = deviceMaps.find(workerName);
120
+ if (iter == deviceMaps.end()) {
121
+ deviceMaps[workerName] = deviceMap;
122
+ } else {
123
+ for (auto& entry : deviceMap) {
124
+ // c10::Device has no default constructor, hence map[device] dosn't work
125
+ // In C++-17 we can use insert_or_assign.
126
+ auto entryIter = iter->second.find(entry.first);
127
+ if (entryIter == iter->second.end()) {
128
+ iter->second.emplace(entry.first, entry.second);
129
+ } else {
130
+ entryIter->second = entry.second;
131
+ }
132
+ }
133
+ }
134
+ }
135
+
136
+ int numWorkerThreads;
137
+ const std::optional<std::vector<std::string>> transports;
138
+ const std::optional<std::vector<std::string>> channels;
139
+ std::unordered_map<std::string, DeviceMap> deviceMaps;
140
+ std::vector<c10::Device> devices;
141
+ };
142
+
143
+ // Struct to track the network source metrics
144
+ struct TORCH_API NetworkSourceInfo {
145
+ worker_id_t srcRank;
146
+ std::vector<uint8_t> srcMachineAddr;
147
+ };
148
+
149
+ // Struct to track aggregated network metrics
150
+ struct TORCH_API AggregatedNetworkData {
151
+ uint64_t numCalls{0};
152
+ uint64_t totalSentBytes{0};
153
+ uint64_t totalRecvBytes{0};
154
+ uint64_t totalErrors{0};
155
+ };
156
+
157
+ // TensorPipeAgent leverages TensorPipe (https://github.com/pytorch/tensorpipe)
158
+ // to transparently move tensors and payloads through the fastest available
159
+ // transport or channel. It acts like a hybrid RPC transport, providing shared
160
+ // memory (linux) and TCP (linux & mac) support. CUDA support is in progress.
161
+ class TORCH_API TensorPipeAgent : public RpcAgent {
162
+ public:
163
+ TensorPipeAgent(
164
+ const c10::intrusive_ptr<::c10d::Store>& store,
165
+ std::string selfName,
166
+ worker_id_t selfId,
167
+ std::optional<int> worldSize,
168
+ TensorPipeRpcBackendOptions opts,
169
+ std::unordered_map<std::string, DeviceMap> reverseDeviceMaps,
170
+ std::vector<c10::Device> devices,
171
+ std::unique_ptr<RequestCallback> cb);
172
+
173
+ TensorPipeAgent(const TensorPipeAgent&) = delete;
174
+ TensorPipeAgent& operator=(const TensorPipeAgent&) = delete;
175
+
176
+ c10::intrusive_ptr<JitFuture> send(
177
+ const WorkerInfo& to,
178
+ c10::intrusive_ptr<Message> message,
179
+ const float rpcTimeoutSeconds = kUnsetRpcTimeout,
180
+ const DeviceMap& deviceMap = {}) override;
181
+
182
+ // join() and sync() would be deprecated -
183
+ // https://github.com/pytorch/pytorch/issues/27647
184
+ void join(bool shutdown = false, float timeout = 0) override;
185
+ void sync() override{};
186
+ void startImpl() override;
187
+ void shutdownImpl() override;
188
+
189
+ ~TensorPipeAgent() override;
190
+
191
+ const WorkerInfo& getWorkerInfo(const std::string& workerName) const override;
192
+ const WorkerInfo& getWorkerInfo(worker_id_t workerId) const override;
193
+ std::vector<WorkerInfo> getWorkerInfos() const override;
194
+ void updateGroupMembership(
195
+ const WorkerInfo& workerInfo,
196
+ const std::vector<c10::Device>& devices,
197
+ const std::unordered_map<std::string, DeviceMap>& reverseDeviceMaps,
198
+ bool isJoin);
199
+
200
+ std::unordered_map<std::string, std::string> getMetrics() override;
201
+
202
+ void addGilWaitTime(const std::chrono::microseconds gilWaitTime) override;
203
+
204
+ TensorPipeRpcBackendOptions getBackendOptions() const;
205
+
206
+ const c10::intrusive_ptr<::c10d::Store> getStore() const;
207
+
208
+ DeviceMap getDeviceMap(const WorkerInfo& dest) const override;
209
+
210
+ const std::vector<c10::Device>& getDevices() const override;
211
+
212
+ using NetworkDataDict =
213
+ std::unordered_map<std::string, AggregatedNetworkData>;
214
+
215
+ // Returns metrics tracked by the NetworkDataDict
216
+ NetworkDataDict getNetworkData();
217
+ // Returns NetworkSourceInfo struct
218
+ NetworkSourceInfo getNetworkSourceInfo();
219
+
220
+ static const std::string& guessAddress();
221
+
222
+ // For testing purposes.
223
+ size_t timeoutMapSize();
224
+ size_t numPendingResponses();
225
+ size_t messageIdToTimeoutMapSize();
226
+
227
+ const bool isStaticGroup_;
228
+
229
+ protected:
230
+ // TensorPipe write function that could be used to write response
231
+ // messages by server, and write request messages by client. This
232
+ // is a protected method since it is overwritten by FaultyTensorPipeAgent
233
+ virtual void pipeWrite(
234
+ const std::shared_ptr<tensorpipe::Pipe>&,
235
+ c10::intrusive_ptr<Message> message,
236
+ std::vector<c10::Device>&& devices,
237
+ std::vector<c10::Stream> streams,
238
+ std::function<void(const tensorpipe::Error&)>) noexcept;
239
+
240
+ private:
241
+ // Removes the given messageId with the given expirationTime from the
242
+ // timeoutMap_.
243
+ void removeFromTimeoutMap(uint64_t messageId);
244
+
245
+ // Populates workerIdToInfo_ and workerNameToInfo_ using addressStore_
246
+ void prepareNames(bool isStaticGroup);
247
+
248
+ // Check the static group attribute with the value set in store
249
+ void checkAndSetStaticGroup(const c10::intrusive_ptr<::c10d::Store>& store);
250
+
251
+ const std::string& findWorkerURL(const WorkerInfo& worker) const;
252
+
253
+ // Only use for Dynamic RPC groups, method to have worker leave group
254
+ void leaveGroup();
255
+
256
+ // TensorPipe read function that could be used to read response messages
257
+ // by client, and read request messages by server.
258
+ void pipeRead(
259
+ const std::shared_ptr<tensorpipe::Pipe>&,
260
+ std::function<void(
261
+ const tensorpipe::Error&,
262
+ c10::intrusive_ptr<Message>,
263
+ std::vector<c10::Stream>)>) noexcept;
264
+
265
+ // Callback of listener accept()
266
+ void onListenerAccepted(
267
+ const tensorpipe::Error& error,
268
+ std::shared_ptr<tensorpipe::Pipe>& pipe);
269
+
270
+ // Respond to a call from a peer
271
+ void respond(std::shared_ptr<tensorpipe::Pipe>& pipe);
272
+
273
+ void sendCompletedResponseMessage(
274
+ std::shared_ptr<tensorpipe::Pipe>& pipe,
275
+ JitFuture& futureResponseMessage,
276
+ uint64_t messageId,
277
+ std::vector<c10::Stream> stream);
278
+
279
+ // Collects metrics from successful RPC calls
280
+ void trackNetworkData(
281
+ uint64_t requestSize,
282
+ uint64_t responseSize,
283
+ const std::string& destWorkerName);
284
+
285
+ // Collects metrics from failed RPC calls
286
+ void trackNetworkError(
287
+ uint64_t requestSize,
288
+ const std::string& destWorkerName);
289
+
290
+ inline std::vector<c10::Device> getDevicesForRemote(
291
+ const std::string& remoteName,
292
+ const Message& message) const;
293
+
294
+ // When a request+response completes, we need to mark the future message as
295
+ // complete. However, if its timeout has already expired, it already has an
296
+ // error set. There is no atomic "test-and-set" way to mark a future complete
297
+ // only if it isn't yet. It does exist for errors (setErrorIfNeeded) but, even
298
+ // then, it ends up printing a log message, which may worry the user. To solve
299
+ // both issues we use a separate atomic flag to know the status of the future.
300
+ struct AtomicJitFuture {
301
+ explicit AtomicJitFuture(const std::vector<c10::Device>& devices) {
302
+ jitFuture = c10::make_intrusive<at::ivalue::Future>(
303
+ at::AnyClassType::get(), devices);
304
+ }
305
+
306
+ std::atomic_flag isComplete = ATOMIC_FLAG_INIT;
307
+ c10::intrusive_ptr<JitFuture> jitFuture;
308
+ };
309
+
310
+ // Maintains state per client pipe to track pending response messages and
311
+ // error states. pendingResponseMessage_ should be protected by a mutex since
312
+ // it can be raced with user send() call.
313
+ // TODO: To achieve better performance we can have a pipe pool per
314
+ // client that can be configured using RpcBackendOptions.
315
+ struct ClientPipe {
316
+ explicit ClientPipe(std::shared_ptr<tensorpipe::Pipe> pipe)
317
+ : pipe_(std::move(pipe)) {}
318
+ std::shared_ptr<tensorpipe::Pipe> pipe_;
319
+ mutable std::mutex mutex_;
320
+ bool inError_{false};
321
+ // Map from Message Request ID's to corresponding futures.
322
+ std::unordered_map<uint64_t, std::shared_ptr<AtomicJitFuture>>
323
+ pendingResponseMessage_;
324
+ };
325
+
326
+ const c10::intrusive_ptr<::c10d::Store> store_;
327
+
328
+ const TensorPipeRpcBackendOptions opts_;
329
+ // For dynamic RPC, the reverse device maps are updated whenever a new rank
330
+ // joins or leaves the group
331
+ std::unordered_map<std::string, DeviceMap> reverseDeviceMaps_;
332
+ // Local devices used by this agent. If application didn't specify this
333
+ // field, it will be initialized using corresponding local devices in
334
+ // opts_.deviceMaps and reverseDeviceMaps_;
335
+ std::vector<c10::Device> devices_;
336
+
337
+ ThreadPool threadPool_;
338
+ std::shared_ptr<tensorpipe::Context> context_;
339
+ std::shared_ptr<tensorpipe::Listener> listener_;
340
+
341
+ mutable std::mutex connectedPipesMutex_;
342
+ std::unordered_map<worker_id_t, ClientPipe> connectedPipes_;
343
+
344
+ // Maps keyed on name and id for easy WorkerInfo lookup.
345
+ std::unordered_map<worker_id_t, WorkerInfo> workerIdToInfo_;
346
+ std::unordered_map<std::string, WorkerInfo> workerNameToInfo_;
347
+ std::unordered_map<std::string, std::string> workerNameToURL_;
348
+
349
+ ::c10d::PrefixStore rankToNameStore_;
350
+ ::c10d::PrefixStore nameToAddressStore_;
351
+ // Store keys that will used to count joined processes and active calls during
352
+ // the shutdown process
353
+ ::c10d::PrefixStore shutdownStore_;
354
+ int worldSize_ = 0;
355
+ std::atomic<uint64_t> nextMessageID_{0};
356
+
357
+ // Metadata used for tracking of whether certain RPCs have timed out or not.
358
+ struct TimeoutMessageMetadata {
359
+ TimeoutMessageMetadata(
360
+ uint64_t messageId_,
361
+ std::shared_ptr<AtomicJitFuture> responseFuture_,
362
+ std::chrono::milliseconds timeout_)
363
+ : messageId(messageId_),
364
+ responseFuture(std::move(responseFuture_)),
365
+ timeout(timeout_) {}
366
+ uint64_t messageId;
367
+ std::shared_ptr<AtomicJitFuture> responseFuture;
368
+ std::chrono::milliseconds timeout;
369
+ };
370
+
371
+ // Map to store the expiration times for each message.
372
+ std::map<steady_clock_time_point, std::vector<TimeoutMessageMetadata>>
373
+ timeoutMap_;
374
+
375
+ // Map to store the messageId to expiry time.
376
+ std::unordered_map<uint64_t, steady_clock_time_point> messageIdToTimeout_;
377
+
378
+ // Thread that will poll the timeoutMap_ for timed out messages and mark them
379
+ // with an error accordingly
380
+ std::thread timeoutThread_;
381
+
382
+ // Function run by the timeoutThread_ to check for timed out RPCs
383
+ void pollTimeoutRpcs();
384
+
385
+ // Mutex to guard the timeoutMap_
386
+ std::mutex timeoutMapMutex_;
387
+
388
+ // Condition Variable to signal population of the timeoutMap_
389
+ std::condition_variable timeoutThreadCV_;
390
+
391
+ // Returns the expiration time for an RPC by adding the current time to the
392
+ // passed in timeout.
393
+ inline steady_clock_time_point computeRpcMessageExpiryTime(
394
+ std::chrono::milliseconds timeout) const {
395
+ return std::chrono::time_point_cast<std::chrono::milliseconds>(
396
+ std::chrono::steady_clock::now() + timeout);
397
+ }
398
+
399
+ // Handle error on an outgoing pipe
400
+ void handleClientError(
401
+ ClientPipe& clientPipe,
402
+ const tensorpipe::Error& error);
403
+
404
+ // This is a generic struct for capturing Time-Series Metrics. It keeps a
405
+ // running sum and count of data points (observations), and can return an
406
+ // average of the data points seen so far. This is currently only used for
407
+ // tracking the GIL Wait Time in RPC Agents, but can be used for other metrics
408
+ // as well.
409
+ struct TimeSeriesMetricsTracker {
410
+ // Running sum of the data points seen so far
411
+ uint64_t currentSum_;
412
+ // Running count of the data points seen so far
413
+ uint64_t currentCount_;
414
+
415
+ explicit TimeSeriesMetricsTracker(
416
+ uint64_t currentSum = 0,
417
+ uint64_t currentCount = 0);
418
+
419
+ // Adds a data point (which is basically one observation for the metric
420
+ // being tracked) to the running sum and count.
421
+ void addData(uint64_t dataPoint);
422
+ // Returns the average of all the data points seen so far.
423
+ float computeAverage() const;
424
+ };
425
+
426
+ // Map of Time-Series metrics tracked by the RPC Agent
427
+ std::unordered_map<std::string, TimeSeriesMetricsTracker> timeSeriesMetrics_;
428
+ // Mutex to guard timeSeriesMetrics_
429
+ std::mutex metricsMutex_;
430
+
431
+ // Custom lock guard used to check if the RPC group is dynamic and lock the
432
+ // mutex if so
433
+ struct GroupMembershipLockGuard {
434
+ GroupMembershipLockGuard(std::mutex& mutex, bool isStaticGroup)
435
+ : ref_(mutex), isStaticGroup_(isStaticGroup) {
436
+ if (isStaticGroup_) {
437
+ ref_.lock();
438
+ }
439
+ }
440
+
441
+ ~GroupMembershipLockGuard() {
442
+ if (isStaticGroup_) {
443
+ ref_.unlock();
444
+ }
445
+ }
446
+
447
+ GroupMembershipLockGuard(const GroupMembershipLockGuard&) = delete;
448
+
449
+ private:
450
+ std::mutex& ref_;
451
+ bool isStaticGroup_;
452
+ };
453
+ // Mutex to guard access to group membership data
454
+ // e.g. updates to (workerIdToInfo_, workerNameToInfo_, workerNameToURL_)
455
+ mutable std::mutex groupMembershipMutex_;
456
+
457
+ // Map to Track Network Data
458
+ NetworkDataDict networkData_;
459
+ // Mutex to guard networkData_
460
+ std::mutex networkDataMutex_;
461
+
462
+ // A mutex and a cv to guard access to the call counts and watch for changes.
463
+ std::mutex callCountMutex_;
464
+ std::condition_variable callCountCV_;
465
+ // Running total of un-processed, un-errored RPC calls sent
466
+ int32_t clientActiveCalls_{0};
467
+ // Running total of un-processed RPC requests received
468
+ int32_t serverActiveCalls_{0};
469
+ // Running total of RPC requests that will be completed asynchronously
470
+ int32_t serverActiveAsyncCalls_{0};
471
+
472
+ // Whether a global graceful shutdown has begun, in which case we'll silence
473
+ // error messages due to remote workers closing their pipes.
474
+ std::atomic<bool> shuttingDown_{false};
475
+
476
+ // Helpers to modify the counts while correctly dealing with the mutex and cv.
477
+ void increaseCallCount(int32_t& count);
478
+ void decreaseCallCount(int32_t& count);
479
+
480
+ // Helpers to set the state of the requests.
481
+ void markFutureAsComplete(
482
+ std::shared_ptr<AtomicJitFuture> atomicFuture,
483
+ c10::intrusive_ptr<Message> message,
484
+ std::vector<c10::Stream> streams);
485
+ void markFutureWithError(
486
+ std::shared_ptr<AtomicJitFuture> atomicFuture,
487
+ std::string errorMsg);
488
+ };
489
+
490
+ } // namespace torch::distributed::rpc
491
+
492
+ #endif // USE_TENSORPIPE
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/tensorpipe_utils.h ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #ifdef USE_TENSORPIPE
4
+
5
+ #include <torch/csrc/distributed/rpc/utils.h>
6
+
7
+ namespace tensorpipe {
8
+ class Message;
9
+ class Allocation;
10
+ class Descriptor;
11
+ } // namespace tensorpipe
12
+
13
+ namespace torch::distributed::rpc {
14
+
15
+ TORCH_API const c10::Stream& getStreamForDevice(
16
+ const std::vector<c10::Stream>& streams,
17
+ const c10::Device& device);
18
+
19
+ // Inspired by c10/core/impl/DeviceGuardImplInterface.h.
20
+
21
+ class TensorpipeDeviceTypeConverter {
22
+ public:
23
+ // Ideally we'd want this to also return a tensorpipe::Message::Tensor object
24
+ // but we cannot forward-declare that class (because it's nested), and we
25
+ // cannot include the TensorPipe headers because it's a private dependency.
26
+ // Thus we bend over backwards and entrust this method with appending that
27
+ // object to the `tensors` field of the tensorpipe::Message object we pass.
28
+ virtual std::optional<std::vector<char>> prepareTensorForSending(
29
+ const c10::Storage& storage,
30
+ const std::vector<c10::Stream>& streams,
31
+ tensorpipe::Message& message) const = 0;
32
+
33
+ // Same as above: this method cannot return a tensorpipe::Allocation::Tensor,
34
+ // thus it appends it to the `tensors` field of the tensorpipe::Allocation.
35
+ virtual at::DataPtr allocateTensorForReceiving(
36
+ c10::DeviceIndex deviceIndex,
37
+ size_t length,
38
+ const std::vector<c10::Stream>& streams,
39
+ tensorpipe::Allocation& allocation) const = 0;
40
+
41
+ virtual ~TensorpipeDeviceTypeConverter() = default;
42
+ };
43
+
44
+ extern TORCH_API std::array<
45
+ std::atomic<const TensorpipeDeviceTypeConverter*>,
46
+ static_cast<size_t>(DeviceType::COMPILE_TIME_MAX_DEVICE_TYPES)>
47
+ device_type_converter_registry;
48
+
49
+ class TORCH_API TensorpipeDeviceTypeConverterRegistrar {
50
+ public:
51
+ TensorpipeDeviceTypeConverterRegistrar(
52
+ DeviceType,
53
+ const TensorpipeDeviceTypeConverter*);
54
+ };
55
+
56
+ #define C10_REGISTER_TENSORPIPE_DEVICE_TYPE_CONVERTER( \
57
+ DevType, TensorpipeDeviceTypeConverter) \
58
+ static ::torch::distributed::rpc::TensorpipeDeviceTypeConverterRegistrar \
59
+ C10_ANONYMOUS_VARIABLE(g_##DeviceType)( \
60
+ ::c10::DeviceType::DevType, new TensorpipeDeviceTypeConverter());
61
+
62
+ inline const TensorpipeDeviceTypeConverter* getDeviceTypeConverter(
63
+ DeviceType type) {
64
+ return device_type_converter_registry[static_cast<size_t>(type)].load();
65
+ }
66
+
67
+ // A struct that holds pointers that keep alive all the memory that will be
68
+ // accessed by TensorPipe during a write operation.
69
+ struct TensorpipeWriteBuffers {
70
+ // Allocate on heap so pointers stay valid as we move the holder.
71
+ std::unique_ptr<MessageType> type;
72
+ std::unique_ptr<int64_t> id;
73
+ std::vector<char> payload;
74
+ std::vector<char> pickle;
75
+ // This contains the original tensors and the clones of the sparse tensors.
76
+ std::vector<torch::Tensor> tensors;
77
+ // This contains the copies of the data of the tensors that didn't own their
78
+ // memory, e.g., the ones created from torch::from_blob() with no deleter.
79
+ std::vector<std::vector<char>> copiedTensors;
80
+ };
81
+
82
+ // A struct that holds pointers that keep alive all the memory that will be
83
+ // accessed by TensorPipe during a read operation.
84
+ struct TensorpipeReadBuffers {
85
+ // Allocate on heap so pointers stay valid as we move the holder.
86
+ std::unique_ptr<MessageType> type;
87
+ std::unique_ptr<int64_t> id;
88
+ std::vector<char> payload;
89
+ std::vector<char> pickle;
90
+ std::vector<c10::DataPtr> tensors;
91
+ };
92
+
93
+ // Convert an RPC message into a TensorPipe message, plus a holder to all the
94
+ // data that must be kept alive while the write is performed asynchronously.
95
+ TORCH_API std::tuple<tensorpipe::Message, TensorpipeWriteBuffers>
96
+ tensorpipeSerialize(
97
+ const c10::intrusive_ptr<Message>& rpcMessage,
98
+ std::vector<c10::Device> devices,
99
+ const std::vector<c10::Stream>& streams);
100
+
101
+ // Allocate the buffers that will hold the incoming data. They will be managed
102
+ // by the returned holder, which must be kept alive until the asynchronous read
103
+ // has finished. Pointers to these buffers will be stored in the returned
104
+ // tensorpipe::Allocation struct.
105
+ TORCH_API std::pair<tensorpipe::Allocation, TensorpipeReadBuffers>
106
+ tensorpipeAllocate(
107
+ const tensorpipe::Descriptor& tpDescriptor,
108
+ const std::vector<c10::Stream>& streams);
109
+
110
+ // Convert a TensorPipe message back into an RPC message. This requires the data
111
+ // to be available and can thus only be performed once the asynchronous read has
112
+ // completed. The holder can be destroyed once this function returns.
113
+ TORCH_API c10::intrusive_ptr<Message> tensorpipeDeserialize(
114
+ tensorpipe::Descriptor&& tpDescriptor,
115
+ TensorpipeReadBuffers&& holder);
116
+
117
+ } // namespace torch::distributed::rpc
118
+
119
+ #endif // USE_TENSORPIPE
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/torchscript_functions.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/ivalue.h>
4
+ #include <torch/csrc/autograd/profiler.h>
5
+ #include <torch/csrc/distributed/autograd/utils.h>
6
+ #include <torch/csrc/distributed/rpc/rref_context.h>
7
+ #include <torch/csrc/distributed/rpc/script_remote_call.h>
8
+
9
+ namespace torch::distributed::rpc {
10
+
11
+ // This function sends an rpc call to run torchscript function, currently the
12
+ // torchscript function could only be a user defined python function with
13
+ // "@torch.jit.script" annotation. The torchscript function could not be
14
+ // a class constructor, class method, instance method or a script module.
15
+ // dst: destination worker name
16
+ // qualifiedName: torchscript function qualified name string like
17
+ // "moduleName::torchscriptFunctionName", e.g,
18
+ // "dist_autograd_test::my_py_add"
19
+ // stack: a bag of IValue args passed to torchscriptFunctionName
20
+ // It returns c10::intrusive_ptr<ivalue::Future>
21
+ c10::intrusive_ptr<c10::ivalue::Future> TORCH_API rpcTorchscript(
22
+ const std::string& dstWorkerName,
23
+ const c10::QualifiedName& qualifiedName,
24
+ const c10::FunctionSchema& functionSchema,
25
+ std::vector<c10::IValue>& stack,
26
+ const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout,
27
+ const bool isAsyncExecution = false);
28
+
29
+ c10::intrusive_ptr<RRef> TORCH_API remoteTorchscript(
30
+ const std::string& dstWorkerName,
31
+ const c10::QualifiedName& qualifiedName,
32
+ const c10::FunctionSchema& functionSchema,
33
+ std::vector<c10::IValue>& stack,
34
+ const float rpcTimeoutSeconds = torch::distributed::rpc::kUnsetRpcTimeout,
35
+ const bool isAsyncExecution = false);
36
+
37
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_call.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
4
+ #include <torch/csrc/distributed/rpc/types.h>
5
+ #include <torch/csrc/utils/pybind.h>
6
+
7
+ namespace torch::distributed::rpc {
8
+
9
+ // This class converts the content in a PythonCall into py::object. This is a
10
+ // helper class to make sure that all arguments deserialization is done before
11
+ // entering RequestCallbackImpl::processRpc(...), so that the deserialization
12
+ // related logic can be carried out in one spot instead of scattered in multiple
13
+ // places for different message types.
14
+ // NB: The reason for not consolidating class into PythonCall is because
15
+ // PythonCall is a libtorch type which should not depend on Python types.
16
+ class TORCH_API UnpickledPythonCall : public RpcCommandBase {
17
+ public:
18
+ UnpickledPythonCall(
19
+ const SerializedPyObj& serializedPyObj,
20
+ bool isAsyncExecution);
21
+ ~UnpickledPythonCall() override;
22
+
23
+ // toMessage() method is not implemented, as objects of this class should
24
+ // never be directly converted into a Message object.
25
+ c10::intrusive_ptr<Message> toMessageImpl() && override;
26
+ const py::object& pythonUdf() const;
27
+
28
+ inline bool isAsyncExecution() const {
29
+ return isAsyncExecution_;
30
+ }
31
+
32
+ private:
33
+ py::object pythonUdf_;
34
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
35
+ const bool isAsyncExecution_;
36
+ };
37
+
38
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/unpickled_python_remote_call.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
4
+ #include <torch/csrc/distributed/rpc/types.h>
5
+ #include <torch/csrc/distributed/rpc/unpickled_python_call.h>
6
+ #include <torch/csrc/utils/pybind.h>
7
+
8
+ namespace torch::distributed::rpc {
9
+
10
+ // This class converts the content in a PythonRemoteCall into py::object. This
11
+ // is a helper class to make sure that all arguments deserialization is done
12
+ // before entering RequestCallbackImpl::processRpc(...), so that the
13
+ // deserialization related logic can be carried out in one spot instead of
14
+ // scattered in multiple places for different message types.
15
+ // NB: The reason for not consolidating class into PythonRemoteCall is because
16
+ // PythonRemoteCall is a libtorch type which should not depend on Python types.
17
+ class TORCH_API UnpickledPythonRemoteCall final : public UnpickledPythonCall {
18
+ public:
19
+ explicit UnpickledPythonRemoteCall(
20
+ const SerializedPyObj& serializedPyObj,
21
+ const at::IValue& retRRefId,
22
+ const at::IValue& retForkId,
23
+ const bool isAsyncExecution);
24
+
25
+ const RRefId& rrefId() const;
26
+ const ForkId& forkId() const;
27
+
28
+ private:
29
+ RRefId rrefId_;
30
+ ForkId forkId_;
31
+ };
32
+
33
+ } // namespace torch::distributed::rpc
janus/lib/python3.10/site-packages/torch/include/torch/csrc/distributed/rpc/utils.h ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/Device.h>
4
+ #include <c10/core/Event.h>
5
+ #include <c10/core/Stream.h>
6
+ #include <torch/csrc/autograd/profiler.h>
7
+ #include <torch/csrc/distributed/rpc/rpc_command_base.h>
8
+ #include <torch/csrc/jit/serialization/pickle.h>
9
+ #include <torch/csrc/utils/byte_order.h>
10
+
11
+ namespace torch {
12
+ namespace distributed {
13
+ namespace rpc {
14
+
15
+ // Parse error message and return RPCErrorType based on the message.
16
+ TORCH_API RPCErrorType getRPCErrorType(const JitFuture& jitFuture);
17
+ // Create an error string given the error description and error type
18
+ TORCH_API std::string makeRPCError(
19
+ const std::string& rpcErrorStr,
20
+ RPCErrorType errorType);
21
+
22
+ // Given an RPC message received as a request over the wire, deserialize it into
23
+ // the appropriate 'RpcCommandBase' type.
24
+ TORCH_API std::unique_ptr<RpcCommandBase> deserializeRequest(
25
+ const Message& request);
26
+
27
+ // Given an RPC message received as a response over the wire, deserialize it
28
+ // into the appropriate 'RpcCommandBase' type, if the response is
29
+ // FORWARD_AUTOGRAD_RESP type, unwrap it, attach recvBackward() functions
30
+ // to received tensors and set the wrappedMsgType to its wrapped message type.
31
+ TORCH_API std::unique_ptr<RpcCommandBase> deserializeResponse(
32
+ const Message& response,
33
+ MessageType& wrappedMsgType);
34
+
35
+ // Given an RPC message received as a response over the wire, deserialize it
36
+ // into the valid IValue if the message is for a script rpc result,
37
+ // otherwise deserialize it into dummy none ivalue that will never be used.
38
+ // In this deserialization, we also attach recv rpc backward functions if
39
+ // needed.
40
+ IValue deserializeResptoIValueInternal(
41
+ RpcCommandBase& rpc,
42
+ MessageType messageType);
43
+ TORCH_API IValue deserializeRespToIValue(const Message& message);
44
+
45
+ // Note: format is subject to change and intended for RPCs.
46
+ // For saving persistently to disk, use torch::save().
47
+ TORCH_API std::string wireSerialize(
48
+ const std::vector<char>& payload,
49
+ const std::vector<at::Tensor>& tensors);
50
+
51
+ TORCH_API std::pair<std::vector<char>, std::vector<at::Tensor>> wireDeserialize(
52
+ const void* data,
53
+ size_t data_size);
54
+
55
+ // We use vector<char> as the type of blobs because it's what rpc::Message uses
56
+ // for its payload, even though it has the disadvantage that it cannot be
57
+ // allocated with uninitialized memory: it is always zeroed out.
58
+
59
+ // Some Tensors are effectively views of larger Tensors, where only a small
60
+ // subset of the Storage data is referenced. This normally is good and avoids
61
+ // copies when kept locally, but if we naively push the whole Storage over the
62
+ // wire, we'll end up with excess network traffic. This change clones tensors if
63
+ // we'd save at least half the data, and over a minimum hurdle.
64
+ TORCH_API c10::List<at::Tensor> cloneSparseTensors(
65
+ const std::vector<at::Tensor>& tensors);
66
+
67
+ // Combines an original payload and wrapped payload into the original payload.
68
+ // Used to generate the overall payload for the wrapped RPC.
69
+ TORCH_API void writeWrappedPayload(
70
+ std::vector<char>& originalPayload,
71
+ std::vector<char>& additionalPayload);
72
+
73
+ // Reads the additional, wrapped payload from a wrapped RPC off of the input
74
+ // payload. After this, payload will contain the payload of the original,
75
+ // un-wrapped RPC.
76
+ TORCH_API std::vector<at::IValue> readWrappedPayload(
77
+ std::vector<char>& payload,
78
+ const rpc::Message& message);
79
+
80
+ // Takes a list of events from autograd profiler and populates them into
81
+ // profiledEvents to be carried over RPC.
82
+ TORCH_API void populateRemoteProfiledEvents(
83
+ std::vector<torch::autograd::profiler::LegacyEvent>& profiledEvents,
84
+ const torch::autograd::profiler::ProfilerConfig& profilerConfig,
85
+ const std::vector<std::vector<torch::autograd::profiler::LegacyEvent>>&
86
+ eventLists);
87
+
88
+ } // namespace rpc
89
+ } // namespace distributed
90
+ } // namespace torch
janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cpp_stacktraces.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/Export.h>
4
+ #include <torch/csrc/profiler/unwind/unwind.h>
5
+
6
+ namespace torch {
7
+ TORCH_API bool get_cpp_stacktraces_enabled();
8
+ TORCH_API torch::unwind::Mode get_symbolize_mode();
9
+ } // namespace torch
janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/cuda_enabled.h ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ namespace torch::utils {
4
+
5
+ inline constexpr bool cuda_enabled() {
6
+ #ifdef USE_CUDA
7
+ return true;
8
+ #else
9
+ return false;
10
+ #endif
11
+ }
12
+
13
+ } // namespace torch::utils
janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/device_lazy_init.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/TensorOptions.h>
4
+
5
+ // device_lazy_init() is always compiled, even for CPU-only builds.
6
+
7
+ namespace torch::utils {
8
+
9
+ /**
10
+ * This mechanism of lazy initialization is designed for each device backend.
11
+ * Currently, CUDA and XPU follow this design. This function `device_lazy_init`
12
+ * MUST be called before you attempt to access any Type(CUDA or XPU) object
13
+ * from ATen, in any way. It guarantees that the device runtime status is lazily
14
+ * initialized when the first runtime API is requested.
15
+ *
16
+ * Here are some common ways that a device object may be retrieved:
17
+ * - You call getNonVariableType or getNonVariableTypeOpt
18
+ * - You call toBackend() on a Type
19
+ *
20
+ * It's important to do this correctly, because if you forget to add it you'll
21
+ * get an oblique error message seems like "Cannot initialize CUDA without
22
+ * ATen_cuda library" or "Cannot initialize XPU without ATen_xpu library" if you
23
+ * try to use CUDA or XPU functionality from a CPU-only build, which is not good
24
+ * UX.
25
+ */
26
+ void device_lazy_init(at::DeviceType device_type);
27
+ void set_requires_device_init(at::DeviceType device_type, bool value);
28
+
29
+ inline void maybe_initialize_device(at::Device& device) {
30
+ // Add more devices here to enable lazy initialization.
31
+ if (device.is_cuda() || device.is_xpu() || device.is_privateuseone()) {
32
+ device_lazy_init(device.type());
33
+ }
34
+ }
35
+
36
+ inline void maybe_initialize_device(std::optional<at::Device>& device) {
37
+ if (!device.has_value()) {
38
+ return;
39
+ }
40
+ maybe_initialize_device(device.value());
41
+ }
42
+
43
+ inline void maybe_initialize_device(const at::TensorOptions& options) {
44
+ auto device = options.device();
45
+ maybe_initialize_device(device);
46
+ }
47
+
48
+ bool is_device_initialized(at::DeviceType device_type);
49
+
50
+ } // namespace torch::utils
janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/init.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/utils/pybind.h>
4
+
5
+ namespace torch::throughput_benchmark {
6
+
7
+ void initThroughputBenchmarkBindings(PyObject* module);
8
+
9
+ } // namespace torch::throughput_benchmark
janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/invalid_arguments.h ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/python_headers.h>
4
+ #include <string>
5
+ #include <vector>
6
+
7
+ namespace torch {
8
+
9
+ std::string format_invalid_args(
10
+ PyObject* given_args,
11
+ PyObject* given_kwargs,
12
+ const std::string& function_name,
13
+ const std::vector<std::string>& options);
14
+
15
+ } // namespace torch
janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/numpy_stub.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/python_headers.h>
4
+
5
+ #ifdef USE_NUMPY
6
+
7
+ #if !defined(NO_IMPORT_ARRAY) && !defined(WITH_NUMPY_IMPORT_ARRAY)
8
+ #define NO_IMPORT_ARRAY
9
+ #endif
10
+
11
+ #ifndef PY_ARRAY_UNIQUE_SYMBOL
12
+ #define PY_ARRAY_UNIQUE_SYMBOL __numpy_array_api
13
+ #endif
14
+
15
+ #ifndef NPY_NO_DEPRECATED_API
16
+ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
17
+ #endif
18
+
19
+ #include <numpy/arrayobject.h>
20
+
21
+ #endif // USE_NUMPY
janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/object_ptr.h ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/Export.h>
4
+ #include <torch/csrc/python_headers.h>
5
+ #include <utility>
6
+
7
+ template <class T>
8
+ class TORCH_PYTHON_API THPPointer {
9
+ public:
10
+ THPPointer() : ptr(nullptr){};
11
+ explicit THPPointer(T* ptr) noexcept : ptr(ptr){};
12
+ THPPointer(THPPointer&& p) noexcept : ptr(std::exchange(p.ptr, nullptr)) {}
13
+
14
+ ~THPPointer() {
15
+ free();
16
+ };
17
+ T* get() {
18
+ return ptr;
19
+ }
20
+ const T* get() const {
21
+ return ptr;
22
+ }
23
+ T* release() {
24
+ T* tmp = ptr;
25
+ ptr = nullptr;
26
+ return tmp;
27
+ }
28
+ operator T*() {
29
+ return ptr;
30
+ }
31
+ THPPointer& operator=(T* new_ptr) noexcept {
32
+ free();
33
+ ptr = new_ptr;
34
+ return *this;
35
+ }
36
+ THPPointer& operator=(THPPointer&& p) noexcept {
37
+ free();
38
+ ptr = p.ptr;
39
+ p.ptr = nullptr;
40
+ return *this;
41
+ }
42
+ T* operator->() {
43
+ return ptr;
44
+ }
45
+ explicit operator bool() const {
46
+ return ptr != nullptr;
47
+ }
48
+
49
+ private:
50
+ void free();
51
+ T* ptr = nullptr;
52
+ };
53
+
54
+ /**
55
+ * An RAII-style, owning pointer to a PyObject. You must protect
56
+ * destruction of this object with the GIL.
57
+ *
58
+ * WARNING: Think twice before putting this as a field in a C++
59
+ * struct. This class does NOT take out the GIL on destruction,
60
+ * so if you will need to ensure that the destructor of your struct
61
+ * is either (a) always invoked when the GIL is taken or (b) takes
62
+ * out the GIL itself. Easiest way to avoid this problem is to
63
+ * not use THPPointer in this situation.
64
+ */
65
+ using THPObjectPtr = THPPointer<PyObject>;
66
+ using THPCodeObjectPtr = THPPointer<PyCodeObject>;
67
+ using THPFrameObjectPtr = THPPointer<PyFrameObject>;
janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/out_types.h ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+
5
+ namespace torch::utils {
6
+
7
+ TORCH_API void check_out_type_matches(
8
+ const at::Tensor& result,
9
+ std::optional<at::ScalarType> scalarType,
10
+ bool scalarType_is_none,
11
+ std::optional<at::Layout> layout,
12
+ std::optional<at::Device> device,
13
+ bool device_is_none);
14
+
15
+ }
janus/lib/python3.10/site-packages/torch/include/torch/csrc/utils/pybind.h ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <torch/csrc/python_headers.h>
4
+ #include <torch/csrc/utils/pythoncapi_compat.h>
5
+
6
+ #include <ATen/core/Tensor.h>
7
+ #include <ATen/core/jit_type_base.h>
8
+ #include <c10/util/irange.h>
9
+ #include <pybind11/pybind11.h>
10
+ #include <pybind11/stl.h>
11
+
12
+ #include <torch/csrc/Device.h>
13
+ #include <torch/csrc/Dtype.h>
14
+ #include <torch/csrc/DynamicTypes.h>
15
+ #include <torch/csrc/Generator.h>
16
+ #include <torch/csrc/MemoryFormat.h>
17
+ #include <torch/csrc/Stream.h>
18
+ #include <torch/csrc/utils/tensor_memoryformats.h>
19
+
20
+ namespace py = pybind11;
21
+
22
+ // This makes intrusive_ptr to be available as a custom pybind11 holder type,
23
+ // see
24
+ // https://pybind11.readthedocs.io/en/stable/advanced/smart_ptrs.html#custom-smart-pointers
25
+ PYBIND11_DECLARE_HOLDER_TYPE(T, c10::intrusive_ptr<T>, true);
26
+
27
+ PYBIND11_DECLARE_HOLDER_TYPE(T, c10::SingletonOrSharedTypePtr<T>);
28
+ PYBIND11_DECLARE_HOLDER_TYPE(T, c10::SingletonTypePtr<T>, true);
29
+
30
+ namespace pybind11::detail {
31
+
32
+ // torch.Tensor <-> at::Tensor conversions (without unwrapping)
33
+ template <>
34
+ struct TORCH_PYTHON_API type_caster<at::Tensor> {
35
+ public:
36
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
37
+ PYBIND11_TYPE_CASTER(at::Tensor, _("torch.Tensor"));
38
+
39
+ bool load(handle src, bool);
40
+
41
+ static handle cast(
42
+ const at::Tensor& src,
43
+ return_value_policy /* policy */,
44
+ handle /* parent */);
45
+ };
46
+
47
+ // torch._StorageBase <-> at::Storage
48
+ template <>
49
+ struct type_caster<at::Storage> {
50
+ public:
51
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
52
+ PYBIND11_TYPE_CASTER(at::Storage, _("torch.StorageBase"));
53
+
54
+ bool load(handle src, bool) {
55
+ PyObject* obj = src.ptr();
56
+ if (torch::isStorage(obj)) {
57
+ value = torch::createStorage(obj);
58
+ return true;
59
+ }
60
+ return false;
61
+ }
62
+
63
+ static handle cast(
64
+ const at::Storage& src,
65
+ return_value_policy /* policy */,
66
+ handle /* parent */) {
67
+ return handle(torch::createPyObject(src));
68
+ }
69
+ };
70
+
71
+ template <>
72
+ struct type_caster<at::Generator> {
73
+ public:
74
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
75
+ PYBIND11_TYPE_CASTER(at::Generator, _("torch.Generator"));
76
+
77
+ bool load(handle src, bool) {
78
+ PyObject* obj = src.ptr();
79
+ if (THPGenerator_Check(obj)) {
80
+ value = reinterpret_cast<THPGenerator*>(obj)->cdata;
81
+ return true;
82
+ }
83
+ return false;
84
+ }
85
+
86
+ static handle cast(
87
+ const at::Generator& src,
88
+ return_value_policy /* policy */,
89
+ handle /* parent */) {
90
+ return handle(THPGenerator_Wrap(src));
91
+ }
92
+ };
93
+
94
+ template <>
95
+ struct TORCH_PYTHON_API type_caster<at::IntArrayRef> {
96
+ public:
97
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
98
+ PYBIND11_TYPE_CASTER(at::IntArrayRef, _("Tuple[int, ...]"));
99
+
100
+ bool load(handle src, bool);
101
+ static handle cast(
102
+ at::IntArrayRef src,
103
+ return_value_policy /* policy */,
104
+ handle /* parent */);
105
+
106
+ private:
107
+ std::vector<int64_t> v_value;
108
+ };
109
+
110
+ template <>
111
+ struct TORCH_PYTHON_API type_caster<at::SymIntArrayRef> {
112
+ public:
113
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
114
+ PYBIND11_TYPE_CASTER(at::SymIntArrayRef, _("List[int]"));
115
+
116
+ bool load(handle src, bool);
117
+ static handle cast(
118
+ at::SymIntArrayRef src,
119
+ return_value_policy /* policy */,
120
+ handle /* parent */);
121
+
122
+ private:
123
+ std::vector<c10::SymInt> v_value;
124
+ };
125
+
126
+ template <>
127
+ struct TORCH_PYTHON_API type_caster<at::ArrayRef<c10::SymNode>> {
128
+ public:
129
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
130
+ PYBIND11_TYPE_CASTER(at::ArrayRef<c10::SymNode>, _("List[SymNode]"));
131
+
132
+ bool load(handle src, bool);
133
+ static handle cast(
134
+ at::ArrayRef<c10::SymNode> src,
135
+ return_value_policy /* policy */,
136
+ handle /* parent */);
137
+
138
+ private:
139
+ std::vector<c10::SymNode> v_value;
140
+ };
141
+
142
+ template <>
143
+ struct type_caster<at::MemoryFormat> {
144
+ public:
145
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
146
+ PYBIND11_TYPE_CASTER(at::MemoryFormat, _("torch.memory_format"));
147
+
148
+ bool load(handle src, bool) {
149
+ PyObject* obj = src.ptr();
150
+ if (THPMemoryFormat_Check(obj)) {
151
+ value = reinterpret_cast<THPMemoryFormat*>(obj)->memory_format;
152
+ return true;
153
+ }
154
+ return false;
155
+ }
156
+ static handle cast(
157
+ at::MemoryFormat src,
158
+ return_value_policy /* policy */,
159
+ handle /* parent */) {
160
+ return handle(Py_NewRef(torch::utils::getTHPMemoryFormat(src)));
161
+ }
162
+ };
163
+
164
+ template <>
165
+ struct type_caster<at::Device> {
166
+ public:
167
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
168
+ PYBIND11_TYPE_CASTER(at::Device, _("torch.device"));
169
+
170
+ // PYBIND11_TYPE_CASTER defines a member field called value. Since at::Device
171
+ // cannot be default-initialized, we provide this constructor to explicitly
172
+ // initialize that field. The value doesn't matter as it will be overwritten
173
+ // after a successful call to load.
174
+ type_caster() : value(c10::kCPU) {}
175
+
176
+ bool load(handle src, bool) {
177
+ PyObject* obj = src.ptr();
178
+ if (THPDevice_Check(obj)) {
179
+ value = reinterpret_cast<THPDevice*>(obj)->device;
180
+ return true;
181
+ }
182
+ return false;
183
+ }
184
+
185
+ static handle cast(
186
+ const at::Device& src,
187
+ return_value_policy /* policy */,
188
+ handle /* parent */) {
189
+ return handle(THPDevice_New(src));
190
+ }
191
+ };
192
+
193
+ template <>
194
+ struct type_caster<at::ScalarType> {
195
+ public:
196
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
197
+ PYBIND11_TYPE_CASTER(at::ScalarType, _("torch.dtype"));
198
+
199
+ // PYBIND11_TYPE_CASTER defines a member field called value. at::ScalarType
200
+ // cannot be default-initialized, we provide this constructor to explicitly
201
+ // initialize that field. The value doesn't matter as it will be overwritten
202
+ // after a successful call to load.
203
+ type_caster() : value(at::kFloat) {}
204
+
205
+ bool load(handle src, bool) {
206
+ PyObject* obj = src.ptr();
207
+ if (THPDtype_Check(obj)) {
208
+ value = reinterpret_cast<THPDtype*>(obj)->scalar_type;
209
+ return true;
210
+ }
211
+ return false;
212
+ }
213
+
214
+ static handle cast(
215
+ const at::ScalarType& src,
216
+ return_value_policy /* policy */,
217
+ handle /* parent */) {
218
+ return Py_NewRef(torch::getTHPDtype(src));
219
+ }
220
+ };
221
+
222
+ template <>
223
+ struct type_caster<c10::Stream> {
224
+ public:
225
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
226
+ PYBIND11_TYPE_CASTER(c10::Stream, _("torch.Stream"));
227
+
228
+ // PYBIND11_TYPE_CASTER defines a member field called value. Since c10::Stream
229
+ // cannot be default-initialized, we provide this constructor to explicitly
230
+ // initialize that field. The value doesn't matter as it will be overwritten
231
+ // after a successful call to load.
232
+ type_caster() : value(c10::Stream::DEFAULT, c10::Device(c10::kCPU, 0)) {}
233
+
234
+ bool load(handle src, bool) {
235
+ PyObject* obj = src.ptr();
236
+ if (THPStream_Check(obj)) {
237
+ value = c10::Stream::unpack3(
238
+ ((THPStream*)obj)->stream_id,
239
+ static_cast<c10::DeviceIndex>(((THPStream*)obj)->device_index),
240
+ static_cast<c10::DeviceType>(((THPStream*)obj)->device_type));
241
+ return true;
242
+ }
243
+ return false;
244
+ }
245
+
246
+ static handle cast(
247
+ const c10::Stream& src,
248
+ return_value_policy /* policy */,
249
+ handle /* parent */) {
250
+ return handle(THPStream_Wrap(src));
251
+ }
252
+ };
253
+
254
+ template <>
255
+ struct type_caster<c10::DispatchKey>
256
+ : public type_caster_base<c10::DispatchKey> {
257
+ using base = type_caster_base<c10::DispatchKey>;
258
+ c10::DispatchKey tmp{};
259
+
260
+ public:
261
+ bool load(handle src, bool convert) {
262
+ if (base::load(src, convert)) {
263
+ return true;
264
+ } else if (py::isinstance(
265
+ src, py::module_::import("builtins").attr("str"))) {
266
+ tmp = c10::parseDispatchKey(py::cast<std::string>(src));
267
+ value = &tmp;
268
+ return true;
269
+ }
270
+ return false;
271
+ }
272
+
273
+ static handle cast(
274
+ c10::DispatchKey src,
275
+ return_value_policy policy,
276
+ handle parent) {
277
+ return base::cast(src, policy, parent);
278
+ }
279
+ };
280
+
281
+ template <>
282
+ struct TORCH_PYTHON_API type_caster<c10::Scalar> {
283
+ public:
284
+ PYBIND11_TYPE_CASTER(
285
+ c10::Scalar,
286
+ _("Union[Number, torch.SymInt, torch.SymFloat, torch.SymBool]"));
287
+ bool load(py::handle src, bool);
288
+
289
+ static py::handle cast(
290
+ const c10::Scalar& si,
291
+ return_value_policy /* policy */,
292
+ handle /* parent */);
293
+ };
294
+
295
+ template <>
296
+ struct TORCH_PYTHON_API type_caster<c10::SymInt> {
297
+ public:
298
+ PYBIND11_TYPE_CASTER(c10::SymInt, _("Union[int, torch.SymInt]"));
299
+ bool load(py::handle src, bool);
300
+
301
+ static py::handle cast(
302
+ const c10::SymInt& si,
303
+ return_value_policy /* policy */,
304
+ handle /* parent */);
305
+ };
306
+
307
+ template <>
308
+ struct TORCH_PYTHON_API type_caster<c10::SymFloat> {
309
+ public:
310
+ PYBIND11_TYPE_CASTER(c10::SymFloat, _("float"));
311
+ bool load(py::handle src, bool);
312
+
313
+ static py::handle cast(
314
+ const c10::SymFloat& si,
315
+ return_value_policy /* policy */,
316
+ handle /* parent */);
317
+ };
318
+
319
+ template <>
320
+ struct TORCH_PYTHON_API type_caster<c10::SymBool> {
321
+ public:
322
+ PYBIND11_TYPE_CASTER(c10::SymBool, _("Union[bool, torch.SymBool]"));
323
+ bool load(py::handle src, bool);
324
+
325
+ static py::handle cast(
326
+ const c10::SymBool& si,
327
+ return_value_policy /* policy */,
328
+ handle /* parent */);
329
+ };
330
+
331
+ template <typename T>
332
+ struct type_caster<c10::complex<T>> {
333
+ public:
334
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
335
+ PYBIND11_TYPE_CASTER(c10::complex<T>, _("complex"));
336
+
337
+ bool load(handle src, bool) {
338
+ PyObject* obj = src.ptr();
339
+
340
+ // Refered from `THPUtils_unpackComplexDouble`
341
+ Py_complex py_complex = PyComplex_AsCComplex(obj);
342
+ if (py_complex.real == -1.0 && PyErr_Occurred()) {
343
+ return false;
344
+ }
345
+
346
+ // Python's Complex is always double precision.
347
+ value = c10::complex<double>(py_complex.real, py_complex.imag);
348
+ return true;
349
+ }
350
+
351
+ static handle cast(
352
+ const c10::complex<T>& complex,
353
+ return_value_policy /* policy */,
354
+ handle /* parent */) {
355
+ // Python only knows double precision complex.
356
+ return handle(PyComplex_FromDoubles(complex.real(), complex.imag()));
357
+ }
358
+ };
359
+
360
+ } // namespace pybind11::detail
361
+
362
+ namespace torch::impl {
363
+
364
+ // Use this function if you have a C++ object that is used from both C++
365
+ // and Python contexts, and you need its GIL to be released when you
366
+ // destruct it in the Python context.
367
+ //
368
+ // This function is a valid shared_ptr destructor and can be used to
369
+ // conveniently allocate a shared_ptr to an object whose destructor will be run
370
+ // without the GIL. Pass it as the second argument to shared_ptr, e.g.,
371
+ //
372
+ // shared_ptr<T>(new T(), destroy_without_gil<T>)
373
+ //
374
+ // Attaching the GIL release logic to the holder pointer rather than the
375
+ // actual destructor of T is helpful when T is Python-agnostic and
376
+ // shouldn't refer to the PYthon API.
377
+ //
378
+ // Note there are limitations to the correctness of code that makes use of this.
379
+ // In particular, if a shared_ptr is constructed from C++ code without this
380
+ // destructor and then passed to pybind11, pybind11 will happily take ownership
381
+ // of the shared_ptr (and be willing to destruct it from a context where it is
382
+ // holding the GIL). unique_ptr with a type branded deleter is less prone to
383
+ // this problem, because a stock deleter unique_ptr is not convertible with it.
384
+ // I plan to mitigate this problem by adding DEBUG-only asserts to the true C++
385
+ // destructors that the GIL is not held (using a virtual call to get to the
386
+ // Python interpreter); alternately, we could use a virtual call to simply
387
+ // ensure we release the GIL in the C++ destructor, however, this is a layering
388
+ // violation (why does code that is ostensibly Python agnostic calling into the
389
+ // GIL).
390
+ //
391
+ // Adapted from
392
+ // https://github.com/pybind/pybind11/issues/1446#issuecomment-406341510
393
+ template <typename T>
394
+ inline void destroy_without_gil(T* ptr) {
395
+ // Because the ownership of a shared_ptr is diffuse, it's not possible to
396
+ // necessarily predict whether or not the last reference to an object will
397
+ // be destructed from Python or C++. This means that in the destructor here,
398
+ // we don't necessarily know if we actually have the GIL or not; in fact,
399
+ // we don't even know if the Python interpreter still exists! Thus, we have
400
+ // to test for it before releasing the GIL.
401
+ //
402
+ // PyGILState_Check is hopefully self explanatory. But Py_IsInitialized or
403
+ // _PyIsFinalizing? Both get set at the same time during the Python
404
+ // destruction process:
405
+ // https://github.com/python/cpython/blob/d92513390a1a0da781bb08c284136f4d7abea36d/Python/pylifecycle.c#L1716-L1717
406
+ // so the operant question is whether or not you want to release the GIL after
407
+ // finalization has completed (and there is just no Python interpreter).
408
+ // Clearly there is no need to release GIL in that state, so we want
409
+ // Py_IsInitialized.
410
+ if (Py_IsInitialized() && PyGILState_Check()) {
411
+ pybind11::gil_scoped_release nogil;
412
+ delete ptr;
413
+ } else {
414
+ delete ptr;
415
+ }
416
+ }
417
+
418
+ } // namespace torch::impl