/
memory.pyx
1980 lines (1607 loc) · 68.8 KB
/
memory.pyx
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
# distutils: language = c++
cimport cpython # NOQA
cimport cython # NOQA
import atexit
import collections
import gc
import os
import threading
import warnings
import weakref
from fastrlock cimport rlock
from libc.stdint cimport int8_t
from libc.stdint cimport intptr_t
from libc.stdint cimport UINT64_MAX
from libcpp cimport algorithm
from cupy.cuda cimport device
from cupy.cuda cimport memory_hook
from cupy.cuda cimport stream as stream_module
from cupy_backends.cuda.api cimport driver
from cupy_backends.cuda.api cimport runtime
from cupy_backends.cuda.api.runtime import CUDARuntimeError
from cupy import _util
cdef bint _exit_mode = False
@atexit.register
def _exit():
_exit_mode = True
class OutOfMemoryError(MemoryError):
"""Out-of-memory error.
Args:
size (int): Size of memory about to be allocated.
total (int): Size of memory successfully allocated so far.
limit (int): Allocation limit.
"""
def __init__(self, size, total, limit=0):
self._size = size
self._total = total
self._limit = limit
if limit == 0:
msg = 'Out of memory allocating {:,} bytes'.format(size)
if total != -1:
msg += ' (allocated so far: {:,} bytes).'.format(total)
else:
msg = (
'Out of memory allocating {:,} bytes '
'(allocated so far: {:,} bytes, '
'limit set to: {:,} bytes).'.format(size, total, limit))
super(OutOfMemoryError, self).__init__(msg)
def __reduce__(self):
return (type(self), (self._size, self._total, self._limit))
@cython.no_gc
cdef class BaseMemory:
"""Memory on a CUDA device.
Attributes:
~Memory.ptr (int): Pointer to the place within the buffer.
~Memory.size (int): Size of the memory allocation in bytes.
~Memory.device (~cupy.cuda.Device): Device whose memory the pointer
refers to.
"""
def __int__(self):
"""Returns the pointer value to the head of the allocation."""
return self.ptr
@property
def device(self):
return device.Device(self.device_id)
@cython.no_gc
cdef class Memory(BaseMemory):
"""Memory allocation on a CUDA device.
This class provides an RAII interface of the CUDA memory allocation.
Args:
size (int): Size of the memory allocation in bytes.
"""
def __init__(self, size_t size):
self.size = size
self.device_id = device.get_device_id()
self.ptr = 0
if size > 0:
self.ptr = runtime.malloc(size)
def __dealloc__(self):
# Note: Cannot raise in the destructor! (cython/cython#1613)
if self.ptr:
runtime.free(self.ptr)
cdef inline void check_async_alloc_supported(int device_id) except*:
if runtime._is_hip_environment:
raise RuntimeError('HIP does not support memory_async')
cdef int dev_id
cdef list support
try:
is_supported = _thread_local.device_support_async_alloc[device_id]
except AttributeError:
support = [runtime.deviceGetAttribute(
runtime.cudaDevAttrMemoryPoolsSupported, dev_id)
for dev_id in range(runtime.getDeviceCount())]
_thread_local.device_support_async_alloc = support
is_supported = support[device_id]
if not is_supported:
raise RuntimeError('Device {} does not support '
'malloc_async'.format(device_id))
@cython.no_gc
cdef class MemoryAsync(BaseMemory):
"""Asynchronous memory allocation on a CUDA device.
This class provides an RAII interface of the CUDA memory allocation.
Args:
size (int): Size of the memory allocation in bytes.
stream (Stream): The stream on which the memory is allocated and freed.
"""
cdef:
readonly object stream_ref
def __init__(self, size_t size, stream):
self.size = size
self.device_id = device.get_device_id()
# The stream is allowed to be destroyed before the memory is freed, so
# we don't need to hold a strong reference to the stream.
self.stream_ref = weakref.ref(stream)
check_async_alloc_supported(self.device_id)
if size > 0:
self.ptr = runtime.mallocAsync(size, stream.ptr)
def __dealloc__(self):
# Free on the stream on which this memory was allocated.
# If the stream is already destroyed, free on the current stream. In
# this case, we trust the user has established a correct stream order.
if self.ptr == 0:
return
stream = self.stream_ref()
if stream is None:
stream = stream_module.get_current_stream()
runtime.freeAsync(self.ptr, stream.ptr)
cdef class UnownedMemory(BaseMemory):
"""CUDA memory that is not owned by CuPy.
Args:
ptr (int): Pointer to the buffer.
size (int): Size of the buffer.
owner (object): Reference to the owner object to keep the memory
alive.
device_id (int): CUDA device ID of the buffer. If omitted, the device
associated to the pointer is retrieved.
"""
cdef:
readonly object _owner
def __init__(self, intptr_t ptr, size_t size, object owner,
int device_id=-1):
cdef runtime.PointerAttributes ptr_attrs
# ptr=0 for 0-size arrays from __cuda_array_interface__ v2:
# we need a valid device id as null ptr can't be looked up
if device_id < 0:
if ptr == 0:
raise RuntimeError('UnownedMemory requires explicit'
' device ID for a null pointer.')
# Initialize a context to workaround a bug in CUDA 10.2+. (#3991)
runtime._ensure_context()
ptr_attrs = runtime.pointerGetAttributes(ptr)
device_id = ptr_attrs.device
self.size = size
self.device_id = device_id
self.ptr = ptr
self._owner = owner
@cython.no_gc
cdef class ManagedMemory(BaseMemory):
"""Managed memory (Unified memory) allocation on a CUDA device.
This class provides an RAII interface of the CUDA managed memory
allocation.
Args:
size (int): Size of the memory allocation in bytes.
"""
def __init__(self, size_t size):
if (
runtime._is_hip_environment and
driver.get_build_version() < 40300000
):
raise RuntimeError('Managed memory requires ROCm 4.3+')
self.size = size
self.device_id = device.get_device_id()
self.ptr = 0
if size > 0:
self.ptr = runtime.mallocManaged(size)
def prefetch(self, stream):
"""(experimental) Prefetch memory.
Args:
stream (cupy.cuda.Stream): CUDA stream.
"""
runtime.memPrefetchAsync(self.ptr, self.size, self.device_id,
stream.ptr)
def advise(self, int advise, device.Device dev):
"""(experimental) Advise about the usage of this memory.
Args:
advics (int): Advise to be applied for this memory.
dev (cupy.cuda.Device): Device to apply the advice for.
"""
runtime.memAdvise(self.ptr, self.size, advise, dev.id)
def __dealloc__(self):
# Note: Cannot raise in the destructor! (cython/cython#1613)
if self.ptr:
runtime.free(self.ptr)
@cython.final
cdef class _Chunk:
"""A chunk points to a device memory.
A chunk might be a splitted memory block from a larger allocation.
The prev/next pointers contruct a doubly-linked list of memory addresses
sorted by base address that must be contiguous.
Args:
mem (~cupy.cuda.Memory): The device memory buffer.
offset (int): An offset bytes from the head of the buffer.
size (int): Chunk size in bytes.
stream_ident (intptr_t): Value to uniquely identify the stream.
Attributes:
mem (Memory): The device memory buffer.
ptr (int): Memory address.
offset (int): An offset bytes from the head of the buffer.
size (int): Chunk size in bytes.
prev (Chunk): prev memory pointer if split from a larger allocation
next (Chunk): next memory pointer if split from a larger allocation
stream_ident (intptr_t): Value to uniquely identify the stream.
"""
cdef:
readonly BaseMemory mem
readonly ptrdiff_t offset
readonly size_t size
readonly intptr_t stream_ident
public _Chunk prev
public _Chunk next
def __init__(self, *args):
# For debug
mem, offset, size, stream_ident = args
self._init(mem, offset, size, stream_ident)
cdef _init(self, BaseMemory mem, ptrdiff_t offset,
size_t size, intptr_t stream_ident):
assert mem.ptr != 0 or offset == 0
self.mem = mem
self.offset = offset
self.size = size
self.stream_ident = stream_ident
cpdef intptr_t ptr(self):
return self.mem.ptr + self.offset
cpdef _Chunk split(self, size_t size):
"""Split contiguous block of a larger allocation"""
cdef _Chunk remaining
assert self.size >= size
if self.size == size:
return None
remaining = _Chunk.__new__(_Chunk)
remaining._init(self.mem, self.offset + size, self.size - size,
self.stream_ident)
self.size = size
if self.next is not None:
remaining.next = self.next
remaining.next.prev = remaining
self.next = remaining
remaining.prev = self
return remaining
cpdef merge(self, _Chunk remaining):
"""Merge previously splitted block (chunk)"""
assert self.stream_ident == remaining.stream_ident
self.size += remaining.size
self.next = remaining.next
if remaining.next is not None:
self.next.prev = self
cdef class MemoryPointer:
"""Pointer to a point on a device memory.
An instance of this class holds a reference to the original memory buffer
and a pointer to a place within this buffer.
Args:
mem (~cupy.cuda.BaseMemory): The device memory buffer.
offset (int): An offset from the head of the buffer to the place this
pointer refers.
Attributes:
~MemoryPointer.device (~cupy.cuda.Device): Device whose memory the
pointer refers to.
~MemoryPointer.mem (~cupy.cuda.BaseMemory): The device memory buffer.
~MemoryPointer.ptr (int): Pointer to the place within the buffer.
"""
def __init__(self, BaseMemory mem, ptrdiff_t offset):
self._init(mem, offset)
cdef _init(self, BaseMemory mem, ptrdiff_t offset):
assert mem.ptr != 0 or offset == 0
self.ptr = mem.ptr + offset
self.device_id = mem.device_id
self.mem = mem
def __int__(self):
"""Returns the pointer value."""
return self.ptr
def __repr__(self):
return '<{} 0x{:x} device={} mem={!r}>'.format(
self.__class__.__name__,
self.ptr, self.device_id, self.mem)
@property
def device(self):
return device.Device(self.device_id)
def __add__(x, y):
"""Adds an offset to the pointer."""
cdef MemoryPointer self
cdef ptrdiff_t offset
if isinstance(x, MemoryPointer):
self = x
offset = <ptrdiff_t?>y
else:
self = <MemoryPointer?>y
offset = <ptrdiff_t?>x
assert self.ptr != 0 or offset == 0
return MemoryPointer(self.mem,
self.ptr - self.mem.ptr + offset)
def __iadd__(self, ptrdiff_t offset):
"""Adds an offset to the pointer in place."""
assert self.ptr != 0 or offset == 0
self.ptr += offset
return self
def __sub__(self, offset):
"""Subtracts an offset from the pointer."""
return self + -offset
def __isub__(self, ptrdiff_t offset):
"""Subtracts an offset from the pointer in place."""
return self.__iadd__(-offset)
cpdef copy_from_device(self, MemoryPointer src, size_t size):
"""Copies a memory sequence from a (possibly different) device.
Args:
src (cupy.cuda.MemoryPointer): Source memory pointer.
size (int): Size of the sequence in bytes.
.. warning::
This function always uses the legacy default stream and does not
honor the current stream. Use `copy_from_device_async` instead
if you are using streams in your code, or have PTDS enabled.
"""
stream_ptr = stream_module.get_current_stream_ptr()
if (
not runtime._is_hip_environment
and runtime.streamIsCapturing(stream_ptr)
):
raise RuntimeError(
'the current stream is capturing, so synchronous API calls '
'are disallowed')
if size > 0:
device._enable_peer_access(src.device_id, self.device_id)
runtime.memcpy(self.ptr, src.ptr, size,
runtime.memcpyDefault)
cpdef copy_from_device_async(self, MemoryPointer src, size_t size,
stream=None):
"""Copies a memory from a (possibly different) device asynchronously.
Args:
src (cupy.cuda.MemoryPointer): Source memory pointer.
size (int): Size of the sequence in bytes.
stream (cupy.cuda.Stream): CUDA stream.
The default uses CUDA stream of the current context.
"""
if stream is None:
stream_ptr = stream_module.get_current_stream_ptr()
else:
stream_ptr = stream.ptr
if size > 0:
device._enable_peer_access(src.device_id, self.device_id)
runtime.memcpyAsync(self.ptr, src.ptr, size,
runtime.memcpyDefault, stream_ptr)
cpdef copy_from_host(self, mem, size_t size):
"""Copies a memory sequence from the host memory.
Args:
mem (int or ctypes.c_void_p): Source memory pointer.
size (int): Size of the sequence in bytes.
.. warning::
This function always uses the legacy default stream and does not
honor the current stream. Use `copy_from_host_async` instead
if you are using streams in your code, or have PTDS enabled.
"""
stream_ptr = stream_module.get_current_stream_ptr()
if (
not runtime._is_hip_environment
and runtime.streamIsCapturing(stream_ptr)
):
raise RuntimeError(
'the current stream is capturing, so synchronous API calls '
'are disallowed')
if size > 0:
ptr = mem if isinstance(mem, int) else mem.value
runtime.memcpy(self.ptr, ptr, size,
runtime.memcpyHostToDevice)
cpdef copy_from_host_async(self, mem, size_t size, stream=None):
"""Copies a memory sequence from the host memory asynchronously.
Args:
mem (int or ctypes.c_void_p): Source memory pointer. It must point
to pinned memory.
size (int): Size of the sequence in bytes.
stream (cupy.cuda.Stream): CUDA stream.
The default uses CUDA stream of the current context.
"""
if stream is None:
stream_ptr = stream_module.get_current_stream_ptr()
else:
stream_ptr = stream.ptr
if (
not runtime._is_hip_environment
and runtime.streamIsCapturing(stream_ptr)
):
raise RuntimeError(
'the current stream is capturing, so H2D transfers '
'are disallowed')
if size > 0:
ptr = mem if isinstance(mem, int) else mem.value
runtime.memcpyAsync(self.ptr, ptr, size,
runtime.memcpyHostToDevice, stream_ptr)
cpdef copy_from(self, mem, size_t size):
"""Copies a memory sequence from a (possibly different) device or host.
This function is a useful interface that selects appropriate one from
:meth:`~cupy.cuda.MemoryPointer.copy_from_device` and
:meth:`~cupy.cuda.MemoryPointer.copy_from_host`.
Args:
mem (int or ctypes.c_void_p or cupy.cuda.MemoryPointer):
Source memory pointer.
size (int): Size of the sequence in bytes.
.. warning::
This function always uses the legacy default stream and does not
honor the current stream. Use `copy_from_async` instead
if you are using streams in your code, or have PTDS enabled.
"""
if isinstance(mem, MemoryPointer):
self.copy_from_device(mem, size)
else:
self.copy_from_host(mem, size)
cpdef copy_from_async(self, mem, size_t size, stream=None):
"""Copies a memory sequence from an arbitrary place asynchronously.
This function is a useful interface that selects appropriate one from
:meth:`~cupy.cuda.MemoryPointer.copy_from_device_async` and
:meth:`~cupy.cuda.MemoryPointer.copy_from_host_async`.
Args:
mem (int or ctypes.c_void_p or cupy.cuda.MemoryPointer):
Source memory pointer.
size (int): Size of the sequence in bytes.
stream (cupy.cuda.Stream): CUDA stream.
The default uses CUDA stream of the current context.
"""
if isinstance(mem, MemoryPointer):
self.copy_from_device_async(mem, size, stream)
else:
self.copy_from_host_async(mem, size, stream)
cpdef copy_to_host(self, mem, size_t size):
"""Copies a memory sequence to the host memory.
Args:
mem (int or ctypes.c_void_p): Target memory pointer.
size (int): Size of the sequence in bytes.
.. warning::
This function always uses the legacy default stream and does not
honor the current stream. Use `copy_to_host_async` instead
if you are using streams in your code, or have PTDS enabled.
"""
stream_ptr = stream_module.get_current_stream_ptr()
if (
not runtime._is_hip_environment
and runtime.streamIsCapturing(stream_ptr)
):
raise RuntimeError(
'the current stream is capturing, so synchronous API calls '
'are disallowed')
if size > 0:
ptr = mem if isinstance(mem, int) else mem.value
runtime.memcpy(ptr, self.ptr, size,
runtime.memcpyDeviceToHost)
cpdef copy_to_host_async(self, mem, size_t size, stream=None):
"""Copies a memory sequence to the host memory asynchronously.
Args:
mem (int or ctypes.c_void_p): Target memory pointer. It must point
to pinned memory.
size (int): Size of the sequence in bytes.
stream (cupy.cuda.Stream): CUDA stream.
The default uses CUDA stream of the current context.
"""
if stream is None:
stream_ptr = stream_module.get_current_stream_ptr()
else:
stream_ptr = stream.ptr
if (
not runtime._is_hip_environment
and runtime.streamIsCapturing(stream_ptr)
):
raise RuntimeError(
'the current stream is capturing, so D2H transfers '
'are disallowed')
if size > 0:
ptr = mem if isinstance(mem, int) else mem.value
runtime.memcpyAsync(ptr, self.ptr, size,
runtime.memcpyDeviceToHost, stream_ptr)
cpdef memset(self, int value, size_t size):
"""Fills a memory sequence by constant byte value.
Args:
value (int): Value to fill.
size (int): Size of the sequence in bytes.
.. warning::
This function always uses the legacy default stream and does not
honor the current stream. Use `memset_async` instead
if you are using streams in your code, or have PTDS enabled.
"""
stream_ptr = stream_module.get_current_stream_ptr()
if (
not runtime._is_hip_environment
and runtime.streamIsCapturing(stream_ptr)
):
raise RuntimeError(
'the current stream is capturing, so synchronous API calls '
'are disallowed')
if size > 0:
runtime.memset(self.ptr, value, size)
cpdef memset_async(self, int value, size_t size, stream=None):
"""Fills a memory sequence by constant byte value asynchronously.
Args:
value (int): Value to fill.
size (int): Size of the sequence in bytes.
stream (cupy.cuda.Stream): CUDA stream.
The default uses CUDA stream of the current context.
"""
if stream is None:
stream_ptr = stream_module.get_current_stream_ptr()
else:
stream_ptr = stream.ptr
if size > 0:
runtime.memsetAsync(self.ptr, value, size, stream_ptr)
# cpdef because unit-tested
cpdef MemoryPointer _malloc(size_t size):
mem = Memory(size)
return MemoryPointer(mem, 0)
cpdef MemoryPointer malloc_async(size_t size):
"""(Experimental) Allocate memory from Stream Ordered Memory Allocator.
This method can be used as a CuPy memory allocator. The simplest way to
use CUDA's Stream Ordered Memory Allocator as the default allocator is
the following code::
set_allocator(malloc_async)
Using this feature requires CUDA >= 11.2 with a supported GPU and platform.
If it is not supported, an error will be raised.
The current CuPy stream is used to allocate/free the memory.
Args:
size (int): Size of the memory allocation in bytes.
Returns:
~cupy.cuda.MemoryPointer: Pointer to the allocated buffer.
.. warning::
This feature is currently experimental and subject to change.
.. seealso:: `Stream Ordered Memory Allocator`_
.. _Stream Ordered Memory Allocator:
https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#stream-ordered-memory-allocator
"""
mem = MemoryAsync(size, stream_module.get_current_stream())
return MemoryPointer(mem, 0)
cpdef MemoryPointer malloc_managed(size_t size):
"""Allocate managed memory (unified memory).
This method can be used as a CuPy memory allocator. The simplest way to
use a managed memory as the default allocator is the following code::
set_allocator(malloc_managed)
The advantage using managed memory in CuPy is that device memory
oversubscription is possible for GPUs that have a non-zero value for the
device attribute cudaDevAttrConcurrentManagedAccess.
CUDA >= 8.0 with GPUs later than or equal to Pascal is preferrable.
Read more at: https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html#axzz4qygc1Ry1 # NOQA
Args:
size (int): Size of the memory allocation in bytes.
Returns:
~cupy.cuda.MemoryPointer: Pointer to the allocated buffer.
"""
mem = ManagedMemory(size)
return MemoryPointer(mem, 0)
cdef object _current_allocator = _malloc
cdef object _thread_local = threading.local()
def _get_thread_local_allocator():
try:
allocator = _thread_local.allocator
except AttributeError:
allocator = _thread_local.allocator = None
return allocator
def _set_thread_local_allocator(allocator):
_thread_local.allocator = allocator
cdef inline intptr_t _get_stream_identifier(intptr_t stream_ptr):
# When PTDS is enabled, return an ID to uniquely identify the default
# stream for each thread. (#5069)
if stream_ptr != runtime.streamPerThread:
return stream_ptr
cdef intptr_t tid
try:
tid = _thread_local._tid
except AttributeError:
_thread_local._tid_obj = tid_obj = object()
_thread_local._tid = tid = id(tid_obj)
return -tid
cpdef MemoryPointer alloc(size):
"""Calls the current allocator.
Use :func:`~cupy.cuda.set_allocator` to change the current allocator.
Args:
size (int): Size of the memory allocation.
Returns:
~cupy.cuda.MemoryPointer: Pointer to the allocated buffer.
"""
return get_allocator()(size)
cpdef set_allocator(allocator=None):
"""Sets the current allocator for GPU memory.
Args:
allocator (function): CuPy memory allocator. It must have the same
interface as the :func:`cupy.cuda.alloc` function, which takes the
buffer size as an argument and returns the device buffer of that
size. When ``None`` is specified, raw memory allocator will be
used (i.e., memory pool is disabled).
"""
global _current_allocator
if allocator is None:
allocator = _malloc
if getattr(_thread_local, 'allocator', None) is not None:
raise ValueError('Can\'t change the global allocator inside '
'`using_allocator` context manager')
if allocator is malloc_async:
_util.experimental('cupy.cuda.malloc_async')
_current_allocator = allocator
cpdef get_allocator():
"""Returns the current allocator for GPU memory.
Returns:
function: CuPy memory allocator.
"""
try:
allocator = _thread_local.allocator
except AttributeError:
_thread_local.allocator = allocator = None
if allocator is None:
return _current_allocator
else:
return allocator
@cython.final
@cython.no_gc
cdef class PooledMemory(BaseMemory):
"""Memory allocation for a memory pool.
The instance of this class is created by memory pool allocator, so user
should not instantiate it by hand.
"""
cdef:
readonly object pool
def __init__(self, _Chunk chunk, pool):
self._init(chunk, pool)
cdef _init(self, _Chunk chunk, pool):
self.ptr = chunk.ptr()
self.size = chunk.size
self.device_id = chunk.mem.device_id
self.pool = pool
cpdef free(self):
"""Frees the memory buffer and returns it to the memory pool.
This function actually does not free the buffer. It just returns the
buffer to the memory pool for reuse.
"""
cdef intptr_t ptr
ptr = self.ptr
if ptr == 0:
return
self.ptr = 0
pool = self.pool()
if pool is None:
return
size = self.size
if memory_hook._has_memory_hooks():
hooks = memory_hook.get_memory_hooks()
if hooks:
device_id = self.device_id
pmem_id = id(self)
for hook in hooks.values():
hook.free_preprocess(device_id=device_id,
mem_size=size,
mem_ptr=ptr,
pmem_id=pmem_id)
try:
(<SingleDeviceMemoryPool>pool).free(ptr, size)
finally:
for hook in hooks.values():
hook.free_postprocess(device_id=device_id,
mem_size=size,
mem_ptr=ptr,
pmem_id=pmem_id)
return
(<SingleDeviceMemoryPool>pool).free(ptr, size)
def __dealloc__(self):
if _exit_mode:
return # To avoid error at exit
self.free()
cdef size_t _index_compaction_threshold = 512
# cudaMalloc() is aligned to at least 512 bytes
# cf. https://gist.github.com/sonots/41daaa6432b1c8b27ef782cd14064269
DEF ALLOCATION_UNIT_SIZE = 512
# for test
_allocation_unit_size = ALLOCATION_UNIT_SIZE
cpdef inline size_t _round_size(size_t size):
"""Rounds up the memory size to fit memory alignment of cudaMalloc."""
# avoid 0 div checking
size = (size + ALLOCATION_UNIT_SIZE - 1) // ALLOCATION_UNIT_SIZE
return size * ALLOCATION_UNIT_SIZE
cpdef size_t _bin_index_from_size(size_t size):
"""Returns appropriate bins index from the memory size."""
# avoid 0 div checking
return (size - 1) // ALLOCATION_UNIT_SIZE
cdef _gc_isenabled = gc.isenabled
cdef _gc_disable = gc.disable
cdef _gc_enable = gc.enable
cdef bint _lock_no_gc(lock):
"""Lock to ensure single thread execution and no garbage collection.
Returns:
bool: Whether GC is disabled.
"""
rlock.lock_fastrlock(lock, -1, True)
# This function may be called from the context of finalizer
# (e.g., `__dealloc__` of PooledMemory class).
# If the process is going to be terminated, the module itself may
# already been unavailable.
if not _exit_mode and _gc_isenabled():
_gc_disable()
return True
return False
cdef _unlock_no_gc(lock, bint gc_mode):
if gc_mode:
_gc_enable()
rlock.unlock_fastrlock(lock)
cdef class LockAndNoGc:
"""A context manager that ensures single-thread execution
and no garbage collection in the wrapped code.
The purpose of disabling GC is to prevent unexpected recursion.
See gh-2074 for details.
"""
cdef object _lock
cdef bint _gc
def __cinit__(self, lock):
self._lock = lock
def __enter__(self):
self._gc = _lock_no_gc(self._lock)
def __exit__(self, t, v, tb):
_unlock_no_gc(self._lock, self._gc)
@cython.final
cdef class _Arena:
cdef:
# `_free_lock` must be acquired to access it.
list _free
# `_free_lock` must be acquired to access it.
vector.vector[size_t] _index
# `_free_lock` must be acquired to access it.
vector.vector[int8_t] _flag
def __init__(self):
self._free = []
cdef append_to_free_list(self, _Chunk chunk):
# need self._free_lock
cdef size_t index, bin_index
cdef set free_list
cdef vector.vector[size_t].iterator it
bin_index = _bin_index_from_size(chunk.size)
it = algorithm.lower_bound(
self._index.begin(), self._index.end(), bin_index)
index = <size_t>(it - self._index.begin())
if index < self._index.size() and self._index.at(index) == bin_index:
free_list = self._free[index]
if free_list is None:
self._free[index] = free_list = set()
else:
free_list = set()
self._index.insert(self._index.begin() + index, bin_index)
self._flag.insert(self._flag.begin() + index, 0)
self._free.insert(index, free_list)
free_list.add(chunk)
self._flag[index] = 1
cdef bint remove_from_free_list(self, _Chunk chunk):
"""Removes the chunk from the free list (need self._free_lock).
Returns:
bool: ``True`` if the chunk can successfully be removed from
the free list. ``False`` otherwise (e.g., the chunk could not
be found in the free list as the chunk is allocated.)
"""
cdef size_t index, bin_index
cdef set free_list
cdef vector.vector[size_t].iterator it
bin_index = _bin_index_from_size(chunk.size)
if self._index.size() == 0:
return False
it = algorithm.lower_bound(
self._index.begin(), self._index.end(), bin_index)
index = <size_t>(it - self._index.begin())
if index == self._index.size():
# Bin does not exist for the given chunk size.
return False
if self._index.at(index) != bin_index or self._flag.at(index) == 0:
return False
free_list = self._free[index]
if chunk in free_list:
free_list.remove(chunk)
if len(free_list) == 0:
self._free[index] = None
self._flag[index] = 0
return True
return False
# cpdef because uint-tested
# module-level function can be inlined
cpdef inline dict _parse_limit_string(limit=None):
if limit is None:
limit = os.environ.get('CUPY_GPU_MEMORY_LIMIT')
size = None
fraction = None
if limit is not None:
if limit.endswith('%'):
fraction = float(limit[:-1]) / 100.0
else:
size = int(limit)
return {'size': size, 'fraction': fraction}