forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModule.cpp
1940 lines (1772 loc) · 63.9 KB
/
Module.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <ATen/ATen.h>
#include <ATen/CachedTensorUtils.h>
#include <ATen/core/TensorBody.h>
#include <ATen/cuda/CUDAConfig.h>
#include <ATen/native/ConvUtils.h>
#include <c10/core/Device.h>
#include <c10/core/TensorImpl.h>
#include <c10/util/UniqueVoidPtr.h>
#include <pybind11/pytypes.h>
#include <torch/csrc/utils/python_arg_parser.h>
#include <unordered_set>
#if AT_CUDNN_ENABLED()
#endif
#include <ATen/cuda/CUDAContext.h>
#include <ATen/cuda/CUDAGeneratorImpl.h>
#include <ATen/cuda/CachingHostAllocator.h>
#include <ATen/cuda/Sleep.h>
#include <ATen/cuda/detail/CUDAHooks.h>
#include <ATen/cuda/jiterator.h>
#include <ATen/cuda/tunable/Tunable.h>
#include <c10/core/StorageImpl.h>
#include <c10/cuda/CUDAAllocatorConfig.h>
#include <c10/cuda/CUDACachingAllocator.h>
#include <c10/cuda/CUDAFunctions.h>
#include <ATen/cuda/CUDAGraphsUtils.cuh>
#ifdef USE_NCCL
#include <torch/csrc/cuda/python_nccl.h>
#endif
#include <c10/util/CallOnce.h>
#include <c10/util/irange.h>
#include <torch/csrc/CudaIPCTypes.h>
#include <torch/csrc/Generator.h>
#include <torch/csrc/cuda/CUDAPluggableAllocator.h>
#include <torch/csrc/cuda/THCP.h>
#include <torch/csrc/cuda/memory_snapshot.h>
#include <torch/csrc/cuda/python_comm.h>
#include <torch/csrc/profiler/python/combined_traceback.h>
#include <torch/csrc/python_headers.h>
#include <torch/csrc/utils/device_lazy_init.h>
#include <torch/csrc/utils/pybind.h>
#include <torch/csrc/utils/pycfunction_helpers.h>
#include <torch/csrc/utils/python_numbers.h>
#include <torch/csrc/utils/python_strings.h>
#include <array>
#include <chrono>
#include <iostream>
#include <sstream>
#include <thread>
#include <unordered_map>
#ifndef WIN32
#include <pthread.h>
#endif
using namespace torch;
static bool in_bad_fork = false; // True for children forked after cuda init
#ifndef WIN32
// Called in the forked child if cuda has already been initialized
static void forked_child() {
in_bad_fork = true;
torch::utils::set_requires_device_init(at::kCUDA, true);
}
#endif
// Should be called before the first cuda call.
// Note: This is distinct from initExtension because a stub cuda implementation
// has some working functions (e.g. device_count) but cannot fully initialize.
static void poison_fork() {
#ifndef WIN32
static c10::once_flag flag;
c10::call_once(flag, [] { pthread_atfork(nullptr, nullptr, forked_child); });
#endif
}
////////////////////////////////////////////////////////////////////////////////
// CUDA management methods
////////////////////////////////////////////////////////////////////////////////
PyObject* THCPModule_setDevice_wrap(PyObject* self, PyObject* arg) {
HANDLE_TH_ERRORS
TORCH_CHECK(THPUtils_checkLong(arg), "invalid argument to setDevice");
auto device = THPUtils_unpackLong(arg);
torch::utils::device_lazy_init(at::kCUDA);
c10::cuda::set_device(static_cast<c10::DeviceIndex>(device));
Py_RETURN_NONE;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_exchangeDevice(PyObject* self, PyObject* arg) {
HANDLE_TH_ERRORS
TORCH_CHECK(THPUtils_checkLong(arg), "invalid argument to exchangeDevice");
auto device_index = THPUtils_unpackDeviceIndex(arg);
if (device_index < 0) {
return THPUtils_packInt32(-1);
}
torch::utils::device_lazy_init(at::kCUDA);
auto current_device = c10::cuda::ExchangeDevice(device_index);
return THPUtils_packDeviceIndex(current_device);
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_maybeExchangeDevice(PyObject* self, PyObject* arg) {
HANDLE_TH_ERRORS
TORCH_CHECK(THPUtils_checkLong(arg), "invalid argument to exchangeDevice");
auto device_index = THPUtils_unpackDeviceIndex(arg);
if (device_index < 0) {
return THPUtils_packInt32(-1);
}
torch::utils::device_lazy_init(at::kCUDA);
auto current_device = c10::cuda::MaybeExchangeDevice(device_index);
return THPUtils_packDeviceIndex(current_device);
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_getDevice_wrap(PyObject* self, PyObject* noargs) {
HANDLE_TH_ERRORS
torch::utils::device_lazy_init(at::kCUDA);
// NOLINTNEXTLINE(bugprone-signed-char-misuse)
auto device = static_cast<int32_t>(c10::cuda::current_device());
return THPUtils_packInt32(device);
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_canDeviceAccessPeer_wrap(PyObject* self, PyObject* args) {
HANDLE_TH_ERRORS
PyObject* arg1 = nullptr;
PyObject* arg2 = nullptr;
if (!PyArg_ParseTuple(args, "OO", &arg1, &arg2)) {
THPUtils_invalidArguments(
args,
nullptr,
"can_device_peer_access",
1,
"(int device, int peer_device);");
return nullptr;
}
TORCH_CHECK(
THPUtils_checkLong(arg1), "invalid argument to canDeviceAccessPeer");
TORCH_CHECK(
THPUtils_checkLong(arg2), "invalid argument to canDeviceAccessPeer");
int64_t device = THPUtils_unpackLong(arg1);
int64_t peer_device = THPUtils_unpackLong(arg2);
torch::utils::device_lazy_init(at::kCUDA);
auto can_access = at::cuda::canDeviceAccessPeer(device, peer_device);
return PyBool_FromLong(can_access);
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_getDeviceCount_wrap(PyObject* self, PyObject* noargs) {
HANDLE_TH_ERRORS
poison_fork();
return THPUtils_packUInt64(at::cuda::device_count());
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_getArchFlags(PyObject* self, PyObject* noargs) {
HANDLE_TH_ERRORS
poison_fork();
#ifdef CUDA_ARCH_FLAGS
static const char* flags = C10_STRINGIZE(CUDA_ARCH_FLAGS);
return THPUtils_packString(flags);
#else
Py_RETURN_NONE;
#endif
END_HANDLE_TH_ERRORS
}
static PyObject* THCPModule_isInBadFork(PyObject* self, PyObject* noargs) {
HANDLE_TH_ERRORS
return PyBool_FromLong(in_bad_fork);
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_getCurrentStream_wrap(
PyObject* /* unused */,
PyObject* device_index) {
HANDLE_TH_ERRORS
TORCH_CHECK(
THPUtils_checkLong(device_index), "invalid argument to getCurrentStream");
auto c10_device_index = THPUtils_unpackDeviceIndex(device_index);
auto stream = at::cuda::getCurrentCUDAStream(c10_device_index);
PyObject* output_tuple = PyTuple_New(3);
PyTuple_SetItem(
output_tuple, 0, THPUtils_packInt64(static_cast<int64_t>(stream.id())));
PyTuple_SetItem(
output_tuple, 1, THPUtils_packDeviceIndex(stream.device_index()));
PyTuple_SetItem(
output_tuple,
2,
THPUtils_packInt64(static_cast<int64_t>(stream.device_type())));
return output_tuple;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_getCurrentStream_raw(
PyObject* /* unused */,
PyObject* device_index) {
HANDLE_TH_ERRORS
TORCH_CHECK(
THPUtils_checkLong(device_index), "invalid argument to getCurrentStream");
auto c10_device_index = THPUtils_unpackDeviceIndex(device_index);
return PyLong_FromVoidPtr(
at::cuda::getCurrentCUDAStream(c10_device_index).stream());
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_getDefaultStream_wrap(
PyObject* /* unused */,
PyObject* device_index) {
HANDLE_TH_ERRORS
TORCH_CHECK(
THPUtils_checkLong(device_index), "invalid argument to getDefaultStream");
auto c10_device_index = THPUtils_unpackDeviceIndex(device_index);
auto stream = at::cuda::getDefaultCUDAStream(c10_device_index);
PyObject* output_tuple = PyTuple_New(3);
PyTuple_SetItem(
output_tuple, 0, THPUtils_packInt64(static_cast<int64_t>(stream.id())));
PyTuple_SetItem(
output_tuple, 1, THPUtils_packDeviceIndex(stream.device_index()));
PyTuple_SetItem(
output_tuple,
2,
THPUtils_packInt64(static_cast<int64_t>(stream.device_type())));
return output_tuple;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_setStream_wrap(
PyObject* self,
PyObject* args,
PyObject* kwargs) {
HANDLE_TH_ERRORS
int64_t stream_id = 0;
int64_t device_index = 0;
int64_t device_type = 0;
// NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
constexpr const char* kwlist[] = {
"stream_id", "device_index", "device_type", nullptr};
if (!PyArg_ParseTupleAndKeywords(
args,
kwargs,
"|LLL",
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
const_cast<char**>(kwlist),
&stream_id,
&device_index,
&device_type)) {
}
auto stream = at::cuda::CUDAStream::unpack3(
stream_id,
static_cast<c10::DeviceIndex>(device_index),
static_cast<c10::DeviceType>(device_type));
auto device = c10::cuda::current_device();
if (device != stream.device_index()) {
c10::cuda::set_device(stream.device_index());
}
at::cuda::setCurrentCUDAStream(stream);
Py_RETURN_NONE;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_getCompiledVersion(PyObject* self, PyObject* noargs) {
#if defined(USE_ROCM)
return THPUtils_packInt64((int64_t)ROCM_VERSION);
#else
return THPUtils_packInt64((int64_t)CUDA_VERSION);
#endif
}
PyObject* THCPModule_cudaHostAllocator(PyObject* _unused, PyObject* noargs) {
HANDLE_TH_ERRORS
c10::Allocator* allocator = at::cuda::getCachingHostAllocator();
return PyLong_FromVoidPtr(allocator);
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_cudaCachingAllocator_raw_alloc(
PyObject* _unused,
PyObject* args) {
HANDLE_TH_ERRORS
PyObject* size_o = nullptr;
PyObject* stream_o = nullptr;
if (!PyArg_ParseTuple(args, "OO", &size_o, &stream_o)) {
THPUtils_invalidArguments(
args,
nullptr,
"caching_allocator_alloc",
1,
"(ssize_t size, intptr_t stream);");
return nullptr;
}
auto size = PyLong_AsSsize_t(size_o);
cudaStream_t stream = static_cast<cudaStream_t>(PyLong_AsVoidPtr(stream_o));
void* mem = nullptr;
{
pybind11::gil_scoped_release no_gil;
mem = c10::cuda::CUDACachingAllocator::raw_alloc_with_stream(size, stream);
}
return PyLong_FromVoidPtr(mem);
END_HANDLE_TH_ERRORS
}
// Unpack a PyObject to at::Scalar, throw an exception if it fails
at::Scalar as_scalar(PyObject* arg) {
// Zero-dim tensors are converted to Scalars as-is. Note this doesn't
// currently handle most NumPy scalar types except np.float64.
if (THPVariable_Check(arg)) {
return THPVariable_Unpack(arg).item();
}
if (THPUtils_checkLong(arg)) {
return at::Scalar(static_cast<int64_t>(THPUtils_unpackLong(arg)));
}
if (PyBool_Check(arg)) {
return at::Scalar(THPUtils_unpackBool(arg));
}
if (PyComplex_Check(arg)) {
return at::Scalar(THPUtils_unpackComplexDouble(arg));
}
return at::Scalar(THPUtils_unpackDouble(arg));
}
// Entrypoint for the callable created by torch.cuda.jiterator
// See jiterator.py for more details
PyObject* THCPModule_cudaJiteratorCompileAndLaunchKernel(
PyObject* _unused,
PyObject* args) {
HANDLE_TH_ERRORS
PyObject* code_string_o = nullptr;
PyObject* kernel_name_o = nullptr;
PyObject* return_by_ref_o = nullptr;
PyObject* num_outputs_o = nullptr;
PyObject* tensors_o = nullptr;
PyObject* kwargs_o = nullptr;
if (!PyArg_ParseTuple(
args,
"OOOOO|O",
&code_string_o,
&kernel_name_o,
&return_by_ref_o,
&num_outputs_o,
&tensors_o,
&kwargs_o)) {
return nullptr;
}
const std::string code_string = THPUtils_unpackString(code_string_o);
const std::string kernel_name = THPUtils_unpackString(kernel_name_o);
const bool return_by_ref = THPUtils_unpackBool(return_by_ref_o);
const int num_outputs = static_cast<int>(THPUtils_unpackLong(num_outputs_o));
TORCH_CHECK(
PyTuple_Check(tensors_o),
"tensors argument is expected to "
"be a tuple, but got ",
THPUtils_typename(tensors_o));
Py_ssize_t num_tensors = PyTuple_GET_SIZE(tensors_o);
c10::SmallVector<at::Tensor> tensors;
for (const auto i : c10::irange(num_tensors)) {
PyObject* _tensor = PyTuple_GET_ITEM(tensors_o, i);
TORCH_CHECK(
THPVariable_Check(_tensor),
i,
" of input tensors tuple is not a Tensor");
tensors.emplace_back(THPVariable_Unpack(_tensor));
}
c10::SmallVector<at::Scalar> extra_args;
PyObject* key = nullptr;
PyObject* value = nullptr;
Py_ssize_t pos = 0;
while (PyDict_Next(kwargs_o, &pos, &key, &value)) {
extra_args.emplace_back(as_scalar(value));
}
c10::SmallVector<at::Tensor> outputs = at::cuda::CompileAndLaunchKernel(
code_string,
kernel_name,
num_outputs,
tensors,
extra_args,
return_by_ref);
if (num_outputs == 1) {
return THPVariable_Wrap(outputs[0]);
} else {
PyObject* output_tuple = PyTuple_New(num_outputs);
for (int i = 0; i < num_outputs; ++i) {
PyTuple_SetItem(output_tuple, i, THPVariable_Wrap(outputs[i]));
}
return output_tuple;
}
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_cudaCachingAllocator_raw_delete(
PyObject* _unused,
PyObject* obj) {
HANDLE_TH_ERRORS
void* mem_ptr = PyLong_AsVoidPtr(obj);
{
pybind11::gil_scoped_release no_gil;
c10::cuda::CUDACachingAllocator::raw_delete(mem_ptr);
}
Py_RETURN_NONE;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_cudaCachingAllocator_set_allocator_settings(
PyObject* _unused,
PyObject* env) {
HANDLE_TH_ERRORS
c10::cuda::CUDACachingAllocator::setAllocatorSettings(
THPUtils_unpackString(env));
Py_RETURN_NONE;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_getAllocatorBackend(PyObject* _unused, PyObject* noargs) {
HANDLE_TH_ERRORS
return THPUtils_packString(c10::cuda::CUDACachingAllocator::name());
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_cudaSynchronize(PyObject* _unused, PyObject* noargs) {
HANDLE_TH_ERRORS {
pybind11::gil_scoped_release no_gil;
c10::cuda::device_synchronize();
}
Py_RETURN_NONE;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_cudaIPCCollect(PyObject* _unused, PyObject* noargs) {
HANDLE_TH_ERRORS
torch::CudaIPCCollect();
Py_RETURN_NONE;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_cudaSleep(PyObject* _unused, PyObject* cycles) {
HANDLE_TH_ERRORS
TORCH_CHECK(
THPUtils_checkLong(cycles), "torch.cuda._sleep(): expected 'int'");
int64_t unpacked_cycles = THPUtils_unpackLong(cycles);
{
pybind11::gil_scoped_release no_gil;
at::cuda::sleep(unpacked_cycles);
}
Py_RETURN_NONE;
END_HANDLE_TH_ERRORS
}
// We need to ensure that as long as a thread will NEVER loose the GIL as long
// as it holds the CUDA mutex. Otherwise another thread might be scheduled and
// try to e.g. allocate a new tensor which will cause a deadlock. It's enough to
// have a single global, because it can be only set once (cudaMutex is not
// recursive) by the thread that owns the mutex (obviously there can be only one
// such thread).
static PyGILState_STATE cudaMutexGILState;
PyObject* THCPModule_cudaLockMutex(PyObject* module, PyObject* noargs) {
auto mutex = c10::cuda::getFreeMutex();
// This has to be a busy loop because we **absolutely need to** hold the GIL
// or it's a recipe for a deadlock otherwise (if we let other Python threads
// run while we have the cudaMutex, but not the GIL, they might try to e.g.
// free a CUDA tensor and acquire the cudaMutex without giving up the GIL,
// because it happens deep within THC).
while (true) {
if (mutex->try_lock())
break;
{
pybind11::gil_scoped_release no_gil;
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
}
cudaMutexGILState = PyGILState_Ensure();
Py_RETURN_NONE;
}
PyObject* THCPModule_cudaUnlockMutex(PyObject* module, PyObject* noargs) {
auto mutex = c10::cuda::getFreeMutex();
PyGILState_Release(cudaMutexGILState);
mutex->unlock();
Py_RETURN_NONE;
}
PyObject* THCPModule_hasPrimaryContext(PyObject* _unused, PyObject* arg) {
HANDLE_TH_ERRORS
TORCH_CHECK(
THPUtils_checkLong(arg), "invalid argument to has_primary_context");
auto device_index = THPUtils_unpackDeviceIndex(arg);
if (c10::cuda::hasPrimaryContext(device_index)) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_setMemoryFraction(PyObject* _unused, PyObject* args) {
HANDLE_TH_ERRORS
PyObject* fraction_o = nullptr;
PyObject* device_o = nullptr;
if (!PyArg_ParseTuple(args, "OO", &fraction_o, &device_o)) {
THPUtils_invalidArguments(
args,
nullptr,
"set_memory_fraction",
1,
"(double fraction, int device);");
return nullptr;
}
double fraction = PyFloat_AsDouble(fraction_o);
auto device_index = THPUtils_unpackDeviceIndex(device_o);
c10::cuda::CUDACachingAllocator::setMemoryFraction(fraction, device_index);
END_HANDLE_TH_ERRORS
Py_RETURN_NONE;
}
PyObject* THCPModule_emptyCache(PyObject* _unused, PyObject* noargs) {
HANDLE_TH_ERRORS
c10::cuda::CUDACachingAllocator::emptyCache();
END_HANDLE_TH_ERRORS
Py_RETURN_NONE;
}
PyObject* THCPModule_memoryStats(PyObject* _unused, PyObject* arg) {
HANDLE_TH_ERRORS
TORCH_CHECK(THPUtils_checkLong(arg), "invalid argument to memory_allocated");
const auto device_index = THPUtils_unpackDeviceIndex(arg);
using c10::cuda::CUDACachingAllocator::DeviceStats;
using c10::cuda::CUDACachingAllocator::Stat;
using c10::cuda::CUDACachingAllocator::StatArray;
using c10::cuda::CUDACachingAllocator::StatType;
const auto statToDict = [](const Stat& stat) {
py::dict dict;
dict["current"] = stat.current;
dict["peak"] = stat.peak;
dict["allocated"] = stat.allocated;
dict["freed"] = stat.freed;
return dict;
};
const auto statArrayToDict = [=](const StatArray& statArray) {
const std::array<const char*, static_cast<size_t>(StatType::NUM_TYPES)>
statTypeNames = {"all", "small_pool", "large_pool"};
py::dict dict;
for (const auto i : c10::irange(statTypeNames.size())) {
dict[statTypeNames[i]] = statToDict(statArray[i]);
}
return dict;
};
const DeviceStats stats =
c10::cuda::CUDACachingAllocator::getDeviceStats(device_index);
py::dict result;
result["num_alloc_retries"] = stats.num_alloc_retries;
result["num_ooms"] = stats.num_ooms;
result["max_split_size"] = stats.max_split_size;
result["num_sync_all_streams"] = stats.num_sync_all_streams;
result["num_device_alloc"] = stats.num_device_alloc;
result["num_device_free"] = stats.num_device_free;
result["allocation"] = statArrayToDict(stats.allocation);
result["segment"] = statArrayToDict(stats.segment);
result["active"] = statArrayToDict(stats.active);
result["inactive_split"] = statArrayToDict(stats.inactive_split);
result["allocated_bytes"] = statArrayToDict(stats.allocated_bytes);
result["reserved_bytes"] = statArrayToDict(stats.reserved_bytes);
result["active_bytes"] = statArrayToDict(stats.active_bytes);
result["inactive_split_bytes"] = statArrayToDict(stats.inactive_split_bytes);
result["requested_bytes"] = statArrayToDict(stats.requested_bytes);
result["oversize_allocations"] = statToDict(stats.oversize_allocations);
result["oversize_segments"] = statToDict(stats.oversize_segments);
return result.release().ptr();
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_resetAccumulatedMemoryStats(
PyObject* _unused,
PyObject* arg) {
HANDLE_TH_ERRORS
TORCH_CHECK(
THPUtils_checkLong(arg),
"invalid argument to reset_accumulated_memory_stats");
const auto device_index = THPUtils_unpackDeviceIndex(arg);
c10::cuda::CUDACachingAllocator::resetAccumulatedStats(device_index);
END_HANDLE_TH_ERRORS
Py_RETURN_NONE;
}
PyObject* THCPModule_resetPeakMemoryStats(PyObject* _unused, PyObject* arg) {
HANDLE_TH_ERRORS
TORCH_CHECK(
THPUtils_checkLong(arg), "invalid argument to reset_peak_memory_stats");
const auto device_index = THPUtils_unpackDeviceIndex(arg);
c10::cuda::CUDACachingAllocator::resetPeakStats(device_index);
END_HANDLE_TH_ERRORS
Py_RETURN_NONE;
}
CapturedTraceback* getFromContext(
const std::shared_ptr<c10::GatheredContext>& x) {
if (CapturedTraceback* sc = dynamic_cast<CapturedTraceback*>(x.get())) {
return sc;
}
TORCH_CHECK(
false,
"attempting to gather stack context from the wrong StackContext type.");
}
PyObject* THCPModule_memorySnapshot(PyObject* _unused, PyObject* noargs) {
HANDLE_TH_ERRORS
using c10::cuda::CUDACachingAllocator::BlockInfo;
using c10::cuda::CUDACachingAllocator::SegmentInfo;
py::str device_s = "device";
py::str address_s = "address";
py::str total_size_s = "total_size";
py::str allocated_size_s = "allocated_size";
py::str active_size_s = "active_size";
py::str requested_size_s = "requested_size";
py::str stream_s = "stream";
py::str segment_type_s = "segment_type";
py::str segment_pool_id = "segment_pool_id";
py::str large_s = "large";
py::str small_s = "small";
py::str size_s = "size";
py::str state_s = "state";
py::str active_allocated_s = "active_allocated";
py::str active_pending_free_s = "active_pending_free";
py::str inactive_s = "inactive";
py::str addr_s = "addr";
py::str cpp_frames_s = "cpp_frames";
py::str blocks_s = "blocks";
py::str is_expandable_s = "is_expandable";
py::str frames_s = "frames";
py::str time_us_s = "time_us";
py::list empty_frames;
std::vector<CapturedTraceback*> to_gather_frames;
std::vector<py::dict> to_gather_dest;
auto add_frame_key = [&](const py::dict& d,
const std::shared_ptr<c10::GatheredContext>& ctx) {
if (ctx) {
auto sc = getFromContext(ctx);
to_gather_frames.emplace_back(sc);
to_gather_dest.emplace_back(d);
} else {
d[frames_s] = empty_frames;
}
};
const auto segmentInfoToDict = [&](const SegmentInfo& segmentInfo) {
py::dict segmentDict;
segmentDict[device_s] = segmentInfo.device;
segmentDict[address_s] = segmentInfo.address;
segmentDict[total_size_s] = segmentInfo.total_size;
segmentDict[allocated_size_s] = segmentInfo.allocated_size;
segmentDict[active_size_s] = segmentInfo.active_size;
segmentDict[requested_size_s] = segmentInfo.requested_size;
// we want the python objects to pickle easily so use an int to
// represent the stream rather than a torch.cuda.stream object
segmentDict[stream_s] = int64_t(segmentInfo.stream);
segmentDict[segment_type_s] = (segmentInfo.is_large ? large_s : small_s);
segmentDict[segment_pool_id] = segmentInfo.owner_private_pool_id;
segmentDict[is_expandable_s] = segmentInfo.is_expandable;
add_frame_key(segmentDict, segmentInfo.context_when_allocated);
auto address = segmentInfo.address;
py::list blocks;
for (const auto& blockInfo : segmentInfo.blocks) {
py::dict blockDict;
blockDict[address_s] = address;
blockDict[size_s] = blockInfo.size;
blockDict[requested_size_s] = blockInfo.requested_size;
blockDict[state_s] =
(blockInfo.allocated
? active_allocated_s
: (blockInfo.active ? active_pending_free_s : inactive_s));
add_frame_key(blockDict, blockInfo.context_when_allocated);
blocks.append(blockDict);
address += blockInfo.size;
}
segmentDict[blocks_s] = blocks;
return segmentDict;
};
auto snapshot = c10::cuda::CUDACachingAllocator::snapshot();
py::list segments;
for (const auto& segmentInfo : snapshot.segments) {
segments.append(segmentInfoToDict(segmentInfo));
}
py::list traces;
py::str action_s = "action";
py::str alloc_s = "alloc";
py::str free_requested_s = "free_requested";
py::str free_completed_s = "free_completed";
py::str segment_alloc_s = "segment_alloc";
py::str segment_free_s = "segment_free";
py::str segment_map_s = "segment_map";
py::str segment_unmap_s = "segment_unmap";
py::str snapshot_s = "snapshot";
py::str oom_s = "oom";
py::str device_free_s = "device_free";
using namespace c10::cuda::CUDACachingAllocator;
auto action_to_str = [&](TraceEntry::Action action) {
switch (action) {
case TraceEntry::ALLOC:
return alloc_s;
case TraceEntry::FREE_REQUESTED:
return free_requested_s;
case TraceEntry::FREE_COMPLETED:
return free_completed_s;
case TraceEntry::SEGMENT_ALLOC:
return segment_alloc_s;
case TraceEntry::SEGMENT_FREE:
return segment_free_s;
case TraceEntry::OOM:
return oom_s;
case TraceEntry::SNAPSHOT:
return snapshot_s;
case TraceEntry::SEGMENT_UNMAP:
return segment_unmap_s;
case TraceEntry::SEGMENT_MAP:
return segment_map_s;
}
throw std::runtime_error("unreachable");
};
for (const auto& traceInfo : snapshot.device_traces) {
py::list trace;
for (const auto& te : traceInfo) {
py::dict trace_entry;
if (te.context_) {
// without further compression frames can get really large on dump
auto sc = getFromContext(te.context_);
to_gather_frames.emplace_back(sc);
to_gather_dest.emplace_back(trace_entry);
}
trace_entry[action_s] = action_to_str(te.action_);
trace_entry[TraceEntry::OOM == te.action_ ? device_free_s : addr_s] =
te.addr_;
trace_entry[size_s] = te.size_;
trace_entry[stream_s] = int64_t(te.stream_);
trace_entry[time_us_s] = te.time_.t_;
trace.append(trace_entry);
}
traces.append(trace);
}
py::dict allocator_settings;
py::str last_allocator_settings_s = "PYTORCH_CUDA_ALLOC_CONF";
py::str max_split_size_s = "max_split_size";
py::str garbage_collection_threshold_s = "garbage_collection_threshold";
py::str expandable_segments_s = "expandable_segments";
py::str pinned_num_register_threads_s = "pinned_num_register_threads";
py::str release_lock_on_malloc_s = "release_lock_on_cudamalloc";
py::str pinned_use_host_register_s = "pinned_use_cuda_host_register";
py::str roundup_power2_divisions_s = "roundup_power2_divisions";
allocator_settings[last_allocator_settings_s] =
snapshot.config_metadata.last_allocator_settings;
allocator_settings[max_split_size_s] =
int64_t(snapshot.config_metadata.max_split_size);
allocator_settings[garbage_collection_threshold_s] =
snapshot.config_metadata.garbage_collection_threshold;
allocator_settings[expandable_segments_s] =
snapshot.config_metadata.expandable_segments;
allocator_settings[pinned_num_register_threads_s] =
int64_t(snapshot.config_metadata.pinned_num_register_threads);
allocator_settings[release_lock_on_malloc_s] =
snapshot.config_metadata.release_lock_on_malloc;
allocator_settings[pinned_use_host_register_s] =
snapshot.config_metadata.pinned_use_host_register;
unsigned int roundup_key = 1;
py::dict roundup_settings;
for (const auto& v : snapshot.config_metadata.roundup_power2_divisions) {
py::str roundup_key_s = std::to_string(roundup_key);
roundup_settings[roundup_key_s] = int64_t(v);
roundup_key *= 2;
}
allocator_settings[roundup_power2_divisions_s] = roundup_settings;
py::dict result;
result["segments"] = segments;
result["device_traces"] = traces;
result["allocator_settings"] = allocator_settings;
auto frames = py_symbolize(to_gather_frames);
for (auto i : c10::irange(frames.size())) {
to_gather_dest.at(i)[frames_s] = frames.at(i);
}
return result.release().ptr();
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_attachOutOfMemoryObserver(
PyObject* _unused,
PyObject* observer) {
HANDLE_TH_ERRORS
Py_XINCREF(observer);
auto obs = [observer](
int64_t device,
int64_t alloc,
int64_t device_allocated,
int64_t device_free) {
py::gil_scoped_acquire g;
PyObject* result = PyObject_CallFunction(
observer, "LLLL", device, alloc, device_allocated, device_free);
if (!result) {
throw py::error_already_set();
}
Py_XDECREF(result);
};
at::globalContext().lazyInitCUDA();
c10::cuda::CUDACachingAllocator::attachOutOfMemoryObserver(std::move(obs));
Py_RETURN_NONE;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_cudaSetSyncDebugMode(PyObject* _unused, PyObject* arg) {
HANDLE_TH_ERRORS
TORCH_WARN_ONCE(
"Synchronization debug mode is a prototype feature and does not yet detect all "
"synchronizing operations");
TORCH_CHECK(
THPUtils_checkLong(arg), "invalid argument to set_sync_debug_mode");
int64_t debug_mode = THPUtils_unpackLong(arg);
TORCH_CHECK(
debug_mode >= 0 && debug_mode <= 2,
"invalid value of debug_mode, expected one of 0,1,2");
c10::cuda::SyncDebugMode l = c10::cuda::SyncDebugMode::L_DISABLED;
switch (debug_mode) {
case 0:
l = c10::cuda::SyncDebugMode::L_DISABLED;
break;
case 1:
l = c10::cuda::SyncDebugMode::L_WARN;
break;
case 2:
l = c10::cuda::SyncDebugMode::L_ERROR;
break;
default:
break; // can't happen
}
c10::cuda::warning_state().set_sync_debug_mode(l);
Py_RETURN_NONE;
END_HANDLE_TH_ERRORS
}
PyObject* THCPModule_cudaGetSyncDebugMode(PyObject* self, PyObject* noargs) {
HANDLE_TH_ERRORS
auto debug_mode = c10::cuda::warning_state().get_sync_debug_mode();
switch (debug_mode) {
case c10::cuda::SyncDebugMode::L_DISABLED:
return THPUtils_packInt32(0);
case c10::cuda::SyncDebugMode::L_WARN:
return THPUtils_packInt32(1);
case c10::cuda::SyncDebugMode::L_ERROR:
return THPUtils_packInt32(2);
default:
return THPUtils_packInt32(-1); // can't happen
}
END_HANDLE_TH_ERRORS
}
////////////////////////////////////////////////////////////////////////////////
// Cuda module initialization
////////////////////////////////////////////////////////////////////////////////
static void registerCudaDeviceProperties(PyObject* module) {
// Add _cudaDevicePropertires class to torch._C
auto m = py::handle(module).cast<py::module>();
py::class_<cudaDeviceProp>(m, "_CudaDeviceProperties")
.def_readonly("name", &cudaDeviceProp::name)
.def_readonly("major", &cudaDeviceProp::major)
.def_readonly("minor", &cudaDeviceProp::minor)
.def_readonly("is_multi_gpu_board", &cudaDeviceProp::isMultiGpuBoard)
.def_readonly("is_integrated", &cudaDeviceProp::integrated)
.def_readonly(
"multi_processor_count", &cudaDeviceProp::multiProcessorCount)
.def_readonly("total_memory", &cudaDeviceProp::totalGlobalMem)
.def_readonly(
"max_threads_per_multi_processor",
&cudaDeviceProp::maxThreadsPerMultiProcessor)
#if !USE_ROCM
// NVIDA only property
.def_readonly(
"regs_per_multiprocessor", &cudaDeviceProp::regsPerMultiprocessor)
#endif // USE_ROCM
// HIP-only property; reuse name attribute for CUDA builds
.def_readonly(
"gcnArchName",
#if USE_ROCM
&cudaDeviceProp::gcnArchName
#else
&cudaDeviceProp::name
#endif // USE_ROCM
)
.def("__repr__", [](const cudaDeviceProp& prop) {
std::ostringstream stream;
stream << "_CudaDeviceProperties(name='" << prop.name
<< "', major=" << prop.major << ", minor=" << prop.minor
#if USE_ROCM
<< ", gcnArchName='" << prop.gcnArchName << "'"
#endif // USE_ROCM
<< ", total_memory=" << prop.totalGlobalMem / (1024ull * 1024)
<< "MB, multi_processor_count=" << prop.multiProcessorCount
<< ")";
return stream.str();
});
m.def(
"_cuda_record_memory_history_legacy",
static_cast<void (*)(bool, bool, int64_t, bool, bool)>(
torch::cuda::_record_memory_history));
m.def(
"_cuda_record_memory_history",
static_cast<void (*)(
std::optional<std::string>,
std::optional<std::string>,
const std::string&,
size_t)>(torch::cuda::_record_memory_history));
m.def("_cuda_isHistoryEnabled", []() {
return c10::cuda::CUDACachingAllocator::isHistoryEnabled();
});
m.def("_cuda_get_conv_benchmark_empty_cache", []() {
return at::native::_cudnn_get_conv_benchmark_empty_cache();
});
m.def("_cudnn_set_conv_benchmark_empty_cache", [](bool enable) {
return at::native::_cudnn_set_conv_benchmark_empty_cache(enable);
});
}
// We choose to ignore certain blocks that are currently allocated
// when we set the pool to its checkpoint. For those blocks, we need
// to swap out the deleter function of their corresponding blocks
// so that a deallocation is not triggered when they die.
void removeStorageDeleterFns(
const std::vector<c10::StorageImpl*>& stale_live_storages,
std::unordered_set<void*> definitely_stale_pointers) {
for (c10::StorageImpl* stale_storage : stale_live_storages) {
auto ptr = stale_storage->data_ptr().get();
auto allocated_pointer = definitely_stale_pointers.find(ptr);
TORCH_CHECK(allocated_pointer != definitely_stale_pointers.end());
auto t = c10::cuda::CUDACachingAllocator::get();
bool succeeded = stale_storage->mutable_data_ptr().compare_exchange_deleter(
t->raw_deleter(), &c10::detail::deleteNothing);
TORCH_CHECK(
succeeded,
"Unexpected deleter function on storage, could not swap function");
}
}
void addStorageDeleterFns(
std::vector<c10::StorageImpl*>& storages_to_add_deleters_to,